diff --git a/packages/opencode/src/storage/storage.ts b/packages/opencode/src/storage/storage.ts index cff7211ccb0..30d4e81a2bd 100644 --- a/packages/opencode/src/storage/storage.ts +++ b/packages/opencode/src/storage/storage.ts @@ -170,7 +170,7 @@ export namespace Storage { const target = path.join(dir, ...key) + ".json" return withErrorHandling(async () => { using _ = await Lock.read(target) - return Bun.file(target).json() as Promise + return (await Bun.file(target).json()) as T }) } @@ -178,10 +178,13 @@ export namespace Storage { const dir = await state().then((x) => x.dir) const target = path.join(dir, ...key) + ".json" return withErrorHandling(async () => { - using _ = await Lock.write("storage") + using _ = await Lock.write(target) const content = await Bun.file(target).json() fn(content) - await Bun.write(target, JSON.stringify(content, null, 2)) + const jsonContent = JSON.stringify(content, null, 2) + const tempFile = target + ".tmp" + await Bun.write(tempFile, jsonContent) + await fs.rename(tempFile, target) return content as T }) } @@ -190,8 +193,12 @@ export namespace Storage { const dir = await state().then((x) => x.dir) const target = path.join(dir, ...key) + ".json" return withErrorHandling(async () => { - using _ = await Lock.write("storage") - await Bun.write(target, JSON.stringify(content, null, 2)) + using _ = await Lock.write(target) + const jsonContent = JSON.stringify(content, null, 2) + await fs.mkdir(path.dirname(target), { recursive: true }) + const tempFile = target + ".tmp" + await Bun.write(tempFile, jsonContent) + await fs.rename(tempFile, target) }) }