Skip to content
26 changes: 21 additions & 5 deletions packages/opencode/src/storage/storage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -170,18 +170,26 @@ 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<T>
const result = await Bun.file(target).json()
return result as Promise<T>
Comment thread
Hona marked this conversation as resolved.
Outdated
})
}

export async function update<T>(key: string[], fn: (draft: T) => void) {
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)

Copilot AI Nov 12, 2025

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The file handle is opened without checking if the directory exists first. In the update function, unlike the write function (line 203), there's no fs.mkdir(path.dirname(target), { recursive: true }) call before opening the file. This could fail if the parent directories don't exist yet.

Suggested change
const jsonContent = JSON.stringify(content, null, 2)
const jsonContent = JSON.stringify(content, null, 2)
await fs.mkdir(path.dirname(target), { recursive: true })

Copilot uses AI. Check for mistakes.
const handle = await fs.open(target, "w")
try {
await handle.writeFile(jsonContent, "utf-8")
await handle.sync()
} finally {
await handle.close()
}
return content as T
})
}
Expand All @@ -190,8 +198,16 @@ 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 handle = await fs.open(target, "w")
try {
await handle.writeFile(jsonContent, "utf-8")
await handle.sync()
} finally {
await handle.close()
}
})
}

Expand Down
Loading