Skip to content

fix(editor): refuse saves that would overwrite unnoticed disk changes - #30417

Merged
nwparker merged 1 commit into
mainfrom
nwparker/save-disk-precondition
Oct 20, 2026
Merged

nwparker merged 1 commit into
mainfrom
nwparker/save-disk-precondition

Conversation

@nwparker

@nwparker nwparker commented Oct 18, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 23 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​2739 $\color{#cf222e}{\Huge{\mathbf{−}}}$​120 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​2619
Prod 43 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1229 $\color{#cf222e}{\Huge{\mathbf{−}}}$​178 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1051

ELI5

When you save a file in Orca's editor, Orca now asks the machine that holds the file to check that nobody else changed it since that tab last read or wrote it. If an agent (or anything else) rewrote the file and Orca didn't notice, the save is stopped and the usual "This file changed on disk" banner appears, instead of the save silently wiping out the newer content.

What Changed

Before: autosave, Cmd/Ctrl+S, "Save" in the save-before-closing dialog, and the save-all before a restart wrote the tab's text straight to disk. If file watching missed an outside write, the newer content was overwritten with no warning.

After, for every editor surface that writes a file (code, rich Markdown, notebook, CSV, unstaged diff tabs, and combined-diff sections) and every save path (explicit save, autosave, save-and-close, the quit dialog, restart save):

  • Each save sends the fingerprint of the disk version that tab last loaded or wrote. This is the tab's existing lastKnownDiskSignature, the same one the changed-on-disk banner and restart scan already use. The host compares it with the file inside the write, under the per-file lock from feat(files): guarded file writes that refuse to overwrite a changed file #30605, and writes only if they still match.
  • File changed on disk: nothing is written. The tab keeps your edits and shows the changed-on-disk banner, which also pauses autosave, so there is no retry loop. This happens even when the tab had no unsaved edits. An explicit save says "This file changed on disk since your edits. Use the banner to compare, reload, or overwrite."
  • Overwrite: the banner gains an Overwrite button next to Compare, Reload from Disk and Keep My Edits. It is the only way to replace a disk change: Cmd/Ctrl+S, the save-before-closing dialog, saves from the mobile app, and the save before an explorer delete all stay checked while the banner is up. A refused save before a delete cancels the delete. Overwrite is hidden when the tab has no unsaved edits. Keep My Edits now explains itself: it keeps your version, and your next save replaces the version on disk.
  • Keep My Edits reads the file and records its fingerprint as the tab's new baseline. Any save started meanwhile waits for that read, so the next save overwrites exactly the version you chose to keep. If disk changes again after that, the save is refused again.
  • Saves of one text run in turn: code-view tabs that share one editor text model share one save queue, so each save is checked after the previous one finishes. A second save of identical text simply rewrites the same bytes.
  • Keep My Edits across tabs: Keep moves the one fingerprint of the shared code-view model (the model already holds the kept text), and saves from any tab of it wait for Keep's disk read.
  • Two tabs of the same file (for example, opened from two workspaces): see the table below. In short, tabs sharing one code-view model share one fingerprint; any other pairing (rich Markdown, Changes view, notebook, CSV) is checked independently, so the second save is refused with the banner rather than its text being synced.
  • Large paste: autosave waits while a chunked paste is still being inserted, then saves the pasted text, still checked. A paste that fails part way releases that wait.
  • Combined diff: section saves run one at a time per section; each is checked against the text that section last loaded or wrote, and an older write finishing never replaces newer edits. If the file changed, nothing is written and the section shows a bar with Reload from Disk (discards that section's edits) and Overwrite.
  • File deleted on disk: autosave won't recreate it; the tab is marked deleted. An explicit save or the restart save may recreate it.
  • No known disk version (for example a draft restored from an older session that never recorded one): the save is refused and the banner appears. Every save is built as one of three things: checked against a known version, the banner's explicit Overwrite, or refused. There is no "write without checking" case in editor code; the plain write exists only inside the writer, for hosts that lack the checked write.
  • Mobile: when the desktop tab has no edits and is behind disk, it moves to the version the phone just read and reloads. For a tab the desktop never opened, a phone save records the version the phone just verified as the tab's baseline (and withdraws it if the save fails), so those tabs can still be saved from the phone. If the save is refused, the phone gets its own message ("This file changed on the computer. Reload to get the latest version, then reapply your edit."). The desktop banner appears only if desktop edits were part of that save.
  • Restart save-all stays checked even while the banner shows. A refused file blocks the restart save, as any unsaved file already does.
  • Save results are now typed: written, blocked-stale, or failed. Closing a tab, the quit dialog, and the "saved" event act only on written. Anything else keeps the tab open and dirty. A refused save shows "This file changed on disk..." instead of "Failed to save", and a refused save-and-close answers the close dialog at once instead of after a 10 second timeout.
  • After every successful write, the tab's fingerprint is set to what the write left on disk, even if the save was superseded while writing. Code-view siblings move their fingerprint and drop their cached copy, so reopening one reloads instead of pushing older text back into the editor. That fingerprint comes from the saved text, so no extra file read or stat is needed. A Keep My Edits disk read that started before such a write does not overwrite it.

Older hosts: a remote Orca server or paired web host that predates the checked write (files.write.disk-precondition.v1) gets the compatibility fallback from #30605: Orca reads the file from that host, compares it with the tab's version, and writes only if they match. The gap between that read and the write is wider than on a current host, but it still catches the common case. There is no editor path that writes to an older host without comparing first, except the explicit Overwrite.

Which state is shared between tabs of one file

Rule: one baseline per code-view model; no content push; every other view stands alone. "Siblings" are only tabs in code view (Monaco, not the Changes view) showing one live editor model: the same file on one host, open in two workspaces. They hold one disk fingerprint, written only through setEditorDiskBaseline, so there is nothing for them to disagree about. A write, a clean load, Keep My Edits, Reload and its Undo move that one value. The model is dirty when any of its tabs has unsaved edits: a clean tab of a dirty model is never reloaded on its own, and a disk change marks every tab of the model with the banner. Text is never copied from one tab to another. A tab whose cached copy is stale mounts the live model's text (the truth) and stays editable; only when no live model exists is the stale copy dropped and reloaded from disk, once. Rich Markdown, notebook, CSV, preview, Changes and diff views are never siblings: each is checked against its own fingerprint, and if that is behind disk its save is refused and the banner offers Reload / Compare / Overwrite.

State Lives in Key Rule
Text being edited Monaco model model (path + host) Shared by Monaco between code-view siblings only
Disk fingerprint (baseline) lastKnownDiskSignature one value per code-view model; per tab for other views Written only through setEditorDiskBaseline, which sets every code-view sibling at once
Draft text editorDrafts tab Never copied between tabs; Reload clears it on code-view siblings; Undo of Reload does nothing if any sibling was typed into since
Dirty flag OpenFile.isDirty tab; the model is dirty if any tab is Every shared-text decision asks the model: reload, eviction, change marks, mobile adoption, the Overwrite button. A clean tab's disk text never enters a dirty model (one gate, mayPushTabTextIntoModel); only Reload and Overwrite resolve a dirty model
Content cache panel fileContents tab Never overwritten from another tab; evicted when its tab's fingerprint moves (the visible active tab reloads at once, others on reveal); stale cached text never replaces a live model's text, and a model-less stale copy is reloaded once
Conflict mark / banner externalMutation tab Refusals, external changes, Reload, Keep, Overwrite and mobile refusals set or clear it on every code-view sibling
Save queue saveQueue model Sibling saves run in turn; each is checked against the model's baseline as it stands after the previous one, and every written save is finalized the same way
Keep My Edits read pendingBaselineRestamps tab Saves wait for the read of every sibling; Keep then moves the model's one fingerprint (the model already holds the kept text) and evicts clean siblings' caches; cleared when the read settles
Chunked paste in progress pastesInFlight model Autosave of any tab of the model waits
Restore check pending pendingDiskBaselineVerification tab Per tab; pauses that tab's autosave until its restored draft is compared with disk
Live check pending pendingLiveDiskVerification tab Per tab; pauses that tab's autosave until a watcher event is verified
Owner move pending pendingOwnerMigration tab Per tab; pauses autosave and refuses explicit saves while the tab moves to its restored workspace
Autosave timer, save generation queue internals tab Per tab; they only schedule a save into the shared queue
Close / quit close dialog tab Closes only on written; a refusal marks every code-view sibling
Mobile save bridge tab When the whole model is clean, the save adopts the version the phone read as the model's baseline, and a failed save restores the one it replaced; a refusal goes to the phone, and to the desktop only if desktop edits were included
Combined-diff section section state section key Not a tab; saves run in turn per section and resolve their section by key when they run, are checked against the text that section loaded, and never replace newer edits

Why

The goal is #30415: stop file-watching workspaces that aren't active, which takes load off the macOS file event service. That is only safe if a save from a tab whose workspace isn't watched can never silently overwrite a change it hasn't seen. Watching can't promise that, so the write itself has to check.

Doing the compare inside the write, on the machine that owns the file, keeps the gap between check and write to one file read. A separate read-then-write from the client would leave a larger gap and add a round trip to every remote save.

Each tab is checked against the baseline it already keeps for the banner and the restart scan, so this needs no new stored state. Tabs that share one editor text model must agree on it, because the text being saved belongs to the model, not to one tab.

For older hosts we compare from the client rather than refuse, so saving against a remote server that hasn't updated keeps working while still catching most outside changes.

SSH, WSL and folder workspaces: SSH files are written by the remote Orca server, which compares on the remote machine. WSL and local folder workspaces use the desktop writer, which always supports the check. Nothing here depends on the git provider or on the workspace being a git worktree.

Known limits: another process can still write in the moment between the compare and the write. Tabs showing the same file in two workspaces keep separate drafts but share one disk fingerprint, so a hidden tab holding an older unsaved draft can later overwrite a newer save made from the other tab: the check sees no change on disk. This was already possible before this PR and is out of scope here.

Linked Issue

Fixes #

Visual Proof

N/A for screenshots: the visual changes are an Overwrite button on the existing changed-on-disk banner (whose sentence now says "Overwrite replaces the newer disk content."), a tooltip on Keep My Edits, and a one-line conflict bar on a combined-diff section whose save was refused. All use existing buttons and status colors.

Testing

  • editor-save-disk-precondition.test.ts (new), against a fake host that compares like the real writer:

    • An agent rewrites the file with no watcher event, then autosave runs: blocked, banner raised, disk untouched, no retry loop.
    • Two tabs of one file both save: the second is blocked and shows the banner.
    • An explicit save is refused, and so is a second one with the banner up; only the banner's Overwrite writes.
    • A refused save of a clean tab still raises the banner.
    • Keep My Edits, then save: the save waits for the disk read and passes against the kept version.
    • After a write, the baseline matches what disk holds (including a lone surrogate), and the next autosave passes.
    • A save with no known disk version is refused; Overwrite then writes.
    • Autosave doesn't recreate a deleted file; an explicit save does.
    • The restart save stays checked while the banner shows.
    • Rich Markdown, notebook and CSV saves are guarded the same way.
    • Two workspace tabs sharing one model that disagree on the disk version: both refused.
    • A restored draft whose editor never mounted: autosave and explicit save both guarded.
  • editor-save-disk-precondition.races.test.ts: concurrent identical saves from sibling tabs both succeed with one write; Cmd+S in one tab waits for Keep in its sibling; a sibling that remounts after Keep keeps the kept edits; a sibling's cached text follows another tab's save, so remounting, editing and saving it writes on top of that save; unstaged diff tab guarded; a save superseded mid-write still rebaselines; Keep's older read doesn't restamp over a newer write; stale message; save-and-close refusal answered at once.

  • editor-save-large-paste.test.ts: the real chunked paste holds autosave until the last chunk, then saves guarded; a 70 KiB paste followed by an outside write is refused.

  • mobile-markdown-bridge.test.ts and mobile-markdown-bridge-save-guards.test.ts: the fake writer now compares the precondition like the real one; a phone save refused after an outside write gets the phone message and leaves a clean desktop tab without a banner.

  • useFileDeletion.save-refusal.test.tsx: a refused save cancels the explorer delete.

  • monaco-large-text-paste.test.ts: a throwing paste still reports a result.

  • use-combined-diff-section-actions.disk-precondition.test.tsx: section saves are guarded, a refusal marks the section conflict, and only the conflict bar's Overwrite writes plain.

  • use-monaco-editor-mount.stale-cache.test.tsx: mounting a retained, stale cached text keeps the live model's text and stays editable; with no live model the stale copy is dropped once, and repeated mounts don't loop.

  • editor-save-shared-model-dirty.test.ts: with a dirty sibling, an external change banners both tabs with no lone reload, no eviction and no disk reads; after a restart, a file changed while closed banners every tab of the model.

  • editor-save-shared-model.test.ts: a Changes-view tab is never reached by Keep or Reload; two tabs sharing one model through save, autosave, Keep, Reload, Overwrite, an external change, save-and-close, the quit save, and a refused mobile save; a slow save in a code-view tab leaves a rich-Markdown tab's pending typing alone (its own save is then refused); Undo of Reload leaves a sibling that typed since alone.

  • use-combined-diff-section-actions.disk-precondition.test.tsx also covers overlapping saves of one section; mobile-markdown-bridge.test.ts covers a phone save after an external change to a clean desktop tab.

  • editor-save-guarded-write-paths.test.ts: the raw file write appears only inside writeEditorSave; the precondition builder never returns a plain write except for the explicit Overwrite; overwrite consent comes only from the conflict UI.

    • A remote host without the capability: Orca reads and compares, writes when disk still matches, and refuses when it doesn't.
    • Keep My Edits restamps every tab sharing the text, so the next save goes through.
  • Existing editor save suites updated for the new write arguments and results.

  • pnpm tc, oxlint, and pnpm run check:code-quality:changed pass locally.

  • I manually tested these changes locally

  • Automated tests added/updated, or explained why not below

AI Disclosure

Review

Agent skill upstream boundary

  • Not applicable, or this change copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

Ensure no issues in: Security, Cross-platoform support (Linux, Windows, Mac), Remote SSH, Mobile, general backwards compatibility, performance

Checklist

  • This PR is small and focused
  • I explained what changed and why (ELI5, the user-facing before/after, the mechanism, and why over the alternatives)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)

@coderabbitai

coderabbitai Bot commented Oct 18, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

File writes now accept optional disk preconditions and return results that can report changed or missing disk content. Local and remote write paths check preconditions, with client-side checks for remote hosts that do not enforce them. Editor saves use these results to update editor state, track overwrite verification, and show translated notices for changed or deleted files. Other guarded write paths cover combined-diff saves, file-deletion undo, and starter-config creation.

Priority: ➖ Normal

Merge Risk: 🟡 Moderate · up to ebf3d

The change adds protection against overwriting unnoticed disk changes, but CI currently fails on a lint error. A rare retry path can also refuse a later save wrongly after a lost reply. A small window remains where a concurrent external write is overwritten. Fix the lint failure and the retry recovery before merging.

Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 40.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 100 functions across 68 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed
Check name Status Explanation
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Title check Passed The title clearly and concisely describes the primary change: refusing editor saves that would overwrite unnoticed disk changes.
Description check Passed The pull request description is detailed, on-topic, and covers the required ELI5, changes, rationale, testing, compatibility, and checklist sections. The Linked Issue field is blank, manual testing is…
Full details: Description check

Explanation

The pull request description is detailed, on-topic, and covers the required ELI5, changes, rationale, testing, compatibility, and checklist sections. The Linked Issue field is blank, manual testing is unchecked, several validation commands are unchecked, and the Visual Proof section states N/A despite documented UI changes, but the description is otherwise substantially complete.

  • Fix all pre-merge checks with AI
✨ Finishing Touches: 💡 2
📝 Generate docstrings: 💡
  • Commit to this branch
  • Create a new PR
🛠️ Fix failing CI checks: 💡
  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5


ℹ️ Review info
⚙️ Run configuration
  • Configuration used: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: c67a40fb-ab9f-4f22-91fb-1eeaf1c2190c
📥 Commits

Reviewing files that changed from the base of the PR and between eaa1ee1 and 28dc089.

📒 Files selected for processing: 26
  • src/main/ipc/filesystem.test.ts
  • src/main/ipc/filesystem/filesystem-write-handlers.ts
  • src/main/ipc/filesystem/local-disk-write-precondition.test.ts
  • src/main/ipc/filesystem/local-disk-write-precondition.ts
  • src/main/providers/local-filesystem-provider.ts
  • src/main/runtime/files/file-mutations.ts
  • src/main/runtime/rpc/methods/files-mutation-methods.ts
  • src/main/runtime/rpc/methods/files-write-disk-precondition.test.ts
  • src/preload/api/filesystem-api.ts
  • src/preload/api/fs-bridge.ts
  • src/renderer/src/components/editor/diff-content-signature.ts
  • src/renderer/src/components/editor/editor-autosave-controller-test-fixture.ts
  • src/renderer/src/components/editor/editor-save-disk-precondition.test.ts
  • src/renderer/src/components/editor/editor-save-disk-precondition.ts
  • src/renderer/src/components/editor/editor-save-queue.ts
  • src/renderer/src/components/editor/restored-editor-owner-save-lifecycle.test.ts
  • src/renderer/src/lib/rename-user-named-tab-access.test.ts
  • src/renderer/src/runtime/runtime-file-mutation-client.ts
  • src/renderer/src/runtime/runtime-file-write-disk-precondition.test.ts
  • src/renderer/src/runtime/runtime-file-write-disk-precondition.ts
  • src/renderer/src/web/web-file-mutation-methods.ts
  • src/shared/disk-baseline-signature.ts
  • src/shared/file-write-disk-precondition.test.ts
  • src/shared/file-write-disk-precondition.ts
  • src/shared/protocol-version.ts
  • src/shared/rpc-contract/files-mutation-params.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 7 remain after this review.

if (diskConflict) {
return { ok: false, diskConflict }
}
await writeFile(authorizedPath, content, 'utf-8')

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

Make the guarded write conditional on the validated disk state.

If another process changes the file after checkLocalDiskWritePrecondition returns, this writeFile overwrites that change. The separate read and write operations do not enforce the precondition for that case. Use a write mechanism that coordinates the comparison and replacement with other writers; another check before writeFile would only narrow the race.

expect(file?.externalMutation).toBe('changed')
expect(file?.lastKnownDiskSignature).toBe(getDiskBaselineSignature('original'))
expect(store.getState().editorDrafts[FILE_ID]).toBe('edited')
expect(hasRecentSelfWrite(FILE_ID, 'agent rewrite')).toBe(false)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Check the self-write stamp under the tab’s actual key.

This tab has no runtimeEnvironmentId, but the assertion passes 'agent rewrite' as that ID. The assertion can pass even if the failed save leaves a stamp that suppresses a real disk-change event. Call hasRecentSelfWrite(FILE_ID) instead.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2


ℹ️ Review info
⚙️ Run configuration
  • Configuration used: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 9e3ea51a-b2fb-40cf-897e-0165e18667e0
📥 Commits

Reviewing files that changed from the base of the PR and between 28dc089 and 89b90f9.

📒 Files selected for processing: 30
  • src/main/ipc/filesystem/local-disk-write-precondition.test.ts
  • src/main/ipc/filesystem/local-disk-write-precondition.ts
  • src/main/ipc/filesystem/local-regular-file-read.ts
  • src/renderer/src/components/editor/ExternalFileChangeBanner.test.tsx
  • src/renderer/src/components/editor/ExternalFileChangeBanner.tsx
  • src/renderer/src/components/editor/editor-autosave-controller-test-fixture.ts
  • src/renderer/src/components/editor/editor-autosave.ts
  • src/renderer/src/components/editor/editor-file-save-attempt.test.ts
  • src/renderer/src/components/editor/editor-file-save-attempt.ts
  • src/renderer/src/components/editor/editor-save-baseline-flow.test.ts
  • src/renderer/src/components/editor/editor-save-disk-precondition.ts
  • src/renderer/src/components/editor/editor-save-queue.ts
  • src/renderer/src/i18n/locales/en.json
  • src/renderer/src/i18n/locales/es.json
  • src/renderer/src/i18n/locales/fr.json
  • src/renderer/src/i18n/locales/ja.json
  • src/renderer/src/i18n/locales/ko.json
  • src/renderer/src/i18n/locales/zh.json
  • src/renderer/src/runtime/runtime-file-mutation-client.ts
  • src/renderer/src/runtime/runtime-file-mutation-rpc.ts
  • src/renderer/src/runtime/runtime-file-write-disk-precondition.test.ts
  • src/renderer/src/runtime/runtime-file-write-disk-precondition.ts
  • src/renderer/src/store/slices/editor/actions/open-file-mutations.ts
  • src/renderer/src/store/slices/editor/types/editor-files-slice.ts
  • src/renderer/src/store/slices/editor/types/open-file.ts
  • src/renderer/src/web/preload-api/web-filesystem-api.ts
  • src/renderer/src/web/web-file-mutation-methods.test.ts
  • src/renderer/src/web/web-file-mutation-methods.ts
  • src/renderer/src/web/web-file-write-disk-precondition.test.ts
  • src/shared/disk-baseline-signature.ts
💤 Files with no reviewable changes: 1
  • src/renderer/src/runtime/runtime-file-write-disk-precondition.ts
🚧 Files skipped from review as they are similar to previous changes: 1
  • src/renderer/src/web/web-file-mutation-methods.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 5 remain after this review.

Comment thread src/renderer/src/i18n/locales/es.json Outdated
Comment on lines +16074 to +16075
"changedOnDisk": "This file changed on disk. Review the change before saving.",
"deletedOnDisk": "This file was deleted on disk."

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Translate the save-refusal strings into Spanish.

changedOnDisk and deletedOnDisk contain the English source text. Spanish users therefore see an English toast when a save is refused. The fr, ja and zh catalogs have translated values for these keys.

🌐 Proposed translation
-              "changedOnDisk": "This file changed on disk. Review the change before saving.",
-              "deletedOnDisk": "This file was deleted on disk."
+              "changedOnDisk": "Este archivo cambió en el disco. Revisa el cambio antes de guardar.",
+              "deletedOnDisk": "Este archivo se eliminó del disco."
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
"changedOnDisk": "This file changed on disk. Review the change before saving.",
"deletedOnDisk": "This file was deleted on disk."
"changedOnDisk": "Este archivo cambió en el disco. Revisa el cambio antes de guardar.",
"deletedOnDisk": "Este archivo se eliminó del disco."

Comment thread src/renderer/src/i18n/locales/ko.json Outdated
Comment on lines +16079 to +16080
"changedOnDisk": "This file changed on disk. Review the change before saving.",
"deletedOnDisk": "This file was deleted on disk."

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Translate the save-refusal strings into Korean.

changedOnDisk and deletedOnDisk contain the English source text. Korean users therefore see an English toast when a save is refused. The fr, ja and zh catalogs have translated values for these keys.

🌐 Proposed translation
-              "changedOnDisk": "This file changed on disk. Review the change before saving.",
-              "deletedOnDisk": "This file was deleted on disk."
+              "changedOnDisk": "이 파일이 디스크에서 변경되었습니다. 저장하기 전에 변경 사항을 확인하세요.",
+              "deletedOnDisk": "이 파일이 디스크에서 삭제되었습니다."
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
"changedOnDisk": "This file changed on disk. Review the change before saving.",
"deletedOnDisk": "This file was deleted on disk."
"changedOnDisk": "이 파일이 디스크에서 변경되었습니다. 저장하기 전에 변경 사항을 확인하세요.",
"deletedOnDisk": "이 파일이 디스크에서 삭제되었습니다."

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2


ℹ️ Review info
⚙️ Run configuration
  • Configuration used: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 628950a7-9ef6-4c33-956a-a0565d04434c
📥 Commits

Reviewing files that changed from the base of the PR and between 1ff6627 and f9719c8.

⛔ Files ignored due to path filters: 1
  • src/shared/rpc-contract/rpc-params-catalog.generated.ts is excluded by !**/*.generated.*
📒 Files selected for processing: 32
  • src/main/ipc/filesystem/local-disk-write-precondition.test.ts
  • src/main/ipc/filesystem/local-disk-write-precondition.ts
  • src/main/runtime/rpc/methods/files-mutation-methods.ts
  • src/main/runtime/rpc/methods/files-write-disk-precondition.test.ts
  • src/renderer/src/components/editor/combined-diff/CombinedDiffViewer.tsx
  • src/renderer/src/components/editor/combined-diff/review-controls/combined-diff-section-save-refusal.ts
  • src/renderer/src/components/editor/combined-diff/review-controls/use-combined-diff-section-actions.disk-precondition.test.tsx
  • src/renderer/src/components/editor/combined-diff/review-controls/use-combined-diff-section-actions.ts
  • src/renderer/src/components/editor/editor-autosave-controller.ts
  • src/renderer/src/components/editor/editor-autosave.ts
  • src/renderer/src/components/editor/editor-file-save-attempt.ts
  • src/renderer/src/components/editor/editor-save-overwrite-consent.test.ts
  • src/renderer/src/components/right-sidebar/file-explorer-delete-undo-precondition.test.tsx
  • src/renderer/src/components/right-sidebar/useFileDeletion.ts
  • src/renderer/src/components/settings/McpConfigSection.host-owner.test.tsx
  • src/renderer/src/components/settings/McpConfigSection.tsx
  • src/renderer/src/components/use-terminal-editor-close-dialog-actions.save-refusal.test.tsx
  • src/renderer/src/components/use-terminal-editor-close-dialog-actions.ts
  • src/renderer/src/i18n/locales/en.json
  • src/renderer/src/i18n/locales/es.json
  • src/renderer/src/i18n/locales/fr.json
  • src/renderer/src/i18n/locales/ja.json
  • src/renderer/src/i18n/locales/ko.json
  • src/renderer/src/i18n/locales/zh.json
  • src/renderer/src/runtime/runtime-file-mutation-client.ts
  • src/renderer/src/runtime/runtime-file-mutation-rpc.ts
  • src/renderer/src/runtime/runtime-file-write-disk-precondition.test.ts
  • src/renderer/src/web/web-file-mutation-methods.ts
  • src/renderer/src/web/web-file-write-disk-precondition.test.ts
  • src/shared/disk-baseline-signature.ts
  • src/shared/file-write-disk-precondition.ts
  • src/shared/rpc-contract/files-mutation-params.ts
🚧 Files skipped from review as they are similar to previous changes: 6
  • src/renderer/src/i18n/locales/fr.json
  • src/renderer/src/i18n/locales/es.json
  • src/renderer/src/i18n/locales/ko.json
  • src/renderer/src/i18n/locales/ja.json
  • src/renderer/src/i18n/locales/zh.json
  • src/renderer/src/i18n/locales/en.json

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 3 remain after this review.

}
throw error
}
return (await diskSignatureOfUtf8(buffer)) === precondition.expectedSignature ? null : 'changed'

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

Keep the guarded write bound to the file that was checked.

If another process replaces filePath after this comparison, the later path-based writeFile can overwrite the replacement without checking its content. The process-local lock does not prevent that replacement. Keep the comparison and write bound to one file handle where possible; use exclusive creation when the checked path was missing. Node.js documents the race between a filesystem check and a later path-based operation. (nodejs.org)

Based on learnings, “Repeated filename-based operations re-resolve the path each time,” creating a TOCTOU race.

Source: Learnings

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2


ℹ️ Review info
⚙️ Run configuration
  • Configuration used: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: c919f1aa-0f64-452f-806c-14ebdb530210
📥 Commits

Reviewing files that changed from the base of the PR and between f9719c8 and ebf3df9.

📒 Files selected for processing: 12
  • src/main/ipc/filesystem/local-disk-write-precondition.test.ts
  • src/main/ipc/filesystem/local-disk-write-precondition.ts
  • src/renderer/src/components/editor/combined-diff/review-controls/use-combined-diff-section-actions.refusal-resolution.test.tsx
  • src/renderer/src/components/editor/combined-diff/review-controls/use-combined-diff-section-actions.ts
  • src/renderer/src/components/editor/working-file-diff-disk-baseline.test.ts
  • src/renderer/src/components/editor/working-file-diff-disk-baseline.ts
  • src/renderer/src/runtime/runtime-file-mutation-client.ts
  • src/renderer/src/runtime/runtime-file-mutation-rpc.ts
  • src/renderer/src/runtime/runtime-file-write-disk-precondition.test.ts
  • src/renderer/src/runtime/runtime-file-write-disk-precondition.ts
  • src/shared/file-write-disk-precondition.test.ts
  • src/shared/file-write-disk-precondition.ts
🚧 Files skipped from review as they are similar to previous changes: 1
  • src/renderer/src/components/editor/combined-diff/review-controls/use-combined-diff-section-actions.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 0 remain after this review.

Comment on lines +100 to +115
try {
return await attempt()
} catch (error) {
if (error instanceof RuntimeConnectionChangedError) {
// Why: nothing was sent; one retry re-probes the new connection's capabilities.
return attempt()
}
// Why: a reply lost to the transport may follow a write that landed; keeping it avoids refusing the next save.
if (
isRecoverableRemoteRuntimeConnectionError(toRemoteRuntimeClientErrorLike(error)) &&
(await diskHoldsWrittenContent(context, filePath, content))
) {
return FILE_WRITE_OK
}
throw error
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Apply the lost-reply recovery to the retried attempt.

After a RuntimeConnectionChangedError, Line 105 calls return attempt() outside the try. The retry runs on a connection that just changed, so a transport timeout there is a realistic case. If the retry's write lands but its reply is lost, the save fails without the diskHoldsWrittenContent check. The draft stays dirty while disk already holds the new content. The next guarded save then compares against the old baseline and refuses with changed. This is the outcome the recovery branch exists to prevent. Route both attempts through the same recovery.

🐛 Proposed fix
--- "a/src/renderer/src/runtime/runtime-file-write-disk-precondition.ts"
+++ "b/src/renderer/src/runtime/runtime-file-write-disk-precondition.ts"
@@ -97,22 +97,30 @@
         15_000
       )
     )
-  try {
-    return await attempt()
-  } catch (error) {
-    if (error instanceof RuntimeConnectionChangedError) {
-      // Why: nothing was sent; one retry re-probes the new connection's capabilities.
-      return attempt()
-    }
-    // Why: a reply lost to the transport may follow a write that landed; keeping it avoids refusing the next save.
-    if (
-      isRecoverableRemoteRuntimeConnectionError(toRemoteRuntimeClientErrorLike(error)) &&
-      (await diskHoldsWrittenContent(context, filePath, content))
-    ) {
-      return FILE_WRITE_OK
-    }
-    throw error
-  }
+  const attemptOrRecover = async (): Promise<FileWriteResult> => {
+    try {
+      return await attempt()
+    } catch (error) {
+      // Why: a reply lost to the transport may follow a write that landed; keeping it avoids refusing the next save.
+      if (
+        !(error instanceof RuntimeConnectionChangedError) &&
+        isRecoverableRemoteRuntimeConnectionError(toRemoteRuntimeClientErrorLike(error)) &&
+        (await diskHoldsWrittenContent(context, filePath, content))
+      ) {
+        return FILE_WRITE_OK
+      }
+      throw error
+    }
+  }
+  try {
+    return await attemptOrRecover()
+  } catch (error) {
+    if (error instanceof RuntimeConnectionChangedError) {
+      // Why: nothing was sent; one retry re-probes the new connection's capabilities.
+      return attemptOrRecover()
+    }
+    throw error
+  }
 }
 
 export async function checkDiskPreconditionFromClient(
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
try {
return await attempt()
} catch (error) {
if (error instanceof RuntimeConnectionChangedError) {
// Why: nothing was sent; one retry re-probes the new connection's capabilities.
return attempt()
}
// Why: a reply lost to the transport may follow a write that landed; keeping it avoids refusing the next save.
if (
isRecoverableRemoteRuntimeConnectionError(toRemoteRuntimeClientErrorLike(error)) &&
(await diskHoldsWrittenContent(context, filePath, content))
) {
return FILE_WRITE_OK
}
throw error
}
const attemptOrRecover = async (): Promise<FileWriteResult> => {
try {
return await attempt()
} catch (error) {
// Why: a reply lost to the transport may follow a write that landed; keeping it avoids refusing the next save.
if (
!(error instanceof RuntimeConnectionChangedError) &&
isRecoverableRemoteRuntimeConnectionError(toRemoteRuntimeClientErrorLike(error)) &&
(await diskHoldsWrittenContent(context, filePath, content))
) {
return FILE_WRITE_OK
}
throw error
}
}
try {
return await attemptOrRecover()
} catch (error) {
if (error instanceof RuntimeConnectionChangedError) {
// Why: nothing was sent; one retry re-probes the new connection's capabilities.
return attemptOrRecover()
}
throw error
}

@nwparker
nwparker force-pushed the nwparker/save-disk-precondition branch from 0a5c9ac to e07e72b Compare October 19, 2026 05:37
@nwparker
nwparker force-pushed the nwparker/save-disk-precondition branch from 1ffd4fe to 2bdb993 Compare October 19, 2026 07:04
@nwparker
nwparker changed the base branch from main to nwparker/guarded-file-write October 19, 2026 07:04
@nwparker
nwparker force-pushed the nwparker/save-disk-precondition branch 4 times, most recently from a114e54 to aea304b Compare October 19, 2026 08:43
@nwparker
nwparker requested a review from Jinwoo-H as a code owner October 19, 2026 08:43
@nwparker
nwparker changed the base branch from nwparker/guarded-file-write to main October 19, 2026 08:43
@nwparker
nwparker force-pushed the nwparker/save-disk-precondition branch from aea304b to 541e524 Compare October 19, 2026 10:43
@nwparker
nwparker changed the base branch from main to nwparker/reload-as-undoable-edit October 19, 2026 10:43
@nwparker
nwparker force-pushed the nwparker/save-disk-precondition branch 2 times, most recently from 6317bce to 9eabd83 Compare October 19, 2026 11:02
@nwparker
nwparker force-pushed the nwparker/reload-as-undoable-edit branch from 9d9e840 to 7692b61 Compare October 19, 2026 11:04
@nwparker
nwparker force-pushed the nwparker/save-disk-precondition branch from f3a33ec to 4e4cf54 Compare October 19, 2026 11:16
@nwparker
nwparker force-pushed the nwparker/reload-as-undoable-edit branch 2 times, most recently from ca6f78c to c1a7f39 Compare October 19, 2026 11:46
@nwparker
nwparker marked this pull request as draft October 19, 2026 19:51
@nwparker

Copy link
Copy Markdown
Contributor Author

Pausing as draft: reviews of this stack keep tracing back to one root cause — an open file's content and unsaved state live in several places (per-tab store fields, per-panel caches, the draft store, the editor model, rich editors). A short design for a single editor buffer per file is being written first; this PR will be re-scoped against it.

@nwparker
nwparker force-pushed the nwparker/save-disk-precondition branch from 4e4cf54 to 1198438 Compare October 20, 2026 04:23
@nwparker
nwparker changed the base branch from nwparker/reload-as-undoable-edit to nwparker/editor-buffer-1b-share October 20, 2026 04:25
@nwparker
nwparker marked this pull request as ready for review October 20, 2026 04:26
@nwparker
nwparker marked this pull request as draft October 20, 2026 05:31
@nwparker
nwparker force-pushed the nwparker/save-disk-precondition branch from 2915277 to d41bf5d Compare October 20, 2026 05:37
@nwparker
nwparker changed the base branch from nwparker/editor-buffer-1b-share to main October 20, 2026 05:38
@nwparker
nwparker marked this pull request as ready for review October 20, 2026 05:38
Every editor save carries the disk version its text came from and the host
refuses the write when disk moved on; only the banner's explicit Overwrite
writes without that check. Older hosts compare from the client first.

Co-Authored-By: Claude <[email protected]>
@nwparker
nwparker force-pushed the nwparker/save-disk-precondition branch from 2619d82 to 7302aac Compare October 20, 2026 11:21
@nwparker
nwparker merged commit 8b11d90 into main Oct 20, 2026
33 checks passed
Jinwoo-H added a commit that referenced this pull request Oct 20, 2026
origin/main's #30417 edited the renderer Markdown bridge this branch removes; with no
window relay left, its rollback module and the editor's 'mobile' save trigger have no
caller, so they go too.
nwparker added a commit that referenced this pull request Oct 20, 2026
…rt stacks (#31216)

Fixes bugs found reviewing #30270, #30605, #30885, #30417, #31113, #30415,
#30992 and #30997, and removes code those PRs made unnecessary.

Co-authored-by: Claude <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant