fix(webui): stabilize live thread rendering and navigation

This commit is contained in:
Xubin Ren
2026-05-13 16:39:07 +00:00
parent 6a4ed255de
commit 5d7f3f2751
14 changed files with 876 additions and 77 deletions
+74 -19
View File
@@ -2,6 +2,7 @@ import { useCallback, useEffect, useRef, useState } from "react";
import { useClient } from "@/providers/ClientProvider";
import { toMediaAttachment } from "@/lib/media";
import { toolTraceLinesFromEvents } from "@/lib/tool-traces";
import type { StreamError } from "@/lib/nanobot-client";
import type {
InboundEvent,
@@ -107,6 +108,59 @@ function closeReasoningStream(prev: UIMessage[]): UIMessage[] {
return prev;
}
function isReasoningOnlyPlaceholder(message: UIMessage): boolean {
return (
message.role === "assistant"
&& message.kind !== "trace"
&& message.content.trim().length === 0
&& !!message.reasoning
&& !message.reasoningStreaming
&& !message.media?.length
);
}
function isToolTrace(message: UIMessage | undefined): boolean {
return message?.kind === "trace";
}
function pruneReasoningOnlyPlaceholders(prev: UIMessage[]): UIMessage[] {
return prev.filter((message, index) => {
if (!isReasoningOnlyPlaceholder(message)) return true;
// A reasoning-only assistant row immediately followed by tool traces is
// the live equivalent of a persisted assistant tool-call message with
// empty content, reasoning_content, and tool_calls. Keep it so live render
// and history replay stay isomorphic.
return isToolTrace(prev[index + 1]);
});
}
function absorbCompleteAssistantMessage(
prev: UIMessage[],
message: Omit<UIMessage, "id" | "role" | "createdAt">,
): UIMessage[] {
const last = prev[prev.length - 1];
if (!last || !isReasoningOnlyPlaceholder(last)) {
return [
...prev,
{
id: crypto.randomUUID(),
role: "assistant",
createdAt: Date.now(),
...message,
},
];
}
return [
...prev.slice(0, -1),
{
...last,
...message,
isStreaming: false,
reasoningStreaming: false,
},
];
}
/**
* 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
@@ -286,9 +340,10 @@ export function useNanobotStream(
streamEndTimerRef.current = null;
}
setIsStreaming(false);
setMessages((prev) =>
prev.map((m) => (m.isStreaming ? { ...m, isStreaming: false } : m)),
);
setMessages((prev) => {
const finalized = prev.map((m) => (m.isStreaming ? { ...m, isStreaming: false } : m));
return pruneReasoningOnlyPlaceholders(finalized);
});
suppressStreamUntilTurnEndRef.current = false;
onTurnEnd?.();
return;
@@ -314,14 +369,20 @@ export function useNanobotStream(
// 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;
const structuredLines = toolTraceLinesFromEvents(ev.tool_events);
const lines = structuredLines.length > 0
? structuredLines
: ev.text
? [ev.text]
: [];
if (lines.length === 0) return;
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,
traces: [...(last.traces ?? [last.content]), ...lines],
content: lines[lines.length - 1],
};
return [...prev.slice(0, -1), merged];
}
@@ -331,8 +392,8 @@ export function useNanobotStream(
id: crypto.randomUUID(),
role: "tool",
kind: "trace",
content: line,
traces: [line],
content: lines[lines.length - 1],
traces: lines,
createdAt: Date.now(),
},
];
@@ -354,16 +415,10 @@ export function useNanobotStream(
setMessages((prev) => {
const filtered = activeId ? prev.filter((m) => m.id !== activeId) : prev;
const content = ev.text;
return [
...filtered,
{
id: crypto.randomUUID(),
role: "assistant",
content,
createdAt: Date.now(),
...(hasMedia ? { media } : {}),
},
];
return absorbCompleteAssistantMessage(filtered, {
content,
...(hasMedia ? { media } : {}),
});
});
if (hasMedia) {
suppressStreamUntilTurnEndRef.current = true;
@@ -395,7 +450,7 @@ export function useNanobotStream(
const previews = hasImages ? images!.map((i) => i.preview) : undefined;
setMessages((prev) => [
...prev,
...pruneReasoningOnlyPlaceholders(prev),
{
id: crypto.randomUUID(),
role: "user",
+51 -35
View File
@@ -10,6 +10,7 @@ import {
} from "@/lib/api";
import { deriveTitle } from "@/lib/format";
import { toMediaAttachment } from "@/lib/media";
import { formatToolCallTrace } from "@/lib/tool-traces";
import type { ChatSummary, UIMessage } from "@/lib/types";
const EMPTY_MESSAGES: UIMessage[] = [];
@@ -31,24 +32,6 @@ function reasoningFromHistory(message: HistoryMessage): string | undefined {
return parts.length > 0 ? parts.join("\n\n") : undefined;
}
function formatToolCallTrace(call: unknown): string | null {
if (!call || typeof call !== "object") return null;
const item = call as {
name?: unknown;
function?: { name?: unknown; arguments?: unknown };
};
const name =
typeof item.function?.name === "string"
? item.function.name
: typeof item.name === "string"
? item.name
: "";
if (!name) return null;
const args = item.function?.arguments;
if (typeof args === "string" && args.trim()) return `${name}(${args})`;
return `${name}()`;
}
function toolTracesFromHistory(message: HistoryMessage): string[] {
if (!Array.isArray(message.tool_calls)) return [];
return message.tool_calls
@@ -133,23 +116,31 @@ export function useSessionHistory(key: string | null): {
messages: UIMessage[];
loading: boolean;
error: string | null;
refresh: () => void;
version: number;
/** ``true`` when the last persisted assistant turn has ``tool_calls`` but no
* final text yet — the model was still processing when the page loaded. */
hasPendingToolCalls: boolean;
} {
const { token } = useClient();
const [refreshSeq, setRefreshSeq] = useState(0);
const refresh = useCallback(() => {
setRefreshSeq((value) => value + 1);
}, []);
const [state, setState] = useState<{
key: string | null;
messages: UIMessage[];
loading: boolean;
error: string | null;
hasPendingToolCalls: boolean;
version: number;
}>({
key: null,
messages: [],
loading: false,
error: null,
hasPendingToolCalls: false,
version: 0,
});
useEffect(() => {
@@ -160,19 +151,23 @@ export function useSessionHistory(key: string | null): {
loading: false,
error: null,
hasPendingToolCalls: false,
version: 0,
});
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,
hasPendingToolCalls: false,
});
setState((prev) => prev.key === key
? { ...prev, loading: true, error: null }
: {
key,
messages: [],
loading: true,
error: null,
hasPendingToolCalls: false,
version: 0,
});
(async () => {
try {
const body = await fetchSessionMessages(token, key);
@@ -203,7 +198,9 @@ export function useSessionHistory(key: string | null): {
: {}),
};
const traces = m.role === "assistant" ? toolTracesFromHistory(m) : [];
if (traces.length === 0) return [row];
if (traces.length === 0) {
return row.content.trim() || row.media?.length ? [row] : [];
}
return [
...(row.content.trim() || row.reasoning || row.media?.length ? [row] : []),
{
@@ -225,55 +222,74 @@ export function useSessionHistory(key: string | null): {
lastRaw?.role === "assistant" &&
Array.isArray(lastRaw.tool_calls) &&
lastRaw.tool_calls.length > 0;
setState({
setState((prev) => ({
key,
messages: ui,
loading: false,
error: null,
hasPendingToolCalls: hasPending,
});
version: prev.key === key ? prev.version + 1 : 1,
}));
} 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({
setState((prev) => ({
key,
messages: [],
loading: false,
error: null,
hasPendingToolCalls: false,
});
version: prev.key === key ? prev.version + 1 : 1,
}));
} else {
setState({
setState((prev) => ({
key,
messages: [],
loading: false,
error: (e as Error).message,
hasPendingToolCalls: false,
});
version: prev.key === key ? prev.version : 0,
}));
}
}
})();
return () => {
cancelled = true;
};
}, [key, token]);
}, [key, token, refreshSeq]);
if (!key) {
return { messages: EMPTY_MESSAGES, loading: false, error: null, hasPendingToolCalls: false };
return {
messages: EMPTY_MESSAGES,
loading: false,
error: null,
refresh,
version: 0,
hasPendingToolCalls: false,
};
}
// 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: EMPTY_MESSAGES, loading: true, error: null, hasPendingToolCalls: false };
return {
messages: EMPTY_MESSAGES,
loading: true,
error: null,
refresh,
version: 0,
hasPendingToolCalls: false,
};
}
return {
messages: state.messages,
loading: state.loading,
error: state.error,
refresh,
version: state.version,
hasPendingToolCalls: state.hasPendingToolCalls,
};
}