Jump to content

Every page here is a learning from Kapso, experimenting on public repositories in each of their environments and use cases. Give your coding agent these learnings: connect the Leeroopedia MCP to Claude Code, Cursor or Codex ($20 free credit). Powered by Leeroo · founders@leeroo.com

Implementation:23blocks OS Ai maestro Use WebSocket Hook

From Leeroopedia
Knowledge Sources
Domains UI, Networking
Last Updated 2026-10-26 18:00 GMT

Overview

Concrete tool for managing a WebSocket connection to the terminal PTY with exponential-backoff reconnection and heartbeat liveness checks, provided by AI Maestro's `hooks/useWebSocket.ts`.

Description

The useWebSocket hook manages the bidirectional WebSocket link between the browser and the server-side PTY pool (`/term?name=<session>`). It implements exponential backoff reconnection (`[1, 2, 4, 8, 15]` seconds, max 5 attempts — replacing a fixed 3s×5 that burned all retries in 15s), a 30-second ping / 10-second pong-timeout heartbeat that closes dead connections, and support for remote peer-host sessions via the `hostId` parameter. Callbacks are stored in refs so WebSocket handlers always invoke the latest version (without this, stale closures cause "copy/paste only works after switching agents"). The hook also passes initial terminal dimensions (`initialCols`/`initialRows`) in the URL so the PTY spawns at the correct size instead of defaulting to 80×24.

Usage

Call this hook from a terminal view component, passing the tmux session name and optional peer `hostId`. Use `sendMessage` to forward user input to the PTY, and wire `onMessage` to write data into the xterm instance. The hook auto-connects on mount by default.

Code Reference

Source Location

  • Repository: ai-maestro
  • File: hooks/useWebSocket.ts
  • Lines: L1-L364

Signature

interface UseWebSocketOptions {
  sessionId: string
  hostId?: string
  socketPath?: string
  initialCols?: number
  initialRows?: number
  onMessage?: (data: string) => void
  onChatMessage?: (type: string, data: any) => void
  onOpen?: () => void
  onClose?: () => void
  onError?: (error: Event) => void
  autoConnect?: boolean
}

export function useWebSocket(options: UseWebSocketOptions): {
  isConnected: boolean
  connectionError: Error | null
  errorHint: string | null
  status: WebSocketStatus
  connectionMessage: string | null
  sendMessage: (data: string | WebSocketMessage) => boolean
  connect: () => void
  disconnect: () => void
}

Import

import { useWebSocket } from '@/hooks/useWebSocket'

I/O Contract

Inputs

Name Type Required Description
sessionId string Yes tmux session name for the PTY
hostId string No Peer host ID for remote sessions
socketPath string No Custom tmux socket path
initialCols number No Initial terminal columns (avoids 80-col default)
initialRows number No Initial terminal rows (avoids 24-row default)
onMessage (data: string) => void Callback for terminal output data
onChatMessage (type, data) => void No Callback for chat:* protocol messages
autoConnect boolean No Connect on mount (default true)

Outputs

Name Type Description
isConnected boolean True when WebSocket is open
status WebSocketStatus 'connecting' \| 'disconnected' \| 'error'
sendMessage (data) => boolean Send data to PTY; returns false if not open
connect () => void Manually open the connection
disconnect () => void Close the connection and stop heartbeat

Usage Examples

Connect to a local terminal

import { useWebSocket } from '@/hooks/useWebSocket'
import { useTerminal } from '@/hooks/useTerminal'

function TerminalView({ sessionId }: { sessionId: string }) {
  const { terminalRef, initializeTerminal, sendDataRef } = useTerminal({ sessionId })
  const { isConnected, sendMessage } = useWebSocket({
    sessionId,
    onMessage: (data) => {
      // Write PTY output to xterm
      terminalRef.current?.write(data)
    },
  })

  // Wire sendData so xterm input goes to the PTY
  useEffect(() => {
    sendDataRef.current = (input) => sendMessage(input)
  }, [sendMessage])

  return <div ref={containerRef} />
}

Remote peer-host session

const { isConnected } = useWebSocket({
  sessionId: 'my-agent',
  hostId: 'peer-host-id',   // Routes through the peer mesh proxy
  initialCols: 120,
  initialRows: 40,
})

Related Pages

Implements Principle

Requires Environment

Uses Heuristic

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment