Refactor mobile recording, auth, sync, and attachment upload lifecycles into explicit state machines
Summary
Context: Mobile recording, auth session restoration, CloudSync/background-sync lifecycle, and private attachment upload completion previously relied on loosely coordinated booleans and unguarded async continuations. A stream write failure during startup could be overwritten back to "recording" while leaving captureActive stuck true and blocking _layout.tsx auth/Pro gates, unmounting during recordSessionCaptureStart could leak an open SessionWavWriter, stale getSession() or offline fallback resolutions could clobber a deep-link setSession() or resurrect a signed-out session, hourly JWT rotation remounted MobileSyncLifecycle while racing one-time enrollment consumption and unsequenced native.setEnabled(false)/true calls, and an in-flight attachment upload finishing after opt-out or tombstone marked the upload job complete without deleting the uploaded private-cloud object.
Intention: Replace these implicit mobile lifecycle flags and async races with explicit discriminated state machines so every transition is guarded, serialized, and leaves no leaked handles or orphaned cloud objects.
Direction:
- Audio recording (
recorder-status.ts,use-session-recorder.ts,listening-sheet.tsx): Introduce a typedRecorderMachineState+transitionRecorderStateguard, prune unreachable"interrupted","media_services_reset", and"native_error"variants, derivecaptureActivedirectly from active capture phases so"save_error"immediately releases_layout.tsxauth/Pro routing, check active run/state after everyawaitinperformStart, and deterministically close/discardSessionWavWriterand pending capture state on unmount during startup. - Auth & sync (
auth/session-machine.ts,auth/context.tsx,sync/controller.ts,sync/mobile-sync.ts,sync/background-sync.ts,sync/mobile-sync-lifecycle.tsx,app/_layout.tsx): Add a monotonic-epochAuthSessionMachineso stalegetSession(), offline persisted fallback,INITIAL_SESSION,TOKEN_REFRESHED, and in-flight billing refreshes never overwrite a newer deep-linksetSession()or resurrect an explicitsignOut(). KeyMobileSyncLifecycleon${user.id}:${cloudSyncEnabled}with live token refresh (updateAccessToken/getAccessToken), guard one-time recovered enrollment commit/consumption inMobileSyncControlleragainst same-account JWT-rotation remounts, and serializebackground-sync.tsnativesetEnabled/setPendingWork/finishBackgroundFlushtransitions with per-epochlastReportedreset. - Private attachment upload completion (
attachment-sync/upload-store.ts,attachment-sync/upload-runner.ts): Distinguish explicit upload completion outcomes (committed | orphaned_by_opt_out_or_delete | superseded), atomically enqueue adirection = 'delete'transfer job (plus durable blind delete refs) whensession_attachmentsupdate affects 0 rows due to opt-out or tombstone, and drain/retry remotescheduleDeletecalls inrunMobileAttachmentUploadPass.
Demo
N/A — internal mobile state-machine refactor and concurrency/orphan-cleanup hardening with no UI layout changes.
Verification
Local checks run:
pnpm -F @anlg/mobile typecheck— passedpnpm -F @anlg/mobile test— passed (344/344 tests, including new regression tests for recorder startup/unmount/save_error, auth epoch/sign-out/offline fallback, sync JWT-rotation enrollment and serialized background-sync transitions, and SQLite-backed attachment upload opt-out/tombstone orphan deletion)pnpm -F @anlg/provider-validation typecheckandpnpm -F @anlg/provider-validation test— passed (43/43)pnpm exec oxlint --quiet --format=github apps/mobile/src/andapps/web/src/ apps/mobile/src/ packages/— passed (0 errors; 0 warnings on touched files)git diff --name-only --diff-filter=ACMR -z origin/main HEAD | xargs -0 pnpm exec dprint check --allow-no-files— passedci.yamllocal checks: license boundary tests/check passed, version/changelog checks passed,python3 -m unittest discover -s apps/desktop-gpui/packagingpassed (18/18);node --testscripts passed except 2 pre-existingscripts/desktop-release-provenance.test.mjstests requiringpwsh(not installed on this macOS host).
CI checks (mobile_ci, lint, fmt, ci, zizmor) will run on this PR. Native iOS/Android/watchOS builds are not run on PRs per mobile_ci.yaml.
Summary by cubic
Replaces the mobile app's loosely coordinated booleans and unguarded async continuations with explicit state machines for audio recording, auth session restoration, sync lifecycle, and attachment upload completion, removing race conditions and leaked resources.
Recording
save_errornow immediately releases the auth/Pro routing gate in_layout.tsx; a stream write failure during startup can no longer overwrite back torecordingor leavecaptureActivestuck true.- Unmount during startup deterministically closes and discards the
SessionWavWriter, and everyawaitin startup checks the active run and state. canStartRecorderkeeps retry available after failures, and unreachable"interrupted","media_services_reset", and"native_error"phase variants are removed.
Auth, sync & attachment uploads
- A monotonic-epoch session machine prevents stale
getSession(), offline fallback, token refresh, and billing refreshes from overwriting a newer deep-link sign-in or resurrecting a signed-out session; sign-out storage writes are serialized so a failing sign-out can't wipe a newer account's credentials. MobileSyncLifecycleis keyed on user id and sync toggle with live token reads, so hourly JWT rotation no longer remounts and races one-time enrollment consumption or unsequenced nativesetEnabledcalls; sync deactivation is ownership-scoped so a stale teardown can't stop a newer activation, and 401s are retried with the refreshed token.- Upload completion now distinguishes
committedfromorphaned_by_opt_out_or_delete, and when an update affects zero rows the runner atomically enqueues a delete job that removes the uploaded private-cloud object without repeating ready-backup delete loops.