Refactor mobile recording, auth, sync, and attachment upload lifecycles into explicit state machines

CO
25m ago
+4336-530

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 typed RecorderMachineState + transitionRecorderState guard, prune unreachable "interrupted", "media_services_reset", and "native_error" variants, derive captureActive directly from active capture phases so "save_error" immediately releases _layout.tsx auth/Pro routing, check active run/state after every await in performStart, and deterministically close/discard SessionWavWriter and 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-epoch AuthSessionMachine so stale getSession(), offline persisted fallback, INITIAL_SESSION, TOKEN_REFRESHED, and in-flight billing refreshes never overwrite a newer deep-link setSession() or resurrect an explicit signOut(). Key MobileSyncLifecycle on ${user.id}:${cloudSyncEnabled} with live token refresh (updateAccessToken / getAccessToken), guard one-time recovered enrollment commit/consumption in MobileSyncController against same-account JWT-rotation remounts, and serialize background-sync.ts native setEnabled/setPendingWork/finishBackgroundFlush transitions with per-epoch lastReported reset.
  • 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 a direction = 'delete' transfer job (plus durable blind delete refs) when session_attachments update affects 0 rows due to opt-out or tombstone, and drain/retry remote scheduleDelete calls in runMobileAttachmentUploadPass.

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 — passed
  • pnpm -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 typecheck and pnpm -F @anlg/provider-validation test — passed (43/43)
  • pnpm exec oxlint --quiet --format=github apps/mobile/src/ and apps/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 — passed
  • ci.yaml local checks: license boundary tests/check passed, version/changelog checks passed, python3 -m unittest discover -s apps/desktop-gpui/packaging passed (18/18); node --test scripts passed except 2 pre-existing scripts/desktop-release-provenance.test.mjs tests requiring pwsh (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_error now immediately releases the auth/Pro routing gate in _layout.tsx; a stream write failure during startup can no longer overwrite back to recording or leave captureActive stuck true.
  • Unmount during startup deterministically closes and discards the SessionWavWriter, and every await in startup checks the active run and state.
  • canStartRecorder keeps 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.
  • MobileSyncLifecycle is 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 native setEnabled calls; 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 committed from orphaned_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.