Migrating from 0.3
In 0.3, /valence init generated the host runtime — about 1,500 lines of Dart — into your Flutter
project, and copied a client.ts into your web app. Every app therefore carried its own copy of the OTA
verification, the rollback state machine and the bridge trust boundary, and a fix to any of them reached
nobody. During test week one bug in the rollback loop had to be fixed by hand in four separate apps.
From 0.4 the runtime is two published packages:
valence on pub.dev |
The whole Flutter host |
@getvalence/bridge on npm |
The whole web client |
valence codegen now emits only what depends on your schema, and imports the rest.
Before you start
Section titled “Before you start”If you shipped a custom link.initial before schema 9, keep its handler and your
link.opened emitter. A since: 2 method returning string? remains app-owned;
the package’s nullable {url, path} method delegates only from since: 9.
Keep the shipped signature, event payload, since and baseline unchanged.
Do not rebaseline or renumber to migrate. Keep your routing adapter instead of
onLink, which expects the modern shape, and leave links.origins empty while
your own native listeners deliver links. See deep links.
- Commit everything. This deletes files.
- Note your database file name. If your 0.3 host called it anything other than
valence.db, you need one config line — see keeping your database. - Keep
.valence/baseline.json. It is what makes the additive-only schema guard work, and a missing one reads as “no store build yet”, which silently switches the guard off.
1. Update the tooling
Section titled “1. Update the tooling”npx create-valence@latest updateThat replaces valence/valence.mjs and the /valence skill and its agents. Then start a new Claude
Code session, because a session that was already open does not pick up a skill that appeared mid-session.
2. Add the two packages
Section titled “2. Add the two packages”cd <your flutter host> && flutter pub add valencecd <your web app> && npm install @getvalence/bridgeInstalling a prerelease tarball from a fixed path? Check the lock entry, not the file. npm install ./vendor/getvalence-bridge.tgz records the tarball’s SHA-512 in package-lock.json, and replacing the
file at the same path does not change the path — so npm can satisfy the dependency from its integrity
match and keep the older contents, --force included. Verify the lock entry against the tarball you
actually have, and if it disagrees, npm uninstall @getvalence/bridge and install it again rather than
reinstalling over it. Installing by version from npm cannot hit this; a vendored prerelease at a stable
path can, and the symptom is a build whose bridge is one snapshot behind with nothing warning about it.
flutter pub add valence brings the verified stack with it: webview_flutter, sqflite,
path_provider, cryptography, crypto, http, url_launcher and connectivity_plus. Remove those
from your own pubspec.yaml only if nothing else in your app uses them directly.
workmanager is not one of them. The package deliberately does not depend on it — it applies the Kotlin
Gradle Plugin and warns on every Android build — so if you register background sync, keep it, and point
it at Valence.backgroundSync(valenceConfig).
3. Delete the generated runtime
Section titled “3. Delete the generated runtime”From your Flutter host:
lib/valence/server.dart → ValenceServerlib/valence/updater.dart → ValenceUpdaterlib/valence/store.dart → ValenceStorelib/valence/sync.dart → ValenceSynclib/valence/host.dart → ValenceApplib/valence/bridge.dart → the generated ValenceBuiltins, plus your own methods (step 4)lib/valence/manifest.dart → if your host had onelib/valence/state.dart → if your host had oneFrom your web app:
<web lib>/client.ts → @getvalence/bridgeKeep lib/valence/bridge.g.dart, lib/valence/config.g.dart and <web lib>/bridge.g.ts — codegen
rewrites them in step 5 — and keep <web lib>/shim.ts, which is your own browser fallbacks.
Your 0.3 host’s Dart tests for the updater, the state machine, the store, the bridge and sync can go too. That is the §8 test matrix, and it is now the package’s own suite, run on every release of the package rather than once in your repo. Keep any test of your own bridge methods.
4. Write the two small files
Section titled “4. Write the two small files”lib/main.dart becomes about twenty lines:
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, hostBuild: 1); final handlers = AppHandlers(valence); runApp( MaterialApp( home: ValenceApp( valence: valence, dispatch: (raw, nonce) => bridgeDispatch(handlers, raw, nonce: nonce), ), ), );}hostBuild is your Android versionCode or iOS CFBundleVersion. It is what app.info reports as
host.
lib/valence/handlers.dart keeps only the methods your 0.3 bridge.dart wrote itself:
import 'package:flutter/services.dart';// BridgeError and BridgeErrorCode come from here, not from bridge.g.dart.import 'package:valence/valence.dart';
import 'bridge.g.dart';
class AppHandlers extends ValenceBuiltins implements BridgeHandlers { AppHandlers(super.valence);
@override Future<void> hapticsTap() async => HapticFeedback.lightImpact();
@override Future<String> somethingThatCanFail() async { throw BridgeError(BridgeErrorCode.unsupported, 'not on this platform'); }}Delete your implementations of app.ready, app.info, data.get, data.list, data.put, sync.now,
prefs.get, prefs.set, open.external, bundle.applyUpdate and, from 0.4, secure.* and auth.*. The generated ValenceBuiltins
implements all of them by delegating to the runtime — and that is where the policy for them lives: the
writable-bucket check, the reserved valence. prefs keys, the open.external scheme allow-list and the
data.list clamp. Keeping your own copies is exactly how those drift.
The analyzer is your checklist. Anything still abstract on BridgeHandlers is a method the package does
not implement, which means it is yours.
5. Regenerate and check
Section titled “5. Regenerate and check”node valence/valence.mjs codegencd <your flutter host> && flutter pub get && dart analyze --fatal-infos lib test && flutter testconfig.g.dart changes shape. 0.3 emitted five loose constants; 0.4 emits one valenceConfig:
| 0.3 | 0.4 |
|---|---|
valenceAppId |
valenceConfig.appId |
valenceKeyring |
valenceConfig.keyring |
valenceOtaBase |
valenceConfig.otaBase |
valenceSyncBase |
valenceConfig.syncBase |
valenceWritableBuckets |
valenceConfig.writableBuckets |
If codegen refuses with “is implemented by the valence package, so its params must stay …”, your
schema redefined a built-in method. Those are delegated to the runtime, so a changed shape would compile
and then pass the wrong arguments — a bug only a device would find. Restore the shape it names and add
your variant under a new name; the schema is additive only
in any case.
Adopting a built-in that replaces a method of your own — notify.schedule for a hand-written
notify.daily, say — leaves the old name behind, because codegen refuses to remove a method a store
build shipped. Once nothing calls it, mark it
"retired": true: the declaration stays, so
has() and every bundle already in the field are unchanged, and the generated ValenceBuiltins answers
it with E_UNSUPPORTED — so the handler and the native code behind it can finally be deleted.
On the web side, your imports move from client.ts to the generated file:
// 0.3import { call, has, on, ready, connect, BridgeError } from '$lib/valence/client';
// 0.4import { call, has, on, ready, connect, BridgeError } from '#lib/valence/bridge.g';Import from bridge.g.ts, not from @getvalence/bridge. The generated file is what binds your
method table, so call('data.get', { bucket, key }) is type-checked against your schema; importing the
package directly loses that. Your shim.ts can now be typed as the generated AppShim, which turns a
fallback with the wrong signature into a compile error.
Three things to check in your own web app
Section titled “Three things to check in your own web app”The packages fix these for you in the host. These three are in code only you can change.
- Does
ready()run on every screen that can be the first one? The rule was always “after the first meaningful paint”, and the natural place to put it is the end of the data load. A first-run gate, an empty state, a permission prompt and an error screen all paint without that load finishing, and on a fresh install one of them can be the whole first launch — after which the host counts a failed trial and rolls back code that was never broken. Put the call in afinally, or in a mount effect every rendered path reaches. More in the web-app guide. - Does your build register a service worker? It will answer from Cache Storage without asking the
host’s server, which revalidates every bundle file against its hash — so a new release can render as
the old one, and the trial will commit on that old page’s
ready(). Inside the app you do not need one: the bundle is already on the device. Register it only wheninHost()is false.valence bundlewarns if it sees a registration. - Do you want to know whether a sync actually ran?
SyncResultcan now carry"reason": "string?"—"ok","busy"or"offline". Without it a run the sync lease refused to start is indistinguishable from “already up to date”, so a freshness indicator lies. Add the field to yourSyncResulttype and runcodegen; it counts as additive even against a schema a--storebuild recorded, so no--rebaseline. Keep the null check until the store build that has the field is the oldest one you support — your host ships in the APK, your page ships in a bundle.
If you wrote any part of your own host rather than using the package, also change bundle files from
Cache-Control: immutable to no-cache with the file’s sha256 as an ETag. That one is not optional:
immutable means your updates can silently not happen and your rollback cannot tell.
Why.
Optional: take the 0.4 auth methods
Section titled “Optional: take the 0.4 auth methods”Nothing in the migration requires this, but if your app has a login, 0.4 is the release that gives it
somewhere to keep a token. Add five methods and one event to valence/bridge.schema.json, bump
version to 2, and run codegen again:
"secure.get": { "since": 2, "params": { "key": "string" }, "returns": "string?" },"secure.set": { "since": 2, "params": { "key": "string", "value": "string" }, "returns": "void" },"secure.delete": { "since": 2, "params": { "key": "string" }, "returns": "void" },"auth.setToken": { "since": 2, "params": { "token": "string?" }, "returns": "void" },"auth.hasToken": { "since": 2, "params": {}, "returns": "bool" }"auth.expired": { "since": 2, "payload": {} }They are built-ins, so there is no handler to write — ValenceBuiltins delegates them to the package.
What they do and what they deliberately do not do is Login and secrets.
If the device can be shared, take the account switch with them: two more
params on auth.setToken and one more method, at version 13 rather than 2.
The bump has one consequence: requires.bridge follows the schema version, so your next OTA release
declares 2 and the hosts already in the field stop taking it until your store build lands. If you need
one more release to reach them, pin it with valence bundle --requires-bridge 1.
Keeping your database
Section titled “Keeping your database”The package opens <applicationSupportDirectory>/valence.db. If your 0.3 host chose a different file
name, say so once in valence/valence.config.json:
{ "host": { "dir": "mobile", "database": "my_app.db" }}codegen puts it into valenceConfig.databaseName, and the package reads your existing rows.
The directory is fixed, and the package moves a 0.3 database into it
Section titled “The directory is fixed, and the package moves a 0.3 database into it”host.database names the file. The directory is not configurable, and in 0.4 it is always the
application support directory.
That matters because 0.3’s spec never named a directory — it said only that the database lives outside
valence/ — so a 0.3 host could legitimately have used either path_provider directory. On Android they
are different places:
path_provider call |
Android path |
|---|---|
getApplicationSupportDirectory() — what 0.4 uses |
/data/user/0/<applicationId>/files |
getApplicationDocumentsDirectory() |
/data/user/0/<applicationId>/app_flutter |
If your 0.3 host used the documents directory, the package moves the database for you on the first 0.4 launch, before it opens anything:
-
it moves the
-waland-shmsidecars with it, and the.dblast — moving the.dbalone would discard every commit still in the write-ahead log, which for a syncing app is the last sync; -
it never overwrites a database already in the support directory, so a device that has run 0.4 before is left alone;
-
it logs one line, which is how you confirm it happened:
I flutter : store: moved the 0.3 database to /data/user/0/dev.example.app/files(valence.db, valence.db-wal, valence.db-shm)
The package does this rather than your main() because it is the only component that knows nothing else
holds the file open yet. You do not need legacy_db.dart-style code of your own.
What does not change
Section titled “What does not change”lastSyncedAtis the exception, and it readsnullon the first launch.sync.statusis new in 0.4, so no 0.3 host ever wrote its timestamp. A migrated device therefore reportslastSyncedAt: nullwhile holding a complete, current database — and the honest rendering ofnullis “Never synced”, under data that is anything but. It self-corrects on the first 0.4 sync, which is usually seconds after launch, and there is no setter to seed it. If your UI shows freshness, treatnullas “not known yet” rather than “never”: say nothing instead of saying something false.pendingand the last-attemptofflineflag are correct from the first call.state.jsonstays at<appSupport>/valence/state.jsonand is read as written. 0.4 adds one field,builtinRefused; an absent field reads as null, and an older host ignores a field it does not know.- Your CAS files and manifests carry over. The package re-verifies a manifest on disk before serving it, so nothing has to be re-downloaded.
installIdcarries over, so a device stays in the same rollout cohort and keeps the same derived loopback port — which means the page’s web storage survives too.- Your signing key,
keyring.jsonand.valence/baseline.jsonare untouched.seqandfloorkeep rising. This is not a key rotation. - The bundle format, the manifest, the wire protocol and the sync protocol are unchanged. An OTA bundle built by 0.3 is served by a 0.4 host, and the reverse.
The release that ships it
Section titled “The release that ships it”Swapping the host runtime is a store release: lib/ changed, so the binary changed. Nothing about it
reaches existing devices over the air.
node valence/valence.mjs bundle --builtin, thenverify.node valence/valence.mjs bundle --store, which records the reviewed routes and schema.- Build, submit, and only then stage OTA releases on top. See Releasing.
Run /valence doctor first. It compares the built-in manifest’s requires.bridge against the generated
hostBridgeVersion, which is the one mismatch that leaves a fresh install with
nothing to serve.
- The host guide, for what your app still owns
- The bridge guide, for the built-in methods and how to add your own
- What beta means
Existing APIs in 0.4
Section titled “Existing APIs in 0.4”Your own backend documents http.request (since 4; version 3 provides batch reads and sync status), its generated HttpResponse {status, headers, body}, and the reference REST sync adapter. Regenerate and ship a store build for the new method and compiled http.origins origins; guard calls on older hosts with has(). The host attaches the R1 token, returns redirects without following them, caps request bodies at 64 KiB, decompressed response bodies at compiled http.maxBodyBytes (default 65536, range 1..262144), and headers at 16 KiB, and applies a 20-second deadline. An authenticated 401 also emits auth.expired once per request (E_TIMEOUT for the deadline, E_OFFLINE when the OS reports no network interface, E_INTERNAL otherwise; size refusals name the size and the limit; http.cookieJar optionally gives one compiled origin a host-held cookie jar, so a cookie-paired CSRF token can be completed without the page ever seeing a cookie, and without it a session-cookie API is out of scope). Native HTTP is online RPC; offline records still need SQLite and the sync protocol. Android is tested; iOS is experimental and untested.
The database-version-2 upgrade preserves existing queued operations and gives them a durable insertion ordinal. Pull progress is separate from completed pairs, and updater step 7 retains the sync lease until pending publication finishes. See complete pulls and ordered writes.
For the new host layout, add inset-variable content padding and keep text flexible: Safe areas and accessibility. Android applies native text zoom; avoid multiplying it again. Optional AppInfo.fontScale preserves old schemas.
Optional deep links
Section titled “Optional deep links”Schema 9 adds link.initial and link.opened. Regenerate, compile links.origins and register matching native filters in a store build. Existing schemas keep working; onLink() is inert on older hosts. Follow deep-link setup.
Local reminders
Section titled “Local reminders”When adopting this runtime, enable Android core library desugaring; valence codegen writes both Gradle lines. For built-in local notifications, add native receivers and a status drawable, opt in with notifications.enabled, regenerate and ship a store build. Reserve distinct IDs when retaining app-owned notifications. Setup and API details.
Remote push
Section titled “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. Install the optional valence_push package and pass createFirebasePush() after Firebase initialization; core-only hosts do not include Firebase. 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. See Remote push for the required native setup, top-level background callback, images and test checklist.
Hosts installing valence_push require iOS 15.0 or later for Firebase. Core-only hosts no longer inherit Firebase. Upgrade Runner/extension target settings for push hosts; iOS remains experimental and untested.
Schema 15 adds nullable builtins, persisted sync reason and signed pending urgency. Capability revisions and durable status explains the schema opt-in, older-host fallbacks and scope limits.
Custom notification events: preserve the shipped payload and since values. Regenerate config, pass a native notificationEventAdapter to Valence.open for warm taps, and reuse the conversion for consume-once cold responses. Do not reinitialize the shared plugin. See the legacy event recipe.