Avoid OpenCode config cleanup freezes on Windows (#4526)

This commit is contained in:
Jinwoo Hong
2026-06-02 21:20:13 -04:00
committed by GitHub
parent 4f18c7e79d
commit 92d8946209
4 changed files with 183 additions and 80 deletions
+62 -30
View File
@@ -198,14 +198,12 @@ describe('OpenCodeHookService buildPtyEnv / clearPty round-trip', () => {
rmSync(join(userDataDir, 'opencode-config-overlays'), { recursive: true, force: true })
})
it('writes OPENCODE_CONFIG_DIR for a daemon-shaped sessionId and installs the plugin file', () => {
it('writes a shared OPENCODE_CONFIG_DIR and installs the plugin file', () => {
const service = new OpenCodeHookService()
const env = service.buildPtyEnv(daemonSessionId)
expect(env.OPENCODE_CONFIG_DIR).toBeTruthy()
expect(env.OPENCODE_CONFIG_DIR).toBe(
join(userDataDir, 'opencode-hooks', toSafeDirName(daemonSessionId))
)
expect(env.OPENCODE_CONFIG_DIR).toBe(join(userDataDir, 'opencode-hooks', 'shared'))
const pluginPath = join(env.OPENCODE_CONFIG_DIR!, 'plugins', 'orca-opencode-status.js')
expect(existsSync(pluginPath)).toBe(true)
@@ -215,14 +213,17 @@ describe('OpenCodeHookService buildPtyEnv / clearPty round-trip', () => {
expect(pluginSource).toContain('messageID: part.messageID')
})
it('clearPty removes the same directory buildPtyEnv created', () => {
it('clearPty leaves the shared OpenCode config dir off the teardown hot path', () => {
const service = new OpenCodeHookService()
const env = service.buildPtyEnv(daemonSessionId)
const configDir = env.OPENCODE_CONFIG_DIR!
expect(existsSync(configDir)).toBe(true)
mkdirSync(join(configDir, 'node_modules', 'opencode-runtime'), { recursive: true })
writeFileSync(join(configDir, 'node_modules', 'opencode-runtime', 'index.js'), '')
service.clearPty(daemonSessionId)
expect(existsSync(configDir)).toBe(false)
expect(existsSync(configDir)).toBe(true)
expect(existsSync(join(configDir, 'node_modules', 'opencode-runtime', 'index.js'))).toBe(true)
})
it('buildPtyEnv returns {} for an unusable id and creates nothing on disk', () => {
@@ -252,25 +253,22 @@ describe('OpenCodeHookService buildPtyEnv / clearPty round-trip', () => {
const service = new OpenCodeHookService()
const env = service.buildPtyEnv(plainUuidId)
expect(env.OPENCODE_CONFIG_DIR).toBe(
join(userDataDir, 'opencode-hooks', toSafeDirName(plainUuidId))
)
expect(env.OPENCODE_CONFIG_DIR).toBe(join(userDataDir, 'opencode-hooks', 'shared'))
expect(existsSync(join(env.OPENCODE_CONFIG_DIR!, 'plugins', 'orca-opencode-status.js'))).toBe(
true
)
service.clearPty(plainUuidId)
expect(existsSync(env.OPENCODE_CONFIG_DIR!)).toBe(false)
expect(existsSync(env.OPENCODE_CONFIG_DIR!)).toBe(true)
})
})
describe('OpenCodeHookService overlay mode (user OPENCODE_CONFIG_DIR set)', () => {
// Why: locks in docs/opencode-config-dir-collision.md — when the user has
// their own OPENCODE_CONFIG_DIR (e.g. a company-wide opencode config repo),
// Orca must mirror it into a per-PTY overlay rather than `delete` its own
// injection (the prior bug) or overwrite the user's value (Superset's
// failure mode). The user's auth/models/keymap and Orca's status plugin
// both load via a single OPENCODE_CONFIG_DIR.
// Orca must mirror it into a source-scoped overlay rather than `delete` its
// own injection or overwrite the user's value. The user's auth/models/keymap
// and Orca's status plugin both load via a single OPENCODE_CONFIG_DIR.
const ptyId = 'overlay-pty-1'
let userDataDir: string
let userConfigDir: string
@@ -319,7 +317,7 @@ describe('OpenCodeHookService overlay mode (user OPENCODE_CONFIG_DIR set)', () =
const env = service.buildPtyEnv(ptyId, userConfigDir)
expect(env.OPENCODE_CONFIG_DIR).toBe(
join(userDataDir, 'opencode-config-overlays', toSafeDirName(ptyId))
join(userDataDir, 'opencode-config-overlays', toSafeDirName(`source:${userConfigDir}`))
)
expect(env.OPENCODE_CONFIG_DIR).not.toBe(userConfigDir)
@@ -443,9 +441,11 @@ describe('OpenCodeHookService overlay mode (user OPENCODE_CONFIG_DIR set)', () =
// No overlay was created at the typo path.
expect(existsSync(missingPath)).toBe(false)
// No overlay dir under userData either.
expect(existsSync(join(userDataDir, 'opencode-config-overlays', toSafeDirName(ptyId)))).toBe(
false
)
expect(
existsSync(
join(userDataDir, 'opencode-config-overlays', toSafeDirName(`source:${missingPath}`))
)
).toBe(false)
})
it("preserves the user's OPENCODE_CONFIG_DIR when the mirror step fails", async () => {
@@ -462,9 +462,14 @@ describe('OpenCodeHookService overlay mode (user OPENCODE_CONFIG_DIR set)', () =
const service = new OpenCodeHookService()
const env = service.buildPtyEnv(ptyId, userConfigDir)
expect(env).toEqual({ OPENCODE_CONFIG_DIR: userConfigDir })
// Overlay dir was rolled back so a half-built tree does not leak.
const overlayDir = join(userDataDir, 'opencode-config-overlays', toSafeDirName(ptyId))
expect(existsSync(overlayDir)).toBe(false)
// Overlay cleanup is deliberately not on the fallback path; it may hold
// OpenCode-created runtime files on Windows.
const overlayDir = join(
userDataDir,
'opencode-config-overlays',
toSafeDirName(`source:${userConfigDir}`)
)
expect(existsSync(overlayDir)).toBe(true)
expectUserConfigIntact()
} finally {
mirrorSpy.mockRestore()
@@ -472,20 +477,23 @@ describe('OpenCodeHookService overlay mode (user OPENCODE_CONFIG_DIR set)', () =
})
it.skipIf(process.platform === 'win32')(
'clearPty removes the overlay without following symlinks into the user dir',
'clearPty leaves the source overlay off the teardown hot path',
() => {
// Critical regression guard from issue #1083: the overlay's mirrored
// entries are symlinks pointing at the user's real config. Recursive
// teardown must NEVER walk through them.
// Why: OpenCode may populate OPENCODE_CONFIG_DIR with runtime files.
// PTY teardown must not recursively delete that tree on Electron main.
const service = new OpenCodeHookService()
service.buildPtyEnv(ptyId, userConfigDir)
const overlayDir = join(userDataDir, 'opencode-config-overlays', toSafeDirName(ptyId))
const overlayDir = join(
userDataDir,
'opencode-config-overlays',
toSafeDirName(`source:${userConfigDir}`)
)
expect(existsSync(overlayDir)).toBe(true)
service.clearPty(ptyId)
expect(existsSync(overlayDir)).toBe(false)
expect(existsSync(overlayDir)).toBe(true)
// User config must still exist with all original contents.
expectUserConfigIntact()
// The plugins/ dir under the user config is also intact.
@@ -495,9 +503,9 @@ describe('OpenCodeHookService overlay mode (user OPENCODE_CONFIG_DIR set)', () =
it('rebuilding the overlay for the same ptyId does not corrupt the user dir', () => {
// Mirrors the daemon cold-restore code path that calls buildPtyEnv with
// the same sessionId across restarts. Each rebuild must clear the prior
// overlay safely (no symlink-walk into user data) and produce a fresh
// overlay with both user files and Orca's plugin.
// the same sessionId across restarts. Each rebuild must refresh the prior
// overlay safely (no symlink-walk into user data) and keep both user files
// and Orca's plugin reachable.
const service = new OpenCodeHookService()
service.buildPtyEnv(ptyId, userConfigDir)
service.buildPtyEnv(ptyId, userConfigDir)
@@ -508,4 +516,28 @@ describe('OpenCodeHookService overlay mode (user OPENCODE_CONFIG_DIR set)', () =
).toContain('OrcaOpenCodeStatusPlugin')
expectUserConfigIntact()
})
it('reconciles stale mirrored entries while preserving OpenCode runtime files', () => {
const service = new OpenCodeHookService()
const firstEnv = service.buildPtyEnv(ptyId, userConfigDir)
const overlayDir = firstEnv.OPENCODE_CONFIG_DIR!
mkdirSync(join(overlayDir, 'node_modules', 'opencode-runtime'), { recursive: true })
writeFileSync(join(overlayDir, 'node_modules', 'opencode-runtime', 'index.js'), '')
rmSync(join(userConfigDir, 'auth.json'), { force: true })
writeFileSync(join(userConfigDir, 'auth.json'), 'rotated-user-auth-token')
rmSync(join(userConfigDir, 'plugins', 'user-plugin.js'), { force: true })
writeFileSync(join(userConfigDir, 'plugins', 'new-plugin.js'), 'export default "new"')
const secondEnv = service.buildPtyEnv(ptyId, userConfigDir)
expect(secondEnv.OPENCODE_CONFIG_DIR).toBe(overlayDir)
expect(readFileSync(join(overlayDir, 'auth.json'), 'utf8')).toBe('rotated-user-auth-token')
expect(existsSync(join(overlayDir, 'plugins', 'user-plugin.js'))).toBe(false)
expect(readFileSync(join(overlayDir, 'plugins', 'new-plugin.js'), 'utf8')).toBe(
'export default "new"'
)
expect(existsSync(join(overlayDir, 'node_modules', 'opencode-runtime', 'index.js'))).toBe(true)
})
})
+79 -40
View File
@@ -7,19 +7,26 @@ import { join } from 'path'
import {
existsSync,
mkdirSync,
readFileSync,
readdirSync,
realpathSync,
rmSync,
statSync,
unlinkSync,
writeFileSync
} from 'fs'
import { createHash } from 'crypto'
import { mirrorEntry, safeRemoveOverlay } from '../pty/overlay-mirror'
import { mirrorEntry, safeRemoveTree } from '../pty/overlay-mirror'
const ORCA_OPENCODE_PLUGIN_FILE = 'orca-opencode-status.js'
const OPENCODE_LEGACY_HOOKS_DIR = 'opencode-hooks'
const OPENCODE_OVERLAY_DIR = 'opencode-config-overlays'
const OPENCODE_SHARED_CONFIG_DIR = 'shared'
const OPENCODE_OVERLAY_MANIFEST_FILE = '.orca-opencode-overlay-manifest.json'
type OpenCodeOverlayManifest = {
topLevelEntries: string[]
pluginEntries: string[]
}
// Why: the id passed in by pty.ts's daemon path is a sessionId shaped like
// "<worktreeId>@@<uuid>" where worktreeId itself contains "::" and a
@@ -171,8 +178,8 @@ function getOpenCodePluginSource(): string {
'// Why: oh-my-opencode style tools spawn child sessions that emit their',
'// own session.idle / message events. Those child completions must not',
'// flip the root Orca pane to done or overwrite the parent turn preview.',
'// Match Superset by checking `parentID` via client.session.list(), cache',
'// the result per session, and fail closed (assume child) on lookup errors',
'// Detect child sessions by checking `parentID` via client.session.list(),',
'// cache the result per session, and fail closed (assume child) on lookup errors',
'// so a transient SDK failure cannot create false "done" transitions.',
'async function isChildSession(client, sessionID) {',
' if (!sessionID) return true;',
@@ -339,24 +346,14 @@ function getOpenCodePluginSource(): string {
// agent-hooks server (/hook/opencode), so OpenCode rides the same status
// pipeline as Claude/Codex/Gemini.
export class OpenCodeHookService {
clearPty(ptyId: string): void {
if (!isUsableId(ptyId)) {
return
}
// Why: a PTY with this id may have been spawned under either regime —
// overlay (user had OPENCODE_CONFIG_DIR set) or legacy per-PTY (no user
// value). Both roots use the same hashed name, so try the overlay first
// via the safe-descend teardown that never follows symlinks/junctions
// into the user's source dir, then sweep any legacy directory left over
// from a prior code path.
safeRemoveOverlay(this.getOverlayDir(ptyId), this.getOverlayRoot())
try {
rmSync(this.getLegacyConfigDir(ptyId), { recursive: true, force: true })
} catch {
// Why: best-effort cleanup of the no-OPENCODE_CONFIG_DIR-set regime;
// there are no symlinks/junctions in this tree (Orca-only files), so
// rmSync recursive is safe here.
}
clearPty(_ptyId: string): void {
// Why: OpenCode can materialize thousands of plugin runtime files under
// OPENCODE_CONFIG_DIR. This teardown runs on Electron's main process hot
// path, so recursive deletion here can freeze the whole app on Windows
// while Node, antivirus, or indexing still holds file handles.
//
// Current builds use app/source-scoped config dirs, not PTY-scoped dirs,
// so there is no live PTY-owned OpenCode filesystem state to remove.
}
buildPtyEnv(ptyId: string, existingConfigDir?: string | undefined): Record<string, string> {
@@ -368,10 +365,9 @@ export class OpenCodeHookService {
}
if (!existingConfigDir) {
// Why: no user value to mirror — keep the original per-PTY behavior so
// a manually launched `opencode` outside Orca's command templates picks
// up the status plugin via OPENCODE_CONFIG_DIR injection alone.
const configDir = this.writeLegacyPluginConfig(ptyId)
// Why: OpenCode may install plugin dependencies under this root. Sharing
// it prevents per-terminal node_modules churn and teardown freezes.
const configDir = this.writeSharedPluginConfig()
if (!configDir) {
return {}
}
@@ -379,15 +375,14 @@ export class OpenCodeHookService {
}
// Why: do NOT `mkdir -p` the user's typoed path — overriding it with an
// Orca-owned dir is the exact failure mode we reject Superset's wrapper
// for in docs/opencode-config-dir-collision.md. Let OpenCode surface the
// typo on its own; we only forfeit our status plugin for this pane.
// Orca-owned dir is the exact config-replacement failure mode documented in
// docs/opencode-config-dir-collision.md. Let OpenCode surface the typo on
// its own; we only forfeit our status plugin for this pane.
if (!existsSync(existingConfigDir)) {
return { OPENCODE_CONFIG_DIR: existingConfigDir }
}
const overlayDir = this.getOverlayDir(ptyId)
safeRemoveOverlay(overlayDir, this.getOverlayRoot())
const overlayDir = this.getSourceOverlayDir(existingConfigDir)
try {
mkdirSync(overlayDir, { recursive: true })
@@ -399,7 +394,6 @@ export class OpenCodeHookService {
// locked-down corporate machines, etc. In every case, preserve the
// user's OPENCODE_CONFIG_DIR — a missing status plugin is a vastly
// smaller harm than silently dropping the user's auth/models/keymap.
this.clearPty(ptyId)
return { OPENCODE_CONFIG_DIR: existingConfigDir }
}
@@ -410,14 +404,47 @@ export class OpenCodeHookService {
return join(app.getPath('userData'), OPENCODE_OVERLAY_DIR)
}
private getOverlayDir(ptyId: string): string {
// Why: the overlay root is distinct from the legacy hooks root so the
// two regimes are easy to tell apart on disk during debugging.
return join(this.getOverlayRoot(), toSafeDirName(ptyId))
private getSourceOverlayDir(sourceConfigDir: string): string {
return join(this.getOverlayRoot(), toSafeDirName(`source:${sourceConfigDir}`))
}
private getLegacyConfigDir(ptyId: string): string {
return join(app.getPath('userData'), OPENCODE_LEGACY_HOOKS_DIR, toSafeDirName(ptyId))
private getSharedConfigDir(): string {
return join(app.getPath('userData'), OPENCODE_LEGACY_HOOKS_DIR, OPENCODE_SHARED_CONFIG_DIR)
}
private readOverlayManifest(overlayDir: string): OpenCodeOverlayManifest {
try {
const parsed = JSON.parse(
readFileSync(join(overlayDir, OPENCODE_OVERLAY_MANIFEST_FILE), 'utf8')
) as Partial<OpenCodeOverlayManifest>
return {
topLevelEntries: Array.isArray(parsed.topLevelEntries) ? parsed.topLevelEntries : [],
pluginEntries: Array.isArray(parsed.pluginEntries) ? parsed.pluginEntries : []
}
} catch {
return { topLevelEntries: [], pluginEntries: [] }
}
}
private writeOverlayManifest(overlayDir: string, manifest: OpenCodeOverlayManifest): void {
writeFileSync(
join(overlayDir, OPENCODE_OVERLAY_MANIFEST_FILE),
`${JSON.stringify(manifest, null, 2)}\n`
)
}
private clearManifestEntries(overlayDir: string, manifest: OpenCodeOverlayManifest): void {
for (const entryName of manifest.topLevelEntries) {
safeRemoveTree(join(overlayDir, entryName))
}
const overlayPluginsDir = join(overlayDir, 'plugins')
for (const entryName of manifest.pluginEntries) {
if (entryName === ORCA_OPENCODE_PLUGIN_FILE) {
continue
}
safeRemoveTree(join(overlayPluginsDir, entryName))
}
}
// Why: walks the user's OPENCODE_CONFIG_DIR top-level entries. The
@@ -427,6 +454,14 @@ export class OpenCodeHookService {
// top-level entry via symlink/junction so user edits propagate live on
// POSIX (and on Windows-with-developer-mode) without copying files.
private mirrorUserConfig(sourceDir: string, overlayDir: string): void {
const previousManifest = this.readOverlayManifest(overlayDir)
// Why: source-scoped overlays persist across terminals. Only remove paths
// Orca previously mirrored, so deleted/replaced user config cannot stay
// stale while OpenCode-owned runtime dirs such as node_modules survive.
this.clearManifestEntries(overlayDir, previousManifest)
const nextManifest: OpenCodeOverlayManifest = { topLevelEntries: [], pluginEntries: [] }
for (const entry of readdirSync(sourceDir, { withFileTypes: true })) {
const sourcePath = join(sourceDir, entry.name)
@@ -475,13 +510,17 @@ export class OpenCodeHookService {
join(resolvedSource, pluginEntry.name),
join(overlayPluginsDir, pluginEntry.name)
)
nextManifest.pluginEntries.push(pluginEntry.name)
}
continue
}
}
mirrorEntry(sourcePath, join(overlayDir, entry.name))
nextManifest.topLevelEntries.push(entry.name)
}
this.writeOverlayManifest(overlayDir, nextManifest)
}
// Why: write Orca's status plugin into the overlay's plugins/ dir. The
@@ -504,8 +543,8 @@ export class OpenCodeHookService {
writeFileSync(pluginPath, getOpenCodePluginSource())
}
private writeLegacyPluginConfig(ptyId: string): string | null {
const configDir = this.getLegacyConfigDir(ptyId)
private writeSharedPluginConfig(): string | null {
const configDir = this.getSharedConfigDir()
const pluginsDir = join(configDir, 'plugins')
try {
mkdirSync(pluginsDir, { recursive: true })