Personal AI, On Personal Devices
Python
fix(gui): track frontend ownership and clean up process trees (#1058)
srcreativepro-art606fdfad7454
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex dce0c900..46ce500f 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -140,6 +140,10 @@ jobs:- name: Install Rust toolchainuses: dtolnay/rust-toolchain@stable+ - name: Verify GUI process ownership and cleanup+ shell: bash+ run: uv run pytest tests/cli/test_gui_cmd.py tests/cli/test_gui_lifecycle.py -v+- name: Build + import the PyO3 extension on Windowsshell: bashrun: |diff --git a/pyproject.toml b/pyproject.tomlindex 65d1b01a..70bd2aaf 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -36,6 +36,8 @@ dependencies = ["openai>=1.30","nvidia-ml-py>=12.560.30","posthog>=3.0",+ # Process identity and descendant cleanup for the source-checkout GUI.+ "psutil>=5.9","python-telegram-bot>=22.8","rich>=13","tomli>=2.0; python_version < '3.11'",diff --git a/src/openjarvis/cli/daemon_cmd.py b/src/openjarvis/cli/daemon_cmd.pyindex f2324c89..6a418a99 100644--- a/src/openjarvis/cli/daemon_cmd.py+++ b/src/openjarvis/cli/daemon_cmd.py@@ -185,10 +185,11 @@ def _registered_pid_alive(pid: int) -> bool:@contextmanager-def _state_lock() -> Iterator[None]:+def _state_lock(state_file: Path | None = None) -> Iterator[None]:"""Serialize daemon bookkeeping across launching and supervised processes."""- _PID_FILE.parent.mkdir(parents=True, exist_ok=True)- with _PID_FILE.with_suffix(".lock").open("a+b") as lock:+ path = _PID_FILE if state_file is None else state_file+ path.parent.mkdir(parents=True, exist_ok=True)+ with path.with_suffix(".lock").open("a+b") as lock:if os.name == "nt":import msvcrt@@ -477,10 +478,22 @@ def start(def stop() -> None:"""Stop the running OpenJarvis server daemon."""console = Console(stderr=True)+ # Stop the graphical frontend too. It is a sibling process, not a child of+ # the daemon, so it otherwise outlives `stop` and keeps holding its port —+ # leaving both a GUI that serves pages but fails every request, and a next+ # `jarvis gui` that dies on "Frontend port 5173 is unavailable".+ # Imported here rather than at module scope: gui_cmd is a sibling CLI+ # module and only `stop` needs it.+ from openjarvis.cli.gui_cmd import stop_frontend++ frontend_pid = stop_frontend()+ if frontend_pid is not None:+ console.print(f"[green]Frontend stopped[/green] (PID {frontend_pid}).")+pid = _read_pid()if pid is None:console.print("[yellow]No running server found.[/yellow]")- sys.exit(1)+ sys.exit(0 if frontend_pid is not None else 1)# Graceful shutdown (SIGTERM / taskkill), escalating to a forced kill after# 10s if still running. Cross-platform — no POSIX-only os.kill/SIGKILL.diff --git a/src/openjarvis/cli/gui_cmd.py b/src/openjarvis/cli/gui_cmd.pyindex 138ad338..5c28a42d 100644--- a/src/openjarvis/cli/gui_cmd.py+++ b/src/openjarvis/cli/gui_cmd.py@@ -2,18 +2,44 @@from __future__ import annotations+import atexit+import contextlib+import jsonimport os+import secretsimport shutil+import signalimport socketimport subprocessimport sysimport time+import urllib.error+import urllib.requestimport webbrowserfrom pathlib import Pathimport click+import psutilfrom rich.console import Console+from openjarvis.core.config import DEFAULT_CONFIG_DIR+from openjarvis.security.file_utils import secure_write_json++# Records the frontend this command started, so a later run can tell its own+# leftover dev server apart from an unrelated application holding the port.+# ``npm run dev`` is npm -> cmd.exe -> node and only the leaf binds the port,+# so an interrupted run routinely leaves that leaf behind; see _reclaim_port.+_FRONTEND_STATE_FILE = DEFAULT_CONFIG_DIR / "frontend.json"++# How often to re-check that the API is still up while the frontend runs.+_API_POLL_SECONDS = 5.0++# How many consecutive failed probes mean the API is really gone. A single+# failure proves nothing: a loopback connect to a busy server intermittently+# stalls for seconds, and treating one timeout as death tears down a working+# GUI — a worse bug than the dead-backend one this watch exists to catch.+_API_FAILURES_BEFORE_DOWN = 3+def _frontend_dir() -> Path | None:"""Find the source checkout's frontend directory."""@@ -26,23 +52,375 @@ def _frontend_dir() -> Path | None:return None-def _check_frontend_port(port: int) -> None:- """Reject a port already bound by another local application."""+def _read_frontend_state() -> dict:+ """Return the recorded frontend, or {} when it is missing or malformed."""+ try:+ state = json.loads(_FRONTEND_STATE_FILE.read_text())+ except (OSError, ValueError):+ return {}+ if not isinstance(state, dict):+ return {}+ if (+ type(state.get("pid")) is not int+ or state["pid"] <= 0+ or type(state.get("port")) is not int+ or not 0 <= state["port"] <= 65535+ ):+ return {}+ return state+++def _frontend_state_lock():+ from openjarvis.cli.daemon_cmd import _state_lock++ return _state_lock(_FRONTEND_STATE_FILE)+++def clear_frontend_state(pid: int, launch_token: str | None) -> None:+ """Deregister a frontend, but only if it still owns the file."""+ with _frontend_state_lock():+ state = _read_frontend_state()+ if state.get("pid") == pid and state.get("launch_token") == launch_token:+ _FRONTEND_STATE_FILE.unlink(missing_ok=True)+++def _process_identity(process: psutil.Process) -> dict | None:+ """Return an identity that cannot be confused with a recycled PID."""+ if sys.platform == "linux":+ from openjarvis.cli.daemon_cmd import _linux_process_identity++ # psutil's Linux epoch start time depends on the current boot epoch.+ # Keep the same clock-stable identity used by daemon bookkeeping.+ return _linux_process_identity(process.pid)+ return {"pid": process.pid, "created_at": process.create_time()}+++def _inspect_frontend_processes(state: dict) -> tuple[list[psutil.Process], list[dict]]:+ """Separate verified owners from records whose identity is temporarily unknown."""+ if not isinstance(state.get("launch_token"), str) or not state["launch_token"]:+ return [], []+ records = state.get("processes")+ if not isinstance(records, list):+ return [], []+ owned, unknown = [], []+ for record in records:+ if not isinstance(record, dict) or type(record.get("pid")) is not int:+ continue+ if record["pid"] <= 0 or not isinstance(record.get("identity"), dict):+ continue+ try:+ process = psutil.Process(record["pid"])+ identity = _process_identity(process)+ if identity is None:+ unknown.append(record)+ elif (+ identity == record["identity"]+ and process.status() != psutil.STATUS_ZOMBIE+ ):+ # The Linux identity already checks start ticks and boot ID;+ # an epoch-based psutil comparison can change with the clock.+ if sys.platform != "linux" and not process.is_running():+ continue+ owned.append(process)+ except psutil.NoSuchProcess:+ continue+ except (psutil.Error, OSError):+ unknown.append(record)+ except (ValueError, OverflowError):+ continue+ return owned, unknown+++def _owned_processes(state: dict) -> list[psutil.Process]:+ """Recover only verified identities; a bare legacy PID is not ownership."""+ return _inspect_frontend_processes(state)[0]+++def _frontend_processes(+ state: dict,+ live_process: subprocess.Popen | None = None,+ *,+ verified: list[psutil.Process] | None = None,+) -> list[psutil.Process]:+ """Include current descendants of verified owners and the live child we own."""+ owners = _owned_processes(state) if verified is None else verified+ processes = {process.pid: process for process in owners}+ if live_process is not None and live_process.poll() is None:+ try:+ # A live, unreaped Popen child belongs to this invocation. This+ # path also lets startup failure clean up before state is saved.+ processes[live_process.pid] = psutil.Process(live_process.pid)+ except psutil.Error:+ pass+ for process in list(processes.values()):+ try:+ for child in process.children(recursive=True):+ processes[child.pid] = child+ except psutil.Error:+ continue+ return list(processes.values())+++def _terminate_frontend(+ state: dict, live_process: subprocess.Popen | None = None+) -> bool:+ owned, unknown = _inspect_frontend_processes(state)+ if unknown:+ raise click.ClickException(+ "Could not verify frontend process ownership; saved state was kept. "+ "Retry when process information is accessible."+ )+ processes = _frontend_processes(state, live_process, verified=owned)+ # POSIX launchers have a dedicated session. A verified surviving member+ # proves the group still belongs to this launch even after npm has exited.+ group = state.get("process_group")+ if os.name != "nt" and type(group) is int and group == state.get("pid"):+ for process in processes:+ try:+ if os.getpgid(process.pid) == group and process.is_running():+ os.killpg(group, signal.SIGTERM)+ break+ except (OSError, psutil.Error):+ continue+ for process in reversed(processes):+ with contextlib.suppress(psutil.Error):+ process.terminate()+ _, alive = psutil.wait_procs(processes, timeout=5.0)+ for process in alive:+ with contextlib.suppress(psutil.Error):+ process.kill()+ _, remaining = psutil.wait_procs(alive, timeout=1.0)+ if remaining:+ raise click.ClickException("Could not stop every owned frontend process.")+ if live_process is not None and live_process.poll() is None:+ live_process.terminate()+ try:+ live_process.wait(timeout=5.0)+ except subprocess.TimeoutExpired:+ live_process.kill()+ live_process.wait(timeout=1.0)+ remaining_owned, unknown = _inspect_frontend_processes(state)+ if remaining_owned or unknown:+ raise click.ClickException(+ "Frontend ownership could not be cleared safely; saved state was kept."+ )+ return bool(processes)+++class _FrontendOwner:+ """Track a launch's process identities without leaving stale exit hooks."""++ def __init__(self, process: subprocess.Popen, port: int) -> None:+ self.process = process+ self.state = {+ "pid": process.pid,+ "port": port,+ "launch_token": secrets.token_hex(16),+ "processes": [],+ "process_group": process.pid if os.name != "nt" else None,+ }+ self.registered = False+ self.closed = False++ def refresh(self) -> None:+ previous = {record["pid"]: record for record in self.state["processes"]}+ # A denied/transient read is not evidence that a process ended. Keep+ # its last verified identity so a later stop/reclaim can retry safely.+ owned, unknown = _inspect_frontend_processes(self.state)+ records = {record["pid"]: record for record in unknown}+ for process in _frontend_processes(self.state, self.process, verified=owned):+ try:+ identity = _process_identity(process)+ if process.pid in previous:+ # Never replace a recorded identity with a newer process+ # that recycled this PID during refresh.+ if (+ identity is None+ or identity == previous[process.pid]["identity"]+ ):+ records[process.pid] = previous[process.pid]+ elif identity is not None and process.is_running():+ confirmed = _process_identity(process)+ if confirmed == identity:+ records[process.pid] = {+ "pid": process.pid,+ "identity": identity,+ }+ except psutil.NoSuchProcess:+ continue+ except (psutil.Error, OSError):+ if process.pid in previous:+ records[process.pid] = previous[process.pid]+ updated = list(records.values())+ if updated == self.state["processes"]:+ return+ self.state["processes"] = updated+ if self.registered:+ with _frontend_state_lock():+ current = _read_frontend_state()+ if current.get("pid") == self.state["pid"] and (+ current.get("launch_token") == self.state["launch_token"]+ ):+ secure_write_json(_FRONTEND_STATE_FILE, self.state)++ def register(self) -> None:+ self.refresh()+ if not any(+ record["pid"] == self.process.pid for record in self.state["processes"]+ ):+ raise click.ClickException(+ "Could not verify the frontend process identity."+ )+ with _frontend_state_lock():+ current = _read_frontend_state()+ if current.get("launch_token") != self.state["launch_token"]:+ owned, unknown = _inspect_frontend_processes(current)+ if owned or unknown:+ raise click.ClickException(+ "Another frontend is still registered. Stop that graphical "+ "session before starting a new one."+ )+ secure_write_json(_FRONTEND_STATE_FILE, self.state)+ self.registered = True++ def shutdown(self) -> None:+ if self.closed:+ return+ self.closed = True+ _terminate_frontend(self.state, self.process)+ clear_frontend_state(self.state["pid"], self.state["launch_token"])+++def stop_frontend(*, state: dict | None = None) -> int | None:+ """Stop the recorded frontend, optionally using a port check's exact snapshot.++ Unknown ownership keeps the saved state and raises so a later call can+ retry. Returns the launch PID stopped, or None for a stale registration.+ """+ state = _read_frontend_state() if state is None else state+ pid = state.get("pid")+ if pid is None:+ return None+ stopped = _terminate_frontend(state)+ clear_frontend_state(pid, state.get("launch_token"))+ return pid if stopped else None+++def _port_free(port: int) -> bool: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+ except OSError:+ return False+ return True+++def _port_owner_pid(port: int) -> int | None:+ """Best-effort PID listening on *port*, for a message the user can act on."""+ try:+ if sys.platform == "win32":+ out = subprocess.run(+ ["netstat", "-ano", "-p", "tcp"],+ capture_output=True,+ text=True,+ check=False,+ ).stdout+ for line in out.splitlines():+ parts = line.split()+ if (+ len(parts) >= 5+ and parts[0].upper() == "TCP"+ and parts[3].upper() == "LISTENING"+ and parts[1].endswith(f":{port}")+ ):+ return int(parts[4])+ return None+ out = subprocess.run(+ ["lsof", "-ti", f"tcp:{port}", "-sTCP:LISTEN"],+ capture_output=True,+ text=True,+ check=False,+ ).stdout.split()+ return int(out[0]) if out else None+ except (OSError, ValueError):+ return None+++def _reclaim_port(port: int) -> bool:+ """Free *port* when this command's own earlier frontend still holds it.++ A frontend killed outright never runs its cleanup. Saved process+ identities identify verified survivors of our earlier launch; a bare PID+ does not establish ownership after the operating system reuses it.+ """+ state = _read_frontend_state()+ if state.get("port") != port:+ return False+ if stop_frontend(state=state) is None:+ return _port_free(port)+ for _ in range(20):+ if _port_free(port):+ return True+ time.sleep(0.25)+ return False+++def _check_frontend_port(port: int) -> None:+ """Reject a port already bound by another local application."""+ if _port_free(port):+ return+ if _reclaim_port(port):+ return+ owner = _port_owner_pid(port)+ held_by = f" It is held by PID {owner}." if owner else ""+ raise click.ClickException(+ f"Frontend port {port} is unavailable and was not started by "+ f"OpenJarvis.{held_by} Stop it, or choose another port with "+ f"--frontend-port."+ )+++def _api_healthy(port: int, timeout: float = 3.0) -> bool:+ """Return whether an API server is answering on *port*."""+ try:+ with urllib.request.urlopen(+ f"http://127.0.0.1:{port}/health", timeout=timeout+ ) as response:+ return response.status == 200+ except (urllib.error.URLError, OSError, ValueError):+ return False+++def _daemon_pid_alive(port: int, *, require_ready: bool = False) -> bool:+ """Whether the daemon registered on *port* is still a live process.++ Corroborates a run of failed health probes: a wedged-but-running server+ should not be reported as stopped, and only the daemon's own bookkeeping+ knows which process is supposed to be serving this port.+ """+ # Imported lazily; daemon_cmd imports this module for its own `stop`.+ from openjarvis.cli.daemon_cmd import _read_pid_unlocked, _read_state, _state_lock++ with _state_lock():+ state = _read_state()+ if state.get("port") != port or (require_ready and state.get("ready") is False):+ return False+ return _read_pid_unlocked() == state["pid"]def _wait_for_port(- process: subprocess.Popen[bytes], host: str, port: int, timeout: float = 20.0+ process: subprocess.Popen[bytes],+ host: str,+ port: int,+ timeout: float = 20.0,+ *,+ on_poll=None,) -> bool:"""Wait for this launch's frontend process to listen on the requested port."""deadline = time.monotonic() + timeoutwhile time.monotonic() < deadline:+ if on_poll is not None:+ on_poll()if process.poll() is not None:return Falsetry:@@ -107,7 +485,23 @@ def gui(frontend_port: int, api_port: int, no_server: bool, no_browser: bool) ->_check_frontend_port(frontend_port)_ensure_frontend_dependencies(frontend, npm)- if not no_server:+ # `jarvis start` exits non-zero when a daemon is already registered, so+ # without this a perfectly healthy API turned into the misleading "Could+ # not start the OpenJarvis API server." Adopt it instead.+ if not no_server and _api_healthy(api_port):+ if not _daemon_pid_alive(api_port, require_ready=True):+ raise click.ClickException(+ f"API port {api_port} is already serving an unregistered service. "+ "Stop it or choose another port. Use --no-server only when you "+ "intend to use an externally managed OpenJarvis backend."+ )+ console.print(+ f"[green]Reusing the API server already running on port {api_port}.[/green]"+ )+ no_server = True++ launched_api = not no_server+ if launched_api:uv = shutil.which("uv")if uv is None:raise click.ClickException(@@ -136,6 +530,11 @@ def gui(frontend_port: int, api_port: int, no_server: bool, no_browser: bool) -># 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}"+ spawn_kwargs = {}+ if sys.platform == "win32":+ spawn_kwargs["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP+ else:+ spawn_kwargs["start_new_session"] = Trueprocess = subprocess.Popen([npm,@@ -150,20 +549,63 @@ def gui(frontend_port: int, api_port: int, no_server: bool, no_browser: bool) ->],cwd=frontend,env=env,+ **spawn_kwargs,)- 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)+ owner = _FrontendOwner(process, frontend_port)+ shutdown = owner.shutdown+ handlers = {}+ atexit.register(shutdown)try:- process.wait()+ for signum in (signal.SIGTERM, getattr(signal, "SIGBREAK", None)):+ if signum is not None:+ with contextlib.suppress(OSError, ValueError):+ previous = signal.getsignal(signum)+ signal.signal(signum, lambda *_: sys.exit(1))+ handlers[signum] = previous+ owner.register()+ if not _wait_for_port(+ process, "127.0.0.1", frontend_port, on_poll=owner.refresh+ ):+ raise click.ClickException(+ "The graphical frontend did not start on the requested port."+ )+ owner.refresh()+ 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)++ watch_api = _api_healthy(api_port)+ failures = 0+ while True:+ owner.refresh()+ try:+ process.wait(timeout=_API_POLL_SECONDS)+ break+ except subprocess.TimeoutExpired:+ pass+ healthy = _api_healthy(api_port)+ if healthy:+ watch_api = True+ failures = 0+ continue+ if not watch_api and not launched_api:+ continue+ failures += 1+ if failures < _API_FAILURES_BEFORE_DOWN or _daemon_pid_alive(api_port):+ continue+ console.print(+ "[red]The API server stopped or failed to start; "+ "shutting down the frontend.[/red]\n"+ f" Check {DEFAULT_CONFIG_DIR / 'server.log'}, "+ f"then run 'jarvis gui' again."+ )+ raise SystemExit(1)except KeyboardInterrupt:- process.terminate()- process.wait()+ pass+ finally:+ atexit.unregister(shutdown)+ for signum, previous in handlers.items():+ with contextlib.suppress(OSError, ValueError):+ signal.signal(signum, previous)+ shutdown()diff --git a/tests/cli/test_gui_cmd.py b/tests/cli/test_gui_cmd.pyindex d33df9ca..5461c2b1 100644--- a/tests/cli/test_gui_cmd.py+++ b/tests/cli/test_gui_cmd.py@@ -19,6 +19,7 @@ def test_gui_custom_ports_use_project_root_and_same_origin_proxy(frontend = tmp_path / "frontend"frontend.mkdir()process = mock.Mock(spec=subprocess.Popen)+ process.pid = 4321process.poll.return_value = Noneprocess.wait.return_value = 0@@ -33,6 +34,8 @@ def test_gui_custom_ports_use_project_root_and_same_origin_proxy(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, "_FrontendOwner") as owner_type,+ mock.patch.object(gui_cmd, "_api_healthy", return_value=False),mock.patch.object(gui_cmd, "_wait_for_port", return_value=True) as wait_for_port,@@ -76,9 +79,12 @@ def test_gui_custom_ports_use_project_root_and_same_origin_proxy(assert kwargs["cwd"] == frontendassert 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)+ wait_for_port.assert_called_once_with(+ process, "127.0.0.1", 5180, on_poll=owner_type.return_value.refresh+ )open_browser.assert_not_called()- process.wait.assert_called_once_with()+ process.wait.assert_called_once_with(timeout=gui_cmd._API_POLL_SECONDS)+ owner_type.return_value.shutdown.assert_called_once_with()def test_gui_rejects_occupied_frontend_port_before_launch(tmp_path: Path) -> None:@@ -91,6 +97,7 @@ def test_gui_rejects_occupied_frontend_port_before_launch(tmp_path: Path) -> Nonwith (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, "_port_owner_pid", return_value=None),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,diff --git a/tests/cli/test_gui_lifecycle.py b/tests/cli/test_gui_lifecycle.pynew file mode 100644index 00000000..517a7775--- /dev/null+++ b/tests/cli/test_gui_lifecycle.py@@ -0,0 +1,474 @@+"""Frontend cleanup must target owned processes and release invocation hooks."""++from __future__ import annotations++import json+import signal+import subprocess+import sys+import time+from contextlib import nullcontext+from unittest import mock++import click+import psutil+import pytest+from click.testing import CliRunner++from openjarvis.cli import daemon_cmd, gui_cmd++[email protected](autouse=True)+def frontend_state(tmp_path, monkeypatch):+ path = tmp_path / "frontend.json"+ monkeypatch.setattr(gui_cmd, "_FRONTEND_STATE_FILE", path)+ return path+++def _saved_state(pid=4321, token="launch-a", identity=None):+ return {+ "pid": pid,+ "port": 5173,+ "launch_token": token,+ "process_group": pid,+ "processes": [+ {"pid": pid, "identity": identity or {"pid": pid, "created_at": 100.0}}+ ],+ }+++def test_recycled_pid_is_not_signaled(frontend_state, monkeypatch):+ frontend_state.write_text(json.dumps(_saved_state()))+ process = mock.Mock(spec=psutil.Process)+ process.pid = 4321+ monkeypatch.setattr(gui_cmd.psutil, "Process", lambda pid: process)+ monkeypatch.setattr(+ gui_cmd, "_process_identity", lambda p: {"pid": p.pid, "created_at": 200.0}+ )++ assert gui_cmd.stop_frontend() is None+ process.terminate.assert_not_called()+ process.kill.assert_not_called()+ assert not frontend_state.exists()+++def test_legacy_pid_only_state_is_not_authority_to_kill(frontend_state, monkeypatch):+ frontend_state.write_text(json.dumps({"pid": 4321, "port": 5173}))+ process = mock.Mock()+ monkeypatch.setattr(gui_cmd.psutil, "Process", process)++ assert gui_cmd.stop_frontend() is None+ process.assert_not_called()++[email protected]("unavailable", ["permission", "metadata"])+def test_unreadable_identity_preserves_state_without_signaling(+ frontend_state, monkeypatch, unavailable+):+ saved = json.dumps(_saved_state())+ frontend_state.write_text(saved)+ process = mock.Mock(spec=psutil.Process)+ process.pid = 4321+ monkeypatch.setattr(gui_cmd.psutil, "Process", lambda pid: process)+ monkeypatch.setattr(+ gui_cmd,+ "_process_identity",+ mock.Mock(side_effect=PermissionError)+ if unavailable == "permission"+ else lambda p: None,+ )++ with pytest.raises(click.ClickException, match="saved state was kept"):+ gui_cmd.stop_frontend()+ process.terminate.assert_not_called()+ assert frontend_state.read_text() == saved+++def test_refresh_preserves_identity_when_process_inspection_is_denied(+ frontend_state, monkeypatch+):+ process = mock.Mock(spec=subprocess.Popen)+ process.pid = 4321+ process.poll.return_value = 0+ owner = gui_cmd._FrontendOwner(process, 5173)+ owner.state = _saved_state()+ owner.registered = True+ saved = json.dumps(owner.state)+ frontend_state.write_text(saved)+ recorded = mock.Mock(spec=psutil.Process)+ recorded.pid = 4321+ monkeypatch.setattr(gui_cmd.psutil, "Process", lambda pid: recorded)+ monkeypatch.setattr(+ gui_cmd, "_process_identity", mock.Mock(side_effect=psutil.AccessDenied(4321))+ )++ owner.refresh()++ assert owner.state["processes"] == json.loads(saved)["processes"]+ assert frontend_state.read_text() == saved++[email protected]("later", ["denied", "recycled"])+def test_refresh_does_not_lose_or_adopt_an_owner_when_identity_changes_mid_read(+ frontend_state, monkeypatch, later+):+ process = mock.Mock(spec=subprocess.Popen)+ process.pid = 4321+ process.poll.return_value = 0+ owner = gui_cmd._FrontendOwner(process, 5173)+ owner.state = _saved_state()+ owner.registered = True+ saved = json.dumps(owner.state)+ frontend_state.write_text(saved)+ recorded = mock.Mock(spec=psutil.Process)+ recorded.pid = 4321+ recorded.is_running.return_value = True+ recorded.status.return_value = psutil.STATUS_RUNNING+ recorded.children.return_value = []+ monkeypatch.setattr(gui_cmd.psutil, "Process", lambda pid: recorded)+ original = owner.state["processes"][0]["identity"]+ changed = (+ PermissionError() if later == "denied" else {**original, "created_at": 200.0}+ )+ monkeypatch.setattr(+ gui_cmd, "_process_identity", mock.Mock(side_effect=[original, changed])+ )++ owner.refresh()++ if later == "denied":+ assert owner.state["processes"] == json.loads(saved)["processes"]+ assert frontend_state.read_text() == saved+ else:+ assert owner.state["processes"] == []+++def test_stop_preserves_record_if_identity_becomes_unknown_after_signaling(+ frontend_state, monkeypatch+):+ saved = json.dumps(_saved_state())+ frontend_state.write_text(saved)+ process = mock.Mock(spec=psutil.Process)+ process.pid = 4321+ process.is_running.return_value = True+ process.status.return_value = psutil.STATUS_RUNNING+ process.children.return_value = []+ monkeypatch.setattr(gui_cmd.psutil, "Process", lambda pid: process)+ monkeypatch.setattr(+ gui_cmd,+ "_process_identity",+ mock.Mock(+ side_effect=[_saved_state()["processes"][0]["identity"], PermissionError()]+ ),+ )+ monkeypatch.setattr(gui_cmd.psutil, "wait_procs", lambda *args, **kwargs: ([], []))+ monkeypatch.setattr(gui_cmd.os, "getpgid", lambda pid: 9999, raising=False)++ with pytest.raises(click.ClickException, match="saved state was kept"):+ gui_cmd.stop_frontend()++ assert frontend_state.read_text() == saved++[email protected]("unreadable", [False, True])+def test_register_cannot_replace_another_live_or_unverifiable_owner(+ frontend_state, monkeypatch, unreadable+):+ saved = json.dumps(_saved_state())+ frontend_state.write_text(saved)+ processes = {}+ for pid in (4321, 9876):+ process = mock.Mock(spec=psutil.Process)+ process.pid = pid+ process.is_running.return_value = True+ process.status.return_value = psutil.STATUS_RUNNING+ process.children.return_value = []+ processes[pid] = process+ monkeypatch.setattr(gui_cmd.psutil, "Process", processes.__getitem__)++ def identity(process):+ if process.pid == 4321 and unreadable:+ raise psutil.AccessDenied(4321)+ return {"pid": process.pid, "created_at": 100.0}++ monkeypatch.setattr(gui_cmd, "_process_identity", identity)+ child = mock.Mock(spec=subprocess.Popen)+ child.pid = 9876+ child.poll.return_value = None+ owner = gui_cmd._FrontendOwner(child, 5180)++ with pytest.raises(click.ClickException, match="Another frontend"):+ owner.register()++ assert not owner.registered+ assert frontend_state.read_text() == saved+++def test_reclaim_uses_its_snapshot_when_another_port_registers(+ frontend_state, monkeypatch+):+ initial = _saved_state()+ replacement = {**_saved_state(pid=9876, token="replacement"), "port": 5180}+ frontend_state.write_text(json.dumps(replacement))+ monkeypatch.setattr(+ gui_cmd, "_read_frontend_state", mock.Mock(side_effect=[initial, replacement])+ )+ terminate = mock.Mock(return_value=True)+ monkeypatch.setattr(gui_cmd, "_terminate_frontend", terminate)+ monkeypatch.setattr(gui_cmd, "_port_free", lambda port: True)++ assert gui_cmd._reclaim_port(5173)++ terminate.assert_called_once_with(initial)+ assert json.loads(frontend_state.read_text()) == replacement+++def test_linux_identity_uses_boot_id_and_start_ticks(monkeypatch):+ process = mock.Mock(spec=psutil.Process)+ process.pid = 4321+ process.create_time.side_effect = AssertionError("wall-clock epoch is not identity")+ expected = {"pid": 4321, "boot_id": "boot-a", "start_ticks": 12345}+ monkeypatch.setattr(gui_cmd.sys, "platform", "linux")+ monkeypatch.setattr(daemon_cmd, "_linux_process_identity", lambda pid: expected)++ assert gui_cmd._process_identity(process) == expected+ process.create_time.assert_not_called()+++def test_cleanup_is_idempotent_and_cannot_clear_a_later_launch(+ frontend_state, monkeypatch+):+ process = mock.Mock(spec=subprocess.Popen)+ process.pid = 4321+ owner = gui_cmd._FrontendOwner(process, 5173)+ frontend_state.write_text(json.dumps(_saved_state(token="new-launch")))+ terminate = mock.Mock(return_value=True)+ monkeypatch.setattr(gui_cmd, "_terminate_frontend", terminate)++ owner.shutdown()+ owner.shutdown()++ terminate.assert_called_once()+ assert json.loads(frontend_state.read_text())["launch_token"] == "new-launch"+++def test_refresh_does_not_overwrite_another_launch(frontend_state, monkeypatch):+ process = mock.Mock(spec=subprocess.Popen)+ process.pid = 4321+ owner = gui_cmd._FrontendOwner(process, 5173)+ owner.registered = True+ frontend_state.write_text(json.dumps(_saved_state(token="new-launch")))+ observed = mock.Mock(spec=psutil.Process)+ observed.pid = 4321+ observed.is_running.return_value = True+ monkeypatch.setattr(+ gui_cmd, "_frontend_processes", lambda *args, **kwargs: [observed]+ )+ monkeypatch.setattr(+ gui_cmd, "_process_identity", lambda p: {"pid": p.pid, "created_at": 100.0}+ )++ owner.refresh()++ assert json.loads(frontend_state.read_text())["launch_token"] == "new-launch"+++def _is_running(process):+ try:+ return process.is_running() and process.status() != psutil.STATUS_ZOMBIE+ except psutil.NoSuchProcess:+ return False++[email protected]("launcher_exits", [False, True])+def test_stop_cleans_up_real_descendants_even_after_launcher_exit(+ tmp_path, frontend_state, launcher_exits+):+ child_pid_file = tmp_path / "child.pid"+ parent_code = (+ "import pathlib, subprocess, sys, time\n"+ "child = subprocess.Popen([sys.executable, '-c', "+ "'import time; time.sleep(60)'])\n"+ "pathlib.Path(sys.argv[1]).write_text(str(child.pid))\n"+ "time.sleep(60)\n"+ )+ options = (+ {"creationflags": subprocess.CREATE_NEW_PROCESS_GROUP}+ if sys.platform == "win32"+ else {"start_new_session": True}+ )+ parent = subprocess.Popen(+ [sys.executable, "-c", parent_code, str(child_pid_file)], **options+ )+ child = None+ owner = gui_cmd._FrontendOwner(parent, 5173)+ try:+ deadline = time.monotonic() + 10+ while time.monotonic() < deadline:+ try:+ child = psutil.Process(int(child_pid_file.read_text()))+ break+ except (FileNotFoundError, ValueError):+ time.sleep(0.02)+ assert child is not None+ owner.register()+ assert child.pid in {record["pid"] for record in owner.state["processes"]}+ if launcher_exits:+ parent.terminate()+ parent.wait(timeout=5)+ assert _is_running(child)++ assert gui_cmd.stop_frontend() == parent.pid++ parent.wait(timeout=5)+ assert not _is_running(child)+ assert not frontend_state.exists()+ finally:+ if child is not None and _is_running(child):+ child.kill()+ child.wait(timeout=5)+ if parent.poll() is None:+ parent.kill()+ parent.wait(timeout=5)+++def gui_invocation(tmp_path, monkeypatch):+ process = mock.Mock(spec=subprocess.Popen)+ process.pid = 4321+ process.poll.return_value = None+ process.wait.return_value = 0+ owner = mock.Mock()+ monkeypatch.setattr(gui_cmd, "_frontend_dir", lambda: tmp_path)+ monkeypatch.setattr(gui_cmd, "_check_frontend_port", lambda port: None)+ monkeypatch.setattr(gui_cmd, "_ensure_frontend_dependencies", lambda *args: None)+ monkeypatch.setattr(gui_cmd.shutil, "which", lambda name: f"/bin/{name}")+ monkeypatch.setattr(gui_cmd.subprocess, "Popen", lambda *args, **kwargs: process)+ monkeypatch.setattr(gui_cmd, "_FrontendOwner", lambda *args: owner)+ monkeypatch.setattr(gui_cmd, "_api_healthy", lambda *args: False)+ monkeypatch.setattr(gui_cmd, "_wait_for_port", lambda *args, **kwargs: True)+ monkeypatch.setattr(gui_cmd.webbrowser, "open", lambda url: True)+ return process, owner++[email protected]("failure", [None, "register", "startup", "browser"])+def test_invocation_unregisters_exit_hook_and_restores_signals(+ gui_invocation, monkeypatch, failure+):+ process, owner = gui_invocation+ if failure == "register":+ owner.register.side_effect = RuntimeError("cannot record state")+ elif failure == "startup":+ monkeypatch.setattr(gui_cmd, "_wait_for_port", lambda *args, **kwargs: False)+ elif failure == "browser":+ monkeypatch.setattr(+ gui_cmd.webbrowser, "open", mock.Mock(side_effect=RuntimeError)+ )+ previous = signal.getsignal(signal.SIGTERM)+ register, unregister = mock.Mock(), mock.Mock()+ monkeypatch.setattr(gui_cmd.atexit, "register", register)+ monkeypatch.setattr(gui_cmd.atexit, "unregister", unregister)++ result = CliRunner().invoke(gui_cmd.gui, ["--no-server"])++ assert result.exit_code == (0 if failure is None else 1)+ owner.shutdown.assert_called_once()+ unregister.assert_called_once_with(register.call_args.args[0])+ assert signal.getsignal(signal.SIGTERM) is previous+++def test_api_monitor_arms_when_slow_backend_first_becomes_healthy(+ gui_invocation, monkeypatch+):+ process, owner = gui_invocation+ process.wait.side_effect = [subprocess.TimeoutExpired("npm", 5)] * 4 + [0]+ monkeypatch.setattr(+ gui_cmd,+ "_api_healthy",+ mock.Mock(side_effect=[False, True, False, False, False]),+ )+ monkeypatch.setattr(gui_cmd, "_daemon_pid_alive", lambda port: False)++ result = CliRunner().invoke(gui_cmd.gui, ["--no-server", "--no-browser"])++ assert result.exit_code == 1+ assert "API server stopped" in result.output+ owner.shutdown.assert_called_once()+++def test_api_failure_before_first_healthy_probe_does_not_leave_gui_running(+ gui_invocation, monkeypatch+):+ process, owner = gui_invocation+ process.wait.side_effect = [subprocess.TimeoutExpired("npm", 5)] * 3 + [0]+ monkeypatch.setattr(+ gui_cmd.subprocess, "run", mock.Mock(return_value=mock.Mock(returncode=0))+ )+ monkeypatch.setattr(gui_cmd, "_daemon_pid_alive", lambda port: False)++ result = CliRunner().invoke(gui_cmd.gui, ["--no-browser"])++ assert result.exit_code == 1+ assert "failed to start" in result.output+ owner.shutdown.assert_called_once()++[email protected]("registered", [False, True])+def test_automatic_api_reuse_requires_verified_daemon_ownership(+ gui_invocation, monkeypatch, registered+):+ _, owner = gui_invocation+ monkeypatch.setattr(gui_cmd, "_api_healthy", lambda *args: True)+ ownership = mock.Mock(return_value=registered)+ monkeypatch.setattr(gui_cmd, "_daemon_pid_alive", ownership)+ run = mock.Mock(return_value=mock.Mock(returncode=0))+ monkeypatch.setattr(gui_cmd.subprocess, "run", run)++ result = CliRunner().invoke(gui_cmd.gui, ["--no-browser"])++ ownership.assert_called_once_with(8000, require_ready=True)+ run.assert_not_called()+ if registered:+ assert result.exit_code == 0+ assert "Reusing the API server" in result.output+ owner.register.assert_called_once()+ else:+ assert result.exit_code == 1+ assert "unregistered service" in result.output+ owner.register.assert_not_called()+++def test_explicit_no_server_allows_an_externally_managed_backend(+ gui_invocation, monkeypatch+):+ _, owner = gui_invocation+ monkeypatch.setattr(gui_cmd, "_api_healthy", lambda *args: True)+ ownership = mock.Mock(return_value=False)+ monkeypatch.setattr(gui_cmd, "_daemon_pid_alive", ownership)++ result = CliRunner().invoke(gui_cmd.gui, ["--no-server", "--no-browser"])++ assert result.exit_code == 0+ ownership.assert_not_called()+ owner.register.assert_called_once()+++def test_pending_daemon_is_monitored_but_not_automatically_reused(monkeypatch):+ monkeypatch.setattr(daemon_cmd, "_state_lock", lambda: nullcontext())+ monkeypatch.setattr(+ daemon_cmd, "_read_state", lambda: {"pid": 4321, "port": 8000, "ready": False}+ )+ monkeypatch.setattr(daemon_cmd, "_read_pid_unlocked", lambda: 4321)++ assert gui_cmd._daemon_pid_alive(8000)+ assert not gui_cmd._daemon_pid_alive(8000, require_ready=True)+++def test_daemon_stop_can_stop_frontend_without_a_backend(monkeypatch):+ monkeypatch.setattr(gui_cmd, "stop_frontend", lambda: 4321)+ monkeypatch.setattr(daemon_cmd, "_read_pid", lambda: None)++ result = CliRunner().invoke(daemon_cmd.stop)++ assert result.exit_code == 0+ assert "Frontend stopped" in result.outputdiff --git a/uv.lock b/uv.lockindex 2082e6da..aa0407df 100644--- a/uv.lock+++ b/uv.lock@@ -5202,6 +5202,7 @@ dependencies = [{ name = "nvidia-ml-py" },{ name = "openai" },{ name = "posthog" },+ { name = "psutil" },{ name = "python-telegram-bot" },{ name = "rich" },{ name = "tomli", marker = "python_full_version < '3.11'" },@@ -5494,6 +5495,7 @@ requires-dist = [{ name = "posthog", specifier = ">=3.0" },{ name = "praw", marker = "extra == 'channel-reddit'", specifier = ">=7.0" },{ name = "pre-commit", marker = "extra == 'dev'", specifier = ">=3.0" },+ { name = "psutil", specifier = ">=5.9" },{ name = "pydantic", marker = "extra == 'desktop'", specifier = ">=2.0" },{ name = "pydantic", marker = "extra == 'server'", specifier = ">=2.0" },{ name = "pygemma", marker = "extra == 'inference-gemma'", specifier = ">=0.1.3" },