Your lightweight open-source personal agent.
Python agent-frameworkai-agentai-agentschatbotchatopsdiscord-botllm-agentsllmslocal-llmmcpmodel-context-protocolmulti-agentopenai-compatibleopenclawpersonal-ai-assistantpythonself-hostedtelegram-bot-ai-assistantwebuiworkflow-automation
fix(remote): wait for local transport before reviewing pairing links
Xubin Ren83a131c20753
diff --git a/webui/src/components/remote/QuickPairSetup.tsx b/webui/src/components/remote/QuickPairSetup.tsxindex 8ffa004e7..17fdbebb2 100644--- a/webui/src/components/remote/QuickPairSetup.tsx+++ b/webui/src/components/remote/QuickPairSetup.tsx@@ -10,6 +10,7 @@ import { useClient } from "@/providers/ClientProvider";import { copyTextToClipboard } from "@/lib/clipboard";import { remoteAction } from "@/lib/remote-instances";import { pairingReturnOrigin, type PairReturn } from "@/lib/remote-pair-return";+import type { ConnectionStatus } from "@/lib/types";import { useRemoteConnections } from "./RemoteInstances";import { PairRouteSettings } from "./PairRouteSettings";@@ -28,6 +29,7 @@ export function QuickPairSetup({ returned, onSSH, onClose }: { returned?: PairReconst [busy, setBusy] = useState(false);const [busyVisible, setBusyVisible] = useState(false);const [error, setError] = useState("");+ const [status, setStatus] = useState<ConnectionStatus>(client.status);const [copied, setCopied] = useState(false);const [expired, setExpired] = useState(false);const [manual, setManual] = useState(false);@@ -39,13 +41,17 @@ export function QuickPairSetup({ returned, onSSH, onClose }: { returned?: PairReconst focusManual = useRef(false);const codeId = useId();const panelId = useId();+ const waitingForLocal = status !== "open";+ const pending = busy || (waitingForLocal && !error);++ useEffect(() => client.onStatus(setStatus), [client]);useEffect(() => {- if (!busy) { setBusyVisible(false); return; }+ if (!pending) { setBusyVisible(false); return; }// Fast local preparation should not flash a loading label or move the dialog.const timer = window.setTimeout(() => setBusyVisible(true), 200);return () => window.clearTimeout(timer);- }, [busy]);+ }, [pending]);useEffect(() => {alive.current = true;@@ -66,7 +72,8 @@ export function QuickPairSetup({ returned, onSSH, onClose }: { returned?: PairResetBusy(true); setError("");try { await action(); }catch (reason) {- if (alive.current) setError(t(`remote.errors.${reason instanceof Error ? reason.message : "unknown"}`, { defaultValue: t("remote.errors.unknown") }));+ const localFailure = reason instanceof Error && "status" in reason && [503, 504].includes(Number(reason.status));+ if (alive.current) setError(`remote.errors.${localFailure ? "local_connection_unavailable" : reason instanceof Error ? reason.message : "unknown"}`);} finally { if (alive.current) setBusy(false); }};const start = () => run(async () => {@@ -98,31 +105,38 @@ export function QuickPairSetup({ returned, onSSH, onClose }: { returned?: PairReuseEffect(() => {if (initialized.current) return;+ // A return link mounts immediately after bootstrap, before the local socket+ // opens. Wait for it; rejecting here would mislabel a valid link as invalid.+ if (status !== "open") {+ const timer = window.setTimeout(() => setError("remote.errors.local_connection_unavailable"), 10_000);+ return () => window.clearTimeout(timer);+ }initialized.current = true;if (returned) void review();else void start();// One invitation per mounted dialog, never one per re-render. The returned// receipt is reviewed only; saving/connecting still requires a user click.- }, []);+ }, [status]);const copyCommand = () => {if (!request) return;void copyTextToClipboard(request.command).then((ok) => {if (!alive.current || requestId.current !== request.id || Date.now() >= request.expires * 1000) return;if (ok) { setCopied(true); setError(""); setPanel(null); }- else { setPanel("command"); setError(t("remote.pair.copyFailed")); }+ else { setPanel("command"); setError("remote.pair.copyFailed"); }});};- const restartAvailable = !saved && (expired || (!!error && !request?.command && !preview));+ const invalidReturn = ["pair_invalid", "pair_expired", "pair_used"].some((code) => error === `remote.errors.${code}`);+ const restartAvailable = !saved && (expired || (!!error && !request?.command && !preview && (!returned || invalidReturn)));const reviewingReturn = !!returned && !request?.command && !preview && !manual && !restartAvailable;const title = preview ? "remote.pair.confirmTitle" : reviewingReturn ? "remote.pair.review" : restartAvailable ? "remote.add": manual ? "remote.pair.code" : copied ? "remote.pair.copiedTitle" : "remote.add";const description = preview || reviewingReturn ? "remote.pair.confirmLinkDescription" : restartAvailable ? "remote.pair.introHint": manual ? "remote.pair.codeHint" : copied ? "remote.pair.afterCopyHint" : "remote.pair.introHint";const showCopied = copied && !manual && !preview && !restartAvailable;- const showBusy = busy && busyVisible;- const actionLabel = restartAvailable ? "remote.pair.restart" : reviewingReturn ? "remote.pair.review" : preview ? saved ? "remote.retry" : "remote.connect"+ const showBusy = pending && busyVisible;+ const actionLabel = restartAvailable ? "remote.pair.restart" : reviewingReturn ? error ? "remote.retry" : "remote.pair.review" : preview ? saved ? "remote.retry" : "remote.connect": manual ? "remote.pair.review" : copied ? "remote.pair.copyAgain" : "remote.pair.copy";- const busyLabel = preview ? "remote.connecting" : !restartAvailable && (manual || returned)+ const busyLabel = waitingForLocal ? "remote.pair.waitingForLocal" : preview ? "remote.connecting" : !restartAvailable && (manual || returned)? "remote.pair.checkingLink" : "remote.pair.preparing";return <>@@ -180,13 +194,13 @@ export function QuickPairSetup({ returned, onSSH, onClose }: { returned?: PairRe</div></>}{expired && !saved && <p role="status" className="text-xs leading-5 text-muted-foreground">{t("remote.pair.expired")}</p>}- {error && <p role="alert" className="flex items-start gap-2 text-[13px] leading-5 text-foreground"><AlertCircle aria-hidden="true" className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" />{error}</p>}+ {error && <p role="alert" className="flex items-start gap-2 text-[13px] leading-5 text-foreground"><AlertCircle aria-hidden="true" className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" />{t(error, { defaultValue: t("remote.errors.unknown") })}</p>}</div><div className={preview ? "flex shrink-0 flex-col-reverse gap-2 pt-1 sm:flex-row sm:items-center sm:justify-between" : "flex shrink-0 flex-col gap-2 pt-1"}>{preview && (!saved ? <Button variant="ghost" disabled={busy} onClick={() => { setPreview(null); setError(""); if (!request?.command) setManual(true); }}><ArrowLeft className="mr-1 h-4 w-4" />{t("remote.back")}</Button>: <Button variant="ghost" onClick={() => { connections?.cancel(); onClose(); }}>{t("common.cancel")}</Button>)}- <Button variant={showCopied ? "outline" : "default"} className={showCopied ? "bg-transparent" : undefined} aria-label={t(showBusy ? busyLabel : actionLabel)} aria-busy={busy} disabled={busy || (!restartAvailable && (!request || (!preview && (manual ? !code.trim() : !request.command))))} onClick={() => { if (restartAvailable) void start(); else if (preview) void connect(); else if (manual) void review(); else copyCommand(); }}>+ <Button variant={showCopied ? "outline" : "default"} className={showCopied ? "bg-transparent" : undefined} aria-label={t(showBusy ? busyLabel : actionLabel)} aria-busy={pending} disabled={busy || waitingForLocal || (!restartAvailable && (!request || (!preview && (manual || reviewingReturn ? !code.trim() : !request.command))))} onClick={() => { if (restartAvailable) void start(); else if (preview) void connect(); else if (manual || reviewingReturn) void review(); else copyCommand(); }}>{showBusy ? <Loader2 aria-hidden="true" className="mr-2 h-4 w-4 shrink-0 animate-spin motion-reduce:animate-none" /> : !restartAvailable && !preview && !manual && !reviewingReturn ? <Copy aria-hidden="true" className="mr-2 h-4 w-4 shrink-0" /> : null}<span role="status" className="min-w-0 truncate">{t(showBusy ? busyLabel : actionLabel)}</span></Button>diff --git a/webui/src/i18n/locales/en/common.json b/webui/src/i18n/locales/en/common.jsonindex 8f2db358b..67869f43a 100644--- a/webui/src/i18n/locales/en/common.json+++ b/webui/src/i18n/locales/en/common.json@@ -3,6 +3,7 @@"activeForgetWarning": "All tabs using this connection will disconnect. Unsaved work may be lost.","saved": "Saved","pair": {+ "waitingForLocal": "Connecting to local nanobot…","expiringDevice": "Authorization expires {{date}}.","expiredDevice": "Authorization expired. Pair this server again before reconnecting.","introHint": "Run one command in your server terminal to connect.",@@ -145,6 +146,7 @@"forgetTitle": "Forget {{name}}?","forgetDescription": "Only this saved connection will be removed. nanobot, its keys and conversations on the server will stay untouched.","errors": {+ "local_connection_unavailable": "Couldn't reach local nanobot on this computer. Keep it running and try again.","disconnected": "This shared connection was closed. Reconnect when you’re ready.","instance_changed": "This server connection changed. Reconnecting will reload its view; unsent drafts may be lost.","pair_authorization_rejected": "The server no longer accepts this device key. Its authorization may have been revoked or expired. Pair again from your server console.",diff --git a/webui/src/i18n/locales/es/common.json b/webui/src/i18n/locales/es/common.jsonindex 0e95d3009..eea6f1865 100644--- a/webui/src/i18n/locales/es/common.json+++ b/webui/src/i18n/locales/es/common.json@@ -3,6 +3,7 @@"activeForgetWarning": "Se desconectarán todas las pestañas que usen esta conexión. El trabajo sin guardar puede perderse.","saved": "Guardado","pair": {+ "waitingForLocal": "Conectando con nanobot en este equipo…","expiringDevice": "La autorización vence el {{date}}.","expiredDevice": "La autorización ha vencido. Vuelve a emparejar este servidor antes de reconectar.","introHint": "Ejecuta un comando en la terminal de tu servidor para conectarte.",@@ -145,6 +146,7 @@"forgetTitle": "Forget {{name}}?","forgetDescription": "Only this saved connection will be removed. nanobot, its keys and conversations on the server will stay untouched.","errors": {+ "local_connection_unavailable": "No se pudo conectar con nanobot en este equipo. Comprueba que esté en ejecución e inténtalo de nuevo.","disconnected": "Esta conexión compartida se cerró. Reconecta cuando quieras.","instance_changed": "La conexión a este servidor cambió. Al reconectar se recargará la vista; los borradores sin enviar podrían perderse.","pair_authorization_rejected": "El servidor ya no acepta la clave de este dispositivo. La autorización puede haberse revocado o caducado. Vuelve a emparejar desde la consola del servidor.",diff --git a/webui/src/i18n/locales/fr/common.json b/webui/src/i18n/locales/fr/common.jsonindex 8a413bc6e..47c780e24 100644--- a/webui/src/i18n/locales/fr/common.json+++ b/webui/src/i18n/locales/fr/common.json@@ -3,6 +3,7 @@"activeForgetWarning": "Tous les onglets utilisant cette connexion seront déconnectés. Le travail non enregistré peut être perdu.","saved": "Enregistré","pair": {+ "waitingForLocal": "Connexion à nanobot sur cet ordinateur…","expiringDevice": "L’autorisation expire le {{date}}.","expiredDevice": "L’autorisation a expiré. Associez à nouveau ce serveur avant de vous reconnecter.","introHint": "Exécutez une commande dans le terminal du serveur pour vous connecter.",@@ -145,6 +146,7 @@"forgetTitle": "Forget {{name}}?","forgetDescription": "Only this saved connection will be removed. nanobot, its keys and conversations on the server will stay untouched.","errors": {+ "local_connection_unavailable": "Impossible de joindre nanobot sur cet ordinateur. Vérifiez qu’il est en cours d’exécution, puis réessayez.","disconnected": "Cette connexion partagée a été fermée. Reconnectez-vous quand vous le souhaitez.","instance_changed": "La connexion à ce serveur a changé. La reconnexion rechargera la vue ; les brouillons non envoyés risquent d’être perdus.","pair_authorization_rejected": "Le serveur n’accepte plus la clé de cet appareil. L’autorisation a peut-être été révoquée ou a expiré. Relancez l’association depuis la console du serveur.",diff --git a/webui/src/i18n/locales/id/common.json b/webui/src/i18n/locales/id/common.jsonindex 844fec2a5..0fcf60c98 100644--- a/webui/src/i18n/locales/id/common.json+++ b/webui/src/i18n/locales/id/common.json@@ -3,6 +3,7 @@"activeForgetWarning": "Semua tab yang memakai koneksi ini akan terputus. Pekerjaan yang belum disimpan dapat hilang.","saved": "Tersimpan","pair": {+ "waitingForLocal": "Menghubungkan ke nanobot di komputer ini…","expiringDevice": "Otorisasi berakhir pada {{date}}.","expiredDevice": "Otorisasi telah berakhir. Pasangkan ulang server ini sebelum menyambungkan kembali.","introHint": "Jalankan satu perintah di terminal server untuk terhubung.",@@ -145,6 +146,7 @@"forgetTitle": "Forget {{name}}?","forgetDescription": "Only this saved connection will be removed. nanobot, its keys and conversations on the server will stay untouched.","errors": {+ "local_connection_unavailable": "Tidak dapat terhubung ke nanobot di komputer ini. Pastikan nanobot berjalan, lalu coba lagi.","disconnected": "Koneksi bersama ini telah ditutup. Sambungkan kembali saat Anda siap.","instance_changed": "Koneksi server ini berubah. Menyambungkan kembali akan memuat ulang tampilan; draf yang belum dikirim dapat hilang.","pair_authorization_rejected": "Server tidak lagi menerima kunci perangkat ini. Otorisasinya mungkin dicabut atau kedaluwarsa. Pasangkan kembali melalui konsol server.",diff --git a/webui/src/i18n/locales/ja/common.json b/webui/src/i18n/locales/ja/common.jsonindex 9a90b8529..f73dbc0c0 100644--- a/webui/src/i18n/locales/ja/common.json+++ b/webui/src/i18n/locales/ja/common.json@@ -3,6 +3,7 @@"activeForgetWarning": "この接続を使用しているすべてのタブが切断されます。未保存の内容が失われる可能性があります。","saved": "保存済み","pair": {+ "waitingForLocal": "このコンピューターの nanobot に接続しています…","expiringDevice": "認証は {{date}} に期限切れになります。","expiredDevice": "認証の期限が切れました。再接続する前にペアリングし直してください。","introHint": "サーバーのターミナルでコマンドを実行して接続します。",@@ -145,6 +146,7 @@"forgetTitle": "Forget {{name}}?","forgetDescription": "Only this saved connection will be removed. nanobot, its keys and conversations on the server will stay untouched.","errors": {+ "local_connection_unavailable": "このコンピューターの nanobot に接続できませんでした。起動していることを確認して、もう一度お試しください。","disconnected": "この共有接続は閉じられました。必要なときに再接続できます。","instance_changed": "このサーバーへの接続が変わりました。再接続すると画面が再読み込みされ、未送信の下書きが失われる場合があります。","pair_authorization_rejected": "サーバーがこのデバイスの鍵を受け付けなくなりました。認可が取り消されたか期限切れの可能性があります。サーバーのコンソールから再度ペアリングしてください。",diff --git a/webui/src/i18n/locales/ko/common.json b/webui/src/i18n/locales/ko/common.jsonindex fccb4cac4..b33982c5b 100644--- a/webui/src/i18n/locales/ko/common.json+++ b/webui/src/i18n/locales/ko/common.json@@ -3,6 +3,7 @@"activeForgetWarning": "이 연결을 사용하는 모든 탭의 연결이 끊어집니다. 저장하지 않은 내용이 손실될 수 있습니다.","saved": "저장됨","pair": {+ "waitingForLocal": "이 컴퓨터의 nanobot에 연결 중…","expiringDevice": "인증이 {{date}}에 만료됩니다.","expiredDevice": "인증이 만료되었습니다. 다시 연결하기 전에 서버를 다시 페어링하세요.","introHint": "서버 터미널에서 명령어를 실행해 연결하세요.",@@ -145,6 +146,7 @@"forgetTitle": "Forget {{name}}?","forgetDescription": "Only this saved connection will be removed. nanobot, its keys and conversations on the server will stay untouched.","errors": {+ "local_connection_unavailable": "이 컴퓨터의 nanobot에 연결하지 못했습니다. 실행 중인지 확인한 후 다시 시도하세요.","disconnected": "공유 연결이 종료되었습니다. 준비되면 다시 연결하세요.","instance_changed": "이 서버 연결이 변경되었습니다. 다시 연결하면 화면이 새로고침되어 보내지 않은 초안이 사라질 수 있습니다.","pair_authorization_rejected": "서버가 이 기기의 키를 더 이상 허용하지 않습니다. 권한이 취소되었거나 만료되었을 수 있습니다. 서버 콘솔에서 다시 페어링하세요.",diff --git a/webui/src/i18n/locales/pt-BR/common.json b/webui/src/i18n/locales/pt-BR/common.jsonindex ff2051765..4f6a798c2 100644--- a/webui/src/i18n/locales/pt-BR/common.json+++ b/webui/src/i18n/locales/pt-BR/common.json@@ -3,6 +3,7 @@"activeForgetWarning": "Todas as abas que usam esta conexão serão desconectadas. O trabalho não salvo pode ser perdido.","saved": "Salvo","pair": {+ "waitingForLocal": "Conectando ao nanobot neste computador…","expiringDevice": "A autorização expira em {{date}}.","expiredDevice": "A autorização expirou. Pareie este servidor novamente antes de reconectar.","introHint": "Execute um comando no terminal do servidor para conectar.",@@ -145,6 +146,7 @@"forgetTitle": "Forget {{name}}?","forgetDescription": "Only this saved connection will be removed. nanobot, its keys and conversations on the server will stay untouched.","errors": {+ "local_connection_unavailable": "Não foi possível acessar o nanobot neste computador. Verifique se ele está em execução e tente novamente.","disconnected": "Esta conexão compartilhada foi fechada. Reconecte quando quiser.","instance_changed": "A conexão com este servidor mudou. A reconexão recarregará a tela; rascunhos não enviados poderão ser perdidos.","pair_authorization_rejected": "O servidor não aceita mais a chave deste dispositivo. A autorização pode ter sido revogada ou expirado. Faça o pareamento novamente no console do servidor.",diff --git a/webui/src/i18n/locales/vi/common.json b/webui/src/i18n/locales/vi/common.jsonindex e922a4813..d2e271e58 100644--- a/webui/src/i18n/locales/vi/common.json+++ b/webui/src/i18n/locales/vi/common.json@@ -3,6 +3,7 @@"activeForgetWarning": "Tất cả thẻ đang dùng kết nối này sẽ bị ngắt. Nội dung chưa lưu có thể bị mất.","saved": "Đã lưu","pair": {+ "waitingForLocal": "Đang kết nối với nanobot trên máy tính này…","expiringDevice": "Quyền truy cập hết hạn vào {{date}}.","expiredDevice": "Quyền truy cập đã hết hạn. Hãy ghép nối lại máy chủ trước khi kết nối lại.","introHint": "Chạy một lệnh trong terminal máy chủ để kết nối.",@@ -145,6 +146,7 @@"forgetTitle": "Forget {{name}}?","forgetDescription": "Only this saved connection will be removed. nanobot, its keys and conversations on the server will stay untouched.","errors": {+ "local_connection_unavailable": "Không thể kết nối với nanobot trên máy tính này. Hãy đảm bảo nanobot đang chạy rồi thử lại.","disconnected": "Kết nối dùng chung này đã đóng. Bạn có thể kết nối lại khi sẵn sàng.","instance_changed": "Kết nối đến máy chủ này đã thay đổi. Kết nối lại sẽ tải lại giao diện; bản nháp chưa gửi có thể bị mất.","pair_authorization_rejected": "Máy chủ không còn chấp nhận khóa của thiết bị này. Quyền truy cập có thể đã bị thu hồi hoặc hết hạn. Hãy ghép nối lại từ bảng điều khiển máy chủ.",diff --git a/webui/src/i18n/locales/zh-CN/common.json b/webui/src/i18n/locales/zh-CN/common.jsonindex d5759da37..665dcfeea 100644--- a/webui/src/i18n/locales/zh-CN/common.json+++ b/webui/src/i18n/locales/zh-CN/common.json@@ -3,6 +3,7 @@"activeForgetWarning": "也会断开正在使用此连接的标签页,未保存的内容可能丢失。","saved": "已保存","pair": {+ "waitingForLocal": "正在连接本机 nanobot…","expiringDevice": "授权将于 {{date}} 到期。","expiredDevice": "授权已到期,重新连接前请再次配对。","introHint": "在服务器终端运行一条命令,即可开始连接。",@@ -145,6 +146,7 @@"forgetTitle": "忘记 {{name}}?","forgetDescription": "只移除本机保存的连接。服务器上的 nanobot、密钥和会话都不会被删除。","errors": {+ "local_connection_unavailable": "暂时无法连接这台电脑上的 nanobot,请确保它正在运行后重试。","disconnected": "此共享连接已断开,需要时可重新连接。","instance_changed": "此服务器的连接已发生变化。重新连接会重新打开页面,未发送的草稿可能丢失。","pair_authorization_rejected": "服务器不再接受这台设备的密钥,授权可能已撤销或过期。请从服务器终端重新配对。",diff --git a/webui/src/i18n/locales/zh-TW/common.json b/webui/src/i18n/locales/zh-TW/common.jsonindex d144ce3d8..aee05a94a 100644--- a/webui/src/i18n/locales/zh-TW/common.json+++ b/webui/src/i18n/locales/zh-TW/common.json@@ -3,6 +3,7 @@"activeForgetWarning": "也會中斷正在使用此連線的分頁,未儲存的內容可能遺失。","saved": "已儲存","pair": {+ "waitingForLocal": "正在連線到本機 nanobot…","expiringDevice": "授權將於 {{date}} 到期。","expiredDevice": "授權已到期,重新連線前請再次配對。","introHint": "在伺服器終端執行一條指令,即可開始連線。",@@ -145,6 +146,7 @@"forgetTitle": "Forget {{name}}?","forgetDescription": "Only this saved connection will be removed. nanobot, its keys and conversations on the server will stay untouched.","errors": {+ "local_connection_unavailable": "暫時無法連線到這台電腦上的 nanobot,請確認它正在執行後重試。","disconnected": "此共用連線已中斷,需要時可重新連線。","instance_changed": "此伺服器的連線已發生變化。重新連線會重新開啟頁面,未傳送的草稿可能遺失。","pair_authorization_rejected": "伺服器不再接受這台裝置的金鑰,授權可能已撤銷或過期。請從伺服器終端重新配對。",diff --git a/webui/src/tests/quick-pair.test.tsx b/webui/src/tests/quick-pair.test.tsxindex e048af368..2b7b9fd62 100644--- a/webui/src/tests/quick-pair.test.tsx+++ b/webui/src/tests/quick-pair.test.tsx@@ -2,13 +2,25 @@ import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-libraimport { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { QuickPairSetup } from "@/components/remote/QuickPairSetup";import { Dialog, DialogContent } from "@/components/ui/dialog";+import type { ConnectionStatus } from "@/lib/types";+import { NanobotClient } from "@/lib/nanobot-client";import i18n from "@/i18n";const mocks = vi.hoisted(() => {const action = vi.fn();- return { action, client: { requestMutation: action }, connect: vi.fn(), refresh: vi.fn(), cancel: vi.fn(), copy: vi.fn() };+ const listeners = new Set<(status: ConnectionStatus) => void>();+ const client = {+ status: "open" as ConnectionStatus,+ requestMutation: action,+ onStatus: (listener: (status: ConnectionStatus) => void) => {+ listeners.add(listener);+ listener(client.status);+ return () => { listeners.delete(listener); };+ },+ };+ return { action, client, listeners, transportClient: null as NanobotClient | null, connect: vi.fn(), refresh: vi.fn(), cancel: vi.fn(), copy: vi.fn() };});-vi.mock("@/providers/ClientProvider", () => ({ useClient: () => ({ client: mocks.client }) }));+vi.mock("@/providers/ClientProvider", () => ({ useClient: () => ({ client: mocks.transportClient ?? mocks.client }) }));vi.mock("@/components/remote/RemoteInstances", () => ({ useRemoteConnections: () => ({ connect: mocks.connect, refresh: mocks.refresh, cancel: mocks.cancel, directory: { profiles: [] } }) }));vi.mock("@/lib/clipboard", () => ({ copyTextToClipboard: mocks.copy }));const request = () => ({ id: "request-1", command: "nanobot remote pair nbpr1.public", expires: Date.now() / 1000 + 600 });@@ -16,6 +28,8 @@ const preview = { id: "request-1", host: "ubuntu@server", hostname: "team", fingbeforeEach(async () => {await i18n.changeLanguage("en");+ mocks.client.status = "open";+ mocks.listeners.clear();mocks.action.mockReset().mockImplementation(async (action: string) => {if (action === "remote.pair_start") return request();if (action === "remote.pair_preview") return preview;@@ -26,12 +40,21 @@ beforeEach(async () => {mocks.connect.mockReset().mockResolvedValue(undefined);mocks.refresh.mockReset().mockResolvedValue(undefined);});-afterEach(() => { cleanup(); vi.useRealTimers(); vi.restoreAllMocks(); });+afterEach(() => { cleanup(); mocks.transportClient?.close(); mocks.transportClient = null; vi.useRealTimers(); vi.restoreAllMocks(); });const view = (onSSH = vi.fn(), onClose = vi.fn()) => render(<Dialog open><DialogContent><QuickPairSetup onSSH={onSSH} onClose={onClose} /></DialogContent></Dialog>);function chooseOtherWay(name: string) {fireEvent.pointerDown(screen.getByRole("button", { name: "Other ways" }), { button: 0, ctrlKey: false });fireEvent.click(screen.getByRole("menuitem", { name }));}+function setStatus(status: ConnectionStatus) {+ act(() => {+ mocks.client.status = status;+ mocks.listeners.forEach((listener) => listener(status));+ });+}+function returnedView() {+ return render(<Dialog open><DialogContent><QuickPairSetup returned={{ id: "request-1", code: "nbpc1.encrypted" }} onSSH={vi.fn()} onClose={vi.fn()} /></DialogContent></Dialog>);+}async function reviewed() {await screen.findByRole("button", { name: "Copy command" });@@ -42,6 +65,79 @@ async function reviewed() {}describe("quick pairing", () => {+ it("reviews through the real NanobotClient after its socket opens", async () => {+ const socket = {+ readyState: 0,+ onopen: null as (() => void) | null,+ onmessage: null as ((event: MessageEvent) => void) | null,+ onerror: null as (() => void) | null,+ onclose: null as (() => void) | null,+ send: vi.fn(), close: vi.fn(),+ };+ mocks.transportClient = new NanobotClient({+ url: "ws://local-test", reconnect: false,+ socketFactory: () => socket as unknown as WebSocket,+ });+ mocks.transportClient.connect();+ returnedView();+ expect(socket.send).not.toHaveBeenCalled();+ expect(screen.queryByRole("alert")).toBeNull();+ act(() => { socket.readyState = 1; socket.onopen?.(); });+ const frame = JSON.parse(socket.send.mock.calls[0][0]);+ expect(frame).toMatchObject({ type: "webui_request", action: "remote.pair_preview", payload: { id: "request-1", code: "nbpc1.encrypted" } });+ await act(async () => {+ socket.onmessage?.({ data: JSON.stringify({ event: "webui_response", request_id: frame.request_id, ok: true, result: preview }) } as MessageEvent);+ });+ expect(screen.getByRole("heading", { name: "Open this nanobot?" })).toBeVisible();+ expect(socket.send).toHaveBeenCalledTimes(1);+ expect(mocks.connect).not.toHaveBeenCalled();+ });+ it("waits for the local socket on a cold return-link page and reviews only once", async () => {+ mocks.client.status = "connecting";+ returnedView();+ expect(mocks.action).not.toHaveBeenCalled();+ expect(screen.queryByRole("alert")).toBeNull();+ expect(screen.queryByRole("button", { name: "Get a new command" })).toBeNull();+ setStatus("open");+ await screen.findByRole("heading", { name: "Open this nanobot?" });+ setStatus("reconnecting"); setStatus("open");+ expect(mocks.action).toHaveBeenCalledTimes(1);+ expect(mocks.action).toHaveBeenCalledWith("remote.pair_preview", { id: "request-1", code: "nbpc1.encrypted" }, 65000);+ expect(mocks.connect).not.toHaveBeenCalled();+ });+ it("waits before preparing an invitation and stops waiting when the dialog closes", () => {+ mocks.client.status = "connecting";+ const result = view();+ expect(mocks.action).not.toHaveBeenCalled();+ result.unmount();+ setStatus("open");+ expect(mocks.action).not.toHaveBeenCalled();+ expect(mocks.listeners.size).toBe(0);+ });+ it("explains a slow local connection and recovers without discarding the receipt", async () => {+ vi.useFakeTimers();+ mocks.client.status = "connecting";+ returnedView();+ await act(async () => { vi.advanceTimersByTime(10_000); });+ expect(screen.getByRole("alert")).toHaveTextContent(/local nanobot/);+ expect(screen.queryByRole("button", { name: "Get a new command" })).toBeNull();+ expect(mocks.action).not.toHaveBeenCalled();+ setStatus("open");+ await act(async () => {});+ expect(screen.getByRole("heading", { name: "Open this nanobot?" })).toBeVisible();+ expect(screen.queryByRole("alert")).toBeNull();+ });+ it.each([["WebUI connection is not open", 503], ["WebUI request timed out after 65000ms", 504]])("retries the same returned receipt after %s", async (message, status) => {+ mocks.action.mockRejectedValueOnce(Object.assign(new Error(String(message)), { status }));+ returnedView();+ expect(await screen.findByRole("alert")).toHaveTextContent(/local nanobot/);+ expect(screen.queryByRole("button", { name: "Get a new command" })).toBeNull();+ fireEvent.click(screen.getByRole("button", { name: "Retry" }));+ await screen.findByRole("heading", { name: "Open this nanobot?" });+ expect(mocks.action.mock.calls.map(([action]) => action)).toEqual(["remote.pair_preview", "remote.pair_preview"]);+ expect(mocks.action.mock.calls[0]).toEqual(mocks.action.mock.calls[1]);+ expect(mocks.connect).not.toHaveBeenCalled();+ });it("never asks a returning user to copy another command while validating their link", async () => {mocks.action.mockImplementation(() => new Promise(() => {}));render(<Dialog open><DialogContent><QuickPairSetup returned={{ id: "request-1", code: "nbpc1.encrypted" }} onSSH={vi.fn()} onClose={vi.fn()} /></DialogContent></Dialog>);