fix(webui): cache and defer thread history
This commit is contained in:
1 parent
7ba60c2ef0
commit
a490cd629b
30 files changed
+1306
-145
No files matched your search
@@ -127,6 +127,10 @@ function countActivity(
|
||||
continue;
|
||||
}
|
||||
if (m.kind === "trace") {
|
||||
if (m.traceDetail) {
|
||||
toolCalls += m.traceDetail.traceCount;
|
||||
continue;
|
||||
}
|
||||
const lines = traceLines(m);
|
||||
for (const line of lines) {
|
||||
if (!isCliRunTraceLine(line) && !isMcpRunTraceLine(line)) {
|
||||
@@ -157,6 +161,8 @@ interface AgentActivityClusterProps {
|
||||
retryStatus?: RetryStatus | null;
|
||||
cliApps?: CliAppInfo[];
|
||||
mcpPresets?: McpPresetInfo[];
|
||||
traceDetailScope?: string | null;
|
||||
onLoadTraceDetails?: (refs: string[]) => void | Promise<void>;
|
||||
onOpenFilePreview?: (path: string) => void;
|
||||
}
|
||||
|
||||
@@ -228,6 +234,8 @@ function FoldedAgentActivity({
|
||||
retryStatus = null,
|
||||
cliApps = EMPTY_CLI_APPS,
|
||||
mcpPresets = EMPTY_MCP_PRESETS,
|
||||
traceDetailScope = null,
|
||||
onLoadTraceDetails,
|
||||
onOpenFilePreview,
|
||||
}: AgentActivityClusterProps) {
|
||||
const { t } = useTranslation();
|
||||
@@ -265,6 +273,7 @@ function FoldedAgentActivity({
|
||||
const [userToggledOuter, setUserToggledOuter] = useState(false);
|
||||
const [outerOpenLocal, setOuterOpenLocal] = useState(false);
|
||||
const [completionHoldOpen, setCompletionHoldOpen] = useState(false);
|
||||
const [failedTraceDetailKey, setFailedTraceDetailKey] = useState<string | null>(null);
|
||||
const [now, setNow] = useState(() => Date.now());
|
||||
const [activityScrollFade, setActivityScrollFade] = useState({ top: false, bottom: false });
|
||||
const activityScrollRef = useRef<HTMLDivElement>(null);
|
||||
@@ -277,6 +286,28 @@ function FoldedAgentActivity({
|
||||
const outerExpanded = userToggledOuter
|
||||
? outerOpenLocal
|
||||
: isTurnStreaming || completionHoldOpen || (wasTurnStreaming && !isTurnStreaming);
|
||||
const deferredTraceRefs = useMemo(
|
||||
() => Array.from(new Set(
|
||||
messages
|
||||
.map((message) => message.traceDetail?.ref)
|
||||
.filter((ref): ref is string => typeof ref === "string" && ref.length > 0),
|
||||
)),
|
||||
[messages],
|
||||
);
|
||||
const traceDetailKey = useMemo(
|
||||
() => `${traceDetailScope ?? ""}\u0000${deferredTraceRefs.join("\u0000")}`,
|
||||
[deferredTraceRefs, traceDetailScope],
|
||||
);
|
||||
const traceDetailLoadFailed = failedTraceDetailKey === traceDetailKey;
|
||||
const requestTraceDetails = useCallback(async (refs: string[]) => {
|
||||
if (!onLoadTraceDetails) return;
|
||||
setFailedTraceDetailKey(null);
|
||||
try {
|
||||
await onLoadTraceDetails(refs);
|
||||
} catch {
|
||||
setFailedTraceDetailKey(`${traceDetailScope ?? ""}\u0000${refs.join("\u0000")}`);
|
||||
}
|
||||
}, [onLoadTraceDetails, traceDetailScope]);
|
||||
|
||||
const hasVisibleActivity = reasoningSteps > 0 || toolCalls > 0 || modelSegments > 0 || cliCount > 0 || mcpCount > 0 || fileCount > 0;
|
||||
const hasOnlyFileActivity = fileCount > 0 && activityMessages.every(messageHasOnlyFileActivity);
|
||||
@@ -397,6 +428,12 @@ function FoldedAgentActivity({
|
||||
|
||||
useEffect(() => cancelActivityScrollFrame, [cancelActivityScrollFrame]);
|
||||
|
||||
useEffect(() => {
|
||||
if (outerExpanded && deferredTraceRefs.length > 0) {
|
||||
void requestTraceDetails(deferredTraceRefs);
|
||||
}
|
||||
}, [deferredTraceRefs, outerExpanded, requestTraceDetails]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isTurnStreaming || !pageVisible || !threadVisible) return undefined;
|
||||
setNow(Date.now());
|
||||
@@ -453,6 +490,18 @@ function FoldedAgentActivity({
|
||||
onToggle={toggleOuter}
|
||||
onScroll={onActivityScroll}
|
||||
>
|
||||
{traceDetailLoadFailed ? (
|
||||
<div role="alert" className="flex items-center gap-2 py-1 text-[12px] text-destructive">
|
||||
<span>{t("message.traceDetailsLoadFailed", { defaultValue: "Full activity details could not be loaded." })}</span>
|
||||
<button
|
||||
type="button"
|
||||
className="shrink-0 rounded-sm font-medium underline underline-offset-2 hover:no-underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||
onClick={() => void requestTraceDetails(deferredTraceRefs)}
|
||||
>
|
||||
{t("message.retryTraceDetails", { defaultValue: "Retry" })}
|
||||
</button>
|
||||
</div>
|
||||
) : null}
|
||||
<ActivityMessageTimeline
|
||||
messages={activityMessages}
|
||||
active={isTurnStreaming}
|
||||
|
||||
@@ -20,6 +20,8 @@ interface ThreadMessagesProps {
|
||||
mcpPresets?: McpPresetInfo[];
|
||||
slashCommands?: SlashCommand[];
|
||||
forkBoundaryMessageCount?: number | null;
|
||||
traceDetailScope?: string | null;
|
||||
onLoadTraceDetails?: (refs: string[]) => void | Promise<void>;
|
||||
onOpenFilePreview?: (path: string) => void;
|
||||
onForkFromMessage?: (beforeUserIndex: number) => void;
|
||||
onQuoteSelection?: (text: string) => void;
|
||||
@@ -70,6 +72,8 @@ export function ThreadMessages({
|
||||
mcpPresets = [],
|
||||
slashCommands = [],
|
||||
forkBoundaryMessageCount = null,
|
||||
traceDetailScope = null,
|
||||
onLoadTraceDetails,
|
||||
onOpenFilePreview,
|
||||
onForkFromMessage,
|
||||
onQuoteSelection,
|
||||
@@ -175,6 +179,8 @@ export function ThreadMessages({
|
||||
cliApps={cliApps}
|
||||
mcpPresets={mcpPresets}
|
||||
slashCommands={slashCommands}
|
||||
traceDetailScope={traceDetailScope}
|
||||
onLoadTraceDetails={onLoadTraceDetails}
|
||||
onOpenFilePreview={onOpenFilePreview}
|
||||
onForkFromMessage={onForkFromMessage}
|
||||
/>
|
||||
@@ -258,6 +264,8 @@ interface ThreadDisplayUnitProps {
|
||||
cliApps: CliAppInfo[];
|
||||
mcpPresets: McpPresetInfo[];
|
||||
slashCommands: SlashCommand[];
|
||||
traceDetailScope: string | null;
|
||||
onLoadTraceDetails?: (refs: string[]) => void | Promise<void>;
|
||||
onOpenFilePreview?: (path: string) => void;
|
||||
onForkFromMessage?: (beforeUserIndex: number) => void;
|
||||
}
|
||||
@@ -278,6 +286,8 @@ const ThreadDisplayUnit = memo(function ThreadDisplayUnit({
|
||||
cliApps,
|
||||
mcpPresets,
|
||||
slashCommands,
|
||||
traceDetailScope,
|
||||
onLoadTraceDetails,
|
||||
onOpenFilePreview,
|
||||
onForkFromMessage,
|
||||
}: ThreadDisplayUnitProps) {
|
||||
@@ -325,6 +335,8 @@ const ThreadDisplayUnit = memo(function ThreadDisplayUnit({
|
||||
startedAtMs={unit.startedAtMs}
|
||||
cliApps={cliApps}
|
||||
mcpPresets={mcpPresets}
|
||||
traceDetailScope={traceDetailScope}
|
||||
onLoadTraceDetails={onLoadTraceDetails}
|
||||
onOpenFilePreview={onOpenFilePreview}
|
||||
/>
|
||||
) : (
|
||||
@@ -364,6 +376,8 @@ function threadDisplayUnitPropsEqual(
|
||||
&& previous.cliApps === next.cliApps
|
||||
&& previous.mcpPresets === next.mcpPresets
|
||||
&& previous.slashCommands === next.slashCommands
|
||||
&& previous.traceDetailScope === next.traceDetailScope
|
||||
&& previous.onLoadTraceDetails === next.onLoadTraceDetails
|
||||
&& previous.onOpenFilePreview === next.onOpenFilePreview
|
||||
&& previous.onForkFromMessage === next.onForkFromMessage
|
||||
);
|
||||
|
||||
@@ -26,6 +26,7 @@ import {
|
||||
fetchInstalledCliApps,
|
||||
fetchMcpPresets,
|
||||
fetchSettings,
|
||||
fetchWebuiThreadTraceDetail,
|
||||
listSlashCommands,
|
||||
} from "@/lib/api";
|
||||
import {
|
||||
@@ -806,6 +807,9 @@ export function ThreadShell({
|
||||
const completedCanonicalHydrateVersionRef = useRef<Map<string, number>>(new Map());
|
||||
const committedHistoryLineageRef = useRef<Map<string, number>>(new Map());
|
||||
const sessionKeyByChatIdRef = useRef<Map<string, string>>(new Map());
|
||||
const traceDetailRequestsRef = useRef<Map<string, Promise<void>>>(new Map());
|
||||
const activeHistoryKeyRef = useRef(historyKey);
|
||||
activeHistoryKeyRef.current = historyKey;
|
||||
const currentUiMessagesRef = useRef<UIMessage[] | null>(null);
|
||||
const uiRevisionRef = useRef(0);
|
||||
const showTemporaryChatControl =
|
||||
@@ -840,6 +844,49 @@ export function ThreadShell({
|
||||
dismissStreamError,
|
||||
} = useNanobotStream(chatId, initial, hasPendingToolCalls, handleTurnEnd);
|
||||
|
||||
const loadTraceDetails = useCallback(async (refs: string[]) => {
|
||||
const requestKey = historyKey;
|
||||
if (!requestKey) return;
|
||||
const requests: Promise<void>[] = [];
|
||||
for (const ref of refs) {
|
||||
const requestId = `${requestKey}:${ref}`;
|
||||
const existing = traceDetailRequestsRef.current.get(requestId);
|
||||
if (existing) {
|
||||
requests.push(existing);
|
||||
continue;
|
||||
}
|
||||
const request = fetchWebuiThreadTraceDetail(getToken(), requestKey, ref)
|
||||
.then((detail) => {
|
||||
if (activeHistoryKeyRef.current !== requestKey) return;
|
||||
setMessages((current) => current.map((message) => (
|
||||
message.traceDetail?.ref === ref
|
||||
? {
|
||||
...message,
|
||||
content: detail.content,
|
||||
traces: detail.traces,
|
||||
toolEvents: detail.toolEvents,
|
||||
traceDetail: undefined,
|
||||
}
|
||||
: message
|
||||
)));
|
||||
})
|
||||
.catch((error: unknown) => {
|
||||
if (activeHistoryKeyRef.current !== requestKey) return;
|
||||
throw error;
|
||||
})
|
||||
.finally(() => {
|
||||
traceDetailRequestsRef.current.delete(requestId);
|
||||
});
|
||||
traceDetailRequestsRef.current.set(requestId, request);
|
||||
requests.push(request);
|
||||
}
|
||||
await Promise.all(requests);
|
||||
}, [getToken, historyKey, setMessages]);
|
||||
|
||||
useEffect(() => () => {
|
||||
activeHistoryKeyRef.current = null;
|
||||
}, []);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
if (currentUiMessagesRef.current === messages) return;
|
||||
currentUiMessagesRef.current = messages;
|
||||
@@ -1748,6 +1795,8 @@ export function ThreadShell({
|
||||
loadingOlder={loadingOlder}
|
||||
userMessageOffset={userMessageOffset}
|
||||
onLoadOlder={loadOlder}
|
||||
traceDetailScope={historyKey}
|
||||
onLoadTraceDetails={messagesReady ? loadTraceDetails : undefined}
|
||||
onOpenFilePreview={historyKey ? handleOpenFilePreview : undefined}
|
||||
onForkFromMessage={onForkChat ? handleForkFromMessage : undefined}
|
||||
onQuoteSelection={session ? handleQuoteSelection : undefined}
|
||||
|
||||
@@ -56,6 +56,8 @@ interface ThreadViewportProps {
|
||||
loadingOlder?: boolean;
|
||||
userMessageOffset?: number;
|
||||
onLoadOlder?: () => Promise<void> | void;
|
||||
traceDetailScope?: string | null;
|
||||
onLoadTraceDetails?: (refs: string[]) => void | Promise<void>;
|
||||
onOpenFilePreview?: (path: string) => void;
|
||||
onForkFromMessage?: (beforeUserIndex: number) => void;
|
||||
onQuoteSelection?: (text: string) => void;
|
||||
@@ -71,7 +73,7 @@ const SOFT_KEYBOARD_MIN_INSET_PX = 80;
|
||||
const SESSION_HANDOFF_EXIT_DURATION_MS = 80;
|
||||
const SESSION_HANDOFF_ENTER_DURATION_MS = 140;
|
||||
const SESSION_HANDOFF_OPACITY = 0.82;
|
||||
export const INITIAL_HISTORY_WINDOW = 160;
|
||||
export const INITIAL_HISTORY_WINDOW = 120;
|
||||
export const HISTORY_WINDOW_INCREMENT = 120;
|
||||
|
||||
interface HistoryScrollAnchor {
|
||||
@@ -239,6 +241,8 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
|
||||
loadingOlder = false,
|
||||
userMessageOffset = 0,
|
||||
onLoadOlder,
|
||||
traceDetailScope = null,
|
||||
onLoadTraceDetails,
|
||||
onOpenFilePreview,
|
||||
onForkFromMessage,
|
||||
onQuoteSelection,
|
||||
@@ -886,6 +890,8 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
|
||||
mcpPresets={mcpPresets}
|
||||
slashCommands={slashCommands}
|
||||
forkBoundaryMessageCount={visibleForkBoundaryMessageCount}
|
||||
traceDetailScope={traceDetailScope}
|
||||
onLoadTraceDetails={onLoadTraceDetails}
|
||||
onOpenFilePreview={onOpenFilePreview}
|
||||
onForkFromMessage={onForkFromMessage}
|
||||
onQuoteSelection={onQuoteSelection}
|
||||
|
||||
+100
-85
@@ -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 });
|
||||
}
|
||||
}
|
||||
})();
|
||||
|
||||
@@ -1750,6 +1750,8 @@
|
||||
"activityWorkingFor": "Working for {{duration}}",
|
||||
"activityWorked": "Worked",
|
||||
"activityWorkedFor": "Worked for {{duration}}",
|
||||
"traceDetailsLoadFailed": "Full activity details could not be loaded.",
|
||||
"retryTraceDetails": "Retry",
|
||||
"retryConnection": "Connection failed",
|
||||
"retryTimeout": "Model timed out",
|
||||
"retryRateLimit": "Rate limited",
|
||||
|
||||
@@ -1578,6 +1578,8 @@
|
||||
"activityWorkingFor": "Trabajando durante {{duration}}",
|
||||
"activityWorked": "Trabajo completado",
|
||||
"activityWorkedFor": "Trabajó durante {{duration}}",
|
||||
"traceDetailsLoadFailed": "No se pudieron cargar los detalles completos de la actividad.",
|
||||
"retryTraceDetails": "Reintentar",
|
||||
"retryConnection": "Error de conexión",
|
||||
"retryTimeout": "Se agotó el tiempo de espera del modelo",
|
||||
"retryRateLimit": "Límite de solicitudes alcanzado",
|
||||
|
||||
@@ -1577,6 +1577,8 @@
|
||||
"activityWorkingFor": "Travail en cours depuis {{duration}}",
|
||||
"activityWorked": "Travail terminé",
|
||||
"activityWorkedFor": "Travail terminé en {{duration}}",
|
||||
"traceDetailsLoadFailed": "Impossible de charger les détails complets de l’activité.",
|
||||
"retryTraceDetails": "Réessayer",
|
||||
"retryConnection": "Échec de la connexion",
|
||||
"retryTimeout": "Délai d’attente du modèle dépassé",
|
||||
"retryRateLimit": "Limite de requêtes atteinte",
|
||||
|
||||
@@ -1577,6 +1577,8 @@
|
||||
"activityWorkingFor": "Memproses selama {{duration}}",
|
||||
"activityWorked": "Selesai memproses",
|
||||
"activityWorkedFor": "Diproses selama {{duration}}",
|
||||
"traceDetailsLoadFailed": "Detail aktivitas lengkap tidak dapat dimuat.",
|
||||
"retryTraceDetails": "Coba lagi",
|
||||
"retryConnection": "Koneksi gagal",
|
||||
"retryTimeout": "Waktu respons model habis",
|
||||
"retryRateLimit": "Batas permintaan tercapai",
|
||||
|
||||
@@ -1577,6 +1577,8 @@
|
||||
"activityWorkingFor": "{{duration}}作業中",
|
||||
"activityWorked": "作業しました",
|
||||
"activityWorkedFor": "{{duration}}作業しました",
|
||||
"traceDetailsLoadFailed": "アクティビティの詳細を読み込めませんでした。",
|
||||
"retryTraceDetails": "再試行",
|
||||
"retryConnection": "接続に失敗しました",
|
||||
"retryTimeout": "モデルがタイムアウトしました",
|
||||
"retryRateLimit": "リクエスト制限に達しました",
|
||||
|
||||
@@ -1577,6 +1577,8 @@
|
||||
"activityWorkingFor": "{{duration}} 동안 작업 중",
|
||||
"activityWorked": "작업함",
|
||||
"activityWorkedFor": "{{duration}} 동안 작업함",
|
||||
"traceDetailsLoadFailed": "전체 활동 세부 정보를 불러올 수 없습니다.",
|
||||
"retryTraceDetails": "다시 시도",
|
||||
"retryConnection": "연결 실패",
|
||||
"retryTimeout": "모델 응답 시간 초과",
|
||||
"retryRateLimit": "요청 한도 초과",
|
||||
|
||||
@@ -1564,6 +1564,8 @@
|
||||
"activityWorkingFor": "Trabalhando por {{duration}}",
|
||||
"activityWorked": "Trabalhou",
|
||||
"activityWorkedFor": "Trabalhou por {{duration}}",
|
||||
"traceDetailsLoadFailed": "Não foi possível carregar os detalhes completos da atividade.",
|
||||
"retryTraceDetails": "Tentar novamente",
|
||||
"retryConnection": "Falha na conexão",
|
||||
"retryTimeout": "O modelo excedeu o tempo limite",
|
||||
"retryRateLimit": "Limite de solicitações atingido",
|
||||
|
||||
@@ -1577,6 +1577,8 @@
|
||||
"activityWorkingFor": "Đang xử lý trong {{duration}}",
|
||||
"activityWorked": "Đã xử lý",
|
||||
"activityWorkedFor": "Đã xử lý trong {{duration}}",
|
||||
"traceDetailsLoadFailed": "Không thể tải đầy đủ chi tiết hoạt động.",
|
||||
"retryTraceDetails": "Thử lại",
|
||||
"retryConnection": "Kết nối thất bại",
|
||||
"retryTimeout": "Mô hình đã hết thời gian chờ",
|
||||
"retryRateLimit": "Đã đạt giới hạn yêu cầu",
|
||||
|
||||
@@ -1750,6 +1750,8 @@
|
||||
"activityWorkingFor": "处理中 {{duration}}",
|
||||
"activityWorked": "已处理",
|
||||
"activityWorkedFor": "处理了 {{duration}}",
|
||||
"traceDetailsLoadFailed": "无法加载完整活动详情。",
|
||||
"retryTraceDetails": "重试",
|
||||
"retryConnection": "连接失败",
|
||||
"retryTimeout": "模型响应超时",
|
||||
"retryRateLimit": "请求频率受限",
|
||||
|
||||
@@ -1576,6 +1576,8 @@
|
||||
"activityWorkingFor": "處理中,已 {{duration}}",
|
||||
"activityWorked": "已處理",
|
||||
"activityWorkedFor": "已處理 {{duration}}",
|
||||
"traceDetailsLoadFailed": "無法載入完整活動詳情。",
|
||||
"retryTraceDetails": "重試",
|
||||
"retryConnection": "連線失敗",
|
||||
"retryTimeout": "模型回應逾時",
|
||||
"retryRateLimit": "請求頻率受限",
|
||||
|
||||
+24
-1
@@ -41,6 +41,7 @@ import type {
|
||||
WebSearchSettingsUpdate,
|
||||
WorkspacesPayload,
|
||||
WebuiThreadPersistedPayload,
|
||||
WebuiThreadTraceDetailPayload,
|
||||
WorkspaceScopePayload,
|
||||
} from "./types";
|
||||
import { fetchWithTimeout } from "./http";
|
||||
@@ -226,6 +227,8 @@ export interface FetchWebuiThreadOptions {
|
||||
direction?: "latest";
|
||||
before?: string | null;
|
||||
signal?: AbortSignal;
|
||||
revision?: string;
|
||||
cached?: WebuiThreadPersistedPayload;
|
||||
}
|
||||
|
||||
export async function fetchWebuiThread(
|
||||
@@ -243,17 +246,37 @@ export async function fetchWebuiThread(
|
||||
const query = params.toString();
|
||||
const suffix = query ? `?${query}` : "";
|
||||
const url = `${resolvedBase}/api/sessions/${encodeURIComponent(key)}/webui-thread${suffix}`;
|
||||
const headers: Record<string, string> = { Authorization: `Bearer ${token}` };
|
||||
if (options?.revision) headers["If-None-Match"] = `"${options.revision}"`;
|
||||
const res = await fetchWithTimeout(url, {
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
headers,
|
||||
credentials: "same-origin",
|
||||
cache: "no-store",
|
||||
signal: options?.signal,
|
||||
});
|
||||
if (res.status === 304 && options?.cached) return options.cached;
|
||||
if (res.status === 404) return null;
|
||||
if (!res.ok) throw new ApiError(res.status, `HTTP ${res.status}`);
|
||||
return (await res.json()) as WebuiThreadPersistedPayload;
|
||||
}
|
||||
|
||||
export async function fetchWebuiThreadTraceDetail(
|
||||
token: string,
|
||||
key: string,
|
||||
ref: string,
|
||||
base: string = "",
|
||||
): Promise<WebuiThreadTraceDetailPayload> {
|
||||
const query = new URLSearchParams({ ref });
|
||||
const url = `${base}/api/sessions/${encodeURIComponent(key)}/webui-thread/trace-detail?${query}`;
|
||||
const res = await fetchWithTimeout(url, {
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
credentials: "same-origin",
|
||||
cache: "no-store",
|
||||
});
|
||||
if (!res.ok) throw new ApiError(res.status, `HTTP ${res.status}`);
|
||||
return (await res.json()) as WebuiThreadTraceDetailPayload;
|
||||
}
|
||||
|
||||
export async function fetchFilePreview(
|
||||
token: string,
|
||||
key: string,
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
/** Byte- and entry-bounded in-memory LRU for JSON-shaped WebUI state. */
|
||||
export class MemoryLruCache<T> {
|
||||
private entries = new Map<string, { value: T; bytes: number }>();
|
||||
private sizes = new WeakMap<object, number>();
|
||||
private bytes = 0;
|
||||
|
||||
constructor(
|
||||
private maxBytes: number,
|
||||
private maxEntries: number,
|
||||
private canEvict: (key: string) => boolean = () => true,
|
||||
) {}
|
||||
|
||||
get(key: string): T | undefined {
|
||||
const entry = this.entries.get(key);
|
||||
if (!entry) return undefined;
|
||||
this.entries.delete(key);
|
||||
this.entries.set(key, entry);
|
||||
return entry.value;
|
||||
}
|
||||
|
||||
set(key: string, value: T): void {
|
||||
this.delete(key);
|
||||
const bytes = this.estimate(value);
|
||||
this.entries.set(key, { value, bytes });
|
||||
this.bytes += bytes;
|
||||
for (const candidate of this.entries.keys()) {
|
||||
if (this.bytes <= this.maxBytes && this.entries.size <= this.maxEntries) break;
|
||||
if (this.canEvict(candidate)) this.delete(candidate);
|
||||
}
|
||||
}
|
||||
|
||||
delete(key: string): void {
|
||||
const entry = this.entries.get(key);
|
||||
if (entry) this.bytes -= entry.bytes;
|
||||
this.entries.delete(key);
|
||||
}
|
||||
|
||||
clear(): void {
|
||||
this.entries.clear();
|
||||
this.sizes = new WeakMap<object, number>();
|
||||
this.bytes = 0;
|
||||
}
|
||||
|
||||
private estimate(value: unknown): number {
|
||||
if (typeof value === "string") return value.length * 2;
|
||||
if (!value || typeof value !== "object") return 8;
|
||||
const cached = this.sizes.get(value);
|
||||
if (cached !== undefined) return cached;
|
||||
const size = 32 + Object.values(value).reduce<number>(
|
||||
(total, item) => total + this.estimate(item),
|
||||
0,
|
||||
);
|
||||
this.sizes.set(value, size);
|
||||
return size;
|
||||
}
|
||||
}
|
||||
@@ -1,49 +1,14 @@
|
||||
import type { UIMessage } from "./types";
|
||||
import { MemoryLruCache } from "./memory-lru-cache";
|
||||
|
||||
/** Bounded replay cache; temporary chats remain pinned because they have no disk history. */
|
||||
export class ThreadMessageCache {
|
||||
private entries = new Map<string, { messages: UIMessage[]; bytes: number }>();
|
||||
private sizes = new WeakMap<object, number>();
|
||||
private bytes = 0;
|
||||
export class ThreadMessageCache extends MemoryLruCache<UIMessage[]> {
|
||||
|
||||
constructor(
|
||||
private isPinned: (key: string) => boolean,
|
||||
private maxBytes = 16 * 1024 * 1024,
|
||||
private maxEntries = 12,
|
||||
) {}
|
||||
|
||||
get(key: string): UIMessage[] | undefined {
|
||||
const entry = this.entries.get(key);
|
||||
if (!entry) return undefined;
|
||||
this.entries.delete(key);
|
||||
this.entries.set(key, entry);
|
||||
return entry.messages;
|
||||
}
|
||||
|
||||
set(key: string, messages: UIMessage[]): void {
|
||||
this.delete(key);
|
||||
const bytes = this.estimate(messages);
|
||||
this.entries.set(key, { messages, bytes });
|
||||
this.bytes += bytes;
|
||||
for (const candidate of this.entries.keys()) {
|
||||
if (this.bytes <= this.maxBytes && this.entries.size <= this.maxEntries) break;
|
||||
if (!this.isPinned(candidate)) this.delete(candidate);
|
||||
}
|
||||
}
|
||||
|
||||
delete(key: string): void {
|
||||
const entry = this.entries.get(key);
|
||||
if (entry) this.bytes -= entry.bytes;
|
||||
this.entries.delete(key);
|
||||
}
|
||||
|
||||
private estimate(value: unknown): number {
|
||||
if (typeof value === "string") return value.length * 2;
|
||||
if (!value || typeof value !== "object") return 8;
|
||||
const cached = this.sizes.get(value);
|
||||
if (cached !== undefined) return cached;
|
||||
const size = 32 + Object.values(value).reduce<number>((total, item) => total + this.estimate(item), 0);
|
||||
this.sizes.set(value, size);
|
||||
return size;
|
||||
isPinned: (key: string) => boolean,
|
||||
maxBytes = 16 * 1024 * 1024,
|
||||
maxEntries = 12,
|
||||
) {
|
||||
super(maxBytes, maxEntries, (key) => !isPinned(key));
|
||||
}
|
||||
}
|
||||
@@ -81,6 +81,12 @@ export interface UIMessage {
|
||||
/** Structured tool events behind trace rows. Kept so activity cards can
|
||||
* distinguish running, completed, and failed tool phases. */
|
||||
toolEvents?: ToolProgressEvent[];
|
||||
/** Oversized persisted trace content that can be fetched when activity is expanded. */
|
||||
traceDetail?: {
|
||||
ref: string;
|
||||
bytes: number;
|
||||
traceCount: number;
|
||||
};
|
||||
/** Activity rows: explicit file edits emitted by edit tools. */
|
||||
fileEdits?: UIFileEdit[];
|
||||
/** Activity rows created during the same agent phase share one collapsible block. */
|
||||
@@ -1542,6 +1548,8 @@ export interface WebuiThreadPersistedPayload {
|
||||
schemaVersion: number;
|
||||
sessionKey?: string;
|
||||
savedAt?: string;
|
||||
/** Cheap server revision used for application-managed conditional revalidation. */
|
||||
revision?: string;
|
||||
messages: UIMessage[];
|
||||
fork_boundary_message_count?: number;
|
||||
/** Turn ids backed by an explicit persisted ``turn_end`` event. */
|
||||
@@ -1553,6 +1561,13 @@ export interface WebuiThreadPersistedPayload {
|
||||
workspace_scope?: WorkspaceScopePayload;
|
||||
}
|
||||
|
||||
export interface WebuiThreadTraceDetailPayload {
|
||||
message_id: string;
|
||||
content: string;
|
||||
traces?: string[];
|
||||
toolEvents?: ToolProgressEvent[];
|
||||
}
|
||||
|
||||
export interface FilePreviewPayload {
|
||||
path: string;
|
||||
display_path: string;
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
import { MemoryLruCache } from "./memory-lru-cache";
|
||||
import type { WebuiThreadPersistedPayload } from "./types";
|
||||
|
||||
/** Process-local canonical replay cache used for stale-while-revalidate session entry. */
|
||||
export class WebuiThreadCache extends MemoryLruCache<WebuiThreadPersistedPayload> {
|
||||
constructor(
|
||||
maxBytes = 16 * 1024 * 1024,
|
||||
maxEntries = 12,
|
||||
) {
|
||||
super(maxBytes, maxEntries);
|
||||
}
|
||||
}
|
||||
|
||||
export const webuiThreadCache = new WebuiThreadCache();
|
||||
@@ -140,6 +140,36 @@ function installReducedMotion() {
|
||||
}
|
||||
|
||||
describe("AgentActivityCluster", () => {
|
||||
it("loads deferred trace details only after completed activity is expanded", async () => {
|
||||
const onLoadTraceDetails = vi.fn();
|
||||
render(
|
||||
<AgentActivityCluster
|
||||
messages={[{
|
||||
id: "t-deferred",
|
||||
role: "tool",
|
||||
kind: "trace",
|
||||
content: "exec(…)",
|
||||
traces: ["exec(…)"],
|
||||
traceDetail: {
|
||||
ref: "9.tr-deadbeefdeadbeef",
|
||||
bytes: 40_000,
|
||||
traceCount: 1,
|
||||
},
|
||||
createdAt: 1,
|
||||
}]}
|
||||
isTurnStreaming={false}
|
||||
hasBodyBelow={false}
|
||||
onLoadTraceDetails={onLoadTraceDetails}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(onLoadTraceDetails).not.toHaveBeenCalled();
|
||||
fireEvent.click(screen.getByRole("button", { name: /Worked/ }));
|
||||
await waitFor(() => {
|
||||
expect(onLoadTraceDetails).toHaveBeenCalledWith(["9.tr-deadbeefdeadbeef"]);
|
||||
});
|
||||
});
|
||||
|
||||
it("shows model retries in the existing live activity header", () => {
|
||||
render(
|
||||
<AgentActivityCluster
|
||||
|
||||
@@ -28,6 +28,7 @@ import {
|
||||
fetchSkills,
|
||||
fetchTrendingMarketplaceSkills,
|
||||
fetchWebuiThread,
|
||||
fetchWebuiThreadTraceDetail,
|
||||
fetchWorkspaces,
|
||||
importMcpConfig,
|
||||
installMarketplaceSkill,
|
||||
@@ -117,6 +118,47 @@ describe("webui API helpers", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("revalidates a cached WebUI thread and reuses it on 304", async () => {
|
||||
const cached = {
|
||||
schemaVersion: 3,
|
||||
revision: "rev-1",
|
||||
messages: [],
|
||||
};
|
||||
vi.mocked(fetch).mockResolvedValueOnce({
|
||||
ok: false,
|
||||
status: 304,
|
||||
} as Response);
|
||||
|
||||
await expect(fetchWebuiThread("tok", "websocket:chat-1", {
|
||||
revision: cached.revision,
|
||||
cached,
|
||||
})).resolves.toBe(cached);
|
||||
|
||||
expect(fetch).toHaveBeenCalledWith(
|
||||
"/api/sessions/websocket%3Achat-1/webui-thread",
|
||||
expect.objectContaining({
|
||||
headers: {
|
||||
Authorization: "Bearer tok",
|
||||
"If-None-Match": '"rev-1"',
|
||||
},
|
||||
cache: "no-store",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("fetches deferred trace details with encoded session and ref", async () => {
|
||||
await fetchWebuiThreadTraceDetail("tok", "websocket:chat-1", "9.tr-deadbeefdeadbeef");
|
||||
|
||||
expect(fetch).toHaveBeenCalledWith(
|
||||
"/api/sessions/websocket%3Achat-1/webui-thread/trace-detail?ref=9.tr-deadbeefdeadbeef",
|
||||
expect.objectContaining({
|
||||
headers: { Authorization: "Bearer tok" },
|
||||
credentials: "same-origin",
|
||||
cache: "no-store",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("aborts a WebUI thread request when its caller signal is aborted", async () => {
|
||||
let requestSignal: AbortSignal | null = null;
|
||||
vi.mocked(fetch).mockImplementation((_input, init) => new Promise((_resolve, reject) => {
|
||||
|
||||
@@ -8,8 +8,15 @@ import { ThreadShell } from "@/components/thread/ThreadShell";
|
||||
import i18n from "@/i18n";
|
||||
import { CLI_APPS_CHANGED_EVENT } from "@/lib/cli-app-events";
|
||||
import type { CanonicalRunSnapshot, StreamError } from "@/lib/nanobot-client";
|
||||
import { webuiThreadCache } from "@/lib/webui-thread-cache";
|
||||
import { ClientProvider } from "@/providers/ClientProvider";
|
||||
import type { CliAppsPayload, ConnectionStatus, SettingsPayload, UIMessage } from "@/lib/types";
|
||||
import type {
|
||||
CliAppsPayload,
|
||||
ConnectionStatus,
|
||||
SettingsPayload,
|
||||
UIMessage,
|
||||
WebuiThreadPersistedPayload,
|
||||
} from "@/lib/types";
|
||||
|
||||
const HERO_GREETING_PATTERN =
|
||||
/What should we work on\?|Where should we start\?|What are we building today\?|What should we tackle together\?/;
|
||||
@@ -262,6 +269,36 @@ function httpJson(body: unknown) {
|
||||
};
|
||||
}
|
||||
|
||||
function traceDetailThread(
|
||||
deferred: boolean,
|
||||
answer: string,
|
||||
revision?: string,
|
||||
): WebuiThreadPersistedPayload {
|
||||
return {
|
||||
schemaVersion: 3,
|
||||
...(revision ? { revision } : {}),
|
||||
messages: [
|
||||
{
|
||||
id: "trace-shared",
|
||||
role: "tool",
|
||||
kind: "trace",
|
||||
content: deferred ? "exec(…)" : 'exec({"command":"echo full"})',
|
||||
traces: [deferred ? "exec(…)" : 'exec({"command":"echo full"})'],
|
||||
...(deferred
|
||||
? { traceDetail: { ref: "1.trace-shared", bytes: 40_000, traceCount: 1 } }
|
||||
: {}),
|
||||
createdAt: 1_000,
|
||||
},
|
||||
{
|
||||
id: "answer-shared",
|
||||
role: "assistant",
|
||||
content: answer,
|
||||
createdAt: 2_000,
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
function setDocumentVisibility(value: DocumentVisibilityState): void {
|
||||
Object.defineProperty(document, "visibilityState", {
|
||||
configurable: true,
|
||||
@@ -417,6 +454,7 @@ function settingsWithFastPreset(): SettingsPayload {
|
||||
|
||||
describe("ThreadShell", () => {
|
||||
beforeEach(() => {
|
||||
webuiThreadCache.clear();
|
||||
vi.stubGlobal(
|
||||
"fetch",
|
||||
vi.fn().mockResolvedValue({
|
||||
@@ -427,6 +465,153 @@ describe("ThreadShell", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("surfaces and retries a deferred trace-detail request failure", async () => {
|
||||
const client = makeClient();
|
||||
let detailCalls = 0;
|
||||
const fetchMock = vi.fn((input: RequestInfo | URL) => {
|
||||
const url = String(input);
|
||||
if (url.includes("/webui-thread/trace-detail?")) {
|
||||
detailCalls += 1;
|
||||
if (detailCalls === 1) {
|
||||
return Promise.resolve({ ok: false, status: 500, json: async () => ({}) });
|
||||
}
|
||||
return Promise.resolve(httpJson({
|
||||
message_id: "trace-deferred",
|
||||
content: 'exec({"command":"echo full"})',
|
||||
traces: ['exec({"command":"echo full"})'],
|
||||
}));
|
||||
}
|
||||
if (url.includes("websocket%3Atrace-detail-retry/webui-thread")) {
|
||||
return Promise.resolve(httpJson({
|
||||
schemaVersion: 3,
|
||||
messages: [
|
||||
{
|
||||
id: "trace-deferred",
|
||||
role: "tool",
|
||||
kind: "trace",
|
||||
content: "exec(…)",
|
||||
traces: ["exec(…)"],
|
||||
traceDetail: { ref: "1.trace-deferred", bytes: 40_000, traceCount: 1 },
|
||||
createdAt: 1_000,
|
||||
},
|
||||
{ id: "answer", role: "assistant", content: "done", createdAt: 2_000 },
|
||||
],
|
||||
}));
|
||||
}
|
||||
return Promise.resolve({ ok: false, status: 404, json: async () => ({}) });
|
||||
});
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
|
||||
render(wrap(
|
||||
client,
|
||||
<ThreadShell
|
||||
session={session("trace-detail-retry")}
|
||||
title="Trace detail retry"
|
||||
onToggleSidebar={() => {}}
|
||||
/>,
|
||||
));
|
||||
|
||||
const activity = await screen.findByRole("button", { name: /Worked/ });
|
||||
fireEvent.click(activity);
|
||||
expect(await screen.findByRole("alert")).toHaveTextContent(
|
||||
"Full activity details could not be loaded.",
|
||||
);
|
||||
expect(detailCalls).toBe(1);
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "Retry" }));
|
||||
await waitFor(() => expect(detailCalls).toBe(2));
|
||||
await waitFor(() => expect(screen.queryByRole("alert")).not.toBeInTheDocument());
|
||||
|
||||
fireEvent.click(activity);
|
||||
fireEvent.click(activity);
|
||||
await act(async () => Promise.resolve());
|
||||
expect(detailCalls).toBe(2);
|
||||
});
|
||||
|
||||
it("ignores a deferred trace-detail failure after switching sessions", async () => {
|
||||
const client = makeClient();
|
||||
const detailUrls: string[] = [];
|
||||
let rejectDetail!: (reason: Error) => void;
|
||||
const pendingDetail = new Promise<Response>((_resolve, reject) => {
|
||||
rejectDetail = reject;
|
||||
});
|
||||
const cachedB = traceDetailThread(false, "done-b", "rev-b");
|
||||
webuiThreadCache.set("websocket:trace-failure-b", cachedB);
|
||||
vi.stubGlobal("fetch", vi.fn((input: RequestInfo | URL) => {
|
||||
const url = String(input);
|
||||
if (url.includes("/webui-thread/trace-detail?")) {
|
||||
detailUrls.push(url);
|
||||
return pendingDetail;
|
||||
}
|
||||
if (url.includes("websocket%3Atrace-failure-a/webui-thread")) {
|
||||
return Promise.resolve(httpJson(traceDetailThread(true, "done-a")));
|
||||
}
|
||||
if (url.includes("websocket%3Atrace-failure-b/webui-thread")) {
|
||||
return Promise.resolve(httpJson(cachedB));
|
||||
}
|
||||
return Promise.resolve({ ok: false, status: 404, json: async () => ({}) });
|
||||
}));
|
||||
|
||||
const view = (chatId: string) => wrap(
|
||||
client,
|
||||
<ThreadShell
|
||||
session={session(chatId)}
|
||||
title={`Trace ${chatId}`}
|
||||
onToggleSidebar={() => {}}
|
||||
/>,
|
||||
);
|
||||
const { rerender } = render(view("trace-failure-a"));
|
||||
fireEvent.click(await screen.findByRole("button", { name: /Worked/ }));
|
||||
|
||||
rerender(view("trace-failure-b"));
|
||||
await screen.findByText("done-b");
|
||||
await act(async () => rejectDetail(new Error("late failure")));
|
||||
|
||||
expect(detailUrls).toHaveLength(1);
|
||||
expect(detailUrls[0]).toContain("websocket%3Atrace-failure-a");
|
||||
expect(screen.queryByRole("alert")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("does not carry a visible trace-detail failure into a cached session", async () => {
|
||||
const client = makeClient();
|
||||
const detailUrls: string[] = [];
|
||||
const cachedB = traceDetailThread(false, "cached-b", "rev-visible-b");
|
||||
webuiThreadCache.set("websocket:visible-failure-b", cachedB);
|
||||
vi.stubGlobal("fetch", vi.fn((input: RequestInfo | URL) => {
|
||||
const url = String(input);
|
||||
if (url.includes("/webui-thread/trace-detail?")) {
|
||||
detailUrls.push(url);
|
||||
return Promise.resolve({ ok: false, status: 500, json: async () => ({}) });
|
||||
}
|
||||
if (url.includes("websocket%3Avisible-failure-a/webui-thread")) {
|
||||
return Promise.resolve(httpJson(traceDetailThread(true, "failed-a")));
|
||||
}
|
||||
if (url.includes("websocket%3Avisible-failure-b/webui-thread")) {
|
||||
return Promise.resolve(httpJson(cachedB));
|
||||
}
|
||||
return Promise.resolve({ ok: false, status: 404, json: async () => ({}) });
|
||||
}));
|
||||
|
||||
const view = (chatId: string) => wrap(
|
||||
client,
|
||||
<ThreadShell
|
||||
session={session(chatId)}
|
||||
title={`Trace ${chatId}`}
|
||||
onToggleSidebar={() => {}}
|
||||
/>,
|
||||
);
|
||||
const { rerender } = render(view("visible-failure-a"));
|
||||
fireEvent.click(await screen.findByRole("button", { name: /Worked/ }));
|
||||
expect(await screen.findByRole("alert")).toBeInTheDocument();
|
||||
|
||||
rerender(view("visible-failure-b"));
|
||||
await screen.findByText("cached-b");
|
||||
|
||||
expect(detailUrls).toHaveLength(1);
|
||||
expect(detailUrls[0]).toContain("websocket%3Avisible-failure-a");
|
||||
expect(screen.queryByRole("alert")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("renders each logical round in a completed turn as its own usage bar", async () => {
|
||||
const client = makeClient();
|
||||
vi.stubGlobal("fetch", vi.fn((input: RequestInfo | URL) => {
|
||||
|
||||
@@ -1461,6 +1461,7 @@ describe("ThreadViewport", () => {
|
||||
|
||||
it("renders only the tail window for long history by default", () => {
|
||||
const longMessages = makeLongMessages(300);
|
||||
const firstVisible = longMessages.length - INITIAL_HISTORY_WINDOW;
|
||||
|
||||
render(
|
||||
<ThreadViewport
|
||||
@@ -1470,8 +1471,8 @@ describe("ThreadViewport", () => {
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(screen.queryByText("message 139")).not.toBeInTheDocument();
|
||||
expect(screen.getByText("message 140")).toBeInTheDocument();
|
||||
expect(screen.queryByText(`message ${firstVisible - 1}`)).not.toBeInTheDocument();
|
||||
expect(screen.getByText(`message ${firstVisible}`)).toBeInTheDocument();
|
||||
expect(screen.getByText("message 299")).toBeInTheDocument();
|
||||
expect(screen.queryByRole("button", { name: "Load earlier messages" })).not.toBeInTheDocument();
|
||||
});
|
||||
@@ -1509,6 +1510,7 @@ describe("ThreadViewport", () => {
|
||||
});
|
||||
|
||||
it("prefetches earlier history within half a viewport of the top", () => {
|
||||
const expandedFirstVisible = 300 - INITIAL_HISTORY_WINDOW - HISTORY_WINDOW_INCREMENT;
|
||||
const { container } = render(
|
||||
<ThreadViewport
|
||||
messages={makeLongMessages(300)}
|
||||
@@ -1527,14 +1529,16 @@ describe("ThreadViewport", () => {
|
||||
act(() => {
|
||||
dispatchUserScroll(scroller);
|
||||
});
|
||||
expect(screen.queryByText("message 139")).not.toBeInTheDocument();
|
||||
expect(
|
||||
screen.queryByText(`message ${300 - INITIAL_HISTORY_WINDOW - 1}`),
|
||||
).not.toBeInTheDocument();
|
||||
|
||||
scroller.scrollTop = 250;
|
||||
act(() => {
|
||||
dispatchUserScroll(scroller);
|
||||
});
|
||||
expect(screen.getByText("message 20")).toBeInTheDocument();
|
||||
expect(screen.queryByText("message 19")).not.toBeInTheDocument();
|
||||
expect(screen.getByText(`message ${expandedFirstVisible}`)).toBeInTheDocument();
|
||||
expect(screen.queryByText(`message ${expandedFirstVisible - 1}`)).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("keeps the first visible history item fixed while deferred rows materialize", () => {
|
||||
@@ -1562,7 +1566,8 @@ describe("ThreadViewport", () => {
|
||||
},
|
||||
});
|
||||
|
||||
const anchor = screen.getByText("message 140")
|
||||
const firstVisible = 300 - INITIAL_HISTORY_WINDOW;
|
||||
const anchor = screen.getByText(`message ${firstVisible}`)
|
||||
.closest<HTMLElement>("[data-thread-display-unit]");
|
||||
expect(anchor).not.toBeNull();
|
||||
hitTarget = anchor;
|
||||
@@ -1913,15 +1918,16 @@ describe("ThreadViewport", () => {
|
||||
|
||||
it("expands the window start to avoid cutting an agent activity cluster", () => {
|
||||
const clustered = makeLongMessages(200);
|
||||
const boundary = clustered.length - INITIAL_HISTORY_WINDOW;
|
||||
clustered.splice(
|
||||
38,
|
||||
boundary - 2,
|
||||
3,
|
||||
{
|
||||
id: "r0",
|
||||
role: "assistant",
|
||||
content: "",
|
||||
reasoning: "first reasoning",
|
||||
createdAt: 38,
|
||||
createdAt: boundary - 2,
|
||||
},
|
||||
{
|
||||
id: "t0",
|
||||
@@ -1929,14 +1935,14 @@ describe("ThreadViewport", () => {
|
||||
kind: "trace",
|
||||
content: "tool()",
|
||||
traces: ["tool()"],
|
||||
createdAt: 39,
|
||||
createdAt: boundary - 1,
|
||||
},
|
||||
{
|
||||
id: "r1",
|
||||
role: "assistant",
|
||||
content: "",
|
||||
reasoning: "second reasoning",
|
||||
createdAt: 40,
|
||||
createdAt: boundary,
|
||||
},
|
||||
);
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { sessionTitle, useSessionHistory, useSessions } from "@/hooks/useSessions";
|
||||
import * as api from "@/lib/api";
|
||||
import { webuiThreadCache } from "@/lib/webui-thread-cache";
|
||||
import { ClientProvider } from "@/providers/ClientProvider";
|
||||
|
||||
vi.mock("@/lib/api", async (importOriginal) => {
|
||||
@@ -93,6 +94,7 @@ describe("useSessions", () => {
|
||||
vi.mocked(api.listSessions).mockReset();
|
||||
vi.mocked(api.deleteSession).mockReset();
|
||||
vi.mocked(api.fetchWebuiThread).mockReset();
|
||||
webuiThreadCache.clear();
|
||||
});
|
||||
|
||||
it("does not use low-information greetings as fallback session titles", () => {
|
||||
@@ -566,6 +568,70 @@ describe("useSessions", () => {
|
||||
expect(result.current.messages[2]!.content).toBe("summary");
|
||||
});
|
||||
|
||||
it("shows a cached transcript immediately while revalidating it", async () => {
|
||||
const cached = {
|
||||
schemaVersion: 3,
|
||||
revision: "rev-cached",
|
||||
messages: [
|
||||
{ id: "a1", role: "assistant" as const, content: "cached answer", createdAt: 1 },
|
||||
],
|
||||
};
|
||||
vi.mocked(api.fetchWebuiThread).mockResolvedValueOnce(cached);
|
||||
|
||||
const first = renderHook(() => useSessionHistory("websocket:cached"), {
|
||||
wrapper: wrap(fakeClient()),
|
||||
});
|
||||
await waitFor(() => expect(first.result.current.loading).toBe(false));
|
||||
first.unmount();
|
||||
|
||||
vi.mocked(api.fetchWebuiThread).mockImplementationOnce(() => new Promise(() => {}));
|
||||
const second = renderHook(() => useSessionHistory("websocket:cached"), {
|
||||
wrapper: wrap(fakeClient()),
|
||||
});
|
||||
|
||||
expect(second.result.current.loading).toBe(false);
|
||||
expect(second.result.current.messages[0]?.content).toBe("cached answer");
|
||||
expect(api.fetchWebuiThread).toHaveBeenLastCalledWith(
|
||||
"tok",
|
||||
"websocket:cached",
|
||||
expect.objectContaining({
|
||||
limit: 40,
|
||||
direction: "latest",
|
||||
revision: "rev-cached",
|
||||
cached,
|
||||
}),
|
||||
);
|
||||
second.unmount();
|
||||
});
|
||||
|
||||
it("keeps rendered history visible when its LRU entry was evicted before refresh", async () => {
|
||||
const loaded = {
|
||||
schemaVersion: 3,
|
||||
revision: "rev-loaded",
|
||||
messages: [
|
||||
{ id: "a1", role: "assistant" as const, content: "still visible", createdAt: 1 },
|
||||
],
|
||||
};
|
||||
vi.mocked(api.fetchWebuiThread)
|
||||
.mockResolvedValueOnce(loaded)
|
||||
.mockImplementationOnce(() => new Promise(() => {}));
|
||||
|
||||
const { result, unmount } = renderHook(
|
||||
() => useSessionHistory("websocket:evicted"),
|
||||
{ wrapper: wrap(fakeClient()) },
|
||||
);
|
||||
await waitFor(() => expect(result.current.loading).toBe(false));
|
||||
expect(result.current.messages[0]?.content).toBe("still visible");
|
||||
|
||||
webuiThreadCache.delete("websocket:evicted");
|
||||
act(() => result.current.refresh());
|
||||
await waitFor(() => expect(api.fetchWebuiThread).toHaveBeenCalledTimes(2));
|
||||
|
||||
expect(result.current.loading).toBe(false);
|
||||
expect(result.current.messages[0]?.content).toBe("still visible");
|
||||
unmount();
|
||||
});
|
||||
|
||||
it("flags transcript ending with a trace row as pending", async () => {
|
||||
vi.mocked(api.fetchWebuiThread).mockResolvedValue({
|
||||
schemaVersion: 3,
|
||||
@@ -785,7 +851,7 @@ describe("useSessions", () => {
|
||||
"tok",
|
||||
"websocket:paged",
|
||||
expect.objectContaining({
|
||||
limit: 80,
|
||||
limit: 40,
|
||||
direction: "latest",
|
||||
signal: expect.any(AbortSignal),
|
||||
}),
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { WebuiThreadCache } from "@/lib/webui-thread-cache";
|
||||
import type { WebuiThreadPersistedPayload } from "@/lib/types";
|
||||
|
||||
function payload(id: string): WebuiThreadPersistedPayload {
|
||||
return {
|
||||
schemaVersion: 3,
|
||||
revision: `rev-${id}`,
|
||||
messages: [{ id, role: "assistant", content: id, createdAt: 1 }],
|
||||
};
|
||||
}
|
||||
|
||||
describe("WebuiThreadCache", () => {
|
||||
it("evicts the least recently used session", () => {
|
||||
const cache = new WebuiThreadCache(10_000, 2);
|
||||
cache.set("a", payload("a"));
|
||||
cache.set("b", payload("b"));
|
||||
expect(cache.get("a")).toBeDefined();
|
||||
|
||||
cache.set("c", payload("c"));
|
||||
|
||||
expect(cache.get("a")?.revision).toBe("rev-a");
|
||||
expect(cache.get("b")).toBeUndefined();
|
||||
expect(cache.get("c")?.revision).toBe("rev-c");
|
||||
});
|
||||
|
||||
it("does not retain a payload larger than the byte budget", () => {
|
||||
const cache = new WebuiThreadCache(64, 2);
|
||||
cache.set("large", payload("x".repeat(100)));
|
||||
|
||||
expect(cache.get("large")).toBeUndefined();
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user