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.

feat(cli): cause-specific unreachable diagnosis instead of one canned line

Ruben Lütkef64cd025bb6f
diff --git a/jarvis/cli_ctl/__main__.py b/jarvis/cli_ctl/__main__.py
index 84ac89438f..b68fd351ba 100644
--- a/jarvis/cli_ctl/__main__.py
+++ b/jarvis/cli_ctl/__main__.py
@@ -184,11 +184,13 @@ def build_root_command(argv: list[str] | None = None) -> click.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.
+ # "No such command 'api'" — say what actually went wrong, with
+ # the cause-specific unreachable diagnosis (not one canned line).
+ from jarvis.cli_ctl import doctor
+
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.",
+ "The dynamic `api` command group is unavailable (no cached "
+ "schema yet). " + doctor.unreachable_message(None),
err=True,
)
except Exception as exc: # noqa: S110 - static surface must work if dynamic build fails
diff --git a/jarvis/cli_ctl/client.py b/jarvis/cli_ctl/client.py
index 27e08cc325..0f26fbd153 100644
--- a/jarvis/cli_ctl/client.py
+++ b/jarvis/cli_ctl/client.py
@@ -8,14 +8,19 @@ import httpx
class ApiError(Exception):
- """A request failed. `status_code` is None for transport-level failures."""
+ """A request failed. `status_code` is None for transport-level failures.
+
+ ``base_url`` is set on transport failures so callers can run the
+ cause-specific unreachable diagnosis (`jarvis.cli_ctl.doctor`).
+ """
def __init__(self, message: str, status_code: int | None = None,
- payload: Any = None) -> None:
+ payload: Any = None, base_url: str | None = None) -> None:
super().__init__(message)
self.message = message
self.status_code = status_code
self.payload = payload
+ self.base_url = base_url
class JarvisClient:
@@ -54,15 +59,18 @@ class JarvisClient:
method.upper(), path, params=params, json=json
)
except (httpx.ConnectError, httpx.ConnectTimeout) as exc:
+ # Deliberately terse: the CLI layers replace this with the
+ # cause-specific doctor.unreachable_message (running-but-booting /
+ # crashed-stale-session / not-started / remote-target all get
+ # DIFFERENT advice — one canned "start the app" is often wrong).
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,
+ f"Jarvis at {self.base_url} is unreachable.",
+ None, base_url=self.base_url,
) from exc
except httpx.TransportError as exc:
raise ApiError(
- f"Jarvis at {self.base_url} is unreachable: {exc}", None
+ f"Jarvis at {self.base_url} is unreachable: {exc}",
+ None, base_url=self.base_url,
) from exc
if resp.status_code >= 400:
diff --git a/jarvis/cli_ctl/doctor.py b/jarvis/cli_ctl/doctor.py
new file mode 100644
index 0000000000..20ba106d33
--- /dev/null
+++ b/jarvis/cli_ctl/doctor.py
@@ -0,0 +1,106 @@
+"""Diagnose WHY a Jarvis server is unreachable and say something useful.
+
+One static "start the app" line is both boring and frequently WRONG: the app
+may be running and merely still booting, it may have crashed leaving a stale
+session file behind (starting it again IS right there), or the target may be
+a remote ``--url`` that no local start would ever fix. This module inspects
+the actual local state at error time and composes a cause-specific message,
+with a small pool of phrasings per cause so repeated failures don't read
+like a broken record.
+
+Prose only — scripts and agents must key on exit codes / ``--json``, never on
+this text.
+"""
+from __future__ import annotations
+
+import json
+import os
+import random
+
+from jarvis.cli_ctl import discovery, paths
+from jarvis.cli_ctl.config import DEFAULT_BASE_URL
+
+
+def _explicit_target() -> str | None:
+ """A base URL the user pinned via env or ``auth login`` config, if any."""
+ env = os.environ.get("JARVISCTL_BASE_URL")
+ if env:
+ return env
+ p = paths.config_file()
+ if p.exists():
+ try:
+ data = json.loads(p.read_text(encoding="utf-8"))
+ except (ValueError, OSError):
+ return None
+ url = data.get("base_url")
+ if isinstance(url, str) and url:
+ return url
+ return None
+
+
+def _pick(variants: tuple[str, ...]) -> str:
+ # Prose variety only — nothing security-relevant rides on this choice.
+ return random.choice(variants) # noqa: S311
+
+
+def unreachable_message(base_url: str | None) -> str:
+ """Cause-specific, non-repetitive explanation for an unreachable server."""
+ base_url = base_url or DEFAULT_BASE_URL
+ session = discovery.discover(check_pid=False)
+ explicit = _explicit_target()
+
+ # 1) The user pinned a custom/remote target — a local app start is
+ # irrelevant; the host/tunnel/port is what needs checking.
+ if explicit and explicit.rstrip("/") == base_url.rstrip("/") and (
+ session is None or explicit.rstrip("/") != session.base_url.rstrip("/")
+ ):
+ return _pick((
+ f"No answer from {base_url}. That target comes from --url/env/"
+ "config, so check that machine, tunnel, or port — starting the "
+ "local desktop app won't change anything here. `jarvis auth "
+ "login` re-points the CLI if the address moved.",
+ f"The configured target {base_url} stayed silent. It's an "
+ "explicit remote/custom address: verify the host is up and the "
+ "port is reachable; a local app start won't help this one.",
+ ))
+
+ if session is not None and base_url.rstrip("/") == session.base_url.rstrip("/"):
+ pid = session.pid
+ port = session.base_url.rsplit(":", 1)[-1]
+ if pid is not None and discovery._pid_alive(pid):
+ # 2) The app process EXISTS but the port isn't answering —
+ # usually a boot still in progress, sometimes a wedged server.
+ # "Start the app" would be plain wrong here.
+ return _pick((
+ f"Jarvis is actually running (pid {pid}) — port {port} just "
+ "isn't answering yet. A boot takes a few seconds; retry "
+ "shortly. If it stays silent, restart it from the tray or "
+ "via POST /api/settings/restart-app.",
+ f"Found a live Jarvis process (pid {pid}) that isn't serving "
+ f"on port {port} yet. Most likely it's still starting up — "
+ "give it a moment and try again; a tray restart unsticks a "
+ "wedged boot.",
+ f"The app process is alive (pid {pid}) but not reachable on "
+ f"port {port}. Wait a few seconds and retry before anything "
+ "else; if it never answers, trigger a restart "
+ "(tray icon or POST /api/settings/restart-app).",
+ ))
+ # 3) Stale session file: the app died without cleaning up.
+ return _pick((
+ f"A previous Jarvis exited uncleanly — its session file is still "
+ f"there but the process (pid {pid}) is gone. Launch it again "
+ "(run.bat) and retry.",
+ f"Looks like Jarvis crashed earlier: stale session file, dead "
+ f"pid {pid}. Start it fresh with run.bat, then rerun this "
+ "command.",
+ ))
+
+ # 4) Nothing on this machine at all.
+ return _pick((
+ f"Nothing is listening at {base_url} and no local Jarvis session "
+ "was found. Launch the desktop app (run.bat) — or run.bat --headless "
+ "on a server — then retry; for a remote instance pass --url/--key.",
+ f"No running Jarvis found on this machine ({base_url} is silent). "
+ "Start it with run.bat (or run.bat --headless), or point the CLI at "
+ "a remote instance via --url/--key.",
+ ))
diff --git a/jarvis/cli_ctl/dynamic.py b/jarvis/cli_ctl/dynamic.py
index c2ca193c0e..5acb2a617c 100644
--- a/jarvis/cli_ctl/dynamic.py
+++ b/jarvis/cli_ctl/dynamic.py
@@ -129,7 +129,21 @@ def _build_command(
dangerous=flagged_dangerous, as_json=json_out,
):
return # dry run: preview already printed, nothing sent
- result = runner(method, url_path, query, body)
+ from jarvis.cli_ctl.client import ApiError
+
+ try:
+ result = runner(method, url_path, query, body)
+ except ApiError as exc:
+ # Same clean failure contract as the curated commands (invoke.run):
+ # no raw traceback; transport failures get the cause-specific
+ # unreachable diagnosis instead of one canned line.
+ if exc.status_code is None:
+ from jarvis.cli_ctl import doctor
+
+ render.error(doctor.unreachable_message(exc.base_url))
+ else:
+ render.error(exc.message)
+ raise click.exceptions.Exit(1) from exc
render.emit(result, as_json=json_out)
return click.Command(
diff --git a/jarvis/cli_ctl/invoke.py b/jarvis/cli_ctl/invoke.py
index c301eb5db3..fd61fb7f1e 100644
--- a/jarvis/cli_ctl/invoke.py
+++ b/jarvis/cli_ctl/invoke.py
@@ -55,7 +55,15 @@ def run(
try:
out = client.request(method, path, params=params, json=body)
except ApiError as exc:
- render.error(exc.message)
+ if exc.status_code is None:
+ # Transport failure: replace the terse core message with the
+ # cause-specific diagnosis (booting / crashed / not started /
+ # remote target), phrased with a little variety.
+ from jarvis.cli_ctl import doctor
+
+ render.error(doctor.unreachable_message(exc.base_url))
+ else:
+ render.error(exc.message)
raise typer.Exit(code=1) from exc
render.emit(out, as_json=json_out)
finally:
diff --git a/tests/unit/cli_ctl/test_doctor.py b/tests/unit/cli_ctl/test_doctor.py
new file mode 100644
index 0000000000..5f96833647
--- /dev/null
+++ b/tests/unit/cli_ctl/test_doctor.py
@@ -0,0 +1,126 @@
+"""Unreachable-diagnosis contract: the CLI must say WHAT is actually wrong
+(booting / crashed / not started / remote target) instead of one canned
+"start the app" line — and phrase it with some variety."""
+from __future__ import annotations
+
+import json
+import os
+
+import click
+import httpx
+import pytest
+from click.testing import CliRunner
+
+from jarvis.cli_ctl import discovery, doctor
+from jarvis.cli_ctl.client import ApiError
+from jarvis.cli_ctl.dynamic import build_api_group
+
+
[email protected](autouse=True)
+def _isolated_profile(monkeypatch, tmp_path):
+ monkeypatch.delenv("JARVISCTL_BASE_URL", raising=False)
+ monkeypatch.setenv("JARVISCTL_CONFIG_HOME", str(tmp_path / "cfg"))
+ monkeypatch.setenv("JARVISCTL_CACHE_HOME", str(tmp_path / "cache"))
+ yield
+
+
+def _write_session(tmp_path, monkeypatch, *, pid: int) -> str:
+ session = tmp_path / "session.json"
+ session.write_text(
+ json.dumps({"port": 47821, "token": "jctl_t", "pid": pid}),
+ encoding="utf-8",
+ )
+ monkeypatch.setenv("JARVIS_CLI_SESSION_FILE", str(session))
+ return "http://127.0.0.1:47821"
+
+
+def test_running_but_not_answering_never_says_start_the_app(
+ monkeypatch, tmp_path
+) -> None:
+ """The app process is ALIVE (own pid) — advising a start would be wrong;
+ the message must point at booting/retry/restart instead."""
+ url = _write_session(tmp_path, monkeypatch, pid=os.getpid())
+ msg = doctor.unreachable_message(url)
+ assert str(os.getpid()) in msg
+ assert "run.bat" not in msg
+ assert "retry" in msg.lower() or "try again" in msg.lower()
+
+
+def test_stale_session_after_crash_recommends_a_fresh_start(
+ monkeypatch, tmp_path
+) -> None:
+ url = _write_session(tmp_path, monkeypatch, pid=424242)
+ monkeypatch.setattr(discovery, "_pid_alive", lambda pid: False)
+ msg = doctor.unreachable_message(url)
+ assert "run.bat" in msg
+ assert "424242" in msg # names the dead pid — honest, not generic
+
+
+def test_nothing_running_recommends_start_or_remote(monkeypatch) -> None:
+ monkeypatch.setenv("JARVIS_CLI_SESSION_FILE", "") # discovery disabled
+ msg = doctor.unreachable_message(None)
+ assert "run.bat" in msg
+ assert "--url" in msg
+
+
+def test_explicit_remote_target_never_recommends_local_start(
+ monkeypatch,
+) -> None:
+ monkeypatch.setenv("JARVIS_CLI_SESSION_FILE", "")
+ monkeypatch.setenv("JARVISCTL_BASE_URL", "http://10.0.0.5:9999")
+ msg = doctor.unreachable_message("http://10.0.0.5:9999")
+ assert "run.bat" not in msg
+ assert "10.0.0.5:9999" in msg
+
+
+def test_phrasing_varies_across_invocations(monkeypatch, tmp_path) -> None:
+ """Not a broken record: repeated failures must not always read the same."""
+ url = _write_session(tmp_path, monkeypatch, pid=os.getpid())
+ seen = {doctor.unreachable_message(url) for _ in range(25)}
+ assert len(seen) >= 2
+
+
+def test_dynamic_api_layer_fails_clean_with_diagnosis(monkeypatch) -> None:
+ """A dead server on `jarvis api ...` must exit 1 with the diagnosis —
+ never a raw Python traceback."""
+ monkeypatch.setenv("JARVIS_CLI_SESSION_FILE", "")
+ spec = {
+ "openapi": "3.1.0", "info": {"version": "1"},
+ "paths": {"/api/ping": {"get": {"tags": ["diag"], "operationId": "ping",
+ "summary": "Ping"}}},
+ }
+
+ def runner(method, path, params, body):
+ raise ApiError(
+ "Jarvis at http://127.0.0.1:47821 is unreachable.",
+ None, base_url="http://127.0.0.1:47821",
+ )
+
+ group = build_api_group(spec, runner)
+ root = click.Group("jarvis")
+ root.add_command(group)
+ result = CliRunner().invoke(root, ["api", "diag", "ping"])
+ try: # Click >= 8.2 captures stderr separately; older raises ValueError
+ stderr = result.stderr
+ except (ValueError, AttributeError):
+ stderr = ""
+ combined = result.output + stderr
+ assert result.exit_code == 1
+ assert "Traceback" not in combined
+ assert "run.bat" in combined or "--url" in combined
+
+
+def test_client_transport_error_carries_base_url() -> None:
+ from jarvis.cli_ctl.client import JarvisClient
+
+ def handler(request):
+ raise httpx.ConnectError("down")
+
+ client = JarvisClient(
+ base_url="http://test", control_key="jctl_k",
+ transport=httpx.MockTransport(handler),
+ )
+ with pytest.raises(ApiError) as ei:
+ client.request("GET", "/api/tasks")
+ assert ei.value.base_url == "http://test"
+ assert ei.value.status_code is None