perf(subagent): read saved task history by loaded turns (#6634)
This commit is contained in:
1 parent
1196698ecb
commit
eb8546c321
20 files changed
+893
-97
No files matched your search
@@ -7,7 +7,7 @@ import {
|
||||
InterruptedTaskIcon,
|
||||
ErrorTaskIcon,
|
||||
} from "@/components/icons/product-icons";
|
||||
import { createContext, useContext, useEffect, useLayoutEffect, useRef, useState, type ReactNode } from "react";
|
||||
import { createContext, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState, type ReactNode } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
@@ -47,11 +47,13 @@ interface SubagentTasksProviderProps {
|
||||
enabled: boolean;
|
||||
liveEvents: boolean;
|
||||
historyEnabled?: boolean;
|
||||
turnIds: string[];
|
||||
windowReady?: boolean;
|
||||
active?: boolean;
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
export function SubagentTasksProvider({ client, sessionKey, token, enabled, liveEvents, historyEnabled = false, active = true, children }: SubagentTasksProviderProps) {
|
||||
export function SubagentTasksProvider({ client, sessionKey, token, enabled, liveEvents, historyEnabled = false, turnIds, windowReady = true, active = true, children }: SubagentTasksProviderProps) {
|
||||
const { t } = useTranslation("common");
|
||||
const pageVisible = usePageVisibility();
|
||||
const paneVisible = useThreadVisibility();
|
||||
@@ -64,9 +66,29 @@ export function SubagentTasksProvider({ client, sessionKey, token, enabled, live
|
||||
const trigger = useRef<HTMLButtonElement | null>(null);
|
||||
const buttons = useRef(new Map<string, HTMLButtonElement>());
|
||||
const detailPanel = useRef<HTMLDivElement | null>(null);
|
||||
const taskRef = useRef(tasks);
|
||||
taskRef.current = tasks;
|
||||
const windowScope = { turnIds };
|
||||
const windowKey = JSON.stringify(windowScope);
|
||||
const windowRef = useRef(windowScope);
|
||||
windowRef.current = windowScope;
|
||||
const windowKeyRef = useRef(windowKey);
|
||||
windowKeyRef.current = windowKey;
|
||||
const readState = useMemo(() => ({
|
||||
turnIds: new Set<string>(), inFlight: false, force: false, epoch: 0,
|
||||
}), [client, sessionKey]);
|
||||
const readStateRef = useRef(readState);
|
||||
readStateRef.current = readState;
|
||||
const refreshRef = useRef<((force: boolean, invalidate?: boolean) => void) | null>(null);
|
||||
const mergeTasks = (incoming: SubagentTaskSnapshot[]) => {
|
||||
const next = mergeSubagentTasks(taskRef.current, incoming);
|
||||
taskRef.current = next;
|
||||
setTasks(next);
|
||||
};
|
||||
|
||||
useLayoutEffect(() => {
|
||||
scopeGeneration.current += 1;
|
||||
taskRef.current = [];
|
||||
setTasks([]);
|
||||
setSelectedId(null);
|
||||
setStoppingId(null);
|
||||
@@ -84,46 +106,80 @@ export function SubagentTasksProvider({ client, sessionKey, token, enabled, live
|
||||
}, [active, paneVisible]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!enabled || !active || !pageVisible || !paneVisible || !sessionKey || !token) return;
|
||||
if (!enabled || !active || !pageVisible || !paneVisible || !sessionKey || !token || !liveEvents) return;
|
||||
let subscribing = true;
|
||||
const unsubscribeChat = client.onChat(sessionKey.slice("websocket:".length), (event) => {
|
||||
if (readStateRef.current === readState && event.event === "subagent_task" && isSubagentTask(event.task)) mergeTasks([event.task]);
|
||||
});
|
||||
const unsubscribeStatus = client.onStatus((status) => {
|
||||
if (!subscribing && status === "open") refreshRef.current?.(true, true);
|
||||
});
|
||||
subscribing = false;
|
||||
return () => { unsubscribeChat(); unsubscribeStatus(); };
|
||||
}, [client, enabled, liveEvents, active, sessionKey, token, pageVisible, paneVisible, readState]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!enabled || !active || !pageVisible || !paneVisible || !sessionKey || !token || !windowReady) return;
|
||||
let cancelled = false;
|
||||
let refreshing = false;
|
||||
let refreshPending = false;
|
||||
const refresh = async () => {
|
||||
if (refreshing) { refreshPending = true; return; }
|
||||
refreshing = true;
|
||||
try {
|
||||
const payload = await fetchSubagentTasks(token, sessionKey);
|
||||
if (!cancelled) {
|
||||
setTasks((current) => mergeSubagentTasks(current, payload.tasks));
|
||||
let scheduled = false;
|
||||
const read = () => {
|
||||
if (readState.inFlight) return;
|
||||
const full = readState.force;
|
||||
const current = windowRef.current;
|
||||
const requested = {
|
||||
turnIds: current.turnIds.filter((id) => full || !readState.turnIds.has(id)),
|
||||
};
|
||||
if (!full && requested.turnIds.length === 0) return;
|
||||
readState.force = false;
|
||||
readState.inFlight = true;
|
||||
const requestedKey = windowKeyRef.current;
|
||||
const requestedEpoch = readState.epoch;
|
||||
const window = {
|
||||
...requested,
|
||||
trackedIds: taskRef.current.filter(isActiveSubagentTask).map((task) => task.task_id),
|
||||
};
|
||||
let succeeded = false;
|
||||
void fetchSubagentTasks(token, sessionKey, window).then((payload) => {
|
||||
if (!mounted.current || readStateRef.current !== readState) return;
|
||||
succeeded = true;
|
||||
if (requestedEpoch === readState.epoch) {
|
||||
for (const id of requested.turnIds) readState.turnIds.add(id);
|
||||
}
|
||||
} catch {
|
||||
// Background read failures retain the last task snapshot.
|
||||
} finally {
|
||||
refreshing = false;
|
||||
if (refreshPending && !cancelled) {
|
||||
refreshPending = false;
|
||||
void refresh();
|
||||
}
|
||||
}
|
||||
mergeTasks(payload.tasks);
|
||||
}).catch(() => {
|
||||
// Background read failures retain the last task snapshot and remain retryable.
|
||||
}).finally(() => {
|
||||
readState.inFlight = false;
|
||||
if (readStateRef.current === readState
|
||||
&& (succeeded || readState.force || requestedKey !== windowKeyRef.current)) refreshRef.current?.(false);
|
||||
});
|
||||
};
|
||||
const unsubscribeChat = liveEvents ? client.onChat(sessionKey.slice("websocket:".length), (event) => {
|
||||
if (cancelled || event.event !== "subagent_task") return;
|
||||
if (!isSubagentTask(event.task)) return;
|
||||
setTasks((current) => mergeSubagentTasks(current, [event.task]));
|
||||
}) : undefined;
|
||||
const unsubscribeStatus = liveEvents ? client.onStatus((status) => {
|
||||
if (status === "open") void refresh();
|
||||
}) : undefined;
|
||||
if (!refreshing) void refresh();
|
||||
const focus = () => void refresh();
|
||||
const refresh = (force: boolean, invalidate = false) => {
|
||||
if (cancelled) return;
|
||||
if (invalidate) {
|
||||
// Events may have been missed on any previously viewed page. Mark all
|
||||
// pages stale, then refresh only the current one and revisit others lazily.
|
||||
readState.epoch += 1;
|
||||
readState.turnIds.clear();
|
||||
}
|
||||
if (force) readState.force = true;
|
||||
if (scheduled) return;
|
||||
scheduled = true;
|
||||
// Coalesce layout-driven window changes and Strict Mode effect replays.
|
||||
queueMicrotask(() => { scheduled = false; if (!cancelled) read(); });
|
||||
};
|
||||
refreshRef.current = refresh;
|
||||
refresh(true, true);
|
||||
const focus = () => refresh(true, true);
|
||||
window.addEventListener("focus", focus);
|
||||
return () => {
|
||||
cancelled = true;
|
||||
unsubscribeChat?.();
|
||||
unsubscribeStatus?.();
|
||||
refreshRef.current = null;
|
||||
window.removeEventListener("focus", focus);
|
||||
};
|
||||
}, [client, enabled, liveEvents, active, sessionKey, token, pageVisible, paneVisible]);
|
||||
}, [client, enabled, active, sessionKey, token, pageVisible, paneVisible, windowReady, readState]);
|
||||
|
||||
useEffect(() => { refreshRef.current?.(false); }, [windowKey]);
|
||||
|
||||
const stop = async (task: SubagentTaskSnapshot) => {
|
||||
if (!sessionKey) return;
|
||||
@@ -133,7 +189,7 @@ export function SubagentTasksProvider({ client, sessionKey, token, enabled, live
|
||||
try {
|
||||
const next = await cancelSubagentTask(client, sessionKey, task.task_id);
|
||||
if (!mounted.current || generation !== scopeGeneration.current) return;
|
||||
setTasks((current) => mergeSubagentTasks(current, [next]));
|
||||
mergeTasks([next]);
|
||||
} catch (reason) {
|
||||
if (mounted.current && generation === scopeGeneration.current) setStopError(reason instanceof Error ? reason.message : t("thread.subagents.stopFailed"));
|
||||
} finally {
|
||||
|
||||
@@ -485,6 +485,17 @@ export function ThreadShell({
|
||||
const { t } = useTranslation();
|
||||
const chatId = session?.chatId ?? null;
|
||||
const historyKey = temporary ? null : session?.key ?? null;
|
||||
const [visibleWindow, setVisibleWindow] = useState<{ key: string | null; turnIds: string[]; hasMessages: boolean } | null>(null);
|
||||
const reportVisibleMessages = useCallback((messages: UIMessage[]) => {
|
||||
// Saved results attach to turns, so only the rendered user turns matter here.
|
||||
const turnIds = [...new Set(messages.flatMap((message) => (
|
||||
message.role === "user" && message.turnId ? [message.turnId] : []
|
||||
)))];
|
||||
setVisibleWindow((current) => current?.key === historyKey && current.hasMessages === (messages.length > 0)
|
||||
&& current.turnIds.length === turnIds.length
|
||||
&& current.turnIds.every((turnId, index) => turnId === turnIds[index])
|
||||
? current : { key: historyKey, turnIds, hasMessages: messages.length > 0 });
|
||||
}, [historyKey]);
|
||||
const previewSessionKey = session?.key ?? null;
|
||||
const mentionSessions = useMemo(
|
||||
() => sessions.filter((candidate) => candidate.key !== historyKey).map((candidate) => {
|
||||
@@ -1527,6 +1538,8 @@ export function ThreadShell({
|
||||
sessionKey={session?.key ?? null}
|
||||
liveEvents={webuiCapabilities.includes("webui.subagents.events.v1")}
|
||||
historyEnabled={webuiCapabilities.includes("webui.subagents.history.v1")}
|
||||
turnIds={visibleWindow?.key === historyKey ? visibleWindow.turnIds : []}
|
||||
windowReady={messagesReady && visibleWindow?.key === historyKey && (!initialHistoryLoading || visibleWindow.hasMessages)}
|
||||
active={composerActive}
|
||||
enabled={!temporary && !!session?.key.startsWith("websocket:") && webuiCapabilities.includes("webui.subagents.v1")}>
|
||||
<section ref={setSidebarHost} style={{ "--sidebar-enter-width": `${sidebarEnterWidth}px`, "--sidebar-enter-mobile-width": sidebarEnterWidth ? "100%" : "0px" } as CSSProperties} data-preview-open={sidebarOpen || undefined} className="thread-preview-layout relative flex min-h-0 flex-1 overflow-hidden">
|
||||
@@ -1573,6 +1586,7 @@ export function ThreadShell({
|
||||
activeTurnStartedHere={activeTurnStartedHere}
|
||||
conversationKey={historyKey}
|
||||
conversationReady={messagesReady}
|
||||
onVisibleMessagesChange={reportVisibleMessages}
|
||||
showScrollToBottomButton={!!session}
|
||||
cliApps={cliApps}
|
||||
mcpPresets={mcpPresets}
|
||||
|
||||
@@ -60,6 +60,7 @@ interface ThreadViewportProps {
|
||||
/** Override when message ownership changes after the selected conversation. */
|
||||
messagesKey?: string | null;
|
||||
conversationReady?: boolean;
|
||||
onVisibleMessagesChange?: (messages: UIMessage[]) => void;
|
||||
showScrollToBottomButton?: boolean;
|
||||
cliApps?: CliAppInfo[];
|
||||
mcpPresets?: McpPresetInfo[];
|
||||
@@ -287,6 +288,7 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
|
||||
conversationKey = null,
|
||||
messagesKey = conversationKey,
|
||||
conversationReady = true,
|
||||
onVisibleMessagesChange,
|
||||
showScrollToBottomButton = true,
|
||||
cliApps = [],
|
||||
mcpPresets = [],
|
||||
@@ -471,6 +473,9 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
|
||||
() => windowMessages(messages, visibleMessageCount),
|
||||
[messages, visibleMessageCount],
|
||||
);
|
||||
useLayoutEffect(() => {
|
||||
if (conversationReady) onVisibleMessagesChange?.(visibleMessages);
|
||||
}, [conversationReady, onVisibleMessagesChange, visibleMessages]);
|
||||
const hiddenMessageCount = messages.length - visibleMessages.length;
|
||||
const historyUnknown = hasMoreBefore === null;
|
||||
const historyExhausted = hasMoreBefore === false && hiddenMessageCount === 0;
|
||||
|
||||
Reference in new issue
Block a user