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