fix(webui): admit history without dropping live output (NAN-311)

This commit is contained in:
chengyongru authored and chengyongru committed 2026-10-22 01:22:49 +08:00
1 parent df63526ddf
commit b37a23698d
21 files changed
+3026 -1607

No files matched your search

+7 -513
View File
@@ -1,211 +1,24 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { useClient } from "@/providers/ClientProvider";
import { useNanobotStream } from "@/hooks/useNanobotStream";
import {
ApiError,
deleteSession as apiDeleteSession,
fetchSessionAutomations,
fetchWebuiThread,
listSessions,
} from "@/lib/api";
import { hasPendingAgentActivity } from "@/lib/activity-timeline";
import { projectThreadEvents } from "@/lib/thread-event-projection";
import { webuiThreadCache } from "@/lib/webui-thread-cache";
import { fetchLatestWebuiThread } from "@/lib/latest-thread-request";
import { readReloadSessions, writeReloadCache } from "@/lib/reload-cache";
import type {
ChatSummary,
SessionAutomationJob,
SessionDeleteResult,
UIMessage,
WebuiThreadPersistedPayload,
WorkspaceScopePayload,
} from "@/lib/types";
const EMPTY_MESSAGES: UIMessage[] = [];
const OLDER_HISTORY_PAGE_LIMIT = 120;
const CHAT_CREATE_TIMEOUT_MS = 60_000;
function isAbortError(error: unknown): boolean {
return (
typeof error === "object"
&& error !== null
&& "name" in error
&& error.name === "AbortError"
);
}
export type SessionHistoryContinuity = "initial" | "overlap" | "reset";
function projectPersistedThread(body: WebuiThreadPersistedPayload | null): {
messages: UIMessage[];
forkBoundaryMessageCount: number | null;
} {
const events = body?.events ?? [];
const messages = projectThreadEvents(events);
const boundaryIndex = body?.fork_boundary_event_index;
const forkBoundaryMessageCount = typeof boundaryIndex === "number"
&& Number.isInteger(boundaryIndex)
&& boundaryIndex >= 0
&& boundaryIndex <= events.length
? projectThreadEvents(events.slice(0, boundaryIndex)).length
: null;
return { messages, forkBoundaryMessageCount };
}
function sameSemanticMessage(a: UIMessage, b: UIMessage): boolean {
return (
a.role === b.role
&& (a.kind ?? "") === (b.kind ?? "")
&& a.content === b.content
&& (!a.turnId || !b.turnId || a.turnId === b.turnId)
);
}
function longestSemanticOverlap(previous: UIMessage[], latest: UIMessage[]): number {
const maxOverlap = Math.min(previous.length, latest.length);
for (let overlap = maxOverlap; overlap > 0; overlap -= 1) {
const previousStart = previous.length - overlap;
let matches = true;
for (let index = 0; index < overlap; index += 1) {
if (!sameSemanticMessage(previous[previousStart + index], latest[index])) {
matches = false;
break;
}
}
if (matches) return overlap;
}
return 0;
}
function mergeLatestHistory(
previous: UIMessage[],
latest: UIMessage[],
initial: boolean,
): {
continuity: SessionHistoryContinuity;
messages: UIMessage[];
retainedPrefixLength: number;
} {
if (initial) {
return {
continuity: "initial",
messages: latest,
retainedPrefixLength: 0,
};
}
const overlapLength = longestSemanticOverlap(previous, latest);
if (overlapLength === 0) {
return {
continuity: "reset",
messages: latest,
retainedPrefixLength: 0,
};
}
const retainedPrefixLength = previous.length - overlapLength;
return {
continuity: "overlap",
messages: [...previous.slice(0, retainedPrefixLength), ...latest],
retainedPrefixLength,
};
}
function hasPendingToolCallsFromThread(
body: Awaited<ReturnType<typeof fetchWebuiThread>>,
messages: UIMessage[],
): boolean {
if (typeof body?.has_pending_tool_calls === "boolean") {
return body.has_pending_tool_calls;
}
return hasPendingAgentActivity(messages);
}
function completedTurnIdsFromThread(
body: Awaited<ReturnType<typeof fetchWebuiThread>>,
): string[] {
if (Array.isArray(body?.completed_turn_ids)) {
return Array.from(new Set(body.completed_turn_ids.filter(
(turnId) => typeof turnId === "string" && turnId.length > 0,
)));
}
if (body?.has_pending_tool_calls !== false || body.active_turn_id) return [];
return Array.from(new Set(
body.events.flatMap((event) => (
event.event === "turn_end" && event.turn_id ? [event.turn_id] : []
)),
));
}
interface SessionHistoryState {
key: string | null;
messages: UIMessage[];
loading: boolean;
loadingOlder: boolean;
olderError: string | null;
error: string | null;
hasPendingToolCalls: boolean;
completedTurnIds: string[];
completionIdsProvided: boolean;
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,
olderError: null,
error: null,
hasPendingToolCalls: false,
completedTurnIds: [],
completionIdsProvided: false,
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 projected = projectPersistedThread(body);
const messages = projected.messages;
return {
key,
messages,
loading: false,
loadingOlder: false,
olderError: null,
error: null,
hasPendingToolCalls: hasPendingToolCallsFromThread(body, messages),
completedTurnIds: completedTurnIdsFromThread(body),
completionIdsProvided: Array.isArray(body.completed_turn_ids),
forkBoundaryMessageCount: projected.forkBoundaryMessageCount,
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[];
@@ -392,329 +205,10 @@ export function useSessions(): {
};
}
/** 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;
loadingOlder: boolean;
olderError: string | null;
error: string | null;
refresh: () => void;
loadOlder: () => Promise<void>;
hasMoreBefore: boolean;
userMessageOffset: number;
version: number;
forkBoundaryMessageCount: number | null;
/** ``true`` when the server reports that the turn is still in flight. */
hasPendingToolCalls: boolean;
/** Turn identities backed by explicit persisted completion events. */
completedTurnIds: string[];
/** A supplied list is authoritative even when empty (unfinished transcripts). */
completionIdsProvided: boolean;
/** Relationship between the latest canonical page and its predecessor. */
continuity: SessionHistoryContinuity;
/** Stable across overlapping latest pages; changes on initial load or reset. */
lineage: number;
/** Exact active turn when supplied by a current gateway. */
activeTurnId: string | null;
} {
const { client, getToken } = useClient();
const loadingOlderRef = useRef(false);
const olderRequestAbortRef = useRef<AbortController | null>(null);
const historyVersionRef = useRef(0);
const [refreshSeq, setRefreshSeq] = useState(0);
const refresh = useCallback(() => {
setRefreshSeq((value) => value + 1);
}, []);
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(() => () => {
olderRequestAbortRef.current?.abort();
olderRequestAbortRef.current = null;
loadingOlderRef.current = false;
}, []);
useEffect(() => {
if (!key) {
olderRequestAbortRef.current?.abort();
olderRequestAbortRef.current = null;
loadingOlderRef.current = false;
setState(emptyHistoryState(null));
return;
}
let cancelled = false;
const controller = new AbortController();
olderRequestAbortRef.current?.abort();
olderRequestAbortRef.current = null;
loadingOlderRef.current = false;
const cachedBody = webuiThreadCache.get(key);
const cachedVersion = cachedBody ? historyVersionRef.current + 1 : 0;
if (cachedBody) historyVersionRef.current = cachedVersion;
setState((prev) => prev.key === key
? {
...prev,
loading: cachedBody ? false : prev.messages.length === 0 && prev.lineage === 0,
loadingOlder: false,
error: null,
}
: cachedBody
? cachedHistoryState(key, cachedBody, cachedVersion)
: emptyHistoryState(key, true));
const adoptBody = (body: WebuiThreadPersistedPayload | null) => {
historyVersionRef.current += 1;
const responseVersion = historyVersionRef.current;
const completedTurnIds = completedTurnIdsFromThread(body);
const projected = projectPersistedThread(body);
const ui = projected.messages;
const hasPending = hasPendingToolCallsFromThread(body, ui);
const forkBoundary = projected.forkBoundaryMessageCount;
setState((prev) => {
const merged = prev.key === key
? mergeLatestHistory(prev.messages, ui, prev.lineage === 0)
: mergeLatestHistory([], ui, true);
const retainedPrefix = merged.retainedPrefixLength > 0;
const retainedForkBoundary = (
retainedPrefix
&& prev.forkBoundaryMessageCount !== null
&& prev.forkBoundaryMessageCount <= merged.retainedPrefixLength
)
? prev.forkBoundaryMessageCount
: null;
return {
key,
messages: merged.messages,
loading: false,
loadingOlder: false,
olderError: merged.continuity === "overlap"
&& (retainedPrefix || prev.beforeCursor === body?.page?.before_cursor)
? prev.olderError
: null,
error: null,
hasPendingToolCalls: hasPending,
completedTurnIds,
completionIdsProvided: Array.isArray(body?.completed_turn_ids),
forkBoundaryMessageCount: forkBoundary === null
? retainedForkBoundary
: forkBoundary + merged.retainedPrefixLength,
beforeCursor: retainedPrefix
? prev.beforeCursor
: body?.page?.before_cursor ?? null,
hasMoreBefore: retainedPrefix
? prev.hasMoreBefore
: body?.page?.has_more_before === true,
userMessageOffset: retainedPrefix
? prev.userMessageOffset
: Math.max(0, body?.page?.user_message_offset ?? 0),
version: responseVersion,
continuity: merged.continuity,
lineage: merged.continuity === "overlap"
? prev.lineage
: responseVersion,
activeTurnId: typeof body?.active_turn_id === "string"
? body.active_turn_id
: null,
};
});
};
let publishingBody = false;
const unsubscribeCache = webuiThreadCache.subscribe(key, (body) => {
if (publishingBody) return;
// A reconnect read can finish before this thread's older HTTP request.
// Adopt that published page now and prevent the older response from
// overwriting its completed content or lifecycle facts.
cancelled = true;
controller.abort();
olderRequestAbortRef.current?.abort();
olderRequestAbortRef.current = null;
loadingOlderRef.current = false;
adoptBody(body);
});
(async () => {
try {
const body = await fetchLatestWebuiThread(client, getToken(), key, controller.signal);
if (cancelled) return;
publishingBody = true;
if (body) webuiThreadCache.set(key, body);
else webuiThreadCache.delete(key);
publishingBody = false;
adoptBody(body);
} 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) => {
const continuity = prev.key === key && prev.lineage > 0
? "reset"
: "initial";
return {
...emptyHistoryState(key),
version: responseVersion,
continuity,
lineage: responseVersion,
};
});
} else {
setState((prev) => prev.key === key && prev.messages.length > 0
? { ...prev, loading: false, error: (e as Error).message }
: { ...emptyHistoryState(key), error: (e as Error).message });
}
}
})();
return () => {
cancelled = true;
controller.abort();
unsubscribeCache();
};
}, [client, getToken, key, refreshSeq]);
const loadOlder = useCallback(async () => {
if (!key || loadingOlderRef.current) return;
const requestKey = key;
const requestLineage = state.key === requestKey ? state.lineage : 0;
const beforeCursor = state.key === requestKey ? state.beforeCursor : null;
if (!beforeCursor || !state.hasMoreBefore || requestLineage === 0) return;
const matchesRequest = (candidate: typeof state) => (
candidate.key === requestKey
&& candidate.lineage === requestLineage
&& candidate.beforeCursor === beforeCursor
);
loadingOlderRef.current = true;
const controller = new AbortController();
olderRequestAbortRef.current = controller;
setState((prev) => matchesRequest(prev)
? { ...prev, loadingOlder: true, olderError: null }
: prev);
try {
const body = await fetchWebuiThread(getToken(), requestKey, {
limit: OLDER_HISTORY_PAGE_LIMIT,
before: beforeCursor,
signal: controller.signal,
});
setState((prev) => {
if (!matchesRequest(prev)) return prev;
const projected = projectPersistedThread(body);
if (!body || !projected.messages.length) {
return {
...prev,
loadingOlder: false,
hasMoreBefore: false,
beforeCursor: null,
};
}
const older = projected.messages;
const olderBoundary = projected.forkBoundaryMessageCount;
const shiftedBoundary = prev.forkBoundaryMessageCount === null
? null
: prev.forkBoundaryMessageCount + older.length;
const nextMessages = [...older, ...prev.messages];
// An older page cannot change the authoritative latest-turn lifecycle
// state or masquerade as a completed latest-page refresh.
return {
...prev,
messages: nextMessages,
loadingOlder: false,
olderError: null,
forkBoundaryMessageCount: olderBoundary ?? shiftedBoundary,
beforeCursor: body.page?.before_cursor ?? null,
hasMoreBefore: body.page?.has_more_before === true,
userMessageOffset: Math.max(0, body.page?.user_message_offset ?? 0),
};
});
} catch (e) {
if (isAbortError(e)) return;
setState((prev) => matchesRequest(prev)
? {
...prev,
loadingOlder: false,
olderError: (e as Error).message || "Could not load earlier messages",
}
: prev);
} finally {
if (olderRequestAbortRef.current === controller) {
olderRequestAbortRef.current = null;
loadingOlderRef.current = false;
}
}
}, [
key,
state.beforeCursor,
state.hasMoreBefore,
state.key,
state.lineage,
getToken,
]);
if (!key) {
return {
messages: EMPTY_MESSAGES,
loading: false,
loadingOlder: false,
olderError: null,
error: null,
refresh,
loadOlder,
hasMoreBefore: false,
userMessageOffset: 0,
version: 0,
forkBoundaryMessageCount: null,
hasPendingToolCalls: false,
completedTurnIds: [],
completionIdsProvided: false,
continuity: "initial",
lineage: 0,
activeTurnId: 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: EMPTY_MESSAGES,
loading: true,
loadingOlder: false,
olderError: null,
error: null,
refresh,
loadOlder,
hasMoreBefore: false,
userMessageOffset: 0,
version: 0,
forkBoundaryMessageCount: null,
hasPendingToolCalls: false,
completedTurnIds: [],
completionIdsProvided: false,
continuity: "initial",
lineage: 0,
activeTurnId: null,
};
}
return {
messages: state.messages,
loading: state.loading,
loadingOlder: state.loadingOlder,
olderError: state.olderError,
error: state.error,
refresh,
loadOlder,
hasMoreBefore: state.hasMoreBefore,
userMessageOffset: state.userMessageOffset,
version: state.version,
forkBoundaryMessageCount: state.forkBoundaryMessageCount,
hasPendingToolCalls: state.hasPendingToolCalls,
completedTurnIds: state.completedTurnIds,
completionIdsProvided: state.completionIdsProvided,
continuity: state.continuity,
lineage: state.lineage,
activeTurnId: state.activeTurnId,
};
/** Read-only history view backed by the conversation owner. */
export function useSessionHistory(key: string | null) {
const { messages, history, refreshHistory, loadOlder } = useNanobotStream(
null, undefined, false, undefined, undefined, undefined, { key },
);
return { messages, ...history, refresh: refreshHistory, loadOlder };
}