From d88f76230ee24a8cfdd951130262022172402ff7 Mon Sep 17 00:00:00 2001 From: zfoong Date: Sat, 21 Nov 2026 09:35:27 +0900 Subject: [PATCH 1/9] feat: verify the Python and Node runtimes against pinned checksums The installer downloaded the newest python-build-standalone release and the newest Node 24 from nodejs.org's index, trusting TLS alone. Both now come from a release pinned in app/provision (python_downloads.json and node_downloads.json) and are checked against the SHA-256 each release publishes for its archives (Node's from its signed SHASUMS256.txt), so a mirror or a compromised download can't change them and resolving the URL needs no network. A cached archive is used only when it matches the pin. Co-Authored-By: Claude Opus 5.5 Signed-off-by: zfoong --- .github/workflows/startup.yml | 8 +- README.md | 2 +- app/downloads.py | 24 ---- app/node_runtime.py | 140 +++++++-------------- app/provision/node_downloads.json | 12 ++ app/provision/python_downloads.json | 9 +- app/provision/runtimes.py | 125 +++++++------------ scripts/prefetch_runtimes.py | 22 ++-- scripts/test_install_e2e.py | 1 + tests/test_node_downloads.py | 99 +++++++++++++++ tests/test_python_downloads.py | 183 +++++++--------------------- 11 files changed, 269 insertions(+), 356 deletions(-) create mode 100644 app/provision/node_downloads.json create mode 100644 tests/test_node_downloads.py diff --git a/.github/workflows/startup.yml b/.github/workflows/startup.yml index 7d922e2a..deec508c 100644 --- a/.github/workflows/startup.yml +++ b/.github/workflows/startup.yml @@ -10,9 +10,12 @@ on: - 'app/python_runtime.py' - 'app/provision/runtimes.py' - 'app/provision/python_downloads.json' + - 'app/provision/node_downloads.json' + - 'app/node_runtime.py' - 'app/provision/verify.py' - 'tests/test_native_runtime.py' - 'tests/test_python_downloads.py' + - 'tests/test_node_downloads.py' - 'tests/test_autostart.py' - 'tests/test_craftbot_service.py' - '.github/workflows/startup.yml' @@ -25,9 +28,12 @@ on: - 'app/python_runtime.py' - 'app/provision/runtimes.py' - 'app/provision/python_downloads.json' + - 'app/provision/node_downloads.json' + - 'app/node_runtime.py' - 'app/provision/verify.py' - 'tests/test_native_runtime.py' - 'tests/test_python_downloads.py' + - 'tests/test_node_downloads.py' - 'tests/test_autostart.py' - 'tests/test_craftbot_service.py' - '.github/workflows/startup.yml' @@ -46,4 +52,4 @@ jobs: python-version: '3.10' - run: python -m pip install pytest==9.0.2 - name: Check login startup and browser-only shortcuts - run: python -m pytest tests/test_autostart.py tests/test_craftbot_service.py tests/test_python_downloads.py tests/test_native_runtime.py -q + run: python -m pytest tests/test_autostart.py tests/test_craftbot_service.py tests/test_python_downloads.py tests/test_node_downloads.py tests/test_native_runtime.py -q diff --git a/README.md b/README.md index 6d366e87..d10d899e 100644 --- a/README.md +++ b/README.md @@ -241,7 +241,7 @@ Point the downloads at mirrors before you install: export CRAFTBOT_MIRRORS="https://github.com/=https:///https://github.com/;https://nodejs.org/dist/=https://npmmirror.com/mirrors/node/" ``` -Python packages and the memory embedding model are still checked against pinned SHA-256 checksums, so a mirror cannot change them. The Python and Node.js runtimes are not pinned, so only use a mirror you trust for those. In Windows PowerShell, set variables with `$env:NAME = "value"` instead of `export`. +Python packages, the Python and Node.js runtimes, and the memory embedding model are checked against pinned SHA-256 checksums, so a mirror cannot change them. In Windows PowerShell, set variables with `$env:NAME = "value"` instead of `export`. ### Server without a desktop diff --git a/app/downloads.py b/app/downloads.py index a67c9a5d..b914fa79 100644 --- a/app/downloads.py +++ b/app/downloads.py @@ -205,30 +205,6 @@ def cache_name(url: str) -> str: return unquote(name) or "download.bin" -def find_cached(pattern: str) -> Optional[str]: - """A cached archive matching a glob, or None. - - Lets a caller use the cache WITHOUT first resolving a download URL. - That matters more than it sounds: resolving the Python runtime's URL - means fetching a large JSON release index, and on a slow or flaky link - that request is itself a failure point — observed as - `IncompleteRead(1277952 bytes read)` in Windows Sandbox. Having the file - already and still failing because the index could not be read is an - absurd way to lose an install. - - The archive names carry version and platform, so a glob like - `cpython-3.10.*-x86_64-pc-windows-msvc-install_only.tar.gz` identifies - the right file without asking anyone. - """ - import glob as _glob - - cache = cache_dir() - if not cache: - return None - matches = sorted(_glob.glob(os.path.join(cache, pattern))) - return matches[-1] if matches else None - - def _download_once( url: str, dest: str, diff --git a/app/node_runtime.py b/app/node_runtime.py index 68f2dbd2..1f929005 100644 --- a/app/node_runtime.py +++ b/app/node_runtime.py @@ -36,7 +36,7 @@ import sys from dataclasses import dataclass from pathlib import Path -from typing import Optional +from typing import Optional, Tuple logger = logging.getLogger(__name__) @@ -44,6 +44,12 @@ REPO_ROOT = Path(__file__).resolve().parents[1] +# The Node release a private copy is downloaded from, with the SHA-256 of each +# platform's archive as its signed SHASUMS256.txt lists it. +NODE_CONFIG_PATH = Path(__file__).resolve().parent / "provision" / "node_downloads.json" + +_SHA256_RE = re.compile(r"[0-9a-f]{64}") + # app.paths is the single answer to "where does state live" — in a dev # checkout that is the repo (so this is unchanged), and in an install it is # the per-user data dir. Before this, SIDECAR_DIR was derived from __file__ @@ -371,55 +377,45 @@ def _platform_suffix(): return f"linux-{arch}", "tar.xz" -def latest_download_url(log=None) -> Optional[str]: - """URL of the newest Node on the MIN_NODE_MAJOR line for this machine. +def pinned_download(log=None) -> Optional[Tuple[str, str, str]]: + """(version, url, sha256) of the pinned Node build for this machine, or None. + Only the release node_downloads.json names, checked against the SHA-256 + it pins for this platform's archive, as published in that release's + signed SHASUMS256.txt. Nothing is asked of nodejs.org's index, so the + version every install runs is the one the repository was reviewed with. Split out of download_sidecar so the archive can be pre-fetched into a cache without installing it (scripts/prefetch_runtimes.py). """ import json - import ssl - import urllib.request say = log or (lambda _m: None) - - try: - import certifi - - ctx = ssl.create_default_context(cafile=certifi.where()) - except ImportError: - ctx = ssl.create_default_context() - suffix, ext = _platform_suffix() - try: - req = urllib.request.Request( - "https://nodejs.org/dist/index.json", headers={"User-Agent": "CraftBot"} - ) - index = json.loads(urllib.request.urlopen(req, timeout=60, context=ctx).read()) - except Exception as e: - say(f" Could not reach the Node index: {str(e)[:160]}") + config = json.loads(NODE_CONFIG_PATH.read_text(encoding="utf-8")) + ver = str(config["version"]) + digest = config["sha256"].get(f"{suffix}.{ext}", "") + base = str(config["download_base"]).rstrip("/") + except (OSError, ValueError, KeyError, TypeError, AttributeError) as error: + say(f" Invalid Node download configuration: {error}") return None - ver = next( - ( - e["version"] - for e in index - if e.get("version", "").startswith(f"v{MIN_NODE_MAJOR}.") - ), - None, - ) - if not ver: - say(f" No v{MIN_NODE_MAJOR}.x release found in the Node index") + # nodejs.org names every release directory v... + if not re.fullmatch(r"v\d+\.\d+\.\d+", ver) or major_of(ver) != MIN_NODE_MAJOR: + say(f" The pinned Node {ver} is not a v{MIN_NODE_MAJOR}.x release") return None - return f"https://nodejs.org/dist/{ver}/node-{ver}-{suffix}.{ext}" + if not _SHA256_RE.fullmatch(str(digest)): + say(f" No pinned Node {ver} build for {suffix}") + return None + return ver, f"{base}/{ver}/node-{ver}-{suffix}.{ext}", digest -def _extract_node(archive_src, ver, suffix, ext, say, url=None): - """Put a Node archive into SIDECAR_DIR and return its binary path. +def _extract_node(ver, suffix, ext, say, url, sha256): + """Download a Node archive into SIDECAR_DIR and return its binary path. - Shared by the cached and downloaded paths so extraction, layout and the - binary probe cannot drift between them. + downloads.download uses a cached copy (CRAFTBOT_DOWNLOAD_CACHE) only when + it matches the pin, and refuses a download that doesn't, so nothing + unverified is ever extracted. """ import tarfile import zipfile @@ -430,13 +426,11 @@ def _extract_node(archive_src, ver, suffix, ext, say, url=None): os.makedirs(dest_root, exist_ok=True) archive = os.path.join(dest_root, f"_download.{ext}") try: - if archive_src: - say(f" Using cached {os.path.basename(archive_src)}") - shutil.copyfile(archive_src, archive) - else: - # Streamed with progress: the archive is 30-55MB, and a single - # silent blocking copy is indistinguishable from a hung install. - downloads.download(url, archive, log=say, label=f"Node {ver}") + # Streamed with progress: the archive is 30-55MB, and a single + # silent blocking copy is indistinguishable from a hung install. + downloads.download( + url, archive, log=say, label=f"Node {ver}", expected_sha256=sha256 + ) say(" Extracting...") if ext == "zip": zipfile.ZipFile(archive).extractall(dest_root) @@ -470,67 +464,17 @@ def download_sidecar(log=None) -> Optional[str]: the installer needs it too: installer users never run install.py, so that was the only route by which they could obtain Node, and they had none. - Stdlib-only (certifi when importable, else the system trust store). + Stdlib-only. """ - import json - import ssl - import urllib.request - say = log or (lambda _m: None) - try: - import certifi - - ctx = ssl.create_default_context(cafile=certifi.where()) - except ImportError: - ctx = ssl.create_default_context() - + pinned = pinned_download(log=say) + if not pinned: + return None + ver, url, sha256 = pinned suffix, ext = _platform_suffix() - - # Consult the cache BEFORE the network. Resolving the version means - # fetching nodejs.org's release index, which on a slow or flaky link is - # its own failure point — and failing there while the archive is already - # on disk would be a pointless way to lose an install. - cached_archive = None - ver_from_cache = None - try: - from app import downloads - - cached_archive = downloads.find_cached( - f"node-v{MIN_NODE_MAJOR}.*-{suffix}.{ext}" - ) - if cached_archive: - m = _NODE_VER_RE.search(os.path.basename(cached_archive)) - if m: - ver_from_cache = "v" + ".".join(m.groups()) - except Exception: - cached_archive = None - - if cached_archive and ver_from_cache: - ver = ver_from_cache - url = f"https://nodejs.org/dist/{ver}/node-{ver}-{suffix}.{ext}" - return _extract_node(cached_archive, ver, suffix, ext, say, url) - try: - # Newest release on the MIN_NODE_MAJOR line (the index is newest-first). - req = urllib.request.Request( - "https://nodejs.org/dist/index.json", headers={"User-Agent": "CraftBot"} - ) - index = json.loads(urllib.request.urlopen(req, timeout=60, context=ctx).read()) - ver = next( - ( - e["version"] - for e in index - if e.get("version", "").startswith(f"v{MIN_NODE_MAJOR}.") - ), - None, - ) - if not ver: - say(f" ⚠ No v{MIN_NODE_MAJOR}.x release found in the Node index") - return None - - url = f"https://nodejs.org/dist/{ver}/node-{ver}-{suffix}.{ext}" - return _extract_node(None, ver, suffix, ext, say, url) + return _extract_node(ver, suffix, ext, say, url, sha256) except Exception as e: say(f" ⚠ Sidecar Node download failed: {str(e)[:200]}") return None diff --git a/app/provision/node_downloads.json b/app/provision/node_downloads.json new file mode 100644 index 00000000..a471b883 --- /dev/null +++ b/app/provision/node_downloads.json @@ -0,0 +1,12 @@ +{ + "download_base": "https://nodejs.org/dist", + "version": "v24.22.3", + "sha256": { + "darwin-arm64.tar.gz": "ff6e17d4874b76d272212b908cc020d6e815fba5a6c7eaaa06add725840307fd", + "darwin-x64.tar.gz": "977614af0504c81045e7fd85596dbca0e5f951b96681516dadafedcca8c447f7", + "linux-arm64.tar.xz": "6e51a2ada00f0011cc266f65d98922b403d7ad88f809ca2aa615a5fe1ce6e86c", + "linux-x64.tar.xz": "4f2b175a6d53a5c617a80dba2676238a0688cef28c6da4eba35c7d844e66fcfb", + "win-arm64.zip": "b3cc74a295b39d4f273271e96f58c06dd2b35757ca12abec64c7d0598b434f14", + "win-x64.zip": "e612af99f626ab415ea225af6bce5c971feb448cb5cae250bb1c3fa50c5f7d9f" + } +} diff --git a/app/provision/python_downloads.json b/app/provision/python_downloads.json index ac19395b..3b2ab46d 100644 --- a/app/provision/python_downloads.json +++ b/app/provision/python_downloads.json @@ -10,5 +10,12 @@ "aarch64-unknown-linux-gnu", "x86_64-apple-darwin", "aarch64-apple-darwin" - ] + ], + "sha256": { + "x86_64-pc-windows-msvc": "cb023e83e42d8937ba77c7cf83641083c3b81e88e1226e1c694a347ae1924d54", + "x86_64-unknown-linux-gnu": "1780de9ddda04e956d2a4a0ad09b7f5667d92f4f12cd0881ec939de5d542903f", + "aarch64-unknown-linux-gnu": "ad9fc572c8e67cae305de627433e3cb6d459cbe94711921d5b673766b5a20c72", + "x86_64-apple-darwin": "998d4159933724eba107bbb0e01ed920d267d59c815b256fc39ffe8658df1350", + "aarch64-apple-darwin": "02d1a66b5fe8676e6df5084f4e0b71779a4e6f1c46f192d3d3a12b7eb3a789ec" + } } diff --git a/app/provision/runtimes.py b/app/provision/runtimes.py index f8777667..6017eaee 100644 --- a/app/provision/runtimes.py +++ b/app/provision/runtimes.py @@ -11,10 +11,11 @@ import os import platform +import re import subprocess import sys from pathlib import Path -from typing import Optional +from typing import Optional, Tuple from app.provision.types import Context, LogFn, StageResult, Status @@ -26,8 +27,12 @@ # # The native launcher embeds this same file. Keep download locations and # the compatible fallback release together so the two install paths agree. +# `sha256` pins each platform's archive of that release, as published in the +# release's SHA256SUMS. PBS_CONFIG_PATH = Path(__file__).with_name("python_downloads.json") +_SHA256_RE = re.compile(r"[0-9a-f]{64}") + # The version the locks are generated for. NOT a minimum: a lock is valid # for exactly one (platform, python) pair, so accepting "3.10 or newer" would # mean a user on 3.14 has no lock at all — which is precisely what happened on @@ -189,17 +194,19 @@ def _pbs_triple() -> Optional[str]: return f"{arch}-unknown-linux-gnu" -def _pbs_download_url(log: LogFn) -> Optional[str]: - """Resolve the download URL for a TARGET_PYTHON build, or None. +def _pbs_download(log: LogFn) -> Optional[Tuple[str, str]]: + """The pinned TARGET_PYTHON build for this machine: (url, sha256), or None. - Tries the newest release, then the configured compatible fallback release, - and picks the asset matching this machine's triple. `install_only` extracts to a - ready-to-run tree; the full builds carry object files and headers nobody - here needs. + Only the release python_downloads.json names, checked against the SHA-256 + it pins for this machine's triple, so the runtime every later stage + installs into is the one the repository was reviewed with. The newest + upstream release is never consulted: it may have dropped 3.10, and + nothing could vouch for it. Resolving needs no network either, so a + GitHub API rate limit or a slow index cannot fail an install. + `install_only` extracts to a ready-to-run tree; the full builds carry + object files and headers nobody here needs. """ import json - import ssl - import urllib.request triple = _pbs_triple() if not triple: @@ -207,55 +214,29 @@ def _pbs_download_url(log: LogFn) -> Optional[str]: try: config = json.loads(PBS_CONFIG_PATH.read_text(encoding="utf-8")) - api = f"{config['api_base'].rstrip('/')}/repos/{config['repository']}/releases" release = config["fallback_release"] version = config["fallback_version"] - compatible = version.startswith(f"{TARGET_PYTHON[0]}.{TARGET_PYTHON[1]}.") - archive = ( + platforms = config["fallback_platforms"] + digest = config["sha256"].get(triple, "") if triple in platforms else "" + url = ( f"{config['download_base'].rstrip('/')}/{config['repository']}" f"/releases/download/{release}/cpython-{version}%2B{release}" f"-{triple}-install_only.tar.gz" - if compatible and triple in config["fallback_platforms"] - else None ) except (OSError, ValueError, KeyError, TypeError, AttributeError) as error: log(f" invalid Python download configuration: {error}") return None - try: - import certifi - - ctx = ssl.create_default_context(cafile=certifi.where()) - except ImportError: - ctx = ssl.create_default_context() - - prefix = f"cpython-{TARGET_PYTHON[0]}.{TARGET_PYTHON[1]}." - suffix = f"-{triple}-install_only.tar.gz" - indexes = [f"{api}/latest"] - if compatible: - indexes.append(f"{api}/tags/{release}") - for index in indexes: - try: - req = urllib.request.Request(index, headers={"User-Agent": "CraftBot"}) - with urllib.request.urlopen(req, timeout=60, context=ctx) as response: - data = json.load(response) - except Exception as e: - log(f" could not reach the Python download index: {str(e)[:160]}") - # Shared/public IPs can exhaust GitHub's unauthenticated API quota. - # Release assets have a separate download endpoint. Keep the known - # compatible build available even when metadata cannot be queried. - if archive: - log(f" using the archived Python {version} release download") - return archive - return None - for asset in data.get("assets", []): - name = asset.get("name") or "" - if name.startswith(prefix) and name.endswith(suffix): - url = asset.get("browser_download_url") - if url: - return url - log(f" no {prefix}*{suffix} in release {data.get('tag_name')}") - return None + if not version.startswith(f"{TARGET_PYTHON[0]}.{TARGET_PYTHON[1]}."): + log( + f" the pinned Python {version} is not " + f"{TARGET_PYTHON[0]}.{TARGET_PYTHON[1]}; refusing to download it" + ) + return None + if not _SHA256_RE.fullmatch(str(digest)): + log(f" no pinned Python {version} build for {triple}") + return None + return url, digest class PythonStage: @@ -342,7 +323,6 @@ def apply(self, ctx: Context, log: LogFn) -> StageResult: if ctx.offline: return StageResult(Status.FAILED, "offline: cannot download Python") - import shutil as _shutil import tarfile from app import downloads @@ -351,40 +331,25 @@ def apply(self, ctx: Context, log: LogFn) -> StageResult: dest.mkdir(parents=True, exist_ok=True) archive = dest / "_download.tar.gz" - # Look in the cache BEFORE asking the network anything. Resolving the - # URL means fetching a large release index, which is itself a failure - # point on a slow link - and failing there while holding the very file - # we need would be perverse. - triple = _pbs_triple() - cached = ( - downloads.find_cached( - f"cpython-{TARGET_PYTHON[0]}.{TARGET_PYTHON[1]}.*-{triple}-install_only.tar.gz" + pinned = _pbs_download(log) + if not pinned: + return StageResult( + Status.FAILED, + f"no portable Python {TARGET_PYTHON[0]}.{TARGET_PYTHON[1]} " + f"available for {platform.machine()} on {sys.platform}", ) - if triple - else None - ) - - url = None - if not cached: - url = _pbs_download_url(log) - if not url: - return StageResult( - Status.FAILED, - f"no portable Python {TARGET_PYTHON[0]}.{TARGET_PYTHON[1]} " - f"available for {platform.machine()} on {sys.platform}", - ) + url, sha256 = pinned try: - if cached: - log(f" using cached {os.path.basename(cached)}") - _shutil.copyfile(cached, archive) - else: - downloads.download( - url, - str(archive), - log=log, - label=f"Python {TARGET_PYTHON[0]}.{TARGET_PYTHON[1]}", - ) + # A cached copy (CRAFTBOT_DOWNLOAD_CACHE) is used only when it + # matches the pin, and a download that doesn't is never extracted. + downloads.download( + url, + str(archive), + log=log, + label=f"Python {TARGET_PYTHON[0]}.{TARGET_PYTHON[1]}", + expected_sha256=sha256, + ) log(" extracting...") # tar preserves the executable bit, which a zip would not — that # matters on macOS/Linux where the extracted python must be +x. diff --git a/scripts/prefetch_runtimes.py b/scripts/prefetch_runtimes.py index 75438acb..013d7426 100644 --- a/scripts/prefetch_runtimes.py +++ b/scripts/prefetch_runtimes.py @@ -49,30 +49,32 @@ def _fetch_archives(out: Path) -> int: targets = [] - py_url = runtimes._pbs_download_url(print) - if py_url: - targets.append(("Python runtime", py_url)) + python = runtimes._pbs_download(print) + if python: + targets.append(("Python runtime", *python)) else: print("warning: could not resolve the Python runtime URL", file=sys.stderr) - node_url = node_runtime.latest_download_url(log=print) - if node_url: - targets.append(("Node.js", node_url)) + node = node_runtime.pinned_download(log=print) + if node: + targets.append(("Node.js", *node[1:])) else: print("warning: could not resolve the Node URL", file=sys.stderr) if sys.platform == "win32": - targets.append(("Visual C++ runtime", _vcredist_url())) + targets.append(("Visual C++ runtime", _vcredist_url(), None)) failures = 0 - for label, url in targets: + for label, url, sha256 in targets: dest = out / downloads.cache_name(url) - if dest.is_file(): + if downloads.verify_checksum(str(dest), sha256): print(f"\n{label}: cached already ({dest.stat().st_size / 1048576:.1f} MB)") continue print(f"\n{label}:") try: - downloads.download(url, str(dest), log=print, label=label) + downloads.download( + url, str(dest), log=print, label=label, expected_sha256=sha256 + ) except Exception as e: failures += 1 print(f" failed: {str(e)[:200]}", file=sys.stderr) diff --git a/scripts/test_install_e2e.py b/scripts/test_install_e2e.py index 2a96f8d3..1d270e91 100644 --- a/scripts/test_install_e2e.py +++ b/scripts/test_install_e2e.py @@ -133,6 +133,7 @@ def main() -> int: "installer/startup.py", "app/provision/__init__.py", "app/provision/python_downloads.json", + "app/provision/node_downloads.json", "app/provision/agent_app_framework.py", "app/vendor/agent-app/source.json", "app/vendor/agent-app/agent-app-framework.zip", diff --git a/tests/test_node_downloads.py b/tests/test_node_downloads.py new file mode 100644 index 00000000..1a17c5ba --- /dev/null +++ b/tests/test_node_downloads.py @@ -0,0 +1,99 @@ +"""The private Node comes only from the pinned release, checked against its SHA-256.""" + +import json +import re +import urllib.request + +import pytest + +from app import downloads, node_runtime + +DOWNLOADS = json.loads(node_runtime.NODE_CONFIG_PATH.read_text(encoding="utf-8")) +ARCHIVES = sorted(DOWNLOADS["sha256"]) + + +@pytest.fixture +def download_config(monkeypatch, tmp_path): + path = tmp_path / "node_downloads.json" + monkeypatch.setattr(node_runtime, "NODE_CONFIG_PATH", path) + return path + + +@pytest.fixture(autouse=True) +def configured_context_window(): + """Download selection needs no model configuration.""" + + +@pytest.fixture(autouse=True) +def no_network(monkeypatch): + """The version is pinned, so nodejs.org's index is never asked.""" + monkeypatch.setattr( + urllib.request, "urlopen", lambda *a, **kw: pytest.fail("network used") + ) + + +def _platform(monkeypatch, archive): + suffix, ext = archive.split(".", 1) + monkeypatch.setattr(node_runtime, "_platform_suffix", lambda: (suffix, ext)) + + +def test_the_pin_is_on_the_supported_major(): + assert node_runtime.major_of(DOWNLOADS["version"]) == node_runtime.MIN_NODE_MAJOR + + +@pytest.mark.parametrize("archive", ARCHIVES) +def test_every_platform_resolves_its_pinned_archive(monkeypatch, archive): + _platform(monkeypatch, archive) + version = DOWNLOADS["version"] + assert node_runtime.pinned_download() == ( + version, + f"{DOWNLOADS['download_base']}/{version}/node-{version}-{archive}", + DOWNLOADS["sha256"][archive], + ) + assert re.fullmatch(r"[0-9a-f]{64}", DOWNLOADS["sha256"][archive]) + + +def test_platform_without_a_pin_is_refused(monkeypatch, download_config): + archive = ARCHIVES[0] + pins = {k: v for k, v in DOWNLOADS["sha256"].items() if k != archive} + download_config.write_text(json.dumps(dict(DOWNLOADS, sha256=pins))) + _platform(monkeypatch, archive) + logs = [] + assert node_runtime.pinned_download(log=logs.append) is None + assert any("No pinned Node" in message for message in logs) + + +@pytest.mark.parametrize("version", ["v22.11.0", "24.22.3", "v24.22"]) +def test_configuration_cannot_supply_another_line( + monkeypatch, download_config, version +): + download_config.write_text(json.dumps(dict(DOWNLOADS, version=version))) + _platform(monkeypatch, ARCHIVES[0]) + assert node_runtime.pinned_download() is None + + +@pytest.mark.parametrize("contents", [None, "not JSON", "{}"]) +def test_missing_or_invalid_configuration_fails_clearly( + monkeypatch, download_config, contents +): + if contents is not None: + download_config.write_text(contents, encoding="utf-8") + logs = [] + assert node_runtime.pinned_download(log=logs.append) is None + assert "Invalid Node download configuration" in logs[0] + + +def test_the_sidecar_downloads_against_the_pin(monkeypatch, tmp_path): + archive = next(name for name in ARCHIVES if name.startswith("linux-")) + _platform(monkeypatch, archive) + monkeypatch.setattr(node_runtime, "SIDECAR_DIR", tmp_path) + calls = [] + + def download(url, dest, **kwargs): + calls.append((url, kwargs.get("expected_sha256"))) + raise ValueError("SHA-256 verification failed") + + monkeypatch.setattr(downloads, "download", download) + assert node_runtime.download_sidecar() is None + assert calls == [node_runtime.pinned_download()[1:]] + assert [path.name for path in tmp_path.iterdir()] == [] diff --git a/tests/test_python_downloads.py b/tests/test_python_downloads.py index 89582039..ef986be5 100644 --- a/tests/test_python_downloads.py +++ b/tests/test_python_downloads.py @@ -1,13 +1,14 @@ -"""A newer upstream release must not strand installs pinned to Python 3.10.""" +"""The private Python comes only from the pinned release, checked against its SHA-256.""" -import io import json +import re import urllib.request -import urllib.error import pytest +from app import downloads from app.provision import runtimes +from app.provision.types import Context, Status DOWNLOADS = json.loads(runtimes.PBS_CONFIG_PATH.read_text(encoding="utf-8")) PLATFORMS = DOWNLOADS["fallback_platforms"] @@ -25,127 +26,35 @@ def configured_context_window(): """Download selection needs no model configuration.""" -@pytest.mark.parametrize("triple", PLATFORMS) -def test_api_rate_limit_uses_known_release_asset(monkeypatch, triple): - monkeypatch.setattr(runtimes, "_pbs_triple", lambda: triple) - - def rate_limited(request, **kwargs): - raise urllib.error.HTTPError( - request.full_url, 403, "rate limit exceeded", {}, None - ) - - monkeypatch.setattr(urllib.request, "urlopen", rate_limited) - assert runtimes._pbs_download_url(lambda message: None) == ( - f"{DOWNLOADS['download_base']}/{DOWNLOADS['repository']}/releases/download/" - f"{DOWNLOADS['fallback_release']}/cpython-{DOWNLOADS['fallback_version']}" - f"%2B{DOWNLOADS['fallback_release']}-{triple}-install_only.tar.gz" - ) - - -def test_unavailable_index_never_falls_back_to_wrong_python_version(monkeypatch): - monkeypatch.setattr(runtimes, "TARGET_PYTHON", (3, 11)) - monkeypatch.setattr(runtimes, "_pbs_triple", lambda: "x86_64-unknown-linux-gnu") +@pytest.fixture(autouse=True) +def no_network(monkeypatch): + """Resolving the pinned build never asks GitHub anything, so a rate limit + or an unreachable index cannot fail an install.""" monkeypatch.setattr( - urllib.request, - "urlopen", - lambda *a, **kw: (_ for _ in ()).throw(OSError("offline")), + urllib.request, "urlopen", lambda *a, **kw: pytest.fail("network used") ) - assert runtimes._pbs_download_url(lambda message: None) is None @pytest.mark.parametrize("triple", PLATFORMS) -def test_retired_python_uses_last_supported_release(monkeypatch, triple): +def test_every_platform_resolves_its_pinned_archive(monkeypatch, triple): monkeypatch.setattr(runtimes, "_pbs_triple", lambda: triple) - requests = [] - api = f"{DOWNLOADS['api_base']}/repos/{DOWNLOADS['repository']}/releases" - - def fetch(request, **kwargs): - requests.append(request.full_url) - assets = ( - [] - if request.full_url == f"{api}/latest" - else [ - { - "name": ( - f"cpython-{DOWNLOADS['fallback_version']}" - f"+{DOWNLOADS['fallback_release']}-{triple}-install_only.tar.gz" - ), - "browser_download_url": "https://example.test/compatible-python.tar.gz", - } - ] - ) - return io.BytesIO(json.dumps({"assets": assets}).encode()) - - monkeypatch.setattr(urllib.request, "urlopen", fetch) - assert ( - runtimes._pbs_download_url(lambda message: None) - == "https://example.test/compatible-python.tar.gz" - ) - assert requests == [f"{api}/latest", f"{api}/tags/{DOWNLOADS['fallback_release']}"] - - -def test_latest_matching_asset_takes_priority(monkeypatch): - monkeypatch.setattr(runtimes, "_pbs_triple", lambda: "x86_64-unknown-linux-gnu") - requests = [] - - def fetch(request, **kwargs): - requests.append(request.full_url) - return io.BytesIO( - json.dumps( - { - "assets": [ - { - "name": "cpython-3.10.99+test-x86_64-unknown-linux-gnu-install_only.tar.gz", - "browser_download_url": "https://example.test/newer-python.tar.gz", - } - ] - } - ).encode() - ) - - monkeypatch.setattr(urllib.request, "urlopen", fetch) - assert runtimes._pbs_download_url(lambda message: None) == ( - "https://example.test/newer-python.tar.gz" + release, version = DOWNLOADS["fallback_release"], DOWNLOADS["fallback_version"] + assert runtimes._pbs_download(lambda message: None) == ( + f"{DOWNLOADS['download_base']}/{DOWNLOADS['repository']}/releases/download/" + f"{release}/cpython-{version}%2B{release}-{triple}-install_only.tar.gz", + DOWNLOADS["sha256"][triple], ) - assert len(requests) == 1 + assert re.fullmatch(r"[0-9a-f]{64}", DOWNLOADS["sha256"][triple]) -@pytest.mark.parametrize("fail_on", [1, 2]) -def test_configuration_controls_indexes_archive_and_log( - monkeypatch, download_config, fail_on -): - config = dict( - DOWNLOADS, - api_base="https://api.example.test/", - download_base="https://downloads.example.test/", - repository="maintainer/python", - fallback_release="20990101", - fallback_version="3.10.99", - fallback_platforms=["test-platform"], - ) - download_config.write_text(json.dumps(config), encoding="utf-8") - monkeypatch.setattr(runtimes, "_pbs_triple", lambda: "test-platform") - requests, logs = [], [] - - def fetch(request, **kwargs): - requests.append(request.full_url) - if len(requests) == fail_on: - raise OSError("index unavailable") - return io.BytesIO(b'{"assets": []}') - - monkeypatch.setattr(urllib.request, "urlopen", fetch) - assert runtimes._pbs_download_url(logs.append) == ( - "https://downloads.example.test/maintainer/python/releases/download/20990101/" - "cpython-3.10.99%2B20990101-test-platform-install_only.tar.gz" - ) - assert ( - requests - == [ - "https://api.example.test/repos/maintainer/python/releases/latest", - "https://api.example.test/repos/maintainer/python/releases/tags/20990101", - ][:fail_on] - ) - assert any("archived Python 3.10.99" in message for message in logs) +def test_platform_without_a_pin_is_refused(monkeypatch, download_config): + triple = PLATFORMS[0] + pins = {k: v for k, v in DOWNLOADS["sha256"].items() if k != triple} + download_config.write_text(json.dumps(dict(DOWNLOADS, sha256=pins))) + monkeypatch.setattr(runtimes, "_pbs_triple", lambda: triple) + logs = [] + assert runtimes._pbs_download(logs.append) is None + assert any("no pinned Python" in message for message in logs) @pytest.mark.parametrize( @@ -157,12 +66,7 @@ def test_configuration_cannot_supply_wrong_version_or_platform( ): download_config.write_text(json.dumps(dict(DOWNLOADS, fallback_version=version))) monkeypatch.setattr(runtimes, "_pbs_triple", lambda: triple) - monkeypatch.setattr( - urllib.request, - "urlopen", - lambda *a, **kw: (_ for _ in ()).throw(OSError("offline")), - ) - assert runtimes._pbs_download_url(lambda message: None) is None + assert runtimes._pbs_download(lambda message: None) is None @pytest.mark.parametrize("contents", [None, "not JSON", "{}"]) @@ -171,27 +75,24 @@ def test_missing_or_invalid_configuration_fails_clearly( ): if contents is not None: download_config.write_text(contents, encoding="utf-8") - monkeypatch.setattr( - urllib.request, "urlopen", lambda *a, **kw: pytest.fail("network used") - ) logs = [] - assert runtimes._pbs_download_url(logs.append) is None + assert runtimes._pbs_download(logs.append) is None assert "invalid Python download configuration" in logs[0] -def test_missing_matching_python_does_not_select_a_different_version(monkeypatch): - data = { - "assets": [ - { - "name": "cpython-3.11.0+20261110-x86_64-unknown-linux-gnu-install_only.tar.gz", - "browser_download_url": "https://example.test/wrong-python.tar.gz", - } - ] - } - monkeypatch.setattr(runtimes, "_pbs_triple", lambda: "x86_64-unknown-linux-gnu") - monkeypatch.setattr( - urllib.request, - "urlopen", - lambda *a, **kw: io.BytesIO(json.dumps(data).encode()), - ) - assert runtimes._pbs_download_url(lambda message: None) is None +def test_the_stage_downloads_against_the_pin(monkeypatch, tmp_path): + triple = PLATFORMS[0] + monkeypatch.setattr(runtimes, "_pbs_triple", lambda: triple) + calls = [] + + def download(url, dest, **kwargs): + calls.append((url, kwargs.get("expected_sha256"))) + raise ValueError("SHA-256 verification failed") + + monkeypatch.setattr(downloads, "download", download) + ctx = Context(code_root=str(tmp_path), state_root=str(tmp_path)) + result = runtimes.PythonStage().apply(ctx, lambda message: None) + + assert result.status == Status.FAILED + assert calls == [runtimes._pbs_download(lambda message: None)] + assert not (tmp_path / "runtime" / "python" / "python").exists() From 95f4899fd41779c7d085a43b5aaffd0d3f42d26a Mon Sep 17 00:00:00 2001 From: zfoong Date: Sat, 21 Nov 2026 09:43:46 +0900 Subject: [PATCH 2/9] feat: let the terminal client open a new chat with --message A launcher that starts CraftBot with a prompt (Omarchy's agent key and its starter prompts) needs the terminal edition to take one. --message opens a new chat with it once the agent can answer: after the backend's first init and, when the agent still needs onboarding, after onboarding, so it never reaches an agent with no model yet. Co-Authored-By: Claude Opus 5.5 Signed-off-by: zfoong --- app/ui_layer/terminal/src/config.ts | 4 ++ app/ui_layer/terminal/src/main.tsx | 2 +- app/ui_layer/terminal/src/runtime/runtime.tsx | 21 ++++++++++- .../terminal/src/runtime/startupMessage.ts | 17 +++++++++ .../terminal/test/unit/startupMessage.test.ts | 37 +++++++++++++++++++ 5 files changed, 79 insertions(+), 2 deletions(-) create mode 100644 app/ui_layer/terminal/src/runtime/startupMessage.ts create mode 100644 app/ui_layer/terminal/test/unit/startupMessage.test.ts diff --git a/app/ui_layer/terminal/src/config.ts b/app/ui_layer/terminal/src/config.ts index 3716ee6c..a7d314f8 100644 --- a/app/ui_layer/terminal/src/config.ts +++ b/app/ui_layer/terminal/src/config.ts @@ -6,6 +6,7 @@ * --state-dir DIR CraftBot's state directory (remembered UI state lives here) * --log FILE the backend's log file, shown when it fails to start * --plain numbered menus and labeled lines, never the alternate screen + * --message TEXT start a new chat with this message once the agent is ready */ import { homedir } from 'node:os' import { join } from 'node:path' @@ -16,6 +17,8 @@ export interface ClientConfig { stateDir: string logFile: string | null plain: boolean + /** A prompt to open a new chat with (see runtime/startupMessage). */ + message: string | null } function valueOf(argv: string[], flag: string): string | undefined { @@ -40,6 +43,7 @@ export function parseConfig(argv: string[], env: NodeJS.ProcessEnv): ClientConfi stateDir: valueOf(argv, '--state-dir') ?? env.CRAFTBOT_HOME ?? join(homedir(), '.craftbot'), logFile: valueOf(argv, '--log') ?? null, plain, + message: valueOf(argv, '--message')?.trim() || null, } } diff --git a/app/ui_layer/terminal/src/main.tsx b/app/ui_layer/terminal/src/main.tsx index cce3330b..282abe3f 100644 --- a/app/ui_layer/terminal/src/main.tsx +++ b/app/ui_layer/terminal/src/main.tsx @@ -1,7 +1,7 @@ /** * CraftBot terminal edition: entry point. * - * node dist/craftbot-tui.mjs --port 7926 [--owner] [--state-dir DIR] [--log FILE] [--plain] + * node dist/craftbot-tui.mjs --port 7926 [--owner] [--state-dir DIR] [--log FILE] [--plain] [--message TEXT] * * `./boot` must stay the first import: it parses the command line, sends * console output to a log file and installs the browser globals that the diff --git a/app/ui_layer/terminal/src/runtime/runtime.tsx b/app/ui_layer/terminal/src/runtime/runtime.tsx index 075cdcf2..d570d449 100644 --- a/app/ui_layer/terminal/src/runtime/runtime.tsx +++ b/app/ui_layer/terminal/src/runtime/runtime.tsx @@ -23,8 +23,10 @@ import { closeAllScreens, linkSubagent, openScreen, pushToast, setHello } from ' import { persistentStorage } from '../platform/globals' import { notify, setBusyProgress, setTitle, terminalCaps } from '../caps/terminal' import { sessionTitle } from '../chat/transcriptWriter' -import { isQuitting } from './actions' +import { isQuitting, startNewChat } from './actions' import { Splash } from './Splash' +import { startupMessageReady } from './startupMessage' +import { sendChat } from '../chat/intents' /** Extra frames this client reads beyond the browser's (backend client_hello). */ const CAPABILITIES = ['subagent_link'] @@ -92,6 +94,20 @@ function sync(): void { export async function startClient(): Promise { const client = getSocketClient() + // A prompt from the command line opens a new chat, once, as soon as the + // agent can take it (see startupMessage.ts). + let initSeen = false + let startupMessage = config().message + const sendStartupMessage = () => { + if (!startupMessage || !startupMessageReady(store.getState(), initSeen)) return + const message = startupMessage + startupMessage = null + startNewChat() + sendChat(message, 'new').catch(err => { + store.dispatch(pushToast(i18n.t('tui:composer.sendFailed', { error: String((err as Error)?.message ?? err) }), 'error')) + }) + } + // Say hello on every (re)connect: what this client is and what it reads. client.onOpen(() => { client.send('client_hello', { client: 'terminal', protocol: CLIENT_PROTOCOL, capabilities: CAPABILITIES }) @@ -121,6 +137,8 @@ export async function startClient(): Promise { store.dispatch(openScreen({ id: 'onboarding' })) } client.send('settings_get', {}) + initSeen = true + sendStartupMessage() break } case 'settings_get': @@ -142,6 +160,7 @@ export async function startClient(): Promise { let seen: { messages: unknown; runs: unknown; active: string } | null = null store.subscribe(() => { sync() + sendStartupMessage() const state = store.getState() const active = state.tui.activeSessionId if (seen && seen.messages === state.messages && seen.runs === state.agent.runStateBySession && seen.active === active) return diff --git a/app/ui_layer/terminal/src/runtime/startupMessage.ts b/app/ui_layer/terminal/src/runtime/startupMessage.ts new file mode 100644 index 00000000..a29bfd6e --- /dev/null +++ b/app/ui_layer/terminal/src/runtime/startupMessage.ts @@ -0,0 +1,17 @@ +/** + * A prompt given on the command line (`--message`), as a launcher such as + * Omarchy's agent key passes one: it opens a new chat as if it had been typed + * there, once the agent can take it. That is after the backend's first `init` + * and, when the agent still needs onboarding, after onboarding, so a prompt + * never reaches an agent that has no model yet. + */ +import type { RootState } from '../state/store' + +/** Whether the agent can take the startup message now. */ +export function startupMessageReady(state: RootState, initSeen: boolean): boolean { + return initSeen + && state.connection.connected + && state.tui.hello !== null + && !state.onboarding.needsHardOnboarding + && !state.tui.screens.some(screen => screen.id === 'onboarding') +} diff --git a/app/ui_layer/terminal/test/unit/startupMessage.test.ts b/app/ui_layer/terminal/test/unit/startupMessage.test.ts new file mode 100644 index 00000000..b406838b --- /dev/null +++ b/app/ui_layer/terminal/test/unit/startupMessage.test.ts @@ -0,0 +1,37 @@ +import { describe, expect, it } from 'vitest' +import { parseConfig } from '../../src/config' +import { startupMessageReady } from '../../src/runtime/startupMessage' +import type { RootState } from '../../src/state/store' + +function state(over: { connected?: boolean; hello?: boolean; needsHardOnboarding?: boolean; screens?: string[] } = {}): RootState { + return { + connection: { connected: over.connected ?? true }, + tui: { + hello: over.hello === false ? null : { protocol: 1, edition: 'terminal', version: '1.4.6' }, + screens: (over.screens ?? []).map(id => ({ id })), + }, + onboarding: { needsHardOnboarding: over.needsHardOnboarding ?? false }, + } as unknown as RootState +} + +describe('--message', () => { + it('is read in both spellings, trimmed, and empty means none', () => { + expect(parseConfig(['--message', ' make a theme '], {}).message).toBe('make a theme') + expect(parseConfig(['--message=--starts with a dash'], {}).message).toBe('--starts with a dash') + expect(parseConfig(['--message', ' '], {}).message).toBeNull() + expect(parseConfig([], {}).message).toBeNull() + }) + + it('waits for the backend to greet the client and send its init', () => { + expect(startupMessageReady(state(), false)).toBe(false) + expect(startupMessageReady(state({ hello: false }), true)).toBe(false) + expect(startupMessageReady(state({ connected: false }), true)).toBe(false) + expect(startupMessageReady(state(), true)).toBe(true) + }) + + it('never reaches an agent that still needs onboarding', () => { + expect(startupMessageReady(state({ needsHardOnboarding: true }), true)).toBe(false) + expect(startupMessageReady(state({ screens: ['onboarding'] }), true)).toBe(false) + expect(startupMessageReady(state({ screens: ['settings'] }), true)).toBe(true) + }) +}) From 2745e98dda6dce638db78dcbeadde13c862b9c5c Mon Sep 17 00:00:00 2001 From: zfoong Date: Sat, 21 Nov 2026 09:43:46 +0900 Subject: [PATCH 3/9] feat: give launchers a craftbot command, status --json and install --no-start What a desktop launcher such as Omarchy needs to run CraftBot: - install writes ~/.local/bin/craftbot on Linux and macOS, which runs this install's craftbot.py with its state root; uninstall removes it, and a file there CraftBot did not write is left alone. - status --json says whether CraftBot runs and is ready, where it answers, its version and roots, so a launcher opens the UI only once it serves. - install --no-start registers startup without starting the detached process, so a caller can run CraftBot through its systemd unit. - tui --message passes a starting message to the terminal client. Co-Authored-By: Claude Opus 5.5 Signed-off-by: zfoong --- craftbot.py | 177 +++++++++++++++++++++++++++++++-- tests/test_craftbot_service.py | 135 +++++++++++++++++++++++++ 2 files changed, 306 insertions(+), 6 deletions(-) diff --git a/craftbot.py b/craftbot.py index edb381a1..fdec6654 100644 --- a/craftbot.py +++ b/craftbot.py @@ -11,11 +11,13 @@ first if it is not running (desktop icon) python craftbot.py stop Stop CraftBot python craftbot.py restart [options] Stop then start - python craftbot.py status Show if CraftBot is running + python craftbot.py status [--json] Show if CraftBot is running (--json: as JSON, + for launchers and scripts) python craftbot.py logs [-n N] Show last N log lines (default: 50) python craftbot.py tui [options] Open the terminal edition in this console, starting CraftBot in the background first - if it is not running + if it is not running; --message TEXT opens + a new chat with that message python craftbot.py install [options] Register for auto-start on boot/login python craftbot.py autostart enable Enable automatic startup at login python craftbot.py autostart disable Disable automatic startup (keep installed) @@ -38,6 +40,8 @@ --conda Use conda environment --no-conda Don't use conda --no-autostart Install without automatic startup at login + --no-start Install without starting CraftBot now (a caller such + as systemd starts it) 'start' waits until CraftBot answers (or prints why it stopped). @@ -72,7 +76,7 @@ import subprocess import time import webbrowser -from typing import Callable, List, Optional +from typing import Callable, List, Optional, Tuple from installer import helpers as _helpers from installer import metadata as _metadata @@ -874,6 +878,23 @@ def cmd_start(extra_args: List[str]) -> bool: return True +def _take_value(args: List[str], flag: str) -> Tuple[Optional[str], List[str]]: + """The value given for `flag` (as `flag VALUE` or `flag=VALUE`) and the + arguments without it. The separate form takes the next argument whatever + it is, so a message that starts with a dash stays a message.""" + value: Optional[str] = None + rest: List[str] = [] + it = iter(args) + for arg in it: + if arg == flag: + value = next(it, None) + elif arg.startswith(f"{flag}="): + value = arg.split("=", 1)[1] + else: + rest.append(arg) + return value, rest + + def cmd_tui(extra_args: List[str]) -> int: """Open the terminal edition in this console. @@ -882,9 +903,15 @@ def cmd_tui(extra_args: List[str]) -> int: terminal edition in the background first. Quitting the client leaves the service running, so scheduled and proactive work goes on; `craftbot.py stop` stops it. + + `--message TEXT` opens a new chat with that message once the agent is + ready (after onboarding, if it still needs it), as a launcher passes one. """ from app import edition, node_runtime + message, extra_args = _take_value(extra_args, "--message") + message_args = ["--message", message] if message and message.strip() else [] + ui = _instance.read_ui() if ui is None or not _instance.http_answers(str(ui["url"])): if _owned_pid() is not None and _wait_for_running( @@ -925,6 +952,7 @@ def cmd_tui(extra_args: List[str]) -> int: str(paths.STATE_ROOT), "--log", LOG_FILE, + *message_args, ], env=node_runtime.child_env(), ).returncode @@ -1163,8 +1191,40 @@ def _kill_owned_pid(pid: int) -> None: print(f"Warning: {e}") -def cmd_status() -> None: +def _status_record() -> dict: + """What `status --json` prints, for launchers and scripts. + + `ready` is the same signal `start` waits for: run.py writes ui.json once + the agent has booted and the backend answers, so a launcher can open + `url` the moment it is true. ui.json is read only while this install's + process runs, since a crash leaves the last one behind. In the terminal + edition `url` is the backend, which points a browser to `tui`. + """ + pid = _owned_pid() + ui = _instance.read_ui() if pid else None + return { + "running": pid is not None, + "pid": pid, + "ready": ui is not None, + "url": str(ui["url"]) if ui else None, + "edition": ui.get("edition") if ui else None, + "frontend_port": ui.get("frontend_port") if ui else None, + "backend_port": ui.get("backend_port") if ui else None, + "autostart": _is_installed(), + "version": _read_bundled_version(), + "code_root": str(paths.CODE_ROOT), + "state_root": str(paths.STATE_ROOT.resolve()), + "log_file": LOG_FILE, + } + + +def cmd_status(args: Optional[List[str]] = None) -> None: """Print whether CraftBot is currently running and whether auto-start is installed.""" + if args and "--json" in args: + import json + + print(json.dumps(_status_record())) + return W = max(50, len(LOG_FILE) + 12) pid = _owned_pid() print(f"\n{ORANGE}╔{'═' * W}╗{RESET}") @@ -2330,7 +2390,15 @@ def _install_failed(message: str, hint: Optional[str] = None) -> bool: def cmd_install(extra_args: List[str]) -> bool: """Install dependencies (source mode) or copy-and-register (frozen mode), - then start the service.""" + then start the service. + + --no-start leaves starting to the caller: a launcher that runs CraftBot + through its systemd unit, rather than as the detached process `start` + makes, starts the unit itself once install returns. (On macOS, loading + the launchd agent starts it all the same.) + """ + no_start = "--no-start" in extra_args + extra_args = [arg for arg in extra_args if arg != "--no-start"] if "--cli" in extra_args: print(f" {RED}✗{RESET} {WHITE}{_CLI_RETIRED}{RESET}") return False @@ -2415,10 +2483,20 @@ def cmd_install(extra_args: List[str]) -> bool: "Packages installed but not importable. Wrong interpreter?", "Run 'python install.py' to reinstall with this Python.", ) + _install_command() print() else: print(f" {DIM}(install.py not found, skipping dependency install){RESET}\n") + if no_start: + _retro_step(2, 2, "Updating automatic startup") + if not _configure_autostart(auto_start, extra_args): + _hold_console_on_failure() + return False + print(f"\n {GREEN}▸{RESET} {WHITE}CRAFTBOT IS INSTALLED{RESET}") + print(f" {DIM}Start it with: python craftbot.py start{RESET}") + return True + # ── Step 2: Start the service now ────────────────────────────────────── # # Starting BEFORE registering auto-start, not after. The macOS plist @@ -2459,6 +2537,92 @@ def cmd_install(extra_args: List[str]) -> bool: return True +#: Written into the `craftbot` command, so `install` can tell its own from one +#: the user put there and `uninstall` removes only what install wrote. +_COMMAND_MARKER = "# The craftbot command, written by `craftbot.py install`." + + +def _command_path() -> Optional[str]: + """Where `install` puts the `craftbot` command: ~/.local/bin on Linux and + macOS. None on Windows and in the frozen installer EXE.""" + if IS_FROZEN or _PLATFORM == "win32": + return None + return os.path.join(os.path.expanduser("~"), ".local", "bin", "craftbot") + + +def _command_target() -> str: + """The line the command runs: this install's interpreter and craftbot.py, + naming its state root, as the desktop icon does (a shell does not carry + CRAFTBOT_HOME).""" + return " ".join( + shlex.quote(part) + for part in [ + _installed_python(), + os.path.abspath(__file__), + f"--state-root={paths.STATE_ROOT.resolve()}", + ] + ) + + +def _command_text(path: str) -> Optional[str]: + """The command at `path` if CraftBot wrote it, else None. A link, or a + file without the marker, is someone else's.""" + try: + if os.path.islink(path) or not os.path.isfile(path): + return None + with open(path, "r", encoding="utf-8", errors="replace") as f: + text = f.read(4096) + except OSError: + return None + return text if _COMMAND_MARKER in text else None + + +def _install_command() -> None: + """Put a `craftbot` command on PATH that runs this install's craftbot.py, + so `craftbot status` or `craftbot tui` reach it from any shell and a + launcher has a command to run. Rewritten on every install, so it follows + the interpreter; anything at the path CraftBot did not write stays.""" + path = _command_path() + if not path: + return + if os.path.lexists(path) and _command_text(path) is None: + print(f" {DIM}Left {path} alone: CraftBot did not write it.{RESET}") + return + content = f'#!/bin/sh\n{_COMMAND_MARKER}\nexec {_command_target()} "$@"\n' + temporary = f"{path}.{os.getpid()}.tmp" + try: + os.makedirs(os.path.dirname(path), exist_ok=True) + with open(temporary, "w", encoding="utf-8") as f: + f.write(content) + os.chmod(temporary, 0o755) + os.replace(temporary, path) + except OSError as e: + print(f" {DIM}Could not write the craftbot command at {path}: {e}{RESET}") + return + finally: + if os.path.exists(temporary): + os.remove(temporary) + print(f" {DIM}Command: {path}{RESET}") + if os.path.dirname(path) not in os.environ.get("PATH", "").split(os.pathsep): + print( + f" {DIM}Add {os.path.dirname(path)} to PATH to run it as `craftbot`.{RESET}" + ) + + +def _remove_command() -> None: + """Remove the `craftbot` command if this install wrote it. One that runs + another install (a second checkout, another CRAFTBOT_HOME) stays.""" + path = _command_path() + text = _command_text(path) if path else None + if text is None or _command_target() not in text: + return + try: + os.remove(path) + print(f"Command removed: {path}") + except OSError as e: + print(f"Warning: Could not remove {path} — {e}") + + def _remove_desktop_shortcut() -> None: """Remove the CraftBot desktop shortcut if it exists.""" desktop = _find_desktop() @@ -2493,6 +2657,7 @@ def cmd_uninstall() -> None: # Remove desktop shortcut _remove_desktop_shortcut() + _remove_command() if IS_FROZEN: # Frozen mode: remove the install dir and everything in the user data @@ -2803,7 +2968,7 @@ def main() -> None: sys.exit(cmd_tui(rest)) elif command == "status": - cmd_status() + cmd_status(rest) elif command == "logs": n = 50 diff --git a/tests/test_craftbot_service.py b/tests/test_craftbot_service.py index 052f3a07..2d1a67d6 100644 --- a/tests/test_craftbot_service.py +++ b/tests/test_craftbot_service.py @@ -649,3 +649,138 @@ def test_start_without_browser_still_checks_the_announced_url( assert probed == ["http://localhost:7925"] assert opened == [] assert "Waiting for the browser interface" in output + + +# ─── Launcher interface: status --json, tui --message, install --no-start ── + + +def test_status_json_says_where_a_ready_craftbot_answers(monkeypatch, capsys): + craftbot._instance.write_ui(7925, 7926) + monkeypatch.setattr(craftbot, "_owned_pid", lambda: 4242) + monkeypatch.setattr(craftbot, "_is_installed", lambda: True) + + craftbot.cmd_status(["--json"]) + + record = json.loads(capsys.readouterr().out) + assert record["running"] is True and record["ready"] is True + assert record["pid"] == 4242 and record["autostart"] is True + assert record["url"] == craftbot._instance.read_ui()["url"] + assert (record["frontend_port"], record["backend_port"]) == (7925, 7926) + assert record["edition"] == "browser" + assert record["state_root"] == str(craftbot.paths.STATE_ROOT.resolve()) + + +def test_status_json_never_offers_a_crashed_runs_address(monkeypatch, capsys): + craftbot._instance.write_ui(7925, 7926) + monkeypatch.setattr(craftbot, "_owned_pid", lambda: None) + monkeypatch.setattr(craftbot, "_is_installed", lambda: False) + + craftbot.cmd_status(["--json"]) + + record = json.loads(capsys.readouterr().out) + assert record["running"] is False and record["ready"] is False + assert record["url"] is None + + +@pytest.mark.parametrize( + "args", [["--message", "-make a theme"], ["--message=-make a theme"]] +) +def test_tui_hands_its_message_to_the_client(tmp_path, monkeypatch, args): + from app import edition, node_runtime + + craftbot._instance.write_ui(7925, 7926) + monkeypatch.setattr(craftbot._instance, "http_answers", lambda url: True) + bundle = tmp_path / "craftbot-tui.mjs" + bundle.write_text("") + monkeypatch.setattr(edition, "terminal_client_bundle", lambda: bundle) + monkeypatch.setattr(node_runtime, "node_cmd", lambda: "node") + monkeypatch.setattr(node_runtime, "child_env", lambda extra=None: {}) + monkeypatch.setattr(craftbot, "cmd_start", lambda args: pytest.fail("started")) + runs = [] + monkeypatch.setattr( + craftbot.subprocess, + "run", + lambda cmd, **kwargs: runs.append(cmd) or SimpleNamespace(returncode=0), + ) + + assert craftbot.cmd_tui(args) == 0 + assert runs[0][:2] == ["node", str(bundle)] + assert runs[0][-2:] == ["--message", "-make a theme"] + + +def test_install_without_start_registers_startup_and_starts_nothing( + tmp_path, monkeypatch, capsys +): + monkeypatch.setattr(craftbot, "IS_FROZEN", False) + monkeypatch.setattr(craftbot, "BASE_DIR", str(tmp_path)) + monkeypatch.setattr(craftbot, "cmd_start", lambda args: pytest.fail("started")) + registered = [] + monkeypatch.setattr( + craftbot, + "_configure_autostart", + lambda enabled, args: registered.append((enabled, list(args))) or True, + ) + + assert craftbot.cmd_install(["--no-start", "--no-open-browser"]) is True + # The flag is install's own: run.py never sees it in the unit it registers. + assert registered == [(True, ["--no-open-browser"])] + assert "CRAFTBOT IS INSTALLED" in capsys.readouterr().out + + +# ─── The craftbot command ────────────────────────────────────────────────── + + +@pytest.fixture +def command_home(tmp_path, monkeypatch): + """A home of its own, and an interpreter that prints what it was given.""" + home = tmp_path / "home" + monkeypatch.setenv("HOME", str(home)) + monkeypatch.setattr(craftbot, "IS_FROZEN", False) + monkeypatch.setattr(craftbot, "_PLATFORM", "linux") + python = tmp_path / "py thon" + python.write_text('#!/bin/sh\nprintf "%s\\n" "$@"\n') + python.chmod(0o755) + monkeypatch.setattr(craftbot, "_installed_python", lambda: str(python)) + return home / ".local" / "bin" / "craftbot" + + +@pytest.mark.skipif(sys.platform == "win32", reason="the command is for unix shells") +def test_install_puts_a_command_on_path_that_runs_this_install(command_home): + craftbot._install_command() + + out = subprocess.run( + [str(command_home), "tui", "--message", "a b"], + capture_output=True, + text=True, + check=True, + ).stdout.splitlines() + assert out == [ + str(Path(craftbot.__file__).resolve()), + f"--state-root={craftbot.paths.STATE_ROOT.resolve()}", + "tui", + "--message", + "a b", + ] + + +def test_a_command_craftbot_did_not_write_is_left_alone(command_home): + command_home.parent.mkdir(parents=True) + command_home.write_text("#!/bin/sh\necho mine\n") + + craftbot._install_command() + craftbot._remove_command() + + assert command_home.read_text() == "#!/bin/sh\necho mine\n" + + +def test_uninstall_removes_only_the_command_for_this_install( + tmp_path, monkeypatch, command_home +): + craftbot._install_command() + monkeypatch.setattr(craftbot.paths, "STATE_ROOT", tmp_path / "another install") + craftbot._remove_command() + assert command_home.exists() + + monkeypatch.setattr(craftbot.paths, "STATE_ROOT", tmp_path) + craftbot._remove_command() + assert not command_home.exists() From 50265ef388e22a833721ce8fac73fec70b7c56e1 Mon Sep 17 00:00:00 2001 From: zfoong Date: Sat, 21 Nov 2026 09:58:41 +0900 Subject: [PATCH 4/9] feat: add a monochrome mark for icon fonts A single-path, one-colour CraftBot mark: the mascot's silhouette from mascotPaths.ts as CraftBotMascot.tsx draws it, with the eyes cut out. Icon fonts that recolour a glyph with the theme (Omarchy's menu font) need exactly this shape, which the multi-colour logos cannot give. Co-Authored-By: Claude Opus 5.5 Signed-off-by: zfoong --- assets/craftbot-mark.svg | 1 + 1 file changed, 1 insertion(+) create mode 100644 assets/craftbot-mark.svg diff --git a/assets/craftbot-mark.svg b/assets/craftbot-mark.svg new file mode 100644 index 00000000..1361a059 --- /dev/null +++ b/assets/craftbot-mark.svg @@ -0,0 +1 @@ + From 08583513f06eb0166114306c40a25b18b7c8afd6 Mon Sep 17 00:00:00 2001 From: zfoong Date: Sat, 21 Nov 2026 10:02:41 +0900 Subject: [PATCH 5/9] fix: pass over a PATH node whose npm it cannot run On Arch, the nodejs package ships node without npm, so the npm on PATH can belong to another install, such as a version manager's. resolve() took that pair because both were found, but npm_command cannot run one with the other, so the Node stage downloaded the sidecar and then resolved the same unusable pair again: setup never finished. A PATH node is now taken only with an npm it can run; otherwise the sidecar is used. Co-Authored-By: Claude Opus 5.5 Signed-off-by: zfoong --- app/node_runtime.py | 12 +++++++++-- tests/test_node_downloads.py | 42 ++++++++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+), 2 deletions(-) diff --git a/app/node_runtime.py b/app/node_runtime.py index 1f929005..1c99d902 100644 --- a/app/node_runtime.py +++ b/app/node_runtime.py @@ -206,14 +206,22 @@ def resolve(refresh: bool = False) -> Optional[NodeRuntime]: and path_major is not None and path_major >= MIN_NODE_MAJOR ): - _cached = NodeRuntime( + candidate = NodeRuntime( node=path_node, npm=path_npm, bin_dir=os.path.dirname(path_node), version=path_version, source="path", ) - return _cached + # Only an npm this node can run counts. Arch's nodejs ships node + # without npm, so the npm on PATH can be another install's (a version + # manager's), which npm_command cannot pair with it. Taking that pair + # left `install` downloading the sidecar and then resolving the same + # unusable pair again, so setup never finished; the sidecar is used + # instead. + if npm_command(candidate): + _cached = candidate + return _cached discovered = discover_node() if discovered: diff --git a/tests/test_node_downloads.py b/tests/test_node_downloads.py index 1a17c5ba..4dc5227d 100644 --- a/tests/test_node_downloads.py +++ b/tests/test_node_downloads.py @@ -2,6 +2,7 @@ import json import re +import sys import urllib.request import pytest @@ -97,3 +98,44 @@ def download(url, dest, **kwargs): assert node_runtime.download_sidecar() is None assert calls == [node_runtime.pinned_download()[1:]] assert [path.name for path in tmp_path.iterdir()] == [] + + +def _node(path, version): + """A node binary that reports `version`, as probe_version asks it.""" + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(f"#!/bin/sh\necho {version}\n") + path.chmod(0o755) + return path + + +@pytest.mark.skipif(sys.platform == "win32", reason="unix node layout") +def test_a_path_node_whose_npm_it_cannot_run_gives_way_to_the_sidecar( + monkeypatch, tmp_path +): + # Arch's nodejs: node on PATH with no npm beside it, and another install's + # npm (a version manager's) found on PATH instead. + path_node = _node(tmp_path / "usr" / "bin" / "node", "v26.12.0") + foreign_npm = tmp_path / "mise" / "bin" / "npm" + foreign_npm.parent.mkdir(parents=True) + foreign_npm.write_text("#!/bin/sh\n") + which = {"node": str(path_node), "npm": str(foreign_npm)} + monkeypatch.setattr(node_runtime.shutil, "which", lambda name: which.get(name)) + monkeypatch.setattr(node_runtime, "_recorded_node", lambda: None) + monkeypatch.delenv("CRAFTBOT_NODE", raising=False) + + # The sidecar, laid out as nodejs.org's archive is. + sidecar = tmp_path / "sidecar" + root = sidecar / "node-v24.22.3-linux-x64" + _node(root / "bin" / "node", "v24.22.3") + cli = root / "lib" / "node_modules" / "npm" / "bin" / "npm-cli.js" + cli.parent.mkdir(parents=True) + cli.write_text("") + (root / "bin" / "npm").symlink_to("../lib/node_modules/npm/bin/npm-cli.js") + monkeypatch.setattr(node_runtime, "SIDECAR_DIR", sidecar) + monkeypatch.setattr(node_runtime.Path, "home", lambda: tmp_path / "home") + + rt = node_runtime.resolve(refresh=True) + + assert rt.source == "discovered" + assert rt.node == str(root / "bin" / "node") + assert node_runtime.npm_command(rt) == [str(root / "bin" / "node"), str(cli)] From 5eed39411190c236aafc8aabe9d1fdf50c9b75bb Mon Sep 17 00:00:00 2001 From: zfoong Date: Sat, 21 Nov 2026 10:24:43 +0900 Subject: [PATCH 6/9] fix: show attaching to the browser edition as a note, not an error Only `craftbot tui` reaches a backend of the other edition, and it does so on purpose: it attaches to the CraftBot already running, which a launcher such as Omarchy's runs as the browser edition for its web app. The client called that an error and said to restart for the terminal, which there would break the web app. It is now a passing note that chats are shared with the browser and that pages CraftBot makes show only there. Co-Authored-By: Claude Opus 5.5 Signed-off-by: zfoong --- app/ui_layer/terminal/locales/en/tui.json | 2 +- app/ui_layer/terminal/locales/es/tui.json | 2 +- app/ui_layer/terminal/locales/id/tui.json | 2 +- app/ui_layer/terminal/locales/ja/tui.json | 2 +- app/ui_layer/terminal/locales/ko/tui.json | 2 +- app/ui_layer/terminal/locales/zh-CN/tui.json | 2 +- app/ui_layer/terminal/locales/zh-TW/tui.json | 2 +- app/ui_layer/terminal/src/runtime/runtime.tsx | 6 +++++- 8 files changed, 12 insertions(+), 8 deletions(-) diff --git a/app/ui_layer/terminal/locales/en/tui.json b/app/ui_layer/terminal/locales/en/tui.json index c2c1ae50..a659f635 100644 --- a/app/ui_layer/terminal/locales/en/tui.json +++ b/app/ui_layer/terminal/locales/en/tui.json @@ -66,7 +66,7 @@ "seeLog": "Its log: {{path}}", "stopHint": "Press Ctrl+C to quit, then run: python craftbot.py stop", "legacyConsole": "This is the classic Windows console. CraftBot works better in Windows Terminal (smoother redraws, Shift+Enter, paste).", - "wrongEdition": "CraftBot is running as the {{edition}} edition. Restart it for the terminal: python craftbot.py restart --tui" + "sharedWithBrowser": "Attached to the CraftBot your browser uses: chats show in both, and pages it makes show only in the browser." }, "working": { "label": "Working", diff --git a/app/ui_layer/terminal/locales/es/tui.json b/app/ui_layer/terminal/locales/es/tui.json index 603b12a6..7959518f 100644 --- a/app/ui_layer/terminal/locales/es/tui.json +++ b/app/ui_layer/terminal/locales/es/tui.json @@ -66,7 +66,7 @@ "seeLog": "Su registro: {{path}}", "stopHint": "Pulsa Ctrl+C para salir y luego ejecuta: python craftbot.py stop", "legacyConsole": "Esta es la consola clásica de Windows. CraftBot funciona mejor en Windows Terminal (redibujado más fluido, Shift+Enter, pegar).", - "wrongEdition": "CraftBot se está ejecutando en la edición {{edition}}. Reinícialo para la terminal: python craftbot.py restart --tui" + "sharedWithBrowser": "Conectado al CraftBot que usa tu navegador: los chats aparecen en ambos, y las páginas que crea solo se ven en el navegador." }, "working": { "label": "Trabajando", diff --git a/app/ui_layer/terminal/locales/id/tui.json b/app/ui_layer/terminal/locales/id/tui.json index 5ff4fa9e..365c8f39 100644 --- a/app/ui_layer/terminal/locales/id/tui.json +++ b/app/ui_layer/terminal/locales/id/tui.json @@ -66,7 +66,7 @@ "seeLog": "Log-nya: {{path}}", "stopHint": "Tekan Ctrl+C untuk keluar, lalu jalankan: python craftbot.py stop", "legacyConsole": "Ini konsol Windows klasik. CraftBot bekerja lebih baik di Windows Terminal (gambar ulang lebih mulus, Shift+Enter, tempel).", - "wrongEdition": "CraftBot berjalan sebagai edisi {{edition}}. Mulai ulang untuk terminal: python craftbot.py restart --tui" + "sharedWithBrowser": "Terhubung ke CraftBot yang dipakai browser Anda: obrolan tampil di keduanya, dan halaman yang dibuatnya hanya tampil di browser." }, "working": { "label": "Bekerja", diff --git a/app/ui_layer/terminal/locales/ja/tui.json b/app/ui_layer/terminal/locales/ja/tui.json index e4640b81..7bc3726b 100644 --- a/app/ui_layer/terminal/locales/ja/tui.json +++ b/app/ui_layer/terminal/locales/ja/tui.json @@ -66,7 +66,7 @@ "seeLog": "ログ: {{path}}", "stopHint": "Ctrl+C で終了してから、次を実行してください: python craftbot.py stop", "legacyConsole": "これは従来の Windows コンソールです。CraftBot は Windows Terminal のほうが快適に動作します(再描画が滑らか、Shift+Enter、貼り付けに対応)。", - "wrongEdition": "CraftBot は {{edition}} エディションとして実行中です。ターミナル版で再起動してください: python craftbot.py restart --tui" + "sharedWithBrowser": "ブラウザーで使っている CraftBot に接続しました。チャットは両方に表示され、作成されたページはブラウザーにのみ表示されます。" }, "working": { "label": "作業中", diff --git a/app/ui_layer/terminal/locales/ko/tui.json b/app/ui_layer/terminal/locales/ko/tui.json index 03282804..3461fae5 100644 --- a/app/ui_layer/terminal/locales/ko/tui.json +++ b/app/ui_layer/terminal/locales/ko/tui.json @@ -66,7 +66,7 @@ "seeLog": "로그: {{path}}", "stopHint": "Ctrl+C로 종료한 뒤 다음을 실행하세요: python craftbot.py stop", "legacyConsole": "기존 Windows 콘솔입니다. CraftBot은 Windows Terminal에서 더 잘 작동합니다(더 부드러운 화면 갱신, Shift+Enter, 붙여넣기).", - "wrongEdition": "CraftBot이 {{edition}} 에디션으로 실행 중입니다. 터미널용으로 다시 시작하세요: python craftbot.py restart --tui" + "sharedWithBrowser": "브라우저에서 사용하는 CraftBot에 연결했습니다. 채팅은 양쪽에 표시되며, 만든 페이지는 브라우저에만 표시됩니다." }, "working": { "label": "작업 중", diff --git a/app/ui_layer/terminal/locales/zh-CN/tui.json b/app/ui_layer/terminal/locales/zh-CN/tui.json index 6d7f737d..39f901e3 100644 --- a/app/ui_layer/terminal/locales/zh-CN/tui.json +++ b/app/ui_layer/terminal/locales/zh-CN/tui.json @@ -66,7 +66,7 @@ "seeLog": "日志:{{path}}", "stopHint": "按 Ctrl+C 退出,然后运行:python craftbot.py stop", "legacyConsole": "这是经典 Windows 控制台。CraftBot 在 Windows Terminal 中体验更好(重绘更流畅,支持 Shift+Enter 和粘贴)。", - "wrongEdition": "CraftBot 正以 {{edition}} 版本运行。请重启为终端版:python craftbot.py restart --tui" + "sharedWithBrowser": "已连接到浏览器正在使用的 CraftBot:聊天会同时显示在两边,它生成的页面只在浏览器中显示。" }, "working": { "label": "工作中", diff --git a/app/ui_layer/terminal/locales/zh-TW/tui.json b/app/ui_layer/terminal/locales/zh-TW/tui.json index c752f4c7..1e23b941 100644 --- a/app/ui_layer/terminal/locales/zh-TW/tui.json +++ b/app/ui_layer/terminal/locales/zh-TW/tui.json @@ -66,7 +66,7 @@ "seeLog": "記錄檔:{{path}}", "stopHint": "按 Ctrl+C 結束,然後執行:python craftbot.py stop", "legacyConsole": "這是傳統的 Windows 主控台。CraftBot 在 Windows Terminal 中運作得更好(重繪更流暢,支援 Shift+Enter 與貼上)。", - "wrongEdition": "CraftBot 正以 {{edition}} 版本執行。請重新啟動為終端機版:python craftbot.py restart --tui" + "sharedWithBrowser": "已連線到瀏覽器正在使用的 CraftBot:聊天會同時顯示在兩邊,它產生的頁面只會在瀏覽器中顯示。" }, "working": { "label": "處理中", diff --git a/app/ui_layer/terminal/src/runtime/runtime.tsx b/app/ui_layer/terminal/src/runtime/runtime.tsx index d570d449..a14800c7 100644 --- a/app/ui_layer/terminal/src/runtime/runtime.tsx +++ b/app/ui_layer/terminal/src/runtime/runtime.tsx @@ -118,8 +118,12 @@ export async function startClient(): Promise { case 'client_hello': { const d = (msg.data ?? {}) as { protocol?: number; edition?: string; version?: string } store.dispatch(setHello({ protocol: d.protocol ?? 0, edition: d.edition ?? '', version: d.version ?? '' })) + // Only `craftbot tui` reaches a backend of another edition, and it does + // so on purpose: it attaches to the CraftBot already running, which a + // launcher such as Omarchy's runs as the browser edition for its web + // app. Chats are shared, so this is a passing note, not an error. if (d.edition && d.edition !== 'terminal') { - store.dispatch(pushToast(i18n.t('tui:connect.wrongEdition', { edition: d.edition }), 'error', null, 'edition')) + store.dispatch(pushToast(i18n.t('tui:connect.sharedWithBrowser'), 'info', 10_000, 'edition')) } break } From 9d3c96802934aec38b891a7b2505766892d0ec42 Mon Sep 17 00:00:00 2001 From: zfoong Date: Sat, 21 Nov 2026 10:25:06 +0900 Subject: [PATCH 7/9] docs: say the runtimes are pinned in every README translation The English README was updated with the pinned Python and Node runtimes; the translations still told readers to trust their mirror for them. Co-Authored-By: Claude Opus 5.5 Signed-off-by: zfoong --- README.cn.md | 2 +- README.de.md | 2 +- README.es.md | 2 +- README.fr.md | 2 +- README.ja.md | 2 +- README.ko.md | 2 +- README.pt-BR.md | 2 +- README.zh-TW.md | 2 +- 8 files changed, 8 insertions(+), 8 deletions(-) diff --git a/README.cn.md b/README.cn.md index f679323d..09d851db 100644 --- a/README.cn.md +++ b/README.cn.md @@ -248,7 +248,7 @@ python craftbot.py install export CRAFTBOT_MIRRORS="https://github.com/=https:///https://github.com/;https://nodejs.org/dist/=https://npmmirror.com/mirrors/node/" ``` -Python 依赖包和记忆嵌入模型仍会按固定的 SHA-256 校验值进行校验,因此镜像无法改变它们。Python 和 Node.js 运行时没有固定校验值,请只为它们使用你信任的镜像。在 Windows PowerShell 中,请用 `$env:NAME = "value"` 代替 `export` 设置变量。 +Python 依赖包、Python 和 Node.js 运行时以及记忆嵌入模型都会按固定的 SHA-256 校验值进行校验,因此镜像无法改变它们。在 Windows PowerShell 中,请用 `$env:NAME = "value"` 代替 `export` 设置变量。 ### 没有桌面环境的服务器 diff --git a/README.de.md b/README.de.md index b7e1f376..fcec86e9 100644 --- a/README.de.md +++ b/README.de.md @@ -248,7 +248,7 @@ Leite die Downloads vor der Installation auf Mirrors um: export CRAFTBOT_MIRRORS="https://github.com/=https:///https://github.com/;https://nodejs.org/dist/=https://npmmirror.com/mirrors/node/" ``` -Python-Pakete und das Embedding-Modell für den Speicher werden weiterhin gegen fest hinterlegte SHA-256-Prüfsummen geprüft, ein Mirror kann sie also nicht verändern. Die Python- und Node.js-Laufzeiten sind nicht fest hinterlegt, verwende dafür nur einen Mirror, dem du vertraust. In Windows PowerShell setzt du Variablen mit `$env:NAME = "value"` statt `export`. +Python-Pakete, die Python- und Node.js-Laufzeiten und das Embedding-Modell für den Speicher werden gegen fest hinterlegte SHA-256-Prüfsummen geprüft, ein Mirror kann sie also nicht verändern. In Windows PowerShell setzt du Variablen mit `$env:NAME = "value"` statt `export`. ### Server ohne Desktop diff --git a/README.es.md b/README.es.md index 079f7038..4cabfbfe 100644 --- a/README.es.md +++ b/README.es.md @@ -248,7 +248,7 @@ Antes de instalar, dirige las descargas a mirrors: export CRAFTBOT_MIRRORS="https://github.com/=https:///https://github.com/;https://nodejs.org/dist/=https://npmmirror.com/mirrors/node/" ``` -Los paquetes de Python y el modelo de embeddings de la memoria se siguen verificando con checksums SHA-256 fijados, así que un mirror no puede cambiarlos. Los runtimes de Python y Node.js no están fijados, así que para ellos usa solo un mirror de confianza. En Windows PowerShell, define las variables con `$env:NAME = "value"` en lugar de `export`. +Los paquetes de Python, los runtimes de Python y Node.js y el modelo de embeddings de la memoria se verifican con checksums SHA-256 fijados, así que un mirror no puede cambiarlos. En Windows PowerShell, define las variables con `$env:NAME = "value"` en lugar de `export`. ### Servidor sin escritorio diff --git a/README.fr.md b/README.fr.md index c8935569..259baf15 100644 --- a/README.fr.md +++ b/README.fr.md @@ -248,7 +248,7 @@ Avant l'installation, redirigez les téléchargements vers des miroirs : export CRAFTBOT_MIRRORS="https://github.com/=https:///https://github.com/;https://nodejs.org/dist/=https://npmmirror.com/mirrors/node/" ``` -Les paquets Python et le modèle d'embeddings de la mémoire restent vérifiés avec des sommes de contrôle SHA-256 épinglées : un miroir ne peut donc pas les modifier. Les environnements d'exécution Python et Node.js ne sont pas épinglés, n'utilisez donc pour eux qu'un miroir de confiance. Dans Windows PowerShell, définissez les variables avec `$env:NAME = "value"` au lieu de `export`. +Les paquets Python, les environnements d'exécution Python et Node.js et le modèle d'embeddings de la mémoire sont vérifiés avec des sommes de contrôle SHA-256 épinglées : un miroir ne peut donc pas les modifier. Dans Windows PowerShell, définissez les variables avec `$env:NAME = "value"` au lieu de `export`. ### Serveur sans bureau diff --git a/README.ja.md b/README.ja.md index 0f8b5d5e..309ab505 100644 --- a/README.ja.md +++ b/README.ja.md @@ -248,7 +248,7 @@ TLS 通信を検査するネットワークでも追加の設定は不要です export CRAFTBOT_MIRRORS="https://github.com/=https:///https://github.com/;https://nodejs.org/dist/=https://npmmirror.com/mirrors/node/" ``` -Python パッケージとメモリ用の埋め込みモデルは、ミラーを使っても固定された SHA-256 チェックサムで検証されるため、ミラーがそれらを変えることはできません。Python と Node.js のランタイムはチェックサムが固定されていないため、信頼できるミラーだけを使ってください。Windows PowerShell では `export` の代わりに `$env:NAME = "value"` で変数を設定します。 +Python パッケージ、Python と Node.js のランタイム、メモリ用の埋め込みモデルは、ミラーを使っても固定された SHA-256 チェックサムで検証されるため、ミラーがそれらを変えることはできません。Windows PowerShell では `export` の代わりに `$env:NAME = "value"` で変数を設定します。 ### デスクトップのないサーバー diff --git a/README.ko.md b/README.ko.md index 1052e0d0..922191b3 100644 --- a/README.ko.md +++ b/README.ko.md @@ -248,7 +248,7 @@ TLS 트래픽을 검사하는 네트워크에서도 추가 설정이 필요 없 export CRAFTBOT_MIRRORS="https://github.com/=https:///https://github.com/;https://nodejs.org/dist/=https://npmmirror.com/mirrors/node/" ``` -Python 패키지와 메모리 임베딩 모델은 미러를 거쳐도 고정된 SHA-256 체크섬으로 검증되므로, 미러가 이를 바꿀 수 없습니다. Python과 Node.js 런타임은 체크섬이 고정되어 있지 않으므로, 신뢰할 수 있는 미러만 사용하세요. Windows PowerShell에서는 `export` 대신 `$env:NAME = "value"`로 변수를 설정합니다. +Python 패키지, Python과 Node.js 런타임, 메모리 임베딩 모델은 미러를 거쳐도 고정된 SHA-256 체크섬으로 검증되므로, 미러가 이를 바꿀 수 없습니다. Windows PowerShell에서는 `export` 대신 `$env:NAME = "value"`로 변수를 설정합니다. ### 데스크톱이 없는 서버 diff --git a/README.pt-BR.md b/README.pt-BR.md index 9a603d30..7a35ea9f 100644 --- a/README.pt-BR.md +++ b/README.pt-BR.md @@ -248,7 +248,7 @@ Antes de instalar, aponte os downloads para mirrors: export CRAFTBOT_MIRRORS="https://github.com/=https:///https://github.com/;https://nodejs.org/dist/=https://npmmirror.com/mirrors/node/" ``` -Os pacotes Python e o modelo de embeddings da memória continuam sendo verificados por checksums SHA-256 fixados, então um mirror não consegue alterá-los. Os runtimes de Python e Node.js não são fixados, então use para eles apenas um mirror de confiança. No Windows PowerShell, defina as variáveis com `$env:NAME = "value"` em vez de `export`. +Os pacotes Python, os runtimes de Python e Node.js e o modelo de embeddings da memória são verificados por checksums SHA-256 fixados, então um mirror não consegue alterá-los. No Windows PowerShell, defina as variáveis com `$env:NAME = "value"` em vez de `export`. ### Servidor sem desktop diff --git a/README.zh-TW.md b/README.zh-TW.md index 045ff3b7..39428ff8 100644 --- a/README.zh-TW.md +++ b/README.zh-TW.md @@ -248,7 +248,7 @@ python craftbot.py install export CRAFTBOT_MIRRORS="https://github.com/=https:///https://github.com/;https://nodejs.org/dist/=https://npmmirror.com/mirrors/node/" ``` -Python 套件和記憶嵌入模型仍會以固定的 SHA-256 檢查碼驗證,因此鏡像站無法改變它們。Python 和 Node.js 執行環境沒有固定檢查碼,請只為它們使用你信任的鏡像站。在 Windows PowerShell 中,請用 `$env:NAME = "value"` 取代 `export` 來設定變數。 +Python 套件、Python 和 Node.js 執行環境以及記憶嵌入模型都會以固定的 SHA-256 檢查碼驗證,因此鏡像站無法改變它們。在 Windows PowerShell 中,請用 `$env:NAME = "value"` 取代 `export` 來設定變數。 ### 沒有桌面環境的伺服器 From 35cba7424390f08c33a3db367756125894f61377 Mon Sep 17 00:00:00 2001 From: zfoong Date: Sat, 21 Nov 2026 10:43:51 +0900 Subject: [PATCH 8/9] feat: verify the desktop installer's Python against its pinned checksum The Rust launcher still asked GitHub for the newest python-build-standalone release and downloaded it unchecked, while install.py now takes only the release python_downloads.json pins. The launcher reads the same pins: it downloads that release's archive for this platform and refuses one whose SHA-256 differs, and no longer fetches a release listing, so the two install paths agree again and a rate limit cannot stop an install. Co-Authored-By: Claude Opus 5.5 Signed-off-by: zfoong --- app/provision/python_downloads.json | 1 - launcher/README.md | 24 +-- launcher/src/download.rs | 19 --- launcher/src/python.rs | 231 ++++++++-------------------- 4 files changed, 74 insertions(+), 201 deletions(-) diff --git a/app/provision/python_downloads.json b/app/provision/python_downloads.json index 3b2ab46d..97eb0c66 100644 --- a/app/provision/python_downloads.json +++ b/app/provision/python_downloads.json @@ -1,5 +1,4 @@ { - "api_base": "https://api.github.com", "download_base": "https://github.com", "repository": "astral-sh/python-build-standalone", "fallback_release": "20261009", diff --git a/launcher/README.md b/launcher/README.md index e64e5842..6b656959 100644 --- a/launcher/README.md +++ b/launcher/README.md @@ -34,15 +34,17 @@ two things onto the disk that Python cannot fetch for itself: matching the launcher's version, extracted into the install directory and stamped with `.craftbot-managed` (see `app/paths.py`). -Python download locations and the fallback release are maintained in -`app/provision/python_downloads.json`. It defines the API/download hosts, -repository, release tag, Python patch version, and published platforms. -The Rust launcher embeds this file at build time; the Python provisioner -reads the copy shipped in `CraftBot-src.zip`. Update the file and rebuild -both artifacts when the upstream location or compatible fallback changes. -The fallback must match the Python major/minor required by the dependency -locks; changing this file alone does not upgrade CraftBot to another Python -version. Release metadata is still preferred over the direct archive URL. +The Python release is pinned in `app/provision/python_downloads.json`: the +download host, repository, release tag, Python patch version, the published +platforms, and the SHA-256 of each platform's archive (from the release's +`SHA256SUMS`). The Rust launcher embeds this file at build time; the Python +provisioner reads the copy shipped in `CraftBot-src.zip`. Both download only +that release and refuse an archive whose digest differs, and neither asks +GitHub's release listing for anything. To move to another release, update the +tag, version and every digest together and rebuild both artifacts. The pinned +version must match the Python major/minor required by the dependency locks; +changing this file alone does not upgrade CraftBot to another Python +version. Everything after that is `craftbot.py` in the installed tree, run with `CRAFTBOT_PYTHON` pointing at the sidecar: @@ -118,8 +120,8 @@ rustls with the OS trust store. Every download (`src/download.rs`) is retried up to three times with backoff. `CraftBot-src.zip` is verified by SHA-256 against the `CraftBot-src.zip.sha256` asset the release publishes beside it; the Python -runtime comes from the release metadata described above and is accepted -only once the unpacked interpreter reports Python 3.10. The proxy is chosen +runtime is verified against the digest pinned above and is accepted only +once the unpacked interpreter reports Python 3.10. The proxy is chosen per URL (`src/proxy.rs`): `HTTPS_PROXY`/`HTTP_PROXY`/`ALL_PROXY` with `NO_PROXY`, otherwise the OS setting (Windows Internet Options, macOS `scutil --proxy`, GNOME gsettings). diff --git a/launcher/src/download.rs b/launcher/src/download.rs index aa13fbb8..012a4b14 100644 --- a/launcher/src/download.rs +++ b/launcher/src/download.rs @@ -173,25 +173,6 @@ pub fn fetch_text(url: &str) -> Result { }) } -/// A small JSON document (a GitHub release listing), with retries. -pub fn get_json(url: &str) -> Result { - let url = mirror(url); - logger::log(&format!("fetch: {url}")); - with_retries(&url, || { - get(&url, Some("application/vnd.github+json"))? - .into_json() - .map_err(|e| Failure::Transient(format!("{url}: bad JSON: {e}"))) - }) -} - -/// Download `url` to `dest`, with retries, for a file published without a -/// checksum (the Python runtime, resolved from its release listing). -pub fn to_file(url: &str, dest: &Path, progress: Progress) -> Result<(), String> { - let url = mirror(url); - logger::log(&format!("download: {url}")); - with_retries(&url, || to_file_once(&url, dest, progress)) -} - /// Download `url` to `dest` and check its SHA-256 before anything can use /// it. A mismatch is retried too: a mirror or cache can hand out a stale or /// partial file once and the right one next time. diff --git a/launcher/src/python.rs b/launcher/src/python.rs index 319a4973..a8c1f974 100644 --- a/launcher/src/python.rs +++ b/launcher/src/python.rs @@ -8,9 +8,10 @@ //! module puts it. When install.py later runs its own `python` stage it //! finds this one already there and accepts it; nothing is downloaded twice. //! -//! Asset URLs are resolved from GitHub release metadata, including the final -//! Python 3.10 release when the newest release no longer carries that version. -//! This mirrors app/provision/runtimes.py and its dependency-lock constraint. +//! The archive comes from the release python_downloads.json pins, checked +//! against the SHA-256 it pins for this platform before it is unpacked, as +//! app/provision/runtimes.py does. No release listing is asked for, so a +//! GitHub API rate limit cannot stop an install. use crate::download; use crate::logger; @@ -25,12 +26,12 @@ pub const TARGET: (u32, u32) = (3, 10); // the source payload. The CLI reads the same file from that payload. #[derive(serde::Deserialize)] struct DownloadConfig { - api_base: String, download_base: String, repository: String, fallback_release: String, fallback_version: String, fallback_platforms: Vec, + sha256: std::collections::HashMap, } impl DownloadConfig { @@ -39,37 +40,37 @@ impl DownloadConfig { .map_err(|error| format!("invalid Python download configuration: {error}")) } - fn compatible_fallback(&self) -> bool { - self.fallback_version + /// The pinned archive for `triple` and the SHA-256 it must have. + fn pinned(&self, triple: &str) -> Result<(String, String), String> { + if !self + .fallback_version .starts_with(&format!("{}.{}.", TARGET.0, TARGET.1)) - } - - fn indexes(&self) -> Vec { - let api = format!( - "{}/repos/{}/releases", - self.api_base.trim_end_matches('/'), - self.repository - ); - let mut indexes = vec![format!("{api}/latest")]; - if self.compatible_fallback() { - indexes.push(format!("{api}/tags/{}", self.fallback_release)); - } - indexes - } - - fn archived_url(&self, triple: &str) -> Option { - if self.compatible_fallback() && self.fallback_platforms.iter().any(|p| p == triple) { - Some(format!( - "{}/{}/releases/download/{}/cpython-{}%2B{}-{triple}-install_only.tar.gz", - self.download_base.trim_end_matches('/'), - self.repository, - self.fallback_release, - self.fallback_version, - self.fallback_release - )) - } else { - None + { + return Err(format!( + "the pinned Python {} is not {}.{}", + self.fallback_version, TARGET.0, TARGET.1 + )); } + let digest = self + .sha256 + .get(triple) + .filter(|_| self.fallback_platforms.iter().any(|p| p == triple)) + .filter(|d| d.len() == 64 && d.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))) + .ok_or_else(|| { + format!( + "no pinned Python {} build for {triple}", + self.fallback_version + ) + })?; + let url = format!( + "{}/{}/releases/download/{}/cpython-{}%2B{}-{triple}-install_only.tar.gz", + self.download_base.trim_end_matches('/'), + self.repository, + self.fallback_release, + self.fallback_version, + self.fallback_release + ); + Ok((url, digest.clone())) } } @@ -109,14 +110,14 @@ pub fn ensure( ) })?; say(&format!("Downloading Python {}.{}…", TARGET.0, TARGET.1)); - let url = resolve_url(&triple)?; + let (url, sha256) = DownloadConfig::bundled()?.pinned(&triple)?; logger::log(&format!("python: {url}")); let dest_dir = paths::python_runtime_dir(); std::fs::create_dir_all(&dest_dir) .map_err(|e| format!("cannot create {}: {e}", dest_dir.display()))?; let archive = dest_dir.join("_download.tar.gz"); - download::to_file(&url, &archive, progress)?; + download::verified_to_file(&url, &archive, &sha256, progress)?; say("Unpacking Python…"); let result = extract_tar_gz(&archive, &dest_dir); @@ -178,61 +179,6 @@ fn triple() -> Option { } } -fn resolve_url(triple: &str) -> Result { - resolve_url_with(triple, download::get_json) -} - -fn resolve_url_with( - triple: &str, - fetch: impl FnMut(&str) -> Result, -) -> Result { - resolve_url_with_config(triple, &DownloadConfig::bundled()?, fetch) -} - -fn resolve_url_with_config( - triple: &str, - config: &DownloadConfig, - mut fetch: impl FnMut(&str) -> Result, -) -> Result { - let prefix = format!("cpython-{}.{}.", TARGET.0, TARGET.1); - let suffix = format!("-{triple}-install_only.tar.gz"); - for index in config.indexes() { - let data = match fetch(&index) { - Ok(data) => data, - Err(error) => { - // GitHub API quotas are shared by public egress IP. Assets - // use a separate endpoint, so metadata throttling must not - // strand a fresh install whose compatible build is known. - if let Some(url) = config.archived_url(triple) { - logger::log(&format!( - "Python index unavailable ({error}); using archived {} download", - config.fallback_version - )); - return Ok(url); - } - return Err(format!( - "could not reach the Python download index: {error}" - )); - } - }; - if let Some(assets) = data.get("assets").and_then(|a| a.as_array()) { - for asset in assets { - let name = asset.get("name").and_then(|n| n.as_str()).unwrap_or(""); - if name.starts_with(&prefix) && name.ends_with(&suffix) { - if let Some(url) = asset.get("browser_download_url").and_then(|u| u.as_str()) { - if !url.is_empty() { - return Ok(url.to_string()); - } - } - } - } - } - } - Err(format!( - "no {prefix}*{suffix} in the checked python-build-standalone releases" - )) -} - /// Extract a .tar.gz, preserving permissions — the executable bit on /// bin/python3 is the whole point on macOS and Linux. fn extract_tar_gz(archive: &std::path::Path, dest: &std::path::Path) -> Result<(), String> { @@ -261,83 +207,43 @@ mod tests { use serde_json::json; #[test] - fn api_rate_limit_does_not_block_known_python_downloads() { + fn every_platform_resolves_its_pinned_archive_and_digest() { let config = DownloadConfig::bundled().unwrap(); for triple in &config.fallback_platforms { - let url = - resolve_url_with(triple, |_| Err("HTTP 403 rate limit exceeded".into())).unwrap(); - assert_eq!(url, config.archived_url(triple).unwrap()); - } - assert!(resolve_url_with("unsupported-target", |_| Err("HTTP 403".into())).is_err()); - } - - #[test] - fn resolves_retired_python_from_last_supported_release() { - let config = DownloadConfig::bundled().unwrap(); - for triple in &config.fallback_platforms { - let mut requests = Vec::new(); - let url = resolve_url_with(triple, |index| { - requests.push(index.to_string()); - Ok(if index == config.indexes()[0] { - json!({"assets": []}) - } else { - json!({"assets": [{ - "name": format!("cpython-{}+{}-{triple}-install_only.tar.gz", config.fallback_version, config.fallback_release), - "browser_download_url": "https://example.test/compatible-python.tar.gz" - }]}) - }) - }) - .unwrap(); - assert_eq!(requests, config.indexes()); - assert_eq!(url, "https://example.test/compatible-python.tar.gz"); + let (url, sha256) = config.pinned(triple).unwrap(); + assert_eq!( + url, + format!( + "https://github.com/astral-sh/python-build-standalone/releases/download/{0}/cpython-{1}%2B{0}-{triple}-install_only.tar.gz", + config.fallback_release, config.fallback_version + ) + ); + assert_eq!(&sha256, &config.sha256[triple]); + assert_eq!(sha256.len(), 64); } + assert!(config.pinned("unsupported-target").is_err()); } #[test] - fn latest_matching_asset_takes_priority() { - let mut requests = Vec::new(); - let url = resolve_url_with("x86_64-unknown-linux-gnu", |index| { - requests.push(index.to_string()); - Ok(json!({"assets": [{ - "name": "cpython-3.10.99+test-x86_64-unknown-linux-gnu-install_only.tar.gz", - "browser_download_url": "https://example.test/newer-python.tar.gz" - }]})) - }) - .unwrap(); - assert_eq!(url, "https://example.test/newer-python.tar.gz"); - assert_eq!(requests.len(), 1); - } - - #[test] - fn configuration_controls_indexes_and_archive() { + fn a_platform_without_a_pinned_digest_is_refused() { let config: DownloadConfig = serde_json::from_value(json!({ - "api_base": "https://api.example.test/", "download_base": "https://downloads.example.test/", "repository": "maintainer/python", "fallback_release": "20990101", "fallback_version": "3.10.99", - "fallback_platforms": ["test-platform"] + "fallback_platforms": ["pinned", "unpinned", "malformed"], + "sha256": {"pinned": "a".repeat(64), "malformed": "A".repeat(64), "unlisted": "b".repeat(64)} })) .unwrap(); - for fail_on in [1, 2] { - let mut requests = Vec::new(); - let url = resolve_url_with_config("test-platform", &config, |index| { - requests.push(index.to_string()); - if requests.len() == fail_on { - Err("index unavailable".into()) - } else { - Ok(json!({"assets": []})) - } - }) - .unwrap(); - assert_eq!(url, "https://downloads.example.test/maintainer/python/releases/download/20990101/cpython-3.10.99%2B20990101-test-platform-install_only.tar.gz"); - assert_eq!( - requests, - [ - "https://api.example.test/repos/maintainer/python/releases/latest", - "https://api.example.test/repos/maintainer/python/releases/tags/20990101" - ][..fail_on] - ); + assert_eq!( + config.pinned("pinned").unwrap(), + ( + "https://downloads.example.test/maintainer/python/releases/download/20990101/cpython-3.10.99%2B20990101-pinned-install_only.tar.gz".to_string(), + "a".repeat(64) + ) + ); + for triple in ["unpinned", "malformed", "unlisted"] { + assert!(config.pinned(triple).is_err(), "{triple}"); } } @@ -345,21 +251,6 @@ mod tests { fn configuration_cannot_supply_a_different_python_version() { let mut config = DownloadConfig::bundled().unwrap(); config.fallback_version = "3.11.0".into(); - assert!( - resolve_url_with_config("x86_64-pc-windows-msvc", &config, |_| Err("offline".into())) - .is_err() - ); - assert_eq!(config.indexes().len(), 1); - } - - #[test] - fn does_not_substitute_a_different_python_version() { - let result = resolve_url_with("x86_64-unknown-linux-gnu", |_| { - Ok(json!({"assets": [{ - "name": "cpython-3.11.0+20261110-x86_64-unknown-linux-gnu-install_only.tar.gz", - "browser_download_url": "https://example.test/wrong-python.tar.gz" - }]})) - }); - assert!(result.is_err()); + assert!(config.pinned("x86_64-unknown-linux-gnu").is_err()); } } From 726797444e269209b71fef3470cbe51d6745bbea Mon Sep 17 00:00:00 2001 From: zfoong Date: Sat, 21 Nov 2026 10:56:38 +0900 Subject: [PATCH 9/9] test: give the craftbot command tests their own home on Windows too Windows' expanduser reads USERPROFILE, not HOME, so the command landed in the runner's own home and the uninstall test looked for it in vain. Co-Authored-By: Claude Opus 5.5 Signed-off-by: zfoong --- tests/test_craftbot_service.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tests/test_craftbot_service.py b/tests/test_craftbot_service.py index 2d1a67d6..db168328 100644 --- a/tests/test_craftbot_service.py +++ b/tests/test_craftbot_service.py @@ -734,7 +734,9 @@ def test_install_without_start_registers_startup_and_starts_nothing( def command_home(tmp_path, monkeypatch): """A home of its own, and an interpreter that prints what it was given.""" home = tmp_path / "home" + # Windows' expanduser reads USERPROFILE, not HOME. monkeypatch.setenv("HOME", str(home)) + monkeypatch.setenv("USERPROFILE", str(home)) monkeypatch.setattr(craftbot, "IS_FROZEN", False) monkeypatch.setattr(craftbot, "_PLATFORM", "linux") python = tmp_path / "py thon"