@mentra/bluetooth-sdk 3.4.0-dev.999 → 3.5.0-dev.1239

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (140) hide show
  1. package/README.md +33 -11
  2. package/android/build.gradle +60 -51
  3. package/android/gradle.properties +3 -0
  4. package/android/settings.gradle +47 -3
  5. package/android/src/main/java/com/mentra/bluetoothsdk/BesCrashReportWaiters.kt +68 -0
  6. package/android/src/main/java/com/mentra/bluetoothsdk/BluetoothSdkDefaults.kt +5 -2
  7. package/android/src/main/java/com/mentra/bluetoothsdk/BluetoothSdkModule.kt +76 -3
  8. package/android/src/main/java/com/mentra/bluetoothsdk/Bridge.kt +27 -0
  9. package/android/src/main/java/com/mentra/bluetoothsdk/DeviceManager.kt +98 -120
  10. package/android/src/main/java/com/mentra/bluetoothsdk/GeneratedChangelogCatalog.kt +2 -1
  11. package/android/src/main/java/com/mentra/bluetoothsdk/GeneratedReleaseMetadata.kt +6 -6
  12. package/android/src/main/java/com/mentra/bluetoothsdk/MentraBluetoothSdk.kt +24 -9
  13. package/android/src/main/java/com/mentra/bluetoothsdk/events/BluetoothEvents.kt +16 -0
  14. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/MentraLive.kt +170 -23
  15. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/Nimo.kt +13 -316
  16. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasCoordinator.kt +0 -35
  17. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasSession.kt +2 -10
  18. package/android/src/main/java/com/mentra/bluetoothsdk/sgcs/SGCManager.kt +6 -0
  19. package/android/src/main/java/com/mentra/bluetoothsdk/stt/BoundedAudioQueue.kt +92 -0
  20. package/android/src/main/java/com/mentra/bluetoothsdk/stt/OnDeviceRecognizerHost.kt +169 -0
  21. package/android/src/main/java/com/mentra/bluetoothsdk/stt/STTTools.kt +74 -115
  22. package/android/src/main/java/com/mentra/bluetoothsdk/stt/SherpaOnnxTranscriber.kt +348 -357
  23. package/android/src/main/java/com/mentra/bluetoothsdk/stt/SpeechActivityDetector.kt +211 -0
  24. package/android/src/main/java/com/mentra/bluetoothsdk/stt/SpeechActivityEngine.kt +137 -0
  25. package/android/src/main/java/com/mentra/bluetoothsdk/stt/SttTextFormatter.kt +52 -0
  26. package/android/src/main/java/com/mentra/bluetoothsdk/stt/WakeWordDetector.kt +235 -0
  27. package/android/src/main/java/com/mentra/bluetoothsdk/utils/AvifExifStripper.java +2 -2
  28. package/android/src/main/java/com/mentra/bluetoothsdk/utils/BlePhotoUploadService.java +3 -3
  29. package/android/src/main/java/com/mentra/bluetoothsdk/utils/IncidentLogBleRelayNaming.java +11 -0
  30. package/android/src/main/java/com/mentra/bluetoothsdk/utils/audio/AudioRouteWatcher.kt +120 -0
  31. package/android/src/main/java/com/mentra/bluetoothsdk/utils/audio/PcmStreamPlayer.kt +181 -16
  32. package/android/src/main/java/com/mentra/bluetoothsdk/utils/audio/PcmUrlPlayback.kt +177 -0
  33. package/android/src/test/java/com/mentra/bluetoothsdk/BesCrashReportWaitersTest.kt +112 -0
  34. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveGlassesReadyBurstTest.kt +141 -0
  35. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveIncidentDispatchTest.kt +183 -0
  36. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/MentraLiveRgbLedResponseTest.kt +76 -0
  37. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasCoordinatorTest.kt +1 -56
  38. package/android/src/test/java/com/mentra/bluetoothsdk/sgcs/NimoCanvasSessionTest.kt +0 -22
  39. package/android/src/test/java/com/mentra/bluetoothsdk/utils/IncidentLogBleRelayNamingTest.kt +23 -0
  40. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/BoundedAudioQueueTest.kt +81 -0
  41. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/OnDeviceRecognizerHostTest.kt +216 -0
  42. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/STTToolsExtractionTest.kt +108 -0
  43. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/SpeechActivityDetectorTest.kt +126 -0
  44. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/SpeechActivityEngineTest.kt +245 -0
  45. package/android/src/testDebug/java/com/mentra/bluetoothsdk/stt/SttTextFormatterTest.kt +67 -0
  46. package/android/src/testDebug/java/com/mentra/bluetoothsdk/utils/audio/PcmUrlPlaybackTest.kt +76 -0
  47. package/build/BluetoothSdk.types.d.ts +98 -1
  48. package/build/BluetoothSdk.types.d.ts.map +1 -1
  49. package/build/BluetoothSdk.types.js.map +1 -1
  50. package/build/_private/BluetoothSdkModule.d.ts +42 -7
  51. package/build/_private/BluetoothSdkModule.d.ts.map +1 -1
  52. package/build/_private/BluetoothSdkModule.js +1 -0
  53. package/build/_private/BluetoothSdkModule.js.map +1 -1
  54. package/build/generated/changelogCatalog.d.ts +4 -1
  55. package/build/generated/changelogCatalog.d.ts.map +1 -1
  56. package/build/generated/changelogCatalog.js +5 -1
  57. package/build/generated/changelogCatalog.js.map +1 -1
  58. package/build/generated/releaseMetadata.js +6 -6
  59. package/build/generated/releaseMetadata.js.map +1 -1
  60. package/build/index.d.ts +1 -1
  61. package/build/index.d.ts.map +1 -1
  62. package/build/index.js +6 -0
  63. package/build/index.js.map +1 -1
  64. package/ios/BluetoothSdkModule.swift +66 -14
  65. package/ios/MentraBluetoothSDK.podspec +4 -0
  66. package/ios/Packages/SherpaOnnx/SherpaOnnx.swift +23 -5
  67. package/ios/Resources/SileroVad/silero_vad.onnx +0 -0
  68. package/ios/Source/BesCrashReportWaiters.swift +64 -0
  69. package/ios/Source/BluetoothSdkDefaults.swift +2 -2
  70. package/ios/Source/DeviceManager.swift +43 -22
  71. package/ios/Source/GeneratedChangelogCatalog.swift +2 -1
  72. package/ios/Source/GeneratedReleaseMetadata.swift +6 -6
  73. package/ios/Source/MentraBluetoothSDK.swift +27 -15
  74. package/ios/Source/audio/PcmStreamPlayer.swift +290 -57
  75. package/ios/Source/audio/PcmUrlPlayback.swift +231 -0
  76. package/ios/Source/audio/SpeechActivity.swift +277 -0
  77. package/ios/Source/events/BluetoothEvents.swift +41 -0
  78. package/ios/Source/internal/BluetoothAvailability.swift +15 -5
  79. package/ios/Source/sgcs/GlassesAudioSetupPolicy.swift +5 -0
  80. package/ios/Source/sgcs/MentraLive.swift +173 -42
  81. package/ios/Source/sgcs/Nimo.swift +39 -272
  82. package/ios/Source/sgcs/NimoCanvasCoordinator.swift +9 -38
  83. package/ios/Source/sgcs/NimoCanvasSession.swift +0 -1
  84. package/ios/Source/sgcs/SGCManager.swift +6 -0
  85. package/ios/Source/stt/STTTools.swift +13 -31
  86. package/ios/Source/stt/SherpaOnnxTranscriber.swift +204 -162
  87. package/ios/Source/stt/SileroSpeechActivity.swift +87 -0
  88. package/ios/Source/stt/WakeWordDetector.swift +145 -0
  89. package/ios/Source/utils/BoundedWait.swift +44 -0
  90. package/ios/Source/utils/DemandDrivenAudioWorker.swift +79 -0
  91. package/ios/Source/utils/SttModelTraits.swift +62 -0
  92. package/ios/Tests/BesCrashReportTests.swift +142 -0
  93. package/ios/Tests/DemandDrivenAudioWorkerTests.swift +171 -0
  94. package/ios/Tests/DeviceManagerReconnectTests.swift +0 -71
  95. package/ios/Tests/GlassesAudioSetupPolicyTests.swift +9 -3
  96. package/ios/Tests/IncidentLogDispatchTests.swift +158 -0
  97. package/ios/Tests/MentraLiveAudioSetupTests.swift +6 -12
  98. package/ios/Tests/MentraLiveCommandQueueTests.swift +35 -0
  99. package/ios/Tests/MentraLiveSessionReadinessTests.swift +179 -10
  100. package/ios/Tests/NimoCanvasTransportTests.swift +0 -89
  101. package/ios/Tests/PcmStreamTests.swift +299 -0
  102. package/ios/Tests/SpeechActivityTests.swift +238 -0
  103. package/ios/Tests/SttModelTraitsTests.swift +62 -0
  104. package/package.json +2 -2
  105. package/plugin/build/withAndroid.js +9 -11
  106. package/plugin/build/withKotlinVersion.d.ts +2 -0
  107. package/plugin/build/withKotlinVersion.js +46 -0
  108. package/src/BluetoothSdk.types.ts +102 -1
  109. package/src/_private/BluetoothSdkModule.ts +45 -7
  110. package/src/generated/changelogCatalog.ts +5 -1
  111. package/src/generated/releaseMetadata.ts +6 -6
  112. package/src/index.ts +12 -0
  113. package/android/silero/LICENSE.md +0 -17
  114. package/android/silero/build.gradle +0 -50
  115. package/android/silero/proguard-rules.pro +0 -24
  116. package/android/silero/src/androidTest/assets/hello.wav +0 -0
  117. package/android/silero/src/androidTest/java/com/konovalov/vad/silero/VadSileroTest.kt +0 -79
  118. package/android/silero/src/main/java/com/konovalov/vad/silero/Vad.kt +0 -160
  119. package/android/silero/src/main/java/com/konovalov/vad/silero/VadSilero.kt +0 -449
  120. package/android/silero/src/main/java/com/konovalov/vad/silero/config/FrameSize.kt +0 -15
  121. package/android/silero/src/main/java/com/konovalov/vad/silero/config/Mode.kt +0 -14
  122. package/android/silero/src/main/java/com/konovalov/vad/silero/config/SampleRate.kt +0 -12
  123. package/android/silero/src/main/java/com/konovalov/vad/silero/utils/AudioUtils.kt +0 -47
  124. package/android/silero/src/main/java/com/konovalov/vad/silero/utils/TensorMap.kt +0 -41
  125. package/android/silero/src/test/java/com/konovalov/vad/silero/utils/AudioUtilsTest.kt +0 -44
  126. package/android/src/debug/java/com/mentra/bluetoothsdk/sgcs/NimoDiagnostics.kt +0 -368
  127. package/android/src/debug/java/com/mentra/bluetoothsdk/sgcs/NimoFramebufferProtocol.kt +0 -156
  128. package/android/src/debug/java/com/mentra/bluetoothsdk/sgcs/NimoResourceDiagnostics.kt +0 -274
  129. package/android/src/main/java/com/mentra/bluetoothsdk/stt/VadGateSpeechPolicy.kt +0 -229
  130. package/android/src/release/java/com/mentra/bluetoothsdk/sgcs/NimoDiagnostics.kt +0 -20
  131. package/android/src/release/java/com/mentra/bluetoothsdk/sgcs/NimoResourceDiagnostics.kt +0 -16
  132. package/android/src/testDebug/java/com/mentra/bluetoothsdk/sgcs/NimoDiagnosticsTest.kt +0 -287
  133. package/android/src/testDebug/java/com/mentra/bluetoothsdk/sgcs/NimoFramebufferProtocolTest.kt +0 -127
  134. package/android/src/testDebug/java/com/mentra/bluetoothsdk/sgcs/NimoLifecycleTest.kt +0 -851
  135. package/ios/Source/sgcs/NimoMacResourceTransport.swift +0 -217
  136. package/ios/Source/sgcs/NimoResourceFixture.swift +0 -384
  137. package/ios/Source/sgcs/NimoResourceSession.swift +0 -406
  138. package/ios/Tests/NimoResourceSessionTests.swift +0 -476
  139. /package/android/{silero/src/main/assets/LICENSE → src/main/assets/vad/LICENSE.silero_vad} +0 -0
  140. /package/android/{silero/src/main/assets → src/main/assets/vad}/silero_vad.onnx +0 -0
@@ -155,6 +155,9 @@ class MentraLive : SGCManager() {
155
155
  private const val A2DP_CONNECT_MAX_ATTEMPTS = 5
156
156
  private const val A2DP_CONNECT_RETRY_MS = 800L
157
157
  private const val UNPAIR_FLUSH_MS = 400L
158
+ // Longer than the glasses' bounded relay of one report (BES logs, two file transfers,
159
+ // the phone POST), so an unreleased name cannot be reused while its report is in flight.
160
+ internal const val INCIDENT_RELAY_OWNERSHIP_MS = 10 * 60_000L
158
161
  private const val GATT_DISCONNECT_TIMEOUT_MS = 2_000L
159
162
  private const val MTU_CALLBACK_TIMEOUT_MS = 3_000L
160
163
  private val gattTeardownBarrier = MentraLiveGattTeardownBarrier()
@@ -457,6 +460,22 @@ class MentraLive : SGCManager() {
457
460
  }
458
461
  }
459
462
 
463
+ /** The one Mentra Live this phone is bonded with. Null when there is none, several, or no permission to read bonds. */
464
+ fun soleBondedMentraLive(context: Context?): BluetoothDevice? {
465
+ val adapter =
466
+ (context?.getSystemService(Context.BLUETOOTH_SERVICE) as? BluetoothManager)
467
+ ?.adapter
468
+ ?: return null
469
+ return try {
470
+ adapter.bondedDevices
471
+ ?.filter { isMentraLiveBluetoothName(safeBondedDeviceName(it)) }
472
+ ?.singleOrNull()
473
+ } catch (e: Exception) {
474
+ Bridge.log("LIVE: Unable to read bonded devices: " + e.message)
475
+ null
476
+ }
477
+ }
478
+
460
479
  private const val SHUTDOWN_RECENT_MS = 45_000L // Consider "recent shutdown" for 45s
461
480
 
462
481
  // Keep-alive parameters
@@ -479,9 +498,9 @@ class MentraLive : SGCManager() {
479
498
  private const val PREFS_NAME = "MentraLivePrefs"
480
499
  private const val PREF_DEVICE_NAME = "LastConnectedDeviceName"
481
500
 
482
- // Auth settings
483
- private const val AUTH_PREFS_NAME = "augmentos_auth_prefs"
484
- private const val KEY_CORE_TOKEN = "core_token"
501
+ // A Core token older builds kept in plain SharedPreferences. Deleted, never read.
502
+ private const val LEGACY_AUTH_PREFS_NAME = "augmentos_auth_prefs"
503
+ private const val LEGACY_KEY_CORE_TOKEN = "core_token"
485
504
 
486
505
  private const val MAX_BONDING_RETRIES = 3
487
506
  private const val BONDING_RETRY_DELAY_MS =
@@ -579,6 +598,13 @@ class MentraLive : SGCManager() {
579
598
  // the physical connection (never on heartbeat readiness flaps), so a first-seen sid
580
599
  // after an upgrade OTA is always detected as a restart.
581
600
  private var readinessCompletedThisBleSession = false
601
+ // Readiness exchange the phone is waiting on. Every phone_ready carries it until the
602
+ // matching glasses_ready arrives, so retries and the copies the BES buffers while the
603
+ // glasses boot are one exchange: the glasses reset their transport once for it and answer
604
+ // later copies without resetting. Both exchange fields are scoped to the BLE session.
605
+ private var pendingReadyId: String? = null
606
+ // `sid` of the glasses process whose glasses_ready this BLE session last handled.
607
+ private var readyGlassesSessionId: String? = null
582
608
  // Note: appVersion, buildNumber, deviceModel, androidVersion
583
609
  // are inherited from SGCManager parent class
584
610
 
@@ -823,6 +849,7 @@ class MentraLive : SGCManager() {
823
849
  val apiBaseUrl: String,
824
850
  val kind: BleIncidentLogKind
825
851
  ) {
852
+ val reservedAtMs: Long = SystemClock.elapsedRealtime()
826
853
  var session: FileTransferSession? = null
827
854
  }
828
855
 
@@ -1078,6 +1105,7 @@ class MentraLive : SGCManager() {
1078
1105
  this.type = DeviceTypes.LIVE
1079
1106
  this.hasMic = true
1080
1107
  this.context = Bridge.getContext()
1108
+ forgetLegacyCoreToken()
1081
1109
 
1082
1110
  // Initialize bluetooth adapter
1083
1111
  val bluetoothManager =
@@ -1241,6 +1269,7 @@ class MentraLive : SGCManager() {
1241
1269
  if (state == ConnTypes.DISCONNECTED) {
1242
1270
  resetWireNegotiationState()
1243
1271
  resetPendingAckState()
1272
+ resetReadinessExchange()
1244
1273
  // Queued writes are session-bound: transmitting them into the NEXT session
1245
1274
  // (e.g. a stale handshake whose reply activates v2 before the new session
1246
1275
  // negotiated) is the bug class this clear removes. Higher layers re-send
@@ -1306,6 +1335,7 @@ class MentraLive : SGCManager() {
1306
1335
  DeviceStore.apply("glasses", "signalStrengthUpdatedAt", 0L)
1307
1336
  resetWireNegotiationState()
1308
1337
  resetPendingAckState()
1338
+ resetReadinessExchange()
1309
1339
  // The glasses reset mic and wear tuning on BLE disconnect, so the
1310
1340
  // next link must be allowed to send them again.
1311
1341
  lastSentMicTuningBody = null
@@ -4772,6 +4802,16 @@ class MentraLive : SGCManager() {
4772
4802
  if (json.has("bytes_downloaded")) json.optLong("bytes_downloaded", 0) else null
4773
4803
  )
4774
4804
  }
4805
+ "bes_crash_detected", "bes_crash_reported_ack" ->
4806
+ try {
4807
+ Bridge.log(
4808
+ "LIVE: $type incidentKey=${json.optString("incidentKey")} " +
4809
+ "state=${json.optString("state")} ok=${json.opt("ok")}"
4810
+ )
4811
+ Bridge.sendTypedMessage(type, jsonObjectToMap(json))
4812
+ } catch (e: JSONException) {
4813
+ Log.e(TAG, "Error converting $type to Map", e)
4814
+ }
4775
4815
  "ota_progress" -> {
4776
4816
  // Legacy glasses firmware: map to unified ota_status so JS has a single path
4777
4817
  // (Mantle / progress UI).
@@ -4943,6 +4983,16 @@ class MentraLive : SGCManager() {
4943
4983
 
4944
4984
  handleSwitchStatus(switchType, switchValue, switchTimestamp)
4945
4985
  }
4986
+ "rgb_led_control_response" -> {
4987
+ // Settles the sendRgbLedControl request this reply echoes (matches iOS).
4988
+ val requestId = json.optString("requestId", "")
4989
+ val success =
4990
+ json.optString("state", "") == "success" ||
4991
+ json.optBoolean("success", false)
4992
+ val error =
4993
+ json.optString("errorCode", "").ifEmpty { json.optString("error", "") }
4994
+ Bridge.sendRgbLedControlResponse(requestId, success, error.ifEmpty { null })
4995
+ }
4946
4996
  "sensor_data" -> {
4947
4997
  // Process sensor data
4948
4998
  // ...
@@ -4953,6 +5003,19 @@ class MentraLive : SGCManager() {
4953
5003
  Bridge.log("LIVE: Ignoring stale glasses_ready without a link")
4954
5004
  return
4955
5005
  }
5006
+ val sid = json.optString("sid", "").takeIf { it.isNotEmpty() }
5007
+ val readyId = json.optString("readyId", "").takeIf { it.isNotEmpty() }
5008
+ if (readyId != null && isRepeatedGlassesReady(readyId, sid)) {
5009
+ Bridge.log(
5010
+ "LIVE: Ignoring repeated glasses_ready for readiness exchange $readyId - " +
5011
+ "the glasses did not reset for it"
5012
+ )
5013
+ return
5014
+ }
5015
+ if (readyId != null && readyId == pendingReadyId) {
5016
+ pendingReadyId = null
5017
+ }
5018
+ readyGlassesSessionId = sid
4956
5019
  Bridge.log("LIVE: 🎉 Received glasses_ready message - SOC is booted and ready!")
4957
5020
  markPairingTiming(
4958
5021
  "glasses_ready",
@@ -4970,7 +5033,7 @@ class MentraLive : SGCManager() {
4970
5033
  // Record the session id BEFORE marking ready: an unsolicited glasses_ready
4971
5034
  // already runs this full remote-reset flow, so recording (not re-triggering)
4972
5035
  // is correct here; version_info detection covers the restart case.
4973
- glassesSessionId = json.optString("sid", "").takeIf { it.isNotEmpty() }
5036
+ glassesSessionId = sid
4974
5037
  streamControlVersion = json.optInt("streamControlVersion", 0)
4975
5038
  Bridge.sendTypedMessage(
4976
5039
  "wifi_protocol_session_ready",
@@ -6470,6 +6533,30 @@ class MentraLive : SGCManager() {
6470
6533
  }
6471
6534
  }
6472
6535
 
6536
+ /**
6537
+ * The 16-character relay file names keep only 15 characters of the report id, so two reports
6538
+ * can share them. The phone routes a received file to the report registered under its name;
6539
+ * refuse a second report until the owner's Cloud POST is confirmed or its ownership expires.
6540
+ */
6541
+ private fun reserveIncidentRelays(vararg relays: BleIncidentLogRelay) {
6542
+ synchronized(bleIncidentLogRelays) {
6543
+ val now = SystemClock.elapsedRealtime()
6544
+ for (relay in relays) {
6545
+ val owner = bleIncidentLogRelays[relay.fileBaseKey] ?: continue
6546
+ if (owner.incidentId != relay.incidentId &&
6547
+ now - owner.reservedAtMs < INCIDENT_RELAY_OWNERSHIP_MS) {
6548
+ throw BluetoothSdkException(
6549
+ "incident_relay_busy",
6550
+ "BLE relay ${relay.fileBaseKey} is still owned by report ${owner.incidentId}.",
6551
+ )
6552
+ }
6553
+ }
6554
+ for (relay in relays) {
6555
+ bleIncidentLogRelays[relay.fileBaseKey] = relay
6556
+ }
6557
+ }
6558
+ }
6559
+
6473
6560
  override fun sendIncidentId(incidentId: String, apiBaseUrl: String?) {
6474
6561
  if (!isConnected || bluetoothGatt == null || txCharacteristic == null) {
6475
6562
  throw BluetoothSdkException(
@@ -6489,10 +6576,9 @@ class MentraLive : SGCManager() {
6489
6576
  }
6490
6577
  val bKey = IncidentLogBleRelayNaming.bleFileBaseName(incidentId, 'B')
6491
6578
  val lKey = IncidentLogBleRelayNaming.bleFileBaseName(incidentId, 'L')
6492
- bleIncidentLogRelays[bKey] =
6493
- BleIncidentLogRelay(bKey, incidentId, base, BleIncidentLogKind.FIRMWARE)
6494
- bleIncidentLogRelays[lKey] =
6495
- BleIncidentLogRelay(lKey, incidentId, base, BleIncidentLogKind.LOGCAT)
6579
+ val bRelay = BleIncidentLogRelay(bKey, incidentId, base, BleIncidentLogKind.FIRMWARE)
6580
+ val lRelay = BleIncidentLogRelay(lKey, incidentId, base, BleIncidentLogKind.LOGCAT)
6581
+ reserveIncidentRelays(bRelay, lRelay)
6496
6582
 
6497
6583
  val auth = JSONObject()
6498
6584
  auth.put("type", "auth_token")
@@ -6507,8 +6593,8 @@ class MentraLive : SGCManager() {
6507
6593
  sessionGeneration != bleSessionGeneration.get() ||
6508
6594
  !isConnected || bluetoothGatt == null || txCharacteristic == null ||
6509
6595
  !sendJson(json, true, true, sessionGeneration) || sessionGeneration != bleSessionGeneration.get()) {
6510
- bleIncidentLogRelays.remove(bKey)
6511
- bleIncidentLogRelays.remove(lKey)
6596
+ bleIncidentLogRelays.remove(bKey, bRelay)
6597
+ bleIncidentLogRelays.remove(lKey, lRelay)
6512
6598
  throw BluetoothSdkException("incident_dispatch_failed", "Could not queue the glasses incident-log request.")
6513
6599
  }
6514
6600
  Bridge.log(
@@ -6525,6 +6611,27 @@ class MentraLive : SGCManager() {
6525
6611
  }
6526
6612
  }
6527
6613
 
6614
+ override fun sendBesCrashReported(incidentKey: String, reportId: String) {
6615
+ if (!isConnected || bluetoothGatt == null || txCharacteristic == null) {
6616
+ throw BluetoothSdkException(
6617
+ "glasses_not_connected", "Cannot report the BES crash because the glasses BLE link is not ready.",
6618
+ )
6619
+ }
6620
+ val sessionGeneration = bleSessionGeneration.get()
6621
+ try {
6622
+ val json = JSONObject()
6623
+ json.put("type", "bes_crash_reported")
6624
+ json.put("incidentKey", incidentKey)
6625
+ json.put("reportId", reportId)
6626
+ if (!sendJson(json, true, true, sessionGeneration) || sessionGeneration != bleSessionGeneration.get()) {
6627
+ throw BluetoothSdkException("bes_crash_dispatch_failed", "Could not queue bes_crash_reported to the glasses.")
6628
+ }
6629
+ Bridge.log("LIVE: Queued bes_crash_reported incidentKey=$incidentKey reportId=$reportId")
6630
+ } catch (e: JSONException) {
6631
+ throw BluetoothSdkException("bes_crash_dispatch_failed", "Could not create bes_crash_reported.", e)
6632
+ }
6633
+ }
6634
+
6528
6635
  /** Query gallery status from the glasses */
6529
6636
  override fun queryGalleryStatus() {
6530
6637
  try {
@@ -9772,13 +9879,34 @@ class MentraLive : SGCManager() {
9772
9879
  wireHandshakeSentGeneration = -1
9773
9880
  }
9774
9881
 
9882
+ /**
9883
+ * A glasses_ready that echoes a readyId answers a phone_ready exchange. The answer to the
9884
+ * exchange the phone is waiting on, and any answer from a glasses process other than the one
9885
+ * this link last handled (an asg restart resets for every exchange it first sees), followed a
9886
+ * transport reset. Any other answer repeats an exchange that process already reset for, or one
9887
+ * superseded by the pending exchange, whose answer is still to come.
9888
+ */
9889
+ private fun isRepeatedGlassesReady(readyId: String, sid: String?): Boolean =
9890
+ readyId != pendingReadyId && sid == readyGlassesSessionId
9891
+
9892
+ private fun resetReadinessExchange() {
9893
+ pendingReadyId = null
9894
+ readyGlassesSessionId = null
9895
+ }
9896
+
9775
9897
  /** Sends phone_ready to (re)start the glasses-driven readiness flow. */
9776
9898
  private fun sendPhoneReady(reason: String) {
9777
- Bridge.log("LIVE: 📱 Sending phone_ready to glasses ($reason) - waiting for glasses_ready response")
9899
+ val readyId = pendingReadyId ?: UUID.randomUUID().toString()
9900
+ pendingReadyId = readyId
9901
+ Bridge.log(
9902
+ "LIVE: 📱 Sending phone_ready to glasses ($reason, exchange $readyId) - " +
9903
+ "waiting for glasses_ready response"
9904
+ )
9778
9905
  markPairingTiming("phone_ready_sent", "reason=$reason queueSize=${sendQueue.size}")
9779
9906
  val readyMsg = JSONObject()
9780
9907
  readyMsg.put("type", "phone_ready")
9781
9908
  readyMsg.put("timestamp", System.currentTimeMillis())
9909
+ readyMsg.put("readyId", readyId)
9782
9910
  sendJson(readyMsg, true)
9783
9911
  }
9784
9912
 
@@ -11161,6 +11289,15 @@ class MentraLive : SGCManager() {
11161
11289
  // Transfer is complete - process successfully
11162
11290
  Bridge.log("LIVE: 📦 File transfer complete: " + packetInfo.fileName)
11163
11291
 
11292
+ if (IncidentLogBleRelayNaming.isRelayFileName(packetInfo.fileName)) {
11293
+ // No relay registered (e.g. the app restarted mid-relay): nothing reached
11294
+ // Cloud, so success would make the glasses mark the incident uploaded.
11295
+ Log.w(TAG, "Incident log relay without a registered report: " + packetInfo.fileName)
11296
+ sendTransferCompleteConfirmation(packetInfo.fileName, false)
11297
+ activeFileTransfers.remove(packetInfo.fileName)
11298
+ return
11299
+ }
11300
+
11164
11301
  // Assemble and save the file
11165
11302
  val fileData = session.assembleFile()
11166
11303
  if (fileData != null) {
@@ -11377,6 +11514,13 @@ class MentraLive : SGCManager() {
11377
11514
  success,
11378
11515
  message ->
11379
11516
  Handler(Looper.getMainLooper()).post {
11517
+ // A different report now owns this name (it was admitted after our owner finished),
11518
+ // so a completion here would mark ITS file done. Drop the stale callback.
11519
+ val owner = bleIncidentLogRelays[relay.fileBaseKey]
11520
+ if (owner != null && owner.incidentId != relay.incidentId) {
11521
+ Log.w(TAG, "Dropping stale incident relay callback for " + relay.fileBaseKey)
11522
+ return@post
11523
+ }
11380
11524
  if (success) {
11381
11525
  Bridge.log(
11382
11526
  "LIVE: ✅ Incident log BLE relay uploaded (" +
@@ -11384,7 +11528,6 @@ class MentraLive : SGCManager() {
11384
11528
  "): " +
11385
11529
  relay.incidentId
11386
11530
  )
11387
- bleIncidentLogRelays.remove(relay.fileBaseKey)
11388
11531
  } else {
11389
11532
  Log.e(
11390
11533
  TAG,
@@ -11397,6 +11540,11 @@ class MentraLive : SGCManager() {
11397
11540
  relay.session = null
11398
11541
  }
11399
11542
  sendTransferCompleteConfirmation(fileName, success)
11543
+ // Release only after the glasses' confirmation is queued, so a report that reuses
11544
+ // this name is ordered behind the owner's completion.
11545
+ if (success) {
11546
+ bleIncidentLogRelays.remove(relay.fileBaseKey, relay)
11547
+ }
11400
11548
  }
11401
11549
  }
11402
11550
  }
@@ -11553,20 +11701,19 @@ class MentraLive : SGCManager() {
11553
11701
  }
11554
11702
 
11555
11703
  /**
11556
- * Get the core authentication token. Reads from DeviceStore first (synced from JS via
11557
- * BluetoothSdkModule.update), then falls back to SharedPreferences for backward compatibility.
11704
+ * Get the current Core access token, synced from JS into the in-memory DeviceStore
11705
+ * (BluetoothSdkModule.update). Empty when there is none: credentials are never read from
11706
+ * plain storage.
11558
11707
  */
11559
11708
  private fun getCoreToken(): String {
11560
11709
  val fromStore = DeviceStore.get("bluetooth", "core_token")
11561
- if (fromStore is String) {
11562
- val token = fromStore
11563
- if (token != null && !token.isEmpty()) {
11564
- return token
11565
- }
11566
- }
11567
- val prefs = context!!.getSharedPreferences(AUTH_PREFS_NAME, Context.MODE_PRIVATE)
11568
- val fromPrefs = prefs.getString(KEY_CORE_TOKEN, "")
11569
- return if (fromPrefs != null) fromPrefs else ""
11710
+ return if (fromStore is String) fromStore else ""
11711
+ }
11712
+
11713
+ /** Delete the Core token older builds left in plain SharedPreferences. */
11714
+ private fun forgetLegacyCoreToken() {
11715
+ val prefs = context?.getSharedPreferences(LEGACY_AUTH_PREFS_NAME, Context.MODE_PRIVATE) ?: return
11716
+ if (prefs.contains(LEGACY_KEY_CORE_TOKEN)) prefs.edit().remove(LEGACY_KEY_CORE_TOKEN).apply()
11570
11717
  }
11571
11718
 
11572
11719
  /** Send BLE transfer completion notification */