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