Skip to content

fix(files): concurrent saves of one terminal file no longer overwrite each other - #35418

Merged
AmoabaKelvin merged 1 commit into
mainfrom
fix/terminal-artifact-write-serialize
Oct 29, 2026
Merged

AmoabaKelvin merged 1 commit into
mainfrom
fix/terminal-artifact-write-serialize

Conversation

@AmoabaKelvin

@AmoabaKelvin AmoabaKelvin commented Oct 28, 2026 •

Copy link
Copy Markdown
Collaborator
Files Added Deleted Net
Test 1 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​39 0 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​39
Prod 2 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​75 $\color{#cf222e}{\Huge{\mathbf{−}}}$​52 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​23

ELI5

Two phones (or a phone and the desktop editor) save the same file at almost the same moment. Today both saves are accepted and the later one silently replaces the earlier one. Now these saves take turns on the desktop, so the later one sees the file has changed and is refused with the usual "file changed" error.

What Changed

  • writeTerminalArtifactFile already refuses a save when the file no longer matches what its grant last saw. Each client holds its own grant, so two concurrent saves could both pass that check in the few milliseconds before either renamed its temp file. Orca's editor saves (writeLocalTextFileWithDiskPrecondition) have the same check-then-write shape.
  • The editor's existing lock (canonical parent + folded file name, then inode) is now exported as runSerializedLocalFileWrite, and the artifact check-to-rename runs inside it. Phone-vs-phone and phone-vs-editor saves of one file take turns; the loser gets terminal_file_grant_stale (phone: "File changed on desktop. Reload preview before saving") or the editor's existing disk-conflict prompt.
  • The lock key now applies windowsFsPath itself, so every caller locks a WSL UNC drive-mount file under the same spelling. The editor already passed that spelling, so its behaviour is unchanged.

Why

Found while carrying #31696 (mobile file preview edits), whose risk review said "checking the previous file contents before writing is still not atomic against another client writing at the same time". The host owns both the check and the rename, so the fix belongs there. A protocol-level compare-and-swap wouldn't help: the grant digest already is one, and the gap was in-process writers interleaving. Nothing changes on the wire, so old phones benefit as is and old hosts keep today's behaviour.

Not covered: writers in other processes (external editors, tools). No in-process lock can cover them, and rename has no compare step. The existing digest check still catches any of those writes that land before the check.

Linked Issue

No issue. Maintainer-found while carrying #31696.

Visual Proof

N/A: host-side ordering change with no new UI. The losing save shows the existing "file changed" error.

Testing

  • I manually tested these changes locally
  • Automated tests added/updated, or explained why not below

New test in orca-runtime-files-terminal-artifact-io.test.ts: two clients resolve grants for one file and save different content concurrently through a committing rename. It fails on main (both saves succeed and the later one wins) and passes here (exactly one lands, the other is refused as stale). The test doesn't assume which writer takes the lock first. Focused suites pass: terminal artifact I/O and swap detection, and local-disk-write-precondition.

AI Disclosure

Review

Codex and Claude reviewed the first design (a separate per-file queue) for two rounds, then the shared-lock redesign, each round clean. CodeRabbit pointed out that the editor already had a lock for the same files, which led to the redesign. Checked: an artifact grant path (a realpath) produces the same lock key as an editor save of that file (symlinks, macOS case, WSL UNC); no task re-enters the lock (staged saves take their own queue, then this lock); errors propagate and never block the next writer; editor save behaviour is unchanged.

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

Security: unchanged checks (canonical path, O_NOFOLLOW, hard-link refusal); the grant is validated before the lock is taken. Cross-platform: lock keys reuse the editor's canonicalization (Windows drive spelling for WSL UNC mounts, case folding). Remote/SSH: terminal artifact grants are local-only. Mobile: old and new phones get the existing stale error on the losing save. Performance: only writes to the same file wait on each other; about three extra syscalls per artifact save.

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)

@greptile-apps

greptile-apps Bot commented Oct 28, 2026 •

Copy link
Copy Markdown

RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] The PR appears safe to merge; no blocking issues were found.

Summary

The PR puts terminal artifact saves behind the same file lock as guarded editor saves.

  • Terminal and guarded editor saves take turns before replacing the same file.

No actionable new issues were found.

Diagram

sequenceDiagram
  participant A as First client
  participant L as Shared file lock
  participant F as Local file
  participant B as Second client
  A->>L: Request save
  B->>L: Request save
  L->>F: Check first grant and write
  F-->>A: Save succeeds
  L->>F: Check second grant
  F-->>B: Reject stale grant
Loading

Reviews (6) · Last reviewed commit: "fix(files): terminal artifact saves shar..." · Reviewed by Greptile

@coderabbitai

coderabbitai Bot commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Important

Review skipped

Review was skipped as selected files did not have any reviewable changes.

Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 63e18d14-142d-4012-964c-d5b6c8ae259c
Commits

Reviewing files that changed from the base of the PR and between ddb9115 and 05c5e6b.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review
Walkthrough

A shared helper now serializes local file writes by canonical path and, when available, inode. Guarded writes use the helper. Terminal artifact writes run their existing validation and atomic replacement under serialization keyed by the grant’s absolute path. A concurrent-write test checks that one write succeeds, the other fails with terminal_file_grant_stale, and the file contains the successful write’s content.

Priority: Normal

Merge Risk: Low · previous review ddb91

The change is mergeable with a follow-up test for concurrent editor and terminal saves. The previously reported CI failure is resolved.

Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 66.67% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documenta… Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed
Check name Status Explanation
Title check Passed The title clearly and concisely describes the main change: preventing concurrent terminal-file saves from overwriting each other.
Description check Passed The description is complete and relevant. It explains the user impact, implementation, rationale, scope limits, testing, cross-platform considerations, and review notes. The missing linked issue is ad…
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 is complete and relevant. It explains the user impact, implementation, rationale, scope limits, testing, cross-platform considerations, and review notes. The missing linked issue is adequately explained as a maintainer-found fix while carrying issue #31696, and the unselected manual/full-suite checks are explicitly reflected in the testing details.

Full details: Docstring Coverage

Explanation

Docstring coverage is 66.67% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentation-only edits and deletions within surviving functions are included; unchanged diff context and fully deleted functions are excluded. Analyzed 3 functions across 3 files.

Resolution

Write docstrings for the functions missing them to satisfy the coverage threshold.

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: 1


Review info
Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 0ce2f711-3aba-4ce2-9287-b814d69d22f1
Commits

Reviewing files that changed from the base of the PR and between 4881182 and 0c2f3f8.

Files selected for processing: 5
  • src/main/per-file-task-queue.test.ts
  • src/main/per-file-task-queue.ts
  • src/main/runtime/orca-runtime-files-terminal-artifact-io.test.ts
  • src/main/runtime/terminal/artifacts/artifact-write.ts
  • src/main/sidecar-snapshot-file.ts

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

@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 (2)

Major · Use one lock domain for local writes and terminal-artifact commits. · artifact-write.ts:69-79

src/main/runtime/terminal/artifacts/artifact-write.ts:69-79
🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

Use one lock domain for local writes and terminal-artifact commits.

The registered fs:writeFile handler accepts an absolute user-file path and uses the local-disk lock. A write to the same path can occur after the terminal artifact's final digest check but before rename. The rename can then overwrite the local write without reporting a conflict.

Make the terminal artifact check-and-rename sequence acquire the same canonical path/inode lock as writeLocalTextFileWithDiskPrecondition.

Minor · Revalidate the grant after the per-file queue wait. · artifact-write.ts:38-39

src/main/runtime/terminal/artifacts/artifact-write.ts:38-39
🔒 Security & Privacy | 🟡 Minor | ⚡ Quick win

Revalidate the grant after the per-file queue wait.

A second client can validate its grant, then wait behind another write for the same file. If its grant expires or is revoked while it waits, the queued callback still uses the captured grant and can rename the temporary file when the path, stat identity, and content digest remain unchanged. This allows a disconnected client or an expired grant to complete a write.

Suggested fix
  return withPerFileTaskQueue(grant.absolutePath, async () => {
+   const { grant } = await grants.requireTerminalFileGrant(
+     worktreeSelector,
+     grantId,
+     absolutePath,
+     clientId
+   )
    let originalMode: number | null = null

Review info
Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: ff373f9e-042b-4dc2-b661-c68eb22dd858
Commits

Reviewing files that changed from the base of the PR and between 0c2f3f8 and 9f2d728.

Files selected for processing: 1
  • src/main/runtime/orca-runtime-files-terminal-artifact-io.test.ts

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

@AmoabaKelvin
AmoabaKelvin force-pushed the fix/terminal-artifact-write-serialize branch 2 times, most recently from ed8d181 to c75b09a Compare October 28, 2026 23:18
@AmoabaKelvin

Copy link
Copy Markdown
Collaborator Author

@coderabbitai Thanks on the two outside-diff items:

  • Major, one lock domain with local writes: agreed and done in c75b09a. The editor's canonical-path/inode lock from writeLocalTextFileWithDiskPrecondition is exported as runSerializedLocalFileWrite, and the artifact check-to-rename runs inside it. The separate per-file queue is gone.
  • Minor, revalidate the grant after the wait: leaving as is. The grant is checked when the request arrives, and a save sent while the client was authorized may still commit after waiting its turn. Refusing it would turn a correctly ordered save into a spurious error.

@coderabbitai

coderabbitai Bot commented Oct 28, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

@AmoabaKelvin Thanks for the update.

  • Shared lock: The reported change in c75b09a31ad addresses the lock-domain concern by using runSerializedLocalFileWrite for both write paths.
  • Grant validation: Agreed. Under the stated contract, authorization is checked when the request arrives. Waiting for the lock does not invalidate an accepted save. I withdraw the request to revalidate the grant after the wait.

✏️ Learnings added
Learnt from: AmoabaKelvin
URL: https://github.com/stablyai/orca/pull/35418

Timestamp: 2026-10-28T23:19:40.995Z
Learning: Within repository "stablyai/orca", only for files matching one of ["src/main/runtime/terminal/artifacts/artifact-write.ts"]: When reviewing queued terminal-artifact saves in src/main/runtime/terminal/artifacts/artifact-write.ts, check that the grant is validated when the request arrives. Do not require grant revalidation solely because the save waits for the file-write lock: a save accepted while the client was authorized may commit after waiting its turn.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.


If you found this review helpful, would you consider giving us a shout-out on X?

Thank you for using CodeRabbit!

You are interacting with an AI system.

@AmoabaKelvin
AmoabaKelvin force-pushed the fix/terminal-artifact-write-serialize branch from c75b09a to ddb9115 Compare October 28, 2026 23:32

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

Nitpick comments: 1
src/main/runtime/orca-runtime-files-terminal-artifact-io.test.ts: 1

145-182: Trivial · Data Integrity & Integration · Quick win

Exercise the editor and terminal entrypoints together.

The new test runs two terminal artifact writes, so it verifies terminal-to-terminal serialization only. It does not call the guarded editor write path. A regression that gives terminal writes a separate lock would still pass this test and could reintroduce an editor-versus-terminal overwrite. Add a concurrent test that calls writeLocalTextFileWithDiskPrecondition (or the local provider's guarded write) and commands.writeTerminalArtifactFile for the same file, then assert that one writer reports the expected conflict and the final content belongs to only one writer.


Review info
Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 4bee7d9d-0c41-40cb-abce-71a922ba896e
Commits

Reviewing files that changed from the base of the PR and between ed8d181 and ddb9115.

Files selected for processing: 3
  • src/main/ipc/filesystem/local-disk-write-precondition.ts
  • src/main/runtime/orca-runtime-files-terminal-artifact-io.test.ts
  • src/main/runtime/terminal/artifacts/artifact-write.ts

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

… lock

Two clients hold separate grants for one file, and the desktop editor saves through its own guarded path, so concurrent writers could all pass their content check before any of them replaced the file, and the last one silently won. Run the artifact check-to-rename under the same canonical-path/inode lock that guarded editor saves already use; the later writer now sees the earlier one's bytes and is refused.
@AmoabaKelvin
AmoabaKelvin force-pushed the fix/terminal-artifact-write-serialize branch from ddb9115 to 05c5e6b Compare October 29, 2026 00:06
@AmoabaKelvin
AmoabaKelvin merged commit ad50070 into main Oct 29, 2026
41 checks passed
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