Skip to content

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

fix(update): keep installs cloned before the rename on the update channel (#544)

Ruben Lütkea50e9687ea10
diff --git a/install/install.ps1 b/install/install.ps1
index 94416aa6b1..fd82f59a22 100644
--- a/install/install.ps1
+++ b/install/install.ps1
@@ -203,6 +203,7 @@ if ($OfficialRepoSlug -notmatch '^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$') {
throw 'JARVIS_OFFICIAL_REPO_SLUG must be an exact owner/repository slug'
}
$RepoUrl = if ($env:JARVIS_INSTALL_REPO) { $env:JARVIS_INSTALL_REPO } else { "https://github.com/$OfficialRepoSlug.git" }
+$LegacyOfficialRepoSlug = 'PersonalJarvis/PersonalJarvis'
$ConfigFileName = 'jarvis.toml'
$Branch = if ($env:JARVIS_INSTALL_REF) { $env:JARVIS_INSTALL_REF } else { 'main' }
$InstallDir = if ($env:JARVIS_INSTALL_DIR) { $env:JARVIS_INSTALL_DIR } else { Join-Path $env:USERPROFILE '.personal-jarvis' }
@@ -687,7 +688,27 @@ function Invoke-SalvageReclone {
Write-Ok 'reinstalled fresh (previous state preserved in the backup dir)'
}
+# A checkout cloned before the GitHub rename still stores the old origin. Git
+# fetches through GitHub's redirect, but the in-app updater identifies a managed
+# install by this remote, so an untouched one loses its Update button. Only the
+# stock repository is retargeted; an explicit repository override is left alone.
+# (POSIX twin: retarget_legacy_origin in install.sh.)
+function Update-LegacyOrigin {
+ if ($env:JARVIS_INSTALL_REPO -or $env:JARVIS_OFFICIAL_REPO_SLUG) { return }
+ $Origin = & git -C $InstallDir config --get remote.origin.url
+ if ($LASTEXITCODE -ne 0 -or -not $Origin) { return }
+ $Tail = "$Origin".Trim().TrimEnd('/') -replace '\.git$', ''
+ if ($Tail -notmatch ('github\.com[:/]' + [regex]::Escape($LegacyOfficialRepoSlug) + '$')) { return }
+ & git -C $InstallDir remote set-url origin $RepoUrl
+ if ($LASTEXITCODE -eq 0) {
+ Write-Note 'pointed this install at the renamed repository'
+ } else {
+ Write-Note 'could not update the stored repository address - continuing'
+ }
+}
+
if (Test-Path (Join-Path $InstallDir '.git')) {
+ Update-LegacyOrigin
$UpdateOk = $true
Push-Location $InstallDir
try {
diff --git a/install/install.sh b/install/install.sh
index 79fd3229c7..c61ee0071b 100755
--- a/install/install.sh
+++ b/install/install.sh
@@ -25,6 +25,7 @@ if [[ ! "$OFFICIAL_REPO_SLUG" =~ ^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$ ]]; then
exit 2
fi
REPO_URL="${JARVIS_INSTALL_REPO:-https://github.com/${OFFICIAL_REPO_SLUG}.git}"
+LEGACY_OFFICIAL_REPO_SLUG="PersonalJarvis/PersonalJarvis"
CONFIG_FILE_NAME="jarvis.toml"
MACOS_AUTOSTART_LABEL="com.personal-jarvis.autostart"
BRANCH="${JARVIS_INSTALL_REF:-main}"
@@ -1074,7 +1075,33 @@ salvage_reclone() {
ok 'reinstalled fresh (previous state preserved in the backup dir)'
}
+# A checkout cloned before the GitHub rename still stores the old origin. Git
+# fetches through GitHub's redirect, but the in-app updater identifies a managed
+# install by this remote, so an untouched one loses its Update button. Only the
+# stock repository is retargeted; an explicit repository override is left alone.
+retarget_legacy_origin() {
+ # --- retarget-legacy-origin begin
+ if [ -z "${JARVIS_INSTALL_REPO:-}" ] && [ -z "${JARVIS_OFFICIAL_REPO_SLUG:-}" ]; then
+ _origin="$(git -C "$INSTALL_DIR" config --get remote.origin.url 2>/dev/null || true)"
+ _origin="$(printf '%s' "$_origin" | tr '[:upper:]' '[:lower:]')"
+ _origin="${_origin%/}"
+ _origin="${_origin%.git}"
+ _legacy="$(printf '%s' "$LEGACY_OFFICIAL_REPO_SLUG" | tr '[:upper:]' '[:lower:]')"
+ case "$_origin" in
+ *github.com[:/]"$_legacy")
+ if git -C "$INSTALL_DIR" remote set-url origin "$REPO_URL"; then
+ note 'pointed this install at the renamed repository'
+ else
+ note 'could not update the stored repository address - continuing'
+ fi
+ ;;
+ esac
+ fi
+ # --- retarget-legacy-origin end
+}
+
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" \
&& git -C "$INSTALL_DIR" checkout --quiet "$BRANCH" \
diff --git a/jarvis/core/branding.py b/jarvis/core/branding.py
index 317c49032e..ccff0c82b3 100644
--- a/jarvis/core/branding.py
+++ b/jarvis/core/branding.py
@@ -57,6 +57,9 @@ LINUX_DESKTOP_ENTRY_FILE_NAME = f"{PRODUCT_SLUG}.desktop"
LINUX_WM_CLASS = PRODUCT_SLUG
DEFAULT_OFFICIAL_REPO_SLUG = "Dodaios/Dodaios"
+# Checkouts cloned before the GitHub rename still store this origin. The
+# updater accepts it and rewrites origin to the current slug when it applies.
+LEGACY_OFFICIAL_REPO_SLUGS = ("PersonalJarvis/PersonalJarvis",)
OFFICIAL_REPO_SLUG_ENV_VAR = "JARVIS_OFFICIAL_REPO_SLUG"
@@ -89,6 +92,7 @@ __all__ = [
"CONTROL_KEY_PREFIX",
"DEFAULT_OFFICIAL_REPO_SLUG",
"DEFAULT_INSTALL_DIR_NAME",
+ "LEGACY_OFFICIAL_REPO_SLUGS",
"DESKTOP_OUTPUT_MIRROR_DIR_NAME",
"FALLBACK_USER_DATA_DIR_NAME",
"KEYRING_SERVICE_NAME",
diff --git a/jarvis/ui/web/update_routes.py b/jarvis/ui/web/update_routes.py
index b218ba45c7..7b235d64d9 100644
--- a/jarvis/ui/web/update_routes.py
+++ b/jarvis/ui/web/update_routes.py
@@ -73,8 +73,11 @@ from typing import Any, Literal
from fastapi import APIRouter, HTTPException, Request
from jarvis.core.branding import (
+ DEFAULT_OFFICIAL_REPO_SLUG,
+ LEGACY_OFFICIAL_REPO_SLUGS,
MANAGED_INSTALL_MARKER,
OFFICIAL_RELEASES_LATEST_API_URL,
+ OFFICIAL_REPO_GIT_URL,
OFFICIAL_REPO_SLUG,
UPDATER_USER_AGENT,
)
@@ -101,6 +104,7 @@ router = APIRouter(prefix="/api/update", tags=["update"])
# guard verifies the installed checkout's ``origin`` resolves here before any
# ``git reset --hard`` runs, so a dev checkout or a fork can never be self-reset.
_OFFICIAL_REPO_SLUG = OFFICIAL_REPO_SLUG
+_LEGACY_OFFICIAL_REPO_SLUGS = LEGACY_OFFICIAL_REPO_SLUGS
_RELEASES_LATEST_API = OFFICIAL_RELEASES_LATEST_API_URL
# Written by install/installer.py into the checkout root. Its presence is one
# half of "this copy is safe to self-update".
@@ -387,15 +391,60 @@ def _normalize_remote(url: str) -> str:
return tail
+def _remote_matches_slug(url: str, slug: str) -> bool:
+ """True when ``url`` resolves to exactly ``slug``, not a look-alike name."""
+ norm = _normalize_remote(url).lower()
+ needle = slug.lower()
+ return norm == needle or norm.endswith("/" + needle)
+
+
+def _accepted_official_slugs() -> tuple[str, ...]:
+ """Current slug, plus the pre-rename address while that slug is still ours.
+
+ An environment override points the updater at a different repository on
+ purpose, so the legacy address is accepted only for the stock slug.
+ """
+ if _OFFICIAL_REPO_SLUG != DEFAULT_OFFICIAL_REPO_SLUG:
+ return (_OFFICIAL_REPO_SLUG,)
+ return (_OFFICIAL_REPO_SLUG, *_LEGACY_OFFICIAL_REPO_SLUGS)
+
+
def _remote_is_official(url: str) -> bool:
- """True only if ``url`` resolves to exactly the official ``owner/name``.
+ """True only if ``url`` resolves to an accepted official ``owner/name``.
Must MATCH the last two path segments, not merely contain the slug — so a
- look-alike fork (``.../PersonalJarvis/PersonalJarvisEvil``) is rejected.
+ look-alike fork (``.../Dodaios/DodaiosEvil``) is rejected. A checkout whose
+ origin is still ``PersonalJarvis/PersonalJarvis`` stays official; applying
+ an update rewrites that remote to the current URL.
"""
- norm = _normalize_remote(url).lower()
- slug = _OFFICIAL_REPO_SLUG.lower()
- return norm == slug or norm.endswith("/" + slug)
+ return any(_remote_matches_slug(url, slug) for slug in _accepted_official_slugs())
+
+
+async def _retarget_legacy_origin(root: Path) -> None:
+ """Point a pre-rename origin at the current official URL.
+
+ Git still fetches through GitHub's redirect, but the next release of this
+ app identifies the checkout by the stored remote. Rewriting it here is what
+ keeps one-click updates working after the legacy slug is no longer enough.
+ """
+ origin = await _git_output(["remote", "get-url", "origin"], cwd=root)
+ if origin is None or _remote_matches_slug(origin, _OFFICIAL_REPO_SLUG):
+ return
+ if not _remote_is_official(origin):
+ return
+ rc, _out, err = await _git(
+ ["remote", "set-url", "origin", OFFICIAL_REPO_GIT_URL],
+ cwd=root,
+ timeout_s=30.0,
+ )
+ if rc != 0:
+ raise HTTPException(
+ status_code=500,
+ detail=(
+ "could not retarget origin to the current repository: "
+ f"{err[:300] or 'unknown error'}"
+ ),
+ )
async def _resolve_managed_repo() -> Path | None:
@@ -429,7 +478,21 @@ async def _fetch_latest_release() -> dict[str, Any] | None:
try:
import httpx
- async with httpx.AsyncClient(timeout=_NETWORK_TIMEOUT_S) as client:
+ async def _stay_on_github_api(response: httpx.Response) -> None:
+ # A renamed repository answers 301. Follow that hop, and refuse any
+ # hop that leaves GitHub's API host: the JSON decides which
+ # installer the button will download.
+ if not response.has_redirect_location:
+ return
+ target = response.url.join(response.headers.get("location") or "")
+ if target.scheme != "https" or target.host != "api.github.com":
+ raise httpx.HTTPError(f"refusing a release-check redirect to {target}")
+
+ async with httpx.AsyncClient(
+ timeout=_NETWORK_TIMEOUT_S,
+ follow_redirects=True,
+ event_hooks={"response": [_stay_on_github_api]},
+ ) as client:
resp = await client.get(
_RELEASES_LATEST_API,
headers={
@@ -1380,6 +1443,8 @@ async def _apply_managed() -> dict[str, object]:
detail="could not identify the currently installed revision",
)
+ await _retarget_legacy_origin(root)
+
# Fetch the published tag, never the moving main branch. The update button
# promises a specific GitHub Release; applying an unreleased main commit
# would make the displayed version and installed bytes disagree.
diff --git a/tests/unit/install/test_install_legacy_origin.py b/tests/unit/install/test_install_legacy_origin.py
new file mode 100644
index 0000000000..7a47b3dd52
--- /dev/null
+++ b/tests/unit/install/test_install_legacy_origin.py
@@ -0,0 +1,283 @@
+"""A re-run quick installer points a pre-rename checkout at the current repository.
+
+The in-app updater identifies a managed install by its stored ``origin``. A
+checkout cloned before the GitHub rename keeps the old address, so the shell
+installers rewrite it before they fetch. Runs the REAL blocks extracted from
+``install/install.sh`` and ``install/install.ps1`` against a real git checkout,
+so the shipped logic cannot drift from what is tested.
+"""
+from __future__ import annotations
+
+import os
+import re
+import shutil
+import subprocess
+from pathlib import Path
+
+import pytest
+
+from jarvis.core.branding import (
+ DEFAULT_OFFICIAL_REPO_SLUG,
+ LEGACY_OFFICIAL_REPO_SLUGS,
+ OFFICIAL_REPO_GIT_URL,
+)
+from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS
+
+REPO = Path(__file__).resolve().parents[3]
+INSTALL_SH = REPO / "install" / "install.sh"
+INSTALL_PS1 = REPO / "install" / "install.ps1"
+
+BLOCK_BEGIN = "# --- retarget-legacy-origin begin"
+BLOCK_END = "# --- retarget-legacy-origin end"
+
+LEGACY_SLUG = LEGACY_OFFICIAL_REPO_SLUGS[0]
+LEGACY_URL = f"https://github.com/{LEGACY_SLUG}.git"
+CURRENT_URL = f"https://github.com/{DEFAULT_OFFICIAL_REPO_SLUG}.git"
+OVERRIDES = ["JARVIS_INSTALL_REPO", "JARVIS_OFFICIAL_REPO_SLUG"]
+
+SH_DRIVER = """#!/usr/bin/env bash
+set -euo pipefail
+note() { printf 'NOTE|%s\\n' "$*"; }
+source "$BLOCK_FILE"
+"""
+
+PS_DRIVER = """$ErrorActionPreference = 'Stop'
+function Write-Note([string]$Text) { Write-Host "NOTE|$Text" }
+$InstallDir = $env:TEST_INSTALL_DIR
+$RepoUrl = $env:TEST_REPO_URL
+$LegacyOfficialRepoSlug = $env:TEST_LEGACY_SLUG
+. $env:TEST_FUNCTION_FILE
+Update-LegacyOrigin
+"""
+
+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_git = pytest.mark.skipif(GIT is None, reason="git is not installed")
+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"
+)
+
+
+def _run(
+ args: list[str], *, env: dict[str, str] | None = None
+) -> subprocess.CompletedProcess[str]:
+ return subprocess.run( # noqa: S603 -- test-controlled command
+ args,
+ capture_output=True,
+ text=True,
+ encoding="utf-8",
+ errors="replace",
+ timeout=120,
+ env=env,
+ creationflags=NO_WINDOW_CREATIONFLAGS,
+ )
+
+
+def _checkout(tmp_path: Path, origin: str | None) -> Path:
+ root = tmp_path / "install"
+ root.mkdir()
+ assert _run([GIT, "init", "--quiet", str(root)]).returncode == 0
+ if origin is not None:
+ added = _run([GIT, "-C", str(root), "remote", "add", "origin", origin])
+ assert added.returncode == 0, added.stderr
+ return root
+
+
+def _origin(root: Path) -> str:
+ return _run(
+ [GIT, "-C", str(root), "config", "--get", "remote.origin.url"]
+ ).stdout.strip()
+
+
+def _sh_path(path: Path) -> str:
+ return str(path).replace("\\", "/")
+
+
+def _base_env() -> dict[str, str]:
+ return {key: value for key, value in os.environ.items() if key not in OVERRIDES}
+
+
+def _run_sh(
+ tmp_path: Path, root: Path, **overrides: str
+) -> subprocess.CompletedProcess[str]:
+ source = INSTALL_SH.read_text(encoding="utf-8")
+ assert BLOCK_BEGIN in source and BLOCK_END in source, (
+ "the retarget-legacy-origin extraction markers vanished from install.sh"
+ )
+ block = tmp_path / "block.sh"
+ block.write_text(
+ source.split(BLOCK_BEGIN, 1)[1].split(BLOCK_END, 1)[0],
+ encoding="utf-8",
+ newline="\n",
+ )
+ driver = tmp_path / "driver.sh"
+ driver.write_text(SH_DRIVER, encoding="utf-8", newline="\n")
+ env = _base_env()
+ env.update(
+ BLOCK_FILE=_sh_path(block),
+ INSTALL_DIR=_sh_path(root),
+ REPO_URL=CURRENT_URL,
+ LEGACY_OFFICIAL_REPO_SLUG=LEGACY_SLUG,
+ **overrides,
+ )
+ return _run([BASH, str(driver)], env=env)
+
+
+def _run_ps(
+ tmp_path: Path, root: Path, **overrides: str
+) -> subprocess.CompletedProcess[str]:
+ source = INSTALL_PS1.read_text(encoding="utf-8")
+ match = re.search(
+ r"^function Update-LegacyOrigin \{\r?\n.*?^\}\r?$", source, re.S | re.M
+ )
+ assert match is not None, "Update-LegacyOrigin 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 = _base_env()
+ env.update(
+ TEST_INSTALL_DIR=str(root),
+ TEST_REPO_URL=CURRENT_URL,
+ TEST_LEGACY_SLUG=LEGACY_SLUG,
+ TEST_FUNCTION_FILE=str(function_file),
+ **overrides,
+ )
+ return _run(
+ [
+ POWERSHELL,
+ "-NoProfile",
+ "-NonInteractive",
+ "-ExecutionPolicy",
+ "Bypass",
+ "-File",
+ str(driver),
+ ],
+ env=env,
+ )
+
+
+def test_installer_projections_match_core_branding() -> None:
+ shell = INSTALL_SH.read_text(encoding="utf-8")
+ powershell = INSTALL_PS1.read_text(encoding="utf-8")
+ assert len(LEGACY_OFFICIAL_REPO_SLUGS) == 1
+ assert f'LEGACY_OFFICIAL_REPO_SLUG="{LEGACY_SLUG}"' in shell
+ assert f"$LegacyOfficialRepoSlug = '{LEGACY_SLUG}'" in powershell
+ assert CURRENT_URL == OFFICIAL_REPO_GIT_URL
+
+
+LEGACY_FORMS = [
+ LEGACY_URL,
+ LEGACY_URL.removesuffix(".git"),
+ LEGACY_URL.lower(),
+ f"[email protected]:{LEGACY_SLUG}.git",
+]
+UNTOUCHED_FORMS = [
+ CURRENT_URL,
+ "https://github.com/someone/fork.git",
+ f"https://github.com/{LEGACY_SLUG}Evil.git",
+ f"https://github.com/evil/{LEGACY_SLUG.split('/')[1]}.git",
+]
+
+
+@needs_git
+@needs_bash
[email protected]("origin", LEGACY_FORMS)
+def test_sh_rewrites_a_legacy_origin(tmp_path: Path, origin: str) -> None:
+ root = _checkout(tmp_path, origin)
+ proc = _run_sh(tmp_path, root)
+ assert proc.returncode == 0, proc.stderr
+ assert _origin(root) == CURRENT_URL
+ assert "NOTE|pointed this install at the renamed repository" in proc.stdout
+
+
+@needs_git
+@needs_bash
[email protected]("origin", UNTOUCHED_FORMS)
+def test_sh_leaves_other_origins_alone(tmp_path: Path, origin: str) -> None:
+ root = _checkout(tmp_path, origin)
+ proc = _run_sh(tmp_path, root)
+ assert proc.returncode == 0, proc.stderr
+ assert _origin(root) == origin
+ assert "NOTE|" not in proc.stdout
+
+
+@needs_git
+@needs_bash
[email protected]("variable", OVERRIDES)
+def test_sh_respects_an_explicit_repository_override(
+ tmp_path: Path, variable: str
+) -> None:
+ root = _checkout(tmp_path, LEGACY_URL)
+ proc = _run_sh(tmp_path, root, **{variable: "own/repo"})
+ assert proc.returncode == 0, proc.stderr
+ assert _origin(root) == LEGACY_URL
+
+
+@needs_git
+@needs_bash
+def test_sh_tolerates_a_checkout_without_origin(tmp_path: Path) -> None:
+ root = _checkout(tmp_path, None)
+ proc = _run_sh(tmp_path, root)
+ assert proc.returncode == 0, proc.stderr
+ assert _origin(root) == ""
+
+
+@needs_git
+@needs_powershell
[email protected]("origin", LEGACY_FORMS)
+def test_ps1_rewrites_a_legacy_origin(tmp_path: Path, origin: str) -> None:
+ root = _checkout(tmp_path, origin)
+ proc = _run_ps(tmp_path, root)
+ assert proc.returncode == 0, proc.stderr
+ assert _origin(root) == CURRENT_URL
+ assert "NOTE|pointed this install at the renamed repository" in proc.stdout
+
+
+@needs_git
+@needs_powershell
[email protected]("origin", UNTOUCHED_FORMS)
+def test_ps1_leaves_other_origins_alone(tmp_path: Path, origin: str) -> None:
+ root = _checkout(tmp_path, origin)
+ proc = _run_ps(tmp_path, root)
+ assert proc.returncode == 0, proc.stderr
+ assert _origin(root) == origin
+ assert "NOTE|" not in proc.stdout
+
+
+@needs_git
+@needs_powershell
[email protected]("variable", OVERRIDES)
+def test_ps1_respects_an_explicit_repository_override(
+ tmp_path: Path, variable: str
+) -> None:
+ root = _checkout(tmp_path, LEGACY_URL)
+ proc = _run_ps(tmp_path, root, **{variable: "own/repo"})
+ assert proc.returncode == 0, proc.stderr
+ assert _origin(root) == LEGACY_URL
+
+
+@needs_git
+@needs_powershell
+def test_ps1_tolerates_a_checkout_without_origin(tmp_path: Path) -> None:
+ root = _checkout(tmp_path, None)
+ proc = _run_ps(tmp_path, root)
+ assert proc.returncode == 0, proc.stderr
+ assert _origin(root) == ""
diff --git a/tests/unit/ui/web/test_update_routes.py b/tests/unit/ui/web/test_update_routes.py
index 6310a35ea8..48dbaed6f3 100644
--- a/tests/unit/ui/web/test_update_routes.py
+++ b/tests/unit/ui/web/test_update_routes.py
@@ -71,16 +71,20 @@ def test_versions_equal_is_normalized_and_fail_closed() -> None:
assert not u._versions_equal("invalid", "invalid")
-def test_remote_is_official_accepts_only_exact_repo() -> None:
+def test_remote_is_official_accepts_current_and_legacy_repo() -> None:
# https, ssh, and a local path on either slash style all resolve.
assert u._remote_is_official("https://github.com/Dodaios/Dodaios.git")
assert u._remote_is_official("[email protected]:Dodaios/Dodaios.git")
assert u._remote_is_official("C:\\x\\Dodaios\\Dodaios")
+ # A checkout cloned before the rename is still this repository.
+ assert u._remote_is_official("https://github.com/PersonalJarvis/PersonalJarvis.git")
+ assert u._remote_is_official("[email protected]:PersonalJarvis/PersonalJarvis.git")
# A different repo is rejected...
assert not u._remote_is_official("https://github.com/someone/fork.git")
# ...and so is a look-alike fork whose name merely starts with the slug...
+ assert not u._remote_is_official("https://github.com/Dodaios/DodaiosEvil.git")
assert not u._remote_is_official(
- "https://github.com/Dodaios/DodaiosEvil.git"
+ "https://github.com/PersonalJarvis/PersonalJarvisEvil.git"
)
# ...or one under a different owner with the right repo name.
assert not u._remote_is_official("https://github.com/evil/Dodaios.git")
@@ -232,6 +236,7 @@ def test_apply_happy_path_pulls_and_signals_restart(
"refs/tags/v1.0.2",
] in calls
assert not any(call[:2] == ["reset", "--hard"] for call in calls)
+ assert not any(call[:2] == ["remote", "set-url"] for call in calls)
assert sentinel.read_text(encoding="utf-8") == "old"
pending = json.loads(
@@ -242,6 +247,96 @@ def test_apply_happy_path_pulls_and_signals_restart(
assert pending["profile"] == "full"
+def test_apply_rewrites_legacy_origin_before_fetch(
+ 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"})
+ calls: list[list[str]] = []
+
+ async def _fake_git(args, *, cwd, timeout_s=60.0, on_stderr_line=None):
+ calls.append(args)
+ return 0, "", ""
+
+ async def _fake_git_output(args, *, cwd, timeout_s=15.0):
+ calls.append(args)
+ if args == ["remote", "get-url", "origin"]:
+ return "https://github.com/PersonalJarvis/PersonalJarvis.git"
+ if args == ["rev-parse", "HEAD"]:
+ return "a" * 40
+ if args == ["rev-parse", "FETCH_HEAD^{commit}"]:
+ return "b" * 40
+ if args == ["show", f"{'b' * 40}:jarvis/__init__.py"]:
+ return '__version__ = "1.0.2"'
+ return None
+
+ monkeypatch.setattr(u, "_git", _fake_git)
+ monkeypatch.setattr(u, "_git_output", _fake_git_output)
+ body = client.post("/api/update/apply").json()
+ assert body["ok"] is True
+ rewrite = ["remote", "set-url", "origin", u.OFFICIAL_REPO_GIT_URL]
+ fetch = ["fetch", "--progress", "--depth", "1", "origin", "refs/tags/v1.0.2"]
+ assert rewrite in calls
+ assert calls.index(rewrite) < calls.index(fetch)
+
+
+def test_apply_leaves_current_origin_untouched(
+ 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"})
+ calls: list[list[str]] = []
+
+ async def _fake_git(args, *, cwd, timeout_s=60.0, on_stderr_line=None):
+ calls.append(args)
+ return 0, "", ""
+
+ async def _fake_git_output(args, *, cwd, timeout_s=15.0):
+ calls.append(args)
+ if args == ["remote", "get-url", "origin"]:
+ return "https://github.com/Dodaios/Dodaios.git"
+ if args == ["rev-parse", "HEAD"]:
+ return "a" * 40
+ if args == ["rev-parse", "FETCH_HEAD^{commit}"]:
+ return "b" * 40
+ if args == ["show", f"{'b' * 40}:jarvis/__init__.py"]:
+ return '__version__ = "1.0.2"'
+ return None
+
+ monkeypatch.setattr(u, "_git", _fake_git)
+ monkeypatch.setattr(u, "_git_output", _fake_git_output)
+ assert client.post("/api/update/apply").json()["ok"] is True
+ assert not any(call[:2] == ["remote", "set-url"] for call in calls)
+
+
+def test_apply_fails_when_legacy_origin_cannot_be_rewritten(
+ 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"})
+
+ async def _fake_git(args, *, cwd, timeout_s=60.0, on_stderr_line=None):
+ if args[:2] == ["remote", "set-url"]:
+ return 1, "", "denied"
+ return 0, "", ""
+
+ async def _fake_git_output(args, *, cwd, timeout_s=15.0):
+ if args == ["remote", "get-url", "origin"]:
+ return "[email protected]:PersonalJarvis/PersonalJarvis.git"
+ if args == ["rev-parse", "HEAD"]:
+ return "a" * 40
+ return None
+
+ monkeypatch.setattr(u, "_git", _fake_git)
+ monkeypatch.setattr(u, "_git_output", _fake_git_output)
+ response = client.post("/api/update/apply")
+ assert response.status_code == 500
+ assert not (tmp_path / u._PENDING_UPDATE_NAME).exists()
+
+
def test_apply_git_fetch_failure_is_502(
client: TestClient, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
@@ -546,3 +641,67 @@ def test_legacy_linux_marker_distinguishes_desktop_from_headless(
monkeypatch.setenv("WAYLAND_DISPLAY", "wayland-0")
assert u._managed_install_profile(tmp_path) == "full"
+
+
+# --------------------------------------------------------------------------- #
+# Release check across the repository rename
+# --------------------------------------------------------------------------- #
+def _serve_release_api(monkeypatch: pytest.MonkeyPatch, handler) -> list[str]:
+ """Route the updater's real httpx client through an in-process transport."""
+ import httpx
+
+ seen: list[str] = []
+
+ def _recording(request: httpx.Request) -> httpx.Response:
+ seen.append(str(request.url))
+ return handler(request)
+
+ real_client = httpx.AsyncClient
+
+ def _client(**kwargs):
+ return real_client(transport=httpx.MockTransport(_recording), **kwargs)
+
+ monkeypatch.setattr(httpx, "AsyncClient", _client)
+ return seen
+
+
+async def test_release_check_follows_a_renamed_repository(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ import httpx
+
+ moved = "https://api.github.com/repositories/1255092568/releases/latest"
+
+ def _handler(request: httpx.Request) -> httpx.Response:
+ if str(request.url) == u._RELEASES_LATEST_API:
+ return httpx.Response(301, headers={"location": moved})
+ assert str(request.url) == moved
+ return httpx.Response(200, json={"tag_name": "v9.9.9", "assets": []})
+
+ seen = _serve_release_api(monkeypatch, _handler)
+ release = await u._fetch_latest_release()
+ assert release is not None and release["version"] == "9.9.9"
+ assert seen == [u._RELEASES_LATEST_API, moved]
+
+
+ "location",
+ [
+ "https://example.invalid/repos/Dodaios/Dodaios/releases/latest",
+ "http://api.github.com/repositories/1/releases/latest",
+ ],
+)
+async def test_release_check_refuses_a_redirect_off_the_github_api(
+ monkeypatch: pytest.MonkeyPatch, location: str
+) -> None:
+ import httpx
+
+ def _handler(request: httpx.Request) -> httpx.Response:
+ if str(request.url) == u._RELEASES_LATEST_API:
+ return httpx.Response(301, headers={"location": location})
+ return httpx.Response(200, json={"tag_name": "v9.9.9", "assets": []})
+
+ seen = _serve_release_api(monkeypatch, _handler)
+ assert await u._fetch_latest_release() is None
+ assert seen == [u._RELEASES_LATEST_API]
+ assert u._last_good_release is None