refactor(webui): separate gateway mutations and UI state (#6727)

This commit is contained in:
chengyongru authored and GitHub committed 2026-11-19 22:22:51 +08:00
1 parent ce12bfdd0d
commit 5537bdabd3
70 files changed
+4058 -3650

No files matched your search

+21 -440
View File
@@ -25,11 +25,21 @@ import { invalidateToolsCatalog } from "@/lib/tools-catalog-cache";
import type { SidebarDeleteItem } from "@/components/ChatList";
import type { SettingsSectionKey } from "@/components/settings/SettingsView";
import { StartupShell } from "@/components/StartupShell";
import { ComposerDraftStore, clearStoredComposerDrafts } from "@/lib/composer-draft";
import { activateReloadCache, clearReloadCache } from "@/lib/reload-cache";
import { webuiThreadCache } from "@/lib/webui-thread-cache";
import { ComposerDraftStore } from "@/lib/composer-draft";
import { ThreadVisibilityContext } from "@/hooks/useThreadVisibility";
import { isAppsSection, type SettingsExitGuard, type SettingsFocusTarget } from "@/components/settings/contracts";
import {
RESTART_ROUTE_KEY,
RESTART_STARTED_KEY,
changesSettingsSurface,
defaultShellRoute,
readShellRoute,
rememberRestartRoute,
shellViewForSettingsSection,
writeShellRoute,
type ShellRoute,
type ShellView,
} from "@/shell-route";
import { PaneWorkbench } from "@/components/workbench/PaneWorkbench";
import { transitionSession } from "@/components/thread/session-transition";
import {
@@ -52,6 +62,7 @@ import {
import { ToastProvider, useToast } from "@/components/ui/toast";
import { Sheet, SheetContent, SheetTitle } from "@/components/ui/sheet";
import { useLocalGateway } from "@/hooks/useLocalGateway";
import { useSessions } from "@/hooks/useSessions";
import { useReconnectRuns } from "@/hooks/useReconnectRuns";
import { useDeferredTitleRefresh } from "@/hooks/useDeferredTitleRefresh";
@@ -63,18 +74,8 @@ import type { SendAttachment, SendOptions } from "@/hooks/useNanobotStream";
import { ThemeProvider, useTheme } from "@/hooks/useTheme";
import { useReadingTypography } from "@/hooks/useReadingTypography";
import { cn } from "@/lib/utils";
import {
BootstrapAuthRequiredError,
clearSavedSecret,
consumeUrlBootstrapSecret,
deriveWsUrl,
fetchBootstrap,
loadSavedSecret,
saveSecret,
} from "@/lib/bootstrap";
import { displayTitle, sortSessions } from "@/lib/chat-groups";
import { deriveTitle } from "@/lib/format";
import { NanobotClient } from "@/lib/nanobot-client";
import { BrowserNotifications, useBrowserNotificationLifecycle } from "@/components/BrowserNotifications";
import { ThreadMessageCache } from "@/lib/thread-message-cache";
import { FilePreviewStore } from "@/hooks/useFilePreviewState";
@@ -83,7 +84,6 @@ import { BackgroundProvider } from "@/providers/BackgroundProvider";
import { useVersionCheck } from "@/providers/VersionCheckProvider";
import { useUpdateFlow } from "@/providers/UpdateFlowProvider";
import type {
BootstrapResponse,
ChatSummary,
RuntimeSurface,
SessionAutomationJob,
@@ -97,57 +97,20 @@ import { Input } from "@/components/ui/input";
import { Dialog, DialogContent, DialogDescription, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import { HoverHint } from "@/components/ui/hover-hint";
import { fetchSettings, fetchWorkspaces } from "@/lib/api";
import {
createRuntimeHost,
isNativeRuntime,
toRuntimeSurface,
} from "@/lib/runtime";
import { isNativeRuntime } from "@/lib/runtime";
import { projectNameFromPath, scopeWithAccessMode } from "@/lib/workspace";
import {
createTemporaryChatSession,
deriveTemporaryChatTitle,
} from "@/lib/temporary-chat";
type BootState =
| { status: "loading" }
| { status: "error"; message: string }
| { status: "auth" }
| {
status: "ready";
client: NanobotClient;
token: string;
tokenExpiresAt: number | null;
modelName: string | null;
ingressLimits: BootstrapResponse["limits"] | null;
runtimeSurface: RuntimeSurface;
webuiCapabilities: string[];
};
function bootstrapCapabilities(boot: BootstrapResponse): string[] {
const capabilities = boot.terminal?.webui?.capabilities;
return Array.isArray(capabilities) ? capabilities.filter((entry) => typeof entry === "string") : [];
}
const SIDEBAR_STORAGE_KEY = "nanobot-webui.sidebar";
const SESSION_UPDATES_STORAGE_KEY = "nanobot-webui.sidebar.session-updates.v1";
const LEGACY_COMPLETED_RUNS_STORAGE_KEY = "nanobot-webui.sidebar.completed-runs.v1";
const RESTART_STARTED_KEY = "nanobot-webui.restartStartedAt";
const RESTART_ROUTE_KEY = "nanobot-webui.restartRoute";
const RESTART_ROUTE_TTL_MS = 5 * 60 * 1000;
const SIDEBAR_WIDTH = 272;
const SIDEBAR_WIDTH_STORAGE_KEY = "nanobot-webui.sidebar.width";
const SIDEBAR_RAIL_WIDTH = 56;
const MOBILE_SIDEBAR_WIDTH = `min(${SIDEBAR_WIDTH}px, calc(100vw - 0.75rem))`;
const TOKEN_REFRESH_MARGIN_MS = 30_000;
const TOKEN_REFRESH_MIN_DELAY_MS = 5_000;
type ShellView = "chat" | "settings" | "apps" | "automations" | "remote";
type ShellRoute = {
view: ShellView;
activeKey: string | null;
settingsSection: SettingsSectionKey;
settingsFocus?: SettingsFocusTarget;
temporary?: boolean;
};
const loadThreadShell = () => import("@/components/thread/ThreadShell");
const ThreadShell = lazy(() => loadThreadShell().then(
(module) => ({ default: module.ThreadShell }),
@@ -170,214 +133,6 @@ const RenameDialog = lazy(async () => {
return { default: module.RenameDialog };
});
const SETTINGS_SECTION_KEYS: SettingsSectionKey[] = [
"capabilities",
"overview",
"about",
"appearance",
"notifications",
"models",
"image",
"voice",
"browser",
"channels",
"apps",
"automations",
"memory",
"skills",
"runtime",
"advanced",
];
function isSettingsSectionKey(value: string | null): value is SettingsSectionKey {
return SETTINGS_SECTION_KEYS.includes(value as SettingsSectionKey);
}
function defaultShellRoute(): ShellRoute {
return { view: "chat", activeKey: null, settingsSection: "overview" };
}
function shellViewForSettingsSection(section: SettingsSectionKey): ShellView {
if (isAppsSection(section)) return "apps";
if (section === "automations") return "automations";
return "settings";
}
function changesSettingsSurface(current: ShellRoute, next: ShellRoute): boolean {
return current.view !== "chat" && current.view !== "remote" &&
(current.view !== next.view || current.settingsSection !== next.settingsSection);
}
function fallbackRestartHash(hash: string): boolean {
return !hash || hash === "/" || hash === "/new";
}
function rememberRestartRoute(): void {
if (typeof window === "undefined") return;
try {
window.localStorage.setItem(RESTART_ROUTE_KEY, window.location.hash || "#/new");
} catch {
// ignore storage errors
}
}
function maybeRestoreRestartHash(hash: string): string {
if (typeof window === "undefined" || !fallbackRestartHash(hash)) return hash;
try {
const startedAt = Number(window.localStorage.getItem(RESTART_STARTED_KEY) ?? "0");
const storedHash = window.localStorage.getItem(RESTART_ROUTE_KEY);
if (!startedAt || !storedHash || Date.now() - startedAt > RESTART_ROUTE_TTL_MS) {
window.localStorage.removeItem(RESTART_ROUTE_KEY);
return hash;
}
window.localStorage.removeItem(RESTART_ROUTE_KEY);
const nextHash = storedHash.startsWith("#") ? storedHash : `#${storedHash}`;
window.history.replaceState(
null,
"",
`${window.location.pathname}${window.location.search}${nextHash}`,
);
return nextHash.slice(1);
} catch {
return hash;
}
}
function readShellRoute(): ShellRoute {
if (typeof window === "undefined") return defaultShellRoute();
const currentHash = window.location.hash.startsWith("#")
? window.location.hash.slice(1)
: window.location.hash;
const hash = maybeRestoreRestartHash(currentHash);
if (!hash || hash === "/" || hash === "/new") return defaultShellRoute();
const [path, query = ""] = hash.split("?", 2);
const params = new URLSearchParams(query);
const rawSettingsSection = params.get("section");
const settingsSection = isSettingsSectionKey(rawSettingsSection)
? rawSettingsSection
: "overview";
const saved: unknown = window.history.state?.nanobotReturnChat;
const returnChat = saved && typeof saved === "object" && "hash" in saved
&& saved.hash === window.location.hash ? saved : null;
const activeKey = params.get("chat")?.trim()
|| (returnChat && "key" in returnChat && typeof returnChat.key === "string"
? returnChat.key : null);
const temporary = Boolean(returnChat && "temporary" in returnChat && returnChat.temporary === true);
if (path === "/settings") {
const focus = params.get("focus");
return {
view: shellViewForSettingsSection(settingsSection),
activeKey,
temporary,
settingsSection,
settingsFocus: settingsSection === "advanced" && (focus === "sandbox" || focus === "sandbox-launcher")
? focus
: settingsSection === "models" && focus?.startsWith("image-input:")
? `image-input:${focus.slice("image-input:".length)}`
: undefined,
};
}
if (path === "/apps") {
return { view: "apps", activeKey, temporary, settingsSection: isAppsSection(settingsSection) ? settingsSection : "apps" };
}
if (path === "/automations") {
return { view: "automations", activeKey, temporary, settingsSection: "automations" };
}
if (path === "/channels") {
return { view: "apps", activeKey, temporary, settingsSection: "channels" };
}
if (path === "/remote") {
return { view: "remote", activeKey, temporary, settingsSection: "overview" };
}
if (path === "/skills") {
return { view: "apps", activeKey, temporary, settingsSection: "skills" };
}
if (path.startsWith("/temporary/")) {
const encoded = path.slice("/temporary/".length);
try {
const chatId = decodeURIComponent(encoded).trim();
return chatId
? {
view: "chat",
activeKey: `websocket:${chatId}`,
settingsSection: "overview",
temporary: true,
}
: defaultShellRoute();
} catch {
return defaultShellRoute();
}
}
if (path.startsWith("/chat/")) {
const encoded = path.slice("/chat/".length);
try {
const key = decodeURIComponent(encoded).trim();
return key
? { view: "chat", activeKey: key, settingsSection: "overview" }
: defaultShellRoute();
} catch {
return defaultShellRoute();
}
}
return defaultShellRoute();
}
function shellRouteHash(route: ShellRoute): string {
if (route.view === "chat") {
if (route.temporary && route.activeKey?.startsWith("websocket:")) {
const chatId = route.activeKey.slice("websocket:".length);
return `#/temporary/${encodeURIComponent(chatId)}`;
}
return route.activeKey
? `#/chat/${encodeURIComponent(route.activeKey)}`
: "#/new";
}
const params = new URLSearchParams();
if (route.view === "settings" && route.settingsSection !== "overview") {
params.set("section", route.settingsSection);
if (route.settingsFocus) params.set("focus", route.settingsFocus);
}
if (route.view === "apps" && route.settingsSection !== "apps") {
params.set("section", route.settingsSection);
}
const query = params.toString();
return `#/${route.view}${query ? `?${query}` : ""}`;
}
function writeShellRoute(route: ShellRoute, replace = false): void {
if (typeof window === "undefined") return;
const nextHash = shellRouteHash(route);
const state = {
...window.history.state,
nanobotReturnChat: route.view === "chat" ? null : {
hash: nextHash,
key: route.activeKey,
temporary: route.temporary === true,
},
};
const url = `${window.location.pathname}${window.location.search}${nextHash}`;
if (replace || window.location.hash === nextHash) {
window.history.replaceState(state, "", url);
} else {
window.history.pushState(state, "", url);
}
}
function bootstrapTokenExpiresAt(expiresInSeconds: number): number {
return Date.now() + Math.max(0, expiresInSeconds) * 1000;
}
function tokenRefreshDelayMs(expiresAt: number): number {
const remaining = Math.max(0, expiresAt - Date.now());
const margin = Math.min(
TOKEN_REFRESH_MARGIN_MS,
Math.max(1_000, remaining / 2),
);
return Math.max(TOKEN_REFRESH_MIN_DELAY_MS, remaining - margin);
}
function AuthForm({ onSecret }: {
onSecret: (secret: string, onAuthRejected: () => void) => void;
}) {
@@ -590,12 +345,6 @@ function normalizeWorkspaceScope(scope: WorkspaceScopePayload): WorkspaceScopePa
};
}
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 HostChrome({
rightAction,
}: {
@@ -612,12 +361,8 @@ function HostChrome({
);
}
function resolveRuntimeSurface(
surface: RuntimeSurface | null | undefined,
fallback: RuntimeSurface,
): RuntimeSurface {
if (isNativeRuntime(surface)) return "native";
return surface ? toRuntimeSurface(surface) : fallback;
function prefetchChat() {
if (readShellRoute().view === "chat") void loadThreadShell().catch(() => {});
}
export default function App() {
@@ -625,129 +370,7 @@ export default function App() {
useBrowserNotificationLifecycle();
useReadingTypography();
const { t } = useTranslation();
const [state, setState] = useState<BootState>({ status: "loading" });
const bootstrapSecretRef = useRef("");
const refreshReadyClient = useCallback(
async (client: NanobotClient, fallbackSurface: RuntimeSurface, signal?: AbortSignal) => {
const boot = await fetchBootstrap("", bootstrapSecretRef.current);
signal?.throwIfAborted();
const url = deriveWsUrl(boot.ws_path, boot.token, boot.ws_url);
const runtimeSurface = resolveRuntimeSurface(boot.runtime_surface, fallbackSurface);
const runtimeHost = createRuntimeHost(runtimeSurface, boot.runtime_capabilities);
const tokenExpiresAt = boot.expires_in
? bootstrapTokenExpiresAt(boot.expires_in)
: null;
if (runtimeHost.socketFactory) {
client.updateUrl(url, runtimeHost.socketFactory);
} else {
client.updateUrl(url);
}
client.updateMaxFrameBytes(boot.limits?.transport.max_frame_bytes);
setState((current) =>
current.status === "ready" && current.client === client
? {
...current,
token: boot.api_token ?? "",
tokenExpiresAt,
modelName: boot.model_name ?? current.modelName,
ingressLimits: boot.limits ?? current.ingressLimits,
runtimeSurface,
webuiCapabilities: bootstrapCapabilities(boot),
}
: current,
);
return { token: boot.api_token ?? "", url };
},
[],
);
const bootstrapWithSecret = useCallback(
(secret: string, onAuthRejected?: () => void) => {
let cancelled = false;
if (readShellRoute().view === "chat") void loadThreadShell().catch(() => {});
(async () => {
if (!onAuthRejected) setState({ status: "loading" });
try {
const boot = await fetchBootstrap("", secret);
if (cancelled) return;
if (secret) saveSecret(secret);
const url = deriveWsUrl(boot.ws_path, boot.token, boot.ws_url);
activateReloadCache(url);
const runtimeSurface = resolveRuntimeSurface(boot.runtime_surface, "browser");
const runtimeHost = createRuntimeHost(runtimeSurface, boot.runtime_capabilities);
const client = new NanobotClient({
url,
maxFrameBytes: boot.limits?.transport.max_frame_bytes,
socketFactory: runtimeHost.socketFactory,
onReauth: async (signal) => {
try {
const refreshed = await refreshReadyClient(client, runtimeSurface, signal);
return refreshed.url;
} catch {
return null;
}
},
});
bootstrapSecretRef.current = secret;
client.connect();
setState({
status: "ready",
client,
token: boot.api_token ?? "",
tokenExpiresAt: boot.expires_in
? bootstrapTokenExpiresAt(boot.expires_in)
: null,
modelName: boot.model_name ?? null,
ingressLimits: boot.limits ?? null,
runtimeSurface,
webuiCapabilities: bootstrapCapabilities(boot),
});
} catch (e) {
if (cancelled) return;
if (isBootstrapAuthRequired(e)) {
clearReloadCache();
clearStoredComposerDrafts();
webuiThreadCache.clear();
if (onAuthRejected) onAuthRejected();
else setState({ status: "auth" });
} else {
setState({
status: "error",
message: e instanceof Error ? e.message : String(e),
});
}
}
})();
return () => {
cancelled = true;
};
},
[refreshReadyClient],
);
useEffect(() => {
if (state.status !== "ready" || state.tokenExpiresAt === null) return;
const client = state.client;
const timer = window.setTimeout(async () => {
try {
await refreshReadyClient(client, state.runtimeSurface);
} catch (e) {
if (isBootstrapAuthRequired(e)) {
clearReloadCache();
clearStoredComposerDrafts();
webuiThreadCache.clear();
setState({ status: "auth" });
}
}
}, tokenRefreshDelayMs(state.tokenExpiresAt));
return () => window.clearTimeout(timer);
}, [refreshReadyClient, state]);
useEffect(() => {
const saved = consumeUrlBootstrapSecret() || loadSavedSecret();
return bootstrapWithSecret(saved);
}, [bootstrapWithSecret]);
const { state, bootstrapWithSecret, changeModelName, logout, restartEngine } = useLocalGateway(prefetchChat);
if (state.status === "loading") {
return <StartupShell />;
@@ -769,48 +392,6 @@ export default function App() {
);
}
const handleModelNameChange = (modelName: string | null) => {
setState((current) =>
current.status === "ready" ? { ...current, modelName } : current,
);
};
const handleLogout = () => {
if (state.status === "ready") {
state.client.close();
}
clearSavedSecret();
clearReloadCache();
clearStoredComposerDrafts();
webuiThreadCache.clear();
setState({ status: "auth" });
};
const handleNativeEngineRestart = async (): Promise<string> => {
const runtimeHost = createRuntimeHost(state.runtimeSurface);
if (!runtimeHost.restartEngine) {
throw new Error("native engine restart is unavailable");
}
rememberRestartRoute();
try {
window.localStorage.setItem(RESTART_STARTED_KEY, String(Date.now()));
} catch {
// ignore storage errors
}
try {
await runtimeHost.restartEngine();
const refreshed = await refreshReadyClient(state.client, state.runtimeSurface);
return refreshed.token;
} finally {
try {
window.localStorage.removeItem(RESTART_STARTED_KEY);
window.localStorage.removeItem(RESTART_ROUTE_KEY);
} catch {
// ignore storage errors
}
}
};
return (
<ClientProvider
client={state.client}
@@ -823,9 +404,9 @@ export default function App() {
<BrowserNotifications client={state.client} />
<BackgroundProvider><RemoteInstances><ToastProvider><Shell
runtimeSurface={state.runtimeSurface}
onModelNameChange={handleModelNameChange}
onLogout={handleLogout}
onNativeEngineRestart={handleNativeEngineRestart}
onModelNameChange={changeModelName}
onLogout={logout}
onNativeEngineRestart={restartEngine}
/></ToastProvider></RemoteInstances></BackgroundProvider>
</ClientProvider>
);
+5 -59
View File
@@ -32,6 +32,7 @@ import {
Unplug,
X,
} from "lucide-react";
import { useSidebarGroupMotion } from "@/hooks/useSidebarGroupMotion";
import { useTranslation } from "react-i18next";
import {
@@ -342,9 +343,6 @@ export const ChatList = memo(function ChatList({
observer?.disconnect();
};
}, [hasListHeader, loading, sessions.length, temporarySessions.length]);
const layoutRowRefs = useRef(new Map<string, HTMLElement>());
const pendingLayoutRectsRef = useRef<Map<string, DOMRect> | null>(null);
const layoutAnimationsRef = useRef(new Map<string, Animation>());
const [collapsedPaneGroups, setCollapsedPaneGroups] = useState<Set<string>>(
readCollapsedPaneGroups,
);
@@ -551,19 +549,7 @@ export const ChatList = memo(function ChatList({
});
}, [loading, paneGroups]);
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(() => {
for (const animation of layoutAnimationsRef.current.values()) animation.cancel();
layoutAnimationsRef.current.clear();
pendingLayoutRectsRef.current = measureLayoutRows();
}, [measureLayoutRows]);
const { registerRow, captureLayout } = useSidebarGroupMotion(collapsedGroups, collapsedPaneGroups);
const togglePaneGroup = useCallback((key: string) => {
captureLayout();
@@ -581,43 +567,6 @@ export const ChatList = memo(function ChatList({
onToggleGroup(key);
}, [captureLayout, onToggleGroup]);
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(() => () => {
for (const animation of layoutAnimationsRef.current.values()) animation.cancel();
}, []);
if (initialLoading && sessions.length === 0 && temporarySessions.length === 0) {
return (
<SkeletonStatus label={t("chat.loading")} className="px-2 py-1.5">
@@ -796,8 +745,7 @@ export const ChatList = memo(function ChatList({
<div
ref={(element) => {
const key = `group:${group.id}`;
if (element) layoutRowRefs.current.set(key, element);
else layoutRowRefs.current.delete(key);
registerRow(key, element);
}}
data-sidebar-group-header={group.id}
>
@@ -866,8 +814,7 @@ export const ChatList = memo(function ChatList({
<li
key={s.key}
ref={(element) => {
if (element) layoutRowRefs.current.set(s.key, element);
else layoutRowRefs.current.delete(s.key);
registerRow(s.key, element);
}}
data-sidebar-tab-group="true"
data-pane-group-collapsed={paneGroupCollapsed ? "true" : undefined}
@@ -1008,8 +955,7 @@ export const ChatList = memo(function ChatList({
<li
key={s.key}
ref={(element) => {
if (element) layoutRowRefs.current.set(s.key, element);
else layoutRowRefs.current.delete(s.key);
registerRow(s.key, element);
}}
className="relative min-w-0"
>
+3 -1
View File
@@ -6,6 +6,7 @@ import { floatingItemClassName, floatingItemFocusClassName, floatingSurfaceClass
import { useFloatingPortal } from "@/components/ui/floating-portal";
import { useToast } from "@/components/ui/toast";
import { copyTextToClipboard } from "@/lib/clipboard";
import { useOverlaySurfaceRef } from "@/lib/dom-overlays";
import type { FileReferenceMetadata, FilePreviewPayload } from "@/lib/types";
import { cn } from "@/lib/utils";
@@ -41,6 +42,7 @@ export function FileActions({
const [copyStatus, setCopyStatus] = useState<"copied" | "failed" | null>(null);
const resolveMetadata = context?.resolveMetadata;
const portal = useFloatingPortal();
const surfaceRef = useOverlaySurfaceRef<HTMLDivElement>("overlay");
const point = useRef({ x: 0, y: 0 });
const anchor = useRef({ getBoundingClientRect: () => new DOMRect(point.current.x, point.current.y, 0, 0) });
const opener = useRef<HTMLElement | null>(null);
@@ -112,7 +114,7 @@ export function FileActions({
{children}
</span>
<Menu.Portal container={portal ?? undefined}>
<Menu.Content aria-label={t("fileActions.menu", { name: path.split(/[\\/]/).pop() || path })}
<Menu.Content ref={surfaceRef} aria-label={t("fileActions.menu", { name: path.split(/[\\/]/).pop() || path })}
align="start" sideOffset={4} collisionPadding={12}
className={cn(floatingSurfaceClassName, floatingSurfaceMotionClassName, "min-w-40 origin-[var(--radix-popper-transform-origin)] rounded-control p-1 [&_[role=menuitem]]:py-1.5")}
onClick={(event) => event.stopPropagation()}
+3
View File
@@ -3,6 +3,7 @@ import * as DialogPrimitive from "@radix-ui/react-dialog";
import { ChevronLeft, ChevronRight, X } from "lucide-react";
import { useTranslation } from "react-i18next";
import { useOverlaySurfaceRef } from "@/lib/dom-overlays";
import { cn } from "@/lib/utils";
import type { UIImage } from "@/lib/types";
import { ZoomableImage } from "@/components/ZoomableImage";
@@ -38,6 +39,7 @@ export function ImageLightbox({
const total = images.length;
const current = index !== null ? images[index] : null;
const opener = useRef<HTMLElement | null>(null);
const surfaceRef = useOverlaySurfaceRef<HTMLDivElement>("dialog");
const go = useCallback(
(delta: number) => {
@@ -93,6 +95,7 @@ export function ImageLightbox({
)}
/>
<DialogPrimitive.Content
ref={surfaceRef}
aria-label={current.name ?? t("lightbox.title")}
aria-describedby={undefined}
onOpenAutoFocus={() => { opener.current = document.activeElement instanceof HTMLElement ? document.activeElement : null; }}
+4 -3
View File
@@ -1,5 +1,5 @@
import { surfaceFocusProps } from "@/lib/surface-focus";
import { useEffect, useId, useRef, type PointerEvent, type ReactNode } from "react";
import { useEffect, useId, useRef, type PointerEvent, type ReactNode, type Ref } from "react";
import { SidebarPanel } from "@/components/ui/sidebar-panel";
import { PanelRightClose, X } from "lucide-react";
import { useTranslation } from "react-i18next";
@@ -11,7 +11,7 @@ import { cn } from "@/lib/utils";
import { sidePanelSurfaceClassName } from "@/components/ui/floating-surface";
/** One stable sidebar shell: switching targets never replays its opening animation. */
export function PreviewPane({ tabs, activeId, width, isClosing, onSelect, onCloseTab, onClose, onResizeStart, children }: {
export function PreviewPane({ tabs, activeId, width, isClosing, onSelect, onCloseTab, onClose, panelRef, onResizeStart, children }: {
tabs: PreviewTab[];
activeId: string;
width: number;
@@ -19,6 +19,7 @@ export function PreviewPane({ tabs, activeId, width, isClosing, onSelect, onClos
onSelect: (id: string) => void;
onCloseTab: (id: string) => void;
onClose: () => void;
panelRef?: Ref<HTMLElement>;
onResizeStart: (event: PointerEvent<HTMLButtonElement>) => void;
children: ReactNode;
}) {
@@ -46,7 +47,7 @@ export function PreviewPane({ tabs, activeId, width, isClosing, onSelect, onClos
onCloseTab(tab.id);
};
const iconButton = "touch-target inline-flex size-8 shrink-0 items-center justify-center rounded-control text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring";
return <SidebarPanel aria-label={t("previewTabs.title")} data-testid="preview-pane" data-file-preview-panel
return <SidebarPanel ref={panelRef} aria-label={t("previewTabs.title")} data-testid="preview-pane" data-file-preview-panel
width={width} isClosing={isClosing} contentClassName={sidePanelSurfaceClassName}
header={<>
<div ref={tabList} role="tablist" aria-label={t("previewTabs.title")} className="min-w-0 flex-1 overflow-x-auto [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
+3 -2
View File
@@ -2,6 +2,7 @@ import { useEffect, useRef, useState } from "react";
import { StarLinkView, StarPromptView } from "@/components/StarPromptView";
import { starPromptAction } from "@/lib/api";
import { hasAnyDialogMounted } from "@/lib/dom-overlays";
import { useClient } from "@/providers/ClientProvider";
export function StarLink({ onSaved, fullWidth = false }: {
@@ -43,10 +44,10 @@ export function StarPrompt({ ready }: { ready: boolean }) {
if (status !== "open" || attempted.current) return;
attempted.current = true;
if (interacted.current || document.visibilityState !== "visible"
|| document.querySelector('[role="dialog"], [role="alertdialog"]')) return;
|| hasAnyDialogMounted()) return;
void starPromptAction(client, "claim").then(({ show }) => {
if (cancelled || !show || interacted.current || document.visibilityState !== "visible"
|| document.querySelector('[role="dialog"], [role="alertdialog"]')) return;
|| hasAnyDialogMounted()) return;
previousFocus.current = document.activeElement instanceof HTMLElement
? document.activeElement : null;
setOpen(true);
@@ -6,6 +6,7 @@ import { channelUiPresentation } from "@/channel-plugins/registry";
import { Button } from "@/components/ui/button";
import { floatingSurfaceElevationClassName } from "@/components/ui/floating-surface";
import { useLogoFallback } from "@/hooks/useLogoFallback";
import { useOverlaySurfaceRef } from "@/lib/dom-overlays";
import type { PairingRequestInfo } from "@/lib/types";
import { cn } from "@/lib/utils";
@@ -27,6 +28,7 @@ export function PairingCodePopup({
const { t } = useTranslation();
const [value, setValue] = useState("");
const attemptedCode = useRef<string | null>(null);
const surfaceRef = useOverlaySurfaceRef<HTMLDivElement>("dialog");
const normalizedCode = normalizePairingCode(value);
const matchedRequest = useMemo(
() => requests.find((request) => request.code === normalizedCode) ?? null,
@@ -74,6 +76,7 @@ export function PairingCodePopup({
return (
<div
ref={surfaceRef}
role="dialog"
aria-live="polite"
aria-label={t("app.pairing.title", { defaultValue: "Pair a chat user" })}
@@ -12,6 +12,7 @@ import { useToast } from "@/components/ui/toast";
import { useClient } from "@/providers/ClientProvider";
import { groupRemoteProfiles, isCompatibilityError, remoteAction, type RemoteInspection, type RemoteProfile } from "@/lib/remote-instances";
import { cn } from "@/lib/utils";
import { hasOpenDialogSurface } from "@/lib/dom-overlays";
import { parseSSHAddress } from "@/lib/ssh-address";
import { clearPairReturn, readPairReturn, subscribePairReturn } from "@/lib/remote-pair-return";
import { useRemoteConnections } from "./remote-context";
@@ -197,7 +198,7 @@ export function RemoteConnectionsPage({ mainNavigationExpanded = false, hostChro
if (reason instanceof Error && reason.message === "same_instance" && showToast
&& !editorOpen && !fingerprint && !detailsOpen && page.current
&& !page.current.closest("[hidden], [inert], [aria-hidden='true']")
&& !document.querySelector(":is([role='dialog'], [role='alertdialog']):not([data-state='closed'])")) {
&& !hasOpenDialogSurface()) {
showToast({ message: t("remote.errors.same_instance"), tone: "error", dedupeKey: "remote-same-instance" });
return;
}
@@ -1,4 +1,4 @@
import { useEffect, useId, useRef, useState, type KeyboardEvent, type ReactNode } from "react";
import { useEffect, useId, useRef, useState, type KeyboardEvent, type ReactNode, type Ref } from "react";
import { createPortal } from "react-dom";
import { useTranslation } from "react-i18next";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
@@ -30,6 +30,7 @@ export function ComposerUsagePopover({
showLabel = false,
compactLabel = false,
sidebarHost,
sidebarRef,
sessionKey,
children,
open: controlledOpen,
@@ -42,6 +43,7 @@ export function ComposerUsagePopover({
showLabel?: boolean;
compactLabel?: boolean;
sidebarHost?: HTMLElement | null;
sidebarRef?: Ref<HTMLElement>;
sessionKey?: string | null;
children?: (renderControl: ComposerUsageControl | undefined) => ReactNode;
open?: boolean;
@@ -196,7 +198,7 @@ export function ComposerUsagePopover({
<DialogTitle className="sr-only">{t("thread.composer.context.panelTitle")}</DialogTitle>
{inspector}
</DialogContent>
</Dialog> : createPortal(<SidebarPanel open={open} width={420} floating={!sidebarHost} id={panelId}
</Dialog> : createPortal(<SidebarPanel ref={sidebarRef} open={open} width={420} floating={!sidebarHost} id={panelId}
aria-label={t("thread.composer.context.panelTitle")} data-testid="context-sidebar" onKeyDown={onPanelKeyDown}>
{inspector}
</SidebarPanel>, sidebarHost ?? document.body))}
@@ -14,6 +14,7 @@ import {
import { fmtDateTime } from "@/lib/format-time";
import type { UIMessage } from "@/lib/types";
import { cn } from "@/lib/utils";
import { hasOpenDialogSurface } from "@/lib/dom-overlays";
interface PromptNavigatorProps {
messages: UIMessage[];
@@ -45,7 +46,7 @@ export function PromptNavigator({
const keyDown = (event: KeyboardEvent) => {
if (!shortcutEnabled || !prompts.length || event.defaultPrevented || event.repeat || event.isComposing
|| event.altKey || event.shiftKey || !(event.ctrlKey || event.metaKey) || event.key.toLowerCase() !== "f") return;
if (!open && (triggerRef.current?.closest("[hidden], [aria-hidden=true]") || document.querySelector("[role=dialog][data-state=open]"))) return;
if (!open && (triggerRef.current?.closest("[hidden], [aria-hidden=true]") || hasOpenDialogSurface())) return;
event.preventDefault();
setListTop(0); setOpen(true);
inputRef.current?.focus(); inputRef.current?.select();
+25 -118
View File
@@ -110,7 +110,7 @@ import { useComposerMentionInput } from "@/hooks/useComposerMentionInput";
import { useLogoFallback } from "@/hooks/useLogoFallback";
import { useMediaQuery } from "@/hooks/useMediaQuery";
import type { SendAttachment, SendOptions } from "@/hooks/useNanobotStream";
import { useVoiceRecorder, type VoiceRecorderErrorKey } from "@/hooks/useVoiceRecorder";
import { useComposerVoiceInput } from "@/hooks/useComposerVoiceInput";
import type {
CliAppInfo,
ChatSummary,
@@ -144,6 +144,7 @@ import {
readDraggedSession,
} from "@/lib/session-drag";
import { formatQuotedUserMessage } from "@/lib/user-message-quote";
import { useOverlaySurfaceRef } from "@/lib/dom-overlays";
import { cn } from "@/lib/utils";
import type { ComposerDraft, ComposerDraftStore } from "@/lib/composer-draft";
import { useLocalPreferences } from "@/hooks/useLocalPreferences";
@@ -155,10 +156,6 @@ import {
type QueuedPromptContent,
} from "@/components/thread/useQueuedPrompt";
const VOICE_SHORTCUT_CODE = "KeyD";
const VOICE_SHORTCUT_ARIA = "Control+Shift+D";
type VoiceShortcutPlatform = "apple" | "chromeos" | "linux" | "other" | "windows";
function formatBytes(n: number): string {
if (n < 1024) return `${n} B`;
if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KiB`;
@@ -169,54 +166,6 @@ function utf8Bytes(value: string): number {
return new TextEncoder().encode(value).byteLength;
}
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";
}
}
interface ThreadComposerProps {
onSend: (
content: string,
@@ -631,7 +580,6 @@ export function ThreadComposer({
end: number;
} | null>(null);
const [inlineError, setInlineError] = useState<string | null>(null);
const [voiceSetupError, setVoiceSetupError] = useState<VoiceRecorderErrorKey | null>(null);
const showToast = useToast();
const [sendPending, setSendPending] = useState(false);
const [pathInspection, setPathInspection] = useState<{
@@ -797,9 +745,7 @@ export function ThreadComposer({
const fileInputRef = useRef<HTMLInputElement>(null);
const chipRefs = useRef(new Map<string, HTMLButtonElement>());
const previousPendingQueueKeyRef = useRef(pendingQueueKey);
const voiceShortcutDownRef = useRef(false);
const isHero = variant === "hero";
const voiceShortcutLabel = useMemo(getVoiceShortcutLabel, []);
const projectPickerAvailable =
!workspaceProjectLocked
&& !!workspaceDefaultScope
@@ -1428,19 +1374,6 @@ export function ThreadComposer({
measureDraft();
}, [readingTextSize, customReadingTextSize, measureDraft]);
// Runs before paint so switching sessions never flashes stale draft text.
useLayoutEffect(() => {
if (previousPendingQueueKeyRef.current === pendingQueueKey) return;
previousPendingQueueKeyRef.current = pendingQueueKey;
setValue("");
setInlineError(null);
setVoiceSetupError(null);
setSlashMenuDismissed(false);
setCliAppMenuDismissed(false);
setCursorPosition(0);
clear();
}, [clear, pendingQueueKey]);
const appendTranscription = useCallback((text: string) => {
const transcript = text.trim();
if (!transcript) return;
@@ -1454,56 +1387,26 @@ export function ThreadComposer({
focusTextarea();
}, [focusTextarea]);
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: interactionDisabled,
onClearError: clearVoiceSetupError,
onError: setVoiceError,
onTranscript: appendTranscription,
onTranscribeAudio,
const {
recorder: voiceRecorder, setupError: voiceSetupError, clearSetupError,
shortcutLabel: voiceShortcutLabel, shortcutAria, canSendQueuedPrompt,
} = useComposerVoiceInput({
disabled: interactionDisabled, onTranscribeAudio, onTranscript: appendTranscription,
wantsWav: transcriptionProvider === "xiaomi_mimo",
});
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]);
// Runs before paint so switching sessions never flashes stale draft text.
useLayoutEffect(() => {
if (previousPendingQueueKeyRef.current === pendingQueueKey) return;
previousPendingQueueKeyRef.current = pendingQueueKey;
setValue("");
setInlineError(null);
clearSetupError();
setSlashMenuDismissed(false);
setCliAppMenuDismissed(false);
setCursorPosition(0);
clear();
}, [clear, clearSetupError, pendingQueueKey]);
const handleStop = useCallback(() => {
pauseQueue();
@@ -1890,7 +1793,7 @@ export function ThreadComposer({
&& !e.ctrlKey
&& !e.metaKey
) {
if (!e.repeat && voiceRecorder.state === "idle" && !voiceShortcutDownRef.current) {
if (!e.repeat && canSendQueuedPrompt()) {
sendQueuedPrompt(queuedPrompt);
}
return;
@@ -2371,7 +2274,7 @@ export function ThreadComposer({
? t("thread.composer.configureModel", { defaultValue: "Configure model" })
: isUserShell ? t("thread.composer.shell.run") : t("thread.composer.send")
}
aria-keyshortcuts={showVoiceButton ? VOICE_SHORTCUT_ARIA : undefined}
aria-keyshortcuts={showVoiceButton ? shortcutAria : undefined}
onPointerDown={showVoiceButton ? voiceRecorder.beginPress : undefined}
onPointerUp={showVoiceButton ? voiceRecorder.endPress : undefined}
onPointerCancel={showVoiceButton ? voiceRecorder.endPress : undefined}
@@ -2653,6 +2556,7 @@ function CliAppMentionPalette({
layout.maxHeight - SLASH_PALETTE_CHROME_PX,
);
const listRef = useSelectedOptionScroll(selectedIndex);
const surfaceRef = useOverlaySurfaceRef<HTMLDivElement>("overlay");
const groupedCandidates = (["session", "cli", "mcp"] as const)
.map((kind) => ({
kind,
@@ -2668,6 +2572,7 @@ function CliAppMentionPalette({
.filter((group) => group.items.length > 0);
return (
<div
ref={surfaceRef}
role="listbox"
aria-label={t("thread.composer.mentions.ariaLabel")}
style={{ maxHeight: layout.maxHeight }}
@@ -2817,8 +2722,10 @@ function SlashCommandPalette({
layout.maxHeight - SLASH_PALETTE_CHROME_PX,
);
const listRef = useSelectedOptionScroll(selectedIndex);
const surfaceRef = useOverlaySurfaceRef<HTMLDivElement>("overlay");
return (
<div
ref={surfaceRef}
role="listbox"
aria-label={t("thread.composer.slash.ariaLabel")}
style={{ maxHeight: layout.maxHeight }}
+25 -20
View File
@@ -8,6 +8,7 @@ import {
completedActivityDurationMs,
formatActivityDuration,
} from "@/components/thread/AgentActivityCluster";
import { sameHistoryRowIdentity, type HistoryRowIdentity, type HistoryRowSource } from "@/components/thread/history-row-identity";
import { AssistantSelectionAction } from "@/components/thread/AssistantSelectionAction";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Dialog, DialogContent, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
@@ -22,6 +23,7 @@ import { cn } from "@/lib/utils";
import type { CliAppInfo, McpPresetInfo, RetryStatus, SlashCommand, UIMessage } from "@/lib/types";
interface ThreadMessagesProps {
historyRows?: WeakMap<HTMLElement, HistoryRowIdentity>;
messages: UIMessage[];
beforeMessages?: ReactNode;
beforeUnit?: { key: string; content: ReactNode };
@@ -82,6 +84,7 @@ export function assistantForkFlags(units: DisplayUnit[]): boolean[] {
}
export function ThreadMessages({
historyRows,
messages,
beforeMessages,
beforeUnit,
@@ -257,6 +260,7 @@ export function ThreadMessages({
key={unitKeys[index]}
unitKey={unitKeys[index]}
scrollAnchor={scrollAnchors[index]}
historyRows={historyRows}
unit={unit}
mobileActions={mobileActions}
marginTop={prelude ? "" : marginTop}
@@ -370,7 +374,8 @@ function pendingTurnProjection(
interface ThreadDisplayUnitProps {
mobileActions: boolean;
unitKey: string;
scrollAnchor: ScrollAnchorIdentity;
scrollAnchor: HistoryRowIdentity;
historyRows?: WeakMap<HTMLElement, HistoryRowIdentity>;
unit: DisplayUnit;
marginTop: string;
userPromptId?: string;
@@ -574,6 +579,7 @@ const ThreadDisplayUnit = memo(function ThreadDisplayUnit({
mobileActions,
unitKey,
scrollAnchor,
historyRows,
unit,
marginTop,
userPromptId,
@@ -607,6 +613,12 @@ const ThreadDisplayUnit = memo(function ThreadDisplayUnit({
}: ThreadDisplayUnitProps) {
const { t } = useTranslation();
const elementRef = useRef<HTMLDivElement>(null);
useLayoutEffect(() => {
const element = elementRef.current;
if (!element || !historyRows) return;
historyRows.set(element, scrollAnchor);
return () => { historyRows.delete(element); };
}, [historyRows, scrollAnchor]);
const activityDetailsId = useId();
const heightRef = useRef(0);
const [nearViewport, setNearViewport] = useState(true);
@@ -699,8 +711,6 @@ const ThreadDisplayUnit = memo(function ThreadDisplayUnit({
onContextBlockActiveChange(contextBlockKey ?? null);
}}
data-thread-display-unit={unitKey}
data-thread-scroll-sources={scrollAnchor.sources}
data-thread-scroll-fallback={scrollAnchor.fallback}
data-user-prompt-id={userPromptId}
data-message-context-block={contextBlockKey}
data-context-block-active={contextBlockActive || undefined}
@@ -793,8 +803,8 @@ function threadDisplayUnitPropsEqual(
): boolean {
return (
displayUnitsEqual(previous.unit, next.unit)
&& previous.scrollAnchor.sources === next.scrollAnchor.sources
&& previous.scrollAnchor.fallback === next.scrollAnchor.fallback
&& previous.historyRows === next.historyRows
&& sameHistoryRowIdentity(previous.scrollAnchor, next.scrollAnchor)
&& previous.mobileActions === next.mobileActions
&& previous.marginTop === next.marginTop
&& previous.userPromptId === next.userPromptId
@@ -956,39 +966,34 @@ export function unitKeysForDisplay(units: DisplayUnit[]): string[] {
});
}
interface ScrollAnchorIdentity {
sources: string;
fallback?: string;
}
function scrollAnchorsForUnits(units: DisplayUnit[]): ScrollAnchorIdentity[] {
function scrollAnchorsForUnits(units: DisplayUnit[]): HistoryRowIdentity[] {
const sourceKeys = units.map((unit) => {
const messages = unit.type === "message" ? [unit.message] : unit.messages;
// Either edge of an activity cluster can survive when the other grows.
const edges = messages.length > 1 ? [messages[0], messages[messages.length - 1]] : messages;
const streams: string[] = [];
const sequences: string[] = [];
const ids: string[] = [];
const streams: HistoryRowSource[] = [];
const sequences: HistoryRowSource[] = [];
const ids: HistoryRowSource[] = [];
for (const message of edges) {
const stream = unit.type === "message" ? message.streamId : message.reasoningStreamId;
if (message.turnId && stream) streams.push(JSON.stringify([unit.type, "stream", message.turnId, stream]));
if (message.turnId && stream) streams.push({ kind: "stream", key: JSON.stringify([unit.type, "stream", message.turnId, stream]) });
const sequence = message.projectionStartSeq ?? message.turnSeq;
if (message.turnId && Number.isFinite(sequence)) {
sequences.push(JSON.stringify([unit.type, "sequence", message.turnId, sequence]));
sequences.push({ kind: "sequence", key: JSON.stringify([unit.type, "sequence", message.turnId, sequence]) });
}
ids.push(JSON.stringify([unit.type, "id", message.id]));
ids.push({ kind: "id", key: JSON.stringify([unit.type, "id", message.id]) });
}
return [...new Set([...streams, ...sequences, ...ids])];
return Array.from(new Map([...streams, ...sequences, ...ids].map((source) => [source.key, source])).values());
});
const sourceCounts = new Map<string, number>();
const bases = units.map(unitKeyBase);
const baseCounts = new Map<string, number>();
for (const sources of sourceKeys) for (const source of sources) {
sourceCounts.set(source, (sourceCounts.get(source) ?? 0) + 1);
sourceCounts.set(source.key, (sourceCounts.get(source.key) ?? 0) + 1);
}
for (const base of bases) baseCounts.set(base, (baseCounts.get(base) ?? 0) + 1);
return sourceKeys.map((sources, index) => ({
sources: JSON.stringify(sources.filter((source) => sourceCounts.get(source) === 1)),
sources: sources.filter((source) => sourceCounts.get(source.key) === 1),
// A sole turn/phase row can keep its live identity when replay replaces
// both its source id and sequence. Occurrence keys are unsafe otherwise.
...(bases[index].startsWith("turn-") && baseCounts.get(bases[index]) === 1
+21 -117
View File
@@ -1,5 +1,5 @@
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import type { CSSProperties, PointerEvent as ReactPointerEvent, ReactNode } from "react";
import type { CSSProperties, ReactNode } from "react";
import { createPortal } from "react-dom";
import { useTranslation } from "react-i18next";
import { composerUsageSnapshots, type ComposerUsageSnapshot } from "@/lib/model-request";
@@ -87,6 +87,8 @@ import { projectWebuiThreadMessages } from "@/lib/thread-display-projection";
import { ThreadMessageCache } from "@/lib/thread-message-cache";
import { providerDisplayLabel } from "@/lib/provider-brand";
import { cn } from "@/lib/utils";
import { useFilePreviewResize } from "@/hooks/useFilePreviewResize";
import { hasAnyOverlayMounted } from "@/lib/dom-overlays";
import { composerContextSnapshots } from "@/lib/context-graph";
import { useClient } from "@/providers/ClientProvider";
@@ -187,10 +189,6 @@ function hasInlineDeliveryError(
));
}
const FILE_PREVIEW_DEFAULT_WIDTH = 544;
const FILE_PREVIEW_MIN_WIDTH = 360;
const FILE_PREVIEW_MAX_WIDTH = 860;
const FILE_PREVIEW_MIN_MAIN_WIDTH = 420;
const FILE_PREVIEW_CLOSE_ANIMATION_MS = 320;
type FilePreviewAvailabilityCacheEntry = {
@@ -199,20 +197,6 @@ type FilePreviewAvailabilityCacheEntry = {
revision: number;
};
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),
),
);
}
const EMPTY_TITLE_OVERRIDES: Record<string, string> = {};
interface ThreadShellProps {
@@ -498,6 +482,7 @@ export function ThreadShell({
}, [multiplePanes, previewSessionKey]);
const [sidebarEnterWidth, setSidebarEnterWidth] = useState(0);
const [contextSidebarHost, setContextSidebarHost] = useState<HTMLElement | null>(null);
const contextSidebarRef = useRef<HTMLElement>(null);
const setSidebarHost = useCallback((node: HTMLElement | null) => { shellRef.current = node; setContextSidebarHost(node); }, []);
const [closingPreview, setClosingPreview] = useState<{ key: string; state: FilePreviewState } | null>(null);
const filePreviewClosing = closingPreview?.key === previewSessionKey;
@@ -525,8 +510,6 @@ export function ThreadShell({
if (range && selection) { selection.removeAllRanges(); selection.addRange(range); }
}, [composerDestination, composerMount, inlineComposer]);
useLayoutEffect(() => () => composerMount.remove(), [composerMount]);
const [filePreviewMaxWidth, setFilePreviewMaxWidth] = useState(FILE_PREVIEW_MAX_WIDTH);
const filePreviewWidth = clampFilePreviewWidth(previewState.width, filePreviewMaxWidth);
const draftKey = session?.key ?? (temporaryChatEnabled ? "new:temporary" : "new:chat");
const persistDraft = session ? !temporary : !temporaryChatEnabled;
const [quote, setQuote] = useState<{ key: string; text: string | null } | null>(null);
@@ -538,6 +521,9 @@ export function ThreadShell({
}, [draftKey]);
const [composerFocusSignal, setComposerFocusSignal] = useState(0);
const shellRef = useRef<HTMLElement | null>(null);
const { width: filePreviewWidth, panelRef: previewPanelRef, startResize: handleFilePreviewResizeStart, cancelResize: cancelPreviewResize } = useFilePreviewResize(
shellRef, previewOpen, previewState.width, setFilePreviewWidth,
);
const [conversationElement, setConversationElement] = useState<HTMLDivElement | null>(null);
const [composerSurface, setComposerSurface] = useState<HTMLDivElement | null>(null);
const alignSidebar = useCallback(() => {
@@ -556,9 +542,7 @@ export function ThreadShell({
observer.observe(composerSurface);
return () => observer.disconnect();
}, [alignSidebar, contextSidebarHost, sidebarOpen, inlineComposer, composerDestination, composerMount, composerSurface]);
const filePreviewWidthRef = useRef(FILE_PREVIEW_DEFAULT_WIDTH);
const filePreviewCloseTimerRef = useRef<number | null>(null);
const filePreviewResizeCleanupRef = useRef<(() => void) | null>(null);
const pendingFirstRef = useRef<(PendingFirstMessage & { draft?: ComposerDraft; draftKey: string }) | null>(null);
const [restoredFirstDraft, setRestoredFirstDraft] = useState<{ chatId: string; revision: number; error: string } | null>(null);
const [pendingFirstTargetChatId, setPendingFirstTargetChatId] = useState<string | null>(null);
@@ -647,18 +631,14 @@ export function ThreadShell({
}, [chatId, historyKey]);
useEffect(() => {
filePreviewWidthRef.current = filePreviewWidth;
}, [filePreviewWidth]);
useEffect(() => {
filePreviewResizeCleanupRef.current?.();
cancelPreviewResize();
if (filePreviewCloseTimerRef.current !== null) {
window.clearTimeout(filePreviewCloseTimerRef.current);
filePreviewCloseTimerRef.current = null;
}
setClosingPreview(null);
setSubmittedViewportTurn(null);
}, [previewSessionKey]);
}, [cancelPreviewResize, previewSessionKey]);
useEffect(() => {
const retained = new Set(temporaryChatIds);
@@ -680,7 +660,6 @@ export function ThreadShell({
useEffect(() => {
return () => {
filePreviewResizeCleanupRef.current?.();
if (filePreviewCloseTimerRef.current !== null) {
window.clearTimeout(filePreviewCloseTimerRef.current);
}
@@ -1133,7 +1112,7 @@ export function ThreadShell({
const handleCloseFilePreview = useCallback(() => {
if (!previewSessionKey || !previewState.activeId || filePreviewClosing) return;
filePreviewResizeCleanupRef.current?.();
cancelPreviewResize();
setClosingPreview({ key: previewSessionKey, state: previewState });
// Record the closed state immediately, even if navigation interrupts the animation.
closePreview();
@@ -1141,23 +1120,24 @@ export function ThreadShell({
filePreviewCloseTimerRef.current = null;
setClosingPreview(null);
}, FILE_PREVIEW_CLOSE_ANIMATION_MS);
}, [previewSessionKey, filePreviewClosing, previewState, closePreview]);
}, [cancelPreviewResize, previewSessionKey, filePreviewClosing, previewState, closePreview]);
const cancelPreviewClose = useCallback(() => {
filePreviewResizeCleanupRef.current?.();
cancelPreviewResize();
if (filePreviewCloseTimerRef.current !== null) {
window.clearTimeout(filePreviewCloseTimerRef.current);
filePreviewCloseTimerRef.current = null;
}
setClosingPreview(null);
}, []);
}, [cancelPreviewResize]);
const handleOpenFilePreview = useCallback((path: string) => {
setSidebarEnterWidth(shellRef.current?.querySelector(".file-preview-pane")?.getBoundingClientRect().width ?? 0);
const outgoingSidebar = previewPanelRef.current ?? contextSidebarRef.current;
setSidebarEnterWidth(outgoingSidebar?.getBoundingClientRect().width ?? 0);
setContextSidebarOpen(false);
cancelPreviewClose();
openFile(path);
}, [cancelPreviewClose, openFile]);
}, [cancelPreviewClose, openFile, previewPanelRef]);
const handleContextSidebarOpenChange = useCallback((open: boolean) => {
if (open) {
@@ -1170,10 +1150,10 @@ export function ThreadShell({
const handleClosePreviewTab = useCallback((id: string) => {
if (previewState.tabs.length === 1) handleCloseFilePreview();
else {
filePreviewResizeCleanupRef.current?.();
cancelPreviewResize();
closeTab(id);
}
}, [previewState.tabs.length, handleCloseFilePreview, closeTab]);
}, [cancelPreviewResize, previewState.tabs.length, handleCloseFilePreview, closeTab]);
// Markdown blocks can retain rendered links while their text is unchanged.
// Keep their callback stable, but always act on the current pane/session state.
@@ -1203,7 +1183,7 @@ export function ThreadShell({
const onKeyDown = (event: KeyboardEvent) => {
if (event.key !== "Escape" || event.defaultPrevented || event.isComposing) return;
// Let a dialog/menu above the pane consume Escape without closing this preview.
if (document.querySelector('[role="dialog"], [role="alertdialog"], [role="menu"], [role="listbox"], [data-radix-popper-content-wrapper]')) return;
if (hasAnyOverlayMounted()) return;
event.preventDefault();
handleCloseFilePreview();
};
@@ -1211,84 +1191,6 @@ export function ThreadShell({
return () => window.removeEventListener("keydown", onKeyDown);
}, [previewOpen, headerActive, handleCloseFilePreview]);
const handleFilePreviewResizeStart = useCallback((event: ReactPointerEvent<HTMLButtonElement>) => {
filePreviewResizeCleanupRef.current?.();
event.preventDefault();
event.stopPropagation();
const panel = event.currentTarget.closest<HTMLElement>("[data-file-preview-panel]");
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]);
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]);
const handleForkFromMessage = useCallback(
async (beforeUserIndex: number) => {
if (!chatId || !onForkChat) return;
@@ -1588,6 +1490,7 @@ export function ThreadShell({
rounds={composerRoundUsage}
snapshots={contextGraphSnapshots}
sidebarHost={contextSidebarHost}
sidebarRef={contextSidebarRef}
open={contextSidebarOpen}
onOpenChange={handleContextSidebarOpenChange}
onOpenFile={handleOpenFilePreview}
@@ -1615,6 +1518,7 @@ export function ThreadShell({
onSelect={selectTab}
onCloseTab={handleClosePreviewTab}
onClose={handleCloseFilePreview}
panelRef={previewPanelRef}
onResizeStart={handleFilePreviewResizeStart}
>
<FilePreviewPanel
+12 -44
View File
@@ -13,6 +13,7 @@ import { ArrowDown } from "lucide-react";
import { useTranslation } from "react-i18next";
import { PromptRail } from "@/components/thread/PromptRail";
import { matchHistoryRow, type HistoryRowIdentity } from "@/components/thread/history-row-identity";
import { SubagentThreadMessages } from "@/components/thread/SubagentTaskResults";
import { DiagramScope } from "@/components/markdown-diagrams/context";
import { DiffViewportContext } from "./activity/DiffViewportContext";
@@ -93,25 +94,13 @@ export const INITIAL_HISTORY_WINDOW = 120;
export const HISTORY_WINDOW_INCREMENT = 120;
interface HistoryScrollAnchor {
sources: string[];
fallback?: string;
identity: HistoryRowIdentity;
offsetTop: number;
scrollTop: number;
}
const THREAD_DISPLAY_UNIT_SELECTOR = "[data-thread-display-unit]";
function scrollSourceKind(source: string): string {
return (JSON.parse(source) as string[])[1];
}
function scrollSourcesDisagree(left: string[], right: string[], kind: string): boolean {
const leftKeys = left.filter((source) => scrollSourceKind(source) === kind);
const rightKeys = right.filter((source) => scrollSourceKind(source) === kind);
return leftKeys.length > 0 && rightKeys.length > 0
&& !leftKeys.some((source) => rightKeys.includes(source));
}
function promptTopInset(scroller: HTMLElement): number {
const padding = Number.parseFloat(getComputedStyle(scroller).scrollPaddingTop);
return Number.isFinite(padding) ? padding : PROMPT_TOP_INSET_PX;
@@ -333,6 +322,7 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
const contentRef = useRef<HTMLDivElement>(null);
const messageRegionRef = useRef<HTMLDivElement | null>(null);
const messageContentRef = useRef<HTMLDivElement>(null);
const [historyRows] = useState(() => new WeakMap<HTMLElement, HistoryRowIdentity>());
const diffViewport = useMemo(() => ({ scroller: messageRegionRef, content: messageContentRef }), []);
const emptyStateRef = useRef<HTMLDivElement>(null);
const composerDockRef = useRef<HTMLDivElement>(null);
@@ -558,26 +548,20 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
}
const viewport = scroller.getBoundingClientRect();
const element = visibleHistoryUnit(content, viewport);
if (!element?.dataset.threadScrollSources) {
historyScrollAnchorRef.current = null;
return false;
}
const sources = JSON.parse(element.dataset.threadScrollSources) as string[];
const fallback = element.dataset.threadScrollFallback;
if (sources.length === 0 && !fallback) {
const identity = element ? historyRows.get(element) : undefined;
if (!element || !identity || (identity.sources.length === 0 && !identity.fallback)) {
historyScrollAnchorRef.current = null;
return false;
}
historyScrollAnchorRef.current = {
sources,
fallback,
identity,
scrollTop: scroller.scrollTop,
// Normalize out the reveal lease, even when reading above its inline slot.
offsetTop: element.getBoundingClientRect().top - viewport.top
- (historySlotRef.current ? HISTORY_HOLD_PX : 0),
};
return true;
}, []);
}, [historyRows]);
const reconcileHistoryScrollAnchor = useCallback(() => {
const scroller = scrollRef.current;
@@ -588,26 +572,9 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
if (Math.abs(scroller.scrollTop - Math.min(anchor.scrollTop, maxScrollTop)) >= 0.5) {
return captureHistoryScrollAnchor();
}
const candidates = Array.from(content.querySelectorAll<HTMLElement>(THREAD_DISPLAY_UNIT_SELECTOR));
const bySource = new Map<string, { element: HTMLElement; sources: string[] }>();
for (const candidate of candidates) {
const sources = JSON.parse(candidate.dataset.threadScrollSources ?? "[]") as string[];
for (const source of sources) bySource.set(source, { element: candidate, sources });
}
let element: HTMLElement | undefined;
for (const source of anchor.sources) {
const candidate = bySource.get(source);
if (!candidate) continue;
const kind = scrollSourceKind(source);
// An index-generated replay id can be reused by a different message.
if (kind !== "stream" && scrollSourcesDisagree(anchor.sources, candidate.sources, "stream")) continue;
if (kind === "id" && scrollSourcesDisagree(anchor.sources, candidate.sources, "sequence")) continue;
element = candidate.element;
break;
}
if (!element && anchor.fallback) {
element = candidates.find((candidate) => candidate.dataset.threadScrollFallback === anchor.fallback);
}
const element = matchHistoryRow(
anchor.identity, content.querySelectorAll<HTMLElement>(THREAD_DISPLAY_UNIT_SELECTOR), historyRows,
);
if (!element) {
historyScrollAnchorRef.current = null;
return false;
@@ -626,7 +593,7 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
// A clamped layout is the new reading position, not space owed by a later prepend.
anchor.offsetTop += requestedTop - nextTop;
return true;
}, [captureHistoryScrollAnchor]);
}, [captureHistoryScrollAnchor, historyRows]);
const resetHistoryHeader = useCallback(() => {
setHistorySlotKey(null);
@@ -1342,6 +1309,7 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro
<DiffViewportContext.Provider value={diffViewport}>
<DiagramScope identity={conversationKey}>
<SubagentThreadMessages
historyRows={historyRows}
key={messagesKey}
messages={visibleMessages}
topInset={PROMPT_TOP_INSET_PX}
@@ -206,7 +206,7 @@ function FileUnifiedDiff({
const renderBody = () => (
<div
className="mt-1 overflow-hidden rounded-md border border-border/55 bg-background/80 shadow-[0_1px_0_rgba(15,23,42,0.03)]"
className="file-edit-diff-surface mt-1 overflow-hidden rounded-md border border-border/55 bg-background/80 shadow-[0_1px_0_rgba(15,23,42,0.03)]"
data-testid="file-edit-diff"
>
<DiffSyntaxHighlight language={language} text={diff.text!} diff={renderableDiff} lineLimit={lineLimit} />
@@ -0,0 +1,45 @@
type HistorySourceKind = "stream" | "sequence" | "id";
export interface HistoryRowSource {
kind: HistorySourceKind;
key: string;
}
export interface HistoryRowIdentity {
sources: HistoryRowSource[];
fallback?: string;
}
export function sameHistoryRowIdentity(left: HistoryRowIdentity, right: HistoryRowIdentity): boolean {
return left.fallback === right.fallback && left.sources.length === right.sources.length
&& left.sources.every((source, index) => source.key === right.sources[index].key);
}
function sourcesDisagree(left: HistoryRowIdentity, right: HistoryRowIdentity, kind: HistorySourceKind): boolean {
const leftKeys = left.sources.filter((source) => source.kind === kind);
const rightKeys = right.sources.filter((source) => source.kind === kind);
return leftKeys.length > 0 && rightKeys.length > 0
&& !leftKeys.some((source) => rightKeys.some((other) => source.key === other.key));
}
export function matchHistoryRow(
anchor: HistoryRowIdentity, candidates: Iterable<HTMLElement>, rows: WeakMap<HTMLElement, HistoryRowIdentity>,
): HTMLElement | undefined {
const bySource = new Map<string, { element: HTMLElement; identity: HistoryRowIdentity }>();
let fallback: HTMLElement | undefined;
for (const element of candidates) {
const identity = rows.get(element);
if (!identity) continue;
for (const source of identity.sources) bySource.set(source.key, { element, identity });
if (!fallback && anchor.fallback && anchor.fallback === identity.fallback) fallback = element;
}
for (const source of anchor.sources) {
const candidate = bySource.get(source.key);
if (!candidate) continue;
// A replay-generated row id may be reused for a different message.
if (source.kind !== "stream" && sourcesDisagree(anchor, candidate.identity, "stream")) continue;
if (source.kind === "id" && sourcesDisagree(anchor, candidate.identity, "sequence")) continue;
return candidate.element;
}
return fallback;
}
+20 -16
View File
@@ -6,6 +6,7 @@ import {
modalOverlayClassName,
modalSurfaceClassName,
} from "@/components/ui/floating-surface";
import { useOverlaySurfaceRef } from "@/lib/dom-overlays";
import { cn } from "@/lib/utils";
const AlertDialog = AlertDialogPrimitive.Root;
@@ -29,22 +30,25 @@ AlertDialogOverlay.displayName = AlertDialogPrimitive.Overlay.displayName;
const AlertDialogContent = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Content>
>(({ className, ...props }, ref) => (
<AlertDialogPortal>
<AlertDialogOverlay />
<div className="fixed inset-0 z-50 flex items-center justify-center p-4">
<AlertDialogPrimitive.Content
ref={ref}
className={cn(
modalSurfaceClassName,
"grid w-full max-w-lg origin-center gap-4 rounded-modal p-6 duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95",
className,
)}
{...props}
/>
</div>
</AlertDialogPortal>
));
>(({ className, ...props }, ref) => {
const surfaceRef = useOverlaySurfaceRef("dialog", ref);
return (
<AlertDialogPortal>
<AlertDialogOverlay />
<div className="fixed inset-0 z-50 flex items-center justify-center p-4">
<AlertDialogPrimitive.Content
ref={surfaceRef}
className={cn(
modalSurfaceClassName,
"grid w-full max-w-lg origin-center gap-4 rounded-modal p-6 duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95",
className,
)}
{...props}
/>
</div>
</AlertDialogPortal>
);
});
AlertDialogContent.displayName = AlertDialogPrimitive.Content.displayName;
const AlertDialogHeader = ({
+3 -1
View File
@@ -7,6 +7,7 @@ import {
modalOverlayClassName,
modalSurfaceClassName,
} from "@/components/ui/floating-surface";
import { useOverlaySurfaceRef } from "@/lib/dom-overlays";
import { cn } from "@/lib/utils";
import { FloatingPortalContext } from "@/components/ui/floating-portal";
@@ -47,6 +48,7 @@ const DialogPositionedContent = React.forwardRef<
overlayClassName?: string;
}
>(({ contained, positionerStyle, placement, overlayClassName, ...props }, ref) => {
const surfaceRef = useOverlaySurfaceRef("dialog", ref);
const Overlay = contained ? "div" : DialogOverlay;
return <Overlay data-dialog-backdrop {...(contained ? {} : { forceMount: true })} className={cn(contained && "absolute inset-0 z-50", overlayClassName)}>
<div className={cn("fixed inset-0 z-50 flex items-start justify-center overscroll-contain", placement === "bottom" ? "overflow-clip" : "overflow-y-auto p-4", contained && "absolute")} style={{
@@ -55,7 +57,7 @@ const DialogPositionedContent = React.forwardRef<
bottom: "auto",
...(contained ? { top: 0, height: "100%" } : positionerStyle),
}}>
<DialogPrimitive.Content ref={ref} {...props} />
<DialogPrimitive.Content ref={surfaceRef} {...props} />
</div>
</Overlay>;
});
+19 -14
View File
@@ -8,6 +8,7 @@ import {
floatingSurfaceClassName,
floatingSurfaceMotionClassName,
} from "@/components/ui/floating-surface";
import { useOverlaySurfaceRef } from "@/lib/dom-overlays";
import { cn } from "@/lib/utils";
import { useFloatingPortal } from "@/components/ui/floating-portal";
@@ -29,10 +30,11 @@ const DropdownMenuContent = React.forwardRef<
DropdownMenuContentProps
>(({ className, sideOffset = 4, portalContainer, ...props }, ref) => {
const dialogContainer = useFloatingPortal();
const surfaceRef = useOverlaySurfaceRef("overlay", ref);
return (
<DropdownMenuPrimitive.Portal container={portalContainer ?? dialogContainer ?? undefined}>
<DropdownMenuPrimitive.Content
ref={ref}
ref={surfaceRef}
sideOffset={sideOffset}
className={cn(
floatingSurfaceClassName,
@@ -140,19 +142,22 @@ DropdownMenuSubTrigger.displayName = DropdownMenuPrimitive.SubTrigger.displayNam
const DropdownMenuSubContent = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.SubContent>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.SubContent>
>(({ className, sideOffset = 6, ...props }, ref) => (
<DropdownMenuPrimitive.SubContent
ref={ref}
sideOffset={sideOffset}
className={cn(
floatingSurfaceClassName,
floatingSurfaceMotionClassName,
"origin-[var(--radix-dropdown-menu-content-transform-origin)] max-h-[min(var(--radix-dropdown-menu-content-available-height),22rem)] min-w-[11rem] overflow-y-auto",
className,
)}
{...props}
/>
));
>(({ className, sideOffset = 6, ...props }, ref) => {
const surfaceRef = useOverlaySurfaceRef("overlay", ref);
return (
<DropdownMenuPrimitive.SubContent
ref={surfaceRef}
sideOffset={sideOffset}
className={cn(
floatingSurfaceClassName,
floatingSurfaceMotionClassName,
"origin-[var(--radix-dropdown-menu-content-transform-origin)] max-h-[min(var(--radix-dropdown-menu-content-available-height),22rem)] min-w-[11rem] overflow-y-auto",
className,
)}
{...props}
/>
);
});
DropdownMenuSubContent.displayName = DropdownMenuPrimitive.SubContent.displayName;
export {
+4 -1
View File
@@ -5,6 +5,7 @@ import {
floatingSurfaceClassName,
floatingSurfaceMotionClassName,
} from "@/components/ui/floating-surface";
import { useOverlaySurfaceRef } from "@/lib/dom-overlays";
import { cn } from "@/lib/utils";
import { useFloatingPortal } from "@/components/ui/floating-portal";
@@ -23,10 +24,12 @@ const PopoverContent = React.forwardRef<
PopoverContentProps
>(({ className, sideOffset = 4, portalContainer, motionClassName = floatingSurfaceMotionClassName, ...props }, ref) => {
const dialogContainer = useFloatingPortal();
// Radix renders Popover.Content as role="dialog".
const surfaceRef = useOverlaySurfaceRef("dialog", ref);
return (
<PopoverPrimitive.Portal container={portalContainer ?? dialogContainer ?? undefined}>
<PopoverPrimitive.Content
ref={ref}
ref={surfaceRef}
sideOffset={sideOffset}
className={cn(
floatingSurfaceClassName,
+3 -1
View File
@@ -4,6 +4,7 @@ import { Check, ChevronDown, ChevronUp } from "lucide-react";
import { floatingSurfaceElevationClassName, floatingItemClassName } from "@/components/ui/floating-surface";
import { useFloatingPortal } from "@/components/ui/floating-portal";
import { useOverlaySurfaceRef } from "@/lib/dom-overlays";
import { cn } from "@/lib/utils";
import { ControlChevron } from "@/components/ui/control-chevron";
@@ -28,9 +29,10 @@ export function SelectContent({ children, ...props }: Pick<
"children" | "onPointerUpCapture" | "onPointerDownOutside" | "onKeyDownCapture" | "onEscapeKeyDown" | "onCloseAutoFocus"
>) {
const container = useFloatingPortal();
const surfaceRef = useOverlaySurfaceRef<HTMLDivElement>("overlay");
return (
<SelectPrimitive.Portal container={container ?? undefined}>
<SelectPrimitive.Content {...props} position="item-aligned" className={cn("z-50 max-h-[min(24rem,calc(100dvh-2rem))] min-w-[10rem] overflow-hidden rounded-control border border-transparent", floatingSurfaceElevationClassName)}>
<SelectPrimitive.Content ref={surfaceRef} {...props} position="item-aligned" className={cn("z-50 max-h-[min(24rem,calc(100dvh-2rem))] min-w-[10rem] overflow-hidden rounded-control border border-transparent", floatingSurfaceElevationClassName)}>
<SelectPrimitive.ScrollUpButton className="flex h-6 items-center justify-center"><ChevronUp className="h-3.5 w-3.5" /></SelectPrimitive.ScrollUpButton>
<SelectPrimitive.Viewport className="p-1">
{children}
+3 -1
View File
@@ -4,6 +4,7 @@ import { X } from "lucide-react";
import { cva, type VariantProps } from "class-variance-authority";
import { useTranslation } from "react-i18next";
import { useOverlaySurfaceRef } from "@/lib/dom-overlays";
import { cn } from "@/lib/utils";
import { modalOverlayClassName, sidePanelSurfaceClassName } from "./floating-surface";
@@ -84,11 +85,12 @@ const SheetContent = React.forwardRef<
ref,
) => {
const { t } = useTranslation();
const surfaceRef = useOverlaySurfaceRef("dialog", ref);
return (
<SheetPortal>
<SheetOverlay className={cn((side === "right" || side === "left") && modalOverlayClassName, overlayClassName)} />
<DialogPrimitive.Content
ref={ref}
ref={surfaceRef}
className={cn(
sheetVariants({ side }),
"data-[state=open]:animate-in data-[state=closed]:animate-out",
+18 -14
View File
@@ -2,6 +2,7 @@ import * as React from "react";
import * as TooltipPrimitive from "@radix-ui/react-tooltip";
import { floatingSurfaceElevationClassName } from "@/components/ui/floating-surface";
import { useOverlaySurfaceRef } from "@/lib/dom-overlays";
import { cn } from "@/lib/utils";
function TooltipProvider({
@@ -16,20 +17,23 @@ const TooltipTrigger = TooltipPrimitive.Trigger;
const TooltipContent = React.forwardRef<
React.ElementRef<typeof TooltipPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof TooltipPrimitive.Content>
>(({ className, sideOffset = 4, ...props }, ref) => (
<TooltipPrimitive.Portal>
<TooltipPrimitive.Content
ref={ref}
sideOffset={sideOffset}
className={cn(
floatingSurfaceElevationClassName,
"z-50 origin-[var(--radix-tooltip-content-transform-origin)] overflow-hidden rounded-control px-3 py-1.5 text-caption animate-in fade-in-0 zoom-in-95 motion-reduce:animate-none",
className,
)}
{...props}
/>
</TooltipPrimitive.Portal>
));
>(({ className, sideOffset = 4, ...props }, ref) => {
const surfaceRef = useOverlaySurfaceRef("overlay", ref);
return (
<TooltipPrimitive.Portal>
<TooltipPrimitive.Content
ref={surfaceRef}
sideOffset={sideOffset}
className={cn(
floatingSurfaceElevationClassName,
"z-50 origin-[var(--radix-tooltip-content-transform-origin)] overflow-hidden rounded-control px-3 py-1.5 text-caption animate-in fade-in-0 zoom-in-95 motion-reduce:animate-none",
className,
)}
{...props}
/>
</TooltipPrimitive.Portal>
);
});
TooltipContent.displayName = TooltipPrimitive.Content.displayName;
export { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger };
+1 -1
View File
@@ -2153,7 +2153,7 @@ html[data-custom-background] .markdown-inline-code {
html[data-custom-background] .thread-history-status {
--thread-history-background: hsl(var(--background) / 0.65);
}
html[data-custom-background] [data-testid="file-edit-diff"] {
html[data-custom-background] .file-edit-diff-surface {
background-color: hsl(var(--background) / 0.78);
backdrop-filter: blur(12px);
}
+128
View File
@@ -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,
};
}
+116
View File
@@ -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 };
}
+205
View File
@@ -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 };
}
+82 -177
View File
@@ -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,
]);
+70
View File
@@ -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 };
}
+101
View File
@@ -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 };
}
+43
View File
@@ -0,0 +1,43 @@
import { useCallback, useRef, type ForwardedRef, type RefCallback } from "react";
type OverlayKind = "dialog" | "overlay";
const surfaces = new Map<HTMLElement, OverlayKind>();
// Track the content node's presence, not the owner's open prop: Radix can keep
// closed content mounted through its exit animation.
export function useOverlaySurfaceRef<T extends HTMLElement>(
kind: OverlayKind,
forwardedRef?: ForwardedRef<T>,
): RefCallback<T> {
const current = useRef<T | null>(null);
return useCallback((node) => {
if (current.current) surfaces.delete(current.current);
current.current = node;
if (node) surfaces.set(node, kind);
if (typeof forwardedRef === "function") forwardedRef(node);
else if (forwardedRef) forwardedRef.current = node;
}, [kind, forwardedRef]);
}
function hasDialogSurface(includeClosed: boolean): boolean {
for (const [node, kind] of surfaces) {
if (kind === "dialog" && node.isConnected && (includeClosed || node.dataset.state !== "closed")) return true;
}
return false;
}
export function hasAnyDialogMounted(): boolean {
return hasDialogSurface(true);
}
export function hasOpenDialogSurface(): boolean {
return hasDialogSurface(false);
}
export function hasAnyOverlayMounted(): boolean {
for (const node of surfaces.keys()) {
if (node.isConnected) return true;
}
return false;
}
+27 -13
View File
@@ -33,29 +33,40 @@ function createDefaultSocket(url: string): WebSocket {
return new WebSocket(url);
}
const WS_DEBUG_CACHE_TTL_MS = 1_000;
let wsDebugCache: { checkedAt: number; enabled: boolean } | null = null;
/** Inbound WebSocket ``console.log`` / parse-failure ``console.warn``.
*
* - **Dev** (non-production bundle): **on by default** — messages appear at default log level.
* - **Production**: off unless ``localStorage.setItem('nanobot_debug_ws','1')`` (or ``true``).
* - **Silence anywhere**: ``localStorage.setItem('nanobot_debug_ws','0')`` (or ``false`` / ``off``).
* Values are read on every frame; no reload needed.
* Values are cached briefly so toggling takes effect without reload while avoiding
* synchronous ``localStorage`` reads on every streamed delta frame.
*/
function wsInboundDebugEnabled(): boolean {
if (typeof globalThis === "undefined") return false;
if (import.meta.env.MODE === "test") return false;
const now = Date.now();
if (wsDebugCache && now - wsDebugCache.checkedAt < WS_DEBUG_CACHE_TTL_MS) {
return wsDebugCache.enabled;
}
let enabled: boolean;
try {
if (import.meta.env.MODE === "test") return false;
const ls = (globalThis as unknown as { localStorage?: Storage }).localStorage;
const raw = ls?.getItem("nanobot_debug_ws")?.trim().toLowerCase() ?? "";
if (raw === "0" || raw === "false" || raw === "off" || raw === "no") {
return false;
enabled = false;
} else if (raw === "1" || raw === "true" || raw === "on" || raw === "yes") {
enabled = true;
} else {
enabled = !import.meta.env.PROD;
}
if (raw === "1" || raw === "true" || raw === "on" || raw === "yes") {
return true;
}
return !import.meta.env.PROD;
} catch {
return !import.meta.env.PROD;
enabled = !import.meta.env.PROD;
}
wsDebugCache = { checkedAt: now, enabled };
return enabled;
}
function summarizeInboundWsPayload(ev: InboundEvent): unknown {
@@ -247,6 +258,7 @@ export class NanobotClient {
/** Inbound frames received while the transcript owner is absent, regardless of observers. */
private pendingInboundByChat = new Map<string, InboundEvent[]>();
private static readonly PENDING_INBOUND_MAX = 2000;
private static readonly PENDING_TEMP_INBOUND_MAX = 20_000;
private knownChats = new Set<string>();
/** Temporary chats are connection-owned and intentionally not reattached. */
private temporaryChatIds = new Set<string>();
@@ -1171,11 +1183,13 @@ export class NanobotClient {
this.pendingInboundByChat.set(chatId, pending);
}
pending.push(ev);
// Temporary chats have no canonical history to recover evicted events from.
if (!this.temporaryChatIds.has(chatId)) {
const over = pending.length - NanobotClient.PENDING_INBOUND_MAX;
if (over > 0) pending.splice(0, over);
}
// Temporary chats have no canonical history to recover evicted events from,
// but still keep a generous upper bound so an unmounted chat cannot OOM the tab.
const maxPending = this.temporaryChatIds.has(chatId)
? NanobotClient.PENDING_TEMP_INBOUND_MAX
: NanobotClient.PENDING_INBOUND_MAX;
const over = pending.length - maxPending;
if (over > 0) pending.splice(0, over);
}
for (const handler of this.chatHandlers.get(chatId) ?? []) handler(ev);
}
+210
View File
@@ -0,0 +1,210 @@
import { isAppsSection, type SettingsFocusTarget } from "@/components/settings/contracts";
import type { SettingsSectionKey } from "@/components/settings/SettingsView";
export const RESTART_STARTED_KEY = "nanobot-webui.restartStartedAt";
export const RESTART_ROUTE_KEY = "nanobot-webui.restartRoute";
const RESTART_ROUTE_TTL_MS = 5 * 60 * 1000;
export type ShellView = "chat" | "settings" | "apps" | "automations" | "remote";
export type ShellRoute = {
view: ShellView;
activeKey: string | null;
settingsSection: SettingsSectionKey;
settingsFocus?: SettingsFocusTarget;
temporary?: boolean;
};
const SETTINGS_SECTION_KEYS: SettingsSectionKey[] = [
"capabilities",
"overview",
"about",
"appearance",
"notifications",
"models",
"image",
"voice",
"browser",
"channels",
"apps",
"automations",
"memory",
"skills",
"runtime",
"advanced",
];
function isSettingsSectionKey(value: string | null): value is SettingsSectionKey {
return SETTINGS_SECTION_KEYS.includes(value as SettingsSectionKey);
}
export function defaultShellRoute(): ShellRoute {
return { view: "chat", activeKey: null, settingsSection: "overview" };
}
export function shellViewForSettingsSection(section: SettingsSectionKey): ShellView {
if (isAppsSection(section)) return "apps";
if (section === "automations") return "automations";
return "settings";
}
export function changesSettingsSurface(current: ShellRoute, next: ShellRoute): boolean {
return current.view !== "chat" && current.view !== "remote" &&
(current.view !== next.view || current.settingsSection !== next.settingsSection);
}
function fallbackRestartHash(hash: string): boolean {
return !hash || hash === "/" || hash === "/new";
}
export function rememberRestartRoute(): void {
if (typeof window === "undefined") return;
try {
window.localStorage.setItem(RESTART_ROUTE_KEY, window.location.hash || "#/new");
} catch {
// ignore storage errors
}
}
function maybeRestoreRestartHash(hash: string): string {
if (typeof window === "undefined" || !fallbackRestartHash(hash)) return hash;
try {
const startedAt = Number(window.localStorage.getItem(RESTART_STARTED_KEY) ?? "0");
const storedHash = window.localStorage.getItem(RESTART_ROUTE_KEY);
if (!startedAt || !storedHash || Date.now() - startedAt > RESTART_ROUTE_TTL_MS) {
window.localStorage.removeItem(RESTART_ROUTE_KEY);
return hash;
}
window.localStorage.removeItem(RESTART_ROUTE_KEY);
const nextHash = storedHash.startsWith("#") ? storedHash : `#${storedHash}`;
window.history.replaceState(
null,
"",
`${window.location.pathname}${window.location.search}${nextHash}`,
);
return nextHash.slice(1);
} catch {
return hash;
}
}
export function readShellRoute(): ShellRoute {
if (typeof window === "undefined") return defaultShellRoute();
const currentHash = window.location.hash.startsWith("#")
? window.location.hash.slice(1)
: window.location.hash;
const hash = maybeRestoreRestartHash(currentHash);
if (!hash || hash === "/" || hash === "/new") return defaultShellRoute();
const [path, query = ""] = hash.split("?", 2);
const params = new URLSearchParams(query);
const rawSettingsSection = params.get("section");
const settingsSection = isSettingsSectionKey(rawSettingsSection)
? rawSettingsSection
: "overview";
const saved: unknown = window.history.state?.nanobotReturnChat;
const returnChat = saved && typeof saved === "object" && "hash" in saved
&& saved.hash === window.location.hash ? saved : null;
const activeKey = params.get("chat")?.trim()
|| (returnChat && "key" in returnChat && typeof returnChat.key === "string"
? returnChat.key : null);
const temporary = Boolean(returnChat && "temporary" in returnChat && returnChat.temporary === true);
if (path === "/settings") {
const focus = params.get("focus");
return {
view: shellViewForSettingsSection(settingsSection),
activeKey,
temporary,
settingsSection,
settingsFocus: settingsSection === "advanced" && (focus === "sandbox" || focus === "sandbox-launcher")
? focus
: settingsSection === "models" && focus?.startsWith("image-input:")
? `image-input:${focus.slice("image-input:".length)}`
: undefined,
};
}
if (path === "/apps") {
return { view: "apps", activeKey, temporary, settingsSection: isAppsSection(settingsSection) ? settingsSection : "apps" };
}
if (path === "/automations") {
return { view: "automations", activeKey, temporary, settingsSection: "automations" };
}
if (path === "/channels") {
return { view: "apps", activeKey, temporary, settingsSection: "channels" };
}
if (path === "/remote") {
return { view: "remote", activeKey, temporary, settingsSection: "overview" };
}
if (path === "/skills") {
return { view: "apps", activeKey, temporary, settingsSection: "skills" };
}
if (path.startsWith("/temporary/")) {
const encoded = path.slice("/temporary/".length);
try {
const chatId = decodeURIComponent(encoded).trim();
return chatId
? {
view: "chat",
activeKey: `websocket:${chatId}`,
settingsSection: "overview",
temporary: true,
}
: defaultShellRoute();
} catch {
return defaultShellRoute();
}
}
if (path.startsWith("/chat/")) {
const encoded = path.slice("/chat/".length);
try {
const key = decodeURIComponent(encoded).trim();
return key
? { view: "chat", activeKey: key, settingsSection: "overview" }
: defaultShellRoute();
} catch {
return defaultShellRoute();
}
}
return defaultShellRoute();
}
export function shellRouteHash(route: ShellRoute): string {
if (route.view === "chat") {
if (route.temporary && route.activeKey?.startsWith("websocket:")) {
const chatId = route.activeKey.slice("websocket:".length);
return `#/temporary/${encodeURIComponent(chatId)}`;
}
return route.activeKey
? `#/chat/${encodeURIComponent(route.activeKey)}`
: "#/new";
}
const params = new URLSearchParams();
if (route.view === "settings" && route.settingsSection !== "overview") {
params.set("section", route.settingsSection);
if (route.settingsFocus) params.set("focus", route.settingsFocus);
}
if (route.view === "apps" && route.settingsSection !== "apps") {
params.set("section", route.settingsSection);
}
const query = params.toString();
return `#/${route.view}${query ? `?${query}` : ""}`;
}
export function writeShellRoute(route: ShellRoute, replace = false): void {
if (typeof window === "undefined") return;
const nextHash = shellRouteHash(route);
const state = {
...window.history.state,
nanobotReturnChat: route.view === "chat" ? null : {
hash: nextHash,
key: route.activeKey,
temporary: route.temporary === true,
},
};
const url = `${window.location.pathname}${window.location.search}${nextHash}`;
if (replace || window.location.hash === nextHash) {
window.history.replaceState(state, "", url);
} else {
window.history.pushState(state, "", url);
}
}
+22
View File
@@ -4812,6 +4812,28 @@ describe("App layout", () => {
unmount();
});
it("does not apply a timed credential refresh after signing out", async () => {
vi.mocked(fetchBootstrap).mockResolvedValueOnce({
token: "old", api_token: "old-api", ws_path: "/", expires_in: 0.001,
});
let complete!: (boot: Awaited<ReturnType<typeof fetchBootstrap>>) => void;
vi.mocked(fetchBootstrap).mockImplementationOnce(() => new Promise((resolve) => { complete = resolve; }));
vi.mocked(deriveWsUrl).mockImplementation((_path, token) => `ws://test?token=${token}`);
mockFetchRoutes({ "/api/settings": baseSettingsPayload() });
window.history.replaceState(null, "", "/#/settings");
await import("@/components/settings/SettingsView");
render(<App />);
const signOut = await screen.findByRole("button", { name: "Sign out" }, { timeout: 4_000 });
await waitFor(() => expect(fetchBootstrap).toHaveBeenCalledTimes(2), { timeout: 8_000 });
fireEvent.click(signOut);
await screen.findByLabelText("WebUI password");
await act(async () => complete({ token: "late", api_token: "late-api", ws_path: "/" }));
expect(updateUrlSpy).not.toHaveBeenCalled();
expect(screen.getByLabelText("WebUI password")).toBeInTheDocument();
}, 10_000);
it("refreshes the bootstrap token before REST settings auth expires", async () => {
vi.useFakeTimers();
vi.mocked(fetchBootstrap)
+11 -4
View File
@@ -341,7 +341,7 @@ describe("NanobotClient", () => {
expect(notice).toHaveBeenCalledWith({ event, temporary: false });
client.close();
});
it("bounds regular replay tails but retains temporary events until discard", async () => {
it("retains a larger replay tail for temporary chats and clears it on discard", async () => {
const client = new NanobotClient({
url: "ws://test", reconnect: false,
socketFactory: (url) => new FakeSocket(url) as unknown as WebSocket,
@@ -357,13 +357,20 @@ describe("NanobotClient", () => {
socket.fakeMessage({ event: "delta", chat_id: chatId, text: String(index) });
}
}
for (let index = 2_010; index < 20_010; index++) {
socket.fakeMessage({ event: "delta", chat_id: "temporary", text: String(index) });
}
const regular = vi.fn();
const temporary = vi.fn();
const temporary: string[] = [];
client.onTranscript("regular", regular);
const unsubscribe = client.onTranscript("temporary", temporary);
const unsubscribe = client.onTranscript("temporary", (event) => {
if (event.event === "delta") temporary.push(event.text);
});
expect(regular).toHaveBeenCalledTimes(2_000);
expect(regular.mock.calls[0][0].text).toBe("10");
expect(temporary.mock.calls.filter(([event]) => event.event === "delta")).toHaveLength(2_010);
expect(temporary).toHaveLength(20_000);
expect(temporary[0]).toBe("10");
expect(temporary.at(-1)).toBe("20009");
unsubscribe();
socket.fakeMessage({ event: "delta", chat_id: "temporary", text: "discard me" });
client.discardTemporaryChat("temporary");
+24
View File
@@ -3,6 +3,7 @@ import userEvent from "@testing-library/user-event";
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import { PromptNavigator } from "@/components/thread/PromptNavigator";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { mockBrowserFocus } from "./browser-focus";
let restoreBrowserFocus: () => void;
@@ -80,6 +81,29 @@ it("keeps an unknown recovered time blank while the prompt remains navigable", a
expect(onJumpToPrompt).toHaveBeenCalledWith("undated");
});
it("defers Ctrl+F to an open popover but not to its exit animation", async () => {
render(<>
<style>{`.test-popover[data-state="open"] { animation-name: enter; }
.test-popover[data-state="closed"] { animation-name: exit; }`}</style>
<Popover>
<PopoverTrigger>Model options</PopoverTrigger>
<PopoverContent aria-label="Model options" className="test-popover"><button>Choose model</button></PopoverContent>
</Popover>
<PromptNavigator messages={[{ id: "one", role: "user", content: "alpha", createdAt: 1 }]} onJumpToPrompt={vi.fn()} />
</>);
fireEvent.click(screen.getByRole("button", { name: "Model options" }));
const popover = screen.getByRole("dialog", { name: "Model options" });
const option = screen.getByRole("button", { name: "Choose model" });
fireEvent.keyDown(option, { key: "f", ctrlKey: true });
expect(screen.queryByRole("textbox", { name: "Search messages" })).not.toBeInTheDocument();
fireEvent.keyDown(option, { key: "Escape" });
expect(popover).toHaveAttribute("data-state", "closed");
expect(popover).toBeInTheDocument();
fireEvent.keyDown(screen.getByRole("button", { name: "Model options" }), { key: "f", ctrlKey: true });
expect(screen.getByRole("textbox", { name: "Search messages" })).toBeInTheDocument();
});
it("returns shortcut-opened search to the interrupted editor", async () => {
const user = userEvent.setup();
render(<><input aria-label="Draft" /><PromptNavigator messages={[
@@ -10,6 +10,7 @@ import { canonicalThreadPayload } from "./thread-test-payload";
let groupedTopics = false;
let withFiles = false;
let withPairing = false;
const previewFile = (path: string) => ({
path: `/workspace/${path}`, display_path: path, project_path: "/workspace",
language: "text", content: `Preview of ${path}`, size: 20, truncated: false,
@@ -105,12 +106,16 @@ describe("temporary chat navigation", () => {
vi.mocked(fetchBootstrap).mockReset().mockResolvedValue({ token: "test", api_token: "test", ws_path: "/" });
groupedTopics = false;
withFiles = false;
withPairing = false;
localStorage.clear();
sessionStorage.clear();
window.history.replaceState(null, "", "/");
vi.stubGlobal("WebSocket", TestSocket);
vi.stubGlobal("fetch", vi.fn(async (input: RequestInfo | URL) => {
const path = String(input);
if (path === "/api/settings/pairing") {
return Response.json({ requests: withPairing ? [{ code: "ABCD-EFGH", channel: "telegram", sender_id: "1" }] : [] });
}
if (path === "/api/sessions") {
return Response.json({ sessions: ["regular", ...(groupedTopics ? ["child"] : [])].map((id) => ({
key: `websocket:${id}`,
@@ -345,16 +350,49 @@ describe("temporary chat navigation", () => {
expect(screen.getAllByRole("tab")).toHaveLength(1);
fireEvent.click(screen.getByRole("button", { name: "notes.txt" }));
await screen.findByText("Preview of notes.txt");
const dialog = document.createElement("div");
dialog.setAttribute("role", "dialog");
document.body.append(dialog);
fireEvent.keyDown(window, { key: "Escape" });
withPairing = true;
act(() => TestSocket.current.receive({ event: "pairing_changed" }));
const dialog = await screen.findByRole("dialog", { name: "Pair account" });
// This popup does not intercept Escape itself; the preview must still yield.
fireEvent.keyDown(within(dialog).getByRole("textbox", { name: "Pairing code" }), { key: "Escape" });
expect(screen.getByTestId("file-preview-panel")).toBeInTheDocument();
dialog.remove();
fireEvent.keyDown(window, { key: "Escape" });
fireEvent.click(within(dialog).getByRole("button", { name: "Close" }));
await waitFor(() => expect(dialog).not.toBeInTheDocument());
fireEvent.keyDown(screen.getByRole("button", { name: "notes.txt" }), { key: "Escape" });
await waitFor(() => expect(screen.queryByTestId("file-preview-panel")).not.toBeInTheDocument());
});
it("commits a file preview drag and restores the page when closing mid-drag", async () => {
withFiles = true;
render(<App />);
await screen.findByRole("button", { name: "Temporary chat" });
act(() => TestSocket.current.open());
await selectTopic("Regular topic");
fireEvent.click(await screen.findByRole("button", { name: "notes.txt" }));
await screen.findByText("Preview of notes.txt");
const panel = screen.getByTestId("preview-pane");
vi.spyOn(panel.parentElement!, "getBoundingClientRect")
.mockReturnValue(DOMRect.fromRect({ width: 1_200 }));
fireEvent(window, new Event("resize"));
const handle = screen.getByRole("button", { name: "Resize file preview" });
const { cursor, userSelect } = document.body.style;
fireEvent.pointerDown(handle, { clientX: 700 });
expect(document.body.style.cursor).toBe("col-resize");
fireEvent.pointerMove(window, { clientX: 570 });
fireEvent.pointerUp(window);
expect(panel.style.getPropertyValue("--file-preview-width")).toBe("630px");
expect(document.body.style.cursor).toBe(cursor);
fireEvent.pointerDown(handle, { clientX: 600 });
fireEvent.click(screen.getByRole("button", { name: "Close notes.txt" }));
expect(document.body.style.cursor).toBe(cursor);
expect(document.body.style.userSelect).toBe(userSelect);
await waitFor(() => expect(panel).not.toBeInTheDocument());
fireEvent.click(screen.getByRole("button", { name: "notes.txt" }));
expect(screen.getByTestId("preview-pane").style.getPropertyValue("--file-preview-width")).toBe("630px");
});
it("forgets preview paths on temporary close and disconnect", async () => {
const update = vi.spyOn(FilePreviewStore.prototype, "open");
render(<App />);
+2 -12
View File
@@ -1272,18 +1272,9 @@ describe("ThreadViewport", () => {
});
expect(hitTest.mock).toHaveBeenCalled();
const replacement = anchor.cloneNode(true) as HTMLElement;
anchor.replaceWith(replacement);
// Deferred content grows above the existing row wrapper.
anchorDocumentTop += 180;
scrollHeight += 180;
Object.defineProperty(replacement, "getBoundingClientRect", {
configurable: true,
value: () => DOMRect.fromRect({
y: anchorDocumentTop - scroller.scrollTop,
width: 800,
height: 40,
}),
});
const content = screen.getByTestId("thread-message-region").firstElementChild;
const observer = resizeObserver.observers.find((candidate) =>
content ? candidate.elements.includes(content) : false,
@@ -1294,10 +1285,9 @@ describe("ThreadViewport", () => {
});
expect(scroller.scrollTop).toBe(260);
expect(replacement.getBoundingClientRect().top).toBe(120);
expect(anchor.getBoundingClientRect().top).toBe(120);
// ResizeObserver may arrive before the next native scroll event.
hitTarget = replacement;
scroller.scrollTop = 240;
anchorDocumentTop += 60;
scrollHeight += 60;