Skip to content

feat(files): guarded file writes that refuse to overwrite a changed file - #30605

Merged
nwparker merged 4 commits into
mainfrom
nwparker/guarded-file-write
Oct 19, 2026
Merged

nwparker merged 4 commits into
mainfrom
nwparker/guarded-file-write

Conversation

@nwparker

@nwparker nwparker commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 15 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1719 $\color{#cf222e}{\Huge{\mathbf{−}}}$​8 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1711
Prod 36 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1219 $\color{#cf222e}{\Huge{\mathbf{−}}}$​142 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​1077

ELI5

This adds a "write only if the file hasn't changed" option to Orca's file writes. The caller says which version of the file it expects to find. If the file on disk is no longer that version, nothing is written and the caller is told why ("changed" or "deleted").

This is groundwork for guarding editor saves (#30417). Editor saves don't use it yet. The only users in this PR are undoing a file delete and creating the starter MCP config.

What Changed

Before: every file write simply replaced whatever was on disk.

After:

  • New option on writes. A write can carry an expected-version fingerprint. The process doing the write reads the file, compares, and writes only if it matches. Otherwise it returns a "changed" or "missing" refusal, unless the caller allowed recreating a missing file.
  • Where the check runs: in Orca's main process for local and WSL files (fs:writeFile), and on runtime hosts for remote and SSH workspaces.
    • Writes to one file are serialized for every writer in that process: a lock on the file's canonical path, then one on its inode, so symlinks and hardlinks share a lock. Symlink chains are followed to their final target (up to 40 links); a link loop is refused. Locally, only the ENOENT code counts as a missing file.
    • Large files are hashed in slices so the main process isn't blocked. The fingerprint covers what UTF-8 actually stores.
  • Remote servers expose this as a separate RPC method, files.writeIfUnchanged, advertised by the capability files.write.disk-precondition.v1. Plain files.write is unchanged.
    • A server too old to know the new method answers "method not found" and writes nothing, so the check can't be silently dropped.
    • For older servers, the client reads the file and compares before a plain write. Only a real "file not found" counts as deleted, a file now too large to read counts as changed, and any other read error fails the write.
    • Each guarded write is pinned to the runtime that answered the capability check, and the pin is checked on the socket that actually sends it: the desktop asks that socket's own status first (shared or one-shot) and sends only if it names the same runtime; the paired web client pins to its own connection. A mismatch sends nothing, and the client retries once after checking again, but only within the same pairing: a save never follows the environment to a host it was re-paired to.
    • Writes without a fingerprint behave exactly as before: no locks, no pinning.
    • On an older server, a file too large for one preview reply is read in chunks for the comparison, as the desktop client already does.
  • First users:
    • Undoing a file delete now refuses if something else has been created at that path since the delete. An undo the host refused (it wrote nothing) stays on the history so it can be retried; any other failure, such as a timeout that may have applied it, drops the step as before.
    • Creating the starter .mcp.json now refuses if a different file appeared after the listing.
    • In both cases the error goes through the existing failure messages.

Why

Editor saves currently overwrite disk blindly, so an agent's changes can be lost when file watching misses them. Fixing that needs a write that can refuse. Landing the write path on its own lets reviewers check the file-system, locking and remote-compatibility parts separately from the editor change that will use them (#30417).

Doing the check inside the write, rather than a separate read beforehand, keeps the gap between check and write to one file read. Another process can still write inside that gap.

Linked Issue

Fixes #

Visual Proof

N/A: no UI change.

Testing

  • Writer:

    • Match, mismatch, and missing file (with and without allowing recreation).
    • A file that grows during the check.
    • Concurrent writes through the same path, a symlink, a hardlink, a dangling symlink (including a relative one through a symlinked folder), and a file created mid-queue.
    • Inode 0 on network mounts, and folders whose real path can't be resolved.
    • Sliced hashing matches whole-file hashing.
  • Remote and paired web client:

    • A server that supports the check, and one that doesn't (match, mismatch, not found, too large, other read errors).
    • An older server reached after the capability check can't perform the write.
    • Runtime and connection pinning, including retrying after a reconnect, and a reply lost after the write landed (only confirmed on the same pairing).
  • Not-found classification: only the ENOENT code, or not-found wording at the start of the message (after the desktop's IPC wrapper), counts. A path that contains "ENOENT" or "Error: ENOENT: …", or any other errno code, doesn't.

  • Pinning on the sending socket: a shared socket and a one-shot socket that reached a replacement runtime send nothing; a socket change between the check and the send rejects without sending; plain writes after a reconnect aren't pinned.

  • Plain writes: a write without a fingerprint isn't held up by a stuck guarded write to the same file.

  • First users: undo-delete and the MCP starter don't replace an existing different file.

  • pnpm tc, pnpm lint, the changed-code quality gate, and the related vitest suites 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

Remote compatibility: the new method is used only when the server advertises it, and old clients never send it. Mobile and older desktop builds see no change.

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)

Adds an optional disk precondition to file writes: the writer compares the file
on disk with an expected signature inside the write, serialized per file (path
then inode), and refuses with a typed changed/missing result instead of writing.
Remote hosts serve it as files.writeIfUnchanged behind a capability; older
hosts get a client-side compare that fails closed, pinned to the probed runtime
and connection. Undo of a delete and the MCP starter config use it to write only
into a missing or identical file. Groundwork for guarding editor saves.
@coderabbitai

coderabbitai Bot commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

📝 Walkthrough

The change adds shared disk-baseline signatures and conditional-write contracts. Local and runtime-mediated file writes can check a disk precondition and return a conflict result. Runtime calls can be pinned to the runtime and connection observed during capability checks. File-deletion undo, starter-config creation, and web file writes use the conditional-write flow. Tests cover baseline comparisons, write conflicts, aliasing, reconnects, and caller behavior.

Priority: ⬇️ Low

Merge Risk: 🔵 Low · up to 3de11

Guarded writes may fail during a web reconnect, and recovery after a lost reply may report success from a replacement host. Both are bounded cases, but they warrant correction or explicit acceptance before merging.

Pre-merge checks: Passed 3 · Failed 2

Failed Failed checks: 2 warnings

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 47.22% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 72 functions across 50 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check Warning The description clearly explains the change, motivation, implementation, testing, compatibility considerations, and checklist status. However, the required Linked Issue field is incomplete: it contain… Add the actual issue reference under Linked Issue, such as Fixes #30417 if that is the issue addressed by this pull request. If the pull request is internal and does not need an issue, update the section according to the repository’s main…
Passed Passed checks: 3 passed
Check name Status Explanation
Title check Passed The title clearly summarizes the main change: guarded file writes refuse to overwrite files that changed.
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.
Full details: Description check

Explanation

The description clearly explains the change, motivation, implementation, testing, compatibility considerations, and checklist status. However, the required Linked Issue field is incomplete: it contains Fixes # without an issue number or link. The referenced #30417 appears in the explanation but is not entered in the Linked Issue section.

Resolution

Add the actual issue reference under Linked Issue, such as Fixes #30417 if that is the issue addressed by this pull request. If the pull request is internal and does not need an issue, update the section according to the repository’s maintainer exception. Also complete or explicitly mark the AI Disclosure section if required for this contributor.

  • Fix all pre-merge checks with AI
✨ Finishing Touches: 💡 1
📝 Generate docstrings: 💡
  • 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: 1


ℹ️ Review info
⚙️ Run configuration
  • Configuration used: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 4e9bd761-a022-4837-9a8d-764bd1e58b01
📥 Commits

Reviewing files that changed from the base of the PR and between b331710 and 0e2d7c9.

⛔ Files ignored due to path filters: 1
  • src/shared/rpc-contract/rpc-params-catalog.generated.ts is excluded by !**/*.generated.*
📒 Files selected for processing: 40
  • src/main/destination-serialized-local-rename.ts
  • 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/ipc/filesystem/local-regular-file-read.ts
  • src/main/ipc/runtime-environments/runtime-environment-support-routing.test.ts
  • src/main/ipc/runtime-environments/runtime-environment-support-routing.ts
  • src/main/ipc/runtime-environments/runtime-environment-transport-routing.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/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/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/web/preload-api/web-filesystem-api.ts
  • src/renderer/src/web/preload-api/web-runtime-calls-connection-pin.test.ts
  • src/renderer/src/web/preload-api/web-runtime-calls.ts
  • src/renderer/src/web/preload-api/web-runtime-environments-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/renderer/src/web/web-runtime-client.ts
  • src/renderer/src/web/web-runtime-connection-transport.ts
  • src/renderer/src/web/web-runtime-request-registry-connection-pin.test.ts
  • src/renderer/src/web/web-runtime-request-registry.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; 5 remain after this review.

Comment on lines +232 to +239
const epochBeforeProbe = client.connectionEpoch
const status = await callBoundRuntimeResult<RuntimeStatus>('status.get', undefined, 15_000)
assertFileMutationOwnershipCapability(status)
// Why: the same client reconnects internally; the mutation must reach the runtime that answered.
if (client.connectionEpoch !== epochBeforeProbe) {
throw new Error(RUNTIME_CONNECTION_CHANGED_MESSAGE)
}
probedEpoch = epochBeforeProbe

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

Retry the probe once when the epoch changes during status.get.

epochBeforeProbe is read before status.get waits for a connection. A mutation can start while the client is disconnected or reconnecting. In that case, connectionOpened() increments the epoch during the probe, and the check on Line 236 throws RUNTIME_CONNECTION_CHANGED_MESSAGE. Nothing was sent at that point.

callMutation in web-file-mutation-methods.ts does not retry this error. The mutation then fails for the user. This applies to every web mutation that calls assertMutationSupported: writeFile, createFile, createDir, rename, copy and deletePath. Before this change, these mutations waited for the connection and then succeeded. The renderer path in writeRemoteFileIfUnchanged retries once on the same error, but the web path does not.

Re-probe once inside assertMutationSupported when the epoch changed. The status that is used then always comes from the connection that is pinned.

🔁 Proposed fix
--- "a/src/renderer/src/web/preload-api/web-filesystem-api.ts"
+++ "b/src/renderer/src/web/preload-api/web-filesystem-api.ts"
@@ -228,17 +228,20 @@
         false,
         environment.id
       ),
     assertMutationSupported: async () => {
-      const epochBeforeProbe = client.connectionEpoch
-      const status = await callBoundRuntimeResult<RuntimeStatus>('status.get', undefined, 15_000)
-      assertFileMutationOwnershipCapability(status)
-      // Why: the same client reconnects internally; the mutation must reach the runtime that answered.
-      if (client.connectionEpoch !== epochBeforeProbe) {
-        throw new Error(RUNTIME_CONNECTION_CHANGED_MESSAGE)
-      }
-      probedEpoch = epochBeforeProbe
-      return status.capabilities ?? []
+      // Why: the same client reconnects internally; the mutation must reach the runtime that answered.
+      // One re-probe covers a probe that started before the connection was established.
+      for (let attempt = 0; attempt < 2; attempt += 1) {
+        const epochBeforeProbe = client.connectionEpoch
+        const status = await callBoundRuntimeResult<RuntimeStatus>('status.get', undefined, 15_000)
+        assertFileMutationOwnershipCapability(status)
+        if (client.connectionEpoch === epochBeforeProbe) {
+          probedEpoch = epochBeforeProbe
+          return status.capabilities ?? []
+        }
+      }
+      throw new Error(RUNTIME_CONNECTION_CHANGED_MESSAGE)
     },
     callRuntimeResult: callBoundRuntimeResult,
     getSshState: async (targetId) =>
       (

nwparker added a commit that referenced this pull request Oct 19, 2026
The tab's one shared Monaco model owns the disk version its text is based on;
a save of that text carries it as the write precondition (#30605), and a refusal
raises the existing changed-on-disk banner or deleted tombstone. Other editor
surfaces (rich markdown, notebooks, CSV, diff views, mobile) save as before.

@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.

Caution

Some comments are outside the diff and can’t be posted inline due to GitHub limitations.

⚠️ Outside diff range comments (1)

🟡 Minor · Keep lost-reply verification on the original… · runtime-file-write-disk-precondition.ts:125-128

src/renderer/src/runtime/runtime-file-write-disk-precondition.ts:125-128
🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

Keep lost-reply verification on the original pairing.

When the write loses its reply, the recovery read captures the current pairing revision. A re-pair can therefore route the read to the replacement host. If that host already contains content, the function returns FILE_WRITE_OK without confirming the original write.

Check the pairing revision before and after the recovery read, or pass the captured revision into readRuntimeFileContent.

🐛 Suggested fix
     if (
       isRecoverableRemoteRuntimeConnectionError(toRemoteRuntimeClientErrorLike(error)) &&
-      (await diskHoldsWrittenContent(context, filePath, content))
+      getRuntimeEnvironmentRevision(context.target.environmentId) === pairingRevision &&
+      (await diskHoldsWrittenContent(context, filePath, content)) &&
+      getRuntimeEnvironmentRevision(context.target.environmentId) === pairingRevision
     ) {

ℹ️ Review info
⚙️ Run configuration
  • Configuration used: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 48edf7fc-8f47-423a-ae76-e52621a528af
📥 Commits

Reviewing files that changed from the base of the PR and between 81ed9ff and 3de1185.

📒 Files selected for processing: 6
  • src/renderer/src/components/right-sidebar/file-explorer-delete-undo-precondition.test.tsx
  • src/renderer/src/components/right-sidebar/fileExplorerUndoRedo.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.ts

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

@nwparker
nwparker merged commit 699b9a0 into main Oct 19, 2026
40 checks passed
nwparker added a commit that referenced this pull request Oct 19, 2026
The tab's one shared Monaco model owns the disk version its text is based on;
a save of that text carries it as the write precondition (#30605), and a refusal
raises the existing changed-on-disk banner or deleted tombstone. Other editor
surfaces (rich markdown, notebooks, CSV, diff views, mobile) save as before.
Jinwoo-H added a commit that referenced this pull request Oct 20, 2026
…cover the untitled tab

A server before #30605 has no files.writeIfUnchanged, so the save is refused with the
existing update-required message rather than written unchecked.
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]>
Jinwoo-H added a commit that referenced this pull request Oct 21, 2026
…ver (#31101)

* fix(runtime): a phone reads and saves Markdown tabs on a headless server

With no window to relay through, markdown.readTab and markdown.saveTab answered
renderer_unavailable. Main now reads the tab's file (or its saved draft) from disk and
saves with a version compare plus the disk write precondition, in the shapes the
window's editor relay returns. With a window attached the relay is unchanged.

* Headless Markdown save: keep the draft's disk baseline, honour read-only tabs, re-find the record to clear

* Use the disk baseline only for a draft

* ci: run the phone Markdown spec's orcad case in the orca serve mode-switch job

* Headless Markdown: answer from disk only; a window's saved draft stays its view state

Clearing a saved draft wrote workspace layout from main, which no layout command carries.
Main now never shows or edits a draft; the desktop's restore check reports a disk change.

* Phone Markdown: one path through main and the disk, window or not

A paired server's workspace is read and saved on that server with files.read /
files.writeIfUnchanged, so it answers from its own disk and keeps the precondition.
The window relay (ui:mobileMarkdownRequest and the renderer bridge) is removed.

* e2e: a phone saves a Markdown tab the desktop holds unsaved edits in

The phone reads the disk with the tab marked dirty; its save lands on disk, and the
desktop keeps its draft and shows the changed-on-disk banner.

* Group the Markdown disk host's imports

* Drop an unneeded store cast from the dirty-readers test

* Phone Markdown: refuse a save on a server too old to check the disk; cover the untitled tab

A server before #30605 has no files.writeIfUnchanged, so the save is refused with the
existing update-required message rather than written unchecked.

* Phone Markdown: refuse a file an SSH host holds outside the workspace; pin the untitled answer

* Phone Markdown: untitled tabs stay read-only; older servers save like the desktop editor; a closed-source preview still reads

- The desktop lists an untitled document's tab with isUntitled (optional, additive); main answers
  it read-only with unsupported_untitled and refuses its save before touching the disk.
- A server without the files.write.disk-precondition capability gets the desktop editor's guarded
  save: compare from here, then a plain files.write, or a conflict. Every call of a save is pinned
  to the pairing it probed.
- A preview whose source tab was closed has no saved record; it reads its own file, read-only.

* e2e: read the untitled tab's answer without a cast

* Phone Markdown: pin a save's pairing before its first read

A save captures the server's pairing before it reads, and every call of the save, the read
included, is pinned to it, so a re-pair between the read and the write is refused.

* Test: with no window, a phone saves an existing untitled.md and never creates a deleted one

---------

Co-authored-by: E2E Test <[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