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