Skip to content

fix: dispose OpenCode 2 hooks after prompt setup and cleanup failures - #23209

Merged
OrcaWin merged 12 commits into
mainfrom
nwparker/perf-09-25-opencode2-hook-cleanup
Sep 26, 2026
Merged

OrcaWin merged 12 commits into
mainfrom
nwparker/perf-09-25-opencode2-hook-cleanup

Conversation

@nwparker

@nwparker nwparker commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

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 finally blocks 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 generated opencode and opencode2 variants use this setup API.

Why

A shared try block 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.

Behavior Before After
Hook disposal after registration or prompt-cleanup failure 0 1
Active hook owners after 12 failed registrations 12 0
Rejecting unload while Busy or waiting for permission Old status retained Existing final Idle publication
Failed instance B while A is still busy B's wait retained A remains Busy
Ordinary unload One prompt/hook disposal each Same
Failed setup/unload completion Skips later cleanup Waits for existing cleanup/delivery; may remain pending indefinitely

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

  • Live provider/app validation
  • Automated tests added

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 2753c760132cf4a559b2c4419c059cbd20d442ce passed 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.

Surface Coverage
Generated JavaScript on macOS Both variants, mocked external boundaries
Local/daemon PTY liveness, attach, input and exit Unaffected by this diff; not exercised
SSH/remote and WSL plugin hosts Host-side path retained; live execution gap
Mobile/relay readers No protocol shape/routing change; end-to-end delivery gap
Linux/Windows native and packaged execution Validation gap
Folder workspace Synthetic folder identifier; no Git/path dependency added

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

  • Not applicable.

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

  • This PR is small and focused
  • Before/after, mechanism and choice of approach explained
  • Visual proof is N/A with reason
  • Self-reviewed and independently reviewed for correctness, security and performance
  • Cross-platform, SSH/remote and folder workspace impact considered
  • Full CI passed, including static analysis, typecheck, eight unit shards, both packaging jobs and ten persistence lanes.

@coderabbitai

coderabbitai Bot commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

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 configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 7cdf9e92-6ddc-464f-9334-ac1a75843618

📥 Commits

Reviewing files that changed from the base of the PR and between 01c4ee2 and 2753c76.

📒 Files selected for processing (2)
  • config/reliability-gates.jsonc
  • config/scripts/nsis-process-check.test.mjs

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 8 remain after this review.


📝 Walkthrough

Walkthrough

OpenCode 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 2753c

The cleanup and Windows policy-probe changes appear ready to merge after normal checks.

Security Architecture Review

Security architecture risk: 🔵 Low · up to 2753c

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
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — The changed production behavior is confined to an acquired plugin hook owner and status it may publish; the Windows policy-probe change is test-scoped. No new caller with greater authority or attacker-controlled entrypoint was established.

Trust Boundaries and Controls

  • observed — The Windows probe retains the shared process-execution boundary and adds assertions about Restricted policy; the test’s injected CIM failure is a local fixture.

Resilience and Maintainability Implications

  • observed — Cleanup remains best-effort rather than a guaranteed terminal transition: setup and unload suppress disposal errors, and the existing factory clears active ownership only after asynchronous status work. The reliability record also identifies non-abortable operations as a remaining delay risk.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning 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 … Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title is concise, specific, and accurately describes the main OpenCode 2 hook cleanup change.
Description check ✅ Passed The description is complete and follows the required template. It explains the user impact, mechanism, rationale, testing, risks, known gaps, and checklist status. The Linked Issue field is marked N/A…
Full details: Docstring Coverage

Explanation

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.)

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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 — setupOpenCode2Status hoists the acquired hook factory to let hooks; and disposes it from the setup catch, so a throwing or rejecting ctx.session.hook("prompt", …) no longer strands an active hook owner.
  • Ordered cleanup under failure — the unload closure nests try/finally so 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.ts executes 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) to config/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.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ 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.ts now expects c81893814f08… for getOpenCodePluginSource(), 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) and status-plugin-setup-lifetime.test.ts (10 tests) both pass at this head.

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ 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") and 5e9b3d0c2e ("Adding..."), plus a trailing comma on commentTooLarge, across all six locale catalogs. Values match the source fallbacks in DiffCommentDraftCard.tsx.
  • Reliability gate preserved through the main merge — agent-session.opencode2-hook-cleanup in config/reliability-gates.jsonc is 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) and hook-service.test.ts (34) pass.

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ 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 — getHourlyBuildIdentity gained an optional packageVersion option; when supplied it is used directly, otherwise the helper still reads package.json. The CLI entry point omits it, so release behavior is unchanged.
  • Hourly build tests made deterministic — the two getHourlyBuildIdentity cases now pass a fixed version (1.4.201 / 1.4.214) through the new option instead of depending on the working tree's package.json, and a new case covers a package version that outruns the published tags.
  • Merge-up churn — config/reliability-gates.jsonc retains the agent-session.opencode2-hook-cleanup gate and is oxfmt-clean; the locale catalogs an earlier commit restored no longer appear because main now carries them; a trailing blank line left hook-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?

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

✅ 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.mjs now runs a Test-OrcaRestrictedPolicy helper (invalid scope must return $false, Process/default scopes must be Restricted), strips PSModulePath from the child env, and reports richer failures via JSON.stringify(result).
  • Hourly-version ride-along dropped — base main advanced and now carries the same hourly build-version isolation, so config/scripts/hourly-build-version.{mjs,test.mjs} no longer appear in this PR's diff.
  • Merge of main — no interaction with the OpenCode fix; the agent-session.opencode2-hook-cleanup gate 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?

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@OrcaWin
OrcaWin merged commit ee6281f into main Sep 26, 2026
40 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants