Skip to content

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

Open
ComputelessComputer wants to merge 3 commits into
mainfrom
refactor/explicit-mobile-recording-auth-sync-state
Open

ComputelessComputer wants to merge 3 commits into
mainfrom
refactor/explicit-mobile-recording-auth-sync-state

Conversation

@ComputelessComputer

@ComputelessComputer ComputelessComputer commented Nov 30, 2026 •

Copy link
Copy Markdown
Collaborator

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.

Written for commit f6b1e4f. Summary will update on new commits.

View guided diff Turn on auto-fix

@coderabbitai

coderabbitai Bot commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

Warning

Review limit reached

You'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.

Check out review usage here.

View limit details

Limit details: You’ve used all 10 included reviews currently available.

Learn how review limits work.

Review configuration:

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: QUIET
  • Plan: Advanced
  • Run ID: e023ced6-5bc6-47fe-bfa4-b1d3665df546
Commits

Reviewing files that changed from the base of the PR and between 536ab50 and f6b1e4f.

Files selected for processing: 11

  • apps/mobile/src/attachment-sync/upload-runner.test.mjs
  • apps/mobile/src/attachment-sync/upload-runner.ts
  • apps/mobile/src/audio/use-session-recorder.test.mjs
  • apps/mobile/src/audio/use-session-recorder.ts
  • apps/mobile/src/auth/context.tsx
  • apps/mobile/src/auth/session-machine.test.mjs
  • apps/mobile/src/auth/session-machine.ts
  • apps/mobile/src/auth/session-operations.test.mjs
  • apps/mobile/src/auth/session-operations.ts
  • apps/mobile/src/sync/controller.test.mjs
  • apps/mobile/src/sync/controller.ts
Walkthrough

The mobile changes add attachment upload eligibility and durable delete-job handling, a run-aware recorder state machine, and an epoch-based authentication session machine. The sync controller now tracks activation ownership and current same-account sessions. Background sync serializes native operations and ignores stale activation results. Tests cover these state transitions, retries, and cancellation paths.

Suggested reviewers: yujonglee

Merge Risk: Moderate · previous review 536ab

Several race and failure paths in recording, sign-in/sign-out, token refresh and attachment cleanup can leave a recording unsaveable, a new sign-in unrestorable, or sync paused until a manual retry. These cases are narrow and recoverable, but should be addressed or explicitly accepted before merging.

Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title accurately names the main change: the PR refactors mobile recording, auth, sync, and attachment upload lifecycles into explicit state machines. The summary and objectives describe the same c…
Description check Passed The description states the context, intent, and direction of the change. It covers audio recording, auth session restoration, sync lifecycle, and attachment upload completion. It also lists the verifi…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Title check

Explanation

The title accurately names the main change: the PR refactors mobile recording, auth, sync, and attachment upload lifecycles into explicit state machines. The summary and objectives describe the same change. The title is long at 100 characters, but it stays specific and on topic.

Full details: Description check

Explanation

The description states the context, intent, and direction of the change. It covers audio recording, auth session restoration, sync lifecycle, and attachment upload completion. It also lists the verification performed. This matches the changeset, so the check passes.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

devin-ai-integration[bot]

This comment was marked as resolved.

devin-ai-integration[bot]

This comment was marked as resolved.

coderabbitai[bot]

This comment was marked as resolved.

…, sync 401 freshness, and delete null handling

@devin-ai-integration devin-ai-integration Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Devin Review found 2 new potential issues.

Devin Review

Comment on lines +97 to +102
const signOutEpochAtStart = this.machine.getSignOutEpoch();
while (this.pendingSignOut) {
await this.pendingSignOut;
if (this.machine.getSignOutEpoch() !== signOutEpochAtStart) {
return false;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 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.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

Comment on lines +168 to +175
const firstSignOut = operations.signOut();
await new Promise((resolve) => setImmediate(resolve));

const pendingInstall = operations.installDeepLinkSession(
"token-b",
"refresh-token-b",
);
const secondSignOut = operations.signOut();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔍 Missing active session cancellation coverage

The cancellation test never starts setSession. It leaves untested whether sign-out clears credentials written by an SDK installation already in flight.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant