@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
@@ -154,4 +154,175 @@ final class DemandDrivenAudioWorkerTests: XCTestCase {
154
154
  worker.setActive(false)
155
155
  queue.sync {}
156
156
  }
157
+
158
+ func testControlOperationDoesNotEnableMicrophoneDemand() async {
159
+ let worker = DemandDrivenAudioWorker<Processor>(makeProcessor: { Processor() }, process: { _, _, _ in })
160
+ let prepared = await worker.perform { true }
161
+ XCTAssertTrue(prepared)
162
+ XCTAssertFalse(worker.snapshot().active)
163
+ XCTAssertEqual(worker.snapshot().processedBuffers, 0)
164
+ let ran = await worker.withCurrentProcessor { _, _ in true }
165
+ XCTAssertNil(ran)
166
+ XCTAssertFalse(worker.snapshot().initialized)
167
+ }
168
+
169
+ func testCurrentProcessorOperationRunsAfterQueuedAudio() async {
170
+ var events = [String]()
171
+ let worker = DemandDrivenAudioWorker<Processor>(makeProcessor: { Processor() }, process: { _, _, _ in
172
+ events.append("audio")
173
+ })
174
+ worker.setActive(true)
175
+ worker.accept(Data([1, 0]))
176
+ let finished = await worker.withCurrentProcessor { _, token -> Bool in
177
+ events.append("flush")
178
+ return worker.isCurrent(token)
179
+ }
180
+ XCTAssertEqual(finished, true)
181
+ XCTAssertEqual(events, ["audio", "flush"])
182
+ worker.setActive(false)
183
+ }
184
+
185
+ func testDemandEndReleasesProcessorAndNextDemandLoadsAgain() async {
186
+ var creations = 0
187
+ var releases = 0
188
+ let worker = DemandDrivenAudioWorker<Processor>(makeProcessor: {
189
+ creations += 1
190
+ return Processor { releases += 1 }
191
+ }, process: { _, _, _ in })
192
+ let idle = await worker.awaitLoad()
193
+ XCTAssertEqual(idle, .noDemand)
194
+ XCTAssertEqual(creations, 0)
195
+
196
+ worker.setActive(true)
197
+ let loaded = await worker.awaitLoad()
198
+ XCTAssertEqual(loaded, .loaded)
199
+ XCTAssertTrue(worker.snapshot().initialized)
200
+ XCTAssertEqual(creations, 1)
201
+
202
+ worker.setActive(false)
203
+ // Release is serialized on the worker queue, after which no processor is reachable.
204
+ let afterRelease = await worker.withCurrentProcessor { _, _ in true }
205
+ XCTAssertNil(afterRelease)
206
+ XCTAssertEqual(releases, 1)
207
+ XCTAssertFalse(worker.snapshot().initialized)
208
+ let ended = await worker.awaitLoad()
209
+ XCTAssertEqual(ended, .noDemand)
210
+
211
+ worker.setActive(true)
212
+ let reloaded = await worker.awaitLoad()
213
+ XCTAssertEqual(reloaded, .loaded)
214
+ XCTAssertEqual(creations, 2)
215
+ worker.setActive(false)
216
+ _ = await worker.perform { true }
217
+ XCTAssertEqual(releases, 2)
218
+ }
219
+
220
+ func testRestartAndAwaitLoadReportsFailureAndSkipsLoadingWithoutDemand() async {
221
+ var attempts = 0
222
+ var succeed = true
223
+ let worker = DemandDrivenAudioWorker<Processor>(makeProcessor: {
224
+ attempts += 1
225
+ return succeed ? Processor() : nil
226
+ }, process: { _, _, _ in })
227
+ let withoutDemand = await worker.restartAndAwaitLoad()
228
+ XCTAssertEqual(withoutDemand, .noDemand)
229
+ _ = await worker.perform { true }
230
+ XCTAssertEqual(attempts, 0)
231
+
232
+ worker.setActive(true)
233
+ let first = await worker.awaitLoad()
234
+ XCTAssertEqual(first, .loaded)
235
+ succeed = false
236
+ let failed = await worker.restartAndAwaitLoad()
237
+ XCTAssertEqual(failed, .failed)
238
+ XCTAssertFalse(worker.snapshot().initialized)
239
+ succeed = true
240
+ let recovered = await worker.restartAndAwaitLoad()
241
+ XCTAssertEqual(recovered, .loaded)
242
+ XCTAssertEqual(attempts, 3)
243
+ worker.setActive(false)
244
+ }
245
+
246
+ func testControlOperationRunsWhileAudioArrivesFasterThanInference() async {
247
+ let queue = DispatchQueue(label: "test.speech.slow")
248
+ let worker = DemandDrivenAudioWorker<Processor>(queue: queue, makeProcessor: { Processor() }, process: { _, _, _ in
249
+ Thread.sleep(forTimeInterval: 0.004)
250
+ })
251
+ let loaded = await worker.activateAndAwaitLoad()
252
+ XCTAssertEqual(loaded, .loaded)
253
+
254
+ let feeding = ManagedAtomicFlag()
255
+ let feeder = Thread {
256
+ // One buffer per millisecond against 4 ms of inference each: the queue never empties.
257
+ while !feeding.isSet {
258
+ worker.accept(Data([1]))
259
+ Thread.sleep(forTimeInterval: 0.001)
260
+ }
261
+ }
262
+ feeder.start()
263
+ let started = Date()
264
+ let ran = await worker.perform { true }
265
+ let waited = Date().timeIntervalSince(started)
266
+ feeding.set()
267
+ XCTAssertTrue(ran)
268
+ XCTAssertLessThan(waited, 1.0)
269
+ worker.setActive(false)
270
+ }
271
+
272
+ func testEnablingAgainRetriesAFailedLoadButNotAWorkingOne() async {
273
+ var attempts = 0
274
+ var succeed = false
275
+ let worker = DemandDrivenAudioWorker<Processor>(makeProcessor: {
276
+ attempts += 1
277
+ return succeed ? Processor() : nil
278
+ }, process: { _, _, _ in })
279
+ let failed = await worker.activateAndAwaitLoad()
280
+ XCTAssertEqual(failed, .failed)
281
+ XCTAssertEqual(attempts, 1)
282
+
283
+ succeed = true
284
+ let recovered = await worker.activateAndAwaitLoad()
285
+ XCTAssertEqual(recovered, .loaded)
286
+ XCTAssertEqual(attempts, 2)
287
+
288
+ let again = await worker.activateAndAwaitLoad()
289
+ XCTAssertEqual(again, .loaded)
290
+ XCTAssertEqual(attempts, 2)
291
+ worker.setActive(false)
292
+ }
293
+
294
+ func testAwaitLoadWaitsForASlowLoad() async {
295
+ let loading = DispatchSemaphore(value: 0)
296
+ let release = DispatchSemaphore(value: 0)
297
+ let worker = DemandDrivenAudioWorker<Processor>(makeProcessor: {
298
+ loading.signal()
299
+ release.wait()
300
+ return Processor()
301
+ }, process: { _, _, _ in })
302
+ worker.setActive(true)
303
+ XCTAssertEqual(loading.wait(timeout: .now() + 2), .success)
304
+ XCTAssertFalse(worker.snapshot().initialized)
305
+ DispatchQueue.global().asyncAfter(deadline: .now() + 0.05) { release.signal() }
306
+ let state = await worker.awaitLoad()
307
+ XCTAssertEqual(state, .loaded)
308
+ XCTAssertTrue(worker.snapshot().initialized)
309
+ worker.setActive(false)
310
+ }
311
+ }
312
+
313
+ /// A tiny thread-safe stop flag for the feeder thread.
314
+ private final class ManagedAtomicFlag: @unchecked Sendable {
315
+ private let lock = NSLock()
316
+ private var value = false
317
+ var isSet: Bool {
318
+ lock.lock()
319
+ defer { lock.unlock() }
320
+ return value
321
+ }
322
+
323
+ func set() {
324
+ lock.lock()
325
+ value = true
326
+ lock.unlock()
327
+ }
157
328
  }
@@ -5,77 +5,6 @@ import XCTest
5
5
  final class DeviceManagerReconnectTests: XCTestCase {
6
6
  private let requests = ["should_send_lc3", "should_send_pcm", "should_send_transcript", "local_stt_fallback_active"]
7
7
 
8
- func testActualManagerHandoffCleanupDoesNotInvalidateClosedOriginalStatus() {
9
- withRecordingDevice { manager, _ in
10
- let original = manager.sgc as! ReconnectRecordingDevice
11
- original.type = DeviceTypes.NIMO
12
- let uuid = "00000000-0000-4000-8000-000000000001"
13
- let model = NimoResourceSession(captureNonce: uuid, pair: NimoResourcePair(name: "Nimo-Test", peripheralUuid: uuid))
14
- XCTAssertTrue(model.admit(original, instanceId: uuid, name: "Nimo-Test"))
15
- XCTAssertTrue(model.beginRelease(nonce: uuid, cancel: true, mic: false, canvas: false))
16
- model.proveNoTransport()
17
- let verifiedClosed = model.settled(producers: NimoResourceProducers())
18
- var cleanupCalls = 0, disconnectEffects = 0
19
- original.onCleanup = {
20
- cleanupCalls += 1
21
- // Same original-session guard used by actual Nimo.disconnect.
22
- if model.shouldRunOrdinaryDisconnect(original, originalClosed: verifiedClosed) { disconnectEffects += 1 }
23
- }
24
- manager.initSGC(DeviceTypes.SIMULATED) // Actual manager replacement; no Bluetooth device.
25
- XCTAssertEqual(cleanupCalls, 1)
26
- XCTAssertEqual(disconnectEffects, 0)
27
- XCTAssertTrue(model.errors.isEmpty)
28
- XCTAssertTrue(model.settled(producers: NimoResourceProducers())) // Fresh status after cleanup.
29
- XCTAssertTrue(NimoResourceManagerState.allowsReplacement(fixtureEnabled: true, originalClosed: model.settled(producers: NimoResourceProducers())))
30
- XCTAssertEqual(manager.sgc?.type, DeviceTypes.SIMULATED)
31
- }
32
- }
33
-
34
- func testActualQueuedReplacementDoesNotJoinOriginalNimoProducerRoster() {
35
- withRecordingDevice { manager, store in
36
- let original = manager.sgc as! ReconnectRecordingDevice
37
- original.type = DeviceTypes.NIMO
38
- let uuid = "00000000-0000-4000-8000-000000000001"
39
- let model = NimoResourceSession(captureNonce: uuid, pair: NimoResourcePair(name: "Nimo-Test", peripheralUuid: uuid))
40
- XCTAssertTrue(model.admit(original, instanceId: uuid, name: "Nimo-Test"))
41
- XCTAssertTrue(model.beginRelease(nonce: uuid, cancel: true, mic: false, canvas: false)); model.proveNoTransport()
42
- let stopped = expectation(description: "Original disposal inside real queued manager handoff")
43
- original.onDisconnect = {
44
- XCTAssertFalse(model.shouldRunOrdinaryDisconnect(original, originalClosed: true))
45
- stopped.fulfill()
46
- }
47
- // Same asynchronous connectByName path as G2; simulated replacement
48
- // avoids any Bluetooth transport in this source regression.
49
- store.set("bluetooth", "pending_wearable", DeviceTypes.SIMULATED)
50
- manager.connectByName("Simulated")
51
- XCTAssertEqual(NimoResourceFixture.shared.pendingManagerEntries, 1)
52
- XCTAssertEqual(NimoResourceFixture.shared.pendingOriginalManagerEntries, 0)
53
- wait(for: [stopped], timeout: 1)
54
- var producers = NimoResourceProducers()
55
- producers.postedCallbacks = NimoResourceFixture.shared.pendingOriginalManagerEntries
56
- XCTAssertTrue(model.settled(producers: producers)) // Fresh status during replacement wait.
57
- XCTAssertTrue(model.errors.isEmpty)
58
- let completed = expectation(description: "Replacement queued work has actually settled")
59
- Task { @MainActor in
60
- let deadline = ProcessInfo.processInfo.systemUptime + 2
61
- while ProcessInfo.processInfo.systemUptime < deadline {
62
- if NimoResourceFixture.shared.pendingManagerEntries == 0,
63
- manager.sgc?.type == DeviceTypes.SIMULATED {
64
- completed.fulfill()
65
- return
66
- }
67
- try? await Task.sleep(nanoseconds: 5_000_000)
68
- }
69
- // Leave the expectation unmet on timeout; elapsed delay alone
70
- // cannot stand in for the queued manager's actual completion.
71
- }
72
- wait(for: [completed], timeout: 2.5)
73
- XCTAssertEqual(NimoResourceFixture.shared.pendingManagerEntries, 0)
74
- XCTAssertTrue(model.settled(producers: NimoResourceProducers()))
75
- XCTAssertEqual(manager.sgc?.type, DeviceTypes.SIMULATED)
76
- }
77
- }
78
-
79
8
  func testDelayedReconnectReplayPreservesNimoDepthEndpoints() {
80
9
  for depth in [0, 10] {
81
10
  withRecordingDevice { manager, store in
@@ -138,18 +138,24 @@ final class GlassesAudioSetupPolicyTests: XCTestCase {
138
138
  )
139
139
  }
140
140
 
141
- func testTheGlassesReportingAudioDownAfterConnectedStartsTheReconnectWait() {
141
+ func testPairingProtocolGlassesNeverAskTheUserAfterSetup() {
142
142
  var tracker = GlassesAudioSetupTracker()
143
143
  tracker.startPhase(.reconnect, nowMs: t0)
144
144
  tracker.classicLink(a2dp: true, hfp: true)
145
145
  XCTAssertEqual(tracker.evaluate(sessionReady: true, phoneAudioUp: false, nowMs: t0).state, .connected)
146
146
  tracker.classicLink(a2dp: false, hfp: false)
147
147
  XCTAssertEqual(
148
- tracker.evaluate(sessionReady: true, phoneAudioUp: false, nowMs: t0 + 30000),
149
- GlassesAudioSetupDecision(state: .connecting, nextDeadlineMs: t0 + 40000)
148
+ tracker.evaluate(sessionReady: true, phoneAudioUp: false, nowMs: t0 + 3_600_000),
149
+ GlassesAudioSetupDecision(state: .connecting, nextDeadlineMs: nil)
150
150
  )
151
151
  }
152
152
 
153
+ func testPairingProtocolGlassesStillAskWhenAudioNeverCameUpAfterPairing() {
154
+ let pairing = inputs(report: (false, false), phase: .pairing(autoAudio: true))
155
+ XCTAssertEqual(state(pairing, at: 7999), .connecting)
156
+ XCTAssertEqual(state(pairing, at: 8000), .needsUserConnectInSettings)
157
+ }
158
+
153
159
  func testASessionDropIsIdleAndForgetsTheGlassesReport() {
154
160
  var tracker = GlassesAudioSetupTracker()
155
161
  tracker.startPhase(.reconnect, nowMs: t0)
@@ -16,6 +16,41 @@ private final class IncidentLogTransport: MentraLive {
16
16
  }
17
17
  }
18
18
 
19
+ /// Stands in for Cloud so the tests observe the report each relayed file is posted to.
20
+ private final class CloudStub: URLProtocol {
21
+ nonisolated(unsafe) static var status = 200
22
+ nonisolated(unsafe) static var requests: [String] = []
23
+
24
+ override class func canInit(with request: URLRequest) -> Bool {
25
+ request.url?.host == "cloud-stub.invalid"
26
+ }
27
+
28
+ override class func canonicalRequest(for request: URLRequest) -> URLRequest {
29
+ request
30
+ }
31
+
32
+ override func startLoading() {
33
+ var body = request.httpBody ?? Data()
34
+ if body.isEmpty, let stream = request.httpBodyStream {
35
+ stream.open()
36
+ var buffer = [UInt8](repeating: 0, count: 4096)
37
+ while stream.hasBytesAvailable {
38
+ let count = stream.read(&buffer, maxLength: buffer.count)
39
+ if count <= 0 { break }
40
+ body.append(buffer, count: count)
41
+ }
42
+ stream.close()
43
+ }
44
+ let path = request.url?.path ?? ""
45
+ DispatchQueue.main.sync { CloudStub.requests.append("\(path) \(String(decoding: body, as: UTF8.self))") }
46
+ let response = HTTPURLResponse(url: request.url!, statusCode: CloudStub.status, httpVersion: nil, headerFields: nil)!
47
+ client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)
48
+ client?.urlProtocolDidFinishLoading(self)
49
+ }
50
+
51
+ override func stopLoading() {}
52
+ }
53
+
19
54
  @MainActor
20
55
  final class IncidentLogDispatchTests: XCTestCase {
21
56
  private let incident = "rep_01M4HBVT88DFSN8TYNZ1WTV4PB"
@@ -98,6 +133,129 @@ final class IncidentLogDispatchTests: XCTestCase {
98
133
  XCTAssertNil(queue.dequeue())
99
134
  }
100
135
 
136
+ func testCollidingReportWaitsForOwnerCloudConfirmationAndNeverReceivesItsEvidence() async throws {
137
+ try await withCloud(status: 200) {
138
+ let live = IncidentLogTransport()
139
+ let name = "Brep_01m4hbvt88d"
140
+ try live.sendIncidentId(incident, apiBaseUrl: cloudBase)
141
+ XCTAssertThrowsError(try live.sendIncidentId(collidingIncident, apiBaseUrl: cloudBase)) { error in
142
+ XCTAssertEqual((error as? BluetoothSdkError)?.code, "incident_relay_busy")
143
+ }
144
+ XCTAssertFalse(wire(live).contains(collidingIncident))
145
+ XCTAssertEqual(live.bleIncidentLogRelays[name]?.incidentId, incident)
146
+ XCTAssertEqual(live.bleIncidentLogRelays["Lrep_01m4hbvt88d"]?.incidentId, incident)
147
+
148
+ let logcat = "Lrep_01m4hbvt88d"
149
+ try await receive(live, name, "owner")
150
+ XCTAssertEqual(CloudStub.requests, ["/api/client/reports/\(incident)/artifacts owner"])
151
+ let confirmation = try XCTUnwrap(sentMessages(live).last { $0.contains("transfer_complete") })
152
+ XCTAssertTrue(confirmation.contains(name) && confirmation.contains("\"success\":true"))
153
+ XCTAssertThrowsError(try live.sendIncidentId(collidingIncident, apiBaseUrl: cloudBase)) { error in
154
+ XCTAssertEqual((error as? BluetoothSdkError)?.code, "incident_relay_busy")
155
+ }
156
+ try await receive(live, logcat, "owner-logcat")
157
+
158
+ try live.sendIncidentId(collidingIncident, apiBaseUrl: cloudBase)
159
+ try await receive(live, name, "second")
160
+ XCTAssertEqual(CloudStub.requests.last, "/api/client/reports/\(collidingIncident)/artifacts second")
161
+ }
162
+ }
163
+
164
+ func testStaleCallbackOfFinishedOwnerCannotConfirmCollidingReportsFile() async throws {
165
+ try await withCloud(status: 200) {
166
+ let live = IncidentLogTransport()
167
+ let name = "Brep_01m4hbvt88d"
168
+ let logcat = "Lrep_01m4hbvt88d"
169
+ try live.sendIncidentId(incident, apiBaseUrl: cloudBase)
170
+ let staleRelay = try XCTUnwrap(live.bleIncidentLogRelays[name])
171
+ try await receive(live, name, "owner")
172
+ try await receive(live, logcat, "owner-logcat")
173
+ try live.sendIncidentId(collidingIncident, apiBaseUrl: cloudBase)
174
+ let confirmationsBefore = sentMessages(live).filter { $0.contains("transfer_complete") }.count
175
+ let requestsBefore = CloudStub.requests.count
176
+
177
+ // A late callback of the first report's request arrives while the colliding report owns the name.
178
+ live.uploadBleIncidentLogRelay(relay: staleRelay, fileName: name, data: Data("late".utf8))
179
+ try await waitFor { CloudStub.requests.count == requestsBefore + 1 }
180
+ try await Task.sleep(nanoseconds: 300_000_000)
181
+
182
+ XCTAssertEqual(sentMessages(live).filter { $0.contains("transfer_complete") }.count, confirmationsBefore)
183
+ XCTAssertEqual(live.bleIncidentLogRelays[name]?.incidentId, collidingIncident)
184
+ }
185
+ }
186
+
187
+ func testFailedCloudPostKeepsOwnerUntilOwnershipExpires() async throws {
188
+ try await withCloud(status: 500) {
189
+ let live = IncidentLogTransport()
190
+ var now: TimeInterval = 1000
191
+ live.incidentRelayClock = { now }
192
+ let name = "Brep_01m4hbvt88d"
193
+ try live.sendIncidentId(incident, apiBaseUrl: cloudBase)
194
+ live.uploadBleIncidentLogRelay(
195
+ relay: try XCTUnwrap(live.bleIncidentLogRelays[name]), fileName: name, data: Data("owner".utf8)
196
+ )
197
+ try await waitFor { wire(live).contains("transfer_complete") }
198
+ XCTAssertEqual(live.bleIncidentLogRelays[name]?.incidentId, incident)
199
+ XCTAssertThrowsError(try live.sendIncidentId(collidingIncident, apiBaseUrl: cloudBase)) { error in
200
+ XCTAssertEqual((error as? BluetoothSdkError)?.code, "incident_relay_busy")
201
+ }
202
+
203
+ now += MentraLive.incidentRelayOwnershipSeconds
204
+ try live.sendIncidentId(collidingIncident, apiBaseUrl: cloudBase)
205
+ XCTAssertEqual(live.bleIncidentLogRelays[name]?.incidentId, collidingIncident)
206
+ }
207
+ }
208
+
209
+ func testDispatchFailureOfRefusedReportCannotReleaseOwner() throws {
210
+ try withToken("synthetic") {
211
+ let live = IncidentLogTransport()
212
+ try live.sendIncidentId(incident, apiBaseUrl: apiBase)
213
+ live.ready = false
214
+ XCTAssertThrowsError(try live.sendIncidentId(collidingIncident, apiBaseUrl: apiBase))
215
+ XCTAssertEqual(live.bleIncidentLogRelays["Brep_01m4hbvt88d"]?.incidentId, incident)
216
+ }
217
+ }
218
+
219
+ private let collidingIncident = "rep_01M4HBVT88DZZZZZZZZZZZZZZZ"
220
+ private let cloudBase = "https://cloud-stub.invalid"
221
+
222
+ /// Each message is wrapped as {"C":"<escaped json>"}; unescape so assertions read the message.
223
+ private func sentMessages(_ live: IncidentLogTransport) -> [String] {
224
+ live.writes.map { String(decoding: $0.0, as: UTF8.self).replacingOccurrences(of: "\\\"", with: "\"") }
225
+ }
226
+
227
+ private func wire(_ live: IncidentLogTransport) -> String {
228
+ sentMessages(live).joined()
229
+ }
230
+
231
+ private func withCloud(status: Int, body: () async throws -> Void) async throws {
232
+ CloudStub.status = status
233
+ CloudStub.requests = []
234
+ URLProtocol.registerClass(CloudStub.self)
235
+ defer { URLProtocol.unregisterClass(CloudStub.self) }
236
+ let store = DeviceStore.shared.store
237
+ let saved = store.getCategory("bluetooth")["core_token"]
238
+ store.set("bluetooth", "core_token", "synthetic")
239
+ defer {
240
+ if let saved { store.set("bluetooth", "core_token", saved) }
241
+ else { store.remove("bluetooth", "core_token") }
242
+ }
243
+ try await body()
244
+ }
245
+
246
+ private func receive(_ live: IncidentLogTransport, _ name: String, _ payload: String) async throws {
247
+ let relay = try XCTUnwrap(live.bleIncidentLogRelays[name])
248
+ live.uploadBleIncidentLogRelay(relay: relay, fileName: name, data: Data(payload.utf8))
249
+ try await waitFor { live.bleIncidentLogRelays[name] !== relay }
250
+ }
251
+
252
+ private func waitFor(_ condition: () -> Bool) async throws {
253
+ for _ in 0 ..< 500 where !condition() {
254
+ try await Task.sleep(nanoseconds: 10_000_000)
255
+ }
256
+ XCTAssertTrue(condition())
257
+ }
258
+
101
259
  private func withToken<T>(_ value: String, body: () throws -> T) rethrows -> T {
102
260
  let store = DeviceStore.shared.store
103
261
  let saved = store.getCategory("bluetooth")["core_token"]
@@ -98,24 +98,18 @@ final class MentraLiveAudioSetupTests: XCTestCase {
98
98
  try receive(transport, ["type": "classic_link", "a2dp": true, "hfp": false])
99
99
  XCTAssertEqual(events.count, eventCount)
100
100
 
101
- // Audio lost after connected: the reconnect wait starts again from now.
101
+ // Audio lost after connected: this firmware reconnects its owner's audio itself, so
102
+ // the SDK keeps waiting and never asks the user to pair in Settings.
102
103
  clock(1_060_000)
103
104
  try receive(transport, ["type": "classic_link", "a2dp": false, "hfp": false])
104
105
  XCTAssertEqual(audioSetup(store), .connecting)
105
- clock(1_069_999)
106
- try receive(transport, ["type": "classic_link", "a2dp": false, "hfp": false])
107
- XCTAssertEqual(audioSetup(store), .connecting)
108
-
109
- // The deadline timer gives up at the end of the wait.
110
- clock(1_069_950)
111
- try receive(transport, ["type": "classic_link", "a2dp": false, "hfp": false])
112
106
  clock(1_070_000)
113
- let deadline = Date().addingTimeInterval(2)
114
- while audioSetup(store) != .needsUserConnectInSettings, Date() < deadline {
107
+ let deadline = Date().addingTimeInterval(0.2)
108
+ while Date() < deadline {
115
109
  RunLoop.main.run(until: Date().addingTimeInterval(0.01))
116
110
  }
117
- XCTAssertEqual(audioSetup(store), .needsUserConnectInSettings)
118
- XCTAssertEqual(events.last as NSDictionary?, ["state": "needs_user", "action": "connect_in_settings"])
111
+ XCTAssertEqual(audioSetup(store), .connecting)
112
+ XCTAssertEqual(events.last as NSDictionary?, ["state": "connecting"])
119
113
 
120
114
  // The phone's own signals are enough on their own.
121
115
  store.set("glasses", "bluetoothAudioRouted", true)
@@ -0,0 +1,35 @@
1
+ @testable import MentraBluetoothSDK
2
+ import XCTest
3
+
4
+ @MainActor
5
+ final class MentraLiveCommandQueueTests: XCTestCase {
6
+ func testStaleGenerationRunIsDiscardedInOnePassAheadOfTheCurrentWrite() {
7
+ let queue = MentraLive.CommandQueue()
8
+ for (id, generation) in [("1", 1), ("2", 1), ("3", 2), ("4", 3), ("5", 3)] {
9
+ _ = queue.enqueue(write(id, generation: generation))
10
+ }
11
+
12
+ let next = queue.dequeue(currentGeneration: 3)
13
+ XCTAssertEqual(next.command?.id, "4")
14
+ XCTAssertEqual(next.staleIds, ["1", "2", "3"])
15
+
16
+ let following = queue.dequeue(currentGeneration: 3)
17
+ XCTAssertEqual(following.command?.id, "5")
18
+ XCTAssertEqual(following.staleIds, [])
19
+ }
20
+
21
+ func testQueueOfOnlyStaleWritesDrainsToEmpty() {
22
+ let queue = MentraLive.CommandQueue()
23
+ _ = queue.enqueue(write("1", generation: 1))
24
+ _ = queue.enqueue(write("2", generation: 2))
25
+
26
+ let next = queue.dequeue(currentGeneration: 3)
27
+ XCTAssertNil(next.command)
28
+ XCTAssertEqual(next.staleIds, ["1", "2"])
29
+ XCTAssertNil(queue.dequeue())
30
+ }
31
+
32
+ private func write(_ id: String, generation: Int) -> MentraLive.PendingMessage {
33
+ MentraLive.PendingMessage(data: Data([1]), id: id, retries: 0, generation: generation)
34
+ }
35
+ }