refactor(webui): separate gateway mutations and UI state (#6727)
This commit is contained in:
1 parent
ce12bfdd0d
commit
5537bdabd3
70 files changed
+4058
-3650
No files matched your search
@@ -0,0 +1,128 @@
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useToast } from "@/components/ui/toast";
|
||||
import { useVoiceRecorder, type VoiceRecorderErrorKey } from "@/hooks/useVoiceRecorder";
|
||||
|
||||
const VOICE_SHORTCUT_CODE = "KeyD";
|
||||
const VOICE_SHORTCUT_ARIA = "Control+Shift+D";
|
||||
type VoiceShortcutPlatform = "apple" | "chromeos" | "linux" | "other" | "windows";
|
||||
|
||||
function isVoiceShortcutDown(event: KeyboardEvent): boolean {
|
||||
return (
|
||||
event.code === VOICE_SHORTCUT_CODE
|
||||
&& event.ctrlKey
|
||||
&& event.shiftKey
|
||||
&& !event.altKey
|
||||
&& !event.metaKey
|
||||
);
|
||||
}
|
||||
|
||||
function isVoiceShortcutRelease(event: KeyboardEvent): boolean {
|
||||
return (
|
||||
event.code === VOICE_SHORTCUT_CODE
|
||||
|| event.key === "Control"
|
||||
|| event.key === "Shift"
|
||||
);
|
||||
}
|
||||
|
||||
function getVoiceShortcutPlatform(): VoiceShortcutPlatform {
|
||||
if (typeof navigator === "undefined") return "other";
|
||||
const userAgentData = (navigator as Navigator & { userAgentData?: { platform?: string } })
|
||||
.userAgentData;
|
||||
const platform = [
|
||||
userAgentData?.platform,
|
||||
navigator.platform,
|
||||
navigator.userAgent,
|
||||
].filter(Boolean).join(" ").toLowerCase();
|
||||
const isIpadPretendingToBeMac =
|
||||
navigator.platform === "MacIntel" && navigator.maxTouchPoints > 1;
|
||||
if (isIpadPretendingToBeMac || /mac|iphone|ipad|ipod/.test(platform)) return "apple";
|
||||
if (/win/.test(platform)) return "windows";
|
||||
if (/cros/.test(platform)) return "chromeos";
|
||||
if (/linux|x11|android/.test(platform)) return "linux";
|
||||
return "other";
|
||||
}
|
||||
|
||||
function getVoiceShortcutLabel(): string {
|
||||
switch (getVoiceShortcutPlatform()) {
|
||||
case "apple":
|
||||
return "⌃⇧D";
|
||||
case "chromeos":
|
||||
case "linux":
|
||||
case "windows":
|
||||
case "other":
|
||||
return "Ctrl ⇧ D";
|
||||
}
|
||||
}
|
||||
|
||||
type VoiceInputOptions = Pick<Parameters<typeof useVoiceRecorder>[0],
|
||||
"disabled" | "onTranscribeAudio" | "onTranscript" | "wantsWav">;
|
||||
|
||||
/** Owns press/shortcut recording and how the composer presents voice setup errors. */
|
||||
export function useComposerVoiceInput({ disabled, onTranscribeAudio, onTranscript, wantsWav }: VoiceInputOptions) {
|
||||
const { t } = useTranslation();
|
||||
const showToast = useToast();
|
||||
const [voiceSetupError, setVoiceSetupError] = useState<VoiceRecorderErrorKey | null>(null);
|
||||
const [shortcutLabel] = useState(getVoiceShortcutLabel);
|
||||
const voiceShortcutDownRef = useRef(false);
|
||||
const clearVoiceSetupError = useCallback(() => setVoiceSetupError(null), []);
|
||||
const setVoiceError = useCallback((key: VoiceRecorderErrorKey) => {
|
||||
// Setup blockers carry instructions users may need to keep in view while fixing them.
|
||||
if (key === "insecureContext" || key === "permission" || key === "notConfigured") {
|
||||
setVoiceSetupError(key);
|
||||
return;
|
||||
}
|
||||
showToast?.({ message: t(`thread.composer.voiceErrors.${key}`), tone: "error", dedupeKey: "voice-input" });
|
||||
}, [showToast, t]);
|
||||
const voiceRecorder = useVoiceRecorder({
|
||||
disabled,
|
||||
onClearError: clearVoiceSetupError,
|
||||
onError: setVoiceError,
|
||||
onTranscript,
|
||||
onTranscribeAudio,
|
||||
wantsWav,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (!onTranscribeAudio) return;
|
||||
|
||||
function onKeyDown(event: KeyboardEvent): void {
|
||||
if (!isVoiceShortcutDown(event) || event.repeat || voiceShortcutDownRef.current) return;
|
||||
event.preventDefault();
|
||||
voiceShortcutDownRef.current = true;
|
||||
voiceRecorder.beginShortcutHold();
|
||||
}
|
||||
|
||||
function onKeyUp(event: KeyboardEvent): void {
|
||||
if (!voiceShortcutDownRef.current || !isVoiceShortcutRelease(event)) return;
|
||||
event.preventDefault();
|
||||
voiceShortcutDownRef.current = false;
|
||||
voiceRecorder.endShortcutHold();
|
||||
}
|
||||
|
||||
function onWindowBlur(): void {
|
||||
if (!voiceShortcutDownRef.current) return;
|
||||
voiceShortcutDownRef.current = false;
|
||||
voiceRecorder.endShortcutHold();
|
||||
}
|
||||
|
||||
window.addEventListener("keydown", onKeyDown);
|
||||
window.addEventListener("keyup", onKeyUp);
|
||||
window.addEventListener("blur", onWindowBlur);
|
||||
return () => {
|
||||
window.removeEventListener("keydown", onKeyDown);
|
||||
window.removeEventListener("keyup", onKeyUp);
|
||||
window.removeEventListener("blur", onWindowBlur);
|
||||
};
|
||||
}, [onTranscribeAudio, voiceRecorder.beginShortcutHold, voiceRecorder.endShortcutHold]);
|
||||
|
||||
return {
|
||||
recorder: voiceRecorder,
|
||||
setupError: voiceSetupError,
|
||||
clearSetupError: clearVoiceSetupError,
|
||||
shortcutLabel,
|
||||
shortcutAria: VOICE_SHORTCUT_ARIA,
|
||||
// Includes the interval while the shortcut is held and permission is still pending.
|
||||
canSendQueuedPrompt: () => voiceRecorder.state === "idle" && !voiceShortcutDownRef.current,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
import { useCallback, useEffect, useRef, useState, type PointerEvent as ReactPointerEvent, type RefObject } from "react";
|
||||
|
||||
const FILE_PREVIEW_MIN_WIDTH = 360;
|
||||
const FILE_PREVIEW_MAX_WIDTH = 860;
|
||||
const FILE_PREVIEW_MIN_MAIN_WIDTH = 420;
|
||||
|
||||
function clampFilePreviewWidth(width: number, maxWidth: number): number {
|
||||
return Math.min(Math.max(width, FILE_PREVIEW_MIN_WIDTH), maxWidth);
|
||||
}
|
||||
|
||||
function maxFilePreviewWidth(containerWidth: number): number {
|
||||
return Math.min(
|
||||
containerWidth > 0 ? containerWidth : FILE_PREVIEW_MIN_WIDTH,
|
||||
Math.max(
|
||||
FILE_PREVIEW_MIN_WIDTH,
|
||||
Math.min(FILE_PREVIEW_MAX_WIDTH, containerWidth - FILE_PREVIEW_MIN_MAIN_WIDTH),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/** Owns the transient drag, panel geometry and restoration of drag-time styles. */
|
||||
export function useFilePreviewResize(
|
||||
shellRef: RefObject<HTMLElement>, previewOpen: boolean, storedWidth: number, setFilePreviewWidth: (width: number) => void,
|
||||
) {
|
||||
const panelRef = useRef<HTMLElement>(null);
|
||||
const [filePreviewMaxWidth, setFilePreviewMaxWidth] = useState(FILE_PREVIEW_MAX_WIDTH);
|
||||
const filePreviewWidth = clampFilePreviewWidth(storedWidth, filePreviewMaxWidth);
|
||||
const filePreviewWidthRef = useRef(filePreviewWidth);
|
||||
const filePreviewResizeCleanupRef = useRef<(() => void) | null>(null);
|
||||
const cancelResize = useCallback(() => filePreviewResizeCleanupRef.current?.(), []);
|
||||
useEffect(() => cancelResize, [cancelResize]);
|
||||
|
||||
useEffect(() => {
|
||||
filePreviewWidthRef.current = filePreviewWidth;
|
||||
}, [filePreviewWidth]);
|
||||
|
||||
const handleFilePreviewResizeStart = useCallback((event: ReactPointerEvent<HTMLButtonElement>) => {
|
||||
filePreviewResizeCleanupRef.current?.();
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
const panel = panelRef.current;
|
||||
const shellRect = shellRef.current?.getBoundingClientRect();
|
||||
const rightEdge = shellRect?.right ?? window.innerWidth;
|
||||
const maxWidth = maxFilePreviewWidth(shellRect?.width ?? window.innerWidth);
|
||||
const originalBodyCursor = document.body.style.cursor;
|
||||
const originalBodyUserSelect = document.body.style.userSelect;
|
||||
const originalPanelTransition = panel?.style.transition ?? "";
|
||||
const frameElement = panel?.querySelector("iframe");
|
||||
const originalFramePointerEvents = frameElement?.style.pointerEvents ?? "";
|
||||
let nextWidth = filePreviewWidthRef.current;
|
||||
let frame: number | null = null;
|
||||
|
||||
document.body.style.cursor = "col-resize";
|
||||
document.body.style.userSelect = "none";
|
||||
if (panel) panel.style.transition = "none";
|
||||
if (frameElement) frameElement.style.pointerEvents = "none";
|
||||
|
||||
const applyWidth = (clientX: number) => {
|
||||
nextWidth = clampFilePreviewWidth(rightEdge - clientX, maxWidth);
|
||||
filePreviewWidthRef.current = nextWidth;
|
||||
if (frame !== null) return;
|
||||
frame = window.requestAnimationFrame(() => {
|
||||
frame = null;
|
||||
panel?.style.setProperty("--file-preview-width", `${nextWidth}px`);
|
||||
panel?.style.setProperty("--file-preview-slot-width", `${nextWidth}px`);
|
||||
});
|
||||
};
|
||||
const handlePointerMove = (moveEvent: PointerEvent) => {
|
||||
moveEvent.preventDefault();
|
||||
applyWidth(moveEvent.clientX);
|
||||
};
|
||||
const stopResize = (commit: boolean) => {
|
||||
if (frame !== null) {
|
||||
window.cancelAnimationFrame(frame);
|
||||
frame = null;
|
||||
}
|
||||
panel?.style.setProperty("--file-preview-width", `${nextWidth}px`);
|
||||
panel?.style.setProperty("--file-preview-slot-width", `${nextWidth}px`);
|
||||
if (panel) panel.style.transition = originalPanelTransition;
|
||||
if (frameElement) frameElement.style.pointerEvents = originalFramePointerEvents;
|
||||
if (commit) setFilePreviewWidth(nextWidth);
|
||||
document.body.style.cursor = originalBodyCursor;
|
||||
document.body.style.userSelect = originalBodyUserSelect;
|
||||
window.removeEventListener("pointermove", handlePointerMove);
|
||||
window.removeEventListener("pointerup", handlePointerUp);
|
||||
window.removeEventListener("pointercancel", handlePointerUp);
|
||||
filePreviewResizeCleanupRef.current = null;
|
||||
};
|
||||
const handlePointerUp = () => stopResize(true);
|
||||
filePreviewResizeCleanupRef.current = () => stopResize(false);
|
||||
|
||||
applyWidth(event.clientX);
|
||||
window.addEventListener("pointermove", handlePointerMove);
|
||||
window.addEventListener("pointerup", handlePointerUp);
|
||||
window.addEventListener("pointercancel", handlePointerUp);
|
||||
}, [setFilePreviewWidth, shellRef]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!previewOpen) return;
|
||||
const clampToShell = () => {
|
||||
const shellWidth = shellRef.current?.getBoundingClientRect().width ?? window.innerWidth;
|
||||
const maxWidth = maxFilePreviewWidth(shellWidth);
|
||||
setFilePreviewMaxWidth(maxWidth);
|
||||
};
|
||||
clampToShell();
|
||||
const observer = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(clampToShell);
|
||||
if (shellRef.current) observer?.observe(shellRef.current);
|
||||
window.addEventListener("resize", clampToShell);
|
||||
return () => {
|
||||
observer?.disconnect();
|
||||
window.removeEventListener("resize", clampToShell);
|
||||
};
|
||||
}, [previewOpen, shellRef]);
|
||||
|
||||
return { width: filePreviewWidth, panelRef, startResize: handleFilePreviewResizeStart, cancelResize };
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import {
|
||||
BootstrapAuthRequiredError,
|
||||
clearSavedSecret,
|
||||
consumeUrlBootstrapSecret,
|
||||
deriveWsUrl,
|
||||
fetchBootstrap,
|
||||
loadSavedSecret,
|
||||
saveSecret,
|
||||
} from "@/lib/bootstrap";
|
||||
import { clearStoredComposerDrafts } from "@/lib/composer-draft";
|
||||
import { NanobotClient } from "@/lib/nanobot-client";
|
||||
import { activateReloadCache, clearReloadCache } from "@/lib/reload-cache";
|
||||
import { createRuntimeHost, isNativeRuntime, toRuntimeSurface } from "@/lib/runtime";
|
||||
import type { BootstrapResponse, RuntimeSurface } from "@/lib/types";
|
||||
import { webuiThreadCache } from "@/lib/webui-thread-cache";
|
||||
import { RESTART_ROUTE_KEY, RESTART_STARTED_KEY, rememberRestartRoute } from "@/shell-route";
|
||||
|
||||
type ReadyGateway = {
|
||||
status: "ready";
|
||||
client: NanobotClient;
|
||||
token: string;
|
||||
tokenExpiresAt: number | null;
|
||||
modelName: string | null;
|
||||
ingressLimits: BootstrapResponse["limits"] | null;
|
||||
runtimeSurface: RuntimeSurface;
|
||||
webuiCapabilities: string[];
|
||||
};
|
||||
|
||||
type GatewayState = ReadyGateway | { status: "loading" } | { status: "auth" }
|
||||
| { status: "error"; message: string };
|
||||
|
||||
function bootstrapCredentials(boot: BootstrapResponse, fallbackSurface: RuntimeSurface) {
|
||||
const capabilities = boot.terminal?.webui?.capabilities;
|
||||
return {
|
||||
token: boot.api_token ?? "",
|
||||
tokenExpiresAt: boot.expires_in ? Date.now() + Math.max(0, boot.expires_in) * 1000 : null,
|
||||
runtimeSurface: isNativeRuntime(boot.runtime_surface) ? "native"
|
||||
: boot.runtime_surface ? toRuntimeSurface(boot.runtime_surface) : fallbackSurface,
|
||||
webuiCapabilities: Array.isArray(capabilities) ? capabilities.filter((entry) => typeof entry === "string") : [],
|
||||
};
|
||||
}
|
||||
|
||||
function tokenRefreshDelayMs(expiresAt: number): number {
|
||||
const remaining = Math.max(0, expiresAt - Date.now());
|
||||
return Math.max(5_000, remaining - Math.min(30_000, Math.max(1_000, remaining / 2)));
|
||||
}
|
||||
|
||||
function isBootstrapAuthRequired(error: unknown): boolean {
|
||||
if (error instanceof BootstrapAuthRequiredError) return true;
|
||||
const msg = error instanceof Error ? error.message : String(error);
|
||||
return msg.includes("HTTP 401") || msg.includes("HTTP 403");
|
||||
}
|
||||
|
||||
function clearGatewayCaches() {
|
||||
clearReloadCache();
|
||||
clearStoredComposerDrafts();
|
||||
webuiThreadCache.clear();
|
||||
}
|
||||
|
||||
/** Owns the local socket and credentials; remote panes have separate clients. */
|
||||
export function useLocalGateway(prefetchChat: () => void) {
|
||||
const [state, setState] = useState<GatewayState>({ status: "loading" });
|
||||
const owner = useRef<NanobotClient | null>(null);
|
||||
const attempt = useRef(0);
|
||||
|
||||
const closeClient = useCallback(() => {
|
||||
const client = owner.current;
|
||||
owner.current = null;
|
||||
client?.close();
|
||||
}, []);
|
||||
|
||||
const refreshClient = useCallback(async (
|
||||
client: NanobotClient, secret: string, fallbackSurface: RuntimeSurface, signal?: AbortSignal,
|
||||
) => {
|
||||
if (owner.current !== client) throw new DOMException("Gateway client changed", "AbortError");
|
||||
const boot = await fetchBootstrap("", secret);
|
||||
signal?.throwIfAborted();
|
||||
if (owner.current !== client) throw new DOMException("Gateway client changed", "AbortError");
|
||||
const url = deriveWsUrl(boot.ws_path, boot.token, boot.ws_url);
|
||||
const credentials = bootstrapCredentials(boot, fallbackSurface);
|
||||
const host = createRuntimeHost(credentials.runtimeSurface, boot.runtime_capabilities);
|
||||
if (host.socketFactory) client.updateUrl(url, host.socketFactory);
|
||||
else client.updateUrl(url);
|
||||
client.updateMaxFrameBytes(boot.limits?.transport.max_frame_bytes);
|
||||
setState((current) => current.status === "ready" && current.client === client ? {
|
||||
...current,
|
||||
...credentials,
|
||||
modelName: boot.model_name ?? current.modelName,
|
||||
ingressLimits: boot.limits ?? current.ingressLimits,
|
||||
} : current);
|
||||
return { token: credentials.token, url };
|
||||
}, []);
|
||||
|
||||
const secretRef = useRef("");
|
||||
const bootstrapWithSecret = useCallback((secret: string, onAuthRejected?: () => void) => {
|
||||
const generation = ++attempt.current;
|
||||
prefetchChat();
|
||||
if (!onAuthRejected) setState({ status: "loading" });
|
||||
void (async () => {
|
||||
try {
|
||||
const boot = await fetchBootstrap("", secret);
|
||||
if (generation !== attempt.current) return;
|
||||
if (secret) saveSecret(secret);
|
||||
const url = deriveWsUrl(boot.ws_path, boot.token, boot.ws_url);
|
||||
activateReloadCache(url);
|
||||
const credentials = bootstrapCredentials(boot, "browser");
|
||||
const host = createRuntimeHost(credentials.runtimeSurface, boot.runtime_capabilities);
|
||||
const client: NanobotClient = new NanobotClient({
|
||||
url,
|
||||
maxFrameBytes: boot.limits?.transport.max_frame_bytes,
|
||||
socketFactory: host.socketFactory,
|
||||
onReauth: async (signal) => {
|
||||
try {
|
||||
return (await refreshClient(client, secret, credentials.runtimeSurface, signal)).url;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
},
|
||||
});
|
||||
secretRef.current = secret;
|
||||
owner.current = client;
|
||||
client.connect();
|
||||
setState({ status: "ready", client, ...credentials,
|
||||
modelName: boot.model_name ?? null, ingressLimits: boot.limits ?? null });
|
||||
} catch (error) {
|
||||
if (generation !== attempt.current) return;
|
||||
if (isBootstrapAuthRequired(error)) {
|
||||
clearGatewayCaches();
|
||||
if (onAuthRejected) onAuthRejected();
|
||||
else setState({ status: "auth" });
|
||||
} else {
|
||||
setState({ status: "error", message: error instanceof Error ? error.message : String(error) });
|
||||
}
|
||||
}
|
||||
})();
|
||||
}, [prefetchChat, refreshClient]);
|
||||
|
||||
useEffect(() => {
|
||||
bootstrapWithSecret(consumeUrlBootstrapSecret() || loadSavedSecret());
|
||||
return () => {
|
||||
++attempt.current;
|
||||
closeClient();
|
||||
};
|
||||
}, [bootstrapWithSecret, closeClient]);
|
||||
|
||||
const client = state.status === "ready" ? state.client : null;
|
||||
const expiresAt = state.status === "ready" ? state.tokenExpiresAt : null;
|
||||
const runtimeSurface = state.status === "ready" ? state.runtimeSurface : "browser";
|
||||
useEffect(() => {
|
||||
if (!client || expiresAt === null) return;
|
||||
const controller = new AbortController();
|
||||
const timer = window.setTimeout(async () => {
|
||||
try {
|
||||
await refreshClient(client, secretRef.current, runtimeSurface, controller.signal);
|
||||
} catch (error) {
|
||||
if (controller.signal.aborted || owner.current !== client || !isBootstrapAuthRequired(error)) return;
|
||||
closeClient();
|
||||
clearGatewayCaches();
|
||||
setState({ status: "auth" });
|
||||
}
|
||||
}, tokenRefreshDelayMs(expiresAt));
|
||||
return () => {
|
||||
window.clearTimeout(timer);
|
||||
controller.abort();
|
||||
};
|
||||
}, [client, closeClient, expiresAt, refreshClient, runtimeSurface]);
|
||||
|
||||
const changeModelName = useCallback((modelName: string | null) => {
|
||||
setState((current) => current.status === "ready" ? { ...current, modelName } : current);
|
||||
}, []);
|
||||
|
||||
const logout = useCallback(() => {
|
||||
++attempt.current;
|
||||
closeClient();
|
||||
clearSavedSecret();
|
||||
clearGatewayCaches();
|
||||
setState({ status: "auth" });
|
||||
}, [closeClient]);
|
||||
|
||||
const restartEngine = useCallback(async () => {
|
||||
const host = createRuntimeHost(runtimeSurface);
|
||||
if (!client || !host.restartEngine) throw new Error("native engine restart is unavailable");
|
||||
const secret = secretRef.current;
|
||||
rememberRestartRoute();
|
||||
try {
|
||||
window.localStorage.setItem(RESTART_STARTED_KEY, String(Date.now()));
|
||||
} catch {
|
||||
// ignore storage errors
|
||||
}
|
||||
try {
|
||||
await host.restartEngine();
|
||||
return (await refreshClient(client, secret, runtimeSurface)).token;
|
||||
} finally {
|
||||
try {
|
||||
window.localStorage.removeItem(RESTART_STARTED_KEY);
|
||||
window.localStorage.removeItem(RESTART_ROUTE_KEY);
|
||||
} catch {
|
||||
// ignore storage errors
|
||||
}
|
||||
}
|
||||
}, [client, refreshClient, runtimeSurface]);
|
||||
|
||||
return { state, bootstrapWithSecret, changeModelName, logout, restartEngine };
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { acceptsCompactionPhase } from "../../../packages/client-events/notifications";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { useThreadVisibility } from "@/hooks/useThreadVisibility";
|
||||
import { useStreamBatch } from "@/hooks/useStreamBatch";
|
||||
|
||||
import { useClient } from "@/providers/ClientProvider";
|
||||
import { hasPendingAgentActivity } from "@/lib/activity-timeline";
|
||||
@@ -47,9 +47,6 @@ type PendingStreamEvent =
|
||||
| { kind: "delta"; text: string; turn: UIMessageTurnFields; streamId?: string; source?: UIMessage["source"]; responseSources?: UIMessage["responseSources"]; responseInputIds?: string[] }
|
||||
| { kind: "reasoning"; text: string; turn: UIMessageTurnFields; streamId?: string };
|
||||
|
||||
const BACKGROUND_STREAM_FLUSH_INTERVAL_MS = 1_000;
|
||||
// Markdown and layout work must leave room for input between visible updates.
|
||||
const VISIBLE_STREAM_FLUSH_INTERVAL_MS = 50;
|
||||
const EMPTY_INITIAL_MESSAGES: UIMessage[] = [];
|
||||
const EMPTY_COMPLETED_TURN_IDS: readonly string[] = [];
|
||||
|
||||
@@ -173,9 +170,6 @@ export function useNanobotStream(
|
||||
const publishHistory = useCallback(() => setHistoryState(transcriptRef.current.paging), []);
|
||||
const [refreshSeq, setRefreshSeq] = useState(0);
|
||||
const refreshHistory = useCallback(() => setRefreshSeq((value) => value + 1), []);
|
||||
const threadVisible = useThreadVisibility();
|
||||
const threadVisibleRef = useRef(threadVisible);
|
||||
threadVisibleRef.current = threadVisible;
|
||||
const [runState, setRunState] = useState(() => chatId ? client.getRunState(chatId) : null);
|
||||
const isStreaming = runState?.active ?? false;
|
||||
const runStartedAt = runState?.startedAt ?? null;
|
||||
@@ -216,27 +210,8 @@ export function useNanobotStream(
|
||||
const [recoveryState, setRecoveryState] = useState<RecoveryState | null>(null);
|
||||
const [streamError, setStreamError] = useState<StreamError | null>(null);
|
||||
|
||||
const pendingStreamEventsRef = useRef<PendingStreamEvent[]>([]);
|
||||
const streamFrameRef = useRef<number | null>(null);
|
||||
const streamTimerRef = useRef<number | null>(null);
|
||||
const lastStreamFlushRef = useRef(0);
|
||||
|
||||
|
||||
const dismissStreamError = useCallback(() => setStreamError(null), []);
|
||||
|
||||
const clearPendingStreamWork = useCallback(() => {
|
||||
if (streamFrameRef.current !== null) {
|
||||
window.cancelAnimationFrame(streamFrameRef.current);
|
||||
streamFrameRef.current = null;
|
||||
}
|
||||
if (streamTimerRef.current !== null) {
|
||||
window.clearTimeout(streamTimerRef.current);
|
||||
streamTimerRef.current = null;
|
||||
}
|
||||
pendingStreamEventsRef.current = [];
|
||||
lastStreamFlushRef.current = 0;
|
||||
}, []);
|
||||
|
||||
const isSideChannelEvent = useCallback((ev: InboundEvent) => {
|
||||
const turnId = eventTurnId(ev);
|
||||
return turnId !== undefined && transcriptRef.current.sideChannelTurnIds.has(turnId);
|
||||
@@ -252,73 +227,6 @@ export function useNanobotStream(
|
||||
return hadActiveAssistant;
|
||||
}, []);
|
||||
|
||||
const applyStreamError = useCallback((err: StreamError) => {
|
||||
// One multiplexed client serves every thread. A correlated send fault
|
||||
// belongs only to its target chat. An uncorrelated transport close can
|
||||
// still be shown in the mounted thread, but cannot roll back any turn.
|
||||
if (!chatId || (err.chatId && err.chatId !== chatId)) return;
|
||||
setStreamError(err);
|
||||
if (err.kind === "model_request_failed") return;
|
||||
if (!err.turnId) return;
|
||||
|
||||
const rejectedTurnId = err.turnId;
|
||||
pendingStreamEventsRef.current = pendingStreamEventsRef.current.filter(
|
||||
(event) => event.turn.turnId !== rejectedTurnId,
|
||||
);
|
||||
transcriptRef.current.sideChannelTurnIds.delete(rejectedTurnId);
|
||||
setMessages((prev) => {
|
||||
const rejectedRows = prev.filter((message) => message.turnId === rejectedTurnId);
|
||||
if (rejectedRows.length === 0) return prev;
|
||||
const rejectedIds = new Set(rejectedRows.map((message) => message.id));
|
||||
const rejectedSegments = new Set(
|
||||
rejectedRows
|
||||
.map((message) => message.activitySegmentId)
|
||||
.filter((segmentId): segmentId is string => typeof segmentId === "string"),
|
||||
);
|
||||
const projection = transcriptRef.current.projection;
|
||||
const closedAssistantIds = new Set(projection.closedAssistantIds);
|
||||
for (const id of rejectedIds) closedAssistantIds.delete(id);
|
||||
const nextMessages = prev.flatMap<UIMessage>((message) => {
|
||||
if (message.turnId !== rejectedTurnId) return [message];
|
||||
if (message.role !== "user") return [];
|
||||
return [{
|
||||
...message,
|
||||
deliveryStatus: "failed" as const,
|
||||
deliveryErrorKind: err.kind,
|
||||
}];
|
||||
});
|
||||
transcriptRef.current.projection = {
|
||||
...projection,
|
||||
messages: nextMessages,
|
||||
activeAssistantId: projection.activeAssistantId
|
||||
&& rejectedIds.has(projection.activeAssistantId)
|
||||
? null
|
||||
: projection.activeAssistantId,
|
||||
closedAssistantIds,
|
||||
activitySegmentId: projection.activitySegmentId
|
||||
&& rejectedSegments.has(projection.activitySegmentId)
|
||||
? null
|
||||
: projection.activitySegmentId,
|
||||
fileEditSegmentId: projection.fileEditSegmentId
|
||||
&& rejectedSegments.has(projection.fileEditSegmentId)
|
||||
? null
|
||||
: projection.fileEditSegmentId,
|
||||
};
|
||||
transcriptRef.current.rejectTurn(rejectedTurnId);
|
||||
setExecSourceMessages(nextMessages);
|
||||
return nextMessages;
|
||||
});
|
||||
|
||||
if (!client.getRunState(chatId).active) {
|
||||
transcriptRef.current.projection = {
|
||||
...transcriptRef.current.projection,
|
||||
suppressUntilTurnEnd: false,
|
||||
};
|
||||
}
|
||||
}, [chatId, client, setMessages]);
|
||||
|
||||
useEffect(() => client.onError(applyStreamError), [applyStreamError, client]);
|
||||
|
||||
const applyPendingStreamEvents = useCallback(
|
||||
(prev: UIMessage[], events: PendingStreamEvent[]): UIMessage[] => {
|
||||
transcriptRef.current.projection = { ...transcriptRef.current.projection, messages: prev };
|
||||
@@ -389,19 +297,79 @@ export function useNanobotStream(
|
||||
[chatId],
|
||||
);
|
||||
|
||||
const publishStreamBatch = useCallback((events: PendingStreamEvent[]) => {
|
||||
setMessages((prev) => applyPendingStreamEvents(prev, events));
|
||||
}, [applyPendingStreamEvents, setMessages]);
|
||||
const { enqueue: enqueueStreamEvent, drain: drainStreamEvents, discard: discardStreamEvents } = useStreamBatch(publishStreamBatch);
|
||||
|
||||
const applyStreamError = useCallback((err: StreamError) => {
|
||||
// One multiplexed client serves every thread. A correlated send fault
|
||||
// belongs only to its target chat. An uncorrelated transport close can
|
||||
// still be shown in the mounted thread, but cannot roll back any turn.
|
||||
if (!chatId || (err.chatId && err.chatId !== chatId)) return;
|
||||
setStreamError(err);
|
||||
if (err.kind === "model_request_failed") return;
|
||||
if (!err.turnId) return;
|
||||
|
||||
const rejectedTurnId = err.turnId;
|
||||
discardStreamEvents((event) => event.turn.turnId === rejectedTurnId);
|
||||
transcriptRef.current.sideChannelTurnIds.delete(rejectedTurnId);
|
||||
setMessages((prev) => {
|
||||
const rejectedRows = prev.filter((message) => message.turnId === rejectedTurnId);
|
||||
if (rejectedRows.length === 0) return prev;
|
||||
const rejectedIds = new Set(rejectedRows.map((message) => message.id));
|
||||
const rejectedSegments = new Set(
|
||||
rejectedRows
|
||||
.map((message) => message.activitySegmentId)
|
||||
.filter((segmentId): segmentId is string => typeof segmentId === "string"),
|
||||
);
|
||||
const projection = transcriptRef.current.projection;
|
||||
const closedAssistantIds = new Set(projection.closedAssistantIds);
|
||||
for (const id of rejectedIds) closedAssistantIds.delete(id);
|
||||
const nextMessages = prev.flatMap<UIMessage>((message) => {
|
||||
if (message.turnId !== rejectedTurnId) return [message];
|
||||
if (message.role !== "user") return [];
|
||||
return [{
|
||||
...message,
|
||||
deliveryStatus: "failed" as const,
|
||||
deliveryErrorKind: err.kind,
|
||||
}];
|
||||
});
|
||||
transcriptRef.current.projection = {
|
||||
...projection,
|
||||
messages: nextMessages,
|
||||
activeAssistantId: projection.activeAssistantId
|
||||
&& rejectedIds.has(projection.activeAssistantId)
|
||||
? null
|
||||
: projection.activeAssistantId,
|
||||
closedAssistantIds,
|
||||
activitySegmentId: projection.activitySegmentId
|
||||
&& rejectedSegments.has(projection.activitySegmentId)
|
||||
? null
|
||||
: projection.activitySegmentId,
|
||||
fileEditSegmentId: projection.fileEditSegmentId
|
||||
&& rejectedSegments.has(projection.fileEditSegmentId)
|
||||
? null
|
||||
: projection.fileEditSegmentId,
|
||||
};
|
||||
transcriptRef.current.rejectTurn(rejectedTurnId);
|
||||
setExecSourceMessages(nextMessages);
|
||||
return nextMessages;
|
||||
});
|
||||
|
||||
if (!client.getRunState(chatId).active) {
|
||||
transcriptRef.current.projection = {
|
||||
...transcriptRef.current.projection,
|
||||
suppressUntilTurnEnd: false,
|
||||
};
|
||||
}
|
||||
}, [chatId, client, discardStreamEvents, setMessages]);
|
||||
|
||||
useEffect(() => client.onError(applyStreamError), [applyStreamError, client]);
|
||||
|
||||
const flushPendingStreamEvents = useCallback((end?: Extract<ThreadProjectionEvent, { event: "stream_end" }>) => {
|
||||
lastStreamFlushRef.current = 0;
|
||||
if (streamFrameRef.current !== null) {
|
||||
window.cancelAnimationFrame(streamFrameRef.current);
|
||||
streamFrameRef.current = null;
|
||||
}
|
||||
if (streamTimerRef.current !== null) {
|
||||
window.clearTimeout(streamTimerRef.current);
|
||||
streamTimerRef.current = null;
|
||||
}
|
||||
const events = pendingStreamEventsRef.current;
|
||||
const events = drainStreamEvents();
|
||||
if (events.length === 0 && !end) return;
|
||||
pendingStreamEventsRef.current = [];
|
||||
setMessages((prev) => {
|
||||
const nextMessages = events.length > 0 ? applyPendingStreamEvents(prev, events) : prev;
|
||||
transcriptRef.current.projection = { ...transcriptRef.current.projection, messages: nextMessages };
|
||||
@@ -410,67 +378,7 @@ export function useNanobotStream(
|
||||
});
|
||||
return transcriptRef.current.messages;
|
||||
});
|
||||
}, [applyPendingStreamEvents, setMessages]);
|
||||
|
||||
const schedulePendingStreamFlush = useCallback(function schedule() {
|
||||
if (streamFrameRef.current !== null || streamTimerRef.current !== null) return;
|
||||
if (document.visibilityState === "hidden" || !threadVisibleRef.current) {
|
||||
streamTimerRef.current = window.setTimeout(() => {
|
||||
streamTimerRef.current = null;
|
||||
const events = pendingStreamEventsRef.current;
|
||||
if (events.length === 0) return;
|
||||
pendingStreamEventsRef.current = [];
|
||||
setMessages((prev) => applyPendingStreamEvents(prev, events));
|
||||
}, BACKGROUND_STREAM_FLUSH_INTERVAL_MS);
|
||||
return;
|
||||
}
|
||||
const delay = VISIBLE_STREAM_FLUSH_INTERVAL_MS
|
||||
- (performance.now() - lastStreamFlushRef.current);
|
||||
if (delay > 0) {
|
||||
streamTimerRef.current = window.setTimeout(() => {
|
||||
streamTimerRef.current = null;
|
||||
schedule();
|
||||
}, delay);
|
||||
return;
|
||||
}
|
||||
streamFrameRef.current = window.requestAnimationFrame(() => {
|
||||
streamFrameRef.current = null;
|
||||
const events = pendingStreamEventsRef.current;
|
||||
if (events.length === 0) return;
|
||||
pendingStreamEventsRef.current = [];
|
||||
lastStreamFlushRef.current = performance.now();
|
||||
setMessages((prev) => applyPendingStreamEvents(prev, events));
|
||||
});
|
||||
}, [applyPendingStreamEvents, setMessages]);
|
||||
|
||||
useEffect(() => {
|
||||
if (threadVisible) {
|
||||
flushPendingStreamEvents();
|
||||
} else if (streamFrameRef.current !== null || streamTimerRef.current !== null) {
|
||||
if (streamFrameRef.current !== null) window.cancelAnimationFrame(streamFrameRef.current);
|
||||
streamFrameRef.current = null;
|
||||
if (streamTimerRef.current !== null) window.clearTimeout(streamTimerRef.current);
|
||||
streamTimerRef.current = null;
|
||||
schedulePendingStreamFlush();
|
||||
}
|
||||
}, [threadVisible, flushPendingStreamEvents, schedulePendingStreamFlush]);
|
||||
|
||||
useEffect(() => {
|
||||
const onVisibilityChange = () => {
|
||||
if (pendingStreamEventsRef.current.length === 0) return;
|
||||
if (document.visibilityState === "visible" && threadVisibleRef.current) {
|
||||
flushPendingStreamEvents();
|
||||
} else {
|
||||
if (streamFrameRef.current !== null) window.cancelAnimationFrame(streamFrameRef.current);
|
||||
streamFrameRef.current = null;
|
||||
if (streamTimerRef.current !== null) window.clearTimeout(streamTimerRef.current);
|
||||
streamTimerRef.current = null;
|
||||
schedulePendingStreamFlush();
|
||||
}
|
||||
};
|
||||
document.addEventListener("visibilitychange", onVisibilityChange);
|
||||
return () => document.removeEventListener("visibilitychange", onVisibilityChange);
|
||||
}, [flushPendingStreamEvents, schedulePendingStreamFlush]);
|
||||
}, [applyPendingStreamEvents, drainStreamEvents, setMessages]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!chatId) return;
|
||||
@@ -505,8 +413,8 @@ export function useNanobotStream(
|
||||
setRetryStatus(null);
|
||||
setGoalState(chatId ? client.getGoalState(chatId) : undefined);
|
||||
setRecoveryState(null);
|
||||
clearPendingStreamWork();
|
||||
}, [chatId, client, historyKey, temporary, clearActivitySegment, clearPendingStreamWork, setMessages]);
|
||||
drainStreamEvents();
|
||||
}, [chatId, client, historyKey, temporary, clearActivitySegment, drainStreamEvents, setMessages]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!chatId || (!hasPendingToolCalls && !initialStreaming)) return;
|
||||
@@ -784,7 +692,7 @@ export function useNanobotStream(
|
||||
if (transcriptRef.current.projection.suppressUntilTurnEnd || transcriptRef.current.represented(ev)) return;
|
||||
const chunk = typeof ev.text === "string" ? ev.text : "";
|
||||
if (!chunk) return;
|
||||
pendingStreamEventsRef.current.push({
|
||||
enqueueStreamEvent({
|
||||
kind: "delta",
|
||||
text: chunk,
|
||||
turn: turnFieldsFromEvent(ev, "answer"),
|
||||
@@ -793,7 +701,6 @@ export function useNanobotStream(
|
||||
responseSources: ev.response_sources,
|
||||
responseInputIds: ev.response_input_ids,
|
||||
});
|
||||
schedulePendingStreamFlush();
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -801,13 +708,12 @@ export function useNanobotStream(
|
||||
if (transcriptRef.current.projection.suppressUntilTurnEnd || transcriptRef.current.represented(ev)) return;
|
||||
const chunk = ev.text;
|
||||
if (!chunk) return;
|
||||
pendingStreamEventsRef.current.push({
|
||||
enqueueStreamEvent({
|
||||
kind: "reasoning",
|
||||
text: chunk,
|
||||
turn: turnFieldsFromEvent(ev, "reasoning"),
|
||||
streamId: ev.stream_id,
|
||||
});
|
||||
schedulePendingStreamFlush();
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -935,7 +841,7 @@ export function useNanobotStream(
|
||||
|| ev.status === "failed"
|
||||
) {
|
||||
setRetryStatus(null);
|
||||
clearPendingStreamWork();
|
||||
drainStreamEvents();
|
||||
closeActiveAssistantStream();
|
||||
clearActivitySegment();
|
||||
}
|
||||
@@ -954,7 +860,7 @@ export function useNanobotStream(
|
||||
ev.recovery_state?.status === "awaiting_user"
|
||||
|| ev.recovery_state?.status === "failed"
|
||||
) {
|
||||
clearPendingStreamWork();
|
||||
drainStreamEvents();
|
||||
closeActiveAssistantStream();
|
||||
clearActivitySegment();
|
||||
}
|
||||
@@ -984,14 +890,13 @@ export function useNanobotStream(
|
||||
setLiveInputs(null);
|
||||
// Navigation may happen before the throttled paint. Snapshot the pending
|
||||
// deltas synchronously while they still belong to this subscription.
|
||||
const pending = pendingStreamEventsRef.current;
|
||||
const pending = drainStreamEvents();
|
||||
const snapshot = pending.length > 0
|
||||
? applyPendingStreamEvents(messagesRef.current, pending)
|
||||
: messagesRef.current;
|
||||
onStreamDetach?.(snapshot);
|
||||
if (pending.length > 0) setMessages(snapshot);
|
||||
messageCache?.set(chatId, transcriptRef.current.save());
|
||||
clearPendingStreamWork();
|
||||
};
|
||||
}, [
|
||||
applyProjectionEvent,
|
||||
@@ -1001,13 +906,13 @@ export function useNanobotStream(
|
||||
closeActiveAssistantStream,
|
||||
client,
|
||||
clearActivitySegment,
|
||||
clearPendingStreamWork,
|
||||
drainStreamEvents,
|
||||
flushPendingStreamEvents,
|
||||
isSideChannelEvent,
|
||||
onTurnEnd,
|
||||
onStreamDetach,
|
||||
messageCache,
|
||||
schedulePendingStreamFlush,
|
||||
enqueueStreamEvent,
|
||||
setMessages,
|
||||
]);
|
||||
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
import { useCallback, useEffect, useLayoutEffect, useRef } from "react";
|
||||
|
||||
/** Animates already mounted rows when a project or pane group expands or collapses. */
|
||||
export function useSidebarGroupMotion(
|
||||
collapsedGroups: Readonly<Record<string, boolean>>,
|
||||
collapsedPaneGroups: ReadonlySet<string>,
|
||||
) {
|
||||
const layoutRowRefs = useRef(new Map<string, HTMLElement>());
|
||||
const pendingLayoutRectsRef = useRef<Map<string, DOMRect> | null>(null);
|
||||
const layoutAnimationsRef = useRef(new Map<string, Animation>());
|
||||
const registerRow = useCallback((key: string, element: HTMLElement | null) => {
|
||||
if (element) layoutRowRefs.current.set(key, element);
|
||||
else layoutRowRefs.current.delete(key);
|
||||
}, []);
|
||||
|
||||
const cancelAnimations = useCallback(() => {
|
||||
for (const animation of layoutAnimationsRef.current.values()) animation.cancel();
|
||||
layoutAnimationsRef.current.clear();
|
||||
}, []);
|
||||
|
||||
const measureLayoutRows = useCallback(() => {
|
||||
const rects = new Map<string, DOMRect>();
|
||||
for (const [key, row] of layoutRowRefs.current) {
|
||||
rects.set(key, row.getBoundingClientRect());
|
||||
}
|
||||
return rects;
|
||||
}, []);
|
||||
|
||||
const captureLayout = useCallback(() => {
|
||||
cancelAnimations();
|
||||
pendingLayoutRectsRef.current = measureLayoutRows();
|
||||
}, [cancelAnimations, measureLayoutRows]);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const previousRects = pendingLayoutRectsRef.current;
|
||||
if (!previousRects) return;
|
||||
pendingLayoutRectsRef.current = null;
|
||||
const nextRects = measureLayoutRows();
|
||||
const reduceMotion = typeof window.matchMedia === "function"
|
||||
&& window.matchMedia("(prefers-reduced-motion: reduce)").matches;
|
||||
if (reduceMotion) return;
|
||||
for (const [key, nextRect] of nextRects) {
|
||||
const previousRect = previousRects.get(key);
|
||||
const row = layoutRowRefs.current.get(key);
|
||||
if (!previousRect || !row || typeof row.animate !== "function") continue;
|
||||
const deltaY = previousRect.top - nextRect.top;
|
||||
if (Math.abs(deltaY) < 0.5) continue;
|
||||
const animation = row.animate(
|
||||
[
|
||||
{ transform: `translateY(${deltaY}px)` },
|
||||
{ transform: "translateY(0)" },
|
||||
],
|
||||
{
|
||||
duration: 180,
|
||||
easing: "cubic-bezier(0.2, 0, 0, 1)",
|
||||
},
|
||||
);
|
||||
layoutAnimationsRef.current.set(key, animation);
|
||||
animation.addEventListener("finish", () => {
|
||||
if (layoutAnimationsRef.current.get(key) === animation) {
|
||||
layoutAnimationsRef.current.delete(key);
|
||||
}
|
||||
}, { once: true });
|
||||
}
|
||||
}, [collapsedGroups, collapsedPaneGroups, measureLayoutRows]);
|
||||
|
||||
useEffect(() => cancelAnimations, [cancelAnimations]);
|
||||
|
||||
return { captureLayout, registerRow };
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
import { useCallback, useEffect, useRef } from "react";
|
||||
import { useThreadVisibility } from "@/hooks/useThreadVisibility";
|
||||
|
||||
const BACKGROUND_FLUSH_INTERVAL_MS = 1_000;
|
||||
// Markdown and layout work must leave room for input between visible updates.
|
||||
const VISIBLE_FLUSH_INTERVAL_MS = 50;
|
||||
|
||||
/** Schedules batch publication; the transcript owner drains synchronously at semantic boundaries. */
|
||||
export function useStreamBatch<Event>(onFlush: (events: Event[]) => void) {
|
||||
const visible = useThreadVisibility();
|
||||
const visibleRef = useRef(visible);
|
||||
visibleRef.current = visible;
|
||||
const pending = useRef<Event[]>([]);
|
||||
const frame = useRef<number | null>(null);
|
||||
const timer = useRef<number | null>(null);
|
||||
const lastFlush = useRef(0);
|
||||
|
||||
const take = useCallback(() => {
|
||||
const events = pending.current;
|
||||
pending.current = [];
|
||||
return events;
|
||||
}, []);
|
||||
|
||||
const cancelScheduled = useCallback(() => {
|
||||
if (frame.current !== null) window.cancelAnimationFrame(frame.current);
|
||||
if (timer.current !== null) window.clearTimeout(timer.current);
|
||||
frame.current = null;
|
||||
timer.current = null;
|
||||
}, []);
|
||||
|
||||
const drain = useCallback(() => {
|
||||
cancelScheduled();
|
||||
lastFlush.current = 0;
|
||||
return take();
|
||||
}, [cancelScheduled, take]);
|
||||
|
||||
const discard = useCallback((matches: (event: Event) => boolean) => {
|
||||
pending.current = pending.current.filter((event) => !matches(event));
|
||||
}, []);
|
||||
|
||||
const schedule = useCallback(function schedule() {
|
||||
if (frame.current !== null || timer.current !== null) return;
|
||||
if (document.visibilityState === "hidden" || !visibleRef.current) {
|
||||
timer.current = window.setTimeout(() => {
|
||||
timer.current = null;
|
||||
const events = take();
|
||||
if (events.length > 0) onFlush(events);
|
||||
}, BACKGROUND_FLUSH_INTERVAL_MS);
|
||||
return;
|
||||
}
|
||||
const delay = VISIBLE_FLUSH_INTERVAL_MS - (performance.now() - lastFlush.current);
|
||||
if (delay > 0) {
|
||||
timer.current = window.setTimeout(() => {
|
||||
timer.current = null;
|
||||
schedule();
|
||||
}, delay);
|
||||
return;
|
||||
}
|
||||
frame.current = window.requestAnimationFrame(() => {
|
||||
frame.current = null;
|
||||
const events = take();
|
||||
if (events.length === 0) return;
|
||||
lastFlush.current = performance.now();
|
||||
onFlush(events);
|
||||
});
|
||||
}, [onFlush, take]);
|
||||
|
||||
const enqueue = useCallback((event: Event) => {
|
||||
pending.current.push(event);
|
||||
schedule();
|
||||
}, [schedule]);
|
||||
|
||||
const flush = useCallback(() => {
|
||||
const events = drain();
|
||||
if (events.length > 0) onFlush(events);
|
||||
}, [drain, onFlush]);
|
||||
|
||||
useEffect(() => {
|
||||
if (visible) flush();
|
||||
else if (frame.current !== null || timer.current !== null) {
|
||||
cancelScheduled();
|
||||
schedule();
|
||||
}
|
||||
}, [cancelScheduled, flush, schedule, visible]);
|
||||
|
||||
useEffect(() => {
|
||||
const onVisibilityChange = () => {
|
||||
if (pending.current.length === 0) return;
|
||||
if (document.visibilityState === "visible" && visibleRef.current) flush();
|
||||
else {
|
||||
cancelScheduled();
|
||||
schedule();
|
||||
}
|
||||
};
|
||||
document.addEventListener("visibilitychange", onVisibilityChange);
|
||||
return () => document.removeEventListener("visibilitychange", onVisibilityChange);
|
||||
}, [cancelScheduled, flush, schedule]);
|
||||
|
||||
// The subscription drains on detach before saving its last snapshot.
|
||||
return { enqueue, discard, drain };
|
||||
}
|
||||
Reference in new issue
Block a user