Architecture
This page is for maintainers. It describes how the code is layered after plan 26 (platform readiness), and where a new user interface would plug in.
Most of the logic is in ledgeline-core. It reads journals, edits them safely, and computes every report and view. ledgeline-server wraps it in an HTTP API. Each host reaches that API in its own way: a desktop window, a headless server, or an iOS app calling the router in-process. The Svelte app in web/ only displays what the API returns.
hosts desktop (wry window) headless (--server) iOS (ledgeline-ffi, in-process)
│ │ │
server ledgeline-server: axum router, snapshots, AppState
│ features: gui · watcher · external-tools
shell ledgeline-shell: token + Host guard · CSP · SPA embed · AppDirs · recents · GUI boot
│ features: gui
core ledgeline-core: vault · parse/edit · reports · view · display · ui_prefs
Core: crates/ledgeline-core
It is a plain library with no platform cfgs, no clock reads in report code, no HTTP, and no knowledge of where files live.
| Area | Modules | What it owns |
|---|---|---|
| Storage | vault/, pinned.rs | The Vault trait (VaultPath, Entry, Availability, Revision, VaultError). LocalVault wraps the pinned, symlink-refusing, fsync’d writes; MemVault is for tests and can simulate files that are not downloaded yet and edits made behind the editor’s back. Writes are conditional on a Revision, so an external change produces a conflict instead of being overwritten. |
| Reading | parse.rs, dirscan.rs, hledger_conf.rs, journals.rs | parse_journal_in(vault, main, …) resolves includes inside the vault and returns each source’s revision. |
| Writing | edit.rs, periodic.rs, accounts.rs, aliases.rs, rules/, projections/serialize.rs | Span-splice edits that change only the bytes they mean to, verified by a re-parse before anything is written. |
| Reports | reports/ | Balance sheet, income statement, cash flow, net worth, budget and the budget summary (span totals, pace, health, labels), insights, subscriptions, holdings. Exact decimals throughout (Dec, MixedAmount). |
| Journal view | view/ | The windowed journal: filter, sort, search text, summary, charts, local checks, cash balances. |
| Classification and display | reports/account_types.rs, reports/account_class.rs, display.rs | One resolver for account types and terms (declared, else inferred), the sign rule for entered amounts (signed_entry: revenue is entered positive and written negative), and the number formatter the UI uses. |
| Projections | projections.rs | The what-if engine, the scenario model, and the section a scenario line belongs in (line_section). |
| UI preferences | ui_prefs.rs, ui_prefs/ledgeline.rs | The settings-files data model (plan 38/39): per-key merge of ledgeline.toml [ui] over ui-prefs.toml over the defaults, save routing, the theme pin, edit_ledger_text. Generic over a Schema each app registers; theme and uiScale are common to all of them. |
Pure functions that used to be in TypeScript were ported here, with golden fixtures captured from the TypeScript first. See fixtures/journal-view/, fixtures/journal-meta/, fixtures/display-format/, fixtures/budget-summary/ and fixtures/projections-signs/, and the *_golden.rs tests that read them.
Server: crates/ledgeline-server
The server is an axum Router over an AppState. Every host links the library, and main.rs is the desktop and headless binary.
- Snapshots.
AppStateholds the current parsed journal as an immutableSnapshot(with lazily built, memoized views such as the sort order and search text). A reload builds a new snapshot and swaps it in, and requests in flight keep the one they started with.GET /api/journalreports the snapshotgeneration, and the journal-view routes carry anETagderived from it. - Entry points.
AppState::from_vault(Arc<dyn Vault>, VaultPath)is the general constructor, andfrom_journal_pathbuilds aLocalVaultand delegates to it.reload()re-parses, andrefresh()is a vault-based content check for hosts with no file watcher. AppDirs(fromledgeline-shell). Config, cache and temp directories and thehledgerbinary are injected rather than looked up, so a sandboxed host can point them inside its container. Recents store an opaque location token.- Routes.
reports_api.rs(reports, budget),journal_api.rs(the windowed journal),budget_api.rs,projections_api.rs,edit_api.rs,import_api.rsand the rest. The hledger-web-compatible routes (/version,/transactions,/prices, …) are kept for external tools, with their parity tests. - Cargo features.
gui(default): the wry/tao desktop window, menus and file dialogs.watcher(default): live reload from anotifyfile watcher. Without it, the host callsrefresh().external-tools(default): runninghledgeras a subprocess. It needs a real path (Vault::local_path). Without this feature, the features that callhledgerreport that this build cannot run it.
Shell: crates/ledgeline-shell
This crate has the code that turns a router and a built SPA into a hardened local server in a desktop window. Ledgeline and the invoicer both use it. An app describes itself once in an AppIdentity (name, bundle id, its token variable, the SPA’s two window globals and the path its SPA is served under; Ledgeline’s is ledgeline::APP, whose SPA is the whole origin, /, and the invoicer’s is under /app/).
security. The bearer token, theHostguard, the CORS allowlist and the security headers, withprotect(token + CORS over the explicit routes) andharden(everything else) to put them on a router.SecurityPlansets the bind posture.spa.spa::fallback::<E>(&APP)serves aRustEmbed-ed SPA with the embedded marker and a per-response CSP.app_dirs,recents. One config directory for every app, so recents andui-prefs.tomlare shared.gui(feature).spawn_server,AppMenu,RecentMenu,build_window,build_webviewand the Linux and macOS glue code. An app’s ownguimodule combines them around its state. The webview’s navigation policy has two layers. Every frame stays on the app’s own origin, and an allowlisted external link opens in the system browser instead. The main frame may show only the SPA underAppIdentity::spa_base. If it commits to any other page, even one on the same origin (an MBR page in the invoicer), the last SPA page is loaded back. wry’s navigation handler can’t tell frames apart, so the main-frame rule runs on commit, and the invoicer’s sandboxed MBR iframes still load. The token’s init script (security::token_init_script) checks the origin and, for a base other than/,location.pathnametoo, so a non-SPA page never receives the token.
Hosts
- Desktop (
ledgeline, default features).gui.rsbinds axum to an ephemeral loopback port and opens a wry webview at it, through the boot pieces incrates/ledgeline-shell(shared with the invoicer). The SPA is embedded in the binary. - Headless (
ledgeline --server, or a build with--no-default-features --features watcher,external-tools). This runs the same router on a fixed port, token-guarded, for a browser or another client. - iOS (
crates/ledgeline-ffi,mobilefeature). There is no socket.LedgelineApp::handle(method, url, headers, body)runs the router in-process (Router::oneshot) behind the app’s custom-scheme handler. Storage is aCoordinatedVaultthat writes through a SwiftFileCoordinator(conditionally, against the expected revision), detects iCloud placeholder files and fails fast withNotDownloadedinstead of blocking. Themobilefeature builds the server withoutgui,watcherorexternal-tools. UniFFI exports are compiled on Apple targets only, so the crate builds and tests everywhere. The Swift shell is inapple/ios(plan 42) and shows the same SPA in native mode, below.
The web app
web/ is a SvelteKit SPA. Since plan 26 it requires the native API and holds no journal-sized data. The Journal tab reads windows of rows, the budget bars come with their pace and verdicts, and a projection line is sent signed as the file writes it, which the engine writes unchanged. The TypeScript that remains handles presentation: layout, formatting with the engine’s styles, chart and bar geometry, and form state. A component may still preview something while the user types (for example, whether a projection rule’s postings balance on their own), but once the engine’s answer arrives, it replaces the preview.
Native mode (the iOS app)
The iOS app shows the same SPA bundle with its own navigation bar in place of the HTML header. Its document-start script sets window.__LEDGELINE_NATIVE__ = {platform, idiom, version} and the ll-native class on <html>; isNative() in packages/ui/src/native/ (the UI package web/ shares with the invoicer) reads either. Every native-only path is gated on it, so the desktop app and a browser behave as before. The contract is in plans/42-mobile-app.md.
- Page to app.
window.webkit.messageHandlers.ledgeline.postMessage(msg)with{type: "page", title, sections, actions, canGoBack}(posted from the root layout after every navigation and whenever an action, an open overlay or the history depth changes, deduped),{type: "share", filename, mime, base64}for an export, and{type: "haptic", style}. - App to page.
window.ledgelineNative.navigate(sectionId),.action(actionId),.back()and.state().back()closes the topmost overlay, else goes back in in-app history, else returnsfalseand the app shows its home screen. - Actions. A component adds menu entries with
registerNativeActions(() => [...])during init. The getter is reactive, so counts in labels stay current. The layout adds Refresh everything and Problems, everyExportButtonadds Export to Excel, and the journal adds Add transaction, the review and match runs, and the insights toggle. - Overlays. Anything built on
use:dismissibleregisters its dismiss handler with the bridge on its own. Other modals (the problems drawer, the goal and save-scenario dialogs) callregisterNativeOverlay. - Layout.
html.ll-nativecollapses the header to zero height (notdisplay: none, because fixed popups anchored inside it must still render) and pads the body by the safe-area insets (viewport-fit=coveris inapp.html). Imports and the new-ledger wizard need a desktop host, so in native mode they are not rendered and redirect to the journal. - Exports.
downloadWorkbooksends the bytes to the share sheet instead of an<a download>.
Two related changes depend on the device, not on native mode, so they apply in any browser too. Keyboard hints (<kbd> and “(v)” suffixes in tooltips, through hint() in packages/ui/src/keys/hint.svelte.ts) hide when there is no fine pointer (any-pointer: fine), and the journal’s calendar is not offered below the md breakpoint. There is no toggle and no v, and a cal=1 link shows its month as the list.
The invoicer: invoicer/
Ledgeline Invoicer is under invoicer/ in the same Cargo and bun workspaces, so it can move out later. Its design is in invoicer/ARCHITECTURE.md and its build order in invoicer/PLAN.md.
invoicer/crates/invoicer-core(lib). Invoice documents, the bill-table engine, the booking bridge, reconciliation and the views, on top ofledgeline-core. The same plan 26 rules as core: no globals, all IO through aVault, no platformcfg.invoicer/crates/ledgeline-invoicer(bin). The CLI, the axum API, the desktop window onledgeline-shell, and PDF export through mbr.invoicer/web. A SvelteKit SPA served under/app(the root belongs to mbr’s router). It importspackages/uiasweb/does, so the themes, UI scale and keymap are shared.
Invoicer code layout has the details.
Adding a native UI
A native desktop UI (egui, GPUI) or a SwiftUI app can connect in two ways:
- Link core directly. Parse through a vault, call the report and view functions, and draw the results. This is the fastest path (the native spikes put rows on screen in well under a second at 200k transactions) and needs nothing from the server. Writes go through the same core editors, so the conditional-write guarantee holds.
- Call the router in-process. Build an
AppStateand send requests to the router without a socket, asledgeline-ffidoes. This reuses every route’s validation, caching and JSON shape, which is quicker if a UI already uses the API.
Either way, nothing in core needs to change, and new domain logic belongs in core rather than in a UI.
Deferred until a UI is chosen (plan 26): a view-model crate that shapes report rows for display, server-side xlsx export, and protocols for the edit and import forms.