@davoodmehraban89 / Aram-1 / commits / ffc9888
Fork 0

feat(desktop): Phase 8 offline desktop entrypoint + reproducible PyInstaller recipe

- desktop.py: per-user data dir, idempotent SQLite schema + D-07 triggers, FastAPI + bundled React workbench served on 127.0.0.1 only (zero network). database.reconfigure rebinds the shared engine to the local file at launch. - packaging/aram.spec (one-folder Aram.exe) + build_desktop.py (npm build -> PyInstaller) + README. Binary is a build artifact, never committed (§19). ADR-024. - 3 tests: DB init creates schema+triggers (idempotent), desktop app serves health + API end-to-end, data-dir override. Full suite: 308 passed; mypy clean. Live proof: desktop app serves bundled RTL workbench at / (200) + health ok. Co-authored-by: arena-agent <297053741+arena-agent@users.noreply.github.com>

davoodmehraban89 committed Dec 3, 2026 at 11:48 UTC ffc9888d6f055a22f8c751d073df6a6d747d3bc6
7 files changed +432 -1
backend/src/aram_backend/database.py
+14 -1
@@ -1,4 +1,5 @@
1 from collections.abc import Generator
2 +from typing import Any
3
4 from sqlalchemy import MetaData, create_engine, event
5 from sqlalchemy.engine import Engine
@@ -39,7 +40,7 @@ def ensure_triggers(engine: Engine) -> None:
40 install_on_engine(engine)
41
42
42 -def _enable_sqlite_foreign_keys(dbapi_connection, _connection_record) -> None:
43 +def _enable_sqlite_foreign_keys(dbapi_connection: Any, _connection_record: Any) -> None:
44 cursor = dbapi_connection.cursor()
45 cursor.execute("PRAGMA foreign_keys=ON")
46 cursor.close()
@@ -49,6 +50,18 @@ engine = build_engine()
50 SessionLocal = sessionmaker(bind=engine, expire_on_commit=False)
51
52
53 +def reconfigure(database_url: str) -> None:
54 + """Rebind the shared engine/session factory to a new database URL.
55 +
56 + Used by the desktop entrypoint to point at the per-user local SQLite file
57 + after import time. ``get_session`` reads ``SessionLocal`` at call time, so
58 + reassigning it here takes effect for all subsequent requests.
59 + """
60 + global engine, SessionLocal
61 + engine = build_engine(database_url)
62 + SessionLocal = sessionmaker(bind=engine, expire_on_commit=False)
63 +
64 +
65 def get_session() -> Generator[Session, None, None]:
66 with SessionLocal() as session:
67 yield session
backend/src/aram_backend/desktop.py new
+102
@@ -0,0 +1,102 @@
1 +"""Offline Windows desktop entrypoint (Phase 8, booklet §15).
2 +
3 +Runs the FastAPI backend and serves the bundled React workbench on 127.0.0.1
4 +(loopback only; zero runtime network). On first launch it initializes a local
5 +SQLite database (WAL, foreign keys ON) and the content-addressed source store in
6 +a per-user data directory, applying the schema and D-07 immutability triggers.
7 +
8 +The packaged executable (PyInstaller, see packaging/aram.spec) bundles this
9 +module, the migrations, and the built frontend (frontend/dist). No external
10 +service, browser plugin, or network access is required at runtime.
11 +"""
12 +
13 +from __future__ import annotations
14 +
15 +import os
16 +import sys
17 +from pathlib import Path
18 +
19 +from fastapi import FastAPI
20 +from fastapi.staticfiles import StaticFiles
21 +
22 +from aram_backend import __version__
23 +from aram_backend.admin_api import router as admin_router
24 +from aram_backend.config import get_settings
25 +from aram_backend.database import Base, build_engine, ensure_triggers
26 +from aram_backend.models import FiscalYearStatus, StatementType # noqa: F401 (register mappers)
27 +from aram_backend.schemas import HealthResponse
28 +from aram_backend.statement_api import router as statement_router
29 +
30 +
31 +def default_data_dir() -> Path:
32 + """Per-user data directory (override with ARAM_DATA_DIR)."""
33 + override = os.environ.get("ARAM_DATA_DIR")
34 + if override:
35 + return Path(override)
36 + if sys.platform == "win32":
37 + base = Path(os.environ.get("APPDATA", Path.home() / "AppData" / "Roaming"))
38 + return base / "Aram"
39 + return Path.home() / ".aram"
40 +
41 +
42 +def _bundled_frontend() -> Path | None:
43 + """Locate the built React workbench (PyInstaller _MEIPASS or repo dist)."""
44 + candidates = []
45 + meipass = getattr(sys, "_MEIPASS", None)
46 + if meipass:
47 + candidates.append(Path(meipass) / "frontend_dist")
48 + candidates.append(Path(__file__).resolve().parents[2] / "frontend_dist")
49 + candidates.append(Path(__file__).resolve().parents[3] / "frontend" / "dist")
50 + for candidate in candidates:
51 + if (candidate / "index.html").exists():
52 + return candidate
53 + return None
54 +
55 +
56 +def initialize_database(data_dir: Path) -> None:
57 + """Create the schema + triggers idempotently for a fresh local install."""
58 + data_dir.mkdir(parents=True, exist_ok=True)
59 + (data_dir / "source_store").mkdir(exist_ok=True)
60 + db_path = data_dir / "aram.db"
61 + engine = build_engine(f"sqlite:///{db_path}")
62 + Base.metadata.create_all(engine)
63 + ensure_triggers(engine)
64 + engine.dispose()
65 +
66 +
67 +def create_desktop_app() -> FastAPI:
68 + app = FastAPI(title="Aram Desktop", version=__version__)
69 + app.include_router(statement_router)
70 + app.include_router(admin_router)
71 +
72 + @app.get("/api/v1/health", response_model=HealthResponse, tags=["system"])
73 + def health() -> HealthResponse:
74 + return HealthResponse(status="ok", service="Aram Desktop", version=__version__)
75 +
76 + frontend = _bundled_frontend()
77 + if frontend is not None:
78 + app.mount("/", StaticFiles(directory=str(frontend), html=True), name="workbench")
79 + return app
80 +
81 +
82 +def main() -> None:
83 + import uvicorn
84 +
85 + from aram_backend.database import reconfigure
86 +
87 + data_dir = default_data_dir()
88 + initialize_database(data_dir)
89 + # Point the shared settings + engine at the local data dir before serving.
90 + db_url = f"sqlite:///{data_dir / 'aram.db'}"
91 + os.environ["ARAM_DATABASE_URL"] = db_url
92 + os.environ["ARAM_SOURCE_STORE_ROOT"] = str(data_dir / "source_store")
93 + get_settings.cache_clear()
94 + reconfigure(db_url)
95 +
96 + app = create_desktop_app()
97 + # Loopback only: the desktop app never exposes a network interface.
98 + uvicorn.run(app, host="127.0.0.1", port=int(os.environ.get("ARAM_PORT", "8765")), log_level="info")
99 +
100 +
101 +if __name__ == "__main__":
102 + main()
backend/tests/test_desktop.py new
+49
@@ -0,0 +1,49 @@
1 +"""Phase 8 desktop entrypoint: local DB init, triggers, loopback API serving."""
2 +
3 +from __future__ import annotations
4 +
5 +import sqlite3
6 +
7 +from fastapi.testclient import TestClient
8 +
9 +from aram_backend.database import reconfigure
10 +from aram_backend.desktop import create_desktop_app, default_data_dir, initialize_database
11 +
12 +
13 +def test_initialize_database_creates_schema_and_triggers(tmp_path):
14 + data_dir = tmp_path / "aram-data"
15 + initialize_database(data_dir)
16 + assert (data_dir / "aram.db").exists()
17 + assert (data_dir / "source_store").is_dir()
18 + conn = sqlite3.connect(str(data_dir / "aram.db"))
19 + try:
20 + triggers = {r[0] for r in conn.execute("SELECT name FROM sqlite_master WHERE type='trigger'")}
21 + tables = {r[0] for r in conn.execute("SELECT name FROM sqlite_master WHERE type='table'")}
22 + finally:
23 + conn.close()
24 + assert "ledger_balances" in tables
25 + assert "users" in tables
26 + assert any(t.startswith("aram_lock_") for t in triggers)
27 + assert "aram_audit_update" in triggers
28 + # Idempotent: a second init must not fail.
29 + initialize_database(data_dir)
30 +
31 +
32 +def test_desktop_app_serves_health_and_api(tmp_path):
33 + data_dir = tmp_path / "aram-data"
34 + initialize_database(data_dir)
35 + reconfigure(f"sqlite:///{data_dir / 'aram.db'}")
36 + app = create_desktop_app()
37 + with TestClient(app) as client:
38 + r = client.get("/api/v1/health")
39 + assert r.status_code == 200
40 + assert r.json()["status"] == "ok"
41 + # End-to-end through the desktop app's local DB.
42 + r = client.post("/api/v1/companies", json={"code": "D1", "name": "شرکت", "year": 1404})
43 + assert r.status_code == 200, r.text
44 + assert r.json()["year"] == 1404
45 +
46 +
47 +def test_default_data_dir_override(monkeypatch, tmp_path):
48 + monkeypatch.setenv("ARAM_DATA_DIR", str(tmp_path / "custom"))
49 + assert default_data_dir() == tmp_path / "custom"
docs/adr/ADR-024-desktop-packaging.md new
+57
@@ -0,0 +1,57 @@
1 +# ADR-024 — Offline desktop packaging (Phase 8)
2 +
3 +- Status: Accepted (Phase 8)
4 +- Date: 2026-12-03
5 +- Booklet: §15 Phase 8 (reproducible Windows package), §19 (no committed binaries)
6 +
7 +## Context
8 +
9 +The product must run as an offline Windows desktop/local application: the React
10 +workbench and the FastAPI backend together, on loopback only, with a local SQLite
11 +database and content-addressed source store, and zero runtime network. The package
12 +must be reproducible from source and reviewable; binaries are build artifacts, not
13 +committed source (booklet §19).
14 +
15 +## Decision
16 +
17 +### Desktop entrypoint (`aram_backend/desktop.py`)
18 +
19 +- `default_data_dir()`: per-user data directory (`%APPDATA%/Aram` on Windows,
20 + `~/.aram` elsewhere; override `ARAM_DATA_DIR`).
21 +- `initialize_database()`: idempotent `create_all` + D-07 triggers on a local
22 + SQLite file (WAL-capable, foreign keys ON via the shared engine), and creates the
23 + source-store directory.
24 +- `create_desktop_app()`: FastAPI with the statement + admin routers, a health
25 + endpoint, and the bundled React workbench mounted at `/` (StaticFiles html).
26 +- `main()`: initialize the DB, rebind the shared engine to the local file
27 + (`database.reconfigure`), and run uvicorn on **127.0.0.1** only (port `ARAM_PORT`,
28 + default 8765). No network interface is exposed.
29 +
30 +### Reproducible build (`packaging/`)
31 +
32 +- `build_desktop.py`: builds `frontend/dist` (npm ci + build), then runs PyInstaller.
33 +- `aram.spec`: one-folder PyInstaller package `dist/Aram/` (`Aram.exe` on Windows)
34 + bundling the backend, the built frontend as `frontend_dist`, migrations, and
35 + required data/hidden imports (sqlalchemy sqlite dialect, uvicorn, openpyxl,
36 + multipart). `console=True` keeps logs visible for review.
37 +- The Windows package is built on Windows from this recipe; CI/release produces the
38 + artifact. **No EXE/ZIP/binary is committed** (§19).
39 +
40 +## Consequences
41 +
42 +- A clean Windows machine runs `Aram.exe` with no Python, Node, or network needed;
43 + all data stays local under the per-user data dir.
44 +- The build is reproducible from source (pinned frontend lockfile + spec).
45 +- Loopback-only binding satisfies the zero-runtime-network constraint.
46 +- Schema is created idempotently on first launch; migrations are bundled for
47 + upgrade paths.
48 +
49 +## Rejected alternatives
50 +
51 +- One-file EXE: slower startup and trickier data-file resolution for FastAPI/uvicorn;
52 + one-folder is more reliable and inspectable.
53 +- Bundling a separate web server or requiring an installed Python/Node: violates the
54 + clean-environment, offline goal.
55 +- Committing the built EXE/ZIP: prohibited by §19 (large binaries); the recipe is the
56 + reviewable source of truth.
57 +- Binding 0.0.0.0: would expose a network interface; the desktop app is loopback-only.
packaging/README.md new
+47
@@ -0,0 +1,47 @@
1 +# Aram desktop packaging (Phase 8)
2 +
3 +Offline Windows desktop app: FastAPI backend + bundled React workbench on
4 +`127.0.0.1` only, local SQLite + content-addressed source store, zero runtime
5 +network. See `docs/adr/ADR-024-desktop-packaging.md`.
6 +
7 +## Build (reproducible)
8 +
9 +On Windows (for the Windows package):
10 +
11 +```bat
12 +python packaging\build_desktop.py
13 +```
14 +
15 +This builds `frontend/dist` (npm ci + build) and runs PyInstaller with
16 +`packaging/aram.spec`, producing `dist\Aram\Aram.exe`.
17 +
18 +Options:
19 +
20 +```bat
21 +python packaging\build_desktop.py --skip-frontend :: reuse existing frontend/dist
22 +python packaging\build_desktop.py --skip-pyinstaller :: only build the frontend
23 +```
24 +
25 +Manual PyInstaller (after the frontend is built):
26 +
27 +```bat
28 +pip install pyinstaller
29 +pyinstaller packaging\aram.spec --noconfirm
30 +```
31 +
32 +## Run
33 +
34 +```bat
35 +dist\Aram\Aram.exe
36 +```
37 +
38 +Then open `http://127.0.0.1:8765/`. Data lives under `%APPDATA%\Aram`
39 +(override with `ARAM_DATA_DIR`; port with `ARAM_PORT`).
40 +
41 +## Notes
42 +
43 +- The executable/ZIP is a **build artifact** and is never committed (booklet §19).
44 + CI/release builds it from this recipe; the spec + build script are the reviewable
45 + source of truth.
46 +- Loopback-only binding; no network interface is exposed.
47 +- First launch creates the schema + immutability triggers idempotently.
packaging/aram.spec new
+95
@@ -0,0 +1,95 @@
1 +# -*- mode: python ; coding: utf-8 -*-
2 +"""PyInstaller spec for the Aram offline desktop app (Phase 8, ADR-024).
3 +
4 +Build (from the repo root, after `python packaging/build_desktop.py` prepares
5 +frontend/dist):
6 +
7 + pyinstaller packaging/aram.spec --noconfirm
8 +
9 +Produces a one-folder Windows package `dist/Aram/` whose `Aram.exe` runs the
10 +FastAPI backend + bundled React workbench on 127.0.0.1 only. No runtime network.
11 +The binary is a build artifact and is NOT committed (booklet §19); CI/release
12 +builds it from this reproducible recipe.
13 +"""
14 +
15 +import sys
16 +from pathlib import Path
17 +
18 +from PyInstaller.utils.hooks import collect_data_files, collect_submodules
19 +
20 +ROOT = Path(SPECPATH).resolve().parent
21 +BACKEND_SRC = ROOT / "backend" / "src"
22 +FRONTEND_DIST = ROOT / "frontend" / "dist"
23 +
24 +block_cipher = None
25 +
26 +# Bundle the built React workbench as frontend_dist (served at / by desktop.py).
27 +datas = []
28 +if FRONTEND_DIST.exists():
29 + datas.append((str(FRONTEND_DIST), "frontend_dist"))
30 +# Bundle Alembic migrations + config for upgrade paths.
31 +migrations = ROOT / "backend" / "migrations"
32 +if migrations.exists():
33 + datas.append((str(migrations), "migrations"))
34 +alembic_ini = ROOT / "backend" / "alembic.ini"
35 +if alembic_ini.exists():
36 + datas.append((str(alembic_ini), "."))
37 +# openpyxl / sqlalchemy / uvicorn data files.
38 +datas += collect_data_files("openpyxl")
39 +datas += collect_data_files("uvicorn")
40 +
41 +hiddenimports = []
42 +hiddenimports += collect_submodules("aram_backend")
43 +hiddenimports += collect_submodules("sqlalchemy")
44 +hiddenimports += collect_submodules("uvicorn")
45 +hiddenimports += [
46 + "sqlalchemy.dialects.sqlite",
47 + "sqlite3",
48 + "multipart",
49 + "python_multipart",
50 +]
51 +
52 +a = Analysis(
53 + [str(BACKEND_SRC / "aram_backend" / "desktop.py")],
54 + pathex=[str(BACKEND_SRC)],
55 + binaries=[],
56 + datas=datas,
57 + hiddenimports=hiddenimports,
58 + hookspath=[],
59 + hooksconfig={},
60 + runtime_hooks=[],
61 + excludes=["tkinter", "pytest", "hypothesis", "mypy", "ruff"],
62 + win_no_prefer_redirects=False,
63 + win_private_assemblies=False,
64 + cipher=block_cipher,
65 + noarchive=False,
66 +)
67 +pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher)
68 +
69 +exe = EXE(
70 + pyz,
71 + a.scripts,
72 + [],
73 + exclude_binaries=True,
74 + name="Aram",
75 + debug=False,
76 + bootloader_ignore_signals=False,
77 + strip=False,
78 + upx=False,
79 + console=True, # keep logs visible for review; flip to False for a windowed build
80 + disable_windowed_traceback=False,
81 + argv_emulation=False,
82 + target_arch=None,
83 + codesign_identity=None,
84 + entitlements_file=None,
85 +)
86 +coll = COLLECT(
87 + exe,
88 + a.binaries,
89 + a.zipfiles,
90 + a.datas,
91 + strip=False,
92 + upx=False,
93 + upx_exclude=[],
94 + name="Aram",
95 +)
packaging/build_desktop.py new
+68
@@ -0,0 +1,68 @@
1 +#!/usr/bin/env python3
2 +"""Reproducible desktop build (Phase 8, ADR-024).
3 +
4 +Steps:
5 + 1. Build the React workbench (frontend/dist) with npm.
6 + 2. Run PyInstaller with packaging/aram.spec to produce dist/Aram/.
7 +
8 +Run on Windows to produce the Windows package (Aram.exe). The binary is a build
9 +artifact and is never committed (booklet §19). Use --skip-frontend to reuse an
10 +existing frontend/dist, and --skip-pyinstaller to only build the frontend.
11 +
12 +Usage:
13 + python packaging/build_desktop.py
14 + python packaging/build_desktop.py --skip-frontend
15 +"""
16 +
17 +from __future__ import annotations
18 +
19 +import argparse
20 +import shutil
21 +import subprocess
22 +import sys
23 +from pathlib import Path
24 +
25 +ROOT = Path(__file__).resolve().parents[1]
26 +FRONTEND = ROOT / "frontend"
27 +SPEC = ROOT / "packaging" / "aram.spec"
28 +
29 +
30 +def _run(cmd: list[str], cwd: Path) -> None:
31 + print("+", " ".join(cmd), flush=True)
32 + subprocess.run(cmd, cwd=cwd, check=True)
33 +
34 +
35 +def build_frontend() -> None:
36 + npm = shutil.which("npm")
37 + if npm is None:
38 + raise SystemExit("npm is required to build the frontend")
39 + _run([npm, "ci", "--no-audit", "--no-fund"], FRONTEND)
40 + _run([npm, "run", "build"], FRONTEND)
41 + if not (FRONTEND / "dist" / "index.html").exists():
42 + raise SystemExit("frontend build did not produce dist/index.html")
43 +
44 +
45 +def build_package() -> None:
46 + pyinstaller = shutil.which("pyinstaller")
47 + if pyinstaller is None:
48 + raise SystemExit("pyinstaller is required (pip install pyinstaller)")
49 + _run([pyinstaller, str(SPEC), "--noconfirm"], ROOT)
50 + out = ROOT / "dist" / "Aram"
51 + print(f"Package built: {out}")
52 + if sys.platform == "win32":
53 + print(f"Windows executable: {out / 'Aram.exe'}")
54 +
55 +
56 +def main() -> None:
57 + parser = argparse.ArgumentParser(description=__doc__)
58 + parser.add_argument("--skip-frontend", action="store_true")
59 + parser.add_argument("--skip-pyinstaller", action="store_true")
60 + args = parser.parse_args()
61 + if not args.skip_frontend:
62 + build_frontend()
63 + if not args.skip_pyinstaller:
64 + build_package()
65 +
66 +
67 +if __name__ == "__main__":
68 + main()