@onairosofficial/onairos-capacitor 0.1.0 → 0.1.2

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 (202) hide show
  1. package/CAPACITOR_QUICK_START.md +379 -0
  2. package/CONNECTORS.md +122 -0
  3. package/LICENSE +194 -10
  4. package/OnairosofficialOnairosCapacitor.podspec +13 -0
  5. package/Package.swift +26 -0
  6. package/README.md +176 -25
  7. package/dist/onairos.capacitor.esm.js +1 -0
  8. package/dist/onairos.capacitor.esm.turbopack.js +1 -0
  9. package/docs/CAPACITOR_INTEGRATION_GUIDE.md +159 -0
  10. package/docs/CAPACITOR_MOCK_APP_TESTING.md +213 -0
  11. package/docs/CAPACITOR_SDK_FIXES_SUMMARY.md +65 -0
  12. package/docs/CROSS_SDK_PARITY.md +239 -0
  13. package/docs/DATA_FREQUENCY.md +57 -0
  14. package/docs/DEVELOPER_SDK_CHANGES.md +532 -0
  15. package/docs/INCIDENT_ENABLETRAINING_PIN_WEB_8.1.9.md +82 -0
  16. package/docs/ONAIROS_BUTTON_PROPS.md +152 -0
  17. package/docs/PLATFORM_APIS.md +559 -0
  18. package/docs/RAW_MEMORIES_API.md +305 -0
  19. package/docs/RAW_MEMORIES_SDK_UPDATE.md +54 -0
  20. package/docs/SDK_PARITY_ROLLUP_2026_04_24_to_05_02.md +96 -0
  21. package/docs/oldFixes.md +216 -0
  22. package/ios/Sources/OnairosNativeConnectorsPlugin/OnairosChatGPTNativePlugin.swift +993 -0
  23. package/ios/Sources/OnairosNativeConnectorsPlugin/OnairosNetflixNativePlugin.swift +33 -0
  24. package/ios/Sources/OnairosNativeConnectorsPlugin/OnairosSpotifyNativePlugin.swift +1082 -0
  25. package/onairos.d.ts +656 -0
  26. package/package.json +188 -37
  27. package/src/OnairosReconnectButton.jsx +272 -0
  28. package/src/RSA.jsx +57 -0
  29. package/src/assets/NewLogo.png +0 -0
  30. package/src/assets/OnairosNewLogo.png +0 -0
  31. package/src/assets/chatgpt-icon.png +0 -0
  32. package/src/assets/fire-horse.png +0 -0
  33. package/src/assets/fire-horse.transparent.png +0 -0
  34. package/src/assets/latest-firehorse.png +0 -0
  35. package/src/assets/perplexity.png +0 -0
  36. package/src/assets/persona.png +0 -0
  37. package/src/assets/persona1.png +0 -0
  38. package/src/assets/persona2.png +0 -0
  39. package/src/assets/persona3.png +0 -0
  40. package/src/assets/persona4.png +0 -0
  41. package/src/assets/persona5.png +0 -0
  42. package/src/capacitorConnectorCatalog.js +38 -0
  43. package/src/capacitorOAuthConfig.js +52 -0
  44. package/src/chatgptHostedImport/index.js +303 -0
  45. package/src/components/AuthButtons.jsx +48 -0
  46. package/src/components/ConnectChatGPTModal.jsx +666 -0
  47. package/src/components/ConnectClaudeModal.jsx +610 -0
  48. package/src/components/ConnectGeminiModal.jsx +639 -0
  49. package/src/components/ConnectGrokModal.jsx +701 -0
  50. package/src/components/ConnectPerplexityModal.jsx +726 -0
  51. package/src/components/DataExplainerScreen.jsx +349 -0
  52. package/src/components/DataRequest.js +885 -0
  53. package/src/components/DataRequest.jsx +1055 -0
  54. package/src/components/EmailAuth.js +1871 -0
  55. package/src/components/EmailAuth.jsx +2062 -0
  56. package/src/components/ExtensionInstallPrompt.jsx +142 -0
  57. package/src/components/GoogleButton.js +133 -0
  58. package/src/components/LLMConnectorManager.jsx +201 -0
  59. package/src/components/LoadingPage.jsx +19 -0
  60. package/src/components/LoadingScreen.jsx +81 -0
  61. package/src/components/LunarBirthdate.jsx +96 -0
  62. package/src/components/LunarLoadingPage.jsx +251 -0
  63. package/src/components/Notification.jsx +21 -0
  64. package/src/components/OnairosAppButton.jsx +85 -0
  65. package/src/components/OnairosSSO.jsx +645 -0
  66. package/src/components/OnairosTrigger.jsx +61 -0
  67. package/src/components/PerplexityLogo.jsx +43 -0
  68. package/src/components/PinSetup.js +200 -0
  69. package/src/components/PinSetup.jsx +228 -0
  70. package/src/components/SDK_PIN_INTEGRATION_REQUIRED_CHANGES.md +526 -0
  71. package/src/components/SdkErrorBoundary.jsx +36 -0
  72. package/src/components/SecuritySetup.js +81 -0
  73. package/src/components/SessionUserBar.jsx +83 -0
  74. package/src/components/SignUp.js +123 -0
  75. package/src/components/TestTelegramButton.js +53 -0
  76. package/src/components/TrainingComponent.jsx +200 -0
  77. package/src/components/TrainingScreen.jsx +897 -0
  78. package/src/components/UniversalOnboarding.js +306 -0
  79. package/src/components/UniversalOnboarding.jsx +4837 -0
  80. package/src/components/ValentineLoadingPage.jsx +502 -0
  81. package/src/components/ValentineModeSelector.jsx +162 -0
  82. package/src/components/WelcomeScreen.jsx +435 -0
  83. package/src/components/WrappedLoadingPage.jsx +205 -0
  84. package/src/components/connectors/ChatGPTConnector.js +348 -0
  85. package/src/components/connectors/ChatGPTConnector.jsx +348 -0
  86. package/src/components/connectors/ClaudeConnector.js +44 -0
  87. package/src/components/connectors/ClaudeConnector.jsx +44 -0
  88. package/src/components/connectors/GeminiConnector.js +170 -0
  89. package/src/components/connectors/GeminiConnector.jsx +170 -0
  90. package/src/components/connectors/GmailConnector.js +148 -0
  91. package/src/components/connectors/GmailConnector.jsx +148 -0
  92. package/src/components/connectors/GrokConnector.js +16 -0
  93. package/src/components/connectors/GrokConnector.jsx +16 -0
  94. package/src/components/connectors/HingeConnector.js +419 -0
  95. package/src/components/connectors/HingeConnector.jsx +419 -0
  96. package/src/components/connectors/InstagramDataConnector.js +726 -0
  97. package/src/components/connectors/InstagramDataConnector.jsx +726 -0
  98. package/src/components/connectors/LinkedInConnector.js +4 -0
  99. package/src/components/connectors/LinkedInConnector.jsx +296 -0
  100. package/src/components/connectors/PerplexityConnector.jsx +16 -0
  101. package/src/components/connectors/PinterestConnector.js +208 -0
  102. package/src/components/connectors/PinterestConnector.jsx +208 -0
  103. package/src/components/connectors/README.md +292 -0
  104. package/src/components/connectors/RedditConnector.js +229 -0
  105. package/src/components/connectors/RedditConnector.jsx +229 -0
  106. package/src/components/connectors/SephoraConnector.js +482 -0
  107. package/src/components/connectors/SephoraConnector.jsx +482 -0
  108. package/src/components/connectors/TikTokConnector.jsx +430 -0
  109. package/src/components/connectors/YoutubeConnector.js +361 -0
  110. package/src/components/connectors/YoutubeConnector.jsx +361 -0
  111. package/src/components/connectors/index.js +50 -0
  112. package/src/components/icons.jsx +46 -0
  113. package/src/components/icons.tsx +21 -0
  114. package/src/components/ui/PageLayout.jsx +1255 -0
  115. package/src/components/ui/PrimaryButton.jsx +162 -0
  116. package/src/components/ui/button.jsx +49 -0
  117. package/src/components/ui/card.jsx +61 -0
  118. package/src/components/ui/checkbox.jsx +33 -0
  119. package/src/components/ui/label.jsx +29 -0
  120. package/src/components/utils/UpdateConnections.js +45 -0
  121. package/src/components/utils/oauthHelper.js +97 -0
  122. package/src/config/api-config.js +138 -0
  123. package/src/deepLink.jsx +38 -0
  124. package/src/getPin.js +26 -0
  125. package/src/icons/Avatar.png +0 -0
  126. package/src/icons/Sentiment.png +0 -0
  127. package/src/icons/Trait.png +0 -0
  128. package/src/iframe/DataRequestPage.jsx +285 -0
  129. package/src/iframe/OnairosButtonIntegration.md +148 -0
  130. package/src/iframe/components/Box.jsx +56 -0
  131. package/src/iframe/components/IndividualConnection.jsx +88 -0
  132. package/src/iframe/dataRequestHandler.js +714 -0
  133. package/src/iframe/data_request_iframe.html +27 -0
  134. package/src/iframe/data_request_page.js +47 -0
  135. package/src/iframe/icons/Avatar.png +1 -0
  136. package/src/iframe/icons/Avatar2.png +1 -0
  137. package/src/iframe/icons/Sentiment.png +1 -0
  138. package/src/iframe/icons/Trait.png +1 -0
  139. package/src/iframe/icons/onairos_logo.png +0 -0
  140. package/src/iframe/utils/api.js +57 -0
  141. package/src/index.js +274 -0
  142. package/src/laravel/OnairosVue.vue +410 -0
  143. package/src/laravel/blade-helpers.js +320 -0
  144. package/src/laravel/vite-plugin.js +179 -0
  145. package/src/mobile/MobileDataRequestPage.jsx +233 -0
  146. package/src/mobile/components/MobileBox.jsx +71 -0
  147. package/src/mobile/components/MobileIndividualConnection.jsx +51 -0
  148. package/src/mobile/shims/browser-apis.js +78 -0
  149. package/src/mobile/shims/lucide-shim.js +85 -0
  150. package/src/nativeConnectors.js +5 -0
  151. package/src/newUI/EMAIL_VERIFICATION_API_SCHEMA.md +268 -0
  152. package/src/newUI/PlatformConnectorsStep.tsx +435 -0
  153. package/src/newUI/PrimaryButton.tsx +213 -0
  154. package/src/newUI/SignInStep.tsx +194 -0
  155. package/src/newUI/VerificationStep.tsx +133 -0
  156. package/src/newUI/WelcomeScreen.tsx +311 -0
  157. package/src/newUI/services/connectedAccountsService.js +129 -0
  158. package/src/onairos.capacitor.jsx +15 -0
  159. package/src/onairos.core.jsx +133 -0
  160. package/src/onairos.jsx +14 -0
  161. package/src/onairos.native.jsx +15 -0
  162. package/src/onairosButton.jsx +9000 -0
  163. package/src/overlay/CheckBox.jsx +114 -0
  164. package/src/overlay/IndividualConnection copy.js +86 -0
  165. package/src/overlay/IndividualConnection.js +191 -0
  166. package/src/overlay/IndividualConnectionNew.jsx +157 -0
  167. package/src/overlay/box.js +84 -0
  168. package/src/overlay/overlay.js +437 -0
  169. package/src/styles/onairos-scoped-preflight.css +97 -0
  170. package/src/styles/sdkCssRegistry.js +20 -0
  171. package/src/styles/styleLoaderInsertShadow.js +69 -0
  172. package/src/styles/tailwind.capacitor.css +395 -0
  173. package/src/styles/tailwind.css +395 -0
  174. package/src/theme/colors.js +40 -0
  175. package/src/utils/apiKeyValidation.js +341 -0
  176. package/src/utils/apiResponseLogger.js +316 -0
  177. package/src/utils/authHeaders.js +275 -0
  178. package/src/utils/biometrics.js +26 -0
  179. package/src/utils/bookmarkletUtils.js +28 -0
  180. package/src/utils/capacitorDetection.js +278 -0
  181. package/src/utils/capacitorLLMHelper.js +352 -0
  182. package/src/utils/capacitorPlugins.js +366 -0
  183. package/src/utils/crossDomainSSO.js +587 -0
  184. package/src/utils/deepLinking.js +27 -0
  185. package/src/utils/devLogger.js +46 -0
  186. package/src/utils/extensionDetection.js +418 -0
  187. package/src/utils/extractMemory.js +277 -0
  188. package/src/utils/framerBrandingOverrides.js +40 -0
  189. package/src/utils/googleWebClientId.js +55 -0
  190. package/src/utils/overlayHandler.js +224 -0
  191. package/src/utils/platformDisconnect.js +309 -0
  192. package/src/utils/pollTrainingStatus.js +200 -0
  193. package/src/utils/rawMemoriesAccess.js +211 -0
  194. package/src/utils/resolveBackendAppId.js +47 -0
  195. package/src/utils/responseFormatter.js +140 -0
  196. package/src/utils/sdkDebugStorage.js +113 -0
  197. package/src/utils/sdkInitialization.js +645 -0
  198. package/src/utils/sessionManager.js +1258 -0
  199. package/src/utils/startBackgroundTraining.js +100 -0
  200. package/src/utils/userDataFormatter.js +222 -0
  201. package/index.d.ts +0 -1
  202. package/index.js +0 -1
@@ -0,0 +1,897 @@
1
+ import React, { useEffect, useState, useRef } from 'react';
2
+ import Lottie from 'lottie-react';
3
+ import rainAnim from '../../public/rain-anim.json';
4
+ import io from 'socket.io-client';
5
+ import { API_CONFIG } from '../config/api-config';
6
+
7
+ const traitsPhrases = [
8
+ "Understanding you...",
9
+ "Aligning to your goals...",
10
+ "Learning your preferences...",
11
+ "Finding helpful patterns...",
12
+ "Almost ready..."
13
+ ];
14
+
15
+ const fullTrainingPhrases = [
16
+ "Understanding you...",
17
+ "Aligning to your goals...",
18
+ "Learning what matters to you...",
19
+ "Finding helpful patterns...",
20
+ "Personalizing your experience...",
21
+ "Getting things ready...",
22
+ "Almost ready..."
23
+ ];
24
+
25
+ const PREFLIGHT_TIMEOUT_MS = 5000;
26
+
27
+ const PLATFORM_DISPLAY_NAMES = {
28
+ chatgpt: 'ChatGPT',
29
+ claude: 'Claude',
30
+ facebook: 'Facebook',
31
+ gemini: 'Gemini',
32
+ github: 'GitHub',
33
+ gmail: 'Gmail',
34
+ google: 'Gmail',
35
+ grok: 'Grok',
36
+ instagram: 'Instagram',
37
+ linkedin: 'LinkedIn',
38
+ netflix: 'Netflix',
39
+ perplexity: 'Perplexity',
40
+ pinterest: 'Pinterest',
41
+ reddit: 'Reddit',
42
+ sephora: 'Sephora',
43
+ spotify: 'Spotify',
44
+ tiktok: 'TikTok',
45
+ twitter: 'X',
46
+ x: 'X',
47
+ youtube: 'YouTube',
48
+ };
49
+
50
+ const PLATFORM_TEXT_COLORS = {
51
+ chatgpt: '#10A37F',
52
+ claude: '#D97757',
53
+ facebook: '#1877F2',
54
+ gemini: '#4285F4',
55
+ github: '#24292F',
56
+ gmail: '#EA4335',
57
+ google: '#4285F4',
58
+ grok: '#111827',
59
+ instagram: '#C13584',
60
+ linkedin: '#0A66C2',
61
+ netflix: '#E50914',
62
+ perplexity: '#20808D',
63
+ pinterest: '#E60023',
64
+ reddit: '#FF4500',
65
+ sephora: '#111827',
66
+ spotify: '#1DB954',
67
+ tiktok: '#FE2C55',
68
+ twitter: '#111827',
69
+ x: '#111827',
70
+ youtube: '#FF0000',
71
+ };
72
+
73
+ const getPlatformKey = (value) => String(value || '').trim().toLowerCase().replace(/\s+/g, '-');
74
+
75
+ const getPlatformLabel = (value) => {
76
+ const raw = String(value || '').trim();
77
+ const key = getPlatformKey(raw);
78
+ if (!raw || /^\d+$/.test(raw)) return '';
79
+ return PLATFORM_DISPLAY_NAMES[key] || raw.charAt(0).toUpperCase() + raw.slice(1);
80
+ };
81
+
82
+ const getConnectedPlatformLabels = (accounts) => {
83
+ if (!Array.isArray(accounts)) return [];
84
+
85
+ const labels = [];
86
+ const seen = new Set();
87
+ accounts.forEach((account) => {
88
+ const source =
89
+ account && typeof account === 'object'
90
+ ? account.platform || account.displayName || account.name || account.connector || account.id || ''
91
+ : account;
92
+ const label = getPlatformLabel(source);
93
+ const key = getPlatformKey(label);
94
+ if (!label || seen.has(key)) return;
95
+ seen.add(key);
96
+ labels.push(label);
97
+ });
98
+
99
+ return labels;
100
+ };
101
+
102
+ const renderPlatformList = (platforms) =>
103
+ platforms.map((platform, index) => {
104
+ const key = getPlatformKey(platform);
105
+ const separator = index > 0 ? ', ' : '';
106
+ return (
107
+ <React.Fragment key={`${key}-${index}`}>
108
+ {separator}
109
+ <span style={{ color: PLATFORM_TEXT_COLORS[key] || '#374151', fontWeight: 700 }}>
110
+ {platform}
111
+ </span>
112
+ </React.Fragment>
113
+ );
114
+ });
115
+
116
+ const normalizeTrainingGuardFromSocket = (data) => {
117
+ if (!data || typeof data !== 'object') return null;
118
+ const rawCode = String(data.code || data.errorCode || '').toUpperCase();
119
+ const code =
120
+ data.requiresConnections === true
121
+ ? 'NO_CONNECTIONS'
122
+ : rawCode === 'CONNECTIONS_REQUIRED'
123
+ ? 'NO_CONNECTIONS'
124
+ : rawCode === 'NO_TRAINING_DATA' || rawCode === 'NO_DATA'
125
+ ? 'INSUFFICIENT_DATA'
126
+ : rawCode;
127
+
128
+ if (!['NO_CONNECTIONS', 'INSUFFICIENT_DATA', 'TRAITS_REGENERATING'].includes(code)) {
129
+ return null;
130
+ }
131
+
132
+ return {
133
+ success: false,
134
+ code,
135
+ error:
136
+ data.error ||
137
+ data.message ||
138
+ (code === 'NO_CONNECTIONS'
139
+ ? 'No connected platforms. Connect at least one account to continue.'
140
+ : code === 'INSUFFICIENT_DATA'
141
+ ? 'Not enough connected activity to personalize your experience.'
142
+ : 'Your experience is being refreshed.'),
143
+ retryable: true,
144
+ details: data.details || null,
145
+ raw: data,
146
+ };
147
+ };
148
+
149
+ const normalizeTrainingGuardFromHttp = (payload, { status, retryAfter, url } = {}) => {
150
+ if (!payload || typeof payload !== 'object' || payload.success !== false) return null;
151
+ const code = String(payload.code || payload.errorCode || '').toUpperCase();
152
+ if (!['NO_CONNECTIONS', 'INSUFFICIENT_DATA', 'TRAITS_REGENERATING'].includes(code)) {
153
+ return null;
154
+ }
155
+
156
+ return {
157
+ success: false,
158
+ code,
159
+ error:
160
+ payload.error ||
161
+ payload.message ||
162
+ (code === 'NO_CONNECTIONS'
163
+ ? 'No connected platforms. Connect at least one account to continue.'
164
+ : code === 'INSUFFICIENT_DATA'
165
+ ? 'Not enough connected activity to personalize your experience.'
166
+ : 'Your experience is being refreshed.'),
167
+ retryable: payload.retryable !== false,
168
+ status,
169
+ retryAfterSeconds: retryAfter ? Number(retryAfter) : undefined,
170
+ training: payload.training || payload.Training || undefined,
171
+ url,
172
+ raw: payload,
173
+ };
174
+ };
175
+
176
+ /**
177
+ * @param {object} props
178
+ * @param {'mock'|'fast'|'real'|'none'} [props.trainingScreenMode='fast']
179
+ * - `'mock'` — loading-screen UI with the real Socket.IO training path.
180
+ * - `'fast'` — real socket, completes when personality traits land (~30 s – 1 min).
181
+ * - `'real'` — real socket, waits for full MIND1 model training (~2 – 3 min).
182
+ * - `'none'` — defensive no-op render. Caller should not mount TrainingScreen
183
+ * in this mode; if it does, hooks still run but JSX is null.
184
+ */
185
+ export default function TrainingScreen({
186
+ onComplete,
187
+ onTrainingStart,
188
+ onBack,
189
+ userEmail,
190
+ connectedAccounts = [],
191
+ userToken,
192
+ fastTraits = true,
193
+ trainingScreenMode = 'fast',
194
+ appId = null,
195
+ webpageName = null,
196
+ trainingIntent = null,
197
+ insufficientDataReasoning = null,
198
+ }) {
199
+ const requiresPreferenceInference = !!(
200
+ trainingIntent?.requiresInference ||
201
+ trainingIntent?.requiresMbti ||
202
+ trainingIntent?.wantsPreferences
203
+ );
204
+ // Preference/MBTI requests need the sentiment model; do not leave on traits-only readiness.
205
+ const waitFor = trainingScreenMode === 'real' || requiresPreferenceInference ? 'full' : 'traits';
206
+ const phrases = waitFor === 'full' ? fullTrainingPhrases : traitsPhrases;
207
+ const [progress, setProgress] = useState(0);
208
+ const [currentPhrase, setCurrentPhrase] = useState(phrases[0]);
209
+ const [trainingWarning, setTrainingWarning] = useState(null);
210
+ const lottieRef = useRef(null);
211
+ const connectedPlatformLabels = getConnectedPlatformLabels(connectedAccounts);
212
+ const connectedAccountsSignature = connectedPlatformLabels
213
+ .sort()
214
+ .join('|');
215
+
216
+ const onCompleteRef = useRef(onComplete);
217
+ const onTrainingStartRef = useRef(onTrainingStart);
218
+ const trainingIntentRef = useRef(trainingIntent);
219
+ useEffect(() => { onCompleteRef.current = onComplete; }, [onComplete]);
220
+ useEffect(() => { onTrainingStartRef.current = onTrainingStart; }, [onTrainingStart]);
221
+ useEffect(() => { trainingIntentRef.current = trainingIntent; }, [trainingIntent]);
222
+
223
+ useEffect(() => {
224
+ // 'none' is a defensive no-op - callers should skip rendering this component
225
+ // entirely, but if they do mount it, do not open a socket or fake-complete.
226
+ if (trainingScreenMode === 'none') {
227
+ return undefined;
228
+ }
229
+ setTrainingWarning(null);
230
+
231
+ let socket = null;
232
+ let progressTimer = null;
233
+ let didSignalStart = false;
234
+ let watchdogTimer = null;
235
+ let hardStopTimer = null;
236
+ let phraseTimer = null;
237
+ let phraseIndex = 0;
238
+ let didComplete = false;
239
+ let didReceiveCompletionEvent = false;
240
+ let didSignalSufficiency = false;
241
+ let isCancelled = false;
242
+ const platformsForTraining = connectedAccountsSignature
243
+ ? connectedAccountsSignature.split('|').filter(Boolean)
244
+ : [];
245
+
246
+ const signalTrainingStarted = () => {
247
+ if (didSignalStart) return;
248
+ didSignalStart = true;
249
+ try {
250
+ onTrainingStartRef.current?.();
251
+ } catch (e) {
252
+ // never block training due to callback issues
253
+ }
254
+ };
255
+
256
+ // UI should stay vague; do NOT surface backend trainingUpdate/status strings.
257
+ const startVaguePhraseRotation = () => {
258
+ if (phraseTimer) return;
259
+ phraseTimer = setInterval(() => {
260
+ phraseIndex = (phraseIndex + 1) % phrases.length;
261
+ setCurrentPhrase(phrases[phraseIndex]);
262
+ }, 4000);
263
+ };
264
+
265
+ // Shorter watchdog on Capacitor: WKWebView WebSocket is less reliable and
266
+ // the backend often completes before we reconnect, so don't make the user wait 10 min.
267
+ const isCapacitor = !!(
268
+ typeof window !== 'undefined' &&
269
+ window?.Capacitor?.isNativePlatform?.()
270
+ );
271
+ const watchdogMs = isCapacitor ? 90 * 1000 : 10 * 60 * 1000;
272
+
273
+ const resetWatchdog = () => {
274
+ // We keep a long watchdog to avoid infinite hangs, but we do not scare the user
275
+ // and we do not auto-complete while backend is actively sending updates.
276
+ if (watchdogTimer) clearTimeout(watchdogTimer);
277
+ watchdogTimer = setTimeout(() => {
278
+ // Silent timeout -> complete with fallback so flow can proceed,
279
+ // but keep UI vague.
280
+ safeComplete({
281
+ fallback: true,
282
+ message: 'Training timed out (watchdog)',
283
+ autoCompleted: true
284
+ });
285
+ }, watchdogMs);
286
+ };
287
+
288
+ const safeComplete = (payload) => {
289
+ if (isCancelled) return;
290
+ if (didComplete) return;
291
+ didComplete = true;
292
+ try { if (progressTimer) clearInterval(progressTimer); } catch {}
293
+ try { if (watchdogTimer) clearTimeout(watchdogTimer); } catch {}
294
+ try { if (hardStopTimer) clearTimeout(hardStopTimer); } catch {}
295
+ try { if (phraseTimer) clearInterval(phraseTimer); } catch {}
296
+ try { if (socket) socket.disconnect(); } catch {}
297
+
298
+ try { setProgress(100); } catch {}
299
+ try { setCurrentPhrase('Finalizing...'); } catch {}
300
+ try {
301
+ if (typeof window !== 'undefined') {
302
+ window.dispatchEvent(new CustomEvent('onairos-training-end', {
303
+ detail: { status: payload?.error || payload?.fallback ? 'fallback' : 'complete', payload }
304
+ }));
305
+ }
306
+ } catch {}
307
+
308
+ setTimeout(() => {
309
+ try { onCompleteRef.current?.(payload); } catch {}
310
+ }, 500);
311
+ };
312
+
313
+ const signalSufficiency = (status, detail = {}) => {
314
+ if (status === 'sufficient' && didSignalSufficiency) return;
315
+ if (status === 'sufficient') didSignalSufficiency = true;
316
+ try {
317
+ if (typeof window !== 'undefined') {
318
+ window.dispatchEvent(new CustomEvent('onairos-training-sufficiency', {
319
+ detail: { status, ...detail }
320
+ }));
321
+ }
322
+ } catch (_) {}
323
+ };
324
+
325
+ const signalConnectorsCheckComplete = (data) => {
326
+ const detail = {
327
+ status: 'connectors_checked',
328
+ code: 'CONNECTORS_CHECK_COMPLETE',
329
+ details: data?.details || null,
330
+ raw: data,
331
+ };
332
+
333
+ try {
334
+ if (typeof window !== 'undefined') {
335
+ window.dispatchEvent(new CustomEvent('onairos-training-connectors-check-complete', { detail }));
336
+ window.dispatchEvent(new CustomEvent('onairos-data-connection-end', { detail }));
337
+ }
338
+ } catch (_) {}
339
+ };
340
+
341
+ const isBlockingTrainingGuard = (guard) => {
342
+ const code = String(guard?.code || '').toUpperCase();
343
+ return code === 'NO_CONNECTIONS' || code === 'INSUFFICIENT_DATA';
344
+ };
345
+
346
+ const completeWithTrainingGuard = (guard) => {
347
+ if (!guard) return false;
348
+ didComplete = true;
349
+ signalSufficiency('insufficient', {
350
+ code: guard.code,
351
+ error: guard.error,
352
+ guard,
353
+ });
354
+ try {
355
+ if (typeof window !== 'undefined') {
356
+ window.dispatchEvent(new CustomEvent('onairos-training-guard', { detail: guard }));
357
+ window.dispatchEvent(new CustomEvent('onairos-training-end', {
358
+ detail: { status: 'blocked', guard }
359
+ }));
360
+ }
361
+ } catch (_) {}
362
+ try { if (progressTimer) clearInterval(progressTimer); } catch {}
363
+ try { if (watchdogTimer) clearTimeout(watchdogTimer); } catch {}
364
+ try { if (hardStopTimer) clearTimeout(hardStopTimer); } catch {}
365
+ try { if (phraseTimer) clearInterval(phraseTimer); } catch {}
366
+ try { if (socket) socket.disconnect(); } catch {}
367
+ setProgress(100);
368
+ setCurrentPhrase('Not enough context yet');
369
+ setTrainingWarning(guard);
370
+ return true;
371
+ };
372
+
373
+ const hasSufficientPersonaPayload = (payload) => {
374
+ const traits =
375
+ payload?.traits ||
376
+ payload?.UserTraits?.DataAnalysis?.personality_traits ||
377
+ payload?.personality_traits ||
378
+ null;
379
+ const positive = traits?.positive_traits || traits?.positiveTraits || null;
380
+ const hasPositive = positive && typeof positive === 'object' && Object.keys(positive).length > 0;
381
+ return payload?.metadata?.hasPersonalityTraits === true && hasPositive;
382
+ };
383
+
384
+ const getAuthToken = () => {
385
+ if (userToken) return userToken;
386
+
387
+ try {
388
+ const storedToken = localStorage.getItem('onairos_user_token');
389
+ if (storedToken) return storedToken;
390
+ const storedUser = JSON.parse(localStorage.getItem('onairosUser') || '{}');
391
+ return storedUser.token || storedUser.jwtToken || null;
392
+ } catch (_) {
393
+ return null;
394
+ }
395
+ };
396
+
397
+ const runSufficiencyPreflight = async () => {
398
+ const token = getAuthToken();
399
+ if (!token) return { status: 'unknown' };
400
+
401
+ const url = `${API_CONFIG.getBaseUrl()}/persona/full?skipRegeneration=true`;
402
+ const controller = new AbortController();
403
+ const timeoutId = setTimeout(() => controller.abort(), PREFLIGHT_TIMEOUT_MS);
404
+
405
+ try {
406
+ const response = await fetch(url, {
407
+ method: 'GET',
408
+ headers: {
409
+ Authorization: `Bearer ${token}`,
410
+ 'Content-Type': 'application/json',
411
+ },
412
+ cache: 'no-store',
413
+ signal: controller.signal,
414
+ });
415
+
416
+ const payload = await response.clone().json().catch(() => null);
417
+ if (response.ok && hasSufficientPersonaPayload(payload)) {
418
+ return { status: 'sufficient', payload };
419
+ }
420
+
421
+ if (response.ok) {
422
+ return { status: 'unknown', payload };
423
+ }
424
+
425
+ const guard = normalizeTrainingGuardFromHttp(payload, {
426
+ status: response.status,
427
+ retryAfter: response.headers.get('Retry-After'),
428
+ url,
429
+ });
430
+
431
+ if (guard && guard.code !== 'TRAITS_REGENERATING') {
432
+ return { status: 'blocked', guard };
433
+ }
434
+
435
+ return { status: 'unknown', guard };
436
+ } catch (error) {
437
+ if (error?.name !== 'AbortError') {
438
+ console.warn('[TrainingScreen] Sufficiency preflight failed:', error?.message || error);
439
+ }
440
+ return { status: 'unknown' };
441
+ } finally {
442
+ clearTimeout(timeoutId);
443
+ }
444
+ };
445
+
446
+ const handlePreflightResult = (preflight) => {
447
+ if (preflight?.status === 'blocked') {
448
+ const guardCode = String(preflight.guard?.code || '').toUpperCase();
449
+
450
+ if (guardCode === 'INSUFFICIENT_DATA' && platformsForTraining.length > 0) {
451
+ signalSufficiency('preflight_insufficient', {
452
+ source: 'http-preflight',
453
+ code: guardCode,
454
+ guard: preflight.guard,
455
+ ignoredForSocketTraining: true,
456
+ connectedPlatforms: platformsForTraining,
457
+ });
458
+ return false;
459
+ }
460
+
461
+ return completeWithTrainingGuard(preflight.guard);
462
+ }
463
+
464
+ if (preflight?.status === 'sufficient') {
465
+ // REST preflight only proves traits already exist; it is not the backend's
466
+ // per-run data viability signal. Keep training and wait for SUFFICIENT_DATA.
467
+ return false;
468
+ }
469
+
470
+ return false;
471
+ };
472
+
473
+ // ACTUALLY run training + inference using Socket.IO
474
+ const runTrainingAndInference = async () => {
475
+ try {
476
+ const preflight = await runSufficiencyPreflight();
477
+ if (isCancelled) return;
478
+ if (handlePreflightResult(preflight)) return;
479
+
480
+ // Use token passed from parent component, fallback to localStorage
481
+ const token = getAuthToken();
482
+ if (isCancelled) return;
483
+
484
+ if (!token) {
485
+ throw new Error('No authentication token');
486
+ }
487
+
488
+ // Phase 1: Connect to Socket.IO
489
+ setCurrentPhrase(phrases[0]);
490
+ startVaguePhraseRotation();
491
+ resetWatchdog();
492
+
493
+ // Hard-stop: watchdog resets on updates; this one never resets.
494
+ // On Capacitor use 2 min (watchdog is 90s, so this is a safety net only).
495
+ if (hardStopTimer) clearTimeout(hardStopTimer);
496
+ hardStopTimer = setTimeout(() => {
497
+ safeComplete({
498
+ fallback: true,
499
+ message: 'Training timed out (hard stop)',
500
+ autoCompleted: true
501
+ });
502
+ }, isCapacitor ? 2 * 60 * 1000 : 12 * 60 * 1000);
503
+
504
+ // Get API base URL from config (handles internship.onairos.uk -> api2.onairos.uk)
505
+ const apiBaseUrl = API_CONFIG.getBaseUrl();
506
+ if (isCancelled) return;
507
+
508
+ socket = io(apiBaseUrl, {
509
+ auth: { token },
510
+ transports: ['websocket'], // Force WebSocket to avoid sticky session issues (400 on polling)
511
+ reconnection: true,
512
+ reconnectionAttempts: 10,
513
+ timeout: 20000
514
+ });
515
+
516
+ // Handle connection
517
+ socket.on('connect', () => {
518
+ // At this point, training can actually start (server reachable).
519
+ signalTrainingStarted();
520
+ startVaguePhraseRotation();
521
+ resetWatchdog();
522
+
523
+ // Start progress animation (slow + steady; completion comes from backend event)
524
+ progressTimer = setInterval(() => {
525
+ setProgress(prev => {
526
+ if (prev < 95) return prev + 0.5; // Slower progress
527
+ return prev;
528
+ });
529
+ }, 300);
530
+
531
+ // Trigger training
532
+ socket.emit('start-training', {
533
+ socketId: socket.id,
534
+ email: userEmail,
535
+ username: userEmail,
536
+ platforms: platformsForTraining,
537
+ connectedAccounts: platformsForTraining,
538
+ appId: appId || null,
539
+ webpageName: webpageName || null,
540
+ Options: {
541
+ fastTraits,
542
+ trainingIntent: trainingIntentRef.current
543
+ }
544
+ });
545
+ resetWatchdog();
546
+ });
547
+
548
+ // Handle training progress updates
549
+ socket.on('training-progress', (data) => {
550
+ // Progress events mean training has definitely started.
551
+ signalTrainingStarted();
552
+ startVaguePhraseRotation();
553
+ resetWatchdog();
554
+
555
+ if (data.percentage) {
556
+ setProgress(Math.min(data.percentage, 95)); // Cap at 95% until complete
557
+ }
558
+ });
559
+
560
+ // Handle training updates (legacy event name from old mobile SDK)
561
+ socket.on('trainingUpdate', (data) => {
562
+ // We are receiving backend updates; reset watchdog so we don't timeout mid-training.
563
+ startVaguePhraseRotation();
564
+ resetWatchdog();
565
+
566
+ const rawCode = String(data?.code || data?.errorCode || '').toUpperCase();
567
+ if (rawCode === 'SUFFICIENT_DATA') {
568
+ signalSufficiency('sufficient', {
569
+ source: 'socket',
570
+ details: data.details || null,
571
+ raw: data,
572
+ });
573
+ return;
574
+ }
575
+ if (rawCode === 'CONNECTORS_CHECK_COMPLETE') {
576
+ signalConnectorsCheckComplete(data);
577
+ setProgress(prev => Math.max(prev, 25));
578
+ return;
579
+ }
580
+
581
+ const guard = normalizeTrainingGuardFromSocket(data);
582
+ if (guard && (isBlockingTrainingGuard(guard) || data.error || data.requiresConnections === true)) {
583
+ completeWithTrainingGuard(guard);
584
+ return;
585
+ }
586
+
587
+ // In traits-only mode, complete as soon as personality analysis finishes.
588
+ // Traits are already written to MongoDB at this point by the backend.
589
+ // Model training continues in the background but we don't block on it.
590
+ if (waitFor === 'traits' && data.stage === 'personality_analysis_complete') {
591
+ didReceiveCompletionEvent = true;
592
+ safeComplete({ success: true, traitsOnly: true });
593
+ return;
594
+ }
595
+
596
+ // Check if this is an error
597
+ if (data.error) {
598
+ if (progressTimer) clearInterval(progressTimer);
599
+ if (watchdogTimer) clearTimeout(watchdogTimer);
600
+ if (phraseTimer) clearInterval(phraseTimer);
601
+
602
+ setProgress(100);
603
+ setCurrentPhrase('Finalizing...');
604
+
605
+ socket.disconnect();
606
+
607
+ setTimeout(() => {
608
+ // Complete anyway with fallback flag
609
+ safeComplete({
610
+ error: data.error,
611
+ errorCode: data.code,
612
+ errorDetails: data.details,
613
+ fallback: true
614
+ });
615
+ }, 500);
616
+ return;
617
+ }
618
+ });
619
+
620
+ // Handle old training completion event (trainingCompleted)
621
+ socket.on('trainingCompleted', (result) => {
622
+ if (result?.mode === 'personality_only') {
623
+ didReceiveCompletionEvent = true;
624
+ safeComplete({ ...(result || {}), success: true, traitsOnly: true });
625
+ return;
626
+ }
627
+ // In traits-only mode, ignore this event — we complete on
628
+ // personality_analysis_complete instead, which fires earlier.
629
+ if (waitFor === 'traits') return;
630
+ didReceiveCompletionEvent = true;
631
+ safeComplete(result || { success: true, fallback: false });
632
+ });
633
+
634
+ // Handle training completion
635
+ socket.on('training-complete', (result) => {
636
+ // In traits-only mode, ignore — personality_analysis_complete is the exit.
637
+ if (waitFor === 'traits') return;
638
+ didReceiveCompletionEvent = true;
639
+
640
+ // Clear timers
641
+ if (progressTimer) clearInterval(progressTimer);
642
+ if (watchdogTimer) clearTimeout(watchdogTimer);
643
+ if (phraseTimer) clearInterval(phraseTimer);
644
+
645
+ setProgress(100);
646
+ setCurrentPhrase('Finalizing...');
647
+
648
+ // Complete (safeComplete will disconnect + guard)
649
+ safeComplete(result);
650
+ });
651
+
652
+ // Handle errors
653
+ socket.on('training-error', (error) => {
654
+ const guard = normalizeTrainingGuardFromSocket(error);
655
+ if (completeWithTrainingGuard(guard)) return;
656
+ safeComplete({
657
+ error: error?.message || 'Training failed',
658
+ fallback: true
659
+ });
660
+ });
661
+
662
+ socket.on('trainingError', (error) => {
663
+ const guard = normalizeTrainingGuardFromSocket(error);
664
+ if (completeWithTrainingGuard(guard)) return;
665
+ safeComplete({
666
+ error: error?.message || error?.error || 'Training failed',
667
+ fallback: true
668
+ });
669
+ });
670
+
671
+ // Handle connection errors
672
+ socket.on('connect_error', (error) => {
673
+ console.warn('Socket connection error:', error);
674
+ // Only complete if we are not actively trying to reconnect
675
+ if (!socket.active) {
676
+ safeComplete({
677
+ error: 'Failed to connect to training server',
678
+ fallback: true
679
+ });
680
+ }
681
+ });
682
+
683
+ // Handle reconnection failure (via Manager)
684
+ socket.io.on("reconnect_failed", () => {
685
+ safeComplete({
686
+ error: 'Failed to connect to training server (reconnect failed)',
687
+ fallback: true
688
+ });
689
+ });
690
+
691
+ // If the socket had to reconnect, the backend already sent training-complete to the
692
+ // old socket ID and won't resend it — so we'll never receive the event.
693
+ // Complete with fallback immediately on reconnect to unblock the user.
694
+ socket.io.on("reconnect", () => {
695
+ safeComplete({
696
+ fallback: true,
697
+ message: 'Socket reconnected after disconnect — training-complete was likely already sent',
698
+ autoCompleted: true
699
+ });
700
+ });
701
+
702
+ // Handle disconnect
703
+ socket.on('disconnect', (reason) => {
704
+ // Avoid racing the success path: we intentionally disconnect on success.
705
+ // Only auto-complete on disconnect if we never got a completion event and it's not our own disconnect.
706
+ if (didComplete) return;
707
+ if (didReceiveCompletionEvent) return;
708
+ if (reason === 'io client disconnect') return;
709
+ setTimeout(() => {
710
+ if (didComplete) return;
711
+ if (didReceiveCompletionEvent) return;
712
+ safeComplete({
713
+ fallback: true,
714
+ message: `Socket disconnected before completion (${reason || 'unknown'})`,
715
+ autoCompleted: true
716
+ });
717
+ }, 750);
718
+ });
719
+
720
+ } catch (error) {
721
+ safeComplete({
722
+ error: error?.message,
723
+ fallback: true
724
+ });
725
+ }
726
+ };
727
+
728
+ runTrainingAndInference();
729
+
730
+ // Cleanup on unmount
731
+ return () => {
732
+ isCancelled = true;
733
+ if (progressTimer) clearInterval(progressTimer);
734
+ if (watchdogTimer) clearTimeout(watchdogTimer);
735
+ if (hardStopTimer) clearTimeout(hardStopTimer);
736
+ if (phraseTimer) clearInterval(phraseTimer);
737
+ if (socket) {
738
+ socket.disconnect();
739
+ }
740
+ };
741
+ }, [userEmail, connectedAccountsSignature, userToken, fastTraits, waitFor, phrases, trainingScreenMode, appId, webpageName]);
742
+
743
+ // Defensive no-op render for 'none'. Hooks above always run so order is stable.
744
+ if (trainingScreenMode === 'none') {
745
+ return null;
746
+ }
747
+
748
+ if (trainingWarning) {
749
+ const appLabel =
750
+ typeof webpageName === 'string' && webpageName.trim()
751
+ ? webpageName.trim()
752
+ : 'This app';
753
+ const reasoning =
754
+ typeof insufficientDataReasoning === 'string' && insufficientDataReasoning.trim()
755
+ ? insufficientDataReasoning.trim()
756
+ : `${appLabel} needs to understand you better for your experience.`;
757
+ const activityTarget =
758
+ connectedPlatformLabels.length > 0
759
+ ? <> in {renderPlatformList(connectedPlatformLabels)}</>
760
+ : ' in your connected apps';
761
+ return (
762
+ <div className="h-full w-full flex flex-col items-center justify-center px-4 sm:px-6 py-4" style={{ minHeight: 400 }}>
763
+ <div
764
+ className="w-full max-w-md flex flex-col items-center text-center rounded-[28px] border border-gray-100 bg-white px-6 py-8 sm:px-8 sm:py-10 shadow-sm"
765
+ style={{
766
+ minHeight: 480,
767
+ justifyContent: 'center',
768
+ gap: 20
769
+ }}
770
+ >
771
+ <div
772
+ className="flex items-center justify-center rounded-full bg-amber-50 border border-amber-100 text-amber-700 shadow-[0_10px_30px_rgba(245,158,11,0.12)]"
773
+ style={{ width: 58, height: 58, fontSize: 28, fontWeight: 700 }}
774
+ aria-hidden="true"
775
+ >
776
+ !
777
+ </div>
778
+
779
+ <div>
780
+ <h2
781
+ className="text-xl sm:text-2xl font-semibold text-gray-950"
782
+ style={{
783
+ fontFamily: 'IBM Plex Sans, system-ui, sans-serif',
784
+ lineHeight: 1.2,
785
+ maxWidth: 380
786
+ }}
787
+ >
788
+ Please connect more apps
789
+ </h2>
790
+ <p
791
+ className="mt-3 text-sm sm:text-base text-gray-600"
792
+ style={{ fontFamily: 'IBM Plex Sans, system-ui, sans-serif', lineHeight: 1.55, maxWidth: 380 }}
793
+ >
794
+ We could not find enough activity{activityTarget} to continue.
795
+ </p>
796
+ <div
797
+ className="mt-4 rounded-2xl border border-gray-100 bg-gray-50 px-4 py-3 text-left"
798
+ style={{ maxWidth: 380 }}
799
+ >
800
+ <p
801
+ className="text-[11px] font-semibold uppercase tracking-[0.16em] text-gray-400"
802
+ style={{ fontFamily: 'IBM Plex Sans, system-ui, sans-serif' }}
803
+ >
804
+ Reasoning
805
+ </p>
806
+ <p
807
+ className="mt-1 text-sm text-gray-700"
808
+ style={{ fontFamily: 'IBM Plex Sans, system-ui, sans-serif', lineHeight: 1.5 }}
809
+ >
810
+ {reasoning}
811
+ </p>
812
+ </div>
813
+ </div>
814
+
815
+ {typeof onBack === 'function' ? (
816
+ <button
817
+ type="button"
818
+ onClick={onBack}
819
+ className="w-full sm:w-auto rounded-full bg-gray-950 hover:bg-gray-800 text-white px-7 py-3.5 text-sm font-semibold transition-colors shadow-[0_12px_28px_rgba(17,24,39,0.18)]"
820
+ style={{ fontFamily: 'IBM Plex Sans, system-ui, sans-serif', maxWidth: 320 }}
821
+ >
822
+ Connect more apps
823
+ </button>
824
+ ) : null}
825
+ </div>
826
+ </div>
827
+ );
828
+ }
829
+
830
+ return (
831
+ <div className="h-full w-full flex flex-col items-center justify-center px-6 py-4" style={{ minHeight: 400 }}>
832
+ {/* Fixed layout container to prevent shifting when phrases change */}
833
+ <div
834
+ className="w-full max-w-md flex flex-col items-center"
835
+ style={{
836
+ // Keep consistent vertical rhythm across devices
837
+ minHeight: 520,
838
+ justifyContent: 'center',
839
+ gap: 18
840
+ }}
841
+ >
842
+ {/* Vague message only (never show backend training/inference details) */}
843
+ <div className="text-center" style={{ minHeight: 56, display: 'flex', alignItems: 'center' }}>
844
+ <h2
845
+ className="text-xl md:text-2xl font-semibold text-gray-900"
846
+ style={{
847
+ fontFamily: 'IBM Plex Sans, system-ui, sans-serif',
848
+ lineHeight: 1.2,
849
+ maxWidth: 360
850
+ }}
851
+ >
852
+ {currentPhrase}
853
+ </h2>
854
+ </div>
855
+
856
+ {/* Lottie Animation */}
857
+ <div className="w-full flex items-center justify-center" style={{ height: 300 }}>
858
+ <div className="relative" style={{ width: 300, height: 300 }}>
859
+ <Lottie
860
+ lottieRef={lottieRef}
861
+ animationData={rainAnim}
862
+ loop={true}
863
+ autoplay={true}
864
+ className="absolute inset-0"
865
+ style={{ width: '100%', height: '100%' }}
866
+ />
867
+ </div>
868
+ </div>
869
+
870
+ {/* Black and White Loading Bar - Below Lottie */}
871
+ <div className="w-full" style={{ maxWidth: 360 }}>
872
+ <div className="relative w-full h-1.5 bg-gray-200 rounded-full overflow-hidden">
873
+ <div
874
+ className="absolute top-0 left-0 h-full bg-gray-900 rounded-full transition-all duration-300 ease-out"
875
+ style={{
876
+ width: `${progress}%`
877
+ }}
878
+ />
879
+ </div>
880
+ <p
881
+ className="mt-3 text-center text-xs md:text-sm text-gray-400"
882
+ style={{ fontFamily: 'IBM Plex Sans, system-ui, sans-serif', lineHeight: 1.4 }}
883
+ >
884
+ This usually takes about a minute - sit tight!
885
+ </p>
886
+ </div>
887
+
888
+ </div>
889
+ <div
890
+ className="mt-auto pt-6 text-center text-sm text-gray-300"
891
+ style={{ fontFamily: 'IBM Plex Sans, system-ui, sans-serif', letterSpacing: '0.01em' }}
892
+ >
893
+ Onairos
894
+ </div>
895
+ </div>
896
+ );
897
+ }