@@ -22,7 +22,12 @@ import type { FileObservation } from "../../core/task/observationRegistry"
2222import { versionTokenOfStat } from "../../utils/versionToken"
2323import { withFileLock } from "../../utils/fileLock"
2424import { resolveLockKey } from "../../services/file-safety/safeWriteText"
25- import { guardedWrite , GuardRejectedError , type GuardedWriteKind } from "../../core/tools/guardedWrite"
25+ import {
26+ guardedWrite ,
27+ GuardRejectedError ,
28+ replaceIfVersion ,
29+ type GuardedWriteKind ,
30+ } from "../../core/tools/guardedWrite"
2631
2732import { DecorationController } from "./DecorationController"
2833
@@ -1222,6 +1227,9 @@ export class DiffViewProvider {
12221227 const fileExists = this . editType === "modify"
12231228 const updatedDocument = this . activeDiffEditor . document
12241229 const absolutePath = path . resolve ( this . cwd , this . relPath )
1230+ // Captured while narrowed: the CAS below runs after awaits inside the
1231+ // teardown closure.
1232+ const displayRelPath = this . relPath
12251233
12261234 // Stop tracking touches and cancel any pending scroll-to-diff before any
12271235 // programmatic editor activation below.
@@ -1237,26 +1245,27 @@ export class DiffViewProvider {
12371245 // before the rollback acts, and an unguarded restore or unlink would
12381246 // clobber or delete bytes this session never wrote.
12391247 await withFileLock ( await resolveLockKey ( absolutePath ) , async ( ) => {
1240- // Decide against the disk state under the lock: the rollback may overwrite
1241- // or remove the file only while it still carries the token this session
1242- // last wrote (the post-publish observation for a modify, the placeholder
1243- // token for a create). A different token means a peer published in the
1244- // settled window: preserve the peer's bytes, close this session's views,
1245- // and report the conflict explicitly.
1246- // The same token source the publish and adoption paths use, so the
1247- // comparison is apples to apples with what this session recorded.
1248- const diskStat = await fs . stat ( absolutePath , { bigint : true } ) . catch ( ( ) => undefined )
1249- const diskToken = diskStat === undefined ? undefined : versionTokenOfStat ( diskStat )
1250- const oursToken = this . lastWrittenToken ?? ( fileExists ? undefined : this . placeholderVersion )
1251- if ( diskToken !== undefined && oursToken !== undefined && diskToken !== oursToken ) {
1252- await this . closeAllDiffViews ( )
1253- throw new RollbackConflictError ( absolutePath , oursToken , diskToken )
1254- }
12551248 if ( ! fileExists ) {
1256- if ( updatedDocument . isDirty ) {
1257- await updatedDocument . save ( )
1249+ // Decide against the disk state under the lock: the rollback may
1250+ // remove the file only while it still carries the token this session
1251+ // left there (the post-publish observation or the placeholder token).
1252+ // A different token means a peer published in the settled window:
1253+ // preserve the peer's bytes, close this session's views, and report
1254+ // the conflict explicitly. The same token source the publish and
1255+ // adoption paths use, so the comparison is apples to apples with
1256+ // what this session recorded.
1257+ const diskStat = await fs . stat ( absolutePath , { bigint : true } ) . catch ( ( ) => undefined )
1258+ const diskToken = diskStat === undefined ? undefined : versionTokenOfStat ( diskStat )
1259+ const oursToken = this . lastWrittenToken ?? this . placeholderVersion
1260+ if ( diskToken !== undefined && oursToken !== undefined && diskToken !== oursToken ) {
1261+ await this . closeAllDiffViews ( )
1262+ throw new RollbackConflictError ( absolutePath , oursToken , diskToken )
12581263 }
1259-
1264+ // No save before the delete: saving the diff buffer would publish the
1265+ // cancelled edit's content to disk immediately before deleting it -
1266+ // a write the rollback never intended, unbound to the placeholder
1267+ // check above, and a visible flash of cancelled content for anyone
1268+ // reading the path in that window.
12601269 await this . closeAllDiffViews ( )
12611270 // The file was newly created for this edit; close its transiently
12621271 // opened tab before deleting it from disk.
@@ -1267,40 +1276,91 @@ export class DiffViewProvider {
12671276 for ( let i = this . createdDirs . length - 1 ; i >= 0 ; i -- ) {
12681277 await fs . rmdir ( this . createdDirs [ i ] )
12691278 }
1270- } else {
1271- // Revert document.
1272- const edit = new vscode . WorkspaceEdit ( )
1279+ }
1280+ // The modify rollback publishes through replaceIfVersion below: it
1281+ // takes this same lock itself, and withFileLock is not reentrant.
1282+ } )
12731283
1274- const fullRange = new vscode . Range (
1275- updatedDocument . positionAt ( 0 ) ,
1276- updatedDocument . positionAt ( updatedDocument . getText ( ) . length ) ,
1277- )
1284+ if ( fileExists ) {
1285+ // Revert the existing file with an atomic guarded compare-and-swap
1286+ // publish: the original bytes reach the disk only while the path still
1287+ // carries the token this session last wrote, with the version check and
1288+ // the publish inside one acquisition of the shared advisory lock
1289+ // (replaceIfVersion). The old check-then-save applied the buffer through
1290+ // VS Code's save path without binding the publish to the checked
1291+ // version, so a peer publish landing after the check was silently
1292+ // overwritten. On a CAS rejection the peer's bytes stay on disk and the
1293+ // rollback reports the conflict.
1294+ const originalBytes = this . stripAllBOMs ( this . originalContent ?? "" )
1295+ const expectedToken = this . lastWrittenToken
1296+ // The CAS needs both sides of the comparison: the version this session
1297+ // left and the version the disk reports. The probe below only decides
1298+ // eligibility - replaceIfVersion re-reads the version under the lock,
1299+ // and that read is the authoritative check the publish is bound to.
1300+ const diskStat = await fs . stat ( absolutePath , { bigint : true } ) . catch ( ( ) => undefined )
1301+ let casPublished = false
1302+ if ( expectedToken !== undefined && diskStat !== undefined ) {
1303+ try {
1304+ await replaceIfVersion ( absolutePath , expectedToken , originalBytes , displayRelPath )
1305+ casPublished = true
1306+ } catch ( error : unknown ) {
1307+ if ( error instanceof GuardRejectedError ) {
1308+ // The CAS rejected: the peer's bytes are preserved. Report the
1309+ // conflict with the disk token the rejection is about.
1310+ const conflictStat = await fs
1311+ . stat ( absolutePath , { bigint : true } )
1312+ . catch ( ( ) => undefined )
1313+ const diskToken =
1314+ conflictStat === undefined ? "<absent>" : versionTokenOfStat ( conflictStat )
1315+ await this . closeAllDiffViews ( )
1316+ throw new RollbackConflictError ( absolutePath , expectedToken , diskToken )
1317+ }
1318+ throw error
1319+ }
1320+ }
12781321
1279- edit . replace ( updatedDocument . uri , fullRange , this . stripAllBOMs ( this . originalContent ?? "" ) )
1322+ // Restore the buffer to the original content.
1323+ const edit = new vscode . WorkspaceEdit ( )
12801324
1281- // Apply the edit and save, since contents shouldn't have changed
1282- // this won't show in local history unless of course the user made
1283- // changes and saved during the edit.
1284- await vscode . workspace . applyEdit ( edit )
1285- await updatedDocument . save ( )
1325+ const fullRange = new vscode . Range (
1326+ updatedDocument . positionAt ( 0 ) ,
1327+ updatedDocument . positionAt ( updatedDocument . getText ( ) . length ) ,
1328+ )
12861329
1287- await this . closeAllDiffViews ( )
1330+ edit . replace ( updatedDocument . uri , fullRange , originalBytes )
1331+ await vscode . workspace . applyEdit ( edit )
12881332
1289- // Read auto-close preferences from state; fall back to defaults that
1290- // preserve the existing behavior when unset.
1291- const revertTask = this . taskRef . deref ( )
1292- const revertState = await revertTask ?. providerRef . deref ( ) ?. getState ( )
1293-
1294- await this . keepOrCloseEditedFile (
1295- absolutePath ,
1296- false ,
1297- revertState ?. autoCloseZooOpenedFiles ?? DEFAULT_AUTO_CLOSE_ZOO_OPENED_FILES ,
1298- revertState ?. autoCloseZooOpenedFilesAfterUserEdited ??
1299- DEFAULT_AUTO_CLOSE_ZOO_OPENED_FILES_AFTER_USER_EDITED ,
1300- revertState ?. autoCloseZooOpenedNewFiles ?? DEFAULT_AUTO_CLOSE_ZOO_OPENED_NEW_FILES ,
1301- )
1333+ if ( casPublished ) {
1334+ // The CAS published the original bytes outside VS Code's save path:
1335+ // reconcile the buffer with the disk - reverting reloads the published
1336+ // bytes and clears the dirty flag - instead of saving the buffer back
1337+ // over the disk through the unguarded path this rollback replaced.
1338+ await this . revertDocument ( updatedDocument )
1339+ } else {
1340+ // No CAS: either this session never published to the path (no expected
1341+ // version exists) or the disk reported no version to compare against
1342+ // (absent or unreadable). Saving the restored buffer rewrites the
1343+ // bytes this session last knew, as it did before the guarded rollback
1344+ // existed; there was no version to bind the publish to.
1345+ await updatedDocument . save ( )
13021346 }
1303- } )
1347+
1348+ await this . closeAllDiffViews ( )
1349+
1350+ // Read auto-close preferences from state; fall back to defaults that
1351+ // preserve the existing behavior when unset.
1352+ const revertTask = this . taskRef . deref ( )
1353+ const revertState = await revertTask ?. providerRef . deref ( ) ?. getState ( )
1354+
1355+ await this . keepOrCloseEditedFile (
1356+ absolutePath ,
1357+ false ,
1358+ revertState ?. autoCloseZooOpenedFiles ?? DEFAULT_AUTO_CLOSE_ZOO_OPENED_FILES ,
1359+ revertState ?. autoCloseZooOpenedFilesAfterUserEdited ??
1360+ DEFAULT_AUTO_CLOSE_ZOO_OPENED_FILES_AFTER_USER_EDITED ,
1361+ revertState ?. autoCloseZooOpenedNewFiles ?? DEFAULT_AUTO_CLOSE_ZOO_OPENED_NEW_FILES ,
1362+ )
1363+ }
13041364 } )
13051365 } catch ( error ) {
13061366 if ( error instanceof RollbackConflictError ) {
0 commit comments