multica/apps/web/app/hooks/use-gateway.ts
Naiyuan Qing c5bf56282f feat(web): add gateway, hub, active-agent hooks and real message state
- use-gateway: GatewayClient WebSocket lifecycle with auto-connect/disconnect
- use-hub: REST polling for Hub status and agent CRUD operations
- use-active-agent: Zustand store for cross-component selected agent state
- use-messages: replace mock data with real addUser/addAssistant/clear API

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-30 22:40:50 +08:00

41 lines
1.1 KiB
TypeScript

import { useEffect, useRef, useState, useCallback } from "react"
import { GatewayClient, type ConnectionState, type RoutedMessage } from "@multica/sdk"
import { useDeviceId } from "./use-device-id"
import { GATEWAY_URL } from "../lib/config"
interface UseGatewayOptions {
onMessage?: (msg: RoutedMessage) => void
}
export function useGateway(options?: UseGatewayOptions) {
const deviceId = useDeviceId()
const [state, setState] = useState<ConnectionState>("disconnected")
const clientRef = useRef<GatewayClient | null>(null)
const onMessageRef = useRef(options?.onMessage)
onMessageRef.current = options?.onMessage
useEffect(() => {
if (!deviceId) return
const client = new GatewayClient({
url: GATEWAY_URL,
deviceId,
deviceType: "client",
})
.onStateChange(setState)
.onMessage(msg => onMessageRef.current?.(msg))
clientRef.current = client
client.connect()
return () => { client.disconnect() }
}, [deviceId])
const send = useCallback(
(to: string, action: string, payload: unknown) => {
clientRef.current?.send(to, action, payload)
},
[]
)
return { state, send }
}