Offline & sync
The app stays usable without a perfect connection. Two ambient signals drive this: connectivity (can we reach the network?) and per-store staleness (is cached data current?). Both are soft hints — they escalate to a real error only when a view has no usable data at all. This pairs with error handling.
Connectivity
@enode/core/connectivity is a module store seeded from navigator.onLine and
updated by the online/offline events. apiRequest also feeds it real
reachability: markOnline() on any response, markOffline() when it wraps a
NetworkError/TimeoutError — but not on a caller-driven abort (unmount,
navigation), which says nothing about reachability. So ordinary traffic is a
free heartbeat — no polling while online. useIsOnline() reads it; the ambient OfflineBanner (mounted in the
root layout) shows a soft pill while offline and a brief “Back online” on
reconnect.
Recovery probe while offline
While the store reads offline, ordinary traffic stops: the stores do not retry
a failed load, and their revalidation waits for the offline → online edge. So
startOfflineRecovery (packages/core/src/connectivity/recovery.ts, started in
apps/tracking/src/app/error-handling/ErrorEngineInit.tsx) sends one light
request (GET /user_device_sessions) after 5 s, then on a doubling backoff
capped at 30 s, until the store reads online again. Any response flips the
store online, which revalidates the stores and drains the upload queue. No
probe is sent while the app is in the background or while the OS reports no
network. The portal does not start the probe.
apiRequest also enforces a 15 s timeout (AbortController), so a stalled
request becomes a TimeoutError (→ offline) instead of an endless spinner.
The deadline is enforced in the transport seam (httpFetch,
packages/core/src/api/transport.ts) rather than left to the transport:
Capacitor's native HTTP plugin, which carries every write on a device, does not
honour the abort signal.
The store-status convention
@enode/core/store-kit unifies the previously ad-hoc per-store flags
(lastLoadOK vs data|null + loadError vs per-entry status) into one shape. A
store embeds createStoreStatus() and calls the transitions around its fetch:
const status = createStoreStatus();
// in loadX:
status.markLoading();
try { /* fetch */ status.markReady(/* hasData */ true); }
catch (e) { status.markError(e); }
Views read it via hooks:
const f = useFreshness(exercisesStatus);
// f: { status, hasData, isStale, isOffline, canWork }
canWork === hasData — the rule that encodes “a hint is usually enough; only a
dataless view is an error”.
The view decision tree
For any data-driven view:
- Has cached data? → render it. If
isStale(last refresh failed or offline), show a subtleStalenessHintabove. The user keeps working. - No data + offline? → an offline empty state with retry.
- No data + error? → a real error state (with the backend
userMessage) plus retry / report.
The exercise picker (ExercisePickerDrawer) is the reference implementation: a
failed refresh degrades to a hint over the cached list rather than a blocking
error.
Adoption
The convention is applied to the view-driving stores (starting with
exercises); other prefetch stores adopt it incrementally — embed
createStoreStatus(), call the transitions, read with useFreshness. New stores
should follow the same shape.
Offline training persistence
The store-status convention above is the read side. The write and
durability side — crash-safe in-session persistence, a deferred upload outbox,
and downloading a day for fully-offline training — lives in
@enode/core/offline and is specified by
ADR 0002 — offline training persistence:
- Plan A persists the live session tree + draft to IndexedDB and queues the
finished workout's wire payload before the network call, draining it when
connectivity returns (so a finish never blocks on signal). The drain
(
use-upload-drain.ts) runs on the OSonlineevent, on a return to the foreground, when the backend becomes reachable again (the reachability store's offline → online edge — a Wi-Fi without internet never firesonline), and every 60 s while a batch waits only for connectivity. - Plan B (the offline copy of the schedule) caches the loaded workouts and
each athlete's exercise instances — automatically after every successful
schedule load (
refreshOfflineDayInBackground; Sync now on the schedule status line is the manual refresh — it renews the copy even when it looks fresh, through the same path, so it also takes the coming seven days and an athlete's device copies only their own exercises), and usable for up to seven days, not just on the day it was made — and snapshots the global reference catalogues (metrics, text-content, equipments, exercise-variations, tags, display-bases, feedback-modes, data-package-types, tracking-source-settings, app-languages) so the app can cold-start with no network. Reference stores snapshot themselves on each successful load (reference-cache.ts) and fall back to the snapshot when their fetch fails; the tracking-source settings apply theirs while the fetch is still running, because the sensor records nothing without them. Two per-account records use the same cache, stamped with the user id and applied only to that account: the app settings (user-app-settings/store.ts— set timeout, focus metrics, units; offline the language stays on the locale mirror) and the signed-in user's profile (current-user/store.ts— role, recording licence, wellness eligibility). The exercise catalogue and the roster are snapshotted per account as well (offline/account-snapshot.ts), so a workout can be composed after a launch without a connection; an empty store takes its snapshot while the first load is still running. The template library and the UI-string catalogue have the same kind of fallback. - Unbound sessions (ADR 0002 amendment 7). A session records into the
athlete's exercise instance, an id only the server issues. When the server
cannot be asked for it — offline, unreachable, or the request fails — and the
day bundle does not cover the pair, the session starts unbound and
records exactly like any other; nothing blocks the start, an ad-hoc workout
included. Only what needs the athlete's history is missing (1RM baseline,
load suggestions), and the training view says so. The session is bound in
place as soon as the server answers, and at the latest when the finished
training uploads (
postSessionBatch). An exercise swapped in mid-training under the same conditions moves its session to the new exercise unbound. A pair the server answered it has no instance for still gets no session. An athlete or exercise added mid-training follows the same rules; whatever pair still has no session is retried when the connection returns, and its warning is withdrawn as soon as the session exists or the athlete or exercise is removed again. - Nothing recorded is dropped silently (ADR 0002 amendment 9). A training
the server rejects is split and re-sent one session at a time, so only the
rejected session stays queued; a batch the server keeps failing on stops
blocking the ones behind it; the finish asks before discarding reps that were
recorded but never saved as a set; a device that can no longer store shows a
warning in the training view, and its finish goes to the server directly; and
a 401 during a training postpones the logout until the training is over
(
auth/unauthorized-hold.ts). - Questionnaire answers (ADR 0002 amendment 11). A wellness check-in or a session RPE given in the embedded questionnaire is stored and sent by the app, not by the embedded page: kept in the offline database until the server has it, sent on the same opportunities as the session uploads, and — for a session RPE — only after the training it rates has uploaded. Takes effect once the deployed questionnaire service supports the handover; until then the service sends the answers itself. The questionnaire still has to be loaded from the network.
- One rejected session no longer holds back a training (ADR 0002 amendment 13). Uploads ask the server to accept a request session by session and act on its per-session answer: what it stored leaves the device, what it rejected stays queued with the server's reason. Against a backend without that answer the queue falls back to re-sending a rejected training one session at a time.
- A past workout being logged survives a restart (ADR 0002 amendment 12). What is typed into "Log past workout" is written to the device while it is typed and reopened at the next launch, until it is uploaded or discarded.
- A finish is visible (ADR 0002 amendment 10). The finish confirms with a toast whether the training is uploading or waiting on this device; the schedule marks workouts recorded today on this device ("Recorded today", with "upload pending" while their sessions are queued); and the pending count shows on the station header's sidebar button where the sidebar itself is not pinned.
- Account switch. The offline database belongs to one account (ADR 0002
amendment 2). When a different account signs in while the device still holds
unsynced uploads, videos or in-progress trainings,
login/registerstop before storing the token (OtherAccountOfflineDataError) and the sign-in asks before deleting them. Logging out with unsynced data asks too (LogoutButton).
A database connection the platform took away
WebKit closes a WebView's IndexedDB connection while iOS holds the app
suspended. The wrapper (packages/core/src/offline/db.ts) reopens the
connection once and repeats the unit of work when a call fails with
InvalidStateError (the transaction could not be opened), UnknownError
("Connection to Indexed Database server lost" and similar) or an abort without
a cause. Repeating is safe: a transaction that failed or aborted was rolled back
as a whole. A failure with a cause of its own, such as QuotaExceededError, is
not repeated.
A database that is NEWER than the build asks for (an older build installed over
a newer one) is opened at the version it has instead of failing every call. The
upgrade is additive, so the newer database holds every store the older build
uses. Builds up to 3.0.7 do not have this fallback: installing one of them over
a build with a higher DB_VERSION leaves it without offline storage.
An upload the server refuses
A session the server rejects stays in the queue and is retried, but retrying
alone never delivers it. A manual retry therefore says so and offers "Report",
which sends the server's status and reason to support
(latestUploadRejection). For the uploader's own sessions the client sends the
exercise definition along (selfUploadExerciseDefinitionID), so the server can
replace an exercise id it no longer knows. It does not for an athlete's session
uploaded by a coach: the server would attribute the recovered session to the
coach.
A measurement whose number is NaN or infinite would serialise as JSON null
and fail the whole request: the rep builders drop such readings, the mapper
leaves such measurements out, and postSessionBatch strips them from batches
queued before that (dropMeasurementsWithoutValue).
Every batch also records each session's exercise definition and athlete
(exerciseRefs). When the server answers exercise_not_found for a session
(the exercise was merged away after the training), the uploader binds it to
the athlete's current instance for that definition and sends it once more in
the same drain (rebindRejected in api/sessions.ts); a coach's upload of an
athlete's session stays the athlete's that way. Batches queued before the
field existed cannot be rebound.
A video the server refuses is dropped from the outbox and stays on the device;
the user is told once per drain (video-drain.ts). Every reviewable set video
offers "Save video to device" in the Technique view (save-video-button.tsx,
saveVideoToDevice in @enode/core/video), which copies it into the photo
library — the only durable place for a recording when the account has no cloud
video storage.
The retry message of a rejected upload also offers "Export": the stuck batches
as a JSON file through the system share sheet (export-stuck-uploads.ts), so a
training the server never accepts still exists outside the app's database and
can be replayed by support.
Loading only what changed
On a native build GET /text_contents is asked with If-Modified-Since (epoch
seconds, as the server reads it) for the rows changed since the last complete
load; the response lists every current id, so deleted rows are dropped as well
(mergeTextContentDelta). The header is not in the API's CORS allow-list, so a
browser build keeps loading the whole table. A state older than a day is
reloaded in full: the server filters on the text's own change time, which a
changed translation does not necessarily move.
Testing it
The debug area has a one-button offline self-test that runs all of the above on the device — a server that goes silent, an upload whose answer is lost, a rejected session, a training that has to survive a kill — against simulated network faults, and writes a protocol to copy out.
Still a non-goal: caching media/Lottie assets for offline. The media
catalogue (packages/core/src/media/store.ts) lives in memory only: cards wait
for the two bulk requests, and after a launch without signal they show their
fallback until a bulk retry (on reconnect, focus, or the next card mounting)
succeeds.