Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

feat(background): keep routines and chat channels running after the app closes

rubenluetke10-beepb031b05182b2
diff --git a/docs/background-service.md b/docs/background-service.md
new file mode 100644
index 0000000000..cd0da1829b
--- /dev/null
+++ b/docs/background-service.md
@@ -0,0 +1,78 @@
+# Background agent service
+
+Routines and chat channels keep running after the desktop app is closed.
+
+## What the user sees
+
+- Closing the app (the window's X, or **Quit** in the tray) with something to
+ keep — an armed routine, or a running Telegram / Discord channel — starts a
+ small windowless service. A tray icon ("agents keep running in the
+ background") shows it is there, with **Open** and **Stop background
+ agents**.
+- 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.
+- **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
+ login"), which starts the service instead of the window after a reboot.
+
+## How it works
+
+The service is the existing headless backend
+(`python -m jarvis.ui.web.launcher --background-service`, which implies
+`--headless`) with no window, no microphone, no wake word and no overlay
+(`JARVIS_VOICE=0`). It runs the same task scheduler, channel stack, agent
+society runtime and Agentic IDE re-attach as a headless install.
+
+Exactly one of desktop app and service runs at a time. Both go through the
+single-instance lock (`data/jarvis.lock`):
+
+1. **Hand-off on quit** (`DesktopApp._hand_off_to_background_service` →
+ `jarvis.core.background_service.hand_off_on_quit`). On a real quit, if
+ `[background] keep_agents_running` is on and `work_from_state` finds an
+ armed routine, a run in flight or a started channel, the desktop spawns the
+ service detached (`--after-pid <desktop pid>`). A restart, an update, a
+ declined Terms gate or a failed backend skip it. Only the default instance
+ hands off; a dev instance stops with its window.
+2. **Service boot** (`launcher._prepare_background_service`). It waits for the
+ desktop pid to exit, steps aside when a desktop launch is already waiting,
+ and takes the lock without evicting anyone, BEFORE it binds the port.
+ It writes `user_data_dir()/background/service{suffix}.json` and the usual
+ instance sidecar.
+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
+ 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
+ and exits after two empty checks. Its teardown is capped at 30 s, then the
+ process ends hard — an invisible process holding the lock is the one thing
+ it must never become.
+
+Log: `<data dir>/jarvis_background.log`, next to `jarvis_desktop.log`.
+
+## Limits
+
+- 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
+ 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
+ turn the setting off.
+
+## Verifying
+
+- Unit: `tests/unit/core/test_background_service.py`.
+- Live round trip on an isolated dev instance (`JARVIS_DATA_DIR` and
+ `LOCALAPPDATA` pointed at a temp folder, `--port` set): start the service
+ with `--after-pid` of a short-lived process, confirm it boots only after
+ that process exits, fire an `after_delay` task through `POST /api/tasks`,
+ 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).
diff --git a/docs/os-parity.md b/docs/os-parity.md
index 0d121175fa..0e64a7444e 100644
--- a/docs/os-parity.md
+++ b/docs/os-parity.md
@@ -69,6 +69,29 @@ Server without winget. Covered by `tests/unit/computers/test_posix_remote.py`,
`tests/unit/society/test_remote_placement.py` against scripted SSH servers.
+## Background agent service (2026-10-01, T3)
+
+Quitting the desktop app with an armed routine or a running chat channel hands
+the app to a windowless service (`launcher --background-service`), which hands
+it back when the app opens again (`docs/background-service.md`). The service
+is the headless backend, so it boots wherever `--headless` boots, including a
+bare `python:3.11-slim`.
+
+- **Spawn:** Windows uses `DETACHED_PROCESS | CREATE_NO_WINDOW |
+ CREATE_BREAKAWAY_FROM_JOB` with `pythonw.exe`, and WMI
+ `Win32_Process.Create` when the app's job refuses breakaway (the PTY host's
+ route). macOS and Linux use `start_new_session`. A frozen build re-enters
+ its own executable with `--background-service` first.
+- **Tray:** Windows and Linux desktops with a notification area show a pystray
+ icon (Open / Stop background agents). macOS shows none (status items need
+ the main thread) and logs one line; a host without a display logs one line.
+- **Login:** `[autostart] background_only` puts `--background-service` into the
+ 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.
+
## Persistent Agentic IDE terminals (2026-09-28, T3)
Coding-agent panes now live in a separate PTY host process
diff --git a/jarvis/__main__.py b/jarvis/__main__.py
index 00756b5acd..f8a38c863d 100644
--- a/jarvis/__main__.py
+++ b/jarvis/__main__.py
@@ -39,6 +39,14 @@ if len(sys.argv) >= 2 and sys.argv[1] == "--relauncher":
raise SystemExit(_relauncher_main(sys.argv[2:]))
+# The background agent service of a frozen build, same reason: no ``-m`` to
+# start ``jarvis.ui.web.launcher --background-service`` with
+# (see jarvis/core/background_service.py).
+if len(sys.argv) >= 2 and sys.argv[1] == "--background-service":
+ from jarvis.ui.web.launcher import main as _launcher_main
+
+ raise SystemExit(_launcher_main(sys.argv[1:]))
+
# Windows Terminal defaults to cp1252 — which breaks Unicode (box-drawing,
# emojis, ✓/✗). Force utf-8 before printing anything.
if sys.platform == "win32":
diff --git a/jarvis/autostart/command.py b/jarvis/autostart/command.py
index 64cec53657..dbcdb3e0ed 100644
--- a/jarvis/autostart/command.py
+++ b/jarvis/autostart/command.py
@@ -6,7 +6,11 @@ about *which* interpreter/path Jarvis should be relaunched with at login.
The launch target is the full desktop app (``-m jarvis.ui.web.launcher``, voice +
Orb enabled — NOT ``--headless``): that is what makes "Hey Jarvis" available
-after boot. The interpreter and working directory are computed at call time from
+after boot. With ``[autostart] background_only`` the entry starts only the
+windowless background agent service (``--background-service``) instead, so
+routines and chat channels run after login without opening the window.
+
+The interpreter and working directory are computed at call time from
the running package, never from a stored absolute string, so a moved/re-cloned
project never leaves a stale autostart entry (BUG-006 restore-trap class).
"""
@@ -77,11 +81,20 @@ def resolve_launch_spec(cfg: object | None = None) -> LaunchSpec:
actually running.
"""
minimized = False
+ background_only = False
autostart = getattr(cfg, "autostart", None) if cfg is not None else None
if autostart is not None:
minimized = bool(getattr(autostart, "start_minimized", False))
+ background_only = bool(getattr(autostart, "background_only", False))
+ # Imported lazily: the service module pulls in loguru and is not needed to
+ # build the plain desktop entry.
+ service_args: tuple[str, ...] = ()
+ if background_only:
+ from jarvis.core.background_service import SERVICE_FLAG
+
+ service_args = (SERVICE_FLAG,)
- args: tuple[str, ...] = ("-m", LAUNCHER_MODULE)
+ args: tuple[str, ...] = ("-m", LAUNCHER_MODULE, *service_args)
if sys.platform == "win32":
program = _detect_pythonw()
elif sys.platform == "darwin":
@@ -107,8 +120,9 @@ def resolve_launch_spec(cfg: object | None = None) -> LaunchSpec:
)
command = macos_launch_services_command(
bundle,
- background=minimized,
+ background=minimized or background_only,
wait_for_exit=True,
+ arguments=service_args,
)
program, *launch_args = command
args = tuple(launch_args)
@@ -119,8 +133,10 @@ def resolve_launch_spec(cfg: object | None = None) -> LaunchSpec:
exc,
)
launch_args = ["-W", "-a", str(bundle)]
- if minimized:
+ if minimized or background_only:
launch_args.insert(0, "-g")
+ if service_args:
+ launch_args += ["--args", *service_args]
args = tuple(launch_args)
else:
program = sys.executable
diff --git a/jarvis/core/background_service.py b/jarvis/core/background_service.py
new file mode 100644
index 0000000000..662cb63ef2
--- /dev/null
+++ b/jarvis/core/background_service.py
@@ -0,0 +1,453 @@
+"""Background agent service — routines and chat channels outlive the window.
+
+The desktop app owns everything while it is open. When the user quits it and
+there is work to keep (an armed routine, a running Telegram/Discord channel),
+it starts this service: the same backend as ``launcher --headless``, without a
+window, microphone, wake word or overlay. The service takes the single-instance
+lock and the admin port, so routines fire, channels answer, and the Agentic IDE
+re-attaches to its PTY host exactly as in a headless install.
+
+Opening the app again reverses the hand-off. The launcher finds the service as
+the lock holder, drops a handover request file, and the service shuts down
+cleanly and releases the lock; the desktop then boots normally. A file (not
+an HTTP call) carries the request because it also works while the service is
+still booting, needs no credentials, and costs one ``stat`` per half second.
+
+Exactly one of the two ever runs: both go through the same lock. Lifecycle
+states live under ``user_data_dir()/background`` with the instance suffix, so a
+dev instance never touches the default instance's service.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import sys
+import time
+from collections.abc import Callable
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Any
+
+from loguru import logger
+
+#: argv flag that turns ``launcher --headless`` into the background service.
+SERVICE_FLAG = "--background-service"
+#: argv flag: wait for this pid (the quitting desktop app) before booting.
+AFTER_PID_FLAG = "--after-pid"
+
+#: How long a booting service waits for the quitting desktop to exit.
+PARENT_EXIT_WAIT_S = 90.0
+#: A handover request older than this is a leftover from a crashed launch.
+HANDOVER_MAX_AGE_S = 120.0
+#: How often the service checks for a handover request.
+HANDOVER_POLL_S = 0.5
+#: How often the service re-checks that it still has work to keep.
+IDLE_CHECK_S = 300.0
+#: Consecutive empty checks before the service exits on its own.
+IDLE_STRIKES = 2
+#: How long the desktop waits for the service to hand back before stopping it.
+TAKEOVER_WAIT_S = 45.0
+
+
+# ---------------------------------------------------------------------------
+# Paths
+# ---------------------------------------------------------------------------
+
+
+def _state_dir() -> Path:
+ from jarvis.core.paths import user_data_dir
+
+ return user_data_dir() / "background"
+
+
+def _suffix() -> str:
+ from jarvis.core.instance import current_instance
+
+ return current_instance().state_file_suffix
+
+
+def marker_path() -> Path:
+ """``{pid, port, started_at}`` of the running service (absent = none)."""
+ return _state_dir() / f"service{_suffix()}.json"
+
+
+def handover_path() -> Path:
+ """Exists while a desktop launch is waiting for the service to let go."""
+ return _state_dir() / f"handover{_suffix()}.request"
+
+
+def log_path() -> Path:
+ """The service's own log, next to ``jarvis_desktop.log``."""
+ from jarvis.ui.desktop_log import desktop_log_path
+
+ return desktop_log_path().with_name("jarvis_background.log")
+
+
+# ---------------------------------------------------------------------------
+# What is worth keeping
+# ---------------------------------------------------------------------------
+
+
+@dataclass(frozen=True)
+class BackgroundWork:
+ """The work a closed window would otherwise stop."""
+
+ routines: int = 0
+ running: int = 0
+ channels: tuple[str, ...] = ()
+
+ def __bool__(self) -> bool:
+ return bool(self.routines or self.running or self.channels)
+
+ def describe(self) -> str:
+ parts: list[str] = []
+ if self.routines:
+ parts.append(f"{self.routines} armed routine(s)")
+ if self.running:
+ parts.append(f"{self.running} run(s) in flight")
+ if self.channels:
+ parts.append("channels: " + ", ".join(self.channels))
+ return "; ".join(parts) or "nothing"
+
+
+def work_from_state(state: Any) -> BackgroundWork:
+ """Read the live work off ``app.state``. Never raises, never awaits."""
+ routines = running = 0
+ scheduler = getattr(state, "task_scheduler", None)
+ pending = getattr(scheduler, "pending_work", None)
+ if callable(pending):
+ try:
+ routines, running = pending()
+ except Exception: # noqa: BLE001 — a broken scheduler means no routines to keep
+ logger.opt(exception=True).debug("background: scheduler state unreadable")
+ channels: tuple[str, ...] = ()
+ manager = getattr(state, "channel_manager", None)
+ started = getattr(manager, "started", None)
+ if callable(started):
+ try:
+ channels = tuple(str(name) for name in started())
+ except Exception: # noqa: BLE001 — same: unreadable means none to keep
+ logger.opt(exception=True).debug("background: channel state unreadable")
+ return BackgroundWork(routines=int(routines), running=int(running), channels=channels)
+
+
+def keep_running_enabled(cfg: Any) -> bool:
+ """``[background] keep_agents_running`` (default on)."""
+ section = getattr(cfg, "background", None)
+ return bool(getattr(section, "keep_agents_running", True))
+
+
+# ---------------------------------------------------------------------------
+# Marker + handover request
+# ---------------------------------------------------------------------------
+
+
+def _write_json(path: Path, payload: dict[str, Any]) -> None:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ tmp = path.with_name(f"{path.name}.{os.getpid()}.tmp")
+ tmp.write_text(json.dumps(payload), encoding="utf-8")
+ os.replace(tmp, path)
+
+
+def write_marker(port: int) -> None:
+ _write_json(
+ marker_path(),
+ {"pid": os.getpid(), "port": int(port), "started_at": time.time()},
+ )
+
+
+def clear_marker() -> None:
+ """Remove the marker if it is still ours."""
+ path = marker_path()
+ data = read_marker()
+ if data is not None and int(data.get("pid") or 0) not in (0, os.getpid()):
+ return
+ try:
+ path.unlink(missing_ok=True)
+ except OSError as exc:
+ logger.debug("background: marker not removed: {}", exc)
+
+
+def read_marker() -> dict[str, Any] | None:
+ try:
+ data = json.loads(marker_path().read_text(encoding="utf-8"))
+ except (OSError, ValueError): # no readable marker means no service
+ return None
+ return data if isinstance(data, dict) else None
+
+
+def _is_service_process(pid: int) -> bool:
+ """The pid exists AND is a background service (pids are reused)."""
+ try:
+ import psutil
+
+ cmdline = psutil.Process(int(pid)).cmdline()
+ except Exception: # noqa: BLE001 — gone or unreadable: not our service
+ return False
+ return SERVICE_FLAG in cmdline
+
+
+def service_pid(*, is_service: Callable[[int], bool] = _is_service_process) -> int | None:
+ """Pid of the running background service of this instance, or ``None``."""
+ data = read_marker()
+ if not data:
+ return None
+ try:
+ pid = int(data.get("pid") or 0)
+ except (TypeError, ValueError): # a garbled marker names no service
+ return None
+ if pid <= 0 or pid == os.getpid() or not is_service(pid):
+ return None
+ return pid
+
+
+def request_handover() -> None:
+ _write_json(handover_path(), {"pid": os.getpid(), "requested_at": time.time()})
+
+
+def clear_handover_request() -> None:
+ try:
+ handover_path().unlink(missing_ok=True)
+ except OSError as exc:
+ logger.debug("background: handover request not removed: {}", exc)
+
+
+def handover_requested(*, now: Callable[[], float] = time.time) -> bool:
+ """A desktop launch is waiting. A request older than two minutes is a
+ leftover from a launch that crashed and is ignored."""
+ try:
+ age = now() - handover_path().stat().st_mtime
+ except OSError: # no request file
+ return False
+ return age <= HANDOVER_MAX_AGE_S
+
+
+# ---------------------------------------------------------------------------
+# Starting the service
+# ---------------------------------------------------------------------------
+
+
+def _source_root() -> str:
+ import jarvis
+
+ return str(Path(jarvis.__file__).resolve().parent.parent)
+
+
+def _windowless_python(executable: str) -> str:
+ """``pythonw.exe`` beside a ``python.exe`` on Windows; unchanged elsewhere."""
+ if sys.platform != "win32":
+ return executable
+ candidate = Path(executable).with_name("pythonw.exe")
+ return str(candidate) if candidate.exists() else executable
+
+
+def service_command(
+ *,
+ after_pid: int | None,
+ executable: str | None = None,
+ frozen: bool | None = None,
+) -> list[str]:
+ """Argv that starts the background service for the current instance.
+
+ A source install runs the web launcher through the interpreter; a frozen
+ build re-enters its own executable with :data:`SERVICE_FLAG` first (it has
+ no ``-m``), which ``jarvis/__main__.py`` routes to the same launcher.
+ """
+ from jarvis.core.instance import current_instance
+
+ active = sys.executable if executable is None else executable
+ if frozen is None:
+ from jarvis.core.frozen import is_frozen
+
+ frozen = is_frozen()
+ tail = [*current_instance().launcher_args]
+ if after_pid is not None:
+ tail += [AFTER_PID_FLAG, str(int(after_pid))]
+ if frozen:
+ return [active, SERVICE_FLAG, *tail]
+ return [
+ _windowless_python(active),
+ "-m",
+ "jarvis.ui.web.launcher",
+ "--headless",
+ SERVICE_FLAG,
+ *tail,
+ ]
+
+
+def _spawn_windows_outside_job(argv: list[str], cwd: str, env: dict[str, str]) -> bool:
+ """Start ``argv`` so no job object of the app can take it down.
+
+ Same reasoning as the PTY host (``pty_host_client._start_host_windows``):
+ a child leaves a kill-on-close job only with ``CREATE_BREAKAWAY_FROM_JOB``,
+ and when the job refuses that, WMI starts the process outside every job.
+ """
+ import subprocess
+
+ from jarvis.ui.relauncher import detached_popen_kwargs
+
+ try:
+ subprocess.Popen(argv, **detached_popen_kwargs(cwd=cwd, env=env)) # type: ignore[call-overload] # noqa: S603
+ return True
+ except PermissionError:
+ logger.info("background: the app's job refuses breakaway — starting the service via WMI")
+ except OSError as exc:
+ logger.warning("background: service could not be started: {}", exc)
+ return False
+
+ from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS
+
+ line = subprocess.list2cmdline(argv).replace("'", "''")
+ folder = cwd.replace("'", "''")
+ script = (
+ "$si = New-CimInstance -ClassName Win32_ProcessStartup -ClientOnly "
+ "-Property @{ShowWindow=[uint16]0}; "
+ "$r = Invoke-CimMethod -ClassName Win32_Process -MethodName Create -Arguments "
+ f"@{{CommandLine='{line}'; CurrentDirectory='{folder}'; ProcessStartupInformation=$si}}; "
+ "exit [int]$r.ReturnValue"
+ )
+ try:
+ done = subprocess.run( # noqa: S603 — fixed PowerShell script, our own argv
+ ["powershell", "-NoProfile", "-NonInteractive", "-Command", script],
+ creationflags=NO_WINDOW_CREATIONFLAGS,
+ capture_output=True,
+ timeout=30,
+ check=False,
+ )
+ except (OSError, subprocess.SubprocessError) as exc:
+ logger.warning("background: WMI start failed: {}", exc)
+ return False
+ if done.returncode != 0:
+ logger.warning("background: WMI start returned {}", done.returncode)
+ return False
+ return True
+
+
+def spawn_service(*, after_pid: int | None) -> bool:
+ """Start the service detached from this process. Never raises."""
+ try:
+ from jarvis.core.instance import current_instance
+ from jarvis.ui.relauncher import fresh_user_env, restart_workdir, spawn_detached
+
+ cwd = restart_workdir(_source_root())
+ env = current_instance().environ(fresh_user_env())
+ env["PYTHONIOENCODING"] = "utf-8"
+ argv = service_command(after_pid=after_pid)
+ if sys.platform == "win32":
+ return _spawn_windows_outside_job(argv, cwd, env)
+ spawn_detached(argv, cwd=cwd, env=env)
+ return True
+ except Exception as exc: # noqa: BLE001 — a failed hand-off must never block quitting
+ logger.opt(exception=exc).warning("background: service could not be started")
+ return False
+
+
+def hand_off_on_quit(state: Any, cfg: Any, *, pid: int | None = None) -> bool:
+ """Called by the quitting desktop app: start the service if there is work.
+
+ Returns ``True`` when a service was started. Never raises.
+ """
+ try:
+ from jarvis.core.instance import current_instance
+
+ if not current_instance().owns_ambient_duties:
+ # A dev instance carries no channels and must not linger unseen.
+ return False
+ if not keep_running_enabled(cfg):
+ logger.info("background: keep_agents_running is off — everything stops with the app")
+ return False
+ work = work_from_state(state)
+ if not work:
+ logger.info("background: no routines or channels to keep — no background service")
+ return False
+ # A leftover request would make the new service exit at once.
+ clear_handover_request()
+ started = spawn_service(after_pid=os.getpid() if pid is None else pid)
+ logger.info(
+ "background: {} the background service to keep {}",
+ "started" if started else "could NOT start",
+ work.describe(),
+ )
+ return started
+ except Exception as exc: # noqa: BLE001 — quitting always wins
+ logger.opt(exception=exc).warning("background: hand-off skipped")
+ return False
+
+
+# ---------------------------------------------------------------------------
+# Taking over from the service (desktop launch)
+# ---------------------------------------------------------------------------
+
+
+def take_over_from_service(
+ acquire: Callable[[], Any],
+ *,
+ busy_error: type[BaseException],
+ wait_s: float = TAKEOVER_WAIT_S,
+ find_pid: Callable[[], int | None] = service_pid,
+ alive: Callable[[int], bool] = _is_service_process,
+ terminate: Callable[[int], bool] | None = None,
+ sleep: Callable[[float], None] = time.sleep,
+ now: Callable[[], float] = time.monotonic,
+) -> Any | None:
+ """Ask the running service to hand back, then take the lock.
+
+ Returns the acquired lock, or ``None`` when no service holds it (the
+ caller then runs its normal "already running" handling). A service that
+ does not let go within ``wait_s`` is stopped: it is our own windowless
+ process and the user has just opened the app.
+ """
+ pid = find_pid()
+ if pid is None:
+ return None
+ logger.info("launcher: background service pid={} holds the app — asking it to hand back", pid)
+ request_handover()
+ try:
+ deadline = now() + wait_s
+ while now() < deadline:
+ try:
+ return acquire()
+ except busy_error: # still shutting down: poll again
+ sleep(0.25)
+ if alive(pid):
+ from jarvis.ui.desktop_app import _terminate_pid
+
+ killer = terminate or _terminate_pid
+ logger.warning(
+ "launcher: background service pid={} did not hand back in {:.0f}s — stopping it",
+ pid,
+ wait_s,
+ )
+ killer(pid)
+ settle = now() + 5.0
+ while now() < settle:
+ try:
+ return acquire()
+ except busy_error: # the OS is still releasing the lock: poll again
+ sleep(0.25)
+ logger.warning("launcher: the lock stayed held after the background service stopped")
+ return None
+ finally:
+ clear_handover_request()
+
+
+__all__ = [
+ "AFTER_PID_FLAG",
+ "SERVICE_FLAG",
+ "BackgroundWork",
+ "clear_handover_request",
+ "clear_marker",
+ "hand_off_on_quit",
+ "handover_requested",
+ "keep_running_enabled",
+ "log_path",
+ "read_marker",
+ "request_handover",
+ "service_command",
+ "service_pid",
+ "spawn_service",
+ "take_over_from_service",
+ "work_from_state",
+ "write_marker",
+]
diff --git a/jarvis/core/config.py b/jarvis/core/config.py
index a19eca73df..74e42b741c 100644
--- a/jarvis/core/config.py
+++ b/jarvis/core/config.py
@@ -2364,6 +2364,24 @@ class AutostartConfig(BaseModel):
# (7 = minimized/tray, 1 = normal); the logon scheduled task launches visibly
# regardless. macOS/Linux ignore it.
start_minimized: bool = False
+ # At login, start only the background agent service (routines, chat
+ # channels) instead of the desktop window. Read by
+ # ``jarvis.autostart.command.resolve_launch_spec``.
+ background_only: bool = False
+
+
+class BackgroundConfig(BaseModel):
+ """What keeps running after the desktop app is closed.
+
+ ``keep_agents_running``: on quit, the desktop hands its routines and chat
+ channels (Telegram, Discord) to a windowless background service, which
+ hands them back the next time the app opens. The service is only started
+ when there is work to keep (a scheduled routine or a running channel).
+ Read by :mod:`jarvis.core.background_service`.
+ """
+
+ model_config = ConfigDict(extra="allow")
+ keep_agents_running: bool = True
class TelemetryConfig(BaseModel):
@@ -4466,6 +4484,8 @@ class JarvisConfig(BaseModel):
# Cross-platform login autostart (Windows .lnk / macOS LaunchAgent / Linux
# XDG .desktop). Default ON; headless host = graceful no-op.
autostart: AutostartConfig = Field(default_factory=AutostartConfig)
+ # Background agent service after the window closes (routines, channels).
+ background: BackgroundConfig = Field(default_factory=BackgroundConfig)
telemetry: TelemetryConfig = Field(default_factory=TelemetryConfig)
security: SecurityConfig = Field(default_factory=SecurityConfig)
# ``validation_alias`` back-compat: old installs use [sub_agents];
diff --git a/jarvis/core/config_writer.py b/jarvis/core/config_writer.py
index 74adcce166..5fbb9d9abd 100644
--- a/jarvis/core/config_writer.py
+++ b/jarvis/core/config_writer.py
@@ -1165,6 +1165,24 @@ def set_autostart(enabled: bool, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
_patch_table(path, "autostart", "enabled", bool(enabled))
+def set_autostart_background_only(enabled: bool, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
+ """Persist ``[autostart] background_only`` (login starts only the agent service).
+
+ Toml-only, same rationale as :func:`set_autostart`; the caller re-applies
+ the OS entry so its command line follows the new mode.
+ """
+ _patch_table(path, "autostart", "background_only", bool(enabled))
+
+
+def set_background_keep_running(enabled: bool, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
+ """Persist ``[background] keep_agents_running`` in jarvis.toml.
+
+ Toml-only, same rationale as :func:`set_autostart`: the drift-guard does
+ not track it. Read at quit time, so it applies without a restart.
+ """
+ _patch_table(path, "background", "keep_agents_running", bool(enabled))
+
+
def set_wiki_vault_root(vault_root: str, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
"""Persist ``[wiki_integration] vault_root`` in jarvis.toml (AP-7).
diff --git a/jarvis/tasks/scheduler.py b/jarvis/tasks/scheduler.py
index 6efab5bc92..a69899156c 100644
--- a/jarvis/tasks/scheduler.py
+++ b/jarvis/tasks/scheduler.py
@@ -542,6 +542,14 @@ class TaskScheduler:
self._wakeup.set()
return due
+ def pending_work(self) -> tuple[int, int]:
+ """``(armed tasks, runs in flight)`` — synchronous and cheap.
+
+ Armed = waiting for a time or an event. The background service reads
+ this to decide whether closing the window leaves anything to keep.
+ """
+ return len(self._known), sum(1 for task in self._runner_tasks if not task.done())
+
def _remove_from_memory(self, task_id: str) -> None:
"""Drop a task from the heap, the event index and the known set."""
self.sources.cancel(task_id)
diff --git a/jarvis/ui/background_tray.py b/jarvis/ui/background_tray.py
new file mode 100644
index 0000000000..ee76ca5e2c
--- /dev/null
+++ b/jarvis/ui/background_tray.py
@@ -0,0 +1,140 @@
+"""Tray icon of the background agent service.
+
+The service has no window, so this icon is the user's proof that agents keep
+running after the app closed — and the way to stop them or reopen the app.
+
+Two actions only: "Open" starts the desktop app (which then takes over from
+the service), "Stop background agents" ends the service. Windows and Linux
+desktops get the icon on a pystray worker thread; macOS allows status items on
+the main thread only, which the service's event loop owns, and a host without
+a display or notification area has nowhere to draw one. Both degrade to a
+logged no-op — the service runs the same without the icon.
+"""
+
+from __future__ import annotations
+
+import sys
+import threading
+from collections.abc import Callable
+from typing import Any
+
+from loguru import logger
+
+
+def _icon_image(size: int = 64) -> Any:
+ from PIL import Image, ImageDraw # type: ignore[import-untyped]
+
+ from jarvis.ui.icon_utils import load_ico_as_pil_image, project_icon_path
+
+ image = load_ico_as_pil_image(project_icon_path(), size=size)
+ if image is not None:
+ return image
+ image = Image.new("RGBA", (size, size), (0, 0, 0, 0))
+ ImageDraw.Draw(image).ellipse((4, 4, size - 4, size - 4), fill=(80, 120, 200))
+ return image
+
+
+class BackgroundTray:
+ """Owns the pystray icon on its own daemon thread."""
+
+ def __init__(self, *, on_open: Callable[[], None], on_stop: Callable[[], None]) -> None:
+ self._on_open = on_open
+ self._on_stop = on_stop
+ self._icon: Any = None
+ self._thread: threading.Thread | None = None
+
+ def start(self) -> bool:
+ """Show the icon. ``False`` (and one log line) where none can exist."""
+ if sys.platform == "darwin":
+ logger.info(
+ "background: no menu-bar icon on macOS for the windowless service "
+ "(status items need the main thread); open the app to stop it"
+ )
+ return False
+ from jarvis.platform.probes import display_present
+
+ if not display_present():
+ logger.info("background: no display / notification area — service runs without a tray")
+ return False
+ try:
+ import pystray # type: ignore[import-untyped]
+
+ from jarvis.core.branding import PRODUCT_NAME
+
+ menu = pystray.Menu(
+ pystray.MenuItem(
+ f"{PRODUCT_NAME}: agents keep running in the background", None, enabled=False
+ ),
+ pystray.MenuItem(f"Open {PRODUCT_NAME}", self._open, default=True),
+ pystray.MenuItem("Stop background agents", self._stop),
+ )
+ self._icon = pystray.Icon(
+ "jarvis-background",
+ icon=_icon_image(),
+ title=f"{PRODUCT_NAME} — agents running in the background",
+ menu=menu,
+ )
+ except Exception: # noqa: BLE001 — a tray is a convenience, never a boot blocker
+ logger.opt(exception=True).warning("background: tray icon unavailable")
+ self._icon = None
+ return False
+ self._thread = threading.Thread(
+ target=self._run, name="jarvis-background-tray", daemon=True
+ )
+ self._thread.start()
+ return True
+
+ def _run(self) -> None:
+ icon = self._icon
+ if icon is None:
+ return
+ try:
+ icon.run()
+ except Exception: # noqa: BLE001 — the service keeps running without the icon
+ logger.opt(exception=True).warning("background: tray icon stopped unexpectedly")
+
+ def _open(self, *_: Any) -> None:
+ try:
+ self._on_open()
+ except Exception: # noqa: BLE001 — a failed open must not take the tray down
+ logger.opt(exception=True).warning("background: opening the app failed")
+
+ def _stop(self, *_: Any) -> None:
+ try:
+ self._on_stop()
+ except Exception: # noqa: BLE001 — same: report, keep the icon alive
+ logger.opt(exception=True).warning("background: stop request failed")
+
+ def stop(self) -> None:
+ icon, self._icon = self._icon, None
+ if icon is not None:
+ try:
+ icon.stop()
+ except Exception: # noqa: BLE001 — teardown on the way out
+ logger.opt(exception=True).debug("background: tray stop raised")
+ thread = self._thread
+ if thread is not None and thread is not threading.current_thread():
+ thread.join(timeout=2.0)
+
+
+def open_desktop_app() -> bool:
+ """Start the desktop app; it takes over from the running service."""
+ try:
+ from jarvis.core.background_service import _source_root
+ from jarvis.core.instance import current_instance
+ from jarvis.ui.relauncher import (
+ build_launch_command,
+ fresh_user_env,
+ restart_workdir,
+ spawn_detached,
+ )
+
+ # The service itself runs windowless (pythonw on Windows), so its own
+ # interpreter is the right one for the window app too.
+ argv = build_launch_command(sys.executable)
+ cwd = restart_workdir(_source_root())
+ spawn_detached(argv, cwd=cwd, env=current_instance().environ(fresh_user_env()))
+ return True
+ except Exception: # noqa: BLE001 — reported to the tray caller's log
+ logger.opt(exception=True).warning("background: could not start the desktop app")
+ return False
diff --git a/jarvis/ui/desktop_app.py b/jarvis/ui/desktop_app.py
index cc4b7876db..c918fe1448 100644
--- a/jarvis/ui/desktop_app.py
+++ b/jarvis/ui/desktop_app.py
@@ -3197,6 +3197,7 @@ class DesktopApp:
logger.critical(
"Backend stopped in background mode ({}); exiting the owned shell.", reason,
)
+ self._skip_background_handoff = True
self._user_requested_quit = True
self._arm_force_exit(after_s=20.0)
threading.Thread(
@@ -3846,6 +3847,7 @@ class DesktopApp:
return (False, f"{type(exc).__name__}: {exc}")
def _mark_quit() -> None:
+ self._skip_background_handoff = True
self._user_requested_quit = True
def _quit_soon() -> None:
@@ -3890,6 +3892,7 @@ class DesktopApp:
return False
def _mark_quit() -> None:
+ self._skip_background_handoff = True
self._user_requested_quit = True
def _quit_soon() -> None:
@@ -5865,6 +5868,7 @@ class DesktopApp:
# False → normal return, so callers still get an exit code.
if self._user_requested_quit:
self._arm_force_exit(after_s=20.0)
+ self._hand_off_to_background_service()
code = self.shutdown()
if self._user_requested_quit:
with suppress(Exception):
@@ -6275,6 +6279,25 @@ class DesktopApp:
if backstop:
self._arm_force_exit(after_s=self._CLOSE_QUIT_BACKSTOP_S)
+ def _hand_off_to_background_service(self) -> None:
+ """On a real quit, start the background agent service if there is work.
+
+ Routines and chat channels would otherwise stop with the window; the
+ service (``jarvis.core.background_service``) waits for this process to
+ exit, takes over the lock and keeps them running until the app opens
+ again. A restart, a declined Terms gate or a failed backend set
+ ``_skip_background_handoff`` — those must not leave anything behind.
+ """
+ if getattr(self, "_skip_background_handoff", False):
+ return
+ server = getattr(self, "_server", None)
+ state = getattr(getattr(server, "app", None), "state", None)
+ if state is None:
+ return
+ from jarvis.core.background_service import hand_off_on_quit
+
+ hand_off_on_quit(state, getattr(server, "cfg", None) or self.cfg)
+
def _stop_overlay(self) -> None:
"""Take the on-screen bar or mascot down. Idempotent, never raises."""
orb = getattr(self, "_orb", None)
diff --git a/jarvis/ui/web/frontend/src/hooks/useBackgroundAgents.ts b/jarvis/ui/web/frontend/src/hooks/useBackgroundAgents.ts
new file mode 100644
index 0000000000..66779a1ac3
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/hooks/useBackgroundAgents.ts
@@ -0,0 +1,59 @@
+import { useCallback, useEffect, useState } from "react";
+
+/**
+ * What keeps running after the desktop window closes — GET/PUT
+ * /api/settings/background (jarvis/core/background_service.py).
+ */
+export interface BackgroundAgentsConfig {
+ keep_agents_running: boolean;
+ background_only_at_login: boolean;
+ autostart_enabled: boolean;
+ /** This page is served by the windowless background service itself. */
+ running_as_service: boolean;
+ /** False on a dev instance: it stops with its window, by design. */
+ supported: boolean;
+ /** The work a quit would hand to the background service right now. */
+ work: { routines: number; running: number; channels: string[] };
+}
+
+export type BackgroundAgentsPatch = Partial<
+ Pick<BackgroundAgentsConfig, "keep_agents_running" | "background_only_at_login">
+>;
+
+/** Loads the background-agents settings and exposes save(). Mirrors useAutostart. */
+export function useBackgroundAgents() {
+ const [config, setConfig] = useState<BackgroundAgentsConfig | null>(null);
+ const [loading, setLoading] = useState(true);
+ const [error, setError] = useState<string | null>(null);
+
+ const refetch = useCallback(async () => {
+ setError(null);
+ try {
+ const res = await fetch("/api/settings/background");
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
+ setConfig((await res.json()) as BackgroundAgentsConfig);
+ } catch (e) {
+ setError((e as Error).message);
+ } finally {
+ setLoading(false);
+ }
+ }, []);
+
+ useEffect(() => {
+ void refetch();
+ }, [refetch]);
+
+ const save = useCallback(async (patch: BackgroundAgentsPatch) => {
+ const res = await fetch("/api/settings/background", {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(patch),
+ });
+ const body = await res.json().catch(() => ({}));
+ if (!res.ok) throw new Error(body.detail ?? `HTTP ${res.status}`);
+ setConfig(body as BackgroundAgentsConfig);
+ return body as BackgroundAgentsConfig;
+ }, []);
+
+ return { config, loading, error, refetch, save };
+}
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.json
index d6868dee62..42cf4563d9 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json
@@ -2509,6 +2509,17 @@
"instant_start_enabled_toast": "Sofortstart aktiviert — {name} startet direkt nach der Anmeldung.",
"instant_start_declined_toast": "Berechtigung abgelehnt — {name} startet weiterhin über die Verknüpfung (evtl. verzögert)."
},
+ "background_agents": {
+ "title": "Agenten nach dem Schließen weiterlaufen lassen",
+ "description": "Wenn du {name} schließt, hält ein kleiner Hintergrund-Dienst deine Routinen und Chat-Kanäle (Telegram, Discord) am Laufen. Öffnest du die App, übernimmt sie wieder. Er startet nur, wenn es etwas weiterzuführen gibt.",
+ "keeps_now": "Beim Schließen laufen weiter: {what}.",
+ "keeps_nothing": "Gerade gibt es nichts weiterzuführen — Schließen beendet alles.",
+ "routines": "{count} Routine(n)",
+ "login_title": "Beim Anmelden nur die Hintergrund-Agenten starten",
+ "login_description": "Führt Routinen und Chat-Kanäle nach einem Neustart aus, ohne das Fenster zu öffnen. Setzt \"App beim Anmelden starten\" voraus.",
+ "service_active": "Du siehst gerade den Hintergrund-Dienst. Öffne die Desktop-App, um zu übernehmen.",
+ "saved_toast": "Gespeichert."
+ },
"overlay_style": {
"title": "Anzeige-Stil",
"description": "Wähle, wie {name} bei Sprachaktivität auf dem Bildschirm erscheint. Die Bar ist der schlanke Standard; das Maskottchen ist der klassische Begleiter; der Voice-Orb ist eine leuchtende Kugel; das Pet ist ein Pixel-Begleiter, der sichtbar bleibt; oder ganz ausblenden. Jeder schwebende Stil lässt sich auf jeden Monitor ziehen.",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.json
index 9348ce2b51..4ab0ccb453 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json
@@ -2542,6 +2542,17 @@
"instant_start_enabled_toast": "Instant start enabled — {name} will launch right after login.",
"instant_start_declined_toast": "Permission was declined — {name} still starts via the shortcut (may be delayed)."
},
+ "background_agents": {
+ "title": "Keep agents running after closing",
+ "description": "When you close {name}, a small background service keeps your routines and chat channels (Telegram, Discord) running. Opening the app takes over again. It only starts when there is something to keep.",
+ "keeps_now": "Closing now keeps: {what}.",
+ "keeps_nothing": "Right now there is nothing to keep — closing stops everything.",
+ "routines": "{count} routine(s)",
+ "login_title": "At login, start only the background agents",
+ "login_description": "Runs routines and chat channels after a restart without opening the window. Needs \"Launch app at login\".",
+ "service_active": "You are looking at the background service. Open the desktop app to take over.",
+ "saved_toast": "Saved."
+ },
"overlay_style": {
"title": "Display style",
"description": "Choose how {name} appears on screen during voice activity. The bar is the slim default; the mascot is the classic companion; the voice orb is a glowing sphere; the pet is a pixel companion that stays on screen; or hide it entirely. Every floating style can be dragged to any monitor.",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.json
index eda263d807..f4cbfb19c5 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json
@@ -2509,6 +2509,17 @@
"instant_start_enabled_toast": "Inicio instantáneo activado: {name} se iniciará justo después de iniciar sesión.",
"instant_start_declined_toast": "Se denegó el permiso: {name} sigue iniciándose mediante el acceso directo (puede retrasarse)."
},
+ "background_agents": {
+ "title": "Mantener los agentes activos al cerrar",
+ "description": "Al cerrar {name}, un pequeño servicio en segundo plano mantiene activas tus rutinas y canales de chat (Telegram, Discord). Al abrir la app, esta vuelve a tomar el control. Solo se inicia cuando hay algo que mantener.",
+ "keeps_now": "Al cerrar ahora se mantiene: {what}.",
+ "keeps_nothing": "Ahora mismo no hay nada que mantener: cerrar lo detiene todo.",
+ "routines": "{count} rutina(s)",
+ "login_title": "Al iniciar sesión, iniciar solo los agentes en segundo plano",
+ "login_description": "Ejecuta rutinas y canales de chat tras reiniciar sin abrir la ventana. Requiere \"Iniciar la app al iniciar sesión\".",
+ "service_active": "Estás viendo el servicio en segundo plano. Abre la app de escritorio para tomar el control.",
+ "saved_toast": "Guardado."
+ },
"overlay_style": {
"title": "Estilo de visualización",
"description": "Elige cómo aparece {name} en pantalla durante la actividad de voz. La barra es el valor predeterminado; la mascota es el acompañante clásico; el orbe de voz es una esfera luminosa; la mascota es un compañero de píxeles que permanece en pantalla; o ocúltalo por completo. Cualquier estilo flotante se puede arrastrar a cualquier monitor.",
diff --git a/jarvis/ui/web/frontend/src/views/settings/AppSettingsGroup.tsx b/jarvis/ui/web/frontend/src/views/settings/AppSettingsGroup.tsx
index 3900612a9c..30f9ec19e1 100644
--- a/jarvis/ui/web/frontend/src/views/settings/AppSettingsGroup.tsx
+++ b/jarvis/ui/web/frontend/src/views/settings/AppSettingsGroup.tsx
@@ -1,11 +1,12 @@
import { useState } from "react";
-import { Compass, Monitor, Moon, Power, Sparkles, Sun, Zap } from "lucide-react";
+import { Bot, Compass, Monitor, Moon, Power, Sparkles, Sun, Zap } from "lucide-react";
import { FIRST_STEPS_START_EVENT, SETUP_REPLAY_EVENT } from "@/components/onboarding/tourEvents";
import { Switch } from "@/components/ui/switch";
import { useAutostart } from "@/hooks/useAutostart";
+import { useBackgroundAgents, type BackgroundAgentsPatch } from "@/hooks/useBackgroundAgents";
import { useTheme, type ThemePreference } from "@/hooks/useTheme";
import { useEventStore } from "@/store/events";
-import { useLocaleChunk, useT } from "@/i18n";
+import { fill, useLocaleChunk, useT } from "@/i18n";
/**
* "App settings" group inside the Settings view. Currently hosts the
@@ -30,6 +31,7 @@ export function AppSettingsGroup() {
</h3>
<AppearanceRow />
<AutostartRow />
+ <BackgroundAgentsRow />
<TourRow />
<FirstStepsRow />
</div>
@@ -297,3 +299,95 @@ function AutostartRow() {
</div>
);
}
+
+const CHANNEL_LABELS: Record<string, string> = { telegram: "Telegram", discord: "Discord" };
+
+/**
+ * "Keep agents running after closing": on quit the app hands routines and chat
+ * channels to a windowless background service, which hands them back when the
+ * app opens again. The second switch makes the login entry start only that
+ * service. The line below says what a quit would keep right now.
+ */
+function BackgroundAgentsRow() {
+ const t = useT();
+ const { config, loading, error, save } = useBackgroundAgents();
+ const pushToast = useEventStore((s) => s.pushToast);
+ const [saving, setSaving] = useState(false);
+
+ if (config && !config.supported) return null;
+
+ async function apply(patch: BackgroundAgentsPatch) {
+ setSaving(true);
+ try {
+ await save(patch);
+ pushToast("success", t("settings_view.background_agents.saved_toast"));
+ } catch (e) {
+ pushToast("error", (e as Error).message);
+ } finally {
+ setSaving(false);
+ }
+ }
+
+ const keep = config?.keep_agents_running ?? true;
+ const work = config?.work;
+ const parts: string[] = [];
+ if (work?.routines) {
+ parts.push(fill(t("settings_view.background_agents.routines"), { count: work.routines }));
+ }
+ for (const channel of work?.channels ?? []) parts.push(CHANNEL_LABELS[channel] ?? channel);
+
+ return (
+ <div className="rounded-lg border border-border bg-card p-4">
+ <div className="flex items-start gap-3">
+ <Bot className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" />
+ <div className="min-w-0 flex-1">
+ <div className="flex items-center justify-between gap-4">
+ <h4 className="font-medium">{t("settings_view.background_agents.title")}</h4>
+ <Switch
+ checked={keep}
+ disabled={loading || saving}
+ aria-label={t("settings_view.background_agents.title")}
+ onCheckedChange={(next) => void apply({ keep_agents_running: next })}
+ />
+ </div>
+ <p className="mt-0.5 text-xs text-muted-foreground">
+ {t("settings_view.background_agents.description")}
+ </p>
+
+ {error && <p className="mt-3 text-xs text-destructive">{error}</p>}
+
+ {config?.running_as_service && (
+ <p className="mt-3 text-xs text-foreground">
+ {t("settings_view.background_agents.service_active")}
+ </p>
+ )}
+
+ {config && keep && !config.running_as_service && (
+ <p className="mt-3 text-xs text-muted-foreground">
+ {parts.length > 0
+ ? fill(t("settings_view.background_agents.keeps_now"), { what: parts.join(", ") })
+ : t("settings_view.background_agents.keeps_nothing")}
+ </p>
+ )}
+
+ <div className="mt-3 flex items-center justify-between gap-4 rounded-md border border-border bg-background p-3">
+ <div className="min-w-0">
+ <p className="text-xs font-medium">
+ {t("settings_view.background_agents.login_title")}
+ </p>
+ <p className="mt-0.5 text-xs text-muted-foreground">
+ {t("settings_view.background_agents.login_description")}
+ </p>
+ </div>
+ <Switch
+ checked={config?.background_only_at_login ?? false}
+ disabled={loading || saving || !config?.autostart_enabled}
+ aria-label={t("settings_view.background_agents.login_title")}
+ onCheckedChange={(next) => void apply({ background_only_at_login: next })}
+ />
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/jarvis/ui/web/launcher.py b/jarvis/ui/web/launcher.py
index 407a5217d1..bc03350fd5 100644
--- a/jarvis/ui/web/launcher.py
+++ b/jarvis/ui/web/launcher.py
@@ -3,6 +3,9 @@
Usage:
python -m jarvis.ui.web.launcher # full desktop app
python -m jarvis.ui.web.launcher --headless # backend only, no window
+ python -m jarvis.ui.web.launcher --background-service
+ # the windowless agent service
+ # a quitting desktop hands to
python -m jarvis.ui.web.launcher --dev # dev_mode=True
This launcher is DELIBERATELY separate from jarvis/__main__.py so Phase 1a and
@@ -106,6 +109,23 @@ def _parse_args(argv: list[str]) -> argparse.Namespace:
action="store_true",
help="No single-instance lock (for parallel dev sessions)",
)
+ p.add_argument(
+ "--background-service",
+ action="store_true",
+ dest="background_service",
+ help=(
+ "Run as the background agent service (implies --headless): keeps "
+ "routines and chat channels running while the desktop app is closed "
+ "and hands back when it opens. See jarvis/core/background_service.py."
+ ),
+ )
+ p.add_argument(
+ "--after-pid",
+ type=int,
+ default=None,
+ dest="after_pid",
+ help=argparse.SUPPRESS,
+ )
p.add_argument(
"--instance",
default=None,
@@ -406,11 +426,20 @@ async def _run_headless(args) -> int:
except Exception: # noqa: BLE001,S110 - a diagnostic never breaks a boot.
pass
+ # The background agent service is the exception: it may only exist while
+ # no desktop app does, so it takes the lock BEFORE it binds the port and
+ # simply ends when the lock is not free.
+ _service_lock = None
+ if getattr(args, "background_service", False):
+ _service_lock = _prepare_background_service(args)
+ if _service_lock is None:
+ return 0
+
# The single-instance lock (and its heavy ``desktop_app`` import — pywebview +
# win32, ~420 ms) is acquired in the deferred section below, OFF the
# time-to-serving path. It only needs to set JARVIS_PRIMARY_INSTANCE before
# the mission stack init, which is also deferred.
- _headless_lock = None
+ _headless_lock = _service_lock
_lx_mark("lock")
# === Fast-boot bootstrap: bind the port and serve a holding app NOW ===
@@ -574,7 +603,10 @@ 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, port=_port)
+ if _service_lock is None:
+ _headless_lock = _claim_headless_primary_lock(args, port=_port)
+ else:
+ _write_service_sidecar(_port)
_lx_mark("lock")
from jarvis.brain.factory import build_default_brain
@@ -883,6 +915,13 @@ async def _run_headless(args) -> int:
except (ValueError, AttributeError):
pass
+ _service_tray = None
+ _service_watch = None
+ if _service_lock is not None:
+ _service_watch, _service_tray = _start_background_service_duties(
+ server.app.state, stop_event
+ )
+
# Show the actual bind host (JARVIS_BIND_HOST may be 0.0.0.0 on a VPS);
# bracket IPv6 literals so the printed URL stays valid.
_url_host = f"[{_host}]" if ":" in _host else _host
@@ -892,6 +931,14 @@ async def _run_headless(args) -> int:
try:
await stop_event.wait()
finally:
+ if _service_lock is not None:
+ # A wedged teardown must not keep a windowless process holding the
+ # lock the reopening desktop is waiting for.
+ _arm_service_exit_backstop(SERVICE_SHUTDOWN_BACKSTOP_S)
+ if _service_watch is not None:
+ _service_watch.cancel()
+ if _service_tray is not None:
+ _service_tray.stop()
# Stop the fast-boot bootstrap server (it owns the listening socket).
_bootstrap_server.should_exit = True
try:
@@ -923,10 +970,171 @@ 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
+
+ clear_marker()
return 0
+#: Seconds a stopping background service may spend on its teardown before it
+#: is ended hard (the desktop waiting to take over gives up after 45 s).
+SERVICE_SHUTDOWN_BACKSTOP_S = 30.0
+
+
+def _arm_service_exit_backstop(after_s: float) -> None:
+ def _force() -> None:
+ time.sleep(after_s)
+ from loguru import logger
+
+ logger.warning("background: teardown took over {:.0f}s — ending the service hard", after_s)
+ _exit_background_service(0)
+
+ threading.Thread(target=_force, name="background-exit-backstop", daemon=True).start()
+
+
+def _exit_background_service(code: int) -> None:
+ """End the service process now, after a bounded flush of the exit hooks.
+
+ ``asyncio.run`` returning is not the end of the process: a worker thread
+ that never finishes keeps the interpreter alive (measured: over a minute
+ after the lock was released), and an invisible process nobody can see is
+ exactly what the service must never become. The exit hooks (log drain
+ among them) get five seconds, then the process ends.
+ """
+ import atexit
+
+ flush = threading.Thread(
+ target=atexit._run_exitfuncs, # noqa: SLF001 — the only public-free way to drain them
+ name="background-exit-flush",
+ daemon=True,
+ )
+ flush.start()
+ flush.join(timeout=5.0)
+ os._exit(code)
+
+
+def _prepare_background_service(args):
+ """Gate a background-service boot; return the held lock or ``None``.
+
+ The service exists only while no desktop app does: it waits for the
+ quitting desktop (``--after-pid``), steps aside when a desktop launch is
+ already asking for the app back, and takes the single-instance lock
+ without evicting anyone. ``None`` means "do not start" and is logged.
+ """
+ from loguru import logger
+
+ from jarvis.core import background_service as bg
+
+ try:
+ from jarvis.ui.desktop_log import _install_desktop_log_sink
+
+ _install_desktop_log_sink(bg.log_path())
+ except Exception: # noqa: BLE001,S110 - a mute service still serves; boot on
+ pass
+ # No microphone, wake-word or voice warm-up: no window, nobody in front of it.
+ os.environ["JARVIS_VOICE"] = "0"
+ after = getattr(args, "after_pid", None)
+ if after:
+ from jarvis.ui.relauncher import wait_for_pid_exit
+
+ logger.info("background: waiting for the desktop app (pid={}) to exit", after)
+ if not wait_for_pid_exit(int(after), timeout=bg.PARENT_EXIT_WAIT_S):
+ logger.warning("background: desktop pid={} never exited — service not started", after)
+ return None
+ if bg.handover_requested():
+ logger.info("background: the desktop app is opening again — service not started")
+ return None
+ from jarvis.ui.desktop_app import SingleInstanceError, acquire_single_instance_lock
+
+ try:
+ lock = acquire_single_instance_lock(terminate=lambda _pid: False)
+ except SingleInstanceError as exc:
+ logger.info("background: the app is already running ({}) — service not started", exc)
+ return None
+ os.environ["JARVIS_PRIMARY_INSTANCE"] = "1"
+ logger.info("background: agent service starting (pid={})", os.getpid())
+ return lock
+
+
+def _write_service_sidecar(port: int) -> None:
+ """The service's marker plus the instance sidecar a desktop launch reads."""
+ from loguru import logger
+
+ from jarvis.core import background_service as bg
+
+ try:
+ bg.write_marker(port)
+ except OSError as exc:
+ logger.warning("background: service marker not written: {}", exc)
+ try:
+ from jarvis.ui.desktop_app import _write_meta
+
+ _write_meta(int(port), os.getpid())
+ except Exception: # noqa: BLE001 — the sidecar is recovery, not boot
+ logger.opt(exception=True).warning("background: instance sidecar not written")
+
+
+def _start_background_service_duties(state, stop_event):
+ """Start the handover/idle watch and the tray. Returns ``(task, tray)``."""
+ from loguru import logger
+
+ from jarvis.ui.background_tray import BackgroundTray, open_desktop_app
+
+ loop = asyncio.get_running_loop()
+ task = loop.create_task(
+ _watch_background_service(state, stop_event), name="background-service-watch"
+ )
+
+ def _stop_from_tray() -> None:
+ logger.info("background: stopped from the tray")
+ loop.call_soon_threadsafe(stop_event.set)
+
+ tray = BackgroundTray(on_open=open_desktop_app, on_stop=_stop_from_tray)
+ tray.start()
+ return task, tray
+
+
+async def _watch_background_service(
+ state,
+ stop_event,
+ *,
+ poll_s: float | None = None,
+ idle_check_s: float | None = None,
+ idle_strikes: int | None = None,
+) -> None:
+ """End the service when the desktop asks for the app back, or when the
+ work it was started for is gone (no armed routine, no channel, no run)."""
+ from loguru import logger
+
+ from jarvis.core import background_service as bg
+
+ poll = bg.HANDOVER_POLL_S if poll_s is None else poll_s
+ idle_every = bg.IDLE_CHECK_S if idle_check_s is None else idle_check_s
+ strikes_needed = bg.IDLE_STRIKES if idle_strikes is None else idle_strikes
+ loop = asyncio.get_running_loop()
+ next_idle_check = loop.time() + idle_every
+ strikes = 0
+ while not stop_event.is_set():
+ await asyncio.sleep(poll)
+ if bg.handover_requested():
+ logger.info("background: the desktop app is opening — handing the agents back")
+ stop_event.set()
+ return
+ if loop.time() < next_idle_check:
+ continue
+ next_idle_check = loop.time() + idle_every
+ if bg.work_from_state(state):
+ strikes = 0
+ continue
+ strikes += 1
+ if strikes >= strikes_needed:
+ logger.info("background: no routines, channels or runs left — service exits")
+ stop_event.set()
+ return
+
+
def _show_error_dialog(title: str, message: str) -> None:
"""Native modal box on every desktop OS — see ``jarvis.ui.native_dialog``.
@@ -1562,6 +1770,27 @@ def _recover_from_already_running(
return lock
+def _take_over_from_background_service():
+ """The lock, handed back by a running background service — else ``None``."""
+ try:
+ from jarvis.core.background_service import take_over_from_service
+ from jarvis.ui import desktop_app as _desktop_app
+
+ return take_over_from_service(
+ lambda: _desktop_app.acquire_single_instance_lock(
+ timeout=0.5, terminate=lambda _pid: False
+ ),
+ busy_error=_desktop_app.SingleInstanceError,
+ )
+ except Exception: # noqa: BLE001 — fall through to the normal lock handling
+ import logging as _logging
+
+ _logging.getLogger(__name__).warning(
+ "taking over from the background service failed", exc_info=True
+ )
+ return None
+
+
def _run_desktop(cfg, use_lock: bool) -> int:
"""Full desktop app with a pywebview window.
@@ -1579,12 +1808,19 @@ def _run_desktop(cfg, use_lock: bool) -> int:
lock = None
if use_lock:
+ # A background agent service holds the app while the window is closed;
+ # asking it to hand back is not "already running".
+ lock = _take_over_from_background_service()
+ if use_lock and lock is None:
try:
lock = acquire_single_instance_lock()
except SingleInstanceError as exc:
+ # The service may have won the lock while this launch started.
+ lock = _take_over_from_background_service()
# An older native build quitting for an update is not "already
# running" — this build is its replacement and takes over.
- lock = _wait_out_an_older_holder()
+ if lock is None:
+ lock = _wait_out_an_older_holder()
if lock is None:
print(f"{APP_DISPLAY_NAME} is already running.", file=sys.stderr)
lock = _recover_from_already_running(
@@ -1731,7 +1967,9 @@ def _desktop_backend_main(args, port: int, token: str, holder: dict, app_ready)
if not args.no_lock:
try:
- holder["lock"] = acquire_single_instance_lock()
+ holder["lock"] = (
+ _take_over_from_background_service() or acquire_single_instance_lock()
+ )
os.environ["JARVIS_PRIMARY_INSTANCE"] = "1"
except SingleInstanceError:
holder["already_running"] = True
@@ -1954,6 +2192,8 @@ def _main(argv: list[str] | None = None) -> int:
)
args = _parse_args(_raw_argv)
+ if args.background_service:
+ args.headless = True
# From here on every desktop launch is written down — see the helper.
if not args.headless:
@@ -2065,7 +2305,10 @@ def _main(argv: list[str] | None = None) -> int:
# time-to-serving. The desktop path keeps the heavy init up front because the
# pywebview window needs the resolved config before it can be shown.
if args.headless:
- return asyncio.run(_run_headless(args))
+ code = asyncio.run(_run_headless(args))
+ if args.background_service:
+ _exit_background_service(code)
+ return code
# Desktop boot: CLASSIC path (proven + GUI-safe). The serve-first bootstrap
# + static-shell + boot-splash (the black-screen fix) live in
diff --git a/jarvis/ui/web/settings_routes.py b/jarvis/ui/web/settings_routes.py
index 713732948f..dadeff0c3d 100644
--- a/jarvis/ui/web/settings_routes.py
+++ b/jarvis/ui/web/settings_routes.py
@@ -2144,6 +2144,82 @@ async def put_autostart(body: AutostartBody, request: Request) -> dict[str, obje
}
+# ---------------------------------------------------------------------------
+# Background agents: what keeps running after the window closes
+# (jarvis/core/background_service.py). GET reports the setting, the login mode
+# and the work a quit would hand over right now; PUT changes either setting.
+# ---------------------------------------------------------------------------
+
+
+class BackgroundBody(BaseModel):
+ keep_agents_running: bool | None = Field(default=None)
+ background_only_at_login: bool | None = Field(default=None)
+
+
+def _background_payload(request: Request) -> dict[str, object]:
+ import sys as _sys
+
+ from jarvis.core.background_service import SERVICE_FLAG, keep_running_enabled, work_from_state
+ from jarvis.core.instance import current_instance
+
+ cfg = _config(request)
+ autostart_cfg = getattr(cfg, "autostart", None)
+ work = work_from_state(request.app.state)
+ return {
+ "keep_agents_running": keep_running_enabled(cfg),
+ "background_only_at_login": bool(getattr(autostart_cfg, "background_only", False)),
+ "autostart_enabled": bool(getattr(autostart_cfg, "enabled", True)),
+ # This process IS the windowless service (a browser on its port).
+ "running_as_service": SERVICE_FLAG in _sys.argv,
+ # Only the default app hands off; a dev instance stops with its window.
+ "supported": current_instance().owns_ambient_duties,
+ "work": {
+ "routines": work.routines,
+ "running": work.running,
+ "channels": list(work.channels),
+ },
+ }
+
+
[email protected]("/background")
+def get_background(request: Request) -> dict[str, object]:
+ return _background_payload(request)
+
+
[email protected]("/background")
+async def put_background(body: BackgroundBody, request: Request) -> dict[str, object]:
+ from jarvis.core import config_writer
+
+ cfg = _config(request)
+ if body.keep_agents_running is not None:
+ value = bool(body.keep_agents_running)
+ config_writer.set_background_keep_running(value)
+ section = getattr(cfg, "background", None)
+ if section is not None:
+ try:
+ section.keep_agents_running = value # type: ignore[attr-defined]
+ except Exception as exc: # noqa: BLE001 — frozen model: the toml write still counts
+ log.debug("in-memory background.keep_agents_running update skipped: %s", exc)
+ if body.background_only_at_login is not None:
+ value = bool(body.background_only_at_login)
+ config_writer.set_autostart_background_only(value)
+ autostart_cfg = getattr(cfg, "autostart", None)
+ if autostart_cfg is not None:
+ try:
+ autostart_cfg.background_only = value # type: ignore[attr-defined]
+ except Exception as exc: # noqa: BLE001 — same as above
+ log.debug("in-memory autostart.background_only update skipped: %s", exc)
+ enabled, _caps, manager, spec = _autostart_components(request)
+ if enabled:
+ # The login entry carries the mode in its command line; refresh it
+ # now (user-initiated, so Windows may ask once to update its task).
+ try:
+ await asyncio.to_thread(manager.install, spec, interactive=True)
+ except Exception as exc: # noqa: BLE001 — persisted; the boot reconcile retries
+ log.warning("autostart refresh after a login-mode change failed: %s", exc)
+ return _background_payload(request)
+
+
_OVERLAY_STYLES = OVERLAY_STYLES
diff --git a/tests/unit/core/test_background_service.py b/tests/unit/core/test_background_service.py
new file mode 100644
index 0000000000..2e650cd8c3
--- /dev/null
+++ b/tests/unit/core/test_background_service.py
@@ -0,0 +1,463 @@
+"""Background agent service: hand-off on quit, hand-back on launch.
+
+Routines and chat channels must outlive the desktop window. These tests pin
+the decisions (when a service starts, who owns the lock, when it stops) with
+fakes; the process-level round trip is covered by the live smoke described in
+docs/background-service.md.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import os
+import sys
+from types import SimpleNamespace
+
+import pytest
+
+from jarvis.core import background_service as bg
+
+
[email protected](autouse=True)
+def _isolated_state(monkeypatch, tmp_path):
+ monkeypatch.setenv("LOCALAPPDATA", str(tmp_path))
+ monkeypatch.setenv("HOME", str(tmp_path))
+ monkeypatch.delenv("JARVIS_INSTANCE", raising=False)
+
+
+class _Scheduler:
+ def __init__(self, armed: int = 0, running: int = 0) -> None:
+ self._value = (armed, running)
+
+ def pending_work(self) -> tuple[int, int]:
+ return self._value
+
+
+class _Channels:
+ def __init__(self, *names: str) -> None:
+ self._names = list(names)
+
+ def started(self) -> list[str]:
+ return self._names
+
+
+def _state(*, armed: int = 0, running: int = 0, channels: tuple[str, ...] = ()) -> SimpleNamespace:
+ return SimpleNamespace(
+ task_scheduler=_Scheduler(armed, running), channel_manager=_Channels(*channels)
+ )
+
+
+def _cfg(*, keep: bool = True) -> SimpleNamespace:
+ return SimpleNamespace(background=SimpleNamespace(keep_agents_running=keep))
+
+
+# ---------------------------------------------------------------------------
+# What is worth keeping
+# ---------------------------------------------------------------------------
+
+
+def test_work_counts_routines_runs_and_channels() -> None:
+ work = bg.work_from_state(_state(armed=2, running=1, channels=("telegram",)))
+ assert work == bg.BackgroundWork(routines=2, running=1, channels=("telegram",))
+ assert work
+ assert "2 armed routine(s)" in work.describe()
+ assert "telegram" in work.describe()
+
+
+def test_no_scheduler_and_no_channels_is_no_work() -> None:
+ assert not bg.work_from_state(SimpleNamespace())
+ assert not bg.work_from_state(_state())
+
+
+def test_broken_scheduler_reads_as_no_routines() -> None:
+ class Broken:
+ def pending_work(self):
+ raise RuntimeError("store closed")
+
+ state = SimpleNamespace(task_scheduler=Broken(), channel_manager=_Channels("discord"))
+ assert bg.work_from_state(state) == bg.BackgroundWork(channels=("discord",))
+
+
+def test_keep_running_defaults_on() -> None:
+ assert bg.keep_running_enabled(SimpleNamespace()) is True
+ assert bg.keep_running_enabled(_cfg(keep=False)) is False
+
+
+def test_config_defaults() -> None:
+ from jarvis.core.config import JarvisConfig
+
+ cfg = JarvisConfig()
+ assert cfg.background.keep_agents_running is True
+ assert cfg.autostart.background_only is False
+
+
+# ---------------------------------------------------------------------------
+# Marker + handover request
+# ---------------------------------------------------------------------------
+
+
+def test_marker_round_trip_and_only_own_marker_is_cleared() -> None:
+ bg.write_marker(47821)
+ data = bg.read_marker()
+ assert data is not None and data["pid"] == os.getpid() and data["port"] == 47821
+ bg.clear_marker()
+ assert bg.read_marker() is None
+
+ bg._write_json(bg.marker_path(), {"pid": os.getpid() + 1, "port": 1})
+ bg.clear_marker()
+ assert bg.read_marker() is not None
+
+
+def test_service_pid_requires_a_live_service_process() -> None:
+ assert bg.service_pid(is_service=lambda _pid: True) is None
+ bg._write_json(bg.marker_path(), {"pid": 4242, "port": 1})
+ assert bg.service_pid(is_service=lambda pid: pid == 4242) == 4242
+ assert bg.service_pid(is_service=lambda _pid: False) is None
+
+
+def test_marker_paths_are_per_instance(monkeypatch) -> None:
+ default = bg.marker_path()
+ monkeypatch.setenv("JARVIS_INSTANCE", "dev")
+ assert bg.marker_path() != default
+ assert bg.handover_path().name.startswith("handover")
+
+
+def test_handover_request_expires() -> None:
+ assert not bg.handover_requested()
+ bg.request_handover()
+ assert bg.handover_requested()
+ mtime = bg.handover_path().stat().st_mtime
+ assert not bg.handover_requested(now=lambda: mtime + bg.HANDOVER_MAX_AGE_S + 1)
+ bg.clear_handover_request()
+ assert not bg.handover_requested()
+
+
+# ---------------------------------------------------------------------------
+# Command line
+# ---------------------------------------------------------------------------
+
+
+def test_source_command_runs_the_headless_launcher_as_service() -> None:
+ argv = bg.service_command(after_pid=42, executable="/usr/bin/python3", frozen=False)
+ assert argv[1:] == [
+ "-m",
+ "jarvis.ui.web.launcher",
+ "--headless",
+ bg.SERVICE_FLAG,
+ bg.AFTER_PID_FLAG,
+ "42",
+ ]
+
+
+def test_command_carries_the_instance(monkeypatch) -> None:
+ monkeypatch.setenv("JARVIS_INSTANCE", "dev")
+ argv = bg.service_command(after_pid=None, executable="/usr/bin/python3", frozen=False)
+ assert argv[-2:] == ["--instance", "dev"]
+
+
+def test_frozen_command_reenters_the_executable() -> None:
+ argv = bg.service_command(after_pid=7, executable="/opt/jarvis/Jarvis", frozen=True)
+ assert argv == ["/opt/jarvis/Jarvis", bg.SERVICE_FLAG, bg.AFTER_PID_FLAG, "7"]
+
+
+def test_after_pid_is_parsed() -> None:
+ from jarvis.ui.web import launcher
+
+ assert launcher._parse_args([bg.SERVICE_FLAG, bg.AFTER_PID_FLAG, "9"]).after_pid == 9
+
+
+# ---------------------------------------------------------------------------
+# Hand-off on quit
+# ---------------------------------------------------------------------------
+
+
+def spawned(monkeypatch):
+ calls: list[int | None] = []
+
+ def _spawn(*, after_pid):
+ calls.append(after_pid)
+ return True
+
+ monkeypatch.setattr(bg, "spawn_service", _spawn)
+ return calls
+
+
+def test_quit_with_work_starts_the_service_and_drops_a_stale_request(spawned) -> None:
+ bg.request_handover()
+ assert bg.hand_off_on_quit(_state(armed=1), _cfg(), pid=1234) is True
+ assert spawned == [1234]
+ assert not bg.handover_path().exists()
+
+
+def test_quit_without_work_starts_nothing(spawned) -> None:
+ assert bg.hand_off_on_quit(_state(), _cfg()) is False
+ assert spawned == []
+
+
+def test_quit_with_setting_off_starts_nothing(spawned) -> None:
+ assert bg.hand_off_on_quit(_state(channels=("telegram",)), _cfg(keep=False)) is False
+ assert spawned == []
+
+
+def test_dev_instance_never_hands_off(monkeypatch, spawned) -> None:
+ monkeypatch.setenv("JARVIS_INSTANCE", "dev")
+ assert bg.hand_off_on_quit(_state(armed=3), _cfg()) is False
+ assert spawned == []
+
+
+def test_desktop_skips_the_hand_off_on_restart(monkeypatch) -> None:
+ from jarvis.ui.desktop_app import DesktopApp
+
+ seen: list[object] = []
+ monkeypatch.setattr(bg, "hand_off_on_quit", lambda state, cfg: seen.append(state))
+ app = DesktopApp.__new__(DesktopApp)
+ state = _state(armed=1)
+ app._server = SimpleNamespace(app=SimpleNamespace(state=state), cfg=_cfg())
+ app.cfg = _cfg()
+
+ app._skip_background_handoff = True
+ app._hand_off_to_background_service()
+ assert seen == []
+
+ app._skip_background_handoff = False
+ app._hand_off_to_background_service()
+ assert seen == [state]
+
+
+# ---------------------------------------------------------------------------
+# Hand-back on launch
+# ---------------------------------------------------------------------------
+
+
+class _Busy(Exception):
+ pass
+
+
+class _Clock:
+ def __init__(self) -> None:
+ self.t = 0.0
+
+ def now(self) -> float:
+ return self.t
+
+ def sleep(self, seconds: float) -> None:
+ self.t += seconds
+
+
+def test_no_service_means_no_takeover() -> None:
+ def acquire():
+ raise AssertionError("must not touch the lock")
+
+ assert bg.take_over_from_service(acquire, busy_error=_Busy, find_pid=lambda: None) is None
+
+
+def test_service_hands_back_and_the_request_is_cleared() -> None:
+ clock = _Clock()
+ attempts: list[bool] = []
+
+ def acquire():
+ attempts.append(bg.handover_path().exists())
+ if len(attempts) < 3:
+ raise _Busy
+ return "lock"
+
+ lock = bg.take_over_from_service(
+ acquire, busy_error=_Busy, find_pid=lambda: 99, sleep=clock.sleep, now=clock.now
+ )
+ assert lock == "lock"
+ assert attempts == [True, True, True]
+ assert not bg.handover_path().exists()
+
+
+def test_service_that_never_lets_go_is_stopped() -> None:
+ clock = _Clock()
+ killed: list[int] = []
+
+ def acquire():
+ if not killed:
+ raise _Busy
+ return "lock"
+
+ lock = bg.take_over_from_service(
+ acquire,
+ busy_error=_Busy,
+ wait_s=2.0,
+ find_pid=lambda: 77,
+ alive=lambda _pid: True,
+ terminate=lambda pid: killed.append(pid) or True,
+ sleep=clock.sleep,
+ now=clock.now,
+ )
+ assert lock == "lock"
+ assert killed == [77]
+
+
+# ---------------------------------------------------------------------------
+# The service side (launcher)
+# ---------------------------------------------------------------------------
+
+
+def test_service_steps_aside_for_an_opening_desktop(monkeypatch) -> None:
+ from jarvis.ui import desktop_log
+ from jarvis.ui.web import launcher
+
+ monkeypatch.setattr(desktop_log, "_install_desktop_log_sink", lambda _path: None)
+ monkeypatch.setenv("JARVIS_VOICE", "1")
+ bg.request_handover()
+ args = launcher._parse_args([bg.SERVICE_FLAG])
+ assert launcher._prepare_background_service(args) is None
+ assert os.environ["JARVIS_VOICE"] == "0"
+
+
+def test_service_never_evicts_a_running_app(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")
+ calls: list[object] = []
+
+ def busy(**kwargs):
+ calls.append(kwargs["terminate"](1))
+ raise desktop_app.SingleInstanceError("Jarvis is already running (pid=1).")
+
+ monkeypatch.setattr(desktop_app, "acquire_single_instance_lock", busy)
+ assert launcher._prepare_background_service(launcher._parse_args([bg.SERVICE_FLAG])) is None
+ assert calls == [False]
+
+
+def test_background_service_flag_implies_headless() -> None:
+ from jarvis.ui.web import launcher
+
+ args = launcher._parse_args([bg.SERVICE_FLAG])
+ assert args.background_service is True
+
+
+def _run_watch(state, **kwargs) -> bool:
+ from jarvis.ui.web import launcher
+
+ async def scenario() -> bool:
+ stop = asyncio.Event()
+ try:
+ await asyncio.wait_for(
+ launcher._watch_background_service(state, stop, poll_s=0.01, **kwargs), 1.0
+ )
+ except TimeoutError:
+ return stop.is_set()
+ return stop.is_set()
+
+ return asyncio.run(scenario())
+
+
+def test_watch_stops_on_a_handover_request() -> None:
+ bg.request_handover()
+ assert _run_watch(_state(armed=1), idle_check_s=60.0) is True
+
+
+def test_watch_stops_when_the_work_is_gone() -> None:
+ assert _run_watch(_state(), idle_check_s=0.01, idle_strikes=2) is True
+
+
+def test_watch_keeps_running_while_there_is_work() -> None:
+ assert _run_watch(_state(channels=("telegram",)), idle_check_s=0.01, idle_strikes=1) is False
+
+
+def test_scheduler_reports_pending_work() -> None:
+ from jarvis.tasks.scheduler import TaskScheduler
+
+ scheduler = TaskScheduler.__new__(TaskScheduler)
+ scheduler._known = {"a", "b"}
+
+ class _Done:
+ def done(self) -> bool:
+ return True
+
+ class _Live:
+ def done(self) -> bool:
+ return False
+
+ scheduler._runner_tasks = {_Done(), _Live()}
+ assert scheduler.pending_work() == (2, 1)
+
+
+# ---------------------------------------------------------------------------
+# Login entry
+# ---------------------------------------------------------------------------
+
+
+def _autostart_cfg(*, background_only: bool) -> SimpleNamespace:
+ return SimpleNamespace(
+ autostart=SimpleNamespace(
+ enabled=True, start_minimized=False, background_only=background_only
+ )
+ )
+
+
+def test_login_entry_starts_only_the_service_when_asked(monkeypatch) -> None:
+ from jarvis.autostart.command import LAUNCHER_MODULE, resolve_launch_spec
+
+ monkeypatch.setattr(sys, "platform", "linux")
+ assert resolve_launch_spec(_autostart_cfg(background_only=False)).args == (
+ "-m",
+ LAUNCHER_MODULE,
+ )
+ assert resolve_launch_spec(_autostart_cfg(background_only=True)).args == (
+ "-m",
+ LAUNCHER_MODULE,
+ bg.SERVICE_FLAG,
+ )
+
+
+def test_macos_login_entry_passes_the_flag_through_launchservices(monkeypatch, tmp_path) -> None:
+ import jarvis.setup.macos_app_bundle as bundle_module
+ from jarvis.autostart.command import resolve_launch_spec
+
+ bundle = tmp_path / "Personal Jarvis.app"
+ monkeypatch.setattr(sys, "platform", "darwin")
+ monkeypatch.setattr(bundle_module, "macos_app_bundle_path", lambda: bundle)
+ monkeypatch.setattr(bundle_module, "macos_app_bundle_is_launchable", lambda _b: True)
+ spec = resolve_launch_spec(_autostart_cfg(background_only=True))
+ assert spec.args == ("-g", "-W", "-a", str(bundle), "--args", bg.SERVICE_FLAG)
+
+
+# ---------------------------------------------------------------------------
+# Settings route
+# ---------------------------------------------------------------------------
+
+
+def test_settings_route_reports_and_persists(monkeypatch) -> None:
+ from fastapi import FastAPI
+ from fastapi.testclient import TestClient
+
+ from jarvis.core import config_writer
+ from jarvis.ui.web import settings_routes
+
+ writes: list[tuple[str, bool]] = []
+ monkeypatch.setattr(
+ config_writer, "set_background_keep_running", lambda v: writes.append(("keep", v))
+ )
+ app = FastAPI()
+ app.include_router(settings_routes.router)
+ app.state.config = SimpleNamespace(
+ background=SimpleNamespace(keep_agents_running=True),
+ autostart=SimpleNamespace(enabled=False, background_only=False),
+ )
+ app.state.task_scheduler = _Scheduler(armed=2)
+ app.state.channel_manager = _Channels("telegram")
+ client = TestClient(app)
+
+ body = client.get("/api/settings/background").json()
+ assert body["keep_agents_running"] is True
+ assert body["work"] == {"routines": 2, "running": 0, "channels": ["telegram"]}
+ assert body["supported"] is True
+
+ body = client.put("/api/settings/background", json={"keep_agents_running": False}).json()
+ assert writes == [("keep", False)]
+ assert body["keep_agents_running"] is False
+
+
+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