Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(packaging): freeze one bundle with a GUI and a CLI executable
rubenluetke10-beep0ac317e07b6c
diff --git a/build.bat b/build.batindex 49b8d5589d..d5f114e342 100644--- a/build.bat+++ b/build.bat@@ -1,37 +1,37 @@@echo off-REM Personal Jarvis — Production-Build (Phase 1a → 6)-REM Schritt 1: Frontend-Bundle via Vite → jarvis/ui/web/dist/-REM Schritt 2: PyInstaller → dist/Jarvis/Jarvis.exe (onedir-Bundle)+REM Personal Jarvis - Windows build.+REM+REM Thin wrapper around packaging\windows\build.ps1, which is the one script+REM that builds the frontend, freezes the app with PyInstaller and wraps the+REM result in the Inno Setup wizard. Keeping the logic in one place is what+REM stops this file and the release workflow from drifting apart.+REM+REM Result: dist\installers\PersonalJarvis-Setup-x64.exe+REM (the frozen bundle it is built from stays in dist\Jarvis)+REM+REM Any build.ps1 switch is passed straight through, for example:+REM build.bat -SkipPyInstaller-setlocal EnableDelayedExpansion+setlocalcd /d "%~dp0"-if exist ".venv\Scripts\activate.bat" (- call .venv\Scripts\activate.bat+set "SCRIPT=%~dp0packaging\windows\build.ps1"+if not exist "%SCRIPT%" (+ echo [build] packaging\windows\build.ps1 is missing - aborting.+ exit /b 1)-echo [build] 1/2 Frontend-pushd jarvis\ui\web\frontend-if not exist node_modules (- echo [build] npm ci...- call npm ci || goto :error+REM pwsh (PowerShell 7) when available, Windows PowerShell otherwise.+where pwsh >nul 2>&1+if %ERRORLEVEL% EQU 0 (+ pwsh -NoProfile -ExecutionPolicy Bypass -File "%SCRIPT%" %*+) else (+ powershell -NoProfile -ExecutionPolicy Bypass -File "%SCRIPT%" %*)-call npm run build || goto :error-popd-echo [build] 2/2 PyInstaller-if not exist jarvis.spec (- echo [build] jarvis.spec fehlt — Abbruch.+if %ERRORLEVEL% NEQ 0 (+ echo [build] FAILED.exit /b 1)-pyinstaller jarvis.spec --noconfirm --clean || goto :error--echo [build] Fertig. Artefakt: dist\Jarvis\Jarvis.exe-goto :end--:error-echo [build] FEHLGESCHLAGEN.-exit /b 1-:endendlocaldiff --git a/jarvis.spec b/jarvis.specindex 5da64e8029..0f25c87f12 100644--- a/jarvis.spec+++ b/jarvis.spec@@ -1,18 +1,32 @@-# PyInstaller spec for the Personal Jarvis desktop app (Phase 1a).+# PyInstaller spec for the natively installed Personal Jarvis desktop app.#-# Strategy (see plan section 5.10 and the Phase 1a plan section 5):+# Strategy:# - `onedir` instead of `onefile` avoids 3-5 seconds of MEIPASS extraction and# allows each DLL to be signed independently.+# - TWO executables share ONE Analysis/COLLECT, because a native install has to+# cover both surfaces the project promises:+# * a windowed GUI launcher (Start Menu / Applications / .desktop), and+# * a console CLI named `jarvis`, so `jarvis serve`, `jarvis --version`,+# `jarvis missions list` behave exactly like the pip console script.+# Both run `jarvis/__main__.py`; only the console flag differs.+# - The GUI binary is `PersonalJarvis`, not `Jarvis`: `Jarvis` and `jarvis`+# are the SAME path on Windows (NTFS) and on a default macOS APFS volume, so+# the second executable would overwrite the first. `PersonalJarvis` is the+# name jarvis.core.branding already uses for the Windows branded launcher and+# the macOS bundle executable.# - Downloaded ML models are not bundled. The first-run wizard downloads them to# the platform-specific Jarvis model directory when the user enables them.# - Optional native voice engines are loaded lazily and degrade to cloud paths# when unavailable. No Jarvis install profile requires torch or a GPU.# - Excluding unused GUI frameworks saves roughly 500 MB.#-# Invoke with `build.bat` or `pyinstaller jarvis.spec --noconfirm`.+# Invoke through the per-OS build script (packaging/<os>/build.*) or directly+# with `pyinstaller jarvis.spec --noconfirm --clean`.# ruff: noqa+import re+import sysfrom pathlib import Pathfrom PyInstaller.utils.hooks import (@@ -25,6 +39,31 @@ from PyInstaller.utils.hooks import (PROJECT_ROOT = Path(SPECPATH).resolve() # noqa: F821 (SPECPATH is PyInstaller-injected)FRONTEND_DIST = PROJECT_ROOT / "jarvis" / "ui" / "web" / "dist"PACKAGE_ASSETS = PROJECT_ROOT / "jarvis" / "assets"+ICON_DIR = PROJECT_ROOT / "assets" / "icons"++# The COLLECT directory name stays `Jarvis` — the per-OS packaging scripts and+# the release contract address the bundle as `dist/Jarvis/`.+BUNDLE_DIR_NAME = "Jarvis"+# Windowed launcher; see the header note on the case-collision.+GUI_EXE_NAME = "PersonalJarvis"+# Console entry point. Same name as the pip console script on purpose.+CLI_EXE_NAME = "jarvis"++MACOS_APP_NAME = "Personal Jarvis.app"+MACOS_BUNDLE_IDENTIFIER = "ai.personaljarvis.desktop"+MACOS_MIN_SYSTEM_VERSION = "12.0"+++def _package_version() -> str:+ """Read ``jarvis.__version__`` without importing the package."""+ text = (PROJECT_ROOT / "jarvis" / "__init__.py").read_text(encoding="utf-8")+ match = re.search(r'__version__\s*=\s*"([^"]+)"', text)+ if not match:+ raise SystemExit("jarvis/__init__.py does not define __version__")+ return match.group(1)+++VERSION = _package_version()# --- Data files -------------------------------------------------------------@@ -39,7 +78,9 @@ if FRONTEND_DIST.exists():rel = entry.relative_to(FRONTEND_DIST).parentdatas.append((str(entry), str(Path("jarvis/ui/web/dist") / rel)))-# Include the default configuration loaded by a fresh desktop installation.+# Include the default configuration a fresh install is seeded from. The runtime+# hook copies it to the per-user app directory on first launch; the frozen app+# never reads or writes the copy inside the bundle.datas.append((str(PROJECT_ROOT / "jarvis.toml"), "."))datas.append((str(PROJECT_ROOT / "docs" / "product"), "docs/product"))@@ -60,6 +101,42 @@ if PACKAGE_ASSETS.exists():rel = entry.relative_to(PACKAGE_ASSETS).parentdatas.append((str(entry), str(Path("jarvis/assets") / rel)))+# Every non-Python file inside the `jarvis` package. PyInstaller collects only+# modules, so without this the frozen app silently loses its SQL migrations+# (jarvis/memory, jarvis/ultrawiki), the built-in skills (jarvis/skills/builtin+# — the boot log says "builtin skill '...' missing from package"), the CLI and+# skill catalogs, the wiki templates and the marketplace usage cards. Roughly+# 100 files / 400 KB, so collecting them wholesale costs nothing and closes the+# whole "works from source, missing when frozen" class at once.+_PACKAGE_DATA_SKIP_DIRS = {"__pycache__", "node_modules"}+_PACKAGE_DATA_SKIP_ROOTS = (+ PROJECT_ROOT / "jarvis" / "ui" / "web" / "frontend", # source, not runtime+ FRONTEND_DIST, # already collected above, with its own layout+ PACKAGE_ASSETS, # collected explicitly below+)+_PACKAGE_DATA_SKIP_SUFFIXES = {".py", ".pyc", ".pyd", ".so", ".dylib", ".map"}+_package_root = PROJECT_ROOT / "jarvis"+for entry in _package_root.rglob("*"):+ if not entry.is_file():+ continue+ if _PACKAGE_DATA_SKIP_DIRS & set(entry.parts):+ continue+ if entry.suffix.lower() in _PACKAGE_DATA_SKIP_SUFFIXES:+ continue+ if any(entry.is_relative_to(skip) for skip in _PACKAGE_DATA_SKIP_ROOTS):+ continue+ rel = entry.relative_to(PROJECT_ROOT).parent+ datas.append((str(entry), str(rel)))++# Configuration profiles live beside the checkout root, and jarvis.core.config+# resolves them relative to it.+profiles_dir = PROJECT_ROOT / "profiles"+if profiles_dir.exists():+ for entry in profiles_dir.rglob("*"):+ if entry.is_file():+ rel = entry.relative_to(profiles_dir).parent+ datas.append((str(entry), str(Path("profiles") / rel)))+# Preserve distribution metadata so importlib.metadata can discover the Jarvis# entry-point plugins in the frozen layout.datas += copy_metadata("personal-jarvis")@@ -108,6 +185,33 @@ for pkg in ("faster_whisper", "ctranslate2"):except Exception:pass+# Optional per-OS integrations reached through lazy imports at runtime. Only the+# ones actually installed on the build machine are added, so the spec stays+# buildable on a host without the platform extras.+_optional_hidden = [+ "webview",+ "pystray",+ "PIL",+]+if sys.platform == "win32":+ _optional_hidden += [+ "win32api",+ "win32com.client",+ "win32con",+ "win32gui",+ "win32process",+ "pythoncom",+ "pywintypes",+ "comtypes",+ "pycaw",+ ]+for pkg in _optional_hidden:+ try:+ __import__(pkg)+ except Exception:+ continue+ hiddenimports.append(pkg)+# --- Bundle-size exclusions -------------------------------------------------@@ -124,10 +228,21 @@ excludes = ["notebook","torch.test","tornado",+ # Development-only. They arrive through the `[dev]` extra that the build+ # machine installs (PyInstaller itself lives there too), and every one of+ # them is dead weight in a shipped app - mypy alone is tens of megabytes of+ # compiled mypyc extensions.+ "PyInstaller",+ "_pytest",+ "coverage",+ "hypothesis",+ "mypy",+ "mypyc",+ "ruff",]-# --- Analysis / executable --------------------------------------------------+# --- Analysis ---------------------------------------------------------------block_cipher = None@@ -137,9 +252,13 @@ a = Analysis(binaries=[],datas=datas,hiddenimports=hiddenimports,- hookspath=[],+ # Outranks pyinstaller-hooks-contrib (HOOK_PRIORITY_USER_HOOKS); see the+ # files in that directory for why each override exists.+ hookspath=[str(PROJECT_ROOT / "packaging" / "pyinstaller_hooks")],hooksconfig={},- runtime_hooks=[],+ # Redirects jarvis.toml + the data directory to the per-user app directory+ # BEFORE jarvis.core.config freezes its import-time path constants.+ runtime_hooks=[str(PROJECT_ROOT / "packaging" / "pyinstaller_rthook_frozen.py")],excludes=excludes,win_no_prefer_redirects=False,win_private_assemblies=False,@@ -149,12 +268,85 @@ a = Analysis(pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher)-exe = EXE(++# --- Windows version resource ----------------------------------------------+# Explorer's Details tab, the SmartScreen prompt and AV reputation engines read+# this. An unversioned binary is treated as less trustworthy.++version_resource = None+if sys.platform == "win32":+ from PyInstaller.utils.win32.versioninfo import (+ FixedFileInfo,+ StringFileInfo,+ StringStruct,+ StringTable,+ VarFileInfo,+ VarStruct,+ VSVersionInfo,+ )++ _numeric = [int(part) for part in re.findall(r"\d+", VERSION)[:4]]+ _numeric += [0] * (4 - len(_numeric))+ _filevers = tuple(_numeric)++ version_resource = VSVersionInfo(+ ffi=FixedFileInfo(+ filevers=_filevers,+ prodvers=_filevers,+ mask=0x3F,+ flags=0x0,+ OS=0x40004,+ fileType=0x1,+ subtype=0x0,+ date=(0, 0),+ ),+ kids=[+ StringFileInfo(+ [+ StringTable(+ "040904B0",+ [+ StringStruct("CompanyName", "Personal Jarvis"),+ StringStruct("FileDescription", "Personal Jarvis"),+ StringStruct("FileVersion", VERSION),+ StringStruct("InternalName", GUI_EXE_NAME),+ StringStruct(+ "LegalCopyright",+ "Personal Jarvis contributors. MIT licensed.",+ ),+ StringStruct("OriginalFilename", f"{GUI_EXE_NAME}.exe"),+ StringStruct("ProductName", "Personal Jarvis"),+ StringStruct("ProductVersion", VERSION),+ ],+ )+ ]+ ),+ VarFileInfo([VarStruct("Translation", [0x0409, 1200])]),+ ],+ )+++def _icon_path():+ """The platform's icon, or ``None`` when it has not been generated yet."""+ candidate = ICON_DIR / ("jarvis.icns" if sys.platform == "darwin" else "jarvis.ico")+ if candidate.is_file():+ return str(candidate)+ print(f"[jarvis.spec] icon {candidate} is missing - building without one")+ return None+++ICON = _icon_path()+++# --- Executables ------------------------------------------------------------+# Two targets, one COLLECT: the windowed launcher and the console CLI.++exe_gui = EXE(pyz,a.scripts,[],exclude_binaries=True,- name="Jarvis",+ name=GUI_EXE_NAME,debug=False,bootloader_ignore_signals=False,strip=False,@@ -165,17 +357,104 @@ exe = EXE(target_arch=None,codesign_identity=None,entitlements_file=None,- icon=str(PROJECT_ROOT / "assets" / "icons" / "jarvis.ico"), # Gigi mascot icon.+ icon=ICON,+ version=version_resource,uac_admin=False, # Run asInvoker; elevate only individual actions.)+exe_cli = EXE(+ pyz,+ a.scripts,+ [],+ exclude_binaries=True,+ name=CLI_EXE_NAME,+ debug=False,+ bootloader_ignore_signals=False,+ strip=False,+ upx=False,+ console=True, # `jarvis serve` must print to the terminal it ran in.+ disable_windowed_traceback=False,+ argv_emulation=False,+ target_arch=None,+ codesign_identity=None,+ entitlements_file=None,+ icon=ICON,+ version=version_resource,+ uac_admin=False,+)+coll = COLLECT(- exe,+ exe_gui,+ exe_cli,a.binaries,a.zipfiles,a.datas,strip=False,upx=False,upx_exclude=[],- name="Jarvis",+ name=BUNDLE_DIR_NAME,)+++# --- macOS application bundle ----------------------------------------------+# Cannot be produced anywhere else: BUNDLE only runs on darwin. packaging/macos+# wraps the resulting .app in the release DMG.++if sys.platform == "darwin":+ app = BUNDLE(+ coll,+ name=MACOS_APP_NAME,+ icon=ICON,+ bundle_identifier=MACOS_BUNDLE_IDENTIFIER,+ version=VERSION,+ info_plist={+ "CFBundleName": "Personal Jarvis",+ "CFBundleDisplayName": "Personal Jarvis",+ "CFBundleExecutable": GUI_EXE_NAME,+ "CFBundleIdentifier": MACOS_BUNDLE_IDENTIFIER,+ "CFBundleShortVersionString": VERSION,+ "CFBundleVersion": VERSION,+ "CFBundlePackageType": "APPL",+ "LSMinimumSystemVersion": MACOS_MIN_SYSTEM_VERSION,+ "LSApplicationCategoryType": "public.app-category.productivity",+ "NSHighResolutionCapable": True,+ # Personal Jarvis is voice-first: without a usage string macOS kills+ # the process the moment it touches the matching API.+ "NSMicrophoneUsageDescription": (+ "Personal Jarvis listens for your wake word and your spoken "+ "requests. Audio stays on this Mac unless you configure a cloud "+ "speech provider yourself."+ ),+ "NSSpeechRecognitionUsageDescription": (+ "Personal Jarvis turns what you say into text so it can act on "+ "your request."+ ),+ "NSCameraUsageDescription": (+ "Personal Jarvis uses the camera only for features you start "+ "yourself, such as showing it what is in front of you."+ ),+ "NSAppleEventsUsageDescription": (+ "Personal Jarvis controls other applications on your behalf "+ "when you ask it to, for example to open a file or a window."+ ),+ "NSSystemAdministrationUsageDescription": (+ "Personal Jarvis needs Accessibility and Input Monitoring "+ "access to type, click and read the screen for the automation "+ "tasks you ask it to run."+ ),+ "NSDesktopFolderUsageDescription": (+ "Personal Jarvis saves the files it produces for you to your "+ "Desktop."+ ),+ "NSDocumentsFolderUsageDescription": (+ "Personal Jarvis reads and writes the documents you point it at."+ ),+ "NSDownloadsFolderUsageDescription": (+ "Personal Jarvis opens the downloads you ask it to work with."+ ),+ "NSLocalNetworkUsageDescription": (+ "Personal Jarvis serves its own interface to your browser on "+ "this machine."+ ),+ },+ )diff --git a/packaging/pyinstaller_hooks/hook-webrtcvad.py b/packaging/pyinstaller_hooks/hook-webrtcvad.pynew file mode 100644index 0000000000..31a51f350d--- /dev/null+++ b/packaging/pyinstaller_hooks/hook-webrtcvad.py@@ -0,0 +1,32 @@+# Overrides the pyinstaller-hooks-contrib hook for `webrtcvad`.+#+# The contrib hook calls `copy_metadata('webrtcvad')` unconditionally. Personal+# Jarvis installs `webrtcvad-wheels` — the maintained fork that ships binary+# wheels, so no compiler is needed on any OS — which provides the SAME+# `webrtcvad` import name under a DIFFERENT distribution name. `copy_metadata`+# then raises, and PyInstaller aborts the whole build while importing the hook+# ("Failed to import module __PyInstaller_hooks_0_webrtcvad").+#+# User hook directories outrank the contrib ones (HOOK_PRIORITY_USER_HOOKS), so+# this file replaces it. Both distribution names are tried, and neither being+# present is fine: the metadata is not needed at runtime, only the module is.++from PyInstaller.utils.hooks import copy_metadata+++def _metadata_of_first_installed(*distributions: str) -> list:+ """Metadata of the first distribution that is actually installed.++ An absent distribution is the expected case, not an error worth reporting:+ only one of the two names is ever present, and neither being present is+ fine because the module - not its metadata - is what the app imports.+ """+ for distribution in distributions:+ try:+ return copy_metadata(distribution)+ except Exception as exc: # noqa: BLE001 - any resolution failure means "not this one"+ print(f"[hook-webrtcvad] {distribution}: {exc}")+ return []+++datas = _metadata_of_first_installed("webrtcvad-wheels", "webrtcvad")diff --git a/packaging/pyinstaller_rthook_frozen.py b/packaging/pyinstaller_rthook_frozen.pynew file mode 100644index 0000000000..209accb5ae--- /dev/null+++ b/packaging/pyinstaller_rthook_frozen.py@@ -0,0 +1,99 @@+"""PyInstaller runtime hook: keep a frozen install out of its own program files.++Why this exists+---------------+``jarvis.core.config`` derives ``PROJECT_ROOT`` from ``jarvis/core/config.py``'s+own location. Inside a PyInstaller ``onedir`` bundle that resolves to the+bundled-resources root (``sys._MEIPASS`` = ``<install dir>/_internal``), so+without this hook a natively installed app would keep its ``jarvis.toml`` and+its whole ``data/`` tree INSIDE the installed program directory. Two things+break there:++* an in-place upgrade reinstalls ``_internal/jarvis.toml`` and silently+ discards every setting the user made, and+* an uninstall that removes the program directory takes the user's memory,+ skills and logs with it.++A runtime hook runs before the frozen entry script imports anything from+``jarvis``, which is the only moment where the import-time path constants in+``jarvis.core.config`` can still be steered. It points the two documented+override variables at the per-user application directory and seeds a first-run+``jarvis.toml`` from the copy inside the bundle.++An explicitly exported ``JARVIS_CONFIG`` / ``JARVIS_DATA_DIR`` always wins, so a+maintainer can still run a frozen build against a scratch directory.++Standard library only, and no ``jarvis`` import: a failure in a runtime hook+kills a windowed process before any logging exists. ``tests/unit/packaging/+test_frozen_runtime_hook.py`` pins the directory convention below to+``jarvis.core.paths.user_data_dir`` so the duplication cannot drift.+"""++from __future__ import annotations++import os+import shutil+import sys+from pathlib import Path++# Mirrors jarvis.core.branding.WINDOWS_USER_DATA_DIR_NAME / FALLBACK_USER_DATA_DIR_NAME.+_WINDOWS_USER_DATA_DIR_NAME = "Jarvis"+_FALLBACK_USER_DATA_DIR_NAME = ".jarvis"+_CONFIG_FILE_NAME = "jarvis.toml"+++def _user_data_dir() -> Path:+ """``%LOCALAPPDATA%\\Jarvis`` on Windows, ``~/.jarvis`` everywhere else."""+ base = os.environ.get("LOCALAPPDATA")+ if base:+ return Path(base) / _WINDOWS_USER_DATA_DIR_NAME+ return Path.home() / _FALLBACK_USER_DATA_DIR_NAME+++def _is_set(name: str) -> bool:+ value = os.environ.get(name)+ return bool(value and value.strip())+++def _warn(message: str) -> None:+ """Report a hook problem without ever becoming the crash itself."""+ stream = getattr(sys, "stderr", None)+ if stream is None:+ return+ try:+ stream.write(f"[jarvis] {message}\n")+ except (OSError, ValueError, AttributeError):+ # A windowed bundle can hand out a closed or null stream. There is no+ # log file yet at hook time, so an unreportable warning is dropped on+ # purpose rather than killing a boot that still works.+ pass+++def _apply() -> None:+ if not (getattr(sys, "frozen", False) and hasattr(sys, "_MEIPASS")):+ return++ home = _user_data_dir()+ config_path = home / _CONFIG_FILE_NAME++ if not _is_set("JARVIS_CONFIG"):+ if not config_path.exists():+ bundled = Path(sys._MEIPASS) / _CONFIG_FILE_NAME # noqa: SLF001+ try:+ home.mkdir(parents=True, exist_ok=True)+ if bundled.is_file():+ shutil.copyfile(bundled, config_path)+ except OSError as exc:+ # Not silence: say it on stderr (a console CLI run shows it) and+ # continue. jarvis.core.config_writer creates the file on first+ # write anyway, so an unseeded config still boots on defaults.+ # A windowed bundle has no stderr yet — ensure_standard_streams()+ # runs later — so writing to it must never become the crash.+ _warn(f"could not seed {config_path}: {exc}")+ os.environ["JARVIS_CONFIG"] = str(config_path)++ if not _is_set("JARVIS_DATA_DIR"):+ os.environ["JARVIS_DATA_DIR"] = str(home / "data")+++_apply()diff --git a/tests/unit/packaging/__init__.py b/tests/unit/packaging/__init__.pynew file mode 100644index 0000000000..61f0e8f9e6--- /dev/null+++ b/tests/unit/packaging/__init__.py@@ -0,0 +1 @@+"""Tests for the packaging layer (PyInstaller spec helpers, installer scripts)."""diff --git a/tests/unit/packaging/test_frozen_runtime_hook.py b/tests/unit/packaging/test_frozen_runtime_hook.pynew file mode 100644index 0000000000..7b4468b398--- /dev/null+++ b/tests/unit/packaging/test_frozen_runtime_hook.py@@ -0,0 +1,150 @@+"""``packaging/pyinstaller_rthook_frozen.py`` — the frozen path redirection.++Why this file matters: the hook is what stops a natively installed app from+keeping the user's ``jarvis.toml`` and whole data tree inside its own program+directory, where an upgrade would overwrite the settings and an uninstall would+delete the memory. It cannot import ``jarvis`` (a runtime-hook exception kills a+windowed process before any logging exists), so it re-states the app-directory+convention — and the first test below is what stops that copy from drifting.+"""++from __future__ import annotations++import importlib.util+import sys+from pathlib import Path+from types import ModuleType++import pytest++from jarvis.core.paths import user_data_dir++HOOK_PATH = Path(__file__).resolve().parents[3] / "packaging" / "pyinstaller_rthook_frozen.py"+++def _load_hook() -> ModuleType:+ """Import the hook as a module. Its top-level ``_apply()`` is a no-op here.++ The hook returns immediately when ``sys.frozen`` is absent, which it is+ under pytest, so importing it has no side effects.+ """+ spec = importlib.util.spec_from_file_location("jarvis_rthook_frozen", HOOK_PATH)+ assert spec is not None and spec.loader is not None+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ return module+++def hook() -> ModuleType:+ return _load_hook()+++def frozen_bundle(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> tuple[Path, Path]:+ """Pretend to be a PyInstaller bundle with a per-user app directory."""+ meipass = tmp_path / "bundle" / "_internal"+ meipass.mkdir(parents=True)+ home = tmp_path / "AppData" / "Local"+ home.mkdir(parents=True)++ monkeypatch.setattr(sys, "frozen", True, raising=False)+ monkeypatch.setattr(sys, "_MEIPASS", str(meipass), raising=False)+ monkeypatch.setenv("LOCALAPPDATA", str(home))+ monkeypatch.delenv("JARVIS_CONFIG", raising=False)+ monkeypatch.delenv("JARVIS_DATA_DIR", raising=False)+ return meipass, home / "Jarvis"+++def test_hook_directory_matches_jarvis_core_paths(+ hook: ModuleType, monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ # The hook duplicates the convention on purpose; this is the gate that keeps+ # the duplicate honest. If jarvis.core.paths ever moves the app directory,+ # this fails instead of the frozen app quietly writing to the old place.+ monkeypatch.setenv("LOCALAPPDATA", str(tmp_path / "local"))+ assert hook._user_data_dir() == user_data_dir()++ monkeypatch.delenv("LOCALAPPDATA", raising=False)+ assert hook._user_data_dir() == user_data_dir()+++def test_apply_points_config_and_data_at_the_user_directory(+ hook: ModuleType, frozen_bundle: tuple[Path, Path], monkeypatch: pytest.MonkeyPatch+) -> None:+ meipass, home = frozen_bundle+ (meipass / "jarvis.toml").write_text("[app]\nname = 'bundled'\n", encoding="utf-8")++ hook._apply()++ import os++ assert Path(os.environ["JARVIS_CONFIG"]) == home / "jarvis.toml"+ assert Path(os.environ["JARVIS_DATA_DIR"]) == home / "data"+ # First run seeds the config from the copy inside the bundle, so the app+ # starts on the shipped defaults instead of an empty file.+ assert (home / "jarvis.toml").read_text(encoding="utf-8") == ("[app]\nname = 'bundled'\n")+++def test_apply_never_overwrites_an_existing_user_config(+ hook: ModuleType, frozen_bundle: tuple[Path, Path]+) -> None:+ meipass, home = frozen_bundle+ (meipass / "jarvis.toml").write_text("bundled\n", encoding="utf-8")+ home.mkdir(parents=True)+ (home / "jarvis.toml").write_text("the user's own settings\n", encoding="utf-8")++ hook._apply()++ # This is the whole point: an in-place upgrade reinstalls the bundled file+ # and must not touch what the user configured.+ assert (home / "jarvis.toml").read_text(encoding="utf-8") == ("the user's own settings\n")+++def test_apply_respects_an_explicit_override(+ hook: ModuleType, frozen_bundle: tuple[Path, Path], monkeypatch: pytest.MonkeyPatch+) -> None:+ meipass, home = frozen_bundle+ (meipass / "jarvis.toml").write_text("bundled\n", encoding="utf-8")+ monkeypatch.setenv("JARVIS_CONFIG", "D:/scratch/jarvis.toml")+ monkeypatch.setenv("JARVIS_DATA_DIR", "D:/scratch/data")++ hook._apply()++ import os++ assert os.environ["JARVIS_CONFIG"] == "D:/scratch/jarvis.toml"+ assert os.environ["JARVIS_DATA_DIR"] == "D:/scratch/data"+ # No seeding happens for an overridden path.+ assert not (home / "jarvis.toml").exists()+++def test_apply_does_nothing_outside_a_frozen_bundle(+ hook: ModuleType, monkeypatch: pytest.MonkeyPatch+) -> None:+ monkeypatch.delattr(sys, "frozen", raising=False)+ monkeypatch.delattr(sys, "_MEIPASS", raising=False)+ monkeypatch.delenv("JARVIS_CONFIG", raising=False)+ monkeypatch.delenv("JARVIS_DATA_DIR", raising=False)++ hook._apply()++ import os++ # A dev checkout keeps resolving its own paths; the hook is inert there.+ assert "JARVIS_CONFIG" not in os.environ+ assert "JARVIS_DATA_DIR" not in os.environ+++def test_apply_still_sets_the_path_when_seeding_fails(+ hook: ModuleType, frozen_bundle: tuple[Path, Path]+) -> None:+ meipass, home = frozen_bundle+ # No jarvis.toml inside the bundle: nothing to copy, but the app must still+ # be pointed at the writable location (config_writer creates the file).+ hook._apply()++ import os++ assert Path(os.environ["JARVIS_CONFIG"]) == home / "jarvis.toml"+ assert not (home / "jarvis.toml").exists()