@mentra/engine 0.1.0-beta.0

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 (842) hide show
  1. package/README.md +79 -0
  2. package/build/devtools.d.ts +11 -0
  3. package/build/devtools.d.ts.map +1 -0
  4. package/build/devtools.js +13 -0
  5. package/build/devtools.js.map +1 -0
  6. package/build/engine.d.ts +261 -0
  7. package/build/engine.d.ts.map +1 -0
  8. package/build/engine.js +170 -0
  9. package/build/engine.js.map +1 -0
  10. package/build/facades/dev.d.ts +58 -0
  11. package/build/facades/dev.d.ts.map +1 -0
  12. package/build/facades/dev.js +189 -0
  13. package/build/facades/dev.js.map +1 -0
  14. package/build/facades/display.d.ts +21 -0
  15. package/build/facades/display.d.ts.map +1 -0
  16. package/build/facades/display.js +17 -0
  17. package/build/facades/display.js.map +1 -0
  18. package/build/facades/displayMirror.d.ts +15 -0
  19. package/build/facades/displayMirror.d.ts.map +1 -0
  20. package/build/facades/displayMirror.js +29 -0
  21. package/build/facades/displayMirror.js.map +1 -0
  22. package/build/facades/gallery.d.ts +62 -0
  23. package/build/facades/gallery.d.ts.map +1 -0
  24. package/build/facades/gallery.js +61 -0
  25. package/build/facades/gallery.js.map +1 -0
  26. package/build/facades/glasses.d.ts +141 -0
  27. package/build/facades/glasses.d.ts.map +1 -0
  28. package/build/facades/glasses.js +199 -0
  29. package/build/facades/glasses.js.map +1 -0
  30. package/build/facades/glassesSettings.d.ts +13 -0
  31. package/build/facades/glassesSettings.d.ts.map +1 -0
  32. package/build/facades/glassesSettings.js +54 -0
  33. package/build/facades/glassesSettings.js.map +1 -0
  34. package/build/facades/glassesWifi.d.ts +25 -0
  35. package/build/facades/glassesWifi.d.ts.map +1 -0
  36. package/build/facades/glassesWifi.js +57 -0
  37. package/build/facades/glassesWifi.js.map +1 -0
  38. package/build/facades/miniapps.d.ts +43 -0
  39. package/build/facades/miniapps.d.ts.map +1 -0
  40. package/build/facades/miniapps.js +49 -0
  41. package/build/facades/miniapps.js.map +1 -0
  42. package/build/facades/notifications.d.ts +13 -0
  43. package/build/facades/notifications.d.ts.map +1 -0
  44. package/build/facades/notifications.js +12 -0
  45. package/build/facades/notifications.js.map +1 -0
  46. package/build/facades/ota.d.ts +103 -0
  47. package/build/facades/ota.d.ts.map +1 -0
  48. package/build/facades/ota.js +156 -0
  49. package/build/facades/ota.js.map +1 -0
  50. package/build/facades/pairing.d.ts +114 -0
  51. package/build/facades/pairing.d.ts.map +1 -0
  52. package/build/facades/pairing.js +275 -0
  53. package/build/facades/pairing.js.map +1 -0
  54. package/build/facades/permissions.d.ts +33 -0
  55. package/build/facades/permissions.d.ts.map +1 -0
  56. package/build/facades/permissions.js +155 -0
  57. package/build/facades/permissions.js.map +1 -0
  58. package/build/facades/phoneNotifications.d.ts +21 -0
  59. package/build/facades/phoneNotifications.d.ts.map +1 -0
  60. package/build/facades/phoneNotifications.js +51 -0
  61. package/build/facades/phoneNotifications.js.map +1 -0
  62. package/build/facades/reports.d.ts +36 -0
  63. package/build/facades/reports.d.ts.map +1 -0
  64. package/build/facades/reports.js +134 -0
  65. package/build/facades/reports.js.map +1 -0
  66. package/build/facades/session.d.ts +21 -0
  67. package/build/facades/session.d.ts.map +1 -0
  68. package/build/facades/session.js +52 -0
  69. package/build/facades/session.js.map +1 -0
  70. package/build/facades/settings.d.ts +37 -0
  71. package/build/facades/settings.d.ts.map +1 -0
  72. package/build/facades/settings.js +55 -0
  73. package/build/facades/settings.js.map +1 -0
  74. package/build/facades/speech.d.ts +30 -0
  75. package/build/facades/speech.d.ts.map +1 -0
  76. package/build/facades/speech.js +37 -0
  77. package/build/facades/speech.js.map +1 -0
  78. package/build/index.d.ts +43 -0
  79. package/build/index.d.ts.map +1 -0
  80. package/build/index.js +45 -0
  81. package/build/index.js.map +1 -0
  82. package/build/internal.d.ts +67 -0
  83. package/build/internal.d.ts.map +1 -0
  84. package/build/internal.js +90 -0
  85. package/build/internal.js.map +1 -0
  86. package/build/runtime/bootstrap.d.ts +83 -0
  87. package/build/runtime/bootstrap.d.ts.map +1 -0
  88. package/build/runtime/bootstrap.js +56 -0
  89. package/build/runtime/bootstrap.js.map +1 -0
  90. package/build/runtime/config.d.ts +146 -0
  91. package/build/runtime/config.d.ts.map +1 -0
  92. package/build/runtime/config.js +18 -0
  93. package/build/runtime/config.js.map +1 -0
  94. package/build/runtime/streamConfig.d.ts +4 -0
  95. package/build/runtime/streamConfig.d.ts.map +1 -0
  96. package/build/runtime/streamConfig.js +38 -0
  97. package/build/runtime/streamConfig.js.map +1 -0
  98. package/build/services/AppRegistry.d.ts +269 -0
  99. package/build/services/AppRegistry.d.ts.map +1 -0
  100. package/build/services/AppRegistry.js +1079 -0
  101. package/build/services/AppRegistry.js.map +1 -0
  102. package/build/services/AudioCloudUplink.d.ts +9 -0
  103. package/build/services/AudioCloudUplink.d.ts.map +1 -0
  104. package/build/services/AudioCloudUplink.js +48 -0
  105. package/build/services/AudioCloudUplink.js.map +1 -0
  106. package/build/services/AudioPlaybackService.d.ts +175 -0
  107. package/build/services/AudioPlaybackService.d.ts.map +1 -0
  108. package/build/services/AudioPlaybackService.js +705 -0
  109. package/build/services/AudioPlaybackService.js.map +1 -0
  110. package/build/services/AutomaticReportResult.d.ts +20 -0
  111. package/build/services/AutomaticReportResult.d.ts.map +1 -0
  112. package/build/services/AutomaticReportResult.js +29 -0
  113. package/build/services/AutomaticReportResult.js.map +1 -0
  114. package/build/services/BlobStore.d.ts +91 -0
  115. package/build/services/BlobStore.d.ts.map +1 -0
  116. package/build/services/BlobStore.js +668 -0
  117. package/build/services/BlobStore.js.map +1 -0
  118. package/build/services/CaptionsTesterReportService.d.ts +4 -0
  119. package/build/services/CaptionsTesterReportService.d.ts.map +1 -0
  120. package/build/services/CaptionsTesterReportService.js +80 -0
  121. package/build/services/CaptionsTesterReportService.js.map +1 -0
  122. package/build/services/CloudAudioSubscriptionSync.d.ts +24 -0
  123. package/build/services/CloudAudioSubscriptionSync.d.ts.map +1 -0
  124. package/build/services/CloudAudioSubscriptionSync.js +39 -0
  125. package/build/services/CloudAudioSubscriptionSync.js.map +1 -0
  126. package/build/services/CloudClientService.d.ts +143 -0
  127. package/build/services/CloudClientService.d.ts.map +1 -0
  128. package/build/services/CloudClientService.js +644 -0
  129. package/build/services/CloudClientService.js.map +1 -0
  130. package/build/services/CloudTranscriptE2EMetrics.d.ts +4 -0
  131. package/build/services/CloudTranscriptE2EMetrics.d.ts.map +1 -0
  132. package/build/services/CloudTranscriptE2EMetrics.js +24 -0
  133. package/build/services/CloudTranscriptE2EMetrics.js.map +1 -0
  134. package/build/services/ConnectionCoordinator.d.ts +51 -0
  135. package/build/services/ConnectionCoordinator.d.ts.map +1 -0
  136. package/build/services/ConnectionCoordinator.js +34 -0
  137. package/build/services/ConnectionCoordinator.js.map +1 -0
  138. package/build/services/DevServerBridge.d.ts +63 -0
  139. package/build/services/DevServerBridge.d.ts.map +1 -0
  140. package/build/services/DevServerBridge.js +294 -0
  141. package/build/services/DevServerBridge.js.map +1 -0
  142. package/build/services/DeviceEventRouter.d.ts +3 -0
  143. package/build/services/DeviceEventRouter.d.ts.map +1 -0
  144. package/build/services/DeviceEventRouter.js +190 -0
  145. package/build/services/DeviceEventRouter.js.map +1 -0
  146. package/build/services/DeviceStoreHydration.d.ts +38 -0
  147. package/build/services/DeviceStoreHydration.d.ts.map +1 -0
  148. package/build/services/DeviceStoreHydration.js +124 -0
  149. package/build/services/DeviceStoreHydration.js.map +1 -0
  150. package/build/services/DisplayProcessor.d.ts +223 -0
  151. package/build/services/DisplayProcessor.d.ts.map +1 -0
  152. package/build/services/DisplayProcessor.js +552 -0
  153. package/build/services/DisplayProcessor.js.map +1 -0
  154. package/build/services/GlassesReadiness.d.ts +41 -0
  155. package/build/services/GlassesReadiness.d.ts.map +1 -0
  156. package/build/services/GlassesReadiness.js +82 -0
  157. package/build/services/GlassesReadiness.js.map +1 -0
  158. package/build/services/GlassesSettingsSync.d.ts +33 -0
  159. package/build/services/GlassesSettingsSync.d.ts.map +1 -0
  160. package/build/services/GlassesSettingsSync.js +121 -0
  161. package/build/services/GlassesSettingsSync.js.map +1 -0
  162. package/build/services/GlassesStatusProjection.d.ts +3 -0
  163. package/build/services/GlassesStatusProjection.d.ts.map +1 -0
  164. package/build/services/GlassesStatusProjection.js +65 -0
  165. package/build/services/GlassesStatusProjection.js.map +1 -0
  166. package/build/services/HeadingService.d.ts +27 -0
  167. package/build/services/HeadingService.d.ts.map +1 -0
  168. package/build/services/HeadingService.js +96 -0
  169. package/build/services/HeadingService.js.map +1 -0
  170. package/build/services/LocalDisplayManager.d.ts +139 -0
  171. package/build/services/LocalDisplayManager.d.ts.map +1 -0
  172. package/build/services/LocalDisplayManager.js +579 -0
  173. package/build/services/LocalDisplayManager.js.map +1 -0
  174. package/build/services/LocalMiniappRuntime.d.ts +439 -0
  175. package/build/services/LocalMiniappRuntime.d.ts.map +1 -0
  176. package/build/services/LocalMiniappRuntime.js +3695 -0
  177. package/build/services/LocalMiniappRuntime.js.map +1 -0
  178. package/build/services/LocalSttFallbackCoordinator.d.ts +57 -0
  179. package/build/services/LocalSttFallbackCoordinator.d.ts.map +1 -0
  180. package/build/services/LocalSttFallbackCoordinator.js +137 -0
  181. package/build/services/LocalSttFallbackCoordinator.js.map +1 -0
  182. package/build/services/MentraJSCrashController.d.ts +97 -0
  183. package/build/services/MentraJSCrashController.d.ts.map +1 -0
  184. package/build/services/MentraJSCrashController.js +138 -0
  185. package/build/services/MentraJSCrashController.js.map +1 -0
  186. package/build/services/MentraJSCrashloopReportService.d.ts +9 -0
  187. package/build/services/MentraJSCrashloopReportService.d.ts.map +1 -0
  188. package/build/services/MentraJSCrashloopReportService.js +54 -0
  189. package/build/services/MentraJSCrashloopReportService.js.map +1 -0
  190. package/build/services/MentraJSLogPipeline.d.ts +87 -0
  191. package/build/services/MentraJSLogPipeline.d.ts.map +1 -0
  192. package/build/services/MentraJSLogPipeline.js +137 -0
  193. package/build/services/MentraJSLogPipeline.js.map +1 -0
  194. package/build/services/MentraJSRouter.d.ts +203 -0
  195. package/build/services/MentraJSRouter.d.ts.map +1 -0
  196. package/build/services/MentraJSRouter.js +480 -0
  197. package/build/services/MentraJSRouter.js.map +1 -0
  198. package/build/services/MentraUIRouter.d.ts +137 -0
  199. package/build/services/MentraUIRouter.d.ts.map +1 -0
  200. package/build/services/MentraUIRouter.js +210 -0
  201. package/build/services/MentraUIRouter.js.map +1 -0
  202. package/build/services/MicStateCoordinator.d.ts +37 -0
  203. package/build/services/MicStateCoordinator.d.ts.map +1 -0
  204. package/build/services/MicStateCoordinator.js +81 -0
  205. package/build/services/MicStateCoordinator.js.map +1 -0
  206. package/build/services/MiniappEngine.d.ts +31 -0
  207. package/build/services/MiniappEngine.d.ts.map +1 -0
  208. package/build/services/MiniappEngine.js +119 -0
  209. package/build/services/MiniappEngine.js.map +1 -0
  210. package/build/services/MiniappLauncher.d.ts +129 -0
  211. package/build/services/MiniappLauncher.d.ts.map +1 -0
  212. package/build/services/MiniappLauncher.js +291 -0
  213. package/build/services/MiniappLauncher.js.map +1 -0
  214. package/build/services/MiniappRunningRegistry.d.ts +24 -0
  215. package/build/services/MiniappRunningRegistry.d.ts.map +1 -0
  216. package/build/services/MiniappRunningRegistry.js +52 -0
  217. package/build/services/MiniappRunningRegistry.js.map +1 -0
  218. package/build/services/NativeHttpResponse.d.ts +3 -0
  219. package/build/services/NativeHttpResponse.d.ts.map +1 -0
  220. package/build/services/NativeHttpResponse.js +6 -0
  221. package/build/services/NativeHttpResponse.js.map +1 -0
  222. package/build/services/NavigationHandlers.d.ts +90 -0
  223. package/build/services/NavigationHandlers.d.ts.map +1 -0
  224. package/build/services/NavigationHandlers.js +379 -0
  225. package/build/services/NavigationHandlers.js.map +1 -0
  226. package/build/services/NavigationService.d.ts +254 -0
  227. package/build/services/NavigationService.d.ts.map +1 -0
  228. package/build/services/NavigationService.js +553 -0
  229. package/build/services/NavigationService.js.map +1 -0
  230. package/build/services/NotificationsEmitter.d.ts +28 -0
  231. package/build/services/NotificationsEmitter.d.ts.map +1 -0
  232. package/build/services/NotificationsEmitter.js +22 -0
  233. package/build/services/NotificationsEmitter.js.map +1 -0
  234. package/build/services/OfflineSpeechModelService.d.ts +33 -0
  235. package/build/services/OfflineSpeechModelService.d.ts.map +1 -0
  236. package/build/services/OfflineSpeechModelService.js +136 -0
  237. package/build/services/OfflineSpeechModelService.js.map +1 -0
  238. package/build/services/OtaInstallCoordinator.d.ts +195 -0
  239. package/build/services/OtaInstallCoordinator.d.ts.map +1 -0
  240. package/build/services/OtaInstallCoordinator.js +1047 -0
  241. package/build/services/OtaInstallCoordinator.js.map +1 -0
  242. package/build/services/OtaService.d.ts +3 -0
  243. package/build/services/OtaService.d.ts.map +1 -0
  244. package/build/services/OtaService.js +65 -0
  245. package/build/services/OtaService.js.map +1 -0
  246. package/build/services/OtaUpdateCheckService.d.ts +65 -0
  247. package/build/services/OtaUpdateCheckService.d.ts.map +1 -0
  248. package/build/services/OtaUpdateCheckService.js +260 -0
  249. package/build/services/OtaUpdateCheckService.js.map +1 -0
  250. package/build/services/PairingIdentity.d.ts +80 -0
  251. package/build/services/PairingIdentity.d.ts.map +1 -0
  252. package/build/services/PairingIdentity.js +145 -0
  253. package/build/services/PairingIdentity.js.map +1 -0
  254. package/build/services/PhoneCalendarHelpers.d.ts +32 -0
  255. package/build/services/PhoneCalendarHelpers.d.ts.map +1 -0
  256. package/build/services/PhoneCalendarHelpers.js +157 -0
  257. package/build/services/PhoneCalendarHelpers.js.map +1 -0
  258. package/build/services/PhoneCalendarService.d.ts +5 -0
  259. package/build/services/PhoneCalendarService.d.ts.map +1 -0
  260. package/build/services/PhoneCalendarService.js +24 -0
  261. package/build/services/PhoneCalendarService.js.map +1 -0
  262. package/build/services/PhoneCameraFovCoordinator.d.ts +28 -0
  263. package/build/services/PhoneCameraFovCoordinator.d.ts.map +1 -0
  264. package/build/services/PhoneCameraFovCoordinator.js +180 -0
  265. package/build/services/PhoneCameraFovCoordinator.js.map +1 -0
  266. package/build/services/PhoneLocationService.d.ts +36 -0
  267. package/build/services/PhoneLocationService.d.ts.map +1 -0
  268. package/build/services/PhoneLocationService.js +115 -0
  269. package/build/services/PhoneLocationService.js.map +1 -0
  270. package/build/services/PhoneNotificationsSync.d.ts +3 -0
  271. package/build/services/PhoneNotificationsSync.d.ts.map +1 -0
  272. package/build/services/PhoneNotificationsSync.js +35 -0
  273. package/build/services/PhoneNotificationsSync.js.map +1 -0
  274. package/build/services/PhonePhotoCoordinator.d.ts +103 -0
  275. package/build/services/PhonePhotoCoordinator.d.ts.map +1 -0
  276. package/build/services/PhonePhotoCoordinator.js +326 -0
  277. package/build/services/PhonePhotoCoordinator.js.map +1 -0
  278. package/build/services/PhoneStreamCoordinator.d.ts +168 -0
  279. package/build/services/PhoneStreamCoordinator.d.ts.map +1 -0
  280. package/build/services/PhoneStreamCoordinator.js +632 -0
  281. package/build/services/PhoneStreamCoordinator.js.map +1 -0
  282. package/build/services/PhoneVideoCoordinator.d.ts +50 -0
  283. package/build/services/PhoneVideoCoordinator.d.ts.map +1 -0
  284. package/build/services/PhoneVideoCoordinator.js +147 -0
  285. package/build/services/PhoneVideoCoordinator.js.map +1 -0
  286. package/build/services/STTModelManager.d.ts +65 -0
  287. package/build/services/STTModelManager.d.ts.map +1 -0
  288. package/build/services/STTModelManager.js +292 -0
  289. package/build/services/STTModelManager.js.map +1 -0
  290. package/build/services/SceneRenderer.d.ts +90 -0
  291. package/build/services/SceneRenderer.d.ts.map +1 -0
  292. package/build/services/SceneRenderer.js +248 -0
  293. package/build/services/SceneRenderer.js.map +1 -0
  294. package/build/services/SentenceTtsPipeline.d.ts +31 -0
  295. package/build/services/SentenceTtsPipeline.d.ts.map +1 -0
  296. package/build/services/SentenceTtsPipeline.js +67 -0
  297. package/build/services/SentenceTtsPipeline.js.map +1 -0
  298. package/build/services/StreamLifecycleController.d.ts +67 -0
  299. package/build/services/StreamLifecycleController.d.ts.map +1 -0
  300. package/build/services/StreamLifecycleController.js +152 -0
  301. package/build/services/StreamLifecycleController.js.map +1 -0
  302. package/build/services/TTSModelManager.d.ts +90 -0
  303. package/build/services/TTSModelManager.d.ts.map +1 -0
  304. package/build/services/TTSModelManager.js +366 -0
  305. package/build/services/TTSModelManager.js.map +1 -0
  306. package/build/services/TranscriptionRouting.d.ts +12 -0
  307. package/build/services/TranscriptionRouting.d.ts.map +1 -0
  308. package/build/services/TranscriptionRouting.js +24 -0
  309. package/build/services/TranscriptionRouting.js.map +1 -0
  310. package/build/services/WebviewBridge.d.ts +22 -0
  311. package/build/services/WebviewBridge.d.ts.map +1 -0
  312. package/build/services/WebviewBridge.js +47 -0
  313. package/build/services/WebviewBridge.js.map +1 -0
  314. package/build/services/asg/GalleryMediaIntegrityReportService.d.ts +17 -0
  315. package/build/services/asg/GalleryMediaIntegrityReportService.d.ts.map +1 -0
  316. package/build/services/asg/GalleryMediaIntegrityReportService.js +43 -0
  317. package/build/services/asg/GalleryMediaIntegrityReportService.js.map +1 -0
  318. package/build/services/asg/asgCameraApi.d.ts +205 -0
  319. package/build/services/asg/asgCameraApi.d.ts.map +1 -0
  320. package/build/services/asg/asgCameraApi.js +1410 -0
  321. package/build/services/asg/asgCameraApi.js.map +1 -0
  322. package/build/services/asg/cameraRollExportCoordinator.d.ts +60 -0
  323. package/build/services/asg/cameraRollExportCoordinator.d.ts.map +1 -0
  324. package/build/services/asg/cameraRollExportCoordinator.js +618 -0
  325. package/build/services/asg/cameraRollExportCoordinator.js.map +1 -0
  326. package/build/services/asg/cameraRollExportLedger.d.ts +44 -0
  327. package/build/services/asg/cameraRollExportLedger.d.ts.map +1 -0
  328. package/build/services/asg/cameraRollExportLedger.js +78 -0
  329. package/build/services/asg/cameraRollExportLedger.js.map +1 -0
  330. package/build/services/asg/galleryMediaValidation.d.ts +29 -0
  331. package/build/services/asg/galleryMediaValidation.d.ts.map +1 -0
  332. package/build/services/asg/galleryMediaValidation.js +149 -0
  333. package/build/services/asg/galleryMediaValidation.js.map +1 -0
  334. package/build/services/asg/galleryNotices.d.ts +33 -0
  335. package/build/services/asg/galleryNotices.d.ts.map +1 -0
  336. package/build/services/asg/galleryNotices.js +29 -0
  337. package/build/services/asg/galleryNotices.js.map +1 -0
  338. package/build/services/asg/galleryPathMigration.d.ts +3 -0
  339. package/build/services/asg/galleryPathMigration.d.ts.map +1 -0
  340. package/build/services/asg/galleryPathMigration.js +26 -0
  341. package/build/services/asg/galleryPathMigration.js.map +1 -0
  342. package/build/services/asg/gallerySettingsService.d.ts +20 -0
  343. package/build/services/asg/gallerySettingsService.d.ts.map +1 -0
  344. package/build/services/asg/gallerySettingsService.js +53 -0
  345. package/build/services/asg/gallerySettingsService.js.map +1 -0
  346. package/build/services/asg/gallerySyncNotifications.d.ts +56 -0
  347. package/build/services/asg/gallerySyncNotifications.d.ts.map +1 -0
  348. package/build/services/asg/gallerySyncNotifications.js +198 -0
  349. package/build/services/asg/gallerySyncNotifications.js.map +1 -0
  350. package/build/services/asg/gallerySyncService.d.ts +137 -0
  351. package/build/services/asg/gallerySyncService.d.ts.map +1 -0
  352. package/build/services/asg/gallerySyncService.js +1933 -0
  353. package/build/services/asg/gallerySyncService.js.map +1 -0
  354. package/build/services/asg/galleryTransferLedger.d.ts +58 -0
  355. package/build/services/asg/galleryTransferLedger.d.ts.map +1 -0
  356. package/build/services/asg/galleryTransferLedger.js +225 -0
  357. package/build/services/asg/galleryTransferLedger.js.map +1 -0
  358. package/build/services/asg/localNetworkTransport.d.ts +15 -0
  359. package/build/services/asg/localNetworkTransport.d.ts.map +1 -0
  360. package/build/services/asg/localNetworkTransport.js +144 -0
  361. package/build/services/asg/localNetworkTransport.js.map +1 -0
  362. package/build/services/asg/localStorageService.d.ts +146 -0
  363. package/build/services/asg/localStorageService.d.ts.map +1 -0
  364. package/build/services/asg/localStorageService.js +572 -0
  365. package/build/services/asg/localStorageService.js.map +1 -0
  366. package/build/services/asg/mediaProcessingQueue.d.ts +70 -0
  367. package/build/services/asg/mediaProcessingQueue.d.ts.map +1 -0
  368. package/build/services/asg/mediaProcessingQueue.js +451 -0
  369. package/build/services/asg/mediaProcessingQueue.js.map +1 -0
  370. package/build/services/asgOtaVersionUrl.d.ts +2 -0
  371. package/build/services/asgOtaVersionUrl.d.ts.map +1 -0
  372. package/build/services/asgOtaVersionUrl.js +36 -0
  373. package/build/services/asgOtaVersionUrl.js.map +1 -0
  374. package/build/services/blobPaths.d.ts +31 -0
  375. package/build/services/blobPaths.d.ts.map +1 -0
  376. package/build/services/blobPaths.js +86 -0
  377. package/build/services/blobPaths.js.map +1 -0
  378. package/build/services/cloudStreamApi.d.ts +59 -0
  379. package/build/services/cloudStreamApi.d.ts.map +1 -0
  380. package/build/services/cloudStreamApi.js +81 -0
  381. package/build/services/cloudStreamApi.js.map +1 -0
  382. package/build/services/gallerySyncClock.d.ts +17 -0
  383. package/build/services/gallerySyncClock.d.ts.map +1 -0
  384. package/build/services/gallerySyncClock.js +21 -0
  385. package/build/services/gallerySyncClock.js.map +1 -0
  386. package/build/services/glassesClockSync.d.ts +20 -0
  387. package/build/services/glassesClockSync.d.ts.map +1 -0
  388. package/build/services/glassesClockSync.js +97 -0
  389. package/build/services/glassesClockSync.js.map +1 -0
  390. package/build/services/manifestVersionGate.d.ts +28 -0
  391. package/build/services/manifestVersionGate.d.ts.map +1 -0
  392. package/build/services/manifestVersionGate.js +41 -0
  393. package/build/services/manifestVersionGate.js.map +1 -0
  394. package/build/services/mentraUiShim.d.ts +38 -0
  395. package/build/services/mentraUiShim.d.ts.map +1 -0
  396. package/build/services/mentraUiShim.js +360 -0
  397. package/build/services/mentraUiShim.js.map +1 -0
  398. package/build/services/navigation/roadNameResolver.d.ts +67 -0
  399. package/build/services/navigation/roadNameResolver.d.ts.map +1 -0
  400. package/build/services/navigation/roadNameResolver.js +96 -0
  401. package/build/services/navigation/roadNameResolver.js.map +1 -0
  402. package/build/services/navigation/routesApiCodec.d.ts +38 -0
  403. package/build/services/navigation/routesApiCodec.d.ts.map +1 -0
  404. package/build/services/navigation/routesApiCodec.js +68 -0
  405. package/build/services/navigation/routesApiCodec.js.map +1 -0
  406. package/build/services/otaDisplayState.d.ts +42 -0
  407. package/build/services/otaDisplayState.d.ts.map +1 -0
  408. package/build/services/otaDisplayState.js +92 -0
  409. package/build/services/otaDisplayState.js.map +1 -0
  410. package/build/services/otaInstallPolicy.d.ts +81 -0
  411. package/build/services/otaInstallPolicy.d.ts.map +1 -0
  412. package/build/services/otaInstallPolicy.js +96 -0
  413. package/build/services/otaInstallPolicy.js.map +1 -0
  414. package/build/services/otaLegacyMapping.d.ts +22 -0
  415. package/build/services/otaLegacyMapping.d.ts.map +1 -0
  416. package/build/services/otaLegacyMapping.js +56 -0
  417. package/build/services/otaLegacyMapping.js.map +1 -0
  418. package/build/services/slimStreamStatus.d.ts +7 -0
  419. package/build/services/slimStreamStatus.d.ts.map +1 -0
  420. package/build/services/slimStreamStatus.js +26 -0
  421. package/build/services/slimStreamStatus.js.map +1 -0
  422. package/build/stores/apps.d.ts +104 -0
  423. package/build/stores/apps.d.ts.map +1 -0
  424. package/build/stores/apps.js +492 -0
  425. package/build/stores/apps.js.map +1 -0
  426. package/build/stores/bluetoothSettingKeys.d.ts +4 -0
  427. package/build/stores/bluetoothSettingKeys.d.ts.map +1 -0
  428. package/build/stores/bluetoothSettingKeys.js +31 -0
  429. package/build/stores/bluetoothSettingKeys.js.map +1 -0
  430. package/build/stores/cloudClientStatus.d.ts +9 -0
  431. package/build/stores/cloudClientStatus.d.ts.map +1 -0
  432. package/build/stores/cloudClientStatus.js +24 -0
  433. package/build/stores/cloudClientStatus.js.map +1 -0
  434. package/build/stores/connection.d.ts +22 -0
  435. package/build/stores/connection.d.ts.map +1 -0
  436. package/build/stores/connection.js +43 -0
  437. package/build/stores/connection.js.map +1 -0
  438. package/build/stores/core.d.ts +15 -0
  439. package/build/stores/core.d.ts.map +1 -0
  440. package/build/stores/core.js +21 -0
  441. package/build/stores/core.js.map +1 -0
  442. package/build/stores/display.d.ts +24 -0
  443. package/build/stores/display.d.ts.map +1 -0
  444. package/build/stores/display.js +96 -0
  445. package/build/stores/display.js.map +1 -0
  446. package/build/stores/gallerySync.d.ts +101 -0
  447. package/build/stores/gallerySync.d.ts.map +1 -0
  448. package/build/stores/gallerySync.js +217 -0
  449. package/build/stores/gallerySync.js.map +1 -0
  450. package/build/stores/glasses.d.ts +62 -0
  451. package/build/stores/glasses.d.ts.map +1 -0
  452. package/build/stores/glasses.js +203 -0
  453. package/build/stores/glasses.js.map +1 -0
  454. package/build/stores/settings.d.ts +37 -0
  455. package/build/stores/settings.d.ts.map +1 -0
  456. package/build/stores/settings.js +922 -0
  457. package/build/stores/settings.js.map +1 -0
  458. package/build/types/applet.d.ts +96 -0
  459. package/build/types/applet.d.ts.map +1 -0
  460. package/build/types/applet.js +5 -0
  461. package/build/types/applet.js.map +1 -0
  462. package/build/types/asg.d.ts +53 -0
  463. package/build/types/asg.d.ts.map +1 -0
  464. package/build/types/asg.js +2 -0
  465. package/build/types/asg.js.map +1 -0
  466. package/build/types/capabilities/even-realities-g1.d.ts +12 -0
  467. package/build/types/capabilities/even-realities-g1.d.ts.map +1 -0
  468. package/build/types/capabilities/even-realities-g1.js +55 -0
  469. package/build/types/capabilities/even-realities-g1.js.map +1 -0
  470. package/build/types/capabilities/even-realities-g2.d.ts +12 -0
  471. package/build/types/capabilities/even-realities-g2.d.ts.map +1 -0
  472. package/build/types/capabilities/even-realities-g2.js +75 -0
  473. package/build/types/capabilities/even-realities-g2.js.map +1 -0
  474. package/build/types/capabilities/mentra-display.d.ts +12 -0
  475. package/build/types/capabilities/mentra-display.d.ts.map +1 -0
  476. package/build/types/capabilities/mentra-display.js +63 -0
  477. package/build/types/capabilities/mentra-display.js.map +1 -0
  478. package/build/types/capabilities/mentra-live.d.ts +12 -0
  479. package/build/types/capabilities/mentra-live.d.ts.map +1 -0
  480. package/build/types/capabilities/mentra-live.js +92 -0
  481. package/build/types/capabilities/mentra-live.js.map +1 -0
  482. package/build/types/capabilities/none.d.ts +13 -0
  483. package/build/types/capabilities/none.d.ts.map +1 -0
  484. package/build/types/capabilities/none.js +65 -0
  485. package/build/types/capabilities/none.js.map +1 -0
  486. package/build/types/capabilities/simulated-glasses.d.ts +13 -0
  487. package/build/types/capabilities/simulated-glasses.d.ts.map +1 -0
  488. package/build/types/capabilities/simulated-glasses.js +65 -0
  489. package/build/types/capabilities/simulated-glasses.js.map +1 -0
  490. package/build/types/capabilities/vuzix-z100.d.ts +12 -0
  491. package/build/types/capabilities/vuzix-z100.d.ts.map +1 -0
  492. package/build/types/capabilities/vuzix-z100.js +52 -0
  493. package/build/types/capabilities/vuzix-z100.js.map +1 -0
  494. package/build/types/enums.d.ts +40 -0
  495. package/build/types/enums.d.ts.map +1 -0
  496. package/build/types/enums.js +44 -0
  497. package/build/types/enums.js.map +1 -0
  498. package/build/types/hardware.d.ts +160 -0
  499. package/build/types/hardware.d.ts.map +1 -0
  500. package/build/types/hardware.js +36 -0
  501. package/build/types/hardware.js.map +1 -0
  502. package/build/types/index.d.ts +11 -0
  503. package/build/types/index.d.ts.map +1 -0
  504. package/build/types/index.js +10 -0
  505. package/build/types/index.js.map +1 -0
  506. package/build/utils/GlobalEventEmitter.d.ts +10 -0
  507. package/build/utils/GlobalEventEmitter.d.ts.map +1 -0
  508. package/build/utils/GlobalEventEmitter.js +13 -0
  509. package/build/utils/GlobalEventEmitter.js.map +1 -0
  510. package/build/utils/cloudClient/RnUdpAdapter.d.ts +3 -0
  511. package/build/utils/cloudClient/RnUdpAdapter.d.ts.map +1 -0
  512. package/build/utils/cloudClient/RnUdpAdapter.js +41 -0
  513. package/build/utils/cloudClient/RnUdpAdapter.js.map +1 -0
  514. package/build/utils/cloudClient/cloudSecureStore.d.ts +3 -0
  515. package/build/utils/cloudClient/cloudSecureStore.d.ts.map +1 -0
  516. package/build/utils/cloudClient/cloudSecureStore.js +26 -0
  517. package/build/utils/cloudClient/cloudSecureStore.js.map +1 -0
  518. package/build/utils/debouncedPatch.d.ts +6 -0
  519. package/build/utils/debouncedPatch.d.ts.map +1 -0
  520. package/build/utils/debouncedPatch.js +25 -0
  521. package/build/utils/debouncedPatch.js.map +1 -0
  522. package/build/utils/devLogging.d.ts +26 -0
  523. package/build/utils/devLogging.d.ts.map +1 -0
  524. package/build/utils/devLogging.js +116 -0
  525. package/build/utils/devLogging.js.map +1 -0
  526. package/build/utils/devMiniappLaunch.d.ts +44 -0
  527. package/build/utils/devMiniappLaunch.d.ts.map +1 -0
  528. package/build/utils/devMiniappLaunch.js +52 -0
  529. package/build/utils/devMiniappLaunch.js.map +1 -0
  530. package/build/utils/diagnosticContext.d.ts +3 -0
  531. package/build/utils/diagnosticContext.d.ts.map +1 -0
  532. package/build/utils/diagnosticContext.js +119 -0
  533. package/build/utils/diagnosticContext.js.map +1 -0
  534. package/build/utils/display/composer/ColumnComposer.d.ts +131 -0
  535. package/build/utils/display/composer/ColumnComposer.d.ts.map +1 -0
  536. package/build/utils/display/composer/ColumnComposer.js +204 -0
  537. package/build/utils/display/composer/ColumnComposer.js.map +1 -0
  538. package/build/utils/display/composer/index.d.ts +9 -0
  539. package/build/utils/display/composer/index.d.ts.map +1 -0
  540. package/build/utils/display/composer/index.js +9 -0
  541. package/build/utils/display/composer/index.js.map +1 -0
  542. package/build/utils/display/helpers/DisplayHelpers.d.ts +165 -0
  543. package/build/utils/display/helpers/DisplayHelpers.d.ts.map +1 -0
  544. package/build/utils/display/helpers/DisplayHelpers.js +312 -0
  545. package/build/utils/display/helpers/DisplayHelpers.js.map +1 -0
  546. package/build/utils/display/helpers/ScrollView.d.ts +183 -0
  547. package/build/utils/display/helpers/ScrollView.d.ts.map +1 -0
  548. package/build/utils/display/helpers/ScrollView.js +257 -0
  549. package/build/utils/display/helpers/ScrollView.js.map +1 -0
  550. package/build/utils/display/helpers/index.d.ts +11 -0
  551. package/build/utils/display/helpers/index.d.ts.map +1 -0
  552. package/build/utils/display/helpers/index.js +10 -0
  553. package/build/utils/display/helpers/index.js.map +1 -0
  554. package/build/utils/display/index.d.ts +174 -0
  555. package/build/utils/display/index.d.ts.map +1 -0
  556. package/build/utils/display/index.js +185 -0
  557. package/build/utils/display/index.js.map +1 -0
  558. package/build/utils/display/measurer/TextMeasurer.d.ts +160 -0
  559. package/build/utils/display/measurer/TextMeasurer.d.ts.map +1 -0
  560. package/build/utils/display/measurer/TextMeasurer.js +273 -0
  561. package/build/utils/display/measurer/TextMeasurer.js.map +1 -0
  562. package/build/utils/display/measurer/index.d.ts +10 -0
  563. package/build/utils/display/measurer/index.d.ts.map +1 -0
  564. package/build/utils/display/measurer/index.js +11 -0
  565. package/build/utils/display/measurer/index.js.map +1 -0
  566. package/build/utils/display/measurer/script-detection.d.ts +53 -0
  567. package/build/utils/display/measurer/script-detection.d.ts.map +1 -0
  568. package/build/utils/display/measurer/script-detection.js +184 -0
  569. package/build/utils/display/measurer/script-detection.js.map +1 -0
  570. package/build/utils/display/profiles/g1.d.ts +33 -0
  571. package/build/utils/display/profiles/g1.d.ts.map +1 -0
  572. package/build/utils/display/profiles/g1.js +213 -0
  573. package/build/utils/display/profiles/g1.js.map +1 -0
  574. package/build/utils/display/profiles/g2.d.ts +13 -0
  575. package/build/utils/display/profiles/g2.d.ts.map +1 -0
  576. package/build/utils/display/profiles/g2.js +34 -0
  577. package/build/utils/display/profiles/g2.js.map +1 -0
  578. package/build/utils/display/profiles/index.d.ts +12 -0
  579. package/build/utils/display/profiles/index.d.ts.map +1 -0
  580. package/build/utils/display/profiles/index.js +15 -0
  581. package/build/utils/display/profiles/index.js.map +1 -0
  582. package/build/utils/display/profiles/nex.d.ts +10 -0
  583. package/build/utils/display/profiles/nex.d.ts.map +1 -0
  584. package/build/utils/display/profiles/nex.js +150 -0
  585. package/build/utils/display/profiles/nex.js.map +1 -0
  586. package/build/utils/display/profiles/types.d.ts +103 -0
  587. package/build/utils/display/profiles/types.d.ts.map +1 -0
  588. package/build/utils/display/profiles/types.js +2 -0
  589. package/build/utils/display/profiles/types.js.map +1 -0
  590. package/build/utils/display/profiles/z100.d.ts +33 -0
  591. package/build/utils/display/profiles/z100.d.ts.map +1 -0
  592. package/build/utils/display/profiles/z100.js +182 -0
  593. package/build/utils/display/profiles/z100.js.map +1 -0
  594. package/build/utils/display/scene/degrade.d.ts +25 -0
  595. package/build/utils/display/scene/degrade.d.ts.map +1 -0
  596. package/build/utils/display/scene/degrade.js +64 -0
  597. package/build/utils/display/scene/degrade.js.map +1 -0
  598. package/build/utils/display/scene/differ.d.ts +38 -0
  599. package/build/utils/display/scene/differ.d.ts.map +1 -0
  600. package/build/utils/display/scene/differ.js +107 -0
  601. package/build/utils/display/scene/differ.js.map +1 -0
  602. package/build/utils/display/scene/index.d.ts +10 -0
  603. package/build/utils/display/scene/index.d.ts.map +1 -0
  604. package/build/utils/display/scene/index.js +6 -0
  605. package/build/utils/display/scene/index.js.map +1 -0
  606. package/build/utils/display/scene/process.d.ts +35 -0
  607. package/build/utils/display/scene/process.d.ts.map +1 -0
  608. package/build/utils/display/scene/process.js +187 -0
  609. package/build/utils/display/scene/process.js.map +1 -0
  610. package/build/utils/display/scene/store.d.ts +48 -0
  611. package/build/utils/display/scene/store.d.ts.map +1 -0
  612. package/build/utils/display/scene/store.js +0 -0
  613. package/build/utils/display/scene/store.js.map +1 -0
  614. package/build/utils/display/scene/types.d.ts +120 -0
  615. package/build/utils/display/scene/types.d.ts.map +1 -0
  616. package/build/utils/display/scene/types.js +0 -0
  617. package/build/utils/display/scene/types.js.map +1 -0
  618. package/build/utils/display/wrapper/TextWrapper.d.ts +102 -0
  619. package/build/utils/display/wrapper/TextWrapper.d.ts.map +1 -0
  620. package/build/utils/display/wrapper/TextWrapper.js +471 -0
  621. package/build/utils/display/wrapper/TextWrapper.js.map +1 -0
  622. package/build/utils/display/wrapper/index.d.ts +12 -0
  623. package/build/utils/display/wrapper/index.d.ts.map +1 -0
  624. package/build/utils/display/wrapper/index.js +12 -0
  625. package/build/utils/display/wrapper/index.js.map +1 -0
  626. package/build/utils/display/wrapper/types.d.ts +75 -0
  627. package/build/utils/display/wrapper/types.d.ts.map +1 -0
  628. package/build/utils/display/wrapper/types.js +11 -0
  629. package/build/utils/display/wrapper/types.js.map +1 -0
  630. package/build/utils/e2eMetrics.d.ts +6 -0
  631. package/build/utils/e2eMetrics.d.ts.map +1 -0
  632. package/build/utils/e2eMetrics.js +27 -0
  633. package/build/utils/e2eMetrics.js.map +1 -0
  634. package/build/utils/hardware/hardware.d.ts +42 -0
  635. package/build/utils/hardware/hardware.d.ts.map +1 -0
  636. package/build/utils/hardware/hardware.js +127 -0
  637. package/build/utils/hardware/hardware.js.map +1 -0
  638. package/build/utils/hardware/index.d.ts +2 -0
  639. package/build/utils/hardware/index.d.ts.map +1 -0
  640. package/build/utils/hardware/index.js +2 -0
  641. package/build/utils/hardware/index.js.map +1 -0
  642. package/build/utils/miniappGlobals.d.ts +60 -0
  643. package/build/utils/miniappGlobals.d.ts.map +1 -0
  644. package/build/utils/miniappGlobals.js +224 -0
  645. package/build/utils/miniappGlobals.js.map +1 -0
  646. package/build/utils/permissions/MediaLibraryPermissions.d.ts +45 -0
  647. package/build/utils/permissions/MediaLibraryPermissions.d.ts.map +1 -0
  648. package/build/utils/permissions/MediaLibraryPermissions.js +145 -0
  649. package/build/utils/permissions/MediaLibraryPermissions.js.map +1 -0
  650. package/build/utils/permissions/galleryDisplayName.d.ts +8 -0
  651. package/build/utils/permissions/galleryDisplayName.d.ts.map +1 -0
  652. package/build/utils/permissions/galleryDisplayName.js +25 -0
  653. package/build/utils/permissions/galleryDisplayName.js.map +1 -0
  654. package/build/utils/storage/index.d.ts +3 -0
  655. package/build/utils/storage/index.d.ts.map +1 -0
  656. package/build/utils/storage/index.js +3 -0
  657. package/build/utils/storage/index.js.map +1 -0
  658. package/build/utils/storage/storage.d.ts +24 -0
  659. package/build/utils/storage/storage.d.ts.map +1 -0
  660. package/build/utils/storage/storage.js +85 -0
  661. package/build/utils/storage/storage.js.map +1 -0
  662. package/build/utils/storage/zip.d.ts +3 -0
  663. package/build/utils/storage/zip.d.ts.map +1 -0
  664. package/build/utils/storage/zip.js +14 -0
  665. package/build/utils/storage/zip.js.map +1 -0
  666. package/build/utils/timers/index.d.ts +3 -0
  667. package/build/utils/timers/index.d.ts.map +1 -0
  668. package/build/utils/timers/index.js +3 -0
  669. package/build/utils/timers/index.js.map +1 -0
  670. package/build/utils/timers/timers.d.ts +9 -0
  671. package/build/utils/timers/timers.d.ts.map +1 -0
  672. package/build/utils/timers/timers.js +105 -0
  673. package/build/utils/timers/timers.js.map +1 -0
  674. package/package.json +120 -0
  675. package/src/devtools.ts +13 -0
  676. package/src/engine.ts +173 -0
  677. package/src/facades/dev.ts +198 -0
  678. package/src/facades/display.ts +17 -0
  679. package/src/facades/displayMirror.ts +33 -0
  680. package/src/facades/gallery.ts +69 -0
  681. package/src/facades/glasses.ts +206 -0
  682. package/src/facades/glassesSettings.ts +56 -0
  683. package/src/facades/glassesWifi.ts +68 -0
  684. package/src/facades/miniapps.ts +55 -0
  685. package/src/facades/notifications.ts +15 -0
  686. package/src/facades/ota.ts +174 -0
  687. package/src/facades/pairing.ts +329 -0
  688. package/src/facades/permissions.ts +165 -0
  689. package/src/facades/phoneNotifications.ts +50 -0
  690. package/src/facades/reports.ts +185 -0
  691. package/src/facades/session.ts +55 -0
  692. package/src/facades/settings.ts +57 -0
  693. package/src/facades/speech.ts +38 -0
  694. package/src/index.ts +191 -0
  695. package/src/internal.ts +159 -0
  696. package/src/runtime/bootstrap.ts +118 -0
  697. package/src/runtime/config.ts +147 -0
  698. package/src/runtime/streamConfig.ts +34 -0
  699. package/src/services/AppRegistry.ts +1190 -0
  700. package/src/services/AudioCloudUplink.ts +50 -0
  701. package/src/services/AudioPlaybackService.ts +813 -0
  702. package/src/services/AutomaticReportResult.ts +48 -0
  703. package/src/services/BlobStore.ts +746 -0
  704. package/src/services/CaptionsTesterReportService.ts +107 -0
  705. package/src/services/CloudAudioSubscriptionSync.ts +41 -0
  706. package/src/services/CloudClientService.ts +689 -0
  707. package/src/services/CloudTranscriptE2EMetrics.ts +27 -0
  708. package/src/services/ConnectionCoordinator.ts +65 -0
  709. package/src/services/DevServerBridge.ts +332 -0
  710. package/src/services/DeviceEventRouter.ts +238 -0
  711. package/src/services/DeviceStoreHydration.ts +130 -0
  712. package/src/services/DisplayProcessor.ts +775 -0
  713. package/src/services/GlassesReadiness.ts +103 -0
  714. package/src/services/GlassesSettingsSync.ts +134 -0
  715. package/src/services/GlassesStatusProjection.ts +73 -0
  716. package/src/services/HeadingService.ts +98 -0
  717. package/src/services/LocalDisplayManager.ts +703 -0
  718. package/src/services/LocalMiniappRuntime.ts +4213 -0
  719. package/src/services/LocalSttFallbackCoordinator.ts +147 -0
  720. package/src/services/MentraJSCrashController.ts +189 -0
  721. package/src/services/MentraJSCrashloopReportService.ts +66 -0
  722. package/src/services/MentraJSLogPipeline.ts +166 -0
  723. package/src/services/MentraJSRouter.ts +557 -0
  724. package/src/services/MentraUIRouter.ts +244 -0
  725. package/src/services/MicStateCoordinator.ts +94 -0
  726. package/src/services/MiniappEngine.ts +143 -0
  727. package/src/services/MiniappLauncher.ts +340 -0
  728. package/src/services/MiniappRunningRegistry.ts +57 -0
  729. package/src/services/NativeHttpResponse.ts +6 -0
  730. package/src/services/NavigationHandlers.ts +423 -0
  731. package/src/services/NavigationService.ts +731 -0
  732. package/src/services/NotificationsEmitter.ts +48 -0
  733. package/src/services/OfflineSpeechModelService.ts +168 -0
  734. package/src/services/OtaInstallCoordinator.ts +1205 -0
  735. package/src/services/OtaService.ts +83 -0
  736. package/src/services/OtaUpdateCheckService.ts +386 -0
  737. package/src/services/PairingIdentity.ts +154 -0
  738. package/src/services/PhoneCalendarHelpers.ts +212 -0
  739. package/src/services/PhoneCalendarService.ts +42 -0
  740. package/src/services/PhoneCameraFovCoordinator.ts +195 -0
  741. package/src/services/PhoneLocationService.ts +122 -0
  742. package/src/services/PhoneNotificationsSync.ts +44 -0
  743. package/src/services/PhonePhotoCoordinator.ts +409 -0
  744. package/src/services/PhoneStreamCoordinator.ts +777 -0
  745. package/src/services/PhoneVideoCoordinator.ts +189 -0
  746. package/src/services/STTModelManager.ts +360 -0
  747. package/src/services/SceneRenderer.ts +292 -0
  748. package/src/services/SentenceTtsPipeline.ts +106 -0
  749. package/src/services/StreamLifecycleController.ts +213 -0
  750. package/src/services/TTSModelManager.ts +466 -0
  751. package/src/services/TranscriptionRouting.ts +37 -0
  752. package/src/services/WebviewBridge.ts +50 -0
  753. package/src/services/asg/GalleryMediaIntegrityReportService.ts +70 -0
  754. package/src/services/asg/asgCameraApi.ts +1695 -0
  755. package/src/services/asg/cameraRollExportCoordinator.ts +627 -0
  756. package/src/services/asg/cameraRollExportLedger.ts +122 -0
  757. package/src/services/asg/galleryMediaValidation.ts +183 -0
  758. package/src/services/asg/galleryNotices.ts +61 -0
  759. package/src/services/asg/galleryPathMigration.ts +22 -0
  760. package/src/services/asg/gallerySettingsService.ts +68 -0
  761. package/src/services/asg/gallerySyncNotifications.ts +236 -0
  762. package/src/services/asg/gallerySyncService.ts +2269 -0
  763. package/src/services/asg/galleryTransferLedger.ts +312 -0
  764. package/src/services/asg/localNetworkTransport.ts +173 -0
  765. package/src/services/asg/localStorageService.ts +652 -0
  766. package/src/services/asg/mediaProcessingQueue.ts +518 -0
  767. package/src/services/asgOtaVersionUrl.ts +41 -0
  768. package/src/services/blobPaths.ts +86 -0
  769. package/src/services/cloudStreamApi.ts +154 -0
  770. package/src/services/gallerySyncClock.ts +39 -0
  771. package/src/services/glassesClockSync.ts +115 -0
  772. package/src/services/manifestVersionGate.ts +43 -0
  773. package/src/services/mentraUiShim.ts +366 -0
  774. package/src/services/navigation/roadNameResolver.ts +112 -0
  775. package/src/services/navigation/routesApiCodec.ts +69 -0
  776. package/src/services/otaDisplayState.ts +115 -0
  777. package/src/services/otaInstallPolicy.ts +106 -0
  778. package/src/services/otaLegacyMapping.ts +71 -0
  779. package/src/services/slimStreamStatus.ts +28 -0
  780. package/src/stores/apps.ts +614 -0
  781. package/src/stores/bluetoothSettingKeys.ts +36 -0
  782. package/src/stores/cloudClientStatus.ts +37 -0
  783. package/src/stores/connection.ts +69 -0
  784. package/src/stores/core.ts +32 -0
  785. package/src/stores/display.ts +121 -0
  786. package/src/stores/gallerySync.ts +380 -0
  787. package/src/stores/glasses.ts +309 -0
  788. package/src/stores/settings.ts +1001 -0
  789. package/src/types/applet.ts +112 -0
  790. package/src/types/asg.ts +58 -0
  791. package/src/types/capabilities/even-realities-g1.ts +67 -0
  792. package/src/types/capabilities/even-realities-g2.ts +88 -0
  793. package/src/types/capabilities/mentra-display.ts +75 -0
  794. package/src/types/capabilities/mentra-live.ts +103 -0
  795. package/src/types/capabilities/none.ts +76 -0
  796. package/src/types/capabilities/simulated-glasses.ts +76 -0
  797. package/src/types/capabilities/vuzix-z100.ts +64 -0
  798. package/src/types/enums.ts +43 -0
  799. package/src/types/hardware.ts +203 -0
  800. package/src/types/index.ts +37 -0
  801. package/src/utils/GlobalEventEmitter.ts +14 -0
  802. package/src/utils/cloudClient/RnUdpAdapter.ts +47 -0
  803. package/src/utils/cloudClient/cloudSecureStore.ts +28 -0
  804. package/src/utils/debouncedPatch.ts +28 -0
  805. package/src/utils/devLogging.ts +140 -0
  806. package/src/utils/devMiniappLaunch.ts +68 -0
  807. package/src/utils/diagnosticContext.ts +155 -0
  808. package/src/utils/display/composer/ColumnComposer.ts +285 -0
  809. package/src/utils/display/composer/index.ts +15 -0
  810. package/src/utils/display/helpers/DisplayHelpers.ts +413 -0
  811. package/src/utils/display/helpers/ScrollView.ts +337 -0
  812. package/src/utils/display/helpers/index.ts +14 -0
  813. package/src/utils/display/index.ts +273 -0
  814. package/src/utils/display/measurer/TextMeasurer.ts +346 -0
  815. package/src/utils/display/measurer/index.ts +21 -0
  816. package/src/utils/display/measurer/script-detection.ts +218 -0
  817. package/src/utils/display/profiles/g1.ts +236 -0
  818. package/src/utils/display/profiles/g2.ts +39 -0
  819. package/src/utils/display/profiles/index.ts +28 -0
  820. package/src/utils/display/profiles/nex.ts +166 -0
  821. package/src/utils/display/profiles/types.ts +132 -0
  822. package/src/utils/display/profiles/z100.ts +198 -0
  823. package/src/utils/display/scene/degrade.ts +80 -0
  824. package/src/utils/display/scene/differ.ts +128 -0
  825. package/src/utils/display/scene/index.ts +21 -0
  826. package/src/utils/display/scene/process.ts +214 -0
  827. package/src/utils/display/scene/store.ts +0 -0
  828. package/src/utils/display/scene/types.ts +0 -0
  829. package/src/utils/display/wrapper/TextWrapper.ts +546 -0
  830. package/src/utils/display/wrapper/index.ts +15 -0
  831. package/src/utils/display/wrapper/types.ts +102 -0
  832. package/src/utils/e2eMetrics.ts +30 -0
  833. package/src/utils/hardware/hardware.ts +166 -0
  834. package/src/utils/hardware/index.ts +1 -0
  835. package/src/utils/miniappGlobals.ts +260 -0
  836. package/src/utils/permissions/MediaLibraryPermissions.ts +161 -0
  837. package/src/utils/permissions/galleryDisplayName.ts +28 -0
  838. package/src/utils/storage/index.ts +2 -0
  839. package/src/utils/storage/storage.ts +101 -0
  840. package/src/utils/storage/zip.ts +13 -0
  841. package/src/utils/timers/index.ts +2 -0
  842. package/src/utils/timers/timers.ts +139 -0
@@ -0,0 +1,2269 @@
1
+ /**
2
+ * Gallery Sync Service
3
+ * Orchestrates gallery sync independently of UI lifecycle
4
+ */
5
+
6
+ import * as RNFS from "@dr.pogodin/react-native-fs"
7
+ import NetInfo from "@react-native-community/netinfo"
8
+ import BluetoothSdk from "@mentra/bluetooth-sdk/internal"
9
+ import CrustModule from "@mentra/crust"
10
+ import {AppState, AppStateStatus, Platform} from "react-native"
11
+ import BleManager from "react-native-ble-manager"
12
+ import WifiManager from "react-native-wifi-reborn"
13
+
14
+ import {useGallerySyncStore, HotspotInfo} from "../../stores/gallerySync"
15
+ import {selectGlassesConnected, useGlassesStore} from "../../stores/glasses"
16
+ import {isGlassesConnected} from "../GlassesReadiness"
17
+ import {SETTINGS, useSettingsStore} from "../../stores/settings"
18
+ import {PhotoInfo, CaptureGroup} from "../../types/asg"
19
+ import GlobalEventEmitter from "../../utils/GlobalEventEmitter"
20
+ import {BgTimer} from "../../utils/timers"
21
+ import {fixGlassesClockIfSkewed} from "../glassesClockSync"
22
+ import {detectClockSkew, isSyncManifestEmpty} from "../gallerySyncClock"
23
+ import {MediaLibraryPermissions} from "../../utils/permissions/MediaLibraryPermissions"
24
+ import {permissions, PermissionFeatures} from "../../facades/permissions"
25
+
26
+ import {asgCameraApi} from "./asgCameraApi"
27
+ import {gallerySettingsService} from "./gallerySettingsService"
28
+ import {gallerySyncNotifications} from "./gallerySyncNotifications"
29
+ import {localNetworkTransport} from "./localNetworkTransport"
30
+ import {localStorageService} from "./localStorageService"
31
+ import {mediaProcessingQueue} from "./mediaProcessingQueue"
32
+ import {validateCaptureMetadataForDownload} from "./galleryMediaValidation"
33
+ import {emitGalleryNotice} from "./galleryNotices"
34
+ import {galleryTransferLedger} from "./galleryTransferLedger"
35
+ import {cameraRollExportCoordinator} from "./cameraRollExportCoordinator"
36
+
37
+ // Timing constants
38
+ const TIMING = {
39
+ HOTSPOT_CONNECT_DELAY_MS: 3000, // Increased from 1000ms - hotspot needs time to broadcast and become discoverable
40
+ HOTSPOT_REQUEST_TIMEOUT_MS: 30000, // Timeout waiting for hotspot to enable
41
+ WIFI_CONNECTION_TIMEOUT_MS: 30000,
42
+ RETRY_DELAY_MS: 2000,
43
+ MAX_QUEUE_AGE_MS: 2 * 60 * 1000, // 2 min - glasses hotspot auto-disables after 40s inactivity
44
+ // iOS WiFi connection timing - the system shows a dialog that user must accept
45
+ IOS_WIFI_RETRY_DELAY_MS: 3000, // Wait for user to interact with iOS dialog
46
+ IOS_WIFI_MAX_RETRIES: 5, // Retry multiple times to give user time to accept
47
+ // WiFi initialization cooldown - prevents repeated "enable WiFi" alerts while WiFi is initializing
48
+ WIFI_COOLDOWN_MS: 3000, // Wait 3 seconds after user visits WiFi settings before showing alert again
49
+ // Cap the native location-services (GPS) check so a hung CrustModule call can't freeze
50
+ // the sync pre-flight (mirrors the host's former PermissionsUtils guard).
51
+ LOCATION_SERVICES_CHECK_TIMEOUT_MS: 5000,
52
+ } as const
53
+
54
+ type SyncManifestData = {
55
+ api_version?: number
56
+ client_id: string
57
+ captures?: CaptureGroup[]
58
+ changed_files: PhotoInfo[]
59
+ deleted_files?: string[]
60
+ server_time: number
61
+ total_changed?: number
62
+ total_size?: number
63
+ }
64
+
65
+ class GallerySyncService {
66
+ private static instance: GallerySyncService
67
+ private hotspotListenerRegistered = false
68
+ private hotspotConnectionTimeout: number | null = null
69
+ private hotspotRequestTimeout: number | null = null
70
+ private abortController: AbortController | null = null
71
+ private isInitialized = false
72
+ private glassesStoreUnsubscribe: (() => void) | null = null
73
+ private appStateSubscription: ReturnType<typeof AppState.addEventListener> | null = null
74
+ private waitingForWifiRetry = false
75
+ // Guards full-sync recovery so we don't re-download the entire gallery every sync
76
+ // when glasses retain leftover files (e.g. a previous delete-from-glasses failed).
77
+ // Keyed by `${client_id}:${last_sync_time}` — same pair = already tried, skip.
78
+ private lastFullSyncRetryKey: string | null = null
79
+ private wifiSettingsOpenedAt: number | null = null // Timestamp when user was sent to WiFi settings
80
+ private syncStartPromise: Promise<void> | null = null
81
+ private startAborted = false
82
+
83
+ private constructor() {}
84
+
85
+ static getInstance(): GallerySyncService {
86
+ if (!GallerySyncService.instance) {
87
+ GallerySyncService.instance = new GallerySyncService()
88
+ }
89
+ return GallerySyncService.instance
90
+ }
91
+
92
+ /**
93
+ * Initialize the service - register event listeners
94
+ */
95
+ initialize(): void {
96
+ if (this.isInitialized) return
97
+
98
+ // Listen for hotspot status changes
99
+ GlobalEventEmitter.addListener("hotspot_status_change", this.handleHotspotStatusChange)
100
+ GlobalEventEmitter.addListener("hotspot_error", this.handleHotspotError)
101
+ GlobalEventEmitter.addListener("gallery_status", this.handleGalleryStatus)
102
+
103
+ // Subscribe to glasses store to detect disconnection during sync
104
+ this.glassesStoreUnsubscribe = useGlassesStore.subscribe(selectGlassesConnected, (connected, prevConnected) => {
105
+ // Only trigger on disconnect (was connected, now not connected)
106
+ if (prevConnected && !connected) {
107
+ this.handleGlassesDisconnected()
108
+ }
109
+ })
110
+
111
+ // Listen for app state changes to auto-retry sync after user enables WiFi
112
+ this.appStateSubscription = AppState.addEventListener("change", this.handleAppStateChange)
113
+
114
+ this.hotspotListenerRegistered = true
115
+ this.isInitialized = true
116
+
117
+ void cameraRollExportCoordinator.initialize()
118
+
119
+ // console.log("[GallerySyncService] Initialized")
120
+
121
+ // Check for resumable sync on startup
122
+ this.checkForResumableSync()
123
+ }
124
+
125
+ /**
126
+ * Cleanup - remove event listeners
127
+ */
128
+ cleanup(): void {
129
+ void localNetworkTransport.disconnect()
130
+ if (this.hotspotListenerRegistered) {
131
+ GlobalEventEmitter.removeListener("hotspot_status_change", this.handleHotspotStatusChange)
132
+ GlobalEventEmitter.removeListener("hotspot_error", this.handleHotspotError)
133
+ GlobalEventEmitter.removeListener("gallery_status", this.handleGalleryStatus)
134
+ this.hotspotListenerRegistered = false
135
+ }
136
+
137
+ if (this.glassesStoreUnsubscribe) {
138
+ this.glassesStoreUnsubscribe()
139
+ this.glassesStoreUnsubscribe = null
140
+ }
141
+
142
+ if (this.appStateSubscription) {
143
+ this.appStateSubscription.remove()
144
+ this.appStateSubscription = null
145
+ }
146
+ cameraRollExportCoordinator.cleanup()
147
+
148
+ if (this.hotspotConnectionTimeout) {
149
+ BgTimer.clearTimeout(this.hotspotConnectionTimeout!)
150
+ this.hotspotConnectionTimeout = null
151
+ }
152
+
153
+ if (this.hotspotRequestTimeout) {
154
+ BgTimer.clearTimeout(this.hotspotRequestTimeout!)
155
+ this.hotspotRequestTimeout = null
156
+ }
157
+
158
+ this.syncStartPromise = null
159
+ this.isInitialized = false
160
+ console.log("[GallerySyncService] Cleaned up")
161
+ }
162
+
163
+ /**
164
+ * Handle glasses disconnection during sync
165
+ */
166
+ private handleGlassesDisconnected = (): void => {
167
+ const store = useGallerySyncStore.getState()
168
+
169
+ // Pre-flight has no sync state yet — abort quietly; runStartSync checks this flag after awaits
170
+ if (this.syncStartPromise && !this.isSyncing()) {
171
+ console.log("[GallerySyncService] Glasses disconnected during pre-flight — aborting start")
172
+ this.startAborted = true
173
+ return
174
+ }
175
+
176
+ // Only handle if we're actively syncing
177
+ if (!this.isSyncing()) {
178
+ return
179
+ }
180
+
181
+ console.log("[GallerySyncService] Glasses disconnected during sync - cancelling")
182
+ store.setSyncError("Glasses disconnected")
183
+
184
+ // Abort ongoing downloads
185
+ if (this.abortController) {
186
+ this.abortController.abort()
187
+ this.abortController = null
188
+ }
189
+
190
+ // Clear timeouts
191
+ if (this.hotspotConnectionTimeout) {
192
+ BgTimer.clearTimeout(this.hotspotConnectionTimeout!)
193
+ this.hotspotConnectionTimeout = null
194
+ }
195
+ if (this.hotspotRequestTimeout) {
196
+ BgTimer.clearTimeout(this.hotspotRequestTimeout!)
197
+ this.hotspotRequestTimeout = null
198
+ }
199
+
200
+ gallerySyncNotifications.showSyncError("Glasses disconnected")
201
+ void localNetworkTransport.disconnect()
202
+ }
203
+
204
+ /**
205
+ * Handle app state changes to auto-retry sync when user returns from settings
206
+ */
207
+ private handleAppStateChange = async (nextAppState: AppStateStatus): Promise<void> => {
208
+ // Only handle when app comes to foreground
209
+ if (nextAppState !== "active") {
210
+ return
211
+ }
212
+
213
+ // Camera-roll backfill is phone-local and must resume independently of glasses/WiFi.
214
+ void cameraRollExportCoordinator.resume("app foreground")
215
+
216
+ // Only auto-retry if we were waiting for WiFi
217
+ if (!this.waitingForWifiRetry) {
218
+ return
219
+ }
220
+
221
+ console.log("[GallerySyncService] App returned to foreground - checking if WiFi is enabled")
222
+
223
+ const store = useGallerySyncStore.getState()
224
+ const glassesStore = useGlassesStore.getState()
225
+ const glassesConnected = isGlassesConnected(glassesStore.connection)
226
+
227
+ // Check if glasses are still connected
228
+ if (!glassesConnected) {
229
+ console.log("[GallerySyncService] Glasses disconnected - not retrying sync")
230
+ this.waitingForWifiRetry = false
231
+ return
232
+ }
233
+
234
+ // Check if WiFi is now enabled (Android only)
235
+ // Use retry logic because WiFi status takes time to propagate after user enables it
236
+ if (Platform.OS === "android") {
237
+ const MAX_RETRIES = 5
238
+ const RETRY_DELAY_MS = 1000 // Wait 500ms between checks
239
+
240
+ console.log("[GallerySyncService] Waiting for WiFi to initialize (may take a moment after enabling)...")
241
+
242
+ for (let attempt = 1; attempt <= MAX_RETRIES; attempt++) {
243
+ try {
244
+ await new Promise<void>((resolve) => BgTimer.setTimeout(() => resolve(), RETRY_DELAY_MS))
245
+
246
+ const netState = await NetInfo.fetch()
247
+ console.log(
248
+ `[GallerySyncService] WiFi check attempt ${attempt}/${MAX_RETRIES}: enabled=${netState.isWifiEnabled}`,
249
+ )
250
+
251
+ if (netState.isWifiEnabled === true) {
252
+ console.log("[GallerySyncService] ✅ WiFi is now enabled - auto-retrying sync")
253
+ this.waitingForWifiRetry = false
254
+ this.wifiSettingsOpenedAt = null // Clear cooldown timestamp
255
+ // Clear previous error state
256
+ store.setSyncState("idle")
257
+ // Auto-retry sync
258
+ await this.startSync()
259
+ return
260
+ }
261
+
262
+ // If this was the last attempt, log and give up
263
+ if (attempt === MAX_RETRIES) {
264
+ console.log(
265
+ "[GallerySyncService] ❌ WiFi still disabled after all retries - user may need to tap sync manually",
266
+ )
267
+ this.waitingForWifiRetry = false
268
+ this.wifiSettingsOpenedAt = null // Clear cooldown timestamp
269
+ }
270
+ } catch (error) {
271
+ console.warn(`[GallerySyncService] Failed to check WiFi status on attempt ${attempt}:`, error)
272
+ // Continue to next retry
273
+ }
274
+ }
275
+ }
276
+ }
277
+
278
+ /**
279
+ * Handle gallery status from glasses
280
+ */
281
+ private handleGalleryStatus = (data: any): void => {
282
+ console.log("[GallerySyncService] Received gallery_status:", data)
283
+
284
+ const store = useGallerySyncStore.getState()
285
+ store.setGlassesGalleryStatus(data.photos || 0, data.videos || 0, data.total || 0, data.has_content || false)
286
+ }
287
+
288
+ /**
289
+ * Handle hotspot status change event
290
+ */
291
+ private handleHotspotStatusChange = async (eventData: any): Promise<void> => {
292
+ console.log("[GallerySyncService] Hotspot status changed:", eventData)
293
+
294
+ const store = useGallerySyncStore.getState()
295
+
296
+ // Only process if we're in a connecting state
297
+ if (store.syncState !== "requesting_hotspot" && store.syncState !== "connecting_wifi") {
298
+ console.log("[GallerySyncService] Ignoring hotspot event - not in connecting state")
299
+ return
300
+ }
301
+
302
+ if (!eventData.enabled || !eventData.ssid || !eventData.password) {
303
+ console.log("[GallerySyncService] Hotspot not ready yet")
304
+ return
305
+ }
306
+
307
+ // Clear the hotspot request timeout since we got a response
308
+ if (this.hotspotRequestTimeout) {
309
+ BgTimer.clearTimeout(this.hotspotRequestTimeout!)
310
+ this.hotspotRequestTimeout = null
311
+ }
312
+
313
+ // Pre-flight: do not start the wait if already disconnected (e.g. BT dropped right after hotspot enabled)
314
+ if (!isGlassesConnected(useGlassesStore.getState().connection)) {
315
+ console.log("[GallerySyncService] ❌ Glasses disconnected on hotspot_status_change - aborting (no wait)")
316
+ store.setSyncError("Glasses disconnected")
317
+ gallerySyncNotifications.showSyncError("Glasses disconnected")
318
+ return
319
+ }
320
+
321
+ const hotspotInfo: HotspotInfo = {
322
+ ssid: eventData.ssid,
323
+ password: eventData.password,
324
+ ip: eventData.local_ip,
325
+ }
326
+
327
+ store.setHotspotInfo(hotspotInfo)
328
+
329
+ // Wait for hotspot to become discoverable
330
+ console.log(
331
+ `[GallerySyncService] Hotspot enabled, waiting ${TIMING.HOTSPOT_CONNECT_DELAY_MS}ms for broadcast initialization...`,
332
+ )
333
+ console.log("[GallerySyncService] 📡 Glasses need time to start WiFi AP and broadcast SSID")
334
+
335
+ if (this.hotspotConnectionTimeout) {
336
+ BgTimer.clearTimeout(this.hotspotConnectionTimeout!)
337
+ }
338
+
339
+ this.hotspotConnectionTimeout = BgTimer.setTimeout(() => {
340
+ this.hotspotConnectionTimeout = null
341
+ // Pre-flight: abort if Bluetooth disconnected during the wait
342
+ const stillConnected = isGlassesConnected(useGlassesStore.getState().connection)
343
+ if (!stillConnected) {
344
+ console.log("[GallerySyncService] ❌ Glasses disconnected during hotspot wait - skipping WiFi connection")
345
+ const currentStore = useGallerySyncStore.getState()
346
+ currentStore.setSyncError("Glasses disconnected")
347
+ gallerySyncNotifications.showSyncError("Glasses disconnected")
348
+ return
349
+ }
350
+ console.log("[GallerySyncService] ✅ Hotspot broadcast window complete - attempting connection")
351
+ this.connectToHotspotWifi(hotspotInfo)
352
+ }, TIMING.HOTSPOT_CONNECT_DELAY_MS)
353
+ }
354
+
355
+ /**
356
+ * Handle hotspot error event
357
+ */
358
+ private handleHotspotError = (eventData: any): void => {
359
+ console.error("[GallerySyncService] Hotspot error:", eventData)
360
+
361
+ const store = useGallerySyncStore.getState()
362
+
363
+ if (this.hotspotConnectionTimeout) {
364
+ BgTimer.clearTimeout(this.hotspotConnectionTimeout!)
365
+ this.hotspotConnectionTimeout = null
366
+ }
367
+
368
+ store.setSyncError(eventData.error_message || "Failed to start hotspot")
369
+ gallerySyncNotifications.showSyncError("Failed to start hotspot")
370
+ }
371
+
372
+ /**
373
+ * Start the sync process
374
+ */
375
+ async startSync(): Promise<void> {
376
+ if (this.syncStartPromise) {
377
+ console.log("[GallerySyncService] ⚠️ Sync start already in progress, joining existing attempt")
378
+ return this.syncStartPromise
379
+ }
380
+
381
+ this.syncStartPromise = this.runStartSync().finally(() => {
382
+ this.syncStartPromise = null
383
+ })
384
+ return this.syncStartPromise
385
+ }
386
+
387
+ /**
388
+ * Native location-services (GPS on/off) check, raced against a timeout so a hung
389
+ * CrustModule call can't freeze the sync pre-flight. Mirrors the host's former
390
+ * PermissionsUtils.isLocationServicesEnabled exactly: on timeout assume enabled
391
+ * (proceed); on any other native error assume disabled (block + prompt). Android-only
392
+ * callers; iOS doesn't need location for BLE since iOS 13.
393
+ */
394
+ private async isLocationServicesEnabled(): Promise<boolean> {
395
+ try {
396
+ return await Promise.race([
397
+ CrustModule.isLocationServicesEnabled(),
398
+ new Promise<boolean>((_, reject) =>
399
+ setTimeout(
400
+ () => reject(new Error("Location services check timed out")),
401
+ TIMING.LOCATION_SERVICES_CHECK_TIMEOUT_MS,
402
+ ),
403
+ ),
404
+ ])
405
+ } catch (error) {
406
+ console.error("[GallerySyncService] Error checking location services:", error)
407
+ if (error instanceof Error && error.message.includes("timed out")) {
408
+ console.warn("[GallerySyncService] Location services check timed out — assuming enabled so sync can proceed")
409
+ return true
410
+ }
411
+ return false
412
+ }
413
+ }
414
+
415
+ /**
416
+ * Mirrors the host's old PermissionsUtils.isBluetoothEnabled exactly: poll
417
+ * BleManager for up to 500ms while the adapter reports "unknown"; assume
418
+ * enabled on a timeout (a slow adapter must not block the sync) and disabled
419
+ * on a check error.
420
+ */
421
+ private async isBluetoothAdapterEnabled(): Promise<boolean> {
422
+ try {
423
+ await BleManager.start({showAlert: false})
424
+ for (let attempt = 0; attempt < 10; attempt++) {
425
+ const state = await BleManager.checkState()
426
+ if (state !== "unknown") {
427
+ return state === "on"
428
+ }
429
+ await new Promise((resolve) => setTimeout(resolve, 50))
430
+ }
431
+ console.warn("[GallerySyncService] Bluetooth state still unknown after 500ms - assuming enabled")
432
+ return true
433
+ } catch (error) {
434
+ console.error("[GallerySyncService] Error checking Bluetooth state:", error)
435
+ return false
436
+ }
437
+ }
438
+
439
+ private shouldAbortPreFlight(): boolean {
440
+ if (this.startAborted) {
441
+ this.startAborted = false
442
+ return true
443
+ }
444
+ if (!isGlassesConnected(useGlassesStore.getState().connection)) {
445
+ return true
446
+ }
447
+ return false
448
+ }
449
+
450
+ private async runStartSync(): Promise<void> {
451
+ // Clear stale abort flag — it can persist when a prior pre-flight exited through
452
+ // a non-shouldAbortPreFlight path (e.g. connectivity failed, disk full), which
453
+ // would otherwise cause the next sync attempt to abort spuriously.
454
+ this.startAborted = false
455
+
456
+ console.log("[GallerySyncService] ========================================")
457
+ console.log("[GallerySyncService] 🚀 SYNC START INITIATED")
458
+ console.log("[GallerySyncService] ========================================")
459
+
460
+ const store = useGallerySyncStore.getState()
461
+ const glassesStore = useGlassesStore.getState()
462
+ const glassesConnected = isGlassesConnected(glassesStore.connection)
463
+ const glassesHotspot =
464
+ glassesStore.hotspot.state === "enabled"
465
+ ? {
466
+ ssid: glassesStore.hotspot.ssid,
467
+ password: glassesStore.hotspot.password,
468
+ ip: glassesStore.hotspot.localIp,
469
+ }
470
+ : null
471
+
472
+ // R1: Check if already syncing (including requesting_hotspot to prevent double-tap)
473
+ if (
474
+ store.syncState === "syncing" ||
475
+ store.syncState === "connecting_wifi" ||
476
+ store.syncState === "requesting_hotspot"
477
+ ) {
478
+ console.log(`[GallerySyncService] ⚠️ Already syncing (state: ${store.syncState}), ignoring start request`)
479
+ return
480
+ }
481
+
482
+ // Engine-owned pre-flight: glasses reachable + bluetooth adapter on. The host
483
+ // renders the alerts off the structured notices; Android location permission
484
+ // and services are handled in the permission steps below.
485
+ if (!glassesConnected) {
486
+ console.warn("[GallerySyncService] Sync aborted - Glasses not connected")
487
+ store.setSyncError("Glasses not connected")
488
+ emitGalleryNotice({code: "glasses_disconnected"})
489
+ return
490
+ }
491
+
492
+ if (!(await this.isBluetoothAdapterEnabled())) {
493
+ console.warn("[GallerySyncService] Sync aborted - Bluetooth is disabled")
494
+ store.setSyncError("Bluetooth disabled - enable Bluetooth and try again")
495
+ emitGalleryNotice({code: "bluetooth_off"})
496
+ return
497
+ }
498
+
499
+ console.log("[GallerySyncService] ✅ Pre-flight check passed - BT enabled, Glasses connected")
500
+ console.log("[GallerySyncService] 📊 Glasses info:", {
501
+ connected: glassesConnected,
502
+ hotspotEnabled: glassesHotspot !== null,
503
+ })
504
+
505
+ // Request all permissions upfront so user isn't interrupted during WiFi/download
506
+ console.log("[GallerySyncService] 🔐 Step 1/6: Requesting permissions...")
507
+
508
+ // 1. Notification permission (for background sync progress)
509
+ console.log("[GallerySyncService] 📱 Requesting notification permission...")
510
+ await gallerySyncNotifications.requestPermissions()
511
+ if (this.shouldAbortPreFlight()) {
512
+ console.log("[GallerySyncService] Pre-flight aborted after notification permission")
513
+ return
514
+ }
515
+ console.log("[GallerySyncService] ✅ Notification permission handled")
516
+
517
+ // 2. Location permission (required to read WiFi SSID for hotspot verification)
518
+ console.log("[GallerySyncService] 📍 Checking location permission...")
519
+ const hasLocationPermission = await permissions.check(PermissionFeatures.LOCATION)
520
+ if (!hasLocationPermission) {
521
+ console.log("[GallerySyncService] ⚠️ Location permission not granted - requesting...")
522
+ const granted = await permissions.request(PermissionFeatures.LOCATION)
523
+ if (!granted) {
524
+ console.warn("[GallerySyncService] ❌ Location permission denied - WiFi SSID verification may fail")
525
+ // Don't block sync - we'll try anyway and fall back to IP-based verification if needed
526
+ } else {
527
+ console.log("[GallerySyncService] ✅ Location permission granted")
528
+ }
529
+ } else {
530
+ console.log("[GallerySyncService] ✅ Location permission already granted")
531
+ }
532
+ if (this.shouldAbortPreFlight()) {
533
+ console.log("[GallerySyncService] Pre-flight aborted after location permission")
534
+ return
535
+ }
536
+
537
+ if (Platform.OS === "android") {
538
+ console.log("[GallerySyncService] 📡 Checking local WiFi permission...")
539
+ const hasLocalWifiPermission = await permissions.check(PermissionFeatures.LOCAL_WIFI)
540
+ if (!hasLocalWifiPermission) {
541
+ const granted = await permissions.request(PermissionFeatures.LOCAL_WIFI)
542
+ if (!granted) {
543
+ store.setSyncError("Local WiFi permission is required for gallery sync")
544
+ await gallerySyncNotifications.showSyncError("Allow WiFi access to connect to your glasses")
545
+ return
546
+ }
547
+ }
548
+ if (this.shouldAbortPreFlight()) {
549
+ console.log("[GallerySyncService] Pre-flight aborted after local WiFi permission")
550
+ return
551
+ }
552
+ }
553
+
554
+ // 3. Camera roll permission (if auto-save is enabled)
555
+ const shouldAutoSave = await gallerySettingsService.getAutoSaveToCameraRoll()
556
+ console.log(`[GallerySyncService] 📸 Auto-save to camera roll: ${shouldAutoSave}`)
557
+ if (shouldAutoSave) {
558
+ console.log("[GallerySyncService] 📸 Checking camera roll permission...")
559
+ const hasPermission = await MediaLibraryPermissions.checkPermission()
560
+ if (!hasPermission) {
561
+ console.log("[GallerySyncService] ⚠️ Camera roll permission not granted - requesting...")
562
+ const granted = await MediaLibraryPermissions.requestPermission()
563
+ if (!granted) {
564
+ console.warn("[GallerySyncService] ❌ Camera roll permission denied - auto-save sync cannot continue")
565
+ store.setSyncError("Camera-roll permission required while automatic saving is enabled")
566
+ emitGalleryNotice({code: "camera_roll_permission_required"})
567
+ return
568
+ } else {
569
+ console.log("[GallerySyncService] ✅ Camera roll permission granted")
570
+ }
571
+ } else {
572
+ console.log("[GallerySyncService] ✅ Camera roll permission already granted")
573
+ }
574
+ }
575
+ if (this.shouldAbortPreFlight()) {
576
+ console.log("[GallerySyncService] Pre-flight aborted after camera roll permission")
577
+ return
578
+ }
579
+
580
+ // S1: Disk space check — abort early if insufficient space
581
+ try {
582
+ const fsInfo = await RNFS.getFSInfo()
583
+ const freeSpaceMB = fsInfo.freeSpace / (1024 * 1024)
584
+ console.log(`[GallerySyncService] 💾 Free disk space: ${freeSpaceMB.toFixed(0)} MB`)
585
+ if (fsInfo.freeSpace < 500 * 1024 * 1024) {
586
+ console.error("[GallerySyncService] ❌ Insufficient disk space (<500MB)")
587
+ emitGalleryNotice({code: "insufficient_storage", data: {freeSpaceMB: Math.round(freeSpaceMB)}})
588
+ store.setSyncError("Insufficient storage space")
589
+ return
590
+ }
591
+ } catch (fsError) {
592
+ console.warn("[GallerySyncService] ⚠️ Could not check disk space:", fsError)
593
+ // Continue — don't block sync if check fails
594
+ }
595
+ if (this.shouldAbortPreFlight()) {
596
+ console.log("[GallerySyncService] Pre-flight aborted after disk space check")
597
+ return
598
+ }
599
+
600
+ // Reset abort controller
601
+ this.abortController = new AbortController()
602
+
603
+ // COOLDOWN CHECK: If user just went to WiFi settings, show a "please wait" message
604
+ // This prevents showing "enable WiFi" alert repeatedly while WiFi is initializing
605
+ if (Platform.OS === "android" && this.wifiSettingsOpenedAt) {
606
+ const timeSinceSettingsOpened = Date.now() - this.wifiSettingsOpenedAt
607
+ const cooldownRemaining = TIMING.WIFI_COOLDOWN_MS - timeSinceSettingsOpened
608
+
609
+ if (cooldownRemaining > 0) {
610
+ console.log(
611
+ `[GallerySyncService] WiFi cooldown active (${Math.round(
612
+ cooldownRemaining / 1000,
613
+ )}s remaining) - showing wait message`,
614
+ )
615
+
616
+ emitGalleryNotice({code: "wifi_initializing"})
617
+ return
618
+ } else {
619
+ // Cooldown expired, clear the timestamp
620
+ console.log("[GallerySyncService] WiFi cooldown expired - resuming normal behavior")
621
+ this.wifiSettingsOpenedAt = null
622
+ }
623
+ }
624
+
625
+ // Pre-flight WiFi check on Android BEFORE any connection attempts
626
+ // This prevents sync failures even when we think we're already connected
627
+ // NOTE: We use WifiManager.isEnabled() instead of NetInfo.isWifiEnabled because
628
+ // NetInfo can return stale/cached data that reports WiFi as enabled when it's actually OFF
629
+ console.log("[GallerySyncService] 📡 Step 2/6: WiFi pre-flight check...")
630
+ if (Platform.OS === "android") {
631
+ try {
632
+ // Use WifiManager.isEnabled() for accurate WiFi state (NetInfo can be stale)
633
+ const wifiEnabled = await WifiManager.isEnabled()
634
+ console.log("[GallerySyncService] 📡 WiFi enabled (WifiManager):", wifiEnabled)
635
+
636
+ // Also log NetInfo for debugging comparison
637
+ const netState = await NetInfo.fetch()
638
+ console.log("[GallerySyncService] 📡 WiFi enabled (NetInfo):", netState.isWifiEnabled)
639
+ console.log("[GallerySyncService] 📡 Connected:", netState.isConnected)
640
+ console.log("[GallerySyncService] 📡 Internet reachable:", netState.isInternetReachable)
641
+
642
+ if (!wifiEnabled) {
643
+ console.error("[GallerySyncService] ❌ WiFi is disabled - cannot sync")
644
+
645
+ // Don't arm the auto-retry / "WiFi initializing" cooldown yet — whether to arm
646
+ // them depends on the user's choice in the host's prompt, which only the host
647
+ // learns. The host renders an "enable WiFi → open settings" alert from this
648
+ // notice and calls ack() ONLY when the user opts to open settings; on Cancel it
649
+ // does nothing, so a declined prompt leaves no pending retry or phantom cooldown.
650
+ // The engine still owns what arming MEANS (this closure) — the host only reports
651
+ // that the user took the affirmative action.
652
+ emitGalleryNotice({
653
+ code: "wifi_off",
654
+ ack: () => {
655
+ this.waitingForWifiRetry = true
656
+ this.wifiSettingsOpenedAt = Date.now()
657
+ },
658
+ })
659
+ store.setSyncError("WiFi disabled - enable WiFi and try again")
660
+
661
+ // Return early - do NOT proceed with sync
662
+ return
663
+ } else {
664
+ // WiFi is enabled - clear any cooldown timestamp
665
+ console.log("[GallerySyncService] ✅ WiFi is enabled - proceeding")
666
+ this.wifiSettingsOpenedAt = null
667
+ }
668
+ } catch (error) {
669
+ console.warn("[GallerySyncService] ⚠️ Failed to check WiFi status:", error)
670
+ // Continue with sync attempt - don't block if check fails
671
+ }
672
+ if (this.shouldAbortPreFlight()) {
673
+ console.log("[GallerySyncService] Pre-flight aborted after WiFi check")
674
+ return
675
+ }
676
+ } else {
677
+ console.log("[GallerySyncService] ℹ️ iOS - WiFi check not required")
678
+ }
679
+
680
+ // Check if Location Services is enabled (Android only - required for WiFi operations)
681
+ // This must be checked BEFORE attempting any WiFi connection to avoid cryptic errors
682
+ if (Platform.OS === "android") {
683
+ console.log("[GallerySyncService] 📍 Checking Location Services status...")
684
+ try {
685
+ const locationServicesEnabled = await this.isLocationServicesEnabled()
686
+ console.log("[GallerySyncService] 📍 Location Services enabled:", locationServicesEnabled)
687
+
688
+ if (!locationServicesEnabled) {
689
+ console.error("[GallerySyncService] ❌ Location Services is OFF - cannot sync")
690
+ console.error("[GallerySyncService] ❌ Android requires Location Services for WiFi operations")
691
+
692
+ // Emit a notice; the host shows the "enable Location Services" alert + dialog.
693
+ emitGalleryNotice({code: "location_services_off"})
694
+ store.setSyncError("Location Services disabled - enable in Settings and try again")
695
+
696
+ // Return early - do NOT proceed with sync
697
+ return
698
+ } else {
699
+ console.log("[GallerySyncService] ✅ Location Services is enabled - proceeding")
700
+ }
701
+ } catch (error) {
702
+ console.warn("[GallerySyncService] ⚠️ Failed to check Location Services status:", error)
703
+ // Continue with sync attempt - don't block if check fails
704
+ }
705
+ if (this.shouldAbortPreFlight()) {
706
+ console.log("[GallerySyncService] Pre-flight aborted after location services check")
707
+ return
708
+ }
709
+ }
710
+
711
+ // Check if already connected to hotspot
712
+ // IMPORTANT: We must verify the phone's WiFi is actually connected to the hotspot SSID,
713
+ // not just that the glasses reported hotspot is enabled (which persists across app restarts)
714
+ console.log("[GallerySyncService] 🔌 Step 3/6: Checking hotspot connection status...")
715
+
716
+ // Re-read current glasses state from the store — the snapshot from the top of the function
717
+ // may be stale if glasses disconnected during one of the above awaits.
718
+ const currentGlassesConnected = isGlassesConnected(useGlassesStore.getState().connection)
719
+ if (!currentGlassesConnected) {
720
+ console.log("[GallerySyncService] Pre-flight aborted — glasses no longer connected at hotspot check")
721
+ return
722
+ }
723
+ const currentGlassesStore = useGlassesStore.getState()
724
+ const currentGlassesHotspot =
725
+ currentGlassesStore.hotspot.state === "enabled"
726
+ ? {
727
+ ssid: currentGlassesStore.hotspot.ssid,
728
+ password: currentGlassesStore.hotspot.password,
729
+ ip: currentGlassesStore.hotspot.localIp,
730
+ }
731
+ : null
732
+
733
+ let isAlreadyConnected = false
734
+ if (currentGlassesHotspot) {
735
+ console.log("[GallerySyncService] 📊 Glasses hotspot status:")
736
+ console.log("[GallerySyncService] - Enabled: true")
737
+ console.log(`[GallerySyncService] - SSID: ${currentGlassesHotspot.ssid}`)
738
+ console.log(`[GallerySyncService] - IP: ${currentGlassesHotspot.ip}`)
739
+
740
+ try {
741
+ const currentSSID = await WifiManager.getCurrentWifiSSID()
742
+ if (this.shouldAbortPreFlight()) {
743
+ console.log("[GallerySyncService] Pre-flight aborted after SSID check")
744
+ return
745
+ }
746
+ console.log(`[GallerySyncService] 📱 Phone current WiFi SSID: "${currentSSID}"`)
747
+ console.log(`[GallerySyncService] 🔍 Comparing with glasses hotspot SSID: "${currentGlassesHotspot.ssid}"`)
748
+
749
+ isAlreadyConnected = currentSSID === currentGlassesHotspot.ssid
750
+ if (isAlreadyConnected) {
751
+ console.log("[GallerySyncService] ✅ Phone is already connected to glasses hotspot!")
752
+ } else if (currentSSID) {
753
+ console.log(`[GallerySyncService] ⚠️ Phone is on different network (${currentSSID})`)
754
+ console.log("[GallerySyncService] ➡️ Will request hotspot connection")
755
+ } else {
756
+ console.log("[GallerySyncService] ⚠️ Phone not connected to any WiFi network")
757
+ }
758
+ } catch (error) {
759
+ console.warn("[GallerySyncService] ⚠️ Could not verify current WiFi SSID:", error)
760
+ // If we can't verify, don't assume we're connected - request hotspot
761
+ isAlreadyConnected = false
762
+ }
763
+ } else {
764
+ console.log("[GallerySyncService] ℹ️ Glasses hotspot not currently enabled")
765
+ console.log("[GallerySyncService] ➡️ Will request hotspot activation")
766
+ }
767
+
768
+ // Every fallible pre-flight gate has passed. It is now safe to replace the previous
769
+ // in-memory queue; startFileDownload immediately recovers its durable ledger work.
770
+ mediaProcessingQueue.reset()
771
+
772
+ if (isAlreadyConnected && currentGlassesHotspot) {
773
+ const hotspotInfo: HotspotInfo = currentGlassesHotspot
774
+ store.setHotspotInfo(hotspotInfo)
775
+ store.setSyncState("connecting_wifi")
776
+ if (localNetworkTransport.supportsScopedConnection() && !localNetworkTransport.isScopedConnectionActive()) {
777
+ console.log("[GallerySyncService] 📡 System SSID matches; establishing scoped glasses transport")
778
+ await this.connectToHotspotWifi(hotspotInfo)
779
+ } else {
780
+ console.log("[GallerySyncService] 🚀 Skipping hotspot request - already connected!")
781
+ await this.startFileDownload(hotspotInfo)
782
+ }
783
+ return
784
+ }
785
+
786
+ // Request hotspot
787
+ console.log("[GallerySyncService] 📡 Step 4/6: Requesting hotspot from glasses...")
788
+ store.setRequestingHotspot()
789
+ store.setSyncServiceOpenedHotspot(true)
790
+
791
+ // Set timeout for hotspot request - if we don't get a response, fail gracefully
792
+ this.hotspotRequestTimeout = BgTimer.setTimeout(() => {
793
+ const currentStore = useGallerySyncStore.getState()
794
+ if (currentStore.syncState === "requesting_hotspot") {
795
+ console.error("[GallerySyncService] Hotspot request timed out")
796
+ currentStore.setSyncError("Hotspot request timed out")
797
+ currentStore.setSyncServiceOpenedHotspot(false)
798
+ gallerySyncNotifications.showSyncError("Could not start hotspot - please try again")
799
+ }
800
+ this.hotspotRequestTimeout = null
801
+ }, TIMING.HOTSPOT_REQUEST_TIMEOUT_MS)
802
+
803
+ try {
804
+ console.log("[GallerySyncService] 📤 Sending hotspot enable command to glasses...")
805
+ await BluetoothSdk.setHotspotState(true)
806
+ console.log("[GallerySyncService] ✅ Hotspot enabled by glasses")
807
+ } catch (error) {
808
+ // Clear the timeout since we got an immediate error
809
+ if (this.hotspotRequestTimeout) {
810
+ BgTimer.clearTimeout(this.hotspotRequestTimeout!)
811
+ this.hotspotRequestTimeout = null
812
+ }
813
+ console.error("[GallerySyncService] ❌ Failed to request hotspot:", error)
814
+ store.setSyncError("Failed to start hotspot")
815
+ store.setSyncServiceOpenedHotspot(false)
816
+ }
817
+ }
818
+
819
+ /**
820
+ * Show explanation dialog before WiFi connection (first time only)
821
+ * Returns true if user wants to proceed, false if cancelled
822
+ */
823
+ private async showWifiJoinExplanation(ssid: string): Promise<boolean> {
824
+ const settingsStore = useSettingsStore.getState()
825
+ const hasSeenExplanation = settingsStore.getSetting(SETTINGS.gallery_sync_explained.key)
826
+
827
+ if (hasSeenExplanation) {
828
+ console.log("[GallerySyncService] User has seen WiFi explanation before - skipping")
829
+ return true
830
+ }
831
+
832
+ console.log("[GallerySyncService] First sync - showing WiFi join explanation")
833
+
834
+ return new Promise<boolean>((resolve) => {
835
+ const proceed = () => {
836
+ // Mark as explained so we don't show again.
837
+ settingsStore.setSetting(SETTINGS.gallery_sync_explained.key, true, false)
838
+ resolve(true)
839
+ }
840
+ // Emit the one-time wifi-join explanation as a notice the host renders + acknowledges.
841
+ // The host owns the alert + its dismiss timing (Android's native WiFi connect freezes
842
+ // the UI thread, so it should let the dialog fully dismiss before calling ack).
843
+ const delivered = emitGalleryNotice({
844
+ code: "connect_to_glasses",
845
+ data: {ssid, platform: Platform.OS},
846
+ ack: proceed,
847
+ })
848
+ // No host listening (e.g. an OEM that hasn't wired onNotice) — don't hang the sync.
849
+ if (delivered === 0) proceed()
850
+ })
851
+ }
852
+
853
+ /**
854
+ * Connect to hotspot WiFi with retry logic (unified for both platforms)
855
+ * Both iOS and Android benefit from retries:
856
+ * - iOS: Library throws "internal error" before user responds to system dialog
857
+ * - Android: Hotspot needs time to initialize, especially when glasses WiFi was cold
858
+ */
859
+ private async connectToHotspotWifi(hotspotInfo: HotspotInfo): Promise<void> {
860
+ const store = useGallerySyncStore.getState()
861
+
862
+ // Pre-flight: do not attempt WiFi connection if Bluetooth already disconnected
863
+ if (!isGlassesConnected(useGlassesStore.getState().connection)) {
864
+ console.log("[GallerySyncService] ❌ Glasses not connected - aborting WiFi connection")
865
+ store.setSyncError("Glasses disconnected")
866
+ gallerySyncNotifications.showSyncError("Glasses disconnected")
867
+ return
868
+ }
869
+
870
+ // Show explanation dialog on first sync (user must acknowledge before proceeding)
871
+ await this.showWifiJoinExplanation(hotspotInfo.ssid)
872
+
873
+ let lastError: any = null
874
+ const wifiConnectStartTime = Date.now()
875
+
876
+ console.log("[GallerySyncService] ========================================")
877
+ console.log("[GallerySyncService] 📡 WIFI CONNECTION PHASE")
878
+ console.log("[GallerySyncService] ========================================")
879
+ console.log(`[GallerySyncService] 🎯 Target SSID: ${hotspotInfo.ssid}`)
880
+ console.log(`[GallerySyncService] 🔑 Password length: ${hotspotInfo.password.length} chars`)
881
+ console.log(`[GallerySyncService] 🌐 Gateway IP: ${hotspotInfo.ip}`)
882
+ console.log(`[GallerySyncService] 📱 Platform: ${Platform.OS}`)
883
+ console.log(`[GallerySyncService] 🔄 Max retry attempts: ${TIMING.IOS_WIFI_MAX_RETRIES}`)
884
+ console.log(`[GallerySyncService] ⏱️ Retry delay: ${TIMING.IOS_WIFI_RETRY_DELAY_MS}ms`)
885
+
886
+ store.setSyncState("connecting_wifi")
887
+
888
+ // Setup app state monitoring to detect backgrounding
889
+ let appBackgrounded = false
890
+ let appBackgroundTime: number | null = null
891
+ const appStateHandler = (nextAppState: AppStateStatus) => {
892
+ if (nextAppState === "background") {
893
+ appBackgrounded = true
894
+ appBackgroundTime = Date.now()
895
+ console.warn("[GallerySyncService] ⚠️ 🚨 APP BACKGROUNDED during WiFi connection!")
896
+ console.warn("[GallerySyncService] ⚠️ This may indicate Android system dialog appeared")
897
+ console.warn(
898
+ "[GallerySyncService] ⚠️ Time since WiFi connect started:",
899
+ Date.now() - wifiConnectStartTime,
900
+ "ms",
901
+ )
902
+ } else if (nextAppState === "active" && appBackgrounded) {
903
+ console.log("[GallerySyncService] ✅ App returned to foreground")
904
+ console.log("[GallerySyncService] ⏱️ Time spent in background:", Date.now() - (appBackgroundTime || 0), "ms")
905
+ }
906
+ }
907
+
908
+ const appStateSubscription = AppState.addEventListener("change", appStateHandler)
909
+ console.log("[GallerySyncService] 👂 App state listener registered")
910
+
911
+ // L2: Wrap retry loop in try/finally to guarantee listener cleanup on all exit paths
912
+ try {
913
+ for (let attempt = 1; attempt <= TIMING.IOS_WIFI_MAX_RETRIES; attempt++) {
914
+ const attemptStartTime = Date.now()
915
+
916
+ // Check if cancelled
917
+ if (this.abortController?.signal.aborted) {
918
+ console.log("[GallerySyncService] 🛑 Sync was cancelled - aborting WiFi connection")
919
+ store.setSyncError("Sync cancelled")
920
+ return
921
+ }
922
+
923
+ try {
924
+ console.log("[GallerySyncService] ----------------------------------------")
925
+ console.log(
926
+ `[GallerySyncService] 📡 ATTEMPT ${attempt}/${TIMING.IOS_WIFI_MAX_RETRIES} - Starting WiFi connection`,
927
+ )
928
+ console.log(`[GallerySyncService] ⏱️ Time since WiFi phase started: ${Date.now() - wifiConnectStartTime}ms`)
929
+ console.log(`[GallerySyncService] 📱 App backgrounded during connection: ${appBackgrounded}`)
930
+
931
+ // Check current WiFi state before attempting connection
932
+ let preConnectSSID = "unknown"
933
+ try {
934
+ preConnectSSID = await WifiManager.getCurrentWifiSSID()
935
+ console.log(`[GallerySyncService] 📡 Current WiFi SSID: "${preConnectSSID}"`)
936
+
937
+ // Check if already connected (shouldn't happen, but good to verify)
938
+ if (!localNetworkTransport.supportsScopedConnection() && preConnectSSID === hotspotInfo.ssid) {
939
+ console.log("[GallerySyncService] ✅ Already connected to target SSID! Proceeding to download.")
940
+ appStateSubscription.remove()
941
+
942
+ const totalWifiDuration = Date.now() - wifiConnectStartTime
943
+ console.log("[GallerySyncService] ========================================")
944
+ console.log("[GallerySyncService] ✅ WIFI CONNECTION COMPLETE (already connected)")
945
+ console.log("[GallerySyncService] ========================================")
946
+ console.log(`[GallerySyncService] ⏱️ Total WiFi phase duration: ${totalWifiDuration}ms`)
947
+ console.log(`[GallerySyncService] 🚀 Proceeding to file download from ${hotspotInfo.ip}:8089`)
948
+
949
+ await this.startFileDownload(hotspotInfo)
950
+ return // Exit function successfully
951
+ }
952
+ } catch (preError: any) {
953
+ console.warn(`[GallerySyncService] ⚠️ Could not get current SSID: ${preError?.message}`)
954
+ console.warn("[GallerySyncService] ⚠️ Error code:", preError?.code)
955
+ }
956
+
957
+ console.log(`[GallerySyncService] 🔌 Connecting the glasses-local transport...`)
958
+ console.log(`[GallerySyncService] 🔌 Parameters:`)
959
+ console.log(`[GallerySyncService] - SSID: "${hotspotInfo.ssid}"`)
960
+ console.log(`[GallerySyncService] - Password: ${"*".repeat(hotspotInfo.password.length)}`)
961
+ console.log(`[GallerySyncService] - joinOnce: false`)
962
+ console.log(`[GallerySyncService] - isHidden: false`)
963
+
964
+ const connectCallStartTime = Date.now()
965
+ appBackgrounded = false // Reset flag for this attempt
966
+ appBackgroundTime = null
967
+
968
+ await localNetworkTransport.connect(hotspotInfo.ssid, hotspotInfo.password)
969
+
970
+ const connectCallDuration = Date.now() - connectCallStartTime
971
+ console.log(`[GallerySyncService] ✅ Glasses-local transport connected successfully`)
972
+ console.log(`[GallerySyncService] ⏱️ Library call duration: ${connectCallDuration}ms`)
973
+ console.log(`[GallerySyncService] 📱 App was backgrounded during call: ${appBackgrounded}`)
974
+ if (appBackgrounded && appBackgroundTime) {
975
+ console.log(
976
+ `[GallerySyncService] ⏱️ Time until backgrounding: ${appBackgroundTime - connectCallStartTime}ms`,
977
+ )
978
+ }
979
+ console.log(`[GallerySyncService] 📝 Note: On iOS, this does NOT guarantee actual connection!`)
980
+
981
+ // iOS-specific: Verify actual WiFi connection by polling SSID
982
+ // The library promise resolves when iOS ACCEPTS the request, not when connection completes
983
+ if (Platform.OS === "ios") {
984
+ console.log(`[GallerySyncService] 🍎 iOS: Starting connection verification...`)
985
+ console.log(`[GallerySyncService] 🍎 Will poll getCurrentWifiSSID() for up to 15 seconds`)
986
+
987
+ const maxVerifyAttempts = 30 // 30 × 500ms = 15 seconds
988
+ let connected = false
989
+ let lastSeenSSID = "unknown"
990
+
991
+ for (let i = 0; i < maxVerifyAttempts; i++) {
992
+ try {
993
+ const currentSSID = await WifiManager.getCurrentWifiSSID()
994
+ lastSeenSSID = currentSSID || "null"
995
+
996
+ console.log(
997
+ `[GallerySyncService] 🍎 Verify poll ${
998
+ i + 1
999
+ }/${maxVerifyAttempts}: Current="${currentSSID}", Target="${hotspotInfo.ssid}"`,
1000
+ )
1001
+
1002
+ if (currentSSID === hotspotInfo.ssid) {
1003
+ console.log(
1004
+ `[GallerySyncService] 🍎 ✅ VERIFICATION SUCCESS! Connected to target network after ${
1005
+ (i + 1) * 500
1006
+ }ms`,
1007
+ )
1008
+ connected = true
1009
+ break
1010
+ } else if (i === 0 && currentSSID === lastSeenSSID) {
1011
+ console.log(
1012
+ `[GallerySyncService] 🍎 ⚠️ Still on original network - iOS dialog may not have appeared yet`,
1013
+ )
1014
+ }
1015
+ } catch (ssidError: any) {
1016
+ console.log(`[GallerySyncService] 🍎 ⚠️ Poll ${i + 1}: Could not check SSID: ${ssidError?.message}`)
1017
+ lastSeenSSID = "error"
1018
+ }
1019
+
1020
+ // Don't wait after last attempt
1021
+ if (i < maxVerifyAttempts - 1) {
1022
+ await new Promise<void>((resolve) => BgTimer.setTimeout(() => resolve(), 500))
1023
+ }
1024
+ }
1025
+
1026
+ if (!connected) {
1027
+ console.error(`[GallerySyncService] 🍎 ❌ VERIFICATION FAILED after 15 seconds`)
1028
+ console.error(`[GallerySyncService] 🍎 Last seen SSID: "${lastSeenSSID}"`)
1029
+ console.error(`[GallerySyncService] 🍎 Expected SSID: "${hotspotInfo.ssid}"`)
1030
+ console.error(`[GallerySyncService] 🍎 Possible causes:`)
1031
+ console.error(`[GallerySyncService] 🍎 1. User did not tap "Join" on iOS WiFi dialog`)
1032
+ console.error(`[GallerySyncService] 🍎 2. iOS dialog did not appear (permission issue?)`)
1033
+ console.error(`[GallerySyncService] 🍎 3. iOS refused to switch networks`)
1034
+ throw new Error(
1035
+ `iOS WiFi verification failed - still on "${lastSeenSSID}", expected "${hotspotInfo.ssid}"`,
1036
+ )
1037
+ }
1038
+ }
1039
+
1040
+ const attemptDuration = Date.now() - attemptStartTime
1041
+ console.log(`[GallerySyncService] ✅ WiFi connection successful!`)
1042
+ console.log(`[GallerySyncService] ⏱️ Total attempt duration: ${attemptDuration}ms`)
1043
+ console.log(`[GallerySyncService] 🎉 Platform: ${Platform.OS}`)
1044
+
1045
+ // Remove app state listener
1046
+ appStateSubscription.remove()
1047
+ console.log("[GallerySyncService] 👂 App state listener removed")
1048
+
1049
+ // Final verification: Check SSID one more time before starting download
1050
+ try {
1051
+ const finalSSID = localNetworkTransport.isScopedConnectionActive()
1052
+ ? hotspotInfo.ssid
1053
+ : await WifiManager.getCurrentWifiSSID()
1054
+ console.log(`[GallerySyncService] 📶 Final SSID check before download: "${finalSSID}"`)
1055
+ if (Platform.OS === "android") {
1056
+ // Some local builds can have stale generated typings for the Bluetooth SDK module.
1057
+ ;(BluetoothSdk as any).logCurrentWifiFrequency?.()
1058
+ }
1059
+ if (finalSSID !== hotspotInfo.ssid) {
1060
+ console.error(
1061
+ `[GallerySyncService] ❌ SSID mismatch detected! Expected "${hotspotInfo.ssid}", got "${finalSSID}"`,
1062
+ )
1063
+ throw new Error(`WiFi SSID mismatch - connected to "${finalSSID}" instead of "${hotspotInfo.ssid}"`)
1064
+ }
1065
+ } catch (finalError: any) {
1066
+ console.warn(`[GallerySyncService] ⚠️ Could not perform final SSID check: ${finalError?.message}`)
1067
+ // Continue anyway - we've done our best to verify
1068
+ }
1069
+
1070
+ // iOS-specific: Wait for actual network connectivity to glasses
1071
+ // Even though SSID is correct, iOS needs time for routing tables to update
1072
+ // We actively probe the glasses HTTP server until it's reachable
1073
+ if (Platform.OS === "ios") {
1074
+ console.log(`[GallerySyncService] 🍎 Waiting for iOS network routes to glasses IP...`)
1075
+ console.log(`[GallerySyncService] 🍎 Will probe http://${hotspotInfo.ip}:8089/api/health`)
1076
+
1077
+ const maxProbeAttempts = 20 // 20 attempts × 500ms = 10 seconds max
1078
+ let networkReady = false
1079
+
1080
+ for (let probeNum = 1; probeNum <= maxProbeAttempts; probeNum++) {
1081
+ try {
1082
+ console.log(`[GallerySyncService] 🍎 Connectivity probe ${probeNum}/${maxProbeAttempts}...`)
1083
+
1084
+ // Try to reach the glasses health endpoint with a short timeout
1085
+ const probeController = new AbortController()
1086
+ const probeTimeout = BgTimer.setTimeout(() => probeController.abort(), 1000) // 1 second timeout per probe
1087
+
1088
+ const probeStartTime = Date.now()
1089
+ const probeResponse = await localNetworkTransport.fetch(`http://${hotspotInfo.ip}:8089/api/health`, {
1090
+ method: "GET",
1091
+ signal: probeController.signal,
1092
+ })
1093
+ BgTimer.clearTimeout(probeTimeout)
1094
+
1095
+ const probeDuration = Date.now() - probeStartTime
1096
+ console.log(
1097
+ `[GallerySyncService] 🍎 Probe ${probeNum} response: HTTP ${probeResponse.status} (${probeDuration}ms)`,
1098
+ )
1099
+
1100
+ if (probeResponse.status === 200 || probeResponse.status === 404) {
1101
+ // 200 = health endpoint exists, 404 = glasses responded (no health endpoint)
1102
+ // Either way, network is working!
1103
+ console.log(`[GallerySyncService] 🍎 ✅ Network connectivity verified after ${probeNum} probes!`)
1104
+ networkReady = true
1105
+ break
1106
+ }
1107
+ } catch (probeError: any) {
1108
+ const errorMsg = probeError?.message || "unknown"
1109
+ console.log(
1110
+ `[GallerySyncService] 🍎 Probe ${probeNum} failed: ${errorMsg.substring(0, 50)}${
1111
+ errorMsg.length > 50 ? "..." : ""
1112
+ }`,
1113
+ )
1114
+ // Continue to next probe
1115
+ }
1116
+
1117
+ // Wait 500ms before next probe (unless this was the last attempt)
1118
+ if (probeNum < maxProbeAttempts) {
1119
+ await new Promise<void>((resolve) => BgTimer.setTimeout(() => resolve(), 500))
1120
+ }
1121
+ }
1122
+
1123
+ if (!networkReady) {
1124
+ console.error(
1125
+ `[GallerySyncService] 🍎 ❌ Network connectivity probe failed after ${maxProbeAttempts} attempts`,
1126
+ )
1127
+ console.error(`[GallerySyncService] 🍎 iOS routing tables may not be ready for ${hotspotInfo.ip}`)
1128
+ throw new Error(
1129
+ `iOS network not ready - could not reach ${hotspotInfo.ip}:8089 after ${maxProbeAttempts} attempts`,
1130
+ )
1131
+ }
1132
+ }
1133
+
1134
+ // Start the actual download
1135
+ const totalWifiDuration = Date.now() - wifiConnectStartTime
1136
+ console.log("[GallerySyncService] ========================================")
1137
+ console.log("[GallerySyncService] ✅ WIFI CONNECTION COMPLETE")
1138
+ console.log("[GallerySyncService] ========================================")
1139
+ console.log(`[GallerySyncService] ⏱️ Total WiFi phase duration: ${totalWifiDuration}ms`)
1140
+ console.log(`[GallerySyncService] 🎯 Attempts used: ${attempt}/${TIMING.IOS_WIFI_MAX_RETRIES}`)
1141
+ console.log(`[GallerySyncService] 🚀 Proceeding to file download from ${hotspotInfo.ip}:8089`)
1142
+
1143
+ await this.startFileDownload(hotspotInfo)
1144
+ return // Success - exit the retry loop
1145
+ } catch (error: any) {
1146
+ lastError = error
1147
+ const attemptDuration = Date.now() - attemptStartTime
1148
+
1149
+ console.error("[GallerySyncService] ❌ ========================================")
1150
+ console.error(`[GallerySyncService] ❌ WiFi ATTEMPT ${attempt} FAILED`)
1151
+ console.error("[GallerySyncService] ❌ ========================================")
1152
+ console.error(`[GallerySyncService] ❌ Error message: ${error?.message || "No message"}`)
1153
+ console.error(`[GallerySyncService] ❌ Error code: ${error?.code || "No code"}`)
1154
+ console.error(`[GallerySyncService] ❌ Error type: ${error?.name || typeof error}`)
1155
+ console.error(`[GallerySyncService] ❌ Platform: ${Platform.OS}`)
1156
+ console.error(`[GallerySyncService] ❌ Attempt duration: ${attemptDuration}ms`)
1157
+ console.error(`[GallerySyncService] ❌ App was backgrounded: ${appBackgrounded}`)
1158
+ if (appBackgrounded && appBackgroundTime) {
1159
+ console.error(`[GallerySyncService] ❌ Time in background: ${Date.now() - appBackgroundTime}ms`)
1160
+ }
1161
+ console.error(`[GallerySyncService] ❌ Full error object:`, JSON.stringify(error, null, 2))
1162
+
1163
+ // If user explicitly denied, don't retry
1164
+ if (error?.code === "userDenied" || error?.message?.includes("cancel")) {
1165
+ console.warn("[GallerySyncService] 🚫 User cancelled WiFi connection - aborting")
1166
+ appStateSubscription.remove()
1167
+ store.setSyncError("WiFi connection cancelled")
1168
+ if (store.syncServiceOpenedHotspot) {
1169
+ await this.closeHotspot()
1170
+ }
1171
+ return
1172
+ }
1173
+
1174
+ // Handle "didNotFindNetwork" - hotspot may still be initializing
1175
+ if (error?.code === "didNotFindNetwork") {
1176
+ console.warn("[GallerySyncService] 🔍 Network not found - hotspot may still be initializing")
1177
+ console.warn(
1178
+ `[GallerySyncService] 🔍 Will retry in ${TIMING.IOS_WIFI_RETRY_DELAY_MS}ms (attempt ${attempt}/${TIMING.IOS_WIFI_MAX_RETRIES})`,
1179
+ )
1180
+ }
1181
+
1182
+ // Handle "timeoutOccurred" - likely caused by app backgrounding during WiFi dialog
1183
+ if (error?.code === "timeoutOccurred") {
1184
+ console.error("[GallerySyncService] ⏰ WiFi connection timeout occurred")
1185
+ console.error(`[GallerySyncService] ⏰ App was backgrounded: ${appBackgrounded}`)
1186
+ if (appBackgrounded && appBackgroundTime) {
1187
+ console.error(`[GallerySyncService] ⏰ Time in background: ${Date.now() - appBackgroundTime}ms`)
1188
+ console.error("[GallerySyncService] ⏰ Android may have shown WiFi dialog that user didn't interact with")
1189
+ }
1190
+ console.warn(
1191
+ `[GallerySyncService] 🔍 Will retry in ${TIMING.IOS_WIFI_RETRY_DELAY_MS}ms (attempt ${attempt}/${TIMING.IOS_WIFI_MAX_RETRIES})`,
1192
+ )
1193
+ }
1194
+
1195
+ // DISABLED: Check if WiFi was disabled during connection attempt (Android 10+ specific error)
1196
+ // if (Platform.OS === "android" && error?.message?.includes("enable wifi manually")) {
1197
+ // console.error("[GallerySyncService] WiFi was disabled during connection")
1198
+ //
1199
+ // // Mark that we're waiting for WiFi so we can auto-retry when user returns
1200
+ // this.waitingForWifiRetry = true
1201
+ //
1202
+ // showAlert("WiFi Required", "WiFi must be enabled to sync photos. Please enable WiFi and try again.", [
1203
+ // {
1204
+ // text: "Cancel",
1205
+ // style: "cancel",
1206
+ // onPress: () => {
1207
+ // this.waitingForWifiRetry = false
1208
+ // this.wifiSettingsOpenedAt = null
1209
+ // store.setSyncError("WiFi disabled - enable WiFi and try again")
1210
+ // if (store.syncServiceOpenedHotspot) {
1211
+ // this.closeHotspot()
1212
+ // }
1213
+ // },
1214
+ // },
1215
+ // {
1216
+ // text: "Open Settings",
1217
+ // onPress: async () => {
1218
+ // // Set timestamp so we can enforce cooldown on next sync attempt
1219
+ // this.wifiSettingsOpenedAt = Date.now()
1220
+ // await SettingsNavigationUtils.openWifiSettings()
1221
+ // store.setSyncError("Enable WiFi and try sync again")
1222
+ // if (store.syncServiceOpenedHotspot) {
1223
+ // await this.closeHotspot()
1224
+ // }
1225
+ // },
1226
+ // },
1227
+ // ])
1228
+ // return
1229
+ // }
1230
+
1231
+ // Let connection fail naturally and show generic error
1232
+ if (Platform.OS === "android" && error?.message?.includes("enable wifi manually")) {
1233
+ console.error("[GallerySyncService] 🚫 WiFi was disabled during connection - aborting")
1234
+ appStateSubscription.remove()
1235
+ store.setSyncError("Could not connect - check WiFi is enabled")
1236
+ if (store.syncServiceOpenedHotspot) {
1237
+ await this.closeHotspot()
1238
+ }
1239
+ return
1240
+ }
1241
+
1242
+ // For "internal error" or "unableToConnect", wait and retry
1243
+ // iOS: Gives user time to interact with system dialog
1244
+ // Android: Gives hotspot time to fully initialize and start broadcasting
1245
+ if (attempt < TIMING.IOS_WIFI_MAX_RETRIES) {
1246
+ const reason =
1247
+ Platform.OS === "ios" ? "user may be seeing system dialog" : "hotspot may still be initializing"
1248
+ console.log("[GallerySyncService] ----------------------------------------")
1249
+ console.log(`[GallerySyncService] 🔄 Preparing retry ${attempt + 1}/${TIMING.IOS_WIFI_MAX_RETRIES}`)
1250
+ console.log(`[GallerySyncService] ⏱️ Waiting ${TIMING.IOS_WIFI_RETRY_DELAY_MS}ms (${reason})`)
1251
+ console.log(`[GallerySyncService] 📱 App currently: ${AppState.currentState}`)
1252
+ await new Promise<void>((resolve) => BgTimer.setTimeout(() => resolve(), TIMING.IOS_WIFI_RETRY_DELAY_MS))
1253
+ console.log(`[GallerySyncService] ⏱️ Wait complete - starting retry`)
1254
+ } else {
1255
+ console.error("[GallerySyncService] 🚫 No more retry attempts available")
1256
+ }
1257
+ }
1258
+ }
1259
+
1260
+ // All retries exhausted
1261
+ const totalWifiDuration = Date.now() - wifiConnectStartTime
1262
+
1263
+ console.error("[GallerySyncService] ❌ ========================================")
1264
+ console.error("[GallerySyncService] ❌ WIFI CONNECTION FAILED - ALL RETRIES EXHAUSTED")
1265
+ console.error("[GallerySyncService] ❌ ========================================")
1266
+ console.error(`[GallerySyncService] ❌ Platform: ${Platform.OS}`)
1267
+ console.error(`[GallerySyncService] ❌ Total attempts: ${TIMING.IOS_WIFI_MAX_RETRIES}`)
1268
+ console.error(`[GallerySyncService] ❌ Total duration: ${totalWifiDuration}ms`)
1269
+ console.error(`[GallerySyncService] ❌ App was backgrounded at some point: ${appBackgrounded}`)
1270
+ console.error(`[GallerySyncService] ❌ Last error message: ${lastError?.message || "No message"}`)
1271
+ console.error(`[GallerySyncService] ❌ Last error code: ${lastError?.code || "No code"}`)
1272
+ console.error("[GallerySyncService] ❌ ========================================")
1273
+
1274
+ // Provide user-friendly error message based on error type
1275
+ let userErrorMessage = lastError?.message || "Failed to connect to glasses WiFi"
1276
+
1277
+ if (lastError?.code === "timeoutOccurred" && appBackgrounded) {
1278
+ userErrorMessage =
1279
+ "WiFi connection timed out. Android may be blocking automatic WiFi switching. Please manually connect to the glasses hotspot in Settings."
1280
+ } else if (lastError?.message?.includes("internal error")) {
1281
+ userErrorMessage =
1282
+ "Could not connect to glasses WiFi. Please ensure you accept the WiFi prompt when it appears."
1283
+ }
1284
+
1285
+ store.setSyncError(userErrorMessage)
1286
+
1287
+ if (store.syncServiceOpenedHotspot) {
1288
+ await this.closeHotspot()
1289
+ }
1290
+ } finally {
1291
+ // Release the scoped Android Network on every terminal path. This is idempotent with
1292
+ // closeHotspot(), and intentionally leaves Android 9/iOS legacy routing unchanged.
1293
+ await localNetworkTransport.disconnect()
1294
+ // L2: Guarantee listener cleanup on all exit paths (cancel, success, error, exhaustion)
1295
+ appStateSubscription.remove()
1296
+ }
1297
+ }
1298
+
1299
+ private async fetchSyncManifest(clientId: string, lastSyncTime: number): Promise<SyncManifestData> {
1300
+ const v3 = typeof asgCameraApi.getV3Manifest === "function" ? await asgCameraApi.getV3Manifest() : null
1301
+ if (v3) {
1302
+ const downloadedFiles = await localStorageService.getDownloadedFiles()
1303
+ await localStorageService.reconcileRemoteCaptures(
1304
+ v3.captures.map((capture) => capture.capture_id),
1305
+ downloadedFiles,
1306
+ )
1307
+ return {
1308
+ api_version: 3,
1309
+ client_id: clientId,
1310
+ // The ledger is a crash-recovery journal, not proof that app-private media survived an
1311
+ // Android restore or reinstall. Suppress a remote capture only when both records agree.
1312
+ captures: v3.captures.filter(
1313
+ (capture) =>
1314
+ !downloadedFiles[capture.capture_id] || !galleryTransferLedger.isLocallyCommitted(capture.capture_id),
1315
+ ),
1316
+ changed_files: [],
1317
+ deleted_files: [],
1318
+ server_time: v3.server_time,
1319
+ total_changed: v3.captures.length,
1320
+ total_size: v3.captures.reduce((total, capture) => total + capture.total_size, 0),
1321
+ }
1322
+ }
1323
+ // Old firmware remains on the exact v2 endpoint/schema. Avoid expensive inline thumbnails;
1324
+ // the UI can request them lazily after the primary transfer is safe.
1325
+ const syncResponse = await asgCameraApi.syncWithServer(clientId, lastSyncTime, false)
1326
+ const data = (syncResponse.data || syncResponse) as SyncManifestData
1327
+ if (data.captures) {
1328
+ data.captures = data.captures.filter((capture) => !galleryTransferLedger.isLocallyCommitted(capture.capture_id))
1329
+ }
1330
+ data.changed_files = (data.changed_files || []).filter(
1331
+ (file) => !galleryTransferLedger.isFileLocallyCommitted(file.name),
1332
+ )
1333
+ return data
1334
+ }
1335
+
1336
+ /**
1337
+ * Resolve sync manifest: detect skew, optionally fix clock, retry full sync when needed.
1338
+ */
1339
+ private async resolveSyncManifest(
1340
+ clientId: string,
1341
+ lastSyncTime: number,
1342
+ ): Promise<{syncData: SyncManifestData; usedFullSync: boolean} | null> {
1343
+ const store = useGallerySyncStore.getState()
1344
+ let syncData = await this.fetchSyncManifest(clientId, lastSyncTime)
1345
+ let clockFixed = false
1346
+
1347
+ const skewOnFirst = detectClockSkew(Date.now(), syncData.server_time, lastSyncTime)
1348
+ if (skewOnFirst.skewed) {
1349
+ clockFixed = await fixGlassesClockIfSkewed(syncData.server_time, lastSyncTime)
1350
+ if (clockFixed) {
1351
+ console.log("[GallerySyncService] 🔄 Retrying /api/sync with last_sync_time=0 after clock fix")
1352
+ syncData = await this.fetchSyncManifest(clientId, 0)
1353
+ }
1354
+ }
1355
+
1356
+ if (!isSyncManifestEmpty(syncData)) {
1357
+ return {syncData, usedFullSync: clockFixed || lastSyncTime === 0}
1358
+ }
1359
+
1360
+ // Guard against re-firing the full-sync retry every sync when glasses retain leftover files
1361
+ // from a failed delete-from-glasses: at most one retry per (client_id, last_sync_time) pair
1362
+ // per process lifetime. Without this, we'd re-download the entire gallery on every sync.
1363
+ const retryKey = `${clientId}:${lastSyncTime}`
1364
+ const alreadyRetriedForThisWatermark = this.lastFullSyncRetryKey === retryKey
1365
+ if (!clockFixed && store.glassesHasContent && lastSyncTime !== 0 && !alreadyRetriedForThisWatermark) {
1366
+ this.lastFullSyncRetryKey = retryKey
1367
+ console.log("[GallerySyncService] 🔄 Empty sync but glasses report content — retrying with last_sync_time=0")
1368
+ syncData = await this.fetchSyncManifest(clientId, 0)
1369
+ if (!isSyncManifestEmpty(syncData)) {
1370
+ return {syncData, usedFullSync: true}
1371
+ }
1372
+ } else if (!clockFixed && store.glassesHasContent && lastSyncTime !== 0 && alreadyRetriedForThisWatermark) {
1373
+ console.warn(
1374
+ "[GallerySyncService] ⚠️ Glasses still report content but /api/sync empty — already retried this watermark, skipping to avoid re-download loop",
1375
+ )
1376
+ }
1377
+
1378
+ if (store.glassesHasContent) {
1379
+ console.warn("[GallerySyncService] ⚠️ Empty sync while glasses still report gallery content")
1380
+ return null
1381
+ }
1382
+
1383
+ return {syncData, usedFullSync: false}
1384
+ }
1385
+
1386
+ /**
1387
+ * Start downloading files
1388
+ */
1389
+ private async startFileDownload(hotspotInfo: HotspotInfo): Promise<void> {
1390
+ const store = useGallerySyncStore.getState()
1391
+
1392
+ console.log("[GallerySyncService] ========================================")
1393
+ console.log("[GallerySyncService] 📥 Step 5/6: Starting file download phase")
1394
+ console.log("[GallerySyncService] ========================================")
1395
+ console.log(`[GallerySyncService] 🌐 Server: ${hotspotInfo.ip}:8089`)
1396
+
1397
+ try {
1398
+ // Set up the API client
1399
+ asgCameraApi.setServer(hotspotInfo.ip, 8089)
1400
+ console.log("[GallerySyncService] ✅ API client configured")
1401
+
1402
+ const recovery = await mediaProcessingQueue.retryPending()
1403
+ if (recovery.retried > 0 || recovery.failed > 0) {
1404
+ console.log(
1405
+ `[GallerySyncService] ♻️ Recovery: ${recovery.retried} completed, ${recovery.failed} still pending`,
1406
+ )
1407
+ }
1408
+
1409
+ // Get sync state and files to download
1410
+ // IMPORTANT: This creates a SNAPSHOT of files at this moment based on last_sync_time.
1411
+ // Any photos taken AFTER this call (during the sync) will NOT be included in this sync.
1412
+ // They will be detected in the next sync when we query gallery status again.
1413
+ console.log("[GallerySyncService] 📊 Fetching sync state from local storage...")
1414
+ const syncState = await localStorageService.getSyncState()
1415
+ console.log("[GallerySyncService] 📊 Sync state:", {
1416
+ client_id: syncState.client_id,
1417
+ last_sync_time: syncState.last_sync_time,
1418
+ last_sync_date: syncState.last_sync_time > 0 ? new Date(syncState.last_sync_time).toISOString() : "Never",
1419
+ total_downloaded: syncState.total_downloaded,
1420
+ total_size: `${(syncState.total_size / 1024 / 1024).toFixed(2)} MB`,
1421
+ })
1422
+
1423
+ console.log("[GallerySyncService] 📡 Calling /api/sync endpoint...")
1424
+ const syncStartTime = Date.now()
1425
+ const resolved = await this.resolveSyncManifest(syncState.client_id, syncState.last_sync_time)
1426
+ const _syncDuration = Date.now() - syncStartTime
1427
+ console.log(`[GallerySyncService] ✅ /api/sync completed in ${_syncDuration}ms`)
1428
+
1429
+ if (!resolved) {
1430
+ const syncErrorMessage = "Could not sync gallery — try again"
1431
+ store.setSyncError(syncErrorMessage)
1432
+ await gallerySyncNotifications.showSyncError(syncErrorMessage)
1433
+ if (store.syncServiceOpenedHotspot) {
1434
+ await this.closeHotspot()
1435
+ }
1436
+ return
1437
+ }
1438
+
1439
+ const {syncData} = resolved
1440
+
1441
+ console.log("[GallerySyncService] 📋 Sync response received:")
1442
+ console.log(`[GallerySyncService] - Server time: ${syncData.server_time}`)
1443
+ console.log(`[GallerySyncService] - Changed files: ${syncData.changed_files?.length || 0}`)
1444
+ console.log(`[GallerySyncService] - Captures: ${syncData.captures?.length || 0}`)
1445
+
1446
+ if (isSyncManifestEmpty(syncData)) {
1447
+ console.log("[GallerySyncService] ✅ No new files to sync - already up to date!")
1448
+ if (galleryTransferLedger.hasPendingRecovery()) {
1449
+ store.setSyncError("Gallery export or acknowledgement needs retry")
1450
+ } else {
1451
+ store.setSyncComplete()
1452
+ }
1453
+ await this.onSyncComplete(0, 0)
1454
+ return
1455
+ }
1456
+
1457
+ // Detect API version and route to appropriate download path
1458
+ const useCaptures = (syncData.api_version || 0) >= 2 && syncData.captures && syncData.captures.length > 0
1459
+
1460
+ if (useCaptures) {
1461
+ // New capture-aware sync path
1462
+ const captures: CaptureGroup[] = syncData.captures!
1463
+ console.log(
1464
+ `[GallerySyncService] 📊 Found ${captures.length} captures to download (api_version=${syncData.api_version})`,
1465
+ )
1466
+
1467
+ captures.slice(0, 5).forEach((c: CaptureGroup, idx: number) => {
1468
+ console.log(
1469
+ `[GallerySyncService] ${idx + 1}. ${c.capture_id} (${c.type}, ${c.files.length} files, ${(
1470
+ c.total_size / 1024
1471
+ ).toFixed(1)} KB)`,
1472
+ )
1473
+ })
1474
+ if (captures.length > 5) {
1475
+ console.log(`[GallerySyncService] ... and ${captures.length - 5} more captures`)
1476
+ }
1477
+
1478
+ // Build a PhotoInfo[] for the store (one per capture, using primary file info)
1479
+ const capturePhotoInfos: PhotoInfo[] = captures.map((c) => {
1480
+ const primaryFile = c.files.find((f) => f.role === "primary") || c.files[0]
1481
+ return {
1482
+ name: c.capture_id,
1483
+ url: `/api/photo?file=${encodeURIComponent(primaryFile.name)}`,
1484
+ download: `/api/download?file=${encodeURIComponent(primaryFile.name)}`,
1485
+ size: c.total_size,
1486
+ modified: c.timestamp,
1487
+ is_video: c.type === "video",
1488
+ thumbnail_data: c.thumbnail_data,
1489
+ duration: c.duration,
1490
+ }
1491
+ })
1492
+
1493
+ store.setSyncing(capturePhotoInfos)
1494
+
1495
+ await localStorageService.saveSyncQueue({
1496
+ files: capturePhotoInfos,
1497
+ currentIndex: 0,
1498
+ startedAt: Date.now(),
1499
+ hotspotInfo,
1500
+ })
1501
+
1502
+ await gallerySyncNotifications.showSyncStarted(captures.length)
1503
+
1504
+ console.log("[GallerySyncService] 🚀 Beginning capture download execution...")
1505
+ await this.executeCaptureDownload(captures, syncData.server_time)
1506
+ } else {
1507
+ // Legacy flat file sync path
1508
+ const filesToSync = syncData.changed_files
1509
+ // Count only user-visible media files (exclude HDR brackets and IMU sidecars)
1510
+ const userVisibleCount = filesToSync.filter(
1511
+ (f: any) => !f.name?.match(/_ev-?\d+\.(jpg|jpeg)$/i) && !f.name?.match(/\.imu\.json$/i),
1512
+ ).length
1513
+ console.log(
1514
+ `[GallerySyncService] 📊 Found ${filesToSync.length} files to download (${userVisibleCount} media items, legacy path):`,
1515
+ )
1516
+
1517
+ console.log("[GallerySyncService] 📋 First 5 files:")
1518
+ filesToSync.slice(0, 5).forEach((_file: any, _idx: number) => {
1519
+ console.log(
1520
+ `[GallerySyncService] ${_idx + 1}. ${_file.name} (${_file.is_video ? "video" : "photo"}, ${(
1521
+ _file.size / 1024
1522
+ ).toFixed(1)} KB)`,
1523
+ )
1524
+ })
1525
+ if (filesToSync.length > 5) {
1526
+ console.log(`[GallerySyncService] ... and ${filesToSync.length - 5} more files`)
1527
+ }
1528
+
1529
+ store.setSyncing(filesToSync)
1530
+
1531
+ await localStorageService.saveSyncQueue({
1532
+ files: filesToSync,
1533
+ currentIndex: 0,
1534
+ startedAt: Date.now(),
1535
+ hotspotInfo,
1536
+ })
1537
+
1538
+ await gallerySyncNotifications.showSyncStarted(userVisibleCount)
1539
+
1540
+ console.log("[GallerySyncService] 🚀 Beginning download execution (legacy)...")
1541
+ await this.executeDownload(filesToSync, syncData.server_time)
1542
+ }
1543
+ } catch (error: any) {
1544
+ console.error("[GallerySyncService] Failed to start download:", error)
1545
+ store.setSyncError(error?.message || "Failed to start download")
1546
+ await gallerySyncNotifications.showSyncError("Failed to start download")
1547
+
1548
+ if (store.syncServiceOpenedHotspot) {
1549
+ await this.closeHotspot()
1550
+ }
1551
+ }
1552
+ }
1553
+
1554
+ /**
1555
+ * Execute the actual file download.
1556
+ * Used for old asg_client firmware that doesn't send api_version=2 / captures.
1557
+ * NOTE: The sidecar/bracket filtering within is likely dead code — old firmware
1558
+ * only produces flat photos/videos with no sidecars or HDR brackets.
1559
+ */
1560
+ private async executeDownload(files: PhotoInfo[], serverTime: number): Promise<void> {
1561
+ const downloadStartTime = Date.now()
1562
+ console.log("[GallerySyncService] ========================================")
1563
+ console.log("[GallerySyncService] ⬇️ DOWNLOAD EXECUTION STARTED")
1564
+ console.log("[GallerySyncService] ========================================")
1565
+ console.log(`[GallerySyncService] 📊 Files to download: ${files.length}`)
1566
+
1567
+ const store = useGallerySyncStore.getState()
1568
+ const settingsStore = useSettingsStore.getState()
1569
+ const defaultWearable = settingsStore.getSetting(SETTINGS.default_wearable.key)
1570
+
1571
+ let downloadedCount = 0
1572
+ let failedCount = 0
1573
+
1574
+ // Check if auto-save to camera roll is enabled (we'll save each file immediately after download)
1575
+ const shouldAutoSave = await gallerySettingsService.getAutoSaveToCameraRoll()
1576
+ const shouldProcessImages = useSettingsStore.getState().getSetting(SETTINGS.media_post_processing.key)
1577
+ console.log(`[GallerySyncService] 📸 Auto-save to camera roll: ${shouldAutoSave}`)
1578
+ console.log(`[GallerySyncService] 🎨 Image processing: ${shouldProcessImages}`)
1579
+
1580
+ try {
1581
+ const downloadResult = await asgCameraApi.batchSyncFiles(
1582
+ files,
1583
+ true,
1584
+ (current, total, fileName, fileProgress, downloadedFile) => {
1585
+ // CRITICAL: This callback MUST NOT throw!
1586
+ // RNFS progress callbacks run inside native bridge — throwing here causes
1587
+ // EXC_BAD_ACCESS. Cancellation is handled via AbortSignal → the active transport.
1588
+
1589
+ // Check if cancelled — just return, abort signal will stop the download
1590
+ if (this.abortController?.signal.aborted) {
1591
+ return
1592
+ }
1593
+
1594
+ // Update store
1595
+ const currentStore = useGallerySyncStore.getState()
1596
+
1597
+ if (fileProgress === 0 || fileProgress === undefined) {
1598
+ // Starting a new file - but only mark previous complete if this is a NEW file
1599
+ // (not just another 0% progress report for the same file)
1600
+ // This prevents double-counting when both batchSyncFiles and RNFS report 0%
1601
+ const isNewFile = currentStore.currentFile !== fileName
1602
+
1603
+ if (isNewFile) {
1604
+ // Mark previous file as complete when moving to next
1605
+ if (current > 1 && currentStore.currentFile) {
1606
+ currentStore.onFileComplete(currentStore.currentFile)
1607
+ // Persist queue index so we can resume from here if app is killed
1608
+ localStorageService.updateSyncQueueIndex(current - 1).catch((err) => {
1609
+ console.error("[GallerySyncService] Failed to persist queue index:", err)
1610
+ })
1611
+ }
1612
+ // Now set the new current file
1613
+ currentStore.setCurrentFile(fileName, 0)
1614
+ }
1615
+ } else {
1616
+ currentStore.onFileProgress(fileName, fileProgress || 0)
1617
+ }
1618
+
1619
+ // When file completes (100%), update it in the queue with downloaded paths
1620
+ if (fileProgress === 100 && downloadedFile) {
1621
+ // Update file with local paths and URLs for immediate preview display
1622
+ const localFileUrl = downloadedFile.filePath
1623
+ ? downloadedFile.filePath.startsWith("file://")
1624
+ ? downloadedFile.filePath
1625
+ : `file://${downloadedFile.filePath}`
1626
+ : downloadedFile.url
1627
+
1628
+ const localThumbnailUrl = downloadedFile.thumbnailPath
1629
+ ? downloadedFile.thumbnailPath.startsWith("file://")
1630
+ ? downloadedFile.thumbnailPath
1631
+ : `file://${downloadedFile.thumbnailPath}`
1632
+ : undefined
1633
+
1634
+ const updatedFile = {
1635
+ ...downloadedFile,
1636
+ url: localFileUrl, // Update URL to local file for immediate preview
1637
+ download: localFileUrl, // Update download URL for videos
1638
+ filePath: downloadedFile.filePath,
1639
+ thumbnailPath: localThumbnailUrl,
1640
+ }
1641
+ currentStore.updateFileInQueue(fileName, updatedFile)
1642
+
1643
+ // 🎯 IMMEDIATELY process + save to camera roll if enabled
1644
+ if (downloadedFile.filePath) {
1645
+ // Parse the capture timestamp from the photo metadata
1646
+ let captureTime: number | undefined
1647
+ if (downloadedFile.modified) {
1648
+ captureTime =
1649
+ typeof downloadedFile.modified === "string"
1650
+ ? parseInt(downloadedFile.modified, 10)
1651
+ : downloadedFile.modified
1652
+ if (isNaN(captureTime)) {
1653
+ console.warn(
1654
+ `[GallerySyncService] Invalid modified timestamp for ${downloadedFile.name}:`,
1655
+ downloadedFile.modified,
1656
+ )
1657
+ captureTime = undefined
1658
+ }
1659
+ }
1660
+
1661
+ // Enqueue for background processing (non-blocking)
1662
+ const isVideo = downloadedFile.name?.match(/\.(mp4|mov)$/i)
1663
+ const leaf = downloadedFile.name?.includes("/")
1664
+ ? downloadedFile.name.substring(downloadedFile.name.lastIndexOf("/") + 1)
1665
+ : downloadedFile.name
1666
+ const isImuSidecar = leaf?.match(/^imu\.json$/i)
1667
+ const isHdrBracket = leaf?.match(/^ev-?\d+\.jpe?g$/i)
1668
+
1669
+ if (!isImuSidecar && !isHdrBracket && downloadedFile.filePath) {
1670
+ const imuSidecarPath = downloadedFile.filePath.replace(/\.[^.]+$/, ".imu.json")
1671
+ mediaProcessingQueue.enqueue({
1672
+ id: downloadedFile.name,
1673
+ type: isVideo ? "video" : "photo",
1674
+ primaryPath: downloadedFile.filePath,
1675
+ sidecarPath: isVideo ? imuSidecarPath : undefined,
1676
+ timestamp: captureTime,
1677
+ totalSize: downloadedFile.size,
1678
+ duration: downloadedFile.duration,
1679
+ glassesModel: defaultWearable,
1680
+ shouldProcess: !!shouldProcessImages,
1681
+ shouldAutoSave: !!shouldAutoSave,
1682
+ thumbnailPath: downloadedFile.thumbnailPath,
1683
+ deleteFromGlasses: [downloadedFile.name],
1684
+ protocolVersion: 1,
1685
+ })
1686
+ }
1687
+ }
1688
+ }
1689
+
1690
+ // Update notification
1691
+ gallerySyncNotifications.updateProgress(current, total, fileName, fileProgress || 0)
1692
+ },
1693
+ this.abortController?.signal,
1694
+ )
1695
+
1696
+ downloadedCount = downloadResult.downloaded.length
1697
+ failedCount = downloadResult.failed.length
1698
+
1699
+ const downloadDuration = Date.now() - downloadStartTime
1700
+ console.log("[GallerySyncService] ========================================")
1701
+ console.log("[GallerySyncService] ✅ DOWNLOAD EXECUTION COMPLETE")
1702
+ console.log("[GallerySyncService] ========================================")
1703
+ console.log("[GallerySyncService] 📊 Results:")
1704
+ console.log(`[GallerySyncService] - Downloaded: ${downloadedCount}`)
1705
+ console.log(`[GallerySyncService] - Failed: ${failedCount}`)
1706
+ console.log(`[GallerySyncService] - Duration: ${(downloadDuration / 1000).toFixed(1)}s`)
1707
+ console.log(`[GallerySyncService] - Total size: ${(downloadResult.total_size / 1024 / 1024).toFixed(2)} MB`)
1708
+ if (downloadDuration > 0 && downloadResult.total_size > 0) {
1709
+ const _speedMbps = downloadResult.total_size / 1024 / 1024 / (downloadDuration / 1000)
1710
+ console.log(`[GallerySyncService] - Avg speed: ${_speedMbps.toFixed(2)} MB/s`)
1711
+ }
1712
+
1713
+ // Mark the last file as complete (if any files were downloaded)
1714
+ if (downloadResult.downloaded.length > 0) {
1715
+ const lastFileName = downloadResult.downloaded[downloadResult.downloaded.length - 1]?.name
1716
+ if (lastFileName) {
1717
+ const currentStore = useGallerySyncStore.getState()
1718
+ currentStore.onFileComplete(lastFileName)
1719
+ }
1720
+ }
1721
+
1722
+ // Update queue index to final position
1723
+ await localStorageService.updateSyncQueueIndex(files.length)
1724
+
1725
+ // Mark failed files in store
1726
+ for (const failedFileName of downloadResult.failed) {
1727
+ const currentStore = useGallerySyncStore.getState()
1728
+ currentStore.onFileFailed(failedFileName)
1729
+ }
1730
+
1731
+ // Wait for processing queue to finish before marking complete
1732
+ console.log("[GallerySyncService] ⏳ Waiting for processing queue to drain...")
1733
+ await mediaProcessingQueue.waitUntilDrained()
1734
+ console.log("[GallerySyncService] ✅ Processing queue drained")
1735
+
1736
+ // Download success is not destination success. Export, validation, metadata, and
1737
+ // acknowledgement failures are reported asynchronously by the processing queue; fold them
1738
+ // back into the legacy result so its timestamp watermark cannot skip the source forever.
1739
+ const processingFailures = new Set(useGallerySyncStore.getState().failedFiles)
1740
+ for (const file of files) {
1741
+ if (processingFailures.has(file.name) && !downloadResult.failed.includes(file.name)) {
1742
+ downloadResult.failed.push(file.name)
1743
+ }
1744
+ }
1745
+ failedCount = downloadResult.failed.length
1746
+
1747
+ // Update sync state — only advance watermark if files were downloaded.
1748
+ // If any failed, set it before the oldest failure so they get retried.
1749
+ let syncWatermark = serverTime
1750
+ if (downloadedCount === 0) {
1751
+ const currentSyncState = await localStorageService.getSyncState()
1752
+ syncWatermark = currentSyncState.last_sync_time
1753
+ console.log("[GallerySyncService] ℹ️ No files downloaded — last_sync_time unchanged")
1754
+ } else if (downloadResult.failed.length > 0) {
1755
+ const failedSet = new Set(downloadResult.failed)
1756
+ let oldestFailed = Infinity
1757
+ for (const f of files) {
1758
+ if (failedSet.has(f.name)) {
1759
+ const ts = typeof f.modified === "number" ? f.modified : parseInt(String(f.modified), 10)
1760
+ if (!isNaN(ts) && ts < oldestFailed) oldestFailed = ts
1761
+ }
1762
+ }
1763
+ if (oldestFailed < Infinity) {
1764
+ syncWatermark = Math.max(0, oldestFailed - 1)
1765
+ console.log(
1766
+ `[GallerySyncService] ⚠️ ${downloadResult.failed.length} files failed — sync watermark set to ${syncWatermark} instead of ${serverTime}`,
1767
+ )
1768
+ }
1769
+ } else {
1770
+ let maxModified = 0
1771
+ const failedSet = new Set(downloadResult.failed)
1772
+ for (const f of files) {
1773
+ if (failedSet.has(f.name)) continue
1774
+ const ts = typeof f.modified === "number" ? f.modified : parseInt(String(f.modified), 10)
1775
+ if (!isNaN(ts)) maxModified = Math.max(maxModified, ts)
1776
+ }
1777
+ if (maxModified > 0) {
1778
+ syncWatermark = maxModified
1779
+ }
1780
+ }
1781
+ console.log("[GallerySyncService] 💾 Updating sync state in local storage...")
1782
+ const currentSyncState = await localStorageService.getSyncState()
1783
+ // Persist if we downloaded anything OR if a failure needs the watermark rolled back.
1784
+ // (Otherwise a clock-skew-triggered full sync where every legacy file fails would
1785
+ // leave the stale future watermark on disk and never retry those files.)
1786
+ if (downloadedCount > 0 || downloadResult.failed.length > 0) {
1787
+ await localStorageService.updateSyncState({
1788
+ last_sync_time: syncWatermark,
1789
+ total_downloaded: currentSyncState.total_downloaded + downloadedCount,
1790
+ total_size: currentSyncState.total_size + downloadResult.total_size,
1791
+ })
1792
+ }
1793
+ console.log("[GallerySyncService] ✅ Sync state updated:")
1794
+ console.log(
1795
+ `[GallerySyncService] - New last_sync_time: ${syncWatermark} (${new Date(syncWatermark).toISOString()})`,
1796
+ )
1797
+ console.log(
1798
+ `[GallerySyncService] - Total downloads (lifetime): ${
1799
+ currentSyncState.total_downloaded + downloadedCount
1800
+ }`,
1801
+ )
1802
+ console.log(
1803
+ `[GallerySyncService] - Total data (lifetime): ${(
1804
+ (currentSyncState.total_size + downloadResult.total_size) /
1805
+ 1024 /
1806
+ 1024
1807
+ ).toFixed(2)} MB`,
1808
+ )
1809
+
1810
+ if (failedCount > 0 || galleryTransferLedger.hasPendingRecovery()) {
1811
+ store.setSyncError(`${failedCount || "Some"} gallery items need retry`)
1812
+ } else {
1813
+ store.setSyncComplete()
1814
+ }
1815
+ await this.onSyncComplete(downloadedCount, failedCount)
1816
+ } catch (error: any) {
1817
+ mediaProcessingQueue.abort()
1818
+ if (error?.message === "Sync cancelled") {
1819
+ console.log("[GallerySyncService] Sync was cancelled")
1820
+ store.setSyncCancelled()
1821
+ await gallerySyncNotifications.showSyncCancelled()
1822
+ } else {
1823
+ console.error("[GallerySyncService] Download failed:", error)
1824
+ store.setSyncError(error?.message || "Download failed")
1825
+ await gallerySyncNotifications.showSyncError(error?.message || "Download failed")
1826
+ }
1827
+
1828
+ if (store.syncServiceOpenedHotspot) {
1829
+ await this.closeHotspot()
1830
+ }
1831
+ }
1832
+ }
1833
+
1834
+ /**
1835
+ * Execute capture-aware download (api_version=2).
1836
+ * Downloads captures as groups, runs HDR merge, saves single metadata entry per capture.
1837
+ */
1838
+ private async executeCaptureDownload(captures: CaptureGroup[], serverTime: number): Promise<void> {
1839
+ const downloadStartTime = Date.now()
1840
+ console.log("[GallerySyncService] ========================================")
1841
+ console.log("[GallerySyncService] ⬇️ CAPTURE DOWNLOAD EXECUTION STARTED")
1842
+ console.log("[GallerySyncService] ========================================")
1843
+ console.log(`[GallerySyncService] 📊 Captures to download: ${captures.length}`)
1844
+
1845
+ const store = useGallerySyncStore.getState()
1846
+ const settingsStore = useSettingsStore.getState()
1847
+ const defaultWearable = settingsStore.getSetting(SETTINGS.default_wearable.key)
1848
+
1849
+ let downloadedCount = 0
1850
+ let failedCount = 0
1851
+ let totalSizeDownloaded = 0
1852
+ let oldestFailedTimestamp = Infinity // Track for sync watermark
1853
+ let maxSuccessfulTimestamp = 0
1854
+
1855
+ const shouldAutoSave = await gallerySettingsService.getAutoSaveToCameraRoll()
1856
+ const shouldProcessImages = useSettingsStore.getState().getSetting(SETTINGS.media_post_processing.key)
1857
+
1858
+ try {
1859
+ for (let i = 0; i < captures.length; i++) {
1860
+ const capture = captures[i]
1861
+
1862
+ // Check cancellation
1863
+ if (this.abortController?.signal.aborted) {
1864
+ throw new Error("Sync cancelled")
1865
+ }
1866
+
1867
+ // Update store progress
1868
+ const currentStore = useGallerySyncStore.getState()
1869
+ if (i > 0) {
1870
+ // Mark previous capture as complete
1871
+ currentStore.onFileComplete(captures[i - 1].capture_id)
1872
+ await localStorageService.updateSyncQueueIndex(i)
1873
+ }
1874
+ currentStore.setCurrentFile(capture.capture_id, 0)
1875
+
1876
+ try {
1877
+ console.log(
1878
+ `[GallerySyncService] 📦 Downloading capture ${i + 1}/${captures.length}: ${capture.capture_id} (${
1879
+ capture.files.length
1880
+ } files)`,
1881
+ )
1882
+
1883
+ validateCaptureMetadataForDownload(capture)
1884
+
1885
+ // Download all files in this capture
1886
+ const result = await asgCameraApi.downloadCapture(
1887
+ capture,
1888
+ (bytesDownloaded, totalBytes) => {
1889
+ // Don't throw in progress callbacks — abort signal stops the download
1890
+ if (this.abortController?.signal.aborted) return
1891
+ const progress = totalBytes > 0 ? Math.round((bytesDownloaded / totalBytes) * 100) : 0
1892
+ const cs = useGallerySyncStore.getState()
1893
+ cs.onFileProgress(capture.capture_id, Math.min(progress, 99))
1894
+ gallerySyncNotifications.updateProgress(i + 1, captures.length, capture.capture_id, progress)
1895
+ },
1896
+ this.abortController?.signal,
1897
+ )
1898
+
1899
+ // Mark 100% progress
1900
+ const cs2 = useGallerySyncStore.getState()
1901
+ cs2.onFileProgress(capture.capture_id, 100)
1902
+
1903
+ totalSizeDownloaded += capture.total_size
1904
+ downloadedCount++
1905
+ if (capture.timestamp > maxSuccessfulTimestamp) {
1906
+ maxSuccessfulTimestamp = capture.timestamp
1907
+ }
1908
+
1909
+ // Enqueue for processing (runs concurrently with next download)
1910
+ // Delete from glasses happens after processing completes to avoid data loss on crash
1911
+ mediaProcessingQueue.enqueue({
1912
+ id: capture.capture_id,
1913
+ type: capture.type,
1914
+ primaryPath: result.primaryPath,
1915
+ bracketPaths: result.bracketPaths,
1916
+ sidecarPath: result.sidecarPath,
1917
+ thumbnailData: capture.thumbnail_data,
1918
+ captureDir: result.captureDir,
1919
+ timestamp: capture.timestamp,
1920
+ totalSize: capture.total_size,
1921
+ duration: capture.duration,
1922
+ glassesModel: defaultWearable,
1923
+ shouldProcess: !!shouldProcessImages,
1924
+ shouldAutoSave: !!shouldAutoSave,
1925
+ deleteFromGlasses: [capture.capture_id],
1926
+ protocolVersion: capture.files.some((file) => !!file.etag) ? 3 : 2,
1927
+ })
1928
+ } catch (captureError: any) {
1929
+ if (captureError?.message === "Sync cancelled") throw captureError
1930
+ const errMsg = captureError?.message || captureError?.toString?.() || JSON.stringify(captureError)
1931
+ console.error(`[GallerySyncService] ❌ Failed to download capture ${capture.capture_id}: ${errMsg}`)
1932
+ failedCount++
1933
+ // Track oldest failed timestamp so we don't advance sync past it
1934
+ if (capture.timestamp < oldestFailedTimestamp) {
1935
+ oldestFailedTimestamp = capture.timestamp
1936
+ }
1937
+ const cs = useGallerySyncStore.getState()
1938
+ cs.onFileFailed(capture.capture_id)
1939
+ }
1940
+ }
1941
+
1942
+ // Mark last capture as complete
1943
+ if (captures.length > 0) {
1944
+ const lastCapture = captures[captures.length - 1]
1945
+ const cs = useGallerySyncStore.getState()
1946
+ cs.onFileComplete(lastCapture.capture_id)
1947
+ }
1948
+
1949
+ await localStorageService.updateSyncQueueIndex(captures.length)
1950
+
1951
+ const downloadDuration = Date.now() - downloadStartTime
1952
+ console.log("[GallerySyncService] ========================================")
1953
+ console.log("[GallerySyncService] ✅ CAPTURE DOWNLOAD EXECUTION COMPLETE")
1954
+ console.log("[GallerySyncService] ========================================")
1955
+ console.log(`[GallerySyncService] 📊 Downloaded: ${downloadedCount}, Failed: ${failedCount}`)
1956
+ console.log(`[GallerySyncService] ⏱️ Duration: ${(downloadDuration / 1000).toFixed(1)}s`)
1957
+
1958
+ // Wait for processing queue to finish before marking complete
1959
+ console.log("[GallerySyncService] ⏳ Waiting for processing queue to drain...")
1960
+ await mediaProcessingQueue.waitUntilDrained()
1961
+ console.log("[GallerySyncService] ✅ Processing queue drained")
1962
+
1963
+ // Reconcile failures from the processing queue. validateDownloadedMediaFile
1964
+ // (post-download validation in mediaProcessingQueue) runs AFTER enqueue
1965
+ // returns, so a failure there doesn't reach the per-capture catch above. The
1966
+ // gallerySync store collects those failures via onFileFailed — pull them in
1967
+ // here so the watermark holds them back for retry on the next sync.
1968
+ const captureTimestampById = new Map<string, number>()
1969
+ for (const c of captures) {
1970
+ if (typeof c.timestamp === "number") {
1971
+ captureTimestampById.set(c.capture_id, c.timestamp)
1972
+ }
1973
+ }
1974
+ const failedSnapshot = useGallerySyncStore.getState().failedFiles
1975
+ const observedFailures = new Set<string>(failedSnapshot)
1976
+ for (const failedId of observedFailures) {
1977
+ const ts = captureTimestampById.get(failedId)
1978
+ if (ts === undefined) continue // failure from a different scope (e.g. file-level), skip
1979
+ if (ts < oldestFailedTimestamp) {
1980
+ oldestFailedTimestamp = ts
1981
+ }
1982
+ }
1983
+ // failedCount should reflect the total set of failed captures from THIS batch.
1984
+ const failedFromThisBatch = captures.filter((c) => observedFailures.has(c.capture_id)).length
1985
+ if (failedFromThisBatch > failedCount) {
1986
+ failedCount = failedFromThisBatch
1987
+ }
1988
+
1989
+ // Update sync state — only advance watermark when captures were downloaded.
1990
+ let syncWatermark = serverTime
1991
+ const currentSyncState = await localStorageService.getSyncState()
1992
+ if (failedCount > 0 && oldestFailedTimestamp < Infinity) {
1993
+ // Failures take priority — roll the watermark back before the oldest failure so it
1994
+ // gets retried, regardless of whether anything else succeeded in this batch.
1995
+ syncWatermark = Math.max(0, oldestFailedTimestamp - 1)
1996
+ console.log(
1997
+ `[GallerySyncService] ⚠️ ${failedCount} captures failed — sync watermark set to ${syncWatermark} instead of ${serverTime} so they will be retried`,
1998
+ )
1999
+ } else if (downloadedCount === 0) {
2000
+ syncWatermark = currentSyncState.last_sync_time
2001
+ console.log("[GallerySyncService] ℹ️ No captures downloaded — last_sync_time unchanged")
2002
+ } else if (maxSuccessfulTimestamp > 0) {
2003
+ syncWatermark = maxSuccessfulTimestamp
2004
+ }
2005
+ // Persist if we downloaded anything OR if a failure needs the watermark rolled back
2006
+ // (zero-byte / validation failures otherwise leave a stale watermark on disk).
2007
+ if (downloadedCount > 0 || (failedCount > 0 && oldestFailedTimestamp < Infinity)) {
2008
+ await localStorageService.updateSyncState({
2009
+ last_sync_time: syncWatermark,
2010
+ total_downloaded: currentSyncState.total_downloaded + downloadedCount,
2011
+ total_size: currentSyncState.total_size + totalSizeDownloaded,
2012
+ })
2013
+ }
2014
+
2015
+ if (failedCount > 0 || galleryTransferLedger.hasPendingRecovery()) {
2016
+ store.setSyncError(`${failedCount || "Some"} gallery items need retry`)
2017
+ } else {
2018
+ store.setSyncComplete()
2019
+ }
2020
+ await this.onSyncComplete(downloadedCount, failedCount)
2021
+ } catch (error: any) {
2022
+ mediaProcessingQueue.abort()
2023
+ if (error?.message === "Sync cancelled") {
2024
+ console.log("[GallerySyncService] Sync was cancelled")
2025
+ store.setSyncCancelled()
2026
+ await gallerySyncNotifications.showSyncCancelled()
2027
+ } else {
2028
+ console.error("[GallerySyncService] Capture download failed:", error)
2029
+ store.setSyncError(error?.message || "Download failed")
2030
+ await gallerySyncNotifications.showSyncError(error?.message || "Download failed")
2031
+ }
2032
+
2033
+ if (store.syncServiceOpenedHotspot) {
2034
+ await this.closeHotspot()
2035
+ }
2036
+ }
2037
+ }
2038
+
2039
+ /**
2040
+ * Handle sync completion
2041
+ */
2042
+ private async onSyncComplete(downloadedCount: number, failedCount: number): Promise<void> {
2043
+ console.log("[GallerySyncService] ========================================")
2044
+ console.log("[GallerySyncService] 🎉 Step 6/6: Sync completion")
2045
+ console.log("[GallerySyncService] ========================================")
2046
+ console.log("[GallerySyncService] 📊 Final results:")
2047
+ console.log(`[GallerySyncService] - Downloaded: ${downloadedCount}`)
2048
+ console.log(`[GallerySyncService] - Failed: ${failedCount}`)
2049
+ console.log(
2050
+ `[GallerySyncService] - Success rate: ${
2051
+ downloadedCount > 0 ? ((downloadedCount / (downloadedCount + failedCount)) * 100).toFixed(1) : 0
2052
+ }%`,
2053
+ )
2054
+
2055
+ // 🔍 DIAGNOSTIC: Show all pictures currently in storage after sync
2056
+ // try {
2057
+ // const allStoredFiles = await localStorageService.getDownloadedFiles()
2058
+ // const fileNames = Object.keys(allStoredFiles)
2059
+ // console.log(`[GallerySyncService] 📸 POST-SYNC INVENTORY: ${fileNames.length} total files in storage`)
2060
+ // console.log(`[GallerySyncService] 📋 Complete file list:`)
2061
+ // fileNames
2062
+ // .sort((a, b) => {
2063
+ // const fileA = allStoredFiles[a]
2064
+ // const fileB = allStoredFiles[b]
2065
+ // return fileB.downloaded_at - fileA.downloaded_at // Most recent first
2066
+ // })
2067
+ // .slice(0, 20)
2068
+ // .forEach((fileName, idx) => {
2069
+ // const file = allStoredFiles[fileName]
2070
+ // const captureDate = new Date(file.modified).toISOString()
2071
+ // const downloadDate = new Date(file.downloaded_at).toISOString()
2072
+ // console.log(
2073
+ // `[GallerySyncService] ${idx + 1}. ${fileName} - captured: ${captureDate}, downloaded: ${downloadDate}`,
2074
+ // )
2075
+ // })
2076
+ // if (fileNames.length > 20) {
2077
+ // console.log(`[GallerySyncService] ... and ${fileNames.length - 20} more files`)
2078
+ // }
2079
+ // } catch (error) {
2080
+ // console.error(`[GallerySyncService] Failed to get post-sync inventory:`, error)
2081
+ // }
2082
+
2083
+ const hasPendingRecovery = galleryTransferLedger.hasPendingRecovery()
2084
+ if (!hasPendingRecovery && failedCount === 0) {
2085
+ console.log("[GallerySyncService] 🧹 Clearing completed sync queue...")
2086
+ await localStorageService.clearSyncQueue()
2087
+ } else {
2088
+ console.log("[GallerySyncService] ♻️ Keeping recovery state for unfinished export/ack work")
2089
+ }
2090
+
2091
+ if (hasPendingRecovery || failedCount > 0) {
2092
+ console.log("[GallerySyncService] 📱 Showing retry-required notification...")
2093
+ await gallerySyncNotifications.showSyncError(
2094
+ failedCount > 0
2095
+ ? `${failedCount} gallery item${failedCount === 1 ? "" : "s"} will be retried`
2096
+ : "Gallery export or acknowledgement will be retried",
2097
+ )
2098
+ } else {
2099
+ console.log("[GallerySyncService] 📱 Showing completion notification...")
2100
+ await gallerySyncNotifications.showSyncComplete(downloadedCount, 0)
2101
+ }
2102
+
2103
+ // Close hotspot if we opened it
2104
+ const store = useGallerySyncStore.getState()
2105
+ if (store.syncServiceOpenedHotspot) {
2106
+ console.log("[GallerySyncService] 📡 Closing hotspot (service opened it)...")
2107
+ await this.closeHotspot()
2108
+ } else {
2109
+ console.log("[GallerySyncService] ℹ️ Hotspot was not opened by service - leaving it enabled")
2110
+ }
2111
+
2112
+ // Clear glasses gallery count immediately after successful sync
2113
+ // This ensures UI shows 0 items remaining right away
2114
+ // The subsequent query will update this if new photos were taken during sync
2115
+ if (!hasPendingRecovery && failedCount === 0) {
2116
+ console.log("[GallerySyncService] 🔄 Clearing glasses gallery count (synced all items)")
2117
+ store.clearGlassesGalleryStatus()
2118
+ }
2119
+
2120
+ // Auto-reset to idle after 4 seconds to clear "Sync complete!" message,
2121
+ // then query glasses for any new content taken during the sync.
2122
+ // The query MUST happen after the reset — otherwise setGlassesGalleryStatus
2123
+ // sees syncState="complete" + hasContent=true and immediately resets to idle,
2124
+ // making it look like sync accomplished nothing (circular sync loop).
2125
+ console.log("[GallerySyncService] ⏲️ Scheduling auto-reset to idle in 4 seconds...")
2126
+ BgTimer.setTimeout(async () => {
2127
+ const currentStore = useGallerySyncStore.getState()
2128
+ if (currentStore.syncState === "complete") {
2129
+ console.log("[GallerySyncService] 🔄 Auto-resetting sync state to idle")
2130
+ currentStore.setSyncState("idle")
2131
+ }
2132
+ // Now query glasses — any content reported will show the sync button
2133
+ // naturally without preempting the "Sync complete!" message
2134
+ console.log("[GallerySyncService] 🔍 Querying glasses for post-sync gallery status...")
2135
+ await this.queryGlassesGalleryStatus()
2136
+ }, 4000)
2137
+
2138
+ console.log("[GallerySyncService] ========================================")
2139
+ console.log("[GallerySyncService] ✅ SYNC FULLY COMPLETE")
2140
+ console.log("[GallerySyncService] ========================================")
2141
+ }
2142
+
2143
+ /**
2144
+ * Cancel the current sync
2145
+ */
2146
+ async cancelSync(): Promise<void> {
2147
+ console.log("[GallerySyncService] Cancelling sync...")
2148
+
2149
+ // Abort any ongoing downloads
2150
+ if (this.abortController) {
2151
+ this.abortController.abort()
2152
+ this.abortController = null
2153
+ }
2154
+
2155
+ // Clear timeout
2156
+ if (this.hotspotConnectionTimeout) {
2157
+ BgTimer.clearTimeout(this.hotspotConnectionTimeout!)
2158
+ this.hotspotConnectionTimeout = null
2159
+ }
2160
+
2161
+ const store = useGallerySyncStore.getState()
2162
+
2163
+ // Close hotspot if we opened it
2164
+ if (store.syncServiceOpenedHotspot) {
2165
+ await this.closeHotspot()
2166
+ }
2167
+
2168
+ // Update store
2169
+ store.setSyncCancelled()
2170
+
2171
+ // Clear queue
2172
+ await localStorageService.clearSyncQueue()
2173
+
2174
+ // Dismiss notification
2175
+ await gallerySyncNotifications.showSyncCancelled()
2176
+ }
2177
+
2178
+ /**
2179
+ * Close the hotspot
2180
+ */
2181
+ private async closeHotspot(): Promise<void> {
2182
+ const store = useGallerySyncStore.getState()
2183
+
2184
+ try {
2185
+ console.log("[GallerySyncService] Closing hotspot...")
2186
+ await localNetworkTransport.disconnect()
2187
+ await BluetoothSdk.setHotspotState(false)
2188
+ store.setSyncServiceOpenedHotspot(false)
2189
+ store.setHotspotInfo(null)
2190
+ console.log("[GallerySyncService] Hotspot closed")
2191
+ } catch (error) {
2192
+ console.error("[GallerySyncService] Failed to close hotspot:", error)
2193
+ }
2194
+ }
2195
+
2196
+ /**
2197
+ * Check for resumable sync on app start
2198
+ */
2199
+ async checkForResumableSync(): Promise<boolean> {
2200
+ const hasResumable = await localStorageService.hasResumableSyncQueue()
2201
+
2202
+ if (hasResumable) {
2203
+ console.log("[GallerySyncService] Found resumable sync queue")
2204
+ // Don't auto-resume - let user decide
2205
+ // Could emit an event here for UI to show "Resume sync?" prompt
2206
+ }
2207
+
2208
+ return hasResumable
2209
+ }
2210
+
2211
+ /**
2212
+ * Resume a previously interrupted sync
2213
+ */
2214
+ async resumeSync(): Promise<void> {
2215
+ const queue = await localStorageService.getSyncQueue()
2216
+
2217
+ if (!queue || queue.currentIndex >= queue.files.length) {
2218
+ console.log("[GallerySyncService] No queue to resume")
2219
+ await localStorageService.clearSyncQueue()
2220
+ return
2221
+ }
2222
+
2223
+ // Check if queue is too old - hotspot auto-disables after 40s of inactivity,
2224
+ // so stale queues can't be resumed (hotspot credentials are no longer valid)
2225
+ const queueAge = Date.now() - queue.startedAt
2226
+ if (queueAge > TIMING.MAX_QUEUE_AGE_MS) {
2227
+ console.log(`[GallerySyncService] Queue too old (${Math.round(queueAge / 1000)}s) - clearing stale queue`)
2228
+ await localStorageService.clearSyncQueue()
2229
+ // Don't auto-start - let user tap sync button if they want to continue
2230
+ return
2231
+ }
2232
+
2233
+ // R5: Resume by going through full startSync() flow to re-request hotspot
2234
+ // (stale hotspot credentials are unreliable). The saved queue will be used
2235
+ // to skip already-downloaded files when startFileDownload detects them.
2236
+ console.log(`[GallerySyncService] Resuming sync from file ${queue.currentIndex + 1}/${queue.files.length}`)
2237
+ console.log("[GallerySyncService] Re-requesting hotspot via full startSync flow")
2238
+ await this.startSync()
2239
+ }
2240
+
2241
+ /**
2242
+ * Query glasses for gallery status
2243
+ */
2244
+ async queryGlassesGalleryStatus(): Promise<void> {
2245
+ try {
2246
+ await BluetoothSdk.queryGalleryStatus()
2247
+ } catch (error) {
2248
+ console.error("[GallerySyncService] Failed to query gallery status:", error)
2249
+ }
2250
+ }
2251
+
2252
+ /** True while pre-flight startSync work is in flight (before sync state transitions). */
2253
+ isSyncStarting(): boolean {
2254
+ return this.syncStartPromise !== null
2255
+ }
2256
+
2257
+ /**
2258
+ * Check if sync is currently in progress (hotspot/WiFi/download phases).
2259
+ * Does not include pre-flight — use isSyncStarting() for that.
2260
+ */
2261
+ isSyncing(): boolean {
2262
+ const store = useGallerySyncStore.getState()
2263
+ return (
2264
+ store.syncState === "syncing" || store.syncState === "connecting_wifi" || store.syncState === "requesting_hotspot"
2265
+ )
2266
+ }
2267
+ }
2268
+
2269
+ export const gallerySyncService = GallerySyncService.getInstance()