Skip to content

Conversation

@Kitenite
Copy link
Collaborator

@Kitenite Kitenite commented Jan 18, 2026

Summary

  • Add automatic daemon restart with exponential backoff when the terminal host daemon crashes or becomes unresponsive
  • Add periodic health check (ping every 30s) to proactively detect stale daemons
  • Add ping IPC command that returns daemon uptime and active session count
  • Handle protocol version skew gracefully (older daemons without ping support)

Changes

Client (client.ts):

  • Auto-restart on disconnect with exponential backoff (500ms → 30s, max 10 attempts)
  • Periodic health check via ping, triggers restart on timeout
  • New reconnected event emitted on successful auto-restart
  • setAutoRestart() and setHealthCheck() methods for runtime control

Daemon (index.ts):

  • Add ping handler with role check (control only)
  • Defensive socket write handling (socket.writable checks)
  • Extract removeStreamSocket() helper to reduce duplication

Types (types.ts):

  • Add PingRequest / PingResponse types

Test plan

  • Kill daemon manually (kill -9 <pid>) and verify auto-restart
  • Verify health check detects frozen daemon
  • Verify older daemon (without ping) disables health checks gracefully
  • Verify reconnected event fires on successful restart

Summary by CodeRabbit

  • New Features

    • Terminal daemon connections now auto-restart on disconnection using exponential backoff strategy
    • Health check mechanism monitors daemon responsiveness with automatic fallback for older systems
    • New reconnected event notifies when auto-restart succeeds
  • Improvements

    • Enhanced server socket lifecycle and error handling robustness
    • Improved logging for unhandled exceptions and rejections

✏️ Tip: You can customize this high-level summary in your review settings.

Add resilient daemon lifecycle management to ensure the terminal host
daemon automatically restarts if it crashes or becomes unresponsive.

- Add auto-restart with exponential backoff (500ms → 30s, max 10 attempts)
- Add periodic health check via ping every 30 seconds
- Add ping IPC command returning daemon uptime and session count
- Gracefully handle older daemons that don't support ping
- Clean up socket writes with defensive writable checks
- Extract helper functions for better code organization

The client now emits a 'reconnected' event when auto-restart succeeds.
@coderabbitai
Copy link

coderabbitai bot commented Jan 18, 2026

📝 Walkthrough

Walkthrough

The changes add health check and auto-restart capabilities to the TerminalHostClient, implementing a ping-based health monitoring mechanism with exponential backoff auto-restart logic. New IPC types and daemon-side ping handler support this functionality with more robust socket management.

Changes

Cohort / File(s) Summary
Client Health Check & Auto-Restart
apps/desktop/src/main/lib/terminal-host/client.ts
Introduced exponential backoff auto-restart (500ms initial, 30s max, 2x factor, 10 max attempts) triggered on disconnect if previously connected. Added health check mechanism (30s interval, 5s per-check timeout) that disables gracefully for unsupported daemons. New public methods: ping() and setAutoRestart(), plus reconnected event. Internal state tracking for both subsystems with lifecycle management.
IPC Protocol Types
apps/desktop/src/main/lib/terminal-host/types.ts
Added PingRequest and PingResponse types with fields for client timestamp, daemon uptime, and active session count. Registered ping entry in RequestTypeMap.
Daemon Ping Handler & Socket Robustness
apps/desktop/src/main/terminal-host/index.ts
Implemented ping IPC handler with auth and control-role validation, responding with daemon uptime (computed from DAEMON_START_TIME) and active session count. Enhanced socket management with removeStreamSocket() helper and defensive checks before writes (skip destroyed/unwritable sockets, cleanup on failure). Wrapped response sending in try-catch. Updated error logging to indicate restart behavior.

Sequence Diagram

sequenceDiagram
    participant Client as TerminalHostClient
    participant Timer as Auto-Restart Timer
    participant Daemon as Terminal Host Daemon
    
    Note over Client,Daemon: Healthy State
    Client->>Daemon: ensureConnected()
    Daemon-->>Client: connected
    Client->>Client: resetAutoRestartState()
    Client->>Client: startHealthCheck()
    
    Note over Client,Daemon: Health Check Cycle
    Client->>Client: performHealthCheck()
    Client->>Daemon: ping(request)
    Daemon-->>Client: pong(uptime, sessions)
    Note over Client: Health OK, continue
    
    Note over Client,Daemon: Connection Lost
    Daemon--xClient: disconnect
    Client->>Client: Is autoRestartEnabled?
    alt Auto-Restart Enabled
        Client->>Timer: scheduleAutoRestart(initialDelay)
        Timer->>Client: timeout
        Client->>Client: attemptAutoRestart()
        alt Reconnection Success
            Client->>Daemon: ensureConnected()
            Daemon-->>Client: reconnected
            Client->>Client: resetAutoRestartState()
            Client->>Client: emit reconnected event
        else Retry with Backoff
            Client->>Timer: scheduleAutoRestart(delay × 2)
            Note over Client: Exponential backoff up to 10 attempts
        end
    else Auto-Restart Disabled
        Note over Client: Stay disconnected
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~30 minutes

Possibly related PRs

Suggested reviewers

  • AviPeltz

Poem

🐰 Ping, ping! the client cries with glee,
Checking if the daemon's still free,
When connection fades, don't lose hope,
With exponential backoff we cope,
Hop, hop, reconnect—let's ski! 🚀✨

🚥 Pre-merge checks | ✅ 2 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 14.29% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely summarizes the main changes: adding daemon auto-restart and health check functionality to the desktop application.
Description check ✅ Passed The PR description is well-structured, covering all key sections: summary of changes, detailed breakdown by file, new types, and a comprehensive test plan. It aligns with the required template structure.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@Kitenite Kitenite closed this Jan 19, 2026
@Kitenite Kitenite deleted the daemon-lifecycle branch January 19, 2026 00:32
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.

2 participants