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(code): applying a staged change overwrote edits made in the meantime

David474021548535
diff --git a/src/components/chat/StagedChangesPanel.tsx b/src/components/chat/StagedChangesPanel.tsx
index 38fc836a..03bb881a 100644
--- a/src/components/chat/StagedChangesPanel.tsx
+++ b/src/components/chat/StagedChangesPanel.tsx
@@ -34,20 +34,31 @@ export function StagedChangesPanel({ chatId }: Props) {
const clear = useStagedChangesStore((s) => s.clear)
const [expanded, setExpanded] = useState(true)
const [applying, setApplying] = useState<Set<string>>(new Set())
+ const [errors, setErrors] = useState<Record<string, string>>({})
if (!chatId || changes.length === 0) return null
async function applyOne(change: StagedChange) {
if (!chatId) return
setApplying((prev) => new Set(prev).add(change.id))
+ setErrors((prev) => {
+ if (!(change.id in prev)) return prev
+ const { [change.id]: _gone, ...rest } = prev
+ 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.
+ // 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).
log.error('[StagedChangesPanel] apply failed', { err: e })
+ const message = e instanceof Error ? e.message : String(e)
+ setErrors((prev) => ({ ...prev, [change.id]: message }))
} finally {
setApplying((prev) => {
const next = new Set(prev)
@@ -131,6 +142,14 @@ export function StagedChangesPanel({ chatId }: Props) {
</button>
</span>
</div>
+ {errors[change.id] && (
+ <div
+ className="px-1.5 py-1 text-[0.5rem] leading-snug text-red-700 dark:text-red-300 bg-red-50 dark:bg-red-500/10"
+ data-testid="staged-change-error"
+ >
+ {errors[change.id]}
+ </div>
+ )}
{change.diff && (
<div className="text-[0.5rem]">
<DiffView diff={change.diff} maxLines={40} />
diff --git a/src/lib/__tests__/staged-apply.test.ts b/src/lib/__tests__/staged-apply.test.ts
index cf3e4262..1a7788a3 100644
--- a/src/lib/__tests__/staged-apply.test.ts
+++ b/src/lib/__tests__/staged-apply.test.ts
@@ -99,3 +99,68 @@ describe('applyAllStagedChanges', () => {
expect(left[0].path).toBe('bad.py')
})
})
+
+// A staged change carries the file as it looked at stage time. The user reviews
+// the diff, edits the file themselves in the meantime, then clicks Apply — the
+// write used to silently revert their edit, with no undo.
+describe('applyStagedChange refuses to overwrite a file that moved on', () => {
+ beforeEach(() => {
+ fsWrite.mockReset()
+ addMessage.mockClear()
+ useStagedChangesStore.getState().clear(CHAT)
+ })
+
+ const route = (disk: string | Error) =>
+ fsWrite.mockImplementation((cmd: string) => {
+ if (cmd === 'fs_read') {
+ return disk instanceof Error ? Promise.reject(disk) : Promise.resolve({ content: disk })
+ }
+ return Promise.resolve({ status: 'saved' })
+ })
+
+ it('throws and keeps the entry when the file changed since staging', async () => {
+ route('the user edited this')
+ stage('a.py', { resolvedPath: '/proj/a.py', workingDirectory: '/proj', oldContent: 'as staged' })
+ const change = useStagedChangesStore.getState().list(CHAT)[0]
+
+ await expect(applyStagedChange(CHAT, change)).rejects.toThrow(/changed on disk/)
+ expect(fsWrite).not.toHaveBeenCalledWith('fs_write', expect.anything())
+ expect(useStagedChangesStore.getState().list(CHAT)).toHaveLength(1)
+ })
+
+ it('writes when the file still matches the stage-time content', async () => {
+ route('as staged')
+ stage('a.py', { resolvedPath: '/proj/a.py', workingDirectory: '/proj', oldContent: 'as staged' })
+ await applyStagedChange(CHAT, useStagedChangesStore.getState().list(CHAT)[0])
+ expect(useStagedChangesStore.getState().list(CHAT)).toHaveLength(0)
+ })
+
+ it('does not read at all for a new file (no baseline to compare against)', async () => {
+ fsWrite.mockResolvedValue({ status: 'saved' })
+ stage('new.py', { oldContent: '' })
+ await applyStagedChange(CHAT, useStagedChangesStore.getState().list(CHAT)[0])
+ expect(fsWrite).toHaveBeenCalledTimes(1)
+ expect(fsWrite.mock.calls[0][0]).toBe('fs_write')
+ })
+
+ it('still writes when the file is gone — the write recreates it', async () => {
+ route(new Error('no such file'))
+ stage('a.py', { oldContent: 'as staged' })
+ await applyStagedChange(CHAT, useStagedChangesStore.getState().list(CHAT)[0])
+ expect(useStagedChangesStore.getState().list(CHAT)).toHaveLength(0)
+ })
+
+ it('one drifted file never blocks the rest of an apply-all', async () => {
+ stage('good.py', { oldContent: 'base' })
+ stage('drifted.py', { oldContent: 'base' })
+ fsWrite.mockImplementation((cmd: string, args: { path: string }) => {
+ if (cmd === 'fs_read') {
+ return Promise.resolve({ content: args.path.includes('drifted') ? 'moved on' : 'base' })
+ }
+ return Promise.resolve({ status: 'saved' })
+ })
+ const res = await applyAllStagedChanges(CHAT)
+ expect(res.applied).toEqual(['good.py'])
+ expect(res.failed).toEqual(['drifted.py'])
+ })
+})
diff --git a/src/lib/staged-apply.ts b/src/lib/staged-apply.ts
index 0b24cd99..a2dd09f2 100644
--- a/src/lib/staged-apply.ts
+++ b/src/lib/staged-apply.ts
@@ -17,7 +17,41 @@ import { backendCall } from '../api/backend'
import { useStagedChangesStore, type StagedChange } from '../stores/stagedChangesStore'
import { useChatStore } from '../stores/chatStore'
+/**
+ * Refuse to apply on top of someone else's edit.
+ *
+ * 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.
+ *
+ * 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.
+ */
+async function assertNoDrift(chatId: string, change: StagedChange): Promise<void> {
+ if (!change.oldContent) return
+ let current: string
+ try {
+ const res = await backendCall<{ content?: string }>('fs_read', {
+ path: change.resolvedPath || change.path,
+ chatId,
+ workingDirectory: change.workingDirectory,
+ })
+ current = res?.content ?? ''
+ } catch {
+ return // gone or unreadable — the write recreates it, which is what the user asked for
+ }
+ 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.`,
+ )
+ }
+}
+
export async function applyStagedChange(chatId: string, change: StagedChange): Promise<void> {
+ await assertNoDrift(chatId, change)
const res = await backendCall<{ status?: string; path?: string }>('fs_write', {
path: change.resolvedPath || change.path,
content: change.newContent,