feat(mobile): keep Android connections alive in the background #5179
Closedsnipemanmike(GitHub profile, opens in a new tab)wants to merge 12 commits into
main fromrefs/pull/5179/headopened View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- apps/mobile/src/features/background-connection/background-root.ts line 64Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +44,21 @@44+ console.error(`[background-connection] failed to release ${label}`, error);45+ }46+}47+48+export function createBackgroundConnectionRoot(49+ registry: AtomRegistry.AtomRegistry,50+): BackgroundConnectionRoot {51+ let started = false;52+ let retainedThread = getBackgroundConnectionRetainedThreadSnapshot().thread;53+ let catalogReady = false;54+ let catalogEnvironmentIds = new Set<EnvironmentId>();55+ let threadShells = registry.get(environmentThreadShells.threadShellsAtom);56+ let catalogRelease: (() => void) | null = null;57+ let threadShellsRelease: (() => void) | null = null;58+ let serverConfigsRelease: (() => void) | null = null;59+ let retainedThreadRelease: (() => void) | null = null;60+ let clearingDeletedKey: string | null = null;61+ const shellLeases = new Map<EnvironmentId, () => void>();62+ const detailLeases = new Map<string, DetailLease>();63+64+ const clearRetainedIfCurrent = (ref: ScopedThreadRef) => {
- apps/mobile/src/features/cloud/backgroundManagedRelayAuth.ts line 124Resolvedby snipemanmike(GitHub profile, opens in a new tab)@@ -0,0 +69,21 @@69+ }70+ const session = clerk.session;71+ if (!session?.user.id) {72+ return { state: { status: "signed-out" } };73+ }74+75+ // Clerk loading crosses an async boundary. Sign-out or account switching76+ // can invalidate this result while it is in flight; never let that stale77+ // account reacquire the background owner after ownership was cleared.78+ if (attemptEpoch !== authenticationEpoch) {79+ return { state: { status: "superseded" } };80+ }81+82+ const release = dependencies.acquireSession({83+ accountId: session.user.id,84+ readClerkToken: () => session.getToken(dependencies.resolveTokenOptions()),85+ });86+ return {87+ state: { status: "active", accountId: session.user.id },88+ release,89+ };
- apps/mobile/src/features/background-connection/background-root.ts line 79Resolvedby snipemanmike(GitHub profile, opens in a new tab)@@ -0,0 +59,21 @@59+ let retainedThreadRelease: (() => void) | null = null;60+ const clearingDeletedKeys = new Set<string>();61+ const shellLeases = new Map<EnvironmentId, () => void>();62+ const detailLeases = new Map<string, DetailLease>();63+64+ const clearRetainedIfCurrent = (ref: ScopedThreadRef) => {65+ if (!refsEqual(retainedThread, ref)) {66+ return;67+ }68+ const key = refKey(ref);69+ if (clearingDeletedKeys.has(key)) {70+ return;71+ }72+ clearingDeletedKeys.add(key);73+ void clearBackgroundConnectionRetainedThread().finally(() => {74+ clearingDeletedKeys.delete(key);75+ // Saving publishes before its persistence operation is queued. If the76+ // same deleted ref was saved while this clear was pending, clear it once77+ // more now so the final persistence operation cannot restore it.78+ if (started && refsEqual(retainedThread, ref)) {79+ clearRetainedIfCurrent(ref);
- apps/mobile/src/persistence/mobile-storage.ts lines 288 to 288OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -245,3 +272,17 @@245272 ),246273 );247274275+ const loadBackgroundConnectionRetainedThread = secureStorage276+ .getItem(BACKGROUND_CONNECTION_RETAINED_THREAD_KEY)277+ .pipe(278+ Effect.flatMap((encoded) => {279+ if (encoded === null || encoded.trim().length === 0) {280+ return Effect.succeed(null);281+ }282+ return decodeBackgroundConnectionRetainedThread(encoded).pipe(283+ Effect.map((thread): ScopedThreadRefType | null => thread),284+ Effect.catch((cause) =>285+ Effect.logWarning("Ignored an invalid retained background thread.").pipe(286+ Effect.annotateLogs({287+ storageKey: BACKGROUND_CONNECTION_RETAINED_THREAD_KEY,288+ cause: String(cause),
- apps/mobile/src/features/cloud/backgroundManagedRelayAuth.ts line 199Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +147,21 @@147+ (error): BackgroundManagedRelayAuthAttempt => ({148+ state: { status: "retrying", error },149+ }),150+ );151+ if (stopped) {152+ attempt.release?.();153+ return attempt.state;154+ }155+156+ if (attempt.state.status === "active") {157+ failureCount = 0;158+ const previousRelease = releaseSession;159+ releaseSession = attempt.release ?? null;160+ previousRelease?.();161+ } else if (attempt.state.status === "retrying") {162+ const retryDelay = Math.min(INITIAL_RETRY_DELAY_MS * 2 ** failureCount, MAX_RETRY_DELAY_MS);163+ failureCount += 1;164+ cancelRetry = scheduleRetry(() => {165+ cancelRetry = null;166+ void runAttempt();167+ }, retryDelay);
juliusmarminge closed this
Sign in to join this conversation.




Important
Review skipped#
Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the
.coderabbit.yamlfile in this repository. To trigger a single review, invoke the@coderabbitai reviewcommand.⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID:
6f807a1b-4f6d-42c6-a833-ef045a6e163dYou can disable this status message by setting the
reviews.review_statustofalsein the CodeRabbit configuration file.Use the checkbox below for a quick retry:
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