GeezerVison is showing github.com — fix(core): keep opencode tmp files on disk and sweep them after 7 days by opencode-agent[bot] · Pull Request #64031 · anomalyco/opencode
fix(core): keep opencode tmp files on disk and sweep them after 7 days
#64031
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement . We’ll occasionally send you account related emails.
Already on GitHub?
Sign in
to your account
Uh oh!
There was an error while loading. Please reload this page.
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter
Filter by extension
.ts
(8)
All 1 file type selected
Viewed files
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Diff view
Hide whitespace
Diff view
Hide whitespace
There are no files selected for viewing
Original file line number
Diff line number
Diff line change
Expand Up
@@ -15,7 +15,8 @@ export const cleanup = Effect.fn("FileRetention.cleanup")(function* (
Effect.gen(function* () {
const info = yield* fs.stat(file).pipe(Effect.orElseSucceed(() => undefined))
const mtime = info && Option.getOrUndefined(info.mtime)
if (!mtime || mtime.getTime() >= cutoff) return
// Runtimes without real timestamps (workerd) report the epoch; keep those files.
if (!mtime || mtime.getTime() <= 0 || mtime.getTime() >= cutoff) return
yield* fs.remove(file).pipe(Effect.ignore)
}),
{ concurrency: 8, discard: true },
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -5,6 +5,7 @@ import { Context, DateTime, Effect, Layer, Schema } from "effect"
import { Global } from "@opencode/util/global"
import { Location } from "../location.js"
import { Instructions } from "./index.js"
import { TmpRetention } from "../tmp-retention.js"
export interface Interface {
readonly load: () => Effect.Effect<Instructions.List>
Expand Down
Expand Up
@@ -40,7 +41,7 @@ const layer = Layer.effect(
` Workspace root folder: ${location.project.directory}`,
` Is directory a git repo: ${location.vcs?.type === "git" ? "yes" : "no"}`,
` Platform: ${process.platform}`,
` Prefer ${global.tmp} over generic system temporary directories such as /tmp; it is pre-created and approved for external access.`,
` Prefer ${global.tmp} over generic system temporary directories such as /tmp; it is pre-created and approved for external access. Files there untouched for 7 days are deleted automatically. `,
"</env>",
].join("\n"),
),
Expand All
@@ -57,4 +58,4 @@ const layer = Layer.effect(
}),
)
export const node = makeLocationNode({ service: Service, layer, deps: [Global.node, Location.node] })
export const node = makeLocationNode({ service: Service, layer, deps: [Global.node, Location.node, TmpRetention.node ] })
Original file line number
Diff line number
Diff line change
@@ -0,0 +1,68 @@
export * as TmpRetention from "./tmp-retention.js"
import path from "path"
import { Duration, Effect, Layer, Option, Schedule } from "effect"
import { makeGlobalNode } from "@opencode/util/effect/app-node"
import { FSUtil } from "@opencode/util/fs-util"
import { Global } from "@opencode/util/global"
import { FileRetention } from "./file-retention.js"
export const RETENTION = Duration.days(7)
/** Deletes files under `directory` untouched for `RETENTION`, then the directories that leaves empty. */
export const cleanup = Effect.fn("TmpRetention.cleanup")(function* (fs: FSUtil.Interface, directory: string) {
const cutoff = Date.now() - Duration.toMillis(RETENTION)
const files: string[] = []
// Directories with no entry added or removed within the retention, judged before this sweep
// removes anything (which would touch them). A newer one may be about to receive a file.
const stale: string[] = []
const walk = (current: string): Effect.Effect<void> =>
fs.readDirectoryEntries(current).pipe(
Effect.orElseSucceed(() => []),
Effect.flatMap((entries) =>
Effect.forEach(
entries,
(entry) => {
const target = path.join(current, entry.name)
if (entry.type !== "Directory") return Effect.sync(() => void files.push(target))
Comment thread
Outdated
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more .
On Windows, global.tmp also holds RetainedImage links: opencode-upgrade-<pid>-*.exe (the package-removal step of uninstall, via updater.removal → retaining(…, global.tmp)) and the opencode-service-* links that uninstall moves here. These are hard links, so their mtime is the binary's mtime, which is usually older than 7 days. Any OpenCode process that cleans up during an uninstall will delete them while their process is still running. That is exactly what they exist to prevent: Bun spins forever when a package replacement meets the last link of a running image. Could the cleanup skip the opencode-(service|upgrade)-<pid>-*.exe pattern (RetainedImage already sweeps dead ones), or could those links move out of tmp?
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
return fs.stat(target).pipe(
Effect.map((info) => Option.getOrUndefined(info.mtime)),
Effect.orElseSucceed(() => undefined),
Effect.flatMap((mtime) => {
if (mtime && mtime.getTime() > 0 && mtime.getTime() < cutoff) stale.push(target)
return walk(target)
}),
)
},
{ discard: true },
),
),
)
yield* walk(directory)
yield* FileRetention.cleanup(fs, files, RETENTION)
// Children are listed after their parents; remove deepest first so a parent can empty out.
yield* Effect.forEach(
stale.reverse(),
(target) =>
Effect.gen(function* () {
const entries = yield* fs.readDirectory(target).pipe(Effect.orElseSucceed(() => [""]))
// Node's rm needs `recursive` for any directory; it is empty here.
if (entries.length === 0) yield* fs.remove(target, { recursive: true }).pipe(Effect.ignore)
}),
{ discard: true },
)
})
const layer = Layer.effectDiscard(
Effect.gen(function* () {
const fs = yield* FSUtil.Service
const global = yield* Global.Service
yield* cleanup(fs, global.tmp).pipe(Effect.repeat(Schedule.spaced(Duration.hours(1))), Effect.forkScoped)
}),
)
export const node = makeGlobalNode({
name: "tmp-retention",
layer,
deps: [FSUtil.node, Global.node],
})
Original file line number
Diff line number
Diff line change
@@ -1,5 +1,7 @@
import { describe, expect } from "bun:test"
import fs from "fs"
import os from "os"
import path from "path"
import { Effect, Layer } from "effect"
import { TestClock } from "effect/testing"
import { AppNodeBuilder } from "@opencode/core/effect/app-node-builder"
Expand All
@@ -15,7 +17,8 @@ import { readInitial, readUpdate } from "../lib/instructions"
const directory = AbsolutePath.make(FSUtil.resolve("/repo/packages/core"))
const projectDirectory = AbsolutePath.make(FSUtil.resolve("/repo"))
const timestamp = Date.parse("2026-06-03T12:00:00.000Z")
const temporary = os.tmpdir()
// Its own directory: building the node starts the tmp retention sweep there.
const temporary = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "opencode-builtins-")))
const localDate = (time: number) => new Date(time).toDateString()
const locationLayer = Layer.succeed(
Location.Service,
Expand Down
Expand Up
@@ -50,7 +53,7 @@ describe("InstructionBuiltIns", () => {
` Workspace root folder: ${projectDirectory}`,
" Is directory a git repo: yes",
` Platform: ${process.platform}`,
` Prefer ${temporary} over generic system temporary directories such as /tmp; it is pre-created and approved for external access.`,
` Prefer ${temporary} over generic system temporary directories such as /tmp; it is pre-created and approved for external access. Files there untouched for 7 days are deleted automatically. `,
"</env>",
].join("\n"),
)
Expand Down
Original file line number
Diff line number
Diff line change
@@ -0,0 +1,57 @@
import { describe, expect } from "bun:test"
import path from "path"
import { Effect } from "effect"
import { AppNodeBuilder } from "@opencode/core/effect/app-node-builder"
import { FSUtil } from "@opencode/util/fs-util"
import { TmpRetention } from "@opencode/core/tmp-retention"
import { withTempDir } from "./fixture/tmpdir"
import { it } from "./lib/effect"
const fsLayer = AppNodeBuilder.build(FSUtil.node, [])
const old = new Date(Date.now() - 8 * 24 * 60 * 60 * 1_000)
describe("TmpRetention", () => {
it.live("deletes stale files at any depth and the directories they leave empty", () =>
withTempDir((tmp) =>
Effect.gen(function* () {
const fs = yield* FSUtil.Service
const upload = path.join(tmp.path, "uploads", "a", "photo.png")
const image = path.join(tmp.path, "images", "ses_1", "image_1.png")
const fresh = path.join(tmp.path, "images", "ses_1", "image_2.png")
const scratch = path.join(tmp.path, "notes.txt")
for (const file of [upload, image, fresh, scratch]) yield* fs.writeWithDirs(file, "x")
for (const file of [upload, image, scratch]) yield* fs.utimes(file, old, old)
for (const directory of ["uploads", "uploads/a", "images", "images/ses_1"])
yield* fs.utimes(path.join(tmp.path, directory), old, old)
yield* TmpRetention.cleanup(fs, tmp.path)
expect(yield* fs.exists(upload)).toBe(false)
expect(yield* fs.exists(image)).toBe(false)
expect(yield* fs.exists(scratch)).toBe(false)
expect(yield* fs.exists(fresh)).toBe(true)
expect(yield* fs.exists(path.join(tmp.path, "uploads"))).toBe(false)
expect(yield* fs.exists(path.join(tmp.path, "images", "ses_1"))).toBe(true)
expect(yield* fs.exists(tmp.path)).toBe(true)
}),
).pipe(Effect.provide(fsLayer)),
)
it.live("keeps a recently created empty directory and files without a real timestamp", () =>
withTempDir((tmp) =>
Effect.gen(function* () {
const fs = yield* FSUtil.Service
const directory = path.join(tmp.path, "uploads", "b")
const epoch = path.join(tmp.path, "epoch.txt")
yield* fs.ensureDir(directory)
yield* fs.writeFileString(epoch, "x")
yield* fs.utimes(epoch, new Date(0), new Date(0))
yield* TmpRetention.cleanup(fs, tmp.path)
expect(yield* fs.exists(directory)).toBe(true)
expect(yield* fs.exists(epoch)).toBe(true)
}),
).pipe(Effect.provide(fsLayer)),
)
})
Original file line number
Diff line number
Diff line change
Expand Up
@@ -14,6 +14,7 @@ export function roots(app: string) {
cache: path.join(cache!, app),
config: path.join(config!, app),
state: path.join(state!, app),
tmp: path.join(os.tmpdir(), app),
// On disk rather than os.tmpdir(), which is often RAM-backed (tmpfs).
tmp: path.join(data!, app, "tmp"),
}
}
Original file line number
Diff line number
Diff line change
Expand Up
@@ -20,7 +20,7 @@ describe("global roots", () => {
cache: path.join(env.XDG_CACHE_HOME, "opencode"),
config: path.join(env.XDG_CONFIG_HOME, "opencode"),
state: path.join(env.XDG_STATE_HOME, "opencode"),
tmp: path.join(os.tmpdir() , "opencode"),
tmp: path.join(env.XDG_DATA_HOME , "opencode", "tmp "),
})
})
Expand All
@@ -40,7 +40,7 @@ describe("global roots", () => {
cache: path.join(home, ".cache", "opencode"),
config: path.join(home, ".config", "opencode"),
state: path.join(home, ".local", "state", "opencode"),
tmp: path.join(os.tmpdir() , "opencode"),
tmp: path.join(home, ".local" , "share", " opencode", "tmp "),
})
})
})
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -9,7 +9,7 @@ import { Global } from "../src/global.js"
describe("global", () => {
test("importing the module does not create directories", () => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), "opencode-global-import-"))
const directories = ["data", "cache", "config", "state", "tmp" ].map((directory) => path.join(root, directory))
const directories = ["data", "cache", "config", "state"].map((directory) => path.join(root, directory))
const module = pathToFileURL(path.join(import.meta.dir, "../src/global.ts")).href
const result = Bun.spawnSync({
cmd: [process.execPath, "-e", `const { Global } = await import(${JSON.stringify(module)}); void Global.Path.tmp`],
Expand All
@@ -19,9 +19,6 @@ describe("global", () => {
XDG_CACHE_HOME: directories[1],
XDG_CONFIG_HOME: directories[2],
XDG_STATE_HOME: directories[3],
// os.tmpdir() reads TMPDIR on POSIX and TEMP on Windows.
TMPDIR: directories[4],
TEMP: directories[4],
},
stderr: "pipe",
})
Expand Down
Expand Up
@@ -52,7 +49,7 @@ describe("global", () => {
test("building a layer with default tmp creates and canonicalizes it", () => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), "opencode-global-layer-"))
const directories = ["data", "cache", "config", "state", "tmp" ].map((directory) => path.join(root, directory))
const directories = ["data", "cache", "config", "state"].map((directory) => path.join(root, directory))
const module = pathToFileURL(path.join(import.meta.dir, "../src/global.ts")).href
const result = Bun.spawnSync({
cmd: [
Expand All
@@ -72,9 +69,6 @@ describe("global", () => {
XDG_CACHE_HOME: directories[1],
XDG_CONFIG_HOME: directories[2],
XDG_STATE_HOME: directories[3],
// os.tmpdir() reads TMPDIR on POSIX and TEMP on Windows.
TMPDIR: directories[4],
TEMP: directories[4],
},
stdout: "pipe",
stderr: "pipe",
Expand All
@@ -83,15 +77,15 @@ describe("global", () => {
expect(result.exitCode, result.stderr.toString()).toBe(0)
// The layer canonicalizes through the native realpath, which on Windows also expands 8.3 short
// names such as RUNNER~1 that the JavaScript realpathSync leaves in place.
expect(result.stdout.toString()).toBe(fs.realpathSync.native(path.join(directories[4 ], "opencode")))
expect(result.stdout.toString()).toBe(fs.realpathSync.native(path.join(directories[0 ], "opencode", "tmp ")))
const created = [
path.join(directories[0], "opencode"),
path.join(directories[1], "opencode", "bin"),
path.join(directories[2], "opencode"),
path.join(directories[3], "opencode"),
path.join(directories[0], "opencode", "log"),
path.join(directories[0], "opencode", "repos"),
path.join(directories[4 ], "opencode"),
path.join(directories[0 ], "opencode", "tmp "),
]
created.forEach((directory) => expect(fs.statSync(directory).isDirectory()).toBe(true))
fs.rmSync(root, { recursive: true, force: true })
Expand Down
Loading
Oops, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.