Personal AI, On Personal Devices
Python
feat: add graphical mode for Jarvis (#1029)
shingoabaddoncf4f7723f1e5
diff --git a/README.md b/README.mdindex d7a74449..5a0526be 100644--- a/README.md+++ b/README.md@@ -56,9 +56,15 @@ Platform-specific notes (WSL2 setup, native-Windows scheduled-task service, desk```bashjarvis # start chatting (default: chat-simple)+jarvis gui # start the graphical browser interfacejarvis init --preset <name> --force # replace config with a starter preset```+`jarvis gui` starts the local API server and frontend, then opens the graphical+chat interface in your default browser. It requires Node.js 22+ and is+available from a source checkout; packaged desktop installers are available+from the [latest release](https://github.com/open-jarvis/OpenJarvis/releases).+> Prefix `jarvis ...` with `uv run`, or `source .venv/bin/activate` first.| Preset | What it does |diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 03bc8ca7..dc8f09c1 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -302,7 +302,13 @@ export async function checkHealth(): Promise<boolean> {return false;}};+ // In browser mode Vite serves the SPA on a different port than the API.+ // Probe the configured API base first; the relative fallback supports+ // production deployments where both are served from one origin.+ const base = getBase().replace(/\/+$/, '');+ if (base && await probe(`${base}/health`)) return true;if (await probe('/health')) return true;+ if (base && await probe(`${base}/v1/connectors`)) return true;return probe('/v1/connectors');}diff --git a/frontend/vite.config.ts b/frontend/vite.config.tsindex c6b5d1c2..360565cd 100644--- a/frontend/vite.config.ts+++ b/frontend/vite.config.ts@@ -7,6 +7,12 @@ import { VitePWA } from 'vite-plugin-pwa';// VITE_SUPABASE_ANON_KEY is intentionally NOT required here: a missing key// disables the savings leaderboard at runtime (see src/lib/supabase.ts) rather// than failing the build, so the package/app stays publishable without it.+// jarvis gui sets the proxy target without exposing an absolute API URL to the+// browser, so requests stay on Vite's origin even on a custom frontend port.+const apiTarget = process.env.OPENJARVIS_VITE_PROXY_TARGET+ || process.env.VITE_API_URL+ || 'http://localhost:8000';+export default defineConfig({resolve: {alias: {@@ -65,12 +71,12 @@ export default defineConfig({// opens — no error, no close event, just silence — and every live agent// view sits empty in dev while working in a production build.'/v1': {- target: process.env.VITE_API_URL || 'http://localhost:8000',+ target: apiTarget,changeOrigin: true,ws: true,},- '/health': process.env.VITE_API_URL || 'http://localhost:8000',- '/api': process.env.VITE_API_URL || 'http://localhost:8000',+ '/health': apiTarget,+ '/api': apiTarget,},},});diff --git a/src/openjarvis/cli/__init__.py b/src/openjarvis/cli/__init__.pyindex 86420db8..b730a412 100644--- a/src/openjarvis/cli/__init__.py+++ b/src/openjarvis/cli/__init__.py@@ -114,6 +114,7 @@ if not _DATA_BOUNDARY_BOOTSTRAP:from openjarvis.cli.eval_cmd import eval_groupfrom openjarvis.cli.feedback_cmd import feedback_groupfrom openjarvis.cli.gateway_cmd import gateway+ from openjarvis.cli.gui_cmd import guifrom openjarvis.cli.host_cmd import hostfrom openjarvis.cli.init_cmd import initfrom openjarvis.cli.memory_cmd import memory@@ -164,6 +165,7 @@ if not _DATA_BOUNDARY_BOOTSTRAP:cli.add_command(feedback_group, "feedback")cli.add_command(compose, "compose")cli.add_command(gateway, "gateway")+ cli.add_command(gui, "gui")cli.add_command(tool, "tool")cli.add_command(registry, "registry")cli.add_command(config, "config")diff --git a/src/openjarvis/cli/gui_cmd.py b/src/openjarvis/cli/gui_cmd.pynew file mode 100644index 00000000..138ad338--- /dev/null+++ b/src/openjarvis/cli/gui_cmd.py@@ -0,0 +1,169 @@+"""``jarvis gui`` — start and open the local graphical interface."""++from __future__ import annotations++import os+import shutil+import socket+import subprocess+import sys+import time+import webbrowser+from pathlib import Path++import click+from rich.console import Console+++def _frontend_dir() -> Path | None:+ """Find the source checkout's frontend directory."""+ configured = os.environ.get("OPENJARVIS_FRONTEND_DIR")+ candidates = [Path(configured)] if configured else []+ candidates.append(Path(__file__).resolve().parents[3] / "frontend")+ for candidate in candidates:+ if candidate.is_dir() and (candidate / "package.json").is_file():+ return candidate+ return None+++def _check_frontend_port(port: int) -> None:+ """Reject a port already bound by another local application."""+ try:+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as probe:+ probe.bind(("127.0.0.1", port))+ except OSError as exc:+ raise click.ClickException(+ f"Frontend port {port} is unavailable. Choose another with --frontend-port."+ ) from exc+++def _wait_for_port(+ process: subprocess.Popen[bytes], host: str, port: int, timeout: float = 20.0+) -> bool:+ """Wait for this launch's frontend process to listen on the requested port."""+ deadline = time.monotonic() + timeout+ while time.monotonic() < deadline:+ if process.poll() is not None:+ return False+ try:+ with socket.create_connection((host, port), timeout=0.5):+ return process.poll() is None+ except OSError:+ time.sleep(0.2)+ return False+++def _ensure_frontend_dependencies(frontend: Path, npm: str) -> None:+ """Install frontend dependencies when this checkout has not been bootstrapped."""+ vite = (+ frontend+ / "node_modules"+ / ".bin"+ / ("vite.cmd" if sys.platform == "win32" else "vite")+ )+ if vite.exists():+ return+ click.echo("Installing graphical frontend dependencies...", err=True)+ result = subprocess.run(+ [npm, "install", "--no-audit", "--no-fund"],+ cwd=frontend,+ check=False,+ )+ if result.returncode != 0:+ raise click.ClickException(+ "Could not install frontend dependencies. "+ "Run `npm install` in the frontend directory."+ )+++ "--frontend-port", default=5173, show_default=True, type=click.IntRange(1, 65535)+)+ "--api-port", default=8000, show_default=True, type=click.IntRange(1, 65535)+)[email protected]("--no-server", is_flag=True, help="Do not start the API server.")[email protected]("--no-browser", is_flag=True, help="Only start the frontend.")+def gui(frontend_port: int, api_port: int, no_server: bool, no_browser: bool) -> None:+ """Start the browser-based graphical mode in the default browser.++ This command is intended for source checkouts. For an installed desktop+ application, launch OpenJarvis from the operating system menu instead.+ """+ console = Console(stderr=True)+ frontend = _frontend_dir()+ if frontend is None:+ raise click.ClickException(+ "The graphical frontend is not available in this installation. "+ "Download the OpenJarvis desktop app or run this command "+ "from a source checkout."+ )+ npm = shutil.which("npm") or shutil.which("npm.cmd")+ if npm is None:+ raise click.ClickException(+ "Node.js/npm is required for graphical mode. Install Node.js 22 or newer."+ )+ _check_frontend_port(frontend_port)+ _ensure_frontend_dependencies(frontend, npm)++ if not no_server:+ uv = shutil.which("uv")+ if uv is None:+ raise click.ClickException(+ "uv is required to start the API with desktop dependencies. "+ "Install uv or use --no-server with an already-running API."+ )+ server = subprocess.run(+ [+ uv,+ "run",+ "--extra",+ "desktop",+ "jarvis",+ "start",+ "--port",+ str(api_port),+ ],+ cwd=frontend.parent,+ check=False,+ )+ if server.returncode != 0:+ raise click.ClickException("Could not start the OpenJarvis API server.")++ env = os.environ.copy()+ # Let browser requests use Vite's same-origin proxy at any frontend port.+ # VITE_API_URL is exposed to browser code, so clear an inherited override.+ env["VITE_API_URL"] = ""+ env["OPENJARVIS_VITE_PROXY_TARGET"] = f"http://127.0.0.1:{api_port}"+ process = subprocess.Popen(+ [+ npm,+ "run",+ "dev",+ "--",+ "--host",+ "127.0.0.1",+ "--port",+ str(frontend_port),+ "--strictPort",+ ],+ cwd=frontend,+ env=env,+ )+ if not _wait_for_port(process, "127.0.0.1", frontend_port):+ process.terminate()+ process.wait()+ raise click.ClickException(+ "The graphical frontend did not start on the requested port."+ )++ url = f"http://127.0.0.1:{frontend_port}"+ console.print(f"[green]OpenJarvis graphical mode is ready:[/green] {url}")+ if not no_browser:+ webbrowser.open(url)+ try:+ process.wait()+ except KeyboardInterrupt:+ process.terminate()+ process.wait()diff --git a/tests/cli/test_gui_cmd.py b/tests/cli/test_gui_cmd.pynew file mode 100644index 00000000..d33df9ca--- /dev/null+++ b/tests/cli/test_gui_cmd.py@@ -0,0 +1,115 @@+"""Launch behavior for the source-checkout graphical command."""++from __future__ import annotations++import os+import socket+import subprocess+from pathlib import Path+from unittest import mock++from click.testing import CliRunner++from openjarvis.cli import gui_cmd+++def test_gui_custom_ports_use_project_root_and_same_origin_proxy(+ tmp_path: Path,+) -> None:+ frontend = tmp_path / "frontend"+ frontend.mkdir()+ process = mock.Mock(spec=subprocess.Popen)+ process.poll.return_value = None+ process.wait.return_value = 0++ with (+ mock.patch.object(gui_cmd, "_frontend_dir", return_value=frontend),+ mock.patch.object(gui_cmd, "_check_frontend_port") as check_port,+ mock.patch.object(gui_cmd, "_ensure_frontend_dependencies") as ensure_deps,+ mock.patch.object(+ gui_cmd.shutil, "which", side_effect=lambda name: f"/bin/{name}"+ ),+ mock.patch.object(+ gui_cmd.subprocess, "run", return_value=mock.Mock(returncode=0)+ ) as run,+ mock.patch.object(gui_cmd.subprocess, "Popen", return_value=process) as popen,+ mock.patch.object(+ gui_cmd, "_wait_for_port", return_value=True+ ) as wait_for_port,+ mock.patch.object(gui_cmd.webbrowser, "open") as open_browser,+ mock.patch.dict(os.environ, {"VITE_API_URL": "http://stale.example"}),+ ):+ result = CliRunner().invoke(+ gui_cmd.gui,+ ["--frontend-port", "5180", "--api-port", "8123", "--no-browser"],+ )++ assert result.exit_code == 0, result.output+ check_port.assert_called_once_with(5180)+ ensure_deps.assert_called_once_with(frontend, "/bin/npm")+ run.assert_called_once_with(+ [+ "/bin/uv",+ "run",+ "--extra",+ "desktop",+ "jarvis",+ "start",+ "--port",+ "8123",+ ],+ cwd=tmp_path,+ check=False,+ )+ args, kwargs = popen.call_args+ assert args[0] == [+ "/bin/npm",+ "run",+ "dev",+ "--",+ "--host",+ "127.0.0.1",+ "--port",+ "5180",+ "--strictPort",+ ]+ assert kwargs["cwd"] == frontend+ assert kwargs["env"]["OPENJARVIS_VITE_PROXY_TARGET"] == "http://127.0.0.1:8123"+ assert kwargs["env"]["VITE_API_URL"] == ""+ wait_for_port.assert_called_once_with(process, "127.0.0.1", 5180)+ open_browser.assert_not_called()+ process.wait.assert_called_once_with()+++def test_gui_rejects_occupied_frontend_port_before_launch(tmp_path: Path) -> None:+ frontend = tmp_path / "frontend"+ frontend.mkdir()+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as listener:+ listener.bind(("127.0.0.1", 0))+ listener.listen()+ port = listener.getsockname()[1]+ with (+ mock.patch.object(gui_cmd, "_frontend_dir", return_value=frontend),+ mock.patch.object(gui_cmd.shutil, "which", return_value="/bin/npm"),+ mock.patch.object(gui_cmd, "_ensure_frontend_dependencies") as ensure_deps,+ mock.patch.object(gui_cmd.subprocess, "Popen") as popen,+ mock.patch.object(gui_cmd.subprocess, "run") as run,+ ):+ result = CliRunner().invoke(+ gui_cmd.gui,+ ["--frontend-port", str(port), "--no-server", "--no-browser"],+ )++ assert result.exit_code != 0+ assert f"Frontend port {port} is unavailable" in result.output+ ensure_deps.assert_not_called()+ run.assert_not_called()+ popen.assert_not_called()+++def test_wait_for_port_stops_when_vite_exits() -> None:+ process = mock.Mock(spec=subprocess.Popen)+ process.poll.return_value = 1+ with mock.patch.object(gui_cmd.socket, "create_connection") as connect:+ assert not gui_cmd._wait_for_port(process, "127.0.0.1", 5173)+ connect.assert_not_called()