Skip to content

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

Go

feat(web): add useGatewayConnection and useChat hooks

Naiyuan Qing178d71524f6d
diff --git a/apps/web/hooks/use-chat.ts b/apps/web/hooks/use-chat.ts
new file mode 100644
index 0000000000..be63921984
--- /dev/null
+++ b/apps/web/hooks/use-chat.ts
@@ -0,0 +1,325 @@
+"use client";
+
+import { useState, useEffect, useCallback, useRef } from "react";
+import { v7 as uuidv7 } from "uuid";
+import {
+ type GatewayClient,
+ type ContentBlock,
+ type AgentEvent,
+ type StreamPayload,
+ type GetAgentMessagesResult,
+ type ExecApprovalRequestPayload,
+ type ApprovalDecision,
+ StreamAction,
+ ExecApprovalRequestAction,
+} from "@multica/sdk";
+
+export type ToolStatus = "running" | "success" | "error" | "interrupted";
+
+export interface Message {
+ id: string;
+ role: "user" | "assistant" | "toolResult";
+ content: ContentBlock[];
+ agentId: string;
+ stopReason?: string;
+ toolCallId?: string;
+ toolName?: string;
+ toolArgs?: Record<string, unknown>;
+ toolStatus?: ToolStatus;
+ isError?: boolean;
+}
+
+interface UseChatOptions {
+ client: GatewayClient;
+ hubId: string;
+ agentId: string;
+}
+
+export interface ChatError {
+ code: string;
+ message: string;
+}
+
+export interface PendingApproval extends ExecApprovalRequestPayload {
+ /** Timestamp when the request was received (for ordering) */
+ receivedAt: number;
+}
+
+export interface UseChatReturn {
+ messages: Message[];
+ streamingIds: Set<string>;
+ isLoading: boolean;
+ error: ChatError | null;
+ pendingApprovals: PendingApproval[];
+ sendMessage: (text: string) => void;
+ resolveApproval: (approvalId: string, decision: ApprovalDecision) => void;
+}
+
+function toContentBlocks(content: string | ContentBlock[]): ContentBlock[] {
+ if (typeof content === "string") {
+ return content ? [{ type: "text", text: content }] : [];
+ }
+ if (Array.isArray(content)) return content;
+ return [];
+}
+
+function extractContent(event: AgentEvent): ContentBlock[] {
+ if (!("message" in event)) return [];
+ const msg = event.message;
+ if (!msg || !("content" in msg)) return [];
+ const content = msg.content;
+ return Array.isArray(content) ? (content as ContentBlock[]) : [];
+}
+
+export function useChat({ client, hubId, agentId }: UseChatOptions): UseChatReturn {
+ const [messages, setMessages] = useState<Message[]>([]);
+ const [streamingIds, setStreamingIds] = useState<Set<string>>(new Set());
+ const [isLoading, setIsLoading] = useState(false);
+ const [error, setError] = useState<ChatError | null>(null);
+ const [pendingApprovals, setPendingApprovals] = useState<PendingApproval[]>([]);
+ // Keep a ref for use inside callbacks (avoids stale closures)
+ const messagesRef = useRef(messages);
+ messagesRef.current = messages;
+
+ // Fetch history on mount
+ useEffect(() => {
+ async function fetchHistory() {
+ try {
+ const result = await client.request<GetAgentMessagesResult>(
+ hubId,
+ "getAgentMessages",
+ { agentId, limit: 200 },
+ );
+
+ // Build toolCallId → args lookup from assistant tool_use blocks
+ const toolCallArgsMap = new Map<string, { name: string; args: Record<string, unknown> }>();
+ for (const m of result.messages) {
+ if (m.role === "assistant") {
+ for (const block of m.content) {
+ if (block.type === "toolCall") {
+ toolCallArgsMap.set(block.id, { name: block.name, args: block.arguments });
+ }
+ }
+ }
+ }
+
+ const loaded: Message[] = [];
+ for (const m of result.messages) {
+ if (m.role === "user") {
+ loaded.push({
+ id: uuidv7(),
+ role: "user",
+ content: toContentBlocks(m.content),
+ agentId,
+ });
+ } else if (m.role === "assistant") {
+ loaded.push({
+ id: uuidv7(),
+ role: "assistant",
+ content: toContentBlocks(m.content),
+ agentId,
+ stopReason: m.stopReason,
+ });
+ } else if (m.role === "toolResult") {
+ const callInfo = toolCallArgsMap.get(m.toolCallId);
+ loaded.push({
+ id: uuidv7(),
+ role: "toolResult",
+ content: toContentBlocks(m.content),
+ agentId,
+ toolCallId: m.toolCallId,
+ toolName: m.toolName,
+ toolArgs: callInfo?.args,
+ toolStatus: m.isError ? "error" : "success",
+ isError: m.isError,
+ });
+ }
+ }
+
+ if (loaded.length > 0) {
+ setMessages(loaded);
+ }
+ } catch {
+ // History fetch is best-effort
+ }
+ }
+
+ fetchHistory();
+ }, [client, hubId, agentId]);
+
+ // Listen for streaming events
+ useEffect(() => {
+ client.onMessage((msg) => {
+ if (msg.action === StreamAction) {
+ const payload = msg.payload as StreamPayload;
+ const { event } = payload;
+
+ switch (event.type) {
+ case "message_start": {
+ const newMsg: Message = {
+ id: payload.streamId,
+ role: "assistant",
+ content: [],
+ agentId: payload.agentId,
+ };
+ const content = extractContent(event);
+ if (content.length) newMsg.content = content;
+
+ setMessages((prev) => [...prev, newMsg]);
+ setStreamingIds((prev) => new Set(prev).add(payload.streamId));
+ setIsLoading(true);
+ break;
+ }
+ case "message_update": {
+ const content = extractContent(event);
+ setMessages((prev) =>
+ prev.map((m) =>
+ m.id === payload.streamId ? { ...m, content } : m,
+ ),
+ );
+ break;
+ }
+ case "message_end": {
+ const content = extractContent(event);
+ const stopReason =
+ "message" in event
+ ? (event.message as { stopReason?: string })?.stopReason
+ : undefined;
+
+ setMessages((prev) =>
+ prev.map((m) => {
+ if (m.id === payload.streamId) return { ...m, content, stopReason };
+ // Interrupt running tools belonging to the same agent
+ if (
+ m.role === "toolResult" &&
+ m.toolStatus === "running" &&
+ m.agentId === payload.agentId
+ ) {
+ return { ...m, toolStatus: "interrupted" as ToolStatus };
+ }
+ return m;
+ }),
+ );
+ setStreamingIds((prev) => {
+ const next = new Set(prev);
+ next.delete(payload.streamId);
+ return next;
+ });
+ setIsLoading(false);
+ break;
+ }
+ case "tool_execution_start": {
+ const toolMsg: Message = {
+ id: uuidv7(),
+ role: "toolResult",
+ content: [],
+ agentId: payload.agentId,
+ toolCallId: event.toolCallId,
+ toolName: event.toolName,
+ toolArgs: event.args as Record<string, unknown> | undefined,
+ toolStatus: "running",
+ isError: false,
+ };
+ setMessages((prev) => [...prev, toolMsg]);
+ break;
+ }
+ case "tool_execution_end": {
+ setMessages((prev) =>
+ prev.map((m) =>
+ m.role === "toolResult" && m.toolCallId === event.toolCallId
+ ? {
+ ...m,
+ toolStatus: (event.isError ? "error" : "success") as ToolStatus,
+ isError: event.isError ?? false,
+ content:
+ event.result != null
+ ? [
+ {
+ type: "text" as const,
+ text:
+ typeof event.result === "string"
+ ? event.result
+ : JSON.stringify(event.result),
+ },
+ ]
+ : [],
+ }
+ : m,
+ ),
+ );
+ break;
+ }
+ case "tool_execution_update":
+ break;
+ }
+ return;
+ }
+
+ // Exec approval request from Hub
+ if (msg.action === ExecApprovalRequestAction) {
+ const payload = msg.payload as ExecApprovalRequestPayload;
+ setPendingApprovals((prev) => [...prev, { ...payload, receivedAt: Date.now() }]);
+ return;
+ }
+
+ // Error from Hub (e.g. UNAUTHORIZED)
+ if (msg.action === "error") {
+ const errPayload = msg.payload as { code: string; message: string };
+ setError({ code: errPayload.code, message: errPayload.message });
+ return;
+ }
+
+ // Direct (non-streaming) message
+ const payload = msg.payload as { agentId?: string; content?: string };
+ if (payload?.agentId && payload?.content) {
+ setMessages((prev) => [
+ ...prev,
+ {
+ id: uuidv7(),
+ role: "assistant",
+ content: [{ type: "text", text: payload.content! }],
+ agentId: payload.agentId!,
+ },
+ ]);
+ }
+ });
+
+ return () => {
+ // Clear onMessage when unmounting
+ client.onMessage(() => {});
+ };
+ }, [client, agentId]);
+
+ const resolveApproval = useCallback(
+ (approvalId: string, decision: ApprovalDecision) => {
+ setPendingApprovals((prev) => prev.filter((a) => a.approvalId !== approvalId));
+ client.request(hubId, "resolveExecApproval", { approvalId, decision }).catch(() => {
+ // Best-effort — approval may have already expired
+ });
+ },
+ [client, hubId],
+ );
+
+ const sendMessage = useCallback(
+ (text: string) => {
+ const trimmed = text.trim();
+ if (!trimmed) return;
+
+ setMessages((prev) => [
+ ...prev,
+ {
+ id: uuidv7(),
+ role: "user",
+ content: [{ type: "text", text: trimmed }],
+ agentId,
+ },
+ ]);
+
+ client.send(hubId, "message", { agentId, content: trimmed });
+ setIsLoading(true);
+ },
+ [client, hubId, agentId],
+ );
+
+ return { messages, streamingIds, isLoading, error, pendingApprovals, sendMessage, resolveApproval };
+}
diff --git a/apps/web/hooks/use-gateway-connection.ts b/apps/web/hooks/use-gateway-connection.ts
new file mode 100644
index 0000000000..211dd1b6c3
--- /dev/null
+++ b/apps/web/hooks/use-gateway-connection.ts
@@ -0,0 +1,162 @@
+"use client";
+
+import { useState, useEffect, useCallback, useRef } from "react";
+import { v7 as uuidv7 } from "uuid";
+import {
+ GatewayClient,
+ type ConnectionState,
+} from "@multica/sdk";
+
+// Persisted connection identity (separate from one-time token)
+const STORAGE_KEY = "multica-connection-identity";
+const DEVICE_KEY = "multica-device-id";
+
+export interface ConnectionIdentity {
+ gateway: string;
+ hubId: string;
+ agentId: string;
+}
+
+function loadIdentity(): ConnectionIdentity | null {
+ try {
+ const raw = localStorage.getItem(STORAGE_KEY);
+ if (!raw) return null;
+ const parsed = JSON.parse(raw);
+ if (parsed.gateway && parsed.hubId && parsed.agentId) return parsed;
+ return null;
+ } catch {
+ return null;
+ }
+}
+
+function saveIdentity(identity: ConnectionIdentity): void {
+ localStorage.setItem(STORAGE_KEY, JSON.stringify(identity));
+}
+
+function clearIdentity(): void {
+ localStorage.removeItem(STORAGE_KEY);
+}
+
+function getDeviceId(): string {
+ let id = localStorage.getItem(DEVICE_KEY);
+ if (!id) {
+ id = uuidv7();
+ localStorage.setItem(DEVICE_KEY, id);
+ }
+ return id;
+}
+
+export type PageState = "loading" | "not-connected" | "connecting" | "connected";
+
+export interface UseGatewayConnectionReturn {
+ pageState: PageState;
+ /** Raw SDK connection state — used by ConnectAgent for verifying/connecting distinction */
+ connectionState: ConnectionState;
+ identity: ConnectionIdentity | null;
+ error: string | null;
+ client: GatewayClient | null;
+ /** Increments on each disconnect — use as React key to reset child components */
+ pairingKey: number;
+ connect: (identity: ConnectionIdentity, token?: string) => void;
+ disconnect: () => void;
+}
+
+export function useGatewayConnection(): UseGatewayConnectionReturn {
+ const [pageState, setPageState] = useState<PageState>("loading");
+ const [connectionState, setConnectionState] = useState<ConnectionState>("disconnected");
+ const [identity, setIdentity] = useState<ConnectionIdentity | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const clientRef = useRef<GatewayClient | null>(null);
+ const disconnectingRef = useRef(false);
+ const pairingKeyRef = useRef(0);
+
+ const connectToGateway = useCallback(
+ (id: ConnectionIdentity, token?: string) => {
+ if (clientRef.current) {
+ clientRef.current.disconnect();
+ clientRef.current = null;
+ }
+
+ disconnectingRef.current = false;
+ setPageState("connecting");
+ setError(null);
+
+ const deviceId = getDeviceId();
+
+ const client = new GatewayClient({
+ url: id.gateway,
+ deviceId,
+ deviceType: "client",
+ hubId: id.hubId,
+ ...(token ? { token } : {}),
+ })
+ .onStateChange((state: ConnectionState) => {
+ if (disconnectingRef.current) return;
+ setConnectionState(state);
+ if (state === "registered") {
+ saveIdentity(id);
+ setIdentity(id);
+ setPageState("connected");
+ }
+ })
+ .onError((err: Error) => {
+ if (disconnectingRef.current) return;
+ pairingKeyRef.current += 1;
+ clearIdentity();
+ setIdentity(null);
+ setError(err.message);
+ setPageState("not-connected");
+ clientRef.current?.disconnect();
+ clientRef.current = null;
+ })
+ .onSendError((err) => {
+ if (disconnectingRef.current) return;
+ setError(err.error);
+ });
+
+ clientRef.current = client;
+ client.connect();
+ },
+ [],
+ );
+
+ // Try to reconnect with saved identity on mount
+ useEffect(() => {
+ const saved = loadIdentity();
+ if (!saved) {
+ setPageState("not-connected");
+ return;
+ }
+
+ setIdentity(saved);
+ connectToGateway(saved);
+
+ return () => {
+ clientRef.current?.disconnect();
+ clientRef.current = null;
+ };
+ }, []);
+
+ const disconnect = useCallback(() => {
+ disconnectingRef.current = true;
+ pairingKeyRef.current += 1;
+ clientRef.current?.disconnect();
+ clientRef.current = null;
+ clearIdentity();
+ setIdentity(null);
+ setPageState("not-connected");
+ setConnectionState("disconnected");
+ setError(null);
+ }, []);
+
+ return {
+ pageState,
+ connectionState,
+ identity,
+ error,
+ client: clientRef.current,
+ pairingKey: pairingKeyRef.current,
+ connect: connectToGateway,
+ disconnect,
+ };
+}