perf(webui): defer non-chat startup interfaces

This commit is contained in:
chengyongru authored and chengyongru committed 2026-10-24 22:15:50 +08:00
1 parent ae7fed88e2
commit 4bd1b74c6b
20 files changed
+710 -70

No files matched your search

+3 -3
View File
@@ -15,7 +15,7 @@ import { StarPrompt } from "@/components/StarPrompt";
import { Sidebar } from "@/components/Sidebar";
import { RemoteInstances } from "@/components/remote/RemoteInstances";
import { useRemoteConnections } from "@/components/remote/remote-context";
import { RemoteConnectionsPage } from "@/components/remote/RemoteConnectionsPage";
import { LazyRemoteConnectionsPage } from "@/components/remote/LazyRemoteConnectionsPage";
import { LanguageSwitcher } from "@/components/LanguageSwitcher";
import { SidebarResizeHandle, SIDEBAR_MIN_WIDTH, SIDEBAR_MAX_WIDTH } from "@/components/SidebarResizeHandle";
import { matchSidebarShortcut } from "@/lib/sidebar-shortcuts";
@@ -3112,7 +3112,7 @@ function Shell({
</div>}
{view !== "chat" && (
<div className="absolute inset-0 flex flex-col">
{view === "remote" ? <RemoteConnectionsPage
{view === "remote" ? <LazyRemoteConnectionsPage
mainNavigationExpanded={showMainSidebar && hostSidebarOpen}
hostChromeInset={showHostChrome}
onBackToChat={onBackToChat}
@@ -3146,7 +3146,7 @@ function Shell({
)}
</div>
{managingConnections && !remoteConnections?.embeddedManagement && <div className="absolute inset-0 flex flex-col">
<RemoteConnectionsPage
<LazyRemoteConnectionsPage
mainNavigationExpanded={showMainSidebar && hostSidebarOpen}
hostChromeInset={showHostChrome}
onBackToChat={() => remoteConnections?.closeManagement()}
@@ -0,0 +1,16 @@
import { Component, type ReactNode } from "react";
export class SurfaceErrorBoundary extends Component<
{ children: ReactNode; fallback: ReactNode },
{ failed: boolean }
> {
state = { failed: false };
static getDerivedStateFromError() {
return { failed: true };
}
render() {
return this.state.failed ? this.props.fallback : this.props.children;
}
}
@@ -0,0 +1,30 @@
import { lazy, Suspense, type ComponentProps } from "react";
import { useTranslation } from "react-i18next";
import { StartupShell } from "@/components/StartupShell";
import { SurfaceErrorBoundary } from "@/components/SurfaceErrorBoundary";
import { Button } from "@/components/ui/button";
const RemoteConnectionsPage = lazy(async () => {
const module = await import("./RemoteConnectionsPage");
return { default: module.RemoteConnectionsPage };
});
export function LazyRemoteConnectionsPage(props: ComponentProps<typeof RemoteConnectionsPage>) {
const { t } = useTranslation();
return <SurfaceErrorBoundary fallback={
<div className="flex min-h-0 flex-1 flex-col items-center justify-center gap-3 bg-background p-6 text-center">
<p role="alert" className="max-w-sm text-sm text-destructive">{t("app.loading.failed")}</p>
<Button variant="ghost" onClick={props.onBackToChat}>{t("remote.back")}</Button>
</div>
}>
<Suspense fallback={
<div className="relative min-h-0 flex-1">
<StartupShell embedded surface="remote" sidebarExpanded={props.mainNavigationExpanded ?? false} />
<Button variant="ghost" className={`touch-target absolute left-4 z-10 ${props.hostChromeInset ? "top-20" : "top-4"}`}
onClick={props.onBackToChat}>{t("remote.back")}</Button>
</div>
}>
<RemoteConnectionsPage {...props} />
</Suspense>
</SurfaceErrorBoundary>;
}
@@ -4,7 +4,7 @@ import { useTranslation } from "react-i18next";
import { Button } from "@/components/ui/button";
import { groupRemoteProfiles, isCompatibilityError, needsRemoteSetup } from "@/lib/remote-instances";
import { HostCompatibilityDialog } from "./HostCompatibilityDialog";
import { RemoteConnectionsPage } from "./RemoteConnectionsPage";
import { LazyRemoteConnectionsPage } from "./LazyRemoteConnectionsPage";
import { ThemeProvider } from "@/hooks/useTheme";
import { useHostSessions } from "./useHostSessions";
import { HostNavigationContext, HostSwitcher, RemoteHostMenu, type HostPicker } from "./HostSwitcher";
@@ -174,7 +174,7 @@ export function RemoteInstances({ children }: { children: ReactNode }) {
className="absolute bottom-0 right-0 flex min-h-0 flex-col bg-background"
style={{ left: offline ? 0 : Math.min(bridge.surface?.left || 0, Math.max(0, window.innerWidth - 280)), top: offline ? 0 : Math.min(bridge.surface?.top || 0, Math.max(0, window.innerHeight - 280)) }}>
<ThemeProvider theme={bridge.surface?.theme || "light"}>
<RemoteConnectionsPage onBackToChat={() => changeManagement(false)} mainNavigationExpanded={!!bridge.surface?.left} />
<LazyRemoteConnectionsPage onBackToChat={() => changeManagement(false)} mainNavigationExpanded={!!bridge.surface?.left} />
</ThemeProvider>
</main>}
{!managing && selected && (offline || !activeFrame?.loaded) && <div role="region" aria-label={t(offline ? recoveryTitle : "remote.opening")} className="absolute inset-0 overflow-y-auto bg-background p-6 text-center"><div className="flex min-h-full flex-col items-center justify-center gap-3">
@@ -1,5 +1,4 @@
import { useEffect, useState, type ReactNode } from "react";
import QRCode from "qrcode";
import { Check, CircleAlert, Clock, Loader2, RotateCcw, X } from "lucide-react";
import { useTranslation } from "react-i18next";
@@ -77,17 +76,20 @@ export function ChannelQrConnectFlowView({
: undefined;
useEffect(() => {
if (!showQrCode || !connect?.qr_url) {
const qrUrl = connect?.qr_url;
if (!showQrCode || !qrUrl) {
setQrDataUrl("");
return;
}
let cancelled = false;
void QRCode.toDataURL(connect.qr_url, {
width: 184,
margin: 1,
color: { dark: "#111827", light: "#ffffff" },
})
.then((url) => {
void import("qrcode")
.then(async ({ default: QRCode }) => {
if (cancelled) return;
const url = await QRCode.toDataURL(qrUrl, {
width: 184,
margin: 1,
color: { dark: "#111827", light: "#ffffff" },
});
if (!cancelled) setQrDataUrl(url);
})
.catch(() => {
@@ -1,4 +1,4 @@
import { useEffect, useRef, useState } from "react";
import { lazy, Suspense, useEffect, useRef, useState } from "react";
import {
CalendarClock,
ChevronRight,
@@ -7,12 +7,9 @@ import {
import type { TFunction } from "i18next";
import { useTranslation } from "react-i18next";
import {
AutomationDeleteDialog,
AutomationDetailDialog,
AutomationEditDialog,
} from "@/components/settings/system/AutomationsSettings";
import type { AutomationAction } from "@/components/settings/system/AutomationsSettings";
import { SurfaceErrorBoundary } from "@/components/SurfaceErrorBoundary";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { SkeletonStatus } from "@/components/settings/shared/SkeletonStatus";
import { formControlFocusClassName } from "@/components/ui/form-control";
@@ -29,6 +26,19 @@ import type {
} from "@/lib/types";
import { cn } from "@/lib/utils";
const AutomationDetailDialog = lazy(async () => {
const module = await import("@/components/settings/system/AutomationsSettings");
return { default: module.AutomationDetailDialog };
});
const AutomationEditDialog = lazy(async () => {
const module = await import("@/components/settings/system/AutomationsSettings");
return { default: module.AutomationEditDialog };
});
const AutomationDeleteDialog = lazy(async () => {
const module = await import("@/components/settings/system/AutomationsSettings");
return { default: module.AutomationDeleteDialog };
});
const RELATIVE_THRESHOLDS: [number, Intl.RelativeTimeFormatUnit][] = [
[60, "second"],
[60, "minute"],
@@ -55,6 +65,8 @@ export function SessionInfoPopoverView({ title, jobs, loading, loadFailed, now,
const { t } = useTranslation("common");
const [open, setOpen] = useState(false);
const [inspectedJob, setInspectedJob] = useState<SessionAutomationJob | null>(null);
// Keep requested dialogs mounted through their close and focus-restoration lifecycle.
const [dialogsRequested, setDialogsRequested] = useState(false);
const [detailOpen, setDetailOpen] = useState(false);
const [actionKey, setActionKey] = useState<string | null>(null);
const [actionError, setActionError] = useState<string | null>(null);
@@ -67,6 +79,7 @@ export function SessionInfoPopoverView({ title, jobs, loading, loadFailed, now,
const selectedJob = inspectedJob;
const inspectJob = (job: SessionAutomationJob) => {
setDialogsRequested(true);
setActionError(null);
setInspectedJob(job);
setOpen(false);
@@ -76,6 +89,15 @@ export function SessionInfoPopoverView({ title, jobs, loading, loadFailed, now,
afterDetailClose.current = next;
setDetailOpen(false);
};
const handleDetailCloseAutoFocus = (event: Event) => {
event.preventDefault();
if (detailOpen) return;
setInspectedJob(null);
triggerRef.current?.focus({ preventScroll: true });
const next = afterDetailClose.current;
afterDetailClose.current = null;
next?.();
};
const updateInspectedJob = (nextJobs: SessionAutomationJob[], id: string) => {
const nextJob = nextJobs.find((job) => job.id === id);
if (nextJob) setInspectedJob(nextJob);
@@ -112,6 +134,18 @@ export function SessionInfoPopoverView({ title, jobs, loading, loadFailed, now,
setActionKey(null);
}
};
const detailPlaceholder = (failed: boolean) => (
<Dialog open={detailOpen} onOpenChange={setDetailOpen}>
<DialogContent aria-describedby={undefined} className="max-w-[520px]" onCloseAutoFocus={handleDetailCloseAutoFocus}>
<DialogHeader><DialogTitle>{selectedJob?.name || selectedJob?.id}</DialogTitle></DialogHeader>
{failed ? <p role="alert" className="text-sm text-destructive">{t("thread.sessionInfo.loadFailed")}</p> : (
<SkeletonStatus label={t("thread.sessionInfo.loading")} className="space-y-3">
<div className="h-24 rounded-control bg-muted/35" />
</SkeletonStatus>
)}
</DialogContent>
</Dialog>
);
const automationContent = loading && jobs.length === 0 ? (
<SkeletonStatus label={t("thread.sessionInfo.loading")} className="space-y-1 px-2">
{[0, 1, 2].map((index) => <div key={index} data-session-job-skeleton className="grid min-h-12 grid-cols-[0.375rem_minmax(0,1fr)_1rem] items-center gap-2.5 px-3 py-2">
@@ -203,46 +237,42 @@ export function SessionInfoPopoverView({ title, jobs, loading, loadFailed, now,
</PopoverContent>
</Popover>
<AutomationDetailDialog
job={selectedJob}
open={detailOpen}
locale={currentLocale()}
actionKey={actionKey}
error={actionError}
onOpenChange={setDetailOpen}
onAction={handleAction}
onRequestEdit={(job) => handOffDetail(() => setPendingEdit(job))}
onRequestDelete={(job) => handOffDetail(() => setPendingDelete(job))}
onCloseAutoFocus={(event) => {
event.preventDefault();
if (detailOpen) return;
setInspectedJob(null);
triggerRef.current?.focus({ preventScroll: true });
const next = afterDetailClose.current;
afterDetailClose.current = null;
next?.();
}}
/>
<AutomationEditDialog
job={pendingEdit}
saving={actionKey === `update:${pendingEdit?.id ?? ""}`}
onOpenChange={(nextOpen) => {
if (!nextOpen) setPendingEdit(null);
}}
onCancel={(job) => {
setInspectedJob(job);
setDetailOpen(true);
}}
onSave={handleEdit}
/>
<AutomationDeleteDialog
job={pendingDelete}
deleting={actionKey === `delete:${pendingDelete?.id ?? ""}`}
onOpenChange={(nextOpen) => {
if (!nextOpen) setPendingDelete(null);
}}
onConfirm={(job) => handleAction("delete", job)}
/>
{dialogsRequested ? <SurfaceErrorBoundary fallback={detailPlaceholder(true)}>
<Suspense fallback={detailPlaceholder(false)}>
<AutomationDetailDialog
job={selectedJob}
open={detailOpen}
locale={currentLocale()}
actionKey={actionKey}
error={actionError}
onOpenChange={setDetailOpen}
onAction={handleAction}
onRequestEdit={(job) => handOffDetail(() => setPendingEdit(job))}
onRequestDelete={(job) => handOffDetail(() => setPendingDelete(job))}
onCloseAutoFocus={handleDetailCloseAutoFocus}
/>
<AutomationEditDialog
job={pendingEdit}
saving={actionKey === `update:${pendingEdit?.id ?? ""}`}
onOpenChange={(nextOpen) => {
if (!nextOpen) setPendingEdit(null);
}}
onCancel={(job) => {
setInspectedJob(job);
setDetailOpen(true);
}}
onSave={handleEdit}
/>
<AutomationDeleteDialog
job={pendingDelete}
deleting={actionKey === `delete:${pendingDelete?.id ?? ""}`}
onOpenChange={(nextOpen) => {
if (!nextOpen) setPendingDelete(null);
}}
onConfirm={(job) => handleAction("delete", job)}
/>
</Suspense>
</SurfaceErrorBoundary> : null}
</>
);
}
+2 -1
View File
@@ -372,7 +372,8 @@
"brand": "nanobot",
"loading": {
"connecting": "Connecting to nanobot…",
"boot": "Loading nanobot…"
"boot": "Loading nanobot…",
"failed": "Couldn't load this view. Go back, or reload the page to try again."
},
"error": {
"title": "Couldn't reach nanobot",
+2 -1
View File
@@ -372,7 +372,8 @@
"brand": "nanobot",
"loading": {
"connecting": "Conectando con nanobot…",
"boot": "Cargando nanobot…"
"boot": "Cargando nanobot…",
"failed": "No se pudo cargar esta vista. Vuelve atrás o recarga la página para intentarlo de nuevo."
},
"error": {
"title": "No se pudo conectar con nanobot",
+2 -1
View File
@@ -372,7 +372,8 @@
"brand": "nanobot",
"loading": {
"connecting": "Connexion à nanobot…",
"boot": "Chargement de nanobot…"
"boot": "Chargement de nanobot…",
"failed": "Impossible de charger cette vue. Revenez en arrière ou rechargez la page pour réessayer."
},
"error": {
"title": "Impossible de joindre nanobot",
+2 -1
View File
@@ -372,7 +372,8 @@
"brand": "nanobot",
"loading": {
"connecting": "Menghubungkan ke nanobot…",
"boot": "Memuat nanobot…"
"boot": "Memuat nanobot…",
"failed": "Tampilan ini tidak dapat dimuat. Kembali atau muat ulang halaman untuk mencoba lagi."
},
"error": {
"title": "Tidak dapat menjangkau nanobot",
+2 -1
View File
@@ -372,7 +372,8 @@
"brand": "nanobot",
"loading": {
"connecting": "nanobot に接続中…",
"boot": "nanobot を読み込み中…"
"boot": "nanobot を読み込み中…",
"failed": "この画面を読み込めませんでした。戻るか、ページを再読み込みしてお試しください。"
},
"error": {
"title": "nanobot に接続できませんでした",
+2 -1
View File
@@ -372,7 +372,8 @@
"brand": "nanobot",
"loading": {
"connecting": "nanobot에 연결 중…",
"boot": "nanobot 불러오는 중…"
"boot": "nanobot 불러오는 중…",
"failed": "이 화면을 불러오지 못했습니다. 뒤로 가거나 페이지를 새로고침하여 다시 시도하세요."
},
"error": {
"title": "nanobot에 연결할 수 없습니다",
+2 -1
View File
@@ -372,7 +372,8 @@
"brand": "nanobot",
"loading": {
"connecting": "Conectando-se ao nanobot…",
"boot": "Carregando nanobot…"
"boot": "Carregando nanobot…",
"failed": "Não foi possível carregar esta tela. Volte ou recarregue a página para tentar novamente."
},
"error": {
"title": "Não foi possível conectar-se com o nanobot",
+2 -1
View File
@@ -372,7 +372,8 @@
"brand": "nanobot",
"loading": {
"connecting": "Đang kết nối tới nanobot…",
"boot": "Đang tải nanobot…"
"boot": "Đang tải nanobot…",
"failed": "Không thể tải giao diện này. Hãy quay lại hoặc tải lại trang để thử lại."
},
"error": {
"title": "Không thể kết nối tới nanobot",
+2 -1
View File
@@ -372,7 +372,8 @@
"brand": "nanobot",
"loading": {
"connecting": "正在连接 nanobot…",
"boot": "正在加载 nanobot…"
"boot": "正在加载 nanobot…",
"failed": "无法加载此页面。请返回,或刷新页面重试。"
},
"error": {
"title": "无法连接到 nanobot",
+2 -1
View File
@@ -372,7 +372,8 @@
"brand": "nanobot",
"loading": {
"connecting": "正在連線到 nanobot…",
"boot": "正在載入 nanobot…"
"boot": "正在載入 nanobot…",
"failed": "無法載入此頁面。請返回,或重新整理頁面再試。"
},
"error": {
"title": "無法連線到 nanobot",
@@ -0,0 +1,197 @@
import { Buffer } from "node:buffer";
import { act, cleanup, render, screen, waitFor } from "@testing-library/react";
import type { QRCodeToDataURLOptions } from "qrcode";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { ChannelQrConnectFlowViewProps } from "@/components/settings/channels/ChannelQrConnectFlowView";
import type { ChannelConnectPayload } from "@/lib/types";
const props: ChannelQrConnectFlowViewProps = {
connect: null,
busy: false,
error: null,
onStart: () => {},
onCancel: () => {},
onPoll: async () => null,
labels: {
qrAlt: "Connection QR code",
scanTitle: "Scan to connect",
scanDescription: "Scan with your app",
waiting: "Waiting",
connected: "Connected",
stopped: "Stopped",
connecting: "Connecting",
scanAgain: "Scan again",
connect: "Connect",
},
};
const firstUrl = "https://example.com/connect/first";
const nextUrl = "https://example.com/connect/next";
const currentImage = "data:image/png;base64,current";
const qrOptions = {
width: 184,
margin: 1,
color: { dark: "#111827", light: "#ffffff" },
};
function pending(qr_url?: string): ChannelConnectPayload {
return { session_id: "qr-session", status: "pending", qr_url };
}
function deferred<T>() {
let resolve!: (value: T) => void;
let reject!: (error: Error) => void;
const promise = new Promise<T>((res, rej) => { resolve = res; reject = rej; });
return { promise, resolve, reject };
}
function mockQrModule(ready: Promise<void> = Promise.resolve()) {
const toDataURL = vi.fn<(text: string, options: QRCodeToDataURLOptions) => Promise<string>>()
.mockResolvedValue(currentImage);
const load = vi.fn(async () => {
await ready;
return { default: { toDataURL } };
});
vi.doMock("qrcode", load);
return { toDataURL, load };
}
async function loadView() {
const { ChannelQrConnectFlowView } = await import("@/components/settings/channels/ChannelQrConnectFlowView");
return ChannelQrConnectFlowView;
}
beforeEach(() => { vi.resetModules(); });
afterEach(() => {
cleanup();
vi.doUnmock("qrcode");
vi.restoreAllMocks();
});
describe("channel QR encoder loading", () => {
it("loads and encodes only when a visible QR URL is available", async () => {
const { toDataURL, load } = mockQrModule();
toDataURL.mockImplementation(async (text, options) => {
const actual = await vi.importActual<typeof import("qrcode")>("qrcode");
return actual.toDataURL(text, options);
});
const View = await loadView();
const view = render(<View {...props} />);
await vi.dynamicImportSettled();
expect(load).not.toHaveBeenCalled();
expect(toDataURL).not.toHaveBeenCalled();
view.rerender(<View {...props} connect={pending()} />);
await vi.dynamicImportSettled();
expect(screen.getByRole("status")).toHaveTextContent("Connecting");
expect(load).not.toHaveBeenCalled();
expect(toDataURL).not.toHaveBeenCalled();
view.rerender(<View {...props} connect={pending(firstUrl)} showQrCode={false} />);
await vi.dynamicImportSettled();
expect(screen.getByRole("status")).toHaveTextContent("Waiting");
expect(screen.getByText("Scan with your app")).toBeVisible();
expect(screen.queryByRole("img")).not.toBeInTheDocument();
expect(load).not.toHaveBeenCalled();
expect(toDataURL).not.toHaveBeenCalled();
view.rerender(<View {...props} connect={pending(firstUrl)} />);
const image = await screen.findByRole("img", { name: "Connection QR code" });
expect(load).toHaveBeenCalledOnce();
expect(toDataURL).toHaveBeenCalledOnce();
expect(toDataURL).toHaveBeenCalledWith(firstUrl, qrOptions);
expect(image).toHaveClass("h-[184px]", "w-[184px]");
expect(screen.getByRole("status")).toHaveTextContent("Waiting");
const source = image.getAttribute("src")!;
expect(source).toMatch(/^data:image\/png;base64,/);
const png = Buffer.from(source.split(",")[1], "base64");
expect(png.subarray(0, 8).toString("hex")).toBe("89504e470d0a1a0a");
expect(png.readUInt32BE(16)).toBe(184);
expect(png.readUInt32BE(20)).toBe(184);
});
it.each(["removed", "hidden", "unmounted"] as const)(
"does not encode if the QR is %s while the library loads",
async (change) => {
const ready = deferred<void>();
const { toDataURL, load } = mockQrModule(ready.promise);
const View = await loadView();
const view = render(<View {...props} connect={pending(firstUrl)} />);
await waitFor(() => expect(load).toHaveBeenCalledOnce());
if (change === "unmounted") {
view.unmount();
} else {
view.rerender(<View {...props}
connect={pending(change === "removed" ? undefined : firstUrl)}
showQrCode={change !== "hidden"} />);
}
await act(async () => {
ready.resolve(undefined);
await vi.dynamicImportSettled();
});
expect(toDataURL).not.toHaveBeenCalled();
expect(screen.queryByRole("img")).not.toBeInTheDocument();
},
);
it.each(["result", "failure"] as const)(
"ignores a late encoder %s after a newer QR is displayed",
async (outcome) => {
const stale = deferred<string>();
const current = deferred<string>();
const { toDataURL } = mockQrModule();
toDataURL.mockReturnValueOnce(stale.promise).mockReturnValueOnce(current.promise);
const View = await loadView();
const view = render(<View {...props} connect={pending(firstUrl)} />);
await waitFor(() => expect(toDataURL).toHaveBeenCalledTimes(1));
view.rerender(<View {...props} connect={pending(nextUrl)} />);
await waitFor(() => expect(toDataURL).toHaveBeenCalledTimes(2));
await act(async () => { current.resolve(currentImage); });
expect(screen.getByRole("img")).toHaveAttribute("src", currentImage);
await act(async () => {
if (outcome === "result") stale.resolve("data:image/png;base64,stale");
else stale.reject(new Error("Old QR encoding failed"));
});
expect(screen.getByRole("img")).toHaveAttribute("src", currentImage);
expect(screen.getByRole("status")).toHaveTextContent("Waiting");
},
);
it("does not resurrect a hidden QR from a late encoder result when shown again", async () => {
const stale = deferred<string>();
const current = deferred<string>();
const { toDataURL } = mockQrModule();
toDataURL.mockReturnValueOnce(stale.promise).mockReturnValueOnce(current.promise);
const View = await loadView();
const view = render(<View {...props} connect={pending(firstUrl)} />);
await waitFor(() => expect(toDataURL).toHaveBeenCalledTimes(1));
view.rerender(<View {...props} connect={pending(firstUrl)} showQrCode={false} />);
await act(async () => { stale.resolve("data:image/png;base64,stale"); });
view.rerender(<View {...props} connect={pending(firstUrl)} />);
await waitFor(() => expect(toDataURL).toHaveBeenCalledTimes(2));
expect(screen.queryByRole("img")).not.toBeInTheDocument();
expect(screen.getByRole("status")).toHaveTextContent("Connecting");
await act(async () => { current.resolve(currentImage); });
expect(screen.getByRole("img")).toHaveAttribute("src", currentImage);
});
it.each(["loading", "encoding"] as const)("keeps the existing placeholder on %s failure", async (stage) => {
const { toDataURL } = mockQrModule();
if (stage === "loading") {
vi.doMock("qrcode", () => { throw new Error("QR chunk unavailable"); });
} else {
toDataURL.mockRejectedValue(new Error("QR encoding failed"));
}
const View = await loadView();
render(<View {...props} connect={pending(firstUrl)} />);
await act(async () => { await vi.dynamicImportSettled(); });
expect(screen.queryByRole("img")).not.toBeInTheDocument();
expect(screen.getByRole("status")).toHaveTextContent("Connecting");
expect(screen.getByRole("button", { name: "Cancel" })).toBeEnabled();
expect(screen.queryByRole("alert")).not.toBeInTheDocument();
});
});
@@ -0,0 +1,255 @@
import { act, cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { Window as HappyWindow } from "happy-dom";
import type { InboundEvent, Outbound } from "@/lib/types";
(window as unknown as HappyWindow).happyDOM.settings.disableIframePageLoading = true;
vi.mock("@/lib/bootstrap", async (original) => ({
...await original<typeof import("@/lib/bootstrap")>(),
fetchBootstrap: vi.fn(async () => ({ token: "test", api_token: "test", ws_path: "/" })),
deriveWsUrl: () => "ws://test",
}));
// Keep this suite focused on App's remote boundary rather than the chat implementation.
vi.mock("@/components/thread/ThreadShell", () => ({
ThreadShell: () => <textarea aria-label="Local draft" />,
}));
const profile = {
id: "3b968d52-081d-4898-9970-ff0a1fc93817", name: "Team server", host: "ubuntu@example.test",
port: 22, config_path: "~/.nanobot/config.json", ssh_config: "", identity_file: "", runtime_user: "", connected: false,
};
const connection = {
...profile, hostname: "team-host", gateway_id: "gateway-1",
url: "http://127.0.0.1:23456/#/?bootstrapSecret=test-only",
};
class TestSocket {
static current: TestSocket;
readyState = 0;
sent: Outbound[] = [];
onopen: (() => void) | null = null;
onmessage: ((event: MessageEvent) => void) | null = null;
onclose: (() => void) | null = null;
constructor() { TestSocket.current = this; }
open() { this.readyState = 1; this.onopen?.(); }
close() { this.readyState = 3; this.onclose?.(); }
receive(event: InboundEvent) {
this.onmessage?.(new MessageEvent("message", { data: JSON.stringify(event) }));
}
send(data: string) {
const frame = JSON.parse(data) as Outbound;
this.sent.push(frame);
if (frame.type !== "webui_request") return;
const result = frame.action === "remote.connect" ? connection
: frame.action === "remote.pair_start" ? { id: "test-pair", command: "nanobot remote pair nbpr1.test", expires: Date.now() / 1000 + 600 }
: frame.action === "remote.discover" ? { hosts: [], files: [], incomplete: false } : {};
queueMicrotask(() => this.receive({
event: "webui_response", request_id: frame.request_id, ok: true, result,
}));
}
}
let releaseManagement: (() => void) | undefined;
let managementImport: Promise<typeof import("@/components/remote/RemoteConnectionsPage")> | undefined;
async function finishManagementImport() {
await act(async () => { releaseManagement?.(); await managementImport; });
}
async function loadApp(deferManagement = false, importError?: Error) {
const loaded = vi.fn();
const gate = new Promise<void>((resolve) => { releaseManagement = resolve; });
vi.doMock("@/components/remote/RemoteConnectionsPage", (original) => {
loaded();
if (importError) return Promise.reject(importError);
managementImport = (async () => {
if (deferManagement) await gate;
return original<typeof import("@/components/remote/RemoteConnectionsPage")>();
})();
return managementImport;
});
const { initializeI18n, loadAllLocaleResources } = await import("@/i18n");
await initializeI18n();
await loadAllLocaleResources();
const { default: App } = await import("@/App");
return { App, loaded };
}
async function readyShell() {
await screen.findByRole("button", { name: "Switch host" });
await act(async () => { TestSocket.current.open(); });
}
async function manageConnections() {
fireEvent.pointerDown(screen.getByRole("button", { name: "Switch host" }), { button: 0, ctrlKey: false });
fireEvent.click(await screen.findByRole("menuitem", { name: "Manage connections" }));
}
function managementSkeleton() {
const status = screen.getByText("Loading nanobot…", { selector: "[role=status]" });
const skeleton = status.closest("section");
expect(skeleton).toBeVisible();
expect(skeleton).toHaveAttribute("aria-busy", "true");
expect(skeleton).toHaveAttribute("data-startup-surface", "remote");
expect(skeleton).toHaveAttribute("data-embedded", "true");
return skeleton;
}
beforeEach(() => {
vi.resetModules();
localStorage.clear();
sessionStorage.clear();
window.history.replaceState(null, "", "/#/new");
vi.stubGlobal("WebSocket", TestSocket);
vi.stubGlobal("fetch", vi.fn(async (input: RequestInfo | URL) => {
const path = String(input);
if (path === "/api/remote-instances") return Response.json({ available: true, machine_name: "Local machine", profiles: [profile] });
if (path === "/api/sessions") return Response.json({ sessions: [] });
if (path === "/api/webui/sidebar-state") return Response.json({});
return new Response(null, { status: 404 });
}));
});
afterEach(async () => {
cleanup();
await finishManagementImport();
releaseManagement = undefined;
managementImport = undefined;
if (TestSocket.current) {
TestSocket.current.onclose = null;
TestSocket.current.close();
}
vi.doUnmock("@/components/remote/RemoteConnectionsPage");
vi.restoreAllMocks();
vi.unstubAllGlobals();
});
describe("lazy remote management", () => {
it("keeps chat and the host picker ready before loading management from the local menu", async () => {
const { App, loaded } = await loadApp();
expect(loaded).not.toHaveBeenCalled();
render(<App />);
await readyShell();
const draft = await screen.findByRole("textbox", { name: "Local draft" });
fireEvent.change(draft, { target: { value: "Keep my local draft" } });
fireEvent.pointerDown(screen.getByRole("button", { name: "Switch host" }), { button: 0, ctrlKey: false });
const host = await screen.findByRole("menuitem", { name: "Team server ubuntu@example.test" });
expect(within(host).getByRole("status")).toHaveTextContent("Disconnected");
expect(loaded).not.toHaveBeenCalled();
fireEvent.click(screen.getByRole("menuitem", { name: "Manage connections" }));
await screen.findByRole("heading", { name: "Remote connections" });
expect(loaded).toHaveBeenCalledTimes(1);
fireEvent.click(screen.getByRole("button", { name: "Back" }));
expect(screen.getByRole("textbox", { name: "Local draft" })).toBe(draft);
expect(draft).toHaveValue("Keep my local draft");
await manageConnections();
await screen.findByRole("heading", { name: "Remote connections" });
expect(loaded).toHaveBeenCalledTimes(1);
expect(TestSocket.current.sent.filter((frame) => frame.type === "webui_request" && frame.action.startsWith("remote."))).toEqual([]);
});
it("keeps the shell and local draft when the management import rejects, and can go back", async () => {
vi.spyOn(console, "error").mockImplementation(() => {});
const { App, loaded } = await loadApp(false, new Error("Failed to fetch dynamically imported module"));
render(<App />);
await readyShell();
const draft = await screen.findByRole("textbox", { name: "Local draft" });
fireEvent.change(draft, { target: { value: "Keep my draft after a chunk failure" } });
const hostPicker = screen.getByRole("button", { name: "Switch host" });
await manageConnections();
const alert = await screen.findByRole("alert");
expect(alert).toHaveTextContent("Couldn't load this view. Go back, or reload the page to try again.");
expect(screen.getByRole("button", { name: "Switch host" })).toBe(hostPicker);
expect(hostPicker).toBeVisible();
expect(draft).toBeInTheDocument();
expect(draft).toHaveValue("Keep my draft after a chunk failure");
fireEvent.click(screen.getByRole("button", { name: "Back" }));
expect(screen.queryByRole("alert")).not.toBeInTheDocument();
expect(screen.getByRole("textbox", { name: "Local draft" })).toBe(draft);
expect(draft).toBeVisible();
expect(draft).toHaveValue("Keep my draft after a chunk failure");
expect(loaded).toHaveBeenCalledTimes(1);
expect(TestSocket.current.sent.filter((frame) => frame.type === "webui_request" && frame.action.startsWith("remote."))).toEqual([]);
});
it("shows the existing skeleton on a cold remote route, then opens pairing and SSH controls", async () => {
window.history.replaceState(null, "", "/#/remote");
const { App, loaded } = await loadApp(true);
render(<App />);
await readyShell();
await waitFor(() => expect(loaded).toHaveBeenCalledTimes(1));
managementSkeleton();
await finishManagementImport();
await screen.findByRole("heading", { name: "Remote connections" });
fireEvent.click(screen.getByRole("button", { name: "Connect to remote nanobot" }));
await screen.findByText("nanobot remote pair nbpr1.test");
fireEvent.pointerDown(screen.getByRole("button", { name: "Other ways" }), { button: 0, ctrlKey: false });
fireEvent.click(screen.getByRole("menuitem", { name: "SSH connection" }));
expect(await screen.findByRole("textbox", { name: "SSH address" })).toBeVisible();
fireEvent.click(screen.getByRole("button", { name: "Cancel" }));
fireEvent.click(await screen.findByRole("button", { name: "Back to chat" }));
expect(await screen.findByRole("textbox", { name: "Local draft" })).toBeVisible();
expect(loaded).toHaveBeenCalledTimes(1);
});
it("can leave local management while its chunk is pending without reopening it on completion", async () => {
const { App, loaded } = await loadApp(true);
render(<App />);
await readyShell();
const draft = await screen.findByRole("textbox", { name: "Local draft" });
fireEvent.change(draft, { target: { value: "Unsent local draft" } });
await manageConnections();
await waitFor(() => expect(loaded).toHaveBeenCalledTimes(1));
managementSkeleton();
fireEvent.click(screen.getByRole("button", { name: "New topic" }));
expect(screen.getByRole("textbox", { name: "Local draft" })).toBe(draft);
expect(draft).toHaveValue("Unsent local draft");
await finishManagementImport();
expect(screen.queryByRole("region", { name: "Remote connections" })).not.toBeInTheDocument();
expect(screen.queryByText("Loading nanobot…")).not.toBeInTheDocument();
expect(TestSocket.current.sent.filter((frame) => frame.type === "webui_request" && frame.action.startsWith("remote."))).toEqual([]);
});
it("restores the host before loading management and preserves its frame, selection and route", async () => {
const { rememberSelectedRemote, readSelectedRemote } = await import("@/lib/remote-instances");
rememberSelectedRemote(connection);
const { App, loaded } = await loadApp(true);
render(<App />);
await readyShell();
const frame = await screen.findByTitle("nanobot on Team server");
await act(async () => { fireEvent.load(frame); });
await waitFor(() => expect(readSelectedRemote()?.id).toBe(profile.id));
expect(loaded).not.toHaveBeenCalled();
const hash = window.location.hash;
const title = document.title;
const requests = TestSocket.current.sent.filter((frame) => frame.type === "webui_request");
await manageConnections();
await waitFor(() => expect(loaded).toHaveBeenCalledTimes(1));
managementSkeleton();
expect(screen.getByTestId("remote-management-surface")).toBeVisible();
expect(screen.getByTitle("nanobot on Team server")).toBe(frame);
expect(readSelectedRemote()?.id).toBe(profile.id);
expect(window.location.hash).toBe(hash);
expect(document.title).toBe(title);
fireEvent.click(screen.getByRole("button", { name: "Back" }));
expect(frame).toBeVisible();
expect(readSelectedRemote()?.id).toBe(profile.id);
await manageConnections();
managementSkeleton();
await finishManagementImport();
const page = await screen.findByRole("region", { name: "Remote connections" });
const host = within(page).getByRole("button", { name: "Team server ubuntu@example.test" });
expect(host).toHaveAttribute("aria-current", "true");
expect(within(host).getByRole("status")).toHaveTextContent("Connected");
fireEvent.click(within(page).getByRole("button", { name: "Back" }));
expect(screen.getByTitle("nanobot on Team server")).toBe(frame);
expect(frame).toBeVisible();
expect(frame).toHaveAttribute("src", connection.url);
expect(readSelectedRemote()?.id).toBe(profile.id);
expect(window.location.hash).toBe(hash);
expect(document.title).toBe(title);
expect(TestSocket.current.sent.filter((frame) => frame.type === "webui_request")).toEqual(requests);
});
});
@@ -0,0 +1,97 @@
import { act, cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { SessionAutomationJob } from "@/lib/types";
const job: SessionAutomationJob = {
id: "job-1", name: "Morning check", enabled: true,
schedule: { kind: "every", every_ms: 3_600_000 },
payload: { message: "Check the project status" },
state: { next_run_at_ms: Date.now() + 3_600_000 },
};
let release: (() => void) | undefined;
let moduleLoad: Promise<unknown> | undefined;
async function loadView(fail = false) {
const loaded = vi.fn();
const gate = new Promise<void>((resolve) => { release = resolve; });
vi.doMock("@/components/settings/system/AutomationsSettings", (original) => {
loaded();
moduleLoad = gate.then(() => {
if (fail) throw new Error("Automation chunk unavailable");
return original<typeof import("@/components/settings/system/AutomationsSettings")>();
});
return moduleLoad;
});
const { initializeI18n, loadAllLocaleResources } = await import("@/i18n");
await initializeI18n();
await loadAllLocaleResources();
const { SessionInfoPopoverView } = await import("@/components/thread/SessionInfoPopoverView");
render(<><textarea aria-label="Unsent draft" defaultValue="Keep this draft" /><SessionInfoPopoverView
title="Release work" jobs={[job]} loading={false} loadFailed={false} now={Date.now()}
onAction={async () => []} onEdit={async () => [job]}
/></>);
return loaded;
}
async function selectJob() {
fireEvent.click(screen.getByRole("button", { name: "Session details" }));
fireEvent.click(await screen.findByRole("button", { name: /Morning check/ }));
return screen.findByRole("dialog", { name: "Morning check" });
}
beforeEach(() => { vi.resetModules(); localStorage.clear(); });
afterEach(async () => {
cleanup();
await act(async () => { release?.(); await moduleLoad?.catch(() => {}); });
release = undefined;
moduleLoad = undefined;
vi.doUnmock("@/components/settings/system/AutomationsSettings");
vi.restoreAllMocks();
});
describe("session automation dialog loading", () => {
it("loads only on inspection and replaces a named loading dialog with the real controls", async () => {
const loaded = await loadView();
await vi.dynamicImportSettled();
expect(loaded).not.toHaveBeenCalled();
fireEvent.click(screen.getByRole("button", { name: "Session details" }));
const row = await screen.findByRole("button", { name: /Morning check/ });
expect(loaded).not.toHaveBeenCalled();
fireEvent.click(row);
const pending = await screen.findByRole("dialog", { name: "Morning check" });
expect(within(pending).getByRole("status", { name: "Loading automations..." })).toHaveAttribute("aria-busy", "true");
await act(async () => { release?.(); await moduleLoad; });
await screen.findByText("Check the project status");
expect(screen.getAllByRole("dialog")).toHaveLength(1);
expect(screen.getByRole("button", { name: "Edit" })).toBeEnabled();
expect(screen.getByRole("textbox", { name: "Unsent draft", hidden: true })).toHaveValue("Keep this draft");
fireEvent.click(screen.getByRole("button", { name: "Close" }));
await waitFor(() => expect(screen.getByRole("button", { name: "Session details" })).toHaveFocus());
});
it("can close during download without a late dialog reopening", async () => {
const loaded = await loadView();
const dialog = await selectJob();
await waitFor(() => expect(loaded).toHaveBeenCalledOnce());
fireEvent.click(within(dialog).getByRole("button", { name: "Close" }));
await waitFor(() => expect(screen.getByRole("button", { name: "Session details" })).toHaveFocus());
await act(async () => { release?.(); await moduleLoad; });
expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
expect(screen.getByRole("textbox", { name: "Unsent draft", hidden: true })).toHaveValue("Keep this draft");
await selectJob();
expect(await screen.findByText("Check the project status")).toBeVisible();
expect(loaded).toHaveBeenCalledOnce();
});
it("contains a failed chunk in a closeable dialog without losing the chat draft", async () => {
vi.spyOn(console, "error").mockImplementation(() => {});
await loadView(true);
await selectJob();
await act(async () => { release?.(); await moduleLoad?.catch(() => {}); });
expect(await screen.findByRole("alert")).toHaveTextContent("Could not load automations.");
expect(screen.getByRole("textbox", { name: "Unsent draft", hidden: true })).toHaveValue("Keep this draft");
fireEvent.click(screen.getByRole("button", { name: "Close" }));
await waitFor(() => expect(screen.getByRole("button", { name: "Session details" })).toHaveFocus());
expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
});
});
@@ -77,6 +77,7 @@ describe("SessionInfoPopover", () => {
expect(screen.queryByText("Check the project status")).not.toBeInTheDocument();
await user.click(row);
await screen.findByText("Check the project status");
const detail = screen.getByRole("dialog", { name: "Morning check" });
expect(detail).toHaveClass("max-w-[520px]", "rounded-modal");
expect(within(detail).queryByText("Task instructions")).not.toBeInTheDocument();
@@ -131,6 +132,7 @@ describe("SessionInfoPopover", () => {
await user.click(screen.getByRole("button", { name: "Session details" }));
await user.click(await screen.findByRole("button", { name: /Morning check/ }));
await screen.findByText("Check the project status");
const detail = screen.getByRole("dialog", { name: "Morning check" });
await user.click(within(detail).getByRole("button", { name: "More actions" }));
await user.click(screen.getByRole("menuitem", { name: "Disable" }));
@@ -167,7 +169,7 @@ describe("SessionInfoPopover", () => {
await user.click(screen.getByRole("button", { name: "Session details" }));
await user.click(await screen.findByRole("button", { name: /Morning check/ }));
await user.click(screen.getByRole("button", { name: "Edit" }));
await user.click(await screen.findByRole("button", { name: "Edit" }));
const editor = await screen.findByRole("dialog", { name: "Edit task" });
expect(screen.getAllByRole("dialog")).toHaveLength(1);
await user.click(within(editor).getByRole("button", { name: "Cancel" }));
@@ -260,6 +262,7 @@ describe("SessionInfoPopover", () => {
const row = await screen.findByRole("button", { name: /PR monitor/ });
expect(screen.queryByText("Review PR #4591")).not.toBeInTheDocument();
await user.click(row);
await screen.findByText("Command");
const detail = screen.getByRole("dialog", { name: "PR monitor" });
expect(within(detail).getByText("Command")).toBeInTheDocument();
expect(within(detail).getByText('nanobot trigger trg_123 "message"')).toBeInTheDocument();