Repository navigation
fix(mobile): reconnect the saved pendant after a failed cold start - #22069
Conversation
Failure-Class: new
Failure-Class: new
…ailure Failure-Class: new
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
Failure-Class: new
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 7fea58d859
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| /// transport stays registered for native events and would swallow the next | ||
| /// device-ready, leaving the UI disconnected over a live link. | ||
| Future<void> disconnectDevice(String deviceId) async { | ||
| _setManualDisconnect(deviceId, true); |
There was a problem hiding this comment.
Do not mark DFU teardown as a manual disconnect
disconnectDevice is also called by DeviceProvider.prepareDFU() to hand the radio to the firmware updater, so persisting suppression here classifies every normal firmware update as an explicit user disconnect. The standard firmware flow only resets the update-state flag and returns to the already-mounted Home page; it does not issue a forced connection, and future launch/resume retries now honor this persisted block. Consequently, after a successful or failed update the pendant can remain disconnected even across app restarts until the user explicitly reconnects. Pass the user-intent flag only from actual Disconnect/Forget actions, or use a separate temporary teardown path for DFU and recovery callers.
Useful? React with 👍 / 👎.
|
|
||
| void _handleDeviceConnected(String deviceId, int generation, {bool requirePersistedPair = false}) async { | ||
| if (!_isCurrent(generation)) return; | ||
| if (!_isCurrent(generation) || !ServiceManager.instance().device.canAutoReconnectDevice(deviceId)) return; |
There was a problem hiding this comment.
Fence saved reconnects to the current persisted device
When a retained saved-device retry succeeds after the user has selected another input, this guard still admits the old device because canAutoReconnectDevice checks only stale-bond and manual-disconnect state. For example, rayban_meta_input_picker_sheet.dart persists the newly selected Ray-Ban before connecting it; if the previously saved pendant then comes back into range, its ordinary connection callback does not set requirePersistedPair or _readoptExpectedPair, so the check below is skipped and _onDeviceConnected can publish and persist the old pendant over the user's new selection. Revalidate that automatic saved-reconnect callbacks still match SharedPreferencesUtil().btDevice.id, while keeping an explicit-connect path for onboarding.
Useful? React with 👍 / 👎.
| } else { | ||
| _disconnectedAt ??= DateTime.now(); | ||
| _schedule(); |
There was a problem hiding this comment.
Honor exhausted CCCD recovery before scheduling another retry
On Android, a descriptor ACK failure beyond CccdReconnectPolicy's durable retry budget is reported as cccd_timeout_exhausted, but this callback receives only the disconnected boolean and unconditionally schedules another saved retry. That automatic retry reaches OmiBleForegroundService as caller Dart, which is explicitly exempted from the service's isExhausted guards, so the supposedly terminal action-required state starts another GATT cycle and can repeat indefinitely at the capped backoff. Preserve the disconnect reason here and suppress automatic retries for exhausted CCCD recovery, reserving the Dart exemption for an actual user-initiated reconnect.
Useful? React with 👍 / 👎.
| if (caller == "Dart") inst.manageDevice(deviceAddress, requiresBond) | ||
| else inst.onConnectRequest(deviceAddress, requiresBond, caller) |
There was a problem hiding this comment.
Restart stale Android GATT attempts after the Dart timeout
When Android's initial connectGatt returns a GATT object but never delivers a connection-state callback, currentGattHash remains non-null while Dart eventually reaches its 60-second readiness timeout. Every new saved backoff now enters this caller == "Dart" branch and calls manageDevice, whose existing-device path returns immediately whenever currentGattHash is non-null; no attempt closes the stale GATT or starts a new radio connection. Before this change, repeated starts used onConnectRequest/forceReconnect, specifically replacing such stuck attempts. Keep idempotence for genuinely active requests, but let a post-timeout saved retry force a fresh GATT attempt.
Useful? React with 👍 / 👎.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 90ae9f4038
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| } else { | ||
| savedReconnect.remove(uuid) | ||
| savedRetryTasks.removeValue(forKey: uuid)?.cancel() | ||
| } |
There was a problem hiding this comment.
Reset iOS retry bookkeeping when disabling reconnect
When the kill switch disables saved reconnect after one or more native attempts, this branch removes authorization and cancels the task but leaves savedRetryAttempts and savedOutageStarted intact. If the flag is later turned off again during the same process, the next outage resumes the old attempt count, can immediately inherit the capped 60-second delay, and reports downtime that includes the disabled interval. Clear both dictionaries here, as the Android policy already does when it is disabled.
Useful? React with 👍 / 👎.
| _lifecycle = null; | ||
| _removeAdapter?.call(); | ||
| _removeAdapter = null; | ||
| } | ||
|
|
||
| int get _elapsed => _disconnectedAt == null ? 0 : DateTime.now().difference(_disconnectedAt!).inMilliseconds; | ||
|
|
||
| void stateChanged(String id, bool isConnected) { |
There was a problem hiding this comment.
Reset the Dart attempt counter after recovery
After a successful reconnect, this branch resets the outage timestamp and backoff but not _attempt. Consequently, if the pendant disconnects again later, the first Dart retry for the new outage is reported as attempt 2 (or higher), while both native implementations restart their counters at 1. This corrupts the newly added attempt-level reconnect telemetry across multiple outages in one app session.
Useful? React with 👍 / 👎.
| if (isTimeout || | ||
| (transport is NativeBleTransport && | ||
| transport.savedReconnectEnabled && | ||
| transport.hasRetryableConnectFailure)) { | ||
| // A launch connection attempt timed out waiting for an offline or | ||
| // out-of-range device. Native BLE maintains auto-reconnect in the | ||
| // background; preserve the transport and registration so when the |
There was a problem hiding this comment.
Resume connector setup after retaining pre-ready failures
When the newly retained hasRetryableConnectFailure path is used and native emits device-ready before the Dart backoff starts, the transport transitions to connected and cancels that backoff, but the connector's original connect() future has already failed. Except for LimitlessDeviceConnection, no connector resumes the code after super.connect(): for example, Plaud never installs _notificationSub, so commands and audio notifications are dropped, while Omi skips its custody probe and time sync. The recovered link is therefore published as connected without completing device-specific initialization; retained pre-ready failures need a reconnect hook for every affected connector or must stay eligible for a full connector connect() pass.
Useful? React with 👍 / 👎.
| (() async { | ||
| await AnalyticsManager().reloadFeatureFlags(); | ||
| return AnalyticsManager().isBooleanFeatureEnabled('saved-pendant-reconnect-kill'); |
There was a problem hiding this comment.
Fail open when the kill-switch refresh fails
This ignores the boolean returned by reloadFeatureFlags() and always reads the adapter cache afterward. If a previous successful fetch or the PostHog SDK cache contains saved-pendant-reconnect-kill=true, a later offline/failed refresh still returns that stale value, sets _killActive, and suppresses the retries precisely when the pendant needs offline recovery. Check the reload result and return false on failure so the documented missing/unreachable-flags behavior is actually default-on.
Useful? React with 👍 / 👎.
…wners Failure-Class: new
What changed and why
A saved pendant could stay disconnected for an entire app process after a cold-start adapter or native connection failure: non-timeout cleanup revoked native reconnect intent, and iOS only retried peripherals connected earlier in that process. Keep one saved connection owner, ensure it on launch/resume/Bluetooth-on, and retry with one deduplicated timer (5s exponential backoff, capped at 5 minutes). Only explicit user disconnect/Forget persist suppression; DFU and capture-wedge teardown retain reconnect intent. Firmware updates pause automatic retries in memory, and relaunch clears that pause. Stale bonds still require user recovery.
Ships default ON, explicitly authorized by David. Remote kill switch: boolean PostHog
saved-pendant-reconnect-kill=truedisables the new saved reconnect policy; missing, unreachable, timed-out, or multivariate flags leave it enabled. Disabled mode retains the legacy one-shot launch connection, ignores this PR's persisted manual flags and creates no new persisted suppression. Launch reads cached boolean policy synchronously (missing cache means enabled); off-path refresh applies a late kill by disarming native saved retries and stopping Dart retry timers. No production flag configuration was changed by this PR.Relative to the proposal: derive iOS eligibility from the saved pairing supplied by Dart rather than persisting
everConnected; scan discoveries remain ineligible. Queue saved connects until adapter power-on, report empty peripheral retrieval, and use a bounded five-second scan only when CoreBluetooth cannot retrieve that saved UUID. Fence delayed native retries against manual disconnect and pairing loss. Android already owns a retry loop: retain it, make repeated Dart manage calls idempotent, report null-GATT failures, and protect queued/sticky starts from explicit disconnect.Retire and unmanage the previous native owner whenever the saved target changes, including switching to Meta input or replacing a pending pendant attempt. Failed retirement is retried before admitting the replacement. Android also fences stale companion-association callbacks and handles a service that is already stopping.
Register
Saved Pendant Reconnectwith executable presence/outcome consumers and admin documentation. It records launch/resume/adapter_on/backoff/native_retry, attempt number, boundedresult(connected,failed_*,skipped_*,attempted) anddisconnected_ms, also through DebugLogManager. Repeated states are suppressed, capped at seven intermediate states plus a reserved connected outcome per outage and source. The outcome query separates attempted episodes, connected outcomes and their recovery rate; empty windows remain missing evidence. Native and Dart attempt counters are separate series; cold-start elapsed time begins at launch when the prior process's disconnect time is unavailable. Includes a user-facing mobile changelog fragment.Product invariants affected
INV-CAP-1 — retain the live connection/subscriptions across transient launch failures and recover capture without implying that overwritten ring audio can be recovered. Explicit user disconnect and pairing-loss blocks remain authoritative.
How it was verified
flutter pub get; generated configuration bootstrapped as in app/test.sh with empty API_BASE_URL. Original build_runner/Pigeon generation remains unchanged by this review round.nice -n 10 flutter test --no-pubfocused real-service review regressions, coordinator, DeviceProvider late-ready and launch-timeout suites: 47 passed.nice -n 10 flutter test --no-pubadjacent service teardown, stale-bond, connection ownership, native transport, Bluetooth readiness, flag adapter/identity and provider-session suites: 46 passed.:app:testDevDebugUnitTest --tests com.friend.ios.ble.BleSavedReconnectTest --max-workers=2: 5 passed (no daemon/VFS cache, compile tasks explicitly rerun).ruby app/ios/test/omi_ble_connection_policy_test.rb: compiled Swift policy assertions passed, including a 10,000-tick telemetry cap and reserved success outcome.swiftc -frontend -parsefor the iOS manager, policy and host bridge passed.make preflightwith the supplied PR body: all 35 selected checks passed./Volumes/EphemeralTMPDIR. Initial unsanitized harness runs hit unrelated ADC-environment and/varsymlink assertions; all four environment failures clear in a seven-test targeted rerun.Tests
app/test/services/devices/saved_reconnect_review_test.dartexercises DeviceService → FriendPendantDeviceConnection → NativeBleTransport → mocked native Pigeon/BleBridge, without stubbing connect: DFU disconnect then relaunch, capture-wedge recovery (including cancelled follow-up), kill mode with a stored manual flag, saved target switches to a pendant/Meta, pending-attempt replacement, transient retirement failure and launch with a hanging flag refresh followed by a late kill. The existing DeviceProvider bridge suite covers cold-start out-of-range then return, unknown adapter, native fail-to-connect and Forget/manual suppression. Coordinator tests cover immediate cached policy, late kill and bounded telemetry over a 12-hour outage. Native policy tests cover bounded reporting and superseded companion targets; SQLite consumer tests separate attempts, successes and rates, including empty windows.UI evidence
UI-Evidence: none -- connection lifecycle and telemetry only; no screen or interaction layout changes.
Failure class (fixes)
Failure-Class: new
Failure-class transition narrative
Adds FC-saved-device-launch-failure-revokes-reconnect. The violated contract is saved reconnect intent surviving transient startup failures until an explicit user action or pairing-loss block revokes it. Canonical prevention is one retained connection owner plus saved-pairing authorization, bounded recovery triggers and persistent explicit-disconnect suppression. The provider/service bridge regression suite and native policy tests are the reusable guards. The existing already-satisfied-request and superseded-connection classes concern replay and retired callbacks, rather than a first-process failure revoking saved reconnect intent.
Size exceptions
Line-Count-Exception: app/lib/backend/preferences.dart | 1538 -> 1545 | A synchronous saved-target change notification retires the previous BLE owner for every btDevice writer; the reconnect state machine lives outside preferences.
Line-Count-Exception: app/lib/providers/device_provider.dart | 1598 -> 1610 | Integration lines arm the extracted owner, fence provider disposal and pause/resume recovery around DFU; retry logic remains in saved_pendant_reconnect.dart.
Line-Count-Exception: app/lib/services/devices/connectors/limitless_connection.dart | 2214 -> 2225 | Extend retained-failure readiness and serialize active Dart setup against native callbacks; real connector audio and backoff-interleaving regressions cover it.
Line-Count-Exception: app/lib/utils/analytics/analytics_manager.dart | 3113 -> 3137 | Expose synchronous boolean cache and off-path refresh through the existing identity/consent fence; PostHog decoding stays in its adapter.
Scoped cleanups
Mobile Device Health Daily.charge_eventsremains unchanged. Its rollup counts recorded false/unknown→true charging samples and already has passing regression coverage; this checkout does not establish why this user's native charging history lacks those transitions. No user-data backfill or inferred charging event is introduced.🤖 Generated with Claude Code