Desktop App Architecture

This page is for developers. It explains how the DigiQual app is put together, how the Windows and macOS installers are built, and why it’s built this way. To use the app, see Launch the App.

1 The Short Version

  • All of the app’s code lives in the digiqual package, in the digiqual.gui subpackage. It ships inside the normal digiqual wheel on PyPI, so pip install digiqual always includes the app.
  • The desktop installers are that same wheel, installed into a self-contained Python by Briefcase. The top-level app/ folder holds only Briefcase’s configuration and a two-line entry point; there’s no app code in it.

So any change to the app goes into src/digiqual/gui/, and every way of launching the app picks it up.

2 Where Everything Lives

src/digiqual/
├── gui/                        ← the app (a normal subpackage of digiqual)
│   ├── __init__.py
│   ├── __main__.py             ← makes `python -m digiqual.gui` work
│   ├── app.py                  ← the page shell (header, stepper, hidden navset of stages) + server()
│   ├── components.py           ← STAGES (order and names), the stage page template, shared helpers
│   ├── state.py                ← per-session shared state, invalidation and the explorer settings
│   ├── stepper.py              ← the workflow stepper: status rules (pure function) and rendering
│   ├── start_page.py           ← the start page (entry cards and stage overview)
│   ├── about_page.py           ← the About page (version, links, papers, funders)
│   ├── stage_design.py         ← 1. Simulation Design (UI + server logic)
│   ├── stage_data.py           ← 2. Data Diagnostics
│   ├── stage_model.py          ← 3. Model Diagnostics (Run models: background fit with progress)
│   ├── stage_explorer.py       ← 4. Model Explorer
│   ├── stage_pod.py            ← 5. PoD Analysis
│   ├── background.py           ← runs slow steps in a worker thread; progress tracking and panel
│   ├── launcher.py             ← starts the server and opens the window (with its Help menu)
│   └── www/                    ← static files served by Shiny: app.css, favicon.png, the funder
│                                 logos and, if downloaded, mathjax-tex-svg.js
├── _digiqual_cpp.*.so / .pyd   ← compiled C++ extension (built by setup.py)
└── ...                         ← the statistical library itself

app/                            ← Briefcase wrapper only (not part of the wheel)
├── pyproject.toml              ← [tool.briefcase] config: name, version, icon, platform options
├── .python-version             ← Python used for desktop builds (3.12)
├── src/digiqual_desktop/
│   └── __main__.py             ← entry point: sets sys.frozen, calls launcher.main()
├── icons/                      ← app icons (.icns / .ico / .png), generated
└── *.csv                       ← example datasets for trying the app

scripts/make_icon.py            ← draws the icon; writes app/icons/, gui/www/favicon.png, docs/www/
.github/workflows/build_app.yml ← builds, self-tests and packages the installers

The static files in gui/www/ are included in the wheel by package_data in setup.py and MANIFEST.in. app.py finds them relative to its own location, so this works the same installed or from a checkout.

MathJax (which renders the model equation) is not kept in the repository. mathjax-tex-svg.js is downloaded into www/ at build time, by just fetch_mathjax or the build_app.yml workflow, so the desktop app works offline. Without it, app.py loads MathJax from a CDN instead.

3 How Results Flow Between Stages

Each stage’s results depend on the stages before it. state.py holds the per-session AppState, and register_shared() keeps the study in sync with the data: a new file or column choice builds a new SimulationStudy and calls AppState.invalidate("data"), which clears every result. invalidate("diagnostics") clears only the diagnostics (the model doesn’t use them).

flowchart LR
    D[Data + columns<br/>study_instance] --> G[Diagnostics<br/>diagnostic_table]
    G -. unlocks .-> C[Candidate models<br/>candidates_ready]
    D --> C
    C --> M[Chosen model<br/>model_fit]
    M --> E[Explorer settings<br/>explorer_config]
    E --> A[Applied PoD setup<br/>applied_structure]
    A --> U[Bootstrap<br/>uq_result]

  • New data or columns clear everything. Changing a diagnostic threshold only marks the diagnostics as out of date (diagnostics_stale).
  • The candidate models are cross-validated once per dataset, when the user presses Run models in Model Diagnostics (which needs the diagnostics to have run). candidates_ready is then set, and model_fit holds the study.fit_model() result for the chosen model.
  • explorer_config (a reactive.calc) is the single source of the model, the plotted, integrated and sliced variables and the threshold. AppState.structure(config) is the part that needs the Update PoD button (model, plotted and integrated variables, distributions and ranges); after Update PoD it is stored as applied_structure. When the current structure differs from it, the explorer asks for Update PoD and the PoD Analysis stage won’t run. Slices and the threshold are not part of it: they update the plots live. Choosing another model therefore needs Update PoD, like a role change, and marks the bootstrap out of date.
  • The bootstrap result (uq_result) is a record of everything the run used: config (the explorer settings), fit (model metrics, equation, name and dropdown choice), settings (iterations, n_jobs, target PoD and confidence, CSV name, columns and diagnostic thresholds), results (the pod() output) and spectrum (the threshold spectrum, for one plotted variable). When config no longer matches explorer_config, the PoD Analysis stage marks the result as out of date instead of discarding it. The exports are built from this record.

3.1 From app settings to library calls

state.analysis_kwargs(study, config) is the single translation from an explorer config to study.pod() arguments: poi_col, nuisance_col, slice_values, nuisance_dists, nuisance_bounds, and model_override / force_degree from the config’s model key (via core.model_key_args). AppState.pod_kwargs() is a thin wrapper around it. Two other module-level helpers go with it: nuisance_dists_for() fits the chosen distributions (one that can’t be fitted is left out, so that variable is integrated uniformly) and column_values() gives a column’s numeric values. Update PoD, the live updates and the bootstrap all use it.

3.2 Background tasks

The three slow steps (Run models or a model change, Update PoD, the bootstrap) run in a worker thread as reactive.extended_tasks, so the page stays live. While a task runs, fit_running / pod_running / uq_running in AppState are set, the stepper shows a spinner, and the explorer’s live updates pause so nothing else changes the study. background.py provides the pieces:

  • TaskProgress follows one task: the library’s log messages from its thread (which mark its steps) and its (done, total, label) progress callback (fit_model and pod take one).
  • step_states(reached, n) turns “how far it got” into each step’s state (done, active, todo).
  • progress_panel() draws the panel once: spinner, elapsed time, bar and steps.
  • push_progress() then updates it in place twice a second through a custom message, handled in the browser by PROGRESS_JS (added to the page head in app.py). Redrawing the panel instead would restart its spinners.

4 Ways the App Gets Launched

Every route ends up in the same function, digiqual.gui.launcher.main():

How it’s started Path to launcher.main()
Desktop app (MSI / zip / DMG) Briefcase’s executable → digiqual_desktop/__main__.py → main()
digiqual command (uv tool install, uvx digiqual) [project.gui-scripts] in pyproject.toml → main()
dq_ui() in Python / Jupyter starts python -m digiqual.gui in a new process → main()
python -m digiqual.gui gui/__main__.py → main()
just app (from a checkout) uv run python -m digiqual.gui → main()
just app_dev shiny run digiqual.gui.app:app: browser only, skips the launcher (for UI work)

5 What launcher.main() Does

flowchart TD
    A[main] --> B{Started as a multiprocessing<br/>worker or resource tracker?}
    B -- yes --> C[Run that task, then exit]
    B -- no --> D[Set up logging to digiqual.log<br/>Point empty stdout/stderr at it]
    D --> E{--self-test?}
    E -- yes --> F[Check C++ extension, pywebview,<br/>worker processes and HTTP server<br/>Exit 0 or 1]
    E -- no --> G[Start the Shiny server on a free<br/>127.0.0.1 port, in a background thread]
    G --> H[Wait until it answers HTTP]
    H --> I[Open a pywebview window<br/>WebView2 on Windows, WebKit on macOS]
    I -- fails --> J[Fall back to an Edge app window on Windows,<br/>otherwise the default browser]

launcher.py keeps its module-level imports light (shiny and pywebview are only imported inside functions), because worker processes import it before they know they are workers.

6 Why It’s Built This Way

These are the decisions most likely to puzzle someone reading the code, with the reason for each.

6.1 Briefcase rather than PyInstaller

PyInstaller freezes an app: it analyses imports to decide which files to bundle. That missed Shiny’s static files, pythonnet’s DLLs and some hidden imports, which needed a long hand-maintained .spec file. Briefcase instead runs pip install into a bundled, standalone Python. The app therefore gets exactly the files a normal install would, including the prebuilt C++ extension from the digiqual wheel. Nothing has to be listed by hand.

6.2 Worker processes and sys.frozen

The PoD bootstrap runs in parallel with joblib (backend="multiprocessing"), which starts worker processes by running sys.executable again. In the desktop app, sys.executable is the DigiQual app itself, not python, and it can’t run python -c "..." commands. Without special handling, every worker would open another DigiQual window.

To prevent this, digiqual_desktop/__main__.py sets sys.frozen = True. That makes Python’s multiprocessing start workers as DigiQual --multiprocessing-fork .... The first thing launcher.main() does is spot those arguments, and the -c commands used by Python’s and joblib’s resource trackers, and run the requested task instead of the app. This mirrors what PyInstaller’s runtime hooks do.

6.3 Redirecting stdout and stderr

A desktop app has no console, so sys.stdout and sys.stderr are None. uvicorn, the web server under Shiny, calls .isatty() on them while setting up logging, and crashes the server thread. The window then shows a blank page. The launcher points them at the log file before starting the server.

6.4 Build details in build_app.yml

Detail Reason
Python 3.12 pywebview’s Windows backend needs pythonnet, which supports up to Python 3.13.
macOS 12.0 minimum (min_os_version) scipy and scikit-learn only publish Apple Silicon wheels for macOS 12+.
The digiqual wheel is built in the job and passed to Briefcase with -C requires=[...] PyPI has an identically named wheel, and pip may otherwise choose that one. The installers must contain the code being built.
A proxy_tools wheel is built in the job pywebview needs proxy_tools, which is only published as source code. Briefcase installs wheels only, so without this pip silently falls back to the ancient pywebview 3.4, which has no menu support. pywebview>=5.0 in pyproject.toml makes that fail loudly instead.
Self-test runs without redirected output It behaves like a user double-clicking the app, so the stdout/stderr problem above would be caught.

7 The Build Pipeline

.github/workflows/build_app.yml runs on Windows and macOS:

  1. Build the digiqual wheel for Python 3.12 with cibuildwheel. This is the same C++ build that goes to PyPI.
  2. Build a proxy_tools wheel.
  3. briefcase create and briefcase build: the standalone Python, the app executable, and every dependency installed from wheels.
  4. Run DigiQual --self-test, which must exit 0.
  5. briefcase package: an MSI and a portable zip on Windows, a DMG on macOS. Signing is ad hoc (no certificate) for now.
  6. Upload them as run artifacts.

It runs in two situations:

  • Manually (just trigger_build, or Actions → Build App Executables → Run workflow): this stops at the run artifacts, which you need to be logged in to GitHub to download.
  • On a version tag (vX.Y.Z, pushed by just patch / just minor): an extra job creates the GitHub Release, if it doesn’t exist yet, and attaches the installers. The download instructions link to /releases/latest.

The version comes from app/pyproject.toml, which just bump keeps in step with the package version.

8 Working on the App Locally

Task Command
Run the app in a browser, without the launcher (restart it to see code changes) just app_dev
Run the full desktop window from your checkout just app
Check the C++ extension, workers and server, without a window uv run python -m digiqual.gui --self-test
Build the desktop app on your own machine uv tool install briefcase, then just build_app_local
Build the installers in CI gh workflow run build_app.yml --ref <branch>
Change the icon Edit scripts/make_icon.py, then run uv run python scripts/make_icon.py

--self-test results, and everything the app prints, go to the log file:

  • Windows: %LOCALAPPDATA%\Digiqual\digiqual.log
  • macOS: ~/Library/Logs/Digiqual/digiqual.log
  • Linux: ~/.local/share/Digiqual/digiqual.log

9 Common Changes

Adding a dependency. Add it to dependencies in the root pyproject.toml; the desktop app picks it up through the wheel. Check that it publishes wheels for Windows x64, macOS arm64 (macOS 12+) and Python 3.12. If it only publishes source, the desktop build fails or falls back to an older version; build a wheel of it in build_app.yml the way proxy_tools is.

Adding a static file (an image, CSS or JavaScript) to the app: put it in src/digiqual/gui/www/ and refer to it by file name (e.g. src="my_image.png"). It is packaged automatically.

Adding a page or feature to the app: edit the relevant stage_*.py module. Each builds its page with components.stage_page() (settings sidebar, results, Back / Next) and has a register(...) function with its server logic; shared reactive state lives in state.py. A new stage is a new module, added to STAGE_MODULES in app.py, to STAGES in components.py (which names the stages everywhere: stepper, start page, buttons), to the status rules in stepper.stage_statuses and, if those rules need new state, to snapshot() in stepper.register. A page that is not a stage (like Start and About) is a ui.nav_panel added to the navset_hidden in app.py and to the ("start", "about") check in stepper_ui, which hides the stepper on it. Navigation needs no server code per button: components.nav_button() sets the goto_stage input from the browser and one effect in stepper.py switches stage. Prefer calling library functions (and digiqual.defaults for default values) over re-implementing statistics in the GUI. Nothing in app/ or the workflow needs to change.

The desktop menu. The native window has a Help menu with View Documentation (opens the docs site in the browser) and About DigiQual (the version). It is defined in launcher.launch_webview_window, so it only exists in the pywebview window, not in a browser.