feat(webui): add initial webui with websocket chat flow

This commit is contained in:
Xubin Ren
2026-04-18 18:51:53 +00:00
parent 6bfb75ed03
commit 9ed3031a42
76 changed files with 7088 additions and 38 deletions
+165
View File
@@ -0,0 +1,165 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { useClient } from "@/providers/ClientProvider";
import type { InboundEvent, UIMessage } from "@/lib/types";
interface StreamBuffer {
/** ID of the assistant message currently receiving deltas. */
messageId: string;
/** Sequence of deltas accumulated in order. */
parts: string[];
}
/**
* Subscribe to a chat by ID. Returns the in-memory message list for the chat,
* a streaming flag, and a ``send`` function. Initial history must be seeded
* separately (e.g. via ``fetchSessionMessages``) since the server only replays
* live events.
*/
export function useNanobotStream(
chatId: string | null,
initialMessages: UIMessage[] = [],
): {
messages: UIMessage[];
isStreaming: boolean;
send: (content: string) => void;
setMessages: React.Dispatch<React.SetStateAction<UIMessage[]>>;
} {
const { client } = useClient();
const [messages, setMessages] = useState<UIMessage[]>(initialMessages);
const [isStreaming, setIsStreaming] = useState(false);
const buffer = useRef<StreamBuffer | null>(null);
// Reset local state when switching chats.
useEffect(() => {
setMessages(initialMessages);
setIsStreaming(false);
buffer.current = null;
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [chatId]);
useEffect(() => {
if (!chatId) return;
const handle = (ev: InboundEvent) => {
if (ev.event === "delta") {
const id = buffer.current?.messageId ?? crypto.randomUUID();
if (!buffer.current) {
buffer.current = { messageId: id, parts: [] };
setMessages((prev) => [
...prev,
{
id,
role: "assistant",
content: "",
isStreaming: true,
createdAt: Date.now(),
},
]);
setIsStreaming(true);
}
buffer.current.parts.push(ev.text);
const combined = buffer.current.parts.join("");
const targetId = buffer.current.messageId;
setMessages((prev) =>
prev.map((m) => (m.id === targetId ? { ...m, content: combined } : m)),
);
return;
}
if (ev.event === "stream_end") {
if (!buffer.current) {
setIsStreaming(false);
return;
}
const finalId = buffer.current.messageId;
buffer.current = null;
setIsStreaming(false);
setMessages((prev) =>
prev.map((m) =>
m.id === finalId ? { ...m, isStreaming: false } : m,
),
);
return;
}
if (ev.event === "message") {
// Intermediate agent breadcrumbs (tool-call hints, raw progress).
// Attach them to the last trace row if it was the last emitted item
// so a sequence of calls collapses into one compact trace group.
if (ev.kind === "tool_hint" || ev.kind === "progress") {
const line = ev.text;
setMessages((prev) => {
const last = prev[prev.length - 1];
if (last && last.kind === "trace" && !last.isStreaming) {
const merged: UIMessage = {
...last,
traces: [...(last.traces ?? [last.content]), line],
content: line,
};
return [...prev.slice(0, -1), merged];
}
return [
...prev,
{
id: crypto.randomUUID(),
role: "tool",
kind: "trace",
content: line,
traces: [line],
createdAt: Date.now(),
},
];
});
return;
}
// A complete (non-streamed) assistant message. If a stream was in
// flight, drop the placeholder so we don't render the text twice.
const activeId = buffer.current?.messageId;
buffer.current = null;
setIsStreaming(false);
setMessages((prev) => {
const filtered = activeId ? prev.filter((m) => m.id !== activeId) : prev;
return [
...filtered,
{
id: crypto.randomUUID(),
role: "assistant",
content: ev.text,
createdAt: Date.now(),
},
];
});
return;
}
// ``attached`` / ``error`` frames aren't actionable here; the client
// shell handles them separately.
};
const unsub = client.onChat(chatId, handle);
return () => {
unsub();
buffer.current = null;
};
}, [chatId, client]);
const send = useCallback(
(content: string) => {
if (!chatId || !content.trim()) return;
setMessages((prev) => [
...prev,
{
id: crypto.randomUUID(),
role: "user",
content,
createdAt: Date.now(),
},
]);
client.sendMessage(chatId, content);
},
[chatId, client],
);
return { messages, isStreaming, send, setMessages };
}
+187
View File
@@ -0,0 +1,187 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { useClient } from "@/providers/ClientProvider";
import {
ApiError,
deleteSession as apiDeleteSession,
fetchSessionMessages,
listSessions,
} from "@/lib/api";
import { deriveTitle } from "@/lib/format";
import type { ChatSummary, UIMessage } from "@/lib/types";
/** Sidebar state: fetches the full session list and exposes create / delete actions. */
export function useSessions(): {
sessions: ChatSummary[];
loading: boolean;
error: string | null;
refresh: () => Promise<void>;
createChat: () => Promise<string>;
deleteChat: (key: string) => Promise<void>;
} {
const { client, token } = useClient();
const [sessions, setSessions] = useState<ChatSummary[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const tokenRef = useRef(token);
tokenRef.current = token;
const refresh = useCallback(async () => {
try {
setLoading(true);
const rows = await listSessions(tokenRef.current);
setSessions(rows);
setError(null);
} catch (e) {
const msg =
e instanceof ApiError ? `HTTP ${e.status}` : (e as Error).message;
setError(msg);
} finally {
setLoading(false);
}
}, []);
useEffect(() => {
void refresh();
}, [refresh]);
const createChat = useCallback(async (): Promise<string> => {
const chatId = await client.newChat();
const key = `websocket:${chatId}`;
// Optimistic insert; a subsequent refresh will replace it with the
// authoritative row once the server persists the session.
setSessions((prev) => [
{
key,
channel: "websocket",
chatId,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
preview: "",
},
...prev.filter((s) => s.key !== key),
]);
return chatId;
}, [client]);
const deleteChat = useCallback(
async (key: string) => {
await apiDeleteSession(tokenRef.current, key);
setSessions((prev) => prev.filter((s) => s.key !== key));
},
[],
);
return { sessions, loading, error, refresh, createChat, deleteChat };
}
/** Lazy-load a session's on-disk messages the first time the UI displays it. */
export function useSessionHistory(key: string | null): {
messages: UIMessage[];
loading: boolean;
error: string | null;
} {
const { token } = useClient();
const [state, setState] = useState<{
key: string | null;
messages: UIMessage[];
loading: boolean;
error: string | null;
}>({
key: null,
messages: [],
loading: false,
error: null,
});
useEffect(() => {
if (!key) {
setState({
key: null,
messages: [],
loading: false,
error: null,
});
return;
}
let cancelled = false;
// Mark the new key as loading immediately so callers never see stale
// messages from the previous session during the render right after a switch.
setState({
key,
messages: [],
loading: true,
error: null,
});
(async () => {
try {
const body = await fetchSessionMessages(token, key);
if (cancelled) return;
const ui: UIMessage[] = body.messages.flatMap((m, idx) => {
if (m.role !== "user" && m.role !== "assistant") return [];
if (typeof m.content !== "string") return [];
return [
{
id: `hist-${idx}`,
role: m.role,
content: m.content,
createdAt: m.timestamp ? Date.parse(m.timestamp) : Date.now(),
},
];
});
setState({
key,
messages: ui,
loading: false,
error: null,
});
} catch (e) {
if (cancelled) return;
// A 404 just means the session hasn't been persisted yet (brand-new
// chat, first message not sent). That's a normal state, not an error.
if (e instanceof ApiError && e.status === 404) {
setState({
key,
messages: [],
loading: false,
error: null,
});
} else {
setState({
key,
messages: [],
loading: false,
error: (e as Error).message,
});
}
}
})();
return () => {
cancelled = true;
};
}, [key, token]);
if (!key) {
return { messages: [], loading: false, error: null };
}
// Even before the effect above commits its loading state, never surface the
// previous session's payload for a brand-new key.
if (state.key !== key) {
return { messages: [], loading: true, error: null };
}
return {
messages: state.messages,
loading: state.loading,
error: state.error,
};
}
/** Produce a compact display title for a session. */
export function sessionTitle(
session: ChatSummary,
firstUserMessage?: string,
): string {
return deriveTitle(firstUserMessage || session.preview, "New chat");
}
+48
View File
@@ -0,0 +1,48 @@
import { useCallback, useEffect, useState } from "react";
type Theme = "light" | "dark";
const STORAGE_KEY = "nanobot-webui.theme";
function readStored(): Theme | null {
try {
const v = localStorage.getItem(STORAGE_KEY);
return v === "light" || v === "dark" ? v : null;
} catch {
return null;
}
}
function applyTheme(theme: Theme): void {
const root = document.documentElement;
if (theme === "dark") root.classList.add("dark");
else root.classList.remove("dark");
}
export function useTheme(): { theme: Theme; toggle: () => void; setTheme: (t: Theme) => void } {
const [theme, setThemeState] = useState<Theme>(() => {
const stored = readStored();
if (stored) return stored;
if (typeof window !== "undefined" && window.matchMedia) {
return window.matchMedia("(prefers-color-scheme: dark)").matches
? "dark"
: "light";
}
return "light";
});
useEffect(() => {
applyTheme(theme);
try {
localStorage.setItem(STORAGE_KEY, theme);
} catch {
// ignore
}
}, [theme]);
const setTheme = useCallback((t: Theme) => setThemeState(t), []);
const toggle = useCallback(
() => setThemeState((t) => (t === "dark" ? "light" : "dark")),
[],
);
return { theme, toggle, setTheme };
}