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(update): let a release tell the previous version where its files live (#567)

Ruben Lütke57940b3c0c87
diff --git a/docs/desktop-installers.md b/docs/desktop-installers.md
index 7e55ed0598..515580a7b8 100644
--- a/docs/desktop-installers.md
+++ b/docs/desktop-installers.md
@@ -280,9 +280,12 @@ switch between them.
For a frozen install (`jarvis/core/installer_update.py`):
-1. **Pick the asset.** OS plus CPU architecture map to exactly one name from the
- table in section 1. No mapping (Windows on ARM, Linux on aarch64) means the
- button never appears.
+1. **Pick the asset.** OS plus CPU architecture map to one row of
+ `INSTALLER_ASSET_NAMES` in `jarvis/core/installer_update.py`: the name from
+ the table in section 1, and the same file under the `Dodaios-` prefix. The
+ updater takes the first accepted name a release carries; when a release
+ carries more than one, the first that `installers-SHA256SUMS.txt` lists. No
+ mapping (Windows on ARM, Linux on aarch64) means the button never appears.
2. **Refuse to offer what cannot be installed.** `status` reports
`update_available: true` only when the release actually carries both this
platform's installer and `installers-SHA256SUMS.txt`. Status is fail-open:
@@ -297,7 +300,15 @@ For a frozen install (`jarvis/core/installer_update.py`):
Manager closes the app, the files are replaced, the app comes back.
- macOS: `hdiutil attach` the DMG, swap the running `.app` with two renames
on one filesystem (the old bundle is put back if the second rename fails),
- `hdiutil detach`, relaunch with `open`.
+ `hdiutil detach`, relaunch with `open`. The swap is in place whenever the
+ disk image carries the app under the running bundle's name or under the
+ name this version ships with, so a bundle the user renamed or duplicated
+ in Finder is updated where it is. Only a disk image whose bundle has a
+ name this version has never used counts as a renamed app: it is installed
+ beside the running bundle under its own name and relaunched from there.
+ The superseded bundle is removed only after that copy is complete and
+ only when its `CFBundleIdentifier` is one of ours; an unrelated app that
+ already has the new name is never overwritten.
- Linux: copy the new AppImage next to the running one, `chmod +x`,
`os.replace` onto `$APPIMAGE` (atomic), relaunch.
@@ -308,6 +319,51 @@ still holds - but the honest answer is "no restart needed from you".
Managed installs keep today's behaviour untouched: the frozen branch is entered
only when `is_frozen()` is true, and the frozen branch never runs git.
+A managed update is applied by the restart helper of the version that is being
+replaced: it resets the checkout to the new revision, runs that revision's
+installer, verifies its UI bundle and starts it. The helper does not assume the
+new tree looks like its own. Each release states where it keeps its UI bundle,
+launcher module, version file, config file and macOS app bundle (name and
+bundle identifier) in
+`install/update-contract.json` (reader: `jarvis/core/update_contract.py`), and
+the helper reads the contract of whichever tree is checked out at that moment -
+the target after the reset, the previous one after a rollback. A tree without
+the file, or with one that fails validation (unknown schema, a path that leaves
+the checkout), is treated as using the default locations, so a wrong contract
+fails the bundle check and rolls back. A contract may name a `rollback_hook`: a
+tracked script of the new release that runs when its install failed, before
+the checkout returns to the previous revision.
+
+Re-running the one-line installer over an existing install downloads first
+(a fetch only writes inside `.git`), then stops every app running out of that
+install right before it resets the checkout, and again before it rebuilds the
+environment. A failed download therefore leaves the app running. The path that
+moves a broken install aside asks the download server first (`git ls-remote`,
+then a plain HTTPS request for the hosted repository, because the archive
+download still works where git is blocked) and changes nothing while it is out
+of reach. Started from a terminal inside the app, the installer
+refuses before it stops anything: its own parent processes run out of the
+install's environment, so stopping the app would end the installer with it.
+
+Known limits of the update contract. These names are not part of it, so a
+release that changes one has to keep the old one working for the update that
+crosses it:
+
+- the Windows launcher copy the desktop app runs as
+ (`WINDOWS_BRANDED_LAUNCHER_FILE_NAME`) and its one-process loop guard, the
+ environment variable `JARVIS_BRANDED_LAUNCH`
+ (`WINDOWS_BRANDED_LAUNCH_ENV_VAR`). The helper starts the new launcher
+ module through the old copy when one still exists, otherwise through the
+ interpreter;
+- the launcher module written into autostart entries and shortcuts
+ (`LAUNCHER_MODULE` in `jarvis/autostart/command.py`, `_LAUNCHER_MODULE` in
+ `jarvis/ui/icon_utils.py`). The helper rewrites neither: shortcuts are
+ renewed by the installer of the new release, the autostart entry by the new
+ app when it first starts;
+- processes of the old version that outlive the app window, such as the
+ terminal host (`jarvis.terminal.pty_host`), which keeps running the old code
+ until it is stopped. The helper waits for the app process only.
+
---
## 7. What an uninstall keeps
diff --git a/docs/os-parity.md b/docs/os-parity.md
index 301ea8511b..075f9c5d60 100644
--- a/docs/os-parity.md
+++ b/docs/os-parity.md
@@ -1375,6 +1375,37 @@ script compiled twice and upgraded over a running install
Windows, Apple Silicon and Intel macOS. Still not run against a real released
build: the first release with this code needs one live update per OS.
+**Updating across a moved tree (2026-10-12).** The version being replaced
+applies the update, so it reads where the new release keeps things from that
+release's `install/update-contract.json` instead of assuming its own layout
+(`docs/desktop-installers.md` section 6). Per OS: the restart helper starts the
+launcher module the installed tree names (Linux directly, Windows through the
+branded launcher when one exists, macOS through the app bundle the tree names,
+looked up next to the known bundle and in both Applications folders and taken
+only when it carries the bundle identifier the tree names). The
+helper loads every package module it still needs before it resets the
+checkout; a fresh-interpreter test fails if a later code path imports one. A
+frozen install accepts each installer under two file names per platform. On
+macOS a disk image is swapped in place when it carries the app under the
+running bundle's name or the name this version ships with (a bundle the user
+renamed stays where it is); only a name this version has never used is
+installed beside the running app, and the superseded bundle removed only when
+its bundle identifier is ours.
+`install.sh` (`pkill -f <venv>`, plus `launchctl unload` on macOS) and
+`install.ps1` (every process whose image lives in the install's venv) stop the
+running app after the fetch and right before they reset the checkout. Both
+refuse, before stopping anything, when one of the installer's own parent
+processes belongs to that install (`ps` ancestor walk on POSIX, the
+`ParentProcessId` chain on Windows), which is what a terminal inside the app
+looks like. Covered by
+`tests/unit/core/test_update_contract.py`,
+`tests/unit/ui/test_relauncher_update_contract.py` (a real git checkout whose
+new release moved its package, including the rollback),
+`tests/unit/core/test_installer_update.py` and
+`tests/unit/install/test_install_stops_app_first.py` (real processes on
+Windows and POSIX). Not verified on hardware: the macOS bundle rename and the
+macOS restart through a renamed bundle run only against fakes.
+
| # | Impact | Area | Gap | Evidence | Behavior off-Windows |
|---|---|---|---|---|---|
| P-38 | Medium | Native installer / desktop window | The Linux AppImage and `.deb` have **no native desktop window**. Windows (WebView2) and macOS (WKWebView) get one from the frozen bundle; Linux does not, because pywebview's GTK backend needs PyGObject and a frozen interpreter can never import the distribution's `python3-gi` (it is compiled against the system CPython), while bundling GTK 3 + WebKit2GTK portably means shipping its helper processes, GIO modules, pixbuf loaders, GSettings schemas and typelibs. The Qt route is also closed today: the `[desktop]` extra installs `pyside6-essentials`, which has no QtWebEngine, and `jarvis.spec` excludes PySide6 outright. Adding `pyside6-addons` and dropping that exclusion is the realistic fix, at roughly +400 MB | `packaging/linux/README.md` ("The window question"), `jarvis/ui/desktop_app.py::_degrade_to_browser_ui`, `jarvis.spec` `excludes`, `pyproject.toml` `[desktop]` | Linux: honest degradation, verified against a real build — the app catches pywebview's `WebViewException`, keeps the backend serving, and `AppRun` waits for `/api/health` and opens the interface with `xdg-open`. Everything except the window frame works, including the whole CLI. A source/pipx install on a Linux desktop with `python3-gi` + `gir1.2-webkit2-4.1` still gets the native window; only the frozen build does not. Sub-gap: the app's fallback message advises installing those system packages, which does not help a frozen build |
diff --git a/install/install.ps1 b/install/install.ps1
index fd82f59a22..a01d310892 100644
--- a/install/install.ps1
+++ b/install/install.ps1
@@ -641,12 +641,45 @@ function Invoke-FetchPayload {
return $false
}
+# Nothing is stopped or moved until the download server answers. Without a
+# connection the fresh copy cannot arrive, and an install that was moved aside
+# for nothing is worse than one that simply was not updated.
+# git is asked first. A network that lets no git transfer through still reaches
+# the archive download the installer falls back to, so a plain HTTPS answer
+# from the same host counts as well.
+# (POSIX twin: the salvage-guard block in install.sh.)
+function Test-RepositoryReachable {
+ # git reports an unreachable repository on stderr, which Windows PowerShell
+ # turns into a terminating error under 'Stop'. The exit code is the answer.
+ $PreviousPreference = $ErrorActionPreference
+ $ErrorActionPreference = 'Continue'
+ try {
+ & git @GitNetOpts ls-remote --quiet --heads $RepoUrl 2>&1 | Out-Null
+ if ($LASTEXITCODE -eq 0) { return $true }
+ if ($RepoUrl -notmatch 'github\.com/') { return $false }
+ if (-not (Get-Command curl.exe -ErrorAction SilentlyContinue)) { return $false }
+ $ProbePath = ($RepoUrl -split 'github\.com/', 2)[1] -replace '\.git$', ''
+ & curl.exe -fsIL --max-time 20 "https://github.com/$ProbePath" 2>&1 | Out-Null
+ return ($LASTEXITCODE -eq 0)
+ } catch {
+ return $false
+ } finally {
+ $ErrorActionPreference = $PreviousPreference
+ }
+}
+
# Self-heal a broken install dir (leftover non-git folder from an earlier or
# aborted install, or a checkout whose git state no longer updates): keep the
# old tree as a timestamped sibling backup - never delete - clone fresh, then
# carry the user's local state (data/, jarvis.toml, .env) into the new
# checkout. A stale folder must never require manual cleanup to install.
function Invoke-SalvageReclone {
+ if (-not (Test-RepositoryReachable)) {
+ Write-Err 'cannot reach the download server right now - nothing was changed.'
+ Write-Note 'Check your internet connection (Wi-Fi, VPN, proxy), then re-run the installer.'
+ exit 1
+ }
+ Stop-RunningApp
$StaleBackup = "$InstallDir.stale-$(Get-Date -Format 'yyyyMMdd-HHmmss')"
try {
Move-Item -LiteralPath $InstallDir -Destination $StaleBackup -ErrorAction Stop
@@ -707,6 +740,78 @@ function Update-LegacyOrigin {
}
}
+# Stop any Jarvis still running out of THIS install. Called before the
+# checkout is replaced and again before its environment is rebuilt: a release
+# may move or delete files the live app still loads, and an app left running
+# across that keeps serving a half-old, half-new program until it falls over.
+# On Windows the running interpreter additionally holds venv DLLs open, which
+# can make pip's in-place upgrade fail.
+#
+# Every process whose image lives in this install's venv is stopped, whatever
+# it is called: the desktop app usually runs as the branded launcher copy
+# beside python.exe, not as python.exe itself. Best-effort: a lookup or stop
+# failure never blocks the install. Safe to call twice - the second call finds
+# nothing left to stop. (POSIX twin: stop_running_app in install.sh.)
+function Stop-RunningApp {
+ $StopVenv = Join-Path $InstallDir '.venv'
+ if (-not (Test-Path (Join-Path $StopVenv 'Scripts\python.exe'))) { return }
+ $StartedInsideApp = $false
+ try {
+ $venvPrefix = $StopVenv.TrimEnd('\') + '\'
+ $all = @(Get-CimInstance Win32_Process -ErrorAction Stop)
+ $stale = @($all |
+ Where-Object {
+ $_.ExecutablePath -and
+ $_.ExecutablePath.StartsWith($venvPrefix, [System.StringComparison]::OrdinalIgnoreCase) -and
+ $_.ProcessId -ne $PID
+ })
+ if ($stale.Count -gt 0) {
+ # The installer refuses to do this to itself. Started from a
+ # terminal inside the app, its own parents (the pane's console
+ # host, the terminal host, the app) run out of this venv; stopping
+ # them would end the installer mid-way with the app gone and
+ # nothing installed.
+ $staleIds = @{}
+ foreach ($proc in $stale) { $staleIds[[int]$proc.ProcessId] = $true }
+ $byId = @{}
+ foreach ($proc in $all) { $byId[[int]$proc.ProcessId] = $proc }
+ $seen = @{}
+ $cursor = $byId[[int]$PID]
+ while ($cursor -and -not $seen.ContainsKey([int]$cursor.ProcessId)) {
+ $seen[[int]$cursor.ProcessId] = $true
+ $parent = $byId[[int]$cursor.ParentProcessId]
+ # Windows reuses process ids: a "parent" that started after its
+ # child is an unrelated process that inherited the number.
+ if (-not $parent -or $parent.CreationDate -gt $cursor.CreationDate) { break }
+ if ($staleIds.ContainsKey([int]$parent.ProcessId)) { $StartedInsideApp = $true; break }
+ $cursor = $parent
+ }
+ }
+ # A refusal is reported below, outside this try: its catch would turn
+ # it into "could not check" and carry on.
+ if (-not $StartedInsideApp -and $stale.Count -gt 0) {
+ foreach ($proc in $stale) {
+ try { Stop-Process -Id $proc.ProcessId -Force -ErrorAction Stop } catch {}
+ }
+ # Give the OS a beat to release file handles before files change.
+ Start-Sleep -Milliseconds 500
+ Write-Note 'stopped the running Jarvis app for the update'
+ }
+ } catch {
+ Write-Note 'could not check for a running Jarvis app - continuing'
+ }
+ if ($StartedInsideApp) {
+ Write-Err 'this installer was started from inside the running app.'
+ Write-Note 'Updating stops the app, which would end this installer with it.'
+ Write-Note 'Nothing was changed. Run the install command again from a normal'
+ Write-Note 'terminal outside the app.'
+ exit 1
+ }
+}
+
+# The fetch only writes inside .git, so the app keeps running through it: a
+# failed download (offline, an outage) then leaves a working app behind. It is
+# stopped at the last moment, right before the files it runs from change.
if (Test-Path (Join-Path $InstallDir '.git')) {
Update-LegacyOrigin
$UpdateOk = $true
@@ -715,6 +820,7 @@ if (Test-Path (Join-Path $InstallDir '.git')) {
& git @GitNetOpts fetch $GitVerbosity --depth 1 origin $Branch
if ($LASTEXITCODE -ne 0) { $UpdateOk = $false }
if ($UpdateOk) {
+ Stop-RunningApp
& git checkout --quiet $Branch
if ($LASTEXITCODE -ne 0) { $UpdateOk = $false }
}
@@ -804,32 +910,10 @@ $VenvPython = Join-Path $VenvPath 'Scripts\python.exe'
# touch its environment. A live app (often revived by the login autostart)
# keeps serving stale, half-updated features while pip rewrites the venv
# under it - the "app is already open but nothing works yet" field report
-# (2026-07-14; POSIX twin: the pkill block in install.sh). On Windows the
-# running pythonw.exe additionally holds venv DLLs open, which can make
-# pip's in-place upgrade fail. The installer relaunches a fresh instance
-# as its very last step. Best-effort: a lookup/stop failure never blocks
-# the install.
-if (Test-Path $VenvPython) {
- try {
- $venvPrefix = $VenvPath.TrimEnd('\') + '\'
- $stale = @(Get-CimInstance Win32_Process -Filter "Name='python.exe' OR Name='pythonw.exe'" -ErrorAction Stop |
- Where-Object {
- $_.ExecutablePath -and
- $_.ExecutablePath.StartsWith($venvPrefix, [System.StringComparison]::OrdinalIgnoreCase) -and
- $_.ProcessId -ne $PID
- })
- if ($stale.Count -gt 0) {
- foreach ($proc in $stale) {
- try { Stop-Process -Id $proc.ProcessId -Force -ErrorAction Stop } catch {}
- }
- # Give the OS a beat to release file handles before pip writes.
- Start-Sleep -Milliseconds 500
- Write-Note 'stopped the running Jarvis app for the update'
- }
- } catch {
- Write-Note 'could not check for a running Jarvis app - continuing'
- }
-}
+# (2026-07-14). The installer relaunches a fresh instance as its very last
+# step. The app was already stopped once before the checkout was replaced;
+# this second call catches one the login autostart revived in between.
+Stop-RunningApp
if (-not (Test-Path $VenvPython)) {
& $pythonExe -m venv $VenvPath
diff --git a/install/install.sh b/install/install.sh
index c61ee0071b..cbbb67e0b6 100755
--- a/install/install.sh
+++ b/install/install.sh
@@ -1037,6 +1037,35 @@ fetch_payload() {
# checkout. A stale folder must never require manual cleanup to install.
salvage_reclone() {
local stale_backup
+ # --- salvage-guard begin (extracted by tests/unit/install/test_install_stops_app_first.py)
+ # Nothing is stopped or moved until the download server answers. Without a
+ # connection the fresh copy cannot arrive, and an install that was moved
+ # aside for nothing is worse than one that simply was not updated.
+ # git is asked first. A network that lets no git transfer through still
+ # reaches the archive download the installer falls back to, so a plain
+ # HTTPS answer from the same host counts as well.
+ _reachable=0
+ # shellcheck disable=SC2086 # GIT_NET_OPTS must word-split into -c pairs
+ if git $GIT_NET_OPTS ls-remote --quiet --heads "$REPO_URL" >/dev/null 2>&1; then
+ _reachable=1
+ else
+ case "$REPO_URL" in
+ *github.com/*)
+ _probe_path="${REPO_URL#*github.com/}"
+ if command -v curl >/dev/null 2>&1 \
+ && curl -fsIL --max-time 20 "https://github.com/${_probe_path%.git}" >/dev/null 2>&1; then
+ _reachable=1
+ fi
+ ;;
+ esac
+ fi
+ if [ "$_reachable" -ne 1 ]; then
+ err 'cannot reach the download server right now - nothing was changed.'
+ note 'Check your internet connection (Wi-Fi, VPN, proxy), then re-run the installer.'
+ exit 1
+ fi
+ stop_running_app
+ # --- salvage-guard end
stale_backup="${INSTALL_DIR%/}.stale-$(date +%Y%m%d-%H%M%S)"
if ! mv "$INSTALL_DIR" "$stale_backup"; then
err "cannot move the broken install dir aside ($INSTALL_DIR -> $stale_backup)."
@@ -1100,10 +1129,71 @@ retarget_legacy_origin() {
# --- retarget-legacy-origin end
}
+# Stop any Jarvis still running out of THIS install. Called right before the
+# checkout is replaced and again before its environment is rebuilt: a release
+# may move or delete files the live app still loads, and an app left running
+# across that keeps serving a half-old, half-new program until it falls over.
+# Safe to call twice - the second call finds nothing left to stop.
+#
+# The installer refuses to do this to itself. Started from a terminal inside
+# the app, its own parents run out of this install's environment; stopping
+# them would end the installer mid-way with the app gone and nothing
+# installed. It stops BEFORE anything was touched and says where to run it.
+stop_running_app() {
+ # --- stop-running-app begin (extracted by tests/unit/install/test_install_stops_app_first.py)
+ _stop_venv="$INSTALL_DIR/.venv"
+ if [ -x "$_stop_venv/bin/python" ]; then
+ _stop_pid=$$
+ _stop_depth=0
+ while [ -n "$_stop_pid" ] && [ "$_stop_pid" -gt 1 ] 2>/dev/null && [ "$_stop_depth" -lt 32 ]; do
+ # -ww: BSD ps cuts the command line at the terminal width, and
+ # the stop below matches against the whole of it.
+ _stop_args="$(ps -ww -o args= -p "$_stop_pid" 2>/dev/null || true)"
+ case "$_stop_args" in
+ *"$_stop_venv"*)
+ err 'this installer was started from inside the running app.'
+ note 'Updating stops the app, which would end this installer with it.'
+ note 'Nothing was changed. Run the install command again from a normal'
+ note 'terminal outside the app.'
+ exit 1
+ ;;
+ esac
+ _stop_parent="$(ps -o ppid= -p "$_stop_pid" 2>/dev/null | tr -d ' ' || true)"
+ [ "$_stop_parent" = "$_stop_pid" ] && break
+ _stop_pid="$_stop_parent"
+ _stop_depth=$((_stop_depth + 1))
+ done
+ _stop_found=0
+ if pkill -f "$_stop_venv" 2>/dev/null; then
+ _stop_found=1
+ note 'stopped the running Jarvis app for the update'
+ fi
+ if [ "$(uname -s 2>/dev/null)" = "Darwin" ]; then
+ launchctl unload "$HOME/Library/LaunchAgents/${MACOS_AUTOSTART_LABEL}.plist" >/dev/null 2>&1 || true
+ fi
+ if [ "$_stop_found" -eq 1 ]; then
+ # The signal only asks. Give the app a moment to be gone before
+ # its files change under it; an app that ignores it is not waited
+ # for longer than five seconds.
+ _stop_ticks=0
+ while [ "$_stop_ticks" -lt 50 ] && pgrep -f "$_stop_venv" >/dev/null 2>&1; do
+ sleep 0.1
+ _stop_ticks=$((_stop_ticks + 1))
+ done
+ fi
+ fi
+ # --- stop-running-app end
+ return 0
+}
+
+# The fetch only writes inside .git, so the app keeps running through it: a
+# failed download (offline, an outage) then leaves a working app behind. It is
+# stopped at the last moment, right before the files it runs from change.
if [ -d "$INSTALL_DIR/.git" ]; then
retarget_legacy_origin
# shellcheck disable=SC2086 # GIT_NET_OPTS must word-split into -c pairs
if pretty_git git $GIT_NET_OPTS -C "$INSTALL_DIR" fetch "$GIT_VERBOSITY" --depth 1 origin "$BRANCH" \
+ && stop_running_app \
&& git -C "$INSTALL_DIR" checkout --quiet "$BRANCH" \
&& git -C "$INSTALL_DIR" reset --quiet --hard "origin/$BRANCH"; then
ok 'updated existing checkout to latest'
@@ -1170,14 +1260,9 @@ VENV_PYTHON="$VENV_PATH/bin/python"
# keeps serving stale, half-updated features while pip rewrites the venv
# under it — the "app is already open but nothing works yet" field report
# (2026-07-14). The installer relaunches a fresh instance as its last step.
-if [ -x "$VENV_PYTHON" ]; then
- if pkill -f "$VENV_PATH" 2>/dev/null; then
- note 'stopped the running Jarvis app for the update'
- fi
- if [ "$(uname -s 2>/dev/null)" = "Darwin" ]; then
- launchctl unload "$HOME/Library/LaunchAgents/${MACOS_AUTOSTART_LABEL}.plist" >/dev/null 2>&1 || true
- fi
-fi
+# The app was already stopped once before the checkout was replaced; this
+# second call catches one the login autostart revived in between.
+stop_running_app
# Rebuild the venv when the selected interpreter's major.minor changed
# (BUG-059 follow-up): the 3.13-first preference is useless for an EXISTING
diff --git a/install/update-contract.json b/install/update-contract.json
new file mode 100644
index 0000000000..b085649081
--- /dev/null
+++ b/install/update-contract.json
@@ -0,0 +1,9 @@
+{
+ "schema": 1,
+ "ui_bundle_dir": "jarvis/ui/web/dist",
+ "launcher_module": "jarvis.ui.web.launcher",
+ "version_file": "jarvis/__init__.py",
+ "config_file": "jarvis.toml",
+ "macos_app_dir_name": "Personal Jarvis.app",
+ "macos_bundle_id": "com.personal-jarvis.desktop"
+}
diff --git a/jarvis/cli/app_update.py b/jarvis/cli/app_update.py
index 45e5f1f7b4..1eed5ef881 100644
--- a/jarvis/cli/app_update.py
+++ b/jarvis/cli/app_update.py
@@ -158,7 +158,8 @@ def _run_child(args: list[str], timeout: float | None, detached: bool) -> tuple[
"so this keeps going - please wait.",
flush=True,
)
- except subprocess.TimeoutExpired: # Kill and reap the timed-out probe, then return a failure result.
+ except subprocess.TimeoutExpired:
+ # Kill and reap the timed-out probe, then return a failure result.
proc.kill()
proc.communicate()
return -1, ""
@@ -240,12 +241,17 @@ def _stop_background_service(pid: int, *, wait: Callable[..., bool] | None = Non
clear_handover_request()
-def _read_result(root: Path) -> dict[str, Any]:
+def _result_file_name() -> str:
from jarvis.ui.relauncher import UPDATE_RESULT_FILENAME
+ return UPDATE_RESULT_FILENAME
+
+
+def _read_result(root: Path, file_name: str) -> dict[str, Any]:
try:
- payload = json.loads((root / UPDATE_RESULT_FILENAME).read_text(encoding="utf-8"))
- except (OSError, ValueError): # An absent or incomplete update receipt represents no available result.
+ payload = json.loads((root / file_name).read_text(encoding="utf-8"))
+ except (OSError, ValueError):
+ # An absent or incomplete update receipt represents no available result.
return {}
return payload if isinstance(payload, dict) else {}
@@ -336,12 +342,16 @@ def run_update(
root = Path(str(staged["root"]))
version = staged.get("version") or latest
+ # Resolved before the install step. Afterwards the checkout holds the new
+ # release, and an import from this process would read THAT release's files
+ # - or fail outright if it moved the package.
+ result_file_name = _result_file_name()
with _Ticker(
f"Installing version {version} - this takes a few minutes, keep this window open...",
enabled=interactive,
):
code, _ = run_child([FINALIZE_FLAG, str(root)], None, True)
- result = _read_result(root)
+ result = _read_result(root, result_file_name)
if code == 0 and result.get("ok", True):
print(f"Done. Dodaios {version} is installed.")
print("Start it with: jarvis")
diff --git a/jarvis/core/installer_update.py b/jarvis/core/installer_update.py
index 4ac3dad4ec..2f29e5c980 100644
--- a/jarvis/core/installer_update.py
+++ b/jarvis/core/installer_update.py
@@ -2,14 +2,17 @@
A frozen install (Windows ``Setup.exe``, macOS ``.dmg``, Linux ``.AppImage``)
has no git checkout, so ``jarvis/ui/web/update_routes.py``'s managed path cannot
-update it. What it does have is a GitHub Release carrying exactly one installer
-asset per platform plus a ``installers-SHA256SUMS.txt`` manifest:
+update it. What it does have is a GitHub Release carrying one installer asset
+per platform plus a ``installers-SHA256SUMS.txt`` manifest:
* ``PersonalJarvis-Setup-x64.exe`` Windows 10/11 x64
* ``PersonalJarvis-macOS-arm64.dmg`` Apple Silicon
* ``PersonalJarvis-macOS-x64.dmg`` Intel Mac
* ``PersonalJarvis-Linux-x86_64.AppImage`` Linux x86_64
+A release may publish the same four files under the ``Dodaios-`` prefix instead;
+:data:`INSTALLER_ASSET_NAMES` lists every accepted name per platform.
+
This module resolves which of those belongs to the running machine, downloads
it, proves it byte-for-byte against the checksum manifest of the SAME release,
and then hands control to the platform's own upgrade mechanism.
@@ -46,7 +49,12 @@ from dataclasses import dataclass
from pathlib import Path
from typing import Any, Protocol
-from jarvis.core.branding import UPDATER_USER_AGENT
+from jarvis.core.branding import (
+ MACOS_APP_DIR_NAME,
+ MACOS_BUNDLE_ID,
+ MACOS_DMG_BUNDLE_ID,
+ UPDATER_USER_AGENT,
+)
from jarvis.core.frozen import bundle_root, is_frozen
from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS
@@ -54,6 +62,7 @@ log = logging.getLogger(__name__)
__all__ = [
"CHECKSUMS_ASSET_NAME",
+ "INSTALLER_ASSET_NAMES",
"AssetFetcher",
"CommandRunner",
"DownloadProgress",
@@ -66,10 +75,12 @@ __all__ = [
"download_and_verify",
"handover_env",
"installer_asset_name",
+ "installer_asset_names",
"machine_for_update",
"parse_sha256sums",
"select_asset",
"select_installer_asset",
+ "select_installer_assets",
"sweep_stale_downloads",
"update_blocker",
]
@@ -136,33 +147,62 @@ class InstallerAsset:
# --------------------------------------------------------------------------- #
# Asset selection
# --------------------------------------------------------------------------- #
-def installer_asset_name(platform_name: str, machine: str) -> str | None:
- """The release asset this OS/CPU pair installs, or ``None`` when unsupported.
+#: Every installer file name the updater accepts, per ``(os, cpu)``, best
+#: first. This is the one place the names live.
+#:
+#: A release publishes each installer under ONE of the names in its row. The
+#: updater takes the first name the release actually carries, so an install
+#: keeps updating whichever prefix a release uses. The LAST name of a row is
+#: the one every release published so far carries
+#: (``scripts/ci/release_assets.py`` pins that set for the release pipeline).
+INSTALLER_ASSET_NAMES: dict[tuple[str, str], tuple[str, ...]] = {
+ ("windows", "x64"): ("Dodaios-Setup-x64.exe", "PersonalJarvis-Setup-x64.exe"),
+ ("macos", "arm64"): ("Dodaios-macOS-arm64.dmg", "PersonalJarvis-macOS-arm64.dmg"),
+ ("macos", "x64"): ("Dodaios-macOS-x64.dmg", "PersonalJarvis-macOS-x64.dmg"),
+ ("linux", "x64"): (
+ "Dodaios-Linux-x86_64.AppImage",
+ "PersonalJarvis-Linux-x86_64.AppImage",
+ ),
+}
+
+
+def installer_asset_names(platform_name: str, machine: str) -> tuple[str, ...]:
+ """Accepted release asset names for this OS/CPU pair, best first.
``machine`` is compared case-insensitively because the same CPU reports
different spellings per OS: Windows says ``AMD64``, Linux says ``x86_64``,
macOS says ``arm64`` while ``platform.machine()`` under Rosetta says
- ``x86_64``. An unrecognised pair returns ``None`` — the caller then reports
- "no installer for this platform" instead of guessing.
+ ``x86_64``. An unrecognised pair returns an empty tuple — the caller then
+ reports "no installer for this platform" instead of guessing.
"""
arch = machine.strip().lower()
- intel64 = {"x86_64", "amd64", "x64"}
+ if arch in {"x86_64", "amd64", "x64"}:
+ cpu = "x64"
+ elif arch in {"arm64", "aarch64"}:
+ cpu = "arm64"
+ else:
+ return ()
if platform_name == "win32":
- if arch in intel64:
- return "PersonalJarvis-Setup-x64.exe"
- return None
- if platform_name == "darwin":
- if arch in {"arm64", "aarch64"}:
- return "PersonalJarvis-macOS-arm64.dmg"
- if arch in intel64:
- return "PersonalJarvis-macOS-x64.dmg"
- return None
- if platform_name.startswith("linux"):
- if arch in intel64:
- return "PersonalJarvis-Linux-x86_64.AppImage"
- return None
- return None
+ system = "windows"
+ elif platform_name == "darwin":
+ system = "macos"
+ elif platform_name.startswith("linux"):
+ system = "linux"
+ else:
+ return ()
+ return INSTALLER_ASSET_NAMES.get((system, cpu), ())
+
+
+def installer_asset_name(platform_name: str, machine: str) -> str | None:
+ """The asset name every published release carries for this OS/CPU pair.
+
+ ``None`` when no installer exists for the pair. Use
+ :func:`installer_asset_names` to pick a file out of a release: a release
+ may carry the installer under another accepted name.
+ """
+ names = installer_asset_names(platform_name, machine)
+ return names[-1] if names else None
def _running_under_rosetta() -> bool:
@@ -243,6 +283,20 @@ def select_asset(assets: Iterable[Any], name: str) -> InstallerAsset | None:
return None
+def select_installer_assets(
+ assets: Iterable[Any], names: Sequence[str]
+) -> tuple[InstallerAsset, ...]:
+ """The assets of one release that match ``names``, in the order of ``names``.
+
+ Usually one entry. More than one means the release carries the installer
+ under several accepted names; :func:`download_and_verify` then takes the
+ first that the checksum manifest vouches for.
+ """
+ listed = list(assets)
+ found = (select_asset(listed, name) for name in names)
+ return tuple(asset for asset in found if asset is not None)
+
+
def select_installer_asset(
assets: Iterable[Any],
*,
@@ -251,13 +305,12 @@ def select_installer_asset(
) -> InstallerAsset | None:
"""The installer asset for the running machine, or ``None``."""
active_platform = sys.platform if platform_name is None else platform_name
- name = installer_asset_name(
+ names = installer_asset_names(
active_platform,
machine_for_update(active_platform) if machine is None else machine,
)
- if name is None:
- return None
- return select_asset(assets, name)
+ candidates = select_installer_assets(assets, names)
+ return candidates[0] if candidates else None
# --------------------------------------------------------------------------- #
@@ -432,9 +485,16 @@ async def download_and_verify(
max_bytes: int = MAX_INSTALLER_BYTES,
on_progress: DownloadProgress | None = None,
download_timeout_s: float = DOWNLOAD_TIMEOUT_S,
+ alternatives: Sequence[InstallerAsset] = (),
) -> Path:
"""Download ``asset`` and prove it against ``checksums``. Fail closed.
+ ``alternatives`` are further assets of the SAME release holding the same
+ installer under another accepted name, in order of preference after
+ ``asset``. The first of them all that has a line in the checksum manifest
+ is the one downloaded: a file the manifest does not vouch for is never
+ fetched, whatever it is called.
+
``checksums`` must come from the SAME release as ``asset`` — verifying
against another release's manifest would authorise the wrong bytes. The
caller (``update_routes``) reads both out of one release payload.
@@ -477,12 +537,21 @@ async def download_and_verify(
raise InstallerUpdateError(f"could not download {CHECKSUMS_ASSET_NAME}: {exc}") from exc
digests = parse_sha256sums(manifest_text)
- expected = digests.get(asset.name)
- if not expected:
+ candidates = (asset, *alternatives)
+ vouched = [candidate for candidate in candidates if digests.get(candidate.name)]
+ if not vouched:
+ named = " or ".join(candidate.name for candidate in candidates)
raise InstallerUpdateError(
- f"{CHECKSUMS_ASSET_NAME} of this release has no entry for {asset.name} — "
+ f"{CHECKSUMS_ASSET_NAME} of this release has no entry for {named} — "
"refusing to install an unverified file"
)
+ if vouched[0] is not asset:
+ asset = vouched[0]
+ if asset.size and asset.size > max_bytes:
+ raise InstallerUpdateError(
+ f"{asset.name} is {asset.size} bytes, over the {max_bytes} byte cap"
+ )
+ expected = digests[asset.name]
target = _prepare_target(dest_dir, asset.name)
try:
@@ -796,7 +865,19 @@ def _handover_macos(
relaunch: bool,
wait_for_pid: int,
) -> str:
- """Mount the DMG, swap the running ``.app`` for the one inside, relaunch."""
+ """Mount the DMG, swap the running ``.app`` for the one inside, relaunch.
+
+ The running bundle is replaced in place whenever the disk image carries
+ the app under the running bundle's name or under the name this version
+ ships with. The second case is a bundle the USER renamed or duplicated
+ ("Keep Both" in Finder): the image still holds the usual name, and the
+ update belongs into the bundle they launched.
+
+ Only an image whose single bundle has a name this version has never used is
+ a release that renamed the app. That one is installed beside the running
+ bundle under its own name, relaunched from there, and the old bundle is
+ removed afterwards (see :func:`_install_renamed_bundle`).
+ """
if app_path is None:
raise InstallerUpdateError(
"could not locate the running Personal Jarvis.app — refusing to update"
@@ -832,7 +913,13 @@ def _handover_macos(
)
source = candidates[0]
- _replace_directory(source, app_path)
+ known_names = {app_path.name.casefold(), MACOS_APP_DIR_NAME.casefold()}
+ if source.name.casefold() in known_names:
+ installed = app_path
+ _replace_directory(source, app_path)
+ else:
+ installed = app_path.with_name(source.name)
+ _install_renamed_bundle(source, installed, replaced=app_path)
finally:
# ``attached`` misses one case: hdiutil mounted the image and then
# reported failure (or timed out after mounting). The mountpoint is the
@@ -850,12 +937,18 @@ def _handover_macos(
if relaunch:
try:
runner.spawn_detached(
- relaunch_after_exit_command(wait_for_pid, [MACOS_OPEN, "-n", str(app_path)])
+ relaunch_after_exit_command(wait_for_pid, [MACOS_OPEN, "-n", str(installed)])
)
except OSError as exc:
raise InstallerUpdateError(
f"the update was installed but could not be relaunched: {exc}"
) from exc
+ if installed != app_path:
+ log.info("[update] installed %s from %s, replacing %s", installed, dmg.name, app_path)
+ return (
+ f"{installed.name} was installed in place of {app_path.name}; "
+ "it starts as soon as this window closes"
+ )
log.info("[update] replaced %s from %s", app_path, dmg.name)
return f"{app_path.name} was replaced; it restarts as soon as this window closes"
@@ -967,6 +1060,64 @@ def _replace_directory(source: Path, target: Path) -> None:
shutil.rmtree(previous, ignore_errors=True)
+# Bundle identifiers this product has shipped under: the installer-built app
+# and the downloadable disk image. Only a bundle that names one of them is
+# ever removed by an update.
+_OWN_MACOS_BUNDLE_IDS = frozenset({MACOS_BUNDLE_ID, MACOS_DMG_BUNDLE_ID})
+
+
+def _macos_bundle_identifier(bundle: Path) -> str | None:
+ """``CFBundleIdentifier`` of ``bundle``; ``None`` when it cannot be read."""
+ import plistlib
+
+ try:
+ with (bundle / "Contents" / "Info.plist").open("rb") as stream:
+ bundle_id = plistlib.load(stream).get("CFBundleIdentifier")
+ except (OSError, ValueError, plistlib.InvalidFileException) as exc:
+ # Missing or unreadable metadata proves nothing about ownership.
+ log.debug("[update] no readable Info.plist in %s: %s", bundle, exc)
+ return None
+ return bundle_id if isinstance(bundle_id, str) and bundle_id else None
+
+
+def _install_renamed_bundle(source: Path, installed: Path, *, replaced: Path) -> None:
+ """Install a bundle whose name changed next to the one it supersedes.
+
+ Copying it ONTO the running bundle would leave the new app inside a folder
+ that still carries the old name. It goes beside it instead, and only once
+ that copy is complete is the superseded bundle taken away — so a failure at
+ any point leaves the app the user started exactly where it was.
+
+ Two things are never touched: an unrelated app that already owns the new
+ name, and a superseded bundle that does not identify itself as ours.
+ """
+ if installed.exists():
+ present = _macos_bundle_identifier(installed)
+ if present is None or present != _macos_bundle_identifier(source):
+ raise InstallerUpdateError(
+ f"{installed} already exists and is a different application — "
+ "refusing to overwrite it"
+ )
+
+ _replace_directory(source, installed)
+
+ if _macos_bundle_identifier(replaced) not in _OWN_MACOS_BUNDLE_IDS:
+ log.warning("[update] %s does not identify itself as ours; leaving it in place", replaced)
+ return
+ # Renamed aside first, so a removal that fails halfway leaves a hidden
+ # leftover instead of a visible app that no longer starts.
+ retired = replaced.with_name(f".{replaced.name}.old")
+ shutil.rmtree(retired, ignore_errors=True)
+ try:
+ os.replace(replaced, retired)
+ except OSError as exc:
+ # The new app is installed and is what gets relaunched; a superseded
+ # bundle that stays behind costs disk space, not the update.
+ log.warning("[update] could not remove the superseded %s: %s", replaced, exc)
+ return
+ shutil.rmtree(retired, ignore_errors=True)
+
+
def _running_macos_app() -> Path | None:
"""``/Applications/Personal Jarvis.app`` for the RUNNING process, if any.
@@ -994,7 +1145,7 @@ def supported_here() -> bool:
"""True when this process is frozen AND an installer exists for its platform."""
if not is_frozen():
return False
- return installer_asset_name(sys.platform, machine_for_update()) is not None
+ return bool(installer_asset_names(sys.platform, machine_for_update()))
@dataclass(frozen=True)
diff --git a/jarvis/core/update_contract.py b/jarvis/core/update_contract.py
new file mode 100644
index 0000000000..0986fcddf3
--- /dev/null
+++ b/jarvis/core/update_contract.py
@@ -0,0 +1,210 @@
+"""Where a release keeps the files its updater has to find.
+
+An update is applied by the PREVIOUS version's code: the detached restart
+helper resets the checkout to the new revision, runs that revision's installer
+and then has to verify and start a tree it has never seen. Every location it
+needs for that is stated by the tree itself in ``install/update-contract.json``,
+so a release may move its package, its launcher or its config file and still be
+reachable from the version before it.
+
+A tree without the file — every release before the file existed — is described
+by :data:`DEFAULT_CONTRACT`, which holds exactly the locations those releases
+use. The same answer is given for a file this version cannot trust: an unknown
+schema, malformed JSON, or a value that is not a plain relative location.
+Falling back is the fail-closed choice: the update then looks for the UI bundle
+in the default place, does not find it, and rolls back to the previous revision.
+
+Standard library only and no I/O at import time — the restart helper loads this
+module, and it must stay a throwaway process.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+import re
+from dataclasses import dataclass, replace
+from pathlib import Path
+
+from jarvis.core.branding import CONFIG_FILE_NAME, MACOS_APP_DIR_NAME, MACOS_BUNDLE_ID
+
+log = logging.getLogger(__name__)
+
+__all__ = [
+ "CONTRACT_PATH",
+ "CONTRACT_SCHEMA",
+ "DEFAULT_CONTRACT",
+ "UpdateContract",
+ "VERSION_PATTERN",
+ "parse_update_contract",
+ "read_update_contract",
+]
+
+#: Location of the contract inside a checkout, POSIX-style so the same string
+#: addresses the file on disk and at a git revision (``git show <rev>:<path>``).
+CONTRACT_PATH = "install/update-contract.json"
+CONTRACT_SCHEMA = 1
+
+#: How the version is written in a release's version file. Fixed here rather
+#: than read from the contract: a pattern taken from the target tree would be a
+#: regular expression this process runs on someone else's say-so.
+VERSION_PATTERN = r'__version__\s*=\s*"([^"]+)"'
+
+# A contract is a handful of short lines; anything larger is not one.
+_MAX_CONTRACT_BYTES = 16_384
+
+_RELATIVE_PATH_RE = re.compile(r"^(?:[A-Za-z0-9._-]+/)*[A-Za-z0-9._-]+$")
+_FILE_NAME_RE = re.compile(r"^[A-Za-z0-9._-]+$")
+_MODULE_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*)*$")
+_APP_DIR_NAME_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9 ._-]*\.app$")
+_BUNDLE_ID_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9-]*(\.[A-Za-z0-9][A-Za-z0-9-]*)+$")
+_MAX_VALUE_LENGTH = 240
+
+
+@dataclass(frozen=True)
+class UpdateContract:
+ """The locations one release publishes for the updater of the one before."""
+
+ #: Directory holding the built web UI (``index.html`` plus ``assets/``).
+ ui_bundle_dir: str = "jarvis/ui/web/dist"
+ #: Module ``python -m`` runs to start the desktop app.
+ launcher_module: str = "jarvis.ui.web.launcher"
+ #: File whose ``__version__ = "..."`` line names the release.
+ version_file: str = "jarvis/__init__.py"
+ #: Name of the user's config file in the checkout root.
+ config_file: str = CONFIG_FILE_NAME
+ #: Directory name of the macOS application bundle the installer builds.
+ macos_app_dir_name: str = MACOS_APP_DIR_NAME
+ #: ``CFBundleIdentifier`` of that bundle. A bundle of the right name with
+ #: another identifier is a different app and is never started in its place.
+ macos_bundle_id: str = MACOS_BUNDLE_ID
+ #: Script the release wants run when its install failed and the checkout is
+ #: about to return to the previous revision - the place to undo what its
+ #: installer changed outside the checkout. Run as
+ #: ``<checkout python> <hook> <previous revision> <target revision>`` with
+ #: the checkout as working directory, while the release's own tree is still
+ #: checked out. It must be a file the release tracks; a non-zero exit or a
+ #: timeout is logged and the rollback continues.
+ rollback_hook: str | None = None
+
+
+DEFAULT_CONTRACT = UpdateContract()
+
+
+def _is_relative_path(value: object) -> bool:
+ """A POSIX path that stays inside the checkout it is resolved against."""
+ if not isinstance(value, str) or len(value) > _MAX_VALUE_LENGTH:
+ return False
+ if not _RELATIVE_PATH_RE.fullmatch(value):
+ return False
+ return all(segment not in {".", ".."} for segment in value.split("/"))
+
+
+def _is_file_name(value: object) -> bool:
+ return (
+ isinstance(value, str)
+ and len(value) <= _MAX_VALUE_LENGTH
+ and bool(_FILE_NAME_RE.fullmatch(value))
+ and value not in {".", ".."}
+ )
+
+
+def _is_module_name(value: object) -> bool:
+ return (
+ isinstance(value, str)
+ and len(value) <= _MAX_VALUE_LENGTH
+ and bool(_MODULE_RE.fullmatch(value))
+ )
+
+
+def _is_app_dir_name(value: object) -> bool:
+ return (
+ isinstance(value, str)
+ and len(value) <= _MAX_VALUE_LENGTH
+ and bool(_APP_DIR_NAME_RE.fullmatch(value))
+ )
+
+
+def _is_bundle_id(value: object) -> bool:
+ return (
+ isinstance(value, str)
+ and len(value) <= _MAX_VALUE_LENGTH
+ and bool(_BUNDLE_ID_RE.fullmatch(value))
+ )
+
+
+def _is_rollback_hook(value: object) -> bool:
+ return value is None or (_is_relative_path(value) and str(value).endswith(".py"))
+
+
+_FIELD_CHECKS = (
+ ("ui_bundle_dir", _is_relative_path),
+ ("launcher_module", _is_module_name),
+ ("version_file", _is_relative_path),
+ ("config_file", _is_file_name),
+ ("macos_app_dir_name", _is_app_dir_name),
+ ("macos_bundle_id", _is_bundle_id),
+ ("rollback_hook", _is_rollback_hook),
+)
+
+
+def parse_update_contract(text: str) -> UpdateContract:
+ """Validate one contract document; anything doubtful is the default contract.
+
+ A key the document leaves out keeps its default, so a release states only
+ what it moved. A key this version does not know is ignored. One invalid
+ value rejects the whole document: a contract that is half believed could
+ point the bundle check at one tree layout and the launcher at another.
+ """
+ try:
+ payload = json.loads(text)
+ except (ValueError, TypeError, RecursionError):
+ log.warning("update contract is not valid JSON; using the default locations")
+ return DEFAULT_CONTRACT
+ if not isinstance(payload, dict):
+ log.warning("update contract is not a JSON object; using the default locations")
+ return DEFAULT_CONTRACT
+ schema = payload.get("schema")
+ if type(schema) is not int or schema != CONTRACT_SCHEMA:
+ # A newer schema may mean the same keys differently. The default
+ # locations are the only ones this version can vouch for.
+ log.warning(
+ "update contract schema %r is not %d; using the default locations",
+ schema,
+ CONTRACT_SCHEMA,
+ )
+ return DEFAULT_CONTRACT
+
+ stated: dict[str, str | None] = {}
+ for name, is_valid in _FIELD_CHECKS:
+ if name not in payload:
+ continue
+ value = payload[name]
+ if not is_valid(value):
+ log.warning(
+ "update contract has an invalid %s; using the default locations", name
+ )
+ return DEFAULT_CONTRACT
+ stated[name] = value
+ return replace(DEFAULT_CONTRACT, **stated)
+
+
+def read_update_contract(root: str | Path) -> UpdateContract:
+ """The contract of the tree currently checked out at ``root``."""
+ path = Path(root) / CONTRACT_PATH
+ try:
+ with path.open("rb") as stream:
+ raw = stream.read(_MAX_CONTRACT_BYTES + 1)
+ except OSError:
+ # Absent in every release before the file existed, and in any
+ # directory that is not a checkout (a frozen build's config folder).
+ return DEFAULT_CONTRACT
+ if len(raw) > _MAX_CONTRACT_BYTES:
+ log.warning("update contract at %s is too large; using the default locations", path)
+ return DEFAULT_CONTRACT
+ try:
+ text = raw.decode("utf-8-sig")
+ except UnicodeDecodeError:
+ log.warning("update contract at %s is not UTF-8; using the default locations", path)
+ return DEFAULT_CONTRACT
+ return parse_update_contract(text)
diff --git a/jarvis/ui/relauncher.py b/jarvis/ui/relauncher.py
index dd3bc59ed9..52832b6b48 100644
--- a/jarvis/ui/relauncher.py
+++ b/jarvis/ui/relauncher.py
@@ -31,7 +31,6 @@ import time
from pathlib import Path
from jarvis.core.branding import (
- CONFIG_FILE_NAME,
LAUNCHER_ENTRY_NAME,
MACOS_APP_DIR_NAME,
MANAGED_INSTALL_MARKER,
@@ -39,8 +38,13 @@ from jarvis.core.branding import (
WINDOWS_BRANDED_LAUNCH_ENV_VAR,
WINDOWS_BRANDED_LAUNCHER_DIR_NAME,
)
+from jarvis.core.update_contract import (
+ DEFAULT_CONTRACT,
+ UpdateContract,
+ read_update_contract,
+)
-LAUNCHER_MODULE = "jarvis.ui.web.launcher"
+LAUNCHER_MODULE = DEFAULT_CONTRACT.launcher_module
MANAGED_MARKER = MANAGED_INSTALL_MARKER
PENDING_UPDATE_FILENAME = ".jarvis-update-pending.json"
UPDATE_RESULT_FILENAME = ".jarvis-update-result.json"
@@ -195,9 +199,14 @@ def build_launch_command(
executable: str,
*,
launcher_args: tuple[str, ...] = (),
+ contract: UpdateContract = DEFAULT_CONTRACT,
) -> list[str]:
"""Argv that boots a fresh desktop app through its stable OS identity.
+ ``contract`` names the launcher module and the macOS bundle of the tree
+ that is installed right now. After an update that is the NEW release's
+ answer, which this (older) process could not know by itself.
+
A macOS desktop restart always re-enters through LaunchServices so it can
never attach TCC access to a raw Python interpreter. A missing or invalid
bundle therefore fails closed; the managed installer/repair path owns
@@ -213,7 +222,8 @@ def build_launch_command(
identity = current_instance()
args = (*identity.launcher_args, *launcher_args)
- fallback = [executable, "-m", LAUNCHER_MODULE, *args]
+ launcher_module = contract.launcher_module
+ fallback = [executable, "-m", launcher_module, *args]
if sys.platform == "darwin" and not identity.is_default:
# The bundle is the DEFAULT app's stable identity and LaunchServices
# does not carry ``JARVIS_INSTANCE`` into it — re-entering through it
@@ -222,7 +232,7 @@ def build_launch_command(
# microphone-bound duties the TCC attachment is for).
return fallback
if sys.platform == "darwin":
- bundle = Path.home() / "Applications" / MACOS_APP_DIR_NAME
+ bundle = Path.home() / "Applications" / contract.macos_app_dir_name
try:
from jarvis.setup.macos_app_bundle import (
macos_app_bundle_is_launchable,
@@ -231,7 +241,9 @@ def build_launch_command(
)
bundle = macos_app_bundle_path()
- if not macos_app_bundle_is_launchable(bundle):
+ if contract.macos_app_dir_name != MACOS_APP_DIR_NAME:
+ bundle = _renamed_macos_bundle(bundle, contract)
+ elif not macos_app_bundle_is_launchable(bundle):
logging.getLogger(__name__).error(
"macOS restart target is missing or invalid: %s", bundle
)
@@ -248,10 +260,53 @@ def build_launch_command(
# process. Spawning ``python -m launcher`` used to re-exec through
# this copy and exit; the helper treated that exit as a bounce and
# started two more copies that raced the first (BUG-181).
- return [str(branded), "-m", LAUNCHER_MODULE, *args]
+ return [str(branded), "-m", launcher_module, *args]
return fallback
+def _macos_bundle_identifier(bundle: Path) -> str | None:
+ """``CFBundleIdentifier`` of ``bundle``; ``None`` when it cannot be read."""
+ import plistlib
+
+ try:
+ with (bundle / "Contents" / "Info.plist").open("rb") as stream:
+ bundle_id = plistlib.load(stream).get("CFBundleIdentifier")
+ except (OSError, ValueError, plistlib.InvalidFileException):
+ return None # missing or unreadable metadata identifies nothing
+ return bundle_id if isinstance(bundle_id, str) and bundle_id else None
+
+
+def _renamed_macos_bundle(known: Path, contract: UpdateContract) -> Path:
+ """Where the installed release keeps its app bundle under another name.
+
+ This version only knows the bundle it was built with. A release that
+ renamed it says so in its update contract; the bundle then sits in one of
+ the two Applications folders, and the one this version used is tried first.
+
+ The name alone does not decide. The downloadable disk-image app can sit in
+ the other Applications folder under the very same name, and starting that
+ one after an installer-managed update would bring back a different install.
+ Only a bundle carrying the identifier the contract names is taken. When
+ none does, the answer is a path where no other app sits, so the restart
+ fails visibly instead of opening someone else.
+ """
+ app_dir_name = contract.macos_app_dir_name
+ vacant: Path | None = None
+ for folder in (known.parent, Path("/Applications"), Path.home() / "Applications"):
+ candidate = folder / app_dir_name
+ if not candidate.is_dir():
+ vacant = vacant or candidate
+ elif _macos_bundle_identifier(candidate) == contract.macos_bundle_id:
+ return candidate
+ logging.getLogger(__name__).error(
+ "macOS restart target %s (%s) was not found next to %s",
+ app_dir_name,
+ contract.macos_bundle_id,
+ known,
+ )
+ return vacant or known.with_name(app_dir_name)
+
+
def _read_windows_user_jarvis_env() -> dict[str, str] | None:
"""The ``JARVIS__*`` config overrides persisted in the user's CURRENT
Windows environment (HKCU\\Environment), or ``None`` when unavailable.
@@ -481,7 +536,9 @@ def _restart_admin_port(cwd: str | Path | None = None) -> int:
base = _DEFAULT_ADMIN_PORT
root = Path(cwd) if cwd else None
if root is not None:
- cfg = root / CONFIG_FILE_NAME
+ # Asked of the tree on disk at probe time: after an update the config
+ # file carries whatever name the installed release gave it.
+ cfg = root / read_update_contract(root).config_file
try:
import tomllib
@@ -490,7 +547,7 @@ def _restart_admin_port(cwd: str | Path | None = None) -> int:
if isinstance(port, int) and 1 <= port <= 65535:
base = port
except (OSError, UnicodeDecodeError, ValueError, TypeError, AttributeError):
- pass # unreadable jarvis.toml → packaged default port
+ pass # unreadable config file → packaged default port
return current_instance().port(base)
@@ -729,9 +786,16 @@ def _installer_command(root: Path, profile: str) -> list[str]:
def _ui_bundle_ready(root: Path) -> bool:
- """Verify that the checked-out release owns a loadable JS/CSS entry set."""
+ """Verify that the checked-out release owns a loadable JS/CSS entry set.
- dist = root / "jarvis" / "ui" / "web" / "dist"
+ The bundle directory is the one the tree on disk names in its update
+ contract, read here so the answer always belongs to the revision that the
+ preceding ``git reset`` checked out — the target, or the previous one after
+ a rollback.
+ """
+
+ bundle_dir = read_update_contract(root).ui_bundle_dir
+ dist = root.joinpath(*bundle_dir.split("/"))
index = dist / "index.html"
try:
html = index.read_text(encoding="utf-8")
@@ -744,7 +808,7 @@ def _ui_bundle_ready(root: Path) -> bool:
if not any(ref.endswith(".js") for ref in refs):
return False
- required = {"jarvis/ui/web/dist/index.html"}
+ required = {f"{bundle_dir}/index.html"}
for ref in refs:
asset = dist / Path(ref)
try:
@@ -752,7 +816,7 @@ def _ui_bundle_ready(root: Path) -> bool:
return False
except OSError:
return False
- required.add(f"jarvis/ui/web/dist/{ref}")
+ required.add(f"{bundle_dir}/{ref}")
for rel in required:
if (
@@ -794,6 +858,37 @@ def _write_update_result(
pass
+#: Upper bound for a release's rollback hook. It undoes what that release's
+#: installer changed outside the checkout, which is file moves, not downloads.
+_ROLLBACK_HOOK_TIMEOUT_S = 300.0
+
+
+def _run_rollback_hook(root: Path, hook: str, *, previous: str, target: str) -> None:
+ """Let the failed release undo what its installer changed, before it goes.
+
+ Only the release that moved a config file or re-registered the desktop
+ entry knows how to put it back, so the script comes from its tree and runs
+ while that tree is still checked out. It must be a file the release tracks:
+ a stray script in the checkout is never executed. Its failure is logged and
+ never stops the rollback, which is the part that brings the app back.
+ """
+ log = logging.getLogger(__name__)
+ script = root.joinpath(*hook.split("/"))
+ tracked = _run_update_command(
+ ["git", "ls-files", "--error-unmatch", "--", hook], root=root, timeout=30.0
+ )
+ if tracked != 0 or not script.is_file():
+ log.warning("update rollback hook %s is not a tracked file; skipping it", hook)
+ return
+ rc = _run_update_command(
+ [_managed_python(root), str(script), previous, target],
+ root=root,
+ timeout=_ROLLBACK_HOOK_TIMEOUT_S,
+ )
+ if rc != 0:
+ log.warning("update rollback hook %s exited with %s; rolling back anyway", hook, rc)
+
+
#: Precious, small user state that must survive ANY update outcome. Copied to
#: a sibling directory OUTSIDE the checkout before the first ``git reset`` so
#: even a catastrophic tree replacement (the 2026-07-20 wipe lost API keys,
@@ -884,7 +979,11 @@ def finalize_pending_update(cwd: str | Path) -> bool:
_run_update_command(["git", "reset", "--hard", target], root=root, timeout=120.0) == 0
)
target_install_ok = False
+ rollback_hook: str | None = None
if target_reset_ok:
+ # Read before the installer runs: a failed install may leave the file
+ # in any state, and the hook is needed exactly then.
+ rollback_hook = read_update_contract(root).rollback_hook
target_install_ok = _run_update_command(
_installer_command(root, profile), root=root, timeout=3600.0
) == 0 and _ui_bundle_ready(root)
@@ -899,6 +998,8 @@ def finalize_pending_update(cwd: str | Path) -> bool:
)
return True
+ if rollback_hook is not None:
+ _run_rollback_hook(root, rollback_hook, previous=previous, target=target)
rollback_reset_ok = (
_run_update_command(["git", "reset", "--hard", previous], root=root, timeout=120.0) == 0
)
@@ -985,8 +1086,12 @@ def main(
except Exception: # noqa: BLE001, S110 — a mute helper is what we had before
pass
+ # Everything below the finalize step may run against a checkout that holds
+ # another release, so the package modules it needs are loaded first.
+ _load_modules_needed_after_update()
+ base_env = fresh_user_env()
cmd = build_launch_command(sys.executable, launcher_args=launcher_args)
- env = _apply_branded_launch_env(fresh_user_env(), cmd)
+ env = _apply_branded_launch_env(base_env, cmd)
update_finalized = False
for attempt in range(attempts):
@@ -1006,6 +1111,15 @@ def main(
if not update_finalized:
_finalize_update(cwd)
update_finalized = True
+ # The command above describes the tree this helper started from.
+ # Whatever the finalizer left installed — the new release, or the
+ # previous one after a rollback — says where its launcher lives.
+ cmd = build_launch_command(
+ sys.executable,
+ launcher_args=launcher_args,
+ contract=read_update_contract(cwd),
+ )
+ env = _apply_branded_launch_env(base_env, cmd)
proc = spawn_detached(cmd, cwd=cwd, env=env, _popen=_spawn)
new_pid = getattr(proc, "pid", None)
@@ -1022,6 +1136,43 @@ def main(
return 1
+#: Package modules this helper imports inside functions that can run after a
+#: pending update was applied. ``jarvis.setup.macos_app_bundle`` is macOS-only
+#: work and is loaded only there.
+_MODULES_NEEDED_AFTER_UPDATE = (
+ "jarvis.core.frozen",
+ "jarvis.core.instance",
+ "jarvis.core.process_utils",
+ "jarvis.ui.native_dialog",
+)
+_MACOS_MODULES_NEEDED_AFTER_UPDATE = ("jarvis.setup.macos_app_bundle",)
+
+
+def _load_modules_needed_after_update() -> None:
+ """Import, now, every package module this helper still calls later.
+
+ Applying a pending update replaces the checkout under this process, and
+ the new release may have moved or renamed the package. A function-level
+ import that first ran after that point would read the NEW tree — or find
+ nothing at all — while the rest of this process still is the old version,
+ and the app would never come back. Loading the modules up front pins them
+ to the version that started the helper; the later imports are then served
+ from ``sys.modules``.
+ """
+ import importlib
+
+ names = _MODULES_NEEDED_AFTER_UPDATE
+ if sys.platform == "darwin":
+ names = (*names, *_MACOS_MODULES_NEEDED_AFTER_UPDATE)
+ for name in names:
+ try:
+ importlib.import_module(name)
+ except Exception: # noqa: BLE001 - the restart must still be attempted
+ logging.getLogger(__name__).warning(
+ "relauncher: could not preload %s", name, exc_info=True
+ )
+
+
def _report_restart_failure(old_pid: int, *, still_alive: bool) -> None:
"""Say out loud that the restart did not bring the app back.
diff --git a/jarvis/ui/web/update_routes.py b/jarvis/ui/web/update_routes.py
index 0002dff4bb..27ec88a31b 100644
--- a/jarvis/ui/web/update_routes.py
+++ b/jarvis/ui/web/update_routes.py
@@ -88,13 +88,22 @@ from jarvis.core.installer_update import (
apply_installer,
download_and_verify,
download_workdir,
- installer_asset_name,
+ installer_asset_names,
machine_for_update,
select_asset,
+ select_installer_assets,
sweep_stale_downloads,
update_blocker,
)
from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS
+from jarvis.core.update_contract import (
+ CONTRACT_PATH,
+ DEFAULT_CONTRACT,
+ VERSION_PATTERN,
+ UpdateContract,
+ parse_update_contract,
+ read_update_contract,
+)
log = logging.getLogger(__name__)
@@ -151,6 +160,19 @@ def _running_version() -> str:
return "unknown"
+def _version_sources(contract: UpdateContract) -> tuple[tuple[str, str], ...]:
+ """``(path, pattern)`` pairs that can name a tree's version, best first.
+
+ The version file is the one the tree itself names in its update contract,
+ so a release that moved its package is still read correctly by the version
+ before it. ``pyproject.toml`` never moves and stays the fallback.
+ """
+ return (
+ (contract.version_file, VERSION_PATTERN),
+ ("pyproject.toml", r'^version\s*=\s*"([^"]+)"'),
+ )
+
+
def _version_on_disk(root: Path) -> str | None:
"""Parse the version from the freshly-pulled files on disk.
@@ -158,12 +180,9 @@ def _version_on_disk(root: Path) -> str | None:
memory is still the OLD version, so the post-update version must be read
from disk, not from ``jarvis.__version__``.
"""
- for rel, pattern in (
- (Path("jarvis") / "__init__.py", r'__version__\s*=\s*"([^"]+)"'),
- (Path("pyproject.toml"), r'^version\s*=\s*"([^"]+)"'),
- ):
+ for rel, pattern in _version_sources(read_update_contract(root)):
try:
- text = (root / rel).read_text(encoding="utf-8")
+ text = root.joinpath(*rel.split("/")).read_text(encoding="utf-8")
except OSError:
# Not "file absent" alone — an unreadable version file makes the
# installed version look older than it is, which shows up as an
@@ -673,12 +692,16 @@ async def _pending_update_overlay(root: Path) -> dict[str, Any]:
async def _version_at_revision(root: Path, revision: str) -> str | None:
- """Read a target version without checking that target out over the live app."""
+ """Read a target version without checking that target out over the live app.
- for rel, pattern in (
- ("jarvis/__init__.py", r'__version__\s*=\s*"([^"]+)"'),
- ("pyproject.toml", r'^version\s*=\s*"([^"]+)"'),
- ):
+ Where the version is written is asked of the TARGET revision's own update
+ contract, not assumed from this version's layout. A revision without a
+ contract keeps its version where every such release keeps it.
+ """
+
+ raw_contract = await _git_output(["show", f"{revision}:{CONTRACT_PATH}"], cwd=root)
+ contract = DEFAULT_CONTRACT if raw_contract is None else parse_update_contract(raw_contract)
+ for rel, pattern in _version_sources(contract):
raw = await _git_output(["show", f"{revision}:{rel}"], cwd=root)
if raw is None:
continue
@@ -893,9 +916,9 @@ def _on_git_progress(line: str) -> None:
_progress.advance(PHASE_DOWNLOADING, low + (high - low) * share)
-def _frozen_asset_name() -> str | None:
- """The installer asset this machine installs, or ``None`` if there is none."""
- return installer_asset_name(sys.platform, machine_for_update())
+def _frozen_asset_names() -> tuple[str, ...]:
+ """The installer assets this machine can install, best first; empty if none."""
+ return installer_asset_names(sys.platform, machine_for_update())
# Old update downloads are reclaimed once per process, on the first status
@@ -915,13 +938,20 @@ async def _sweep_old_downloads_once() -> None:
def _frozen_release_assets(
- release: dict[str, Any], asset_name: str
-) -> tuple[Any | None, Any | None]:
- """``(installer asset, checksum manifest asset)`` from a release payload."""
+ release: dict[str, Any], asset_names: tuple[str, ...]
+) -> tuple[tuple[Any, ...], Any | None]:
+ """``(installer assets, checksum manifest asset)`` from a release payload.
+
+ The installers are this machine's file under every accepted name the
+ release carries, best first — one entry for any release published so far.
+ """
assets = release.get("assets") or []
if not isinstance(assets, list):
- return None, None
- return select_asset(assets, asset_name), select_asset(assets, CHECKSUMS_ASSET_NAME)
+ return (), None
+ return (
+ select_installer_assets(assets, asset_names),
+ select_asset(assets, CHECKSUMS_ASSET_NAME),
+ )
async def _frozen_status(current: str) -> dict[str, object]:
@@ -958,8 +988,8 @@ async def _frozen_status(current: str) -> dict[str, object]:
}
await _sweep_old_downloads_once()
- asset_name = _frozen_asset_name()
- if asset_name is None:
+ asset_names = _frozen_asset_names()
+ if not asset_names:
# No installer is published for this OS/CPU pair (a Windows ARM64 box,
# a Linux aarch64 box). Never offer what cannot be installed.
log.info(
@@ -977,7 +1007,8 @@ async def _frozen_status(current: str) -> dict[str, object]:
return result
version = str(latest.get("version") or "")
- asset, checksums = _frozen_release_assets(latest, asset_name)
+ installers, checksums = _frozen_release_assets(latest, asset_names)
+ asset = installers[0] if installers else None
result["latest"] = version or None
result["published_at"] = latest.get("published_at")
result["release_url"] = latest.get("release_url")
@@ -988,7 +1019,7 @@ async def _frozen_status(current: str) -> dict[str, object]:
log.info(
"[update] release %s carries no %s / %s — not offering a frozen update",
version or "?",
- asset_name,
+ " / ".join(asset_names),
CHECKSUMS_ASSET_NAME,
)
return result
@@ -1079,8 +1110,8 @@ async def _apply_frozen(
_progress.begin(INSTALL_KIND_FROZEN)
_refuse_if_missions_run(request, force=force)
current = _running_version()
- asset_name = _frozen_asset_name()
- if asset_name is None:
+ asset_names = _frozen_asset_names()
+ if not asset_names:
raise HTTPException(
status_code=501,
detail=(
@@ -1112,12 +1143,13 @@ async def _apply_frozen(
if not _is_newer(release_version, current):
raise HTTPException(status_code=409, detail="no newer published release exists")
- asset, checksums = _frozen_release_assets(latest, asset_name)
- if asset is None:
+ installers, checksums = _frozen_release_assets(latest, asset_names)
+ if not installers:
raise HTTPException(
status_code=502,
- detail=f"release {release_tag} does not contain {asset_name}",
+ detail=f"release {release_tag} does not contain {' or '.join(asset_names)}",
)
+ asset = installers[0]
if checksums is None:
raise HTTPException(
status_code=502,
@@ -1149,9 +1181,21 @@ async def _apply_frozen(
workdir = download_workdir()
try:
_progress.enter(PHASE_DOWNLOADING, detail=asset.name)
- installer = await download_and_verify(
- asset, checksums, dest_dir=workdir, on_progress=on_bytes
- )
+ if len(installers) > 1:
+ # The release carries this installer under more than one accepted
+ # name; the checksum manifest decides which of them is downloaded.
+ installer = await download_and_verify(
+ asset,
+ checksums,
+ dest_dir=workdir,
+ on_progress=on_bytes,
+ alternatives=installers[1:],
+ )
+ asset = next((a for a in installers if a.name == installer.name), asset)
+ else:
+ installer = await download_and_verify(
+ asset, checksums, dest_dir=workdir, on_progress=on_bytes
+ )
# download_and_verify hashes the file after the last byte lands, so by
# the time it returns the verify phase is already over — the window is
# closed here rather than announced, to keep the bar truthful.
diff --git a/tests/unit/cli/test_app_update.py b/tests/unit/cli/test_app_update.py
index c1a52b01c8..a5f27717bd 100644
--- a/tests/unit/cli/test_app_update.py
+++ b/tests/unit/cli/test_app_update.py
@@ -3,6 +3,9 @@
from __future__ import annotations
import json
+import os
+import subprocess
+import sys
from pathlib import Path
import pytest
@@ -16,6 +19,7 @@ from jarvis.cli.app_update import (
PROBE_FLAG,
run_update,
)
+from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS
from jarvis.ui.relauncher import UPDATE_RESULT_FILENAME
@@ -209,3 +213,103 @@ def test_jarvis_main_routes_update(monkeypatch):
)
assert entry.main(["update", "--check"]) == 0
assert seen == [True]
+
+
+# --------------------------------------------------------------------------- #
+# 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 jarvis.cli import app_update
+from jarvis.cli.app_update import FINALIZE_FLAG, PROBE_FLAG
+
+root = Path(sys.argv[1])
+outcome = json.loads(sys.argv[2])
+
+
+class PackageIsGone(importlib.abc.MetaPathFinder):
+ def __init__(self):
+ self.late = []
+
+ def find_spec(self, name, path=None, target=None):
+ if name == "jarvis" or name.startswith("jarvis."):
+ 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}))
+"""
+
+
+ ("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
diff --git a/tests/unit/core/test_installer_update.py b/tests/unit/core/test_installer_update.py
index adb74f1a87..1567b2328a 100644
--- a/tests/unit/core/test_installer_update.py
+++ b/tests/unit/core/test_installer_update.py
@@ -12,6 +12,7 @@ from __future__ import annotations
import asyncio
import hashlib
import os
+import plistlib
import shutil
import stat
import subprocess
@@ -33,11 +34,13 @@ from jarvis.core.installer_update import (
download_and_verify,
handover_env,
installer_asset_name,
+ installer_asset_names,
machine_for_update,
parse_sha256sums,
relaunch_after_exit_command,
select_asset,
select_installer_asset,
+ select_installer_assets,
sweep_stale_downloads,
update_blocker,
)
@@ -111,6 +114,80 @@ def test_select_installer_asset_picks_this_machines_file() -> None:
assert picked.name == "PersonalJarvis-macOS-arm64.dmg"
+ ("platform_name", "machine", "expected"),
+ [
+ ("win32", "AMD64", ("Dodaios-Setup-x64.exe", "PersonalJarvis-Setup-x64.exe")),
+ ("darwin", "arm64", ("Dodaios-macOS-arm64.dmg", "PersonalJarvis-macOS-arm64.dmg")),
+ ("darwin", "x86_64", ("Dodaios-macOS-x64.dmg", "PersonalJarvis-macOS-x64.dmg")),
+ (
+ "linux",
+ "x86_64",
+ ("Dodaios-Linux-x86_64.AppImage", "PersonalJarvis-Linux-x86_64.AppImage"),
+ ),
+ ],
+)
+def test_installer_asset_names_lists_every_accepted_name_best_first(
+ platform_name: str, machine: str, expected: tuple[str, ...]
+) -> None:
+ assert installer_asset_names(platform_name, machine) == expected
+ # The name every published release carries stays the single-name answer.
+ assert installer_asset_name(platform_name, machine) == expected[-1]
+
+
+def test_unsupported_platforms_accept_no_name() -> None:
+ assert installer_asset_names("win32", "ARM64") == ()
+ assert installer_asset_names("freebsd", "x86_64") == ()
+
+
+def test_every_accepted_name_belongs_to_exactly_one_platform() -> None:
+ """One table, no name twice: a name must never resolve to two machines."""
+ names = [name for row in iu.INSTALLER_ASSET_NAMES.values() for name in row]
+ assert len(names) == len(set(names))
+ assert all(len(row) == 2 for row in iu.INSTALLER_ASSET_NAMES.values())
+
+
+def test_the_updater_accepts_every_installer_the_release_pipeline_publishes() -> None:
+ """A published installer the updater does not know is an update nobody gets."""
+ from scripts.ci import release_assets
+
+ by_system = {
+ system: {name for (row_system, _cpu), row in iu.INSTALLER_ASSET_NAMES.items()
+ if row_system == system for name in row}
+ for system in ("windows", "macos", "linux")
+ }
+ assert set(release_assets.PLATFORM_INSTALLERS) == set(by_system)
+ for system, published in release_assets.PLATFORM_INSTALLERS.items():
+ assert published <= by_system[system], system
+ assert release_assets.INSTALLERS == set().union(*release_assets.PLATFORM_INSTALLERS.values())
+
+
+def test_select_installer_asset_prefers_the_first_accepted_name() -> None:
+ assets = _release_assets(
+ "PersonalJarvis-macOS-arm64.dmg",
+ "Dodaios-macOS-arm64.dmg",
+ CHECKSUMS_ASSET_NAME,
+ )
+ picked = select_installer_asset(assets, platform_name="darwin", machine="arm64")
+ assert picked is not None
+ assert picked.name == "Dodaios-macOS-arm64.dmg"
+
+
+def test_select_installer_asset_takes_the_only_name_a_release_carries() -> None:
+ for name in installer_asset_names("linux", "x86_64"):
+ assets = _release_assets(name, CHECKSUMS_ASSET_NAME)
+ picked = select_installer_asset(assets, platform_name="linux", machine="x86_64")
+ assert picked is not None
+ assert picked.name == name
+
+
+def test_select_installer_assets_keeps_the_order_of_the_names() -> None:
+ names = installer_asset_names("win32", "AMD64")
+ assets = _release_assets(*reversed(names), "PersonalJarvis-macOS-x64.dmg")
+ assert [asset.name for asset in select_installer_assets(assets, names)] == list(names)
+ assert select_installer_assets([], names) == ()
+
+
def test_select_asset_rejects_a_non_https_url() -> None:
assets = [{"name": "x.exe", "browser_download_url": "http://example.invalid/x.exe"}]
assert select_asset(assets, "x.exe") is None
@@ -191,6 +268,90 @@ async def test_download_and_verify_refuses_when_the_manifest_omits_the_asset(
)
+async def test_download_and_verify_takes_the_first_name_the_manifest_vouches_for(
+ tmp_path: Path,
+) -> None:
+ preferred = _asset("Dodaios-Setup-x64.exe")
+ published = _asset("PersonalJarvis-Setup-x64.exe")
+ both = f"{PAYLOAD_SHA256} {preferred.name}\n{PAYLOAD_SHA256} {published.name}\n"
+ fetcher = FakeAssetFetcher(manifest=both, payload=PAYLOAD)
+
+ result = await download_and_verify(
+ preferred,
+ _asset(CHECKSUMS_ASSET_NAME),
+ dest_dir=tmp_path,
+ fetcher=fetcher,
+ alternatives=[published],
+ )
+
+ assert result == tmp_path / preferred.name
+ assert fetcher.download_urls == [preferred.url]
+
+
+async def test_download_and_verify_skips_a_name_the_manifest_does_not_list(
+ tmp_path: Path,
+) -> None:
+ """Present in the release is not enough: only a checksummed file is fetched."""
+ preferred = _asset("Dodaios-Setup-x64.exe")
+ published = _asset("PersonalJarvis-Setup-x64.exe")
+ fetcher = FakeAssetFetcher(
+ manifest=f"{PAYLOAD_SHA256} {published.name}\n", payload=PAYLOAD
+ )
+
+ result = await download_and_verify(
+ preferred,
+ _asset(CHECKSUMS_ASSET_NAME),
+ dest_dir=tmp_path,
+ fetcher=fetcher,
+ alternatives=[published],
+ )
+
+ assert result == tmp_path / published.name
+ assert fetcher.download_urls == [published.url]
+ assert not (tmp_path / preferred.name).exists()
+
+
+async def test_download_and_verify_refuses_when_no_accepted_name_is_listed(
+ tmp_path: Path,
+) -> None:
+ preferred = _asset("Dodaios-Setup-x64.exe")
+ published = _asset("PersonalJarvis-Setup-x64.exe")
+ fetcher = FakeAssetFetcher(
+ manifest=f"{PAYLOAD_SHA256} PersonalJarvis-macOS-arm64.dmg\n", payload=PAYLOAD
+ )
+ with pytest.raises(InstallerUpdateError, match="no entry") as excinfo:
+ await download_and_verify(
+ preferred,
+ _asset(CHECKSUMS_ASSET_NAME),
+ dest_dir=tmp_path,
+ fetcher=fetcher,
+ alternatives=[published],
+ )
+ assert preferred.name in str(excinfo.value)
+ assert published.name in str(excinfo.value)
+ assert fetcher.download_urls == []
+
+
+async def test_download_and_verify_applies_the_size_cap_to_the_chosen_file(
+ tmp_path: Path,
+) -> None:
+ preferred = _asset("Dodaios-Setup-x64.exe")
+ published = _asset("PersonalJarvis-Setup-x64.exe", size=10_000)
+ fetcher = FakeAssetFetcher(
+ manifest=f"{PAYLOAD_SHA256} {published.name}\n", payload=PAYLOAD
+ )
+ with pytest.raises(InstallerUpdateError, match="cap"):
+ await download_and_verify(
+ preferred,
+ _asset(CHECKSUMS_ASSET_NAME),
+ dest_dir=tmp_path,
+ fetcher=fetcher,
+ max_bytes=1_000,
+ alternatives=[published],
+ )
+ assert fetcher.download_urls == []
+
+
async def test_download_and_verify_refuses_an_oversized_asset(tmp_path: Path) -> None:
asset = _asset("PersonalJarvis-Setup-x64.exe", size=10_000)
fetcher = FakeAssetFetcher(manifest=f"{PAYLOAD_SHA256} {asset.name}\n", payload=PAYLOAD)
@@ -307,16 +468,30 @@ def test_handover_refuses_an_unsupported_platform(tmp_path: Path) -> None:
# --------------------------------------------------------------------------- #
# macOS handover
# --------------------------------------------------------------------------- #
-def _mounting_runner(app_name: str, payload: str) -> FakeCommandRunner:
+def _write_bundle(app: Path, payload: str, bundle_id: str | None = None) -> None:
+ """A minimal ``.app``: one executable, plus an ``Info.plist`` when identified."""
+ macos = app / "Contents" / "MacOS"
+ macos.mkdir(parents=True, exist_ok=True)
+ (macos / "PersonalJarvis").write_text(payload, encoding="utf-8")
+ if bundle_id is not None:
+ with (app / "Contents" / "Info.plist").open("wb") as stream:
+ plistlib.dump({"CFBundleIdentifier": bundle_id}, stream)
+
+
+def _bundle_payload(app: Path) -> str:
+ return (app / "Contents" / "MacOS" / "PersonalJarvis").read_text(encoding="utf-8")
+
+
+def _mounting_runner(
+ app_name: str, payload: str, bundle_id: str | None = None
+) -> FakeCommandRunner:
"""A runner whose ``hdiutil attach`` really populates the mountpoint."""
def _mount(command: list[str]) -> None:
if len(command) < 2 or command[1] != "attach":
return
mountpoint = Path(command[command.index("-mountpoint") + 1])
- bundle = mountpoint / app_name / "Contents" / "MacOS"
- bundle.mkdir(parents=True, exist_ok=True)
- (bundle / "PersonalJarvis").write_text(payload, encoding="utf-8")
+ _write_bundle(mountpoint / app_name, payload, bundle_id)
def _detach(command: list[str]) -> None:
# A real detach empties the mountpoint; the updater then removes the
@@ -386,19 +561,208 @@ def test_macos_handover_refuses_without_a_resolvable_app(tmp_path: Path) -> None
)
+# A disk image whose bundle is named differently from the running app is a
+# release that renamed the app. The names below are arbitrary on purpose: the
+# handover must not depend on knowing the new name in advance.
+OLD_APP_NAME = "Personal Jarvis.app"
+NEW_APP_NAME = "Renamed Product.app"
+NEW_BUNDLE_ID = "ai.renamed.desktop"
+
+# These cases rename freshly written directories, which a Windows virus scanner
+# can hold open for a moment. The swap only ever runs on macOS, so the cases
+# run wherever such a rename is reliable.
+renames_bundles = pytest.mark.skipif(
+ sys.platform == "win32",
+ reason="the .app swap only runs on macOS; Windows scanners can briefly lock a renamed dir",
+)
+
+
+@renames_bundles
+ "running_name",
+ [
+ "Personal Jarvis 2.app", # Finder's "Keep Both"
+ "Assistant.app", # renamed by hand
+ "personal jarvis.app", # same name, other case
+ ],
+)
def test_macos_handover_falls_back_to_the_only_bundle_on_the_volume(
- tmp_path: Path,
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, running_name: str
) -> None:
+ """A bundle the USER renamed is updated in place, never duplicated.
+
+ The disk image still carries the app under the name this version ships
+ with. That is not a release renaming the app: the update goes into the
+ bundle the user launched, and nothing is installed beside it or deleted.
+ """
dmg = tmp_path / "PersonalJarvis-macOS-x64.dmg"
dmg.write_bytes(PAYLOAD)
- app = tmp_path / "Applications" / "Personal Jarvis.app"
- (app / "Contents").mkdir(parents=True)
+ app = tmp_path / "Applications" / running_name
+ _write_bundle(app, "old", iu.MACOS_DMG_BUNDLE_ID)
+ other_copy = tmp_path / "Applications" / "Untouched Copy.app"
+ _write_bundle(other_copy, "the user's second copy", iu.MACOS_DMG_BUNDLE_ID)
+
+ def _forbidden(_bundle: Path) -> str | None:
+ raise AssertionError("an in-place update must not weigh bundle identifiers")
+
+ monkeypatch.setattr(iu, "_macos_bundle_identifier", _forbidden)
+ runner = _mounting_runner(iu.MACOS_APP_DIR_NAME, "new", iu.MACOS_DMG_BUNDLE_ID)
+
+ apply_installer(dmg, platform_name="darwin", runner=runner, app_path=app, wait_for_pid=5)
+
+ assert _bundle_payload(app) == "new"
+ assert _bundle_payload(other_copy) == "the user's second copy"
+ assert runner.spawned == [relaunch_after_exit_command(5, [MACOS_OPEN, "-n", str(app)])]
+ # Nothing new appeared next to it, and no staging leftover survived.
+ assert sorted(p.name.casefold() for p in app.parent.iterdir()) == sorted(
+ [running_name.casefold(), "untouched copy.app"]
+ )
+
+
+def _renamed_release(tmp_path: Path, *, running_id: str | None) -> tuple[Path, Path, Path]:
+ """``(dmg, running app, where the renamed app belongs)``."""
+ dmg = tmp_path / "Dodaios-macOS-arm64.dmg"
+ dmg.write_bytes(PAYLOAD)
+ app = tmp_path / "Applications" / OLD_APP_NAME
+ _write_bundle(app, "old", running_id)
+ return dmg, app, app.with_name(NEW_APP_NAME)
+
+
+@renames_bundles
[email protected]("running_id", sorted(iu._OWN_MACOS_BUNDLE_IDS))
+def test_macos_handover_installs_a_renamed_bundle_beside_the_running_one(
+ tmp_path: Path, running_id: str
+) -> None:
+ dmg, app, renamed = _renamed_release(tmp_path, running_id=running_id)
+ runner = _mounting_runner(NEW_APP_NAME, "new", NEW_BUNDLE_ID)
+
+ message = apply_installer(
+ dmg, platform_name="darwin", runner=runner, app_path=app, wait_for_pid=4242
+ )
+
+ # Under its own name, in the same folder - never inside the old-named one.
+ assert _bundle_payload(renamed) == "new"
+ assert not (app / "Contents" / "MacOS" / "PersonalJarvis").exists()
+ # The NEW path is what comes back; the old one no longer exists to open.
+ assert runner.spawned == [
+ relaunch_after_exit_command(4242, [MACOS_OPEN, "-n", str(renamed)])
+ ]
+ # The superseded bundle is gone, and so is every staging leftover.
+ assert not app.exists()
+ assert sorted(p.name for p in app.parent.iterdir()) == [NEW_APP_NAME]
+ assert NEW_APP_NAME in message and OLD_APP_NAME in message
+
+
+@renames_bundles
[email protected]("running_id", [None, "com.example.someone-else"])
+def test_macos_handover_keeps_a_superseded_bundle_it_cannot_identify(
+ tmp_path: Path, running_id: str | None
+) -> None:
+ """Only a bundle that names one of our identifiers is ever deleted."""
+ dmg, app, renamed = _renamed_release(tmp_path, running_id=running_id)
+ runner = _mounting_runner(NEW_APP_NAME, "new", NEW_BUNDLE_ID)
+
+ apply_installer(dmg, platform_name="darwin", runner=runner, app_path=app, wait_for_pid=7)
+
+ assert _bundle_payload(renamed) == "new"
+ assert _bundle_payload(app) == "old"
+ assert runner.spawned == [relaunch_after_exit_command(7, [MACOS_OPEN, "-n", str(renamed)])]
+
+
+@renames_bundles
+def test_macos_handover_updates_a_renamed_bundle_that_is_already_installed(
+ tmp_path: Path,
+) -> None:
+ dmg, app, renamed = _renamed_release(tmp_path, running_id=iu.MACOS_DMG_BUNDLE_ID)
+ _write_bundle(renamed, "earlier copy", NEW_BUNDLE_ID)
+ runner = _mounting_runner(NEW_APP_NAME, "new", NEW_BUNDLE_ID)
- # The DMG names the bundle differently from the installed one; there is
- # still exactly one, so the swap is unambiguous.
- runner = _mounting_runner("Personal Jarvis 2.app", "new")
apply_installer(dmg, platform_name="darwin", runner=runner, app_path=app)
- assert (app / "Contents" / "MacOS" / "PersonalJarvis").read_text(encoding="utf-8") == "new"
+
+ assert _bundle_payload(renamed) == "new"
+ assert not app.exists()
+
+
[email protected]("squatter_id", [None, "com.example.someone-else"])
+def test_macos_handover_never_overwrites_an_unrelated_app_with_the_new_name(
+ tmp_path: Path, squatter_id: str | None
+) -> None:
+ dmg, app, renamed = _renamed_release(tmp_path, running_id=iu.MACOS_DMG_BUNDLE_ID)
+ _write_bundle(renamed, "someone else", squatter_id)
+ runner = _mounting_runner(NEW_APP_NAME, "new", NEW_BUNDLE_ID)
+
+ with pytest.raises(InstallerUpdateError, match="different application"):
+ apply_installer(dmg, platform_name="darwin", runner=runner, app_path=app)
+
+ assert _bundle_payload(renamed) == "someone else"
+ assert _bundle_payload(app) == "old"
+ assert runner.spawned == []
+ assert any(cmd[:2] == ["hdiutil", "detach"] for cmd in runner.ran)
+
+
+def test_macos_handover_keeps_the_running_app_when_the_renamed_copy_fails(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ dmg, app, renamed = _renamed_release(tmp_path, running_id=iu.MACOS_DMG_BUNDLE_ID)
+ runner = _mounting_runner(NEW_APP_NAME, "new", NEW_BUNDLE_ID)
+
+ def _disk_full(*_args: object, **_kwargs: object) -> None:
+ raise OSError("disk full")
+
+ monkeypatch.setattr(shutil, "copytree", _disk_full)
+
+ with pytest.raises(InstallerUpdateError, match="could not stage"):
+ apply_installer(dmg, platform_name="darwin", runner=runner, app_path=app)
+
+ # The copy never completed, so the bundle the user started is untouched.
+ assert _bundle_payload(app) == "old"
+ assert not renamed.exists()
+ assert runner.spawned == []
+
+
+@renames_bundles
+def test_macos_handover_survives_a_superseded_bundle_that_cannot_be_removed(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ dmg, app, renamed = _renamed_release(tmp_path, running_id=iu.MACOS_DMG_BUNDLE_ID)
+ runner = _mounting_runner(NEW_APP_NAME, "new", NEW_BUNDLE_ID)
+ real_replace = os.replace
+
+ def _locked(src: object, dst: object) -> None:
+ if Path(str(src)) == app:
+ raise OSError("resource busy")
+ real_replace(src, dst)
+
+ monkeypatch.setattr(os, "replace", _locked)
+
+ apply_installer(dmg, platform_name="darwin", runner=runner, app_path=app, wait_for_pid=9)
+
+ # The update itself succeeded: the new app is installed and relaunched.
+ assert _bundle_payload(renamed) == "new"
+ assert _bundle_payload(app) == "old"
+ assert runner.spawned == [relaunch_after_exit_command(9, [MACOS_OPEN, "-n", str(renamed)])]
+
+
+@renames_bundles
+def test_macos_same_name_handover_never_reads_a_bundle_identifier(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """The in-place swap is the unchanged path: no ownership logic runs for it."""
+ dmg = tmp_path / "PersonalJarvis-macOS-arm64.dmg"
+ dmg.write_bytes(PAYLOAD)
+ app = tmp_path / "Applications" / OLD_APP_NAME
+ _write_bundle(app, "old")
+
+ def _forbidden(_bundle: Path) -> str | None:
+ raise AssertionError("a same-name update must not inspect bundle identifiers")
+
+ monkeypatch.setattr(iu, "_macos_bundle_identifier", _forbidden)
+ runner = _mounting_runner(OLD_APP_NAME, "new")
+
+ apply_installer(dmg, platform_name="darwin", runner=runner, app_path=app, wait_for_pid=3)
+
+ assert _bundle_payload(app) == "new"
+ assert runner.spawned == [relaunch_after_exit_command(3, [MACOS_OPEN, "-n", str(app)])]
# --------------------------------------------------------------------------- #
diff --git a/tests/unit/core/test_update_contract.py b/tests/unit/core/test_update_contract.py
new file mode 100644
index 0000000000..4441889363
--- /dev/null
+++ b/tests/unit/core/test_update_contract.py
@@ -0,0 +1,365 @@
+"""``jarvis.core.update_contract`` — where a release tells its updater to look.
+
+Two things are pinned here. The tracked ``install/update-contract.json`` must
+describe THIS tree truthfully, because the version before a release believes
+it. And the reader must fall back to the default locations for anything it
+cannot trust, because those locations are what an update is checked against.
+"""
+
+from __future__ import annotations
+
+import json
+import re
+import subprocess
+import sys
+from dataclasses import asdict
+from pathlib import Path
+
+import pytest
+
+import jarvis
+from jarvis.core.branding import CONFIG_FILE_NAME, MACOS_APP_DIR_NAME, MACOS_BUNDLE_ID
+from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS
+from jarvis.core.update_contract import (
+ CONTRACT_PATH,
+ CONTRACT_SCHEMA,
+ DEFAULT_CONTRACT,
+ VERSION_PATTERN,
+ UpdateContract,
+ parse_update_contract,
+ read_update_contract,
+)
+
+REPO = Path(__file__).resolve().parents[3]
+
+
+def _document(**overrides: object) -> str:
+ return json.dumps({"schema": CONTRACT_SCHEMA, **overrides})
+
+
+# --------------------------------------------------------------------------- #
+# The tracked contract describes this tree
+# --------------------------------------------------------------------------- #
+def test_the_tracked_contract_is_the_default_contract() -> None:
+ """A release without the file must behave exactly like this one."""
+ payload = json.loads((REPO / CONTRACT_PATH).read_text(encoding="utf-8"))
+ assert payload.pop("schema") == CONTRACT_SCHEMA
+ stated = {key: value for key, value in asdict(DEFAULT_CONTRACT).items() if value is not None}
+ assert payload == stated
+ assert read_update_contract(REPO) == DEFAULT_CONTRACT
+
+
+def test_the_contract_points_at_files_this_tree_really_has() -> None:
+ contract = read_update_contract(REPO)
+
+ assert (REPO / contract.ui_bundle_dir / "index.html").is_file()
+ assert (REPO / (contract.launcher_module.replace(".", "/") + ".py")).is_file()
+
+ version_text = (REPO / contract.version_file).read_text(encoding="utf-8")
+ match = re.search(VERSION_PATTERN, version_text)
+ assert match is not None
+ assert match.group(1) == jarvis.__version__
+
+
+def test_the_contract_agrees_with_every_other_copy_of_these_names() -> None:
+ from jarvis.autostart.command import LAUNCHER_MODULE as autostart_launcher
+ from jarvis.ui import relauncher
+
+ assert DEFAULT_CONTRACT.config_file == CONFIG_FILE_NAME
+ assert DEFAULT_CONTRACT.macos_app_dir_name == MACOS_APP_DIR_NAME
+ assert DEFAULT_CONTRACT.macos_bundle_id == MACOS_BUNDLE_ID
+ assert DEFAULT_CONTRACT.launcher_module == autostart_launcher
+ assert relauncher.LAUNCHER_MODULE == DEFAULT_CONTRACT.launcher_module
+ assert DEFAULT_CONTRACT.rollback_hook is None
+
+
+def test_the_reader_is_standard_library_only() -> None:
+ """The restart helper loads it; it must not drag the runtime in."""
+ probe = (
+ "import sys\n"
+ "import jarvis.core.update_contract\n"
+ "print('\\n'.join(sorted(m for m in sys.modules if m.split('.')[0] in "
+ "{'pydantic', 'fastapi', 'httpx', 'loguru'})))\n"
+ )
+ proc = subprocess.run( # noqa: S603 - fixed argv, this interpreter
+ [sys.executable, "-c", probe],
+ capture_output=True,
+ text=True,
+ encoding="utf-8",
+ errors="replace",
+ timeout=120,
+ cwd=str(REPO),
+ creationflags=NO_WINDOW_CREATIONFLAGS,
+ )
+ assert proc.returncode == 0, proc.stderr
+ assert proc.stdout.strip() == ""
+
+
+# --------------------------------------------------------------------------- #
+# Reading
+# --------------------------------------------------------------------------- #
+def test_a_tree_without_the_file_gets_the_default_locations(tmp_path: Path) -> None:
+ assert read_update_contract(tmp_path) == DEFAULT_CONTRACT
+
+
+def test_a_moved_tree_is_read_as_it_describes_itself(tmp_path: Path) -> None:
+ (tmp_path / "install").mkdir()
+ (tmp_path / CONTRACT_PATH).write_text(
+ _document(
+ ui_bundle_dir="newpkg/ui/web/dist",
+ launcher_module="newpkg.ui.web.launcher",
+ version_file="newpkg/__init__.py",
+ config_file="newpkg.toml",
+ macos_app_dir_name="New Product.app",
+ macos_bundle_id="com.new-product.desktop",
+ rollback_hook="install/rollback.py",
+ ),
+ encoding="utf-8",
+ )
+ assert read_update_contract(tmp_path) == UpdateContract(
+ ui_bundle_dir="newpkg/ui/web/dist",
+ launcher_module="newpkg.ui.web.launcher",
+ version_file="newpkg/__init__.py",
+ config_file="newpkg.toml",
+ macos_app_dir_name="New Product.app",
+ macos_bundle_id="com.new-product.desktop",
+ rollback_hook="install/rollback.py",
+ )
+
+
+def test_a_key_the_document_leaves_out_keeps_its_default() -> None:
+ contract = parse_update_contract(_document(launcher_module="newpkg.launcher"))
+ assert contract.launcher_module == "newpkg.launcher"
+ assert contract.ui_bundle_dir == DEFAULT_CONTRACT.ui_bundle_dir
+ assert contract.config_file == DEFAULT_CONTRACT.config_file
+
+
+def test_an_unknown_key_is_ignored() -> None:
+ contract = parse_update_contract(_document(config_file="x.toml", data_dir="somewhere"))
+ assert contract.config_file == "x.toml"
+
+
+def test_an_explicit_null_hook_means_no_hook() -> None:
+ assert parse_update_contract(_document(rollback_hook=None)).rollback_hook is None
+
+
+def test_a_byte_order_mark_does_not_hide_the_contract(tmp_path: Path) -> None:
+ (tmp_path / "install").mkdir()
+ (tmp_path / CONTRACT_PATH).write_bytes(
+ b"\xef\xbb\xbf" + _document(config_file="x.toml").encode("utf-8")
+ )
+ assert read_update_contract(tmp_path).config_file == "x.toml"
+
+
+# --------------------------------------------------------------------------- #
+# Refusing
+# --------------------------------------------------------------------------- #
+ "text",
+ [
+ "",
+ "not json",
+ "[]",
+ '"jarvis/ui/web/dist"',
+ json.dumps({"ui_bundle_dir": "newpkg/dist"}), # no schema at all
+ json.dumps({"schema": 2, "ui_bundle_dir": "newpkg/dist"}),
+ json.dumps({"schema": "1", "ui_bundle_dir": "newpkg/dist"}),
+ json.dumps({"schema": True, "ui_bundle_dir": "newpkg/dist"}),
+ json.dumps({"schema": 1.0, "ui_bundle_dir": "newpkg/dist"}),
+ ],
+)
+def test_an_unreadable_or_unknown_document_is_the_default_contract(text: str) -> None:
+ assert parse_update_contract(text) == DEFAULT_CONTRACT
+
+
+ "bad_path",
+ [
+ "/etc/passwd",
+ "../outside/dist",
+ "pkg/../../outside",
+ "pkg/./dist",
+ "./pkg/dist",
+ "pkg//dist",
+ "pkg/dist/",
+ "C:/Windows/System32",
+ "C:\\Windows\\System32",
+ "pkg\\ui\\dist",
+ "pkg/ui dist",
+ "~/dist",
+ "$HOME/dist",
+ "pkg/dist\n",
+ "",
+ "x" * 300,
+ 42,
+ None,
+ ["pkg", "dist"],
+ ],
+)
[email protected]("field", ["ui_bundle_dir", "version_file"])
+def test_a_path_that_could_leave_the_checkout_rejects_the_document(
+ field: str, bad_path: object
+) -> None:
+ text = _document(**{field: bad_path, "launcher_module": "newpkg.launcher"})
+ # The valid launcher is dropped too: a document is believed whole or not at all.
+ assert parse_update_contract(text) == DEFAULT_CONTRACT
+
+
+ "bad_module",
+ [
+ "newpkg.launcher; import os",
+ "newpkg launcher",
+ "newpkg..launcher",
+ ".newpkg.launcher",
+ "newpkg.launcher.",
+ "1newpkg.launcher",
+ "newpkg/launcher",
+ "-c",
+ "newpkg.launcher\n",
+ "",
+ 7,
+ None,
+ ],
+)
+def test_a_launcher_that_is_not_a_module_name_rejects_the_document(
+ bad_module: object,
+) -> None:
+ assert parse_update_contract(_document(launcher_module=bad_module)) == DEFAULT_CONTRACT
+
+
+ "bad_name", ["sub/dir.toml", "..", ".", "a\\b.toml", "", "name with space.toml", 3, None]
+)
+def test_a_config_name_that_is_not_a_plain_file_name_rejects_the_document(
+ bad_name: object,
+) -> None:
+ assert parse_update_contract(_document(config_file=bad_name)) == DEFAULT_CONTRACT
+
+
+ "bad_name", ["Product", "../Evil.app", "sub/Product.app", ".app", " Product.app", "", 5, None]
+)
+def test_an_app_name_that_is_not_one_bundle_directory_rejects_the_document(
+ bad_name: object,
+) -> None:
+ assert parse_update_contract(_document(macos_app_dir_name=bad_name)) == DEFAULT_CONTRACT
+
+
+ "bad_id",
+ ["desktop", "com..desktop", ".com.app", "com.app.", "com/app", "com.app name", "", 9, None],
+)
+def test_a_bundle_id_that_is_not_a_reverse_dns_name_rejects_the_document(
+ bad_id: object,
+) -> None:
+ assert parse_update_contract(_document(macos_bundle_id=bad_id)) == DEFAULT_CONTRACT
+
+
+ "bad_hook",
+ ["../rollback.py", "/opt/rollback.py", "install/rollback.sh", "install/rollback", "", 1, []],
+)
+def test_a_hook_that_is_not_a_script_inside_the_tree_rejects_the_document(
+ bad_hook: object,
+) -> None:
+ assert parse_update_contract(_document(rollback_hook=bad_hook)) == DEFAULT_CONTRACT
+
+
+def test_an_oversized_file_is_not_a_contract(tmp_path: Path) -> None:
+ (tmp_path / "install").mkdir()
+ padded = json.dumps(
+ {"schema": CONTRACT_SCHEMA, "config_file": "x.toml", "padding": "p" * 20_000}
+ )
+ (tmp_path / CONTRACT_PATH).write_text(padded, encoding="utf-8")
+ assert read_update_contract(tmp_path) == DEFAULT_CONTRACT
+
+
+def test_a_file_that_is_not_utf8_is_not_a_contract(tmp_path: Path) -> None:
+ (tmp_path / "install").mkdir()
+ (tmp_path / CONTRACT_PATH).write_bytes(b'{"schema": 1, "config_file": "\xff\xfe.toml"}')
+ assert read_update_contract(tmp_path) == DEFAULT_CONTRACT
+
+
+# --------------------------------------------------------------------------- #
+# Schema 1, frozen
+# --------------------------------------------------------------------------- #
+# The exact document this version ships, and documents a later release may
+# publish for this version to read. An installed copy keeps the reader it was
+# released with, so these must keep parsing to these values: tightening a rule
+# here silently turns a published contract into "use the defaults", which for a
+# release that moved its files means every update rolls back.
+SCHEMA_1_GOLDEN = [
+ (
+ """{
+ "schema": 1,
+ "ui_bundle_dir": "jarvis/ui/web/dist",
+ "launcher_module": "jarvis.ui.web.launcher",
+ "version_file": "jarvis/__init__.py",
+ "config_file": "jarvis.toml",
+ "macos_app_dir_name": "Personal Jarvis.app",
+ "macos_bundle_id": "com.personal-jarvis.desktop"
+}
+""",
+ UpdateContract(
+ ui_bundle_dir="jarvis/ui/web/dist",
+ launcher_module="jarvis.ui.web.launcher",
+ version_file="jarvis/__init__.py",
+ config_file="jarvis.toml",
+ macos_app_dir_name="Personal Jarvis.app",
+ macos_bundle_id="com.personal-jarvis.desktop",
+ rollback_hook=None,
+ ),
+ ),
+ (
+ '{"schema": 1, "ui_bundle_dir": "dodaios/ui/web/dist",'
+ ' "launcher_module": "dodaios.ui.web.launcher",'
+ ' "version_file": "dodaios/__init__.py", "config_file": "dodaios.toml",'
+ ' "macos_app_dir_name": "Dodaios.app", "macos_bundle_id": "ai.dodaios.desktop",'
+ ' "rollback_hook": "install/rollback_hook.py", "a_key_from_the_future": [1, 2]}',
+ UpdateContract(
+ ui_bundle_dir="dodaios/ui/web/dist",
+ launcher_module="dodaios.ui.web.launcher",
+ version_file="dodaios/__init__.py",
+ config_file="dodaios.toml",
+ macos_app_dir_name="Dodaios.app",
+ macos_bundle_id="ai.dodaios.desktop",
+ rollback_hook="install/rollback_hook.py",
+ ),
+ ),
+ (
+ '{"schema": 1, "ui_bundle_dir": "src/app_2/ui.web/dist-prod",'
+ ' "launcher_module": "_app2.ui.web.launcher_v2",'
+ ' "version_file": "src/app_2/_version.py", "config_file": ".app-2.toml",'
+ ' "macos_app_dir_name": "App 2 (beta)-x.app"}',
+ None, # the app name carries parentheses, which no rule allows
+ ),
+ (
+ '{"schema": 1, "ui_bundle_dir": "src/app_2/ui.web/dist-prod",'
+ ' "launcher_module": "_app2.ui.web.launcher_v2",'
+ ' "version_file": "src/app_2/_version.py", "config_file": ".app-2.toml",'
+ ' "macos_app_dir_name": "App 2 beta-x.app", "macos_bundle_id": "io.app-2.Desktop"}',
+ UpdateContract(
+ ui_bundle_dir="src/app_2/ui.web/dist-prod",
+ launcher_module="_app2.ui.web.launcher_v2",
+ version_file="src/app_2/_version.py",
+ config_file=".app-2.toml",
+ macos_app_dir_name="App 2 beta-x.app",
+ macos_bundle_id="io.app-2.Desktop",
+ rollback_hook=None,
+ ),
+ ),
+]
+
+
[email protected](("document", "expected"), SCHEMA_1_GOLDEN)
+def test_schema_1_documents_keep_their_meaning(
+ document: str, expected: UpdateContract | None
+) -> None:
+ assert parse_update_contract(document) == (expected or DEFAULT_CONTRACT)
+
+
+def test_the_shipped_contract_is_the_first_golden_document() -> None:
+ """Byte for byte: what an installed copy of the previous version will read."""
+ shipped = (REPO / CONTRACT_PATH).read_bytes().replace(b"\r\n", b"\n")
+ assert shipped.decode("utf-8") == SCHEMA_1_GOLDEN[0][0]
diff --git a/tests/unit/install/test_install_sh_python_detection.py b/tests/unit/install/test_install_sh_python_detection.py
index b16bf14836..0cdfb98dde 100644
--- a/tests/unit/install/test_install_sh_python_detection.py
+++ b/tests/unit/install/test_install_sh_python_detection.py
@@ -259,10 +259,12 @@ def test_update_run_stops_the_live_app_before_touching_the_venv() -> None:
half-rewritten venv underneath — 'the app is already open but nothing
works'. install.sh must stop instances of THIS install before phase 3."""
src = INSTALL_SH.read_text(encoding="utf-8")
- assert 'pkill -f "$VENV_PATH"' in src
+ assert '_stop_venv="$INSTALL_DIR/.venv"' in src
+ assert 'pkill -f "$_stop_venv"' in src
assert "stopped the running Jarvis app for the update" in src
# The stop must come BEFORE the venv rebuild block.
- assert src.index("stopped the running Jarvis app") < src.index(
+ environment = src.split("phase '3/6' 'Python environment'", 1)[1]
+ assert environment.index("\nstop_running_app\n") < environment.index(
"rebuilding the Python environment"
)
diff --git a/tests/unit/install/test_install_stops_app_first.py b/tests/unit/install/test_install_stops_app_first.py
new file mode 100644
index 0000000000..1d8a2e1a48
--- /dev/null
+++ b/tests/unit/install/test_install_stops_app_first.py
@@ -0,0 +1,900 @@
+"""A re-run quick installer stops the running app before it replaces the checkout.
+
+A release may move or delete files the live app still loads. Both shell
+installers therefore stop every app running out of THIS install right before
+its files change - after the download, so a failed download leaves a working
+app behind - and refuse outright when they were started from inside that app,
+because stopping it would end the installer too. The stop logic is run for
+real here - the blocks extracted from ``install/install.sh`` and the functions
+extracted from ``install/install.ps1`` - so the shipped scripts cannot drift
+from what is tested, and the order of the steps is pinned from the scripts'
+own text.
+"""
+from __future__ import annotations
+
+import os
+import re
+import shutil
+import subprocess
+import sys
+import time
+from pathlib import Path
+
+import pytest
+
+from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS
+from jarvis.ui.relauncher import pid_alive
+
+REPO = Path(__file__).resolve().parents[3]
+INSTALL_SH = REPO / "install" / "install.sh"
+INSTALL_PS1 = REPO / "install" / "install.ps1"
+
+BLOCK_BEGIN = "# --- stop-running-app begin"
+BLOCK_END = "# --- stop-running-app end"
+STOPPED_NOTE = "NOTE|stopped the running Jarvis app for the update"
+INSIDE_APP = "ERR|this installer was started from inside the running app."
+GUARD_BEGIN = "# --- salvage-guard begin"
+GUARD_END = "# --- salvage-guard end"
+UNREACHABLE = "ERR|cannot reach the download server right now - nothing was changed."
+
+SLEEPER = "import os, sys, time; print(os.getpid(), flush=True); time.sleep(300)"
+
+# Every command the block reaches for is a recording stand-in, so the same
+# logic runs on any host with bash - including Git Bash, which has no pkill.
+# They record to a file, because the block silences some of them on stdout.
+SH_STUB_DRIVER = """#!/usr/bin/env bash
+set -euo pipefail
+record() { printf '%s\\n' "$*" >> "$CALL_LOG"; }
+note() { printf 'NOTE|%s\\n' "$*"; }
+err() { printf 'ERR|%s\\n' "$*"; }
+# ``ps [-ww] -o <field>= -p <pid>`` answered from FAKE_PS_TABLE (pid|ppid|args
+# per line). SELF stands for this script, whose real pid the block starts from.
+ps() {
+ record "PS|$*"
+ _ps_field=''
+ _ps_pid=''
+ while [ "$#" -gt 0 ]; do
+ case "$1" in
+ -o) _ps_field="$2"; shift ;;
+ -p) _ps_pid="$2"; shift ;;
+ esac
+ shift
+ done
+ [ "$_ps_pid" = "$$" ] && _ps_pid=SELF
+ printf '%s\\n' "${FAKE_PS_TABLE:-}" | while IFS='|' read -r _p _pp _a; do
+ [ "$_p" = "$_ps_pid" ] || continue
+ case "$_ps_field" in
+ ppid=) printf '%s\\n' "$_pp" ;;
+ args=) printf '%s\\n' "$_a" ;;
+ esac
+ done
+}
+pkill() { record "PKILL|$*"; [ "${FAKE_APP_RUNNING:-0}" = "1" ]; }
+pgrep() { record "PGREP|$*"; [ "${FAKE_APP_LINGERS:-0}" = "1" ]; }
+sleep() { record "SLEEP|$*"; }
+uname() { printf '%s\\n' "${FAKE_UNAME:-Linux}"; }
+launchctl() { record "LAUNCHCTL|$*"; }
+source "$BLOCK_FILE"
+source "$BLOCK_FILE"
+printf 'DONE\\n'
+"""
+
+# Real pkill/pgrep against real processes. ``launchctl`` stays a stand-in on
+# purpose: the real one would unload the developer's own autostart agent.
+SH_REAL_DRIVER = """#!/usr/bin/env bash
+set -euo pipefail
+note() { printf 'NOTE|%s\\n' "$*"; }
+err() { printf 'ERR|%s\\n' "$*"; }
+launchctl() { printf 'LAUNCHCTL|%s\\n' "$*"; }
+source "$BLOCK_FILE"
+source "$BLOCK_FILE"
+printf 'DONE\\n'
+"""
+
+# The salvage path asks the repository before it stops or moves anything.
+SH_GUARD_DRIVER = """#!/usr/bin/env bash
+set -euo pipefail
+note() { printf 'NOTE|%s\\n' "$*"; }
+err() { printf 'ERR|%s\\n' "$*"; }
+git() { printf 'GIT|%s\\n' "$*" >> "$CALL_LOG"; [ "${FAKE_REMOTE_ANSWERS:-0}" = "1" ]; }
+curl() { printf 'CURL|%s\\n' "$*" >> "$CALL_LOG"; [ "${FAKE_ARCHIVE_ANSWERS:-0}" = "1" ]; }
+stop_running_app() { printf 'STOP|\\n' >> "$CALL_LOG"; }
+GIT_NET_OPTS='-c http.lowSpeedLimit=1024'
+source "$GUARD_FILE"
+printf 'DONE\\n'
+"""
+
+PS_DRIVER = """$ErrorActionPreference = 'Stop'
+function Write-Note([string]$Text) { Write-Host "NOTE|$Text" }
+function Write-Err([string]$Text) { Write-Host "ERR|$Text" }
+$InstallDir = $env:TEST_INSTALL_DIR
+. $env:TEST_FUNCTION_FILE
+Stop-RunningApp
+Stop-RunningApp
+Write-Host 'DONE'
+"""
+
+PS_REACHABLE_DRIVER = """$ErrorActionPreference = 'Stop'
+$GitNetOpts = @('-c', 'http.lowSpeedLimit=1024')
+$RepoUrl = $env:TEST_REPO_URL
+if ($env:TEST_GIT_EXIT) {
+ # Stand-ins for both transports: a function wins over a program of its name.
+ function git { $global:LASTEXITCODE = [int]$env:TEST_GIT_EXIT }
+ function curl.exe {
+ Write-Host "CURL|$($args -join ' ')"
+ $global:LASTEXITCODE = [int]$env:TEST_CURL_EXIT
+ }
+}
+. $env:TEST_FUNCTION_FILE
+Write-Host "REACHABLE|$(Test-RepositoryReachable)"
+"""
+
+# Runs the installer's stop function as a child of a process that lives in the
+# install's venv - what a terminal inside the app looks like to the installer.
+INSIDE_APP_LAUNCHER = (
+ "import subprocess, sys; "
+ "sys.exit(subprocess.run(sys.argv[2:], check=False).returncode)"
+)
+
+PS_PARSE = """$errors = $null
+$tokens = $null
+[void][System.Management.Automation.Language.Parser]::ParseFile(
+ $env:TEST_SCRIPT, [ref]$tokens, [ref]$errors)
+foreach ($e in $errors) { Write-Host "PARSE|$($e.Extent.StartLineNumber)|$($e.Message)" }
+Write-Host "ERRORS|$($errors.Count)"
+"""
+
+GIT = shutil.which("git")
+
+
+def _find_bash() -> str | None:
+ if GIT:
+ for rel in ("../bin/bash.exe", "../../bin/bash.exe", "../usr/bin/bash.exe"):
+ cand = (Path(GIT).parent / rel).resolve()
+ if cand.exists():
+ return str(cand)
+ bash = shutil.which("bash")
+ if bash and not any(t in bash.lower() for t in ("windowsapps", "system32")):
+ return bash
+ return None
+
+
+BASH = _find_bash()
+POWERSHELL = shutil.which("pwsh") or shutil.which("powershell")
+
+needs_bash = pytest.mark.skipif(BASH is None, reason="no usable bash on this host")
+needs_powershell = pytest.mark.skipif(POWERSHELL is None, reason="no PowerShell on this host")
+posix_only = pytest.mark.skipif(
+ os.name != "posix" or shutil.which("pkill") is None or shutil.which("pgrep") is None,
+ reason="needs a POSIX host with pkill and pgrep",
+)
+windows_only = pytest.mark.skipif(
+ sys.platform != "win32", reason="process lookup by image path is Windows-only"
+)
+
+
+def _run(
+ args: list[str], *, env: dict[str, str] | None = None, timeout: float = 120
+) -> subprocess.CompletedProcess[str]:
+ return subprocess.run( # noqa: S603 -- test-controlled command
+ args,
+ capture_output=True,
+ text=True,
+ encoding="utf-8",
+ errors="replace",
+ timeout=timeout,
+ env=env,
+ creationflags=NO_WINDOW_CREATIONFLAGS,
+ )
+
+
+def _sh_path(path: Path) -> str:
+ return str(path).replace("\\", "/")
+
+
+def _sh_block(tmp_path: Path) -> Path:
+ source = INSTALL_SH.read_text(encoding="utf-8")
+ assert BLOCK_BEGIN in source and BLOCK_END in source, (
+ "the stop-running-app extraction markers vanished from install.sh"
+ )
+ block = tmp_path / "block.sh"
+ block.write_text(
+ source.split(BLOCK_BEGIN, 1)[1].split("\n", 1)[1].split(BLOCK_END, 1)[0],
+ encoding="utf-8",
+ newline="\n",
+ )
+ return block
+
+
+def _run_sh(
+ tmp_path: Path, install_dir: Path, driver_text: str, **overrides: str
+) -> subprocess.CompletedProcess[str]:
+ driver = tmp_path / "driver.sh"
+ driver.write_text(driver_text, encoding="utf-8", newline="\n")
+ env = dict(os.environ)
+ (tmp_path / "calls.log").write_text("", encoding="utf-8")
+ env.update(
+ BLOCK_FILE=_sh_path(_sh_block(tmp_path)),
+ CALL_LOG=_sh_path(tmp_path / "calls.log"),
+ INSTALL_DIR=_sh_path(install_dir),
+ MACOS_AUTOSTART_LABEL="com.example.autostart",
+ HOME=_sh_path(tmp_path / "home"),
+ **overrides,
+ )
+ return _run([str(BASH), str(driver)], env=env)
+
+
+def _fake_posix_venv(tmp_path: Path) -> Path:
+ """An install dir whose venv has an executable ``bin/python``."""
+ install_dir = tmp_path / "install"
+ python = install_dir / ".venv" / "bin" / "python"
+ python.parent.mkdir(parents=True)
+ python.write_text("#!/bin/sh\nexit 0\n", encoding="utf-8", newline="\n")
+ python.chmod(0o755)
+ return install_dir
+
+
+def _lines(proc: subprocess.CompletedProcess[str], prefix: str) -> list[str]:
+ return [line for line in proc.stdout.splitlines() if line.startswith(prefix)]
+
+
+def _calls(tmp_path: Path, prefix: str) -> list[str]:
+ """What the stand-in commands were asked to do, in order."""
+ log = (tmp_path / "calls.log").read_text(encoding="utf-8")
+ return [line for line in log.splitlines() if line.startswith(prefix)]
+
+
+# --------------------------------------------------------------------------- #
+# Order: download, stop, then replace
+# --------------------------------------------------------------------------- #
+def test_sh_stops_the_app_after_the_fetch_and_before_the_reset() -> None:
+ source = INSTALL_SH.read_text(encoding="utf-8")
+ update = source.split('if [ -d "$INSTALL_DIR/.git" ]; then\n', 1)[1]
+ update, rest = update.split('\nelif [ -e "$INSTALL_DIR" ]; then\n', 1)
+ leftover = rest.split("\nelse\n", 1)[0]
+
+ fetch = update.index(" fetch ")
+ stop = update.index("&& stop_running_app")
+ # A fetch only writes inside .git: a failed one must leave the app running.
+ assert fetch < stop
+ assert stop < update.index(" checkout ")
+ assert stop < update.index("reset --quiet --hard")
+ assert update.count("stop_running_app") == 1
+ # A directory that is not a checkout goes through the salvage path, which
+ # owns its own stop.
+ assert "stop_running_app" not in leftover
+ assert "salvage_reclone" in leftover
+
+
+def test_sh_salvage_asks_the_repository_then_stops_then_moves() -> None:
+ source = INSTALL_SH.read_text(encoding="utf-8")
+ salvage = source.split("salvage_reclone() {\n", 1)[1].split("\n}\n", 1)[0]
+
+ reachable = salvage.index("ls-remote")
+ stop = salvage.index("stop_running_app")
+ move = salvage.index('mv "$INSTALL_DIR"')
+ assert reachable < stop < move
+ assert move < salvage.index("fetch_payload")
+
+
+def test_sh_still_stops_the_app_before_the_environment_is_rebuilt() -> None:
+ source = INSTALL_SH.read_text(encoding="utf-8")
+ environment = source.split("phase '3/6' 'Python environment'", 1)[1]
+ stop = environment.index("\nstop_running_app\n")
+ assert stop < environment.index('rm -rf "$VENV_PATH"')
+ assert stop < environment.index("-m venv")
+ assert stop < environment.index("pip install")
+
+
+def test_sh_keeps_one_copy_of_the_stop_logic() -> None:
+ source = INSTALL_SH.read_text(encoding="utf-8")
+ assert source.count("pkill ") == 1
+ assert source.count("launchctl unload") == 1
+ assert source.count("stop_running_app() {") == 1
+
+
+def test_ps1_stops_the_app_after_the_fetch_and_before_the_reset() -> None:
+ source = INSTALL_PS1.read_text(encoding="utf-8")
+ update = source.split("if (Test-Path (Join-Path $InstallDir '.git')) {\n", 1)[1]
+ update, rest = update.split("\n} else {\n", 1)
+ leftover = rest.split("\n } else {\n", 1)[0]
+ attempt = update.split("\n } finally {\n", 1)[0]
+
+ fetch = attempt.index(" fetch ")
+ stop = attempt.index("Stop-RunningApp")
+ assert fetch < stop
+ assert stop < attempt.index(" checkout ")
+ assert stop < attempt.index("reset --quiet --hard")
+ assert attempt.count("Stop-RunningApp") == 1
+ # Only reached when the fetch succeeded.
+ guarded = attempt[attempt.rindex("if ($UpdateOk) {", 0, stop) : stop]
+ assert guarded.count("\n") == 1
+ assert "Stop-RunningApp" not in leftover
+ assert "Invoke-SalvageReclone" in leftover
+
+
+def test_ps1_salvage_asks_the_repository_then_stops_then_moves() -> None:
+ source = INSTALL_PS1.read_text(encoding="utf-8")
+ salvage = source.split("function Invoke-SalvageReclone {\n", 1)[1].split("\n}\n", 1)[0]
+
+ reachable = salvage.index("Test-RepositoryReachable")
+ stop = salvage.index("Stop-RunningApp")
+ move = salvage.index("Move-Item")
+ assert reachable < stop < move
+ assert move < salvage.index("Invoke-FetchPayload")
+
+
+def test_ps1_still_stops_the_app_before_the_environment_is_rebuilt() -> None:
+ source = INSTALL_PS1.read_text(encoding="utf-8")
+ environment = source.split("Write-Phase '3/6' 'Python environment'", 1)[1]
+ stop = environment.index("\nStop-RunningApp\n")
+ assert stop < environment.index("-m venv")
+ assert stop < environment.index("pip install")
+
+
+def test_ps1_keeps_one_copy_of_the_stop_logic() -> None:
+ source = INSTALL_PS1.read_text(encoding="utf-8")
+ assert source.count("Stop-Process ") == 1
+ assert source.count("function Stop-RunningApp {") == 1
+
+
+# --------------------------------------------------------------------------- #
+# The scripts still parse
+# --------------------------------------------------------------------------- #
+@needs_bash
+def test_install_sh_is_valid_bash() -> None:
+ proc = _run([str(BASH), "-n", str(INSTALL_SH)])
+ assert proc.returncode == 0, proc.stderr
+
+
+@needs_powershell
+def test_install_ps1_parses_without_errors(tmp_path: Path) -> None:
+ script = tmp_path / "parse.ps1"
+ script.write_text(PS_PARSE, encoding="utf-8")
+ env = dict(os.environ)
+ env["TEST_SCRIPT"] = str(INSTALL_PS1)
+ proc = _run(
+ [
+ str(POWERSHELL),
+ "-NoProfile",
+ "-NonInteractive",
+ "-ExecutionPolicy",
+ "Bypass",
+ "-File",
+ str(script),
+ ],
+ env=env,
+ )
+ assert proc.returncode == 0, proc.stderr
+ assert "ERRORS|0" in proc.stdout, proc.stdout
+
+
+# --------------------------------------------------------------------------- #
+# install.sh: the extracted block, on every host with bash
+# --------------------------------------------------------------------------- #
+@needs_bash
+def test_sh_does_nothing_for_a_directory_without_an_environment(tmp_path: Path) -> None:
+ install_dir = tmp_path / "install"
+ install_dir.mkdir()
+ proc = _run_sh(tmp_path, install_dir, SH_STUB_DRIVER, FAKE_APP_RUNNING="1")
+ assert proc.returncode == 0, proc.stderr
+ assert proc.stdout.strip() == "DONE"
+
+
+@needs_bash
+def test_sh_stops_a_running_app_and_waits_for_it_to_be_gone(tmp_path: Path) -> None:
+ install_dir = _fake_posix_venv(tmp_path)
+ proc = _run_sh(tmp_path, install_dir, SH_STUB_DRIVER, FAKE_APP_RUNNING="1")
+
+ assert proc.returncode == 0, proc.stderr
+ venv = _sh_path(install_dir / ".venv")
+ # Scoped to THIS install: the pattern is its venv, nothing broader.
+ assert set(_calls(tmp_path, "PKILL|")) == {f"PKILL|-f {venv}"}
+ assert set(_calls(tmp_path, "PGREP|")) == {f"PGREP|-f {venv}"}
+ assert STOPPED_NOTE in proc.stdout
+ assert _calls(tmp_path, "SLEEP|") == [] # it was gone at the first look
+ assert _calls(tmp_path, "LAUNCHCTL|") == [] # not macOS
+ assert proc.stdout.strip().endswith("DONE")
+
+
+@needs_bash
+def test_sh_gives_up_waiting_for_an_app_that_ignores_the_signal(tmp_path: Path) -> None:
+ install_dir = _fake_posix_venv(tmp_path)
+ proc = _run_sh(
+ tmp_path, install_dir, SH_STUB_DRIVER, FAKE_APP_RUNNING="1", FAKE_APP_LINGERS="1"
+ )
+ assert proc.returncode == 0, proc.stderr
+ # Two calls of the block, fifty short waits each - bounded, then it moves on.
+ assert len(_calls(tmp_path, "SLEEP|")) == 100
+ assert proc.stdout.strip().endswith("DONE")
+
+
+@needs_bash
+def test_sh_is_quiet_when_no_app_is_running(tmp_path: Path) -> None:
+ install_dir = _fake_posix_venv(tmp_path)
+ proc = _run_sh(tmp_path, install_dir, SH_STUB_DRIVER)
+ assert proc.returncode == 0, proc.stderr
+ assert len(_calls(tmp_path, "PKILL|")) == 2 # asked both times, found nothing
+ assert "NOTE|" not in proc.stdout
+ assert _calls(tmp_path, "PGREP|") == []
+ assert proc.stdout.strip().endswith("DONE")
+
+
+@needs_bash
+def test_sh_unloads_the_macos_autostart_agent(tmp_path: Path) -> None:
+ install_dir = _fake_posix_venv(tmp_path)
+ proc = _run_sh(tmp_path, install_dir, SH_STUB_DRIVER, FAKE_UNAME="Darwin")
+ assert proc.returncode == 0, proc.stderr
+ # Unloaded whether or not a process was found: launchd would start it again.
+ unloads = _calls(tmp_path, "LAUNCHCTL|")
+ assert len(unloads) == 2
+ for call in unloads:
+ # Compared by its tail: Git Bash rewrites the drive part of $HOME.
+ assert call.startswith("LAUNCHCTL|unload ")
+ assert call.endswith("/home/Library/LaunchAgents/com.example.autostart.plist")
+
+
+def _start_sleeper(python: Path | str, *args: str) -> tuple[subprocess.Popen[str], int]:
+ """Start a long sleep and return ``(process, pid of the interpreter)``."""
+ proc = subprocess.Popen( # noqa: S603 -- test-controlled command
+ [str(python), "-c", SLEEPER, *args],
+ stdin=subprocess.DEVNULL,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.DEVNULL,
+ text=True,
+ encoding="utf-8",
+ creationflags=NO_WINDOW_CREATIONFLAGS,
+ )
+ assert proc.stdout is not None
+ return proc, int(proc.stdout.readline().strip())
+
+
+def _wait_until_gone(pid: int, timeout: float = 15.0) -> bool:
+ deadline = time.monotonic() + timeout
+ while time.monotonic() < deadline:
+ if not pid_alive(pid):
+ return True
+ time.sleep(0.1)
+ return not pid_alive(pid)
+
+
+def _end(*procs: subprocess.Popen[str]) -> None:
+ for proc in procs:
+ if proc.poll() is None:
+ proc.kill()
+ proc.wait(timeout=15)
+ if proc.stdout is not None:
+ proc.stdout.close()
+
+
+@needs_bash
+@posix_only
+def test_sh_really_stops_a_process_of_this_install_and_no_other(tmp_path: Path) -> None:
+ install_dir = tmp_path / "install"
+ venv_python = install_dir / ".venv" / "bin" / "python"
+ venv_python.parent.mkdir(parents=True)
+ venv_python.symlink_to(sys.executable)
+
+ # The app is found by the venv path on its command line. This interpreter
+ # carries it as an argument, so the test does not depend on how a symlinked
+ # Python locates its standard library on the host.
+ app, app_pid = _start_sleeper(sys.executable, str(venv_python))
+ bystander, bystander_pid = _start_sleeper(sys.executable)
+ try:
+ proc = _run_sh(tmp_path, install_dir, SH_REAL_DRIVER)
+
+ assert proc.returncode == 0, proc.stderr
+ assert STOPPED_NOTE in proc.stdout
+ assert app.wait(timeout=15) is not None
+ assert _wait_until_gone(app_pid)
+ # Another interpreter on the machine is none of the installer's business.
+ assert pid_alive(bystander_pid)
+ assert bystander.poll() is None
+ finally:
+ _end(app, bystander)
+
+
+# --------------------------------------------------------------------------- #
+# install.ps1: the extracted function
+# --------------------------------------------------------------------------- #
+def _run_ps(tmp_path: Path, install_dir: Path) -> subprocess.CompletedProcess[str]:
+ source = INSTALL_PS1.read_text(encoding="utf-8")
+ match = re.search(r"^function Stop-RunningApp \{\r?\n.*?^\}\r?$", source, re.S | re.M)
+ assert match is not None, "Stop-RunningApp vanished from install.ps1"
+ function_file = tmp_path / "function.ps1"
+ function_file.write_text(match.group(0), encoding="utf-8")
+ driver = tmp_path / "driver.ps1"
+ driver.write_text(PS_DRIVER, encoding="utf-8")
+ env = dict(os.environ)
+ env.update(TEST_INSTALL_DIR=str(install_dir), TEST_FUNCTION_FILE=str(function_file))
+ return _run(
+ [
+ str(POWERSHELL),
+ "-NoProfile",
+ "-NonInteractive",
+ "-ExecutionPolicy",
+ "Bypass",
+ "-File",
+ str(driver),
+ ],
+ env=env,
+ )
+
+
+@needs_powershell
+def test_ps1_does_nothing_for_a_directory_without_an_environment(tmp_path: Path) -> None:
+ install_dir = tmp_path / "install"
+ install_dir.mkdir()
+ proc = _run_ps(tmp_path, install_dir)
+ assert proc.returncode == 0, proc.stderr
+ assert proc.stdout.strip() == "DONE"
+
+
+@needs_powershell
+@windows_only
+def test_ps1_really_stops_processes_of_this_install_and_no_other(tmp_path: Path) -> None:
+ install_dir = tmp_path / "install"
+ venv = install_dir / ".venv"
+ created = _run([sys.executable, "-m", "venv", "--without-pip", str(venv)], timeout=300)
+ assert created.returncode == 0, created.stderr
+ scripts = venv / "Scripts"
+ # The desktop app usually runs as a renamed copy of the venv launcher, so
+ # the image name must not decide what belongs to this install.
+ branded = scripts / "RenamedLauncher.exe"
+ shutil.copy2(scripts / "python.exe", branded)
+
+ app, app_pid = _start_sleeper(scripts / "python.exe")
+ renamed, renamed_pid = _start_sleeper(branded)
+ bystander, bystander_pid = _start_sleeper(sys.executable)
+ try:
+ proc = _run_ps(tmp_path, install_dir)
+
+ assert proc.returncode == 0, proc.stderr
+ # Stopped on the first call; the second finds nothing and says nothing.
+ assert _lines(proc, "NOTE|") == [STOPPED_NOTE]
+ assert proc.stdout.strip().endswith("DONE")
+ for stopped, pid in ((app, app_pid), (renamed, renamed_pid)):
+ assert stopped.wait(timeout=15) is not None
+ # The interpreter behind the venv launcher goes down with it.
+ assert _wait_until_gone(pid)
+ assert pid_alive(bystander_pid)
+ assert bystander.poll() is None
+ finally:
+ _end(app, renamed, bystander)
+
+
+# --------------------------------------------------------------------------- #
+# The installer never stops the process tree it runs in
+# --------------------------------------------------------------------------- #
+def _ps_table(*rows: tuple[str, str, str]) -> str:
+ return "\n".join("|".join(row) for row in rows)
+
+
+@needs_bash
+ "ancestors",
+ [
+ # A terminal pane: the shell's parent is the app's terminal host.
+ [("SELF", "100", "bash install.sh"), ("100", "1", "VENV/bin/python -m jarvis.terminal")],
+ # Further up the chain counts just the same.
+ [
+ ("SELF", "100", "bash install.sh"),
+ ("100", "200", "/bin/zsh -l"),
+ ("200", "300", "VENV/bin/python -m jarvis.ui.web.launcher"),
+ ("300", "1", "/sbin/launchd"),
+ ],
+ # The script itself was started with a path inside the environment.
+ [("SELF", "100", "bash VENV/bin/some-wrapper"), ("100", "1", "/sbin/init")],
+ ],
+)
+def test_sh_refuses_before_stopping_anything_when_started_inside_the_app(
+ tmp_path: Path, ancestors: list[tuple[str, str, str]]
+) -> None:
+ install_dir = _fake_posix_venv(tmp_path)
+ venv = _sh_path(install_dir / ".venv")
+ table = _ps_table(*[(pid, ppid, args.replace("VENV", venv)) for pid, ppid, args in ancestors])
+
+ proc = _run_sh(
+ tmp_path, install_dir, SH_STUB_DRIVER, FAKE_APP_RUNNING="1", FAKE_PS_TABLE=table
+ )
+
+ assert proc.returncode == 1, proc.stdout + proc.stderr
+ assert INSIDE_APP in proc.stdout
+ assert "normal" in proc.stdout and "terminal outside the app" in proc.stdout
+ # Refused BEFORE the first signal: nothing was stopped, nothing unloaded.
+ assert _calls(tmp_path, "PKILL|") == []
+ assert _calls(tmp_path, "LAUNCHCTL|") == []
+ assert "DONE" not in proc.stdout
+
+
+@needs_bash
+def test_sh_stops_the_app_when_started_from_an_ordinary_terminal(tmp_path: Path) -> None:
+ install_dir = _fake_posix_venv(tmp_path)
+ table = _ps_table(
+ ("SELF", "100", "bash install.sh"),
+ ("100", "200", "/bin/zsh -l"),
+ ("200", "1", "/usr/bin/some-terminal"),
+ )
+ proc = _run_sh(
+ tmp_path, install_dir, SH_STUB_DRIVER, FAKE_APP_RUNNING="1", FAKE_PS_TABLE=table
+ )
+ assert proc.returncode == 0, proc.stderr
+ assert STOPPED_NOTE in proc.stdout
+ assert len(_calls(tmp_path, "PKILL|")) == 2
+ # The whole command line is asked for: BSD ps cuts it at the terminal
+ # width otherwise, and pkill matches against all of it.
+ looked_up = [call for call in _calls(tmp_path, "PS|") if "args=" in call]
+ assert looked_up and all(call.startswith("PS|-ww ") for call in looked_up)
+
+
+@needs_bash
+ "table",
+ [
+ # A process reported as its own parent ends the walk at once.
+ pytest.param(
+ _ps_table(("SELF", "100", "bash install.sh"), ("100", "100", "/bin/odd")),
+ id="own-parent",
+ ),
+ # A longer cycle runs into the depth bound. Dozens of subshells are
+ # slow under Git Bash, so that one runs where forking is cheap.
+ pytest.param(
+ _ps_table(
+ ("SELF", "100", "bash install.sh"),
+ ("100", "200", "/bin/a"),
+ ("200", "100", "/bin/b"),
+ ),
+ id="cycle",
+ marks=pytest.mark.skipif(sys.platform == "win32", reason="slow under Git Bash"),
+ ),
+ ],
+)
+def test_sh_gives_up_on_a_process_table_that_loops(tmp_path: Path, table: str) -> None:
+ install_dir = _fake_posix_venv(tmp_path)
+ proc = _run_sh(
+ tmp_path, install_dir, SH_STUB_DRIVER, FAKE_APP_RUNNING="1", FAKE_PS_TABLE=table
+ )
+ assert proc.returncode == 0, proc.stderr
+ assert proc.stdout.strip().endswith("DONE")
+
+
+@needs_bash
+@posix_only
+def test_sh_really_refuses_under_a_parent_from_this_install(tmp_path: Path) -> None:
+ install_dir = tmp_path / "install"
+ venv_python = install_dir / ".venv" / "bin" / "python"
+ venv_python.parent.mkdir(parents=True)
+ venv_python.symlink_to(sys.executable)
+ driver = tmp_path / "driver.sh"
+ driver.write_text(SH_REAL_DRIVER, encoding="utf-8", newline="\n")
+ env = dict(os.environ)
+ env.update(
+ BLOCK_FILE=str(_sh_block(tmp_path)),
+ INSTALL_DIR=str(install_dir),
+ MACOS_AUTOSTART_LABEL="com.example.autostart",
+ HOME=str(tmp_path / "home"),
+ )
+
+ app, app_pid = _start_sleeper(sys.executable, str(venv_python))
+ try:
+ # The parent carries the venv path on its command line, as the app's
+ # terminal host does; the installer block is its child.
+ proc = _run(
+ [sys.executable, "-c", INSIDE_APP_LAUNCHER, str(venv_python), str(BASH), str(driver)],
+ env=env,
+ )
+
+ assert proc.returncode == 1, proc.stdout + proc.stderr
+ assert INSIDE_APP in proc.stdout
+ assert STOPPED_NOTE not in proc.stdout
+ # The app it would have stopped is untouched.
+ assert pid_alive(app_pid)
+ assert app.poll() is None
+ finally:
+ _end(app)
+
+
+# --------------------------------------------------------------------------- #
+# The salvage path changes nothing while the repository is out of reach
+# --------------------------------------------------------------------------- #
+def _run_sh_guard(tmp_path: Path, **overrides: str) -> subprocess.CompletedProcess[str]:
+ source = INSTALL_SH.read_text(encoding="utf-8")
+ assert GUARD_BEGIN in source and GUARD_END in source, (
+ "the salvage-guard extraction markers vanished from install.sh"
+ )
+ guard = tmp_path / "guard.sh"
+ guard.write_text(
+ source.split(GUARD_BEGIN, 1)[1].split("\n", 1)[1].split(GUARD_END, 1)[0],
+ encoding="utf-8",
+ newline="\n",
+ )
+ driver = tmp_path / "driver.sh"
+ driver.write_text(SH_GUARD_DRIVER, encoding="utf-8", newline="\n")
+ (tmp_path / "calls.log").write_text("", encoding="utf-8")
+ env = dict(os.environ)
+ env.update(
+ {
+ "GUARD_FILE": _sh_path(guard),
+ "CALL_LOG": _sh_path(tmp_path / "calls.log"),
+ "REPO_URL": "https://example.invalid/owner/repo.git",
+ **overrides,
+ }
+ )
+ return _run([str(BASH), str(driver)], env=env)
+
+
+@needs_bash
+def test_sh_salvage_changes_nothing_when_the_repository_is_out_of_reach(
+ tmp_path: Path,
+) -> None:
+ proc = _run_sh_guard(tmp_path)
+
+ assert proc.returncode == 1, proc.stdout + proc.stderr
+ assert UNREACHABLE in proc.stdout
+ assert _calls(tmp_path, "STOP|") == []
+ assert "DONE" not in proc.stdout
+ asked = _calls(tmp_path, "GIT|")
+ assert len(asked) == 1
+ assert asked[0].endswith("ls-remote --quiet --heads https://example.invalid/owner/repo.git")
+ # The archive download only exists for the hosted repository.
+ assert _calls(tmp_path, "CURL|") == []
+
+
+@needs_bash
+def test_sh_salvage_stops_the_app_once_the_repository_answers(tmp_path: Path) -> None:
+ proc = _run_sh_guard(tmp_path, FAKE_REMOTE_ANSWERS="1")
+
+ assert proc.returncode == 0, proc.stderr
+ assert "ERR|" not in proc.stdout
+ assert _calls(tmp_path, "STOP|") == ["STOP|"]
+ assert proc.stdout.strip().endswith("DONE")
+
+
+GITHUB_REPO_URL = "https://github.com/owner/repo.git"
+
+
+@needs_bash
+def test_sh_salvage_goes_on_when_only_the_archive_download_gets_through(
+ tmp_path: Path,
+) -> None:
+ """git blocked, HTTPS open: an install that came from the archive still updates."""
+ proc = _run_sh_guard(tmp_path, REPO_URL=GITHUB_REPO_URL, FAKE_ARCHIVE_ANSWERS="1")
+
+ assert proc.returncode == 0, proc.stderr
+ assert "ERR|" not in proc.stdout
+ assert len(_calls(tmp_path, "GIT|")) == 1
+ probes = _calls(tmp_path, "CURL|")
+ assert len(probes) == 1
+ assert probes[0].endswith(" https://github.com/owner/repo")
+ assert _calls(tmp_path, "STOP|") == ["STOP|"]
+ assert proc.stdout.strip().endswith("DONE")
+
+
+@needs_bash
+def test_sh_salvage_changes_nothing_when_neither_transport_answers(tmp_path: Path) -> None:
+ proc = _run_sh_guard(tmp_path, REPO_URL=GITHUB_REPO_URL)
+
+ assert proc.returncode == 1, proc.stdout + proc.stderr
+ assert UNREACHABLE in proc.stdout
+ assert len(_calls(tmp_path, "CURL|")) == 1
+ assert _calls(tmp_path, "STOP|") == []
+ assert "DONE" not in proc.stdout
+
+
+def _ps_function(name: str) -> str:
+ source = INSTALL_PS1.read_text(encoding="utf-8")
+ match = re.search(rf"^function {name} \{{\r?\n.*?^\}}\r?$", source, re.S | re.M)
+ assert match is not None, f"{name} vanished from install.ps1"
+ return match.group(0)
+
+
+def _powershell(script: Path) -> list[str]:
+ return [
+ str(POWERSHELL),
+ "-NoProfile",
+ "-NonInteractive",
+ "-ExecutionPolicy",
+ "Bypass",
+ "-File",
+ str(script),
+ ]
+
+
+@needs_powershell
[email protected](GIT is None, reason="git is not installed")
+def test_ps1_tells_a_reachable_repository_from_an_unreachable_one(tmp_path: Path) -> None:
+ function_file = tmp_path / "function.ps1"
+ function_file.write_text(_ps_function("Test-RepositoryReachable"), encoding="utf-8")
+ driver = tmp_path / "driver.ps1"
+ driver.write_text(PS_REACHABLE_DRIVER, encoding="utf-8")
+ bare = tmp_path / "origin.git"
+ assert _run([str(GIT), "init", "--quiet", "--bare", str(bare)]).returncode == 0
+
+ answers = {}
+ for label, url in (("there", str(bare)), ("gone", str(tmp_path / "no-such-repo.git"))):
+ env = dict(os.environ)
+ env.update(TEST_REPO_URL=url, TEST_FUNCTION_FILE=str(function_file))
+ proc = _run(_powershell(driver), env=env)
+ assert proc.returncode == 0, proc.stderr
+ answers[label] = _lines(proc, "REACHABLE|")
+
+ assert answers == {"there": ["REACHABLE|True"], "gone": ["REACHABLE|False"]}
+
+
+@needs_powershell
+ ("repo_url", "git_exit", "curl_exit", "reachable", "probes"),
+ [
+ # git answers: nothing else is asked.
+ (GITHUB_REPO_URL, "0", "7", "True", 0),
+ # git blocked, HTTPS open: the archive download would get through.
+ (GITHUB_REPO_URL, "128", "0", "True", 1),
+ (GITHUB_REPO_URL, "128", "7", "False", 1),
+ # The archive download only exists for the hosted repository.
+ ("https://example.invalid/owner/repo.git", "128", "0", "False", 0),
+ ],
+)
+def test_ps1_counts_the_archive_download_as_a_way_to_reach_the_repository(
+ tmp_path: Path, repo_url: str, git_exit: str, curl_exit: str, reachable: str, probes: int
+) -> None:
+ function_file = tmp_path / "function.ps1"
+ function_file.write_text(_ps_function("Test-RepositoryReachable"), encoding="utf-8")
+ driver = tmp_path / "driver.ps1"
+ driver.write_text(PS_REACHABLE_DRIVER, encoding="utf-8")
+ env = dict(os.environ)
+ env.update(
+ TEST_REPO_URL=repo_url,
+ TEST_FUNCTION_FILE=str(function_file),
+ TEST_GIT_EXIT=git_exit,
+ TEST_CURL_EXIT=curl_exit,
+ )
+
+ proc = _run(_powershell(driver), env=env)
+
+ assert proc.returncode == 0, proc.stderr
+ assert _lines(proc, "REACHABLE|") == [f"REACHABLE|{reachable}"]
+ asked = _lines(proc, "CURL|")
+ assert len(asked) == probes
+ for call in asked:
+ assert call.endswith(" https://github.com/owner/repo")
+
+
+@needs_powershell
+@windows_only
+def test_ps1_really_refuses_under_a_parent_from_this_install(tmp_path: Path) -> None:
+ install_dir = tmp_path / "install"
+ venv = install_dir / ".venv"
+ created = _run([sys.executable, "-m", "venv", "--without-pip", str(venv)], timeout=300)
+ assert created.returncode == 0, created.stderr
+ function_file = tmp_path / "function.ps1"
+ function_file.write_text(_ps_function("Stop-RunningApp"), encoding="utf-8")
+ driver = tmp_path / "driver.ps1"
+ driver.write_text(PS_DRIVER, encoding="utf-8")
+ env = dict(os.environ)
+ env.update(TEST_INSTALL_DIR=str(install_dir), TEST_FUNCTION_FILE=str(function_file))
+
+ app, app_pid = _start_sleeper(venv / "Scripts" / "python.exe")
+ try:
+ # PowerShell runs as a child of the venv's interpreter - what a
+ # terminal pane inside the app looks like to the installer.
+ proc = _run(
+ [
+ str(venv / "Scripts" / "python.exe"),
+ "-c",
+ INSIDE_APP_LAUNCHER,
+ "-",
+ *_powershell(driver),
+ ],
+ env=env,
+ )
+
+ assert proc.returncode == 1, proc.stdout + proc.stderr
+ assert INSIDE_APP in proc.stdout
+ assert "terminal outside the app" in proc.stdout
+ assert STOPPED_NOTE not in proc.stdout
+ assert "DONE" not in proc.stdout
+ # Refused BEFORE the first kill: the app of this install still runs.
+ assert pid_alive(app_pid)
+ assert app.poll() is None
+ finally:
+ _end(app)
diff --git a/tests/unit/ui/test_relauncher_update_contract.py b/tests/unit/ui/test_relauncher_update_contract.py
new file mode 100644
index 0000000000..7e4f8f91b5
--- /dev/null
+++ b/tests/unit/ui/test_relauncher_update_contract.py
@@ -0,0 +1,1065 @@
+"""The restart helper follows the update contract of the tree it installs.
+
+An update is applied by the previous version's helper. These tests prove it
+asks the checked-out tree where its UI bundle, launcher, version and config
+live instead of assuming its own layout - including the full crossing, run
+against a real git checkout whose new release moved the whole package.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import plistlib
+import shutil
+import subprocess
+import sys
+from dataclasses import replace
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+
+from jarvis.core import instance
+from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS
+from jarvis.core.update_contract import (
+ CONTRACT_PATH,
+ CONTRACT_SCHEMA,
+ DEFAULT_CONTRACT,
+ UpdateContract,
+ read_update_contract,
+)
+from jarvis.ui import desktop_log, relauncher
+from jarvis.ui.web import update_routes
+
+REPO = Path(__file__).resolve().parents[3]
+GIT = shutil.which("git")
+needs_git = pytest.mark.skipif(GIT is None, reason="git is not installed")
+REAL_PLATFORM = sys.platform
+
+MOVED = UpdateContract(
+ ui_bundle_dir="pkg_new/ui/web/dist",
+ launcher_module="pkg_new.ui.web.launcher",
+ version_file="pkg_new/__init__.py",
+ config_file="pkg_new.toml",
+ macos_app_dir_name="Moved Product.app",
+ macos_bundle_id="com.moved-product.desktop",
+ rollback_hook="install/rollback_hook.py",
+)
+
+
+def _contract_document(contract: UpdateContract) -> str:
+ payload: dict[str, object] = {"schema": CONTRACT_SCHEMA}
+ for name in (
+ "ui_bundle_dir",
+ "launcher_module",
+ "version_file",
+ "config_file",
+ "macos_app_dir_name",
+ "macos_bundle_id",
+ "rollback_hook",
+ ):
+ value = getattr(contract, name)
+ if value is not None:
+ payload[name] = value
+ return json.dumps(payload, indent=2) + "\n"
+
+
+def _write_contract(root: Path, contract: UpdateContract) -> None:
+ path = root / CONTRACT_PATH
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(_contract_document(contract), encoding="utf-8", newline="\n")
+
+
+def _write_bundle(root: Path, bundle_dir: str) -> None:
+ dist = root.joinpath(*bundle_dir.split("/"))
+ (dist / "assets").mkdir(parents=True, exist_ok=True)
+ (dist / "index.html").write_text(
+ '<script type="module" src="/assets/app.js"></script>', encoding="utf-8"
+ )
+ (dist / "assets" / "app.js").write_text("export {};\n", encoding="utf-8")
+
+
+def default_instance(monkeypatch: pytest.MonkeyPatch) -> None:
+ """One fixed instance identity, whatever the developer's shell exports."""
+ monkeypatch.setattr(
+ instance,
+ "current_instance",
+ lambda: SimpleNamespace(
+ is_default=True,
+ launcher_args=(),
+ port=lambda base: base,
+ windows_branded_launcher_file_name="NoSuchBrandedLauncher.exe",
+ ),
+ )
+
+
+# --------------------------------------------------------------------------- #
+# Each consumer reads the tree that is on disk
+# --------------------------------------------------------------------------- #
+def test_bundle_check_looks_where_the_checked_out_tree_says(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ _write_contract(tmp_path, MOVED)
+ _write_bundle(tmp_path, MOVED.ui_bundle_dir)
+ tracked: list[str] = []
+
+ def _tracked(cmd: list[str], *, root: Path, timeout: float) -> int:
+ tracked.append(cmd[-1])
+ return 0
+
+ monkeypatch.setattr(relauncher, "_run_update_command", _tracked)
+
+ assert relauncher._ui_bundle_ready(tmp_path) is True
+ assert sorted(tracked) == [
+ "pkg_new/ui/web/dist/assets/app.js",
+ "pkg_new/ui/web/dist/index.html",
+ ]
+
+
+def test_bundle_check_ignores_a_bundle_left_in_the_old_place(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ """A stale bundle where the previous layout kept it proves nothing."""
+ _write_contract(tmp_path, MOVED)
+ _write_bundle(tmp_path, DEFAULT_CONTRACT.ui_bundle_dir)
+ monkeypatch.setattr(relauncher, "_run_update_command", lambda *_a, **_k: 0)
+
+ assert relauncher._ui_bundle_ready(tmp_path) is False
+
+
+def test_bundle_check_without_a_contract_keeps_the_default_place(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ _write_bundle(tmp_path, DEFAULT_CONTRACT.ui_bundle_dir)
+ tracked: list[str] = []
+ monkeypatch.setattr(
+ relauncher,
+ "_run_update_command",
+ lambda cmd, **_k: tracked.append(cmd[-1]) or 0,
+ )
+
+ assert relauncher._ui_bundle_ready(tmp_path) is True
+ assert "jarvis/ui/web/dist/index.html" in tracked
+
+
+def test_admin_port_is_read_from_the_config_file_the_tree_names(
+ tmp_path: Path, default_instance: None
+) -> None:
+ (tmp_path / "jarvis.toml").write_text("[ui]\nadmin_api_port = 40001\n", encoding="utf-8")
+ (tmp_path / "pkg_new.toml").write_text("[ui]\nadmin_api_port = 40002\n", encoding="utf-8")
+
+ assert relauncher._restart_admin_port(tmp_path) == 40001
+ _write_contract(tmp_path, MOVED)
+ assert relauncher._restart_admin_port(tmp_path) == 40002
+
+
+def test_launch_command_starts_the_module_the_tree_names(
+ monkeypatch: pytest.MonkeyPatch, default_instance: None
+) -> None:
+ monkeypatch.setattr(relauncher.sys, "platform", "linux")
+ assert relauncher.build_launch_command("python", contract=MOVED) == [
+ "python",
+ "-m",
+ "pkg_new.ui.web.launcher",
+ ]
+ assert relauncher.build_launch_command("python") == [
+ "python",
+ "-m",
+ "jarvis.ui.web.launcher",
+ ]
+
+
+def test_windows_branded_launcher_runs_the_module_the_tree_names(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, default_instance: None
+) -> None:
+ branded = tmp_path / "Branded.exe"
+ branded.write_bytes(b"MZ")
+ monkeypatch.setattr(relauncher.sys, "platform", "win32")
+ monkeypatch.setattr(relauncher, "_existing_branded_launcher", lambda: branded)
+
+ assert relauncher.build_launch_command("python.exe", contract=MOVED) == [
+ str(branded),
+ "-m",
+ "pkg_new.ui.web.launcher",
+ ]
+
+
+def _app_bundle(path: Path, bundle_id: str | None) -> Path:
+ """An app bundle directory, identified by ``bundle_id`` when one is given."""
+ (path / "Contents").mkdir(parents=True)
+ if bundle_id is not None:
+ with (path / "Contents" / "Info.plist").open("wb") as stream:
+ plistlib.dump({"CFBundleIdentifier": bundle_id}, stream)
+ return path
+
+
+def test_macos_restart_opens_the_bundle_the_tree_names(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, default_instance: None
+) -> None:
+ import jarvis.setup.macos_app_bundle as bundle_module
+
+ known = tmp_path / "Applications" / relauncher.MACOS_APP_DIR_NAME
+ renamed = _app_bundle(known.with_name(MOVED.macos_app_dir_name), MOVED.macos_bundle_id)
+ monkeypatch.setattr(relauncher.sys, "platform", "darwin")
+ monkeypatch.setattr(bundle_module, "macos_app_bundle_path", lambda: known)
+
+ def _unexpected(_bundle: Path) -> bool:
+ raise AssertionError("a renamed bundle is not validated against the old layout")
+
+ monkeypatch.setattr(bundle_module, "macos_app_bundle_is_launchable", _unexpected)
+
+ assert relauncher.build_launch_command("python3", contract=MOVED) == [
+ "/usr/bin/open",
+ "-W",
+ "-a",
+ str(renamed),
+ ]
+
+
+def test_macos_restart_names_the_renamed_bundle_even_before_it_exists(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, default_instance: None
+) -> None:
+ import jarvis.setup.macos_app_bundle as bundle_module
+
+ known = tmp_path / "Applications" / relauncher.MACOS_APP_DIR_NAME
+ monkeypatch.setattr(relauncher.sys, "platform", "darwin")
+ monkeypatch.setattr(relauncher.Path, "home", lambda: tmp_path / "home")
+ monkeypatch.setattr(bundle_module, "macos_app_bundle_path", lambda: known)
+
+ command = relauncher.build_launch_command("python3", contract=MOVED)
+
+ # Fail closed on the new identity; never fall back to a raw interpreter.
+ assert command[:3] == ["/usr/bin/open", "-W", "-a"]
+ assert Path(command[3]).name == MOVED.macos_app_dir_name
+
+
+def test_macos_restart_skips_another_app_that_carries_the_same_name(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, default_instance: None
+) -> None:
+ """The disk-image app can share the new name; it is a different install."""
+ import jarvis.setup.macos_app_bundle as bundle_module
+
+ known = tmp_path / "Applications" / relauncher.MACOS_APP_DIR_NAME
+ home = tmp_path / "home"
+ _app_bundle(known.with_name(MOVED.macos_app_dir_name), "ai.movedproduct.desktop")
+ managed = _app_bundle(
+ home / "Applications" / MOVED.macos_app_dir_name, MOVED.macos_bundle_id
+ )
+ monkeypatch.setattr(relauncher.sys, "platform", "darwin")
+ monkeypatch.setattr(relauncher.Path, "home", lambda: home)
+ monkeypatch.setattr(bundle_module, "macos_app_bundle_path", lambda: known)
+
+ assert relauncher.build_launch_command("python3", contract=MOVED) == [
+ "/usr/bin/open",
+ "-W",
+ "-a",
+ str(managed),
+ ]
+
+
[email protected]("other_id", ["ai.movedproduct.desktop", None])
+def test_macos_restart_never_opens_another_app_for_want_of_the_right_one(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+ default_instance: None,
+ other_id: str | None,
+) -> None:
+ """Only a same-named stranger exists: the restart fails rather than open it."""
+ import jarvis.setup.macos_app_bundle as bundle_module
+
+ known = tmp_path / "Applications" / relauncher.MACOS_APP_DIR_NAME
+ home = tmp_path / "home"
+ stranger = _app_bundle(known.with_name(MOVED.macos_app_dir_name), other_id)
+ monkeypatch.setattr(relauncher.sys, "platform", "darwin")
+ monkeypatch.setattr(relauncher.Path, "home", lambda: home)
+ monkeypatch.setattr(bundle_module, "macos_app_bundle_path", lambda: known)
+
+ command = relauncher.build_launch_command("python3", contract=MOVED)
+
+ assert command[:3] == ["/usr/bin/open", "-W", "-a"]
+ assert Path(command[3]).name == MOVED.macos_app_dir_name
+ assert Path(command[3]) != stranger
+ assert not Path(command[3]).exists()
+
+
+# --------------------------------------------------------------------------- #
+# Rollback hook
+# --------------------------------------------------------------------------- #
+def _pending(root: Path) -> tuple[str, str]:
+ previous, target = "a" * 40, "b" * 40
+ (root / ".git").mkdir()
+ (root / relauncher.MANAGED_MARKER).write_text("{}\n", encoding="utf-8")
+ (root / relauncher.PENDING_UPDATE_FILENAME).write_text(
+ json.dumps(
+ {
+ "schema": 1,
+ "previous_revision": previous,
+ "target_revision": target,
+ "profile": "full",
+ }
+ ),
+ encoding="utf-8",
+ )
+ return previous, target
+
+
+def _is_hook_call(cmd: list[str]) -> bool:
+ """``<python> <root>/install/rollback_hook.py <previous> <target>``."""
+ return len(cmd) == 4 and Path(cmd[1]).name == "rollback_hook.py"
+
+
+class _FakeCheckout:
+ """Stands in for git and the installer; the reset swaps the tree's contract."""
+
+ def __init__(
+ self,
+ root: Path,
+ *,
+ target: str,
+ target_contract: UpdateContract,
+ install_fails: bool,
+ hook_tracked: bool = True,
+ hook_rc: int = 0,
+ target_reset_rc: int = 0,
+ ) -> None:
+ self.root = root
+ self.target = target
+ self.target_contract = target_contract
+ self.install_fails = install_fails
+ self.hook_tracked = hook_tracked
+ self.hook_rc = hook_rc
+ self.target_reset_rc = target_reset_rc
+ self.calls: list[list[str]] = []
+ self.on_target = False
+
+ def __call__(self, cmd: list[str], *, root: Path, timeout: float) -> int:
+ self.calls.append(cmd)
+ if cmd[:3] == ["git", "reset", "--hard"]:
+ if cmd[3] == self.target:
+ if self.target_reset_rc != 0:
+ return self.target_reset_rc
+ self.on_target = True
+ _write_contract(self.root, self.target_contract)
+ hook = self.target_contract.rollback_hook
+ if hook is not None:
+ (self.root / hook).write_text("", encoding="utf-8")
+ else:
+ self.on_target = False
+ (self.root / CONTRACT_PATH).unlink(missing_ok=True)
+ return 0
+ if cmd[:2] == ["git", "ls-files"]:
+ return 0 if self.hook_tracked else 1
+ if cmd == ["installer", "full"]:
+ return 1 if self.install_fails and self.on_target else 0
+ if _is_hook_call(cmd):
+ return self.hook_rc
+ raise AssertionError(f"unexpected update command {cmd}")
+
+ def hook_calls(self) -> list[list[str]]:
+ return [cmd for cmd in self.calls if _is_hook_call(cmd)]
+
+
+def _finalize_with(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, **options: object
+) -> tuple[_FakeCheckout, bool, str, str]:
+ previous, target = _pending(tmp_path)
+ checkout = _FakeCheckout(
+ tmp_path,
+ target=target,
+ target_contract=options.pop("target_contract", MOVED), # type: ignore[arg-type]
+ **options, # type: ignore[arg-type]
+ )
+ monkeypatch.setattr(relauncher, "_run_update_command", checkout)
+ monkeypatch.setattr(relauncher, "_ui_bundle_ready", lambda _root: True)
+ monkeypatch.setattr(
+ relauncher, "_installer_command", lambda _root, profile: ["installer", profile]
+ )
+ monkeypatch.setattr(relauncher, "_managed_python", lambda _root: "python")
+ ok = relauncher.finalize_pending_update(tmp_path)
+ return checkout, ok, previous, target
+
+
+def test_a_successful_update_never_runs_the_rollback_hook(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ checkout, ok, _previous, _target = _finalize_with(
+ monkeypatch, tmp_path, install_fails=False
+ )
+ assert ok is True
+ assert checkout.hook_calls() == []
+
+
+def test_a_failed_install_runs_the_targets_hook_before_the_rollback_reset(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ checkout, ok, previous, target = _finalize_with(monkeypatch, tmp_path, install_fails=True)
+ hook = str(tmp_path.resolve() / "install" / "rollback_hook.py")
+
+ assert ok is False
+ assert checkout.calls == [
+ ["git", "reset", "--hard", target],
+ ["installer", "full"],
+ ["git", "ls-files", "--error-unmatch", "--", "install/rollback_hook.py"],
+ ["python", hook, previous, target],
+ ["git", "reset", "--hard", previous],
+ ["installer", "full"],
+ ]
+ result = json.loads(
+ (tmp_path / relauncher.UPDATE_RESULT_FILENAME).read_text(encoding="utf-8")
+ )
+ assert result["ok"] is False
+ assert result["rolled_back"] is True
+
+
+def test_a_failing_hook_never_stops_the_rollback(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ checkout, ok, previous, _target = _finalize_with(
+ monkeypatch, tmp_path, install_fails=True, hook_rc=-1
+ )
+ assert ok is False
+ assert len(checkout.hook_calls()) == 1
+ assert ["git", "reset", "--hard", previous] in checkout.calls
+ result = json.loads(
+ (tmp_path / relauncher.UPDATE_RESULT_FILENAME).read_text(encoding="utf-8")
+ )
+ assert result["rolled_back"] is True
+
+
+def test_a_hook_the_release_does_not_track_is_never_executed(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ checkout, ok, previous, _target = _finalize_with(
+ monkeypatch, tmp_path, install_fails=True, hook_tracked=False
+ )
+ assert ok is False
+ assert checkout.hook_calls() == []
+ assert ["git", "reset", "--hard", previous] in checkout.calls
+
+
+def test_a_release_without_a_hook_rolls_back_exactly_as_before(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ checkout, ok, previous, target = _finalize_with(
+ monkeypatch, tmp_path, install_fails=True, target_contract=DEFAULT_CONTRACT
+ )
+ assert ok is False
+ assert checkout.calls == [
+ ["git", "reset", "--hard", target],
+ ["installer", "full"],
+ ["git", "reset", "--hard", previous],
+ ["installer", "full"],
+ ]
+
+
+def test_no_hook_runs_when_the_target_was_never_checked_out(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ """A hook left on disk by anything else is not the target's to run."""
+ _write_contract(tmp_path, MOVED)
+ checkout, ok, previous, target = _finalize_with(
+ monkeypatch, tmp_path, install_fails=False, target_reset_rc=1
+ )
+ assert ok is False
+ assert checkout.calls == [
+ ["git", "reset", "--hard", target],
+ ["git", "reset", "--hard", previous],
+ ["installer", "full"],
+ ]
+
+
+# --------------------------------------------------------------------------- #
+# The helper's relaunch command follows what ended up installed
+# --------------------------------------------------------------------------- #
+def _run_main(
+ monkeypatch: pytest.MonkeyPatch, root: Path, finalize: object
+) -> list[list[str]]:
+ monkeypatch.setattr(relauncher.sys, "platform", "linux")
+ monkeypatch.setattr(relauncher.sys, "executable", "python")
+ monkeypatch.setattr(relauncher, "fresh_user_env", lambda: {})
+ monkeypatch.setattr(desktop_log, "_install_desktop_log_sink", lambda _path: None)
+ spawned: list[list[str]] = []
+ rc = relauncher.main(
+ ["123", str(root)],
+ _spawn=lambda cmd, **_kw: spawned.append(cmd) or SimpleNamespace(pid=456),
+ _alive=lambda _pid: False,
+ _sleep=lambda _seconds: None,
+ _serving=lambda: True,
+ _finalize_update=finalize,
+ )
+ assert rc == 0
+ return spawned
+
+
+def test_main_relaunches_through_the_launcher_of_the_installed_tree(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, default_instance: None
+) -> None:
+ def _finalize(cwd: str) -> bool:
+ # The finalizer just checked out a release that moved its package.
+ _write_contract(Path(cwd), MOVED)
+ return True
+
+ assert _run_main(monkeypatch, tmp_path, _finalize) == [
+ ["python", "-m", "pkg_new.ui.web.launcher"]
+ ]
+
+
+def test_main_keeps_the_known_launcher_when_nothing_was_updated(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, default_instance: None
+) -> None:
+ assert _run_main(monkeypatch, tmp_path, lambda _cwd: True) == [
+ ["python", "-m", "jarvis.ui.web.launcher"]
+ ]
+
+
+# --------------------------------------------------------------------------- #
+# The crossing, against a real checkout
+# --------------------------------------------------------------------------- #
+FAKE_INSTALLER = """import sys
+from pathlib import Path
+
+root = Path(__file__).resolve().parents[1]
+(root / ".installer-ran").write_text(" ".join(sys.argv[1:]), encoding="utf-8")
+raise SystemExit(1 if (root / ".fail-install").exists() and FAILS_ON_REQUEST else 0)
+"""
+
+FAKE_HOOK = """import sys
+from pathlib import Path
+
+root = Path(__file__).resolve().parents[1]
+state = "new-tree" if (root / "pkg_new" / "__init__.py").is_file() else "other-tree"
+(root / ".hook-ran").write_text(" ".join([state, *sys.argv[1:]]), encoding="utf-8")
+"""
+
+
+def _git(root: Path, *args: str) -> str:
+ proc = subprocess.run( # noqa: S603 - test-controlled command
+ [str(GIT), "-C", str(root), *args],
+ capture_output=True,
+ text=True,
+ encoding="utf-8",
+ errors="replace",
+ timeout=120,
+ creationflags=NO_WINDOW_CREATIONFLAGS,
+ )
+ assert proc.returncode == 0, proc.stderr
+ return proc.stdout.strip()
+
+
+def _commit(root: Path, message: str) -> str:
+ # Forced: a developer's global ignore file commonly lists ``dist``.
+ _git(root, "add", "-A", "--force")
+ _git(
+ root,
+ "-c",
+ "user.name=Update Test",
+ "-c",
+ "-c",
+ "commit.gpgsign=false",
+ "commit",
+ "--quiet",
+ "-m",
+ message,
+ )
+ return _git(root, "rev-parse", "HEAD")
+
+
+def _write_package(root: Path, package: str, version: str) -> None:
+ (root / package / "ui" / "web").mkdir(parents=True)
+ (root / package / "__init__.py").write_text(
+ f'__version__ = "{version}"\n', encoding="utf-8", newline="\n"
+ )
+ _write_bundle(root, f"{package}/ui/web/dist")
+
+
+def _write_installer(root: Path, *, fails_on_request: bool) -> None:
+ (root / "install").mkdir(exist_ok=True)
+ (root / "install" / "installer.py").write_text(
+ FAKE_INSTALLER.replace("FAILS_ON_REQUEST", repr(fails_on_request)),
+ encoding="utf-8",
+ newline="\n",
+ )
+
+
+class _Crossing:
+ """A managed checkout sitting on ``old`` with ``new`` staged as an update."""
+
+ def __init__(self, root: Path, old_package: str, old: str, new: str) -> None:
+ self.root = root
+ self.old_package = old_package
+ self.old = old
+ self.new = new
+
+ def head(self) -> str:
+ return _git(self.root, "rev-parse", "HEAD")
+
+ def result(self) -> dict[str, object]:
+ return json.loads(
+ (self.root / relauncher.UPDATE_RESULT_FILENAME).read_text(encoding="utf-8")
+ )
+
+
[email protected](params=["jarvis", "pkg_old"])
+def crossing(request: pytest.FixtureRequest, tmp_path: Path) -> _Crossing:
+ """``old`` keeps its package at the default place without a contract, or
+ elsewhere with one; ``new`` moved everything to ``pkg_new``."""
+ old_package: str = request.param
+ root = tmp_path / "install"
+ root.mkdir()
+ _git(root, "init", "--quiet")
+ # Line endings and hooks of the developer's machine must not decide what
+ # this checkout tracks.
+ _git(root, "config", "core.autocrlf", "false")
+ _git(root, "config", "core.hooksPath", str(root / ".git" / "no-hooks"))
+
+ _write_package(root, old_package, "1.0.0")
+ _write_installer(root, fails_on_request=False)
+ if old_package != "jarvis":
+ _write_contract(
+ root,
+ UpdateContract(
+ ui_bundle_dir=f"{old_package}/ui/web/dist",
+ launcher_module=f"{old_package}.ui.web.launcher",
+ version_file=f"{old_package}/__init__.py",
+ ),
+ )
+ old = _commit(root, "old release")
+
+ shutil.rmtree(root / old_package)
+ _write_package(root, "pkg_new", "2.0.0")
+ _write_installer(root, fails_on_request=True)
+ (root / "install" / "rollback_hook.py").write_text(FAKE_HOOK, encoding="utf-8", newline="\n")
+ _write_contract(root, MOVED)
+ new = _commit(root, "new release moves the package")
+
+ _git(root, "reset", "--quiet", "--hard", old)
+ (root / relauncher.MANAGED_MARKER).write_text("{}\n", encoding="utf-8")
+ (root / relauncher.PENDING_UPDATE_FILENAME).write_text(
+ json.dumps(
+ {
+ "schema": 1,
+ "previous_revision": old,
+ "target_revision": new,
+ "profile": "full",
+ }
+ ),
+ encoding="utf-8",
+ )
+ return _Crossing(root, old_package, old, new)
+
+
+def _recording_real_commands(monkeypatch: pytest.MonkeyPatch) -> list[list[str]]:
+ """Run every update command for real, and keep what was run."""
+ calls: list[list[str]] = []
+ real = relauncher._run_update_command
+
+ def _run(cmd: list[str], *, root: Path, timeout: float) -> int:
+ calls.append(list(cmd))
+ return real(cmd, root=root, timeout=timeout)
+
+ monkeypatch.setattr(relauncher, "_run_update_command", _run)
+ return calls
+
+
+def _finalize_on_the_real_platform(monkeypatch: pytest.MonkeyPatch) -> object:
+ """The finalizer spawns real processes, so it must see the real OS."""
+
+ def _finalize(cwd: str) -> bool:
+ with monkeypatch.context() as scoped:
+ scoped.setattr(relauncher.sys, "platform", REAL_PLATFORM)
+ scoped.setattr(relauncher.sys, "executable", sys.executable)
+ return relauncher.finalize_pending_update(cwd)
+
+ return _finalize
+
+
+@needs_git
+def test_crossing_installs_a_release_that_moved_its_package(
+ monkeypatch: pytest.MonkeyPatch, crossing: _Crossing, default_instance: None
+) -> None:
+ root = crossing.root
+ (root / "pkg_new.toml").write_text("[ui]\nadmin_api_port = 40123\n", encoding="utf-8")
+ calls = _recording_real_commands(monkeypatch)
+
+ spawned = _run_main(monkeypatch, root, _finalize_on_the_real_platform(monkeypatch))
+
+ assert crossing.head() == crossing.new
+ assert crossing.result()["ok"] is True
+ assert not (root / relauncher.PENDING_UPDATE_FILENAME).exists()
+ # The TARGET tree's installer ran, with the staged profile.
+ assert (root / ".installer-ran").read_text(encoding="utf-8") == "--no-launch --with-desktop"
+ # The bundle was verified where the new tree keeps it ...
+ tracked = [cmd[-1] for cmd in calls if cmd[:2] == ["git", "ls-files"]]
+ assert sorted(tracked) == [
+ "pkg_new/ui/web/dist/assets/app.js",
+ "pkg_new/ui/web/dist/index.html",
+ ]
+ # ... the app comes back through the new tree's launcher ...
+ assert spawned == [["python", "-m", "pkg_new.ui.web.launcher"]]
+ # ... and its port is read from the config file the new tree names.
+ assert relauncher._restart_admin_port(root) == 40123
+ assert not (root / ".hook-ran").exists()
+
+
+@needs_git
+def test_crossing_rolls_back_through_the_hook_to_the_old_tree(
+ monkeypatch: pytest.MonkeyPatch, crossing: _Crossing, default_instance: None
+) -> None:
+ root = crossing.root
+ (root / ".fail-install").write_text("", encoding="utf-8")
+ calls = _recording_real_commands(monkeypatch)
+
+ spawned = _run_main(monkeypatch, root, _finalize_on_the_real_platform(monkeypatch))
+
+ assert crossing.head() == crossing.old
+ result = crossing.result()
+ assert result["ok"] is False
+ assert result["rolled_back"] is True
+
+ # The hook belonged to the new tree and ran while that tree was still
+ # checked out, with both revisions, before the checkout went back.
+ assert (root / ".hook-ran").read_text(encoding="utf-8") == (
+ f"new-tree {crossing.old} {crossing.new}"
+ )
+ hook_at = next(index for index, cmd in enumerate(calls) if _is_hook_call(cmd))
+ back_at = calls.index(["git", "reset", "--hard", crossing.old])
+ assert hook_at < back_at
+
+ # After the rollback the OLD tree's layout is what gets verified and started.
+ tracked_after = [cmd[-1] for cmd in calls[back_at:] if cmd[:2] == ["git", "ls-files"]]
+ assert sorted(tracked_after) == [
+ f"{crossing.old_package}/ui/web/dist/assets/app.js",
+ f"{crossing.old_package}/ui/web/dist/index.html",
+ ]
+ assert spawned == [["python", "-m", f"{crossing.old_package}.ui.web.launcher"]]
+ assert read_update_contract(root).rollback_hook is None
+
+
+@needs_git
+def test_crossing_refuses_a_release_whose_bundle_is_not_where_it_says(
+ monkeypatch: pytest.MonkeyPatch, crossing: _Crossing, default_instance: None
+) -> None:
+ """The contract is checked, not believed: no bundle there, no update."""
+ root = crossing.root
+ marker = root / relauncher.MANAGED_MARKER
+ pending = root / relauncher.PENDING_UPDATE_FILENAME
+ payload = json.loads(pending.read_text(encoding="utf-8"))
+ # Out of the way while the broken release is committed, so the install's
+ # own untracked files do not become part of it.
+ marker.unlink()
+ pending.unlink()
+ _git(root, "reset", "--quiet", "--hard", crossing.new)
+ _write_contract(root, replace(MOVED, ui_bundle_dir="pkg_new/elsewhere"))
+ broken = _commit(root, "new release with a wrong bundle location")
+ _git(root, "reset", "--quiet", "--hard", crossing.old)
+ marker.write_text("{}\n", encoding="utf-8")
+ payload["target_revision"] = broken
+ pending.write_text(json.dumps(payload), encoding="utf-8")
+
+ spawned = _run_main(monkeypatch, root, _finalize_on_the_real_platform(monkeypatch))
+
+ assert crossing.head() == crossing.old
+ assert crossing.result()["rolled_back"] is True
+ assert spawned == [["python", "-m", f"{crossing.old_package}.ui.web.launcher"]]
+
+
+@needs_git
+async def test_crossing_reads_each_revisions_version_from_its_own_version_file(
+ crossing: _Crossing,
+) -> None:
+ """The staging step must agree with the release before anything is reset."""
+ assert await update_routes._version_at_revision(crossing.root, crossing.new) == "2.0.0"
+ assert await update_routes._version_at_revision(crossing.root, crossing.old) == "1.0.0"
+ # The checkout still holds the old tree, and is read by ITS contract.
+ assert update_routes._version_on_disk(crossing.root) == "1.0.0"
+
+
+# --------------------------------------------------------------------------- #
+# Nothing is imported from the package after the checkout changed
+# --------------------------------------------------------------------------- #
+IMPORT_GUARD_DRIVER = r"""
+import asyncio # noqa: F401 - loaded for the real OS before it is disguised
+import ctypes # noqa: F401
+import importlib.abc
+import json
+import logging # noqa: F401
+import socket # noqa: F401
+import subprocess # noqa: F401
+import sys
+from pathlib import Path
+from types import SimpleNamespace
+
+try:
+ import loguru # noqa: F401
+except ImportError:
+ pass
+
+simulated, workdir, preload, scenario = sys.argv[1], Path(sys.argv[2]), sys.argv[3], sys.argv[5]
+if simulated != "native":
+ # Standard-library and third-party modules above were imported for the
+ # real OS. Only the package under test sees the simulated one.
+ sys.platform = simulated
+
+from jarvis.ui import relauncher
+
+if preload == "skip":
+ relauncher._load_modules_needed_after_update = lambda: None
+
+
+class PackageIsGone(importlib.abc.MetaPathFinder):
+ # After the reset the old package is no longer on disk: refuse and record.
+
+ def __init__(self):
+ self.late = []
+
+ def find_spec(self, name, path=None, target=None):
+ if name == "jarvis" or name.startswith("jarvis."):
+ self.late.append(name)
+ raise ModuleNotFoundError(f"No module named {name!r}", name=name)
+ return None
+
+
+guard = PackageIsGone()
+root = workdir / "install"
+previous, target = "a" * 40, "b" * 40
+(root / ".git").mkdir(parents=True)
+(root / relauncher.MANAGED_MARKER).write_text("{}\n", encoding="utf-8")
+(root / relauncher.PENDING_UPDATE_FILENAME).write_text(
+ json.dumps(
+ {
+ "schema": 1,
+ "previous_revision": previous,
+ "target_revision": target,
+ "profile": "full",
+ }
+ ),
+ encoding="utf-8",
+)
+contract = json.loads(sys.argv[4])
+if scenario != "rollback_hook":
+ contract.pop("rollback_hook", None)
+contract_file = root / "install" / "update-contract.json"
+loaded_at_reset = []
+commands = []
+checkout = {"on_target": False}
+
+
+def write_ui_bundle(bundle_dir):
+ dist = root.joinpath(*bundle_dir.split("/"))
+ (dist / "assets").mkdir(parents=True, exist_ok=True)
+ (dist / "index.html").write_text(
+ '<script type="module" src="/assets/app.js"></script>', encoding="utf-8"
+ )
+ (dist / "assets" / "app.js").write_text("export {};\n", encoding="utf-8")
+
+
+# The tree this helper started from keeps its bundle in the default place.
+write_ui_bundle("jarvis/ui/web/dist")
+
+
+def run_update_command(cmd, *, root, timeout):
+ commands.append([str(part) for part in cmd])
+ if cmd[:3] == ["git", "reset", "--hard"]:
+ if guard not in sys.meta_path:
+ # From here on the checkout holds a release that moved its package.
+ loaded_at_reset.extend(sorted(m for m in sys.modules if m.split(".")[0] == "jarvis"))
+ sys.meta_path.insert(0, guard)
+ if cmd[3] == target:
+ checkout["on_target"] = True
+ contract_file.parent.mkdir(exist_ok=True)
+ contract_file.write_text(json.dumps(contract), encoding="utf-8")
+ write_ui_bundle(contract["ui_bundle_dir"])
+ if "rollback_hook" in contract:
+ root.joinpath(*contract["rollback_hook"].split("/")).write_text(
+ "", encoding="utf-8"
+ )
+ else:
+ # Back on the previous tree, which states no contract of its own.
+ checkout["on_target"] = False
+ contract_file.unlink()
+ return 0
+ if cmd == ["installer", "full"]:
+ return 1 if checkout["on_target"] and scenario != "success" else 0
+ return 0 # git ls-files, and the rollback hook itself
+
+
+relauncher._run_update_command = run_update_command
+relauncher._installer_command = lambda _root, profile: ["installer", profile]
+
+spawned = []
+dialogs = []
+
+
+def spawn(cmd, **_kwargs):
+ spawned.append(list(cmd))
+ # The one thing that cannot run for real is the dialog itself. It is
+ # swapped on the ALREADY LOADED module, reached through sys.modules:
+ # importing it here would load the very module this run checks for, and
+ # the helper's own import statement still has to resolve it afterwards.
+ native_dialog = sys.modules.get("jarvis.ui.native_dialog")
+ if native_dialog is not None:
+ native_dialog.show_error_dialog = lambda title, message: dialogs.append(title)
+ return SimpleNamespace(pid=4321)
+
+
+ports = []
+
+
+def serving():
+ ports.append(relauncher._restart_admin_port(root))
+ return False
+
+
+common = dict(
+ _wait=lambda _pid, **_kw: True,
+ _spawn=spawn,
+ _sleep=lambda _seconds: None,
+ _alive=lambda pid: pid != 4242,
+ _serving=serving,
+)
+came_back = relauncher.main(["4242", str(root)], **common)
+result = json.loads((root / relauncher.UPDATE_RESULT_FILENAME).read_text(encoding="utf-8"))
+
+# A windowed process has no stderr. Taking it away makes the real
+# ``standard_error_is_visible`` answer "no", which is what sends the failure
+# report on to the dialog - through the helper's real imports.
+real_stderr = sys.stderr
+sys.stderr = None
+try:
+ never_settled = relauncher.main(
+ ["4242", str(root)], _settled=lambda *_a, **_kw: False, **common
+ )
+finally:
+ sys.stderr = real_stderr
+print(
+ "RESULT "
+ + json.dumps(
+ {
+ "came_back": came_back,
+ "never_settled": never_settled,
+ "late": guard.late,
+ "guard_installed": guard in sys.meta_path,
+ "spawned": spawned,
+ "dialogs": dialogs,
+ "ports": ports,
+ "loaded_at_reset": loaded_at_reset,
+ "commands": commands,
+ "result": result,
+ }
+ )
+)
+"""
+
+
+def _run_import_guard(
+ tmp_path: Path, simulated: str, *, scenario: str = "success", preload: str = "keep"
+) -> dict:
+ env = {
+ key: value for key, value in os.environ.items() if not key.upper().startswith("JARVIS")
+ }
+ # The helper logs to the desktop log; keep that inside the test directory.
+ env["JARVIS_DATA_DIR"] = str(tmp_path / "data")
+ env["PYTHONIOENCODING"] = "utf-8"
+ proc = subprocess.run( # noqa: S603 - this interpreter, test-controlled script
+ [
+ sys.executable,
+ "-c",
+ IMPORT_GUARD_DRIVER,
+ simulated,
+ str(tmp_path),
+ preload,
+ json.dumps(json.loads(_contract_document(MOVED))),
+ scenario,
+ ],
+ capture_output=True,
+ text=True,
+ encoding="utf-8",
+ errors="replace",
+ timeout=180,
+ cwd=str(REPO),
+ env=env,
+ creationflags=NO_WINDOW_CREATIONFLAGS,
+ )
+ assert proc.returncode == 0, proc.stderr[-4000:]
+ lines = [line for line in proc.stdout.splitlines() if line.startswith("RESULT ")]
+ assert lines, proc.stdout[-2000:] + proc.stderr[-2000:]
+ return json.loads(lines[-1].removeprefix("RESULT "))
+
+
+def _simulated_platforms() -> list[str]:
+ # The native run exercises this OS for real. The others re-run the same
+ # helper with ``sys.platform`` swapped, which reaches every branch except
+ # the Windows registry read (``winreg`` exists on Windows only).
+ return ["native", *(name for name in ("darwin", "linux") if name != REAL_PLATFORM)]
+
+
[email protected]("scenario", ["success", "rollback", "rollback_hook"])
[email protected]("simulated", _simulated_platforms())
+def test_no_package_module_is_imported_after_the_checkout_changed(
+ tmp_path: Path, simulated: str, scenario: str
+) -> None:
+ """Once the tree is reset, the old package may no longer exist on disk.
+
+ A fresh interpreter runs the helper end to end, once per way an update can
+ go: the target installs, the target fails and the checkout goes back, and
+ the same with the target's rollback hook in between. From the first
+ ``git reset`` on, any import of a not-yet-loaded ``jarvis`` module fails
+ the way it would after the package moved - and is recorded. The helper
+ must still bring the app back, report a failed restart through the dialog,
+ and resolve the admin port, all from modules it loaded beforehand.
+ """
+ outcome = _run_import_guard(tmp_path, simulated, scenario=scenario)
+
+ assert outcome["guard_installed"] is True
+ assert outcome["late"] == []
+ assert outcome["came_back"] == 0
+ # Three failed attempts end in the failure report, which needs the dialog.
+ assert outcome["never_settled"] == 1
+ assert len(outcome["dialogs"]) == 1
+ assert outcome["ports"], "the admin-port probe never ran"
+ assert {
+ "jarvis.core.frozen",
+ "jarvis.core.instance",
+ "jarvis.core.process_utils",
+ "jarvis.ui.native_dialog",
+ } <= set(outcome["loaded_at_reset"])
+
+ platform_name = REAL_PLATFORM if simulated == "native" else simulated
+ if platform_name == "darwin":
+ assert "jarvis.setup.macos_app_bundle" in outcome["loaded_at_reset"]
+
+ hook_runs = [cmd for cmd in outcome["commands"] if _is_hook_call(cmd)]
+ resets = [cmd[3] for cmd in outcome["commands"] if cmd[:3] == ["git", "reset", "--hard"]]
+ first_launch = outcome["spawned"][0]
+ if scenario == "success":
+ assert outcome["result"]["ok"] is True
+ assert resets == ["b" * 40]
+ assert hook_runs == []
+ if platform_name == "darwin":
+ assert first_launch[-1].endswith(MOVED.macos_app_dir_name)
+ else:
+ assert first_launch[1:3] == ["-m", MOVED.launcher_module]
+ return
+
+ # Both rollback branches end on the previous tree, verified and started by
+ # ITS layout - on macOS through the bundle this version itself knows.
+ assert outcome["result"] == {**outcome["result"], "ok": False, "rolled_back": True}
+ assert resets == ["b" * 40, "a" * 40]
+ assert len(hook_runs) == (1 if scenario == "rollback_hook" else 0)
+ if platform_name == "darwin":
+ assert first_launch[-1].endswith(relauncher.MACOS_APP_DIR_NAME)
+ else:
+ assert first_launch[1:3] == ["-m", DEFAULT_CONTRACT.launcher_module]
+
+
+def test_the_guard_notices_a_module_that_was_not_loaded_in_time(tmp_path: Path) -> None:
+ """Without the up-front load, the failure report imports from the new tree."""
+ outcome = _run_import_guard(tmp_path, "native", preload="skip")
+
+ assert "jarvis.ui.native_dialog" in outcome["late"] or (
+ "jarvis.core.process_utils" in outcome["late"]
+ )
+ assert outcome["dialogs"] == []
diff --git a/tests/unit/ui/web/test_update_routes.py b/tests/unit/ui/web/test_update_routes.py
index 48dbaed6f3..abbb5b9d00 100644
--- a/tests/unit/ui/web/test_update_routes.py
+++ b/tests/unit/ui/web/test_update_routes.py
@@ -705,3 +705,175 @@ async def test_release_check_refuses_a_redirect_off_the_github_api(
assert await u._fetch_latest_release() is None
assert seen == [u._RELEASES_LATEST_API]
assert u._last_good_release is None
+
+
+# --------------------------------------------------------------------------- #
+# The version is read where the TARGET revision says it lives
+# --------------------------------------------------------------------------- #
+def _patch_git_show(
+ monkeypatch: pytest.MonkeyPatch, files: dict[str, str]
+) -> list[list[str]]:
+ """Serve ``git show <rev>:<path>`` from ``files``; record every question."""
+ asked: list[list[str]] = []
+
+ async def _fake_git_output(args, *, cwd, timeout_s=15.0):
+ asked.append(args)
+ if args == ["rev-parse", "HEAD"]:
+ return "a" * 40
+ if args == ["rev-parse", "FETCH_HEAD^{commit}"]:
+ return "b" * 40
+ if args[0] == "show":
+ return files.get(args[1])
+ return None
+
+ async def _fake_git(args, *, cwd, timeout_s=60.0, on_stderr_line=None):
+ asked.append(args)
+ return 0, "", ""
+
+ monkeypatch.setattr(u, "_git", _fake_git)
+ monkeypatch.setattr(u, "_git_output", _fake_git_output)
+ return asked
+
+
+def _moved_contract(**overrides: object) -> str:
+ return json.dumps({"schema": 1, "version_file": "newpkg/__init__.py", **overrides})
+
+
+async def test_version_at_revision_follows_the_targets_update_contract(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ revision = "c" * 40
+ asked = _patch_git_show(
+ monkeypatch,
+ {
+ f"{revision}:install/update-contract.json": _moved_contract(),
+ f"{revision}:newpkg/__init__.py": '__version__ = "3.0.0"',
+ },
+ )
+
+ assert await u._version_at_revision(tmp_path, revision) == "3.0.0"
+ # The package moved: its old location is not even looked at.
+ assert ["show", f"{revision}:jarvis/__init__.py"] not in asked
+
+
+async def test_version_at_revision_without_a_contract_reads_the_default_file(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ revision = "c" * 40
+ asked = _patch_git_show(
+ monkeypatch, {f"{revision}:jarvis/__init__.py": '__version__ = "2.9.9"'}
+ )
+
+ assert await u._version_at_revision(tmp_path, revision) == "2.9.9"
+ assert asked[0] == ["show", f"{revision}:install/update-contract.json"]
+
+
+ "contract",
+ [
+ "not json",
+ json.dumps({"schema": 99, "version_file": "newpkg/__init__.py"}),
+ json.dumps({"schema": 1, "version_file": "../../outside/__init__.py"}),
+ json.dumps({"schema": 1, "version_file": "/etc/passwd"}),
+ ],
+)
+async def test_version_at_revision_never_follows_a_contract_it_cannot_trust(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, contract: str
+) -> None:
+ revision = "c" * 40
+ asked = _patch_git_show(
+ monkeypatch,
+ {
+ f"{revision}:install/update-contract.json": contract,
+ f"{revision}:newpkg/__init__.py": '__version__ = "6.6.6"',
+ f"{revision}:jarvis/__init__.py": '__version__ = "2.9.9"',
+ },
+ )
+
+ assert await u._version_at_revision(tmp_path, revision) == "2.9.9"
+ shown = [args[1].split(":", 1)[1] for args in asked if args[0] == "show"]
+ assert shown == ["install/update-contract.json", "jarvis/__init__.py"]
+
+
+async def test_version_at_revision_still_falls_back_to_pyproject(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ revision = "c" * 40
+ _patch_git_show(
+ monkeypatch,
+ {
+ f"{revision}:install/update-contract.json": _moved_contract(),
+ f"{revision}:pyproject.toml": '[project]\nversion = "3.1.0"\n',
+ },
+ )
+ assert await u._version_at_revision(tmp_path, revision) == "3.1.0"
+
+
+def _stage_moved_release(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, *, tree_version: str
+) -> None:
+ _patch_managed(monkeypatch, tmp_path)
+ (tmp_path / ".jarvis-managed-install").write_text('{"profile": "full"}\n', encoding="utf-8")
+ monkeypatch.setattr(u, "_running_version", lambda: "1.0.1")
+ _patch_latest(monkeypatch, {"version": "1.0.2", "tag": "v1.0.2"})
+ _patch_git_show(
+ monkeypatch,
+ {
+ f"{'b' * 40}:install/update-contract.json": _moved_contract(),
+ f"{'b' * 40}:newpkg/__init__.py": f'__version__ = "{tree_version}"',
+ },
+ )
+
+
+def test_apply_stages_a_release_that_moved_its_version_file(
+ client: TestClient, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ _stage_moved_release(monkeypatch, tmp_path, tree_version="1.0.2")
+
+ body = client.post("/api/update/apply").json()
+
+ assert body["ok"] is True
+ assert body["version"] == "1.0.2"
+ pending = json.loads((tmp_path / u._PENDING_UPDATE_NAME).read_text(encoding="utf-8"))
+ assert pending["target_revision"] == "b" * 40
+
+
+def test_apply_still_refuses_a_moved_release_whose_version_disagrees(
+ client: TestClient, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ """The safety property survives the move: tag bytes must match the release."""
+ _stage_moved_release(monkeypatch, tmp_path, tree_version="1.0.3")
+
+ response = client.post("/api/update/apply")
+
+ assert response.status_code == 502
+ assert not (tmp_path / u._PENDING_UPDATE_NAME).exists()
+
+
+def test_apply_refuses_a_moved_release_whose_version_cannot_be_read(
+ client: TestClient, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ _patch_managed(monkeypatch, tmp_path)
+ monkeypatch.setattr(u, "_running_version", lambda: "1.0.1")
+ _patch_latest(monkeypatch, {"version": "1.0.2", "tag": "v1.0.2"})
+ # The contract names a version file the revision does not contain.
+ _patch_git_show(
+ monkeypatch, {f"{'b' * 40}:install/update-contract.json": _moved_contract()}
+ )
+
+ assert client.post("/api/update/apply").status_code == 502
+ assert not (tmp_path / u._PENDING_UPDATE_NAME).exists()
+
+
+def test_version_on_disk_follows_the_checked_out_contract(tmp_path: Path) -> None:
+ (tmp_path / "jarvis").mkdir()
+ (tmp_path / "jarvis" / "__init__.py").write_text('__version__ = "1.0.0"\n', encoding="utf-8")
+ assert u._version_on_disk(tmp_path) == "1.0.0"
+
+ (tmp_path / "newpkg").mkdir()
+ (tmp_path / "newpkg" / "__init__.py").write_text('__version__ = "2.0.0"\n', encoding="utf-8")
+ (tmp_path / "install").mkdir()
+ (tmp_path / "install" / "update-contract.json").write_text(
+ _moved_contract(), encoding="utf-8"
+ )
+ assert u._version_on_disk(tmp_path) == "2.0.0"
diff --git a/tests/unit/ui/web/test_update_routes_frozen.py b/tests/unit/ui/web/test_update_routes_frozen.py
index 8bd2217711..3deadb75de 100644
--- a/tests/unit/ui/web/test_update_routes_frozen.py
+++ b/tests/unit/ui/web/test_update_routes_frozen.py
@@ -82,7 +82,9 @@ def _patch_frozen(
) -> None:
monkeypatch.setattr(u, "is_frozen", lambda: frozen)
monkeypatch.setattr(u, "_running_version", lambda: running)
- monkeypatch.setattr(u, "installer_asset_name", lambda _p, _m: asset_name)
+ monkeypatch.setattr(
+ u, "installer_asset_names", lambda _p, _m: (asset_name,) if asset_name else ()
+ )
# The real preflight inspects THIS process (no AppImage on a CI runner, no
# app bundle in a test run); the cases below opt into a blocker explicitly.
monkeypatch.setattr(u, "update_blocker", lambda: None)
@@ -632,9 +634,11 @@ def test_the_frozen_asset_follows_the_native_cpu(monkeypatch: pytest.MonkeyPatch
seen: list[tuple[str, str]] = []
monkeypatch.setattr(u, "machine_for_update", lambda: "arm64")
monkeypatch.setattr(
- u, "installer_asset_name", lambda platform, machine: seen.append((platform, machine))
+ u,
+ "installer_asset_names",
+ lambda platform, machine: seen.append((platform, machine)) or (),
)
- u._frozen_asset_name()
+ u._frozen_asset_names()
assert seen and seen[0][1] == "arm64"
@@ -650,3 +654,141 @@ def test_apply_downloads_into_a_fresh_private_folder(
assert client.post("/api/update/apply").status_code == 200
assert seen["installer"].parent == workdir
+
+
+# --------------------------------------------------------------------------- #
+# A release may carry the installer under more than one accepted name
+# --------------------------------------------------------------------------- #
+NEW_SETUP_NAME = "Dodaios-Setup-x64.exe"
+
+
+def _asset_entry(name: str) -> dict[str, Any]:
+ return {
+ "name": name,
+ "browser_download_url": f"https://example.invalid/{name}",
+ "size": 123,
+ }
+
+
+def _patch_frozen_names(monkeypatch: pytest.MonkeyPatch, *names: str) -> None:
+ _patch_frozen(monkeypatch)
+ monkeypatch.setattr(u, "installer_asset_names", lambda _p, _m: names)
+
+
+def test_real_asset_names_cover_what_this_machine_would_ask_for() -> None:
+ """The route asks the one table; a Windows x64 box accepts both names."""
+ from jarvis.core.installer_update import installer_asset_names
+
+ assert installer_asset_names("win32", "AMD64") == (NEW_SETUP_NAME, SETUP_NAME)
+
+
+def test_status_offers_the_preferred_name_when_a_release_carries_both(
+ client: TestClient, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ _patch_frozen_names(monkeypatch, NEW_SETUP_NAME, SETUP_NAME)
+ assets = [
+ _asset_entry(SETUP_NAME),
+ _asset_entry(NEW_SETUP_NAME),
+ _asset_entry(CHECKSUMS_ASSET_NAME),
+ ]
+ _patch_latest(monkeypatch, _release("1.6.0", assets=assets))
+
+ body = client.get("/api/update/status").json()
+
+ assert body["update_available"] is True
+ assert body["asset"]["name"] == NEW_SETUP_NAME
+
+
[email protected]("published", [SETUP_NAME, NEW_SETUP_NAME])
+def test_status_offers_whichever_single_name_a_release_carries(
+ client: TestClient, monkeypatch: pytest.MonkeyPatch, published: str
+) -> None:
+ _patch_frozen_names(monkeypatch, NEW_SETUP_NAME, SETUP_NAME)
+ assets = [_asset_entry(published), _asset_entry(CHECKSUMS_ASSET_NAME)]
+ _patch_latest(monkeypatch, _release("1.6.0", assets=assets))
+
+ body = client.get("/api/update/status").json()
+
+ assert body["update_available"] is True
+ assert body["asset"]["name"] == published
+
+
[email protected]("published", [SETUP_NAME, NEW_SETUP_NAME])
+def test_apply_with_one_published_name_downloads_exactly_as_before(
+ client: TestClient, monkeypatch: pytest.MonkeyPatch, published: str
+) -> None:
+ """One candidate: the download is called without any alternative."""
+ _patch_frozen_names(monkeypatch, NEW_SETUP_NAME, SETUP_NAME)
+ assets = [_asset_entry(published), _asset_entry(CHECKSUMS_ASSET_NAME)]
+ _patch_latest(monkeypatch, _release("1.6.0", assets=assets))
+ # This recorder accepts no ``alternatives`` keyword - passing one fails.
+ seen = _capture_install(monkeypatch)
+
+ response = client.post("/api/update/apply")
+
+ assert response.status_code == 200
+ assert seen["asset"].name == published
+ assert response.json()["asset"]["name"] == published
+
+
+def test_apply_lets_the_checksum_manifest_choose_between_two_names(
+ client: TestClient, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ _patch_frozen_names(monkeypatch, NEW_SETUP_NAME, SETUP_NAME)
+ assets = [
+ _asset_entry(SETUP_NAME),
+ _asset_entry(NEW_SETUP_NAME),
+ _asset_entry(CHECKSUMS_ASSET_NAME),
+ ]
+ _patch_latest(monkeypatch, _release("1.6.0", assets=assets))
+ seen: dict[str, Any] = {}
+
+ def _write(path: Path) -> Path:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_bytes(b"verified installer")
+ return path
+
+ async def _download(
+ asset: Any,
+ checksums: Any,
+ *,
+ dest_dir: Path,
+ on_progress: Any = None,
+ alternatives: Any = (),
+ ) -> Path:
+ seen["asset"] = asset.name
+ seen["alternatives"] = [candidate.name for candidate in alternatives]
+ # The manifest of this release only vouches for the second name.
+ return _write(dest_dir / alternatives[0].name)
+
+ def _apply(installer: Path, **_kwargs: Any) -> str:
+ seen["installer"] = installer.name
+ return "the Windows installer is running"
+
+ monkeypatch.setattr(u, "download_and_verify", _download)
+ monkeypatch.setattr(u, "apply_installer", _apply)
+ monkeypatch.setattr(u, "download_workdir", lambda: tmp_path / "work")
+
+ response = client.post("/api/update/apply")
+
+ assert response.status_code == 200
+ assert seen["asset"] == NEW_SETUP_NAME
+ assert seen["alternatives"] == [SETUP_NAME]
+ assert seen["installer"] == SETUP_NAME
+ # The answer names the file that was actually verified and handed over.
+ assert response.json()["asset"]["name"] == SETUP_NAME
+
+
+def test_apply_names_every_accepted_file_when_a_release_has_none(
+ client: TestClient, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ _patch_frozen_names(monkeypatch, NEW_SETUP_NAME, SETUP_NAME)
+ _patch_latest(
+ monkeypatch, _release("1.6.0", assets=[_asset_entry(CHECKSUMS_ASSET_NAME)])
+ )
+
+ response = client.post("/api/update/apply")
+
+ assert response.status_code == 502
+ assert NEW_SETUP_NAME in response.json()["detail"]
+ assert SETUP_NAME in response.json()["detail"]