fix(remote): simplify connection mutations and preserve host state
This commit is contained in:
1 parent
0ffdf86619
commit
2330bfc5a5
7 files changed
+96
-37
No files matched your search
@@ -333,11 +333,14 @@ class RemoteInstances:
|
|||||||
))
|
))
|
||||||
if instance_changed:
|
if instance_changed:
|
||||||
self._remember_origins(profiles)
|
self._remember_origins(profiles)
|
||||||
local_port = profiles[key].local_port if key in profiles and not instance_changed else 0
|
# Update editable fields without reconstructing (and losing)
|
||||||
proxy_origin = bool(local_port and profiles[key].proxy_origin)
|
# managed origin metadata for an unchanged destination.
|
||||||
profiles[key] = _SavedProfile(**profile.model_dump(), local_port=local_port,
|
profiles[key] = (profiles[key].model_copy(update=profile.model_dump())
|
||||||
proxy_origin=proxy_origin)
|
if key in profiles and not instance_changed
|
||||||
|
else _SavedProfile(**profile.model_dump()))
|
||||||
self._write(profiles)
|
self._write(profiles)
|
||||||
|
if instance_changed:
|
||||||
|
self._compatibility.pop(key, None)
|
||||||
if target_changed:
|
if target_changed:
|
||||||
self._known_hosts(key).unlink(missing_ok=True)
|
self._known_hosts(key).unlink(missing_ok=True)
|
||||||
self._unverified.pop(key, None)
|
self._unverified.pop(key, None)
|
||||||
|
|||||||
@@ -481,13 +481,33 @@ async def test_health_budget_includes_waiting_for_connection_lock(manager, ssh,
|
|||||||
|
|
||||||
async def test_reconnect_keeps_origin_and_changing_target_does_not(manager, ssh):
|
async def test_reconnect_keeps_origin_and_changing_target_does_not(manager, ssh):
|
||||||
key = await save(manager)
|
key = await save(manager)
|
||||||
await manager.action("connect", {"id": key})
|
first = await manager.action("connect", {"id": key})
|
||||||
assert json.loads(manager.path.read_text())[key]["local_port"] == 23456
|
assert json.loads(manager.path.read_text())[key]["local_port"] == 23456
|
||||||
await manager.action("disconnect", {"id": key})
|
await manager.action("disconnect", {"id": key})
|
||||||
await manager.action("save", {"id": key, "profile": {"name": "Renamed", "host": "ubuntu@example.test"}})
|
await manager.action("save", {"id": key, "profile": {"name": "Renamed", "host": "ubuntu@example.test"}})
|
||||||
assert json.loads(manager.path.read_text())[key]["local_port"] == 23456
|
assert json.loads(manager.path.read_text())[key]["local_port"] == 23456
|
||||||
|
# Editing display metadata must preserve the local-client origin marker,
|
||||||
|
# not just its port: otherwise reconnect silently retires that origin.
|
||||||
|
assert json.loads(manager.path.read_text())[key]["local_client_origin"] is True
|
||||||
|
second = await manager.action("connect", {"id": key})
|
||||||
|
assert second["url"] == first["url"]
|
||||||
|
RemoteProxy.open.assert_awaited_once()
|
||||||
|
await manager.action("disconnect", {"id": key})
|
||||||
await manager.action("save", {"id": key, "profile": {"name": "Other", "host": "other.example.test"}})
|
await manager.action("save", {"id": key, "profile": {"name": "Other", "host": "other.example.test"}})
|
||||||
assert json.loads(manager.path.read_text())[key]["local_port"] == 0
|
assert json.loads(manager.path.read_text())[key]["local_port"] == 0
|
||||||
|
assert "compatibility" not in manager.snapshot()["profiles"][0]
|
||||||
|
|
||||||
|
|
||||||
|
async def test_editing_failed_target_clears_its_compatibility_diagnosis(manager, ssh):
|
||||||
|
key = await save(manager)
|
||||||
|
ssh.state["identity"].pop("webui")
|
||||||
|
with pytest.raises(RemoteError, match="webui_compatibility_unknown"):
|
||||||
|
await manager.action("connect", {"id": key})
|
||||||
|
result = await manager.action("save", {"id": key, "profile": {
|
||||||
|
"name": "Other", "host": "other.example.test",
|
||||||
|
}})
|
||||||
|
assert result["profiles"][0]["connection_error"] == "disconnected"
|
||||||
|
assert "compatibility" not in result["profiles"][0]
|
||||||
|
|
||||||
|
|
||||||
async def test_corrupt_store_not_overwritten(manager):
|
async def test_corrupt_store_not_overwritten(manager):
|
||||||
|
|||||||
@@ -51,8 +51,8 @@ export function RemoteConnectionsPage({ mainNavigationExpanded = false, hostChro
|
|||||||
const [editing, setEditing] = useState(false);
|
const [editing, setEditing] = useState(false);
|
||||||
const [savedId, setSavedId] = useState("");
|
const [savedId, setSavedId] = useState("");
|
||||||
const [busy, setBusy] = useState("");
|
const [busy, setBusy] = useState("");
|
||||||
const [error, setError] = useState("");
|
|
||||||
const [errorCode, setErrorCode] = useState("");
|
const [errorCode, setErrorCode] = useState("");
|
||||||
|
const error = errorCode ? t(`remote.errors.${errorCode}`, { defaultValue: t("remote.errors.unknown") }) : "";
|
||||||
const [sshOptions, setSSHOptions] = useState(false);
|
const [sshOptions, setSSHOptions] = useState(false);
|
||||||
const [manualLocation, setManualLocation] = useState(false);
|
const [manualLocation, setManualLocation] = useState(false);
|
||||||
const [inspection, setInspection] = useState<RemoteInspection | null>(null);
|
const [inspection, setInspection] = useState<RemoteInspection | null>(null);
|
||||||
@@ -96,12 +96,11 @@ export function RemoteConnectionsPage({ mainNavigationExpanded = false, hostChro
|
|||||||
setInspection(null); setManualLocation(false); setInspectBeforeConnect(true);
|
setInspection(null); setManualLocation(false); setInspectBeforeConnect(true);
|
||||||
}
|
}
|
||||||
setErrorCode(code);
|
setErrorCode(code);
|
||||||
setError(t(`remote.errors.${code}`, { defaultValue: t("remote.errors.unknown") }));
|
|
||||||
};
|
};
|
||||||
const closeEditor = () => {
|
const closeEditor = () => {
|
||||||
operation.current += 1;
|
operation.current += 1;
|
||||||
if (busy) connections.cancel();
|
if (busy) connections.cancel();
|
||||||
setBusy(""); setEditorOpen(false); setFingerprint(null); setError(""); setErrorCode("");
|
setBusy(""); setEditorOpen(false); setFingerprint(null); setErrorCode("");
|
||||||
};
|
};
|
||||||
const beginEditor = (profile?: RemoteProfile) => {
|
const beginEditor = (profile?: RemoteProfile) => {
|
||||||
operation.current += 1;
|
operation.current += 1;
|
||||||
@@ -111,20 +110,20 @@ export function RemoteConnectionsPage({ mainNavigationExpanded = false, hostChro
|
|||||||
setForm(profile ? { name: profile.name, host: profile.host, port: profile.port,
|
setForm(profile ? { name: profile.name, host: profile.host, port: profile.port,
|
||||||
ssh_config: profile.ssh_config, identity_file: profile.identity_file,
|
ssh_config: profile.ssh_config, identity_file: profile.identity_file,
|
||||||
config_path: profile.config_path, runtime_user: profile.runtime_user } : emptyProfile());
|
config_path: profile.config_path, runtime_user: profile.runtime_user } : emptyProfile());
|
||||||
setError(""); setCommandImported(false); setEditorOpen(true); setFingerprint(null);
|
setCommandImported(false); setEditorOpen(true); setFingerprint(null);
|
||||||
};
|
};
|
||||||
|
|
||||||
const importCommand = () => {
|
const importCommand = () => {
|
||||||
if (!/^ssh\s/.test(form.host.trim())) return;
|
if (!/^ssh\s/.test(form.host.trim())) return;
|
||||||
try {
|
try {
|
||||||
setForm({ ...form, ...parseSSHAddress(form.host) });
|
setForm({ ...form, ...parseSSHAddress(form.host) });
|
||||||
setCommandImported(true); setError("");
|
setCommandImported(true); setErrorCode("");
|
||||||
} catch (reason) { showError(reason); }
|
} catch (reason) { showError(reason); }
|
||||||
};
|
};
|
||||||
|
|
||||||
const pickFile = async (field: "ssh_config" | "identity_file") => {
|
const pickFile = async (field: "ssh_config" | "identity_file") => {
|
||||||
const attempt = ++operation.current;
|
const attempt = ++operation.current;
|
||||||
setBusy(`pick-${field}`); setError(""); setErrorCode("");
|
setBusy(`pick-${field}`); setErrorCode("");
|
||||||
try {
|
try {
|
||||||
const result = await remoteAction<{ path: string | null }>(client, "pick_file", {});
|
const result = await remoteAction<{ path: string | null }>(client, "pick_file", {});
|
||||||
if (wanted(attempt) && typeof result.path === "string" && result.path) {
|
if (wanted(attempt) && typeof result.path === "string" && result.path) {
|
||||||
@@ -140,7 +139,7 @@ export function RemoteConnectionsPage({ mainNavigationExpanded = false, hostChro
|
|||||||
</Button>;
|
</Button>;
|
||||||
|
|
||||||
const connect = async (id: string, attempt = ++operation.current, inspect = false) => {
|
const connect = async (id: string, attempt = ++operation.current, inspect = false) => {
|
||||||
setBusy(inspect ? "inspect" : id); setError(""); setErrorCode("");
|
setBusy(inspect ? "inspect" : id); setErrorCode("");
|
||||||
try {
|
try {
|
||||||
if (inspect) {
|
if (inspect) {
|
||||||
const result = await remoteAction<RemoteInspection>(client, "inspect", { id });
|
const result = await remoteAction<RemoteInspection>(client, "inspect", { id });
|
||||||
@@ -208,7 +207,7 @@ export function RemoteConnectionsPage({ mainNavigationExpanded = false, hostChro
|
|||||||
if (!fingerprint) return;
|
if (!fingerprint) return;
|
||||||
const attempt = ++operation.current;
|
const attempt = ++operation.current;
|
||||||
const id = fingerprint.id;
|
const id = fingerprint.id;
|
||||||
setBusy("trust"); setError("");
|
setBusy("trust"); setErrorCode("");
|
||||||
try {
|
try {
|
||||||
await remoteAction(client, "trust", { id, challenge: fingerprint.challenge });
|
await remoteAction(client, "trust", { id, challenge: fingerprint.challenge });
|
||||||
if (wanted(attempt)) { setFingerprint(null); await connect(id, attempt, fingerprint.inspect); }
|
if (wanted(attempt)) { setFingerprint(null); await connect(id, attempt, fingerprint.inspect); }
|
||||||
@@ -218,7 +217,7 @@ export function RemoteConnectionsPage({ mainNavigationExpanded = false, hostChro
|
|||||||
|
|
||||||
const save = async () => {
|
const save = async () => {
|
||||||
const attempt = ++operation.current;
|
const attempt = ++operation.current;
|
||||||
setBusy("save"); setError(""); setErrorCode("");
|
setBusy("save"); setErrorCode("");
|
||||||
try {
|
try {
|
||||||
// Also parse here for Enter submission, which doesn't blur the address.
|
// Also parse here for Enter submission, which doesn't blur the address.
|
||||||
const address = parseSSHAddress(form.host);
|
const address = parseSSHAddress(form.host);
|
||||||
@@ -239,12 +238,10 @@ export function RemoteConnectionsPage({ mainNavigationExpanded = false, hostChro
|
|||||||
|
|
||||||
const remove = async () => {
|
const remove = async () => {
|
||||||
if (!removing) return;
|
if (!removing) return;
|
||||||
setBusy("remove"); setError("");
|
setBusy("remove"); setErrorCode("");
|
||||||
try {
|
try {
|
||||||
await disconnectHost(removing.id);
|
await connections.remove(removing.id);
|
||||||
await remoteAction(client, "remove", { id: removing.id });
|
|
||||||
if (mounted.current) setRemoving(null);
|
if (mounted.current) setRemoving(null);
|
||||||
await refresh?.().catch(() => {});
|
|
||||||
} catch (reason) { if (mounted.current) showError(reason); }
|
} catch (reason) { if (mounted.current) showError(reason); }
|
||||||
finally { if (mounted.current) setBusy(""); }
|
finally { if (mounted.current) setBusy(""); }
|
||||||
};
|
};
|
||||||
@@ -259,7 +256,7 @@ export function RemoteConnectionsPage({ mainNavigationExpanded = false, hostChro
|
|||||||
} finally { if (mounted.current) setBusy(""); }
|
} finally { if (mounted.current) setBusy(""); }
|
||||||
};
|
};
|
||||||
const disconnect = async (id: string) => {
|
const disconnect = async (id: string) => {
|
||||||
setBusy(id); setError("");
|
setBusy(id); setErrorCode("");
|
||||||
try { await disconnectHost(id); if (mounted.current) setDisconnecting(null); }
|
try { await disconnectHost(id); if (mounted.current) setDisconnecting(null); }
|
||||||
catch (reason) { if (mounted.current) showError(reason); }
|
catch (reason) { if (mounted.current) showError(reason); }
|
||||||
finally { if (mounted.current) setBusy(""); }
|
finally { if (mounted.current) setBusy(""); }
|
||||||
@@ -277,7 +274,7 @@ export function RemoteConnectionsPage({ mainNavigationExpanded = false, hostChro
|
|||||||
const disconnectProfile = disconnecting || lastDisconnect.current;
|
const disconnectProfile = disconnecting || lastDisconnect.current;
|
||||||
const editSSH = () => {
|
const editSSH = () => {
|
||||||
setInspection(null); setManualLocation(false); setInspectBeforeConnect(true);
|
setInspection(null); setManualLocation(false); setInspectBeforeConnect(true);
|
||||||
setError(""); setErrorCode(""); setSSHOptions(true);
|
setErrorCode(""); setSSHOptions(true);
|
||||||
};
|
};
|
||||||
const groups = groupRemoteProfiles(directory?.profiles || [], connections.activeHostId);
|
const groups = groupRemoteProfiles(directory?.profiles || [], connections.activeHostId);
|
||||||
const detailGroup = groups.find((group) => group.id === details);
|
const detailGroup = groups.find((group) => group.id === details);
|
||||||
@@ -286,8 +283,8 @@ export function RemoteConnectionsPage({ mainNavigationExpanded = false, hostChro
|
|||||||
const connectionActions = (profile: RemoteProfile, grouped = false) => <>
|
const connectionActions = (profile: RemoteProfile, grouped = false) => <>
|
||||||
{!profile.paired && <DropdownMenuItem disabled={profile.connected || connections.openHostIds.includes(profile.id)} onSelect={() => { setDetailsOpen(false); beginEditor(profile); }}>{t("remote.edit")}</DropdownMenuItem>}
|
{!profile.paired && <DropdownMenuItem disabled={profile.connected || connections.openHostIds.includes(profile.id)} onSelect={() => { setDetailsOpen(false); beginEditor(profile); }}>{t("remote.edit")}</DropdownMenuItem>}
|
||||||
{profile.paired && <DropdownMenuItem disabled={profile.connected || connections.openHostIds.includes(profile.id)} onSelect={() => { setDetailsOpen(false); setPairRoute(profile.id); setRouteOpen(true); }}>{t("remote.pair.route")}</DropdownMenuItem>}
|
{profile.paired && <DropdownMenuItem disabled={profile.connected || connections.openHostIds.includes(profile.id)} onSelect={() => { setDetailsOpen(false); setPairRoute(profile.id); setRouteOpen(true); }}>{t("remote.pair.route")}</DropdownMenuItem>}
|
||||||
{(profile.connected || connections.openHostIds.includes(profile.id)) && <DropdownMenuItem onSelect={() => { setDetailsOpen(false); setError(""); setDisconnecting(profile); }}>{t("remote.disconnect")}</DropdownMenuItem>}
|
{(profile.connected || connections.openHostIds.includes(profile.id)) && <DropdownMenuItem onSelect={() => { setDetailsOpen(false); setErrorCode(""); setDisconnecting(profile); }}>{t("remote.disconnect")}</DropdownMenuItem>}
|
||||||
<DropdownMenuItem tone="destructive" onSelect={() => { setDetailsOpen(false); setError(""); setRemoving(profile); }}>{t(grouped ? "remote.sameInstance.forgetConnection" : "remote.forget")}</DropdownMenuItem>
|
<DropdownMenuItem tone="destructive" onSelect={() => { setDetailsOpen(false); setErrorCode(""); setRemoving(profile); }}>{t(grouped ? "remote.sameInstance.forgetConnection" : "remote.forget")}</DropdownMenuItem>
|
||||||
</>;
|
</>;
|
||||||
|
|
||||||
return <div ref={page} tabIndex={-1} role="region" aria-label={t("remote.title")} className="flex min-h-0 flex-1 flex-col overflow-hidden bg-settings-canvas outline-none">
|
return <div ref={page} tabIndex={-1} role="region" aria-label={t("remote.title")} className="flex min-h-0 flex-1 flex-col overflow-hidden bg-settings-canvas outline-none">
|
||||||
@@ -361,7 +358,7 @@ export function RemoteConnectionsPage({ mainNavigationExpanded = false, hostChro
|
|||||||
{pageError && !editorOpen && !fingerprint && !removing && !disconnecting && <div className="settings-list-inset space-y-2">
|
{pageError && !editorOpen && !fingerprint && !removing && !disconnecting && <div className="settings-list-inset space-y-2">
|
||||||
<p role="alert" className="remote-alert 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" />{pageError}</p>
|
<p role="alert" className="remote-alert 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" />{pageError}</p>
|
||||||
{directoryError && <Button variant="ghost" size="sm" disabled={!!busy} onClick={() => {
|
{directoryError && <Button variant="ghost" size="sm" disabled={!!busy} onClick={() => {
|
||||||
setBusy("refresh"); setError(""); void refresh?.().catch((reason: unknown) => { if (mounted.current) showError(reason); }).finally(() => { if (mounted.current) setBusy(""); });
|
setBusy("refresh"); setErrorCode(""); void refresh?.().catch((reason: unknown) => { if (mounted.current) showError(reason); }).finally(() => { if (mounted.current) setBusy(""); });
|
||||||
}}>{t("remote.retry")}</Button>}
|
}}>{t("remote.retry")}</Button>}
|
||||||
</div>}
|
</div>}
|
||||||
</div>
|
</div>
|
||||||
@@ -444,7 +441,7 @@ export function RemoteConnectionsPage({ mainNavigationExpanded = false, hostChro
|
|||||||
<p className="text-xs leading-5 text-muted-foreground">{t("remote.verifyHint")}</p>
|
<p className="text-xs leading-5 text-muted-foreground">{t("remote.verifyHint")}</p>
|
||||||
{error && <p role="alert" className="remote-alert 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" /><span>{error}</span></p>}
|
{error && <p role="alert" className="remote-alert 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" /><span>{error}</span></p>}
|
||||||
<div className="remote-dialog-actions">
|
<div className="remote-dialog-actions">
|
||||||
{editorOpen && <Button variant="ghost" disabled={!!busy} className="gap-1" onClick={() => { setFingerprint(null); setError(""); setErrorCode(""); setInspection(null); setInspectBeforeConnect(true); }}><ChevronLeft className="h-4 w-4" />{t("remote.back")}</Button>}
|
{editorOpen && <Button variant="ghost" disabled={!!busy} className="gap-1" onClick={() => { setFingerprint(null); setErrorCode(""); setInspection(null); setInspectBeforeConnect(true); }}><ChevronLeft className="h-4 w-4" />{t("remote.back")}</Button>}
|
||||||
<Button variant="ghost" onClick={closeEditor}>{t("common.cancel")}</Button>
|
<Button variant="ghost" onClick={closeEditor}>{t("common.cancel")}</Button>
|
||||||
<Button className="col-span-2 h-auto min-h-10 whitespace-normal" disabled={!!busy} aria-busy={!!busy} onClick={() => { void trustHost(); }}>{busy && <Loader2 aria-hidden className="mr-2 h-4 w-4 shrink-0 animate-spin motion-reduce:animate-none" />}{t("remote.verifyConnect")}</Button>
|
<Button className="col-span-2 h-auto min-h-10 whitespace-normal" disabled={!!busy} aria-busy={!!busy} onClick={() => { void trustHost(); }}>{busy && <Loader2 aria-hidden className="mr-2 h-4 w-4 shrink-0 animate-spin motion-reduce:animate-none" />}{t("remote.verifyConnect")}</Button>
|
||||||
</div>
|
</div>
|
||||||
@@ -466,7 +463,7 @@ export function RemoteConnectionsPage({ mainNavigationExpanded = false, hostChro
|
|||||||
{inspection.candidates.map((candidate) => <label key={candidate.config_path + candidate.runtime_user} className={cn("flex cursor-pointer items-start gap-3 rounded-2xl border p-3 transition-colors", !manualLocation && form.config_path === candidate.config_path && form.runtime_user === candidate.runtime_user ? "border-foreground/30 bg-muted/40" : "border-border hover:bg-muted/30")}>
|
{inspection.candidates.map((candidate) => <label key={candidate.config_path + candidate.runtime_user} className={cn("flex cursor-pointer items-start gap-3 rounded-2xl border p-3 transition-colors", !manualLocation && form.config_path === candidate.config_path && form.runtime_user === candidate.runtime_user ? "border-foreground/30 bg-muted/40" : "border-border hover:bg-muted/30")}>
|
||||||
<input type="radio" name="nanobot-location" className="mt-1 accent-foreground" disabled={!!busy}
|
<input type="radio" name="nanobot-location" className="mt-1 accent-foreground" disabled={!!busy}
|
||||||
checked={!manualLocation && form.config_path === candidate.config_path && form.runtime_user === candidate.runtime_user}
|
checked={!manualLocation && form.config_path === candidate.config_path && form.runtime_user === candidate.runtime_user}
|
||||||
onChange={() => { setManualLocation(false); setForm({ ...form, config_path: candidate.config_path, runtime_user: candidate.runtime_user }); setError(""); setErrorCode(""); }} />
|
onChange={() => { setManualLocation(false); setForm({ ...form, config_path: candidate.config_path, runtime_user: candidate.runtime_user }); setErrorCode(""); }} />
|
||||||
<span className="min-w-0 text-[13px]"><span className="block font-medium [overflow-wrap:anywhere]">{candidate.service || t("remote.setup.yourNanobot")}</span>
|
<span className="min-w-0 text-[13px]"><span className="block font-medium [overflow-wrap:anywhere]">{candidate.service || t("remote.setup.yourNanobot")}</span>
|
||||||
<span className="block break-all text-xs leading-5 text-muted-foreground">{candidate.config_path}</span>
|
<span className="block break-all text-xs leading-5 text-muted-foreground">{candidate.config_path}</span>
|
||||||
{candidate.runtime_user && <span className="mt-1 block text-xs leading-5 text-muted-foreground">{t("remote.setup.serviceAccount", { user: candidate.runtime_user })}</span>}
|
{candidate.runtime_user && <span className="mt-1 block text-xs leading-5 text-muted-foreground">{t("remote.setup.serviceAccount", { user: candidate.runtime_user })}</span>}
|
||||||
@@ -482,7 +479,7 @@ export function RemoteConnectionsPage({ mainNavigationExpanded = false, hostChro
|
|||||||
</div> : <>
|
</div> : <>
|
||||||
<SSHHostPicker inputRef={hostInput} disabled={!!busy} value={form.host} configFile={form.ssh_config} imported={commandImported}
|
<SSHHostPicker inputRef={hostInput} disabled={!!busy} value={form.host} configFile={form.ssh_config} imported={commandImported}
|
||||||
suggestions={!editingProfile || form.host !== editingProfile.host || form.ssh_config !== editingProfile.ssh_config}
|
suggestions={!editingProfile || form.host !== editingProfile.host || form.ssh_config !== editingProfile.ssh_config}
|
||||||
onChange={(host) => { setForm({ ...form, host }); setCommandImported(false); setError(""); setErrorCode(""); }} onBlur={importCommand} />
|
onChange={(host) => { setForm({ ...form, host }); setCommandImported(false); setErrorCode(""); }} onBlur={importCommand} />
|
||||||
<div>
|
<div>
|
||||||
<button type="button" disabled={!!busy} aria-expanded={sshOptions} aria-controls={optionsId}
|
<button type="button" disabled={!!busy} aria-expanded={sshOptions} aria-controls={optionsId}
|
||||||
className="flex min-h-9 items-center gap-2 rounded-xl text-[13px] text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
className="flex min-h-9 items-center gap-2 rounded-xl text-[13px] text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||||
|
|||||||
@@ -30,6 +30,7 @@ const RemoteContext = createContext<{
|
|||||||
rename: (id: string, name: string) => Promise<void>;
|
rename: (id: string, name: string) => Promise<void>;
|
||||||
connect: (id: string, stillWanted?: () => boolean) => Promise<void>;
|
connect: (id: string, stillWanted?: () => boolean) => Promise<void>;
|
||||||
disconnect: (id: string) => Promise<void>;
|
disconnect: (id: string) => Promise<void>;
|
||||||
|
remove: (id: string) => Promise<void>;
|
||||||
cancel: () => void;
|
cancel: () => void;
|
||||||
} | null>(null);
|
} | null>(null);
|
||||||
export function useRemoteConnections() { return useContext(RemoteContext); }
|
export function useRemoteConnections() { return useContext(RemoteContext); }
|
||||||
@@ -161,7 +162,7 @@ export function RemoteInstances({ children }: { children: ReactNode }) {
|
|||||||
embeddedManagement: !!bridge.embedded, reportManagementSurface: bridge.embedded ? bridge.reportSurface : undefined,
|
embeddedManagement: !!bridge.embedded, reportManagementSurface: bridge.embedded ? bridge.reportSurface : undefined,
|
||||||
closeManagement: bridge.embedded ? bridge.leaveManagement : () => changeManagement(false), selectLocal,
|
closeManagement: bridge.embedded ? bridge.leaveManagement : () => changeManagement(false), selectLocal,
|
||||||
openHostIds: frames.map((frame) => frame.connection.id),
|
openHostIds: frames.map((frame) => frame.connection.id),
|
||||||
directoryError: hosts.directoryError, refresh: hosts.refresh, rename: hosts.rename, connect, disconnect: hosts.disconnect, cancel: hosts.cancel }}>
|
directoryError: hosts.directoryError, refresh: hosts.refresh, rename: hosts.rename, connect, disconnect: hosts.disconnect, remove: hosts.remove, cancel: hosts.cancel }}>
|
||||||
<HostNavigationContext.Provider value={bridge.embedded || (available || selected ? picker : null)}>
|
<HostNavigationContext.Provider value={bridge.embedded || (available || selected ? picker : null)}>
|
||||||
<div className="flex h-full min-h-0 flex-col bg-background">
|
<div className="flex h-full min-h-0 flex-col bg-background">
|
||||||
<div className="relative min-h-0 flex-1 overflow-hidden">
|
<div className="relative min-h-0 flex-1 overflow-hidden">
|
||||||
|
|||||||
@@ -172,17 +172,21 @@ export function useHostSessions() {
|
|||||||
if (frame) { frame.loaded = true; publish(); }
|
if (frame) { frame.loaded = true; publish(); }
|
||||||
if (waiter.current?.id === id) { waiter.current.finish(true); waiter.current = null; }
|
if (waiter.current?.id === id) { waiter.current.finish(true); waiter.current = null; }
|
||||||
}, [publish]);
|
}, [publish]);
|
||||||
const disconnect = useCallback(async (id: string) => {
|
const closeConnection = useCallback(async (id: string, action: "disconnect" | "remove") => {
|
||||||
directoryGeneration.current += 1;
|
directoryGeneration.current += 1;
|
||||||
if (pendingRef.current?.id === id) cancel();
|
if (pendingRef.current?.id === id) cancel();
|
||||||
await remoteAction(client, "disconnect", { id });
|
// The backend owns the transaction. In particular, a failed Forget must
|
||||||
|
// leave the connection and its browser view intact for a safe retry.
|
||||||
|
const next = await remoteAction<RemoteDirectory>(client, action, { id });
|
||||||
|
directoryGeneration.current += 1;
|
||||||
|
if (!mounted.current) return;
|
||||||
if (selectedRef.current?.id === id) local();
|
if (selectedRef.current?.id === id) local();
|
||||||
cache.current.delete(id);
|
cache.current.delete(id);
|
||||||
|
applyDirectory(next);
|
||||||
publish();
|
publish();
|
||||||
// The mutation succeeded. A failed follow-up read must not ask the user to
|
}, [applyDirectory, cancel, client, local, publish]);
|
||||||
// repeat a destructive action; refresh has its own retryable list error.
|
const disconnect = useCallback((id: string) => closeConnection(id, "disconnect"), [closeConnection]);
|
||||||
await refresh().catch(() => {});
|
const remove = useCallback((id: string) => closeConnection(id, "remove"), [closeConnection]);
|
||||||
}, [cancel, client, local, publish, refresh]);
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
mounted.current = true;
|
mounted.current = true;
|
||||||
@@ -259,5 +263,5 @@ export function useHostSessions() {
|
|||||||
};
|
};
|
||||||
}, [applyDirectory, client, getToken, publish]);
|
}, [applyDirectory, client, getToken, publish]);
|
||||||
return { directory, directoryError, refresh, rename, selected, recentIds, frames, pending,
|
return { directory, directoryError, refresh, rename, selected, recentIds, frames, pending,
|
||||||
error: failure?.code || "", errorId: failure?.id, clearError, connect, cancel, local, disconnect, loaded };
|
error: failure?.code || "", errorId: failure?.id, clearError, connect, cancel, local, disconnect, remove, loaded };
|
||||||
}
|
}
|
||||||
@@ -35,7 +35,10 @@ beforeEach(() => {
|
|||||||
window.sessionStorage.clear();
|
window.sessionStorage.clear();
|
||||||
mocks.read.mockReset().mockResolvedValue(directory);
|
mocks.read.mockReset().mockResolvedValue(directory);
|
||||||
mocks.request.mockReset().mockImplementation(async (action: string, payload: { id: string }) =>
|
mocks.request.mockReset().mockImplementation(async (action: string, payload: { id: string }) =>
|
||||||
action === "remote.connect" ? connections.find((item) => item.id === payload.id) : {});
|
action === "remote.connect" ? connections.find((item) => item.id === payload.id) : {
|
||||||
|
...directory, profiles: directory.profiles.map((profile) =>
|
||||||
|
profile.id === payload.id ? { ...profile, connected: false } : profile),
|
||||||
|
});
|
||||||
});
|
});
|
||||||
afterEach(() => { cleanup(); vi.useRealTimers(); vi.restoreAllMocks(); });
|
afterEach(() => { cleanup(); vi.useRealTimers(); vi.restoreAllMocks(); });
|
||||||
|
|
||||||
@@ -99,14 +102,17 @@ describe("host session lifecycle", () => {
|
|||||||
expect(result.current.frames[0].error).toBe("instance_changed");
|
expect(result.current.frames[0].error).toBe("instance_changed");
|
||||||
});
|
});
|
||||||
|
|
||||||
it("does not report a successful disconnect as failed when refreshing the list fails", async () => {
|
it("uses the disconnect result without a second directory read", async () => {
|
||||||
const { result } = renderHook(useHostSessions);
|
const { result } = renderHook(useHostSessions);
|
||||||
await ready(result, 0);
|
await ready(result, 0);
|
||||||
|
const reads = mocks.read.mock.calls.length;
|
||||||
mocks.read.mockRejectedValue(new Error("directory_unavailable"));
|
mocks.read.mockRejectedValue(new Error("directory_unavailable"));
|
||||||
await act(async () => { await expect(result.current.disconnect(ids[0])).resolves.toBeUndefined(); });
|
await act(async () => { await expect(result.current.disconnect(ids[0])).resolves.toBeUndefined(); });
|
||||||
expect(result.current.selected).toBeNull();
|
expect(result.current.selected).toBeNull();
|
||||||
expect(result.current.frames).toHaveLength(0);
|
expect(result.current.frames).toHaveLength(0);
|
||||||
expect(result.current.directoryError).toBe(true);
|
expect(result.current.directory?.profiles.find((profile) => profile.id === ids[0])?.connected).toBe(false);
|
||||||
|
expect(mocks.read).toHaveBeenCalledTimes(reads);
|
||||||
|
expect(result.current.directoryError).toBe(false);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("keeps the current host until the destination view loads, then switches warm without RPC", async () => {
|
it("keeps the current host until the destination view loads, then switches warm without RPC", async () => {
|
||||||
|
|||||||
@@ -67,6 +67,7 @@ beforeEach(async () => {
|
|||||||
mocks.request.mockReset().mockImplementation(async (action: string) => {
|
mocks.request.mockReset().mockImplementation(async (action: string) => {
|
||||||
if (action === "remote.connect") return connection;
|
if (action === "remote.connect") return connection;
|
||||||
if (action === "remote.save") return { id: profile.id };
|
if (action === "remote.save") return { id: profile.id };
|
||||||
|
if (action === "remote.disconnect") return { available: true, profiles: [profile] };
|
||||||
return {};
|
return {};
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -860,6 +861,33 @@ describe("remote instance UX", () => {
|
|||||||
expect(mocks.request).toHaveBeenCalledWith("remote.disconnect", { id: profile.id }, 65_000);
|
expect(mocks.request).toHaveBeenCalledWith("remote.disconnect", { id: profile.id }, 65_000);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("keeps the current view when forgetting fails and closes it only after a successful retry", async () => {
|
||||||
|
view(); await openDirectory();
|
||||||
|
fireEvent.click(screen.getByRole("button", { name: "Team server ubuntu@example.test" }));
|
||||||
|
const frame = await readyRemote();
|
||||||
|
await openDirectory();
|
||||||
|
fireEvent.pointerDown(screen.getByRole("button", { name: "Manage Team server" }), { button: 0, ctrlKey: false });
|
||||||
|
fireEvent.click(await screen.findByRole("menuitem", { name: "Forget server" }));
|
||||||
|
const dialog = await screen.findByRole("dialog", { name: "Forget Team server?" });
|
||||||
|
mocks.request.mockImplementation(async (action: string) => {
|
||||||
|
if (action === "remote.remove") throw new Error("local_io_error");
|
||||||
|
return {};
|
||||||
|
});
|
||||||
|
fireEvent.click(within(dialog).getByRole("button", { name: "Forget server" }));
|
||||||
|
await within(dialog).findByRole("alert");
|
||||||
|
expect(readSelectedRemote()?.id).toBe(profile.id);
|
||||||
|
expect(frame).toBeInTheDocument();
|
||||||
|
expect(mocks.request.mock.calls.map(([action]) => action)).toEqual(["remote.connect", "remote.remove"]);
|
||||||
|
|
||||||
|
mocks.request.mockResolvedValue({ available: true, profiles: [] });
|
||||||
|
mocks.read.mockRejectedValue(new Error("directory_unavailable"));
|
||||||
|
fireEvent.click(within(dialog).getByRole("button", { name: "Forget server" }));
|
||||||
|
await waitFor(() => expect(frame).not.toBeInTheDocument());
|
||||||
|
expect(readSelectedRemote()).toBeNull();
|
||||||
|
expect(screen.queryByRole("button", { name: "Manage Team server" })).not.toBeInTheDocument();
|
||||||
|
expect(mocks.request.mock.calls.map(([action]) => action)).toEqual(["remote.connect", "remote.remove", "remote.remove"]);
|
||||||
|
});
|
||||||
|
|
||||||
it("refresh restores the selected remote, keeping the local shell hidden", async () => {
|
it("refresh restores the selected remote, keeping the local shell hidden", async () => {
|
||||||
rememberSelectedRemote(connection);
|
rememberSelectedRemote(connection);
|
||||||
view();
|
view();
|
||||||
|
|||||||
Reference in new issue
Block a user