Repository navigation
Refactor mobile recording, auth, sync, and attachment upload lifecycles into explicit state machines - #8364
Refactor mobile recording, auth, sync, and attachment upload lifecycles into explicit state machines#8364ComputelessComputer wants to merge 3 commits into
Conversation
…states explicitly
|
Warning Review limit reachedYou've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository. Next included review available in 9 minutes. View limit details
Walkthrough
Merge Risk:
|
…, sync 401 freshness, and delete null handling
| const signOutEpochAtStart = this.machine.getSignOutEpoch(); | ||
| while (this.pendingSignOut) { | ||
| await this.pendingSignOut; | ||
| if (this.machine.getSignOutEpoch() !== signOutEpochAtStart) { | ||
| return false; | ||
| } |
There was a problem hiding this comment.
🟡 Duplicate sign-out events discard sign-in
When an old refresh and the queued logout both emit SIGNED_OUT, installDeepLinkSession discards a browser callback waiting for logout. The session machine consumes only one event and treats the second as a new logout. The app stays on the sign-in screen without installing the new session.
Learn more
Mobile changes to the signed-out screen as soon as signOut starts, before Supabase finishes logging out. The sign-in screen lets the user open a new browser sign-in during that wait. If an in-flight SDK refresh rejects the old session, auth-js removes it and emits SIGNED_OUT; the SDK then runs the queued logout and removes the already-absent session, emitting SIGNED_OUT again. The auth subscription forwards both events to applyAuthStateChange, where only the first matches the pending logout. The second increments the same epoch used to cancel a handoff when the user explicitly signs out again. A callback already waiting for the original logout therefore returns false without calling setSession.
Example: Account A's refresh is still pending when the user taps Sign out. The user completes browser sign-in for account B while the app waits. A's refresh is rejected and the SDK emits SIGNED_OUT, then the queued logout emits it again. The app drops B's callback and stays signed out even though the browser completed sign-in.
Recommended fix: Distinguish a new explicit logout request from SDK sign-out notifications emitted while the same logout is draining and no new session can be installed. Keep cancellation on a second explicit logout, and add a regression test where both SDK notifications arrive during the first logout while a new browser callback is waiting.
Was this helpful? React with 👍 or 👎 to provide feedback.
| const firstSignOut = operations.signOut(); | ||
| await new Promise((resolve) => setImmediate(resolve)); | ||
|
|
||
| const pendingInstall = operations.installDeepLinkSession( | ||
| "token-b", | ||
| "refresh-token-b", | ||
| ); | ||
| const secondSignOut = operations.signOut(); |
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 leavingcaptureActivestucktrueand blocking_layout.tsxauth/Pro gates, unmounting duringrecordSessionCaptureStartcould leak an openSessionWavWriter, stalegetSession()or offline fallback resolutions could clobber a deep-linksetSession()or resurrect a signed-out session, hourly JWT rotation remountedMobileSyncLifecyclewhile racing one-time enrollment consumption and unsequencednative.setEnabled(false)/truecalls, 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:
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/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.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 permobile_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.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
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.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.Written for commit f6b1e4f. Summary will update on new commits.