fix(webui): scope remote health checks to visible demand (#6657)
* fix(webui): scope remote health checks to visible demand * fix(webui): simplify demand-driven health polling
This commit is contained in:
1 parent
ce3f36983d
commit
5e9810c1ad
15 files changed
+661
-95
No files matched your search
@@ -114,7 +114,7 @@ The host switcher lives beside **Settings at the bottom of the sidebar**, showin
|
||||
|
||||
Each isolated host view loads the same local WebUI and puts the switcher in the same sidebar location. A narrowly scoped, origin-, frame- and nonce-checked bridge sends the current host's display identity and coordinates menu placement, management layout and focus. The embedded view does not receive your host directory, SSH configuration or connection commands; the local shell owns those actions. This does not depend on the server's static WebUI bundle.
|
||||
|
||||
Refreshing restores the selected remote instance. A failed connection stays on a remote error screen; it never silently redirects work to your local agent. The selected server ID is stored per browser tab, without credentials. When the page becomes visible again or the browser reports network recovery, nanobot immediately rechecks existing connections. It does not reload the remote view, switch hosts, or resend messages. If the connection remains unavailable, use **Reconnect**. Different aliases resolving to the same already-connected gateway are rejected; choose its existing entry in the host switcher. Separate nanobot instances on one server can still use separate profiles and config paths.
|
||||
Refreshing restores the selected remote instance. A failed connection stays on a remote error screen; it never silently redirects work to your local agent. The selected server ID is stored per browser tab, without credentials. Periodic connection checks run only while the tab is visible: for the current remote host, or for existing connections shown in the host menu or **Manage connections…**. Hidden tabs and inactive retained views do not keep probing. Returning to a remote view, showing the tab again, or recovering the network rechecks the connections currently in view without reloading the remote page, switching hosts, or resending messages. If the connection remains unavailable, use **Reconnect**. Different aliases resolving to the same already-connected gateway are rejected; choose its existing entry in the host switcher. Separate nanobot instances on one server can still use separate profiles and config paths.
|
||||
|
||||
- **Switching hosts**, including returning local, keeps both pages mounted and keeps SSH connected. Each host retains its own chat, unsent draft, scroll position and UI state; nothing is copied between hosts. Up to three remote views are kept per tab. At the limit, explicitly disconnect one rather than silently discarding its work. Reloading the browser still follows each instance's normal draft persistence; unfinished uploads aren't guaranteed.
|
||||
- A first connection prepares a hidden server page while the current page stays usable. It switches after the page loads; **Cancel switch** keeps you where you are. The most recent choice wins even if an earlier SSH request finishes later. Cancelling navigation does not stop an in-flight server connection. The host view may still show a sign-in/startup indicator while its data connection initializes; returning to an already loaded view avoids that startup.
|
||||
|
||||
@@ -21,6 +21,7 @@ from nanobot.webui.remote_proxy import RemoteProxy
|
||||
from nanobot.webui.remote_ssh import RemoteError, RemoteProfile, Tunnel
|
||||
|
||||
_HEALTH_TIMEOUT_SECONDS = 12
|
||||
_HEALTH_FRESH_SECONDS = 5
|
||||
|
||||
|
||||
class _SavedProfile(RemoteProfile):
|
||||
@@ -42,6 +43,8 @@ class Connection:
|
||||
proxy: RemoteProxy
|
||||
error: str = ""
|
||||
paired: bool = False
|
||||
health_check: int | None = None
|
||||
health_checked_at: float = 0
|
||||
|
||||
|
||||
class RemoteInstances:
|
||||
@@ -60,6 +63,7 @@ class RemoteInstances:
|
||||
self._unverified: dict[str, tuple[str, str, float]] = {}
|
||||
self._unknown_hosts: set[str] = set()
|
||||
self._closed = False
|
||||
self._health_revision = 0
|
||||
self._compatibility: dict[str, Compatibility] = {}
|
||||
from nanobot.webui.remote_pairing import PairStore
|
||||
|
||||
@@ -136,6 +140,8 @@ class RemoteInstances:
|
||||
if connection:
|
||||
item["gateway_id"] = connection.gateway_id
|
||||
item["view_id"] = self._view_session
|
||||
if connection.health_check is not None:
|
||||
item["health_check"] = connection.health_check
|
||||
if key in self._compatibility:
|
||||
item["compatibility"] = self._compatibility[key]
|
||||
if not connection and (compatibility_failure := compatibility_error(self._compatibility[key])):
|
||||
@@ -157,22 +163,37 @@ class RemoteInstances:
|
||||
return {"available": True, "machine_name": socket.gethostname(),
|
||||
"client_version": __version__, "profiles": profiles}
|
||||
|
||||
async def health(self) -> dict[str, Any]:
|
||||
async def health(self, check: set[str] | None = None) -> dict[str, Any]:
|
||||
selected = {key: (item, item.health_check) for key, item in self.connections.items()
|
||||
if check is None or key in check}
|
||||
# Hold a lifetime lease through every credential-bearing request. Final
|
||||
# shutdown cannot release the listeners halfway through a health check.
|
||||
try:
|
||||
# Includes lock contention and all response reads, not just each
|
||||
# socket read. Return the directory before the browser's 20s budget.
|
||||
async with asyncio.timeout(_HEALTH_TIMEOUT_SECONDS):
|
||||
async with asyncio.timeout(_HEALTH_TIMEOUT_SECONDS) as budget:
|
||||
async with self._lock:
|
||||
await asyncio.gather(*(self._check(item) for item in self.connections.values()))
|
||||
if not self._closed:
|
||||
# Another tab may have checked, disconnected or replaced
|
||||
# this connection while we waited for its lifetime lease.
|
||||
due = [item for key, (item, revision) in selected.items()
|
||||
if self.connections.get(key) is item and item.health_check == revision
|
||||
and (item.health_check is None
|
||||
or time.monotonic() - item.health_checked_at >= _HEALTH_FRESH_SECONDS)]
|
||||
await asyncio.gather(*(self._check(item, budget=budget) for item in due))
|
||||
except TimeoutError:
|
||||
pass
|
||||
return self.snapshot()
|
||||
|
||||
async def _check(self, connection: Connection) -> None:
|
||||
def _record_health_check(self, connection: Connection) -> None:
|
||||
self._health_revision += 1
|
||||
connection.health_check = self._health_revision
|
||||
connection.health_checked_at = time.monotonic()
|
||||
|
||||
async def _check(self, connection: Connection, *, budget: asyncio.Timeout | None = None) -> None:
|
||||
if not connection.tunnel.active:
|
||||
connection.error = "ssh_unreachable"
|
||||
self._record_health_check(connection)
|
||||
return
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=20, trust_env=False) as client:
|
||||
@@ -205,8 +226,13 @@ class RemoteInstances:
|
||||
if connection.paired and connection.error == "ssh_auth_failed":
|
||||
connection.error = "pair_authorization_rejected"
|
||||
except asyncio.CancelledError:
|
||||
connection.error = "remote_unreachable"
|
||||
# A spent probe budget is a completed failure; a cancelled browser
|
||||
# request is not evidence of a distinct remote failure.
|
||||
if budget is not None and budget.expired():
|
||||
connection.error = "remote_unreachable"
|
||||
self._record_health_check(connection)
|
||||
raise
|
||||
self._record_health_check(connection)
|
||||
|
||||
async def action(self, action: str, payload: dict[str, Any]) -> dict[str, Any]:
|
||||
if action == "pick_file":
|
||||
|
||||
@@ -19,7 +19,7 @@ from collections.abc import Awaitable, Callable, Mapping
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING, Any, Protocol, TypeVar, cast
|
||||
from urllib.parse import quote, unquote, urlsplit, urlunsplit
|
||||
from urllib.parse import parse_qs, quote, unquote, urlsplit, urlunsplit
|
||||
|
||||
from loguru import logger
|
||||
from websockets.datastructures import Headers
|
||||
@@ -693,7 +693,21 @@ class GatewayHTTPHandler:
|
||||
return _http_error(403, "remote_connections_local_only")
|
||||
try:
|
||||
if path == "/api/remote-instances":
|
||||
return _http_json_response(await self.remote_instances.health(), extra_headers=_NO_STORE_HEADERS)
|
||||
parsed = urlsplit(request.path)
|
||||
try:
|
||||
if parsed.fragment or len(parsed.query) > 4096:
|
||||
raise ValueError
|
||||
query = parse_qs(parsed.query, keep_blank_values=True, strict_parsing=True, max_num_fields=20)
|
||||
if query.keys() - {"check"} or any(
|
||||
re.fullmatch(r"[0-9a-fA-F]{8}-(?:[0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}", key) is None
|
||||
for key in query.get("check", [])
|
||||
):
|
||||
raise ValueError
|
||||
except ValueError:
|
||||
return _http_error(400, "invalid_health_check")
|
||||
check = {key.lower() for key in query.get("check", [])}
|
||||
result = await self.remote_instances.health(check) if check else self.remote_instances.snapshot()
|
||||
return _http_json_response(result, extra_headers=_NO_STORE_HEADERS)
|
||||
if not getattr(request, _WEBUI_MUTATION_REQUEST_ATTR, False):
|
||||
return _http_error(405, "WebSocket required")
|
||||
payload = getattr(request, _WEBUI_MUTATION_PAYLOAD_ATTR, {})
|
||||
|
||||
@@ -48,8 +48,10 @@ def ssh(monkeypatch):
|
||||
monkeypatch.setattr(remote_ssh, "probe", probe)
|
||||
monkeypatch.setattr(remote_ssh, "open_tunnel", AsyncMock(return_value=tunnel))
|
||||
state = {"status": 200, "identity": {"protocolVersion": 1, "gatewayId": "remote-one", "webui": webui_contract()}}
|
||||
requests = []
|
||||
|
||||
def respond(request):
|
||||
requests.append(request.url.port)
|
||||
if request.url.path == "/webui/terminal":
|
||||
assert request.headers["X-Nanobot-Auth"] == "private-webui-secret"
|
||||
return httpx.Response(state["status"], json=state["identity"])
|
||||
@@ -57,7 +59,24 @@ def ssh(monkeypatch):
|
||||
|
||||
real_client = httpx.AsyncClient
|
||||
monkeypatch.setattr(httpx, "AsyncClient", lambda **kwargs: real_client(transport=httpx.MockTransport(respond), **kwargs))
|
||||
return SimpleNamespace(tunnel=tunnel, proxy=proxy, probe=probe, state=state, client=real_client)
|
||||
return SimpleNamespace(tunnel=tunnel, proxy=proxy, probe=probe, state=state, client=real_client, requests=requests)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def connected_hosts(manager, ssh, monkeypatch):
|
||||
first = await save(manager)
|
||||
await manager.action("connect", {"id": first})
|
||||
second = await save(manager, host="another-host")
|
||||
tunnel = SimpleNamespace(active=True, error="", port=23457, pause=AsyncMock(), close=AsyncMock())
|
||||
proxy = SimpleNamespace(tunnel=tunnel, port=23458, origin="http://127.0.0.1:23458",
|
||||
secret="local-two", pause=tunnel.pause, close=tunnel.close)
|
||||
monkeypatch.setattr(remote_ssh, "open_tunnel", AsyncMock(return_value=tunnel))
|
||||
RemoteProxy.open.return_value = proxy
|
||||
ssh.state["identity"]["gatewayId"] = "remote-two"
|
||||
await manager.action("connect", {"id": second})
|
||||
ssh.state["identity"]["gatewayId"] = "remote-one"
|
||||
ssh.requests.clear()
|
||||
return first, second
|
||||
|
||||
|
||||
async def test_save_survives_restart_without_credentials(manager):
|
||||
@@ -446,8 +465,11 @@ async def test_health_deadline_returns_editable_offline_directory(manager, ssh,
|
||||
key = await save(manager)
|
||||
await manager.action("connect", {"id": key})
|
||||
cancelled = asyncio.Event()
|
||||
checks = 0
|
||||
|
||||
async def respond(request):
|
||||
nonlocal checks
|
||||
checks += 1
|
||||
try:
|
||||
await asyncio.Event().wait()
|
||||
finally:
|
||||
@@ -459,7 +481,10 @@ async def test_health_deadline_returns_editable_offline_directory(manager, ssh,
|
||||
))
|
||||
directory = await asyncio.wait_for(manager.health(), 1)
|
||||
assert not directory["profiles"][0]["connected"]
|
||||
assert directory["profiles"][0]["health_check"] > 0
|
||||
assert cancelled.is_set()
|
||||
assert (await manager.health({key}))["profiles"] == directory["profiles"]
|
||||
assert checks == 1
|
||||
await manager.action("save", {"id": key, "profile": {
|
||||
"name": "Repaired", "host": "ubuntu@example.test",
|
||||
}})
|
||||
@@ -473,6 +498,8 @@ async def test_health_budget_includes_waiting_for_connection_lock(manager, ssh,
|
||||
async with manager._lock:
|
||||
directory = await asyncio.wait_for(manager.health(), 1)
|
||||
assert directory["profiles"][0]["id"] == key
|
||||
assert "health_check" not in directory["profiles"][0]
|
||||
assert ssh.requests == [23455] # Only the initial connection verification.
|
||||
|
||||
|
||||
async def test_reconnect_keeps_origin_and_changing_target_does_not(manager, ssh):
|
||||
@@ -678,6 +705,235 @@ def gateway(tmp_path):
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def read_directory(gateway, manager, monkeypatch):
|
||||
monkeypatch.setattr(gateway.http, "remote_instances", manager)
|
||||
token = gateway.tokens.issue_api_token(60)
|
||||
connection = SimpleNamespace(remote_address=("127.0.0.1", 10000))
|
||||
|
||||
async def read(query=""):
|
||||
request = Request("/api/remote-instances" + (f"?{query}" if query else ""), Headers({
|
||||
"Host": "127.0.0.1:8765", "Authorization": f"Bearer {token}",
|
||||
}))
|
||||
return await gateway.http.dispatch(connection, request)
|
||||
|
||||
return read
|
||||
|
||||
|
||||
async def test_directory_snapshot_does_not_probe_or_wait_for_health_lock(manager, ssh, read_directory):
|
||||
key = await save(manager)
|
||||
await manager.action("connect", {"id": key})
|
||||
await save(manager, host="saved-only")
|
||||
ssh.requests.clear()
|
||||
ssh.state["status"] = 503
|
||||
async with manager._lock:
|
||||
response = await asyncio.wait_for(read_directory(), 1)
|
||||
assert response.status_code == 200
|
||||
assert response.headers["Cache-Control"] == "no-store"
|
||||
assert json.loads(response.body) == manager.snapshot()
|
||||
assert ssh.requests == []
|
||||
ssh.probe.assert_awaited_once()
|
||||
|
||||
|
||||
async def test_directory_checks_only_requested_existing_connections(
|
||||
manager, ssh, connected_hosts, read_directory,
|
||||
):
|
||||
first, second = connected_hosts
|
||||
disconnected = await save(manager, host="saved-only")
|
||||
response = await read_directory(
|
||||
f"check={first}&check={first.upper()}&check={disconnected}&check=00000000-0000-0000-0000-000000000000",
|
||||
)
|
||||
assert response.status_code == 200
|
||||
profiles = {item["id"]: item for item in json.loads(response.body)["profiles"]}
|
||||
assert set(profiles) == {first, second, disconnected}
|
||||
assert profiles[first]["connected"]
|
||||
assert profiles[first]["health_check"] > 0
|
||||
assert "health_check" not in profiles[second]
|
||||
assert "health_check" not in profiles[disconnected]
|
||||
assert profiles[disconnected]["connection_error"] == "disconnected"
|
||||
assert ssh.requests == [23455]
|
||||
assert ssh.probe.await_count == 2
|
||||
|
||||
|
||||
@pytest.mark.parametrize("status", [200, 503])
|
||||
async def test_overlapping_and_recent_directory_checks_share_results(
|
||||
manager, ssh, connected_hosts, read_directory, monkeypatch, status,
|
||||
):
|
||||
first, second = connected_hosts
|
||||
entered, release = asyncio.Event(), asyncio.Event()
|
||||
checked = []
|
||||
now = 100.0
|
||||
monkeypatch.setattr(remote_instances, "time", SimpleNamespace(monotonic=lambda: now))
|
||||
|
||||
async def respond(request):
|
||||
checked.append(request.url.port)
|
||||
entered.set()
|
||||
await release.wait()
|
||||
identity = {**ssh.state["identity"],
|
||||
"gatewayId": "remote-one" if request.url.port == 23455 else "remote-two"}
|
||||
return httpx.Response(status, json=identity)
|
||||
|
||||
monkeypatch.setattr(httpx, "AsyncClient", lambda **kwargs: ssh.client(
|
||||
transport=httpx.MockTransport(respond), **kwargs,
|
||||
))
|
||||
one = asyncio.create_task(read_directory(f"check={first}"))
|
||||
await asyncio.wait_for(entered.wait(), 2)
|
||||
both = asyncio.create_task(read_directory(f"check={first}&check={second}"))
|
||||
try:
|
||||
cancelled = asyncio.create_task(read_directory(f"check={first}"))
|
||||
await asyncio.sleep(0)
|
||||
cancelled.cancel()
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await cancelled
|
||||
assert not one.done()
|
||||
assert not both.done()
|
||||
assert checked == [23455]
|
||||
finally:
|
||||
release.set()
|
||||
one_response, both_response = await asyncio.gather(one, both)
|
||||
first_profile = json.loads(one_response.body)["profiles"][0]
|
||||
profiles = json.loads(both_response.body)["profiles"]
|
||||
assert first_profile["health_check"] == profiles[0]["health_check"]
|
||||
assert all(item["connected"] == (status == 200) for item in profiles)
|
||||
assert checked == [23455, 23457]
|
||||
now += 4.9
|
||||
recent = await read_directory(f"check={first}&check={second}")
|
||||
assert json.loads(recent.body)["profiles"] == profiles
|
||||
assert checked == [23455, 23457]
|
||||
now += 0.2
|
||||
refreshed = json.loads((await read_directory(f"check={first}&check={second}")).body)["profiles"]
|
||||
assert all(new["health_check"] != old["health_check"] for new, old in zip(refreshed, profiles))
|
||||
assert checked == [23455, 23457, 23455, 23457]
|
||||
|
||||
|
||||
async def test_overlapping_check_is_reused_even_if_another_host_holds_the_lock(
|
||||
manager, ssh, connected_hosts, read_directory, monkeypatch,
|
||||
):
|
||||
first, second = connected_hosts
|
||||
entered, first_replied = asyncio.Event(), asyncio.Event()
|
||||
release_first, release_second = asyncio.Event(), asyncio.Event()
|
||||
checked = []
|
||||
now = 100.0
|
||||
monkeypatch.setattr(remote_instances, "time", SimpleNamespace(monotonic=lambda: now))
|
||||
|
||||
async def respond(request):
|
||||
checked.append(request.url.port)
|
||||
if request.url.port == 23455:
|
||||
entered.set()
|
||||
await release_first.wait()
|
||||
first_replied.set()
|
||||
else:
|
||||
await release_second.wait()
|
||||
return httpx.Response(503)
|
||||
|
||||
monkeypatch.setattr(httpx, "AsyncClient", lambda **kwargs: ssh.client(
|
||||
transport=httpx.MockTransport(respond), **kwargs,
|
||||
))
|
||||
both = asyncio.create_task(read_directory(f"check={first}&check={second}"))
|
||||
await asyncio.wait_for(entered.wait(), 2)
|
||||
one = asyncio.create_task(read_directory(f"check={first}"))
|
||||
try:
|
||||
await asyncio.sleep(0)
|
||||
release_first.set()
|
||||
await asyncio.wait_for(first_replied.wait(), 2)
|
||||
assert manager.connections[first].health_check is not None
|
||||
now += 6
|
||||
finally:
|
||||
release_first.set()
|
||||
release_second.set()
|
||||
both_response, one_response = await asyncio.gather(both, one)
|
||||
assert checked == [23455, 23457]
|
||||
assert json.loads(one_response.body)["profiles"] == json.loads(both_response.body)["profiles"]
|
||||
|
||||
|
||||
async def test_queued_health_does_not_check_replaced_connection(manager, ssh, read_directory):
|
||||
key = await save(manager)
|
||||
await manager.action("connect", {"id": key})
|
||||
first = json.loads((await read_directory(f"check={key}")).body)["profiles"][0]
|
||||
previous = manager.connections[key]
|
||||
ssh.requests.clear()
|
||||
async with manager._lock:
|
||||
disconnect = asyncio.create_task(manager.action("disconnect", {"id": key}))
|
||||
reconnect = asyncio.create_task(manager.action("connect", {"id": key}))
|
||||
health = asyncio.create_task(read_directory(f"check={key}"))
|
||||
await asyncio.sleep(0)
|
||||
disconnected, _, response = await asyncio.gather(disconnect, reconnect, health)
|
||||
assert "health_check" not in disconnected["profiles"][0]
|
||||
assert manager.connections[key] is not previous
|
||||
assert "health_check" not in json.loads(response.body)["profiles"][0]
|
||||
assert ssh.requests == [23455] # Reconnect verification, not the obsolete demand.
|
||||
refreshed = json.loads((await read_directory(f"check={key}")).body)["profiles"][0]
|
||||
assert refreshed["health_check"] != first["health_check"]
|
||||
assert ssh.requests == [23455, 23455]
|
||||
|
||||
|
||||
async def test_cancelled_health_retains_lifetime_lock_until_request_cleanup(
|
||||
manager, ssh, read_directory, monkeypatch,
|
||||
):
|
||||
key = await save(manager)
|
||||
await manager.action("connect", {"id": key})
|
||||
entered, cleaning, release = asyncio.Event(), asyncio.Event(), asyncio.Event()
|
||||
|
||||
async def respond(request):
|
||||
entered.set()
|
||||
try:
|
||||
await asyncio.Event().wait()
|
||||
finally:
|
||||
cleaning.set()
|
||||
await release.wait()
|
||||
ssh.tunnel.close.assert_not_awaited()
|
||||
|
||||
monkeypatch.setattr(httpx, "AsyncClient", lambda **kwargs: ssh.client(
|
||||
transport=httpx.MockTransport(respond), **kwargs,
|
||||
))
|
||||
health = asyncio.create_task(read_directory(f"check={key}"))
|
||||
await asyncio.wait_for(entered.wait(), 2)
|
||||
health.cancel()
|
||||
await asyncio.wait_for(cleaning.wait(), 2)
|
||||
shutdown = asyncio.create_task(manager.close())
|
||||
try:
|
||||
await asyncio.sleep(0)
|
||||
assert not shutdown.done()
|
||||
assert manager._lock.locked()
|
||||
assert "health_check" not in manager.snapshot()["profiles"][0]
|
||||
ssh.tunnel.close.assert_not_awaited()
|
||||
finally:
|
||||
release.set()
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await health
|
||||
await shutdown
|
||||
ssh.tunnel.close.assert_awaited_once()
|
||||
assert "health_check" not in manager.snapshot()["profiles"][0]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("query", [
|
||||
"check", "check=", "check=not-an-id", "other=value", "check=%GG",
|
||||
"check=00000000-0000-0000-0000-000000000000&other=value",
|
||||
"check=00000000-0000-0000-0000-000000000000&",
|
||||
"check=00000000-0000-0000-0000-000000000000%00",
|
||||
"check=00000000-0000-0000-0000-000000000000#fragment",
|
||||
"check=" + "a" * 4097,
|
||||
"&".join(["check=00000000-0000-0000-0000-000000000000"] * 21),
|
||||
])
|
||||
async def test_invalid_health_query_is_rejected_before_probing(manager, ssh, read_directory, query):
|
||||
key = await save(manager)
|
||||
await manager.action("connect", {"id": key})
|
||||
ssh.requests.clear()
|
||||
response = await read_directory(query)
|
||||
assert response.status_code == 400
|
||||
assert response.body == b"invalid_health_check"
|
||||
assert ssh.requests == []
|
||||
|
||||
|
||||
async def test_maximum_duplicate_checks_probe_once(manager, ssh, read_directory):
|
||||
key = await save(manager)
|
||||
await manager.action("connect", {"id": key})
|
||||
ssh.requests.clear()
|
||||
response = await read_directory("&".join([f"check={key}"] * 20))
|
||||
assert response.status_code == 200
|
||||
assert ssh.requests == [23455]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("action", ["save", "discover", "inspect", "pick_file", "connect", "remove", "trust"])
|
||||
async def test_http_mutations_are_not_gettable_even_with_token(gateway, action):
|
||||
request = Request(f"/api/remote-instances/{action}", Headers())
|
||||
@@ -742,13 +998,14 @@ async def test_remote_clients_cannot_open_local_file_picker(gateway, monkeypatch
|
||||
("127.0.0.1", "bot.example.com", "https://bot.example.com", 403),
|
||||
("127.0.0.1", "127.0.0.1:8765", "https://evil.example", 403),
|
||||
])
|
||||
async def test_ssh_access_is_local_and_authenticated(gateway, peer, host, origin, status):
|
||||
@pytest.mark.parametrize("query", ["", "?check=00000000-0000-0000-0000-000000000000"])
|
||||
async def test_ssh_access_is_local_and_authenticated(gateway, peer, host, origin, status, query):
|
||||
token = gateway.tokens.issue_api_token(60)
|
||||
connection = SimpleNamespace(remote_address=(peer, 10000))
|
||||
request = Request("/api/remote-instances", Headers({"Host": host, "Origin": origin, "Authorization": f"Bearer {token}"}))
|
||||
request = Request("/api/remote-instances" + query, Headers({"Host": host, "Origin": origin, "Authorization": f"Bearer {token}"}))
|
||||
result = await gateway.http.dispatch(connection, request)
|
||||
assert result.status_code == status
|
||||
request = Request("/api/remote-instances", Headers({"Host": host}))
|
||||
request = Request("/api/remote-instances" + query, Headers({"Host": host}))
|
||||
assert (await gateway.http.dispatch(connection, request)).status_code == 401
|
||||
|
||||
|
||||
|
||||
@@ -346,7 +346,7 @@ async def test_rename_paired_instance_updates_only_verified_sibling_grants(tmp_p
|
||||
before = manager._read()
|
||||
receipts = {item.id: manager.pairing.path(item.id).joinpath("receipt").read_bytes() for item in requests}
|
||||
live = SimpleNamespace(tunnel=SimpleNamespace(active=True), error="", gateway_id="live-session",
|
||||
proxy=SimpleNamespace(pause=AsyncMock()))
|
||||
health_check=None, health_checked_at=0, proxy=SimpleNamespace(pause=AsyncMock()))
|
||||
manager.connections[first.id] = live
|
||||
result = await manager.action("rename", {"id": requests[1].id, "name": "My cloud"})
|
||||
assert [p["name"] for p in result["profiles"]] == ["My cloud", "My cloud", original.hostname]
|
||||
@@ -369,7 +369,7 @@ async def test_repair_retains_route_and_reuses_only_a_healthy_existing_connectio
|
||||
profiles[first.id].local_port = 23456
|
||||
manager._write(profiles)
|
||||
live = SimpleNamespace(tunnel=SimpleNamespace(active=True), error="", gateway_id="live-session",
|
||||
proxy=SimpleNamespace(pause=AsyncMock()))
|
||||
health_check=None, health_checked_at=0, proxy=SimpleNamespace(pause=AsyncMock()))
|
||||
manager.connections[first.id] = live
|
||||
|
||||
async def check(connection):
|
||||
|
||||
@@ -23,6 +23,7 @@ function HostMenuContent({ picker, portalContainer }: { picker: HostPicker; port
|
||||
/** Mounted with the menu so every opening starts with a fresh, stable list. */
|
||||
function HostMenuItems({ picker }: { picker: HostPicker }) {
|
||||
const { t } = useTranslation();
|
||||
useEffect(() => picker.watchDirectory?.(), [picker.watchDirectory]);
|
||||
const [searchable] = useState(() => picker.profiles.length > 5);
|
||||
const [query, setQuery] = useState("");
|
||||
const [order] = useState(() => [picker.currentId, ...picker.recentIds]);
|
||||
|
||||
@@ -71,6 +71,9 @@ export function RemoteConnectionsPage({ mainNavigationExpanded = false, hostChro
|
||||
const nameId = useId();
|
||||
const nameInput = useRef<HTMLInputElement>(null);
|
||||
const refresh = connections?.refresh;
|
||||
const watchDirectory = connections?.watchDirectory;
|
||||
const visible = connections?.localActive || connections?.managing;
|
||||
useEffect(() => { if (visible) return watchDirectory?.(); }, [visible, watchDirectory]);
|
||||
const page = useRef<HTMLDivElement>(null);
|
||||
useEffect(() => { if (connections?.managing) page.current?.focus({ preventScroll: true }); }, [connections?.managing]);
|
||||
|
||||
|
||||
@@ -118,7 +118,7 @@ export function RemoteInstances({ children }: { children: ReactNode }) {
|
||||
else if (managing) void connect(id).catch(() => {});
|
||||
else switchHost(id);
|
||||
},
|
||||
manage,
|
||||
manage, watchDirectory: hosts.watchDirectory,
|
||||
cancel: hosts.cancel, clearError: hosts.clearError, restoreFocus: () => { if (!managing) restoreFocus(); },
|
||||
};
|
||||
useEffect(() => { if (selected) document.title = selected.name; }, [selected]);
|
||||
@@ -149,7 +149,7 @@ export function RemoteInstances({ children }: { children: ReactNode }) {
|
||||
embeddedManagement: !!bridge.embedded, reportManagementSurface: bridge.embedded ? bridge.reportSurface : undefined,
|
||||
closeManagement: bridge.embedded ? bridge.leaveManagement : () => changeManagement(false), selectLocal,
|
||||
openHostIds: frames.map((frame) => frame.connection.id),
|
||||
directoryError: hosts.directoryError, refresh: hosts.refresh, rename: hosts.rename, connect, disconnect: hosts.disconnect, remove: hosts.remove, cancel: hosts.cancel }}>
|
||||
directoryError: hosts.directoryError, refresh: hosts.refresh, watchDirectory: hosts.watchDirectory, rename: hosts.rename, connect, disconnect: hosts.disconnect, remove: hosts.remove, cancel: hosts.cancel }}>
|
||||
<HostNavigationContext.Provider value={bridge.embedded || (available || selected ? picker : null)}>
|
||||
<div className="flex h-full min-h-0 flex-col bg-background">
|
||||
<div className="relative min-h-0 flex-1 overflow-hidden">
|
||||
|
||||
@@ -20,6 +20,7 @@ export interface HostPicker {
|
||||
cancel: () => void;
|
||||
clearError: () => void;
|
||||
restoreFocus: () => void;
|
||||
watchDirectory?: () => () => void;
|
||||
}
|
||||
export interface EmbeddedPicker extends EmbeddedHost {
|
||||
kind: "embedded";
|
||||
|
||||
@@ -19,6 +19,7 @@ export const RemoteContext = createContext<{
|
||||
directory: RemoteDirectory | null;
|
||||
directoryError: boolean;
|
||||
refresh: () => Promise<RemoteDirectory>;
|
||||
watchDirectory: () => () => void;
|
||||
rename: (id: string, name: string) => Promise<void>;
|
||||
connect: (id: string, stillWanted?: () => boolean) => Promise<void>;
|
||||
disconnect: (id: string) => Promise<void>;
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { useClient } from "@/providers/ClientProvider";
|
||||
import { usePageVisibility } from "@/hooks/usePageVisibility";
|
||||
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";
|
||||
import { needsRemoteSetup, 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.
|
||||
@@ -11,6 +12,7 @@ export interface HostFrame {
|
||||
loaded: boolean;
|
||||
offline: boolean;
|
||||
failures: number;
|
||||
healthCheck?: number;
|
||||
error?: string;
|
||||
}
|
||||
interface PendingSwitch { id: string; name: string }
|
||||
@@ -18,7 +20,17 @@ interface SwitchFailure { id: string; code: string }
|
||||
|
||||
export function useHostSessions() {
|
||||
const { client, getToken } = useClient();
|
||||
const pageVisible = usePageVisibility();
|
||||
const [directory, setDirectory] = useState<RemoteDirectory | null>(null);
|
||||
const directoryRef = useRef(directory);
|
||||
const directoryRead = useRef<{ generation: number; ids: string[]; promise: Promise<RemoteDirectory> } | null>(null);
|
||||
const observers = useRef(0);
|
||||
const [observing, setObserving] = useState(false);
|
||||
const watchDirectory = useCallback(() => {
|
||||
observers.current += 1;
|
||||
setObserving(true);
|
||||
return () => { observers.current -= 1; setObserving(observers.current > 0); };
|
||||
}, []);
|
||||
const [directoryError, setDirectoryError] = useState(false);
|
||||
const [selected, setSelected] = useState<SelectedRemote | null>(() => readPairReturn() ? null : readSelectedRemote());
|
||||
const [recentIds, setRecentIds] = useState(readRecentRemotes);
|
||||
@@ -66,6 +78,7 @@ export function useHostSessions() {
|
||||
return true;
|
||||
}, [cancel, select]);
|
||||
const applyDirectory = useCallback((next: RemoteDirectory) => {
|
||||
directoryRef.current = next;
|
||||
setDirectory(next); setDirectoryError(false);
|
||||
// Names are metadata, not a new host session. Keep iframe URLs, drafts,
|
||||
// selection and connection state intact when this or another tab renames.
|
||||
@@ -92,39 +105,106 @@ export function useHostSessions() {
|
||||
directoryGeneration.current += 1;
|
||||
if (mounted.current) applyDirectory(next);
|
||||
}, [applyDirectory, client]);
|
||||
const refresh = useCallback(async () => {
|
||||
const generation = ++directoryGeneration.current;
|
||||
try {
|
||||
const next = window.top === window ? await readRemoteInstances(getToken()) : { available: false, profiles: [] };
|
||||
if (mounted.current && generation === directoryGeneration.current) applyDirectory(next);
|
||||
return next;
|
||||
} catch (reason) {
|
||||
if (mounted.current && generation === directoryGeneration.current) setDirectoryError(true);
|
||||
throw reason;
|
||||
const readDirectory = useCallback(function read(ids: string[] = [], wanted: () => boolean = () => true): Promise<RemoteDirectory> {
|
||||
if (!mounted.current || !wanted()) return Promise.resolve(directoryRef.current || { available: false, profiles: [] });
|
||||
if (window.top !== window) {
|
||||
const next = { available: false, profiles: [] };
|
||||
if (mounted.current) applyDirectory(next);
|
||||
return Promise.resolve(next);
|
||||
}
|
||||
}, [applyDirectory, getToken]);
|
||||
// Visibility affects observation, never the shared transport's lifetime.
|
||||
if (document.visibilityState === "hidden") ids = [];
|
||||
const generation = directoryGeneration.current;
|
||||
const pendingRead = directoryRead.current;
|
||||
if (pendingRead?.generation === generation) {
|
||||
if (ids.every((id) => pendingRead.ids.includes(id))) return pendingRead.promise;
|
||||
return pendingRead.promise.catch(() => {}).then(() => read(ids, wanted));
|
||||
}
|
||||
const promise = readRemoteInstances(getToken(), ids).then((next) => {
|
||||
if (!mounted.current || generation !== directoryGeneration.current) return next;
|
||||
applyDirectory(next);
|
||||
for (const [id, frame] of cache.current) {
|
||||
if (id === pendingRef.current?.id) continue;
|
||||
const profile = next.profiles.find((item) => item.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;
|
||||
// Missing connections and changed identities are authoritative, not a
|
||||
// transient probe failure. A cached probe must not count twice.
|
||||
if (connected) frame.failures = 0;
|
||||
else if (!profile?.gateway_id || changed || needsRemoteSetup(profile.connection_error || "")) frame.failures = 2;
|
||||
else if (profile.health_check !== frame.healthCheck) frame.failures += 1;
|
||||
frame.healthCheck = profile?.health_check;
|
||||
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);
|
||||
}
|
||||
if (cache.current.size) publish();
|
||||
return next;
|
||||
}).catch((reason: unknown) => {
|
||||
if (mounted.current && generation === directoryGeneration.current) {
|
||||
setDirectoryError(true);
|
||||
for (const id of ids) {
|
||||
const frame = cache.current.get(id);
|
||||
if (frame && id !== pendingRef.current?.id && ++frame.failures >= 2) {
|
||||
frame.offline = true; frame.error = "directory_unavailable";
|
||||
}
|
||||
}
|
||||
if (ids.length) publish();
|
||||
}
|
||||
throw reason;
|
||||
});
|
||||
directoryRead.current = { generation, ids, promise };
|
||||
const finish = () => { if (directoryRead.current?.promise === promise) directoryRead.current = null; };
|
||||
void promise.then(finish, finish);
|
||||
return promise;
|
||||
}, [applyDirectory, getToken, publish]);
|
||||
const healthTargets = useCallback(() => {
|
||||
const profiles = directoryRef.current?.profiles ?? [];
|
||||
const ids = observers.current ? profiles.filter((profile) => profile.gateway_id).map((profile) => profile.id) : [];
|
||||
if (selectedRef.current && cache.current.has(selectedRef.current.id)) ids.push(selectedRef.current.id);
|
||||
return [...new Set(ids)].filter((id) => id !== pendingRef.current?.id);
|
||||
}, []);
|
||||
const refresh = useCallback(async () => {
|
||||
const next = await readDirectory();
|
||||
const ids = healthTargets();
|
||||
return mounted.current && document.visibilityState !== "hidden" && ids.length ? readDirectory(ids) : next;
|
||||
}, [healthTargets, readDirectory]);
|
||||
|
||||
const connect = useCallback(async (id: string, stillWanted: () => boolean = () => true) => {
|
||||
cancel();
|
||||
const attempt = epoch.current;
|
||||
const wanted = () => mounted.current && attempt === epoch.current && stillWanted();
|
||||
const warm = cache.current.get(id);
|
||||
if (warm?.loaded && !warm.offline) {
|
||||
if (wanted()) select(warm.connection);
|
||||
return;
|
||||
}
|
||||
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 });
|
||||
setFailure(null);
|
||||
let openingFrame = warm?.loaded ? undefined : warm;
|
||||
try {
|
||||
if (warm?.loaded && !warm.offline) {
|
||||
// A retained view may have spent hours unobserved. Check its identity
|
||||
// before reusing it, without reloading the iframe or reconnecting SSH.
|
||||
const next = await readDirectory([id], wanted);
|
||||
if (!wanted()) return;
|
||||
const profile = next.profiles.find((item) => item.id === id);
|
||||
if (profile?.connected && profile.gateway_id === warm.connection.gateway_id
|
||||
&& profile.view_id === warm.connection.view_id) {
|
||||
select(warm.connection);
|
||||
return;
|
||||
}
|
||||
warm.offline = true;
|
||||
publish();
|
||||
}
|
||||
const connection = validateRemoteConnection(await remoteAction<RemoteConnection>(client, "connect", { id }));
|
||||
// Reads started before or during this mutation describe the old tunnel.
|
||||
directoryGeneration.current += 1;
|
||||
if (!wanted()) {
|
||||
// A cancelled SSH request can finish later. Never switch away from the
|
||||
// latest choice or close its tunnel, which another tab may already use.
|
||||
@@ -141,7 +221,7 @@ export function useHostSessions() {
|
||||
}
|
||||
if (!frame.loaded) openingFrame = frame;
|
||||
publish();
|
||||
void refresh().catch(() => {});
|
||||
void readDirectory().catch(() => {});
|
||||
if (!frame.loaded) {
|
||||
const ready = await new Promise<boolean>((resolve, reject) => {
|
||||
const timer = window.setTimeout(() => {
|
||||
@@ -171,7 +251,7 @@ export function useHostSessions() {
|
||||
}
|
||||
if (attempt === epoch.current) setPendingSwitch(null);
|
||||
}
|
||||
}, [cancel, client, directory, publish, refresh, select, setPendingSwitch]);
|
||||
}, [cancel, client, directory, publish, readDirectory, refresh, select, setPendingSwitch]);
|
||||
const connectRef = useRef(connect);
|
||||
connectRef.current = connect;
|
||||
const loaded = useCallback((id: string) => {
|
||||
@@ -197,9 +277,9 @@ export function useHostSessions() {
|
||||
|
||||
useEffect(() => {
|
||||
mounted.current = true;
|
||||
void refresh().catch(() => {});
|
||||
return () => { mounted.current = false; cancel(); };
|
||||
}, [cancel, refresh]);
|
||||
void readDirectory().catch(() => {});
|
||||
return () => { mounted.current = false; directoryGeneration.current += 1; cancel(); };
|
||||
}, [cancel, readDirectory]);
|
||||
useEffect(() => {
|
||||
const saved = initial.current;
|
||||
if (!saved || window.top !== window) return;
|
||||
@@ -222,53 +302,43 @@ export function useHostSessions() {
|
||||
return () => { window.clearTimeout(timer); unsubscribe(); };
|
||||
}, [client, setPendingSwitch]);
|
||||
useEffect(() => {
|
||||
let checking = false;
|
||||
let cancelled = false;
|
||||
const tick = async () => {
|
||||
if (checking || !cache.current.size) return;
|
||||
checking = true;
|
||||
const generation = ++directoryGeneration.current;
|
||||
if (window.top !== window || !pageVisible || (!selected?.id && !observing)) return;
|
||||
let disposed = false;
|
||||
let running = false;
|
||||
let refreshPending = false;
|
||||
let timer: number | undefined;
|
||||
const hidden = () => document.visibilityState === "hidden";
|
||||
const poll = async (readList = false) => {
|
||||
if (disposed || hidden()) return;
|
||||
if (running) { refreshPending = true; return; }
|
||||
running = true;
|
||||
window.clearTimeout(timer);
|
||||
try {
|
||||
const next = await readRemoteInstances(getToken());
|
||||
if (cancelled || generation !== directoryGeneration.current) return;
|
||||
applyDirectory(next);
|
||||
for (const [id, frame] of cache.current) {
|
||||
if (id === pendingRef.current?.id) continue;
|
||||
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;
|
||||
frame.error = connected ? "" : changed ? "instance_changed" : profile?.connection_error || (!profile ? "profile_not_found" : "");
|
||||
}
|
||||
if (connected && frame.loaded) setFailure((current) => current?.id === id ? null : current);
|
||||
}
|
||||
do {
|
||||
refreshPending = false;
|
||||
if (readList || (observing && !healthTargets().length)) await readDirectory([], () => !disposed && !hidden());
|
||||
if (disposed || hidden()) break;
|
||||
const ids = healthTargets();
|
||||
if (ids.length) await readDirectory(ids, () => !disposed && !hidden());
|
||||
} while (refreshPending && !disposed);
|
||||
} catch {
|
||||
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"; }
|
||||
}
|
||||
// Keep the retained page; readDirectory owns health/error projection.
|
||||
} finally {
|
||||
checking = false;
|
||||
if (!cancelled) publish();
|
||||
running = false;
|
||||
if (refreshPending && !disposed && !hidden()) void poll(true);
|
||||
else if (!disposed && (healthTargets().length || observing)) timer = window.setTimeout(() => void poll(), 5_000);
|
||||
}
|
||||
};
|
||||
const timer = window.setInterval(() => { void tick(); }, 5_000);
|
||||
// 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(); };
|
||||
const wake = () => { void poll(true); };
|
||||
window.addEventListener("online", wake);
|
||||
window.addEventListener("pageshow", wake);
|
||||
document.addEventListener("visibilitychange", wake);
|
||||
void poll(true);
|
||||
return () => {
|
||||
cancelled = true; window.clearInterval(timer);
|
||||
disposed = true; window.clearTimeout(timer);
|
||||
window.removeEventListener("online", wake);
|
||||
window.removeEventListener("pageshow", wake);
|
||||
document.removeEventListener("visibilitychange", wake);
|
||||
};
|
||||
}, [applyDirectory, client, getToken, publish]);
|
||||
return { directory, directoryError, refresh, rename, selected, recentIds, frames, pending,
|
||||
}, [healthTargets, observing, pageVisible, pending?.id, readDirectory, selected?.id]);
|
||||
return { directory, directoryError, refresh, watchDirectory, rename, selected, recentIds, frames, pending,
|
||||
error: failure?.code || "", errorId: failure?.id, clearError, connect, cancel, local, reveal, disconnect, remove, loaded };
|
||||
}
|
||||
@@ -24,6 +24,7 @@ export interface RemoteProfile {
|
||||
gateway_id?: string;
|
||||
view_id?: string;
|
||||
connection_error?: string;
|
||||
health_check?: number;
|
||||
paired?: boolean;
|
||||
/** Opaque grouping ID supplied only after the local backend verifies receipts. */
|
||||
instance_id?: string;
|
||||
@@ -97,8 +98,9 @@ export interface RemoteInspection {
|
||||
incomplete: boolean;
|
||||
}
|
||||
|
||||
export async function readRemoteInstances(token: string): Promise<RemoteDirectory> {
|
||||
const response = await fetchWithTimeout("/api/remote-instances", {
|
||||
export async function readRemoteInstances(token: string, check: string[] = []): Promise<RemoteDirectory> {
|
||||
const query = new URLSearchParams(check.map((id) => ["check", id]));
|
||||
const response = await fetchWithTimeout(`/api/remote-instances${query.size ? `?${query}` : ""}`, {
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
});
|
||||
if (response.status === 403 || response.status === 404) return { available: false, profiles: [] };
|
||||
|
||||
@@ -31,6 +31,7 @@ async function ready(result: { current: Session }, index: number) {
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
Object.defineProperty(document, "visibilityState", { configurable: true, get: () => "visible" });
|
||||
vi.useFakeTimers();
|
||||
window.sessionStorage.clear();
|
||||
mocks.read.mockReset().mockResolvedValue(directory);
|
||||
@@ -43,6 +44,170 @@ beforeEach(() => {
|
||||
afterEach(() => { cleanup(); vi.useRealTimers(); vi.restoreAllMocks(); });
|
||||
|
||||
describe("host session lifecycle", () => {
|
||||
it("does not probe retained remote views while local or hidden, and rechecks on return", async () => {
|
||||
let visibility: DocumentVisibilityState = "visible";
|
||||
vi.spyOn(document, "visibilityState", "get").mockImplementation(() => visibility);
|
||||
const { result } = renderHook(useHostSessions);
|
||||
await ready(result, 0);
|
||||
act(() => result.current.local());
|
||||
mocks.read.mockClear();
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(30_000); });
|
||||
expect(mocks.read).not.toHaveBeenCalled();
|
||||
await act(async () => { await result.current.connect(ids[0]); });
|
||||
expect(mocks.read.mock.calls.some(([, targets]) => targets?.includes(ids[0]))).toBe(true);
|
||||
act(() => { visibility = "hidden"; document.dispatchEvent(new Event("visibilitychange")); });
|
||||
mocks.read.mockClear();
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(30_000); });
|
||||
expect(mocks.read).not.toHaveBeenCalled();
|
||||
await act(async () => { visibility = "visible"; document.dispatchEvent(new Event("visibilitychange")); });
|
||||
expect(mocks.read.mock.calls.some(([, targets]) => targets?.includes(ids[0]))).toBe(true);
|
||||
expect(mocks.request.mock.calls.filter(([action]) => action === "remote.connect")).toHaveLength(1);
|
||||
expect(result.current.frames).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("only probes the selected host, not every retained view", async () => {
|
||||
const { result } = renderHook(useHostSessions);
|
||||
await ready(result, 0);
|
||||
await ready(result, 1);
|
||||
mocks.read.mockClear();
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(5_000); });
|
||||
expect(mocks.read).toHaveBeenCalledWith("token", [ids[1]]);
|
||||
expect(mocks.read.mock.calls.every(([, targets]) => !targets?.includes(ids[0]))).toBe(true);
|
||||
});
|
||||
it("checks existing connections only while the local directory is observed", async () => {
|
||||
mocks.read.mockResolvedValue({ ...directory, profiles: [
|
||||
directory.profiles[0], { ...directory.profiles[1], connected: false, connection_error: "remote_unreachable" },
|
||||
{ ...directory.profiles[2], connected: false, connection_error: "pair_authorization_rejected" },
|
||||
{ ...directory.profiles[3], connected: false, gateway_id: undefined },
|
||||
] });
|
||||
const { result } = renderHook(useHostSessions);
|
||||
await act(async () => {});
|
||||
let stop!: () => void;
|
||||
await act(async () => { stop = result.current.watchDirectory(); });
|
||||
expect(mocks.read).toHaveBeenCalledWith("token", ids.slice(0, 3));
|
||||
mocks.read.mockClear();
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(5_000); });
|
||||
expect(mocks.read.mock.calls).toEqual([["token", ids.slice(0, 3)]]);
|
||||
act(stop);
|
||||
mocks.read.mockClear();
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(30_000); });
|
||||
expect(mocks.read).not.toHaveBeenCalled();
|
||||
expect(mocks.request).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("discovers connections and then updates the directory through targeted polls", async () => {
|
||||
mocks.read.mockResolvedValue({ ...directory, profiles: [] });
|
||||
const { result } = renderHook(useHostSessions);
|
||||
await act(async () => {});
|
||||
await act(async () => { result.current.watchDirectory(); });
|
||||
mocks.read.mockResolvedValue({ ...directory, profiles: [directory.profiles[0]] });
|
||||
mocks.read.mockClear();
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(5_000); });
|
||||
expect(mocks.read.mock.calls).toEqual([["token", []], ["token", [ids[0]]]]);
|
||||
mocks.read.mockResolvedValue({ ...directory, profiles: directory.profiles.slice(0, 2) });
|
||||
mocks.read.mockClear();
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(5_000); });
|
||||
expect(mocks.read.mock.calls).toEqual([["token", [ids[0]]]]);
|
||||
expect(result.current.directory?.profiles).toHaveLength(2);
|
||||
mocks.read.mockClear();
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(5_000); });
|
||||
expect(mocks.read.mock.calls).toEqual([["token", ids.slice(0, 2)]]);
|
||||
});
|
||||
|
||||
it("keeps checking an observed host after a setup error and notices its recovery", async () => {
|
||||
const { result } = renderHook(useHostSessions);
|
||||
await ready(result, 0);
|
||||
mocks.read.mockResolvedValue({ ...directory, profiles: directory.profiles.map((p) =>
|
||||
p.id === ids[0] ? { ...p, connected: false, connection_error: "remote_auth_failed", health_check: 1 } : p) });
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(5_000); });
|
||||
expect(result.current.frames[0].offline).toBe(true);
|
||||
mocks.read.mockResolvedValue(directory);
|
||||
mocks.read.mockClear();
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(5_000); });
|
||||
expect(mocks.read.mock.calls).toEqual([["token", [ids[0]]]]);
|
||||
expect(result.current.frames[0].offline).toBe(false);
|
||||
expect(mocks.request.mock.calls.filter(([action]) => action === "remote.connect")).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("counts distinct failed probes rather than repeated reads of a cached failure", async () => {
|
||||
const { result } = renderHook(useHostSessions);
|
||||
await ready(result, 0);
|
||||
let revision = 41;
|
||||
let connected = false;
|
||||
mocks.read.mockImplementation(async () => ({ ...directory, profiles: directory.profiles.map((p) =>
|
||||
p.id === ids[0] ? { ...p, connected, health_check: revision, connection_error: connected ? "" : "remote_unreachable" } : p) }));
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(5_000); });
|
||||
expect(result.current.frames[0].failures).toBe(1);
|
||||
await act(async () => { await result.current.refresh(); await result.current.refresh(); });
|
||||
expect(result.current.frames[0].failures).toBe(1);
|
||||
expect(result.current.frames[0].offline).toBe(false);
|
||||
revision += 1;
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(5_000); });
|
||||
expect(result.current.frames[0].offline).toBe(true);
|
||||
connected = true; revision += 1;
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(5_000); });
|
||||
expect(result.current.frames[0].offline).toBe(false);
|
||||
expect(result.current.selected?.id).toBe(ids[0]);
|
||||
expect(mocks.request.mock.calls.filter(([action]) => action === "remote.connect")).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("does not start a queued probe after its observer leaves", async () => {
|
||||
const { result } = renderHook(useHostSessions);
|
||||
await ready(result, 0);
|
||||
const slow = deferred<typeof directory>();
|
||||
mocks.read.mockReturnValueOnce(slow.promise);
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(5_000); });
|
||||
let stop!: () => void;
|
||||
await act(async () => { stop = result.current.watchDirectory(); });
|
||||
act(() => { stop(); result.current.local(); });
|
||||
mocks.read.mockClear();
|
||||
await act(async () => { slow.resolve(directory); await vi.advanceTimersByTimeAsync(30_000); });
|
||||
expect(mocks.read).not.toHaveBeenCalled();
|
||||
expect(result.current.frames).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("rechecks a queued wake immediately even when the old request fails", async () => {
|
||||
const { result } = renderHook(useHostSessions);
|
||||
await ready(result, 0);
|
||||
const slow = deferred<typeof directory>();
|
||||
mocks.read.mockReturnValueOnce(slow.promise);
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(5_000); });
|
||||
act(() => { window.dispatchEvent(new Event("online")); window.dispatchEvent(new Event("pageshow")); });
|
||||
mocks.read.mockClear();
|
||||
await act(async () => { slow.reject(new Error("directory_unavailable")); });
|
||||
expect(mocks.read.mock.calls.filter(([, targets]) => targets?.length)).toEqual([["token", [ids[0]]]]);
|
||||
expect(result.current.selected?.id).toBe(ids[0]);
|
||||
expect(result.current.frames[0].offline).toBe(false);
|
||||
});
|
||||
|
||||
it("can cancel a warm view's revalidation without activating it", async () => {
|
||||
const { result } = renderHook(useHostSessions);
|
||||
await ready(result, 0);
|
||||
act(() => result.current.local());
|
||||
const slow = deferred<typeof directory>();
|
||||
mocks.read.mockReturnValueOnce(slow.promise);
|
||||
const { completion } = await start(result, 0);
|
||||
expect(result.current.pending?.id).toBe(ids[0]);
|
||||
act(() => result.current.cancel());
|
||||
await act(async () => { slow.resolve(directory); await completion; });
|
||||
expect(result.current.selected).toBeNull();
|
||||
expect(result.current.frames).toHaveLength(1);
|
||||
expect(mocks.request.mock.calls.filter(([action]) => action === "remote.connect")).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("does not reuse a retained view when revalidation finds a different gateway", async () => {
|
||||
const { result } = renderHook(useHostSessions);
|
||||
await ready(result, 0);
|
||||
act(() => result.current.local());
|
||||
mocks.read.mockResolvedValue({ ...directory, profiles: directory.profiles.map((p) =>
|
||||
p.id === ids[0] ? { ...p, gateway_id: "another-gateway" } : p) });
|
||||
mocks.request.mockRejectedValueOnce(new Error("instance_changed"));
|
||||
await act(async () => { await expect(result.current.connect(ids[0])).rejects.toThrow("instance_changed"); });
|
||||
expect(result.current.selected).toBeNull();
|
||||
expect(result.current.frames[0].offline).toBe(true);
|
||||
expect(result.current.frames[0].connection.gateway_id).toBe("gateway-0");
|
||||
});
|
||||
|
||||
it("reveals only a loaded live view for notifications, without connecting", async () => {
|
||||
const { result } = renderHook(useHostSessions);
|
||||
await ready(result, 0);
|
||||
@@ -51,9 +216,10 @@ describe("host session lifecycle", () => {
|
||||
act(() => { expect(result.current.reveal(ids[0])).toBe(true); });
|
||||
expect(result.current.selected?.id).toBe(ids[0]);
|
||||
act(() => { expect(result.current.reveal(ids[3])).toBe(false); });
|
||||
mocks.read.mockResolvedValue({ ...directory, profiles: directory.profiles.map((p) => ({ ...p, connected: false })) });
|
||||
let check = 0;
|
||||
mocks.read.mockImplementation(async () => ({ ...directory, profiles: directory.profiles.map((p) => ({ ...p, connected: false, health_check: ++check })) }));
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(10_000); });
|
||||
act(() => { expect(result.current.reveal(ids[1])).toBe(false); });
|
||||
act(() => { expect(result.current.reveal(ids[0])).toBe(false); });
|
||||
expect(mocks.request).not.toHaveBeenCalled();
|
||||
});
|
||||
it("clears a failed reconnect only after that host's loaded view recovers", async () => {
|
||||
@@ -83,8 +249,11 @@ describe("host session lifecycle", () => {
|
||||
it("ignores a stale health failure that arrives after reconnect succeeds", async () => {
|
||||
const { result } = renderHook(useHostSessions);
|
||||
await ready(result, 0);
|
||||
mocks.read.mockResolvedValue({ ...directory, profiles: [] });
|
||||
let revision = 0;
|
||||
mocks.read.mockImplementation(async () => ({ ...directory, profiles: directory.profiles.map((p) =>
|
||||
({ ...p, connected: false, connection_error: "remote_unreachable", health_check: ++revision })) }));
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(10_000); });
|
||||
expect(result.current.frames[0].offline).toBe(true);
|
||||
const stale = deferred<typeof directory>();
|
||||
mocks.read.mockReturnValueOnce(stale.promise);
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(5_000); });
|
||||
@@ -100,7 +269,9 @@ describe("host session lifecycle", () => {
|
||||
await ready(result, 0);
|
||||
mocks.read.mockResolvedValue({ ...directory, profiles: directory.profiles.map((p) =>
|
||||
p.id === ids[0] ? { ...p, gateway_id: "restarted-gateway" } : p) });
|
||||
mocks.read.mockClear();
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(10_000); });
|
||||
expect(mocks.read.mock.calls).toEqual([["token", [ids[0]]], ["token", [ids[0]]]]);
|
||||
expect(result.current.frames[0].offline).toBe(true);
|
||||
expect(result.current.selected?.id).toBe(ids[0]);
|
||||
});
|
||||
@@ -195,7 +366,9 @@ describe("host session lifecycle", () => {
|
||||
act(() => result.current.loaded(ids[0]));
|
||||
expect(result.current.selected).toBeNull();
|
||||
expect(result.current.frames).toHaveLength(0);
|
||||
expect(vi.getTimerCount()).toBe(1);
|
||||
mocks.read.mockClear();
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(60_000); });
|
||||
expect(mocks.read).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("a timed-out cold page leaves the old host intact and can be retried", async () => {
|
||||
|
||||
@@ -25,6 +25,7 @@ const connection = {
|
||||
|
||||
class TestSocket {
|
||||
static current: TestSocket;
|
||||
static connected = false;
|
||||
readyState = 0;
|
||||
sent: Outbound[] = [];
|
||||
onopen: (() => void) | null = null;
|
||||
@@ -41,6 +42,7 @@ class TestSocket {
|
||||
const frame = JSON.parse(data) as Outbound;
|
||||
this.sent.push(frame);
|
||||
if (frame.type !== "webui_request") return;
|
||||
if (frame.action === "remote.connect") TestSocket.connected = true;
|
||||
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 } : {};
|
||||
@@ -101,10 +103,12 @@ beforeEach(() => {
|
||||
localStorage.clear();
|
||||
sessionStorage.clear();
|
||||
window.history.replaceState(null, "", "/#/new");
|
||||
TestSocket.connected = false;
|
||||
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] });
|
||||
const path = String(input).split("?")[0];
|
||||
if (path === "/api/remote-instances") return Response.json({ available: true, machine_name: "Local machine",
|
||||
profiles: [TestSocket.connected ? { ...connection, connected: true, health_check: 1 } : profile] });
|
||||
if (path === "/api/sessions") return Response.json({ sessions: [] });
|
||||
if (path === "/api/webui/sidebar-state") return Response.json({});
|
||||
return new Response(null, { status: 404 });
|
||||
|
||||
@@ -58,6 +58,7 @@ function LocalShell({ collapsed = false, initialRemote = false }) {
|
||||
const view = (collapsed = false, initialRemote = false) => render(<RemoteInstances><LocalShell collapsed={collapsed} initialRemote={initialRemote} /></RemoteInstances>);
|
||||
|
||||
beforeEach(async () => {
|
||||
Object.defineProperty(document, "visibilityState", { configurable: true, get: () => "visible" });
|
||||
await i18n.changeLanguage("en");
|
||||
window.sessionStorage.clear(); window.localStorage.clear();
|
||||
window.history.replaceState(null, "", "#/new");
|
||||
@@ -66,7 +67,12 @@ beforeEach(async () => {
|
||||
mocks.discover.mockReset().mockResolvedValue({ hosts: [], files: [], incomplete: false });
|
||||
mocks.inspect.mockReset().mockResolvedValue({ hostname: "team-host", candidates: [{ config_path: "~/.nanobot/config.json", runtime_user: "", service: "" }], incomplete: false });
|
||||
mocks.request.mockReset().mockImplementation(async (action: string) => {
|
||||
if (action === "remote.connect") return connection;
|
||||
if (action === "remote.connect") {
|
||||
const current = await mocks.read.getMockImplementation()?.("local-token", []);
|
||||
mocks.read.mockResolvedValue({ ...current, profiles: current.profiles.map((item: typeof profile) => item.id === profile.id
|
||||
? { ...item, connected: true, gateway_id: connection.gateway_id, health_check: 1 } : item) });
|
||||
return connection;
|
||||
}
|
||||
if (action === "remote.save") return { id: profile.id };
|
||||
if (action === "remote.disconnect") return { available: true, profiles: [profile] };
|
||||
return {};
|
||||
@@ -1312,17 +1318,18 @@ describe("remote instance UX", () => {
|
||||
|
||||
it("tolerates transient health failures and covers, rather than reloads, the remote frame", async () => {
|
||||
let tick: (() => void) | undefined;
|
||||
const setInterval = globalThis.setInterval;
|
||||
vi.spyOn(window, "setInterval").mockImplementation((callback, delay) => {
|
||||
if (delay === 5_000) tick = callback;
|
||||
const timer = setInterval(callback, delay);
|
||||
globalThis.clearInterval(timer);
|
||||
const setTimeout = globalThis.setTimeout;
|
||||
vi.spyOn(window, "setTimeout").mockImplementation((callback, delay) => {
|
||||
const timer = setTimeout(callback, delay);
|
||||
if (delay === 5_000) { tick = callback; globalThis.clearTimeout(timer); }
|
||||
return timer;
|
||||
});
|
||||
view(); await openDirectory();
|
||||
fireEvent.click(screen.getByRole("button", { name: "Team server ubuntu@example.test" }));
|
||||
const frame = await readyRemote();
|
||||
fireEvent.load(frame);
|
||||
let check = 1;
|
||||
mocks.read.mockImplementation(async () => ({ available: true, profiles: [{ ...profile, gateway_id: connection.gateway_id, health_check: ++check }] }));
|
||||
await act(async () => { tick?.(); });
|
||||
expect(screen.queryByRole("region", { name: "Server connection lost" })).not.toBeInTheDocument();
|
||||
await act(async () => { tick?.(); });
|
||||
@@ -1338,19 +1345,26 @@ describe("remote instance UX", () => {
|
||||
});
|
||||
|
||||
it("rechecks on wake and network recovery without reloading or switching hosts", async () => {
|
||||
vi.spyOn(document, "visibilityState", "get").mockReturnValue("visible");
|
||||
let visibility: DocumentVisibilityState = "visible";
|
||||
vi.spyOn(document, "visibilityState", "get").mockImplementation(() => visibility);
|
||||
const rendered = view(); await openDirectory();
|
||||
fireEvent.click(screen.getByRole("button", { name: "Team server ubuntu@example.test" }));
|
||||
const frame = await readyRemote();
|
||||
mocks.read.mockClear();
|
||||
let check = 1;
|
||||
mocks.read.mockClear().mockImplementation(async (_token, ids: string[]) => {
|
||||
if (ids.length) check++;
|
||||
return { available: true, profiles: [{ ...profile, gateway_id: connection.gateway_id, health_check: check }] };
|
||||
});
|
||||
const probes = () => mocks.read.mock.calls.filter(([, ids]) => ids?.length);
|
||||
await act(async () => { window.dispatchEvent(new Event("online")); });
|
||||
expect(mocks.read).toHaveBeenCalledTimes(1);
|
||||
await act(async () => { document.dispatchEvent(new Event("visibilitychange")); });
|
||||
expect(mocks.read).toHaveBeenCalledTimes(2);
|
||||
expect(probes()).toHaveLength(1);
|
||||
act(() => { visibility = "hidden"; document.dispatchEvent(new Event("visibilitychange")); });
|
||||
await act(async () => { visibility = "visible"; document.dispatchEvent(new Event("visibilitychange")); });
|
||||
expect(probes()).toHaveLength(2);
|
||||
await screen.findByRole("region", { name: "Server connection lost" });
|
||||
mocks.read.mockResolvedValue({ available: true, profiles: [{ ...profile, connected: true }] });
|
||||
mocks.read.mockResolvedValue({ available: true, profiles: [{ ...profile, connected: true, gateway_id: connection.gateway_id, health_check: ++check }] });
|
||||
await act(async () => { window.dispatchEvent(new Event("pageshow")); });
|
||||
expect(mocks.read).toHaveBeenCalledTimes(3);
|
||||
expect(probes()).toHaveLength(3);
|
||||
expect(screen.queryByRole("region", { name: "Server connection lost" })).not.toBeInTheDocument();
|
||||
expect(screen.getByTitle("nanobot on Team server")).toBe(frame);
|
||||
expect(readSelectedRemote()?.id).toBe(profile.id);
|
||||
|
||||
Reference in new issue
Block a user