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.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
"""`jarvis update` — the terminal twin of the in-app update button."""
from __future__ import annotations
import json
import os
import subprocess
import sys
from pathlib import Path
import pytest
from dodaios.cli import app_update
from dodaios.cli.app_update import (
EXIT_APP_RUNNING,
EXIT_FAILED,
EXIT_NOT_UPDATABLE,
FINALIZE_FLAG,
PROBE_FLAG,
run_update,
)
from dodaios.core.process_utils import NO_WINDOW_CREATIONFLAGS
from dodaios.ui.relauncher import UPDATE_RESULT_FILENAME
class FakeChildren:
"""Answers the child processes run_update would spawn."""
def __init__(self, *, status: dict, stage: dict | None = None, finalize_rc: int = 0,
on_finalize=None) -> None:
self.status = status
self.stage = stage
self.finalize_rc = finalize_rc
self.on_finalize = on_finalize
self.calls: list[tuple[list[str], float | None, bool]] = []
def __call__(self, args: list[str], timeout: float | None, detached: bool):
self.calls.append((args, timeout, detached))
if args == [PROBE_FLAG, "status"]:
return 0, "log noise\n" + json.dumps(self.status) + "\n"
if args == [PROBE_FLAG, "stage"]:
return 0, json.dumps(self.stage or {}) + "\n"
if args[0] == FINALIZE_FLAG:
if self.on_finalize is not None:
self.on_finalize(Path(args[1]))
return self.finalize_rc, ""
raise AssertionError(f"unexpected child {args}")
def modes(self) -> list[str]:
return [args[1] if args[0] == PROBE_FLAG else "finalize" for args, _, _ in self.calls]
def _status(**overrides) -> dict:
base = {
"managed": True,
"kind": "managed",
"current": "2.8.0",
"latest": "2.9.0",
"update_available": True,
"service_pid": None,
}
return {**base, **overrides}
def _run(children: FakeChildren, **kwargs) -> int:
kwargs.setdefault("is_frozen", lambda: False)
kwargs.setdefault("running_app_pid", lambda: None)
kwargs.setdefault("interactive", False)
return run_update(run_child=children, **kwargs)
def _write_result(root: Path, **payload) -> None:
(root / UPDATE_RESULT_FILENAME).write_text(json.dumps(payload), encoding="utf-8")
def test_frozen_install_points_to_the_in_app_button(capsys):
children = FakeChildren(status=_status())
assert _run(children, is_frozen=lambda: True) == EXIT_NOT_UPDATABLE
assert children.calls == []
assert "Settings -> Update" in capsys.readouterr().out
def test_dev_checkout_is_never_updated(capsys):
children = FakeChildren(status=_status(managed=False, kind="dev"))
assert _run(children) == EXIT_NOT_UPDATABLE
assert children.modes() == ["status"]
assert "git pull" in capsys.readouterr().out
def test_already_current_changes_nothing(capsys):
children = FakeChildren(status=_status(latest="2.8.0", update_available=False))
assert _run(children) == 0
assert children.modes() == ["status"]
assert "already the newest version" in capsys.readouterr().out
def test_check_only_reports_and_stops(capsys):
children = FakeChildren(status=_status())
assert _run(children, check_only=True) == 0
assert children.modes() == ["status"]
assert "2.9.0 is available" in capsys.readouterr().out
def test_offline_check_fails_honestly(capsys):
children = FakeChildren(status=_status(latest=None, update_available=False, check_failed=True))
assert _run(children) == EXIT_FAILED
assert "Could not reach GitHub" in capsys.readouterr().err
def test_running_app_blocks_the_update(capsys):
children = FakeChildren(status=_status())
assert _run(children, running_app_pid=lambda: 4242) == EXIT_APP_RUNNING
assert children.modes() == ["status"]
assert "click Update inside the app" in capsys.readouterr().err
def test_background_service_is_asked_to_hand_back(tmp_path):
stopped: list[int] = []
children = FakeChildren(
status=_status(service_pid=777),
stage={"ok": True, "root": str(tmp_path), "version": "2.9.0"},
on_finalize=lambda root: _write_result(root, ok=True, rolled_back=False),
)
rc = _run(
children,
running_app_pid=lambda: 777,
stop_service=lambda pid: stopped.append(pid) or True,
)
assert rc == 0
assert stopped == [777]
assert children.modes() == ["status", "stage", "finalize"]
def test_service_that_will_not_stop_blocks_the_update():
children = FakeChildren(status=_status(service_pid=777))
rc = _run(children, running_app_pid=lambda: 777, stop_service=lambda pid: False)
assert rc == EXIT_APP_RUNNING
assert children.modes() == ["status"]
def test_successful_update_finalizes_detached(tmp_path, capsys):
children = FakeChildren(
status=_status(),
stage={"ok": True, "root": str(tmp_path), "version": "2.9.0"},
on_finalize=lambda root: _write_result(root, ok=True, rolled_back=False),
)
assert _run(children) == 0
finalize_args, timeout, detached = children.calls[-1]
assert finalize_args == [FINALIZE_FLAG, str(tmp_path)]
assert timeout is None and detached is True
assert "2.9.0 is installed" in capsys.readouterr().out
def test_stage_failure_installs_nothing(capsys):
children = FakeChildren(
status=_status(), stage={"ok": False, "error": "git fetch failed: offline"}
)
assert _run(children) == EXIT_FAILED
assert children.modes() == ["status", "stage"]
err = capsys.readouterr().err
assert "git fetch failed" in err
assert "Nothing was changed" in err
def test_failed_install_reports_the_rollback(tmp_path, capsys):
children = FakeChildren(
status=_status(),
stage={"ok": True, "root": str(tmp_path), "version": "2.9.0"},
finalize_rc=1,
on_finalize=lambda root: _write_result(root, ok=False, rolled_back=True),
)
assert _run(children) == EXIT_FAILED
assert "went back to 2.8.0" in capsys.readouterr().err
def test_failed_install_without_rollback_names_the_repair(tmp_path, capsys):
children = FakeChildren(
status=_status(),
stage={"ok": True, "root": str(tmp_path), "version": "2.9.0"},
finalize_rc=1,
on_finalize=lambda root: _write_result(root, ok=False, rolled_back=False),
)
assert _run(children) == EXIT_FAILED
assert "install/install." in capsys.readouterr().err
def test_unreadable_child_output_is_a_failure(capsys):
def broken(args, timeout, detached):
return 1, "Traceback (most recent call last): ..."
assert run_update(
run_child=broken, is_frozen=lambda: False, running_app_pid=lambda: None,
interactive=False,
) == EXIT_FAILED
@pytest.mark.parametrize("argv", [[], ["--probe"], ["--probe", "nope"], ["--finalize"]])
def test_child_entry_rejects_unknown_arguments(argv):
assert app_update._child_main(argv) == 2
def test_last_json_skips_log_lines():
assert app_update._last_json('INFO x\n{"a": 1}\n\n') == {"a": 1}
assert app_update._last_json("no json here") is None
def test_jarvis_main_routes_update(monkeypatch):
import dodaios.__main__ as entry
seen: list[bool] = []
monkeypatch.setattr(
app_update, "run_update", lambda check_only=False: seen.append(check_only) or 0
)
assert entry.main(["update", "--check"]) == 0
assert seen == [True]
def test_service_without_a_session_file_is_still_stopped(tmp_path):
"""A live service with a missing session.json must not stay up through
the reinstall, where it would hold the venv's native modules open."""
stopped: list[int] = []
children = FakeChildren(
status=_status(service_pid=777),
stage={"ok": True, "root": str(tmp_path), "version": "2.9.0"},
on_finalize=lambda root: _write_result(root, ok=True, rolled_back=False),
)
rc = _run(
children,
running_app_pid=lambda: None,
stop_service=lambda pid: stopped.append(pid) or True,
)
assert rc == 0
assert stopped == [777]
def test_stale_result_from_an_earlier_run_is_not_reported(tmp_path, capsys):
_write_result(tmp_path, ok=False, rolled_back=True)
children = FakeChildren(
status=_status(),
stage={"ok": True, "root": str(tmp_path), "version": "2.9.0"},
finalize_rc=1, # the finalize child died without writing a result
)
assert _run(children) == EXIT_FAILED
err = capsys.readouterr().err
assert "went back to" not in err
assert "could not be restored automatically" in err
# --------------------------------------------------------------------------- #
# Nothing is imported from the package once the install step has run
# --------------------------------------------------------------------------- #
_AFTER_INSTALL_DRIVER = r"""
import importlib.abc
import json
import sys
from pathlib import Path
from dodaios.cli import app_update
from dodaios.cli.app_update import FINALIZE_FLAG, PROBE_FLAG
from dodaios.core.branding import LEGACY_PACKAGE_NAMES
root = Path(sys.argv[1])
outcome = json.loads(sys.argv[2])
# Every name the package can be imported as: the one it has here, and the
# earlier ones that still resolve to it.
PACKAGE_NAMES = {app_update.__name__.partition(".")[0], *LEGACY_PACKAGE_NAMES}
class PackageIsGone(importlib.abc.MetaPathFinder):
def __init__(self):
self.late = []
def find_spec(self, name, path=None, target=None):
if name.partition(".")[0] in PACKAGE_NAMES:
self.late.append(name)
raise ModuleNotFoundError(f"No module named {name!r}", name=name)
return None
guard = PackageIsGone()
def run_child(args, timeout, detached):
if args == [PROBE_FLAG, "status"]:
return 0, json.dumps(
{
"managed": True,
"kind": "managed",
"current": "2.8.0",
"latest": "2.9.0",
"update_available": True,
"service_pid": None,
}
)
if args == [PROBE_FLAG, "stage"]:
return 0, json.dumps({"ok": True, "root": str(root), "version": "2.9.0"})
if args[0] == FINALIZE_FLAG:
# The install step replaced the checkout: the release it installed may
# keep its package somewhere else entirely.
(root / ".jarvis-update-result.json").write_text(json.dumps(outcome), encoding="utf-8")
sys.meta_path.insert(0, guard)
return (0 if outcome["ok"] else 1), ""
raise AssertionError(args)
rc = app_update.run_update(
run_child=run_child,
is_frozen=lambda: False,
running_app_pid=lambda: None,
interactive=False,
)
print("RESULT " + json.dumps({"rc": rc, "late": guard.late}))
"""
@pytest.mark.parametrize(
("outcome", "expected_rc", "expected_text"),
[
({"ok": True, "rolled_back": False}, 0, "2.9.0 is installed"),
({"ok": False, "rolled_back": True}, EXIT_FAILED, "went back to 2.8.0"),
],
)
def test_nothing_is_imported_from_the_package_after_the_install_step(
tmp_path, outcome, expected_rc, expected_text
):
"""The parent outlives the install, and must not read the new tree's code.
Run in a fresh interpreter so only what ``jarvis update`` itself loaded is
in memory. From the install step on, importing a not-yet-loaded ``jarvis``
module fails as it would after the package moved, and is recorded.
"""
proc = subprocess.run( # noqa: S603 - this interpreter, test-controlled script
[sys.executable, "-c", _AFTER_INSTALL_DRIVER, str(tmp_path), json.dumps(outcome)],
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
timeout=180,
cwd=str(Path(__file__).resolve().parents[3]),
env={**os.environ, "PYTHONIOENCODING": "utf-8"},
creationflags=NO_WINDOW_CREATIONFLAGS,
)
assert proc.returncode == 0, proc.stderr[-4000:]
result = json.loads(
next(
line for line in reversed(proc.stdout.splitlines()) if line.startswith("RESULT ")
).removeprefix("RESULT ")
)
assert result == {"rc": expected_rc, "late": []}
assert expected_text in proc.stdout + proc.stderr