Skip to content

fix: prevent daemon connection from hanging in connecting state - #19

Merged
elecnix merged 1 commit into
mainfrom
fix/daemon-connection-race
Jun 30, 2026
Merged

fix: prevent daemon connection from hanging in connecting state#19
elecnix merged 1 commit into
mainfrom
fix/daemon-connection-race

Conversation

@elecnix

@elecnix elecnix commented Jun 30, 2026

Copy link
Copy Markdown
Owner

Fixes the issue where new pi sessions get stuck showing 🟡 name (connecting to daemon...) indefinitely.

Root cause

Two bugs in the daemon connection logic:

  1. Race condition on daemon spawn: connectToDaemon() spawns the daemon via spawnDaemon() (fire-and-forget) and immediately calls createConnection() without waiting for the daemon to bind to the Unix socket. The connection attempt races the daemon startup.

  2. No handshake timeout: The version_check → version_ok handshake had no timeout. If the socket connection succeeds but the peer never responds (stale socket, orphaned fd), the state stays at connecting forever with no recovery path.

Fix

  1. Poll for socket after daemon spawn: After spawning the daemon, poll isDaemonRunning() every 100ms for up to 3 seconds until the socket file appears before attempting createConnection(). This eliminates the race.

  2. 5-second handshake timeout: If the handshake doesn't complete within 5 seconds, the connection is treated as dead and reconnection is scheduled with the existing exponential backoff.

Testing

  • All existing tests pass (node --experimental-strip-types --test test/agent-session.test.ts — 10/10)

— rapid-sloth-39

Two fixes for the issue where /new sessions show 'connecting to daemon'
indefinitely:

1. Poll for socket after spawning daemon — previously spawnDaemon() was
   fire-and-forget but createConnection() was called immediately, racing
   the daemon's socket bind. Now we poll every 100ms for up to 3s until
   the socket file appears before attempting to connect.

2. Add 5s handshake timeout — if the version_check/version_ok handshake
   never completes (e.g. stale socket file, orphaned fd), the connection
   is treated as dead and reconnection is scheduled. Previously there was
   no timeout, so the state would hang at 'connecting' forever.

Co-authored-by: rapid-sloth-39 <rapid-sloth-39@pi-agent.local>
@elecnix
elecnix marked this pull request as ready for review June 30, 2026 19:38
@elecnix
elecnix merged commit 2149bd1 into main Jun 30, 2026
1 check passed
@elecnix
elecnix deleted the fix/daemon-connection-race branch June 30, 2026 19:38
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.

1 participant