Skip to content
Valence is in beta. The bundle format and update protocol are meant to stay stable; the CLI, the generated code and the two runtime packages’ APIs may still change. What beta means

Lifecycle, connectivity and updates

A page in a browser tab can answer two of these from the platform — document.visibilityState and navigator.onLine — and is never asked the third. Inside the host all three belong to the host, and until 0.4 all three were answered by inference:

  • app.resumed fired on the way back in, with nothing on the way out. A page could not save a draft when the user swiped away, because it never heard about it.
  • SyncResult.offline described one past attempt. It was the only connectivity signal, so an offline banner could only appear after something had already failed.
  • An update that declined to apply was visible only in the native log. pending stayed null, and “rolled out to 10% of installs”, “still pulling the data this release needs” and “this release is signed with the wrong key” were one indistinguishable answer.

0.4 adds three events and two methods, all at bridge version 6.

import { call, on } from '#lib/valence/bridge.g';
// State, so read it on mount rather than waiting for the next change.
const { lifecycle, online } = await call('app.state');
on('app.lifecycle', ({ state }) => {
if (state === 'background') saveDraft(); // the last state with a live page
});
on('app.online', ({ online }) => setBanner(!online));
on('sync.done', ({ result }) => setLastSynced(result));

Four states, not Flutter’s five. The host does the mapping so your page reads the same four on either OS:

Platform state state
resumed foreground
inactive inactive
hidden, paused background
detached detached

Only a change is emitted. Android delivers hidden and then paused for one backgrounding; that is one transition, so it is one event. A page that counted events would otherwise count two.

Three things worth knowing before you write a handler:

  • inactive is not backgrounded. It is the transient state behind the notification shade, a permission dialog or an incoming call. Treat it as foreground unless you specifically mean “not interactive” — a video paused on inactive flickers every time a notification arrives.
  • detached will usually not arrive. The engine is tearing down, so there may be no WebView left to run the script. Never persist from detached. Persist on background, which is the last state with a live page.
  • app.resumed still fires, unchanged, and is app.lifecycle with state: "foreground" plus the host’s resume work having started. Listen to one or the other, not both.

What this looks like on a real Android device, measured on an API 36 emulator: pressing Home delivers inactive first and background about three seconds later; coming back delivers inactive and then foreground within the same second. The handler really does run while the app is off screen — the page receives the background event with a timestamp from while it was backgrounded.

That three-second gap is why background is not a pre-kill hook. It is the right place to save a draft or flush a cache, because a user who switches away usually comes back. It is the wrong place to rely on when the OS kills the app to reclaim memory, because by then the event may never have been delivered. Route and draft survival after a kill is a separate mechanism — the host saves the route itself, and state.save holds your blob.

For route and draft restoration after the OS kills the app to reclaim memory, there is a separate mechanism — the host saves the route itself, and state.save/state.restore hold a small blob. This event is about the transition; that is about surviving the process.

on('app.online', ({ online }) => { … });

It reports what the OS says about network interfaces, and it is not reachability. It comes from the same source as the host’s “connectivity came back” sync trigger. A device on captive-portal Wi-Fi, or behind a firewall, or whose server is simply down, is online: true and every request still fails.

So the honest pair is:

  • app.online to decide whether to try — enable the retry button, start the upload.
  • SyncResult.reason or sync.status().offline to say whether the last attempt worked — the freshness line, “last synced 3 minutes ago”, the stale-data warning.

A freshness indicator built on app.online alone lies, confidently, on exactly the networks where it matters. “Online” means an interface exists; it does not mean your API answered.

Like the lifecycle event, only a change is emitted, and the host reads the current value at start-up rather than waiting for one — so app.state() has an answer before anything has changed.

const { lifecycle, online } = await call('app.state');

Both of the above are state, not notifications, and a page that mounts after the transition would otherwise learn nothing until the next one. That page is not hypothetical: a cold start from a notification tap, and the reload an applied OTA update does, both begin after the interesting transitions have happened. Read app.state() on mount and subscribe for the changes after it.

The defaults before the host knows better are foreground and online: true, deliberately. Your page only ever runs while the app is on screen, and a UI that refuses to try on a working network is worse than one that tries and fails.

This is not optional politeness — it is the only way to get the value. Unlike every other host event, the two state events are not buffered: if no page is loaded when the state changes, the host drops the event rather than queueing it. Queueing would mean an unbounded list on a host whose page never loads, holding transitions that are stale by the time anything reads them. The host still records the change, so nothing is lost — read app.state() on mount and subscribe for what happens after.

on('sync.done', ({ result }) => setLastSynced(result));

It carries the whole SyncResult — the same record sync.now returns — after every sync run the host made on its own: UI start, resume, connectivity returning, a data.put’s push, and the periodic background run that happens while your page is not on screen.

sync.changed tells you which buckets moved, which is what you want for refetching. What it cannot tell you is that a run finished and moved nothing, and that is most runs. Before sync.done, a run with changed: 0, a run blocked by another sync (busy) and a run rejected with a 401 (unauthorized) emitted no event at all — so a “last synced” line could only ever be updated by a sync your page had asked for itself, and it went stale while the host was working perfectly.

The two are ordered: sync.changed first, so your data is refetched, then sync.done. If your schema declares sync.done, it must also declare the SyncResult type.

One run cannot report itself: the periodic background sync. It runs in a background isolate with no WebView to reach, and no host can change that. Its work is still visible — it moves the data, so the next foreground run’s sync.changed names the buckets, and sync.status() has the new lastSyncedAt — but there is no sync.done for it. So don’t read “no sync.done since I loaded” as “nothing has synced”; call sync.status() on mount, the same way you call app.state().

const { serving, pending, trial, reason, offered, checkedAt } = await call('bundle.status');

Why an update declined, and what is waiting. It reads state the host already keeps and never starts a network request, so a page may poll it.

Don’t drive it by polling alone, though — bundle.updateReady is the push signal that pairs with it. The host emits it with the new seq the moment a bundle becomes pending, for every pending bundle and not only an --urgent one. Read bundle.status() on mount, re-read it on bundle.updateReady, and the “an update is ready” line appears as soon as there is one:

const [update, setUpdate] = useState<BundleStatus | null>(null);
const refresh = async () => setUpdate(await call('bundle.status'));
useEffect(() => {
refresh(); // the check may have finished before this page loaded
return on('bundle.updateReady', refresh); // and the moment one lands while it is open
}, []);

Reading only on app.lifecycle foreground races the update check: both run on resume, and the check finishes a few hundred milliseconds after the read, so the page shows nothing until the resume after the one that found the update. The event closes that gap. If no page is loaded when the bundle becomes pending the event buffers and flushes on the next load, so the mount read and the subscription together never miss one.

urgent on the manifest does not control whether the event fires — it is the release saying it would like to be offered mid-session, and bundle.applyUpdate promotes any pending regardless.

The host releases the sync lease and publishes the completed status before notifying the page, so an event-driven status read sees the ready reason, offered sequence and timestamp together.

Field Meaning
serving the seq of the bundle on screen; 0 before one is served
pending a verified bundle waiting for bundle.applyUpdate, or null
trial the seq on probation, or null — equal to serving while a trial is on screen
reason why the last completed check ended as it did
offered the seq the pointer offered on that check, when it got that far
checkedAt when that check finished, epoch milliseconds, or null before the first one

reason is a closed set, and each value is a sentence you can show:

reason What it means What to show
idle no check has finished yet nothing; don’t claim freshness
unconfigured the app has no ota.base, so it never checks nothing. Not a fault
uptodate the pointer offers nothing above current, pending or trial “up to date”
rollout a newer release exists; this install is outside its rollout percentage “not yet available for this device”
bad the offered seq is on this install’s rejected list, for ever nothing user-facing; it will never be offered again
offline the pointer, the manifest, the signature or a file could not be fetched “could not check on the last attempt”; historical until another check completes
rejected the manifest or a file failed its checks nothing user-facing — alert yourself
needsStoreUpdate verified offer needs a newer store host (revision 17) “update the app from the store”; setup and mandatory policies
toobig over the bundle size cap, or the data pull hit its cap “update too large on this connection”
waitingForData the release is downloaded but its requires.data pairs are not synced yet “preparing an update”
busy another sync held the lease; the next check retries nothing; it is transient
ready a pending is waiting “restart to update”, and call bundle.applyUpdate

Two of these deserve a second look.

rejected is the one to wire into your own telemetry. It means a published release is unservable — a wrong signing key, a tampered file, a manifest for a different appId — and the device refuses it. Legacy status shapes without requiredBridge also use rejected for host incompatibility; revision 17 distinguishes that case. It is the only reason in the set that describes a broken release rather than a working system, and before bundle.status the only way to see it was to read a phone’s log.

waitingForData is where an update sits indefinitely, and it is the state four hosts mistook for “no update”. A release that bumps a read-only bucket’s schema cannot be served until that bucket has been pulled, and on a device that is offline — or whose server has not published the pair yet — that is a healthy, permanent-looking stall. Showing “preparing an update” is the difference between a user who waits and a bug report.

A reason your page does not recognise means “no update right now”, never an error: a newer host can return a value that did not exist when your bundle was built. The set is closed the same way the bridge error codes are — new values are added to the spec, not invented per app.

All five are since: 6. A store build older than that does not have them:

if (has('app.state')) {
const { online } = await call('app.state');
}

has() works on the event names too, which matters more here than it looks. Subscribing to an event an older host has never heard of succeeds and then never fires — nothing throws, nothing logs, and the feature behind the listener simply stops happening:

// Gate the feature, not the subscription.
if (has('app.lifecycle')) on('app.lifecycle', ({ state }) => state === 'background' && saveDraft());
else window.addEventListener('beforeunload', saveDraft); // the web fallback, on an older host too

On the web has() is false for every event, because there is no host to emit one — so the same branch that covers an old host covers the website build.

has() is the gate, and requires.bridge is how a bundle refuses an older host outright. The bridge guide covers the rules; the short version is that calling an unimplemented method returns E_UNSUPPORTED rather than crashing, and your page should degrade rather than assume.

app.info().bridge is not a second gate. It is your app’s own schema version, which you number yourself, so it tells you nothing about which built-ins this host carries — see the bridge guide.

Android is tested. The lifecycle mapping, the double hidden/paused delivery, the connectivity list and the update reasons were all exercised on Android.

iOS is experimental and untested. The code paths are the same Flutter and plugin APIs and are expected to work, but there is no Apple hardware on the machines Valence is developed on, so nothing here is verified on iOS. In particular the detached state and the exact ordering around suspension differ between the platforms, which is another reason to persist on background.

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.

Live-interface connectivity reports while foregrounded now retry the signed update check, including Wi-Fi/cellular handovers. Background reports sync only and leave update discovery to resume. offline describes the completed attempt at checkedAt until another one completes, not current reachability. An immediate status read on app.online can race the check. Listen for bundle.updateReady when a verified bundle becomes pending, and re-read status for completed observations. See Update checks after reconnect.

For a freshness line, reason: "failed" means “Could not sync”, even if some rows changed. A response from the server is not proof that the run succeeded. See Sync outcomes.

Revision 19 adds bundle.check and bundle.checked: request discovery explicitly, and re-read bundle.status after every completed check, including needsStoreUpdate. bundle.updateReady remains limited to bundles that become pending. Refresh tooling, declare the new names, regenerate and rebuild the host to opt in.