Skip to content
Source
Sign inSign up
pingdotgg/t3code

feat(mobile): keep Android connections alive in the background #5179

Closedsnipemanmike(GitHub profile, opens in a new tab)wants to merge 12 commits intomain fromrefs/pull/5179/headopened View on GitHub

What Changed

Android currently suspends the JavaScript connection runtime when T3 Code is backgrounded or the phone is locked. Reopening the app can therefore require a full reconnect and synchronization before current thread state appears.

This PR adds an Android-only, opt-in background connection mode that:

  • runs the existing client runtime from a foreground service backed by React Native Headless JS
  • shares the existing atom registry, connection supervisors, subscriptions, and outbox dispatcher instead of creating a second WebSocket stack
  • keeps every saved environment's shell state current while retaining full detail only for the last-opened and starting/running threads
  • preserves managed-relay authentication for cold T3 Connect startup
  • probes healthy sessions on resume without forcing reconnects or resubscriptions
  • restores the service after ordinary process reclamation, task swipe-away, package replacement, and reboot after unlock
  • exposes an Android setting and the platform-required silent foreground-service notification

This does not change the WebSocket protocol, synchronization reducer, server contracts, or server behavior.

The recovery work in #5154 improves what happens after Android has suspended the client. This PR addresses the preceding problem: while the setting is enabled, it prevents Android suspension from stopping the connection runtime in the first place. The approaches remain compatible.

Why

Mobile is commonly used to monitor or continue work running on another machine through a direct connection, Tailscale, or T3 Connect. Keeping the existing runtime alive means events can arrive while the app is backgrounded, outgoing messages continue draining, and reopening can render current state immediately rather than beginning a reconnect cycle.

The feature defaults off. Android force-stop remains an unavoidable boundary, and users must launch the app once afterward.

Verification

  • 18 focused test files passed (114 tests)
  • mobile and client-runtime typechecks passed
  • mobile lint passed
  • native module unit tests and Android release lint passed
  • arm64 production release APK built successfully, matched the expected signing certificate, and installed with replacement semantics without clearing app data
  • physical Android validation covered direct/Tailscale operation while backgrounded and locked, forced Doze, task swipe-away, Wi-Fi/cellular recovery, package replacement, and reboot restoration
  • T3 Connect ownership and cold-bootstrap paths are covered by focused tests; live T3 Connect validation was intentionally skipped
  • a clean emulator was used for UI evidence; it contains no account or personal data

UI Changes

Before:

Settings before

After:

Settings after

Interaction video (sanitized emulator)

Checklist

  • This PR is small and focused
  • I explained what changed and why
  • I included before/after screenshots for any UI changes
  • I included a video for animation/interaction changes

This is one focused Android runtime concern, but it is not a small diff; the native lifecycle, shared runtime ownership, relay authentication, resume semantics, tests, and documentation must land together to avoid partial behavior.

Implemented with GPT-5.6-sol through the Codex harness. Reviewed with Claude Fable through the Claude Code CLI.


Note

High Risk Large cross-cutting change to Android FGS lifecycle, shared connection/outbox state, and managed-relay auth across UI unmount and account switches—regressions could affect credentials, reconnect behavior, or background message delivery.

Overview Adds an opt-in Android “Keep connected in background” mode that keeps the existing mobile client runtime alive via a remoteMessaging foreground service and a single React Native Headless JS task—no second WebSocket or sync stack.

The new t3-background-connection Expo module owns native lifecycle: persistent enablement, ongoing notification, Wi‑Fi lock, boot/package-replace recovery, exponential restart backoff (only when battery optimization is ignored), and orderly stop when the user turns the feature off. JS registers the headless task at startup and coordinates background-root leases (environment catalog/shells, server configs, thread detail for the retained + active threads) plus acquireThreadOutboxDrain so queued messages still drain without a mounted UI.

T3 Connect / relay gains separate UI vs background managed-relay session ownership and backgroundManagedRelayAuth (cold Clerk bootstrap, holds during account transitions, retries). CloudAuthProvider no longer clears relay on UI unmount when background still owns the session. Returning to the app uses application-active-preserved when the native service and JS runtime are both ready, avoiding forced reconnects.

Settings expose the toggle, status, and optional battery-exemption prompt; the active thread is persisted as the retained target and cleared when environments/threads are removed or caches are wiped.

Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit b36b040a2016508348d5770483b11ff1c742e0b7. Bugbot is set up for automated code reviews on this repo. Configure [here](https://www.cursor.com/dashboard/bugbot).

Note

Add Android background connection with foreground service and shared outbox dispatcher

  • Adds the t3-background-connection Expo native module with a sticky foreground service, headless JS task, broadcast receiver (boot/package-replace/restart), state manager, exponential restart backoff (1s–5min), and battery-optimization exemption support
  • Adds JS background infrastructure: background task lifecycle, retained-thread persistence (single-flight load, serialized saves/clears), target selection, background relay-auth bootstrap with epoch invalidation and transition holds, and lease-based UI/background managed-relay session ownership
  • Refactors the thread outbox drain from React hooks to a registry-backed shared dispatcher (acquireThreadOutboxDrain) that reference-counts owners, coalesces drain requests, and retries through state-backed timers
  • Adds application-active-preserved wakeup type so EnvironmentSupervisor probes the connected session instead of reconnecting when both the native service and runtime are ready
  • Integrates into the app entrypoint, App.tsx startup coordinator, RootStackLayout retained-thread tracking, and Android-only settings UI with battery-exemption prompting
  • Risk: CloudAuthProvider account deactivation now invalidates background relay auth and clears both UI and background ownership; account switches suppress intermediate refresh. The outbox drain lifecycle changed from per-component to registry-scoped shared leases — multiple hook mounts share one dispatcher, and the final release stops drains, cancels retries, and unsubscribes listeners
Macroscope summarized b36b040.
    1. coderabbitai[bot](GitHub profile, opens in a new tab)commented

      Important

      Review skipped

      Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

      ⚙️ Run configuration

      Configuration used: Repository UI

      Review profile: CHILL

      Plan: Pro Plus

      Run ID: 6f807a1b-4f6d-42c6-a833-ef045a6e163d

      You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

      Use the checkbox below for a quick retry:

      • 🔍 Trigger review

      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
      Comment `@coderabbitai help` to get the list of available commands.
    2. github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched

    3. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      Approvability

      Verdict: Not approved

      Macroscope's review found this PR not approvable — This PR introduces a substantial Android background service and headless runtime that changes connection, authentication, outbox, persistence, and resume behavior, with intentional battery, data, and notification side effects. It also adds production lint suppressions, so the cross-cutting implementation requires human review.

      You can add or adjust custom eligibility rules. [Learn more](https://docs.macroscope.com/approvability#example-custom-eligibility-rules).
    4. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium background-connection/retained-thread.ts:80

      When loadPersistedRetainedThread rejects, ensureBackgroundConnectionRetainedThreadLoaded calls publish({ loaded: true, thread: null }). This sets snapshot.loaded = true, so every subsequent call returns Promise.resolve(snapshot.thread) immediately without retrying the read. A transient secure-storage or runtime failure permanently suppresses the persisted retained thread for the rest of the JS process lifetime, and a later background-root restart never recovers it. The .catch handler should leave snapshot.loaded as false (e.g. by not calling publish) so that the next call retries, or schedule an explicit retry.

      ✅ Resolved in 46344f92a81abd4fd74b09a2a7d14078bfc0706d

    5. Reviewed the Effect-service surface of this PR (new MobileStorage operations, the imperative persistence bridge, and the touched client-runtime connection modules). The service definition order, inline Context.Service interface, make/layer exports, Foo["Service"] usage, and namespace subpath imports all follow the conventions; the Promise-based background modules stay on the imperative-adapter side and are not consumed by Effect services. One log-annotation nit noted inline.

      Posted via Macroscope — Effect Service Conventions
    6. Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.

      Fix All in Cursor ❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the [Cursor dashboard](https://www.cursor.com/dashboard/bugbot).

      Want fixes drafted automatically? Bugbot Autofix can create code changes for findings. A team admin can enable Autofix in the Cursor dashboard.

      Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit c7d27a5175662ba0800963fd47a3b1b377d9ce05. Configure [here](https://www.cursor.com/dashboard/bugbot).
    7. Note

      This comment is posted by Julius' dot

      Closing for missing prior maintainer approval. This adds a background runtime with a foreground-service notification, wake locks, and automatic restart after reboot. Those are new product behaviors, even with the setting off by default. No approval for that direction and scope is linked; #5154 addresses reconnect recovery instead.

      Please discuss the background mode and its battery, data, notification, and restart behavior with maintainers in Ideas, then link their explicit approval for reconsideration.

    8. juliusmarminge closed this

Sign in to join this conversation.