From 4bd1b74c6b069e2a7aff9faff36830e040df63c8 Mon Sep 17 00:00:00 2001 From: chengyongru <2755839590@qq.com> Date: Sat, 24 Oct 2026 20:30:26 +0800 Subject: [PATCH] perf(webui): defer non-chat startup interfaces --- webui/src/App.tsx | 6 +- webui/src/components/SurfaceErrorBoundary.tsx | 16 ++ .../remote/LazyRemoteConnectionsPage.tsx | 30 +++ .../src/components/remote/RemoteInstances.tsx | 4 +- .../channels/ChannelQrConnectFlowView.tsx | 18 +- .../thread/SessionInfoPopoverView.tsx | 122 +++++---- webui/src/i18n/locales/en/common.json | 3 +- webui/src/i18n/locales/es/common.json | 3 +- webui/src/i18n/locales/fr/common.json | 3 +- webui/src/i18n/locales/id/common.json | 3 +- webui/src/i18n/locales/ja/common.json | 3 +- webui/src/i18n/locales/ko/common.json | 3 +- webui/src/i18n/locales/pt-BR/common.json | 3 +- webui/src/i18n/locales/vi/common.json | 3 +- webui/src/i18n/locales/zh-CN/common.json | 3 +- webui/src/i18n/locales/zh-TW/common.json | 3 +- .../tests/channel-qr-connect-lazy.test.tsx | 197 ++++++++++++++ .../src/tests/lazy-remote-management.test.tsx | 255 ++++++++++++++++++ .../tests/session-automation-lazy.test.tsx | 97 +++++++ webui/src/tests/session-info-popover.test.tsx | 5 +- 20 files changed, 710 insertions(+), 70 deletions(-) create mode 100644 webui/src/components/SurfaceErrorBoundary.tsx create mode 100644 webui/src/components/remote/LazyRemoteConnectionsPage.tsx create mode 100644 webui/src/tests/channel-qr-connect-lazy.test.tsx create mode 100644 webui/src/tests/lazy-remote-management.test.tsx create mode 100644 webui/src/tests/session-automation-lazy.test.tsx diff --git a/webui/src/App.tsx b/webui/src/App.tsx index 280dbd82c..cf2ffbb80 100644 --- a/webui/src/App.tsx +++ b/webui/src/App.tsx @@ -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({ } {view !== "chat" && (
- {view === "remote" ? {managingConnections && !remoteConnections?.embeddedManagement &&
- remoteConnections?.closeManagement()} diff --git a/webui/src/components/SurfaceErrorBoundary.tsx b/webui/src/components/SurfaceErrorBoundary.tsx new file mode 100644 index 000000000..64526a36b --- /dev/null +++ b/webui/src/components/SurfaceErrorBoundary.tsx @@ -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; + } +} diff --git a/webui/src/components/remote/LazyRemoteConnectionsPage.tsx b/webui/src/components/remote/LazyRemoteConnectionsPage.tsx new file mode 100644 index 000000000..a08236768 --- /dev/null +++ b/webui/src/components/remote/LazyRemoteConnectionsPage.tsx @@ -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) { + const { t } = useTranslation(); + return +

{t("app.loading.failed")}

+ +
+ }> + + + +
+ }> + + + ; +} diff --git a/webui/src/components/remote/RemoteInstances.tsx b/webui/src/components/remote/RemoteInstances.tsx index 092bc4a79..1e291428b 100644 --- a/webui/src/components/remote/RemoteInstances.tsx +++ b/webui/src/components/remote/RemoteInstances.tsx @@ -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)) }}> - changeManagement(false)} mainNavigationExpanded={!!bridge.surface?.left} /> + changeManagement(false)} mainNavigationExpanded={!!bridge.surface?.left} /> } {!managing && selected && (offline || !activeFrame?.loaded) &&
diff --git a/webui/src/components/settings/channels/ChannelQrConnectFlowView.tsx b/webui/src/components/settings/channels/ChannelQrConnectFlowView.tsx index a984bd9b9..6994974f5 100644 --- a/webui/src/components/settings/channels/ChannelQrConnectFlowView.tsx +++ b/webui/src/components/settings/channels/ChannelQrConnectFlowView.tsx @@ -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(() => { diff --git a/webui/src/components/thread/SessionInfoPopoverView.tsx b/webui/src/components/thread/SessionInfoPopoverView.tsx index 7c0bc74fb..5a42d7377 100644 --- a/webui/src/components/thread/SessionInfoPopoverView.tsx +++ b/webui/src/components/thread/SessionInfoPopoverView.tsx @@ -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(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(null); const [actionError, setActionError] = useState(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) => ( + + + {selectedJob?.name || selectedJob?.id} + {failed ?

{t("thread.sessionInfo.loadFailed")}

: ( + +
+ + )} + +
+ ); const automationContent = loading && jobs.length === 0 ? ( {[0, 1, 2].map((index) =>
@@ -203,46 +237,42 @@ export function SessionInfoPopoverView({ title, jobs, loading, loadFailed, now, - 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?.(); - }} - /> - { - if (!nextOpen) setPendingEdit(null); - }} - onCancel={(job) => { - setInspectedJob(job); - setDetailOpen(true); - }} - onSave={handleEdit} - /> - { - if (!nextOpen) setPendingDelete(null); - }} - onConfirm={(job) => handleAction("delete", job)} - /> + {dialogsRequested ? + + handOffDetail(() => setPendingEdit(job))} + onRequestDelete={(job) => handOffDetail(() => setPendingDelete(job))} + onCloseAutoFocus={handleDetailCloseAutoFocus} + /> + { + if (!nextOpen) setPendingEdit(null); + }} + onCancel={(job) => { + setInspectedJob(job); + setDetailOpen(true); + }} + onSave={handleEdit} + /> + { + if (!nextOpen) setPendingDelete(null); + }} + onConfirm={(job) => handleAction("delete", job)} + /> + + : null} ); } diff --git a/webui/src/i18n/locales/en/common.json b/webui/src/i18n/locales/en/common.json index 16ba38897..6358bcc46 100644 --- a/webui/src/i18n/locales/en/common.json +++ b/webui/src/i18n/locales/en/common.json @@ -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", diff --git a/webui/src/i18n/locales/es/common.json b/webui/src/i18n/locales/es/common.json index 0e583d542..3ea246e84 100644 --- a/webui/src/i18n/locales/es/common.json +++ b/webui/src/i18n/locales/es/common.json @@ -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", diff --git a/webui/src/i18n/locales/fr/common.json b/webui/src/i18n/locales/fr/common.json index c830cc3ba..45c576676 100644 --- a/webui/src/i18n/locales/fr/common.json +++ b/webui/src/i18n/locales/fr/common.json @@ -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", diff --git a/webui/src/i18n/locales/id/common.json b/webui/src/i18n/locales/id/common.json index 75691c77f..7dfd64242 100644 --- a/webui/src/i18n/locales/id/common.json +++ b/webui/src/i18n/locales/id/common.json @@ -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", diff --git a/webui/src/i18n/locales/ja/common.json b/webui/src/i18n/locales/ja/common.json index b3a8321f7..30cad0c5f 100644 --- a/webui/src/i18n/locales/ja/common.json +++ b/webui/src/i18n/locales/ja/common.json @@ -372,7 +372,8 @@ "brand": "nanobot", "loading": { "connecting": "nanobot に接続中…", - "boot": "nanobot を読み込み中…" + "boot": "nanobot を読み込み中…", + "failed": "この画面を読み込めませんでした。戻るか、ページを再読み込みしてお試しください。" }, "error": { "title": "nanobot に接続できませんでした", diff --git a/webui/src/i18n/locales/ko/common.json b/webui/src/i18n/locales/ko/common.json index 151736425..88f71ab9a 100644 --- a/webui/src/i18n/locales/ko/common.json +++ b/webui/src/i18n/locales/ko/common.json @@ -372,7 +372,8 @@ "brand": "nanobot", "loading": { "connecting": "nanobot에 연결 중…", - "boot": "nanobot 불러오는 중…" + "boot": "nanobot 불러오는 중…", + "failed": "이 화면을 불러오지 못했습니다. 뒤로 가거나 페이지를 새로고침하여 다시 시도하세요." }, "error": { "title": "nanobot에 연결할 수 없습니다", diff --git a/webui/src/i18n/locales/pt-BR/common.json b/webui/src/i18n/locales/pt-BR/common.json index 456a73ef1..09c189734 100644 --- a/webui/src/i18n/locales/pt-BR/common.json +++ b/webui/src/i18n/locales/pt-BR/common.json @@ -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", diff --git a/webui/src/i18n/locales/vi/common.json b/webui/src/i18n/locales/vi/common.json index 7d7be6b24..9556586d0 100644 --- a/webui/src/i18n/locales/vi/common.json +++ b/webui/src/i18n/locales/vi/common.json @@ -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", diff --git a/webui/src/i18n/locales/zh-CN/common.json b/webui/src/i18n/locales/zh-CN/common.json index 4b4479fc1..4260fc6d1 100644 --- a/webui/src/i18n/locales/zh-CN/common.json +++ b/webui/src/i18n/locales/zh-CN/common.json @@ -372,7 +372,8 @@ "brand": "nanobot", "loading": { "connecting": "正在连接 nanobot…", - "boot": "正在加载 nanobot…" + "boot": "正在加载 nanobot…", + "failed": "无法加载此页面。请返回,或刷新页面重试。" }, "error": { "title": "无法连接到 nanobot", diff --git a/webui/src/i18n/locales/zh-TW/common.json b/webui/src/i18n/locales/zh-TW/common.json index e3599311c..a35780a22 100644 --- a/webui/src/i18n/locales/zh-TW/common.json +++ b/webui/src/i18n/locales/zh-TW/common.json @@ -372,7 +372,8 @@ "brand": "nanobot", "loading": { "connecting": "正在連線到 nanobot…", - "boot": "正在載入 nanobot…" + "boot": "正在載入 nanobot…", + "failed": "無法載入此頁面。請返回,或重新整理頁面再試。" }, "error": { "title": "無法連線到 nanobot", diff --git a/webui/src/tests/channel-qr-connect-lazy.test.tsx b/webui/src/tests/channel-qr-connect-lazy.test.tsx new file mode 100644 index 000000000..a6019e495 --- /dev/null +++ b/webui/src/tests/channel-qr-connect-lazy.test.tsx @@ -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() { + let resolve!: (value: T) => void; + let reject!: (error: Error) => void; + const promise = new Promise((res, rej) => { resolve = res; reject = rej; }); + return { promise, resolve, reject }; +} + +function mockQrModule(ready: Promise = Promise.resolve()) { + const toDataURL = vi.fn<(text: string, options: QRCodeToDataURLOptions) => Promise>() + .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("qrcode"); + return actual.toDataURL(text, options); + }); + const View = await loadView(); + const view = render(); + await vi.dynamicImportSettled(); + expect(load).not.toHaveBeenCalled(); + expect(toDataURL).not.toHaveBeenCalled(); + + view.rerender(); + await vi.dynamicImportSettled(); + expect(screen.getByRole("status")).toHaveTextContent("Connecting"); + expect(load).not.toHaveBeenCalled(); + expect(toDataURL).not.toHaveBeenCalled(); + + view.rerender(); + 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(); + 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(); + const { toDataURL, load } = mockQrModule(ready.promise); + const View = await loadView(); + const view = render(); + await waitFor(() => expect(load).toHaveBeenCalledOnce()); + if (change === "unmounted") { + view.unmount(); + } else { + view.rerender(); + } + + 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(); + const current = deferred(); + const { toDataURL } = mockQrModule(); + toDataURL.mockReturnValueOnce(stale.promise).mockReturnValueOnce(current.promise); + const View = await loadView(); + const view = render(); + await waitFor(() => expect(toDataURL).toHaveBeenCalledTimes(1)); + view.rerender(); + 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(); + const current = deferred(); + const { toDataURL } = mockQrModule(); + toDataURL.mockReturnValueOnce(stale.promise).mockReturnValueOnce(current.promise); + const View = await loadView(); + const view = render(); + await waitFor(() => expect(toDataURL).toHaveBeenCalledTimes(1)); + view.rerender(); + await act(async () => { stale.resolve("data:image/png;base64,stale"); }); + view.rerender(); + 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(); + 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(); + }); +}); diff --git a/webui/src/tests/lazy-remote-management.test.tsx b/webui/src/tests/lazy-remote-management.test.tsx new file mode 100644 index 000000000..7410c6708 --- /dev/null +++ b/webui/src/tests/lazy-remote-management.test.tsx @@ -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(), + 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: () =>