Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

fix(cli): fetch the OpenAPI spec only for api invocations, fail fast when down

Ruben Lütkea530e59a5b62
diff --git a/jarvis/cli_ctl/__main__.py b/jarvis/cli_ctl/__main__.py
index 1436cc31de..ad7b918ed5 100644
--- a/jarvis/cli_ctl/__main__.py
+++ b/jarvis/cli_ctl/__main__.py
@@ -135,20 +135,60 @@ def _dynamic_runner(method, path, params, body):
return client.request(method, path, params=params, json=body)
-def build_root_command() -> click.Group:
- """Return the Click root: the Typer app plus the grafted dynamic `api` group."""
+# Root options that consume the NEXT argv token as their value; skipped when
+# scanning for the invoked subcommand.
+_VALUE_OPTIONS = frozenset({"--url", "--key"})
+
+
+def _first_subcommand(argv: list[str]) -> str | None:
+ """Return the first non-option argv token (the invoked top-level command)."""
+ skip_next = False
+ for tok in argv:
+ if skip_next:
+ skip_next = False
+ continue
+ if tok in _VALUE_OPTIONS:
+ skip_next = True
+ continue
+ if tok.startswith("-"):
+ continue
+ return tok
+ return None
+
+
+def build_root_command(argv: list[str] | None = None) -> click.Group:
+ """Return the Click root: the Typer app plus the grafted dynamic `api` group.
+
+ The OpenAPI document is fetched over the network ONLY when the invocation
+ actually targets the dynamic ``api`` group. Every other command — including
+ ``--help`` and shell completion — grafts from the disk cache alone, so a
+ stale cache plus an unreachable server can never block e.g. ``jarvis
+ version`` on a connect timeout.
+ """
+ if argv is None:
+ argv = sys.argv[1:]
root: click.Group = typer.main.get_command(app)
+ wants_api = not _in_completion() and _first_subcommand(argv) == "api"
try:
- if _in_completion():
- # cache-only: ttl effectively infinite, no fetch attempt
- spec, _ = openapi_cache._read_cache()
- else:
+ if wants_api:
with make_client() as client:
spec = openapi_cache.load_spec(client)
+ else:
+ # cache-only: ttl effectively infinite, no fetch attempt
+ spec, _ = openapi_cache._read_cache()
if spec:
from jarvis.cli_ctl.dynamic import build_api_group
root.add_command(build_api_group(spec, _dynamic_runner))
+ elif wants_api:
+ # `jarvis api ...` would otherwise die with Click's bare
+ # "No such command 'api'" — say what actually went wrong.
+ click.echo(
+ "The dynamic `api` command group is unavailable: no cached "
+ "schema and the Jarvis server could not be reached. Start "
+ "the app (or pass --url), then retry.",
+ err=True,
+ )
except Exception as exc: # noqa: S110 - static surface must work if dynamic build fails
# The static surface must always work even if the dynamic build fails;
# log at DEBUG so a missing `api` group stays diagnosable.
@@ -157,7 +197,7 @@ def build_root_command() -> click.Group:
def main() -> None:
- build_root_command()()
+ build_root_command(sys.argv[1:])()
if __name__ == "__main__":
diff --git a/jarvis/cli_ctl/client.py b/jarvis/cli_ctl/client.py
index 8f20830ec5..27e08cc325 100644
--- a/jarvis/cli_ctl/client.py
+++ b/jarvis/cli_ctl/client.py
@@ -25,13 +25,17 @@ class JarvisClient:
control_key: str | None,
*,
timeout: float = 30.0,
+ connect_timeout: float = 2.0,
transport: httpx.BaseTransport | None = None,
) -> None:
headers = {}
if control_key:
headers["Authorization"] = f"Bearer {control_key}"
+ # Split timeouts: a down/absent server must fail in ~2 s (connect),
+ # while a legitimately slow endpoint may still stream for `timeout`.
self._client = httpx.Client(
- base_url=base_url, headers=headers, timeout=timeout,
+ base_url=base_url, headers=headers,
+ timeout=httpx.Timeout(timeout, connect=min(connect_timeout, timeout)),
transport=transport,
)
self.base_url = base_url
@@ -49,6 +53,13 @@ class JarvisClient:
resp = self._client.request(
method.upper(), path, params=params, json=json
)
+ except (httpx.ConnectError, httpx.ConnectTimeout) as exc:
+ raise ApiError(
+ f"Jarvis at {self.base_url} is unreachable — is the app "
+ "running? Start the desktop app (or `run.bat --headless` on a "
+ "server), or pass --url/--key to target a remote instance.",
+ None,
+ ) from exc
except httpx.TransportError as exc:
raise ApiError(
f"Jarvis at {self.base_url} is unreachable: {exc}", None
diff --git a/tests/unit/cli_ctl/test_dynamic_graft.py b/tests/unit/cli_ctl/test_dynamic_graft.py
index 628b8b3493..c541e1ead1 100644
--- a/tests/unit/cli_ctl/test_dynamic_graft.py
+++ b/tests/unit/cli_ctl/test_dynamic_graft.py
@@ -1,7 +1,11 @@
+import json
+import time
+
import httpx
from click.testing import CliRunner
import jarvis.cli_ctl.__main__ as entry
+from jarvis.cli_ctl import openapi_cache, paths
SPEC = {
"openapi": "3.1.0", "info": {"version": "1"},
@@ -10,6 +14,24 @@ SPEC = {
}
+def _mock_transport(monkeypatch, handler) -> None:
+ import jarvis.cli_ctl.client as client_mod
+ real_init = client_mod.JarvisClient.__init__
+
+ def patched_init(self, base_url, control_key, **kw):
+ kw["transport"] = httpx.MockTransport(handler)
+ real_init(self, base_url, control_key, **kw)
+
+ monkeypatch.setattr(client_mod.JarvisClient, "__init__", patched_init)
+
+
+def _no_network(monkeypatch) -> None:
+ def handler(req): # any request on this path is a regression
+ raise AssertionError(f"unexpected network call: {req.url}")
+
+ _mock_transport(monkeypatch, handler)
+
+
def test_grafted_root_has_api_group(monkeypatch, tmp_path):
monkeypatch.setenv("JARVISCTL_CACHE_HOME", str(tmp_path))
monkeypatch.setenv("JARVISCTL_CONTROL_KEY", "jctl_x")
@@ -19,16 +41,10 @@ def test_grafted_root_has_api_group(monkeypatch, tmp_path):
return httpx.Response(200, json=SPEC)
return httpx.Response(200, json={"pong": True})
- import jarvis.cli_ctl.client as client_mod
- real_init = client_mod.JarvisClient.__init__
-
- def patched_init(self, base_url, control_key, **kw):
- kw["transport"] = httpx.MockTransport(handler)
- real_init(self, base_url, control_key, **kw)
-
- monkeypatch.setattr(client_mod.JarvisClient, "__init__", patched_init)
+ _mock_transport(monkeypatch, handler)
- root = entry.build_root_command() # builds Typer root + grafts api group
+ # An `api` invocation is the one path allowed to fetch the spec.
+ root = entry.build_root_command(["api", "diag", "ping"])
res = CliRunner().invoke(root, ["api", "diag", "ping"])
assert res.exit_code == 0
assert "pong" in res.output
@@ -38,17 +54,48 @@ def test_completion_marker_skips_network(monkeypatch, tmp_path):
monkeypatch.setenv("JARVISCTL_CACHE_HOME", str(tmp_path))
monkeypatch.setenv("_JARVISCTL_COMPLETE", "complete_bash") # completion in flight
- def handler(req): # must NOT be called during completion
- raise AssertionError("network during completion")
+ _no_network(monkeypatch)
+ # Even an `api` invocation stays cache-only while completing.
+ root = entry.build_root_command(["api"])
+ assert root is not None
- import jarvis.cli_ctl.client as client_mod
- real_init = client_mod.JarvisClient.__init__
- def patched_init(self, base_url, control_key, **kw):
- kw["transport"] = httpx.MockTransport(handler)
- real_init(self, base_url, control_key, **kw)
+def test_non_api_command_never_fetches(monkeypatch, tmp_path):
+ """`jarvis version` (or --help) must not pay a spec fetch — ever."""
+ monkeypatch.setenv("JARVISCTL_CACHE_HOME", str(tmp_path))
+ monkeypatch.setenv("JARVISCTL_CONTROL_KEY", "jctl_x")
- monkeypatch.setattr(client_mod.JarvisClient, "__init__", patched_init)
- # Should not raise: no cache + completion marker => no fetch, no api group.
- root = entry.build_root_command()
+ _no_network(monkeypatch)
+ root = entry.build_root_command(["version"])
+ assert "api" not in root.commands # no cache, no fetch -> no dynamic group
+
+ root = entry.build_root_command(["--json", "version"])
+ assert root is not None
+
+
+def test_non_api_command_grafts_from_stale_cache(monkeypatch, tmp_path):
+ """A stale cache still lists the `api` group for help — without a refetch."""
+ monkeypatch.setenv("JARVISCTL_CACHE_HOME", str(tmp_path))
+ monkeypatch.setenv("JARVISCTL_CONTROL_KEY", "jctl_x")
+ openapi_cache._write_cache(SPEC)
+ paths.openapi_meta_file().write_text(
+ json.dumps({"fetched_at": time.time() - 10 * 24 * 3600}), encoding="utf-8"
+ )
+
+ _no_network(monkeypatch)
+ root = entry.build_root_command(["version"])
+ assert "api" in root.commands
+
+
+def test_url_option_value_is_not_mistaken_for_subcommand(monkeypatch, tmp_path):
+ """`--url <value>` consumes its value token when locating the subcommand."""
+ monkeypatch.setenv("JARVISCTL_CACHE_HOME", str(tmp_path))
+ monkeypatch.setenv("JARVISCTL_CONTROL_KEY", "jctl_x")
+
+ _no_network(monkeypatch)
+ # "api" here is the --url VALUE, not the subcommand -> must stay cache-only.
+ root = entry.build_root_command(["--url", "api", "version"])
assert root is not None
+ assert entry._first_subcommand(["--url", "api", "version"]) == "version"
+ assert entry._first_subcommand(["--json", "api"]) == "api"
+ assert entry._first_subcommand([]) is None