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) => (
+
+ );
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: () => ,
+}));
+
+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 | 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((resolve) => { releaseManagement = resolve; });
+ vi.doMock("@/components/remote/RemoteConnectionsPage", (original) => {
+ loaded();
+ if (importError) return Promise.reject(importError);
+ managementImport = (async () => {
+ if (deferManagement) await gate;
+ return original();
+ })();
+ 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();
+ 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();
+ 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();
+ 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();
+ 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();
+ 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);
+ });
+});
diff --git a/webui/src/tests/session-automation-lazy.test.tsx b/webui/src/tests/session-automation-lazy.test.tsx
new file mode 100644
index 000000000..25fb15fdc
--- /dev/null
+++ b/webui/src/tests/session-automation-lazy.test.tsx
@@ -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 | undefined;
+
+async function loadView(fail = false) {
+ const loaded = vi.fn();
+ const gate = new Promise((resolve) => { release = resolve; });
+ vi.doMock("@/components/settings/system/AutomationsSettings", (original) => {
+ loaded();
+ moduleLoad = gate.then(() => {
+ if (fail) throw new Error("Automation chunk unavailable");
+ return original();
+ });
+ return moduleLoad;
+ });
+ const { initializeI18n, loadAllLocaleResources } = await import("@/i18n");
+ await initializeI18n();
+ await loadAllLocaleResources();
+ const { SessionInfoPopoverView } = await import("@/components/thread/SessionInfoPopoverView");
+ render(<> []} 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();
+ });
+});
diff --git a/webui/src/tests/session-info-popover.test.tsx b/webui/src/tests/session-info-popover.test.tsx
index baa151044..eacd03fce 100644
--- a/webui/src/tests/session-info-popover.test.tsx
+++ b/webui/src/tests/session-info-popover.test.tsx
@@ -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();