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.
TypeScript agentai-chatai-studioall-in-onecoding-agentdesktop-appfluximage-generationlinuxllmlocal-ailocal-llmopen-sourceprivacyself-hostedstable-diffusionuncensoreduncensored-aivideo-generationwindows
fix(apply): line endings turned an unrelated edit into a collision
David5115acd0a40b
diff --git a/src/lib/__tests__/staged-apply-crlf.test.ts b/src/lib/__tests__/staged-apply-crlf.test.tsnew file mode 100644index 00000000..4db72706--- /dev/null+++ b/src/lib/__tests__/staged-apply-crlf.test.ts@@ -0,0 +1,138 @@+/**+ * On Windows an approved change was refused because of line endings.+ *+ * Morgan's report was "the plan says done and nothing was written". The first+ * fix taught `reconcile` to merge a foreign edit instead of refusing it. Then+ * the real queue was measured on the Windows box on 2026-08-14 and the same+ * report came back in a narrower shape: `oldContent` and the file on disk both+ * carry CRLF, because that is what Windows editors write, while the model+ * writes `newContent` with plain LF. Every single line then differs from the+ * baseline, `mergeThreeWay` sees one giant replaced block, and a foreign edit+ * in the middle of the file collides with it. The user is told their edit+ * touches the same place, which is false: the two changes never met.+ *+ * A second, quieter half of the same bug: even with no foreign edit at all, the+ * approved LF content was written over a CRLF file, so the whole file flipped+ * its line endings and showed up in git as fully rewritten.+ *+ * So the comparison and the merge run on one normalized form, and the result is+ * written back in the form the FILE has, not the form the model happened to use.+ *+ * Run: npx vitest run src/lib/__tests__/staged-apply-crlf.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 } from '../staged-apply'+import { useStagedChangesStore } from '../../stores/stagedChangesStore'++const call = backendCall as unknown as ReturnType<typeof vi.fn>+const CHAT = 'chat-crlf'++/** Route fs_read to the file on disk, fs_write to a recorder. */+function onDisk(content: string) {+ const written: string[] = []+ call.mockImplementation(async (cmd: string, args: any) => {+ if (cmd === 'fs_read') return { content }+ if (cmd === 'fs_write') {+ written.push(args.content)+ return { status: 'saved', path: args.path }+ }+ return null+ })+ return written+}++const crlf = (lines: string[]) => lines.join('\r\n')+const lf = (lines: string[]) => lines.join('\n')++const BASE = ['import os', '', 'def main():', ' print("hi")', '', 'main()']++describe('an approved change lands on a CRLF file', () => {+ beforeEach(() => {+ call.mockReset()+ addMessage.mockClear()+ useStagedChangesStore.getState().clear(CHAT)+ })++ function stageEdit(newContent: string, oldContent: string) {+ useStagedChangesStore.getState().stage(CHAT, {+ path: 'app.py',+ resolvedPath: '/proj/app.py',+ workingDirectory: '/proj',+ oldContent,+ newContent,+ diff: '',+ })+ return useStagedChangesStore.getState().list(CHAT)[0]+ }++ it('merges a foreign edit elsewhere instead of calling it a collision', async () => {+ // Someone changed the FIRST line on disk. The model changed the print.+ // Different places, so both must survive.+ const disk = crlf(['import os, sys', '', 'def main():', ' print("hi")', '', 'main()'])+ const model = lf(['import os', '', 'def main():', ' print("hello")', '', 'main()'])+ const written = onDisk(disk)++ await applyStagedChange(CHAT, stageEdit(model, crlf(BASE)))++ expect(written).toHaveLength(1)+ expect(written[0]).toContain('import os, sys')+ expect(written[0]).toContain('print("hello")')+ })++ it('writes the merged file back with the line endings the file had', async () => {+ const disk = crlf(['import os, sys', '', 'def main():', ' print("hi")', '', 'main()'])+ const model = lf(['import os', '', 'def main():', ' print("hello")', '', 'main()'])+ const written = onDisk(disk)++ await applyStagedChange(CHAT, stageEdit(model, crlf(BASE)))++ expect(written[0]).toContain('\r\n')+ expect(written[0].replace(/\r\n/g, '')).not.toContain('\n')+ })++ it('keeps CRLF even when nothing else touched the file', async () => {+ // The quiet half: no merge involved, the file just must not flip to LF and+ // show up as rewritten from top to bottom.+ const disk = crlf(BASE)+ const model = lf(['import os', '', 'def main():', ' print("hello")', '', 'main()'])+ const written = onDisk(disk)++ await applyStagedChange(CHAT, stageEdit(model, crlf(BASE)))++ expect(written[0]).toContain('print("hello")')+ expect(written[0]).toContain('\r\n')+ expect(written[0].replace(/\r\n/g, '')).not.toContain('\n')+ })++ it('leaves an LF file on LF', async () => {+ const disk = lf(BASE)+ const model = lf(['import os', '', 'def main():', ' print("hello")', '', 'main()'])+ const written = onDisk(disk)++ await applyStagedChange(CHAT, stageEdit(model, lf(BASE)))++ expect(written[0]).not.toContain('\r')+ })++ it('still refuses when the two edits really are the same line', async () => {+ // Normalizing must not turn a real collision into a silent overwrite.+ const disk = crlf(['import os', '', 'def main():', ' print("from disk")', '', 'main()'])+ const model = lf(['import os', '', 'def main():', ' print("from model")', '', 'main()'])+ onDisk(disk)++ await expect(applyStagedChange(CHAT, stageEdit(model, crlf(BASE)))).rejects.toThrow(+ /changed on disk/,+ )+ expect(useStagedChangesStore.getState().list(CHAT)).toHaveLength(1)+ })+})diff --git a/src/lib/staged-apply.ts b/src/lib/staged-apply.tsindex 3a16866c..ccecdd57 100644--- a/src/lib/staged-apply.ts+++ b/src/lib/staged-apply.ts@@ -18,6 +18,34 @@ import { useStagedChangesStore, type StagedChange } from '../stores/stagedChangeimport { useChatStore } from '../stores/chatStore'import { mergeThreeWay } from './three-way-merge'+/**+ * Line endings, the difference between "merged" and "we refused your own edit".+ *+ * Measured against the real queue on the Windows box, 2026-08-14: `oldContent`+ * and the file on disk both carry CRLF, because that is what a Windows editor+ * writes, and the model writes `newContent` with LF. Compared as bytes, EVERY+ * line differs from the baseline, so mergeThreeWay sees one replaced block+ * spanning the whole file and any foreign edit inside it reads as a collision.+ * The user is told their edit touches the same place, which is not true.+ *+ * The quieter half is on the happy path: writing LF content over a CRLF file+ * flips the whole file and turns a three-line change into a full rewrite in+ * everyone's diff.+ *+ * So compare and merge on LF, and write back in the form the FILE has. The+ * model's choice of ending is an artefact of the model, never a decision.+ */+const toLf = (text: string) => text.replace(/\r\n/g, '\n')++function eolOf(text: string): '\r\n' | '\n' {+ const crlf = (text.match(/\r\n/g) ?? []).length+ const lf = (text.match(/(?<!\r)\n/g) ?? []).length+ return crlf > lf ? '\r\n' : '\n'+}++const withEol = (text: string, eol: '\r\n' | '\n') =>+ eol === '\r\n' ? toLf(text).replace(/\n/g, '\r\n') : toLf(text)+/*** Decide what to write when the file moved on since it was staged.*@@ -63,12 +91,17 @@ async function reconcile(// gone or unreadable, the write recreates it, which is what the user asked forreturn { content: change.newContent, merged: 0 }}- if (current === base || current === change.newContent) {- return { content: change.newContent, merged: 0 }+ // The file on disk decides the form; an empty file inherits the model's.+ const eol = current ? eolOf(current) : eolOf(change.newContent)+ const baseLf = toLf(base)+ const currentLf = toLf(current)+ const newLf = toLf(change.newContent)+ if (currentLf === baseLf || currentLf === newLf) {+ return { content: withEol(change.newContent, eol), merged: 0 }}- const merged = mergeThreeWay(base, current, change.newContent)+ const merged = mergeThreeWay(baseLf, currentLf, newLf)if (merged.ok) {- return { content: merged.content, merged: merged.mergedRegions }+ return { content: withEol(merged.content, eol), 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.`,