Implementation:23blocks OS Ai maestro Use Companion WebSocket Hook
| Knowledge Sources | |
|---|---|
| Domains | UI, Networking |
| Last Updated | 2026-10-26 18:00 GMT |
Overview
Concrete tool for bidirectional WebSocket communication with the server's cerebellum voice subsystem, with exponential-backoff reconnection, provided by AI Maestro's `hooks/useCompanionWebSocket.ts`.
Description
The useCompanionWebSocket hook connects to `/companion-ws?agent=<agentId>` for voice companion features. It receives `speech` events (text to speak) and `interrupt` events (stop speaking), and can `send` user messages back to the voice subsystem. Reconnection uses exponential backoff (`[1, 2, 3, 5, 10]` seconds, max 5 retries). Callbacks are stored in refs so the WebSocket always calls the latest version. A stale-socket guard (`wsRef.current !== ws`) prevents orphaned closures from re-triggering reconnects.
Usage
Call with `agentId`, an `onSpeech` callback, and an optional `onInterrupt` callback. Use `send` to push user messages to the voice subsystem.
Code Reference
Source Location
- Repository: ai-maestro
- File: hooks/useCompanionWebSocket.ts
- Lines: L1-L104
Signature
export function useCompanionWebSocket({
agentId: string | null
onSpeech: (text: string) => void
onInterrupt?: () => void
}): {
send: (data: Record<string, unknown>) => void
}
Import
import { useCompanionWebSocket } from '@/hooks/useCompanionWebSocket'
I/O Contract
Inputs
| Name | Type | Required | Description |
|---|---|---|---|
| agentId | null | Yes | Agent for the companion channel |
| onSpeech | (text: string) => void | Yes | Called when speech text arrives |
| onInterrupt | () => void | No | Called when an interrupt event arrives |
Outputs
| Name | Type | Description |
|---|---|---|
| send | (data) => void | Send a message to the voice subsystem |
Usage Examples
Voice companion
import { useCompanionWebSocket } from '@/hooks/useCompanionWebSocket'
function VoicePanel({ agentId }) {
const { send } = useCompanionWebSocket({
agentId,
onSpeech: (text) => speak(text),
onInterrupt: () => stopSpeaking(),
})
// Send a user message to the voice subsystem
return <button onClick={() => send({ type: 'user_message', text: 'hello' })}>Speak</button>
}