Skip to main content

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.

OutputSourceGeneratorCommitted
packages/api_client/app/app/api/openapi.yamltool/gen_api.dartyes
lib/l10n/keys.g.dartapp/i18n/locales/en.jsontool/gen_i18n.dartyes
assets/i18n/<locale>.jsonapp/i18n/locales/*.jsontool/gen_i18n.dartno, built in CI
lib/theme/tokens.g.dartapp/app/assets/css/main.csstool/gen_tokens.dartyes

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:

  1. Add the key under mobile in en.json (vue-i18n syntax: {name}, one | many plurals).
  2. Run make gen.
  3. Use the typed key: context.l10n.t(K.mobile.home.greeting, named: {'name': name}), or count: n for 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​

FlavorApplication IDConfig file
devcom.budgetthing.app.devconfig/dev.json
stagingcom.budgetthing.app.stagingconfig/staging.json
prodcom.budgetthing.appconfig/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 to ui.action (rebased on KRATOS_PUBLIC_URL, so a local stack that reports localhost still works). The sign-in screen renders ui.nodes and ui.messages generically (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 its method.
  • Journeys. Password or email code; an aal1 session (whoami returns 403 session_aal2_required) continues with login/api?aal=aal2 and the session token, where TOTP and recovery codes are accepted. Registration has no session hook, so it returns no session token: registration, then verification code (from continue_with), then sign in. Recovery by code returns set_ory_session_token and a settings flow (show_settings_ui) for the new password, then signs in.
  • Errors. 410 restarts the flow; 422 browser_location_change_required (or a redirect_browser_to) shows an error and never opens a browser; network failures and 5xx keep the form for a retry.
  • Passkeys are hidden. Kratos's passkey.rp.origins only allows https://app.budgetthing.com; Android passkeys need an android:apk-key-hash: origin, a Kratos config change and real assetlinks.json fingerprints. A passkey-only user signs in with an email code.
  • Session token. Stored in secure storage (kratos_session_token) and sent as X-Session-Token on every API request. A 401 clears it and goes to sign-in. 403 SECOND_FACTOR_REQUIRED and RECENT_AUTHENTICATION_REQUIRED open the in-app step-up screen (/step-up), then replay the request once; the screen pops false (no replay) when "sign in again" is a different account, which also ends the session. On a cold start only a 401 (whoami returns null) or session_aal2_required ends the session; any other whoami error (400, 404, other 403, 5xx, 429) keeps the stored token and the next API call retries. Sign-out calls DELETE /self-service/logout/api with {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.dart drives 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 unless KRATOS_LIVE_URL is set. test/integration/kratos/run-live-test.sh starts a disposable Postgres 16 and Kratos v26.2.0 in Docker (config in test/integration/kratos/, admin API on 4434, which the test reads emailed codes from), runs flutter test test/integration in the Flutter CI image, then removes the containers. Registration is two steps on Kratos 26 (a profile step 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.

VariableContent
ANDROID_UPLOAD_KEYSTORE_BASE64The upload keystore, base64 on one line
ANDROID_UPLOAD_KEYSTORE_PASSWORDKeystore password (also the key password)
ANDROID_UPLOAD_KEY_ALIASKey alias, upload
PLAY_SERVICE_ACCOUNT_JSONService 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 is CI_PIPELINE_ID (--build-number).
  • Fail closed: if only some variables exist the job exits 1 and names the missing ones. If none exist (the Play account is not set up) it exits 42. The jobs use allow_failure: true (a manual job with exit_codes would block the pipeline on main), so any failure, including 42, 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.sh runs first, release builds refuse the dev flavor, the AAB goes through check_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 by mobile/android/Gemfile.lock and installed frozen.
  • No production submission: mobile:android-release-prod builds 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) and enqueueAttachment(...) (Quick add and receipt capture call these; read it with offlineQueueProvider). body is the CreateTransactionInputBody JSON built at capture time, with the capture date in transactionDate (the user's local calendar day, via LocalDate). A currency key 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 is 409. 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 an ambiguous flag (schema 2) set by a transient or network outcome and by an interrupted sending row. QueueReplayer.editAndRetry edits an op that was never ambiguous under a fresh key straight away; for an ambiguous one it replays the original key and body first: 2xx marks it done and drops the edit (EditKind.alreadyCreated), a definitive 4xx takes the fresh key with the edited body, anything else leaves the entry as it was (EditKind.unconfirmed).
  • No id in the answer. A 2xx to a transaction create with no readable id is thrown as a transient error, so the op stays pending and 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. QueueReplayer sends pending ops in creation order, one pass at a time. Offline, timeouts, 5xx, 408, 429 and a lost session stop the pass and leave the op pending; any other 4xx marks it needs_attention with the problem detail and the pass continues. A DioException that carries a response (the signed-URL upload bypasses the problem interceptor) is judged by its status with the same rules, and a storage 401/403 is a rejection, not a lost session. A receipt op that fails on the server's side maxAttachmentAttempts (5) attempts goes to needs_attention so 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 in QueueSync: sign-in, workspace change, connectivity regained and app resume. After a clean pass the snapshot is refreshed.
  • Snapshot. SnapshotRefresher stores the server's JSON for accounts, categories, payees and the current planning period; the app shows it with AsOfLabel and never derives balances from it.
  • Receipt replay. ApiOpSender._upload sends the op id as the Idempotency-Key on create-attachment, so a retry returns the same attachment (with a fresh signed URL while it is unconfirmed). When the reply says the attachment is already available, the sender skips the upload and the confirm and counts the op as done.
  • Quick add (lib/features/quick_add/). QuickAddForm holds the rules (payee's last category, last account, Ready to Assign for inflows, request body, split) in plain Dart; AmountEntry keeps the typed operand as digit strings and reads integer minor units using the workspace's currencyPrecision; AmountCalc adds the + − × ÷ operators on top of it in integer minor units (BigInt products, round half away from zero). The screen is one form (QuickAddScreen) with a CalcKeypad; the pickers and split sheet return to it. QuickAddData is built from the snapshot (workspace, accounts, categories, payees); payee ranking and last categories live in the snapshot entry quick_add_history, written by QuickAddService.save, never by a refresh. save enqueues, then waits up to 2 s for a replay. undo discards an unsent op with discardUnsent (refused while sending; it waits and asks again) or calls the delete endpoint with the op's resultId; purgeDone keeps finished rows for OfflineQueue.doneGrace (2 min) for that. Entry points: Routes.quickAdd, the quick_actions shortcut and the budgetthing://app/open/quick-add deep link, all through QuickAddLauncher, 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.