Skip to content

fix(daemon): drop a legacy daemon that can no longer accept a connection - #24313

Closed
innocarpe wants to merge 3 commits into
stablyai:mainfrom
innocarpe:fix-24281-legacy-daemon-gone
Closed

innocarpe wants to merge 3 commits into
stablyai:mainfrom
innocarpe:fix-24281-legacy-daemon-gone

Conversation

@innocarpe

Copy link
Copy Markdown
Contributor

Description

After an app update, a preserved terminal daemon can die and leave its socket registered. worktree rm lists every routed daemon and fails closed when that leftover answers ECONNREFUSED or connect ENOENT, so every clean worktree is stuck until the app restarts.

Focused fix

  • In scope: when a legacy adapter's process list fails with a connect ECONNREFUSED or ENOENT (isDaemonEndpointGoneError), report an empty inventory, drop that adapter, and ignore a failed disconnectOnly. The next list does not ask it again.
  • Out of scope: respawning the dead daemon, and changing discoverLegacySessions.

Preserves

  • The current daemon still fails the whole list, including on ECONNREFUSED.
  • A missing token file (ENOENT with syscall open), ECONNRESET, timeouts, and protocol errors still fail closed.
  • The legacy adapter stays registered for those other errors.

Evidence

  • Test: node node_modules/vitest/vitest.mjs run --config config/vitest.config.ts src/main/daemon/daemon-pty-router-legacy-gone.test.ts src/main/daemon/daemon-pty-router.test.ts
  • 43 passed.
  • Not reproduced on a Linux AppImage upgrade. The regression covers the connect errors the report names.

User-regression-tradeoffs

  • A dead legacy socket no longer blocks removal of a clean worktree. A live daemon that cannot be listed still blocks removal.

Fixes #24281

@greptile-apps

greptile-apps Bot commented Oct 1, 2026 •

Copy link
Copy Markdown

RetriggerConfidence Score: 5/5

[Medium risk] Removes legacy daemon connections that fail to respond.

The PR appears safe to merge; no new actionable failure or outstanding previous finding was identified.

Summary

The PR treats a legacy daemon’s refused or missing connection as an empty process inventory, removes that adapter from routing and owner resolution, and detaches its data and exit listeners. Current-daemon failures and other legacy errors continue to fail closed.

Reviews (3) · Last reviewed commit: "fix(daemon): unsubscribe a legacy adapte..."

Comment thread src/main/daemon/daemon-pty-router.ts Resolved
@coderabbitai

coderabbitai Bot commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

🧰 Additional context used
📚 Code guidelines (1)
AGENTS.md — auto-discovered

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: c7abf260-7b0f-4b2b-94c0-cfc9058657ba

📥 Commits

Reviewing files that changed from the base of the PR and between b55deef0afdd055a548ca953a955d0009756c0d3 and 5a301d9.

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

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


📝 Walkthrough

Walkthrough

When listProcesses receives a gone-endpoint error from a legacy adapter, it removes that adapter from the legacy list, owner resolver, and subscription fanout. It attempts a best-effort disconnect and returns an empty inventory. Errors from the current adapter and other legacy errors still reject. Tests cover refused and missing legacy endpoints, other legacy errors, and current-adapter errors.

Priority: ➖ Normal

Severity of issue fixed: Medium

Merge Risk: ⚪ Minimal · up to 5a301

This change keeps a dead legacy daemon from blocking worktree removal. Other errors still fail closed. No concrete merge-blocking risk was identified in the reviewed changes.

Security Architecture Review

Security architecture risk: 🔵 Low · up to 5a301

The change is narrowly limited to old terminal connections and preserves blocking failures for the active connection. Risk remains low rather than minimal because connection failure alone does not establish session absence, and some retirement and recovery edge cases remain unresolved.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — The demonstrated exposure is the local router's legacy terminal inventory and dependent worktree-removal decisions. Retirement can affect each legacy adapter encountered during listing, while the current adapter is explicitly excluded. No cross-tenant, cross-service or increased-privilege attack path was established.

Trust Boundaries and Controls

  • observed — The retirement decision requires both a non-current adapter and a specifically classified connection error. It is not driven directly by terminal event payloads. Other listing failures continue to block aggregate inventory.

Resilience and Maintainability Implications

  • observed — Disconnect failure is deliberately contained so it cannot reject an otherwise successful inventory. That containment applies after registry and tracked-listener removal; it does not itself prove complete event cleanup or absence of live sessions behind an unreachable endpoint.

Hardening Proposals

  • proposed — If live sessions can survive loss of a legacy endpoint, distinguish unknown inventory from authoritative emptiness before permitting destructive worktree decisions. Retirement cleanup could also explicitly own pre-existing dynamic subscriptions rather than relying on caller disposal.
🚥 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 3 functions across 5 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 and concisely describes the main change: removing legacy daemons that can no longer accept connections.
Description check ✅ Passed The description is mostly complete. It explains the user impact, scoped behavior change, preserved error handling, testing performed, and linked issue. It omits several template sections, including Vi…
Linked Issues check ✅ Passed The PR meets the coding requirements in issue [#24281]. DaemonPtyRouter.listProcesses treats connect ECONNREFUSED and connect ENOENT from legacy adapters as empty inventories. It removes the ada…
Out of Scope Changes check ✅ Passed The changes remain within issue [#24281]. The router, owner resolver, and subscription fanout changes support removal of a dead legacy adapter from active lookups and listeners. The added tests verify…
  • Fix all pre-merge checks with AI
  • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Autopilot is currently an internal CodeRabbit preview.


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.

ℹ️ No critical issues — the fix targets the reported failure correctly. One design question inline, plus a scope note and a nitpick below.

Reviewed changes

  • A gone legacy endpoint becomes an empty inventory: DaemonPtyRouter.listProcesses now wraps each adapter call. When a legacy adapter rejects with isDaemonEndpointGoneError (connect ECONNREFUSED / connect ENOENT), it is spliced out of this.legacy, disconnectOnly() is fired best-effort, and it contributes [] instead of failing the whole list.
  • Fail-closed is preserved everywhere else: the current adapter and every other error (token-file open ENOENT, ECONNRESET, timeouts, protocol errors) still reject the list, and the legacy adapter stays registered on those errors.
  • Regression test added: daemon-pty-router-legacy-gone.test.ts pins both the drop-and-do-not-ask-again behavior and the fail-closed cases. isDaemonEndpointGoneError matches the real error shape DaemonClient.ensureConnected throws (client.test.ts:323), and worktree teardown reaches the router in normal launch, so the test exercises the reported path.

ℹ️ The same dead-legacy pattern still fails closed in degraded mode

DegradedDaemonPtyProvider.listProcesses (src/main/daemon/degraded-daemon-pty-provider.ts:211) also fans out to the legacy adapters and rejects on a connect error, so a stale legacy socket would still block worktree rm in degraded-new-pty-fallback launch mode. That path is only reached after a preserve/fallback decision (daemon-provider-init.ts:123), and an existing test (degraded-daemon-pty-provider.test.ts:673) deliberately pins the fail-closed behavior — so this may be intentional. Worth confirming the degraded provider is out of scope for #24281.

Technical details
# Degraded-mode inventory unaffected by the fix

## Affected sites
- `src/main/daemon/degraded-daemon-pty-provider.ts:211` — `Promise.all(this.allProviders()...)`; `allProviders()` includes every legacy adapter, so one `ECONNREFUSED` rejects the whole call.
- `src/main/daemon/daemon-provider-init.ts:123` — degraded provider is installed only for `mode === 'degraded-new-pty-fallback'`.

## Open question for the human
- Should the gone-legacy handling be shared between `DaemonPtyRouter` and `DegradedDaemonPtyProvider`, or is the degraded-mode fail-closed behavior intentionally retained?

ℹ️ Nitpicks

  • void Promise.resolve().then(() => adapter.disconnectOnly()).catch(() => undefined) — disconnectOnly() is async, so void adapter.disconnectOnly().catch(() => undefined) is equivalent and reads more directly.

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

Comment thread src/main/daemon/daemon-pty-router.ts Resolved
@innocarpe
innocarpe force-pushed the fix-24281-legacy-daemon-gone branch from 4757c2e to b55deef Compare October 1, 2026 09:08
@innocarpe

Copy link
Copy Markdown
Contributor Author

Sync update (b55deef0af)

Address review: dropping a gone legacy daemon also removes it from owner lookup and later subscriptions, so that socket is not queried again.

@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

  • Owner resolution now drops the gone adapter: DaemonSessionOwnerResolver keeps its provider list in a private array and exposes dropProvider, which splices the adapter out and invalidates cached inventory/routes so later inventories and probe/attach resolution never re-query the dead socket.
  • Subscription fanout now drops the gone adapter: DaemonPtyAdapterSubscriptionFanout stores its adapters and exposes dropAdapter, so a fresh onBackgroundStreamEvent / onWriteUnavailable subscription skips the dropped socket.
  • Router wires the deregistration: after splicing a refused/missing legacy adapter out of this.legacy, listProcesses calls ownerResolver.dropProvider and subscriptions.dropAdapter (the best-effort disconnectOnly is unchanged).
  • Regression test extended: the legacy-gone test now asserts a later discoverLegacySessions and a new background-stream subscription never reach the dropped adapters, while the current adapter still does — this is exactly what fails if either drop is removed.

This closes the prior review's inline thread (the resolver and fanout were built from a copy of allAdapters(), so splicing this.legacy alone left them querying the dead socket). The remaining open item — DegradedDaemonPtyProvider still failing closed in degraded-new-pty-fallback mode — is unchanged and explicitly out of scope for #24281.

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

innocarpe and others added 3 commits October 1, 2026 20:01
worktree rm lists every routed daemon and fails closed if any list fails.
A leftover socket from a previous app version answers with ECONNREFUSED or
connect ENOENT, which blocked removal of every clean worktree. Treat only
that dead connect as an empty inventory and forget the adapter. The current
daemon, a missing token file, and every other error still fail closed.
The owner resolver and subscription fanout kept the adapter list they copied at startup, so a dropped socket was still treated as an unknown session owner.

Co-authored-by: Cursor <[email protected]>
Removing it from the adapter list left the data and exit listeners attached, so a gone socket could still forward events.

Co-authored-by: Cursor <[email protected]>
@innocarpe
innocarpe force-pushed the fix-24281-legacy-daemon-gone branch from b55deef to 5a301d9 Compare October 1, 2026 11:02
@innocarpe

Copy link
Copy Markdown
Contributor Author

Sync update (5a301d93de)

dropAdapter now unsubscribes the data and exit listeners that were attached when the fanout was constructed. A later event from that adapter is not forwarded. dispose does not unsubscribe it again.

@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

  • A dropped adapter's listeners are now detached: DaemonPtyAdapterSubscriptionFanout.dropAdapter records each adapter's onData / onExit / identity unsubscribers in a new adapterUnsubscribers map, invokes them when the adapter is dropped, and removes them from the global list so a later dispose() never calls them twice. Previously the per-adapter closures stayed attached, so a gone socket could still forward data and exit events through this.dataListeners / this.exitListeners.
  • Regression test added: daemon-pty-adapter-subscription-fanout.test.ts pins that data and exit events from a dropped adapter are no longer forwarded, the surviving adapter's events still are, and dispose() leaves the dropped adapter's unsubscribe count unchanged.

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

@OrcaWin

OrcaWin commented Oct 11, 2026

Copy link
Copy Markdown
Collaborator

Thank you for tracking this down, @innocarpe, and for the careful scoping. main moved under this branch and it picked up a conflict, so rather than asking you to rebase we carried it forward in #27436 with all three of your commits and your authorship intact. We added one small commit for the SAFETY: notes our lint now requires on test fakes, plus a comment tweak. Closing this one in favour of #27436. Thanks again!

@OrcaWin OrcaWin closed this Oct 11, 2026
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.

worktree rm fails for every worktree after a preserved daemon dies: legacy adapter stays registered (recurrence of #9569, 1.4.217 Linux AppImage)

2 participants