Repository navigation
fix: stop stale runtime event work after renderer cleanup - #23066
Conversation
|
Navigate logical layers of code changes, visualize relationships, and explore their blast radius. 📝 WalkthroughWalkthroughThe runtime event sync manager tracks subscription attempt ownership and stops stale attempts from delivering events. The IPC bridge skips replay invalidation for subscriptions that are no longer current. New tests cover setup, cleanup, replacement, restart, and replay scenarios. A reliability gate records the ownership invariant, test evidence, budgets, known gaps, and promotion and demotion criteria. Priority: ➖ Normal Severity of issue fixed: Medium Merge Risk: 🟡 Moderate · up to A reentrant runtime update can still process work for an environment that is no longer desired and discard the replacement subscription. The Japanese and Korean prompts also misstate who the note is for; resolve the stale-work issue before merging. Security Architecture ReviewSecurity architecture risk: 🔵 Low · up to The change prevents outdated runtime subscriptions from starting new refresh work. No new security exposure was identified, but live and cross-platform lifecycle behavior remains incompletely verified. Retained concerns Security review detailsSecurity Blast Radius
Trust Boundaries and Controls
Resilience and Maintainability Implications
🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
Full details: Out of Scope Changes checkExplanation The runtime subscription changes, reliability gate, and tests support the historical stale-work behavior. The additions to Full details: Docstring CoverageExplanation Docstring coverage is 20.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 5 functions across 4 files. (6 skipped: 6 unsupported.)
✨ Finishing Touches 💡 1⚔️ Resolve merge conflicts 💡
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: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: 1694b180-92e3-4481-8649-dfc66adb6933
📒 Files selected for processing (5)
config/reliability-gates.jsoncsrc/renderer/src/hooks/ipc-events/runtime-client-ipc-bridge-ownership.test.tssrc/renderer/src/hooks/ipc-events/runtime-client-ipc-bridge.tssrc/renderer/src/hooks/runtime-client-events-sync-ownership.test.tssrc/renderer/src/hooks/runtime-client-events-sync.ts
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 0 remain after this review.
| if (syncGeneration !== generation) { | ||
| return |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy lift
Stop an outer sync when a nested sync replaces its desired set.
If A's initial event changes the desired IDs from ['A', 'B'] to ['C'] and calls sync(), the nested pass starts C. Neither pass changes generation. The outer pass then starts B and deletes C from pending using its stale desiredIds. C's late handle is disposed, while B can deliver an initial event after B is no longer desired. Track sync invocations separately from the stop generation, and end the outer pass when a nested pass takes ownership. Apply that check before starting further subscriptions and before pending cleanup.
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
- Ownership token replaces ad-hoc checks —
createRuntimeClientEventsSyncnow stores a sharedSubscriptionToken({key, generation}) inpendingand on each settledsubscriptionsentry, and exposesisCurrent()to the caller'ssubscribe. - Event delivery gated on ownership — the onEvent wrapper only calls
deps.onEventwhenisCurrent()is true, so an initial frame still arrives before setup settles, but a stopped/replaced/rekeyed attempt cannot dispatch. - Replay recovery gated on ownership —
runtime-client-ipc-bridge.tsreturns early from the reconnect/replayinvalidateRuntimeClientEventReplay(...)callback when!isCurrent(). - Reentrant reconcile hardening —
sync()capturessyncGenerationand aborts both reconcile loops if a synchronousstop()/restart bumpsgeneration, and teardown now deletes fromsubscriptionsbefore callingunsubscribe()so a callback that reenters delivery is rejected. - New regression tests + reliability gate — two focused test files and the
runtime-events.renderer-subscription-ownershipexperimental gate;node config/scripts/check-reliability-gates.mjspasses.
I traced the isCurrent predicate against the stop, same-ID re-pair, rekey, late-rejection, overwrite-orphan, and synchronous-stop/restart paths. It correctly admits synchronous initial frames and settled live frames while dropping every non-owning attempt, and the syncGeneration early return leaves the latest store-driven reconcile in charge. The added tests use exact assertions (not.toHaveBeenCalled, toEqual) rather than loose ones, so they pin the behavior they claim. The focused suites pass locally (25 tests across 3 files).
The gate's knownGaps already document the missing native/live-peer/rendered coverage and the fact that already-admitted async handlers are not canceled.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
Actionable comments posted: 2
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: a7c1ca4e-df5f-4a0d-aed1-e374d6f0cca0
📒 Files selected for processing (6)
src/renderer/src/i18n/locales/en.jsonsrc/renderer/src/i18n/locales/es.jsonsrc/renderer/src/i18n/locales/fr.jsonsrc/renderer/src/i18n/locales/ja.jsonsrc/renderer/src/i18n/locales/ko.jsonsrc/renderer/src/i18n/locales/zh.json
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 1 remain after this review.
| "c845170b3b": "行 {{value0}}-{{value1}}", | ||
| "commentTooLarge": "コメントが大きすぎるため安全に送信できません。" | ||
| "commentTooLarge": "コメントが大きすぎるため安全に送信できません。", | ||
| "f6c449191e": "AI に関するメモを追加", |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Clarify that the note is for the AI.
Line 15500, AI に関するメモを追加, reads as “Add a note about AI.” The placeholder should tell users that the note is for the AI. Consider AIへのメモを追加.
| "c845170b3b": "라인 {{value0}}-{{value1}}", | ||
| "commentTooLarge": "댓글이 너무 길어 안전하게 제출할 수 없습니다." | ||
| "commentTooLarge": "댓글이 너무 길어 안전하게 제출할 수 없습니다.", | ||
| "f6c449191e": "AI에 대한 메모 추가", |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Use wording that means “a note for the AI.”
AI에 대한 메모 추가 can read as “add a note about AI.” Replace it with AI에게 남길 메모.
There was a problem hiding this comment.
ℹ️ No issues in the runtime-event ownership changes — the new delta is an unrelated locale merge. One process note and a translation nitpick below.
Reviewed changes
Re-reviewed the commits landed since the last Pullfrog review (6f7d64ccb3..3e272a479f) against base main (668fa71906).
- Verified the ownership code is unchanged —
runtime-client-events-sync.ts,runtime-client-ipc-bridge.ts, and both ownership test files are byte-identical to the previously reviewed6f7d64ccb3, so the prior review of the ownership logic still stands. - Re-confirmed the reliability gate survived the merge — the
runtime-events.renderer-subscription-ownershipblock is byte-identical to6f7d64ccb3(an earliermainmerge briefly dropped it;3e272a479frestores it) andcheck-reliability-gates.mjspasses (129 gates). - Swept in unrelated locale entries — a merge of branch
ci/fix-note-catalogadded diff-comment note keys to the six locale files (see below).
ℹ️ An unrelated open PR's commit is merged into this branch
Commit 21741ca353 (fix(i18n): restore diff note draft catalog entries) is the head of open PR #23256 on branch ci/fix-note-catalog, and it entered this branch through the merge d98e245b9a. That commit is the source of all six locale-file changes in this PR's diff; they are unrelated to runtime event ownership. If this merges first it lands #23256's content and that PR will need to rebase or close — better to drop the commit from this branch, or confirm the restore is intended here.
Technical details
# Unrelated locale changes carried by this PR
## Affected sites
- `src/renderer/src/i18n/locales/{en,es,fr,ja,ko,zh}.json` — adds `f6c449191e` ("Add note for the AI"), `5fa4bfebaa` ("Add note") and `5e9b3d0c2e` ("Adding...") under `DiffCommentPopover`, and adds the trailing comma to `commentTooLarge`.
## Provenance
- `d98e245b9a`'s second parent is `21741ca353`, which is the head of open PR #23256 (`ci/fix-note-catalog`).
- `git diff 6f7d64ccb3 HEAD -- <runtime files>` is empty; only the locale files differ from the prior reviewed revision.
## Required outcome
- This PR's diff should contain only runtime-event ownership changes, or the locale restore should be explicitly owned here.
## Open questions for the human
- Was `ci/fix-note-catalog` merged deliberately, or swept in by a `main` merge?ℹ️ Nitpicks
ja.json:15500andko.json:15500render "Add note for the AI" as a note about the AI (AI に関する…/AI에 대한…). If the restore is kept in this PR,AI へメモを追加/AI를 위한 메모 추가matches a note addressed to the agent.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
Re-reviewed the commits landed since the last Pullfrog review (3e272a479f..11c7d0e857) against base main (abc4cb0f32).
- Dropped the unrelated locale merge — the six i18n files from
#23256are no longer in the PR diff, resolving the scope contamination flagged in the prior review. - Preserved every reliability gate through the main merge — verified HEAD carries exactly main's 129 gate ids plus
runtime-events.renderer-subscription-ownership(130 total, no duplicates), andnode config/scripts/check-reliability-gates.mjspasses; theterminal-preview.connection-settings-ownershipgate frommainand the PR's own gate both survive. - Added phase diagnostics to the WebRTC packaging probe — the inline Electron script now records the last-entered phase and
protectedGuest, and writes them intoresult.jsonon the existing 20s deadline and on error, so a stalled probe reports where it stopped. The timeout and network-security assertions are unchanged; the generated script still parses.
The runtime-event ownership source, its two ownership test files, and the gate definition remain byte-identical to the previously reviewed 6f7d64ccb3, so the earlier review of that logic still stands. The six ownership suites pass locally (41 tests).
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
Re-reviewed the commits landed since the last Pullfrog review (11c7d0e857..f864537cca) against base main.
- Made nested reconciliation last-writer-wins —
sync()now stamps a monotonicsyncInvocationand each of its loops returns once a reentrantsync()has started, so the outer pass stops acting on its staledesiredIdsinstead of deleting the nested pass's new pending/subscription entries. - Detached stopped handles before disposing them —
stop()snapshots and clearssubscriptions/pendingbefore callingunsubscribe, so a subscription a cleanup callback starts reentrantly is retained rather than wiped by a laterclear(). - Added four regression tests — nested desired replacement (single and multi environment), empty-desired with a reentrant restore, and stop/restart reentrancy. I confirmed these fail against
11c7d0e857's source (4 failed / 10 passed) and pass with the fix. - Isolated the hourly-build identity tests —
getHourlyBuildIdentityaccepts an injectablepackageVersion, so the identity tests no longer read the realpackage.json, with a new base-floor case. The production CLI entrypoint is unchanged.
The ownership source, bridge, gate definition, and WebRTC probe diagnostics are unchanged from the previously reviewed 11c7d0e857. Focused suites pass locally (34 tests / 3 files).
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

ELI5
An old listener now checks that it still owns a connection before acting on delayed messages. Closing or replacing it stops obsolete refresh work immediately, even when setup has not finished.
What Changed
Runtime-event delivery and reconnect recovery reuse the subscription manager's existing attempt token and stop generation. Initial messages still arrive before setup finishes for the current owner. Stopped, removed or replaced owners cannot start new work, and late setup handles still dispose. Cleanup also handles a synchronous stop/restart without deleting the new owner's subscription.
The WebRTC packaging probe now records its current phase when it reaches its existing deadline, so failures no longer end with an unexplained missing result. Its timeout and all network-security assertions are unchanged.
Why
Previously, ownership was checked when setup returned, leaving a window where a closed listener could keep clearing caches and dispatching provider reads. Waiting to accept messages until setup finishes would lose valid initial frames. Reusing the existing token avoids scanning host lists or adding a cache, timer or wire protocol.
Linked Issue
Fixes #23065
Visual Proof
N/A — internal subscription ownership; no layout or interaction flow changed. No app was launched, and rendered latency remains unmeasured.
Performance proof
A composed test using the actual bridge, manager, runtime adapter, preload dispatcher and Linear actions holds fake IPC setup, closes the bridge, then sends 100 stale messages: 100→0 provider-read dispatches and 100→0 cache publications. Both versions dispose the late handle. These are measured application operations, not external network-request or frame-time claims.
Shared hourly CI prerequisite
The branch also carries the shared hourly-build fixture correction from #23274. Historical package-version inputs are explicit, with exact version/build-number assertions retained and a newer-package control. Default build commands still read package.json; the dedicated no-module-mocking lint rule stays enabled.
Testing
ORCA_BACKGROUND_LAUNCH=1 pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/hooks/runtime-client-events-sync-ownership.test.ts src/renderer/src/hooks/ipc-events/runtime-client-ipc-bridge-ownership.test.ts src/renderer/src/hooks/runtime-client-events-sync.test.ts src/renderer/src/hooks/ipc-events/runtime-reconnect-host-status.test.ts src/renderer/src/runtime/runtime-client-events.test.ts src/preload/runtime-environment-subscriptions.test.ts.The previous Linux package run stopped inside the baseline WebRTC probe after 20 seconds, before testing the protected guest. The exact stalled phase was absent from that log. The new diagnostics pass local lint, formatting, and generated-code syntax checks; hosted validation is pending. This diagnostic change is not a claimed fix for the original timeout.
Reentrant ownership validation
Nested synchronization now supersedes the older reconciliation pass before it can create or remove further subscriptions. Stop detaches the old handles before calling their disposers, preserving subscriptions started reentrantly by cleanup. Four regression cases fail on the prior code; all 45 related tests, web typecheck, changed-code quality, and the dedicated anti-slop check pass. Independent review also checked same-ID replacement and retry ownership.
Review
Merge risk: low to medium. Subscription ownership and reconnect ordering are sensitive. Independent review caught a reentrant restart edge; the corrected implementation passes both permanent and independent regressions. Current same-ID re-pair recovery still works after generation-only SSH invalidation.
Negative user-facing trade-offs — isolated in this PR: each live event adds a constant ownership check (at most two map lookups), and a settled subscription retains a token reference plus an attempt guard closure. A paired synthetic benchmark measured about +0.026 ms per 10,000 pending events and +0.062 ms per 10,000 settled events. Those tiny timing differences can include noise; the added operations are the reliable cost. No UI slowdown or heap-size benefit is claimed.
Obsolete one-shot events are ignored and are not replayed by this fix. Work admitted before cleanup can still finish; physical pending listeners still wait for setup settlement or timeout, and pending error callbacks can still log.
Reliability: experimental gate
runtime-events.renderer-subscription-ownershiprequires zero obsolete dispatch/publication/recovery, valid early/current delivery, independent host survival and late handle disposal. Evidence is deterministic callback/resource counts; no new telemetry. The gate records missing native/rendered/live-peer coverage and requires CI soak before promotion.Agent skill upstream boundary
Notes
No producer, message shape, execution-host authority, PTY state, Git provider, path or keyboard behavior changes. Folder and Git workspaces share the same owner check; folder refresh forwarding has an independent composed test.
Checklist