Skip to content

Commit 56f9ba9

Browse files
BearmancerUbuntu
authored andcommitted
fix(tui): retry a state write that loses its rename to a Windows lock
Antivirus, the search indexer and a second write of the same state file hold the destination open, and NTFS fails the rename over them with EPERM or EBUSY. The lock clears on its own, so renameWithRetry waits 50, 150 and 450ms between attempts and rethrows the last error once they run out; any other code still fails at once. The destination is only replaced by a rename that succeeded, so a write that never landed leaves the old file whole. The shape follows the desktop settings write in anomalyco#51470 and PR anomalyco#54530. writeJsonAtomicDetached gives the pinned-session save a place for that final error instead of leaving it as an unhandled rejection, matching the console.error the other TUI state saves already use.
1 parent 5a47777 commit 56f9ba9

3 files changed

Lines changed: 301 additions & 5 deletions

File tree

‎packages/tui/src/context/local.tsx‎

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ import path from "path"
77
import { useTuiPaths } from "./runtime"
88
import { useArgs } from "./args"
99
import { RGBA } from "@opentui/core"
10-
import { readJson, writeJsonAtomic } from "../util/persistence"
10+
import { readJson, writeJsonAtomicDetached } from "../util/persistence"
1111
import {
1212
createModelPreferenceRepository,
1313
cycleModelVariant,
@@ -519,14 +519,27 @@ export const { use: useLocal, provider: LocalProvider } = createSimpleContext({
519519
pending: false,
520520
}
521521

522+
let saving: Promise<void> | undefined
523+
let saveQueued = false
524+
522525
function save() {
523526
if (!sessionStore.ready) {
524527
state.pending = true
525528
return
526529
}
527530
state.pending = false
528-
void writeJsonAtomic(filePath, {
529-
pinned: sessionStore.pinned,
531+
if (saving) {
532+
saveQueued = true
533+
return
534+
}
535+
saving = writeJsonAtomicDetached(filePath, { pinned: sessionStore.pinned }, (error) =>
536+
console.error("Failed to persist pinned sessions", error),
537+
).then(() => {
538+
saving = undefined
539+
if (saveQueued) {
540+
saveQueued = false
541+
save()
542+
}
530543
})
531544
}
532545

‎packages/tui/src/util/persistence.ts‎

Lines changed: 60 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,15 +19,73 @@ export async function appendText(filePath: string, content: string) {
1919
await appendFile(filePath, content)
2020
}
2121

22-
export async function writeJsonAtomic(filePath: string, value: unknown) {
22+
// Replacing a file is not safe on Windows: while any other handle holds the destination open, the
23+
// rename fails with EPERM, or EBUSY. Antivirus, the search indexer, backup agents and a second TUI
24+
// writing the same state all do that, so the failure is transient and clears on its own. The shape
25+
// follows the desktop settings write (#51470, PR #54530): the first attempt, then one retry per
26+
// delay below, then the last error is rethrown. Waiting cannot fix anything else, so any other code
27+
// fails on the first attempt. Only a rename that succeeded replaces the destination, so a write that
28+
// never landed leaves the previous file whole.
29+
const renameRetries = [50, 150, 450]
30+
31+
/** Seam for tests: node:fs cannot hold a destination open on POSIX, so the lock is injected there. */
32+
export type LockRetry = {
33+
readonly rename?: (from: string, to: string) => Promise<void>
34+
readonly wait?: (ms: number) => Promise<void>
35+
}
36+
37+
/**
38+
* Renames `temporary` over `filePath`, retrying while the failure is a transient Windows lock.
39+
* Rethrows the last error once the retries run out, leaving the staging file for the caller to
40+
* clean up.
41+
*/
42+
export async function renameWithRetry(temporary: string, filePath: string, lock: LockRetry = {}) {
43+
const move = lock.rename ?? rename
44+
const wait = lock.wait ?? waiting
45+
for (let attempt = 0; ; attempt++) {
46+
const failure = await move(temporary, filePath).then(
47+
() => undefined,
48+
(error: unknown) => error,
49+
)
50+
if (failure === undefined) return
51+
if (!isLockedError(failure) || attempt >= renameRetries.length) throw failure
52+
await wait(renameRetries[attempt])
53+
}
54+
}
55+
56+
export async function writeJsonAtomic(filePath: string, value: unknown, lock: LockRetry = {}) {
2357
await mkdir(path.dirname(filePath), { recursive: true })
2458
const temporary = `${filePath}.${process.pid}.${crypto.randomUUID()}.tmp`
2559
await writeFile(temporary, JSON.stringify(value)).catch(async (error) => {
2660
await rm(temporary, { force: true }).catch(() => undefined)
2761
throw error
2862
})
29-
await rename(temporary, filePath).catch(async (error) => {
63+
await renameWithRetry(temporary, filePath, lock).catch(async (error) => {
3064
await rm(temporary, { force: true }).catch(() => undefined)
3165
throw error
3266
})
3367
}
68+
69+
/**
70+
* Writes JSON without making the caller wait for it. State saves run from event handlers that cannot
71+
* await, so a write that is still locked after the retries is handed to `report` rather than left as
72+
* an unhandled rejection.
73+
*/
74+
export function writeJsonAtomicDetached(
75+
filePath: string,
76+
value: unknown,
77+
report: (error: unknown) => void,
78+
lock: LockRetry = {},
79+
): Promise<void> {
80+
return writeJsonAtomic(filePath, value, lock).then(() => undefined, report)
81+
}
82+
83+
function isLockedError(cause: unknown) {
84+
if (!(cause instanceof Error)) return false
85+
const code = (cause as { code?: unknown }).code
86+
return code === "EPERM" || code === "EBUSY"
87+
}
88+
89+
function waiting(ms: number) {
90+
return new Promise<void>((resolve) => setTimeout(resolve, ms))
91+
}
Lines changed: 225 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,225 @@
1+
import { describe, expect, test } from "bun:test"
2+
import { dlopen, FFIType, ptr } from "bun:ffi"
3+
import path from "path"
4+
import { mkdtemp, readdir, readFile, rename, rm, writeFile } from "fs/promises"
5+
import { tmpdir } from "os"
6+
import { readJson, renameWithRetry, writeJsonAtomic, writeJsonAtomicDetached } from "../../src/util/persistence"
7+
8+
const root = () => mkdtemp(path.join(tmpdir(), "opencode-tui-lock-"))
9+
10+
function lockError(code: string) {
11+
return Object.assign(new Error(`${code}: operation not permitted, rename`), { code })
12+
}
13+
14+
/**
15+
* A rename seam that fails with each code in `codes`, in order, and then runs `land`. Counts the
16+
* attempts and the waits the retry asked for, which is what these tests assert instead of sleeping.
17+
*/
18+
function failing(codes: string[], land?: (from: string, to: string) => Promise<void>) {
19+
const calls = { attempts: 0, waits: [] as number[] }
20+
return {
21+
calls,
22+
rename: async (from: string, to: string) => {
23+
const code = codes[calls.attempts]
24+
calls.attempts++
25+
if (code !== undefined) throw lockError(code)
26+
await land?.(from, to)
27+
},
28+
wait: async (ms: number) => {
29+
calls.waits.push(ms)
30+
},
31+
}
32+
}
33+
34+
async function failure(promise: Promise<void>) {
35+
return promise.then(
36+
() => undefined,
37+
(error: unknown) => error,
38+
)
39+
}
40+
41+
async function leftovers(directory: string) {
42+
return (await readdir(directory)).filter((entry) => entry.endsWith(".tmp"))
43+
}
44+
45+
describe("writeJsonAtomic rename retry", () => {
46+
test("lands the rename on the second attempt after waiting 50ms", async () => {
47+
const directory = await root()
48+
try {
49+
const target = path.join(directory, "session.json")
50+
const temporary = path.join(directory, "session.json.new")
51+
await writeFile(target, '{"pinned":["old"]}')
52+
await writeFile(temporary, '{"pinned":["new"]}')
53+
const lock = failing(["EPERM"], rename)
54+
55+
await renameWithRetry(temporary, target, lock)
56+
57+
expect(lock.calls.attempts).toBe(2)
58+
expect(lock.calls.waits).toEqual([50])
59+
expect(await readFile(target, "utf8")).toBe('{"pinned":["new"]}')
60+
expect(await leftovers(directory)).toEqual([])
61+
} finally {
62+
await rm(directory, { recursive: true, force: true })
63+
}
64+
})
65+
66+
test("rethrows the last lock error after the first attempt plus 50, 150 and 450ms retries", async () => {
67+
const directory = await root()
68+
try {
69+
const target = path.join(directory, "session.json")
70+
await writeFile(target, '{"pinned":["old"]}')
71+
const lock = failing(["EPERM", "EBUSY", "EPERM", "EBUSY"])
72+
73+
const caught = await failure(writeJsonAtomic(target, { pinned: ["new"] }, lock))
74+
75+
expect(caught).toBeInstanceOf(Error)
76+
expect(lock.calls.attempts).toBe(4)
77+
expect(lock.calls.waits).toEqual([50, 150, 450])
78+
// Only a rename that succeeded replaces the destination, so the old file is still whole, and
79+
// the staging file is removed rather than left for a reader to mistake for state.
80+
expect(await readJson(target)).toEqual({ pinned: ["old"] })
81+
expect(await leftovers(directory)).toEqual([])
82+
} finally {
83+
await rm(directory, { recursive: true, force: true })
84+
}
85+
})
86+
87+
const other = [
88+
{ name: "EACCES", code: "EACCES" },
89+
{ name: "ENOENT", code: "ENOENT" },
90+
{ name: "no error code", code: "" },
91+
]
92+
93+
for (const item of other) {
94+
test(`does not retry a rename that failed with ${item.name}`, async () => {
95+
const directory = await root()
96+
try {
97+
const target = path.join(directory, "session.json")
98+
await writeFile(target, '{"pinned":["old"]}')
99+
const cause = item.code ? lockError(item.code) : new Error("rename failed")
100+
const waits: number[] = []
101+
let attempts = 0
102+
103+
const caught = await failure(
104+
writeJsonAtomic(
105+
target,
106+
{ pinned: ["new"] },
107+
{
108+
rename: async () => {
109+
attempts++
110+
throw cause
111+
},
112+
wait: async (ms: number) => {
113+
waits.push(ms)
114+
},
115+
},
116+
),
117+
)
118+
119+
expect(caught).toBe(cause)
120+
expect(attempts).toBe(1)
121+
expect(waits).toEqual([])
122+
expect(await readJson(target)).toEqual({ pinned: ["old"] })
123+
expect(await leftovers(directory)).toEqual([])
124+
} finally {
125+
await rm(directory, { recursive: true, force: true })
126+
}
127+
})
128+
}
129+
130+
// The lock this retry exists for only happens on Windows: every handle node:fs opens grants
131+
// FILE_SHARE_READ|WRITE|DELETE, so two node:fs handles never contend and a rename always wins.
132+
// Asking for a narrower dwShareMode needs Win32, and bun:ffi reaches it without a native build.
133+
// A scanner such as antivirus or the search indexer holds a state file with FILE_SHARE_READ|WRITE,
134+
// which permits writing through the open handle but not replacing the file.
135+
function holdOpen(file: string) {
136+
const GENERIC_READ = 0x80000000
137+
const FILE_SHARE_READ = 0x00000001
138+
const FILE_SHARE_WRITE = 0x00000002
139+
const OPEN_EXISTING = 3
140+
const kernel32 = dlopen("kernel32.dll", {
141+
CreateFileW: {
142+
args: [FFIType.ptr, FFIType.u32, FFIType.u32, FFIType.ptr, FFIType.u32, FFIType.u32, FFIType.ptr],
143+
returns: FFIType.ptr,
144+
},
145+
CloseHandle: { args: [FFIType.ptr], returns: FFIType.i32 },
146+
})
147+
const wide = Buffer.from(`${file}\0`, "utf16le")
148+
const handle = kernel32.symbols.CreateFileW(
149+
ptr(wide),
150+
GENERIC_READ,
151+
FILE_SHARE_READ | FILE_SHARE_WRITE,
152+
null,
153+
OPEN_EXISTING,
154+
0,
155+
null,
156+
)
157+
if (handle === null) throw new Error(`could not open a handle on ${file}`)
158+
return { release: () => kernel32.symbols.CloseHandle(handle) }
159+
}
160+
161+
const windowsTest = test.skipIf(process.platform !== "win32")
162+
163+
windowsTest("retries a destination a real Windows handle holds, then reports the lock", async () => {
164+
const directory = await root()
165+
const target = path.join(directory, "session.json")
166+
await writeFile(target, '{"pinned":["old"]}')
167+
const holder = holdOpen(target)
168+
const waits: number[] = []
169+
170+
let caught: unknown
171+
try {
172+
caught = await failure(
173+
writeJsonAtomic(
174+
target,
175+
{ pinned: ["new"] },
176+
{
177+
wait: async (ms: number) => {
178+
waits.push(ms)
179+
},
180+
},
181+
),
182+
)
183+
} finally {
184+
holder.release()
185+
}
186+
187+
// The real rename is the one under test here, so the lock is whatever Windows reports for it.
188+
expect(caught).toBeInstanceOf(Error)
189+
expect((caught as Error).message).toMatch(/EPERM|EBUSY/)
190+
expect(waits).toEqual([50, 150, 450])
191+
expect(await readJson(target)).toEqual({ pinned: ["old"] })
192+
expect(await leftovers(directory)).toEqual([])
193+
})
194+
195+
test("a detached write reports its failure and the returned promise never rejects", async () => {
196+
const directory = await root()
197+
try {
198+
const target = path.join(directory, "session.json")
199+
await writeFile(target, '{"pinned":["old"]}')
200+
const cause = lockError("EPERM")
201+
const reported: unknown[] = []
202+
203+
const landed = await writeJsonAtomicDetached(
204+
target,
205+
{ pinned: ["new"] },
206+
(error) => {
207+
reported.push(error)
208+
},
209+
{
210+
rename: async () => {
211+
throw cause
212+
},
213+
wait: async () => undefined,
214+
},
215+
)
216+
217+
expect(landed).toBeUndefined()
218+
expect(reported).toEqual([cause])
219+
expect(await readJson(target)).toEqual({ pinned: ["old"] })
220+
expect(await leftovers(directory)).toEqual([])
221+
} finally {
222+
await rm(directory, { recursive: true, force: true })
223+
}
224+
})
225+
})

0 commit comments

Comments
 (0)