Mobile App (Flutter)
Internal preview. The native app is under construction and is not in any store. This page is for engineers building it; nothing here changes the public API.
The Android app (iOS later) is a Flutter project in mobile/. Sign-in uses Kratos's
native API flows inside the app (no browser, no custom tab); see
Sign-in.
Build and run
You need the Flutter version pinned in mobile/.fvmrc, the Android SDK and an
emulator or device. From mobile/:
make gen # API client, string catalogs, key accessors, design tokens
make run-dev # dev flavor against a local stack (emulator host: 10.0.2.2)
make run-staging # staging flavor against the staging site, no local stack
make test # flutter test --coverage
make analyze # format check + dart analyze (incl. riverpod_lint)
Generated code
The app shares one API contract, one string catalog and one look with the web
app. make gen regenerates all three from the web sources, and the CI job
mobile:codegen-check runs it and fails on any diff, so a change to a web source
must come with the regenerated mobile output in the same merge request.
| Output | Source | Generator | Committed |
|---|---|---|---|
packages/api_client/ | app/app/api/openapi.yaml | tool/gen_api.dart | yes |
lib/l10n/keys.g.dart | app/i18n/locales/en.json | tool/gen_i18n.dart | yes |
assets/i18n/<locale>.json | app/i18n/locales/*.json | tool/gen_i18n.dart | no, built in CI |
lib/theme/tokens.g.dart | app/app/assets/css/main.css | tool/gen_tokens.dart | yes |
Never edit generated files by hand.
API client
tool/gen_api.dart runs swagger_parser (OpenAPI 3.1, pure Dart) to write
Retrofit clients on top of dio plus json_serializable models, then
build_runner for the .g.dart parts. Only the operations the app uses are
generated: the list is include_paths in packages/api_client/swagger_parser.yaml.
To use another operation, add its path there and run make gen.
The package resolves its own dependencies (packages/api_client/pubspec.lock)
because the generators need a newer analyzer than riverpod_generator. Money
fields are int minor units, a field that is both required and nullable stays
required and nullable, and createTransaction takes the optional
Idempotency-Key header as idempotencyKey.
Date-only fields (format: date, such as transactionDate and the from/to
query params) are plain Strings holding YYYY-MM-DD, in bodies, responses and
query params: the API rejects date-times for them, and a ledger date must never
pass through an instant. gen_api.dart strips format: date from a temporary
copy of the spec to get that; format: date-time stays DateTime. Convert with
LocalDate (lib/core/api/date_only.dart): LocalDate.parse(s) and
LocalDate.fromDateTime(d).toWire(), never DateTime.parse or
toIso8601String.
Strings
Strings live only in app/i18n/locales/en.json, under mobile.* (reuse
common.*). Never edit another locale file; the translation tooling fills them
later and the app falls back to English until then.
To add a string:
- Add the key under
mobileinen.json(vue-i18n syntax:{name},one | manyplurals). - Run
make gen. - Use the typed key:
context.l10n.t(K.mobile.home.greeting, named: {'name': name}), orcount: nfor a plural.
tool/gen_i18n.dart copies the mobile, common and a few shared namespaces
(listed in the script) of every locale in app/config/locales.ts to
assets/i18n/. A locale with no mobile strings yet shows English for them. A
test fails on a string literal in Text(...) under lib/features/.
Design tokens
tool/gen_tokens.dart reads the --theme-* custom properties in :root and
.dark of main.css, resolves color-mix() and var() at generation time, and
writes BudgetThingTokens (a ThemeExtension, context.tokens). buildTheme
builds the Material theme from it. A user accent is applied at runtime with
withUserAccent, which recomputes the tokens derived from the accent with the same
mixing rules. The font is Public Sans, the family the web app uses, bundled in
assets/fonts/ (SIL OFL). Shadows and other values the generator does not
understand are skipped.
Flavors
| Flavor | Application ID | Config file |
|---|---|---|
dev | com.budgetthing.app.dev | config/dev.json |
staging | com.budgetthing.app.staging | config/staging.json |
prod | com.budgetthing.app | config/prod.json |
The API base URL (API_BASE_URL, which must include the /api mount, for
example https://api.budgetthing.com/api), the Kratos public URL (KRATOS_PUBLIC_URL,
for example https://auth.budgetthing.com in prod) and the web app URL
(APP_WEB_URL) come from the config file through --dart-define-from-file; no
host names are in the Dart code. The earlier OAUTH_ISSUER, OAUTH_CLIENT_ID
and OAUTH_REDIRECT_URI keys are gone.
Sign-in
The app signs in with Kratos's native (API) self-service flows and never opens a
browser. lib/core/auth/kratos/ holds the client (KratosClient, plain HTTP, no
cookies), the flow models and AuthFlowController, the state machine.
- Flows.
GET /self-service/{login,registration,recovery,verification,settings}/api, then a submit toui.action(rebased onKRATOS_PUBLIC_URL, so a local stack that reportslocalhoststill works). The sign-in screen rendersui.nodesandui.messagesgenerically (FlowForm): inputs, hidden fields, one button per method group, field and flow errors. A button sends the hidden fields, the default-group inputs and its own group's inputs plus itsmethod. - Journeys. Password or email code; an aal1 session (
whoamireturns403 session_aal2_required) continues withlogin/api?aal=aal2and the session token, where TOTP and recovery codes are accepted. Registration has nosessionhook, so it returns no session token: registration, then verification code (fromcontinue_with), then sign in. Recovery by code returnsset_ory_session_tokenand a settings flow (show_settings_ui) for the new password, then signs in. - Errors.
410restarts the flow;422browser_location_change_required(or aredirect_browser_to) shows an error and never opens a browser; network failures and5xxkeep the form for a retry. - Passkeys are hidden. Kratos's
passkey.rp.originsonly allowshttps://app.budgetthing.com; Android passkeys need anandroid:apk-key-hash:origin, a Kratos config change and realassetlinks.jsonfingerprints. A passkey-only user signs in with an email code. - Session token. Stored in secure storage (
kratos_session_token) and sent asX-Session-Tokenon every API request. A401clears it and goes to sign-in.403 SECOND_FACTOR_REQUIREDandRECENT_AUTHENTICATION_REQUIREDopen the in-app step-up screen (/step-up), then replay the request once; the screen popsfalse(no replay) when "sign in again" is a different account, which also ends the session. On a cold start only a401(whoamireturns null) orsession_aal2_requiredends the session; any otherwhoamierror (400, 404, other 403, 5xx, 429) keeps the stored token and the next API call retries. Sign-out callsDELETE /self-service/logout/apiwith{session_token}, then clears local state even if that fails. - Migration. On every cold start the app deletes the Hydra tokens an earlier version stored. They can't be exchanged for a Kratos session, so testers sign in once.
- Live Kratos test.
test/integration/kratos_live_test.dartdrives the real client and flow controller against a Kratos server: registration with the emailed code, password and email-code sign-in, TOTP sign-in, and recovery for password-only and TOTP users. It is skipped unlessKRATOS_LIVE_URLis set.test/integration/kratos/run-live-test.shstarts a disposable Postgres 16 and Kratos v26.2.0 in Docker (config intest/integration/kratos/, admin API on 4434, which the test reads emailed codes from), runsflutter test test/integrationin the Flutter CI image, then removes the containers. Registration is two steps on Kratos 26 (aprofilestep for the email, then a credential method); the generic renderer follows it.
Release builds
Release builds are only allowed for staging and prod. The app refuses to start
as a release build with APP_ENV=dev, and CI fails if a release APK or AAB
contains a local host, the dev-login route or KRATOS_DEV_PROXY_TARGET. The CI
job mobile:build-android produces a staging APK signed with a throwaway key for
sideloading. Store builds come from mobile:android-release, below.
CI also runs mobile:codegen-check (generated sources are current), mobile:analyze
and mobile:test.
Play release pipeline
mobile:android-release signs a staging AAB with the Play upload key and uploads
it to the Play internal testing track with fastlane supply
(mobile/android/fastlane/Fastfile, one lane, no other track). Google holds the
app signing key (Play App Signing); CI holds only the upload key. The job is
manual and runs only on the default branch or a tag, and only when that ref is
protected, so the protected variables are available. The logic is in
mobile/tool/android_release.sh.
| Variable | Content |
|---|---|
ANDROID_UPLOAD_KEYSTORE_BASE64 | The upload keystore, base64 on one line |
ANDROID_UPLOAD_KEYSTORE_PASSWORD | Keystore password (also the key password) |
ANDROID_UPLOAD_KEY_ALIAS | Key alias, upload |
PLAY_SERVICE_ACCOUNT_JSON | Service account JSON, base64; only needs "Release apps to testing tracks" and "View app information" |
All four are masked and protected CI/CD variables. Nothing is written to the
repository or printed; the keystore and JSON live in a temporary directory that
is deleted when the script exits, and the keystore password is passed to
keytool through the environment, not the command line.
- Build number and version: the version name comes from
pubspec.yaml; the version code isCI_PIPELINE_ID(--build-number). - Fail closed: if only some variables exist the job exits
1and names the missing ones. If none exist (the Play account is not set up) it exits42. The jobs useallow_failure: true(a manual job withexit_codeswould block the pipeline onmain), so any failure, including42, shows as a warning. The variable check runs before code generation and the Ruby install. Variables are protected, so release tags must be protected tags too. - Checks:
check_release_config.shruns first, release builds refuse thedevflavor, the AAB goes throughcheck_release_artifact.sh, and the job fails unless the AAB's signer certificate SHA-256 matches the upload keystore alias (an unsigned or debug-signed AAB fails). fastlane dependencies are pinned bymobile/android/Gemfile.lockand installed frozen. - No production submission:
mobile:android-release-prodbuilds the prod AAB (com.budgetthing.app) and publishes it as a job artifact for the first manual Play Console upload, but never uploads. Each production release needs CEO approval.
Offline queue and read snapshot
lib/data/ holds a drift (SQLite) database in app-private storage with two
tables: pending_ops (the write queue) and snapshot_entries (the read
cache). The user's own sign-out wipes everything (AppDatabase.wipe).
A forced sign-out (a 401, a password change, a step-up as someone
else) wipes only the snapshot (wipeSnapshot): the unsent entries and their
receipt files stay. queue_owners holds one row, the Kratos identity ID of the last
interactive sign-in. Session.completeSignIn calls claimQueue(identityId) before the session
turns ready: the same sub resumes, a different or unknown one wipes the
queue and its files before anything is replayed or shown. Sign-in fails closed:
if claimQueue throws, completeSignIn runs the same wipe (AppDatabase.wipe)
before the session turns ready, and if the wipe throws too it sets
replayBlockedProvider, which makes QueueSync.sync do nothing for the rest of
the session and also refuses a Pending Edit (editAndRetry returns
blocked).
- Queue API.
OfflineQueue.enqueueTransaction(workspaceId, body)andenqueueAttachment(...)(Quick add and receipt capture call these; read it withofflineQueueProvider).bodyis theCreateTransactionInputBodyJSON built at capture time, with the capture date intransactionDate(the user's local calendar day, viaLocalDate). Acurrencykey beside it is kept for display and is not sent. - Idempotency. The op id (UUIDv4) is the
Idempotency-Key. A retry with the same key and body returns the original transaction (200); the same key with a different body is409. So Retry keeps the id, and an edit of a rejected entry gets a fresh one only when the server created nothing. Every op has anambiguousflag (schema 2) set by a transient or network outcome and by an interruptedsendingrow.QueueReplayer.editAndRetryedits an op that was never ambiguous under a fresh key straight away; for an ambiguous one it replays the original key and body first:2xxmarks it done and drops the edit (EditKind.alreadyCreated), a definitive4xxtakes the fresh key with the edited body, anything else leaves the entry as it was (EditKind.unconfirmed). - No id in the answer. A
2xxto a transaction create with no readableidis thrown as a transient error, so the op stayspendingand replays with the same key (the server returns the original transaction). A receipt whose parent is done with no stored id (written by an older build) replays the parent's key to read the id; the replayer never assumes a parent id exists. - Replay.
QueueReplayersendspendingops in creation order, one pass at a time. Offline, timeouts,5xx,408,429and a lost session stop the pass and leave the oppending; any other4xxmarks itneeds_attentionwith the problem detail and the pass continues. ADioExceptionthat carries a response (the signed-URL upload bypasses the problem interceptor) is judged by its status with the same rules, and a storage401/403is a rejection, not a lost session. A receipt op that fails on the server's sidemaxAttachmentAttempts(5) attempts goes toneeds_attentionso it can't hold back transactions; only a server-side failure (5xx,408,429) triggers the move, never being offline, and Retry resets the count. Attachments wait for the transaction op (depends_on). Triggers are inQueueSync: sign-in, workspace change, connectivity regained and app resume. After a clean pass the snapshot is refreshed. - Snapshot.
SnapshotRefresherstores the server's JSON for accounts, categories, payees and the current planning period; the app shows it withAsOfLabeland never derives balances from it. - Receipt replay.
ApiOpSender._uploadsends the op id as theIdempotency-Keyoncreate-attachment, so a retry returns the same attachment (with a fresh signed URL while it is unconfirmed). When the reply says the attachment is alreadyavailable, the sender skips the upload and the confirm and counts the op as done. - Quick add (
lib/features/quick_add/).QuickAddFormholds the rules (payee's last category, last account, Ready to Assign for inflows, request body, split) in plain Dart;AmountEntrykeeps the typed operand as digit strings and reads integer minor units using the workspace'scurrencyPrecision;AmountCalcadds the + − × ÷ operators on top of it in integer minor units (BigInt products, round half away from zero). The screen is one form (QuickAddScreen) with aCalcKeypad; the pickers and split sheet return to it.QuickAddDatais built from the snapshot (workspace,accounts,categories,payees); payee ranking and last categories live in the snapshot entryquick_add_history, written byQuickAddService.save, never by a refresh.saveenqueues, then waits up to 2 s for a replay.undodiscards an unsent op withdiscardUnsent(refused whilesending; it waits and asks again) or calls the delete endpoint with the op'sresultId;purgeDonekeeps finished rows forOfflineQueue.doneGrace(2 min) for that. Entry points:Routes.quickAdd, thequick_actionsshortcut and thebudgetthing://app/open/quick-adddeep link, all throughQuickAddLauncher, which holds the request until the session and workspace are ready.
Home-screen widget (Android)
home_widget plus a Jetpack Glance widget (android/app/src/main/kotlin/com/budgetthing/app/widget/)
show Ready to Assign and a Quick add button. The widget process holds no token
and makes no network call: WidgetSync (lib/app/widget_sync.dart) writes a
WidgetPayload (lib/core/widgets/) into the widget's own preferences from
the budget snapshot entry, and the Kotlin side only draws it. All wording
comes from mobile.* strings, so Kotlin has none of its own. It re-publishes
when the budget snapshot is written (SnapshotStore.changes), when the
session, the active workspace or Hide amounts changes, and on start. With Hide
amounts on only the mask is written, never the figure; signed out or without
a workspace the payload carries no amount. The Quick add button fires the
budgetthing://app/open/quick-add intent at MainActivity, so it goes through
QuickAddLauncher like the quick action. The provider has updatePeriodMillis=0:
the widget only changes when the app pushes. The Compose compiler plugin and
glance-appwidget are the only Android additions; iOS (WidgetKit) is a later phase.
Reports
lib/features/reports/ holds the Reports hub (More > Reports, routes /reports and /reports/:slug). report_mapper.dart turns each generated report DTO into a ReportData (a chart kind, summary tiles, series and rows); the chart value only places a mark and every figure shown is the server's display string. report_charts.dart draws the charts with fl_chart (MIT) using theme tokens only, and reports_repository.dart calls the generated ReportsApi and hands CSV to share_plus (BSD-3-Clause) through ReportSharer. The five reports with a server .csv twin share that; the others share csvFromData, which quotes cells and prefixes names that start with = + - @, a tab or a carriage return with a '. Business reports aren't wired yet. Adding the report models put an API class named Options next to Dio's, so files that import both hide one of them.
Tests and compatibility checks
Run make test in mobile/ for the unit and widget tests; CI runs them in
mobile:test.
Golden tests
Home and Settings have a golden test for every combination of width (360, 412
and 430 dp), text size (100 % and 200 %) and theme (light and dark), 12 images
per screen, in test/features/<screen>/goldens/. Each case also fails on a
layout overflow. Goldens are test-font layout snapshots (blocks, not real
glyphs), so they show spacing, wrapping and clipping, not typography.
Render goldens on Linux so they match CI. From mobile/, inside the pinned CI
image on another OS:
docker run --rm -v "$PWD/..":/w -w /w/mobile ghcr.io/cirruslabs/flutter@<FLUTTER_IMAGE_DIGEST> make update-goldens
Review the changed images in the merge request before committing them. New screens add their matrix the same way.
OpenAPI compatibility check
The CI job ci:openapi-breaking runs on merge requests that change
app/app/api/openapi.yaml. It compares the file with the merge base using
oasdiff breaking (pinned by OASDIFF_VERSION) and fails on any
error-level break: a removed path or operation, a removed response field, a
new required request field, a changed type and similar. Installed apps can't
be updated on demand, so make changes additive.
ci/check-openapi-breaking.test.sh proves the check with fixture specs in
ci/testdata/openapi-breaking/ (one compatible change must pass, each breaking
one must fail). A break the CTO approved is added to
ci/openapi-breaking-ignore.txt in oasdiff's --err-ignore format, with a
link to the approval.
Emulator flows (mobile:integration-android), the offline-queue replay suite
and the TalkBack pass are not part of this yet.
Time tracking, projects and tasks
The time, time-entries, running-timer, projects and project-tasks
operations are generated into the client (include_paths in
packages/api_client/swagger_parser.yaml), plus list-clients for the project
form. The timer lives on the server; the app never keeps its own counter. It
reads GET running-timer on start, on resume and on refresh, caches the last
timer (with the task and project names) in shared_preferences for an offline
restart, and shows elapsed time as now - startedAt. A refusal (402, 403, 409,
423) clears the cache and the notification; no answer or a 5xx keeps them.
GET running-timer is read with a raw Dio call: the response's timer is null
when nothing runs, but the OpenAPI schema marks it required and not nullable,
so the generated model would throw. Fix the schema when the API next changes.
The ongoing notification is flutter_local_notifications (Android only,
usesChronometer with when set to the start instant; core library
desugaring is enabled in build.gradle.kts and POST_NOTIFICATIONS is in the
manifest). Time entry, project and task creates take no Idempotency-Key, so
the screens disable the button while saving.