For AI code editing with a diff and an Apply button, treat the model’s reply as a proposal, never as the new file. The server asks the LLM for an edit in a fixed format (a whole file, search/replace blocks or a unified diff), validates it, and returns it next to the exact code it was based on. The editor shows a diff between that base and the proposal, and nothing changes until the user clicks Apply. If the code has changed in the meantime, the proposal is stale and Apply is refused.
The examples below follow one concrete design: an editor for short, single-file coding exercises with an AI assistant that can propose changes to the open file.
Why not overwrite the editor with the model’s output?
Writing the reply straight into the editor fails in four ways:
- Lost edits. A model call takes seconds. Whatever the user typed while waiting is replaced by an answer computed from older code.
- Silent unrelated changes. Asked to fix one method, a model may also rename a variable or drop a comment somewhere else. Without a diff nobody notices.
- Truncated output. A reply cut off at the output limit is half a file. Written over the original, it deletes the other half.
- No way back. If the replacement bypasses the editor’s undo stack, the previous version is gone.
A proposal with a diff and an explicit Apply addresses all four, at the cost of one extra click.
Which edit format should you ask the LLM for?
There are four common choices, and each has a typical failure.
- Whole file. The model returns the complete updated file. It is the simplest format to produce and to apply, and you compute the diff yourself. The cost is output tokens proportional to the file size, a truncation risk for long files, and room for unrelated changes.
- Unified diff. Compact and familiar, but hunk headers contain line numbers and line counts that the model has to get right, and every context line has to match the file. A diff that does not apply cleanly is a common result.
- Search/replace blocks. Each block quotes a piece of the current code and gives its replacement. There are no line numbers to miscount. It fails when the quoted text differs from the file by whitespace, or when the snippet occurs more than once.
- Structured JSON edits. A list of operations such as “replace lines 10 to 14”. Easy to validate against a schema, but line numbers come back, and code inside JSON strings needs escaping that models sometimes get wrong.
The edit formats page of Aider, an open source coding assistant, documents the first three as “whole”, “diff” and “udiff”, with the same trade-off between simplicity and output size.
For a single short file, the whole-file format is a reasonable choice: the model returns the complete file, wrapped in a small JSON object that the request enforces with a strict JSON schema:
{
"explanation": "Sums the prices in a long to avoid overflow.",
"updatedCode": "public class Cart {\n ...\n}",
"summary": "Changed the type of total from int to long."
}
The output cost stays small, and a whole file needs no patch logic on the server. For a model without schema support, a plain-text fallback works: one explanation line, then the full file in a single fenced code block. Schema-enforced replies are covered in Spring AI structured output. For larger files, search/replace blocks are the usual next step.
How do you validate a proposed edit before showing it?
Check the structure first, then the content:
- The reply parses. Required fields are present and delimiters are closed. A truncated JSON document or a code fence without its closing line is an error, not a shorter file.
- The edit applies. For search/replace, each search text must match exactly once. For a unified diff, every hunk must apply without fuzz.
- The base is known. Record the exact code the model was given, so that later you can tell whether the user still has it.
- Sizes are bounded. Limit the instruction, the context you send and the output you accept.
- The result is still the same kind of file. If you can parse or compile the result cheaply, do it, and show the errors with the proposal instead of hiding the proposal.
With the whole-file format the server side of this list is short. Pass the instruction through a safety filter and secret redaction, and limit the inputs in length. Treat a reply without code as an error, and let the fallback parser accept code only from a fence that was closed. Then store the proposal with the chat reply, together with the file path and the base code. Whether the change is correct is decided by the person reading the diff and by the tests they run afterwards.
How do you apply search/replace blocks safely?
The rule is exact-once matching: zero matches means the model quoted code that is not there, two or more means the target is ambiguous. In both cases reject the block. Changes are applied in the browser, next to the editor, so the example is in TypeScript:
type Edit = { search: string; replace: string };
type Result = { ok: true; text: string } | { ok: false; reason: string };
function countOccurrences(text: string, needle: string): number {
let count = 0;
for (let at = text.indexOf(needle); at !== -1; at = text.indexOf(needle, at + 1)) {
count += 1;
}
return count;
}
function applyEdit(source: string, edit: Edit): Result {
if (edit.search.length === 0) {
return { ok: false, reason: 'empty search text' };
}
const matches = countOccurrences(source, edit.search);
if (matches !== 1) {
return { ok: false, reason: `search text matches ${matches} times, expected 1` };
}
const at = source.indexOf(edit.search);
const after = source.slice(at + edit.search.length);
return { ok: true, text: source.slice(0, at) + edit.replace + after };
}
const source = [
'int total = 0;',
'for (int price : prices) {',
' total += price;',
'}',
'System.out.println(total);',
'System.out.println(total);',
].join('\n');
const edits: Edit[] = [
{ search: 'int total = 0;', replace: 'long total = 0;' },
{ search: 'total += cost;', replace: 'total += price * 2;' },
{ search: 'System.out.println(total);', replace: 'log(total);' },
];
for (const [index, edit] of edits.entries()) {
const result = applyEdit(source, edit);
console.log(`block ${index + 1}: ${result.ok ? 'applied' : 'rejected: ' + result.reason}`);
if (result.ok) {
console.log(result.text.split('\n')[0]);
}
}
Saved as apply-edits.ts and run with node apply-edits.ts on Node.js 24, it prints:
block 1: applied
long total = 0;
block 2: rejected: search text matches 0 times, expected 1
block 3: rejected: search text matches 2 times, expected 1
A rejected block is useful feedback for a retry: send the reason back to the model and ask for a longer, unique search text. A silent fuzzy match would be a guess about where the change goes.
How do you show the change and apply it in Monaco?
Monaco ships a diff editor.
createDiffEditor
takes an original and a modified model, and the
renderSideBySide
option switches between two columns and an inline view.
A layout that works well: an open proposal replaces the code editor with a read-only inline diff editor, with the base code as the original and the proposed file as the modified side. A bar below it shows the number of changed lines with Apply and Discard. The chat can show the same change as a collapsible card with the file name and added and removed line counts, computed by a small line diff based on the longest common subsequence.
To apply a change in a mounted editor so that one Ctrl+Z reverts it, use
executeEdits.
Its documentation says the edits land on the undo-redo stack but no undo stop is pushed, so add
the stops yourself with pushUndoStop:
editor.pushUndoStop();
editor.executeEdits('ai-apply', [
{ range: editor.getModel()!.getFullModelRange(), text: proposedCode },
]);
editor.pushUndoStop();
After Apply or Discard, report the outcome to the server, and have the server accept an outcome for a proposal only once. Applied changes can stay in the chat as diff cards rebuilt from the stored base and proposed code, so they survive a reload.
What happens when the code changed before Apply?
The proposal is stale. It was computed from code the user no longer has, and applying it would discard their newer edits. The check is a comparison with the recorded base:
const isStale = proposal.baseCode !== currentCode || proposal.path !== activeFilePath;
Have the client save the editor content before the request, so the model edits what the user sees, and keep that content as the base. If the code or the active file differs when the reply is on screen, do not show the diff view: explain that the code has changed and disable Apply. Repeat the comparison in the Apply handler. The user can discard the proposal and ask again.
Refusing is the simple policy. With search/replace blocks you could instead re-run exact-once matching against the new code and apply only if every block still matches.
Is the model’s output trusted?
No. The model reads the user’s instruction, the code and the task text, and any of them can carry instructions aimed at the model. Treat the reply like any other external input:
- Keep system instructions apart from data. Send the task, the instruction, a summary of the tests and the current code as separately labelled blocks in the user message.
- Never run the proposed code automatically. Nothing executes until the user runs the code or the tests themselves.
- Never apply automatically by default. The diff is the review step, and it only works if a person sees it.
What can a first version leave out?
A first version can stay narrow and still be useful:
- One file per proposal: the file that is open in the editor.
- All or nothing: no accepting single hunks.
- No auto-apply and no automatic test run after Apply.
- No merging of a stale proposal with newer edits.
Summary
- Treat the model’s reply as a proposal and keep the base code it was computed from.
- Choose the edit format for your file sizes: whole file for short files, search/replace blocks with exact-once matching for longer ones.
- Reject replies that do not parse, are cut off or do not apply cleanly.
- Show a diff, and change the editor only on an explicit Apply, as one undoable edit where the editor allows it.
- Refuse stale proposals instead of overwriting newer edits.
- Never run or apply model output automatically.