Skip to content

fix(app): keep Android recording sync alive while the screen is off - #14296

Merged
kodjima33 merged 3 commits into
BasedHardware:mainfrom
apoorvdarshan:cursor/android-sync-transfer-keepalive-4f32
Sep 20, 2026
Merged

kodjima33 merged 3 commits into
BasedHardware:mainfrom
apoorvdarshan:cursor/android-sync-transfer-keepalive-4f32

Conversation

@apoorvdarshan

@apoorvdarshan apoorvdarshan commented Sep 17, 2026 •

Copy link
Copy Markdown
Collaborator

What changed and why

Android BLE/cloud recording file sync died when the screen turned off because RecordingTransferCoordinator treated paused as “stop all wakes” and there was no transfer-lifetime FGS/wake lock. This PR keeps an in-flight WalSyncs.syncAll pass alive with a dataSync foreground service plus PARTIAL_WAKE_LOCK, and stops that keep-alive when the pass completes or the user cancels. Fixes #5221.

Product invariants affected

none

How it was verified

  • Local PR preflight against BasedHardware/omi main (PRE_PUSH_BASE_REMOTE=upstream): 18 manifest checks passed, including failure-class-protocol (Failure-Class: new) and product-invariants (none required).
  • This Cloud VM has no Flutter SDK or Android Gradle wrapper, so these could not be run here:
    • cd app && flutter test test/services/wals/recording_transfer_coordinator_test.dart test/services/wals/sync_transfer_keep_alive_test.dart test/providers/sync_provider_sync_wal_wake_test.dart
    • (cd app/android && ./gradlew :app:testDevDebugUnitTest --tests com.friend.ios.sync.SyncTransferKeepAlivePolicyTest)
  • Push used documented hatches PRE_PUSH_SKIP_FLUTTER_GENERATED=1 and PRE_PUSH_SKIP_DART_FORMAT=1 for the missing Flutter/Dart toolchain. CI remains the full test authority.
  • Device screen-off + CV1 BLE/Wi-Fi transfer still needs a physical Android check.

Tests

  • app/test/services/wals/recording_transfer_coordinator_test.dart — in-flight drain survives screen-off; background connectivity does not start another pass; keep-alive acquire/release including thrown drains
  • app/test/services/wals/sync_transfer_keep_alive_test.dart — refcount start-once / last-release stop / releaseAll on cancel
  • app/test/providers/sync_provider_sync_wal_wake_test.dart — syncWal holds keep-alive until upload finishes; cancelSync drops it immediately
  • app/android/app/src/test/kotlin/com/friend/ios/sync/SyncTransferKeepAlivePolicyTest.kt — notification fallback + wake lock held only while the service is started

Failure class (fixes)

Failure-Class: new

Failure-class transition narrative (only when needed)

Violated contract: An in-flight Android recording file transfer must stay scheduled for its own lifetime. Activity paused / screen-off may refuse new discovery passes, but it must not drop the CPU/process keep-alive the current transfer is using.

Canonical guard: SyncTransferKeepAlive refcount around SyncTransferForegroundService (dataSync FGS + PARTIAL_WAKE_LOCK). Coordinator wake() lets the in-flight pass finish after setForeground(false) and does not queue another whole-WAL drain from background connectivity.

Evidence: #5221 (Discord #files-not-syncing; maintainer VERIFY 2026-08-06: no Android sync FGS; BLE FGS keeps GATT but Dart drain dies). This PR adds FC-android-sync-tied-to-screen-on.

Review in cubic

@apoorvdarshan
apoorvdarshan marked this pull request as ready for review September 17, 2026 01:39
@apoorvdarshan

Copy link
Copy Markdown
Collaborator Author

Dart Analyze & Tests failed on background connectivity during an in-flight drain does not start another pass (#5221) because the harness drain consumed wal-after-lock in the same gated pass (Expected: ['wal-1'], Actual: ['wal-1', 'wal-after-lock']). drainPasses stayed 1 — a second pass was not the CI failure.

Pushed to this branch (cdf7f66): setForeground(false) now drops a coalesced extra wake so screen-off cannot start another whole-WAL drain, and the test claims the backlog at drain start so wal-after-lock can only appear if a second pass runs. Flutter is not on this Cloud VM, so CI remains the test authority.

@Git-on-my-level

Copy link
Copy Markdown
Member

Thanks @apoorvdarshan — this is a well-scoped fix for #5221 with careful lifecycle work. Reviewed across the full diff.

Android keep-alive (new):

  • SyncTransferForegroundService.kt — clean lifecycle shell: START_NOT_STICKY (no orphaned sync resurrection), startForeground() promoted first in onStartCommand with a stopSelf() fallback if it throws, wake lock released in onDestroy, onTaskRemoved stops the service with the task. The 3-arg startForeground with FOREGROUND_SERVICE_TYPE_DATA_SYNC matches the manifest declaration.
  • SyncTransferPlugin.kt — minimal start/stop MethodChannel bridge; service is exported="false". Good.
  • SyncTransferKeepAlivePolicy.kt — constants extracted so policy is JVM-unit-testable without Robolectric; fine.

Dart wiring:

  • sync_transfer_keep_alive.dart — refcount start-once / stop-on-last-release is correct, _invokeStart/_invokeStop swallow channel errors so a rejected FGS start can't break the transfer, iOS no-ops via the Platform.isAndroid guard.
  • recording_transfer_coordinator.dart — the subtle part, and it holds up. wake() off-foreground joins the in-flight pass instead of no-oping; setForeground(false) drops _pendingWake and only cancels cooldown timers when no pass is running; a pass completing in background cancels timers rather than running the late wake; the cooldown fire() callback re-checks _foreground, so even a timer that survives screen-off during a pass cannot start a new one. I found no path that starts a new whole-WAL drain with the screen off.
  • sync_provider.dart — acquire/release around _performSync and syncWal are finally-paired (exception-safe), and both cancelSync() and dispose() releaseAll(). The syncWal finally-release after an earlier cancel is a refcount no-op, which the cancelSync drops transfer keep-alive immediately test pins down.
  • MainActivity.kt — stopping the FGS in engine teardown mirrors the BLE foreground-service pattern; SyncTransferPlugin.register in configureFlutterEngine re-arms on re-attach.

Manifest/docs:

  • AndroidManifest.xml — FOREGROUND_SERVICE_DATA_SYNC permission plus the dataSync service declaration are correct; WAKE_LOCK and base FOREGROUND_SERVICE were already present. Verified at head: 5 FGS types and the +1 permission match the app/AGENTS.md matrix update (4→5 types, 26→27 permissions).
  • .github/failure-classes/FC-android-sync-tied-to-screen-on.json — the stated contract matches the implemented behavior, and every listed artifact exists.
  • .github/agent-docs/android-sync-transfer.md — accurate against the code (channel, surfaces, wiring). One nit: it lists transferWalToPhone under "wired from", but that method holds no keep-alive ref — it delegates to syncWal, which does. Worth rewording so a future reader doesn't add a double-acquire.
  • sync_reconciler.dart / wals.dart — comment/export-only; fine.

Tests: the three Dart suites cover in-flight drain surviving screen-off, no second pass from background connectivity, the coalesced-wake drop, refcount semantics, acquire/release around syncWal, and immediate releaseAll on cancel; the Kotlin policy test runs in CI's :app:testDevDebugUnitTest lane. The follow-up commit fixing the harness to claim the backlog at drain start was the right fix — that CI failure was test-harness aliasing, not a production regression.

Agent-guidance note for maintainers: this PR adds agent-facing documentation — a new contract at .github/agent-docs/android-sync-transfer.md and the app/AGENTS.md permission-matrix update. Future AI coding agents touching WAL sync will be directed to preserve the keep-alive refcount invariants and will expect 5 FGS types / 27 permissions. Both docs check out against the manifest and the diff, so the guidance is accurate and narrowly scoped.

Two heads-ups before merge (no code blockers found):

  1. FOREGROUND_SERVICE_DATA_SYNC is a restricted type on Android 14+ (targetSdk 34): Play requires a use-case declaration at submission, and Android 15 caps dataSync FGS runtime around 6h/day — per-pass stopping should keep well under the cap, but the Play declaration is worth confirming.
  2. Per the PR description, screen-off + CV1 BLE/Wi-Fi transfer hasn't been validated on a physical device yet — that's the one behavior CI can't cover.

Background-execution policy change (new dataSync FGS + manifest permission) and the outstanding physical-device check need maintainer sign-off before merge.


by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.

@Git-on-my-level Git-on-my-level added positive-signal Automation verified a genuine fix/quality contribution needs-maintainer-review Needs a human maintainer to sign off before merge android labels Sep 17, 2026

@kodjima33 kodjima33 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Android sync-alive fix: root cause + fixes #5221 + CI green + new tests = 4/5 confidence (diff 807 lines only fails the scope criterion). Not already-fixed on main. mergeStateStatus UNKNOWN after refetch -- approve only per override b.

@Git-on-my-level

Copy link
Copy Markdown
Member

Re-verified this PR at the current head; one correction to my earlier review.

The earlier nit on .github/agent-docs/android-sync-transfer.md was wrong: SyncProvider.transferWalToPhone does hold its own keep-alive reference — await _keepAlive.acquire() before the transfer with a finally release after it — and it calls the low-level WalSyncs.syncWal, not the provider-level syncWal, so there is no double-acquire. The doc listing transferWalToPhone among the wired surfaces is accurate as written; no rewording needed. Apologies for the noise.

Everything else in the earlier review was re-checked against the head and stands (service lifecycle, refcount pairing, coordinator screen-off gating, manifest delta, tests). With kodjima33's approval on this head, the remaining pre-merge items are unchanged from before: the physical-device screen-off transfer check and the Play dataSync use-case declaration for Android 14+.


by AI on behalf of David

@kodjima33 kodjima33 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Reeval: real fix for #5221 (screen-off kills Android BLE/cloud sync), well tested, but mergeStateStatus is DIRTY. Per policy, never rebase — approve only, needs manual rebase.

cursoragent and others added 3 commits September 19, 2026 23:25
Hold a dataSync foreground service and PARTIAL_WAKE_LOCK for the
lifetime of BLE/cloud WAL transfers so Phase 0-2 survive screen-off.
Stop the keep-alive when the pass completes or the user cancels.

Failure-Class: new

Fixes BasedHardware#5221

Co-authored-by: Apoorv Darshan <[email protected]>
Move transfer-lifetime FGS detail to agent-docs so the component
guide stays inside the size ratchet.

Co-authored-by: Apoorv Darshan <[email protected]>
An in-flight RecordingTransferCoordinator pass must finish, but
setForeground(false) now drops a coalesced extra wake so background
connectivity cannot start another whole-WAL drain (BasedHardware#5221). The
harness claims the backlog at drain start so wal-after-lock can only
appear if a second pass runs.

Failure-Class: FC-android-sync-tied-to-screen-on

Co-authored-by: Apoorv Darshan <[email protected]>
@cursor
cursor Bot force-pushed the cursor/android-sync-transfer-keepalive-4f32 branch from cdf7f66 to d20ac86 Compare September 19, 2026 23:26

@kodjima33 kodjima33 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

4/5: real fix for #5221 (Android sync death on screen-off), thorough tests, CI green. Diff size (807 lines) is the only soft miss; landing since prior DIRTY block has cleared.

@kodjima33
kodjima33 merged commit 09ecaab into BasedHardware:main Sep 20, 2026
31 checks passed
summersmile1984 added a commit to summersmile1984/omi that referenced this pull request Sep 27, 2026
… re-record eleven owners

Review of bf7f4f6..8d1f8e2 per owner, then re-record. Where upstream's
change was semantic for the staged artifact the fork replacement moved with
it — re-recording alone would have shipped upstream identity behavior:

- AndroidManifest.xml (BasedHardware#14296, BasedHardware#5221): FOREGROUND_SERVICE_DATA_SYNC,
  foregroundServiceType shortService and the sync keep-alive service. No
  package, permission-identity or intent change; the new service name is
  already absolute, so native_android()'s namespace pass is untouched.
- main.dart (BasedHardware#15956, BasedHardware#15883, BasedHardware#19157): startup moved behind
  PhysicalQualification.startupStage. _init is replaced wholesale by the
  stage anyway; the two crash fallbacks became
  "if (!PhysicalQualification.enabled && Firebase.apps.isNotEmpty) {
  unawaited(FirebaseCrashlytics...catchError(...)) }" so their reviewed
  replacement regex moved to that shape and still yields a Firebase-free
  Logger.debug fallback.
- auth_service.dart (SCA-486/SCA-488): the token gateway gained a debug-only
  harness seam, so _tokenGateway is non-final — the stage strips the seam and
  keeps the field final; isSignedIn now routes through the gateway (the stage
  replaces its body, and NativeIdentity has no anonymous principal, so the
  reviewed semantics hold); a transient refresh failure now schedules
  _scheduleLocalDevRecovery, an Auth-emulator re-mint that cannot exist in a
  Firebase-free stage, so the kept refreshIdToken loses that call and keeps
  its reviewed retry-on-the-next-request behavior.
- change_name_widget.dart / name_widget.dart (BasedHardware#18436): both collapsed into
  _save()/_submit(). The replacements were re-anchored so the staged app
  still awaits updateGivenName before success or advancing, still ships the
  identity_name_edit / identity_name_error keys gateway_test taps, and still
  never writes given/family name itself — only the auth-provider projection
  does. The dialog error moved into the content column the rewrite left
  behind.
- settings: BasedHardware#18618/BasedHardware#18723 extracted the confirmed sign-out out of
  settings_drawer.dart into lib/pages/settings/sign_out.dart (now clearing
  through clearPreferencesForSignOut so device preferences survive). The
  completeNativeSignOut transaction owner moved with it — one owner instead
  of two — and sign_out.dart enters the registry as a reviewed input.
- wrapper.dart: onboarding was restructured and gained a "Use a Different
  Account" path; both firebase_auth anchors (the import and the three
  FirebaseAuth.instance.currentUser! calls) still hold, and the staged
  AuthService.signOut still revokes remotely before the secure credential is
  cleared.
- logger.dart / platform_manager.dart / platform_service.dart /
  crashlytics_manager.dart: PhysicalQualification gates. The stage still
  replaces the three reviewed members with the fork's false/no-op bodies and
  still overlays crashlytics_manager wholesale.
- New upstream file lib/env/physical_qualification.dart reads
  Env.firebaseAuthEmulatorHost/firebaseAuthEmulatorPort, which the fork's
  env overlay did not expose: both are added there as compile-time inputs
  (the lane is iOS dev/local_dev only and never enabled in this artifact).

Re-record: sha256 of the eleven stale paths plus the new sign_out.dart owner
written into app/fork/source-owners.json, base moved to the reviewed tree.

Verification: bash app/fork/test.sh exit 0 with the pinned Flutter 3.44.5 —
test_stage.py 5/5, both targets staged, 20/20 staged Dart tests per target
including gateway_test's failed-name-save contract, and flutter build bundle
for both targets. python3 scripts/fork/check-overlay-owners.py exit 0.

Failure-Class: none
mdmohsin7 added a commit that referenced this pull request Oct 3, 2026
… runs out (#20488)

## Summary

Android users get "Omi keeps stopping" when a long background recording
sync hits Android's foreground-service time limit.

- Android 15+ caps a `dataSync` foreground service at about 6 hours a
day.
- Android 14+ caps `shortService` at about 3 minutes.
- When a cap is reached, the system calls `Service.onTimeout`. If the
service is still running a few seconds later, Android kills the process
with `ForegroundServiceDidNotStopInTimeException`.
- `SyncTransferForegroundService` never overrode `onTimeout`.

Crashlytics, last 14 days:
- 31 users, all on 1.0.553+1320, Android 15–17.
- Every crash happened with the app in the background.
- The message is "A foreground service of type dataSync did not stop
within its timeout:
ComponentInfo{com.friend.ios/com.friend.ios.sync.SyncTransferForegroundService}".

## Change

- Both `onTimeout` overloads now release the wake lock, drop the
notification and call `stopSelf()`:
  - `onTimeout(startId)`, Android 14+, for `shortService`;
  - `onTimeout(startId, fgsType)`, Android 15+, for `dataSync`.
- The service uses `shortService` as its cold-start type, so that limit
needs handling too.
- The Dart transfer continues without the keep-alive, as it already does
when Android refuses the start.

## Not in this PR

- **The larger crash in the same service:**
`ForegroundServiceDidNotStartInTimeException`, about 750 users on
1.0.553. It's addressed by #20437, which is in 1.0.554+1338.
- **Whether the service is needed at all:** #14296 added it for #5221
("sync stops when the screen turns off") without a device test. The
later VERIFY on #5221 traced the stall to the coordinator stopping all
wakes on pause, and a connected pendant already runs
`OmiBleForegroundService` (`connectedDevice`). Removing the service
needs a screen-off sync test on a real Android device, so that is a
follow-up.

## Product invariants affected

none

## Failure class

Failure-Class: none

The existing foreground-service classes
(`FC-foreground-service-promotion-after-startup-work` and
`FC-foreground-start-cancelled-before-delivery`) cover promotion at
start. This bug is a missing timeout stop.

## Verification

- `./gradlew :app:testDevDebugUnitTest --tests
com.friend.ios.sync.SyncTransferForegroundServiceTest` (JDK 21): 5 tests
pass, including the two new ones:
  - a `dataSync` timeout stops the service and releases the wake lock;
  - a `shortService` timeout stops the service.
- Both new tests fail without the fix.
- `scripts/pr-preflight --pr-body-file <this body>`: passes.
- Not run on a device or emulator. Reaching the real 6-hour limit needs
`adb shell cmd activity` FGS timeout overrides on an Android 15+ device.

🤖 Generated with [Claude Code](https://claude.com/claude-code)


<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/BasedHardware/omi/pull/20488?utm_source=github"
target="_blank" rel="noopener noreferrer"
data-no-image-dialog="true"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img
alt="Review in cubic"
src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a>
<!-- End of auto-generated description by cubic. -->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

android needs-maintainer-review Needs a human maintainer to sign off before merge positive-signal Automation verified a genuine fix/quality contribution

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Android] Audio sync fails when screen turns off during file transfer

4 participants