Repository navigation
refactor(daemon): consolidate snapshot-safe listener delivery - #20945
Conversation
There was a problem hiding this comment.
ℹ️ No blocking issues. The refactor is behavior-preserving and well covered; one optional observation below.
Reviewed changes
- New emission helpers —
daemon-pty-listener-emission.tsaddsemitPtyListeners(slice-then-emit) andcreatePtyExitPayload, centralizing the snapshot-safe iteration pattern and exit-payload construction. - Five fan-out sites consolidated — adapter data/exit, recovery background-stream, subscription write-unavailable, and
fanoutSyntheticExitsall route through the helpers, dropping the repeatedunicorn/no-useless-spreaddisable comments. - Listener removal unified — the four
onData/onBackgroundStreamEvent/onExit/onWriteUnavailableunsubscribers now delegate toremoveDaemonListener. - Payload types unified —
dataListeners/exitListenersare now typed withDaemonPtyRouterDataEvent/DaemonPtyRouterExitEventrather than inline literals. - Test strengthened — the single synthetic-exit ordering test is replaced by an
it.each(['synthetic','daemon'])case asserting snapshot order, deferral of listeners added mid-emission, honored unsubscription, and per-listener payload isolation.
I verified the refactor is equivalent to the code it replaces: optional incarnationId/cause are still omitted when falsy, each listener still receives a fresh payload object (so one listener's mutation cannot leak to the next), the write-unavailable per-listener try/catch and the abort-on-throw semantics of the other fan-outs are unchanged, and fanoutSyntheticExits now reads sessionIncarnations.get(id) once instead of twice with no behavioral effect. pnpm tc:node is clean, daemon-pty-adapter.test.ts passes 50/50, and the full src/main/daemon suite passes (1862 passed / 30 skipped).
ℹ️ Two same-shape fan-out loops remain in the router
DaemonPtyAdapterSubscriptionFanout.onData/onExit still forward through for (const listener of this.dataListeners) / for (const listener of this.exitListeners), which is the exact non-snapshot iteration this PR centralizes: a listener that unsubscribes during an emission shifts the array and can cause the next listener to be skipped. This is pre-existing and outside the diff, so it is not a blocker, but since the new helper exists it would be a one-line fold-in at src/main/daemon/daemon-pty-adapter-subscription-fanout.ts:19,25.
Technical details
# Router fan-out iterates the live listener array
## Affected sites
- `src/main/daemon/daemon-pty-adapter-subscription-fanout.ts:19` — `for (const listener of this.dataListeners)`
- `src/main/daemon/daemon-pty-adapter-subscription-fanout.ts:25` — `for (const listener of this.exitListeners)`
- (related, lower value) `src/main/daemon/daemon-client-listener-registry.ts:17` — `DaemonClientListeners.each`
## Why it matters
Every other daemon PTY fan-out was spread-copied precisely because "listeners may unsubscribe
during iteration" (the comments this PR removed). These two loops were missed, so an unsubscribe
from inside a callback can skip the following listener. The new `emitPtyListeners` helper already
encodes the fix.
## Required outcome
Router fan-out emits behave like the other five sites: each emission iterates a snapshot taken at
emit time, and unsubscribes apply to the next emission.
## Suggested approach
Replace both loops with `emitPtyListeners(this.dataListeners, (listener) => listener(payload))`
(and the exit equivalent), and optionally reuse `removeDaemonListener` for their unsubscribers for
consistency. Not required for this PR to merge.DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
|
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 (7)
Included review availability: Your plan provides up to 10 included reviews per hour; 7 remain after this review. 📝 WalkthroughWalkthroughThe change adds shared helpers for snapshot-based listener emission and exit-payload construction. Daemon PTY adapters, recovery, subscriptions, and session inventory use these helpers. Runtime listener payloads use shared router event types. Tests cover synthetic and daemon exits, payload isolation, subscription changes during emission, and listener order. Priority: ⬇️ Low Merge Risk: ⚪ Minimal · up to The refactor preserves the listener and exit-payload contracts for valid daemon and synthetic exits, with no actionable merge risk identified. 🚥 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 |
…ai#20945) Consolidate snapshot-safe daemon PTY listener delivery and exit payload construction. Reuse listener removal and event types while preserving callback ordering, payload isolation, optional exit fields, and recovery exception handling. Fixes stablyai#10984. Adapted from stablyai#11119. Co-authored-by: MumuTW <42820974+MumuTW@users.noreply.github.com>

ELI5
Keep terminal event delivery consistent by defining listener snapshotting and exit payload construction once.
What Changed
Consolidate five snapshot-safe listener loops, reuse the existing listener-removal function and event types, and share exit payload construction. Production code decreases by 32 lines; stronger tests add 26 lines, for 6 fewer lines overall (+86 / -92).
Why
Subscriptions can change during callbacks. Centralizing snapshotting keeps those changes effective on the next emission, while preserving independent data/exit payloads, shared background payloads, exit causes, and write-unavailable error handling.
Linked Issue
Fixes #10984. Adapted from #11119 by @MumuTW.
Visual Proof
N/A — no visual or interaction changes.
Testing
Review
Preserved optional incarnation/cause omission, shallow payload identity, abort-on-throw behavior, and write-unavailable catch/continue recovery. No host routing, protocol, path, platform, workspace, or security-boundary changes. Current main equals the branchpoint at review time.
Agent skill upstream boundary
Notes
Original PR author credited in the commit:
Co-authored-by: MumuTW 42820974+MumuTW@users.noreply.github.com
Checklist