Repository navigation
fix(opencode): stop OpenCode 2 loading a stale plugin from the retired shared hooks dir - #23500
Conversation
…d shared hooks dir Before 1.4.209 Orca pointed OPENCODE_CONFIG_DIR at <userData>/opencode-hooks/shared and wrote a server()-only status plugin there. 1.4.209 moved the plugin to OpenCode's global config dir and 1.4.210 added the v2 setup() export, but nothing rewrote the old file. Shells, daemon-persisted panes and OpenCode 2 background services that still carry that OPENCODE_CONFIG_DIR load only that dir under OpenCode 2 (it replaces the global dir), so the v2 loader rejects the stale plugin with "Plugin must export a default definition with an id and an effect or setup function" and pane status dies. - Refresh the plugin in the retired shared dir (only when it already exists and its content differs) so OpenCode processes started later from old shells load the dual v1/v2 export. Runs on OpenCode pane spawns and on any spawn that inherits the retired dir, even with agent status hooks off. - Drop an inherited OPENCODE_CONFIG_DIR / ORCA_OPENCODE_* marker that points at the retired dir when building a new pane env, so new panes use global discovery. Limitation: an OpenCode 2 background service already running from an old pane keeps its cached copy of the stale module even after the file is rewritten (verified with opencode2 v2.0.18). It must be restarted (`opencode service restart`); a restart from a new Orca pane then picks up the global config because the env is stripped.
|
Navigate logical layers of code changes, visualize relationships, and explore their blast radius. Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Advanced Run ID: 📒 Files selected for processing (5)
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 8 remain after this review. 📝 WalkthroughWalkthroughPTY environment assembly removes OpenCode config values that point to either retired shared config directory. When it finds a matching value, it refreshes both OpenCode hook services and treats the resolved legacy directory as absent. Hook services refresh the legacy plugin only when its contents differ. Daemon and disconnected PTY spawn-option builders also remove matching legacy config values. Tests cover both legacy paths, neighboring user config directories, and plugin refresh behavior. Priority: ⬇️ Low Merge Risk: ⚪ Minimal · up to The retired OpenCode configuration cleanup appears ready to merge after normal checks. Already-running services that cached the stale plugin still need a restart. Security Architecture ReviewSecurity architecture risk: 🔵 Low · up to The cleanup is limited to known retired OpenCode paths, and no broad new exposure was identified. The new file repair does, however, rely on the retired plugin location being exclusively application-owned. Retained concerns
Security review detailsSecurity Blast Radius
Security Findings and Attack Paths
Trust Boundaries and Controls
Resilience and Maintainability Implications
Hardening Proposals
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 4
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: 5d5361f4-9429-4c4b-b41d-b86fd237149d
📒 Files selected for processing (6)
src/main/ipc/pty/host-env/assembly.tssrc/main/ipc/pty/host-env/opencode-hook-installation.test.tssrc/main/opencode/hook-service.test.tssrc/main/opencode/hook-service.tssrc/main/opencode/legacy-shared-config-dir.test.tssrc/main/opencode/legacy-shared-config-dir.ts
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 8 remain after this review.
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
This branch stops OpenCode 2 from loading a stale server()-only status plugin left in the retired shared hooks dir, which the v2 loader rejects and which suppresses agent status. It covers the full 6-file diff end to end.
- Retired-dir locator — new
src/main/opencode/legacy-shared-config-dir.tsnamesopencode-hooks/opencode2-hooksand resolves/matches<userData>/<hooksDir>/shared;hook-service.tsdrops its private constants in favour of it. - Stale plugin refresh —
OpenCodeHookService.refreshLegacySharedPlugin()rewrites<shared>/plugins/<pluginFileName>only when the file already exists and differs, at most once per variant per app run. ENOENT marks it done; other errors retry on the next spawn. It never creates the retired dir. - Host env scrubbing —
buildPtyHostEnvdropsOPENCODE_CONFIG_DIR/ORCA_OPENCODE_CONFIG_DIR/ORCA_OPENCODE_SOURCE_CONFIG_DIRwhen they resolve to a retired shared dir, nulls a retired resolved source dir (including theprocess.envfallback), and triggers the refresh on both services even when status hooks are off. - Tests — a locator unit test, host-env retirement scenarios (marked/unmarked × both variants, a non-matching neighbour dir), and hook-service tests that load the rewritten and untouched files through a real ESM import.
I verified the two historical details the fix rests on: ee354a35d7 wrote orca-opencode-status.js into opencode-hooks/shared and orca-opencode2-status.js into opencode2-hooks/shared, so each singleton refreshes the file its variant actually produced; and both plugin sources emit server + setup, so the refreshed file is accepted by the OpenCode 1 and 2 loaders.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: 50043804-3ec0-4cf9-866c-c76be19a2fdd
📒 Files selected for processing (10)
src/main/daemon/pty-subprocess/spawn-environment.tssrc/main/ipc/pty/host-env/assembly.tssrc/main/ipc/pty/host-env/opencode-hook-installation.test.tssrc/main/ipc/pty/ipc/spawn-options.tssrc/main/ipc/pty/opencode-legacy-spawn-deletions.test.tssrc/main/ipc/pty/runtime/spawn-options.tssrc/main/opencode/hook-service.test.tssrc/main/opencode/hook-service.tssrc/main/opencode/legacy-shared-config-dir.test.tssrc/main/opencode/legacy-shared-config-dir.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- src/main/opencode/legacy-shared-config-dir.test.ts
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.
There was a problem hiding this comment.
ℹ️ No critical issues — one edge-case note inline.
Reviewed changes
This re-review covers commit 9fdbe640 ("harden legacy plugin repair and inherited config cleanup"); the original fix 53991b5680 and the base-sync merge 486ae7ac were reviewed previously.
- Atomic legacy-plugin repair —
refreshLegacySharedPlugindrops the once-per-process flag, swapswriteFileSyncforwriteFileAtomically(temp + rename), and is now also called frombuildPtyEnv, so a plugin dropped late or overwritten by an older process is repaired on the next check without a needless watcher reload. - Normalized retired-path matching —
isOpenCodeLegacySharedConfigDircanonicalizes both sides (separators,.., Windows case), and the retired-dir/env-key constants move from privatehook-service.tsstate intolegacy-shared-config-dir.tswith a newgetLegacyOpenCodeEnvKeysToDelete. - Inherited-env cleanup on every spawn route —
buildPtyHostEnvnow also consultsprocess.envand re-applies the retired-dir guard after overlay restoration; the renderer, runtime, and daemon paths carry or perform the deletion of retiredOPENCODE_CONFIG_DIRkeys, while explicit user config and SSH are preserved. - Tests — normalization, late/overwritten atomic repair with an open reader, inherited-vs-explicit hooks-off refresh, daemon-inherited stripping, explicit-config preservation, and a two-route spawn-deletion matrix; all four touched suites pass locally.
I traced the open concern below and verified the daemon scrub's ORCA_USER_DATA_PATH is always set by spawnDaemonChildProcess, that writeFileAtomically preserves the old inode (the atomicity assertion is real), and that the global vitest setup installs an AppEnvironment so the new getAppEnvironment() calls in the spawn-options paths cannot throw.
Technical details
# Retired-key cleanup is unconditional once it reaches the daemon
## Affected sites
- `src/main/ipc/pty/ipc/spawn-options.ts:48-50` — adds `getLegacyOpenCodeEnvKeysToDelete(ctx.spawnEnv, …)` to `envToDelete` for daemon-host spawns too.
- `src/main/ipc/pty/runtime/spawn-options.ts:77-79` — same shape for runtime spawns.
- `src/main/daemon/pty-subprocess/spawn-environment.ts:54-91` — `deleteRequestedDaemonEnvKeys` deletes every `keys` entry unconditionally after its own retired-path scrub.
## Why it matters
`getLegacyOpenCodeEnvKeysToDelete` resolves on main's `process.env`, but the daemon's effective env is the daemon's own inherited `process.env` merged with the request env. If main inherited a retired `OPENCODE_CONFIG_DIR` while a persistent daemon (which outlives Electron) inherited a valid user config dir, main adds the key to `envToDelete`, the daemon merges its valid value, the retired-path scrub leaves it (it is not retired), and the trailing `for (const key of keys) delete env[key]` removes the valid value. Result: that terminal's OpenCode silently falls back to global config. Trigger is narrow — the daemon must predate the current main env divergence.
## Required outcome
A retired-path cleanup must not delete a daemon-effective value that is not itself retired, without dropping the cleanup for older daemons that lack the in-process scrub.
## Suggested approach (optional)
Distinguish "delete if retired" requests from "delete unconditionally" requests in the daemon contract (e.g. a separate conditional key list, or compare the daemon's own value before honoring the request), rather than gating the entry to non-daemon spawns — gating would regress older daemons that rely on `envToDelete`.
## Open questions for the human (optional)
- Is the older-daemon compatibility path still load-bearing, or can the envToDelete entry be gated to `!ctx.isDaemonHostSpawn` now that the daemon has its own scrub?
- Add a regression test with different inherited OpenCode values in main and the daemon.DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
This covers commit ddbb2387 ("preserve daemon-owned user config during legacy cleanup"), the fix for the one inline concern from the prior review; its changes touch both spawn-options routes and their tests.
- Daemon-owned config preserved — the retired-key entry is now added to
envToDeleteonly when!args.connectionId && !ctx.isDaemonHostSpawn, in bothipc/spawn-options.tsandruntime/spawn-options.ts, so main no longer asks the daemon to unconditionally delete a key whose effective value only the daemon knows. Daemon host spawns rely on the daemon's own in-process scrub. - Tests updated to match — the spawn-deletion matrix gains a
daemonaxis covering a retired inherited value (stripped), a valid daemon-owned value (kept), an explicit renderer config (kept), and an explicitenvToDelete(still deleted); the daemon host-env tests now exercise the scrub without a passedenvToDelete.
I re-ran the four touched suites locally: 100 passed, 1 skipped. The prior inline thread is resolved.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
|
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to GitHub limitations.
🟡 Minor · Clean retired OpenCode variables in the relay environment. · spawn-options.ts:69-78
src/main/ipc/pty/ipc/spawn-options.ts:69-78
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winClean retired OpenCode variables in the relay environment.
Connection spawns skip
getLegacyOpenCodeEnvKeysToDelete. The relay copies its inherited environment intobuildSpawnEnv.restoreOrStripOverlayEnvremoves theORCA_OPENCODE_*markers but can preserve an inherited retiredOPENCODE_CONFIG_DIR. The finalpty.spawncan then load the retired shared config and its old hooks.Apply the legacy-path cleanup in
buildSpawnEnv. Use the relay’sORCA_USER_DATA_PATHand delete only keys recognized as retired. This covers both relay spawn paths and preserves explicit non-retired directories.Suggested fix
+import { getLegacyOpenCodeEnvKeysToDelete } from '../main/opencode/legacy-shared-config-dir' + @@ const result = mergeGitConfigEnvProtocol(baseEnv, augmented) as Record<string, string> + const userDataPath = process.env.ORCA_USER_DATA_PATH + if (userDataPath) { + for (const key of getLegacyOpenCodeEnvKeysToDelete(result, userDataPath, {})) { + delete result[key] + } + } result[ORCA_IMAGE_PROTOCOL_ENV] = ORCA_IMAGE_PROTOCOL_VALUE
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: 5772c15e-334f-4eed-82d9-9bb32ef7f5d4
📒 Files selected for processing (4)
src/main/ipc/pty/host-env/opencode-hook-installation.test.tssrc/main/ipc/pty/ipc/spawn-options.tssrc/main/ipc/pty/opencode-legacy-spawn-deletions.test.tssrc/main/ipc/pty/runtime/spawn-options.ts
🚧 Files skipped from review as they are similar to previous changes (4)
- src/main/ipc/pty/runtime/spawn-options.ts
- src/main/ipc/pty/ipc/spawn-options.ts
- src/main/ipc/pty/opencode-legacy-spawn-deletions.test.ts
- src/main/ipc/pty/host-env/opencode-hook-installation.test.ts
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 8 remain after this review.
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
This re-review covers commit eb466a5 ("sanitize inherited sources and repair unseen legacy copies"), the delta since the prior pullfrog review of ddbb238.
- Sanitized inherited OpenCode env —
buildPtyHostEnvbuildsinheritedOpenCodeEnvfromprocess.envwith any retired shared-hooks value omitted, and passes it to bothresolveOpenCodeSourceConfigDirandrestoreOrStripOverlayEnv. This structurally prevents a retired path from being restored through the inherited fallback, replacing the previous post-restoration delete guard. - Unconditional legacy repair — both hook services refresh their retired plugin copies on every host-env assembly, not only when a retired path is visible to main, so a retained daemon or sibling-shell path is still repaired. Missing files stay absent; only non-
ENOENTfailures log and retry. resolveOpenCodeSourceConfigDiraccepts aninheritedEnvoverride (defaulting toprocess.env), letting callers supply sanitized values without touching the other call sites.- Tests — explicit config preserved when a retired parent source is inherited, both variants repaired with hooks off, and repair-failure logging plus retry once the obstruction clears.
I traced the filter through restoreOrStripOverlayEnv (a retired value can no longer enter inheritedOpenCodeEnv, so the removed delete guard is safe) and re-ran the four touched suites: 104 passed, 1 skipped.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
Integrate ~2007 upstream commits, mostly OpenCode v2 integration maturity (status reporting per pane stablyai#23722/stablyai#24962, hook install in terminal config dir stablyai#25296, stop stale plugin from retired shared hooks dir stablyai#23500) plus @orca/process-host extraction, structured chat over ACP, and many agents. Fork conflicts resolved (6): minimax/zai catalog entries relocated to the new split agent-catalog-entries-secondary.ts; redraw shortcut moved to the new matches() helper; createLocalNestedRepoScanFilesystem updated to isGitRepoAsync; nestedReposPromise kept after upstream made timing a param; showNestedReposToast import kept, dead settingsForRepoOwner dropped. Added minimax/zai to the new Record<TuiAgent> maps (rest-signal, readiness lane) and switched the Activity wrapper-grouping types to TerminalAgent. Accepted upstream's deletion of the global-fetch audit test (stablyai#25791). typecheck clean; git-crypt, time-tracker, activity and shortcut-policy suites green (2305 tests).

ELI5
Older Orca left a status plugin in a folder that OpenCode 2 still loads. That copy is too old for OpenCode 2, so agent status stops updating. Orca now repairs the old copy and stops new terminals from inheriting that folder.
What Changed
Existing retired plugins are compared with the current OpenCode 1/2-compatible source on subsequent launches and replaced atomically only when different. Missing files stay absent; late files and copies overwritten by an older process are repaired on the next check.
Retired config paths are normalized before matching, including Windows case and separators. Both renderer and runtime spawns carry inherited-path deletions only to the local provider that shares their environment. The terminal daemon checks its own effective environment, so a different app-inherited value cannot remove its legitimate user config. Explicit user config directories are preserved. Every host environment assembly checks both existing retired plugin copies, including when status hooks are disabled and only a daemon or sibling shell retains the path. Config resolution and overlay restoration share sanitized inherited values, preserving explicit pane config. Non-missing repair failures are logged and retried.
Why
Repairing Orca's known old files lets existing shells load a compatible plugin without deleting user configuration. Removing retired paths from new terminals restores normal OpenCode config discovery. Atomic replacement prevents concurrent readers from seeing a half-written plugin; checking content avoids needless watcher reloads.
Linked Issue
Reported in Orca crash scan 28 on v1.4.215; no separate GitHub issue.
Visual Proof
N/A — no UI layout or interaction change. Real OpenCode loader and hook-event evidence appears below.
Testing
pnpm tcand changed-code quality gate passed.Review
Addressed the original four substantive review comments and follow-ups about differing app/daemon environments, explicit config preservation, daemon-only repair, and diagnostics: inherited environment cleanup, repeat repair, atomic writes, and path normalization.
Agent skill upstream boundary
Notes
An OpenCode 2 background service that already cached the broken module still needs a restart. New launches and restarted services load the repaired plugin. An old OpenCode 1 shell can still discover both global and legacy copies and emit duplicate events, as before.
The cleanup is confined to the execution host's known Orca directories. SSH requests do not receive client-local path deletions; WSL guest paths and folder workspaces retain their existing behavior. Each check reads a small plugin file and writes only changed content. Explicit
envToDeleterequests keep their unconditional semantics. No new wire fields are introduced. Older daemons keep their prior environment behavior until replaced; the repaired plugin still makes their old config directory loadable.Checklist
Fix evidence
Real binaries:
@opencode/[email protected](opencode v2.0.18) and[email protected]. HOME/XDG were isolated and everyORCA_*variable was unset. A local HTTP receiver on :47655 stood in for Orca's hook server.1. The current v1.4.215 plugin is accepted. It was built with
getOpenCodePluginSource()and ends withexport default { id, server: OrcaOpenCodeStatusPlugin, setup: setupOpenCode2Status }.opencode run --standalone --print-logslogsmsg="loading plugin" id=.../orca-opencode-status.jswith no error.2. The stale file reproduces the exact user error. v1.4.207's generated source ends with
export default { id: "orca-opencode-status", server: OrcaOpenCodeStatusPlugin, };. Under 2.0.18:3. Why it persists.
OPENCODE_CONFIG_DIR=cfg opencode debug configlists onlycfg, not~/.config/opencode.buildPtyHostEnvwith an inherited shared dir gives:PANE_ENV {"OPENCODE_CONFIG_DIR":".../opencode-hooks/shared","ORCA_OPENCODE_CONFIG_DIR":".../opencode-hooks/shared"},SHARED_PLUGIN_HAS_SETUP false.plugin errors: 1,hook POSTs received: <none>.main unmarked: {"OPENCODE_CONFIG_DIR":".../shared",...} sharedHasSetup=0.OPENCODE_CONFIG_DIR=shared, a later call from a pane with no such variable still printed"path": ".../opencode-hooks/shared", and the service loggedfailed to load plugin.BEFORE (v1.4.215 / main):
AFTER (this branch, same harness, v1.4.207 stale file seeded):
A background service restarted with
OPENCODE_CONFIG_DIR=sharedafter the refresh logsloading pluginwith no failure.OpenCode 1 regression check (opencode-ai 1.18.31):
[v1-after-newpane] plugin errors: 0,hook POSTs received: 1 MessagePart; 1 SessionBusy; 1 SessionIdle; 1 SessionStart[v1-after-oldshell] plugin errors: 0. Events are posted twice here, the same as v1.4.215 for such shells; see Trade-offs.Unit tests: the new tests fail against origin/main code (
6 failed | 77 passed): "refreshes a stale plugin left in the retired shared hooks dir" and 4 x "drops opencode-hooks/opencode2-hooks for opencode/opencode2 panes (unmarked)", plus one more. All pass with the fix.