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(edit): file_edit finds the line the model actually sent

Davidc539aa74d96f
diff --git a/src/lib/__tests__/surgical-edit-crlf.test.ts b/src/lib/__tests__/surgical-edit-crlf.test.ts
new file mode 100644
index 00000000..078d30c9
--- /dev/null
+++ b/src/lib/__tests__/surgical-edit-crlf.test.ts
@@ -0,0 +1,102 @@
+/**
+ * `file_edit` could not touch a single Windows file.
+ *
+ * Measured at the wire on the Windows box, 2026-08-15, with the real coding
+ * agent against a real CRLF file: `file_read` handed the model the raw content
+ * (6 CRLF, 0 bare LF), the model sent back a multi-line `old_string` with
+ * plain LF, twice in a row, and `file_edit` answered "old_string not found"
+ * both times. The model said it out loud in its final message: the tool could
+ * not match because of the line endings, so it fell back to a shell one-liner.
+ * A user on a stricter setup, or a smaller model without that idea, is simply
+ * told the file cannot be edited.
+ *
+ * Models emit LF. That is not a decision anyone made about the file, it is an
+ * artefact of the model, exactly as in the staged-apply fix (E14). So the
+ * search compares on one normalized form.
+ *
+ * The write-back is stricter here than in staged-apply, and deliberately so:
+ * `file_edit` is the surgical tool. Only the matched region is replaced, in the
+ * file's own line endings, and every byte around it stays untouched, so an
+ * edit to three lines never shows up as a whole-file rewrite.
+ *
+ * Run: npx vitest run src/lib/__tests__/surgical-edit-crlf.test.ts
+ */
+import { describe, it, expect } from 'vitest'
+import { applyUniqueEdit } from '../surgical-edit'
+
+const crlf = (lines: string[]) => lines.join('\r\n')
+const lf = (lines: string[]) => lines.join('\n')
+
+const FILE = ['import sys', '', 'def greet():', ' print("alpha")', ' print("beta")', '', 'greet()']
+
+describe('file_edit on a CRLF file with an LF search string', () => {
+ it('finds a multi-line old_string that arrives with LF', () => {
+ // The exact pair measured on the box.
+ const r = applyUniqueEdit(
+ crlf(FILE),
+ lf([' print("alpha")', ' print("beta")']),
+ ' print("gamma")',
+ )
+ expect(r.ok).toBe(true)
+ expect(r.matches).toBe(1)
+ expect(r.content).toContain('print("gamma")')
+ expect(r.content).not.toContain('alpha')
+ })
+
+ it('leaves the rest of the file byte for byte alone', () => {
+ const before = crlf(FILE)
+ const r = applyUniqueEdit(
+ before,
+ lf([' print("alpha")', ' print("beta")']),
+ ' print("gamma")',
+ )
+ expect(r.content).toBe(crlf(['import sys', '', 'def greet():', ' print("gamma")', '', 'greet()']))
+ // No LF sneaked in anywhere, and nothing outside the match moved.
+ expect(r.content!.replace(/\r\n/g, '')).not.toContain('\n')
+ })
+
+ it('writes a multi-line new_string in the line endings the file has', () => {
+ const r = applyUniqueEdit(
+ crlf(FILE),
+ lf([' print("alpha")', ' print("beta")']),
+ lf([' print("one")', ' print("two")']),
+ )
+ expect(r.ok).toBe(true)
+ expect(r.content).toContain('print("one")\r\n print("two")')
+ expect(r.content!.replace(/\r\n/g, '')).not.toContain('\n')
+ })
+
+ it('leaves an LF file on LF', () => {
+ const r = applyUniqueEdit(
+ lf(FILE),
+ lf([' print("alpha")', ' print("beta")']),
+ lf([' print("one")', ' print("two")']),
+ )
+ expect(r.ok).toBe(true)
+ expect(r.content).not.toContain('\r')
+ })
+
+ it('still counts two CRLF places as two, so an ambiguous edit is refused', () => {
+ // Normalizing must not turn "matches twice" into a silent single hit.
+ const twice = crlf(['a = 1', 'x()', 'y()', 'b = 2', 'x()', 'y()'])
+ const r = applyUniqueEdit(twice, lf(['x()', 'y()']), 'z()')
+ expect(r.ok).toBe(false)
+ expect(r.reason).toBe('not_unique')
+ expect(r.matches).toBe(2)
+ })
+
+ it('calls a CRLF old_string against LF-only content a no-op when it is one', () => {
+ // The mirror case: the model copied the CRLF text back verbatim. Identical
+ // content must not be written as a "change".
+ const r = applyUniqueEdit(lf(FILE), crlf([' print("alpha")']), lf([' print("alpha")']))
+ expect(r.ok).toBe(false)
+ expect(r.reason).toBe('noop')
+ })
+
+ it('still reports a genuinely missing string as not_found', () => {
+ const r = applyUniqueEdit(crlf(FILE), lf([' print("nope")', ' print("gone")']), 'x')
+ expect(r.ok).toBe(false)
+ expect(r.reason).toBe('not_found')
+ expect(r.matches).toBe(0)
+ })
+})
diff --git a/src/lib/surgical-edit.ts b/src/lib/surgical-edit.ts
index 205be7eb..5a33c218 100644
--- a/src/lib/surgical-edit.ts
+++ b/src/lib/surgical-edit.ts
@@ -24,6 +24,54 @@ export interface EditOutcome {
reason?: EditFailReason
}
+/**
+ * Line endings, the reason `file_edit` could not touch a Windows file at all.
+ *
+ * Measured at the wire on the Windows box, 2026-08-15: `file_read` hands the
+ * model the raw file, so on Windows it carries CRLF, and the model sends its
+ * `old_string` back with plain LF, which is what models emit. A literal search
+ * then finds nothing and the user is told the file cannot be edited. Same
+ * mismatch as the staged-apply fix, one layer down.
+ *
+ * So the search runs on one normalized form. The write-back does NOT: this is
+ * the surgical tool, so only the matched region is replaced, in the file's own
+ * endings, and every byte around it is left exactly as it was.
+ */
+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)
+
+/**
+ * Normalize to LF and keep, for every LF position, the index it came from in
+ * the original. That is what lets the match be found on the normalized form
+ * and the replacement be cut out of the ORIGINAL, so the untouched part of the
+ * file never changes shape. The trailing entry is the end marker, so
+ * `map[start + needle.length]` is the index just past the match.
+ */
+function lfWithMap(text: string): { lf: string; map: number[] } {
+ let lf = ''
+ const map: number[] = []
+ for (let i = 0; i < text.length; i++) {
+ if (text[i] === '\r' && text[i + 1] === '\n') {
+ lf += '\n'
+ map.push(i)
+ i++
+ continue
+ }
+ lf += text[i]
+ map.push(i)
+ }
+ map.push(text.length)
+ return { lf, map }
+}
+
/** Count NON-overlapping occurrences of `needle` in `haystack`. */
export function countOccurrences(haystack: string, needle: string): number {
if (needle === '') return 0
@@ -43,13 +91,22 @@ export function countOccurrences(haystack: string, needle: string): number {
*/
export function applyUniqueEdit(content: string, oldString: string, newString: string): EditOutcome {
if (oldString === '') return { ok: false, matches: 0, reason: 'empty_old' }
- const matches = countOccurrences(content, oldString)
- if (oldString === newString) return { ok: false, matches, reason: 'noop' }
+ const { lf: contentLf, map } = lfWithMap(content)
+ const oldLf = toLf(oldString)
+ const newLf = toLf(newString)
+ const matches = countOccurrences(contentLf, oldLf)
+ if (oldLf === newLf) return { ok: false, matches, reason: 'noop' }
if (matches === 0) return { ok: false, matches: 0, reason: 'not_found' }
if (matches > 1) return { ok: false, matches, reason: 'not_unique' }
- // Exactly one occurrence. Use a FUNCTION replacer so `$&`, `$1`, `$$` etc.
- // in newString are inserted literally — a plain-string replacement would
- // interpret them as capture-group references and corrupt the output.
- const updated = content.replace(oldString, () => newString)
+ // Exactly one occurrence. Cut it out of the ORIGINAL by index instead of
+ // running a replace over the normalized copy: that keeps every byte outside
+ // the match untouched, so a three-line edit stays a three-line diff. Slicing
+ // also sidesteps the `$&` / `$1` / `$$` capture-group syntax that a plain
+ // string replacement would interpret and corrupt.
+ const start = contentLf.indexOf(oldLf)
+ const updated =
+ content.slice(0, map[start]) +
+ withEol(newLf, eolOf(content)) +
+ content.slice(map[start + oldLf.length])
return { ok: true, content: updated, matches: 1 }
}