ft-scout 6.0.8 → 7.0.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.
package/web/app.js CHANGED
@@ -3,443 +3,456 @@
3
3
  ========================================================================== */
4
4
 
5
5
  const FIREBASE_CONFIG = {
6
- apiKey: 'AIzaSyCMVNDgR8EejfXofUy87L7hsKxi3E_C3lg',
7
- projectId: 'frontterrain',
8
- tenantId: 'ft-scout-auth-gc2v5',
9
- baseAuthUrl: 'https://identitytoolkit.googleapis.com/v1/accounts',
6
+ apiKey: 'AIzaSyCMVNDgR8EejfXofUy87L7hsKxi3E_C3lg',
7
+ projectId: 'frontterrain',
8
+ tenantId: 'ft-scout-auth-gc2v5',
9
+ baseAuthUrl: 'https://identitytoolkit.googleapis.com/v1/accounts',
10
10
  };
11
11
 
12
12
  // Tier Configuration Details
13
13
  const TIER_DETAILS = {
14
- free: {
15
- name: 'Developer Free Tier',
16
- badge: 'ACTIVE',
17
- desc: 'Standard access to Scout CLI features & local execution.',
18
- icon: '<i class="fa-solid fa-star text-warning" style="font-size: 24px;"></i>',
19
- },
20
- pro: {
21
- name: 'Pro Developer Tier',
22
- badge: 'PRO ACTIVE',
23
- desc: 'High-power AI co-pilot capabilities, priority quota & 5 active CLI sessions.',
24
- icon: '<i class="fa-solid fa-bolt text-primary" style="font-size: 24px;"></i>',
25
- },
26
- enterprise: {
27
- name: 'Team & Enterprise Tier',
28
- badge: 'ENTERPRISE ACTIVE',
29
- desc: 'Organization controls, security policies & dedicated scale.',
30
- icon: '<i class="fa-solid fa-building text-warning" style="font-size: 24px;"></i>',
31
- },
14
+ free: {
15
+ name: 'Developer Free Tier',
16
+ badge: 'ACTIVE',
17
+ desc: 'Standard access to Scout CLI features & local execution.',
18
+ icon: '<i class="fa-solid fa-star text-warning" style="font-size: 24px;"></i>',
19
+ },
20
+ pro: {
21
+ name: 'Pro Developer Tier',
22
+ badge: 'PRO ACTIVE',
23
+ desc: 'High-power AI co-pilot capabilities, priority quota & 5 active CLI sessions.',
24
+ icon: '<i class="fa-solid fa-bolt text-primary" style="font-size: 24px;"></i>',
25
+ },
26
+ enterprise: {
27
+ name: 'Team & Enterprise Tier',
28
+ badge: 'ENTERPRISE ACTIVE',
29
+ desc: 'Organization controls, security policies & dedicated scale.',
30
+ icon: '<i class="fa-solid fa-building text-warning" style="font-size: 24px;"></i>',
31
+ },
32
32
  };
33
33
 
34
34
  // Global Application State
35
35
  let state = {
36
- user: null,
37
- token: null,
38
- refreshToken: null,
39
- activeTab: 'account',
40
- serverConnected: false,
41
- apiBaseUrl: '',
42
- sessions: [],
43
- currentTier: 'free',
44
- billingCycle: 'monthly',
45
- creditsUsed: 0,
46
- creditsTotal: 100,
47
- renewAt: null,
48
- byokEnabled: false,
49
- customLlmProvider: 'gemini',
50
- customApiKey: '',
51
- customBaseUrl: '',
36
+ user: null,
37
+ token: null,
38
+ refreshToken: null,
39
+ activeTab: 'account',
40
+ serverConnected: false,
41
+ apiBaseUrl: '',
42
+ sessions: [],
43
+ currentTier: 'free',
44
+ billingCycle: 'monthly',
45
+ creditsUsed: 0,
46
+ creditsTotal: 100,
47
+ renewAt: null,
48
+ byokEnabled: false,
49
+ customLlmProvider: 'gemini',
50
+ customApiKey: '',
51
+ customBaseUrl: '',
52
52
  };
53
53
 
54
54
  let pendingCheckoutTier = null;
55
55
 
56
56
  // DOM Elements Reference
57
57
  const elements = {
58
- // Views
59
- authSection: document.getElementById('auth-section'),
60
- dashboardSection: document.getElementById('dashboard-section'),
61
-
62
- // Auth Controls
63
- tabLoginBtn: document.getElementById('tab-login-btn'),
64
- tabSignupBtn: document.getElementById('tab-signup-btn'),
65
- loginForm: document.getElementById('login-form'),
66
- signupForm: document.getElementById('signup-form'),
67
- btnOpenAuth: document.getElementById('btn-open-auth'),
68
- btnDemoMode: document.getElementById('btn-demo-mode'),
69
- btnForgotPwd: document.getElementById('btn-forgot-pwd'),
70
-
71
- // Navigation & User Menu
72
- mainNav: document.getElementById('main-nav'),
73
- userMenu: document.getElementById('user-menu'),
74
- userMenuToggle: document.getElementById('user-menu-toggle'),
75
- userDropdown: document.getElementById('user-dropdown'),
76
- navAvatar: document.getElementById('nav-avatar'),
77
- navUserName: document.getElementById('nav-user-name'),
78
- dropdownName: document.getElementById('dropdown-name'),
79
- dropdownEmail: document.getElementById('dropdown-email'),
80
- btnDropdownLogout: document.getElementById('btn-dropdown-logout'),
81
- btnDropdownProfile: document.getElementById('btn-dropdown-profile'),
82
- btnDropdownTiers: document.getElementById('btn-dropdown-tiers'),
83
- navTenantTag: document.getElementById('nav-tenant-tag'),
84
- navTenantName: document.getElementById('nav-tenant-name'),
85
-
86
- // Account & Header Controls
87
- userDisplayName: document.getElementById('user-display-name'),
88
- btnNavTiersHero: document.getElementById('btn-nav-tiers-hero'),
89
- sessionTableBody: document.getElementById('session-table-body'),
90
-
91
- // Credit Quota & Usage Controls
92
- valCreditsUsed: document.getElementById('val-credits-used'),
93
- valCreditsRemaining: document.getElementById('val-credits-remaining'),
94
- valCreditsTotal: document.getElementById('val-credits-total'),
95
- valCreditsPct: document.getElementById('val-credits-pct'),
96
- creditProgressFill: document.getElementById('credit-progress-fill'),
97
- valRenewDatetime: document.getElementById('val-renew-datetime'),
98
- btnUpgradeCreditsHero: document.getElementById('btn-upgrade-credits-hero'),
99
- creditStatusBadge: document.getElementById('credit-status-badge'),
100
- labelCreditConsumption: document.getElementById('label-credit-consumption'),
101
- byokBannerNote: document.getElementById('byok-banner-note'),
102
-
103
- // BYOK & Custom Proxy Endpoint Inputs
104
- byokForm: document.getElementById('byok-form'),
105
- selectByokProvider: document.getElementById('select-byok-provider'),
106
- inputByokEndpoint: document.getElementById('input-byok-endpoint'),
107
- inputByokKey: document.getElementById('input-byok-key'),
108
- checkboxEnableByok: document.getElementById('checkbox-enable-byok'),
109
- byokStatusBadge: document.getElementById('byok-status-badge'),
110
-
111
- // Profile Settings Inputs
112
- settingsDisplayName: document.getElementById('settings-display-name'),
113
- settingsEmail: document.getElementById('settings-email'),
114
- settingsUid: document.getElementById('settings-uid'),
115
- settingsActiveTier: document.getElementById('settings-active-tier'),
116
- profileForm: document.getElementById('profile-form'),
117
- btnAccountLogout: document.getElementById('btn-account-logout'),
118
-
119
- // Paid Tiers UI
120
- currentPlanTitle: document.getElementById('current-plan-title'),
121
- currentPlanBadge: document.getElementById('current-plan-badge'),
122
- currentPlanDesc: document.getElementById('current-plan-desc'),
123
- tierActiveIcon: document.getElementById('tier-active-icon'),
124
- toggleBillingCycle: document.getElementById('toggle-billing-cycle'),
125
- priceProVal: document.getElementById('price-pro-val'),
126
- priceProPeriod: document.getElementById('price-pro-period'),
127
- priceEntVal: document.getElementById('price-ent-val'),
128
- priceEntPeriod: document.getElementById('price-ent-period'),
129
-
130
- // Checkout Modal Controls
131
- checkoutModal: document.getElementById('checkout-modal'),
132
- checkoutModalTitle: document.getElementById('checkout-modal-title'),
133
- checkoutPlanName: document.getElementById('checkout-plan-name'),
134
- checkoutBillingCycle: document.getElementById('checkout-billing-cycle'),
135
- checkoutPlanPrice: document.getElementById('checkout-plan-price'),
136
- checkoutPricePeriod: document.getElementById('checkout-price-period'),
137
- checkoutQuotaVal: document.getElementById('checkout-quota-val'),
138
- btnCloseCheckout: document.getElementById('btn-close-checkout'),
139
- btnCancelCheckout: document.getElementById('btn-cancel-checkout'),
140
- btnConfirmCheckout: document.getElementById('btn-confirm-checkout'),
141
-
142
- // Toast Container
143
- toastContainer: document.getElementById('toast-container'),
58
+ // Views
59
+ authSection: document.getElementById('auth-section'),
60
+ dashboardSection: document.getElementById('dashboard-section'),
61
+
62
+ // Auth Controls
63
+ tabLoginBtn: document.getElementById('tab-login-btn'),
64
+ tabSignupBtn: document.getElementById('tab-signup-btn'),
65
+ loginForm: document.getElementById('login-form'),
66
+ signupForm: document.getElementById('signup-form'),
67
+ btnOpenAuth: document.getElementById('btn-open-auth'),
68
+ btnDemoMode: document.getElementById('btn-demo-mode'),
69
+ btnForgotPwd: document.getElementById('btn-forgot-pwd'),
70
+
71
+ // Navigation & User Menu
72
+ mainNav: document.getElementById('main-nav'),
73
+ userMenu: document.getElementById('user-menu'),
74
+ userMenuToggle: document.getElementById('user-menu-toggle'),
75
+ userDropdown: document.getElementById('user-dropdown'),
76
+ navAvatar: document.getElementById('nav-avatar'),
77
+ navUserName: document.getElementById('nav-user-name'),
78
+ dropdownName: document.getElementById('dropdown-name'),
79
+ dropdownEmail: document.getElementById('dropdown-email'),
80
+ btnDropdownLogout: document.getElementById('btn-dropdown-logout'),
81
+ btnDropdownProfile: document.getElementById('btn-dropdown-profile'),
82
+ btnDropdownTiers: document.getElementById('btn-dropdown-tiers'),
83
+ navTenantTag: document.getElementById('nav-tenant-tag'),
84
+ navTenantName: document.getElementById('nav-tenant-name'),
85
+
86
+ // Account & Header Controls
87
+ userDisplayName: document.getElementById('user-display-name'),
88
+ btnNavTiersHero: document.getElementById('btn-nav-tiers-hero'),
89
+ sessionTableBody: document.getElementById('session-table-body'),
90
+
91
+ // Credit Quota & Usage Controls
92
+ valCreditsUsed: document.getElementById('val-credits-used'),
93
+ valCreditsRemaining: document.getElementById('val-credits-remaining'),
94
+ valCreditsTotal: document.getElementById('val-credits-total'),
95
+ valCreditsPct: document.getElementById('val-credits-pct'),
96
+ creditProgressFill: document.getElementById('credit-progress-fill'),
97
+ valRenewDatetime: document.getElementById('val-renew-datetime'),
98
+ btnUpgradeCreditsHero: document.getElementById('btn-upgrade-credits-hero'),
99
+ creditStatusBadge: document.getElementById('credit-status-badge'),
100
+ labelCreditConsumption: document.getElementById('label-credit-consumption'),
101
+ byokBannerNote: document.getElementById('byok-banner-note'),
102
+
103
+ // BYOK & Custom Proxy Endpoint Inputs
104
+ byokForm: document.getElementById('byok-form'),
105
+ selectByokProvider: document.getElementById('select-byok-provider'),
106
+ inputByokEndpoint: document.getElementById('input-byok-endpoint'),
107
+ inputByokKey: document.getElementById('input-byok-key'),
108
+ checkboxEnableByok: document.getElementById('checkbox-enable-byok'),
109
+ byokStatusBadge: document.getElementById('byok-status-badge'),
110
+
111
+ // Profile Settings Inputs
112
+ settingsDisplayName: document.getElementById('settings-display-name'),
113
+ settingsEmail: document.getElementById('settings-email'),
114
+ settingsUid: document.getElementById('settings-uid'),
115
+ settingsActiveTier: document.getElementById('settings-active-tier'),
116
+ profileForm: document.getElementById('profile-form'),
117
+ btnAccountLogout: document.getElementById('btn-account-logout'),
118
+
119
+ // Paid Tiers UI
120
+ currentPlanTitle: document.getElementById('current-plan-title'),
121
+ currentPlanBadge: document.getElementById('current-plan-badge'),
122
+ currentPlanDesc: document.getElementById('current-plan-desc'),
123
+ tierActiveIcon: document.getElementById('tier-active-icon'),
124
+ toggleBillingCycle: document.getElementById('toggle-billing-cycle'),
125
+ priceProVal: document.getElementById('price-pro-val'),
126
+ priceProPeriod: document.getElementById('price-pro-period'),
127
+ priceEntVal: document.getElementById('price-ent-val'),
128
+ priceEntPeriod: document.getElementById('price-ent-period'),
129
+
130
+ // Checkout Modal Controls
131
+ checkoutModal: document.getElementById('checkout-modal'),
132
+ checkoutModalTitle: document.getElementById('checkout-modal-title'),
133
+ checkoutPlanName: document.getElementById('checkout-plan-name'),
134
+ checkoutBillingCycle: document.getElementById('checkout-billing-cycle'),
135
+ checkoutPlanPrice: document.getElementById('checkout-plan-price'),
136
+ checkoutPricePeriod: document.getElementById('checkout-price-period'),
137
+ checkoutQuotaVal: document.getElementById('checkout-quota-val'),
138
+ btnCloseCheckout: document.getElementById('btn-close-checkout'),
139
+ btnCancelCheckout: document.getElementById('btn-cancel-checkout'),
140
+ btnConfirmCheckout: document.getElementById('btn-confirm-checkout'),
141
+
142
+ // Toast Container
143
+ toastContainer: document.getElementById('toast-container'),
144
144
  };
145
145
 
146
146
  // Initialize Application
147
147
  document.addEventListener('DOMContentLoaded', async () => {
148
- loadTierAndCreditsFromStorage();
149
- loadSessionsFromStorage();
150
- initEventListeners();
151
- renderAllDynamicComponents();
152
- await checkServerStatusAndSession();
148
+ loadTierAndCreditsFromStorage();
149
+ loadSessionsFromStorage();
150
+ initEventListeners();
151
+ renderAllDynamicComponents();
152
+ await checkServerStatusAndSession();
153
153
  });
154
154
 
155
155
  // Time Helper Function for Dynamic Relative Timestamps
156
156
  function timeAgo(dateInput) {
157
- if (!dateInput) return 'Just now';
158
- const date = new Date(dateInput);
159
- if (isNaN(date.getTime())) return String(dateInput);
160
-
161
- const now = new Date();
162
- const seconds = Math.floor((now - date) / 1000);
163
- if (seconds < 45) return 'Just now';
164
- const minutes = Math.floor(seconds / 60);
165
- if (minutes < 60) return `${minutes}m ago`;
166
- const hours = Math.floor(minutes / 60);
167
- if (hours < 24) return `${hours}h ago`;
168
- const days = Math.floor(hours / 24);
169
- return `${days}d ago`;
157
+ if (!dateInput) return 'Just now';
158
+ const date = new Date(dateInput);
159
+ if (isNaN(date.getTime())) return String(dateInput);
160
+
161
+ const now = new Date();
162
+ const seconds = Math.floor((now - date) / 1000);
163
+ if (seconds < 45) return 'Just now';
164
+ const minutes = Math.floor(seconds / 60);
165
+ if (minutes < 60) return `${minutes}m ago`;
166
+ const hours = Math.floor(minutes / 60);
167
+ if (hours < 24) return `${hours}h ago`;
168
+ const days = Math.floor(hours / 24);
169
+ return `${days}d ago`;
170
170
  }
171
171
 
172
172
  // Load Subscription Tier & Dynamic Credits from Local Storage / Config
173
173
  function loadTierAndCreditsFromStorage() {
174
- const savedTier = localStorage.getItem('scout_current_tier');
175
- if (savedTier && TIER_DETAILS[savedTier]) {
176
- state.currentTier = savedTier;
177
- }
178
-
179
- const savedUsed = localStorage.getItem('scout_credits_used');
180
- if (savedUsed !== null) {
181
- state.creditsUsed = parseInt(savedUsed, 10) || 0;
182
- } else {
183
- state.creditsUsed = 0;
184
- }
185
-
186
- const savedTotal = localStorage.getItem('scout_credits_total');
187
- if (savedTotal !== null) {
188
- state.creditsTotal = parseInt(savedTotal, 10) || 100;
189
- } else {
190
- state.creditsTotal = state.currentTier === 'pro' ? 1000 : state.currentTier === 'enterprise' ? 10000 : 100;
191
- }
192
-
193
- const savedRenew = localStorage.getItem('scout_renew_at');
194
- if (savedRenew) {
195
- state.renewAt = savedRenew;
196
- } else {
197
- const now = new Date();
198
- state.renewAt = new Date(now.getFullYear(), now.getMonth() + 1, 1, 0, 0, 0).toISOString();
199
- }
200
-
201
- state.byokEnabled = localStorage.getItem('scout_byok_enabled') === 'true';
202
- state.customLlmProvider = localStorage.getItem('scout_byok_provider') || 'gemini';
203
- state.customApiKey = localStorage.getItem('scout_byok_key') || '';
204
- state.customBaseUrl = localStorage.getItem('scout_byok_endpoint') || '';
174
+ const savedTier = localStorage.getItem('scout_current_tier');
175
+ if (savedTier && TIER_DETAILS[savedTier]) {
176
+ state.currentTier = savedTier;
177
+ }
178
+
179
+ const savedUsed = localStorage.getItem('scout_credits_used');
180
+ if (savedUsed !== null) {
181
+ state.creditsUsed = parseInt(savedUsed, 10) || 0;
182
+ } else {
183
+ state.creditsUsed = 0;
184
+ }
185
+
186
+ const savedTotal = localStorage.getItem('scout_credits_total');
187
+ if (savedTotal !== null) {
188
+ state.creditsTotal = parseInt(savedTotal, 10) || 100;
189
+ } else {
190
+ state.creditsTotal = state.currentTier === 'pro' ? 1000 : state.currentTier === 'enterprise' ? 10000 : 100;
191
+ }
192
+
193
+ const savedRenew = localStorage.getItem('scout_renew_at');
194
+ if (savedRenew) {
195
+ state.renewAt = savedRenew;
196
+ } else {
197
+ const now = new Date();
198
+ state.renewAt = new Date(now.getFullYear(), now.getMonth() + 1, 1, 0, 0, 0).toISOString();
199
+ }
200
+
201
+ state.byokEnabled = localStorage.getItem('scout_byok_enabled') === 'true';
202
+ state.customLlmProvider = localStorage.getItem('scout_byok_provider') || 'gemini';
203
+ state.customApiKey = localStorage.getItem('scout_byok_key') || '';
204
+ state.customBaseUrl = localStorage.getItem('scout_byok_endpoint') || '';
205
205
  }
206
206
 
207
207
  // Render All Dynamic Components
208
208
  function renderAllDynamicComponents() {
209
- renderSessionsTable();
210
- renderCreditUsageUI();
211
- renderTiersUI();
209
+ renderSessionsTable();
210
+ renderCreditUsageUI();
211
+ renderTiersUI();
212
212
  }
213
213
 
214
214
  // Open / Close Checkout Modal
215
215
  function openCheckoutModal(targetTier) {
216
- pendingCheckoutTier = targetTier;
217
- const isAnnual = state.billingCycle === 'annual';
218
- const tierInfo = TIER_DETAILS[targetTier] || TIER_DETAILS.pro;
219
-
220
- let price = '0';
221
- let quota = '100 Credits / mo';
222
-
223
- if (targetTier === 'pro') {
224
- price = isAnnual ? '15' : '19';
225
- quota = '1,000 Credits / mo';
226
- } else if (targetTier === 'enterprise') {
227
- price = isAnnual ? '39' : '49';
228
- quota = '10,000 Credits / mo';
229
- }
230
-
231
- if (elements.checkoutPlanName) elements.checkoutPlanName.innerText = tierInfo.name;
232
- if (elements.checkoutBillingCycle) elements.checkoutBillingCycle.innerText = isAnnual ? 'Billed Annually (20% Off)' : 'Billed Monthly';
233
- if (elements.checkoutPlanPrice) elements.checkoutPlanPrice.innerText = price;
234
- if (elements.checkoutPricePeriod) elements.checkoutPricePeriod.innerText = isAnnual ? '/ mo (annual)' : '/ mo';
235
- if (elements.checkoutQuotaVal) elements.checkoutQuotaVal.innerText = quota;
236
-
237
- if (elements.checkoutModal) elements.checkoutModal.classList.remove('hidden');
216
+ pendingCheckoutTier = targetTier;
217
+ const isAnnual = state.billingCycle === 'annual';
218
+ const tierInfo = TIER_DETAILS[targetTier] || TIER_DETAILS.pro;
219
+
220
+ let price = '0';
221
+ let quota = '100 Credits / mo';
222
+
223
+ if (targetTier === 'pro') {
224
+ price = isAnnual ? '15' : '19';
225
+ quota = '1,000 Credits / mo';
226
+ } else if (targetTier === 'enterprise') {
227
+ price = isAnnual ? '39' : '49';
228
+ quota = '10,000 Credits / mo';
229
+ }
230
+
231
+ if (elements.checkoutPlanName) elements.checkoutPlanName.innerText = tierInfo.name;
232
+ if (elements.checkoutBillingCycle) elements.checkoutBillingCycle.innerText = isAnnual ? 'Billed Annually (20% Off)' : 'Billed Monthly';
233
+ if (elements.checkoutPlanPrice) elements.checkoutPlanPrice.innerText = price;
234
+ if (elements.checkoutPricePeriod) elements.checkoutPricePeriod.innerText = isAnnual ? '/ mo (annual)' : '/ mo';
235
+ if (elements.checkoutQuotaVal) elements.checkoutQuotaVal.innerText = quota;
236
+
237
+ if (elements.checkoutModal) elements.checkoutModal.classList.remove('hidden');
238
238
  }
239
239
 
240
240
  function closeCheckoutModal() {
241
- pendingCheckoutTier = null;
242
- if (elements.checkoutModal) elements.checkoutModal.classList.add('hidden');
241
+ pendingCheckoutTier = null;
242
+ if (elements.checkoutModal) elements.checkoutModal.classList.add('hidden');
243
243
  }
244
244
 
245
245
  // Setup Event Handlers
246
246
  function initEventListeners() {
247
- // Auth Form Tabs Switcher
248
- elements.tabLoginBtn?.addEventListener('click', () => switchAuthForm('login'));
249
- elements.tabSignupBtn?.addEventListener('click', () => switchAuthForm('signup'));
250
-
251
- // Form Submissions
252
- elements.loginForm?.addEventListener('submit', handleSignIn);
253
- elements.signupForm?.addEventListener('submit', handleSignUp);
254
- elements.btnDemoMode?.addEventListener('click', launchDemoSession);
255
-
256
- elements.btnForgotPwd?.addEventListener('click', (e) => {
257
- e.preventDefault();
258
- handleForgotPassword();
259
- });
260
-
261
- // Navigation Tabs Switcher
262
- document.querySelectorAll('.nav-btn').forEach((btn) => {
263
- btn.addEventListener('click', () => {
264
- const targetTab = btn.getAttribute('data-tab');
265
- if (targetTab) switchDashboardTab(targetTab);
266
- });
267
- });
268
-
269
- // User Dropdown Menu
270
- elements.userMenuToggle?.addEventListener('click', (e) => {
271
- e.stopPropagation();
272
- elements.userDropdown?.classList.toggle('show');
273
- });
274
-
275
- document.addEventListener('click', () => {
276
- elements.userDropdown?.classList.remove('show');
277
- });
278
-
279
- elements.btnDropdownLogout?.addEventListener('click', handleLogout);
280
- elements.btnAccountLogout?.addEventListener('click', handleLogout);
281
- elements.btnDropdownProfile?.addEventListener('click', () => switchDashboardTab('account'));
282
- elements.btnDropdownTiers?.addEventListener('click', () => switchDashboardTab('tiers'));
283
- elements.btnNavTiersHero?.addEventListener('click', () => switchDashboardTab('tiers'));
284
- elements.btnUpgradeCreditsHero?.addEventListener('click', () => switchDashboardTab('tiers'));
285
- elements.btnOpenAuth?.addEventListener('click', showAuthSection);
286
-
287
- // Checkout Modal Events
288
- elements.btnCloseCheckout?.addEventListener('click', closeCheckoutModal);
289
- elements.btnCancelCheckout?.addEventListener('click', closeCheckoutModal);
290
-
291
- elements.btnConfirmCheckout?.addEventListener('click', () => {
292
- if (!pendingCheckoutTier) return;
293
-
294
- const targetTier = pendingCheckoutTier;
295
- const tierInfo = TIER_DETAILS[targetTier];
296
- if (!tierInfo) return;
297
-
298
- state.currentTier = targetTier;
299
- state.creditsTotal = targetTier === 'pro' ? 1000 : targetTier === 'enterprise' ? 10000 : 100;
300
-
301
- const now = new Date();
302
- state.renewAt = new Date(now.getFullYear(), now.getMonth() + 1, 1, 0, 0, 0).toISOString();
303
-
304
- saveSessionToStorage();
305
- syncAuthWithServer();
306
- closeCheckoutModal();
307
- renderCreditUsageUI();
308
- renderTiersUI();
309
- updateUserUI();
310
- showToast(`Subscription activated! Welcome to ${tierInfo.name}. Quota upgraded to ${state.creditsTotal.toLocaleString()} credits.`, 'success');
311
- });
312
-
313
- // Password Visibility Toggle Buttons
314
- document.querySelectorAll('.btn-toggle-pwd').forEach((btn) => {
315
- btn.addEventListener('click', () => {
316
- const targetId = btn.getAttribute('data-target');
317
- const input = document.getElementById(targetId);
318
- if (input) {
319
- const isPwd = input.type === 'password';
320
- input.type = isPwd ? 'text' : 'password';
321
- btn.innerHTML = isPwd ? '<i class="fa-solid fa-eye-slash"></i>' : '<i class="fa-solid fa-eye"></i>';
322
- }
323
- });
324
- });
325
-
326
- // Profile Form Submission
327
- elements.profileForm?.addEventListener('submit', (e) => {
328
- e.preventDefault();
329
- const newName = elements.settingsDisplayName.value.trim();
330
- if (newName && state.user) {
331
- state.user.name = newName;
332
- saveSessionToStorage();
333
- syncAuthWithServer();
334
- updateUserUI();
335
- showToast('Profile display name updated successfully!', 'success');
336
- }
337
- });
338
-
339
- // BYOK & Custom Proxy Form Submission
340
- elements.byokForm?.addEventListener('submit', (e) => {
341
- e.preventDefault();
342
- state.customLlmProvider = elements.selectByokProvider?.value || 'gemini';
343
- state.customBaseUrl = elements.inputByokEndpoint?.value.trim() || '';
344
- state.customApiKey = elements.inputByokKey?.value.trim() || '';
345
- state.byokEnabled = elements.checkboxEnableByok?.checked || false;
346
-
347
- localStorage.setItem('scout_byok_enabled', String(state.byokEnabled));
348
- localStorage.setItem('scout_byok_provider', state.customLlmProvider);
349
- localStorage.setItem('scout_byok_key', state.customApiKey);
350
- localStorage.setItem('scout_byok_endpoint', state.customBaseUrl);
351
-
352
- syncAuthWithServer();
353
- renderCreditUsageUI();
354
- updateUserUI();
355
-
356
- if (state.byokEnabled) {
357
- showToast('BYOK Mode Active! Requests now route through your custom API key/proxy endpoint (Scout credits bypassed).', 'success');
358
- } else {
359
- showToast('Endpoint configuration saved. Using standard Scout key.', 'info');
360
- }
361
- });
362
-
363
- elements.checkboxEnableByok?.addEventListener('change', (e) => {
364
- state.byokEnabled = e.target.checked;
365
- localStorage.setItem('scout_byok_enabled', String(state.byokEnabled));
366
- syncAuthWithServer();
367
- renderCreditUsageUI();
368
- });
369
-
370
- // Billing Cycle Toggle Switcher
371
- elements.toggleBillingCycle?.addEventListener('change', (e) => {
372
- state.billingCycle = e.target.checked ? 'annual' : 'monthly';
373
- renderTiersUI();
374
- });
375
-
376
- // Tier Selection Buttons
377
- document.querySelectorAll('.btn-select-tier').forEach((btn) => {
378
- btn.addEventListener('click', () => {
379
- const targetTier = btn.getAttribute('data-tier');
380
- if (!targetTier || !TIER_DETAILS[targetTier]) return;
381
-
382
- if (targetTier === 'free') {
383
- state.currentTier = 'free';
384
- state.creditsTotal = 100;
385
- saveSessionToStorage();
386
- syncAuthWithServer();
387
- renderCreditUsageUI();
388
- renderTiersUI();
389
- updateUserUI();
390
- showToast('Switched to Developer Free Tier.', 'info');
391
- } else {
392
- openCheckoutModal(targetTier);
393
- }
394
- });
395
- });
247
+ // Auth Form Tabs Switcher
248
+ elements.tabLoginBtn?.addEventListener('click', () => switchAuthForm('login'));
249
+ elements.tabSignupBtn?.addEventListener('click', () => switchAuthForm('signup'));
250
+
251
+ // Form Submissions
252
+ elements.loginForm?.addEventListener('submit', handleSignIn);
253
+ elements.signupForm?.addEventListener('submit', handleSignUp);
254
+ elements.btnDemoMode?.addEventListener('click', launchDemoSession);
255
+
256
+ elements.btnForgotPwd?.addEventListener('click', (e) => {
257
+ e.preventDefault();
258
+ handleForgotPassword();
259
+ });
260
+
261
+ // Navigation Tabs Switcher
262
+ document.querySelectorAll('.nav-btn').forEach((btn) => {
263
+ btn.addEventListener('click', () => {
264
+ const targetTab = btn.getAttribute('data-tab');
265
+ if (targetTab) switchDashboardTab(targetTab);
266
+ });
267
+ });
268
+
269
+ // User Dropdown Menu
270
+ elements.userMenuToggle?.addEventListener('click', (e) => {
271
+ e.stopPropagation();
272
+ elements.userDropdown?.classList.toggle('show');
273
+ });
274
+
275
+ document.addEventListener('click', () => {
276
+ elements.userDropdown?.classList.remove('show');
277
+ });
278
+
279
+ elements.btnDropdownLogout?.addEventListener('click', handleLogout);
280
+ elements.btnAccountLogout?.addEventListener('click', handleLogout);
281
+ elements.btnDropdownProfile?.addEventListener('click', () => switchDashboardTab('account'));
282
+ elements.btnDropdownTiers?.addEventListener('click', () => switchDashboardTab('tiers'));
283
+ elements.btnNavTiersHero?.addEventListener('click', () => switchDashboardTab('tiers'));
284
+ elements.btnUpgradeCreditsHero?.addEventListener('click', () => switchDashboardTab('tiers'));
285
+ elements.btnOpenAuth?.addEventListener('click', showAuthSection);
286
+
287
+ // Checkout Modal Events
288
+ elements.btnCloseCheckout?.addEventListener('click', closeCheckoutModal);
289
+ elements.btnCancelCheckout?.addEventListener('click', closeCheckoutModal);
290
+
291
+ elements.btnConfirmCheckout?.addEventListener('click', () => {
292
+ if (!pendingCheckoutTier) return;
293
+
294
+ const targetTier = pendingCheckoutTier;
295
+ const tierInfo = TIER_DETAILS[targetTier];
296
+ if (!tierInfo) return;
297
+
298
+ state.currentTier = targetTier;
299
+ state.creditsTotal = targetTier === 'pro' ? 1000 : targetTier === 'enterprise' ? 10000 : 100;
300
+
301
+ const now = new Date();
302
+ state.renewAt = new Date(now.getFullYear(), now.getMonth() + 1, 1, 0, 0, 0).toISOString();
303
+
304
+ saveSessionToStorage();
305
+ syncAuthWithServer();
306
+ closeCheckoutModal();
307
+ renderCreditUsageUI();
308
+ renderTiersUI();
309
+ updateUserUI();
310
+ showToast(`Subscription activated! Welcome to ${tierInfo.name}. Quota upgraded to ${state.creditsTotal.toLocaleString()} credits.`, 'success');
311
+ });
312
+
313
+ // Password Visibility Toggle Buttons
314
+ document.querySelectorAll('.btn-toggle-pwd').forEach((btn) => {
315
+ btn.addEventListener('click', () => {
316
+ const targetId = btn.getAttribute('data-target');
317
+ const input = document.getElementById(targetId);
318
+ if (input) {
319
+ const isPwd = input.type === 'password';
320
+ input.type = isPwd ? 'text' : 'password';
321
+ btn.innerHTML = isPwd ? '<i class="fa-solid fa-eye-slash"></i>' : '<i class="fa-solid fa-eye"></i>';
322
+ }
323
+ });
324
+ });
325
+
326
+ // Profile Form Submission
327
+ elements.profileForm?.addEventListener('submit', (e) => {
328
+ e.preventDefault();
329
+ const newName = elements.settingsDisplayName.value.trim();
330
+ if (newName && state.user) {
331
+ state.user.name = newName;
332
+ saveSessionToStorage();
333
+ syncAuthWithServer();
334
+ updateUserUI();
335
+ showToast('Profile display name updated successfully!', 'success');
336
+ }
337
+ });
338
+
339
+ elements.selectByokProvider?.addEventListener('change', (e) => {
340
+ const provider = e.target.value;
341
+ const defaultEndpoints = {
342
+ nvidia: 'https://integrate.api.nvidia.com/v1',
343
+ gemini: 'https://generativelanguage.googleapis.com/v1beta/openai',
344
+ openai: 'https://api.openai.com/v1',
345
+ custom: 'http://localhost:11434/v1',
346
+ };
347
+ if (elements.inputByokEndpoint && defaultEndpoints[provider]) {
348
+ elements.inputByokEndpoint.value = defaultEndpoints[provider];
349
+ }
350
+ });
351
+
352
+ // BYOK & Custom Proxy Form Submission
353
+ elements.byokForm?.addEventListener('submit', (e) => {
354
+ e.preventDefault();
355
+ state.customLlmProvider = elements.selectByokProvider?.value || 'gemini';
356
+ state.customBaseUrl = elements.inputByokEndpoint?.value.trim() || '';
357
+ state.customApiKey = elements.inputByokKey?.value.trim() || '';
358
+ state.byokEnabled = elements.checkboxEnableByok?.checked || false;
359
+
360
+ localStorage.setItem('scout_byok_enabled', String(state.byokEnabled));
361
+ localStorage.setItem('scout_byok_provider', state.customLlmProvider);
362
+ localStorage.setItem('scout_byok_key', state.customApiKey);
363
+ localStorage.setItem('scout_byok_endpoint', state.customBaseUrl);
364
+
365
+ syncAuthWithServer();
366
+ renderCreditUsageUI();
367
+ updateUserUI();
368
+
369
+ if (state.byokEnabled) {
370
+ showToast('BYOK Mode Active! Requests now route through your custom API key/proxy endpoint (Scout credits bypassed).', 'success');
371
+ } else {
372
+ showToast('Endpoint configuration saved. Using standard Scout key.', 'info');
373
+ }
374
+ });
375
+
376
+ elements.checkboxEnableByok?.addEventListener('change', (e) => {
377
+ state.byokEnabled = e.target.checked;
378
+ localStorage.setItem('scout_byok_enabled', String(state.byokEnabled));
379
+ syncAuthWithServer();
380
+ renderCreditUsageUI();
381
+ });
382
+
383
+ // Billing Cycle Toggle Switcher
384
+ elements.toggleBillingCycle?.addEventListener('change', (e) => {
385
+ state.billingCycle = e.target.checked ? 'annual' : 'monthly';
386
+ renderTiersUI();
387
+ });
388
+
389
+ // Tier Selection Buttons
390
+ document.querySelectorAll('.btn-select-tier').forEach((btn) => {
391
+ btn.addEventListener('click', () => {
392
+ const targetTier = btn.getAttribute('data-tier');
393
+ if (!targetTier || !TIER_DETAILS[targetTier]) return;
394
+
395
+ if (targetTier === 'free') {
396
+ state.currentTier = 'free';
397
+ state.creditsTotal = 100;
398
+ saveSessionToStorage();
399
+ syncAuthWithServer();
400
+ renderCreditUsageUI();
401
+ renderTiersUI();
402
+ updateUserUI();
403
+ showToast('Switched to Developer Free Tier.', 'info');
404
+ } else {
405
+ openCheckoutModal(targetTier);
406
+ }
407
+ });
408
+ });
396
409
  }
397
410
 
398
411
  // Data Storage & Session Loaders
399
412
  function loadSessionsFromStorage() {
400
- try {
401
- const stored = localStorage.getItem('scout_cli_sessions');
402
- if (stored) {
403
- state.sessions = JSON.parse(stored);
404
- } else {
405
- state.sessions = [
406
- {
407
- id: 'sess_local_1',
408
- host: 'Local Workstation (FT-CLI)',
409
- platform: 'Windows x64 Node.js',
410
- lastActive: new Date().toISOString(),
411
- ip: '127.0.0.1',
412
- active: true,
413
- },
414
- ];
415
- saveSessionsToStorage();
416
- }
417
- } catch {
418
- state.sessions = [];
419
- }
413
+ try {
414
+ const stored = localStorage.getItem('scout_cli_sessions');
415
+ if (stored) {
416
+ state.sessions = JSON.parse(stored);
417
+ } else {
418
+ state.sessions = [
419
+ {
420
+ id: 'sess_local_1',
421
+ host: 'Local Workstation (FT-CLI)',
422
+ platform: 'Windows x64 Node.js',
423
+ lastActive: new Date().toISOString(),
424
+ ip: '127.0.0.1',
425
+ active: true,
426
+ },
427
+ ];
428
+ saveSessionsToStorage();
429
+ }
430
+ } catch {
431
+ state.sessions = [];
432
+ }
420
433
  }
421
434
 
422
435
  function saveSessionsToStorage() {
423
- try {
424
- localStorage.setItem('scout_cli_sessions', JSON.stringify(state.sessions));
425
- } catch {}
436
+ try {
437
+ localStorage.setItem('scout_cli_sessions', JSON.stringify(state.sessions));
438
+ } catch { }
426
439
  }
427
440
 
428
441
  function renderSessionsTable() {
429
- if (!elements.sessionTableBody) return;
430
-
431
- if (!state.sessions || state.sessions.length === 0) {
432
- elements.sessionTableBody.innerHTML = `
442
+ if (!elements.sessionTableBody) return;
443
+
444
+ if (!state.sessions || state.sessions.length === 0) {
445
+ elements.sessionTableBody.innerHTML = `
433
446
  <tr>
434
447
  <td colspan="4" class="empty-table-notice">No active CLI authorization sessions found.</td>
435
448
  </tr>
436
449
  `;
437
- return;
438
- }
450
+ return;
451
+ }
439
452
 
440
- elements.sessionTableBody.innerHTML = state.sessions
441
- .map((sess) => {
442
- return `
453
+ elements.sessionTableBody.innerHTML = state.sessions
454
+ .map((sess) => {
455
+ return `
443
456
  <tr data-id="${escapeHtml(sess.id)}">
444
457
  <td>
445
458
  <div class="flex-center-gap">
@@ -455,609 +468,617 @@ function renderSessionsTable() {
455
468
  <td><button class="btn btn-xs btn-outline text-danger btn-revoke-session" onclick="revokeSession('${escapeHtml(sess.id)}')"><i class="fa-solid fa-trash"></i> Revoke</button></td>
456
469
  </tr>
457
470
  `;
458
- })
459
- .join('');
471
+ })
472
+ .join('');
460
473
  }
461
474
 
462
475
  function revokeSession(sessionId) {
463
- state.sessions = state.sessions.filter(s => s.id !== sessionId);
464
- saveSessionsToStorage();
465
- renderSessionsTable();
466
- showToast('CLI access session revoked.', 'info');
476
+ state.sessions = state.sessions.filter(s => s.id !== sessionId);
477
+ saveSessionsToStorage();
478
+ renderSessionsTable();
479
+ showToast('CLI access session revoked.', 'info');
467
480
  }
468
481
 
469
482
  // Render Dynamic Credit Usage & BYOK Status UI
470
483
  function renderCreditUsageUI() {
471
- if (state.byokEnabled) {
472
- if (elements.byokStatusBadge) {
473
- elements.byokStatusBadge.innerText = 'BYOK Mode Active';
474
- elements.byokStatusBadge.className = 'badge badge-accent';
475
- }
476
- if (elements.creditStatusBadge) {
477
- elements.creditStatusBadge.innerText = 'Custom Endpoint Active';
478
- elements.creditStatusBadge.className = 'badge badge-accent';
479
- }
480
- if (elements.valCreditsUsed) elements.valCreditsUsed.innerText = 'Unmonitored';
481
- if (elements.valCreditsRemaining) elements.valCreditsRemaining.innerText = 'Unlimited (BYOK)';
482
- if (elements.valCreditsTotal) elements.valCreditsTotal.innerText = 'Custom Provider';
483
- if (elements.valCreditsPct) elements.valCreditsPct.innerText = 'BYOK';
484
-
485
- if (elements.creditProgressFill) {
486
- elements.creditProgressFill.style.width = '100%';
487
- elements.creditProgressFill.style.background = 'linear-gradient(90deg, #a855f7 0%, #ec4899 100%)';
488
- }
489
-
490
- if (elements.labelCreditConsumption) {
491
- elements.labelCreditConsumption.innerText = 'Direct Custom Endpoint Routing (Scout Credits Bypassed)';
492
- }
493
-
494
- if (elements.byokBannerNote) {
495
- elements.byokBannerNote.classList.remove('hidden');
496
- }
497
- } else {
498
- if (elements.byokStatusBadge) {
499
- elements.byokStatusBadge.innerText = 'Scout Default';
500
- elements.byokStatusBadge.className = 'badge';
501
- }
502
- if (elements.creditStatusBadge) {
503
- elements.creditStatusBadge.innerText = 'Quota Active';
504
- elements.creditStatusBadge.className = 'badge badge-success';
505
- }
506
-
507
- const defaultTotal = state.currentTier === 'pro' ? 1000 : state.currentTier === 'enterprise' ? 10000 : 100;
508
- const total = state.creditsTotal || defaultTotal;
509
- const used = state.creditsUsed || 0;
510
- const remaining = Math.max(0, total - used);
511
- const pct = Math.min(100, Math.round((used / total) * 100));
512
-
513
- if (elements.valCreditsUsed) elements.valCreditsUsed.innerText = used.toLocaleString();
514
- if (elements.valCreditsRemaining) elements.valCreditsRemaining.innerText = remaining.toLocaleString();
515
- if (elements.valCreditsTotal) elements.valCreditsTotal.innerText = total.toLocaleString();
516
- if (elements.valCreditsPct) elements.valCreditsPct.innerText = `${pct}%`;
517
-
518
- if (elements.creditProgressFill) {
519
- elements.creditProgressFill.style.width = `${pct}%`;
520
- elements.creditProgressFill.style.background = 'linear-gradient(90deg, #6366f1 0%, #38bdf8 60%, #34d399 100%)';
521
- }
522
-
523
- if (elements.labelCreditConsumption) {
524
- elements.labelCreditConsumption.innerText = 'Monthly Credit Consumption';
525
- }
526
-
527
- if (elements.byokBannerNote) {
528
- elements.byokBannerNote.classList.add('hidden');
529
- }
530
- }
531
-
532
- let renewDateStr = '';
533
- if (state.renewAt) {
534
- const d = new Date(state.renewAt);
535
- if (!isNaN(d.getTime())) {
536
- renewDateStr = `${d.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })} at 00:00:00 UTC`;
537
- }
538
- }
539
- if (!renewDateStr) {
540
- const now = new Date();
541
- const nextMonth = new Date(now.getFullYear(), now.getMonth() + 1, 1);
542
- renewDateStr = `${nextMonth.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })} at 00:00:00 UTC`;
543
- }
544
-
545
- if (elements.valRenewDatetime) {
546
- elements.valRenewDatetime.innerText = renewDateStr;
547
- }
484
+ if (state.byokEnabled) {
485
+ if (elements.byokStatusBadge) {
486
+ elements.byokStatusBadge.innerText = 'BYOK Mode Active';
487
+ elements.byokStatusBadge.className = 'badge badge-accent';
488
+ }
489
+ if (elements.creditStatusBadge) {
490
+ elements.creditStatusBadge.innerText = 'Custom Endpoint Active';
491
+ elements.creditStatusBadge.className = 'badge badge-accent';
492
+ }
493
+ if (elements.valCreditsUsed) elements.valCreditsUsed.innerText = 'Unmonitored';
494
+ if (elements.valCreditsRemaining) elements.valCreditsRemaining.innerText = 'Unlimited (BYOK)';
495
+ if (elements.valCreditsTotal) elements.valCreditsTotal.innerText = 'Custom Provider';
496
+ if (elements.valCreditsPct) elements.valCreditsPct.innerText = 'BYOK';
497
+
498
+ if (elements.creditProgressFill) {
499
+ elements.creditProgressFill.style.width = '100%';
500
+ elements.creditProgressFill.style.background = 'linear-gradient(90deg, #a855f7 0%, #ec4899 100%)';
501
+ }
502
+
503
+ if (elements.labelCreditConsumption) {
504
+ elements.labelCreditConsumption.innerText = 'Direct Custom Endpoint Routing (Scout Credits Bypassed)';
505
+ }
506
+
507
+ if (elements.byokBannerNote) {
508
+ elements.byokBannerNote.classList.remove('hidden');
509
+ }
510
+ } else {
511
+ if (elements.byokStatusBadge) {
512
+ elements.byokStatusBadge.innerText = 'Scout Default';
513
+ elements.byokStatusBadge.className = 'badge';
514
+ }
515
+ if (elements.creditStatusBadge) {
516
+ elements.creditStatusBadge.innerText = 'Quota Active';
517
+ elements.creditStatusBadge.className = 'badge badge-success';
518
+ }
519
+
520
+ const defaultTotal = state.currentTier === 'pro' ? 1000 : state.currentTier === 'enterprise' ? 10000 : 100;
521
+ const total = state.creditsTotal || defaultTotal;
522
+ const used = state.creditsUsed || 0;
523
+ const remaining = Math.max(0, total - used);
524
+ const pct = Math.min(100, Math.round((used / total) * 100));
525
+
526
+ if (elements.valCreditsUsed) elements.valCreditsUsed.innerText = used.toLocaleString();
527
+ if (elements.valCreditsRemaining) elements.valCreditsRemaining.innerText = remaining.toLocaleString();
528
+ if (elements.valCreditsTotal) elements.valCreditsTotal.innerText = total.toLocaleString();
529
+ if (elements.valCreditsPct) elements.valCreditsPct.innerText = `${pct}%`;
530
+
531
+ if (elements.creditProgressFill) {
532
+ elements.creditProgressFill.style.width = `${pct}%`;
533
+ elements.creditProgressFill.style.background = 'linear-gradient(90deg, #6366f1 0%, #38bdf8 60%, #34d399 100%)';
534
+ }
535
+
536
+ if (elements.labelCreditConsumption) {
537
+ elements.labelCreditConsumption.innerText = 'Monthly Credit Consumption';
538
+ }
539
+
540
+ if (elements.byokBannerNote) {
541
+ elements.byokBannerNote.classList.add('hidden');
542
+ }
543
+ }
544
+
545
+ let renewDateStr = '';
546
+ if (state.renewAt) {
547
+ const d = new Date(state.renewAt);
548
+ if (!isNaN(d.getTime())) {
549
+ renewDateStr = `${d.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })} at 00:00:00 UTC`;
550
+ }
551
+ }
552
+ if (!renewDateStr) {
553
+ const now = new Date();
554
+ const nextMonth = new Date(now.getFullYear(), now.getMonth() + 1, 1);
555
+ renewDateStr = `${nextMonth.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })} at 00:00:00 UTC`;
556
+ }
557
+
558
+ if (elements.valRenewDatetime) {
559
+ elements.valRenewDatetime.innerText = renewDateStr;
560
+ }
548
561
  }
549
562
 
550
563
  // Render Paid Tiers UI
551
564
  function renderTiersUI() {
552
- const current = TIER_DETAILS[state.currentTier] || TIER_DETAILS.free;
553
-
554
- if (elements.currentPlanTitle) elements.currentPlanTitle.innerText = current.name;
555
- if (elements.currentPlanBadge) elements.currentPlanBadge.innerText = current.badge;
556
- if (elements.currentPlanDesc) elements.currentPlanDesc.innerText = current.desc;
557
- if (elements.tierActiveIcon) elements.tierActiveIcon.innerHTML = current.icon;
558
-
559
- // Billing Cycle Pricing Adjustments
560
- const isAnnual = state.billingCycle === 'annual';
561
- if (elements.priceProVal) elements.priceProVal.innerText = isAnnual ? '15' : '19';
562
- if (elements.priceProPeriod) elements.priceProPeriod.innerText = isAnnual ? '/ month (billed annually)' : '/ month';
563
-
564
- if (elements.priceEntVal) elements.priceEntVal.innerText = isAnnual ? '39' : '49';
565
- if (elements.priceEntPeriod) elements.priceEntPeriod.innerText = isAnnual ? '/ month (billed annually)' : '/ month';
566
-
567
- // Highlight Active Tier Card
568
- ['free', 'pro', 'enterprise'].forEach((t) => {
569
- const card = document.getElementById(`tier-card-${t}`);
570
- const btn = document.getElementById(`btn-tier-${t}`);
571
- if (!card || !btn) return;
572
-
573
- if (t === state.currentTier) {
574
- card.classList.add('active-tier-card');
575
- btn.className = 'btn btn-success btn-block btn-select-tier';
576
- btn.innerText = 'Current Plan';
577
- btn.disabled = true;
578
- } else {
579
- card.classList.remove('active-tier-card');
580
- btn.disabled = false;
581
- if (t === 'pro') {
582
- btn.className = 'btn btn-primary btn-block btn-select-tier';
583
- btn.innerText = 'Upgrade to Pro';
584
- } else {
585
- btn.className = 'btn btn-outline btn-block btn-select-tier';
586
- btn.innerText = t === 'enterprise' ? 'Upgrade to Enterprise' : 'Switch to Free';
587
- }
588
- }
589
- });
565
+ const current = TIER_DETAILS[state.currentTier] || TIER_DETAILS.free;
566
+
567
+ if (elements.currentPlanTitle) elements.currentPlanTitle.innerText = current.name;
568
+ if (elements.currentPlanBadge) elements.currentPlanBadge.innerText = current.badge;
569
+ if (elements.currentPlanDesc) elements.currentPlanDesc.innerText = current.desc;
570
+ if (elements.tierActiveIcon) elements.tierActiveIcon.innerHTML = current.icon;
571
+
572
+ // Billing Cycle Pricing Adjustments
573
+ const isAnnual = state.billingCycle === 'annual';
574
+ if (elements.priceProVal) elements.priceProVal.innerText = isAnnual ? '15' : '19';
575
+ if (elements.priceProPeriod) elements.priceProPeriod.innerText = isAnnual ? '/ month (billed annually)' : '/ month';
576
+
577
+ if (elements.priceEntVal) elements.priceEntVal.innerText = isAnnual ? '39' : '49';
578
+ if (elements.priceEntPeriod) elements.priceEntPeriod.innerText = isAnnual ? '/ month (billed annually)' : '/ month';
579
+
580
+ // Highlight Active Tier Card
581
+ ['free', 'pro', 'enterprise'].forEach((t) => {
582
+ const card = document.getElementById(`tier-card-${t}`);
583
+ const btn = document.getElementById(`btn-tier-${t}`);
584
+ if (!card || !btn) return;
585
+
586
+ if (t === state.currentTier) {
587
+ card.classList.add('active-tier-card');
588
+ btn.className = 'btn btn-success btn-block btn-select-tier';
589
+ btn.innerText = 'Current Plan';
590
+ btn.disabled = true;
591
+ } else {
592
+ card.classList.remove('active-tier-card');
593
+ btn.disabled = false;
594
+ if (t === 'pro') {
595
+ btn.className = 'btn btn-primary btn-block btn-select-tier';
596
+ btn.innerText = 'Upgrade to Pro';
597
+ } else {
598
+ btn.className = 'btn btn-outline btn-block btn-select-tier';
599
+ btn.innerText = t === 'enterprise' ? 'Upgrade to Enterprise' : 'Switch to Free';
600
+ }
601
+ }
602
+ });
590
603
  }
591
604
 
592
605
  // Sync with Local Server CLI Session
593
606
  async function checkServerStatusAndSession() {
594
- let connected = false;
595
- let data = null;
596
-
597
- try {
598
- const res = await fetch('/api/status', { method: 'GET' });
599
- if (res.ok) {
600
- data = await res.json();
601
- if (data && data.status === 'ok') {
602
- state.apiBaseUrl = '';
603
- connected = true;
604
- }
605
- }
606
- } catch {}
607
-
608
- if (!connected) {
609
- try {
610
- const res = await fetch('http://localhost:9120/api/status', { method: 'GET' });
611
- if (res.ok) {
612
- data = await res.json();
613
- if (data && data.status === 'ok') {
614
- state.apiBaseUrl = 'http://localhost:9120';
615
- connected = true;
616
- }
617
- }
618
- } catch {}
619
- }
620
-
621
- if (connected && data) {
622
- state.serverConnected = true;
623
-
624
- if (elements.navTenantName) {
625
- elements.navTenantName.innerText = `CLI Local Sync Active (${data.repoName || 'Workspace'})`;
626
- }
627
-
628
- if (data.isLoggedIn && data.auth?.user) {
629
- state.user = data.auth.user;
630
- state.token = data.auth.token;
631
- state.refreshToken = data.auth.refreshToken;
632
-
633
- if (typeof data.auth.creditsUsed === 'number') state.creditsUsed = data.auth.creditsUsed;
634
- if (typeof data.auth.creditsTotal === 'number') state.creditsTotal = data.auth.creditsTotal;
635
- if (data.auth.currentTier) state.currentTier = data.auth.currentTier;
636
- if (data.auth.renewAt) state.renewAt = data.auth.renewAt;
637
- if (typeof data.auth.byokEnabled === 'boolean') state.byokEnabled = data.auth.byokEnabled;
638
- if (data.auth.customLlmProvider) state.customLlmProvider = data.auth.customLlmProvider;
639
- if (typeof data.auth.customApiKey === 'string') state.customApiKey = data.auth.customApiKey;
640
- if (typeof data.auth.customBaseUrl === 'string') state.customBaseUrl = data.auth.customBaseUrl;
641
-
642
- const localCliSession = {
643
- id: 'sess_cli_local',
644
- host: `Local Workstation (${data.repoName || 'FT-CLI'})`,
645
- platform: `Node.js CLI (~/.ft/auth.json)`,
646
- lastActive: data.auth.loggedInAt || new Date().toISOString(),
647
- ip: '127.0.0.1 (Local Sync)',
648
- active: true,
649
- };
650
-
651
- const otherSessions = state.sessions.filter(s => s.id !== 'sess_cli_local');
652
- state.sessions = [localCliSession, ...otherSessions];
653
- saveSessionsToStorage();
654
-
655
- saveSessionToStorage();
656
- showDashboard();
657
- updateUserUI();
658
- renderCreditUsageUI();
659
- renderSessionsTable();
660
- return;
661
- }
662
- }
663
-
664
- state.serverConnected = false;
665
- if (elements.navTenantName) {
666
- elements.navTenantName.innerText = FIREBASE_CONFIG.tenantId;
667
- }
668
-
669
- checkLocalStorageSession();
607
+ let connected = false;
608
+ let data = null;
609
+
610
+ try {
611
+ const res = await fetch('/api/status', { method: 'GET' });
612
+ if (res.ok) {
613
+ data = await res.json();
614
+ if (data && data.status === 'ok') {
615
+ state.apiBaseUrl = '';
616
+ connected = true;
617
+ }
618
+ }
619
+ } catch { }
620
+
621
+ if (!connected) {
622
+ try {
623
+ const res = await fetch('http://localhost:9120/api/status', { method: 'GET' });
624
+ if (res.ok) {
625
+ data = await res.json();
626
+ if (data && data.status === 'ok') {
627
+ state.apiBaseUrl = 'http://localhost:9120';
628
+ connected = true;
629
+ }
630
+ }
631
+ } catch { }
632
+ }
633
+
634
+ if (connected && data) {
635
+ state.serverConnected = true;
636
+
637
+ if (elements.navTenantName) {
638
+ elements.navTenantName.innerText = `CLI Local Sync Active (${data.repoName || 'Workspace'})`;
639
+ }
640
+
641
+ if (data.isLoggedIn && data.auth?.user) {
642
+ state.user = data.auth.user;
643
+ state.token = data.auth.token;
644
+ state.refreshToken = data.auth.refreshToken;
645
+
646
+ if (typeof data.auth.creditsUsed === 'number') state.creditsUsed = data.auth.creditsUsed;
647
+ if (typeof data.auth.creditsTotal === 'number') state.creditsTotal = data.auth.creditsTotal;
648
+ if (data.auth.currentTier) state.currentTier = data.auth.currentTier;
649
+ if (data.auth.renewAt) state.renewAt = data.auth.renewAt;
650
+ if (typeof data.auth.byokEnabled === 'boolean') state.byokEnabled = data.auth.byokEnabled;
651
+ if (data.auth.customLlmProvider) state.customLlmProvider = data.auth.customLlmProvider;
652
+ if (typeof data.auth.customApiKey === 'string') state.customApiKey = data.auth.customApiKey;
653
+ if (typeof data.auth.customBaseUrl === 'string') state.customBaseUrl = data.auth.customBaseUrl;
654
+
655
+ const localCliSession = {
656
+ id: 'sess_cli_local',
657
+ host: `Local Workstation (${data.repoName || 'FT-CLI'})`,
658
+ platform: `Node.js CLI (~/.ft/auth.json)`,
659
+ lastActive: data.auth.loggedInAt || new Date().toISOString(),
660
+ ip: '127.0.0.1 (Local Sync)',
661
+ active: true,
662
+ };
663
+
664
+ const otherSessions = state.sessions.filter(s => s.id !== 'sess_cli_local');
665
+ state.sessions = [localCliSession, ...otherSessions];
666
+ saveSessionsToStorage();
667
+
668
+ saveSessionToStorage();
669
+ showDashboard();
670
+ updateUserUI();
671
+ renderCreditUsageUI();
672
+ renderSessionsTable();
673
+ return;
674
+ }
675
+ }
676
+
677
+ state.serverConnected = false;
678
+ if (elements.navTenantName) {
679
+ elements.navTenantName.innerText = FIREBASE_CONFIG.tenantId;
680
+ }
681
+
682
+ checkLocalStorageSession();
670
683
  }
671
684
 
672
685
  function checkLocalStorageSession() {
673
- try {
674
- const storedUser = localStorage.getItem('scout_auth_user');
675
- const storedToken = localStorage.getItem('scout_auth_token');
676
-
677
- if (storedUser && storedToken) {
678
- state.user = JSON.parse(storedUser);
679
- state.token = storedToken;
680
- state.refreshToken = localStorage.getItem('scout_refresh_token') || '';
681
-
682
- showDashboard();
683
- updateUserUI();
684
- return;
685
- }
686
- } catch (err) {
687
- console.error('Saved session parse error:', err);
688
- }
689
-
690
- showAuthSection();
686
+ try {
687
+ const storedUser = localStorage.getItem('scout_auth_user');
688
+ const storedToken = localStorage.getItem('scout_auth_token');
689
+
690
+ if (storedUser && storedToken) {
691
+ state.user = JSON.parse(storedUser);
692
+ state.token = storedToken;
693
+ state.refreshToken = localStorage.getItem('scout_refresh_token') || '';
694
+
695
+ showDashboard();
696
+ updateUserUI();
697
+ return;
698
+ }
699
+ } catch (err) {
700
+ console.error('Saved session parse error:', err);
701
+ }
702
+
703
+ showAuthSection();
691
704
  }
692
705
 
693
706
  // Switch Auth View Forms
694
707
  function switchAuthForm(mode) {
695
- if (mode === 'login') {
696
- elements.tabLoginBtn?.classList.add('active');
697
- elements.tabSignupBtn?.classList.remove('active');
698
- elements.loginForm?.classList.remove('hidden');
699
- elements.signupForm?.classList.add('hidden');
700
- } else {
701
- elements.tabSignupBtn?.classList.add('active');
702
- elements.tabLoginBtn?.classList.remove('active');
703
- elements.signupForm?.classList.remove('hidden');
704
- elements.loginForm?.classList.add('hidden');
705
- }
708
+ if (mode === 'login') {
709
+ elements.tabLoginBtn?.classList.add('active');
710
+ elements.tabSignupBtn?.classList.remove('active');
711
+ elements.loginForm?.classList.remove('hidden');
712
+ elements.signupForm?.classList.add('hidden');
713
+ } else {
714
+ elements.tabSignupBtn?.classList.add('active');
715
+ elements.tabLoginBtn?.classList.remove('active');
716
+ elements.signupForm?.classList.remove('hidden');
717
+ elements.loginForm?.classList.add('hidden');
718
+ }
706
719
  }
707
720
 
708
721
  // Handle Sign In Submission
709
722
  async function handleSignIn(e) {
710
- e.preventDefault();
711
- const email = document.getElementById('login-email').value.trim();
712
- const password = document.getElementById('login-password').value;
713
- const btnSubmit = document.getElementById('btn-submit-login');
714
-
715
- btnSubmit.disabled = true;
716
- btnSubmit.innerHTML = '<i class="fa-solid fa-spinner fa-spin"></i> Authenticating...';
717
-
718
- try {
719
- let authRes;
720
- if (state.serverConnected) {
721
- const res = await fetch(`${state.apiBaseUrl}/api/login`, {
722
- method: 'POST',
723
- headers: { 'Content-Type': 'application/json' },
724
- body: JSON.stringify({ email, password }),
725
- });
726
- const data = await res.json();
727
- if (!res.ok || !data.success) {
728
- throw new Error(data.error || 'Server authentication failed.');
729
- }
730
- authRes = data.auth;
731
- } else {
732
- authRes = await apiFirebaseSignIn(email, password);
733
- }
734
-
735
- state.token = authRes.token || authRes.idToken;
736
- state.refreshToken = authRes.refreshToken;
737
- state.user = authRes.user || {
738
- id: authRes.localId || 'usr_' + Date.now().toString(36),
739
- email: authRes.email || email,
740
- name: authRes.displayName || email.split('@')[0],
741
- createdAt: new Date().toISOString(),
742
- };
743
-
744
- saveSessionToStorage();
745
- syncAuthWithServer();
746
- showDashboard();
747
- updateUserUI();
748
- showToast(`Signed in successfully as ${state.user.name}!`, 'success');
749
- } catch (error) {
750
- showToast(error.message || 'Login failed.', 'error');
751
- } finally {
752
- btnSubmit.disabled = false;
753
- btnSubmit.innerHTML = '<span>Sign In to Scout</span><i class="fa-solid fa-arrow-right"></i>';
754
- }
723
+ e.preventDefault();
724
+ const email = document.getElementById('login-email').value.trim();
725
+ const password = document.getElementById('login-password').value;
726
+ const btnSubmit = document.getElementById('btn-submit-login');
727
+
728
+ btnSubmit.disabled = true;
729
+ btnSubmit.innerHTML = '<i class="fa-solid fa-spinner fa-spin"></i> Authenticating...';
730
+
731
+ try {
732
+ let authRes;
733
+ if (state.serverConnected) {
734
+ const res = await fetch(`${state.apiBaseUrl}/api/login`, {
735
+ method: 'POST',
736
+ headers: { 'Content-Type': 'application/json' },
737
+ body: JSON.stringify({ email, password }),
738
+ });
739
+ const data = await res.json();
740
+ if (!res.ok || !data.success) {
741
+ throw new Error(data.error || 'Server authentication failed.');
742
+ }
743
+ authRes = data.auth;
744
+ } else {
745
+ authRes = await apiFirebaseSignIn(email, password);
746
+ }
747
+
748
+ state.token = authRes.token || authRes.idToken;
749
+ state.refreshToken = authRes.refreshToken;
750
+ state.user = authRes.user || {
751
+ id: authRes.localId || 'usr_' + Date.now().toString(36),
752
+ email: authRes.email || email,
753
+ name: authRes.displayName || email.split('@')[0],
754
+ createdAt: new Date().toISOString(),
755
+ };
756
+
757
+ saveSessionToStorage();
758
+ syncAuthWithServer();
759
+ showDashboard();
760
+ updateUserUI();
761
+ showToast(`Signed in successfully as ${state.user.name}!`, 'success');
762
+ } catch (error) {
763
+ showToast(error.message || 'Login failed.', 'error');
764
+ } finally {
765
+ btnSubmit.disabled = false;
766
+ btnSubmit.innerHTML = '<span>Sign In to Scout</span><i class="fa-solid fa-arrow-right"></i>';
767
+ }
755
768
  }
756
769
 
757
770
  // Handle Sign Up Submission
758
771
  async function handleSignUp(e) {
759
- e.preventDefault();
760
- const name = document.getElementById('signup-name').value.trim();
761
- const email = document.getElementById('signup-email').value.trim();
762
- const password = document.getElementById('signup-password').value;
763
- const confirmPassword = document.getElementById('signup-confirm-password').value;
764
- const btnSubmit = document.getElementById('btn-submit-signup');
765
-
766
- if (password !== confirmPassword) {
767
- showToast('Passwords do not match.', 'error');
768
- return;
769
- }
770
-
771
- btnSubmit.disabled = true;
772
- btnSubmit.innerHTML = '<i class="fa-solid fa-spinner fa-spin"></i> Creating Account...';
773
-
774
- try {
775
- let authRes;
776
- if (state.serverConnected) {
777
- const res = await fetch(`${state.apiBaseUrl}/api/signup`, {
778
- method: 'POST',
779
- headers: { 'Content-Type': 'application/json' },
780
- body: JSON.stringify({ name, email, password }),
781
- });
782
- const data = await res.json();
783
- if (!res.ok || !data.success) {
784
- throw new Error(data.error || 'Server registration failed.');
785
- }
786
- authRes = data.auth;
787
- } else {
788
- authRes = await apiFirebaseSignUp(name, email, password);
789
- }
790
-
791
- state.token = authRes.token || authRes.idToken;
792
- state.refreshToken = authRes.refreshToken;
793
- state.user = authRes.user || {
794
- id: authRes.localId || 'usr_' + Date.now().toString(36),
795
- email: authRes.email || email,
796
- name: name,
797
- createdAt: new Date().toISOString(),
798
- };
799
-
800
- saveSessionToStorage();
801
- syncAuthWithServer();
802
- showDashboard();
803
- updateUserUI();
804
- showToast(`Account created! Welcome to FrontTerrain, ${name}.`, 'success');
805
- } catch (error) {
806
- showToast(error.message || 'Registration failed.', 'error');
807
- } finally {
808
- btnSubmit.disabled = false;
809
- btnSubmit.innerHTML = '<span>Create Scout Account</span><i class="fa-solid fa-user-check"></i>';
810
- }
772
+ e.preventDefault();
773
+ const name = document.getElementById('signup-name').value.trim();
774
+ const email = document.getElementById('signup-email').value.trim();
775
+ const password = document.getElementById('signup-password').value;
776
+ const confirmPassword = document.getElementById('signup-confirm-password').value;
777
+ const btnSubmit = document.getElementById('btn-submit-signup');
778
+
779
+ if (password !== confirmPassword) {
780
+ showToast('Passwords do not match.', 'error');
781
+ return;
782
+ }
783
+
784
+ btnSubmit.disabled = true;
785
+ btnSubmit.innerHTML = '<i class="fa-solid fa-spinner fa-spin"></i> Creating Account...';
786
+
787
+ try {
788
+ let authRes;
789
+ if (state.serverConnected) {
790
+ const res = await fetch(`${state.apiBaseUrl}/api/signup`, {
791
+ method: 'POST',
792
+ headers: { 'Content-Type': 'application/json' },
793
+ body: JSON.stringify({ name, email, password }),
794
+ });
795
+ const data = await res.json();
796
+ if (!res.ok || !data.success) {
797
+ throw new Error(data.error || 'Server registration failed.');
798
+ }
799
+ authRes = data.auth;
800
+ } else {
801
+ authRes = await apiFirebaseSignUp(name, email, password);
802
+ }
803
+
804
+ state.token = authRes.token || authRes.idToken;
805
+ state.refreshToken = authRes.refreshToken;
806
+ state.user = authRes.user || {
807
+ id: authRes.localId || 'usr_' + Date.now().toString(36),
808
+ email: authRes.email || email,
809
+ name: name,
810
+ createdAt: new Date().toISOString(),
811
+ };
812
+
813
+ saveSessionToStorage();
814
+ syncAuthWithServer();
815
+ showDashboard();
816
+ updateUserUI();
817
+ showToast(`Account created! Welcome to FrontTerrain, ${name}.`, 'success');
818
+ } catch (error) {
819
+ showToast(error.message || 'Registration failed.', 'error');
820
+ } finally {
821
+ btnSubmit.disabled = false;
822
+ btnSubmit.innerHTML = '<span>Create Scout Account</span><i class="fa-solid fa-user-check"></i>';
823
+ }
811
824
  }
812
825
 
813
826
  // Forgot Password Flow
814
827
  function handleForgotPassword() {
815
- const email = prompt('Enter your registered email address for password reset:');
816
- if (email && email.includes('@')) {
817
- showToast(`Password reset link dispatched to ${email}`, 'success');
818
- } else if (email) {
819
- showToast('Please enter a valid email address.', 'error');
820
- }
828
+ const email = prompt('Enter your registered email address for password reset:');
829
+ if (email && email.includes('@')) {
830
+ showToast(`Password reset link dispatched to ${email}`, 'success');
831
+ } else if (email) {
832
+ showToast('Please enter a valid email address.', 'error');
833
+ }
821
834
  }
822
835
 
823
836
  // Demo Mode Session Launcher
824
837
  function launchDemoSession() {
825
- state.token = 'ft_demo_token_' + Date.now().toString(36);
826
- state.user = {
827
- id: 'usr_demo_' + Math.floor(1000 + Math.random() * 9000),
828
- email: 'developer@frontterrain.com',
829
- name: 'FrontTerrain Developer',
830
- createdAt: new Date().toISOString(),
831
- };
832
-
833
- saveSessionToStorage();
834
- syncAuthWithServer();
835
- showDashboard();
836
- updateUserUI();
837
- showToast('Demo Developer Session Active!', 'info');
838
+ state.token = 'ft_demo_token_' + Date.now().toString(36);
839
+ state.user = {
840
+ id: 'usr_demo_' + Math.floor(1000 + Math.random() * 9000),
841
+ email: 'developer@frontterrain.com',
842
+ name: 'FrontTerrain Developer',
843
+ createdAt: new Date().toISOString(),
844
+ };
845
+
846
+ saveSessionToStorage();
847
+ syncAuthWithServer();
848
+ showDashboard();
849
+ updateUserUI();
850
+ showToast('Demo Developer Session Active!', 'info');
838
851
  }
839
852
 
840
853
  // Firebase Direct REST API
841
854
  async function apiFirebaseSignIn(email, password) {
842
- const url = `${FIREBASE_CONFIG.baseAuthUrl}:signInWithPassword?key=${FIREBASE_CONFIG.apiKey}`;
843
- const response = await fetch(url, {
844
- method: 'POST',
845
- headers: { 'Content-Type': 'application/json' },
846
- body: JSON.stringify({
847
- email,
848
- password,
849
- returnSecureToken: true,
850
- tenantId: FIREBASE_CONFIG.tenantId,
851
- }),
852
- });
853
-
854
- const data = await response.json();
855
- if (!response.ok) {
856
- throw new Error(parseFirebaseError(data, 'Firebase sign in failed'));
857
- }
858
- return data;
855
+ const url = `${FIREBASE_CONFIG.baseAuthUrl}:signInWithPassword?key=${FIREBASE_CONFIG.apiKey}`;
856
+ const response = await fetch(url, {
857
+ method: 'POST',
858
+ headers: { 'Content-Type': 'application/json' },
859
+ body: JSON.stringify({
860
+ email,
861
+ password,
862
+ returnSecureToken: true,
863
+ tenantId: FIREBASE_CONFIG.tenantId,
864
+ }),
865
+ });
866
+
867
+ const data = await response.json();
868
+ if (!response.ok) {
869
+ throw new Error(parseFirebaseError(data, 'Firebase sign in failed'));
870
+ }
871
+ return data;
859
872
  }
860
873
 
861
874
  async function apiFirebaseSignUp(name, email, password) {
862
- const url = `${FIREBASE_CONFIG.baseAuthUrl}:signUp?key=${FIREBASE_CONFIG.apiKey}`;
863
- const response = await fetch(url, {
864
- method: 'POST',
865
- headers: { 'Content-Type': 'application/json' },
866
- body: JSON.stringify({
867
- email,
868
- password,
869
- returnSecureToken: true,
870
- tenantId: FIREBASE_CONFIG.tenantId,
871
- }),
872
- });
873
-
874
- const data = await response.json();
875
- if (!response.ok) {
876
- throw new Error(parseFirebaseError(data, 'Firebase sign up failed'));
877
- }
878
-
879
- try {
880
- const updateUrl = `${FIREBASE_CONFIG.baseAuthUrl}:update?key=${FIREBASE_CONFIG.apiKey}`;
881
- await fetch(updateUrl, {
882
- method: 'POST',
883
- headers: { 'Content-Type': 'application/json' },
884
- body: JSON.stringify({
885
- idToken: data.idToken,
886
- displayName: name,
887
- tenantId: FIREBASE_CONFIG.tenantId,
888
- }),
889
- });
890
- data.displayName = name;
891
- } catch {}
892
-
893
- return data;
875
+ const url = `${FIREBASE_CONFIG.baseAuthUrl}:signUp?key=${FIREBASE_CONFIG.apiKey}`;
876
+ const response = await fetch(url, {
877
+ method: 'POST',
878
+ headers: { 'Content-Type': 'application/json' },
879
+ body: JSON.stringify({
880
+ email,
881
+ password,
882
+ returnSecureToken: true,
883
+ tenantId: FIREBASE_CONFIG.tenantId,
884
+ }),
885
+ });
886
+
887
+ const data = await response.json();
888
+ if (!response.ok) {
889
+ throw new Error(parseFirebaseError(data, 'Firebase sign up failed'));
890
+ }
891
+
892
+ try {
893
+ const updateUrl = `${FIREBASE_CONFIG.baseAuthUrl}:update?key=${FIREBASE_CONFIG.apiKey}`;
894
+ await fetch(updateUrl, {
895
+ method: 'POST',
896
+ headers: { 'Content-Type': 'application/json' },
897
+ body: JSON.stringify({
898
+ idToken: data.idToken,
899
+ displayName: name,
900
+ tenantId: FIREBASE_CONFIG.tenantId,
901
+ }),
902
+ });
903
+ data.displayName = name;
904
+ } catch { }
905
+
906
+ return data;
894
907
  }
895
908
 
896
909
  function parseFirebaseError(errData, defaultMsg) {
897
- const code = errData?.error?.message || errData?.message || '';
898
- if (code.includes('EMAIL_NOT_FOUND')) return 'No account found with this email.';
899
- if (code.includes('INVALID_PASSWORD') || code.includes('INVALID_LOGIN_CREDENTIALS')) return 'Invalid password entered.';
900
- if (code.includes('EMAIL_EXISTS')) return 'An account already exists with this email.';
901
- if (code.includes('WEAK_PASSWORD')) return 'Password is too weak (min 6 chars).';
902
- if (code.includes('INVALID_EMAIL')) return 'Invalid email address format.';
903
- if (code.includes('TOO_MANY_ATTEMPTS_TRY_LATER')) return 'Too many login attempts. Try later.';
904
- return `${defaultMsg}: ${code || 'Unknown error'}`;
910
+ const code = errData?.error?.message || errData?.message || '';
911
+ if (code.includes('EMAIL_NOT_FOUND')) return 'No account found with this email.';
912
+ if (code.includes('INVALID_PASSWORD') || code.includes('INVALID_LOGIN_CREDENTIALS')) return 'Invalid password entered.';
913
+ if (code.includes('EMAIL_EXISTS')) return 'An account already exists with this email.';
914
+ if (code.includes('WEAK_PASSWORD')) return 'Password is too weak (min 6 chars).';
915
+ if (code.includes('INVALID_EMAIL')) return 'Invalid email address format.';
916
+ if (code.includes('TOO_MANY_ATTEMPTS_TRY_LATER')) return 'Too many login attempts. Try later.';
917
+ return `${defaultMsg}: ${code || 'Unknown error'}`;
905
918
  }
906
919
 
907
920
  // UI State Renderers
908
921
  function showAuthSection() {
909
- elements.authSection?.classList.remove('hidden');
910
- elements.dashboardSection?.classList.add('hidden');
911
- elements.userMenu?.classList.add('hidden');
912
- elements.btnOpenAuth?.classList.remove('hidden');
922
+ elements.authSection?.classList.remove('hidden');
923
+ elements.dashboardSection?.classList.add('hidden');
924
+ elements.userMenu?.classList.add('hidden');
925
+ elements.btnOpenAuth?.classList.remove('hidden');
913
926
  }
914
927
 
915
928
  function showDashboard() {
916
- elements.authSection?.classList.add('hidden');
917
- elements.dashboardSection?.classList.remove('hidden');
918
- elements.userMenu?.classList.remove('hidden');
919
- elements.btnOpenAuth?.classList.add('hidden');
920
-
921
- renderAllDynamicComponents();
929
+ elements.authSection?.classList.add('hidden');
930
+ elements.dashboardSection?.classList.remove('hidden');
931
+ elements.userMenu?.classList.remove('hidden');
932
+ elements.btnOpenAuth?.classList.add('hidden');
933
+
934
+ renderAllDynamicComponents();
922
935
  }
923
936
 
924
937
  function updateUserUI() {
925
- if (!state.user) return;
926
-
927
- const name = state.user.name || 'Developer';
928
- const initial = name.charAt(0).toUpperCase();
929
-
930
- if (elements.navAvatar) elements.navAvatar.innerText = initial;
931
- if (elements.navUserName) elements.navUserName.innerText = name;
932
- if (elements.userDisplayName) elements.userDisplayName.innerText = name;
933
- if (elements.dropdownName) elements.dropdownName.innerText = name;
934
- if (elements.dropdownEmail) elements.dropdownEmail.innerText = state.user.email;
935
-
936
- if (elements.settingsDisplayName) elements.settingsDisplayName.value = name;
937
- if (elements.settingsEmail) elements.settingsEmail.value = state.user.email;
938
- if (elements.settingsUid) elements.settingsUid.value = state.user.id;
939
-
940
- const tierInfo = TIER_DETAILS[state.currentTier] || TIER_DETAILS.free;
941
- if (elements.settingsActiveTier) elements.settingsActiveTier.value = tierInfo.name;
942
-
943
- if (elements.selectByokProvider) elements.selectByokProvider.value = state.customLlmProvider || 'gemini';
944
- if (elements.inputByokEndpoint) elements.inputByokEndpoint.value = state.customBaseUrl || '';
945
- if (elements.inputByokKey) elements.inputByokKey.value = state.customApiKey || '';
946
- if (elements.checkboxEnableByok) elements.checkboxEnableByok.checked = Boolean(state.byokEnabled);
938
+ if (!state.user) return;
939
+
940
+ const name = state.user.name || 'Developer';
941
+ const initial = name.charAt(0).toUpperCase();
942
+
943
+ if (elements.navAvatar) elements.navAvatar.innerText = initial;
944
+ if (elements.navUserName) elements.navUserName.innerText = name;
945
+ if (elements.userDisplayName) elements.userDisplayName.innerText = name;
946
+ if (elements.dropdownName) elements.dropdownName.innerText = name;
947
+ if (elements.dropdownEmail) elements.dropdownEmail.innerText = state.user.email;
948
+
949
+ if (elements.settingsDisplayName) elements.settingsDisplayName.value = name;
950
+ if (elements.settingsEmail) elements.settingsEmail.value = state.user.email;
951
+ if (elements.settingsUid) elements.settingsUid.value = state.user.id;
952
+
953
+ const tierInfo = TIER_DETAILS[state.currentTier] || TIER_DETAILS.free;
954
+ if (elements.settingsActiveTier) elements.settingsActiveTier.value = tierInfo.name;
955
+
956
+ if (elements.selectByokProvider) elements.selectByokProvider.value = state.customLlmProvider || 'gemini';
957
+ if (elements.inputByokEndpoint) elements.inputByokEndpoint.value = state.customBaseUrl || '';
958
+ if (elements.inputByokKey) elements.inputByokKey.value = state.customApiKey || '';
959
+ if (elements.checkboxEnableByok) elements.checkboxEnableByok.checked = Boolean(state.byokEnabled);
947
960
  }
948
961
 
949
962
  function switchDashboardTab(tabId) {
950
- state.activeTab = tabId;
951
-
952
- document.querySelectorAll('.nav-btn').forEach((btn) => {
953
- if (btn.getAttribute('data-tab') === tabId) {
954
- btn.classList.add('active');
955
- } else {
956
- btn.classList.remove('active');
957
- }
958
- });
959
-
960
- document.querySelectorAll('.tab-pane').forEach((pane) => {
961
- if (pane.id === `tab-${tabId}`) {
962
- pane.classList.add('active');
963
- } else {
964
- pane.classList.remove('active');
965
- }
966
- });
963
+ state.activeTab = tabId;
964
+
965
+ document.querySelectorAll('.nav-btn').forEach((btn) => {
966
+ if (btn.getAttribute('data-tab') === tabId) {
967
+ btn.classList.add('active');
968
+ } else {
969
+ btn.classList.remove('active');
970
+ }
971
+ });
972
+
973
+ document.querySelectorAll('.tab-pane').forEach((pane) => {
974
+ if (pane.id === `tab-${tabId}`) {
975
+ pane.classList.add('active');
976
+ } else {
977
+ pane.classList.remove('active');
978
+ }
979
+ });
967
980
  }
968
981
 
969
982
  async function handleLogout() {
970
- if (state.serverConnected) {
971
- try {
972
- await fetch(`${state.apiBaseUrl}/api/logout`, { method: 'POST' });
973
- } catch {}
974
- }
975
-
976
- state.user = null;
977
- state.token = null;
978
- state.refreshToken = null;
979
-
980
- localStorage.removeItem('scout_auth_user');
981
- localStorage.removeItem('scout_auth_token');
982
- localStorage.removeItem('scout_refresh_token');
983
-
984
- showAuthSection();
985
- showToast('Signed out of Scout session.', 'info');
983
+ if (state.serverConnected) {
984
+ try {
985
+ await fetch(`${state.apiBaseUrl}/api/logout`, { method: 'POST' });
986
+ } catch { }
987
+ }
988
+
989
+ state.user = null;
990
+ state.token = null;
991
+ state.refreshToken = null;
992
+
993
+ localStorage.removeItem('scout_auth_user');
994
+ localStorage.removeItem('scout_auth_token');
995
+ localStorage.removeItem('scout_refresh_token');
996
+
997
+ showAuthSection();
998
+ showToast('Signed out of Scout session.', 'info');
986
999
  }
987
1000
 
988
1001
  function saveSessionToStorage() {
989
- if (state.user) localStorage.setItem('scout_auth_user', JSON.stringify(state.user));
990
- if (state.token) localStorage.setItem('scout_auth_token', state.token);
991
- if (state.refreshToken) localStorage.setItem('scout_refresh_token', state.refreshToken);
992
- localStorage.setItem('scout_current_tier', state.currentTier);
993
- localStorage.setItem('scout_credits_used', String(state.creditsUsed));
994
- localStorage.setItem('scout_credits_total', String(state.creditsTotal));
995
- if (state.renewAt) localStorage.setItem('scout_renew_at', state.renewAt);
996
- localStorage.setItem('scout_byok_enabled', String(state.byokEnabled));
997
- localStorage.setItem('scout_byok_provider', state.customLlmProvider);
998
- localStorage.setItem('scout_byok_key', state.customApiKey);
999
- localStorage.setItem('scout_byok_endpoint', state.customBaseUrl);
1002
+ if (state.user) localStorage.setItem('scout_auth_user', JSON.stringify(state.user));
1003
+ if (state.token) localStorage.setItem('scout_auth_token', state.token);
1004
+ if (state.refreshToken) localStorage.setItem('scout_refresh_token', state.refreshToken);
1005
+ localStorage.setItem('scout_current_tier', state.currentTier);
1006
+ localStorage.setItem('scout_credits_used', String(state.creditsUsed));
1007
+ localStorage.setItem('scout_credits_total', String(state.creditsTotal));
1008
+ if (state.renewAt) localStorage.setItem('scout_renew_at', state.renewAt);
1009
+ localStorage.setItem('scout_byok_enabled', String(state.byokEnabled));
1010
+ localStorage.setItem('scout_byok_provider', state.customLlmProvider);
1011
+ localStorage.setItem('scout_byok_key', state.customApiKey);
1012
+ localStorage.setItem('scout_byok_endpoint', state.customBaseUrl);
1000
1013
  }
1001
1014
 
1002
1015
  async function syncAuthWithServer() {
1003
- if (state.user) {
1004
- try {
1005
- await fetch(`${state.apiBaseUrl}/api/save-auth`, {
1006
- method: 'POST',
1007
- headers: { 'Content-Type': 'application/json' },
1008
- body: JSON.stringify({
1009
- user: state.user,
1010
- token: state.token,
1011
- refreshToken: state.refreshToken,
1012
- creditsUsed: state.creditsUsed,
1013
- creditsTotal: state.creditsTotal,
1014
- currentTier: state.currentTier,
1015
- renewAt: state.renewAt,
1016
- byokEnabled: state.byokEnabled,
1017
- customLlmProvider: state.customLlmProvider,
1018
- customApiKey: state.customApiKey,
1019
- customBaseUrl: state.customBaseUrl,
1020
- }),
1021
- });
1022
- } catch {}
1023
- }
1016
+ if (state.user) {
1017
+ try {
1018
+ await fetch(`${state.apiBaseUrl}/api/save-auth`, {
1019
+ method: 'POST',
1020
+ headers: { 'Content-Type': 'application/json' },
1021
+ body: JSON.stringify({
1022
+ user: state.user,
1023
+ token: state.token,
1024
+ refreshToken: state.refreshToken,
1025
+ creditsUsed: state.creditsUsed,
1026
+ creditsTotal: state.creditsTotal,
1027
+ currentTier: state.currentTier,
1028
+ renewAt: state.renewAt,
1029
+ byokEnabled: state.byokEnabled,
1030
+ customLlmProvider: state.customLlmProvider,
1031
+ customApiKey: state.customApiKey,
1032
+ customBaseUrl: state.customBaseUrl,
1033
+ }),
1034
+ });
1035
+ } catch { }
1036
+ }
1024
1037
  }
1025
1038
 
1026
1039
  // Copy Utility
1027
1040
  function copyText(text, successMsg = 'Copied to clipboard!') {
1028
- navigator.clipboard.writeText(text).then(
1029
- () => showToast(successMsg, 'success'),
1030
- () => showToast('Failed to copy to clipboard', 'error')
1031
- );
1041
+ navigator.clipboard.writeText(text).then(
1042
+ () => showToast(successMsg, 'success'),
1043
+ () => showToast('Failed to copy to clipboard', 'error')
1044
+ );
1032
1045
  }
1033
1046
 
1047
+ document.addEventListener('click', (e) => {
1048
+ const copyBtn = e.target.closest('#btn-copy-terminal-cmd');
1049
+ if (copyBtn) {
1050
+ const cmdText = document.getElementById('terminal-cmd-display')?.innerText || 'npx -y ft-scout@latest';
1051
+ copyText(cmdText, 'CLI Command copied to clipboard!');
1052
+ }
1053
+ });
1054
+
1034
1055
  // Toast System
1035
1056
  function showToast(message, type = 'info') {
1036
- if (!elements.toastContainer) return;
1037
-
1038
- const toast = document.createElement('div');
1039
- toast.className = `toast toast-${type}`;
1040
-
1041
- let iconClass = 'fa-circle-info';
1042
- if (type === 'success') iconClass = 'fa-circle-check';
1043
- if (type === 'error') iconClass = 'fa-circle-exclamation';
1044
-
1045
- toast.innerHTML = `<i class="fa-solid ${iconClass}"></i> <span>${message}</span>`;
1046
- elements.toastContainer.appendChild(toast);
1047
-
1048
- setTimeout(() => {
1049
- toast.style.opacity = '0';
1050
- toast.style.transform = 'translateX(100%)';
1051
- toast.style.transition = 'all 0.3s ease-out';
1052
- setTimeout(() => toast.remove(), 300);
1053
- }, 3500);
1057
+ if (!elements.toastContainer) return;
1058
+
1059
+ const toast = document.createElement('div');
1060
+ toast.className = `toast toast-${type}`;
1061
+
1062
+ let iconClass = 'fa-circle-info';
1063
+ if (type === 'success') iconClass = 'fa-circle-check';
1064
+ if (type === 'error') iconClass = 'fa-circle-exclamation';
1065
+
1066
+ toast.innerHTML = `<i class="fa-solid ${iconClass}"></i> <span>${message}</span>`;
1067
+ elements.toastContainer.appendChild(toast);
1068
+
1069
+ setTimeout(() => {
1070
+ toast.style.opacity = '0';
1071
+ toast.style.transform = 'translateX(100%)';
1072
+ toast.style.transition = 'all 0.3s ease-out';
1073
+ setTimeout(() => toast.remove(), 300);
1074
+ }, 3500);
1054
1075
  }
1055
1076
 
1056
1077
  function escapeHtml(str) {
1057
- if (!str) return '';
1058
- return String(str)
1059
- .replace(/&/g, '&amp;')
1060
- .replace(/</g, '&lt;')
1061
- .replace(/>/g, '&gt;')
1062
- .replace(/"/g, '&quot;');
1078
+ if (!str) return '';
1079
+ return String(str)
1080
+ .replace(/&/g, '&amp;')
1081
+ .replace(/</g, '&lt;')
1082
+ .replace(/>/g, '&gt;')
1083
+ .replace(/"/g, '&quot;');
1063
1084
  }