Skip to content

refactor(daemon): consolidate snapshot-safe listener delivery - #20945

Merged
nwparker merged 1 commit into
mainfrom
nwparker/refactor-daemon-pty-adapter-writes-the-same-list
Sep 16, 2026
Merged

nwparker merged 1 commit into
mainfrom
nwparker/refactor-daemon-pty-adapter-writes-the-same-list

Conversation

@nwparker

@nwparker nwparker commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 1 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​41 $\color{#cf222e}{\Huge{\mathbf{−}}}$​15 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​26
Prod 6 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​45 $\color{#cf222e}{\Huge{\mathbf{−}}}$​77 $\color{#cf222e}{\Huge{\mathbf{−}}}$​32

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

  • Automated tests updated: both real and synthetic exits preserve snapshot order, defer newly added listeners, honor subsequent unsubscription, and isolate payload mutations.
  • 263 tests passed across 17 daemon PTY test files; the final test adjustment was rerun with all 50 core adapter tests passing.
  • Node typecheck, touched-file lint/formatting, changed-code quality gate, and diff whitespace checks passed.
  • Independent behavior audit found no regressions; reviewed every production change against the branchpoint.
  • Validated locally on macOS. Full build, full repository tests, Windows/Linux, and SSH execution were not run locally.

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

  • Not applicable; no upstream skill content copied.

Notes

Original PR author credited in the commit:

Co-authored-by: MumuTW 42820974+MumuTW@users.noreply.github.com

Checklist

  • Small and focused; explained what changed and why
  • N/A for visual proof with reason
  • Self-reviewed and independently audited for correctness and performance
  • Cross-platform, SSH/remote, and compatibility impact considered
  • Full lint, typecheck, test, and build suite (targeted validation above; remaining coverage deferred to CI)

Adapt the listener snapshot and exit payload consolidation from PR #11119 to the split adapter modules, preserving exit causes and write-unavailable error handling. Addresses #10984.

Co-authored-by: MumuTW <42820974+MumuTW@users.noreply.github.com>

@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 blocking issues. The refactor is behavior-preserving and well covered; one optional observation below.

Reviewed changes

  • New emission helpers — daemon-pty-listener-emission.ts adds emitPtyListeners (slice-then-emit) and createPtyExitPayload, 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 fanoutSyntheticExits all route through the helpers, dropping the repeated unicorn/no-useless-spread disable comments.
  • Listener removal unified — the four onData/onBackgroundStreamEvent/onExit/onWriteUnavailable unsubscribers now delegate to removeDaemonListener.
  • Payload types unified — dataListeners/exitListeners are now typed with DaemonPtyRouterDataEvent/DaemonPtyRouterExitEvent rather 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.

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

@coderabbitai

coderabbitai Bot commented Sep 16, 2026

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

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: 36fee267-9b70-46b1-b0b7-6b0d0e10ac0f

📥 Commits

Reviewing files that changed from the base of the PR and between 07c7606 and ba3a0b5.

📒 Files selected for processing (7)
  • src/main/daemon/daemon-pty-adapter.test.ts
  • src/main/daemon/daemon-pty-adapter.ts
  • src/main/daemon/daemon-pty-daemon-recovery.ts
  • src/main/daemon/daemon-pty-event-subscriptions.ts
  • src/main/daemon/daemon-pty-listener-emission.ts
  • src/main/daemon/daemon-pty-runtime-state.ts
  • src/main/daemon/daemon-pty-session-inventory.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 7 remain after this review.


📝 Walkthrough

Walkthrough

The 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 ba3a0

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)

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 2 functions across 7 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly describes the main change: centralizing snapshot-safe listener delivery in the daemon.
Description check ✅ Passed The description follows the required structure, explains the change and reason, links issue #10984, documents testing and limitations, marks visual proof as not applicable, and completes the main chec…
Linked Issues check ✅ Passed Issue #10984 requires one snapshot-safe listener fanout helper and one shared exit-payload builder. The PR adds emitPtyListeners, which copies the listener array before callback execution, and repla…
Out of Scope Changes check ✅ Passed The changed files support the listener-fanout refactor in issue #10984. The listener registry cleanup and shared router event types remove duplicated subscription and payload definitions required by t…
  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

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.

@nwparker
nwparker merged commit 7f23d44 into main Sep 16, 2026
34 checks passed
ivanvykopal pushed a commit to ivanvykopal/orca that referenced this pull request Sep 20, 2026
…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>
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.

refactor: daemon-pty-adapter writes the same listener-fanout idiom four times, each with its own copy of the same lint suppression

1 participant