valence

Valence.shareImage backs schema-14 share.image: bounded PNG/JPEG bytes or an active signed bundle image, plus a caption. The runtime checks paths, size, magic and bundle integrity before opening native sharing. Results report selection, dismissal or an unavailable outcome, never delivery. See image sharing. iOS sharing remains experimental and untested.

The Flutter host runtime for Valence: your web app runs inside a native app as a signed over-the-air bundle, on top of an offline-first SQLite store with incremental sync and a typed bridge. UI changes ship without an app-store review; the native shell is reviewed rarely.

This package is the whole host. You get the loopback server with its per-launch nonce, the canonical manifest check order, the activation state machine with automatic rollback, the SQLite store and its seed import, sync with its lease, the strict bridge decoding, and the WebView with its navigation lock, back gesture and console capture.

Your app supplies two things: its generated config, and its own native bridge methods.

Task snapshots are bound to the native account as well as the signed bundle: switching or signing out clears the route and draft, including stale OS snapshots. Refresh and first-account adoption retain the live draft.

Task restoration in 0.4

Schema 8 adds state.save({json}) and state.restore() for at most 65,536 JSON UTF-8 bytes of task-local UI state. ValenceApp installs its own RootRestorationScope and restores the local path/query/hash after OS process reclamation. A fresh task after explicit closure starts empty; an update or rollback clears the snapshot. Use SQLite for durable records and secure storage for secrets. Guide. The iOS FlutterViewController needs a restoration identifier in Main.storyboard; iOS is experimental and untested.

Setup

Migrating custom notification events requires preserving their payload types as well as methods. Regenerate config to exclude pre-11 events from automatic native emission, and pass notificationEventAdapter to Valence.open for your generated legacy event builder. Cold taps stay consume-once and need the same app-owned conversion. Migration recipe.

Seed imports record completion separately from row insertion. A locked completion marker retries up to five times, one second apart; exhausted retries retain rows and leave the marker for the next launch. Recovery and log meanings. No app codegen change is needed.

For debug-only HMR, valence dev binds loopback by default. A physical-device LAN target requires --allow-lan, which acknowledges a cleartext full-bridge trust grant; it provides no encryption or authentication. Start your web dev server and run flutter run --debug --dart-define=VALENCE_DEV_URL=http://10.0.2.2:5173. The loopback proxy injects the normal bridge nonce and forwards HMR WebSockets. Release/profile builds exclude this path. Use a separate development app id and test accounts; the page has the full native bridge and SQLite access. See the development guide.

Native features can also come from a ValencePlugin package. List its schema fragment in config plugins, regenerate, and pass its instance to the generated ValenceBuiltins(valence, plugins: [...]). Regenerated handlers check every fragment namespace and exact method registration at construction in all build modes; missing registrations throw StateError naming the fix. Test construction of your real app handlers. Doctor lists these requirements as a warning, since it cannot execute registration. Generated strict decoding owns the bridge boundary; the registry is not a WebView dispatcher. The plugin owns native setup, initialization and cleanup, and needs a store release. See Writing a Valence plugin and the example's plugins/haptics package. The built-in open.external uses this API too, with its existing scheme restrictions and reserved owner.

flutter pub add valence
npx valence codegen
import 'package:flutter/material.dart';
import 'package:valence/valence.dart';

import 'valence/bridge.g.dart';
import 'valence/config.g.dart';

Future<void> main() async {
  final valence = await Valence.open(valenceConfig);
  final handlers = AppHandlers(valence);
  runApp(
    MaterialApp(
      home: ValenceApp(
        valence: valence,
        dispatch: (raw, nonce) => bridgeDispatch(handlers, raw, nonce: nonce),
      ),
    ),
  );
}

valenceConfig, bridgeDispatch and ValenceBuiltins are generated by valence codegen from your valence/valence.config.json and valence/bridge.schema.json. Your own methods go in one class:

class AppHandlers extends ValenceBuiltins implements BridgeHandlers {
  AppHandlers(super.valence);

  @override
  Future<void> hapticsTap() async => HapticFeedback.lightImpact();
}

ValenceBuiltins already implements app.*, data.*, prefs.*, sync.*, secure.*, auth.*, open.external and bundle.* by delegating to the runtime, so only what is app-specific is left abstract.

What you still do yourself

The package cannot write native project files, so these are yours:

Assets Declare assets/valence/builtin/, assets/valence/builtin/files/ and assets/valence/seed.db in pubspec.yaml. Flutter asset directories are not recursive, so the two builtin lines are both needed.
Android minSdk 23 or later. flutter_secure_storage, which holds the bearer token and secure.* (contracts §4.4), needs the Keystore APIs added there.
Android cleartext res/xml/network_security_config.xml permitting cleartext for 127.0.0.1 only, referenced from AndroidManifest.xml.
Android backups dataExtractionRules and fullBackupContent excluding valence/. A restore should start clean from the built-in bundle.
iOS ATS The App Transport Security loopback exception. Never NSAllowsArbitraryLoads.
iOS backups NSURLIsExcludedFromBackupKey on the valence/ directory, from AppDelegate. The SQLite file lives outside it and is backed up, because it holds user data.
Background sync Valence.backgroundSync(valenceConfig) is the callable; registering it with workmanager or BGTaskScheduler is yours. The package deliberately does not depend on workmanager, which applies the Kotlin Gradle Plugin and warns on every Android build.
Native value At least two of the capabilities in contracts §6, or Apple rejects the app as a repackaged website (guideline 4.2).

Things that cost someone a day

  • PRAGMA journal_mode = WAL must go through rawQuery, not execute. The package does this. sqflite_common_ffi, the factory flutter test uses, accepts execute, so no unit test catches it and the app dies on its first launch on a phone. Check store.isWal in your logs.
  • Never close the database. sqflite keys open databases by path inside the platform plugin, so a close() in a background isolate invalidates the handle the UI isolate holds. There is deliberately no close on ValenceStore. A background isolate needs DartPluginRegistrant.ensureInitialized() first.
  • Build the web app with an absolute base (base: '/' in Vite). The SPA fallback serves the entry page at any depth, so a relative asset URL 404s on every nested route — a blank screen with nothing in the log, visible only after a reload or a back gesture. valence bundle warns about it.
  • The bridge is not a path for bytes. Messages are capped at 256 KB of UTF-8 each way. Native bytes reach the page through valence.publishHostFile(...), which serves them under the reserved /_host/ prefix with nosniff and a locked-down CSP. Pass the type the bytes actually are: a picker's imageQuality is a request, not a guarantee, so a gallery pick can be PNG bytes in a .jpg path, and a type taken from the extension is wrong for everything that reads it. Each call makes a durable copy with a new URL, even for identical bytes. Reuse that URL; deleting a source or row does not revoke it. Nothing collects these copies on its own — and nothing can, because the URLs live in rows only the app can read — so valence.revokeHostFile(url) in the same operation that deletes the row that owned it, and valence.listHostFiles() to reconcile away a publish whose row never got written. A revoked URL 404s, but the WebView's cache is not the disk. See publication lifetime before using it for removable or sensitive media.
  • app.ready() is what commits an OTA release. A bundle that never calls it fails its trial twice and is rolled back. Call it after the first meaningful paint.
  • A WebView eviction kills the app on Android, and 0.4 cannot stop it. The page runs in a separate, lower-priority process; under memory pressure the OS kills that one, and because no released webview_flutter_android exposes onRenderProcessGone, the WebView then kills your process too. No Dart code runs, so nothing logs it — identify it from dumpsys activity exit-info (renderer LOW_MEMORY, then your app SIGNALED/9). Because no Dart code runs, an eviction during a trial costs that release a strike — two of them retire a healthy release on that install, so roll out to 10% first. Where the platform does report the loss, the host reloads the same bundle at the same route and spends no strike. Keep anything the user would miss in SQLite. See contracts §3, "Renderer loss", and the startup diagnostics guide.

Rollback

An OTA bundle gets one trial. If app.ready() does not arrive within 15 s of foreground time, or the process dies first, that is a strike; two strikes and the seq goes into bad for that install, for ever, and the previous bundle is served again. Nothing you have to wire up.

To undo a bad release, roll forward: re-release the last good web commit, which gets a new, higher seq. Pointing the channel at an older seq only cancels pending downloads.

Testing

For startup stalls and database waits, see Startup diagnostics. The existing logger reports Valence.open phase timings and database operations pending for ten seconds, without changing retries or transaction behavior. startup: complete means open returned, not that the WebView painted or a trial committed.

The generated-Dart CLI gate compares ValencePluginRegistry.reservedNamespaces with the CLI's exported PLUGIN_RESERVED set. Update vendored tooling and regenerate when upgrading the runtime. Malformed typed plugin results are E_INTERNAL; parameter failures remain E_PARAMS. Separate npm plugin types are hand-maintained, and plugins have native host privileges; see the plugin guide.

flutter test in this package runs the contracts §8 matrix: every canonical check rejecting, the state machine's strikes and promotions, the server's three branches in order, the store, sync and the lease.

The host widget tests pump the real ValenceApp against a test-only WebView platform, with signed bundles, SQLite and a loopback socket, so flutter test test/app_widget_test.dart covers the lifecycle, the startup resume guard, the navigation lock, bridge nonce forwarding, event buffering and the ready timer.

A green unit suite is not evidence the store opens on a phone — see the first gotcha above. The §8 integration row is what covers that, and the widget harness replaces only the native WebView calls, so it proves host policy and never the OS WebView's own behaviour. iOS stays experimental and untested.

Versioning

The bridge IDL and the manifest format are additive only. This package's version is independent of your schema's BRIDGE_VERSION.

A method of your own that nothing calls any more can be marked "retired": true in the schema: the name and its shape stay, so has() and every shipped bundle are unchanged, and codegen answers it with E_UNSUPPORTED from ValenceBuiltins instead of leaving an abstract member — which is what lets the dead native code go. A built-in, app.ready/app.info and a plugin method cannot be retired.

MIT. The spec is contracts.md, which ships inside the /valence Claude Code skill and is restated at getvalence.dev/docs/.

Native HTTP (contracts section 4.5)

Generated http.request delegates to Valence.httpRequest. Configure exact trusted http.origins origins, regenerate, and ship a host; they become ValenceConfig.httpOrigins (default deny all). The host reads the R1 token per request, with authToken callback precedence, and emits auth.expired for an authenticated 401. Redirects are returned without following them. Request bodies: 64 KiB; decompressed responses: 64 KiB by default, configurable with compiled http.maxBodyBytes (1..262144); headers: 16 KiB; total deadline: 20 seconds (E_TIMEOUT). A transport failure while the OS reports no network interface is E_OFFLINE; a captive portal or a server that is down stays E_INTERNAL. Every size refusal names the observed size and the limit. ValenceConfig.cookieJar (compiled from http.cookieJar) optionally holds cookies for one origin, which must also be in http.origins and must be HTTPS unless it is loopback, and mirrors a named CSRF cookie into a named header the page may not supply — so a cookie-paired CSRF token can be completed. It is host-only by Domain, caps at 16 cookies / 8 KiB, keeps a session cookie in memory by default (sessionCookieDays: 1..30 opts into a fixed lifetime from receipt; guide), is cleared by every path that clears the token, and is revoked at Valence.open when a build drops or moves the grant. Without it a session-cookie API is out of scope. Raise compiled http.maxBodyBytes and ship a host for larger responses; the escaped 256 KiB bridge envelope still applies. Send Range or paginate to read less. Use HTTPS in production and no shared server secrets in an APK. API and adapter guide. iOS remains experimental and untested.

Account switching (contracts section 4.4)

Valence.authSetToken(token, {account, discardPending}) records your own opaque account id beside the token. The same id is a refresh. A different id, or authSetToken(null) with an id recorded, clears every writable bucket's rows, max_usn cursor and the whole outbox in one transaction, under the sync lease, before the new token is stored, and emits sync.changed for those buckets. It throws E_PENDING and changes nothing while the outbox is not empty — the host reads the stored token when it makes a request, so the alternative is pushing one account's writes under another's credentials — unless discardPending is set. A first id with none recorded is an adoption that clears nothing, and an app that never passes one keeps the 0.3 behaviour. Valence.authAccount() reads the id back and is the gate the page must check: the params have no since of their own.

Lifecycle, connectivity and update status (contracts section 4.6)

Valence.appState() returns the current ValenceLifecycle and the OS's network-interface state; Valence.bundleStatus() returns serving, pending, trial, a ValenceBundleReason, the offered seq and when the last check finished. Neither starts a request. ValenceApp maps Flutter's five lifecycle states onto four (hidden and paused are both background, because Android delivers both for one backgrounding), emits app.lifecycle and app.online only on a change, reads the current connectivity at start-up rather than waiting for one, and emits sync.done with the whole ValenceSyncResult after every completed run — after sync.changed for the same run. The generated version-6 built-ins expose these as app.state, bundle.status, app.lifecycle, app.online and sync.done.

valenceLifecycleFor and valenceOnline are the mapping and the "any interface that is not none" rule as pure functions, so a host that builds its own WebView uses the same ones the package does.

A page should persist on background: detached is reported for completeness and usually never delivered, because the engine is tearing down. app.online is interface state and never reachability.

Foreground live-interface reports also retry the signed update check, including handovers, through the existing coalescing and data-lease path. Background reports sync only; resume checks for updates. bundleStatus().reason == offline describes the attempt at checkedAt until another check completes, not current reachability. No new bridge schema or generated host code is needed. Update checks after reconnect.

Batch reads and sync observations

Valence.dataGetMany(bucket, keys) returns distinct live rows in requested order (maximum 500 input keys), using the active manifest schema. Valence.syncStatus() reads current outbox depth, last successful unscoped sync time and the last attempt's transport failure. It does not probe connectivity. From revision 20 it also reports leaseKind and leaseAgeMs: which kind of run holds the §5.6 sync lease (foreground, background, push, or unknown for a row written by an older host) and how long it has held it, both null when a run starting now would not be refused. Valence.backgroundSync takes a kind: so a push-woken run is distinguishable from the periodic job. Generated schema-3 built-ins expose these as data.getMany and sync.status; ValenceSyncResult.pending counts remaining operations. The runtime constrains path_provider_android to >=2.2.17 <2.3.0 temporarily for pre-JNI compatibility (U-7, checked 2026-10-21); no app override is needed.

Sync correctness: pull cursors advance only through returned rows, never push echoes or a later server-head max. Fresh pairs satisfy OTA activation only after all pages or static chunks complete. Progress resumes after an interruption. Pending publication retains the data lease; GC protects in-flight manifests and retries stale snapshots. Step 7 waits up to five seconds for ordinary sync. Outbox operations use a durable insertion ordinal; database version 2 migrates legacy queued ids, values and deletes without changing bucket cursors or user rows.

System layout and accessibility

ValenceApp publishes --valence-inset-top/right/bottom/left CSS variables, applies Android system text zoom and emits schema-7 app.appearance snapshots. ValenceAppearance supports custom hosts. Add optional fontScale: "num?" to AppInfo and regenerate; older schemas still compile. Apply inset padding in HTML, without an extra native SafeArea. Guide; iOS is experimental and untested.

Background work

Periodic sync needs a host-owned scheduler; valence does not register one for you. Android WorkManager's minimum repeat interval is 15 minutes, and constraints or system optimizations can delay or skip a run. Keep foreground and reconnect sync enabled; periodic work gives no freshness deadline. BGTaskScheduler is best effort on iOS, which remains experimental and untested. See background setup.

Remote push

Remote push is opt-in in schema 12: push.token, passive/explicit push.permission, consuming push.initial, push.received, push.tapped and push.tokenChanged. Firebase runs only in configured hosts; exact data-only sync hints use the existing native sync without touching OTA state. Android notification images use FCM background display; foreground messages reach the page. Device validation is blocked: needs Firebase project. iOS/APNs is experimental and untested. Initialize Firebase and install valence_push, import package:valence_push/valence_push.dart and pass push: createFirebasePush() to Valence.open; register a top-level background callback using ValencePush.handleBackground and Valence.backgroundSync. Setup.

Firebase native dependencies ship only through an installed push package or another app dependency. Hosts using valence_push must target iOS 15.0 or later and initialize Firebase explicitly; core-only hosts do not inherit that Firebase requirement. iOS is experimental and untested.

Valence.dataList(bucket, prefix:, limit:, after:) pages past the 500-row clamp: after is the last key of the previous page and the scan resumes strictly after it, which is the only complete read of a bucket larger than the clamp. Valence.dataCount(bucket, prefix:) counts live rows without reading them. Both are exposed as the version-5 built-ins data.list's after param and data.count. The store opens at <applicationSupportDirectory>/<databaseName> and adopts a 0.3 database left in the application documents directory, moving its -wal and -shm sidecars with it and never overwriting an existing destination. A SQLITE_BUSY open — a schema migration's BEGIN EXCLUSIVE racing the WorkManager job the same launch fires — is retried five times a second apart; Valence.backgroundSync then returns ValenceSyncReason.busy rather than throwing, while Valence.open rethrows, and a failed open is never cached.

Compile links.origins with codegen and register matching native filters. The runtime captures startup links before seed import; link.initial() drains the mailbox, then link.opened delivers live intents. The WebView remains on loopback. See setup and security; iOS is experimental and untested.

Permissions (contracts §4.7)

Use the generated permissions.check, permissions.request, permissions.openSettings and permissions.changed (introduced in the template at 10). For new declarations use since >= max(10, shipped store schema version + 1) and an app schema version at least that high; preserve already-shipped declarations and gate new names with has() on older hosts. The runtime serializes prompts and restricts them to a foreground attached host and its compiled permissionKinds. Empty denies all. Add native declarations and ship a store build; see the permissions guide. iOS is experimental and untested.

Valence.dataList(bucket, prefix:, limit:, after:) pages past the 500-row clamp: after is the last key of the previous page and the scan resumes strictly after it, which is the only complete read of a bucket larger than the clamp. Valence.dataCount(bucket, prefix:) counts live rows without reading them. Both are exposed as the version-5 built-ins data.list's after param and data.count. The store opens at <applicationSupportDirectory>/<databaseName> and adopts a 0.3 database left in the application documents directory, moving its -wal and -shm sidecars with it and never overwriting an existing destination. A SQLITE_BUSY open — a schema migration's BEGIN EXCLUSIVE racing the WorkManager job the same launch fires — is retried five times a second apart; Valence.backgroundSync then returns ValenceSyncReason.busy rather than throwing, while Valence.open rethrows, and a failed open is never cached.

Local reminders

Schema 11 adds built-in local reminders: notify.schedule/cancel/pending/channels.set, notify.permission, consuming notify.initial, notify.tapped/notify.action and best-effort badge.set/clear. Opt in with notifications.enabled, regenerate, install native receivers/icon/desugaring and ship a store build. Exact requests report downgrades honestly; one-shot epoch times need no device timezone lookup. Images are bounded PNG/JPEG bytes; every action opens the UI. Schema 16 adds notify.pendingIds, the same native queue as bare IDs, because a full queue of maximum-size requests is over the bridge reply cap and notify.pending cannot answer the cancel-by-difference refill on the apps that queue the most. iOS is experimental and untested. See setup and adoption.

Schema 15 adds nullable AppInfo.builtins, SyncStatus.reason and BundleStatus.urgent; revision 20 adds nullable SyncStatus.leaseKind and SyncStatus.leaseAgeMs, which name the run holding the sync lease and how long it has held it, so a busy reply can be diagnosed. The age counts from when the holder took the lease, so it only increases while one run holds it. Older hosts omit them. See capability revisions and durable status.

Development startup logs dev: serving upstream <origin> and says OTA checks, trials, ready commits and bundle.applyUpdate are disabled. Each skipped ready, signed reload, update check or apply call also logs a dev: diagnostic. A successful call in this mode does not prove an OTA transition. Restart without VALENCE_DEV_URL for signed offline and rollback validation.

Sync outcomes are an open string set: ok, busy, offline, unauthorized, failed. A non-200 or invalid protocol response reports failed, including a 401 sent to a request without a bearer token. Only a bearer-bearing 401 expires authentication. Partial changes remain applied, queued writes remain available for retry, and incomplete runs never advance the last successful unscoped timestamp. Treat every non-ok outcome as incomplete, even when changed is positive. See contracts section 5.6.

Schema 16 adds notify.pendingIds() for cancellation by difference even when full notification content exceeds the bridge reply cap. Keep notify.pending() unchanged. A new declaration needs since at least max(16, shipped store schema version + 1) and app schema version at least that value; preserve an already-shipped declaration unchanged. Update the tooling, regenerate, ship a store build and guard calls with has(). Disabled hosts still deny the group. No delivery guarantee is added; iOS remains experimental and untested.

Store-host update prompts and signed mandatory policies are documented in Forcing an update. Revision 17 adds fixed-destination app.openStore, nullable status fields and a native blocker; older runtimes cannot be forced.

Revision 18 adds dataCache(bucket, key, value) for disposable REST responses in read-only buckets granted by ValenceConfig.cacheBuckets. Read APIs merge these with synced rows (usn: -2 for cache); pulls remove matching overlays. Cache never queues a write or advances sync freshness. Recorded account changes clear it. New data.cache declarations use since >= max(18, shipped store schema version + 1); keep shipped declarations unchanged. Cache-enabled buckets still need valid sync endpoints when sync is configured; serve a valid empty page/index for an empty bucket, not a 404. Retention is the page's, and nothing backs it up: one value is capped at 65,536 UTF-8 bytes and the row count, total bytes and age are not, so a page that never prunes fills the device. doctor's REST cache row names the grant and the missing ceiling. See the REST cache guide.

Response size grants: compiled http.maxBodyBytes raises the decompressed response cap (default 65536, range 1..262144); requests remain 64 KiB and escaped replies remain capped at 256 KiB. Regenerate and ship a store build. Limits and adoption.

Revision 19 adds explicit bundle.check through the attached host policy path and schema-opted bundle.checked for completed checks, including needsStoreUpdate. It never auto-applies. Usage and host migration.

Sync results retain each committed HTTP page or static chunk even if a later page or lease renewal locks. Acquisition locks remain busy. A release-only lock retains the completed outcome, and so does a lock on the final pendingWrites read, which reports 0 pending; cleanup cannot hide a primary non-lock error. Sync outcomes.

A sync lease row this process wrote is held whichever side of now its timestamp falls, unless it is at least the two-minute TTL ahead. Before this, the clock was sampled before the lease transaction's wait, so a renewal read as future-dated and a foreground run could take a live lease from a background sync. No reported lease age is ever negative. Startup diagnostics.

Lease acquisition samples its clock after the lease query returns inside the transaction. Waiting for the database does not consume a new lease's TTL. No schema change or app code adoption is needed; rebuild the native host (K F-83).

The took the lease log line dates the take-time it records — took the lease kind=foreground pid=1234 (dated 2951ms ago) — because the line is written after the sample, with the row insert and the commit in between. Bracketing took and released in logcat otherwise understates the hold the host reports, by a factor of 33 on a loaded device. Subtract the trail from the line's own timestamp to get the take-time every heldForMs is measured from. It is not the database wait, which is sampled around deliberately and which the store's own waiting line reports; and it floors at zero (K F-85).

Libraries

codegen
The surface valence codegen emits calls to. Not for app code.
valence
The Flutter host runtime for Valence.