Repository navigation
fix: dispose OpenCode 2 hooks after prompt setup and cleanup failures - #23209
Conversation
|
Navigate logical layers of code changes, visualize relationships, and explore their blast radius. 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 (2)
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 8 remain after this review. 📝 WalkthroughWalkthroughOpenCode 2 plugin setup now retains initialized hooks so it can dispose them if a later setup step fails. During unload, cleanup continues to await event consumption and dispose hooks if prompt-registration disposal fails. New tests cover setup and cleanup failures, in-flight event delivery, optional disposers, and factory rejection. A reliability-gate record documents cleanup and delivery-order invariants, evidence, budgets, and promotion criteria. The Windows process-check test now validates policy-query behavior and receipts. Priority: ⬇️ Low Merge Risk: ⚪ Minimal · up to The cleanup and Windows policy-probe changes appear ready to merge after normal checks. Security Architecture ReviewSecurity architecture risk: 🔵 Low · up to The change improves cleanup of status hooks without adding an externally reachable path. Exceptional cleanup and execution across supported environments are not fully validated. Retained concerns Security review detailsSecurity Blast Radius
Trust Boundaries and Controls
Resilience and Maintainability Implications
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
Full details: Docstring CoverageExplanation Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 4 functions across 4 files. (1 skipped: 1 unsupported.)
✨ 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.
Important
A required unit test now fails deterministically: the generated plugin bytes changed, but the pinned SHA-256 digest in src/main/opencode/hook-service.test.ts was not updated.
Reviewed changes
- Setup-failure disposal —
setupOpenCode2Statushoists the acquired hook factory tolet hooks;and disposes it from the setupcatch, so a throwing or rejectingctx.session.hook("prompt", …)no longer strands an active hook owner. - Ordered cleanup under failure — the unload closure nests
try/finallyso the prompt disposer, the event-consumption settle, and factory disposal each run even when an earlier stage throws or rejects, while errors stay swallowed to keep unload fail-open. - Lifetime tests —
status-plugin-setup-lifetime.test.tsexecutes the generated setup against synthetic factories, subscribing iterators, and deferred delivery, pinning disposal counts and delivery-before-factory ordering. - Reliability gate — adds
agent-session.opencode2-hook-cleanup(experimental/partial) toconfig/reliability-gates.jsonc, pointing at the new suite.
⚠️ Generated-source digest test is stale and fails
src/main/opencode2/status-plugin-setup-source.ts is embedded verbatim by getStatusPluginFactorySource, and getOpenCodePluginSource() also sets emitNextEvents: true, so editing the setup source changes the bytes hashed by src/main/opencode/hook-service.test.ts:95. That assertion still pins f2c469ff…, so the test fails on this head. The setup/lineage suites pass (59/59); this is a separate, easy-to-miss byte-level contract.
Technical details
# Update the pinned generated-plugin digest
## Affected sites
- `src/main/opencode/hook-service.test.ts:95-97` — `digest(getOpenCodePluginSource())` still expects `f2c469ff2d360ed94955d715705b9d4dd633dd334887906fbb534c1925ec81c9`.
## Evidence
`ORCA_BACKGROUND_LAUNCH=1 pnpm exec vitest run --config config/vitest.config.ts src/main/opencode/hook-service.test.ts -t "keeps generated plugin bytes stable"`
- expected `f2c469ff2d360ed94955d715705b9d4dd633dd334887906fbb534c1925ec81c9`
- received `c81893814f08bfb2f9b5c133c5355b53d485982402d89e92ff15fc4e7d543079`
The second digest in that test (`getOpenCodeFamilyPluginSource('/hook/mimo-code', { emitSessionStart: false })`, `emitNextEvents` unset) is unaffected because it omits the setup source.
## Required outcome
- `hook-service.test.ts` pins the current digest so the full unit suite is green.
## Suggested approach
Update the hex literal at `hook-service.test.ts:96` to the received value above (or regenerate it from a clean run). The argument that this hash gate exists is to force a deliberate acknowledgement whenever generated plugin bytes change — this PR is that change.DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
The delta since the prior review is the follow-up commit 01c4ee2b6a, which addresses the one finding raised previously.
- Pinned generated-plugin digest updated —
src/main/opencode/hook-service.test.tsnow expectsc81893814f08…forgetOpenCodePluginSource(), matching the byte change introduced by the setup-source edit. This resolves the sole prior-review finding. Verified locally:hook-service.test.ts(34 tests) andstatus-plugin-setup-lifetime.test.ts(10 tests) both pass at this head.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
The delta since the prior review is two merges: bd214d97d4 (shared diff-note catalog correction) and 989512be2b (merge main, preserve reliability gate). No changes to the OpenCode hook-cleanup mechanism itself.
- Diff-note draft catalog entries restored — adds
f6c449191e("Add note for the AI"),5fa4bfebaa("Add note") and5e9b3d0c2e("Adding..."), plus a trailing comma oncommentTooLarge, across all six locale catalogs. Values match the source fallbacks inDiffCommentDraftCard.tsx. - Reliability gate preserved through the main merge —
agent-session.opencode2-hook-cleanupinconfig/reliability-gates.jsoncis intact; only its position among the gates changed.
Verification at head `989512be2b`
check:reliability-gates— 129 gates pass.verify:localization-catalog,verify:localization-extraction, and the runtime-required English catalog generator all pass; the six locale JSON files parse and carry no duplicate new keys.status-plugin-setup-lifetime.test.ts(10) andhook-service.test.ts(34) pass.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
The delta since Pullfrog's prior review (989512be2b) is a merge-up plus a small test-isolation repair to the hourly build-version helper. No new issues.
- Hourly build identity accepts an injected package version —
getHourlyBuildIdentitygained an optionalpackageVersionoption; when supplied it is used directly, otherwise the helper still readspackage.json. The CLI entry point omits it, so release behavior is unchanged. - Hourly build tests made deterministic — the two
getHourlyBuildIdentitycases now pass a fixed version (1.4.201/1.4.214) through the new option instead of depending on the working tree'spackage.json, and a new case covers a package version that outruns the published tags. - Merge-up churn —
config/reliability-gates.jsoncretains theagent-session.opencode2-hook-cleanupgate and isoxfmt-clean; the locale catalogs an earlier commit restored no longer appear becausemainnow carries them; a trailing blank line lefthook-service.test.ts.
Verified at head 1328f20e: hourly-build-version.test.mjs (17), status-plugin-setup-lifetime.test.ts (10), and hook-service.test.ts (34) pass; check:reliability-gates passes for 130 gates; oxlint and oxfmt --check are clean on the changed files.
ℹ️ Unrelated hourly-version repair rides along
This PR now edits config/scripts/hourly-build-version.mjs, a release-workflow helper with no connection to OpenCode status hooks, and the PR body does not mention it. The change itself is sound; it is worth confirming that bundling it here (rather than a separate PR or body note) is intentional.
Technical details
# Unrelated hourly-version repair bundled into an OpenCode PR
## Affected sites
- `config/scripts/hourly-build-version.mjs:82-87` — new `packageVersion` option used only by tests; the production caller at line 103 omits it.
- `config/scripts/hourly-build-version.test.mjs:130-156` — tests inject fixed versions to avoid reading the working-tree `package.json`.
## Why it is needed
- The prior un-mocked test read the real `package.json` (now `1.4.214`) and expected base `1.4.203`, so it fails as soon as the package version outranks the published tags. `main`'s copy carries the same fragility (last touched by `1ba9801574`).
## Open questions for the human
- Should this be a separate PR, or is there a shared CI repair it is meant to follow?
- The default `package.json`-read path is now unexercised by tests; acceptable, or worth a narrow assertion?DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
The delta since Pullfrog's prior review (1328f20e) is a merge of main plus one unrelated Windows-only test repair. The OpenCode hook-cleanup source, its lifetime test, and the reliability-gate entry are byte-identical to the previously reviewed head.
- NSIS restricted-policy probe hardened —
config/scripts/nsis-process-check.test.mjsnow runs aTest-OrcaRestrictedPolicyhelper (invalid scope must return$false, Process/default scopes must beRestricted), stripsPSModulePathfrom the child env, and reports richer failures viaJSON.stringify(result). - Hourly-version ride-along dropped — base
mainadvanced and now carries the same hourly build-version isolation, soconfig/scripts/hourly-build-version.{mjs,test.mjs}no longer appear in this PR's diff. - Merge of
main— no interaction with the OpenCode fix; theagent-session.opencode2-hook-cleanupgate survives as exactly one entry.
Verified at head 2753c760: status-plugin-setup-lifetime.test.ts (10), hook-service.test.ts (34), and nsis-process-check.test.mjs (2 pass, 4 skipped on Linux) all green; check:reliability-gates passes 134 gates.
ℹ️ Unrelated NSIS test repair rides along, and the PR description is now stale
This branch is again carrying a change with no connection to OpenCode status hooks, and the PR body still advertises the hourly-version correction that is no longer part of the diff. Mergeable as-is; confirming the intent is all that is needed.
Technical details
# Unrelated CI ride-along and stale PR description
## Affected sites
- `config/scripts/nsis-process-check.test.mjs:51-109` — new restricted-policy probe; no production file touched.
- PR body "Shared hourly CI prerequisite" and the behavior table — still describes `config/scripts/hourly-build-version.{mjs,test.mjs}`, which base `main` (`408499ec`) now carries, so those files are absent from this diff.
## Required outcome
- None for correctness. The NSIS probe is Windows-gated and does not run on the Linux PR lane.
## Open questions for the human
- Is the NSIS repair meant to ride on this PR as a shared CI prerequisite (like the earlier #23274 hourly fix), or does it belong on its own branch / PR?
- Should the PR body be refreshed to drop the hourly-version section and mention the NSIS change so the diff and description agree?DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

ELI5
When OpenCode 2 prompt setup or cleanup failed, Orca could keep abandoned status hooks and leave the agent looking busy or blocked. Release those hooks through the existing cleanup path, while preserving any other active instance.
What Changed
The generated setup retains its acquired hook owner for setup-error cleanup. Nested
finallyblocks keep a throwing or rejecting prompt disposer from skipping event-consumption and hook cleanup once earlier work settles. Errors remain contained so cleanup does not fail the plugin. Both generatedopencodeandopencode2variants use this setup API.Why
A shared
tryblock skipped later cleanup after the first rejection. Reusing the existing disposer preserves ownership and delivery order without adding a second status store, cleanup mechanism or timer. Malformed form handling is outside this change.Negative user-facing trade-off: failed setup and unload can now take longer. A nonsettling prompt disposer, event iterator, hook disposer or earlier shared delivery can keep completion pending indefinitely. No global deadline is added. This is a separate trade-off PR. Successful startup gains no await; no polling, scans or subprocesses are added. Owner counts are deterministic resource evidence, not a CPU, latency or heap-byte benchmark.
Linked Issue
N/A — PR only.
Visual Proof
N/A — generated plugin cleanup, with no renderer or layout change. Before/after evidence checks actual outgoing Busy, permission and Idle payloads and retained owners; no rendered app behavior is claimed.
Windows test correction
The installer probe test now removes the runner's inherited PowerShell 7 module paths from its Windows PowerShell child. It requires Process and effective Restricted-policy verification, rejects a deliberately invalid policy scope, and checks execution receipts for the policy and injected query error. The production installer query, profiles and 20-second deadline stay unchanged.
Hosted comparison 36275214909 shows all four inherited-path probes failing the strict policy check and all four native-path probes passing. The previous guard could continue after module loading failed, creating false success. This establishes the fixture defect; it does not establish the cause of the earlier 20-second timeout.
The final fixture passes the complete Windows packaging job: 501 tests pass, including all six installer-probe tests; 23 unrelated platform cases skip. The initial 32-bit probe finishes in 8.2 seconds. A separate negative control restores only the old unchecked guard and makes all four native cases fail with the expected invalid-scope exit 11, without timeout or query execution. The saved original fixture matches the final file byte-for-byte.
Testing
Ten permanent generated-wrapper tests: original 7 failures/3 controls, candidate 10 pass. Existing setup/lineage suites add 49 passing cases, for 59 passing tests on the fresh-main snapshot.
Independent review executes the complete generated plugins with synthetic external SDK/event/environment/fetch boundaries, without mocking their factory or disposal logic. Candidate 16 pass; original 14 fail/2 ordinary-unload controls pass. Cases cover final status, late callbacks, multiple owners, repeated failures, shared delivery waits and abort-insensitive iterators. All 16 also pass when rerun against the isolated fresh-main candidate.
The generated-plugin byte hash was updated after reviewing the intentional source change. On the current main integration, 82 focused tests pass, including the portable NSIS contracts; all four Windows cases subsequently pass in the hosted packaging job linked above. All changed-code quality checks and dedicated anti-slop lint pass. Earlier Node typecheck and reliability-manifest validation also passed. Runs use
ORCA_BACKGROUND_LAUNCH=1; no real profile, provider, hook server or app is used.Review
Merge risk: medium. The patch is narrow, but newly reached cleanup changes failure completion and published status. Independent review found no blocker for the plugin change. The branch now includes current main and the Windows test correction above; all 40 checks on merged head
2753c760132cf4a559b2c4419c059cbd20d442cepassed or were correctly skipped, including all ten persistence lanes and aggregate verification.Reliability invariant
agent-session.opencode2-hook-cleanup: throwing/rejecting stages cannot skip the acquired hook disposer once earlier work settles; one owner's cleanup preserves another owner's live work, and final status follows older queued delivery. Failure source is the reproduced generated-wrapper registration/unload path. The new experimental gate checks counts and ordering; independent outgoing-payload tests add ownership evidence. Named fault-injection tests and baseline/candidate logs provide diagnostics; no new telemetry is emitted.Newly reached disposal can publish existing Idle or surviving-owner Busy/permission payloads where failure previously left stale status. This is a publication-content change under the wire compatibility rule. Normal disposal already uses those fields, vocabulary, endpoint and authority; no new opcode or reader requirement is added. Old-client transport behavior was assessed from source, not executed. Cleanup does not interpret disconnection as process death or add reader-side status authority.
Agent skill upstream boundary
Notes
Nonsettling work, actual provider resource/heap retention, failed network delivery, malformed factory return values and malformed forms remain outside the proof. Long-running provider soak remains outside this proof.
Checklist