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.

fix(codex): an approved change lands, or says exactly why it cannot

purple35cfdb9026de
diff --git a/src/components/chat/PlanBar.tsx b/src/components/chat/PlanBar.tsx
index d88b7f50..4b8ae8bd 100644
--- a/src/components/chat/PlanBar.tsx
+++ b/src/components/chat/PlanBar.tsx
@@ -14,12 +14,26 @@ import { useState } from 'react'
import { CheckCircle2, Circle, ChevronDown, ChevronRight, Loader2, ListTodo, X } from 'lucide-react'
import { useTodoStore } from '../../stores/todoStore'
import { useChatStore } from '../../stores/chatStore'
+import { useStagedChangesStore } from '../../stores/stagedChangesStore'
+
+/** What the collapsed bar says once the model ticked off every step. Ticking
+ * off a step is not the same as the change being on disk. */
+export function planDoneLabel(pendingChanges: number): string {
+ if (pendingChanges <= 0) return 'every step done'
+ return `every step done, ${pendingChanges} change${pendingChanges === 1 ? '' : 's'} still waiting for your approval`
+}
export function PlanBar() {
const activeConversationId = useChatStore((s) => s.activeConversationId)
const todos = useTodoStore((s) =>
activeConversationId ? s.byConversation[activeConversationId] : undefined,
)
+ // Ticking off every step is not the same as the work being on disk. In
+ // Stage-and-Approve the writes wait in the queue, and Morgan read "every step
+ // done" on a run whose six file changes had all been refused (2026-08-11).
+ const pending = useStagedChangesStore((s) =>
+ activeConversationId ? (s.byChat[activeConversationId]?.length ?? 0) : 0,
+ )
const clearTodos = useTodoStore((s) => s.clearTodos)
const [expanded, setExpanded] = useState(false)
@@ -98,9 +112,16 @@ export function PlanBar() {
)}
{!expanded && allDone && (
- <div className="px-2 pb-1 flex items-center gap-1.5">
- <CheckCircle2 size={9} className="text-emerald-400 shrink-0" />
- <span className="text-[0.55rem] text-emerald-400/80">every step done</span>
+ <div className="px-2 pb-1 flex items-center gap-1.5" data-testid="plan-all-done">
+ <CheckCircle2
+ size={9}
+ className={`${pending > 0 ? 'text-amber-400' : 'text-emerald-400'} shrink-0`}
+ />
+ <span
+ className={`text-[0.55rem] ${pending > 0 ? 'text-amber-400/90' : 'text-emerald-400/80'}`}
+ >
+ {planDoneLabel(pending)}
+ </span>
</div>
)}
</div>
diff --git a/src/components/chat/__tests__/plan-done-vs-applied.test.ts b/src/components/chat/__tests__/plan-done-vs-applied.test.ts
new file mode 100644
index 00000000..610e79a3
--- /dev/null
+++ b/src/components/chat/__tests__/plan-done-vs-applied.test.ts
@@ -0,0 +1,33 @@
+/**
+ * The plan bar reports the MODEL's progress. In Stage-and-Approve the writes
+ * still sit in the queue, so "every step done" on its own reads as "your files
+ * are written" when nothing was. Morgan (2026-08-11) saw exactly that: plan
+ * 6 of 6, every step done, and six file changes that had all been refused.
+ *
+ * Run: npx vitest run src/components/chat/__tests__/plan-done-vs-applied.test.ts
+ */
+import { describe, it, expect } from 'vitest'
+import { readFileSync } from 'node:fs'
+import { fileURLToPath } from 'node:url'
+import { dirname, resolve } from 'node:path'
+import { planDoneLabel } from '../PlanBar'
+
+describe('planDoneLabel', () => {
+ it('says done, plainly, when nothing is waiting', () => {
+ expect(planDoneLabel(0)).toBe('every step done')
+ })
+
+ it('names the changes that still need approval', () => {
+ expect(planDoneLabel(1)).toBe('every step done, 1 change still waiting for your approval')
+ expect(planDoneLabel(6)).toBe('every step done, 6 changes still waiting for your approval')
+ })
+})
+
+describe('the bar reads the staging queue', () => {
+ it('PlanBar subscribes to stagedChangesStore', () => {
+ const here = dirname(fileURLToPath(import.meta.url))
+ const src = readFileSync(resolve(here, '../PlanBar.tsx'), 'utf8')
+ expect(src).toMatch(/useStagedChangesStore/)
+ expect(src).toMatch(/planDoneLabel\(pending\)/)
+ })
+})
diff --git a/src/lib/__tests__/staged-apply.test.ts b/src/lib/__tests__/staged-apply.test.ts
index 1a7788a3..8b67b373 100644
--- a/src/lib/__tests__/staged-apply.test.ts
+++ b/src/lib/__tests__/staged-apply.test.ts
@@ -150,6 +150,46 @@ describe('applyStagedChange refuses to overwrite a file that moved on', () => {
expect(useStagedChangesStore.getState().list(CHAT)).toHaveLength(0)
})
+ // Refusing was too blunt: in Morgan's run (2026-08-11) every file had moved
+ // on, so a finished plan wrote nothing at all. A foreign edit somewhere else
+ // in the file is not a reason to drop work the user approved.
+ it('merges a foreign edit elsewhere in the file and says so', async () => {
+ route('a\nb\nc\nadded by another tool')
+ stage('a.py', {
+ resolvedPath: '/proj/a.py',
+ workingDirectory: '/proj',
+ oldContent: 'a\nb\nc',
+ newContent: 'a\nCHANGED\nc',
+ })
+ await applyStagedChange(CHAT, useStagedChangesStore.getState().list(CHAT)[0])
+
+ expect(fsWrite).toHaveBeenCalledWith('fs_write', {
+ path: '/proj/a.py',
+ content: 'a\nCHANGED\nc\nadded by another tool',
+ chatId: CHAT,
+ workingDirectory: '/proj',
+ })
+ expect(useStagedChangesStore.getState().list(CHAT)).toHaveLength(0)
+ expect(addMessage.mock.calls[0][1].content).toMatch(/merged with 1 change made on disk/)
+ })
+
+ it('counts an already-applied file as done instead of failing it', async () => {
+ route('a\nCHANGED\nc')
+ stage('a.py', { oldContent: 'a\nb\nc', newContent: 'a\nCHANGED\nc' })
+ await applyStagedChange(CHAT, useStagedChangesStore.getState().list(CHAT)[0])
+ expect(useStagedChangesStore.getState().list(CHAT)).toHaveLength(0)
+ expect(addMessage.mock.calls[0][1].content).not.toMatch(/merged/)
+ })
+
+ it('names the collision when the same lines moved on both sides', async () => {
+ route('a\nTHEIRS\nc')
+ stage('a.py', { oldContent: 'a\nb\nc', newContent: 'a\nOURS\nc' })
+ await expect(
+ applyStagedChange(CHAT, useStagedChangesStore.getState().list(CHAT)[0]),
+ ).rejects.toThrow(/same place this edit touches/)
+ expect(fsWrite).not.toHaveBeenCalledWith('fs_write', expect.anything())
+ })
+
it('one drifted file never blocks the rest of an apply-all', async () => {
stage('good.py', { oldContent: 'base' })
stage('drifted.py', { oldContent: 'base' })
diff --git a/src/lib/__tests__/three-way-merge.test.ts b/src/lib/__tests__/three-way-merge.test.ts
new file mode 100644
index 00000000..2e150125
--- /dev/null
+++ b/src/lib/__tests__/three-way-merge.test.ts
@@ -0,0 +1,99 @@
+/**
+ * mergeThreeWay decides whether a staged change can still land after the file
+ * moved on. Two edits in different places must both survive; two edits in the
+ * same place must be refused, never silently picked.
+ */
+import { describe, it, expect } from 'vitest'
+import { mergeThreeWay } from '../three-way-merge'
+
+const lines = (...l: string[]) => l.join('\n')
+
+const BASE = lines(
+ 'from fastapi import FastAPI',
+ '',
+ 'app = FastAPI()',
+ '',
+ 'def health() -> str:',
+ ' return "ok"',
+)
+
+describe('mergeThreeWay', () => {
+ it('keeps both edits when they sit in different places', () => {
+ const ours = BASE.replace('app = FastAPI()', 'app = FastAPI(title="Graphify")')
+ const theirs = lines(BASE, '', 'def payments() -> str:', ' return "btc"')
+
+ const res = mergeThreeWay(BASE, ours, theirs)
+ expect(res.ok).toBe(true)
+ if (!res.ok) return
+ expect(res.content).toContain('title="Graphify"')
+ expect(res.content).toContain('def payments()')
+ expect(res.mergedRegions).toBe(1)
+ })
+
+ it('refuses when both sides changed the same line', () => {
+ const ours = BASE.replace(' return "ok"', ' return "healthy"')
+ const theirs = BASE.replace(' return "ok"', ' return "OK"')
+
+ const res = mergeThreeWay(BASE, ours, theirs)
+ expect(res.ok).toBe(false)
+ if (res.ok) return
+ expect(res.conflicts).toBe(1)
+ })
+
+ it('takes it once when both sides made the identical edit', () => {
+ const same = BASE.replace(' return "ok"', ' return "healthy"')
+ const res = mergeThreeWay(BASE, same, same)
+ expect(res.ok).toBe(true)
+ if (!res.ok) return
+ expect(res.content).toBe(same)
+ expect(res.content.match(/healthy/g)).toHaveLength(1)
+ })
+
+ it('refuses two different insertions in the same gap instead of writing both', () => {
+ const ours = BASE.replace('app = FastAPI()', 'app = FastAPI()\napp.mount("/ours")')
+ const theirs = BASE.replace('app = FastAPI()', 'app = FastAPI()\napp.mount("/theirs")')
+ const res = mergeThreeWay(BASE, ours, theirs)
+ expect(res.ok).toBe(false)
+ })
+
+ it('is the staged content when the disk never moved, and the disk content when the stage is a no-op', () => {
+ const theirs = lines(BASE, 'x = 1')
+ expect(mergeThreeWay(BASE, BASE, theirs)).toEqual({
+ ok: true,
+ content: theirs,
+ mergedRegions: 0,
+ })
+ const ours = lines(BASE, 'y = 2')
+ expect(mergeThreeWay(BASE, ours, BASE)).toEqual({ ok: true, content: ours, mergedRegions: 0 })
+ })
+
+ it('merges an edit at the top with a deletion at the bottom', () => {
+ const ours = lines('# fresh header', ...BASE.split('\n'))
+ const theirs = BASE.split('\n').slice(0, -1).join('\n')
+
+ const res = mergeThreeWay(BASE, ours, theirs)
+ expect(res.ok).toBe(true)
+ if (!res.ok) return
+ expect(res.content.startsWith('# fresh header')).toBe(true)
+ expect(res.content).not.toContain('return "ok"')
+ })
+
+ it('counts every foreign region it carried over', () => {
+ const ours = BASE.replace('from fastapi import FastAPI', 'from fastapi import FastAPI, Depends')
+ .replace(' return "ok"', ' return "ok" # noqa')
+ const theirs = lines(BASE, 'router = None')
+
+ const res = mergeThreeWay(BASE, ours, theirs)
+ expect(res.ok).toBe(true)
+ if (!res.ok) return
+ expect(res.mergedRegions).toBe(2)
+ expect(res.content).toContain('Depends')
+ expect(res.content).toContain('# noqa')
+ expect(res.content).toContain('router = None')
+ })
+
+ it('treats a file created on both sides with different content as a conflict', () => {
+ const res = mergeThreeWay('', 'someone else wrote this', 'the model wrote this')
+ expect(res.ok).toBe(false)
+ })
+})
diff --git a/src/lib/diff.ts b/src/lib/diff.ts
index 7014e59f..444fb03c 100644
--- a/src/lib/diff.ts
+++ b/src/lib/diff.ts
@@ -203,7 +203,10 @@ export function parseUnifiedDiff(diff: string): ParsedDiff {
// ── internals ──────────────────────────────────────────────────────
-type Op =
+/** One run of lines that are equal, added or removed. Exported with
+ * `diffLines` so the three-way merge works off the same line diff the user
+ * reviewed, instead of a second implementation that could disagree with it. */
+export type Op =
| { kind: 'equal'; text: string[] }
| { kind: 'add'; text: string[] }
| { kind: 'remove'; text: string[] }
@@ -218,7 +221,7 @@ type Op =
const MAX_LCS_CELLS = 4_000_000
/** LCS-based line diff. Grouped into op runs for a compact unified format. */
-function diffLines(a: string[], b: string[]): Op[] {
+export function diffLines(a: string[], b: string[]): Op[] {
let head = 0
while (head < a.length && head < b.length && a[head] === b[head]) head++
let tail = 0
diff --git a/src/lib/staged-apply.ts b/src/lib/staged-apply.ts
index a2dd09f2..20c183e1 100644
--- a/src/lib/staged-apply.ts
+++ b/src/lib/staged-apply.ts
@@ -16,22 +16,36 @@
import { backendCall } from '../api/backend'
import { useStagedChangesStore, type StagedChange } from '../stores/stagedChangesStore'
import { useChatStore } from '../stores/chatStore'
+import { mergeThreeWay } from './three-way-merge'
/**
- * Refuse to apply on top of someone else's edit.
+ * Decide what to write when the file moved on since it was staged.
*
* A staged change carries the file as it looked when the model wrote it. The
- * user reviews the diff and clicks Apply minutes later — and in between they may
- * well have touched the file themselves ("I'll just fix that one line"). Writing
- * `newContent` then silently reverts their work, with no undo. We already hold
- * the stage-time baseline, so the check is a single read.
+ * user reviews the diff and clicks Apply minutes later, and in between the file
+ * may well have changed: they fixed a line themselves, another tool ran in the
+ * same folder, or an earlier entry of this very queue landed. Writing
+ * `newContent` blindly reverts all of that, with no undo.
*
- * Only enforced when we HAVE a baseline: `oldContent` is also empty when the
- * stage-time read failed for any reason (useCodex treats a failed read as "new
- * file"), and blocking on that would break applies that are perfectly fine.
+ * Refusing was the first answer to that, and it turned into its own bug: every
+ * file in Morgan's finished run refused, so a plan the app reported as done
+ * wrote nothing (2026-08-11). Refusing is only correct when the two edits
+ * really collide. So:
+ *
+ * 1. baseline intact -> write what was approved
+ * 2. already that content -> nothing to do, treat as applied
+ * 3. foreign edit elsewhere-> merge both and write the result
+ * 4. same lines both sides -> refuse, this one needs a human
+ *
+ * Only steps 2 to 4 need the baseline. `oldContent` is also empty when the
+ * stage-time read failed (useCodex treats a failed read as "new file"), and
+ * gating on that would break applies that are perfectly fine.
*/
-async function assertNoDrift(chatId: string, change: StagedChange): Promise<void> {
- if (!change.oldContent) return
+async function reconcile(
+ chatId: string,
+ change: StagedChange,
+): Promise<{ content: string; merged: number }> {
+ if (!change.oldContent) return { content: change.newContent, merged: 0 }
let current: string
try {
const res = await backendCall<{ content?: string }>('fs_read', {
@@ -41,20 +55,26 @@ async function assertNoDrift(chatId: string, change: StagedChange): Promise<void
})
current = res?.content ?? ''
} catch {
- return // gone or unreadable — the write recreates it, which is what the user asked for
+ // gone or unreadable, the write recreates it, which is what the user asked for
+ return { content: change.newContent, merged: 0 }
+ }
+ if (current === change.oldContent || current === change.newContent) {
+ return { content: change.newContent, merged: 0 }
}
- if (current !== change.oldContent) {
- throw new Error(
- `${change.path} changed on disk after this edit was staged — applying would overwrite those changes. Reject it and let the model read the file again.`,
- )
+ const merged = mergeThreeWay(change.oldContent, current, change.newContent)
+ if (merged.ok) {
+ return { content: merged.content, merged: merged.mergedRegions }
}
+ throw new Error(
+ `${change.path} changed on disk in the same ${merged.conflicts === 1 ? 'place' : 'places'} this edit touches, so applying it would drop those changes. Everything else was left alone. Reject this one and let the model read the file again.`,
+ )
}
export async function applyStagedChange(chatId: string, change: StagedChange): Promise<void> {
- await assertNoDrift(chatId, change)
+ const { content, merged } = await reconcile(chatId, change)
const res = await backendCall<{ status?: string; path?: string }>('fs_write', {
path: change.resolvedPath || change.path,
- content: change.newContent,
+ content,
chatId,
workingDirectory: change.workingDirectory,
})
@@ -65,11 +85,14 @@ export async function applyStagedChange(chatId: string, change: StagedChange): P
}
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.
+ // main pane, not just the side-pane entry disappearing. A merge is named as
+ // one: the file that landed is not byte for byte the diff that was reviewed.
useChatStore.getState().addMessage(chatId, {
id: crypto.randomUUID(),
role: 'system',
- content: `Applied staged change: ${change.path}`,
+ content: merged > 0
+ ? `Applied staged change: ${change.path} (merged with ${merged} change${merged === 1 ? '' : 's'} made on disk since it was staged)`
+ : `Applied staged change: ${change.path}`,
timestamp: Date.now(),
hidden: true,
})
diff --git a/src/lib/three-way-merge.ts b/src/lib/three-way-merge.ts
new file mode 100644
index 00000000..dad15033
--- /dev/null
+++ b/src/lib/three-way-merge.ts
@@ -0,0 +1,176 @@
+/**
+ * Line-level three-way merge for staged changes.
+ *
+ * Morgan, 2026-08-11: every file in his finished run refused to apply with
+ * "changed on disk after this edit was staged", so a six-step plan that the
+ * plan bar reported as done wrote nothing at all. The guard was right (the
+ * file really had moved on, he runs other tools in the same folder), but a
+ * guard whose only exit is Reject all throws away work the customer paid for.
+ *
+ * Almost always the two edits sit in different places in the file, and then
+ * there is nothing to decide: take both. Only when the same lines moved on
+ * both sides is there a real question, and only that case still refuses.
+ *
+ * Built on `diffLines` from ./diff, the same line diff the reviewed diff is
+ * rendered from, so the merge can never disagree with what the user saw.
+ */
+
+import { diffLines } from './diff'
+
+export type MergeResult =
+ /** `content` is safe to write. `mergedRegions` counts the foreign edits kept. */
+ | { ok: true; content: string; mergedRegions: number }
+ /** The same lines changed on both sides. `conflicts` counts the spots. */
+ | { ok: false; conflicts: number }
+
+/** A stretch of base lines [start, end) that one side replaced with `lines`. */
+interface Region {
+ start: number
+ end: number
+ lines: string[]
+}
+
+function split(text: string): string[] {
+ return text === '' ? [] : text.split('\n')
+}
+
+/** Every place `side` differs from `base`, in base coordinates. */
+function regionsOf(base: string[], side: string[]): Region[] {
+ const out: Region[] = []
+ let cursor = 0
+ const ops = diffLines(base, side)
+ for (let i = 0; i < ops.length; ) {
+ if (ops[i].kind === 'equal') {
+ cursor += ops[i].text.length
+ i++
+ continue
+ }
+ const start = cursor
+ let lines: string[] = []
+ // A replacement arrives as a remove run next to an add run; both belong to
+ // the same region, otherwise the add would be treated as a second edit at
+ // the position the remove already consumed.
+ while (i < ops.length && ops[i].kind !== 'equal') {
+ if (ops[i].kind === 'remove') {
+ cursor += ops[i].text.length
+ } else {
+ lines = lines.concat(ops[i].text)
+ }
+ i++
+ }
+ out.push({ start, end: cursor, lines })
+ }
+ return out
+}
+
+/**
+ * Do these two base spans have to be judged together?
+ *
+ * Replacements collide when their spans really overlap. A pure insertion owns
+ * no base line, so it only collides with a replacement it sits INSIDE of:
+ * appending at the end of a block the other side rewrote is an everyday
+ * combination (the model adds a route, someone else fixes the line above it)
+ * and treating it as a collision would refuse most real merges. Two different
+ * insertions in the same gap do collide, because their order would otherwise be
+ * ours by accident.
+ */
+function collides(a: Region, b: Region): boolean {
+ const aInsert = a.start === a.end
+ const bInsert = b.start === b.end
+ if (aInsert && bInsert) return a.start === b.start
+ if (aInsert) return a.start > b.start && a.start < b.end
+ if (bInsert) return b.start > a.start && b.start < a.end
+ return a.start < b.end && b.start < a.end
+}
+
+/** The result of applying one side's regions across [start, end). */
+function rewrite(base: string[], regions: Region[], start: number, end: number): string[] {
+ const out: string[] = []
+ let cursor = start
+ for (const r of regions) {
+ for (let i = cursor; i < r.start; i++) out.push(base[i])
+ for (const line of r.lines) out.push(line)
+ cursor = r.end
+ }
+ for (let i = cursor; i < end; i++) out.push(base[i])
+ return out
+}
+
+function same(a: string[], b: string[]): boolean {
+ return a.length === b.length && a.every((line, i) => line === b[i])
+}
+
+/**
+ * Merge `ours` (what is on disk now) and `theirs` (what we staged) over their
+ * common `base` (the disk content at stage time).
+ */
+export function mergeThreeWay(base: string, ours: string, theirs: string): MergeResult {
+ if (ours === base) return { ok: true, content: theirs, mergedRegions: 0 }
+ if (theirs === base) return { ok: true, content: ours, mergedRegions: 0 }
+ if (ours === theirs) return { ok: true, content: theirs, mergedRegions: 0 }
+
+ const baseLines = split(base)
+ const ourRegions = regionsOf(baseLines, split(ours))
+ const theirRegions = regionsOf(baseLines, split(theirs))
+
+ const out: string[] = []
+ let cursor = 0
+ let oi = 0
+ let ti = 0
+ let mergedRegions = 0
+ let conflicts = 0
+
+ while (oi < ourRegions.length || ti < theirRegions.length) {
+ // Open the group with whichever side comes first in the file.
+ const mine: Region[] = []
+ const yours: Region[] = []
+ const ourNext = ourRegions[oi]
+ const theirNext = theirRegions[ti]
+ const startWithOurs = !theirNext || (ourNext && ourNext.start <= theirNext.start)
+ const first = startWithOurs ? ourRegions[oi++] : theirRegions[ti++]
+ ;(startWithOurs ? mine : yours).push(first)
+ const start = first.start
+ let end = first.end
+
+ // Then pull in everything from either side that collides with the growing
+ // span, so a chain of edits over the same lines is judged as one unit.
+ for (let grew = true; grew; ) {
+ grew = false
+ while (oi < ourRegions.length && collides(ourRegions[oi], { start, end, lines: [] })) {
+ end = Math.max(end, ourRegions[oi].end)
+ mine.push(ourRegions[oi])
+ oi++
+ grew = true
+ }
+ while (ti < theirRegions.length && collides(theirRegions[ti], { start, end, lines: [] })) {
+ end = Math.max(end, theirRegions[ti].end)
+ yours.push(theirRegions[ti])
+ ti++
+ grew = true
+ }
+ }
+
+ for (let i = cursor; i < start; i++) out.push(baseLines[i])
+
+ if (mine.length === 0 || yours.length === 0) {
+ const only = mine.length === 0 ? yours : mine
+ for (const line of rewrite(baseLines, only, start, end)) out.push(line)
+ if (mine.length > 0) mergedRegions++
+ } else {
+ const a = rewrite(baseLines, mine, start, end)
+ const b = rewrite(baseLines, yours, start, end)
+ if (same(a, b)) {
+ // Both sides arrived at the same text. Nothing to decide.
+ for (const line of a) out.push(line)
+ } else {
+ conflicts++
+ }
+ }
+ cursor = end
+ }
+
+ if (conflicts > 0) return { ok: false, conflicts }
+
+ for (let i = cursor; i < baseLines.length; i++) out.push(baseLines[i])
+ return { ok: true, content: out.join('\n'), mergedRegions }
+}
diff --git a/src/stores/__tests__/stagedChangesStore.test.ts b/src/stores/__tests__/stagedChangesStore.test.ts
index 64fafc0c..e6a9188a 100644
--- a/src/stores/__tests__/stagedChangesStore.test.ts
+++ b/src/stores/__tests__/stagedChangesStore.test.ts
@@ -43,6 +43,39 @@ describe('stagedChangesStore', () => {
expect(list[0].newContent).toBe('v2')
})
+ // The queue used to dedupe on the raw string while every reader matches
+ // normalized and on resolvedPath too. One file then sat in the queue twice,
+ // the older entry was written first, and the newer one died in the drift
+ // guard: the user lost the edit he approved (Morgan, 2026-08-11).
+ it('one file is one entry, whatever spelling the model used', () => {
+ const stage = (path: string, resolvedPath: string, newContent: string) =>
+ useStagedChangesStore.getState().stage('c1', {
+ path,
+ resolvedPath,
+ oldContent: 'base',
+ newContent,
+ diff: '',
+ })
+
+ stage('main.py', 'C:/proj/main.py', 'v1')
+ stage('C:\\proj\\main.py', 'C:\\proj\\main.py', 'v2')
+ stage('./main.py', 'C:/PROJ/main.py', 'v3')
+
+ const list = useStagedChangesStore.getState().list('c1')
+ expect(list).toHaveLength(1)
+ expect(list[0].newContent).toBe('v3')
+ })
+
+ it('keeps two genuinely different files apart', () => {
+ useStagedChangesStore.getState().stage('c1', {
+ path: 'src/a.ts', resolvedPath: '/proj/src/a.ts', oldContent: '', newContent: 'x', diff: '',
+ })
+ useStagedChangesStore.getState().stage('c1', {
+ path: 'lib/a.ts', resolvedPath: '/proj/lib/a.ts', oldContent: '', newContent: 'y', diff: '',
+ })
+ expect(useStagedChangesStore.getState().list('c1')).toHaveLength(2)
+ })
+
it('queues across chats are isolated', () => {
useStagedChangesStore.getState().stage('c1', {
path: 'a',
diff --git a/src/stores/stagedChangesStore.ts b/src/stores/stagedChangesStore.ts
index 4239e09d..787450fc 100644
--- a/src/stores/stagedChangesStore.ts
+++ b/src/stores/stagedChangesStore.ts
@@ -1,5 +1,6 @@
import { create } from 'zustand'
import { v4 as uuid } from 'uuid'
+import { normalizeStagedPath } from '../lib/staged-overlay'
export interface StagedChange {
/** Stable id assigned at stage-time so the UI can key + remove safely. */
@@ -39,7 +40,7 @@ export interface StagedChange {
interface StagedChangesState {
/** Per-conversation queue. Cleared on apply-all / reject-all / chat reset. */
byChat: Record<string, StagedChange[]>
- /** Adds a change, returns the assigned id. Identical paths overwrite the prior entry — the model usually means the latest write to win. */
+ /** Adds a change, returns the assigned id. The same file overwrites its prior entry, the model usually means the latest write to win. */
stage: (
chatId: string,
change: Omit<StagedChange, 'id' | 'stagedAt'>,
@@ -54,6 +55,22 @@ interface StagedChangesState {
get: (chatId: string, id: string) => StagedChange | undefined
}
+/**
+ * One file, one entry. The queue used to dedupe on the raw `path` string while
+ * every reader (findStagedForPath, the overlay) matches normalized and also on
+ * `resolvedPath`. A model that writes `main.py` once and `C:\proj\main.py` the
+ * next time therefore left TWO entries for one file, both anchored on the same
+ * disk baseline. Applying them wrote the older version first, and the newer one
+ * then hit the drift guard and refused: the customer lost the edit he approved
+ * and kept the one he did not (Morgan, 2026-08-11).
+ */
+function sameFile(a: Pick<StagedChange, 'path' | 'resolvedPath'>, b: Pick<StagedChange, 'path' | 'resolvedPath'>): boolean {
+ return (
+ normalizeStagedPath(a.path) === normalizeStagedPath(b.path) ||
+ normalizeStagedPath(a.resolvedPath || a.path) === normalizeStagedPath(b.resolvedPath || b.path)
+ )
+}
+
export const useStagedChangesStore = create<StagedChangesState>()((set, get) => ({
byChat: {},
@@ -61,8 +78,8 @@ export const useStagedChangesStore = create<StagedChangesState>()((set, get) =>
const id = uuid()
set((state) => {
const prev = state.byChat[chatId] ?? []
- // Same path — replace, don't dupe. The diff carries the latest intent.
- const without = prev.filter((c) => c.path !== change.path)
+ // Same file, replace, don't dupe. The diff carries the latest intent.
+ const without = prev.filter((c) => !sameFile(c, change))
return {
byChat: {
...state.byChat,