Skip to content

The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.

Code tab: review staged changes per hunk, per file or all

purple995525cd773c
diff --git a/e2e/howto/code-modes.spec.ts b/e2e/howto/code-modes.spec.ts
index 98aed68a..98190838 100644
--- a/e2e/howto/code-modes.spec.ts
+++ b/e2e/howto/code-modes.spec.ts
@@ -48,8 +48,8 @@ test('code-modes', async ({ page }) => {
until: () => expect(page.getByText('The edit to greet.py is staged')).toBeVisible({ timeout: 30_000 }),
})
- rec.scene('The edits wait under Pending: apply or reject each file, or all at once.')
- await rec.move(page.getByTitle('Apply'), { dur: 0.7 })
+ rec.scene('The edits wait for your review: accept or reject each part, each file, or all at once.')
+ await rec.move(page.getByTitle('Accept file'), { dur: 0.7 })
rec.hold(0.8)
await rec.move(page.getByTestId('apply-all'), { dur: 0.5 })
rec.hold(0.8)
diff --git a/e2e/u3-review-shots.spec.ts b/e2e/u3-review-shots.spec.ts
new file mode 100644
index 00000000..900e8807
--- /dev/null
+++ b/e2e/u3-review-shots.spec.ts
@@ -0,0 +1,107 @@
+import { test, expect, type Page } from '@playwright/test'
+import { tauriMockInit, DEFAULT_MODEL_NAME } from './support/tauri-mock'
+import { seedOnboardingDone } from './support/cloud-mock'
+import { openNewChat } from './support/ui'
+
+/**
+ * Pictures of the per hunk review (U3), not a test of anything. A Code tab
+ * Ask run stages one file_write with two hunks. Runs only when LU_CA_SHOTS
+ * names a folder:
+ *
+ * LU_CA_SHOTS=/path LU_E2E_PORT=5431 npx playwright test e2e/u3-review-shots.spec.ts --project=chromium
+ */
+const OUT = process.env.LU_CA_SHOTS
+
+const BEFORE = [
+ 'export function mean(xs: number[]): number {',
+ ' return xs.reduce((a, b) => a + b, 0) / xs.length',
+ '}',
+ '',
+ 'export function sum(xs: number[]): number {',
+ ' return xs.reduce((a, b) => a + b, 0)',
+ '}',
+ '',
+ 'export function max(xs: number[]): number {',
+ ' return Math.max(...xs)',
+ '}',
+ '',
+ 'export function median(xs: number[]): number {',
+ ' return 0 // TODO',
+ '}',
+ '',
+]
+const AFTER = [...BEFORE]
+AFTER[1] = ' if (xs.length === 0) return NaN'
+AFTER.splice(2, 0, ' return sum(xs) / xs.length')
+AFTER.splice(14, 1,
+ ' const s = [...xs].sort((a, b) => a - b)',
+ ' const m = Math.floor(s.length / 2)',
+ ' return s.length % 2 ? s[m] : (s[m - 1] + s[m]) / 2',
+)
+
+type Turn = { text?: string; toolCalls?: Array<{ name: string; args: Record<string, unknown> }> }
+const RUN: Turn[] = [
+ { text: 'Let me look at the file first.', toolCalls: [{ name: 'file_read', args: { path: 'src/stats.ts' } }] },
+ {
+ text: 'I will guard `mean` against an empty list and implement `median`.',
+ toolCalls: [{ name: 'file_write', args: { path: 'src/stats.ts', content: AFTER.join('\n') } }],
+ },
+ { text: 'Both changes are staged for your review.' },
+]
+
+async function boot(page: Page, width: number, theme: 'dark' | 'light') {
+ await page.addInitScript(tauriMockInit, {
+ assistantReply: 'unused',
+ modelName: DEFAULT_MODEL_NAME,
+ replyChunkDelayMs: 6,
+ agentTurns: RUN,
+ toolDelayMs: 150,
+ files: { 'stats.ts': BEFORE.join('\n') },
+ })
+ await seedOnboardingDone(page)
+ await page.setViewportSize({ width, height: 900 })
+ await page.goto('/')
+ const isDark = await page.evaluate(() => document.documentElement.classList.contains('dark'))
+ if (isDark !== (theme === 'dark')) {
+ await page.getByRole('banner').getByTitle(/^(Light|Dark) Mode$/).click()
+ }
+}
+
+async function shot(page: Page, name: string) {
+ await page.waitForTimeout(500)
+ await page.screenshot({ path: `${OUT}/${name}.png` })
+}
+
+test.describe('U3 review shots', () => {
+ test.skip(!OUT, 'set LU_CA_SHOTS to a folder')
+ for (const theme of ['light', 'dark'] as const) {
+ for (const width of [1280, 375]) {
+ test(`review ${theme} ${width}`, async ({ page }) => {
+ await boot(page, width, theme)
+ if (width >= 1024) await page.getByRole('button', { name: 'Code', exact: true }).click()
+ else {
+ await page.getByRole('banner').getByRole('button', { name: 'Main navigation' }).click().catch(() => {})
+ await page.getByRole('button', { name: 'Code', exact: true }).first().click().catch(() => {})
+ }
+ await openNewChat(page)
+ const composer = page.locator('textarea').first()
+ await expect(composer).toBeEnabled({ timeout: 20_000 })
+ await composer.fill('mean() breaks on an empty list and median() is missing, fix both')
+ await composer.press('Enter')
+ await expect(page.getByTestId('staged-changes-panel')).toBeVisible({ timeout: 20_000 })
+ await page.waitForTimeout(1500)
+ await shot(page, `review-${theme}-${width}-1-start`)
+ if (width < 640) {
+ await page.getByTestId('staged-changes-review').click()
+ await shot(page, `review-${theme}-${width}-2-open`)
+ } else {
+ await page.getByTestId('staged-hunk').first().hover()
+ await shot(page, `review-${theme}-${width}-2-hover`)
+ }
+ await page.getByTestId('hunk-reject').first().click()
+ await page.getByTestId('staged-hunk').nth(1).hover()
+ await shot(page, `review-${theme}-${width}-3-one-rejected`)
+ })
+ }
+ }
+})
diff --git a/src/components/chat/DiffView.tsx b/src/components/chat/DiffView.tsx
index 336d0841..600b4707 100644
--- a/src/components/chat/DiffView.tsx
+++ b/src/components/chat/DiffView.tsx
@@ -1,4 +1,5 @@
import { parseUnifiedDiff, displayPath } from '../../lib/diff'
+import { DIFF_TONE, DIFF_LINE_NO, DIFF_ADDED_COUNT, DIFF_REMOVED_COUNT, DIFF_SURFACE, DIFF_HUNK_HEAD } from './diff-tones'
interface Props {
/** Raw unified-diff string as produced by `computeUnifiedDiff`. */
@@ -28,75 +29,47 @@ export function DiffView({ diff, maxLines = 200, showPath = true }: Props) {
const lines = truncated ? parsed.lines.slice(0, maxLines) : parsed.lines
const hiddenCount = parsed.lines.length - lines.length
+ // Light and dark from one palette (diff-tones.ts); it was dark only and
+ // grey on grey in the light theme.
return (
- <div className="rounded border border-white/10 bg-black/30 overflow-hidden">
+ <div className={`rounded border ${DIFF_SURFACE} overflow-hidden`}>
{showPath && (parsed.added > 0 || parsed.removed > 0) && (
- <div className="flex items-center justify-between px-2 py-1 border-b border-white/5 text-[0.55rem] font-mono">
- <span className="text-gray-500 truncate">{displayPath(parsed.path) || 'diff'}</span>
+ <div className="flex items-center justify-between px-2 py-1 border-b border-gray-100 dark:border-white/5 t-mono">
+ <span className="text-gray-600 dark:text-gray-400 truncate">{displayPath(parsed.path) || 'diff'}</span>
<span className="flex gap-2 shrink-0">
- {parsed.added > 0 && (
- <span className="text-emerald-400">+{parsed.added}</span>
- )}
- {parsed.removed > 0 && (
- <span className="text-red-400">-{parsed.removed}</span>
- )}
+ {parsed.added > 0 && <span className={DIFF_ADDED_COUNT}>+{parsed.added}</span>}
+ {parsed.removed > 0 && <span className={DIFF_REMOVED_COUNT}>-{parsed.removed}</span>}
</span>
</div>
)}
- <pre className="t-micro leading-relaxed font-mono overflow-auto scrollbar-thin max-h-[300px]">
- {lines.map((l, i) => {
- if (l.kind === 'hunk') {
+ <div className="t-mono leading-5 overflow-auto scrollbar-thin max-h-[300px] [font-variant-ligatures:none]">
+ <div className="min-w-max">
+ {lines.map((l, i) => {
+ if (l.kind === 'hunk') {
+ return (
+ <div key={i} className={`px-2 t-micro border-y border-gray-100 dark:border-white/5 ${DIFF_HUNK_HEAD}`}>
+ {l.text}
+ </div>
+ )
+ }
+ const kind = l.kind === 'add' || l.kind === 'remove' ? l.kind : 'context'
+ const no = kind === 'remove' ? l.oldLine : l.newLine
+ const sign = kind === 'add' ? '+' : kind === 'remove' ? '-' : ' '
return (
- <div
- key={i}
- className="px-2 bg-blue-500/5 text-blue-300/70 border-y border-white/5"
- >
- {l.text}
+ <div key={i} className={`flex pr-3 ${DIFF_TONE[kind].row}`}>
+ <span className={`w-9 shrink-0 select-none pr-2 text-right ${DIFF_LINE_NO}`}>{no}</span>
+ <span className={`w-3 shrink-0 select-none ${DIFF_TONE[kind].sign}`}>{sign}</span>
+ <span className="whitespace-pre">{l.text || ' '}</span>
</div>
)
- }
- if (l.kind === 'add') {
- return (
- <div key={i} className="px-2 bg-emerald-500/10 text-emerald-200">
- {l.newLine !== undefined && (
- <span className="inline-block w-8 text-right pr-2 text-emerald-500/50">
- {l.newLine}
- </span>
- )}
- <span>{`+${l.text}`}</span>
- </div>
- )
- }
- if (l.kind === 'remove') {
- return (
- <div key={i} className="px-2 bg-red-500/10 text-red-200">
- {l.oldLine !== undefined && (
- <span className="inline-block w-8 text-right pr-2 text-red-500/50">
- {l.oldLine}
- </span>
- )}
- <span>{`-${l.text}`}</span>
- </div>
- )
- }
- // context
- return (
- <div key={i} className="px-2 text-gray-400">
- {l.newLine !== undefined && (
- <span className="inline-block w-8 text-right pr-2 text-gray-700">
- {l.newLine}
- </span>
- )}
- <span>{` ${l.text}`}</span>
+ })}
+ {truncated && (
+ <div className="px-2 py-1 t-micro text-gray-500 italic">
+ … {hiddenCount} more lines
</div>
- )
- })}
- {truncated && (
- <div className="px-2 py-1 text-gray-600 italic">
- … {hiddenCount} more lines
- </div>
- )}
- </pre>
+ )}
+ </div>
+ </div>
</div>
)
}
diff --git a/src/components/chat/StagedChangesPanel.tsx b/src/components/chat/StagedChangesPanel.tsx
index 13801611..4ba9a952 100644
--- a/src/components/chat/StagedChangesPanel.tsx
+++ b/src/components/chat/StagedChangesPanel.tsx
@@ -1,11 +1,12 @@
-import { useState } from 'react'
-import { Check, X, ChevronDown, ChevronRight, FileText } from 'lucide-react'
+import { useMemo, useState } from 'react'
+import { Check, X, ChevronDown, ChevronRight, FileText, Undo2 } from 'lucide-react'
import { useStagedChangesStore, type StagedChange } from '../../stores/stagedChangesStore'
-import { applyStagedChange } from '../../lib/staged-apply'
-import { DiffView } from './DiffView'
-import { displayPath, parseUnifiedDiff } from '../../lib/diff'
+import { applyStagedChange, rejectStagedChange, rejectAllStagedChanges } from '../../lib/staged-apply'
+import { displayPath } from '../../lib/diff'
+import { buildHunks, type Hunk, type HunkLine } from '../../lib/hunks'
import { log } from '../../lib/logger'
import { HINWEIS_TEXT, HINWEIS_ZEILE } from '../../lib/hinweis'
+import { DIFF_TONE, DIFF_LINE_NO, DIFF_ADDED_COUNT, DIFF_REMOVED_COUNT, DIFF_SURFACE, DIFF_HUNK_HEAD } from './diff-tones'
interface Props {
/** Active conversation id — the panel scopes itself to this chat. */
@@ -13,13 +14,18 @@ interface Props {
}
/**
- * Right-sidebar panel that surfaces Codex's queued `file_write` calls when
- * Stage-and-Approve is on. Each change shows its diff and offers per-row
- * Apply/Reject; the footer offers Apply-all/Reject-all for big refactors.
+ * The review of Codex's staged `file_write` / `file_edit` calls (Ask mode),
+ * at the top of the Code transcript.
*
- * `Apply` calls the same `file_write` tool the executor would have called
- * inline — the bridge sees an identical request, so the diff the user
- * approved is exactly what lands on disk.
+ * Review like an editor does it: every hunk of a file can be accepted or
+ * rejected on its own, a file as a whole, or everything at once. Applying a
+ * file writes the original with only the accepted hunks in (lib/hunks), and
+ * the model hears at its next tool result what was left out
+ * (hooks/codex/staged-writes.ts).
+ *
+ * `Apply` goes through the shared trusted write path (lib/staged-apply), the
+ * same call Codex auto-apply uses, so the diff the user approved is what
+ * lands on disk.
*/
// Module-scoped stable empty-array reference. Zustand selectors run on
// every store update; returning a fresh `[]` literal (or any new object)
@@ -28,16 +34,47 @@ interface Props {
// staged changes yet.
const EMPTY_CHANGES: readonly StagedChange[] = Object.freeze([])
+/** Lines drawn per file before "Show more". A 2000 line rewrite would
+ * otherwise stall the transcript. */
+const MAX_LINES_PER_FILE = 160
+
+/** A phone width starts closed: the open list would push the transcript
+ * off the screen (375 px shot, 3.1.0 review). */
+function startsOpen(): boolean {
+ try {
+ return !(typeof window !== 'undefined' && window.matchMedia?.('(max-width: 639px)').matches)
+ } catch {
+ return true
+ }
+}
+
+// The hunk buttons show on hover where there is hover and room; on touch and
+// narrow screens there is no hover, so they stay visible.
+const HOVER_ONLY =
+ '[@media(hover:hover)_and_(min-width:640px)]:opacity-0 ' +
+ '[@media(hover:hover)_and_(min-width:640px)]:group-hover/hunk:opacity-100 ' +
+ '[@media(hover:hover)_and_(min-width:640px)]:group-focus-within/hunk:opacity-100'
+
export function StagedChangesPanel({ chatId }: Props) {
const changes = useStagedChangesStore((s) =>
chatId ? s.byChat[chatId] ?? EMPTY_CHANGES : EMPTY_CHANGES,
) as StagedChange[]
- const remove = useStagedChangesStore((s) => s.remove)
- const clear = useStagedChangesStore((s) => s.clear)
- const [expanded, setExpanded] = useState(true)
+ const [expanded, setExpanded] = useState(startsOpen)
const [applying, setApplying] = useState<Set<string>>(new Set())
const [errors, setErrors] = useState<Record<string, string>>({})
+ const totals = useMemo(() => {
+ let added = 0
+ let removed = 0
+ for (const c of changes) {
+ for (const h of buildHunks(c.oldContent ?? '', c.newContent).hunks) {
+ added += h.added
+ removed += h.removed
+ }
+ }
+ return { added, removed }
+ }, [changes])
+
if (!chatId || changes.length === 0) return null
async function applyOne(change: StagedChange) {
@@ -49,15 +86,11 @@ export function StagedChangesPanel({ chatId }: Props) {
return rest
})
try {
- // Shared trusted write path (lib/staged-apply) — the same call Codex
- // auto-apply uses, so the reviewed diff and the auto-applied diff can
- // never diverge.
await applyStagedChange(chatId, change)
} catch (e) {
- // Apply failures leave the entry in the queue so the user can retry — and
- // the reason has to reach the row, not just the log. The row simply
- // staying put looked like a dead button (and now that a stale-file apply
- // is REFUSED, the reason is the whole point).
+ // Apply failures leave the entry in the queue so the user can retry, and
+ // the reason has to reach the row, not just the log. A stale-file apply
+ // is REFUSED, and the reason is the whole point.
log.error('[StagedChangesPanel] apply failed', { err: e })
const message = e instanceof Error ? e.message : String(e)
setErrors((prev) => ({ ...prev, [change.id]: message }))
@@ -73,151 +106,295 @@ export function StagedChangesPanel({ chatId }: Props) {
async function applyAll() {
if (!chatId) return
for (const change of [...changes]) {
- // Sequential on purpose, not an oversight: two changes can touch the same
- // file, and `applyOne` reads-modifies-writes. In parallel the later write
- // would be based on a snapshot taken before the earlier one landed.
- // (Hier stand eine Unterdrueckung der Regel `no-await-in-loop`. Die ist
- // in KEINER Config dieses Baums eingeschaltet — die Zeile hat nie etwas
- // unterdrueckt, sie hat nur behauptet, es gaebe ein Gate. Der Grund war
- // richtig, die Form war eine Luege; der Grund bleibt.)
+ // Sequential on purpose: two changes can touch the same file, and
+ // `applyOne` reads-modifies-writes. In parallel the later write would be
+ // based on a snapshot taken before the earlier one landed.
await applyOne(change)
}
}
function rejectOne(change: StagedChange) {
if (!chatId) return
- remove(chatId, change.id)
+ rejectStagedChange(chatId, change)
}
function rejectAll() {
if (!chatId) return
- clear(chatId)
+ rejectAllStagedChanges(chatId)
+ }
+
+ /** A hunk decided. Once every hunk of the file is, the file is done: all
+ * rejected drops it, anything accepted writes it with the rejects left out. */
+ function decide(change: StagedChange, hunk: number, decision: 'accepted' | 'rejected' | null) {
+ if (!chatId) return
+ const store = useStagedChangesStore.getState()
+ store.decideHunk(chatId, change.id, hunk, decision)
+ if (!decision) return
+ const latest = store.get(chatId, change.id)
+ if (!latest) return
+ const hunks = buildHunks(latest.oldContent ?? '', latest.newContent).hunks
+ const d = latest.hunkDecisions ?? {}
+ if (!hunks.every((h) => d[h.index])) return
+ if (hunks.every((h) => d[h.index] === 'rejected')) rejectOne(latest)
+ else void applyOne(latest)
}
+ const count = changes.length
return (
- // Die Kopfzeile war komplett in Gelb getaucht, Flaeche, Symbole und
- // Schrift. Wartende Aenderungen sind aber kein Zwischenfall, sondern eine
- // Liste, die auf einen Klick wartet: sie traegt jetzt dieselbe neutrale
- // Haut wie die uebrigen Abschnitte der Spalte, und die Zahl daneben ist
- // das Signal (`lib/hinweis.ts`).
+ // Neutral skin like the other sections of the column; the count is the
+ // signal (`lib/hinweis.ts`).
<div className="shrink-0 border-b border-gray-200 dark:border-white/[0.04]" data-testid="staged-changes-panel">
- <button
- onClick={() => setExpanded(!expanded)}
- className="w-full flex items-center justify-between px-2 py-1.5 group hover:bg-gray-100/70 dark:hover:bg-white/[0.04] transition-colors"
- data-testid="staged-changes-header"
- >
- <span className="flex items-center gap-1.5">
+ {/* One line, open or closed: what waits, Review, Reject all, Apply all.
+ Apply all and Reject all live here and not under the list, so they
+ never scroll away with the diffs (t14 on the box, 2026-09-06). */}
+ <div className="flex items-center gap-1 px-2 py-1" data-testid="staged-changes-header">
+ <button
+ onClick={() => setExpanded(!expanded)}
+ aria-expanded={expanded}
+ className="flex min-w-0 flex-1 items-center gap-1.5 rounded py-0.5 text-left hover:bg-gray-100/70 dark:hover:bg-white/[0.04] transition-colors"
+ data-testid="staged-changes-toggle"
+ >
{expanded ? (
- <ChevronDown size={11} className="text-gray-500 dark:text-gray-400" />
+ <ChevronDown size={12} className="shrink-0 hidden sm:block text-gray-500 dark:text-gray-400" />
) : (
- <ChevronRight size={11} className="text-gray-500 dark:text-gray-400" />
+ <ChevronRight size={12} className="shrink-0 hidden sm:block text-gray-500 dark:text-gray-400" />
)}
- <FileText size={10} className="text-gray-500 dark:text-gray-400" />
- <span className="t-micro font-semibold text-gray-800 dark:text-gray-200">
- Pending ({changes.length})
+ <FileText size={12} className="shrink-0 hidden sm:block text-gray-500 dark:text-gray-400" />
+ <span className="t-micro font-semibold truncate text-gray-800 dark:text-gray-200">
+ {count} {count === 1 ? 'change' : 'changes'} waiting
</span>
- </span>
- </button>
-
- {/* The list scrolls inside a cap of the column. Without the cap two
- staged files with long diffs took the whole column and the
- transcript below shrank to zero height, so the shell approval
- card that followed sat behind the composer with no way to reach
- it (t10 on the box, 2026-09-06: run parked on "Waiting for your
- approval" for 15 minutes). */}
+ <span className="t-mono shrink-0 hidden sm:inline">
+ {totals.added > 0 && <span className={DIFF_ADDED_COUNT}>+{totals.added}</span>}
+ {totals.removed > 0 && <span className={`${DIFF_REMOVED_COUNT} pl-1`}>-{totals.removed}</span>}
+ </span>
+ </button>
+ <button
+ onClick={() => setExpanded(!expanded)}
+ className="shrink-0 px-1.5 py-1 rounded t-micro font-medium text-gray-600 hover:text-gray-900 hover:bg-gray-100 dark:text-gray-300 dark:hover:text-white dark:hover:bg-white/[0.06] transition-colors"
+ data-testid="staged-changes-review"
+ >
+ {expanded ? 'Hide' : 'Review'}
+ </button>
+ <button
+ onClick={rejectAll}
+ title="Reject all"
+ aria-label="Reject all"
+ // Closed on a phone the bar is "N changes waiting, Review, Apply all";
+ // Reject all joins once the list is open.
+ className={`shrink-0 items-center gap-1 px-1.5 py-1 rounded t-micro font-medium text-gray-600 ${expanded ? 'flex' : 'hidden sm:flex'} hover:text-red-700 hover:bg-red-50 dark:text-gray-300 dark:hover:text-red-300 dark:hover:bg-red-500/10 transition-colors`}
+ data-testid="reject-all"
+ >
+ <X size={12} />
+ <span className="hidden sm:inline">Reject all</span>
+ </button>
+ <button
+ onClick={applyAll}
+ className="shrink-0 px-2 py-1 rounded-md t-micro font-semibold bg-emerald-600 hover:bg-emerald-700 text-white transition-colors"
+ data-testid="apply-all"
+ >
+ Apply all
+ </button>
+ </div>
+
+ {/* The list scrolls inside a cap. Without it two staged files with
+ long diffs took the whole column and the shell approval card below
+ sat behind the composer (t10 on the box, 2026-09-06). With the
+ header line the panel stays under ~40 % of the window. */}
{expanded && (
- <div className="px-1.5 pb-2 space-y-1.5 max-h-[40vh] overflow-y-auto scrollbar-thin" data-testid="staged-changes-list">
- {changes.map((change) => {
- const isApplying = applying.has(change.id)
- const counts = change.diff ? parseUnifiedDiff(change.diff) : null
- return (
- <div
- key={change.id}
- className="rounded border border-gray-200 dark:border-white/[0.08] bg-white dark:bg-black/20"
- data-testid="staged-change"
- >
- <div className="flex items-center justify-between gap-1 px-1.5 py-1 border-b border-gray-100 dark:border-white/[0.04] text-[0.55rem]">
- <span
- className="font-mono truncate text-gray-700 dark:text-gray-300"
- title={change.path}
- >
- {displayPath(change.path)}
- </span>
- <span className="flex items-center gap-0.5 shrink-0">
- {counts && counts.added > 0 && (
- <span className="font-mono text-emerald-500 pr-0.5">+{counts.added}</span>
- )}
- {counts && counts.removed > 0 && (
- <span className="font-mono text-red-400 pr-0.5">-{counts.removed}</span>
- )}
- <button
- onClick={() => applyOne(change)}
- disabled={isApplying}
- title="Apply"
- className="p-0.5 rounded hover:bg-emerald-100 dark:hover:bg-emerald-500/20 text-emerald-600 disabled:opacity-50"
- >
- <Check size={10} />
- </button>
- <button
- onClick={() => rejectOne(change)}
- disabled={isApplying}
- title="Reject"
- className="p-0.5 rounded hover:bg-red-100 dark:hover:bg-red-500/20 text-red-500 disabled:opacity-50"
- >
- <X size={10} />
- </button>
- </span>
- </div>
- {errors[change.id] && (
- // Eine Zeile Rot, keine rote Flaeche: der Grund muss lesbar
- // sein, nicht laut. Die Farbe traegt die Dringlichkeit.
- // Die Zeile baut sich hier selbst, statt <Hinweis> zu nehmen,
- // weil sie ihre Testmarke behaelt und ins Kaestchen der
- // Aenderung eingerueckt sitzt; die Klassen kommen trotzdem
- // aus der einen Regel.
- <div
- role="alert"
- className={`px-1.5 py-1 ${HINWEIS_ZEILE} ${HINWEIS_TEXT.fehler}`}
- data-testid="staged-change-error"
- >
- {errors[change.id]}
- </div>
- )}
- {change.diff && (
- <div className="text-[0.5rem]">
- <DiffView diff={change.diff} maxLines={40} showPath={false} />
- </div>
- )}
- </div>
- )
- })}
+ <div className="px-1.5 pb-2 space-y-1.5 max-h-[30vh] sm:max-h-[36vh] overflow-y-auto scrollbar-thin" data-testid="staged-changes-list">
+ {changes.map((change) => (
+ <StagedFile
+ key={change.id}
+ change={change}
+ busy={applying.has(change.id)}
+ error={errors[change.id]}
+ onAccept={() => applyOne(change)}
+ onReject={() => rejectOne(change)}
+ onDecide={(hunk, d) => decide(change, hunk, d)}
+ />
+ ))}
</div>
)}
+ </div>
+ )
+}
- {/* Apply all and Reject all sit OUTSIDE the scroll cap. Inside it they
- scrolled away with the diffs: with two long files the footer sat
- under the fold of the list and a click without scrolling hit
- nothing (t14 on the box, 2026-09-06). */}
- {expanded && (
- <div className="px-1.5 pb-2">
- <div className="flex items-center gap-1 pt-0.5">
+function StagedFile({ change, busy, error, onAccept, onReject, onDecide }: {
+ change: StagedChange
+ busy: boolean
+ error?: string
+ onAccept: () => void
+ onReject: () => void
+ onDecide: (hunk: number, decision: 'accepted' | 'rejected' | null) => void
+}) {
+ const hunks = useMemo(() => buildHunks(change.oldContent ?? '', change.newContent).hunks, [change.oldContent, change.newContent])
+ const [showAll, setShowAll] = useState(false)
+ const decisions = change.hunkDecisions ?? {}
+ const added = hunks.reduce((a, h) => a + h.added, 0)
+ const removed = hunks.reduce((a, h) => a + h.removed, 0)
+ const rejected = hunks.filter((h) => decisions[h.index] === 'rejected').length
+
+ // Hunks up to the line cap; the rest behind "Show more".
+ let budget = MAX_LINES_PER_FILE
+ const visible: Hunk[] = []
+ for (const h of hunks) {
+ if (!showAll && visible.length > 0 && budget - h.lines.length < 0) break
+ visible.push(h)
+ budget -= h.lines.length
+ }
+ const hiddenParts = hunks.length - visible.length
+
+ return (
+ <div className={`rounded border ${DIFF_SURFACE} overflow-hidden`} data-testid="staged-change">
+ <div className="flex items-center gap-1.5 px-2 py-1 border-b border-gray-100 dark:border-white/[0.06]">
+ <span className="t-mono min-w-0 flex-1 truncate text-gray-800 dark:text-gray-200" title={change.path}>
+ {displayPath(change.path)}
+ </span>
+ {/* On a phone the path needs the room; the header line has the totals. */}
+ <span className="t-mono shrink-0 hidden sm:inline">
+ {added > 0 && <span className={DIFF_ADDED_COUNT}>+{added}</span>}
+ {removed > 0 && <span className={`${DIFF_REMOVED_COUNT} pl-1`}>-{removed}</span>}
+ </span>
+ {rejected > 0 && (
+ <span className="t-micro shrink-0 hidden sm:inline text-gray-500 dark:text-gray-400" data-testid="staged-change-rejected-count">
+ {rejected} of {hunks.length} rejected
+ </span>
+ )}
+ <button
+ onClick={onReject}
+ disabled={busy}
+ title="Reject file"
+ aria-label={`Reject ${displayPath(change.path)}`}
+ className="shrink-0 p-1 rounded text-red-600 hover:bg-red-50 dark:text-red-400 dark:hover:bg-red-500/15 disabled:opacity-50"
+ data-testid="staged-change-reject"
+ >
+ <X size={13} />
+ </button>
+ <button
+ onClick={onAccept}
+ disabled={busy}
+ title={rejected > 0 ? 'Apply the rest' : 'Accept file'}
+ aria-label={`Accept ${displayPath(change.path)}`}
+ className="shrink-0 p-1 rounded text-emerald-700 hover:bg-emerald-50 dark:text-emerald-400 dark:hover:bg-emerald-500/15 disabled:opacity-50"
+ data-testid="staged-change-accept"
+ >
+ <Check size={13} />
+ </button>
+ </div>
+ {error && (
+ // One line of red, no red block: the reason must be readable, not loud.
+ <div role="alert" className={`px-2 py-1 ${HINWEIS_ZEILE} ${HINWEIS_TEXT.fehler}`} data-testid="staged-change-error">
+ {error}
+ </div>
+ )}
+ {hunks.length === 0 && (
+ <div className="px-2 py-1 t-micro text-gray-500 dark:text-gray-400">No visible change (line endings only).</div>
+ )}
+ {visible.map((h) => (
+ <HunkBlock
+ key={h.index}
+ hunk={h}
+ single={hunks.length === 1}
+ decision={decisions[h.index]}
+ busy={busy}
+ onDecide={(d) => onDecide(h.index, d)}
+ />
+ ))}
+ {hiddenParts > 0 && (
+ <button
+ onClick={() => setShowAll(true)}
+ className="w-full px-2 py-1 t-micro text-left text-gray-500 hover:text-gray-800 dark:text-gray-400 dark:hover:text-gray-200 border-t border-gray-100 dark:border-white/[0.06]"
+ >
+ Show {hiddenParts} more {hiddenParts === 1 ? 'part' : 'parts'}
+ </button>
+ )}
+ </div>
+ )
+}
+
+function hunkLabel(h: Hunk): string {
+ const [start, n] = h.newCount > 0 ? [h.newStart, h.newCount] : [h.oldStart, h.oldCount]
+ return n <= 1 ? `Line ${start}` : `Lines ${start}-${start + n - 1}`
+}
+
+function HunkBlock({ hunk, single, decision, busy, onDecide }: {
+ hunk: Hunk
+ single: boolean
+ decision?: 'accepted' | 'rejected'
+ busy: boolean
+ onDecide: (decision: 'accepted' | 'rejected' | null) => void
+}) {
+ return (
+ <div
+ className="group/hunk border-t first:border-t-0 border-gray-100 dark:border-white/[0.06]"
+ data-testid="staged-hunk"
+ data-decision={decision ?? 'open'}
+ >
+ <div className={`flex items-center gap-1 px-2 py-0.5 ${DIFF_HUNK_HEAD}`}>
+ <span className="t-micro min-w-0 flex-1 truncate">{hunkLabel(hunk)}</span>
+ {decision ? (
+ <>
+ <span className={`t-micro font-medium ${decision === 'rejected' ? 'text-red-700 dark:text-red-400' : 'text-emerald-700 dark:text-emerald-400'}`}>
+ {decision === 'rejected' ? 'Rejected' : 'Accepted'}
+ </span>
+ <button
+ onClick={() => onDecide(null)}
+ disabled={busy}
+ className="flex items-center gap-0.5 px-1.5 py-0.5 rounded t-micro text-gray-600 hover:bg-gray-200/70 dark:text-gray-300 dark:hover:bg-white/10 disabled:opacity-50"
+ data-testid="hunk-undo"
+ >
+ <Undo2 size={11} /> Undo
+ </button>
+ </>
+ ) : (
+ <span className={`flex items-center gap-1 transition-opacity ${HOVER_ONLY}`}>
<button
- onClick={applyAll}
- className="flex-1 px-1.5 py-1 rounded-md text-[0.55rem] font-medium bg-emerald-500 hover:bg-emerald-600 text-white transition-colors"
- data-testid="apply-all"
+ onClick={() => onDecide('rejected')}
+ disabled={busy}
+ aria-label={single ? 'Reject this change' : `Reject ${hunkLabel(hunk).toLowerCase()}`}
+ className="px-1.5 py-0.5 rounded t-micro font-medium text-red-700 hover:bg-red-100 dark:text-red-300 dark:hover:bg-red-500/15 disabled:opacity-50"
+ data-testid="hunk-reject"
>
- Apply all
+ Reject
</button>
<button
- onClick={rejectAll}
- className="flex-1 px-1.5 py-1 rounded-md text-[0.55rem] font-medium bg-gray-200 dark:bg-white/10 hover:bg-gray-300 dark:hover:bg-white/15 text-gray-800 dark:text-gray-200 transition-colors"
- data-testid="reject-all"
+ onClick={() => onDecide('accepted')}
+ disabled={busy}
+ aria-label={single ? 'Accept this change' : `Accept ${hunkLabel(hunk).toLowerCase()}`}
+ className="px-1.5 py-0.5 rounded t-micro font-medium text-emerald-800 bg-emerald-100 hover:bg-emerald-200 dark:text-emerald-200 dark:bg-emerald-500/15 dark:hover:bg-emerald-500/25 disabled:opacity-50"
+ data-testid="hunk-accept"
>
- Reject all
+ Accept
</button>
+ </span>
+ )}
+ </div>
+ {/* A decided hunk folds to its line, so the list gets shorter as the
+ review goes on. Undo opens it again. */}
+ {!decision && (
+ <div className="overflow-x-auto scrollbar-thin">
+ {/* No ligatures: in a diff "=>" has to read as the two characters it is. */}
+ <div className="t-mono leading-5 min-w-max py-0.5 [font-variant-ligatures:none]">
+ {hunk.lines.map((l, i) => <DiffRow key={i} line={l} />)}
</div>
</div>
)}
</div>
)
}
+
+function DiffRow({ line }: { line: HunkLine }) {
+ const tone = DIFF_TONE[line.kind]
+ const no = line.kind === 'remove' ? line.oldLine : line.newLine
+ const sign = line.kind === 'add' ? '+' : line.kind === 'remove' ? '-' : ' '
+ return (
+ <div className={`flex pr-3 ${tone.row}`} data-kind={line.kind}>
+ <span className={`w-9 shrink-0 select-none pr-2 text-right ${DIFF_LINE_NO}`}>{no}</span>
+ <span className={`w-3 shrink-0 select-none ${tone.sign}`}>{sign}</span>
+ <span className="whitespace-pre">
+ {line.text || ' '}
+ {line.noNewline && <span className={`pl-2 t-micro ${DIFF_LINE_NO}`}>no newline at end</span>}
+ </span>
+ </div>
+ )
+}
diff --git a/src/components/chat/__tests__/die-karte-bleibt-erreichbar.test.ts b/src/components/chat/__tests__/die-karte-bleibt-erreichbar.test.ts
index 6e31f326..8502d2b8 100644
--- a/src/components/chat/__tests__/die-karte-bleibt-erreichbar.test.ts
+++ b/src/components/chat/__tests__/die-karte-bleibt-erreichbar.test.ts
@@ -22,7 +22,11 @@ describe('the approval card stays reachable', () => {
it('caps the Pending list inside the column and lets it scroll on its own', () => {
const src = read('../StagedChangesPanel.tsx')
const list = src.slice(src.indexOf('data-testid="staged-changes-list"') - 200, src.indexOf('data-testid="staged-changes-list"'))
- expect(list).toMatch(/max-h-\[40vh\]/)
+ // 3.1.0 (U3, per hunk review): 30vh on a phone, 36vh from sm up, instead
+ // of 40vh. The header line with Apply all / Reject all now sits above the
+ // list, and list plus header together have to stay under ~40 % of the
+ // window (measured in the 375 px review shots).
+ expect(list).toMatch(/max-h-\[30vh\] sm:max-h-\[36vh\]/)
expect(list).toMatch(/overflow-y-auto/)
// The panel itself never grows at the transcript's expense.
expect(src).toMatch(/className="shrink-0 border-b[^"]*" data-testid="staged-changes-panel"/)
@@ -30,15 +34,22 @@ describe('the approval card stays reachable', () => {
it('keeps Apply all and Reject all outside the scroll cap, so they never scroll away with the diffs', () => {
const src = read('../StagedChangesPanel.tsx')
+ // 3.1.0 (U3): the two buttons moved from a footer under the list into the
+ // one line header above it, so the closed panel is a single bar ("2
+ // changes waiting, Review, Apply all") at 375 px. The rule this test
+ // guards is unchanged: they are siblings of the list, never inside it.
+ const header = src.indexOf('data-testid="staged-changes-header"')
const listOpen = src.indexOf('data-testid="staged-changes-list"')
- const footer = src.indexOf('data-testid="apply-all"')
- expect(listOpen).toBeGreaterThan(0)
- expect(footer).toBeGreaterThan(listOpen)
- // Between the list and the footer the list is closed and a second
- // `expanded` block opens: the footer is a sibling of the list, not a child.
- const between = src.slice(listOpen, footer)
- expect(between).toMatch(/\{expanded && \(\s*<div className="px-1\.5 pb-2">/)
- expect(src.indexOf('data-testid="reject-all"')).toBeGreaterThan(footer)
+ const applyAll = src.indexOf('data-testid="apply-all"')
+ const rejectAll = src.indexOf('data-testid="reject-all"')
+ expect(header).toBeGreaterThan(0)
+ expect(applyAll).toBeGreaterThan(header)
+ expect(rejectAll).toBeGreaterThan(header)
+ expect(listOpen).toBeGreaterThan(applyAll)
+ expect(listOpen).toBeGreaterThan(rejectAll)
+ // The header is closed before the list opens: not a parent of the list.
+ const between = src.slice(applyAll, listOpen)
+ expect(between).toMatch(/<\/div>\s*\{\/\*[\s\S]*?\*\/\}\s*\{expanded && \(\s*<div className="px-1\.5 pb-2 space-y-1\.5 max-h/)
})
it('gives the transcript a floor so no side panel can squeeze it to nothing', () => {
diff --git a/src/components/chat/__tests__/review-per-hunk.test.tsx b/src/components/chat/__tests__/review-per-hunk.test.tsx
new file mode 100644
index 00000000..7897a895
--- /dev/null
+++ b/src/components/chat/__tests__/review-per-hunk.test.tsx
@@ -0,0 +1,137 @@
+/**
+ * @vitest-environment jsdom
+ *
+ * The review panel (Code tab, Ask mode): every hunk has its own Accept and
+ * Reject, a decided hunk folds and can be undone, the last decision resolves
+ * the file, and the panel closes to one line.
+ *
+ * Run: npx vitest run src/components/chat/__tests__/review-per-hunk.test.tsx
+ */
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
+import { createElement } from 'react'
+import { render, cleanup, fireEvent, screen, waitFor, within } from '@testing-library/react'
+
+const lib = vi.hoisted(() => ({
+ applyStagedChange: vi.fn(async () => true),
+ rejectStagedChange: vi.fn(),
+ rejectAllStagedChanges: vi.fn(),
+}))
+vi.mock('../../../lib/staged-apply', () => lib)
+
+const { StagedChangesPanel } = await import('../StagedChangesPanel')
+const { useStagedChangesStore } = await import('../../../stores/stagedChangesStore')
+
+const CHAT = 'chat-review'
+const base = Array.from({ length: 30 }, (_, i) => `line ${i + 1}`)
+const edited = [...base]
+edited[1] = 'TOP EDIT'
+edited[25] = 'BOTTOM EDIT'
+
+function stageTwoHunks(): string {
+ return useStagedChangesStore.getState().stage(CHAT, {
+ path: './src/a.ts',
+ oldContent: base.join('\n') + '\n',
+ newContent: edited.join('\n') + '\n',
+ diff: '',
+ })
+}
+
+function setNarrow(narrow: boolean) {
+ window.matchMedia = ((q: string) => ({ matches: narrow && q.includes('max-width'), media: q, addEventListener() {}, removeEventListener() {} })) as unknown as typeof window.matchMedia
+}
+
+beforeEach(() => {
+ useStagedChangesStore.setState({ byChat: {}, notes: {} })
+ Object.values(lib).forEach((f) => f.mockClear())
+ setNarrow(false)
+})
+afterEach(cleanup)
+
+describe('per hunk review', () => {
+ it('shows each hunk with its own Accept and Reject', () => {
+ stageTwoHunks()
+ render(createElement(StagedChangesPanel, { chatId: CHAT }))
+ const hunks = screen.getAllByTestId('staged-hunk')
+ expect(hunks).toHaveLength(2)
+ for (const h of hunks) {
+ expect(within(h).getByTestId('hunk-accept')).toBeTruthy()
+ expect(within(h).getByTestId('hunk-reject')).toBeTruthy()
+ }
+ expect(screen.getByText('src/a.ts')).toBeTruthy()
+ expect(screen.getByText('1 change waiting')).toBeTruthy()
+ })
+
+ it('a rejected hunk folds, says so, and Undo opens it again', () => {
+ const id = stageTwoHunks()
+ render(createElement(StagedChangesPanel, { chatId: CHAT }))
+ fireEvent.click(within(screen.getAllByTestId('staged-hunk')[0]).getByTestId('hunk-reject'))
+ const first = screen.getAllByTestId('staged-hunk')[0]
+ expect(first.getAttribute('data-decision')).toBe('rejected')
+ expect(within(first).getByText('Rejected')).toBeTruthy()
+ expect(first.querySelector('[data-kind]')).toBeNull()
+ expect(screen.getByTestId('staged-change-rejected-count').textContent).toBe('1 of 2 rejected')
+ expect(useStagedChangesStore.getState().get(CHAT, id)?.hunkDecisions).toEqual({ 0: 'rejected' })
+ // Not every hunk is decided yet: nothing is written.
+ expect(lib.applyStagedChange).not.toHaveBeenCalled()
+
+ fireEvent.click(within(first).getByTestId('hunk-undo'))
+ expect(screen.getAllByTestId('staged-hunk')[0].getAttribute('data-decision')).toBe('open')
+ })
+
+ it('the last decision applies the file with the rejected hunk left out', async () => {
+ const id = stageTwoHunks()
+ render(createElement(StagedChangesPanel, { chatId: CHAT }))
+ fireEvent.click(within(screen.getAllByTestId('staged-hunk')[0]).getByTestId('hunk-reject'))
+ fireEvent.click(within(screen.getAllByTestId('staged-hunk')[1]).getByTestId('hunk-accept'))
+ await waitFor(() => expect(lib.applyStagedChange).toHaveBeenCalledOnce())
+ const [, change] = lib.applyStagedChange.mock.calls[0] as unknown as [string, { id: string; hunkDecisions: unknown }]
+ expect(change.id).toBe(id)
+ expect(change.hunkDecisions).toEqual({ 0: 'rejected', 1: 'accepted' })
+ })
+
+ it('rejecting every hunk rejects the file', () => {
+ stageTwoHunks()
+ render(createElement(StagedChangesPanel, { chatId: CHAT }))
+ fireEvent.click(within(screen.getAllByTestId('staged-hunk')[0]).getByTestId('hunk-reject'))
+ fireEvent.click(within(screen.getAllByTestId('staged-hunk')[1]).getByTestId('hunk-reject'))
+ expect(lib.rejectStagedChange).toHaveBeenCalledOnce()
+ expect(lib.applyStagedChange).not.toHaveBeenCalled()
+ })
+
+ it('file and all buttons still work', async () => {
+ stageTwoHunks()
+ render(createElement(StagedChangesPanel, { chatId: CHAT }))
+ fireEvent.click(screen.getByTestId('staged-change-reject'))
+ expect(lib.rejectStagedChange).toHaveBeenCalledOnce()
+ fireEvent.click(screen.getByTestId('reject-all'))
+ expect(lib.rejectAllStagedChanges).toHaveBeenCalledWith(CHAT)
+ fireEvent.click(screen.getByTestId('apply-all'))
+ await waitFor(() => expect(lib.applyStagedChange).toHaveBeenCalled())
+ })
+})
+
+describe('the one line bar', () => {
+ it('starts closed on a phone width, with Review and Apply all on the line', () => {
+ setNarrow(true)
+ stageTwoHunks()
+ useStagedChangesStore.getState().stage(CHAT, { path: 'b.ts', oldContent: '', newContent: 'x\n', diff: '' })
+ render(createElement(StagedChangesPanel, { chatId: CHAT }))
+ expect(screen.queryByTestId('staged-changes-list')).toBeNull()
+ const bar = screen.getByTestId('staged-changes-header')
+ expect(within(bar).getByText('2 changes waiting')).toBeTruthy()
+ expect(within(bar).getByText('Review')).toBeTruthy()
+ expect(within(bar).getByText('Apply all')).toBeTruthy()
+
+ fireEvent.click(within(bar).getByText('Review'))
+ expect(screen.getByTestId('staged-changes-list')).toBeTruthy()
+ expect(within(bar).getByText('Hide')).toBeTruthy()
+ })
+
+ it('starts open on a desktop width and can be closed', () => {
+ stageTwoHunks()
+ render(createElement(StagedChangesPanel, { chatId: CHAT }))
+ expect(screen.getByTestId('staged-changes-list')).toBeTruthy()
+ fireEvent.click(screen.getByTestId('staged-changes-review'))
+ expect(screen.queryByTestId('staged-changes-list')).toBeNull()
+ })
+})
diff --git a/src/components/chat/diff-tones.ts b/src/components/chat/diff-tones.ts
new file mode 100644
index 00000000..ca563440
--- /dev/null
+++ b/src/components/chat/diff-tones.ts
@@ -0,0 +1,29 @@
+/**
+ * Colours of a diff line, light and dark. One place, so the review panel and
+ * the diff in a tool call read the same.
+ *
+ * The old diff was drawn for dark only (pale text on black/30): in the light
+ * theme it came out grey on grey. Here every row carries a tinted background
+ * and a dark text colour in light, a soft tint and a pale text in dark. Line
+ * numbers stay muted, the sign column carries the colour.
+ */
+export const DIFF_TONE = {
+ add: {
+ row: 'bg-emerald-50 text-emerald-950 dark:bg-emerald-500/[0.12] dark:text-emerald-100',
+ sign: 'text-emerald-700 dark:text-emerald-400',
+ },
+ remove: {
+ row: 'bg-red-50 text-red-950 dark:bg-red-500/[0.12] dark:text-red-100',
+ sign: 'text-red-700 dark:text-red-400',
+ },
+ context: {
+ row: 'text-gray-700 dark:text-gray-300',
+ sign: 'text-gray-400 dark:text-gray-600',
+ },
+} as const
+
+export const DIFF_LINE_NO = 'text-gray-400 dark:text-gray-500'
+export const DIFF_ADDED_COUNT = 'text-emerald-700 dark:text-emerald-400'
+export const DIFF_REMOVED_COUNT = 'text-red-700 dark:text-red-400'
+export const DIFF_SURFACE = 'bg-white dark:bg-black/30 border-gray-200 dark:border-white/10'
+export const DIFF_HUNK_HEAD = 'bg-gray-50 text-gray-500 dark:bg-white/[0.03] dark:text-gray-400'
diff --git a/src/hooks/codex/staged-writes.ts b/src/hooks/codex/staged-writes.ts
index bd8301a0..e0c6adb0 100644
--- a/src/hooks/codex/staged-writes.ts
+++ b/src/hooks/codex/staged-writes.ts
@@ -5,9 +5,12 @@ import { findStagedForPath, stagedReadResult, stagedListingNote } from '../../li
import { codexReadCtx, type CodexFsCtx, type CodexFileRead } from './workspace-fs'
import type { ToolArgs } from '../../api/mcp/types'
import type { StagedReview } from '../../lib/staged-apply'
+import type { ReviewNote } from '../../types/staged-changes'
-/** What the model hears after a blocking review. */
-export function reviewResult(review: StagedReview, path: string, kind: 'write' | 'edit'): string {
+/** What the model hears after a blocking review. A partial apply (some hunks
+ * rejected) left a note for this change; that note is the better answer. */
+export function reviewResult(review: StagedReview, path: string, kind: 'write' | 'edit', note?: string): string {
+ if (note && (review.outcome === 'applied' || review.outcome === 'rejected')) return note
switch (review.outcome) {
case 'applied': return kind === 'write' ? `Wrote ${path}. The user approved the change and it is on disk now.` : `Edited ${path}. The user approved the change and it is on disk now.`
case 'rejected': return `The user declined this change. ${path} was not written.`
@@ -61,6 +64,11 @@ export function reviewResult(review: StagedReview, path: string, kind: 'write' |
* einzige pruefbar.
*/
+/** Review notes as one block for the model. Short on purpose. */
+export function reviewNotesText(notes: readonly ReviewNote[]): string {
+ return `[User review: ${notes.map((n) => n.text).join(' ')}]`
+}
+
export interface StagedWriterDeps {
convId: string
/** Der Ordner, den auch der Systemprompt nennt. `'.'` = Sandbox pro Chat. */
@@ -105,6 +113,14 @@ function resolveStagedPath(path: string, workDir: string): string {
export function createStagedWriter(deps: StagedWriterDeps): StagedWriter {
const { convId, workDir, workspaceSlug, readFile, waitForReview } = deps
+ // A blocking review answers in the tool result itself, so its note is taken
+ // here and not handed out a second time with a later result.
+ const reviewed = async (stagedId: string, path: string, kind: 'write' | 'edit'): Promise<string> => {
+ const review = await waitForReview!(stagedId, path)
+ const note = useStagedChangesStore.getState().takeNotes(convId, stagedId)[0]?.text
+ return reviewResult(review, path, kind, note)
+ }
+
// Multi-File Stage-and-Approve (B10). When the user has codex
// stage mode on, file_write calls don't hit the disk — they
// queue in stagedChangesStore as "pending changes" the user
@@ -158,7 +174,7 @@ export function createStagedWriter(deps: StagedWriterDeps): StagedWriter {
newContent,
diff,
})
- if (waitForReview) return reviewResult(await waitForReview(stagedId, path), path, 'write')
+ if (waitForReview) return reviewed(stagedId, path, 'write')
return `Staged for review: ${path}. The user will apply or reject the change before it lands on disk.`
}
@@ -214,11 +230,23 @@ export function createStagedWriter(deps: StagedWriterDeps): StagedWriter {
newContent,
diff,
})
- if (waitForReview) return reviewResult(await waitForReview(stagedId, path), path, 'edit')
+ if (waitForReview) return reviewed(stagedId, path, 'edit')
return `Staged for review: ${path} (surgical edit). The user will apply or reject the change before it lands on disk.`
}
- const dispatch = (name: string, args: ToolArgs, passthrough: () => Promise<string>): Promise<string> => {
+ const dispatch = (name: string, args: ToolArgs, passthrough: () => Promise<string>): Promise<string> =>
+ route(name, args, passthrough).then(withReviewNotes)
+
+ // The desktop review runs beside the loop: a file or hunk the user rejected
+ // in the panel is invisible to the model, which then builds on code that is
+ // not there. The next tool result carries what was rejected, once.
+ const withReviewNotes = (result: string): string => {
+ if (!convId) return result
+ const notes = useStagedChangesStore.getState().takeNotes(convId)
+ return notes.length === 0 ? result : `${result}\n\n${reviewNotesText(notes)}`
+ }
+
+ const route = (name: string, args: ToolArgs, passthrough: () => Promise<string>): Promise<string> => {
if (name === 'file_write') return stageFileWrite(args)
if (name === 'file_edit') return stageFileEdit(args)
// Read-your-writes: staged content is invisible on disk, so reads
diff --git a/src/lib/__tests__/hunks.test.ts b/src/lib/__tests__/hunks.test.ts
new file mode 100644
index 00000000..b856b73b
--- /dev/null
+++ b/src/lib/__tests__/hunks.test.ts
@@ -0,0 +1,209 @@
+/**
+ * Per hunk review: the hunks match the diff the user sees, and any subset of
+ * them writes back exactly the lines that were accepted.
+ *
+ * Run: npx vitest run src/lib/__tests__/hunks.test.ts
+ */
+import { describe, it, expect } from 'vitest'
+import { buildHunks, applyHunks, contentWithDecisions, hunkHeader, splitKeepEol, describeHunk } from '../hunks'
+import { computeUnifiedDiff } from '../diff'
+
+const lines = (n: number, tag = 'l') => Array.from({ length: n }, (_, i) => `${tag}${i + 1}`)
+const text = (ls: string[], eol = '\n', trailing = true) => ls.join(eol) + (trailing && ls.length ? eol : '')
+
+/** Apply only the hunks in `keep`. */
+const only = (oldT: string, newT: string, keep: number[]) =>
+ applyHunks(buildHunks(oldT, newT), (i) => keep.includes(i), oldT, newT)
+
+describe('splitKeepEol', () => {
+ it('keeps every terminator and a last line without one', () => {
+ expect(splitKeepEol('')).toEqual([])
+ expect(splitKeepEol('a')).toEqual(['a'])
+ expect(splitKeepEol('a\nb\r\nc')).toEqual(['a\n', 'b\r\n', 'c'])
+ expect(splitKeepEol('a\n\n')).toEqual(['a\n', '\n'])
+ })
+})
+
+describe('buildHunks', () => {
+ it('identical texts have no hunks', () => {
+ expect(buildHunks('a\nb\n', 'a\nb\n').hunks).toEqual([])
+ })
+
+ it('two edits far apart are two hunks, close ones one', () => {
+ const base = lines(30)
+ const far = [...base]
+ far[2] = 'X'
+ far[25] = 'Y'
+ expect(buildHunks(text(base), text(far)).hunks).toHaveLength(2)
+ const near = [...base]
+ near[2] = 'X'
+ near[8] = 'Y' // 5 unchanged lines between: within 2 * 3
+ expect(buildHunks(text(base), text(near)).hunks).toHaveLength(1)
+ })
+
+ it('a file that did not exist before is one hunk of adds', () => {
+ const { hunks } = buildHunks('', 'a\nb\nc\n')
+ expect(hunks).toHaveLength(1)
+ expect(hunks[0].added).toBe(3)
+ expect(hunks[0].removed).toBe(0)
+ expect(hunks[0].lines.map((l) => l.kind)).toEqual(['add', 'add', 'add'])
+ })
+
+ it('reads CRLF as LF, a model writing LF into a CRLF file is not a full rewrite', () => {
+ const oldT = text(lines(20), '\r\n')
+ const changed = lines(20)
+ changed[10] = 'X'
+ const { hunks } = buildHunks(oldT, text(changed))
+ expect(hunks).toHaveLength(1)
+ expect(hunks[0].added).toBe(1)
+ expect(hunks[0].removed).toBe(1)
+ })
+
+ it('a missing newline at the end is a change, and says so', () => {
+ const { hunks } = buildHunks('a\nb\n', 'a\nb')
+ expect(hunks).toHaveLength(1)
+ const add = hunks[0].lines.find((l) => l.kind === 'add')
+ expect(add?.text).toBe('b')
+ expect(add?.noNewline).toBe(true)
+ })
+
+ it('matches the hunks of computeUnifiedDiff, header by header (random edits)', () => {
+ let seed = 7
+ const rnd = (n: number) => {
+ seed = (seed * 1103515245 + 12345) & 0x7fffffff
+ return seed % n
+ }
+ for (let round = 0; round < 300; round++) {
+ const base = lines(1 + rnd(40))
+ const next = [...base]
+ for (let e = 0; e < 1 + rnd(5); e++) {
+ const at = rnd(next.length + 1)
+ const what = rnd(3)
+ if (what === 0) next.splice(at, 0, `new${round}-${e}`)
+ else if (what === 1 && next.length > 0) next.splice(Math.min(at, next.length - 1), 1)
+ else if (next.length > 0) next[Math.min(at, next.length - 1)] = `chg${round}-${e}`
+ }
+ const oldT = text(base)
+ const newT = text(next)
+ const expected = computeUnifiedDiff('f', oldT, newT).split('\n').filter((l) => l.startsWith('@@'))
+ expect(buildHunks(oldT, newT).hunks.map(hunkHeader)).toEqual(expected)
+ }
+ })
+})
+
+describe('applyHunks', () => {
+ const base = lines(30)
+ const edited = [...base]
+ edited[0] = 'FIRST'
+ edited[14] = 'MIDDLE'
+ edited[29] = 'LAST'
+ const oldT = text(base)
+ const newT = text(edited)
+
+ it('three hunks: first line, middle, last line', () => {
+ expect(buildHunks(oldT, newT).hunks).toHaveLength(3)
+ })
+
+ it('all accepted is the new text, none the old text, byte for byte', () => {
+ expect(only(oldT, newT, [0, 1, 2])).toBe(newT)
+ expect(only(oldT, newT, [])).toBe(oldT)
+ })
+
+ it('applies exactly the chosen hunks, at the first and the last line too', () => {
+ const want = (first: boolean, mid: boolean, last: boolean) => {
+ const ls = [...base]
+ if (first) ls[0] = 'FIRST'
+ if (mid) ls[14] = 'MIDDLE'
+ if (last) ls[29] = 'LAST'
+ return text(ls)
+ }
+ expect(only(oldT, newT, [0])).toBe(want(true, false, false))
+ expect(only(oldT, newT, [1])).toBe(want(false, true, false))
+ expect(only(oldT, newT, [2])).toBe(want(false, false, true))
+ expect(only(oldT, newT, [0, 2])).toBe(want(true, false, true))
+ })
+
+ it('adjacent hunks (exactly 2 * context + 1 lines apart) stay independent', () => {
+ const b = lines(20)
+ const n = [...b]
+ n[2] = 'A' // gap of 7 unchanged lines to index 10
+ n[10] = 'B'
+ const o = text(b)
+ const nt = text(n)
+ expect(buildHunks(o, nt).hunks).toHaveLength(2)
+ const onlyB = [...b]
+ onlyB[10] = 'B'
+ expect(only(o, nt, [1])).toBe(text(onlyB))
+ })
+
+ it('inserts and deletions in separate hunks keep line counts right', () => {
+ const b = lines(25)
+ const n = [...b]
+ n.splice(20, 2) // delete l21, l22
+ n.splice(1, 0, 'INS1', 'INS2') // insert after l1
+ const o = text(b)
+ const nt = text(n)
+ expect(buildHunks(o, nt).hunks).toHaveLength(2)
+ const insOnly = [...b]
+ insOnly.splice(1, 0, 'INS1', 'INS2')
+ expect(only(o, nt, [0])).toBe(text(insOnly))
+ const delOnly = [...b]
+ delOnly.splice(20, 2)
+ expect(only(o, nt, [1])).toBe(text(delOnly))
+ })
+
+ it('keeps the trailing newline state of the side each part comes from', () => {
+ const b = lines(20)
+ const n = [...b]
+ n[1] = 'X'
+ const o = text(b, '\n', false) // no newline at the end
+ const nt = text(n, '\n', true) // newline added at the end
+ const { hunks } = buildHunks(o, nt)
+ expect(hunks).toHaveLength(2)
+ // only the newline at the end
+ expect(only(o, nt, [1])).toBe(text(b, '\n', true))
+ // only the edit, the file still ends without a newline
+ expect(only(o, nt, [0])).toBe(text(n, '\n', false))
+ })
+
+ it('CRLF file: rejected parts keep their CRLF bytes', () => {
+ const b = lines(20)
+ const n = [...b]
+ n[1] = 'X'
+ n[17] = 'Y'
+ const o = text(b, '\r\n')
+ const nt = text(n, '\r\n')
+ const firstOnly = [...b]
+ firstOnly[1] = 'X'
+ expect(only(o, nt, [0])).toBe(text(firstOnly, '\r\n'))
+ })
+
+ it('a new file with its single hunk rejected stays empty', () => {
+ expect(only('', 'a\nb\n', [])).toBe('')
+ })
+})
+
+describe('contentWithDecisions', () => {
+ it('a hunk without a decision counts as accepted', () => {
+ const b = lines(30)
+ const n = [...b]
+ n[0] = 'A'
+ n[28] = 'B'
+ const o = text(b)
+ const nt = text(n)
+ expect(contentWithDecisions(o, nt, undefined).content).toBe(nt)
+ expect(contentWithDecisions(o, nt, { 0: 'accepted' }).content).toBe(nt)
+ const r = contentWithDecisions(o, nt, { 1: 'rejected' })
+ expect(r.rejected.map((h) => h.index)).toEqual([1])
+ const want = [...b]
+ want[0] = 'A'
+ expect(r.content).toBe(text(want))
+ })
+
+ it('describes a rejected part in lines the model can find', () => {
+ const { hunks } = buildHunks('a\nb\nc\n', 'a\nB\nc\n')
+ expect(describeHunk(hunks[0])).toBe('original line 2')
+ const ins = buildHunks('a\n', 'a\nb\nc\n').hunks[0]
+ expect(describeHunk(ins)).toBe('your new lines 2-3')
+ })
+})
diff --git a/src/lib/__tests__/staged-apply-partial.test.ts b/src/lib/__tests__/staged-apply-partial.test.ts
new file mode 100644
index 00000000..85790d3c
--- /dev/null
+++ b/src/lib/__tests__/staged-apply-partial.test.ts
@@ -0,0 +1,158 @@
+/**
+ * Partial apply: a staged file with some hunks rejected writes the original
+ * with only the accepted hunks in, and the model hears what was left out at
+ * its next tool result.
+ *
+ * Run: npx vitest run src/lib/__tests__/staged-apply-partial.test.ts
+ */
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+
+vi.mock('../../api/backend', () => ({ backendCall: vi.fn() }))
+const { addMessage } = vi.hoisted(() => ({ addMessage: vi.fn() }))
+vi.mock('../../stores/chatStore', () => ({
+ useChatStore: { getState: () => ({ addMessage }) },
+}))
+
+import { backendCall } from '../../api/backend'
+import { applyStagedChange, rejectStagedChange, rejectAllStagedChanges, waitForStagedReview } from '../staged-apply'
+import { useStagedChangesStore } from '../../stores/stagedChangesStore'
+import { useAgentModeStore } from '../../stores/agentModeStore'
+import { createStagedWriter } from '../../hooks/codex/staged-writes'
+
+const backend = backendCall as unknown as ReturnType<typeof vi.fn>
+const CHAT = 'chat-partial'
+
+const base = Array.from({ length: 30 }, (_, i) => `line ${i + 1}`)
+const OLD = base.join('\n') + '\n'
+const edited = [...base]
+edited[1] = 'TOP EDIT'
+edited[25] = 'BOTTOM EDIT'
+const NEW = edited.join('\n') + '\n'
+
+let disk: string
+function wireBackend() {
+ backend.mockReset()
+ backend.mockImplementation(async (cmd: string, args: { content?: string }) => {
+ if (cmd === 'fs_read') return { content: disk }
+ if (cmd === 'fs_write') {
+ disk = args.content ?? ''
+ return { status: 'saved' }
+ }
+ return {}
+ })
+}
+
+const stage = () =>
+ useStagedChangesStore.getState().stage(CHAT, { path: 'src/a.ts', oldContent: OLD, newContent: NEW, diff: '' })
+
+beforeEach(() => {
+ disk = OLD
+ wireBackend()
+ addMessage.mockClear()
+ useStagedChangesStore.setState({ byChat: {}, notes: {} })
+ useAgentModeStore.setState({ workspaceSlugs: { [CHAT]: 'slug' } })
+})
+
+describe('partial apply', () => {
+ it('writes the original with only the accepted hunk, and leaves a note', async () => {
+ const id = stage()
+ useStagedChangesStore.getState().decideHunk(CHAT, id, 1, 'rejected')
+ await applyStagedChange(CHAT, useStagedChangesStore.getState().get(CHAT, id)!)
+
+ const want = [...base]
+ want[1] = 'TOP EDIT'
+ expect(disk).toBe(want.join('\n') + '\n')
+ expect(useStagedChangesStore.getState().list(CHAT)).toHaveLength(0)
+
+ const notes = useStagedChangesStore.getState().notes[CHAT]
+ expect(notes).toHaveLength(1)
+ expect(notes[0].text).toBe(
+ 'The user applied your change to src/a.ts but rejected 1 of 2 parts (original line 26). Those parts keep the original text. Read the file before you edit it again.',
+ )
+ expect(addMessage.mock.calls[0][1].content).toBe('Applied staged change: src/a.ts (1 of 2 parts, 1 rejected)')
+ })
+
+ it('uses the latest decisions even when the caller holds an older snapshot', async () => {
+ const id = stage()
+ const snapshot = useStagedChangesStore.getState().get(CHAT, id)!
+ useStagedChangesStore.getState().decideHunk(CHAT, id, 0, 'rejected')
+ await applyStagedChange(CHAT, snapshot)
+ const want = [...base]
+ want[25] = 'BOTTOM EDIT'
+ expect(disk).toBe(want.join('\n') + '\n')
+ })
+
+ it('an Undo opens the hunk again and the full change lands', async () => {
+ const id = stage()
+ useStagedChangesStore.getState().decideHunk(CHAT, id, 1, 'rejected')
+ useStagedChangesStore.getState().decideHunk(CHAT, id, 1, null)
+ await applyStagedChange(CHAT, useStagedChangesStore.getState().get(CHAT, id)!)
+ expect(disk).toBe(NEW)
+ expect(useStagedChangesStore.getState().notes[CHAT]).toBeUndefined()
+ })
+
+ it('a partial apply still merges with an edit made on disk meanwhile', async () => {
+ const id = stage()
+ useStagedChangesStore.getState().decideHunk(CHAT, id, 1, 'rejected')
+ const foreign = [...base]
+ foreign[14] = 'USER EDIT'
+ disk = foreign.join('\n') + '\n'
+ await applyStagedChange(CHAT, useStagedChangesStore.getState().get(CHAT, id)!)
+ const want = [...foreign]
+ want[1] = 'TOP EDIT'
+ expect(disk).toBe(want.join('\n') + '\n')
+ })
+})
+
+describe('rejecting', () => {
+ it('a rejected file leaves a note and writes nothing', () => {
+ const id = stage()
+ rejectStagedChange(CHAT, { id, path: 'src/a.ts' })
+ expect(backend).not.toHaveBeenCalled()
+ expect(useStagedChangesStore.getState().notes[CHAT][0].text).toBe('The user rejected your change to src/a.ts. Nothing was written to it.')
+ })
+
+ it('Reject all leaves one note per file', () => {
+ stage()
+ useStagedChangesStore.getState().stage(CHAT, { path: 'b.ts', oldContent: '', newContent: 'x\n', diff: '' })
+ rejectAllStagedChanges(CHAT)
+ expect(useStagedChangesStore.getState().list(CHAT)).toHaveLength(0)
+ expect(useStagedChangesStore.getState().notes[CHAT].map((n) => n.path)).toEqual(['src/a.ts', 'b.ts'])
+ })
+})
+
+describe('what the model hears', () => {
+ const writer = (waitForReview?: Parameters<typeof createStagedWriter>[0]['waitForReview']) =>
+ createStagedWriter({
+ convId: CHAT,
+ workDir: '.',
+ workspaceSlug: 'slug',
+ readFile: async () => ({ content: OLD }) as never,
+ waitForReview,
+ })
+
+ it('the next tool result carries the notes once', async () => {
+ const id = stage()
+ rejectStagedChange(CHAT, { id, path: 'src/a.ts' })
+ const w = writer()
+ const first = await w.dispatch('shell_execute', {}, async () => 'ok')
+ expect(first).toBe('ok\n\n[User review: The user rejected your change to src/a.ts. Nothing was written to it.]')
+ const second = await w.dispatch('shell_execute', {}, async () => 'ok')
+ expect(second).toBe('ok')
+ })
+
+ it('a blocking review (phone turn) answers with the partial note in the write result, not again later', async () => {
+ const w = writer((changeId, path) => {
+ // The user rejects the second hunk and applies the rest.
+ queueMicrotask(async () => {
+ useStagedChangesStore.getState().decideHunk(CHAT, changeId, 1, 'rejected')
+ await applyStagedChange(CHAT, useStagedChangesStore.getState().get(CHAT, changeId)!)
+ })
+ return waitForStagedReview(CHAT, changeId, path)
+ })
+ const result = await w.dispatch('file_write', { path: 'src/a.ts', content: NEW }, async () => 'unused')
+ expect(result).toMatch(/^The user applied your change to src\/a\.ts but rejected 1 of 2 parts/)
+ expect(result).not.toContain('[User review:')
+ expect(useStagedChangesStore.getState().notes[CHAT]).toBeUndefined()
+ })
+})
diff --git a/src/lib/hunks.ts b/src/lib/hunks.ts
new file mode 100644
index 00000000..37ec05e0
--- /dev/null
+++ b/src/lib/hunks.ts
@@ -0,0 +1,231 @@
+// Hunks of a staged change, for review part by part (accept or reject each).
+//
+// `computeUnifiedDiff` (lib/diff.ts) gives a string for display. Reviewing per
+// hunk needs more: the same grouping, but tied to the exact lines of both
+// versions, so that a subset of hunks can be written back byte for byte.
+//
+// Lines here keep their terminator ("a\n", "b\r\n", a last "c" without one).
+// Two lines are equal when they match after CRLF is read as LF: a model writes
+// LF into a CRLF file, and every line then differing would turn a three line
+// edit into one hunk over the whole file. The apply path (lib/staged-apply)
+// writes in the form the file on disk has anyway. A missing newline at the end
+// still counts as a difference, it is a real change of the file.
+//
+// The grouping is the one `computeUnifiedDiff` uses (git's rule: two changes
+// share a hunk when no more than 2 * context unchanged lines sit between
+// them), so the hunks the panel shows match the stored diff.
+
+import { diffLines } from './diff'
+
+export interface HunkLine {
+ kind: 'context' | 'add' | 'remove'
+ /** The line without its terminator. */
+ text: string
+ oldLine?: number
+ newLine?: number
+ /** Last line of its file and not ended by a newline. */
+ noNewline?: boolean
+}
+
+export interface Hunk {
+ index: number
+ /** 1-based start and length of the hunk, context included (git header). */
+ oldStart: number
+ oldCount: number
+ newStart: number
+ newCount: number
+ /** The changed lines only, 1-based and inclusive; an empty range has to < from. */
+ changedOld: { from: number; to: number }
+ changedNew: { from: number; to: number }
+ lines: HunkLine[]
+ added: number
+ removed: number
+}
+
+type Segment =
+ | { kind: 'equal'; a: number; b: number; len: number }
+ | { kind: 'change'; a: number; aLen: number; b: number; bLen: number; hunk: number }
+
+export interface HunkModel {
+ hunks: Hunk[]
+ /** Internal: the walk over both files that `applyHunks` replays. */
+ segments: Segment[]
+ oldLines: string[]
+ newLines: string[]
+}
+
+/** Lines with their terminator. "" has none, "a" has one, "a\n" has one. */
+export function splitKeepEol(text: string): string[] {
+ if (text === '') return []
+ const out = text.match(/[^\n]*\n|[^\n]+$/g)
+ return out ?? []
+}
+
+const keyOf = (line: string) => (line.endsWith('\r\n') ? `${line.slice(0, -2)}\n` : line)
+const bare = (line: string) => line.replace(/\r?\n$/, '')
+
+/** Build the hunks of old -> new. `context` as in `computeUnifiedDiff`. */
+export function buildHunks(oldText: string, newText: string, context = 3): HunkModel {
+ const a = splitKeepEol(oldText)
+ const b = splitKeepEol(newText)
+ const ops = diffLines(a.map(keyOf), b.map(keyOf))
+
+ // Ops to segments: one change segment for every run between two equal runs.
+ const segments: Segment[] = []
+ let ai = 0
+ let bi = 0
+ for (const op of ops) {
+ const n = op.text.length
+ if (op.kind === 'equal') {
+ segments.push({ kind: 'equal', a: ai, b: bi, len: n })
+ ai += n
+ bi += n
+ continue
+ }
+ const last = segments[segments.length - 1]
+ const seg = last && last.kind === 'change' ? last : null
+ const target = seg ?? { kind: 'change' as const, a: ai, aLen: 0, b: bi, bLen: 0, hunk: -1 }
+ if (!seg) segments.push(target)
+ if (op.kind === 'remove') { target.aLen += n; ai += n } else { target.bLen += n; bi += n }
+ }
+
+ // Changes to hunks: a gap wider than 2 * context starts a new one.
+ let hunk = -1
+ let lastChange = -1
+ for (let s = 0; s < segments.length; s++) {
+ const seg = segments[s]
+ if (seg.kind !== 'change') continue
+ if (lastChange === -1) {
+ hunk = 0
+ } else {
+ let gap = 0
+ for (let k = lastChange + 1; k < s; k++) {
+ const g = segments[k]
+ if (g.kind === 'equal') gap += g.len
+ }
+ if (gap > context * 2) hunk++
+ }
+ seg.hunk = hunk
+ lastChange = s
+ }
+
+ const hunks: Hunk[] = []
+ for (let h = 0; h <= hunk; h++) {
+ const first = segments.findIndex((s) => s.kind === 'change' && s.hunk === h)
+ let lastIdx = first
+ for (let s = first; s < segments.length; s++) {
+ const seg = segments[s]
+ if (seg.kind === 'change') {
+ if (seg.hunk !== h) break
+ lastIdx = s
+ }
+ }
+ const lines: HunkLine[] = []
+ const firstSeg = segments[first] as Extract<Segment, { kind: 'change' }>
+ const lastSeg = segments[lastIdx] as Extract<Segment, { kind: 'change' }>
+ const lead = Math.min(context, firstSeg.a, firstSeg.b)
+ const oldStart0 = firstSeg.a - lead
+ const newStart0 = firstSeg.b - lead
+ const pushContext = (aIdx: number, bIdx: number) => {
+ lines.push({ kind: 'context', text: bare(b[bIdx]), oldLine: aIdx + 1, newLine: bIdx + 1, noNewline: isLastWithoutEol(b, bIdx) })
+ }
+ for (let k = lead; k > 0; k--) pushContext(firstSeg.a - k, firstSeg.b - k)
+ let added = 0
+ let removed = 0
+ for (let s = first; s <= lastIdx; s++) {
+ const seg = segments[s]
+ if (seg.kind === 'equal') {
+ for (let k = 0; k < seg.len; k++) pushContext(seg.a + k, seg.b + k)
+ continue
+ }
+ for (let k = 0; k < seg.aLen; k++) {
+ lines.push({ kind: 'remove', text: bare(a[seg.a + k]), oldLine: seg.a + k + 1, noNewline: isLastWithoutEol(a, seg.a + k) })
+ }
+ for (let k = 0; k < seg.bLen; k++) {
+ lines.push({ kind: 'add', text: bare(b[seg.b + k]), newLine: seg.b + k + 1, noNewline: isLastWithoutEol(b, seg.b + k) })
+ }
+ removed += seg.aLen
+ added += seg.bLen
+ }
+ const endA = lastSeg.a + lastSeg.aLen
+ const endB = lastSeg.b + lastSeg.bLen
+ const trail = Math.min(context, a.length - endA, b.length - endB)
+ for (let k = 0; k < trail; k++) pushContext(endA + k, endB + k)
+ hunks.push({
+ index: h,
+ oldStart: oldStart0 + 1,
+ oldCount: endA + trail - oldStart0,
+ newStart: newStart0 + 1,
+ newCount: endB + trail - newStart0,
+ changedOld: { from: firstSeg.a + 1, to: endA },
+ changedNew: { from: firstSeg.b + 1, to: endB },
+ lines,
+ added,
+ removed,
+ })
+ }
+ return { hunks, segments, oldLines: a, newLines: b }
+}
+
+function isLastWithoutEol(lines: string[], i: number): boolean {
+ return i === lines.length - 1 && !lines[i].endsWith('\n')
+}
+
+/** The header `computeUnifiedDiff` writes for this hunk. */
+export function hunkHeader(h: Hunk): string {
+ return `@@ -${h.oldStart},${h.oldCount} +${h.newStart},${h.newCount} @@`
+}
+
+/**
+ * Old text with only the accepted hunks applied. All accepted gives the new
+ * text exactly, none accepted gives the old text exactly.
+ */
+export function applyHunks(model: HunkModel, accepted: (index: number) => boolean, oldText: string, newText: string): string {
+ const { hunks, segments, oldLines, newLines } = model
+ if (hunks.every((h) => accepted(h.index))) return newText
+ if (hunks.every((h) => !accepted(h.index))) return oldText
+ const out: string[] = []
+ for (const seg of segments) {
+ if (seg.kind === 'equal') {
+ for (let k = 0; k < seg.len; k++) out.push(oldLines[seg.a + k])
+ } else if (accepted(seg.hunk)) {
+ for (let k = 0; k < seg.bLen; k++) out.push(newLines[seg.b + k])
+ } else {
+ for (let k = 0; k < seg.aLen; k++) out.push(oldLines[seg.a + k])
+ }
+ }
+ // Taking a last line from one side and the line before it from the other can
+ // leave two lines glued together ("a" without its newline, then "b"). Every
+ // line but the last gets the newline it lost.
+ for (let i = 0; i < out.length - 1; i++) {
+ if (!out[i].endsWith('\n')) out[i] += eolOf(oldText, newText)
+ }
+ return out.join('')
+}
+
+function eolOf(...texts: string[]): string {
+ return texts.some((t) => /\r\n/.test(t)) && !texts.some((t) => /(^|[^\r])\n/.test(t)) ? '\r\n' : '\n'
+}
+
+export type HunkDecision = 'accepted' | 'rejected'
+
+/** What a staged change writes, given the per hunk decisions so far. A hunk
+ * without a decision counts as accepted: Apply on the file means "the rest". */
+export function contentWithDecisions(
+ oldText: string,
+ newText: string,
+ decisions: Record<number, HunkDecision> | undefined,
+): { content: string; model: HunkModel; rejected: Hunk[] } {
+ const model = buildHunks(oldText, newText)
+ const rejected = model.hunks.filter((h) => decisions?.[h.index] === 'rejected')
+ if (rejected.length === 0) return { content: newText, model, rejected }
+ const content = applyHunks(model, (i) => decisions?.[i] !== 'rejected', oldText, newText)
+ return { content, model, rejected }
+}
+
+/** A hunk in words, for the model: where it was, in lines it can find. */
+export function describeHunk(h: Hunk): string {
+ const range = (r: { from: number; to: number }) => (r.to <= r.from ? `line ${r.from}` : `lines ${r.from}-${r.to}`)
+ if (h.removed === 0) return `your new ${range(h.changedNew)}`
+ return `original ${range(h.changedOld)}`
+}
diff --git a/src/lib/staged-apply.ts b/src/lib/staged-apply.ts
index 15379c02..c9a34e90 100644
--- a/src/lib/staged-apply.ts
+++ b/src/lib/staged-apply.ts
@@ -18,6 +18,7 @@ import { useStagedChangesStore, type StagedChange } from '../stores/stagedChange
import { useChatStore } from '../stores/chatStore'
import { resolveChatWorkspaceSlug } from '../api/workspace-slug'
import { mergeThreeWay } from './three-way-merge'
+import { contentWithDecisions, describeHunk } from './hunks'
/**
* Line endings, the difference between "merged" and "we refused your own edit".
@@ -172,8 +173,14 @@ export async function applyStagedChange(chatId: string, change: StagedChange): P
}
}
-async function applyStagedChangeInner(chatId: string, change: StagedChange): Promise<boolean> {
- if (!stillPending(chatId, change)) return false
+async function applyStagedChangeInner(chatId: string, staged: StagedChange): Promise<boolean> {
+ if (!stillPending(chatId, staged)) return false
+ // Hunks the user rejected are left out: the file gets the original text
+ // there. The latest decisions count, read from the store, since the caller
+ // may hold a snapshot from before the last click.
+ const latest = useStagedChangesStore.getState().get(chatId, staged.id) ?? staged
+ const partial = contentWithDecisions(latest.oldContent ?? '', latest.newContent, latest.hunkDecisions)
+ const change: StagedChange = { ...latest, newContent: partial.content }
const jail = await jailFor(chatId)
const { content, merged } = await reconcile(jail, change)
if (!stillPending(chatId, change)) return false
@@ -191,6 +198,15 @@ async function applyStagedChangeInner(chatId: string, change: StagedChange): Pro
for (const fn of appliedListeners) {
try { fn(chatId, change.id) } catch { /* a listener never stops the write */ }
}
+ const total = partial.model.hunks.length
+ const left = partial.rejected.length
+ if (left > 0) {
+ useStagedChangesStore.getState().addNote(chatId, {
+ changeId: change.id,
+ path: change.path,
+ text: partialNote(change.path, partial.rejected.map(describeHunk), total),
+ })
+ }
useStagedChangesStore.getState().remove(chatId, change.id)
// Mirror the apply in the chat log so the user sees a confirmation in the
// main pane, not just the side-pane entry disappearing. A merge is named as
@@ -207,15 +223,39 @@ async function applyStagedChangeInner(chatId: string, change: StagedChange): Pro
useChatStore.getState().addMessage(chatId, {
id: crypto.randomUUID(),
role: 'system',
- content: merged > 0
+ content: (merged > 0
? `Applied staged change: ${change.path} (merged with ${merged} change${merged === 1 ? '' : 's'} made on disk since it was staged, so this file is not byte for byte the diff you approved)`
- : `Applied staged change: ${change.path}`,
+ : `Applied staged change: ${change.path}`)
+ + (left > 0 ? ` (${total - left} of ${total} parts, ${left} rejected)` : ''),
timestamp: Date.now(),
notice: merged > 0 ? 'warn' : 'info',
})
return true
}
+/** What the model hears when some hunks of a file were left out. */
+export function partialNote(path: string, rejected: string[], total: number): string {
+ return `The user applied your change to ${path} but rejected ${rejected.length} of ${total} parts (${rejected.join('; ')}). Those parts keep the original text. Read the file before you edit it again.`
+}
+
+/** What the model hears about a file the user rejected as a whole. */
+export function rejectedNote(path: string): string {
+ return `The user rejected your change to ${path}. Nothing was written to it.`
+}
+
+/** Reject one staged change and tell the model at its next tool result. */
+export function rejectStagedChange(chatId: string, change: Pick<StagedChange, 'id' | 'path'>): void {
+ const store = useStagedChangesStore.getState()
+ if (!store.get(chatId, change.id)) return
+ store.remove(chatId, change.id)
+ store.addNote(chatId, { changeId: change.id, path: change.path, text: rejectedNote(change.path) })
+}
+
+/** Reject every staged change of a chat. */
+export function rejectAllStagedChanges(chatId: string): void {
+ for (const change of useStagedChangesStore.getState().list(chatId)) rejectStagedChange(chatId, change)
+}
+
/** Apply the pending changes of a chat staged at or after `since` (all of
* them without it), sequentially (fs_write serializes per path anyway).
* Failures stay in the queue for manual retry and are reported by path
diff --git a/src/stores/stagedChangesStore.ts b/src/stores/stagedChangesStore.ts
index bc20bad7..49203507 100644
--- a/src/stores/stagedChangesStore.ts
+++ b/src/stores/stagedChangesStore.ts
@@ -2,7 +2,7 @@ import { create } from 'zustand'
import { persist } from 'zustand/middleware'
import { v4 as uuid } from 'uuid'
import { normalizeStagedPath } from '../lib/staged-overlay'
-import type { StagedChange } from '../types/staged-changes'
+import type { StagedChange, ReviewNote } from '../types/staged-changes'
import { idbStorage } from '../lib/idbStorage'
import { coalescedJSONStorage } from '../lib/coalescedStorage'
@@ -10,7 +10,7 @@ import { coalescedJSONStorage } from '../lib/coalescedStorage'
// sie lesen kann, ohne diesen Store zu importieren (der seinerseits
// normalizeStagedPath aus dem Overlay zieht). Re-Export, damit bestehende
// Importpfade unverändert bleiben.
-export type { StagedChange }
+export type { StagedChange, ReviewNote }
interface StagedChangesState {
/** Per-conversation queue. Cleared on apply-all / reject-all / chat reset. */
@@ -28,6 +28,18 @@ interface StagedChangesState {
list: (chatId: string) => StagedChange[]
/** Looks up a single change by id. */
get: (chatId: string, id: string) => StagedChange | undefined
+ /** Records the user's decision on one hunk; null opens it again. */
+ decideHunk: (chatId: string, id: string, hunk: number, decision: 'accepted' | 'rejected' | null) => void
+ /**
+ * Review outcomes the model has not heard yet, per chat. The desktop review
+ * happens beside the run, so the model only learns about a rejected file or
+ * hunk when somebody tells it: hooks/codex/staged-writes.ts hands these to
+ * the next tool result and empties the list.
+ */
+ notes: Record<string, ReviewNote[]>
+ addNote: (chatId: string, note: ReviewNote) => void
+ /** Removes and returns the notes of a chat, or only those for one change. */
+ takeNotes: (chatId: string, changeId?: string) => ReviewNote[]
}
/**
@@ -154,12 +166,72 @@ export const useStagedChangesStore = create<StagedChangesState>()(persist((set,
list: (chatId) => get().byChat[chatId] ?? [],
get: (chatId, id) => (get().byChat[chatId] ?? []).find((c) => c.id === id),
+
+ decideHunk: (chatId, id, hunk, decision) =>
+ set((state) => {
+ const prev = state.byChat[chatId]
+ if (!prev || !prev.some((c) => c.id === id)) return state
+ return {
+ byChat: {
+ ...state.byChat,
+ [chatId]: prev.map((c) => {
+ if (c.id !== id) return c
+ const next = { ...(c.hunkDecisions ?? {}) }
+ if (decision) next[hunk] = decision
+ else delete next[hunk]
+ return { ...c, hunkDecisions: next }
+ }),
+ },
+ }
+ }),
+
+ notes: {},
+
+ addNote: (chatId, note) =>
+ set((state) => ({
+ notes: {
+ ...state.notes,
+ // One note per change: a later review of the same change says it all.
+ [chatId]: [...(state.notes[chatId] ?? []).filter((n) => n.changeId !== note.changeId), note],
+ },
+ })),
+
+ takeNotes: (chatId, changeId) => {
+ const all = get().notes[chatId] ?? []
+ const taken = changeId ? all.filter((n) => n.changeId === changeId) : all
+ if (taken.length === 0) return []
+ const rest = changeId ? all.filter((n) => n.changeId !== changeId) : []
+ set((state) => {
+ const notes = { ...state.notes }
+ if (rest.length > 0) notes[chatId] = rest
+ else delete notes[chatId]
+ return { notes }
+ })
+ return taken
+ },
}), {
name: 'staged-changes',
storage: stagedStorage,
- partialize: (state) => ({ byChat: state.byChat }) as StagedChangesState,
+ partialize: (state) => ({ byChat: state.byChat, notes: state.notes }) as StagedChangesState,
merge: (persisted, current) => ({
...current,
byChat: pruneStagedQueues((persisted as { byChat?: unknown } | null)?.byChat, Date.now()),
+ notes: pruneNotes((persisted as { notes?: unknown } | null)?.notes),
}),
}))
+
+/** Notes from disk, kept only when they still look like notes. */
+function pruneNotes(persisted: unknown): Record<string, ReviewNote[]> {
+ if (!persisted || typeof persisted !== 'object') return {}
+ const out: Record<string, ReviewNote[]> = {}
+ for (const [chatId, raw] of Object.entries(persisted as Record<string, unknown>)) {
+ if (!Array.isArray(raw)) continue
+ const kept = raw.filter((n): n is ReviewNote =>
+ !!n && typeof n === 'object'
+ && typeof (n as ReviewNote).changeId === 'string'
+ && typeof (n as ReviewNote).path === 'string'
+ && typeof (n as ReviewNote).text === 'string')
+ if (kept.length > 0) out[chatId] = kept
+ }
+ return out
+}
diff --git a/src/types/staged-changes.ts b/src/types/staged-changes.ts
index c8263962..58afc0b0 100644
--- a/src/types/staged-changes.ts
+++ b/src/types/staged-changes.ts
@@ -47,4 +47,19 @@ export interface StagedChange {
diff: string
/** Wall-clock when the model staged this change. */
stagedAt: number
+ /**
+ * Per hunk review (lib/hunks): index of a hunk of oldContent -> newContent
+ * to the user's decision. A hunk without an entry is still open and counts
+ * as accepted when the file is applied. The hunks are rebuilt from the two
+ * contents, which never change for one id, so the indices stay valid.
+ */
+ hunkDecisions?: Record<number, 'accepted' | 'rejected'>
+}
+
+/** What the model is told about a review it did not see happen: a file the
+ * user rejected, or hunks of a file left out on apply. */
+export interface ReviewNote {
+ changeId: string
+ path: string
+ text: string
}