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