Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

feat(gateway): add auto-connect, hub discovery via list-devices

Naiyuan Qing3622f82a7b73
diff --git a/packages/sdk/src/client.ts b/packages/sdk/src/client.ts
index 05849715e8..f38e6d5d57 100644
--- a/packages/sdk/src/client.ts
+++ b/packages/sdk/src/client.ts
@@ -9,6 +9,8 @@ import type {
SendErrorResponse,
PingPayload,
DeviceType,
+ DeviceInfo,
+ ListDevicesResponse,
} from "./types.js";
import { GatewayEvents } from "./types.js";
import {
@@ -163,6 +165,24 @@ export class GatewayClient {
});
}
+ /** List all devices connected to the Gateway */
+ listDevices(): Promise<DeviceInfo[]> {
+ return new Promise((resolve, reject) => {
+ if (!this.socket || !this.isRegistered) {
+ reject(new Error("Not registered"));
+ return;
+ }
+
+ this.socket.emit(
+ GatewayEvents.LIST_DEVICES,
+ {},
+ (response: ListDevicesResponse) => {
+ resolve(response.devices);
+ }
+ );
+ });
+ }
+
/** Send an RPC request and wait for the response */
request<T = unknown>(
to: string,
diff --git a/packages/sdk/src/index.ts b/packages/sdk/src/index.ts
index e1b696f212..7d9643e039 100644
--- a/packages/sdk/src/index.ts
+++ b/packages/sdk/src/index.ts
@@ -11,6 +11,7 @@ export {
type ConnectionState,
type PingPayload,
type PongResponse,
+ type ListDevicesResponse,
} from "./types.js";
// Actions
diff --git a/packages/sdk/src/types.ts b/packages/sdk/src/types.ts
index eec02b8de4..d0067591f1 100644
--- a/packages/sdk/src/types.ts
+++ b/packages/sdk/src/types.ts
@@ -4,6 +4,7 @@ export const GatewayEvents = {
PING: "ping",
PONG: "pong",
REGISTERED: "registered",
+ LIST_DEVICES: "list-devices",
// Message routing
SEND: "send",
@@ -14,7 +15,7 @@ export const GatewayEvents = {
// ============ Device Related ============
/** Device type */
-export type DeviceType = "client" | "agent";
+export type DeviceType = "client" | "hub" | "agent";
/** Device information */
export interface DeviceInfo {
@@ -54,6 +55,11 @@ export interface SendErrorResponse {
code: "DEVICE_NOT_FOUND" | "NOT_REGISTERED" | "INVALID_MESSAGE";
}
+/** List devices response */
+export interface ListDevicesResponse {
+ devices: DeviceInfo[];
+}
+
// ============ Ping/Pong ============
/** Ping request */
diff --git a/packages/store/src/gateway.ts b/packages/store/src/gateway.ts
index ae7baff0b7..f7cf495893 100644
--- a/packages/store/src/gateway.ts
+++ b/packages/store/src/gateway.ts
@@ -1,17 +1,20 @@
import { create } from "zustand"
-import { GatewayClient, type ConnectionState, type SendErrorResponse } from "@multica/sdk"
+import { GatewayClient, type ConnectionState, type DeviceInfo, type SendErrorResponse } from "@multica/sdk"
import { getGatewayUrl } from "@multica/fetch"
import { useMessagesStore } from "./messages"
interface GatewayState {
connectionState: ConnectionState
hubId: string | null
+ hubs: DeviceInfo[]
lastError: SendErrorResponse | null
}
interface GatewayActions {
- connect: (deviceId: string, hubId: string) => void
+ connect: (deviceId: string) => void
disconnect: () => void
+ setHubId: (hubId: string) => void
+ listDevices: () => Promise<DeviceInfo[]>
send: (to: string, action: string, payload: unknown) => void
request: <T = unknown>(method: string, params?: unknown) => Promise<T>
}
@@ -23,13 +26,12 @@ let client: GatewayClient | null = null
export const useGatewayStore = create<GatewayStore>()((set, get) => ({
connectionState: "disconnected",
hubId: null,
+ hubs: [],
lastError: null,
- connect: (deviceId, hubId) => {
+ connect: (deviceId) => {
if (client) return
- set({ hubId })
-
client = new GatewayClient({
url: getGatewayUrl(),
deviceId,
@@ -52,7 +54,17 @@ export const useGatewayStore = create<GatewayStore>()((set, get) => ({
client.disconnect()
client = null
}
- set({ connectionState: "disconnected", hubId: null })
+ set({ connectionState: "disconnected", hubId: null, hubs: [] })
+ },
+
+ setHubId: (hubId) => set({ hubId }),
+
+ listDevices: async () => {
+ if (!client?.isRegistered) return []
+ const devices = await client.listDevices()
+ const hubs = devices.filter((d) => d.deviceType === "hub")
+ set({ hubs })
+ return devices
},
send: (to, action, payload) => {
diff --git a/packages/store/src/hub-init.ts b/packages/store/src/hub-init.ts
index 6d7ed7029f..ca9de4da01 100644
--- a/packages/store/src/hub-init.ts
+++ b/packages/store/src/hub-init.ts
@@ -2,21 +2,39 @@
import { useEffect } from "react"
import { useHubStore } from "./hub"
+import { useDeviceId } from "./device-id"
import { useGatewayStore } from "./gateway"
export function useHubInit() {
+ const deviceId = useDeviceId()
const gwState = useGatewayStore((s) => s.connectionState)
+ const hubId = useGatewayStore((s) => s.hubId)
const fetchHub = useHubStore((s) => s.fetchHub)
const fetchAgents = useHubStore((s) => s.fetchAgents)
- // Once WS is registered, fetch hub info and agents via RPC
+ // Auto-connect WS when deviceId is available
+ useEffect(() => {
+ if (deviceId) {
+ useGatewayStore.getState().connect(deviceId)
+ return () => { useGatewayStore.getState().disconnect() }
+ }
+ }, [deviceId])
+
+ // Once WS is registered, discover available hubs
useEffect(() => {
if (gwState === "registered") {
+ useGatewayStore.getState().listDevices()
+ }
+ }, [gwState])
+
+ // Once hubId is set and WS is registered, fetch hub info and agents via RPC
+ useEffect(() => {
+ if (gwState === "registered" && hubId) {
fetchHub()
fetchAgents()
}
if (gwState === "disconnected") {
useHubStore.setState({ status: "idle", hub: null, agents: [], activeAgentId: null })
}
- }, [gwState, fetchHub, fetchAgents])
+ }, [gwState, hubId, fetchHub, fetchAgents])
}
diff --git a/packages/ui/src/components/hub-sidebar.tsx b/packages/ui/src/components/hub-sidebar.tsx
index 8897ebc77f..a64b232e48 100644
--- a/packages/ui/src/components/hub-sidebar.tsx
+++ b/packages/ui/src/components/hub-sidebar.tsx
@@ -43,18 +43,24 @@ export function HubSidebar() {
const setActiveAgentId = useHubStore((s) => s.setActiveAgentId)
const gwState = useGatewayStore((s) => s.connectionState)
- const connect = useGatewayStore((s) => s.connect)
- const disconnect = useGatewayStore((s) => s.disconnect)
- const deviceId = useDeviceId()
+ const hubId = useGatewayStore((s) => s.hubId)
+ const hubs = useGatewayStore((s) => s.hubs)
+ const setHubId = useGatewayStore((s) => s.setHubId)
+ const listDevices = useGatewayStore((s) => s.listDevices)
const [hubIdInput, setHubIdInput] = useState("")
- const isDisconnected = gwState === "disconnected"
- const isConnecting = gwState === "connecting" || gwState === "connected"
+ const isRegistered = gwState === "registered"
+ const needsHubSelection = isRegistered && !hubId
const handleConnect = () => {
const id = hubIdInput.trim()
- if (!id || !deviceId) return
- connect(deviceId, id)
+ if (!id) return
+ setHubId(id)
+ }
+
+ const handleDisconnect = () => {
+ useGatewayStore.setState({ hubId: null })
+ useHubStore.setState({ status: "idle", hub: null, agents: [], activeAgentId: null })
}
return (
@@ -62,31 +68,61 @@ export function HubSidebar() {
<SidebarGroup>
<SidebarGroupLabel>Hub</SidebarGroupLabel>
<SidebarGroupContent>
- {isDisconnected ? (
+ {!isRegistered ? (
+ <div className="flex items-center gap-2 px-2 py-1 text-sm">
+ <span className="size-2 rounded-full shrink-0 bg-yellow-500/50 animate-pulse" />
+ <span className="text-muted-foreground/70 text-xs">
+ {gwState === "disconnected" ? "Connecting to Gateway..." : "Registering..."}
+ </span>
+ </div>
+ ) : needsHubSelection ? (
<div className="px-2 space-y-2 py-1">
+ {hubs.length > 0 && (
+ <div className="space-y-1">
+ {hubs.map((h) => (
+ <button
+ key={h.deviceId}
+ onClick={() => setHubId(h.deviceId)}
+ className="w-full text-left px-2 py-1 rounded-md text-xs font-mono hover:bg-sidebar-accent hover:text-sidebar-accent-foreground cursor-pointer truncate"
+ >
+ {h.deviceId}
+ </button>
+ ))}
+ </div>
+ )}
<Input
value={hubIdInput}
onChange={(e) => setHubIdInput(e.target.value)}
- placeholder="Enter Hub ID..."
+ placeholder="Or enter Hub ID..."
className="h-7 text-xs font-mono"
onKeyDown={(e) => e.key === "Enter" && handleConnect()}
/>
- <Button
- variant="outline"
- size="sm"
- onClick={handleConnect}
- disabled={!hubIdInput.trim() || !deviceId}
- className="w-full text-xs"
- >
- Connect
- </Button>
+ <div className="flex gap-1">
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={handleConnect}
+ disabled={!hubIdInput.trim()}
+ className="flex-1 text-xs"
+ >
+ Connect
+ </Button>
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={() => listDevices()}
+ className="text-xs"
+ >
+ Refresh
+ </Button>
+ </div>
</div>
) : (
<>
<div className="flex items-center gap-2 px-2 py-1 text-sm">
<span className={`size-2 rounded-full shrink-0 ${STATUS_DOT[status] ?? STATUS_DOT.idle}`} />
<span className="text-muted-foreground/70 text-xs">
- {isConnecting ? "Connecting..." : STATUS_LABEL[status]}
+ {STATUS_LABEL[status]}
</span>
</div>
{status === "connected" && hub ? (
@@ -97,7 +133,7 @@ export function HubSidebar() {
<Skeleton className="mx-2 h-3.5 w-32" />
) : null}
<div className="px-2 pt-1">
- <Button variant="outline" size="sm" onClick={disconnect} className="w-full text-xs">
+ <Button variant="outline" size="sm" onClick={handleDisconnect} className="w-full text-xs">
Disconnect
</Button>
</div>
@@ -106,7 +142,7 @@ export function HubSidebar() {
</SidebarGroupContent>
</SidebarGroup>
- {isConnecting && (
+ {isRegistered && hubId && (status === "idle" || status === "loading") && (
<SidebarGroup>
<SidebarGroupLabel>Agents</SidebarGroupLabel>
<SidebarGroupContent>
diff --git a/src/gateway/events.gateway.ts b/src/gateway/events.gateway.ts
index 0197e0f40c..ebeb21918b 100644
--- a/src/gateway/events.gateway.ts
+++ b/src/gateway/events.gateway.ts
@@ -169,6 +169,17 @@ export class EventsGateway
this.server.to(targetSocketId).emit(GatewayEvents.RECEIVE, message);
}
+ @SubscribeMessage(GatewayEvents.LIST_DEVICES)
+ handleListDevices(
+ @ConnectedSocket() client: Socket
+ ): { devices: DeviceInfo[] } {
+ const senderDevice = this.socketToDevice.get(client.id);
+ if (!senderDevice) {
+ return { devices: [] };
+ }
+ return { devices: this.getOnlineDevices() };
+ }
+
@SubscribeMessage(GatewayEvents.PING)
handlePing(
@MessageBody() data: PingPayload,
@@ -184,7 +195,7 @@ export class EventsGateway
}
/** Get online devices of specified type */
- getOnlineDevicesByType(type: "client" | "agent"): DeviceInfo[] {
+ getOnlineDevicesByType(type: DeviceType): DeviceInfo[] {
return this.getOnlineDevices().filter((d) => d.deviceType === type);
}
diff --git a/src/hub/hub.ts b/src/hub/hub.ts
index c456d8a731..984082a265 100644
--- a/src/hub/hub.ts
+++ b/src/hub/hub.ts
@@ -66,7 +66,7 @@ export class Hub {
url,
path: this.path,
deviceId: this.hubId,
- deviceType: "client",
+ deviceType: "hub",
autoReconnect: true,
reconnectDelay: 1000,
});