Skip to content

fix(daemon): self-heal write routing for undiscovered legacy sessions - #7456

Closed
brennanb2025 wants to merge 1 commit into
mainfrom
brennanb2025/fix-daemon-router-legacy-write-routing
Closed

brennanb2025 wants to merge 1 commit into
mainfrom
brennanb2025/fix-daemon-router-legacy-write-routing

Conversation

@brennanb2025

Copy link
Copy Markdown
Contributor

Problem

After an update that bumps the daemon protocol version while a previous-protocol daemon survives (holding live terminal sessions), adopted terminals stream live output but accept no keyboard input. Repro'd in production going v1.4.124-rc.1 (protocol v18) → v1.4.124-rc.2.perf (protocol v19): the old v18 daemon kept running with the codex/pwsh PTYs, output continued to stream, but every keystroke vanished.

Root cause

DaemonPtyRouter treats reads and writes asymmetrically:

  • Reads (onData, hasPty, listProcesses) fan out across all adapters (current + legacy).
  • Writes/resizes route through adapterFor(), which consulted a sessionAdapters map populated only by the one-shot boot passes (discoverLegacySessions() / reconcileOnStartup() / spawn()).

When boot discovery misses a legacy-owned session — e.g. a Windows named-pipe / startup-ordering race, widened by the .perf startup reordering — adapterFor() fell back to this.current (the new daemon). Result: reads fan out so output still streams and hasPty/writeAccepted still report healthy, masking that every write was dispatched to the wrong daemon and dropped.

This is why the symptom is specifically frozen input with live output, and why it only bites on a protocol-bumping update where an old daemon is adopted as a legacy adapter.

Fix

Make adapterFor() self-heal on a routing-map miss: ask each adapter whether it owns the pty (hasPty, a synchronous Set lookup), cache the winner in sessionAdapters, and route there. Current-first precedence preserves the safe default. This mirrors the self-healing providerFor() already used by DegradedDaemonPtyProvider — the same lesson, back-ported to the router.

Scope is deliberately limited to write/resize routing; spawn() is left untouched.

Verification

  • Added a regression test reproducing the exact production shape (legacy adapter owns the session, discoverLegacySessions() never ran) — asserts writes/resizes reach the legacy adapter, not current. Confirmed it fails on the unfixed router (legacy.write called 0×) and passes with the fix.
  • Added a no-owner fallback test (routes to current when nobody owns the session).
  • Full src/main/daemon suite: no new failures (3 pre-existing, environment-dependent failures on this Windows checkout — WSL/ConPTY/path-parsing — fail identically on the clean tree).
  • oxlint clean; tsgo typecheck clean (node + cli configs).

Notes / limitations

  • Does not recover already-frozen sessions in a running process (the stale map lives in memory) — those still need a relaunch, but with this fix a relaunch reconnects reliably instead of depending on the discovery race.
  • Hardens the router against the discovery race rather than eliminating it; a follow-up could add retry/backoff to discoverLegacySessions.

DaemonPtyRouter fans out reads (onData/hasPty/listProcesses) across every
adapter, but routes writes and resizes via a sessionAdapters map that is
populated only by the one-shot discoverLegacySessions()/reconcile/spawn boot
passes. When a surviving previous-protocol daemon owns a session that boot
discovery missed (e.g. a Windows named-pipe/startup-order race, widened by the
.perf startup reordering), adapterFor() fell back to `this.current` — so output
kept streaming (reads fan out) while every keystroke was silently dispatched to
the wrong daemon and dropped. Symptom: adopted terminals stream live output but
accept no input after a protocol-bumping update.

Make adapterFor() self-heal: on a routing-map miss, ask each adapter whether it
owns the pty (synchronous Set lookup), cache the winner, and route there;
current-first precedence keeps the safe default. This mirrors the self-healing
providerFor() already used by DegradedDaemonPtyProvider.

Adds regression tests covering the undiscovered-legacy-session route and the
no-owner fallback.
@coderabbitai

coderabbitai Bot commented Jul 5, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Compact Summary: The change modifies DaemonPtyRouter.adapterFor() to probe all registered adapters via hasPty(sessionId) when a session is not already mapped in sessionAdapters, caching the discovered adapter for future lookups, and falling back to the current adapter if no owner is found. Two new Vitest test cases validate this behavior: one confirming undiscovered legacy sessions route to the legacy adapter, and one confirming sessions owned by no adapter fall back to the current adapter.

Related PRs: None identified.

Suggested labels: bug, daemon, tests

Suggested reviewers: None identified.

Poem
A rabbit hopped through session maps so wide,
Sniffing out which adapter should preside.
No longer lost when the cache came up bare,
It checks each pty with practiced care.
Tests now confirm the routing's true—
Legacy or current, the rabbit knew.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description is detailed, but it does not follow the repository template and is missing required sections like Summary, Screenshots, Testing, AI Review Report, and Security Audit. Rewrite it to use the template headings and add the missing sections, including Screenshots/No visual change, testing checklist, AI review report, security audit, and Notes.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly names the daemon routing fix for undiscovered legacy sessions and matches the main code change.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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.
✨ Finishing Touches
📝 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.

@coderabbitai coderabbitai 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.

🧹 Nitpick comments (1)
src/main/daemon/daemon-pty-router.test.ts (1)

121-147: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Consider a test for current-first precedence tie-break.

Both new tests exercise mutually-exclusive ownership (legacy-only or no-owner). The PR explicitly states current-first precedence is preserved during self-heal, but no test exercises the case where both current and a legacy adapter report hasPty(id) === true for the same session — the scenario that actually proves iteration order (allAdapters() = [current, ...legacy]) resolves ties correctly.

✅ Suggested additional test
+  it('prefers current over legacy when both report ownership of the same session', () => {
+    const current = createAdapter('current', ['shared-session'])
+    const legacy = createAdapter('legacy', ['shared-session'])
+    const router = new DaemonPtyRouter({ current, legacy: [legacy] })
+
+    router.write('shared-session', 'input\n')
+
+    expect(current.write).toHaveBeenCalledWith('shared-session', 'input\n')
+    expect(legacy.write).not.toHaveBeenCalled()
+  })

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: f8b3334d-bc34-44e3-9127-29c4c7968259

📥 Commits

Reviewing files that changed from the base of the PR and between 8aecc0b and 6209412.

📒 Files selected for processing (2)
  • src/main/daemon/daemon-pty-router.test.ts
  • src/main/daemon/daemon-pty-router.ts

@Jinwoo-H

Jinwoo-H commented Jul 6, 2026

Copy link
Copy Markdown
Contributor

Holding note: main has reverted the entire update-survival chain this PR belongs to (#7505 backs out #7421→#7499 after three consecutive field regressions: rc.5 console flashing, rc.6 inert fix, rc.7 daemon startup failure). Please keep this unmerged — the routing it self-heals only arises when a daemon survives an update, which no longer happens on the reverted baseline. A future attempt will come as a fresh design with packaged-installer E2E validation before release.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Closing as superseded. The route-less fallback this PR self-heals is being removed at its root: the replacement fix keeps an unreachable previous daemon version in the session census as unverifiable instead of dropping it, and sends kills and writes through the resolver rather than defaulting to the current daemon.

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.

3 participants