fix(webui): cache and defer thread history

This commit is contained in:
chengyongru authored and chengyongru committed 2026-09-12 17:09:51 +08:00
1 parent 7ba60c2ef0
commit a490cd629b
30 files changed
+1306 -145

No files matched your search

+100 -85
View File
@@ -11,16 +11,18 @@ import {
} from "@/lib/api";
import { hasPendingAgentActivity } from "@/lib/activity-timeline";
import { deriveTitle } from "@/lib/format";
import { webuiThreadCache } from "@/lib/webui-thread-cache";
import type {
ChatSummary,
SessionAutomationJob,
SessionDeleteResult,
UIMessage,
WebuiThreadPersistedPayload,
WorkspaceScopePayload,
} from "@/lib/types";
const EMPTY_MESSAGES: UIMessage[] = [];
const INITIAL_HISTORY_PAGE_LIMIT = 80;
const INITIAL_HISTORY_PAGE_LIMIT = 40;
const OLDER_HISTORY_PAGE_LIMIT = 120;
const CHAT_CREATE_TIMEOUT_MS = 60_000;
@@ -121,6 +123,71 @@ function completedTurnIdsFromThread(
));
}
interface SessionHistoryState {
key: string | null;
messages: UIMessage[];
loading: boolean;
loadingOlder: boolean;
error: string | null;
hasPendingToolCalls: boolean;
completedTurnIds: string[];
forkBoundaryMessageCount: number | null;
beforeCursor: string | null;
hasMoreBefore: boolean;
userMessageOffset: number;
version: number;
continuity: SessionHistoryContinuity;
lineage: number;
activeTurnId: string | null;
}
function emptyHistoryState(key: string | null, loading = false): SessionHistoryState {
return {
key,
messages: [],
loading,
loadingOlder: false,
error: null,
hasPendingToolCalls: false,
completedTurnIds: [],
forkBoundaryMessageCount: null,
beforeCursor: null,
hasMoreBefore: false,
userMessageOffset: 0,
version: 0,
continuity: "initial",
lineage: 0,
activeTurnId: null,
};
}
function cachedHistoryState(
key: string,
body: WebuiThreadPersistedPayload,
version: number,
): SessionHistoryState {
const messages = persistedMessagesToUi(body.messages ?? []);
return {
key,
messages,
loading: false,
loadingOlder: false,
error: null,
hasPendingToolCalls: hasPendingToolCallsFromThread(body, messages),
completedTurnIds: completedTurnIdsFromThread(body),
forkBoundaryMessageCount: typeof body.fork_boundary_message_count === "number"
? Math.max(0, Math.min(body.fork_boundary_message_count, messages.length))
: null,
beforeCursor: body.page?.before_cursor ?? null,
hasMoreBefore: body.page?.has_more_before === true,
userMessageOffset: Math.max(0, body.page?.user_message_offset ?? 0),
version,
continuity: "initial",
lineage: version,
activeTurnId: typeof body.active_turn_id === "string" ? body.active_turn_id : null,
};
}
/** Sidebar state: fetches the full session list and exposes create / delete actions. */
export function useSessions(): {
sessions: ChatSummary[];
@@ -273,6 +340,7 @@ export function useSessions(): {
const result = await apiDeleteSession(client, key, options);
if (result.blocked_by_automations || (!result.deleted && !optimistic)) return result;
optimisticKeysRef.current.delete(key);
webuiThreadCache.delete(key);
setSessions((prev) => prev.filter((s) => s.key !== key));
// The gateway may have restarted and forgotten an unpersisted chat's
// draft scope, but removing that optimistic session is still a deletion.
@@ -329,38 +397,12 @@ export function useSessionHistory(key: string | null): {
const refresh = useCallback(() => {
setRefreshSeq((value) => value + 1);
}, []);
const [state, setState] = useState<{
key: string | null;
messages: UIMessage[];
loading: boolean;
loadingOlder: boolean;
error: string | null;
hasPendingToolCalls: boolean;
completedTurnIds: string[];
forkBoundaryMessageCount: number | null;
beforeCursor: string | null;
hasMoreBefore: boolean;
userMessageOffset: number;
version: number;
continuity: SessionHistoryContinuity;
lineage: number;
activeTurnId: string | null;
}>({
key: null,
messages: [],
loading: false,
loadingOlder: false,
error: null,
hasPendingToolCalls: false,
completedTurnIds: [],
forkBoundaryMessageCount: null,
beforeCursor: null,
hasMoreBefore: false,
userMessageOffset: 0,
version: 0,
continuity: "initial",
lineage: 0,
activeTurnId: null,
const [state, setState] = useState<SessionHistoryState>(() => {
if (!key) return emptyHistoryState(null);
const cached = webuiThreadCache.get(key);
if (!cached) return emptyHistoryState(key, true);
historyVersionRef.current = 1;
return cachedHistoryState(key, cached, historyVersionRef.current);
});
useEffect(() => () => {
@@ -374,23 +416,7 @@ export function useSessionHistory(key: string | null): {
olderRequestAbortRef.current?.abort();
olderRequestAbortRef.current = null;
loadingOlderRef.current = false;
setState({
key: null,
messages: [],
loading: false,
loadingOlder: false,
error: null,
hasPendingToolCalls: false,
completedTurnIds: [],
forkBoundaryMessageCount: null,
beforeCursor: null,
hasMoreBefore: false,
userMessageOffset: 0,
version: 0,
continuity: "initial",
lineage: 0,
activeTurnId: null,
});
setState(emptyHistoryState(null));
return;
}
let cancelled = false;
@@ -398,35 +424,37 @@ export function useSessionHistory(key: string | null): {
olderRequestAbortRef.current?.abort();
olderRequestAbortRef.current = null;
loadingOlderRef.current = 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.
const cachedBody = webuiThreadCache.get(key);
const cachedVersion = cachedBody ? historyVersionRef.current + 1 : 0;
if (cachedBody) historyVersionRef.current = cachedVersion;
setState((prev) => prev.key === key
? { ...prev, loading: true, loadingOlder: false, error: null }
: {
key,
messages: [],
loading: true,
? {
...prev,
loading: cachedBody ? false : prev.messages.length === 0 && prev.lineage === 0,
loadingOlder: false,
error: null,
hasPendingToolCalls: false,
completedTurnIds: [],
forkBoundaryMessageCount: null,
beforeCursor: null,
hasMoreBefore: false,
userMessageOffset: 0,
version: 0,
continuity: "initial",
lineage: 0,
activeTurnId: null,
});
}
: cachedBody
? cachedHistoryState(key, cachedBody, cachedVersion)
: emptyHistoryState(key, true));
(async () => {
try {
const body = await fetchWebuiThread(getToken(), key, {
limit: INITIAL_HISTORY_PAGE_LIMIT,
direction: "latest",
signal: controller.signal,
revision: cachedBody?.revision,
cached: cachedBody,
});
if (cancelled) return;
if (body === cachedBody && cachedBody !== undefined) {
setState((prev) => prev.key === key
? { ...prev, loading: false, error: null }
: prev);
return;
}
if (body) webuiThreadCache.set(key, body);
else webuiThreadCache.delete(key);
historyVersionRef.current += 1;
const responseVersion = historyVersionRef.current;
const completedTurnIds = completedTurnIdsFromThread(body);
@@ -480,6 +508,7 @@ export function useSessionHistory(key: string | null): {
} catch (e) {
if (cancelled || isAbortError(e)) return;
if (e instanceof ApiError && e.status === 404) {
webuiThreadCache.delete(key);
historyVersionRef.current += 1;
const responseVersion = historyVersionRef.current;
setState((prev) => {
@@ -505,23 +534,9 @@ export function useSessionHistory(key: string | null): {
};
});
} else {
setState((prev) => ({
key,
messages: [],
loading: false,
loadingOlder: false,
error: (e as Error).message,
hasPendingToolCalls: false,
completedTurnIds: [],
forkBoundaryMessageCount: null,
beforeCursor: null,
hasMoreBefore: false,
userMessageOffset: 0,
version: prev.key === key ? prev.version : 0,
continuity: prev.key === key ? prev.continuity : "initial",
lineage: prev.key === key ? prev.lineage : 0,
activeTurnId: prev.key === key ? prev.activeTurnId : null,
}));
setState((prev) => prev.key === key && prev.messages.length > 0
? { ...prev, loading: false, error: (e as Error).message }
: { ...emptyHistoryState(key), error: (e as Error).message });
}
}
})();