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(desktop): start again when a leftover headless instance holds the lock

rubenluetke10-beep4928962fb7cf
diff --git a/docs/BUGS.md b/docs/BUGS.md
index cf89477aa4..68119f4d35 100644
--- a/docs/BUGS.md
+++ b/docs/BUGS.md
@@ -12645,6 +12645,49 @@ policy as well, so the app does not depend on every shell agreeing with it.
---
+## BUG-181: clicking Restart sometimes only shut the window down (HIGH, FIXED 2026-08-25)
+
+**Symptom.** Click Restart (top bar, Settings, the permissions banner). The
+window closes. Sometimes nothing comes back. A Start-menu click later starts
+it normally. Intermittent: the same button often works.
+
+**Root cause.** Two cooperating defects, both visible in `jarvis_desktop.log`
+around a live restart (2026-08-25 10:52:56 and 16:06:21):
+
+1. The restart helper (`jarvis.ui.relauncher`) spawned
+ `python -m jarvis.ui.web.launcher` and treated "that PID stayed alive for
+ 5 seconds" as proof the app came up. On Windows the launcher immediately
+ re-execs through `PersonalJarvis.exe` (taskbar branding) and the python
+ PID exits in ~40 ms. The helper read that as a bounce off the
+ single-instance lock and spawned two more copies. Three branded processes
+ then raced: the first still booting (lock taken, no window yet), the
+ later ones hitting `_recover_from_already_running` ("lock is held but the
+ holder is not responding"). One of them could focus, bounce, or — if the
+ user confirmed, or if Job-Object kill-on-close took the helper with the
+ dying parent — leave nothing running.
+2. The helper was spawned `DETACHED_PROCESS | CREATE_NO_WINDOW` without
+ `CREATE_BREAKAWAY_FROM_JOB` and without redirecting stdio. A parent
+ inside a Windows Job Object (Windows Terminal, some Start-Menu launches)
+ killed the helper on `os._exit`; invalid stdio could kill a child on its
+ first log line. Both look like "it only shut down".
+
+**Fix.**
+* `build_launch_command` on Windows launches the existing branded exe
+ directly and sets `JARVIS_BRANDED_LAUNCH=1` so it does not re-exec.
+* `_new_instance_settled` succeeds when the admin port answers, not only
+ when the spawn PID stays alive — a branded hand-off is success, not a
+ bounce, so the helper does not spawn extras.
+* `detached_creationflags` includes `CREATE_BREAKAWAY_FROM_JOB` (retry
+ without it on WinError 5). Stdio is redirected to `DEVNULL`.
+* `_recover_from_already_running` waits out a holder that is only seconds
+ old and has no window yet, instead of offering to kill a boot in progress.
+
+**Tests.** `tests/unit/ui/test_relauncher.py` (handoff does not respawn,
+breakaway retry, branded argv) and
+`tests/unit/ui/test_launcher_boot_trace.py` (young holder is waited for).
+
+---
+
## BUG-180: the app "takes minutes to start" — every launch that never reached a window was mute, and a stuck earlier instance turned every click into a silent exit (HIGH, FIXED 2026-08-25)
**Symptom.** Click the Start-Menu shortcut, wait, nothing. Click again,
@@ -12716,6 +12759,52 @@ a shortcut that targets the in-venv branded exe directly skips it.
---
+## BUG-182: the desktop app "does not start" because a leftover headless instance holds the lock and focus is rejected as CSRF (HIGH, FIXED 2026-08-25)
+
+**Symptom.** Clicking the Start-Menu shortcut or `run.bat` does nothing.
+`data/jarvis_desktop.log` shows:
+
+```
+POST http://127.0.0.1:47821/api/window/focus "HTTP/1.1 403 Forbidden"
+launcher: Jarvis lock is held but the holder is not responding. — NO window found
+Personal Jarvis reports that it is already running, but no window could be
+found and the running process is unknown.
+```
+
+**Root cause.** Three things stacked:
+
+1. A `--headless` leftover (smoke / agent / `run.bat --headless`) bound
+ port 47821 and took `data/jarvis.lock`. Headless is allowed to be
+ primary when it is the sole instance, but it never wrote the
+ `.jarvis-running` sidecar, so the desktop launch could not name a pid.
+2. With no sidecar, `acquire_single_instance_lock` treated the holder as a
+ zombie, waited 5 s, and raised "holder is not responding" — even though
+ `/api/health` was 200.
+3. Recovery POSTed `/api/window/focus` with no Origin and no Bearer.
+ Loopback open-access lets the request through authentication, then the
+ CSRF check (`origin_is_trusted(required=True)`) rejects a missing Origin
+ as 403 `Untrusted Origin header.`. No window exists on a headless
+ holder anyway, and with no pid the Yes/No eviction dialog never appeared.
+
+**Fix.**
+* Headless writes the sidecar when it claims the lock, and removes it on
+ shutdown (`launcher._claim_headless_primary_lock(port=…)`).
+* A held production lock with a missing sidecar looks up the process bound
+ to the admin port instead of waiting 5 s.
+* Recovery names the holder from sidecar, then the error text, then the
+ listening pid, so the "stop and start fresh?" dialog can actually run.
+* The focus ping sends the Control-API Bearer (loopback Origin only if no
+ key exists yet).
+
+**Tests.** `tests/contract/test_single_instance.py`
+(`test_missing_sidecar_names_the_listener_instead_of_waiting`),
+`tests/unit/ui/test_launcher_boot_trace.py` (pid from error / port),
+`tests/unit/ui/test_focus_existing_instance.py`,
+`tests/unit/ui/web/test_launcher_primary_instance.py`
+(`test_sole_headless_instance_writes_the_sidecar`).
+
+---
+
## BUG-178: the Costs section could not add up — a stuck filter emptied an area, seats read as "$0.00", Grok Build and three Claude accounts were never counted, and speech metering leaked (HIGH, FIXED 2026-08-25)
**Symptom (maintainer, 2026-08-25).** Overall showed "Total spend $18.41"
@@ -12790,3 +12879,45 @@ index-state endpoint ("63 % of 12.7 GB read") does not exist yet.
and every reader is a place to be wrong in its own way. The audit that found
these was one agent per area with the real databases in front of it, not a
walk through the code.
+
+---
+
+## BUG-179: OpenRouter and Gemini spend nobody could see — twenty callers of the brain protocol never reached the ledger (HIGH, FIXED 2026-08-25)
+
+**Symptom (maintainer, 2026-08-25).** "I have spent money on OpenRouter, I
+know it 100 %, and on Gemini too — the report shows almost nothing." The
+provider table showed OpenRouter at $0.00 and Gemini at $0.19.
+
+**Root cause.** The Costs section learned about spend only from the surfaces
+that happened to record it: a voice turn's `BrainTurnCompleted`, a chat's
+`turn_finished`, a mission's draft, the CLI transcripts. Everything else that
+calls `Brain.complete()` — dictation polish (its own HTTP clients, not even a
+plugin), the wiki curator and session roll-ups, awareness digests, the
+mission critic and decomposer, computer-use planning, skill authoring, board
+profiles, recap/prompt composers — spent on the configured primary brain
+(`openrouter` → `google/gemini-3.5-flash` on this machine) and told no one.
+`rg "\.complete\("` outside plugins and tests: 24 files.
+
+**Fix.**
+
+* `jarvis/costs/ledger.py` — one append-only ledger (`data/llm_usage.db`),
+ written by a daemon thread off the hot path (AP-9), read by the report.
+ `usage_context("wiki")` tags who asked.
+* `jarvis/brain/usage_meter.py` — `MeteredBrain` wraps every provider at the
+ one door they all come through, `BrainProviderRegistry.instantiate`. The
+ usage block a plugin yields is written down with the caller; `__class__`
+ forwards so `isinstance` checks keep their answer.
+* Surfaces that already keep a richer record tag their calls (`voice-turn`,
+ `agent-chat`, `mission-worker`) and the reader skips those tags — the
+ ledger row is the audit trail, not a second bill.
+* The dictation polish clients parse the usage their responses carry and
+ record it as `dictation`.
+* New surface `background` / role `background`, shown inside "{name}"; the
+ entry's label names the job.
+* The section gains a spend switch — all · billed to keys · on
+ subscriptions — and "Where it went" says "the 12 most expensive of N ·
+ share of the total" instead of reading like a sum.
+
+**Lesson.** A report that depends on every caller remembering to report is a
+report of the callers that remembered. Meter where the object is made, not
+where it is used.
diff --git a/jarvis/ui/desktop_app.py b/jarvis/ui/desktop_app.py
index 1dd5cddbc5..91d25ba7f9 100644
--- a/jarvis/ui/desktop_app.py
+++ b/jarvis/ui/desktop_app.py
@@ -335,18 +335,19 @@ def _pid_alive(pid: int) -> bool:
return True
-def _write_meta(port: int, pid: int) -> None:
+def _write_meta(port: int, pid: int, *, meta_path: Path | None = None) -> None:
"""Writes the PID sidecar next to the lock file (atomic via tmp+replace)."""
+ path = meta_path or META_FILE_PATH
try:
- META_FILE_PATH.parent.mkdir(parents=True, exist_ok=True)
+ path.parent.mkdir(parents=True, exist_ok=True)
payload = {
"pid": int(pid),
"port": int(port),
"started_at": time.time(),
}
- tmp = META_FILE_PATH.with_suffix(META_FILE_PATH.suffix + ".tmp")
+ tmp = path.with_suffix(path.suffix + ".tmp")
tmp.write_text(json.dumps(payload), encoding="utf-8")
- os.replace(tmp, META_FILE_PATH)
+ os.replace(tmp, path)
except OSError as exc:
try:
from loguru import logger
@@ -412,6 +413,122 @@ def _read_meta() -> dict[str, Any] | None:
return data
+def _fallback_admin_port() -> int:
+ """The port a missing sidecar still has to probe.
+
+ Headless boots bind this before they write ``.jarvis-running`` (and until
+ 2026-08-25 they never wrote it). The desktop launch must still find them.
+ Config is best-effort: a broken TOML must not block the lock path.
+ """
+ try:
+ port = int(load_config().ui.admin_api_port)
+ except Exception: # noqa: BLE001
+ return 47821
+ return port if port > 0 else 47821
+
+
+def _pid_listening_on_port(port: int) -> int | None:
+ """PID that currently LISTENs on loopback *port*, or ``None``.
+
+ Used when the ``.jarvis-running`` sidecar is missing so a desktop launch
+ can still name the holder and ask to evict it. Best-effort: a probe that
+ cannot see other processes returns None and the caller keeps the safe
+ "unknown holder" path rather than guessing.
+ """
+ port = int(port)
+ pid = _pid_listening_on_port_psutil(port)
+ if pid is not None:
+ return pid
+ return _pid_listening_on_port_netstat(port)
+
+
+def _pid_listening_on_port_psutil(port: int) -> int | None:
+ try:
+ import psutil # type: ignore[import-not-found]
+ except Exception: # noqa: BLE001
+ return None
+ try:
+ connections = psutil.net_connections(kind="inet")
+ except Exception: # noqa: BLE001 — AccessDenied / platform limits
+ return None
+ listen = getattr(psutil, "CONN_LISTEN", "LISTEN")
+ for conn in connections:
+ if getattr(conn, "status", None) != listen:
+ continue
+ laddr = getattr(conn, "laddr", None)
+ if laddr is None or int(getattr(laddr, "port", 0) or 0) != port:
+ continue
+ pid = getattr(conn, "pid", None)
+ if pid:
+ return int(pid)
+ return None
+
+
+def _pid_listening_on_port_netstat(port: int) -> int | None:
+ """Windows fallback when psutil cannot see other processes' sockets."""
+ if sys.platform != "win32":
+ return None
+ try:
+ import subprocess
+
+ from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS
+
+ completed = subprocess.run( # noqa: S603 — fixed argv, port is an int
+ ["netstat", "-ano", "-p", "tcp"],
+ capture_output=True,
+ text=True,
+ encoding="utf-8",
+ errors="replace",
+ check=False,
+ timeout=5.0,
+ creationflags=NO_WINDOW_CREATIONFLAGS,
+ )
+ except Exception: # noqa: BLE001
+ return None
+ needle = f":{int(port)}"
+ for raw in completed.stdout.splitlines():
+ line = raw.upper()
+ if "LISTEN" not in line and "ABH" not in line:
+ continue
+ if needle not in raw:
+ continue
+ parts = raw.split()
+ if not parts:
+ continue
+ try:
+ pid = int(parts[-1])
+ except ValueError:
+ continue
+ if pid > 0:
+ return pid
+ return None
+
+
+def _focus_request_headers(port: int) -> dict[str, str]:
+ """Authenticate the launcher's focus ping so CSRF does not reject it.
+
+ Loopback open-access lets an unauthenticated POST through, but unsafe
+ methods still require a trusted Origin OR a control-key Bearer. pythonw
+ sends neither, so the 2026-08-25 desktop launch saw HTTP 403
+ ``Untrusted Origin header.`` and treated a live holder as windowless.
+ """
+ headers: dict[str, str] = {}
+ try:
+ from jarvis.core.control_key import get_control_key
+
+ key = get_control_key()
+ except Exception: # noqa: BLE001 — a missing key must not block focusing
+ key = None
+ if key:
+ headers["Authorization"] = f"Bearer {key}"
+ else:
+ # No key yet (very early boot): a loopback Origin is enough for the
+ # CSRF check on open-access, and browsers cannot spoof this from a
+ # foreign page. Prefer Bearer whenever the key exists.
+ headers["Origin"] = f"http://127.0.0.1:{int(port)}"
+ return headers
+
+
def _focus_existing_instance() -> bool:
"""Asks the running instance to bring its window to the front.
@@ -428,9 +545,10 @@ def _focus_existing_instance() -> bool:
# httpx is absent on a minimal install; the caller falls back to the
# window-title path, which needs no HTTP at all.
return False
- url = f"http://127.0.0.1:{int(meta['port'])}/api/window/focus"
+ port = int(meta["port"])
+ url = f"http://127.0.0.1:{port}/api/window/focus"
try:
- r = httpx.post(url, timeout=1.0)
+ r = httpx.post(url, headers=_focus_request_headers(port), timeout=1.0)
except Exception: # noqa: BLE001
# Nothing listening = no running instance, which is the ANSWER this
# function returns, not a failure worth reporting.
@@ -466,6 +584,7 @@ def focus_existing_instance_robust() -> bool:
try:
r = httpx.post(
f"http://127.0.0.1:{port}/api/window/focus",
+ headers=_focus_request_headers(port),
timeout=1.0,
)
except Exception: # noqa: BLE001, S112
@@ -713,12 +832,12 @@ def _is_brain_diagnostic(text: str) -> bool:
"""True for backend diagnostics that don't count as a Jarvis reply."""
t = text.lower()
return (
- t.startswith("kein brain-key gefunden") # i18n-allow: matches German diagnostic text produced by jarvis/brain/manager.py
- or t.startswith("keine brain-provider") # i18n-allow: matches German diagnostic text produced by jarvis/brain/manager.py
- or t.startswith("brain nicht verfuegbar") # i18n-allow: matches German diagnostic text produced by jarvis/brain/manager.py
- or t.startswith("brain-fehler") # i18n-allow: matches German diagnostic text produced by jarvis/brain/manager.py
+ t.startswith("kein brain-key gefunden") # i18n-allow
+ or t.startswith("keine brain-provider") # i18n-allow
+ or t.startswith("brain nicht verfuegbar") # i18n-allow
+ or t.startswith("brain-fehler") # i18n-allow
or "api-key" in t
- or ("provider" in t and ("unerreichbar" in t or "nicht verfuegbar" in t)) # i18n-allow: matches German diagnostic text produced by jarvis/brain/manager.py
+ or ("provider" in t and ("unerreichbar" in t or "nicht verfuegbar" in t)) # i18n-allow
)
@@ -950,6 +1069,7 @@ def acquire_single_instance_lock(
meta_path: Path | None = None,
health_probe: Callable[[int], bool] | None = None,
terminate: Callable[[int], bool] | None = None,
+ listen_pid: Callable[[int], int | None] | None = None,
) -> FileLock:
"""Acquire the exclusive lock or raise :class:`SingleInstanceError`.
@@ -971,12 +1091,17 @@ def acquire_single_instance_lock(
meta_path: Override for tests.
health_probe: Override for tests — ``(port) -> bool`` health check.
terminate: Override for tests — ``(pid) -> bool`` process kill.
+ listen_pid: Override for tests — ``(port) -> pid`` of the process
+ bound to that port. Production finds a headless holder that
+ never wrote the sidecar.
"""
lp = lock_path or LOCK_FILE_PATH
mp = meta_path or META_FILE_PATH
lp.parent.mkdir(parents=True, exist_ok=True)
probe = health_probe or _default_lock_holder_health
killer = terminate or _terminate_pid
+ finder_overridden = listen_pid is not None
+ finder = listen_pid or _pid_listening_on_port
lock = FileLock(str(lp))
try:
@@ -993,12 +1118,43 @@ def acquire_single_instance_lock(
raw = mp.read_text(encoding="utf-8")
meta = json.loads(raw)
except (FileNotFoundError, OSError, json.JSONDecodeError):
- # No usable sidecar: pid/port stay None below, which routes to the
- # conservative path (assume a healthy holder, do not evict).
+ # No usable sidecar: pid/port stay None below. A headless boot used
+ # to never write one, so we still name the process on the admin port
+ # instead of waiting 5 s and reporting "not responding".
meta = None
pid = int(meta["pid"]) if meta and "pid" in meta else None
port = int(meta["port"]) if meta and "port" in meta and meta["port"] else None
+ if pid is None or not _pid_alive(pid):
+ # Sidecar missing or stale. Only look at the live admin port when this
+ # IS the production lock (or a test that passed ``listen_pid``).
+ # Isolated test paths must not inherit whatever happens to be bound
+ # on 47821 on the developer machine.
+ try:
+ same_lock = lp.resolve() == LOCK_FILE_PATH.resolve()
+ except OSError:
+ same_lock = False
+ may_discover = same_lock or finder_overridden
+ probe_port = port
+ if probe_port is None and may_discover:
+ probe_port = _fallback_admin_port()
+ if probe_port is not None and may_discover:
+ discovered = None
+ with suppress(Exception):
+ discovered = finder(int(probe_port))
+ if (
+ discovered is not None
+ and int(discovered) > 0
+ and int(discovered) != os.getpid()
+ and _pid_alive(int(discovered))
+ ):
+ pid = int(discovered)
+ if port is None:
+ port = int(probe_port)
+ elif probe(int(probe_port)):
+ raise SingleInstanceError(
+ f"Jarvis is already running (port={int(probe_port)} answering, pid unknown)."
+ )
if pid is not None and _pid_alive(pid):
# Holder is alive. Is it actually FUNCTIONAL (serving its port)? A
# healthy instance, the own pid, or a holder with no recorded port is
@@ -3134,14 +3290,13 @@ class DesktopApp:
launcher → window) lands at ordinary integrity. Any failure returns
``(False, detail)`` WITHOUT scheduling the quit.
"""
- import subprocess
-
from loguru import logger
from jarvis.ui.relauncher import (
detached_creationflags,
fresh_user_env,
run_restart_quit_sequence,
+ spawn_detached,
)
window = getattr(self, "_window", None)
@@ -3174,15 +3329,10 @@ class DesktopApp:
)
return (False, outcome.detail)
else:
- kwargs: dict[str, Any] = {"cwd": repo_root, "close_fds": True}
- if sys.platform == "win32":
- kwargs["creationflags"] = detached_creationflags()
- else:
- kwargs["start_new_session"] = True
- subprocess.Popen( # noqa: S603 — fixed argv, no shell, own interpreter
- argv,
- **kwargs,
- )
+ # Break away from any Job Object and give the helper valid
+ # stdio: without both, the helper dies with this process or
+ # crashes on its first log line, and Restart only shuts down.
+ spawn_detached(argv, cwd=repo_root, env=fresh_user_env())
except Exception as exc: # noqa: BLE001 — never half-quit on a spawn error
logger.opt(exception=exc).warning(
"relauncher spawn failed — staying up (no self-restart)"
diff --git a/jarvis/ui/web/launcher.py b/jarvis/ui/web/launcher.py
index 707a51181c..23fdfd690f 100644
--- a/jarvis/ui/web/launcher.py
+++ b/jarvis/ui/web/launcher.py
@@ -16,6 +16,7 @@ import argparse
import asyncio
import contextlib
import os
+import re
import signal
import sys
import time
@@ -69,12 +70,12 @@ def _is_brain_diagnostic(text: str) -> bool:
"""True for backend diagnostics that don't count as a Jarvis reply."""
t = text.lower()
return (
- t.startswith("kein brain-key gefunden") # i18n-allow: matches German diagnostic text produced by jarvis/brain/manager.py
- or t.startswith("keine brain-provider") # i18n-allow: matches German diagnostic text produced by jarvis/brain/manager.py
- or t.startswith("brain nicht verfuegbar") # i18n-allow: matches German diagnostic text produced by jarvis/brain/manager.py
- or t.startswith("brain-fehler") # i18n-allow: matches German diagnostic text produced by jarvis/brain/manager.py
+ t.startswith("kein brain-key gefunden") # i18n-allow
+ or t.startswith("keine brain-provider") # i18n-allow
+ or t.startswith("brain nicht verfuegbar") # i18n-allow
+ or t.startswith("brain-fehler") # i18n-allow
or "api-key" in t
- or ("provider" in t and ("unerreichbar" in t or "nicht verfuegbar" in t)) # i18n-allow: matches German diagnostic text produced by jarvis/brain/manager.py
+ or ("provider" in t and ("unerreichbar" in t or "nicht verfuegbar" in t)) # i18n-allow
)
@@ -206,15 +207,33 @@ def _acquire_primary_lock_for_headless(*, lock_path=None, meta_path=None):
return lock
-def _claim_headless_primary_lock(args, *, lock_path=None, meta_path=None):
- """Claim the headless primary lock unless this is an explicit no-lock run."""
+def _claim_headless_primary_lock(args, *, lock_path=None, meta_path=None, port=None):
+ """Claim the headless primary lock unless this is an explicit no-lock run.
+
+ When the lock is taken, the PID sidecar is written so a later desktop
+ launch can find this process. Headless used to skip that write, which
+ left the desktop start with a held lock and no pid to ask about.
+ """
if bool(getattr(args, "no_lock", False)):
os.environ["JARVIS_PRIMARY_INSTANCE"] = "0"
return None
- return _acquire_primary_lock_for_headless(
+ lock = _acquire_primary_lock_for_headless(
lock_path=lock_path,
meta_path=meta_path,
)
+ if lock is not None and port is not None:
+ try:
+ from jarvis.ui.desktop_app import _write_meta
+
+ _write_meta(int(port), os.getpid(), meta_path=meta_path)
+ except Exception: # noqa: BLE001 — sidecar is recovery, not boot
+ import logging as _logging
+
+ _logging.getLogger(__name__).warning(
+ "headless could not write the instance sidecar",
+ exc_info=True,
+ )
+ return lock
def _direct_filelock_fallback(lock_path=None):
@@ -541,7 +560,7 @@ async def _run_headless(args) -> int:
# init below. Deferred off the time-to-serving path (its desktop_app import
# is ~420 ms). After a host crash a stale lock is reclaimed here via the
# PID-sidecar in acquire_single_instance_lock.
- _headless_lock = _claim_headless_primary_lock(args)
+ _headless_lock = _claim_headless_primary_lock(args, port=_port)
_lx_mark("lock")
from jarvis.brain.factory import build_default_brain
@@ -875,6 +894,16 @@ async def _run_headless(args) -> int:
_logging.getLogger(__name__).debug(
"headless lock release failed on shutdown: %s", exc
)
+ try:
+ from jarvis.ui.desktop_app import META_FILE_PATH
+
+ META_FILE_PATH.unlink(missing_ok=True)
+ except Exception as exc: # noqa: BLE001 — next boot reclaims a leftover sidecar
+ import logging as _logging
+
+ _logging.getLogger(__name__).debug(
+ "headless sidecar cleanup failed on shutdown: %s", exc
+ )
return 0
@@ -1004,6 +1033,65 @@ def _install_boot_trace(raw_argv: list[str]) -> None:
pass
+_HOLDER_PID_RE = re.compile(r"pid=(\d+)")
+
+
+def _holder_pid_from_error(error: Exception) -> int | None:
+ """Read a pid out of a ``SingleInstanceError`` message, if one was named."""
+ match = _HOLDER_PID_RE.search(str(error))
+ if match is None:
+ return None
+ pid = int(match.group(1))
+ return pid if pid > 0 else None
+
+
+def _discover_holder_pid(error: Exception, meta) -> int | None:
+ """Name the process that is blocking this desktop launch.
+
+ Order: sidecar, the lock-error text, then whoever is bound to the admin
+ port. A headless boot that never wrote the sidecar still has a pid on
+ the port; without this the user got "running process is unknown" and
+ no window.
+ """
+ pid = None
+ with contextlib.suppress(Exception):
+ if meta and meta.get("pid") is not None:
+ pid = int(meta["pid"])
+ if pid is None:
+ with contextlib.suppress(Exception):
+ pid = _holder_pid_from_error(error)
+ if pid is None:
+ with contextlib.suppress(Exception):
+ from jarvis.ui.desktop_app import (
+ _fallback_admin_port,
+ _pid_listening_on_port,
+ )
+
+ port = None
+ if meta and meta.get("port") is not None:
+ port = int(meta["port"])
+ if port is None:
+ port = _fallback_admin_port()
+ found = _pid_listening_on_port(port)
+ if found is not None:
+ pid = int(found)
+ if pid is None or pid <= 0 or pid == os.getpid():
+ return None
+ return pid
+
+
+def _process_age_seconds(pid: int) -> float | None:
+ """How long ``pid`` has been running, or ``None`` when we cannot tell."""
+ if pid <= 0:
+ return None
+ try:
+ import psutil
+
+ return max(0.0, time.time() - float(psutil.Process(pid).create_time()))
+ except Exception: # noqa: BLE001 — unknown / gone / no psutil → not "young"
+ return None
+
+
def _recover_from_already_running(
error: Exception,
*,
@@ -1012,6 +1100,11 @@ def _recover_from_already_running(
ask=None,
terminate=None,
acquire=None,
+ process_age=None,
+ sleep=None,
+ now=None,
+ booting_grace: float = 20.0,
+ discover_pid=None,
):
"""The lock is held. Bring the holder forward — or, with consent, evict it.
@@ -1026,6 +1119,11 @@ def _recover_from_already_running(
stuck process died on its own. Now that turns into one native Yes/No box,
and Yes terminates the holder and takes the lock. No consent, no kill: the
default button is No and any failure to ask counts as No.
+
+ A holder that is only a few seconds old and has no window yet is not
+ stuck — it is still booting (the Restart helper used to spawn extras that
+ landed here and offered to kill the copy that was about to appear). Wait
+ out the remaining boot grace and try to focus again before asking.
"""
from loguru import logger
@@ -1035,6 +1133,9 @@ def _recover_from_already_running(
read_meta = read_meta or _desktop_app._read_meta
terminate = terminate or _desktop_app._terminate_pid
acquire = acquire or _desktop_app.acquire_single_instance_lock
+ process_age = process_age or _process_age_seconds
+ sleep = sleep or time.sleep
+ now = now or time.monotonic
if ask is None:
from jarvis.ui.native_dialog import ask_yes_no
@@ -1056,9 +1157,43 @@ def _recover_from_already_running(
meta = None
with contextlib.suppress(Exception):
meta = read_meta()
+ discover = discover_pid or _discover_holder_pid
pid = None
with contextlib.suppress(Exception):
- pid = int(meta["pid"]) if meta and meta.get("pid") is not None else None
+ pid = discover(error, meta)
+ if pid is not None and pid != os.getpid() and booting_grace > 0:
+ age = None
+ with contextlib.suppress(Exception):
+ age = process_age(pid)
+ if isinstance(age, int | float) and 0 <= float(age) < booting_grace:
+ remaining = booting_grace - float(age)
+ deadline = now() + remaining
+ logger.info(
+ "launcher: holder pid={} is only {:.1f}s old with no window yet — "
+ "waiting up to {:.1f}s for it to finish booting",
+ pid,
+ age,
+ remaining,
+ )
+ while now() < deadline:
+ sleep(0.5)
+ try:
+ if focus():
+ logger.info(
+ "launcher: booting holder pid={} grew a window — focusing it",
+ pid,
+ )
+ return None
+ except Exception as exc: # noqa: BLE001
+ logger.warning("launcher: focusing the booting instance failed: {}", exc)
+ break
+ try:
+ focused = bool(focus())
+ except Exception: # noqa: BLE001
+ focused = False
+ if focused:
+ return None
+ logger.info("launcher: booting holder pid={} never grew a window", pid)
if pid is None or pid == os.getpid():
_report_startup_failure(
f"{APP_DISPLAY_NAME} reports that it is already running, but no window "
diff --git a/tests/contract/test_single_instance.py b/tests/contract/test_single_instance.py
index abee7f9e1c..535badf9f3 100644
--- a/tests/contract/test_single_instance.py
+++ b/tests/contract/test_single_instance.py
@@ -4,6 +4,7 @@ Uses isolated temp paths so parallel test runs don't block each other —
the prod paths live under `DATA_DIR` and are reserved for real Jarvis
instances.
"""
+
from __future__ import annotations
import json
@@ -21,9 +22,7 @@ def test_first_claim_succeeds(tmp_path) -> None:
lock_file = tmp_path / "jarvis.lock"
meta_file = tmp_path / ".jarvis-running"
- lock = acquire_single_instance_lock(
- timeout=0.0, lock_path=lock_file, meta_path=meta_file
- )
+ lock = acquire_single_instance_lock(timeout=0.0, lock_path=lock_file, meta_path=meta_file)
try:
assert lock.is_locked
finally:
@@ -34,9 +33,7 @@ def test_second_claim_raises_when_first_alive(tmp_path) -> None:
lock_file = tmp_path / "jarvis.lock"
meta_file = tmp_path / ".jarvis-running"
- first = acquire_single_instance_lock(
- timeout=0.0, lock_path=lock_file, meta_path=meta_file
- )
+ first = acquire_single_instance_lock(timeout=0.0, lock_path=lock_file, meta_path=meta_file)
# Write the meta file with our PID (our process is guaranteed to be alive)
meta_file.write_text(
json.dumps({"pid": os.getpid(), "port": 47821, "started_at": 0}),
@@ -44,9 +41,7 @@ def test_second_claim_raises_when_first_alive(tmp_path) -> None:
)
try:
with pytest.raises(SingleInstanceError):
- acquire_single_instance_lock(
- timeout=0.0, lock_path=lock_file, meta_path=meta_file
- )
+ acquire_single_instance_lock(timeout=0.0, lock_path=lock_file, meta_path=meta_file)
finally:
first.release()
@@ -68,9 +63,7 @@ def test_live_but_portless_holder_is_evicted(tmp_path, monkeypatch) -> None:
encoding="utf-8",
)
# Pretend the zombie pid is alive (it is — that is the whole trap).
- monkeypatch.setattr(
- "jarvis.ui.desktop_app._pid_alive", lambda pid: pid == 424242
- )
+ monkeypatch.setattr("jarvis.ui.desktop_app._pid_alive", lambda pid: pid == 424242)
killed: dict[str, int] = {}
@@ -99,9 +92,7 @@ def test_live_holder_with_responsive_port_is_respected(tmp_path) -> None:
lock_file = tmp_path / "jarvis.lock"
meta_file = tmp_path / ".jarvis-running"
- first = acquire_single_instance_lock(
- timeout=0.0, lock_path=lock_file, meta_path=meta_file
- )
+ first = acquire_single_instance_lock(timeout=0.0, lock_path=lock_file, meta_path=meta_file)
meta_file.write_text(
json.dumps({"pid": os.getpid(), "port": 47821, "started_at": 0}),
encoding="utf-8",
@@ -129,9 +120,7 @@ def test_live_self_pid_holder_is_never_terminated(tmp_path) -> None:
lock_file = tmp_path / "jarvis.lock"
meta_file = tmp_path / ".jarvis-running"
- first = acquire_single_instance_lock(
- timeout=0.0, lock_path=lock_file, meta_path=meta_file
- )
+ first = acquire_single_instance_lock(timeout=0.0, lock_path=lock_file, meta_path=meta_file)
meta_file.write_text(
json.dumps({"pid": os.getpid(), "port": 47821, "started_at": 0}),
encoding="utf-8",
@@ -153,6 +142,38 @@ def test_live_self_pid_holder_is_never_terminated(tmp_path) -> None:
first.release()
+def test_missing_sidecar_names_the_listener_instead_of_waiting(tmp_path, monkeypatch) -> None:
+ """A headless boot holds the lock and never writes ``.jarvis-running``.
+
+ The desktop launch must name that process immediately — not wait 5 s and
+ report "not responding" with no pid to evict.
+ """
+ lock_file = tmp_path / "jarvis.lock"
+ meta_file = tmp_path / ".jarvis-running"
+
+ first = acquire_single_instance_lock(timeout=0.0, lock_path=lock_file, meta_path=meta_file)
+ monkeypatch.setattr(
+ "jarvis.ui.desktop_app._pid_alive",
+ lambda pid: pid == 99 or pid == os.getpid(),
+ )
+
+ def must_not_terminate(pid: int) -> bool: # pragma: no cover - must never run
+ raise AssertionError(f"a healthy listener must not be evicted, got pid={pid}")
+
+ try:
+ with pytest.raises(SingleInstanceError, match=r"pid=99"):
+ acquire_single_instance_lock(
+ timeout=0.0,
+ lock_path=lock_file,
+ meta_path=meta_file,
+ health_probe=lambda port: True,
+ listen_pid=lambda port: 99,
+ terminate=must_not_terminate,
+ )
+ finally:
+ first.release()
+
+
def test_stale_lock_is_reclaimed(tmp_path) -> None:
"""If the PID in the meta file is dead, a new process may take over."""
lock_file = tmp_path / "jarvis.lock"
@@ -164,9 +185,7 @@ def test_stale_lock_is_reclaimed(tmp_path) -> None:
stale = FileLock(str(lock_file))
stale.acquire(timeout=0.0)
- meta_file.write_text(
- json.dumps({"pid": 0, "port": 47821, "started_at": 0}), encoding="utf-8"
- )
+ meta_file.write_text(json.dumps({"pid": 0, "port": 47821, "started_at": 0}), encoding="utf-8")
# Release the lock again, so the stale detection can kick in.
# (The prod case would be: a dead holder held the lock and the kernel
@@ -174,9 +193,7 @@ def test_stale_lock_is_reclaimed(tmp_path) -> None:
stale.release()
# A new claim must go through (PID 0 is never a real user process).
- fresh = acquire_single_instance_lock(
- timeout=0.0, lock_path=lock_file, meta_path=meta_file
- )
+ fresh = acquire_single_instance_lock(timeout=0.0, lock_path=lock_file, meta_path=meta_file)
try:
assert fresh.is_locked
finally:
diff --git a/tests/unit/ui/test_focus_existing_instance.py b/tests/unit/ui/test_focus_existing_instance.py
new file mode 100644
index 0000000000..60527bfcbe
--- /dev/null
+++ b/tests/unit/ui/test_focus_existing_instance.py
@@ -0,0 +1,60 @@
+"""The launcher's focus ping must authenticate so CSRF does not reject it.
+
+Live 2026-08-25: a headless instance held port 47821, the desktop launch POSTed
+``/api/window/focus`` with no Origin and no Bearer, SurfaceSecurity answered
+403 ``Untrusted Origin header.``, and the start reported "already running"
+with no window.
+"""
+
+from __future__ import annotations
+
+
+def test_focus_headers_send_the_control_key_when_one_exists(monkeypatch):
+ from jarvis.ui import desktop_app
+
+ monkeypatch.setattr("jarvis.core.control_key.get_control_key", lambda: "jctl_test_key")
+ headers = desktop_app._focus_request_headers(47821)
+ assert headers["Authorization"] == "Bearer jctl_test_key"
+ assert "Origin" not in headers
+
+
+def test_focus_headers_fall_back_to_loopback_origin_without_a_key(monkeypatch):
+ from jarvis.ui import desktop_app
+
+ monkeypatch.setattr("jarvis.core.control_key.get_control_key", lambda: None)
+ headers = desktop_app._focus_request_headers(47821)
+ assert headers["Origin"] == "http://127.0.0.1:47821"
+ assert "Authorization" not in headers
+
+
+def test_focus_existing_instance_sends_those_headers(monkeypatch):
+ from types import ModuleType
+
+ from jarvis.ui import desktop_app
+
+ seen: list[dict] = []
+
+ class _Resp:
+ status_code = 200
+
+ def _post(url, headers=None, timeout=1.0): # noqa: ARG001
+ seen.append({"url": url, "headers": dict(headers or {})})
+ return _Resp()
+
+ monkeypatch.setattr(desktop_app, "_read_meta", lambda: {"pid": 1, "port": 47821})
+ monkeypatch.setattr(
+ desktop_app,
+ "_focus_request_headers",
+ lambda port: {"Authorization": "Bearer x"},
+ )
+ fake = ModuleType("httpx")
+ fake.post = _post # type: ignore[attr-defined]
+ monkeypatch.setitem(__import__("sys").modules, "httpx", fake)
+
+ assert desktop_app._focus_existing_instance() is True
+ assert seen == [
+ {
+ "url": "http://127.0.0.1:47821/api/window/focus",
+ "headers": {"Authorization": "Bearer x"},
+ }
+ ]
diff --git a/tests/unit/ui/test_launcher_boot_trace.py b/tests/unit/ui/test_launcher_boot_trace.py
index 56770d7c4b..a752807f7d 100644
--- a/tests/unit/ui/test_launcher_boot_trace.py
+++ b/tests/unit/ui/test_launcher_boot_trace.py
@@ -68,6 +68,12 @@ class _Calls:
return _Lock()
+def _meta_pid(_error, meta):
+ if meta and meta.get("pid") is not None:
+ return int(meta["pid"])
+ return None
+
+
def _recover(calls: _Calls):
return launcher._recover_from_already_running(
RuntimeError("Jarvis is already running (pid=4242)."),
@@ -76,6 +82,8 @@ def _recover(calls: _Calls):
ask=calls.ask,
terminate=calls.terminate,
acquire=calls.acquire,
+ process_age=lambda _pid: None, # a long-lived stuck holder, not a boot
+ discover_pid=_meta_pid,
)
@@ -86,6 +94,59 @@ def test_a_healthy_holder_is_focused_and_never_asked_about(monkeypatch):
assert calls.terminated == []
+def test_a_young_holder_is_waited_for_not_killed():
+ """A restart sibling that lands here while the real copy is still booting
+ must not offer to kill it. Wait until a window appears, then focus it."""
+
+ class _Booting(_Calls):
+ def __init__(self):
+ super().__init__(focused=False, meta={"pid": 4242}, consent=True)
+ self.focus_n = 0
+
+ def focus(self):
+ self.focus_n += 1
+ return self.focus_n >= 3
+
+ calls = _Booting()
+ clock = {"t": 0.0}
+ result = launcher._recover_from_already_running(
+ RuntimeError("Jarvis is already running (pid=4242)."),
+ focus=calls.focus,
+ read_meta=calls.read_meta,
+ ask=calls.ask,
+ terminate=calls.terminate,
+ acquire=calls.acquire,
+ process_age=lambda _pid: 2.0,
+ sleep=lambda s: clock.__setitem__("t", clock["t"] + s),
+ now=lambda: clock["t"],
+ booting_grace=5.0,
+ )
+ assert result is None
+ assert calls.asked == []
+ assert calls.terminated == []
+ assert calls.focus_n >= 3
+
+
+def test_a_young_holder_that_never_grows_a_window_is_still_asked():
+ calls = _Calls(focused=False, meta={"pid": 4242, "port": 47821}, consent=False)
+ clock = {"t": 0.0}
+ result = launcher._recover_from_already_running(
+ RuntimeError("Jarvis is already running (pid=4242)."),
+ focus=calls.focus,
+ read_meta=calls.read_meta,
+ ask=calls.ask,
+ terminate=calls.terminate,
+ acquire=calls.acquire,
+ process_age=lambda _pid: 1.0,
+ sleep=lambda s: clock.__setitem__("t", clock["t"] + s),
+ now=lambda: clock["t"],
+ booting_grace=2.0,
+ )
+ assert result is None
+ assert calls.asked
+ assert calls.terminated == []
+
+
def test_a_holder_without_a_window_is_evicted_only_on_yes(monkeypatch):
calls = _Calls(focused=False, meta={"pid": 4242, "port": 47821}, consent=True)
lock = _recover(calls)
@@ -112,6 +173,43 @@ def test_an_unknown_holder_is_reported_not_killed(monkeypatch):
assert seen and "already running" in seen[0]
+def test_a_holder_named_only_in_the_lock_error_can_still_be_evicted():
+ """Headless never wrote the sidecar, but the lock error still names the pid."""
+ calls = _Calls(focused=False, meta=None, consent=True)
+ lock = launcher._recover_from_already_running(
+ RuntimeError("Jarvis is already running (pid=4242)."),
+ focus=calls.focus,
+ read_meta=calls.read_meta,
+ ask=calls.ask,
+ terminate=calls.terminate,
+ acquire=calls.acquire,
+ process_age=lambda _pid: None,
+ discover_pid=launcher._discover_holder_pid,
+ )
+ assert isinstance(lock, _Lock)
+ assert calls.terminated == [4242]
+
+
+def test_a_holder_found_on_the_admin_port_can_still_be_evicted(monkeypatch):
+ """No sidecar, no pid in the error — the process bound to 47821 is the holder."""
+ monkeypatch.setattr(launcher, "_holder_pid_from_error", lambda _error: None)
+ monkeypatch.setattr("jarvis.ui.desktop_app._pid_listening_on_port", lambda _port: 4242)
+ monkeypatch.setattr("jarvis.ui.desktop_app._fallback_admin_port", lambda: 47821)
+ calls = _Calls(focused=False, meta=None, consent=True)
+ lock = launcher._recover_from_already_running(
+ RuntimeError("Jarvis lock is held but the holder is not responding."),
+ focus=calls.focus,
+ read_meta=calls.read_meta,
+ ask=calls.ask,
+ terminate=calls.terminate,
+ acquire=calls.acquire,
+ process_age=lambda _pid: None,
+ discover_pid=launcher._discover_holder_pid,
+ )
+ assert isinstance(lock, _Lock)
+ assert calls.terminated == [4242]
+
+
def test_a_kill_that_did_not_take_is_reported(monkeypatch):
seen: list[str] = []
monkeypatch.setattr(launcher, "_report_startup_failure", seen.append)
diff --git a/tests/unit/ui/web/test_launcher_primary_instance.py b/tests/unit/ui/web/test_launcher_primary_instance.py
index 5d129f091a..e294fd3bc4 100644
--- a/tests/unit/ui/web/test_launcher_primary_instance.py
+++ b/tests/unit/ui/web/test_launcher_primary_instance.py
@@ -15,8 +15,11 @@ by the desktop app or another run) marks itself NON-primary and must not
sweep — but still boots (headless is meant to coexist with a primary for
tests / parallel dev / smoke probes).
"""
+
from __future__ import annotations
+import json
+import os
from pathlib import Path
from types import SimpleNamespace
@@ -29,18 +32,14 @@ from jarvis.ui.web.launcher import (
)
-def test_sole_headless_instance_is_primary(
- tmp_path: Path, monkeypatch: pytest.MonkeyPatch
-) -> None:
+def test_sole_headless_instance_is_primary(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
"""A headless run that is the ONLY instance holds the lock and IS primary,
so it still recovers genuinely orphaned missions (the VPS case)."""
monkeypatch.delenv("JARVIS_PRIMARY_INSTANCE", raising=False)
lock_path = tmp_path / "jarvis.lock"
meta_path = tmp_path / "jarvis.lock.meta"
- lock = _acquire_primary_lock_for_headless(
- lock_path=lock_path, meta_path=meta_path
- )
+ lock = _acquire_primary_lock_for_headless(lock_path=lock_path, meta_path=meta_path)
try:
assert lock is not None, "sole instance must acquire the lock"
import os
@@ -63,13 +62,9 @@ def test_secondary_headless_instance_is_not_primary(
# Simulate the desktop instance already holding the lock in THIS (live)
# process — the meta PID is our own, so stale-detection sees it alive.
- held = acquire_single_instance_lock(
- lock_path=lock_path, meta_path=meta_path
- )
+ held = acquire_single_instance_lock(lock_path=lock_path, meta_path=meta_path)
try:
- lock = _acquire_primary_lock_for_headless(
- lock_path=lock_path, meta_path=meta_path
- )
+ lock = _acquire_primary_lock_for_headless(lock_path=lock_path, meta_path=meta_path)
assert lock is None, "secondary instance must not acquire the lock"
import os
@@ -101,7 +96,29 @@ def test_no_lock_headless_instance_is_secondary_and_does_not_hold_lock(
assert os.environ["JARVIS_PRIMARY_INSTANCE"] == "0"
- desktop_lock = acquire_single_instance_lock(
- lock_path=lock_path, meta_path=meta_path
- )
+ desktop_lock = acquire_single_instance_lock(lock_path=lock_path, meta_path=meta_path)
desktop_lock.release()
+
+
+def test_sole_headless_instance_writes_the_sidecar(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A later desktop launch must be able to name this process and ask to stop it."""
+ monkeypatch.delenv("JARVIS_PRIMARY_INSTANCE", raising=False)
+ lock_path = tmp_path / "jarvis.lock"
+ meta_path = tmp_path / ".jarvis-running"
+
+ lock = _claim_headless_primary_lock(
+ SimpleNamespace(no_lock=False),
+ lock_path=lock_path,
+ meta_path=meta_path,
+ port=47821,
+ )
+ try:
+ assert lock is not None
+ data = json.loads(meta_path.read_text(encoding="utf-8"))
+ assert data["pid"] == os.getpid()
+ assert data["port"] == 47821
+ finally:
+ if lock is not None:
+ lock.release()