feat(webui): complete remote pairing and connection recovery
This commit is contained in:
1 parent
11889c018e
commit
192ca6e49e
52 files changed
+7313
-675
No files matched your search
@@ -1,6 +1,7 @@
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { useClient } from "@/providers/ClientProvider";
|
||||
import { readRemoteInstances, readSelectedRemote, rememberSelectedRemote, remoteAction, validateRemoteConnection, type RemoteConnection, type RemoteDirectory, type SelectedRemote } from "@/lib/remote-instances";
|
||||
import { readPairReturn } from "@/lib/remote-pair-return";
|
||||
import { readRemoteInstances, readSelectedRemote, readRecentRemotes, rememberSelectedRemote, rememberRecentRemote, remoteAction, validateRemoteConnection, type RemoteConnection, type RemoteDirectory, type SelectedRemote } from "@/lib/remote-instances";
|
||||
|
||||
// Never silently evict a view containing drafts or unfinished attachments.
|
||||
// Tunnels are shared across browser tabs, so only explicit disconnect closes one.
|
||||
@@ -10,21 +11,27 @@ export interface HostFrame {
|
||||
loaded: boolean;
|
||||
offline: boolean;
|
||||
failures: number;
|
||||
error?: string;
|
||||
}
|
||||
interface PendingSwitch { id: string; name: string }
|
||||
interface SwitchFailure { id: string; code: string }
|
||||
|
||||
export function useHostSessions() {
|
||||
const { client, getToken } = useClient();
|
||||
const [directory, setDirectory] = useState<RemoteDirectory | null>(null);
|
||||
const [directoryError, setDirectoryError] = useState(false);
|
||||
const [selected, setSelected] = useState<SelectedRemote | null>(readSelectedRemote);
|
||||
const [selected, setSelected] = useState<SelectedRemote | null>(() => readPairReturn() ? null : readSelectedRemote());
|
||||
const [recentIds, setRecentIds] = useState(readRecentRemotes);
|
||||
const recentIdsRef = useRef(recentIds);
|
||||
const selectedRef = useRef(selected);
|
||||
const initial = useRef(selected);
|
||||
const cache = useRef(new Map<string, HostFrame>());
|
||||
const [frames, setFrames] = useState<HostFrame[]>([]);
|
||||
const [pending, setPending] = useState<PendingSwitch | null>(null);
|
||||
const pendingRef = useRef<PendingSwitch | null>(null);
|
||||
const [error, setError] = useState("");
|
||||
const [pending, setPending] = useState<PendingSwitch | null>(() => selected ? { id: selected.id, name: selected.name } : null);
|
||||
const pendingRef = useRef<PendingSwitch | null>(pending);
|
||||
const [failure, setFailure] = useState<SwitchFailure | null>(null);
|
||||
const clearError = useCallback(() => setFailure(null), []);
|
||||
const directoryGeneration = useRef(0);
|
||||
const mounted = useRef(true);
|
||||
const epoch = useRef(0);
|
||||
const waiter = useRef<{ id: string; finish: (ready: boolean) => void } | null>(null);
|
||||
@@ -43,17 +50,22 @@ export function useHostSessions() {
|
||||
selectedRef.current = value;
|
||||
setSelected(value);
|
||||
rememberSelectedRemote(value);
|
||||
setError("");
|
||||
if (value) {
|
||||
recentIdsRef.current = rememberRecentRemote(value.id, recentIdsRef.current);
|
||||
setRecentIds(recentIdsRef.current);
|
||||
}
|
||||
setFailure(null);
|
||||
publish();
|
||||
}, [publish]);
|
||||
const local = useCallback(() => { cancel(); select(null); }, [cancel, select]);
|
||||
const refresh = useCallback(async () => {
|
||||
const generation = ++directoryGeneration.current;
|
||||
try {
|
||||
const next = window.top === window ? await readRemoteInstances(getToken()) : { available: false, profiles: [] };
|
||||
if (mounted.current) { setDirectory(next); setDirectoryError(false); }
|
||||
if (mounted.current && generation === directoryGeneration.current) { setDirectory(next); setDirectoryError(false); }
|
||||
return next;
|
||||
} catch (reason) {
|
||||
if (mounted.current) setDirectoryError(true);
|
||||
if (mounted.current && generation === directoryGeneration.current) setDirectoryError(true);
|
||||
throw reason;
|
||||
}
|
||||
}, [getToken]);
|
||||
@@ -67,10 +79,15 @@ export function useHostSessions() {
|
||||
if (wanted()) select(warm.connection);
|
||||
return;
|
||||
}
|
||||
if (!warm && cache.current.size >= MAX_HOST_VIEWS) throw new Error("view_limit");
|
||||
if (!warm && cache.current.size >= MAX_HOST_VIEWS) {
|
||||
setFailure({ id, code: "view_limit" });
|
||||
throw new Error("view_limit");
|
||||
}
|
||||
// A health response started before this mutation describes the old tunnel.
|
||||
directoryGeneration.current += 1;
|
||||
const name = directory?.profiles.find((item) => item.id === id)?.name || initial.current?.name || id;
|
||||
setPendingSwitch({ id, name });
|
||||
setError("");
|
||||
setFailure(null);
|
||||
let openingFrame = warm?.loaded ? undefined : warm;
|
||||
try {
|
||||
const connection = validateRemoteConnection(await remoteAction<RemoteConnection>(client, "connect", { id }));
|
||||
@@ -80,12 +97,13 @@ export function useHostSessions() {
|
||||
return;
|
||||
}
|
||||
let frame = cache.current.get(id);
|
||||
if (!frame || frame.connection.url !== connection.url || frame.connection.gateway_id !== connection.gateway_id) {
|
||||
if (!frame || frame.connection.url !== connection.url || frame.connection.gateway_id !== connection.gateway_id
|
||||
|| frame.connection.view_id !== connection.view_id) {
|
||||
frame = { connection, loaded: false, offline: false, failures: 0 };
|
||||
cache.current.set(id, frame);
|
||||
} else {
|
||||
frame.connection = connection;
|
||||
frame.offline = false; frame.failures = 0;
|
||||
frame.offline = false; frame.failures = 0; frame.error = "";
|
||||
}
|
||||
if (!frame.loaded) openingFrame = frame;
|
||||
publish();
|
||||
@@ -95,14 +113,20 @@ export function useHostSessions() {
|
||||
const timer = window.setTimeout(() => {
|
||||
waiter.current = null;
|
||||
reject(new Error("view_load_failed"));
|
||||
}, 25_000);
|
||||
// Cold remote bundles can take several SSH round trips. Keep the
|
||||
// current host usable and cancellable while giving them time to load.
|
||||
}, 60_000);
|
||||
waiter.current = { id, finish: (ready) => { window.clearTimeout(timer); resolve(ready); } };
|
||||
});
|
||||
if (!ready) return;
|
||||
}
|
||||
if (wanted()) select(connection);
|
||||
} catch (reason) {
|
||||
if (wanted()) throw reason;
|
||||
if (wanted()) {
|
||||
setFailure({ id, code: reason instanceof Error ? reason.message : "unknown" });
|
||||
void refresh().catch(() => {});
|
||||
throw reason;
|
||||
}
|
||||
} finally {
|
||||
// Cancelled/failed cold pages contain no user work. Don't let them use up
|
||||
// the view budget; a newer attempt for this host owns its transport now.
|
||||
@@ -122,12 +146,15 @@ export function useHostSessions() {
|
||||
if (waiter.current?.id === id) { waiter.current.finish(true); waiter.current = null; }
|
||||
}, [publish]);
|
||||
const disconnect = useCallback(async (id: string) => {
|
||||
directoryGeneration.current += 1;
|
||||
if (pendingRef.current?.id === id) cancel();
|
||||
await remoteAction(client, "disconnect", { id });
|
||||
if (selectedRef.current?.id === id) local();
|
||||
cache.current.delete(id);
|
||||
publish();
|
||||
await refresh();
|
||||
// The mutation succeeded. A failed follow-up read must not ask the user to
|
||||
// repeat a destructive action; refresh has its own retryable list error.
|
||||
await refresh().catch(() => {});
|
||||
}, [cancel, client, local, publish, refresh]);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -138,41 +165,52 @@ export function useHostSessions() {
|
||||
useEffect(() => {
|
||||
const saved = initial.current;
|
||||
if (!saved || window.top !== window) return;
|
||||
const restoration = epoch.current;
|
||||
let started = false;
|
||||
const timer = window.setTimeout(() => {
|
||||
started = true;
|
||||
if (selectedRef.current?.id === saved.id) setError("ssh_unreachable");
|
||||
if (selectedRef.current?.id === saved.id && epoch.current === restoration) {
|
||||
setPendingSwitch(null);
|
||||
setFailure({ id: saved.id, code: "ssh_unreachable" });
|
||||
}
|
||||
}, 15_000);
|
||||
const unsubscribe = client.onStatus((status) => {
|
||||
if (status !== "open" || started) return;
|
||||
started = true;
|
||||
window.clearTimeout(timer);
|
||||
if (selectedRef.current?.id !== saved.id) return;
|
||||
void connectRef.current(saved.id).catch((reason: unknown) => {
|
||||
if (mounted.current && selectedRef.current?.id === saved.id) setError(reason instanceof Error ? reason.message : "unknown");
|
||||
});
|
||||
if (selectedRef.current?.id !== saved.id || epoch.current !== restoration) return;
|
||||
void connectRef.current(saved.id).catch(() => {});
|
||||
});
|
||||
return () => { window.clearTimeout(timer); unsubscribe(); };
|
||||
}, [client]);
|
||||
}, [client, setPendingSwitch]);
|
||||
useEffect(() => {
|
||||
let checking = false;
|
||||
let cancelled = false;
|
||||
const tick = async () => {
|
||||
if (checking || !cache.current.size) return;
|
||||
checking = true;
|
||||
const generation = ++directoryGeneration.current;
|
||||
try {
|
||||
const next = await readRemoteInstances(getToken());
|
||||
if (cancelled) return;
|
||||
if (cancelled || generation !== directoryGeneration.current) return;
|
||||
setDirectory(next); setDirectoryError(false);
|
||||
for (const [id, frame] of cache.current) {
|
||||
if (id === pendingRef.current?.id) continue;
|
||||
const connected = next.profiles.some((profile) => profile.id === id && profile.connected);
|
||||
const profile = next.profiles.find((profile) => profile.id === id);
|
||||
const changed = (!!profile?.gateway_id && profile.gateway_id !== frame.connection.gateway_id)
|
||||
|| (!!profile?.view_id && profile.view_id !== frame.connection.view_id);
|
||||
const connected = !!profile?.connected && !changed;
|
||||
frame.failures = connected ? 0 : frame.failures + 1;
|
||||
if (connected || frame.failures >= 2) frame.offline = !connected;
|
||||
if (connected || frame.failures >= 2) {
|
||||
frame.offline = !connected;
|
||||
frame.error = connected ? "" : changed ? "instance_changed" : profile?.connection_error || (!profile ? "profile_not_found" : "");
|
||||
}
|
||||
if (connected && frame.loaded) setFailure((current) => current?.id === id ? null : current);
|
||||
}
|
||||
} catch {
|
||||
if (!cancelled) for (const frame of cache.current.values()) {
|
||||
if (++frame.failures >= 2) frame.offline = true;
|
||||
if (!cancelled && generation === directoryGeneration.current) for (const [id, frame] of cache.current) {
|
||||
if (id === pendingRef.current?.id) continue;
|
||||
if (++frame.failures >= 2) { frame.offline = true; frame.error = "directory_unavailable"; }
|
||||
}
|
||||
} finally {
|
||||
checking = false;
|
||||
@@ -180,7 +218,19 @@ export function useHostSessions() {
|
||||
}
|
||||
};
|
||||
const timer = window.setInterval(() => { void tick(); }, 5_000);
|
||||
return () => { cancelled = true; window.clearInterval(timer); };
|
||||
// Background tabs throttle timers. Recheck promptly after waking or a
|
||||
// network change, without reloading a frame or changing the selected host.
|
||||
const wake = () => { if (document.visibilityState === "visible") void tick(); };
|
||||
window.addEventListener("online", wake);
|
||||
window.addEventListener("pageshow", wake);
|
||||
document.addEventListener("visibilitychange", wake);
|
||||
return () => {
|
||||
cancelled = true; window.clearInterval(timer);
|
||||
window.removeEventListener("online", wake);
|
||||
window.removeEventListener("pageshow", wake);
|
||||
document.removeEventListener("visibilitychange", wake);
|
||||
};
|
||||
}, [client, getToken, publish]);
|
||||
return { directory, directoryError, refresh, selected, frames, pending, error, setError, connect, cancel, local, disconnect, loaded };
|
||||
return { directory, directoryError, refresh, selected, recentIds, frames, pending,
|
||||
error: failure?.code || "", errorId: failure?.id, clearError, connect, cancel, local, disconnect, loaded };
|
||||
}
|
||||
Reference in new issue
Block a user