Repository navigation
feat(files): guarded file writes that refuse to overwrite a changed file - #30605
Conversation
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.
📝 Walkthrough
Priority: ⬇️ Low Merge Risk: 🔵 Low · up to
|
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
- Configuration used: Repository UI
- Review profile: CHILL
- Plan: Advanced
- Run ID:
4e9bd761-a022-4837-9a8d-764bd1e58b01
⛔ Files ignored due to path filters: 1
src/shared/rpc-contract/rpc-params-catalog.generated.tsis excluded by!**/*.generated.*
📒 Files selected for processing: 40
src/main/destination-serialized-local-rename.tssrc/main/ipc/filesystem.test.tssrc/main/ipc/filesystem/filesystem-write-handlers.tssrc/main/ipc/filesystem/local-disk-write-precondition.test.tssrc/main/ipc/filesystem/local-disk-write-precondition.tssrc/main/ipc/filesystem/local-regular-file-read.tssrc/main/ipc/runtime-environments/runtime-environment-support-routing.test.tssrc/main/ipc/runtime-environments/runtime-environment-support-routing.tssrc/main/ipc/runtime-environments/runtime-environment-transport-routing.tssrc/main/providers/local-filesystem-provider.tssrc/main/runtime/files/file-mutations.tssrc/main/runtime/rpc/methods/files-mutation-methods.tssrc/main/runtime/rpc/methods/files-write-disk-precondition.test.tssrc/preload/api/filesystem-api.tssrc/preload/api/fs-bridge.tssrc/renderer/src/components/editor/diff-content-signature.tssrc/renderer/src/components/right-sidebar/file-explorer-delete-undo-precondition.test.tsxsrc/renderer/src/components/right-sidebar/useFileDeletion.tssrc/renderer/src/components/settings/McpConfigSection.host-owner.test.tsxsrc/renderer/src/components/settings/McpConfigSection.tsxsrc/renderer/src/runtime/runtime-file-mutation-client.tssrc/renderer/src/runtime/runtime-file-mutation-rpc.tssrc/renderer/src/runtime/runtime-file-write-disk-precondition.test.tssrc/renderer/src/runtime/runtime-file-write-disk-precondition.tssrc/renderer/src/web/preload-api/web-filesystem-api.tssrc/renderer/src/web/preload-api/web-runtime-calls-connection-pin.test.tssrc/renderer/src/web/preload-api/web-runtime-calls.tssrc/renderer/src/web/preload-api/web-runtime-environments-api.tssrc/renderer/src/web/web-file-mutation-methods.test.tssrc/renderer/src/web/web-file-mutation-methods.tssrc/renderer/src/web/web-file-write-disk-precondition.test.tssrc/renderer/src/web/web-runtime-client.tssrc/renderer/src/web/web-runtime-connection-transport.tssrc/renderer/src/web/web-runtime-request-registry-connection-pin.test.tssrc/renderer/src/web/web-runtime-request-registry.tssrc/shared/disk-baseline-signature.tssrc/shared/file-write-disk-precondition.test.tssrc/shared/file-write-disk-precondition.tssrc/shared/protocol-version.tssrc/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.
| 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 |
There was a problem hiding this comment.
🩺 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) =>
(…do; narrow not-found and pinning
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.
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to GitHub limitations.
🟡 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 winKeep 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 returnsFILE_WRITE_OKwithout 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
📒 Files selected for processing: 6
src/renderer/src/components/right-sidebar/file-explorer-delete-undo-precondition.test.tsxsrc/renderer/src/components/right-sidebar/fileExplorerUndoRedo.tssrc/renderer/src/runtime/runtime-file-mutation-rpc.tssrc/renderer/src/runtime/runtime-file-write-disk-precondition.test.tssrc/renderer/src/runtime/runtime-file-write-disk-precondition.tssrc/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.
…st-reply recovery to the save's pairing
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.
…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.
…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]>
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:
fs:writeFile), and on runtime hosts for remote and SSH workspaces.files.writeIfUnchanged, advertised by the capabilityfiles.write.disk-precondition.v1. Plainfiles.writeis unchanged..mcp.jsonnow refuses if a different file appeared after the listing.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:
Remote and paired web client:
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
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
N/Awith reasonpnpm lint,pnpm typecheck,pnpm test, andpnpm buildpass (or CI will cover; local preferred)