""" paths.py — Shared writable-directory resolution (the MSIX §3.5 fix). A normal install runs with the app root writable, so user data and third-party binaries live next to the app (./user_data, ./third_party). MSIX/Store installs land in C:\\Program Files\\WindowsApps\\... which is READ-ONLY for the app — writing there fails at startup. In that case both directories are redirected under %LOCALAPPDATA%\\LocalAiLab\\ so the packaged app still works from the Store (see §3.5 of MICROSOFT_STORE_DEPLOYMENT.md). Every module that resolves user_data/ or third_party/ MUST go through user_data_dir() / third_party_dir() here — never re-derive the paths (AGENTS.md anti-duplication rule). These are the single source of truth for where user state and downloaded binaries live. """ import os import sys from pathlib import Path def _app_root() -> Path: """The folder the app is installed/run from. - Source/dev runs: the repo root (where app.py / run_webview.py live). - PyInstaller-frozen runs: the folder containing LocalAiLab_App.exe. The spec sets contents_directory="internal", so sys._MEIPASS points at /internal — its parent is the real app folder. """ if getattr(sys, "frozen", False): return Path(sys._MEIPASS).parent return Path(__file__).resolve().parent.parent APP_ROOT = _app_root() def _app_root_writable() -> bool: """True when the app root accepts writes (dev repo, loose dist folder, per-user install). MSIX/Store installs under C:\\Program Files\\WindowsApps are ACL-protected read-only, so the probe fails there and user data is redirected to %LOCALAPPDATA%. A REAL write probe is used rather than os.access() because Windows access checks can lie for restricted tokens — the app must never assume a path is writable and then crash on its first real write (AGENTS.md: "the app MUST always launch"). """ probe = APP_ROOT / ".localailab_write_probe" try: probe.write_text("", encoding="ascii") probe.unlink() return True except OSError: return False # Computed once at import — every consumer module derives its constants # from this single decision. _APP_ROOT_WRITABLE = _app_root_writable() def _localappdata_base() -> Path: base = os.environ.get("LOCALAPPDATA") if base: return Path(base) # LOCALAPPDATA is normally always set on Windows; this fallback keeps # the app launching on the rare system where it is missing. return Path.home() / "AppData" / "Local" # %LOCALAPPDATA%\\LocalAiLab — the per-user writable home for a packaged # (MSIX / Program Files) install. LOCALAI_LAB_APP_DATA = _localappdata_base() / "LocalAiLab" def user_data_dir() -> Path: """Writable root for user state: config, .env, ChromaDB, reports, visual index, GGUF downloads, ...""" if _APP_ROOT_WRITABLE: return APP_ROOT / "user_data" return LOCALAI_LAB_APP_DATA / "user_data" def third_party_dir() -> Path: """Writable root for downloaded third-party binaries (llama-server, whisper-server, poppler).""" if _APP_ROOT_WRITABLE: return APP_ROOT / "third_party" return LOCALAI_LAB_APP_DATA / "third_party"