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(background): close the reopen races and let running routines finish

rubenluetke10-beep5d0a2e8173f6
diff --git a/docs/background-service.md b/docs/background-service.md
index cd0da1829b..af135bda6d 100644
--- a/docs/background-service.md
+++ b/docs/background-service.md
@@ -12,6 +12,8 @@ Routines and chat channels keep running after the desktop app is closed.
- Opening the app again takes over from the service in a couple of seconds.
Nothing has to be stopped by hand.
- With nothing to keep, closing the app stops everything, as before.
+- **Quit and stop background agents** in the app's tray menu quits without
+ the hand-off.
- **Settings → App settings → Keep agents running after closing** turns the
hand-off off. The same card shows what a quit would keep right now, and
offers **At login, start only the background agents** (needs "Launch app at
@@ -43,8 +45,11 @@ single-instance lock (`data/jarvis.lock`):
3. **Hand-back on launch** (`launcher._take_over_from_background_service` →
`take_over_from_service`). A desktop launch that finds the service drops
`handover{suffix}.request`; the service polls that file every 0.5 s, shuts
- down and releases the lock; the desktop takes it and boots normally. A
- service that does not let go within 45 s is stopped. A file carries the
+ lets routine runs already in flight finish (up to 30 s), shuts down and
+ releases the lock; the desktop takes it and boots normally. A service that
+ does not let go within 45 s is stopped. The service writes its marker the
+ moment it holds the lock, and removes it and the instance sidecar before
+ releasing the lock, so a desktop reopened mid-boot always finds it. A file carries the
request (not HTTP) because it works while the service is still booting
and needs no credentials.
4. **Self-exit.** The service checks every 5 minutes that it still has work
@@ -59,7 +64,8 @@ Log: `<data dir>/jarvis_background.log`, next to `jarvis_desktop.log`.
- Spoken routines (`speak` actions) fail in the service: there is no voice
without the app. Agent routines and chat channels are unaffected.
- A turn that is running in the desktop at the moment of quitting is
- interrupted, as before; the service starts fresh. The Agentic IDE's coding
+ interrupted, as before; the service starts fresh. A routine run in the
+ service that needs longer than 30 s after the app reopens is cut off. The Agentic IDE's coding
agents are unaffected — they live in the PTY host.
- macOS draws no menu-bar icon for the service (status items need the main
thread, which the service's event loop owns). Open the app to stop it, or
@@ -75,4 +81,6 @@ Log: `<data dir>/jarvis_background.log`, next to `jarvis_desktop.log`.
then call `launcher._take_over_from_background_service()` and confirm the
lock is returned, the service exits with code 0 and the marker is gone.
Measured 2026-10-01 on Windows 11: hand-back 2.4 s, process gone at 2.4 s
- (in-process spawn) and 11.7 s (detached spawn, 5 s exit-hook flush).
+ (in-process spawn) and 11.7 s (detached spawn, 5 s exit-hook flush). Same
+ round trip in Docker `python:3.11-slim` (no display, no tray): hand-back
+ 3.1 s, exit code 0.
diff --git a/docs/os-parity.md b/docs/os-parity.md
index 0e64a7444e..890c9e04ca 100644
--- a/docs/os-parity.md
+++ b/docs/os-parity.md
@@ -89,8 +89,8 @@ bare `python:3.11-slim`.
login entry on all three (Task Scheduler / startup shortcut, LaunchAgent via
LaunchServices `--args`, XDG `.desktop`).
- **Verified:** Windows 11 live (detached spawn, parent wait, routine fired,
- hand-back 2.4 s). macOS and Linux: same code paths, unit-tested, not run live
- from this machine.
+ hand-back 2.4 s). Linux: headless `python:3.11-slim` in Docker (boot, no
+ tray, hand-back 3.1 s). macOS: same code paths, unit-tested, not run live.
## Persistent Agentic IDE terminals (2026-09-28, T3)
diff --git a/jarvis/__main__.py b/jarvis/__main__.py
index f8a38c863d..13b38b201b 100644
--- a/jarvis/__main__.py
+++ b/jarvis/__main__.py
@@ -484,7 +484,7 @@ async def _run_tray_app(debug: bool = False) -> int:
cmd: TrayCommand = await asyncio.wait_for(command_queue.get(), timeout=0.5)
except TimeoutError:
continue
- if cmd.action == "quit":
+ if cmd.action in ("quit", "quit_all"):
stop_event.set()
return
if cmd.action == "pause":
diff --git a/jarvis/core/background_service.py b/jarvis/core/background_service.py
index 662cb63ef2..d3bfc3fb10 100644
--- a/jarvis/core/background_service.py
+++ b/jarvis/core/background_service.py
@@ -48,6 +48,8 @@ IDLE_CHECK_S = 300.0
IDLE_STRIKES = 2
#: How long the desktop waits for the service to hand back before stopping it.
TAKEOVER_WAIT_S = 45.0
+#: How long a handing-back service lets routine runs in flight finish.
+HANDOVER_DRAIN_S = 30.0
# ---------------------------------------------------------------------------
diff --git a/jarvis/ui/desktop_app.py b/jarvis/ui/desktop_app.py
index c918fe1448..7b8441b577 100644
--- a/jarvis/ui/desktop_app.py
+++ b/jarvis/ui/desktop_app.py
@@ -6105,7 +6105,10 @@ class DesktopApp:
# backend bus (the same bus the CU context's KillSwitch is
# bound to) from this non-async pystray bridge thread.
self._publish_kill_requested_threadsafe()
- elif action == "quit":
+ elif action in ("quit", "quit_all"):
+ if action == "quit_all":
+ # Nothing keeps running: no background agent service.
+ self._skip_background_handoff = True
self._user_requested_quit = True
self._arm_force_exit(after_s=20.0)
# Detached windows too: webview.start() returns only once
diff --git a/jarvis/ui/shell/shell.py b/jarvis/ui/shell/shell.py
index 3c1fcf0d2f..dfea89022a 100644
--- a/jarvis/ui/shell/shell.py
+++ b/jarvis/ui/shell/shell.py
@@ -155,6 +155,6 @@ class JarvisShell:
continue
if cmd.action == "open_ui":
self.request_show()
- elif cmd.action == "quit":
+ elif cmd.action in ("quit", "quit_all"):
self.quit()
break
diff --git a/jarvis/ui/tray.py b/jarvis/ui/tray.py
index 11c5d1c19a..6a1bb2930e 100644
--- a/jarvis/ui/tray.py
+++ b/jarvis/ui/tray.py
@@ -85,7 +85,7 @@ def _make_icon(state: JarvisState, size: int = 64) -> Any:
@dataclass(slots=True)
class TrayCommand:
"""Action sent from the tray → Jarvis core."""
- action: str # "quit" | "pause" | "resume" | "reload_config" | "open_settings"
+ action: str # "quit" | "quit_all" | "pause" | "resume" | "reload_config" | "open_settings"
payload: dict[str, Any] | None = None
@@ -192,7 +192,7 @@ class JarvisTray:
cmd = TrayCommand(action=action)
self._command_queue.put(cmd)
self._on_command(cmd)
- if action == "quit":
+ if action in ("quit", "quit_all"):
self.stop()
return _handler
@@ -218,6 +218,9 @@ class JarvisTray:
MenuItem("Emergency stop", _emit("kill")),
Menu.SEPARATOR,
MenuItem("Quit", _emit("quit")),
+ # Quit without handing routines and channels to the background
+ # service (jarvis/core/background_service.py).
+ MenuItem("Quit and stop background agents", _emit("quit_all")),
)
def _run(self) -> None:
@@ -413,7 +416,7 @@ class JarvisTray:
break
continue
asyncio.run_coroutine_threadsafe(aq.put(cmd), loop)
- if cmd.action == "quit":
+ if cmd.action in ("quit", "quit_all"):
break
threading.Thread(target=_forwarder, name="jarvis-tray-bridge", daemon=True).start()
diff --git a/jarvis/ui/web/launcher.py b/jarvis/ui/web/launcher.py
index bc03350fd5..fabd163c0a 100644
--- a/jarvis/ui/web/launcher.py
+++ b/jarvis/ui/web/launcher.py
@@ -952,14 +952,9 @@ async def _run_headless(args) -> int:
# stale-detection in acquire_single_instance_lock reclaims it — so the
# leak is self-healing, not permanent.
if _headless_lock is not None:
- try:
- _headless_lock.release()
- except Exception as exc: # noqa: BLE001 — best-effort release on shutdown
- import logging as _logging
-
- _logging.getLogger(__name__).debug(
- "headless lock release failed on shutdown: %s", exc
- )
+ # Sidecar (and the service marker) go BEFORE the lock: the next
+ # holder may take the lock the moment it is free and write its own
+ # sidecar, which a late unlink here would then delete.
try:
from jarvis.ui.desktop_app import META_FILE_PATH
@@ -970,10 +965,18 @@ async def _run_headless(args) -> int:
_logging.getLogger(__name__).debug(
"headless sidecar cleanup failed on shutdown: %s", exc
)
- if _service_lock is not None:
- from jarvis.core.background_service import clear_marker
+ if _service_lock is not None:
+ from jarvis.core.background_service import clear_marker
- clear_marker()
+ clear_marker()
+ try:
+ _headless_lock.release()
+ except Exception as exc: # noqa: BLE001 — best-effort release on shutdown
+ import logging as _logging
+
+ _logging.getLogger(__name__).debug(
+ "headless lock release failed on shutdown: %s", exc
+ )
return 0
@@ -994,6 +997,9 @@ def _arm_service_exit_backstop(after_s: float) -> None:
threading.Thread(target=_force, name="background-exit-backstop", daemon=True).start()
+_SERVICE_EXIT_LOCK = threading.Lock()
+
+
def _exit_background_service(code: int) -> None:
"""End the service process now, after a bounded flush of the exit hooks.
@@ -1005,6 +1011,10 @@ def _exit_background_service(code: int) -> None:
"""
import atexit
+ if not _SERVICE_EXIT_LOCK.acquire(blocking=False):
+ # The other exit path (backstop or normal return) is already ending
+ # the process; a second flush would run the exit hooks twice.
+ return
flush = threading.Thread(
target=atexit._run_exitfuncs, # noqa: SLF001 — the only public-free way to drain them
name="background-exit-flush",
@@ -1054,6 +1064,12 @@ def _prepare_background_service(args):
logger.info("background: the app is already running ({}) — service not started", exc)
return None
os.environ["JARVIS_PRIMARY_INSTANCE"] = "1"
+ # Findable the instant it holds the lock: a desktop reopened during this
+ # boot must ask for a hand-back, never read the holder as a stuck app.
+ try:
+ bg.write_marker(0)
+ except OSError as exc:
+ logger.warning("background: service marker not written: {}", exc)
logger.info("background: agent service starting (pid={})", os.getpid())
return lock
@@ -1096,6 +1112,33 @@ def _start_background_service_duties(state, stop_event):
return task, tray
+async def _drain_running_routines(state, *, drain_s: float, poll_s: float) -> None:
+ """Let routine runs already in flight finish (bounded) before stopping.
+
+ Stopping cancels their token; a long agent run would otherwise be lost
+ just because the user opened the window. The desktop waits longer than
+ this budget before it stops the service itself.
+ """
+ from loguru import logger
+
+ from jarvis.core import background_service as bg
+
+ loop = asyncio.get_running_loop()
+ deadline = loop.time() + drain_s
+ running = bg.work_from_state(state).running
+ if running:
+ logger.info(
+ "background: {} routine run(s) still in flight — up to {:.0f}s to finish",
+ running,
+ drain_s,
+ )
+ while running and loop.time() < deadline:
+ await asyncio.sleep(poll_s)
+ running = bg.work_from_state(state).running
+ if running:
+ logger.warning("background: {} run(s) still going — they stop with the service", running)
+
+
async def _watch_background_service(
state,
stop_event,
@@ -1119,6 +1162,7 @@ async def _watch_background_service(
while not stop_event.is_set():
await asyncio.sleep(poll)
if bg.handover_requested():
+ await _drain_running_routines(state, drain_s=bg.HANDOVER_DRAIN_S, poll_s=poll)
logger.info("background: the desktop app is opening — handing the agents back")
stop_event.set()
return
diff --git a/tests/unit/core/test_background_service.py b/tests/unit/core/test_background_service.py
index 2e650cd8c3..341ce31e38 100644
--- a/tests/unit/core/test_background_service.py
+++ b/tests/unit/core/test_background_service.py
@@ -461,3 +461,60 @@ def test_service_age_constants_are_sane() -> None:
assert bg.HANDOVER_POLL_S < 1.0
assert bg.TAKEOVER_WAIT_S < bg.PARENT_EXIT_WAIT_S
assert bg.HANDOVER_MAX_AGE_S > bg.TAKEOVER_WAIT_S
+
+
+def test_service_is_findable_the_moment_it_holds_the_lock(monkeypatch) -> None:
+ from jarvis.ui import desktop_app, desktop_log
+ from jarvis.ui.web import launcher
+
+ monkeypatch.setattr(desktop_log, "_install_desktop_log_sink", lambda _path: None)
+ monkeypatch.setenv("JARVIS_VOICE", "1")
+ monkeypatch.setenv("JARVIS_PRIMARY_INSTANCE", "0")
+ monkeypatch.setattr(desktop_app, "acquire_single_instance_lock", lambda **_kw: "lock")
+ assert launcher._prepare_background_service(launcher._parse_args([bg.SERVICE_FLAG])) == "lock"
+ marker = bg.read_marker()
+ assert marker is not None and marker["pid"] == os.getpid()
+
+
+def test_hand_back_lets_running_routines_finish_first() -> None:
+ from jarvis.ui.web import launcher
+
+ class _Draining:
+ def __init__(self) -> None:
+ self.calls = 0
+
+ def pending_work(self) -> tuple[int, int]:
+ self.calls += 1
+ return (1, 1 if self.calls < 4 else 0)
+
+ scheduler = _Draining()
+ state = SimpleNamespace(task_scheduler=scheduler, channel_manager=_Channels())
+ asyncio.run(launcher._drain_running_routines(state, drain_s=5.0, poll_s=0.01))
+ assert scheduler.calls == 4
+
+
+def test_drain_is_bounded() -> None:
+ from jarvis.ui.web import launcher
+
+ state = _state(running=1)
+
+ async def scenario() -> None:
+ await asyncio.wait_for(
+ launcher._drain_running_routines(state, drain_s=0.05, poll_s=0.01), 1.0
+ )
+
+ asyncio.run(scenario())
+
+
+def test_tray_quit_all_skips_the_hand_off(monkeypatch) -> None:
+ pytest.importorskip("pystray")
+ from jarvis.ui.tray import JarvisTray, TrayCommand
+
+ seen: list[str] = []
+ tray = JarvisTray(on_command=lambda cmd: seen.append(cmd.action))
+ monkeypatch.setattr(tray, "stop", lambda: seen.append("stopped"))
+ menu = tray._build_menu()
+ item = next(i for i in menu.items if str(i.text) == "Quit and stop background agents")
+ item._action(None, item)
+ assert seen == ["quit_all", "stopped"]
+ assert isinstance(tray._command_queue.get_nowait(), TrayCommand)