Repository navigation
Architecture Frontends and Desktop
Written against d5aad1f44 on 19 Nov 2026.
In short. Conductor has one React single-page app and one Electron shell. frontend/ is the app: the wheel, the Docker image and the desktop app all serve its build from the same origin as the API. It calls the API only through frontend-sdk/, a client generated from the OpenAPI contract. desktop/ is an Electron shell that carries its own Python, starts the same tz-ps-conductor serve as a child process, shows the web app in a window, and updates itself from GitHub releases on one of four channels.
This diagram shows which package depends on which, and what each shipped artefact is built from.
flowchart LR
CT["contracts/openapi and contracts/grammar"] --> SDK["frontend-sdk<br/>@tz-ps-conductor/sdk"]
SDK -->|"file dependency"| FE["frontend<br/>the React app, port 3000"]
FE -->|"make bundle"| ST["tz_ps_app/static"]
ST --> WH["wheel, Docker image, desktop payload"]
DT["desktop<br/>Electron shell"] -->|"spawns and shows"| WH
Each directory has its own CLAUDE.md with its rules, its own Makefile, and its own pnpm-lock.yaml. There is no pnpm workspace across them: the app holds a copy of the SDK that only its own pnpm updates.
| Package | Node | Stack | Shipped |
|---|---|---|---|
frontend/ |
>=24 |
React 19, Vite 8, TypeScript 7, TanStack Router, Query and Form, shadcn on Base UI, Tailwind 4, AG Grid Community, uPlot, xyflow, Biome | Yes |
frontend-sdk/ |
>=24 |
Orval, antlr-ng, TypeScript source with no build | Inside the app |
desktop/ |
>=22.18 <23 or >=23.6
|
Electron 45, electron-builder 26, electron-updater 6, Playwright | Yes |
frontend-sdk/ is the package @tz-ps-conductor/sdk. Orval generates src/generated/ from contracts/openapi/core-api.yaml: a typed client, TanStack Query hooks and query-option builders, MSW handlers and faker factories, in one folder per API tag. antlr-ng generates the expression parser in src/expressions/generated/ from contracts/grammar/. How the contract is produced and checked is on HTTP API and contracts; this page covers only how the app consumes it.
What an app developer needs to know:
-
Never hand-write a request or restate a contract type. Change the contract, run
make -C frontend-sdk api, and use the generated hook.make -C frontend-sdk grammardoes the same for the expression grammar. Both end withmake refresh, which updates the app's copy and clears Vite's pre-bundle. A running dev server needs a restart. -
The package ships TypeScript source. The app's Vite and
tsccompile it, so it must type-check under the app'stsconfig. Its one environment read isimport.meta.env.VITE_API_BASE_URL, default/api. -
It is installed as
file:../frontend-sdk, neverlink:. A symlink resolves@tanstack/react-queryfrom the SDK's ownnode_modules, the app then holds two copies, and every hook fails with "No QueryClient set".src/sdk.test.tschecks for one copy. -
The hand-written code is small:
src/client.tsandsrc/expressions/(checking, completion, highlighting and the function reference for expressions, with no React). -
Mocks stay out of the build. The
*.msw.tsand*.faker.tsfiles are imported only by tests.make -C frontend mocks-checkgreps the production build for them.
customFetch in frontend-sdk/src/client.ts carries every request the generated code makes. The one other path to the API is a file download: the browser follows a link built with the SDK's apiUrl, as exportInBackground in frontend/src/features/networks/network-export.ts does, so a large file is written to disk as it arrives. customFetch prefixes the base URL, returns a Blob for a successful non-JSON answer such as a CSV, and throws ApiError(status, body) for any non-2xx answer. The body is the server's problem document, and Orval types every hook's error as ApiError<Problem>.
The dependency rule is routes -> features -> { ui, sdk }. frontend/biome.json holds it as noRestrictedImports overrides, so make lint fails on a violation.
| Layer | Holds | May import |
|---|---|---|
src/ui |
The design system: shadcn CLI output and a few hand-written, domain-free components | Only src/ui
|
src/lib |
Domain-free helpers and the three library wrappers |
src/lib, src/ui, the SDK |
src/features |
Everything that knows a network, a run or a component |
src/features, src/lib, src/ui, the SDK |
src/routes |
Routing and wiring only | Anything but src/test
|
The overrides match only the #/ and @/ aliases and the SDK's package name, so cross a layer through an alias; a relative import that climbs into another layer is not caught. The redesign bans ../ outright.
Three third-party libraries are each confined to one wrapper, and the rest of the app uses the wrapper:
| Library | Wrapper | Used as |
|---|---|---|
| AG Grid Community | src/lib/data-grid |
DataGrid<TRow> |
| uPlot | src/lib/chart |
LineChart |
| xyflow | src/lib/flow |
FlowGraph |
The grid wrapper keeps its own cell range, clipboard and paste, because the Community edition has none. It imports nothing from the SDK and passes no enterprise option through, so a licensed fork can replace edition.ts alone.
Routing is file-based under src/routes, and src/routeTree.gen.ts is generated by vite dev and vite build. Every page sits under the pathless _shell layout, which draws the explorer rail, header and breadcrumbs.
| URL | Page |
|---|---|
/ |
Redirects to /projects
|
/projects |
Projects home |
/projects/$project |
A project: its networks and workflow runs |
/projects/$project/networks/$name |
A network: time axis, constraints, status |
…/components, …/components/$type
|
The component grid for one component type |
…/components/$type/series, …/series/$attribute
|
Series for a type, and one attribute across the type |
…/statistics |
Built-in and custom statistics |
…/versions, …/versions/$version, …/versions/compare
|
History, one version, a comparison |
/runs, /runs/$id, /runs/compare
|
Runs, one run with its results and log, a comparison |
/workflow-runs/$id |
A workflow run as a graph |
A route file holds no logic: its loader calls a load function from src/features, and its component renders a feature's page. Every page route sets its own pendingComponent, errorComponent and notFoundComponent, because the router draws those in place of the route that set them; set on _shell alone they would replace the rail and header (src/routes/CLAUDE.md).
This diagram follows one page from its route to the API and back, including the error path.
flowchart LR
R["Route loader"] -->|"ensureQueryData with suspense query options"| QC["QueryClient<br/>staleTime 30 s, no retry on 4xx"]
R --> P["Feature page"]
P -->|"useSuspenseQuery, same options"| QC
P --> UI["src/ui and the wrappers"]
P -->|"generated mutation hook"| GEN["SDK generated code"]
QC --> GEN
GEN --> CF["customFetch"]
CF -->|"fetch under /api"| API["Backend"]
CF -->|"non-2xx"| ERR["ApiError with the problem document"]
ERR --> MP["mapProblem, toastProblem, notFoundFrom"]
P --> IDB["Draft in IndexedDB"]
-
Loaders prefetch, components read the cache. A loader calls
ensureQueryData(getXSuspenseQueryOptions(...))for what the page cannot render without andvoid prefetchQuery(...)for the rest. The component callsuseSuspenseQuerywith the same options. Nobody writes a hook around a generated builder. - A write invalidates by the generated query key. The rail and the pages read the same queries, so one invalidation refreshes both.
-
A long job is polled outside React. An import or export is followed with
settleJob(src/lib/settle-job.ts), notuseQuery, so the wait survives its dialog closing; one toast (progressToast) then follows the job. -
Edits are a draft. Component and series edits for a network are one IndexedDB record, kept in step across tabs (
src/features/components/draft/), with one Save, one Discard and an undo history 20 drafts deep. -
Calls are same-origin. In development Vite proxies
/apitoVITE_API_PROXY_TARGET(defaulthttp://localhost:8080); otherwisetz_ps_appserves the build and the API from one process.
The server refuses a request with a problem document: a type URL ending in a slug, a detail sentence, and for a validation failure an errors list of location and message. src/features/forms/problem.ts is the only reader:
| Function | Use |
|---|---|
readProblem |
Checks that an error is an ApiError whose body has the document's shape |
mapProblem(error, fields) |
For a form. A validation error goes to the field its location names; otherwise the slug picks a field (project-exists and network-exists go to name, unknown-framework to framework, unknown-file-format to format, file-too-large to file); anything else is a message for the whole form |
toastProblem |
For a write with no form, such as an edit in place or a confirmed delete |
notFoundFrom (src/features/shell/shell-not-found.tsx) |
In a loader, turns a 404 into the page's not-found |
A form is made with useAppForm (src/features/forms/app-form.ts). Server refusals are held beside the form by useRefusal, not in its error map, and a field's refusal clears when that field is edited. The slug is matched as a fixed value; the detail text is shown as the server wrote it.
The app learns what the server can do from GET /api/capabilities, never from the shape of another response; the capability model is on HTTP API and contracts. The readers are in src/features/capabilities/capabilities.ts. A loader that depends on a capability calls loadCapabilities, which reads it again on every navigation, so an open tab notices a server restarted onto other storage. A component reading from the cache goes through a helper such as keepsHistory, which counts a pending or failed read as available.
All paths are under frontend/src/features.
| Area | Directory or files |
|---|---|
| Shell, breadcrumbs, window file drop | shell/ |
| Explorer rail | explorer/ |
| Projects | projects/ |
| Networks: page, list, create, copy, rename, delete, time axis, snapshot weightings | networks/ |
| Network file import and export, folder import |
networks/network-import.ts, folder-imports.ts, import-networks-dialog.tsx, network-export.ts
|
| Run dialog |
networks/run-network.tsx, runs/run-method-field.tsx, runs/solve-options-fields.tsx
|
| Runs, results, solver log, comparison | runs/ |
| Component grid, add, delete, CSV import, draft, save, rebase | components/ |
| Series editing, CSV fitting, statistics tiles | series/ |
| Custom constraints and the expression editor |
networks/constraint-*.tsx, networks/expression-*, src/lib/expressions/
|
| Statistics page | statistics/ |
| Version history, compare, restore | versions/ |
| Workflow runs | workflow-runs/ |
| Cost calculator | costs/ |
| Update banner and the desktop bridge | updates/ |
| Product tips (Userpilot), feedback |
product-tips/, feedback/
|
frontend/CLAUDE.md carries a long "Shared pieces" table naming the one component or function to use for each recurring need; a second copy of any of them is a review finding. Read it before writing a new helper.
Components are added with pnpm dlx shadcn@latest add <component> and land flat in src/ui/components/. The primitives are Base UI and the icons Phosphor; Radix and Lucide are banned by import rule. The app has light and dark themes. Text is inline British English in sentence case, and dates go through formatDate in src/lib/format-date.ts; the redesign moves both to Lingui, as the next section describes.
The test suites are described on Testing philosophy and Testing review.
The redesign is built in frontend-next/ and is merged into frontend/ once it reaches feature parity. The design team's prototype decides what the modeller sees and does, and the sections above remain the reference for behaviour: routes, state, validation, errors, and every option the API offers. These are the improvements it brings to the frontend. Each is in place in frontend-next/ today, and a path in this section is relative to that folder until the merge.
| Area | What improves |
|---|---|
| Text | Every string goes through Lingui, so the app can be translated |
| Rules | A rule a tool can enforce is a lint rule with a test, not prose |
| URLs | One segment for each tab of a network, and the same tabs on an earlier version |
| Must-have data | Loaded in beforeLoad, so a page never renders without it |
| Overlays | One Zustand store for each shared overlay, mounted once in _shell.tsx
|
| Imports | The @/ alias only. ../ is banned, which closes the layer gap noted under Layers
|
| Layout | Physical Tailwind classes are banned outside src/ui, so a right-to-left locale flips |
| Devtools | Opt-in with VITE_TANSTACK_DEVTOOLS=true, and only in src/devtools.tsx
|
Text goes through Lingui. The spec is docs/specs/2026-11-06-frontend-next-i18n-design.md.
- Write
t`Run solve`fromuseLingui()in@lingui/react/macro. The English text is the message's id, so there are no keys, and editing the English orphans its translations. - Numbers and dates go through
i18n.number()andi18n.date(). - The only locale is
en-GB, insrc/locales/en-GB/messages.po, loaded bysrc/i18n.ts. - Run
make -C frontend-next extractafter changing a string.make lintrunslingui check sync, so a stale catalogue fails. - Text the backend writes, such as a problem's
detail, is shown as received.
Rules are lint. A rule that Biome, tsc or a test can enforce lives in biome.json or as a GritQL plugin in lint/, with a case in scripts/biome-lint.test.ts. An exception needs a person's approval.
| Plugin | Rule |
|---|---|
no-relative-imports |
No ../ inside src/, since the layer bans match @/ paths only |
lingui-attributes |
No literal text in aria-label, title, placeholder, alt and similar attributes |
logical-classes |
No physical Tailwind classes (ml-, pr-, left-) outside src/ui
|
no-intl |
No Intl at run time |
no-lucide |
Lucide is imported only by src/ui/icons.tsx
|
no-cn-package |
cn comes from @/lib/utils
|
no-devtools |
TanStack devtools only in src/devtools.tsx
|
no-bare-render |
Tests never use Testing Library's bare render
|
hook-file-name |
An exported hook lives in use-<name>.ts(x)
|
no-use-client |
No "use client" or "use server" directive |
Built-in Biome rules add noJsxLiterals, kebab-case file names, no arbitrary Tailwind values or raw colours, and a ban on the fetch global.
URLs follow the tabs. A network's tabs are Overview, map, components[/$type], visualisation, versions and solve, one URL segment each. An earlier version is versions/$version/<tab>, so every tab can show any version.
A page's must-have data loads before it renders. beforeLoad awaits queryClient.query({ ...options, staleTime: "static" }) for what the page cannot render without, and the rest loads in loader. A 404 is read with isApiNotFound from @/lib/errors, then throw notFound().
A visual change is shown against the design. A pull request that changes what the app looks like shows the design and the build side by side, light and dark, at 1440x900, before it leaves draft.
Its designs are docs/specs/2026-11-06-frontend-next-foundation-design.md and the later frontend-next, home, projects-overview and network-overview specs, and its rules are in frontend-next/CLAUDE.md. The redesign also changes the icon set to Lucide and the typeface to Figtree, and keeps its source in a flatter layout: ui, components, hooks, lib, features, routes.
The desktop app is the same backend and the same web app in a window, with its own Python, so the modeller installs neither uv nor Python. The designs are docs/specs/2026-10-19-desktop-app-design.md and 2026-10-28-desktop-settings-design.md; desktop/README.md is the user-facing reference.
File in desktop/src
|
Role |
|---|---|
main.ts |
Electron wiring: the window, the menu, the single-instance lock, status pages, quitting |
supervisor.ts |
BackendSupervisor: starts the backend, waits for it, restarts it, stops it |
settings.ts |
Builds the backend's command and environment, finds the bundled Python, reads the login shell's PATH on macOS |
config-document.ts, settings-apply.ts, settings-window/
|
The Settings window, which edits the backend's config document |
updates.ts, update-providers.ts, release-channels.ts
|
The update controller, the feed providers, and version ordering |
user-data.ts, root-move.ts
|
One-off moves of the data folders after the product's rename |
preferences.ts, port-memory.ts, path-cache.ts
|
Small files in Electron's userData folder |
preload.cts |
Exposes window.desktop to the web app |
supervisor.ts, settings.ts, updates.ts, user-data.ts and root-move.ts import nothing from Electron, so their tests run in plain Node; main.ts passes in what they need. Keep it that way.
findBackendProgram chooses what to run: the program TZ_PS_CONDUCTOR_DESKTOP_BACKEND names, else the bundled Python as python -I -B -m tz_ps_app, else tz-ps-conductor on the PATH. The arguments are always serve --no-open --stop-on-stdin-close.
The backend reads one config document and refuses --port or --root beside one. So when a config exists, the app reads it at each launch, lays the port over it, and passes the whole document as JSON in TZ_PS_CONDUCTOR_CONFIG. With no config it passes --port. The port is remembered in userData/backend.json, because the web app's browser storage belongs to its origin, port included.
The supervisor depends on a contract that backend/libs/tz_ps_app/src/tz_ps_app/__main__.py keeps, set out in full on HTTP API and contracts. In summary:
- One stdout line
{"event": "listening", "url": …}says the backend is serving. The supervisor remembers the port and loads the URL in the window. Astartup-failedevent carries the reason shown when start-up fails. - Exit 2 (config or flags refused) and exit 4 (another Conductor holds the storage root) are refusals: the app reports them and does not restart, since the same start would fail again.
- Exit 3 after a bind error on stderr means the remembered port is taken, and the supervisor starts once more on any free port.
- Any other exit after start-up is a crash. The supervisor restarts after 1, 2, 4, 8 then 16 seconds and then gives up; 60 seconds of uptime resets the count.
To stop the backend the supervisor closes its standard input and waits up to 15 seconds before killing it. A backend that does not report listening within 180 seconds is killed.
This diagram shows a start, a crash and a quit.
sequenceDiagram
participant M as Electron main
participant S as BackendSupervisor
participant B as tz-ps-conductor serve
participant W as Window
M->>W: show the Starting Conductor status page
M->>S: start
S->>B: spawn serve on the remembered port, or any
B-->>S: stdout line with the listening event and URL
S->>M: ready with URL and pid
M->>W: load the URL
Note over S,B: running
B-->>S: unexpected exit
S->>M: crashed, with the delay before the restart
M->>W: show the Restarting status page
S->>B: spawn again after the delay
Note over M: the modeller quits
M->>B: ask whether a run is queued or running
M->>S: close
S->>B: close standard input
B-->>S: clean exit
M->>M: install a downloaded update if no run was in progress, then quit
The main process prints Backend <pid> listening at <url> when the backend is ready. The app's Playwright tests read the pid from that line, so its wording is part of a contract too.
File → Settings (the app menu on macOS) opens a window that edits a fixed set of keys in the backend's config document, among them the storage folder, the memory limits for solves, and the log level. SettingsController validates the change, restarts the backend with a trial start (startTrial), and reports a refusal without leaving the app with no backend. The update channel and the product tips choice are the app's own preferences, in userData/preferences.json, not in the Conductor config.
make -C desktop package builds the installer for the current OS; electron-builder cannot cross-build, so each OS builds its own.
-
The payload.
scripts/payload.tsdownloads a pinned python-build-standalone CPython 3.13 (URL and SHA-256 per platform), builds the release wheel with it, installs the locked third-party packages with--require-hashes, installs the wheel, and compiles bytecode. It needs the frontend bundled into the backend first (the rootmake bundle). The result goes beside the app asextraResources. - Left out. Calliope, as in the wheel, and git: the app uses the git the modeller has installed, and without one each network keeps a single version.
-
Targets (
electron-builder.yml). A one-click per-user NSIS installer for Windows x64, an AppImage for Linux x64, and a DMG for Apple silicon on macOS 14 or later. All are unsigned; the Mac bundle is signed ad hoc. -
Version.
desktop/package.jsonstays at0.0.0. The release workflows stamp the real version at packaging; never commit one.
The update feed is the repository's GitHub releases. The release workflows that fill it are on Build, CI and release.
| Channel | Takes | Tag form |
|---|---|---|
| Stable (default) | Releases | vX.Y.Z |
| Release Candidate | Its pre-releases and releases | vX.Y.Z-rc.N |
| Beta | Its pre-releases and releases | vX.Y.Z-beta.N |
| Nightly | Its pre-releases and releases | vX.Y.Z-nightly.YYYYMMDD |
- A channel never takes another label's pre-releases. For one
X.Y.Zthe order is nightly, beta, rc, then the release (release-channels.ts), the same order PEP 440 gives the wheel's versions. - The app checks at start and every 4 hours. A pre-release build starts on its own channel.
- Windows and an AppImage download the update in the background.
autoInstallOnAppQuitis off: on quit the app installs only if the backend has no run queued or running. - macOS cannot update an unsigned app in place, so the app links to the page of the new
.dmg. - At each check the app asks the GitHub CLI for a token (
readGhToken) and never stores it. With a token it reads the feed throughPrivateChannelProvider; with noghor no login it falls back toPublicChannelProvider, which finds nothing while the repository is private. The app does not fail then: Help → Releases Page opens the releases. - The web app sees all of this through
window.desktop.updates.frontend/src/features/updates/desktop-bridge.tsmirrors theDesktopUpdatesinterface ofdesktop/src/updates.ts; change both together.
From desktop/CLAUDE.md:
-
make -C desktop smoketests one of two things. By default it runs the app from source against the workspace backend, which needs the frontend bundled (make bundle) andbackend/.venvsynced with every package:make devsyncs only the API member, which uninstallstz-ps-app, and the smoke tests then skip. Runuv sync --all-packages --all-extrasinbackend/first. WithDESKTOP_APP_EXECUTABLEset it tests that packaged app instead. -
productNameis in bothpackage.jsonandelectron-builder.yml. Change both together. - Never change
USER_DATA_FOLDERinuser-data.ts: every user would lose their preferences, port and browser storage. - Never change the NSIS
guidinelectron-builder.yml: the installer finds an installed app by it. - Call
dialog.showMessageBox(…)on thedialogobject, never through a destructured copy, or the tests cannot replace it. - Every package is pinned exactly, and
electron-updateris the only runtime dependency. Ask before adding another.
-
The redesign is not merged yet. Each feature added to
frontend/grows whatfrontend-next/must reach before the merge, and the repository holds no dated plan for it. -
frontend/vite.config.tsloads@tanstack/devtools-vite, whose dev server takes unauthenticated install commands. -
frontend/package.jsonpins five TanStack packages tolatest, so only the lockfile fixes their versions. - Desktop installers are unsigned. Windows warns on first open, macOS cannot update in place, and updates from the private repository need the GitHub CLI.
-
The rename to Conductor stops at the artefact names.
electron-builder.ymlstill names the installers and the Linux executable after the former name. - Some screens still assume PyPSA. Adding a framework lists them.
Using the app
Architecture
- Overview
- Python API
- Domain model
- Backend core
- Composition root and config
- Expression language internals
- Storage
- Execution
- Imports and exports
- Workflow engine
- HTTP API and contracts
- Frontend and desktop
- Build, CI and release
Contributing