-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathvps_main.ts
More file actions
2946 lines (2656 loc) · 130 KB
/
Copy pathvps_main.ts
File metadata and controls
2946 lines (2656 loc) · 130 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* SIDIX — main.ts
*
* Semua inference memanggil brain_qa backend lokal via BrainQAClient (src/api.ts).
* TIDAK ada import ke @google/genai, openai, atau vendor AI lain di sini.
* Lihat AGENTS.md — "ATURAN KERAS Arsitektur & Inference".
*/
import {
createIcons,
MessageSquare, Library, Settings, ArrowUp, Plus, FileText,
UploadCloud, AlertTriangle, Cpu, Info,
ChevronDown, Sparkles, Paperclip, Copy, Check, Trash2,
FolderTree, ShieldCheck, Folder, Lock, LockOpen, MoreHorizontal,
LoaderCircle, Zap, BookOpen, ShieldAlert, Key,
Users, Code2, Palette, Coffee, ExternalLink, User,
} from 'lucide';
import {
checkHealth, askStream, askHolisticStream, BRAIN_QA_BASE, listCorpus, uploadDocument, deleteDocument,
triggerReindex, getReindexStatus, agentGenerate, submitFeedback, forgetAgentSession,
agentBurst, agentTwoEyed, agentForesight, agentResurrect,
BrainQAError, BRAIN_QA_BASE,
type Persona, type CorpusDocument, type Citation, type HealthResponse,
type AskInferenceOpts, type QuotaInfo,
} from './api';
import { initWaitingRoom } from './waiting-room';
// Pivot 2026-04-26: drop Supabase auth, pakai own auth via Google Identity
// Services (lib/auth_google.py + /login.html). Supabase HANYA dipakai untuk
// newsletter + feedback DB fallback + contributor signup form (legacy, bisa
// diphase out di iterasi berikutnya).
import {
subscribeNewsletter, submitFeedbackDB, type FeedbackType,
saveDeveloperProfile,
} from './lib/supabase';
// ── Auth error handler (URL hash + searchParams) ────────────────────────────
// Supabase OAuth pakai URL hash fragment (#error=...&error_description=...) untuk
// callback errors, BUKAN searchParams. Sebelumnya code hanya cek searchParams →
// error tidak ke-detect → user bingung kenapa login gagal. Sekarang handle dua-duanya.
(function handleAuthErrors() {
try {
let errCode = '';
let errDesc = '';
// Strategy 1: URL hash fragment (#error=...&error_description=...)
const hash = window.location.hash || '';
if (hash.includes('error=')) {
const params = new URLSearchParams(hash.replace(/^#/, ''));
errCode = params.get('error_code') || params.get('error') || '';
errDesc = params.get('error_description') || '';
}
// Strategy 2: searchParams (?error=...) — fallback
if (!errCode) {
const url = new URL(window.location.href);
if (url.searchParams.has('error')) {
errCode = url.searchParams.get('error_code') || url.searchParams.get('error') || '';
errDesc = url.searchParams.get('error_description') || '';
}
}
if (!errCode) return;
console.warn('[SIDIX auth] OAuth callback error:', { code: errCode, description: errDesc });
// Decode the description (Supabase sends URL-encoded with + for spaces)
const friendlyDesc = decodeURIComponent(errDesc.replace(/\+/g, ' '));
// Build user-facing banner
const banner = document.createElement('div');
banner.id = 'auth-error-banner';
banner.style.cssText = `
position: fixed; top: 0; left: 0; right: 0; z-index: 200;
background: linear-gradient(135deg, #d97a5a, #b85a3a);
color: #fff; padding: 12px 16px; font-size: 13px;
box-shadow: 0 4px 12px rgba(0,0,0,0.3);
display: flex; align-items: start; gap: 12px; justify-content: space-between;
`;
let helpText = '';
if (friendlyDesc.toLowerCase().includes('database error') || friendlyDesc.toLowerCase().includes('saving new user')) {
helpText = 'Backend SIDIX sedang ada glitch saat simpan akun baru. Tim sudah dapat alert otomatis. Coba lagi 1-2 menit, atau lapor via tombol Feedback.';
} else if (friendlyDesc.toLowerCase().includes('access denied') || errCode === 'access_denied') {
helpText = 'Login dibatalkan. Klik Sign In lagi kalau mau coba sekali lagi.';
} else {
helpText = 'Login gagal. Coba refresh + Sign In lagi. Kalau tetap, lapor via tombol Feedback dengan screenshot URL ini.';
}
banner.innerHTML = `
<div style="flex:1; line-height:1.5">
<strong style="display:block; margin-bottom:4px;">⚠️ Login error: ${errCode}</strong>
<div style="font-size:12px; opacity:0.95;">${helpText}</div>
<div style="font-size:10px; margin-top:4px; opacity:0.7; font-family: monospace;">${friendlyDesc}</div>
</div>
<button onclick="document.getElementById('auth-error-banner')?.remove()"
style="background:transparent; border:1px solid rgba(255,255,255,0.4); color:#fff; padding:4px 12px; border-radius:6px; cursor:pointer; font-size:12px; flex-shrink:0;">Tutup</button>
`;
document.body.appendChild(banner);
// Auto-dismiss after 15 seconds
setTimeout(() => {
document.getElementById('auth-error-banner')?.remove();
}, 15000);
// Clean URL — hapus error params + hash
const cleanUrl = new URL(window.location.href);
cleanUrl.hash = '';
cleanUrl.searchParams.delete('error');
cleanUrl.searchParams.delete('error_code');
cleanUrl.searchParams.delete('error_description');
cleanUrl.searchParams.delete('sb');
window.history.replaceState({}, document.title, cleanUrl.toString());
} catch (e) {
console.warn('[SIDIX] auth error handler exception:', e);
}
})();
// ── Bootstrap icons ──────────────────────────────────────────────────────────
function initIcons() {
createIcons({
icons: {
MessageSquare, Library, Settings, ArrowUp, Plus, FileText,
UploadCloud, AlertTriangle, Cpu, Info,
ChevronDown, Sparkles, Paperclip, Copy, Check, Trash2,
FolderTree, ShieldCheck, Folder, Lock, LockOpen, MoreHorizontal,
LoaderCircle, Zap, BookOpen, ShieldAlert, Key,
Users, Code2, Palette, Coffee, ExternalLink, User,
},
});
}
initIcons();
// ── Language Detection & i18n ─────────────────────────────────────────────────
// Detect via browser locale + timezone (no IP call, instant)
type Lang = 'id' | 'en';
function detectLang(): Lang {
const tz = Intl.DateTimeFormat().resolvedOptions().timeZone ?? '';
const locale = navigator.language ?? '';
// Indonesia: WIB/WITA/WIT timezones + bahasa Indonesia
const isID = tz.startsWith('Asia/Jakarta') || tz.startsWith('Asia/Makassar') ||
tz.startsWith('Asia/Jayapura') || locale.startsWith('id');
return isID ? 'id' : 'en';
}
const LANG: Lang = detectLang();
// i18n strings
const T = {
about: { id: 'Tentang SIDIX', en: 'About SIDIX' },
contrib: { id: 'Gabung Kontributor', en: 'Join Contributors' },
signIn: { id: 'Sign In', en: 'Sign In' },
signUp: { id: 'Daftar', en: 'Sign Up' },
signedIn: { id: 'Masuk ✓', en: 'Signed In ✓' },
chat: { id: 'Chat', en: 'Chat' },
settings: { id: 'Setting', en: 'Settings' },
tagline: { id: 'Diskusi dan tanya apa saja — jujur, bersumber, bisa diverifikasi.', en: 'Ask anything — honest, sourced, and verifiable.' },
freeBadge: { id: 'AI Agent Gratis · Open Source · Tanpa Langganan', en: 'Free AI Agent · Open Source · No subscription' },
placeholder: { id: 'Tanya SIDIX…', en: 'Ask SIDIX…' },
contribTitle: { id: 'Gabung Kontributor', en: 'Join as Contributor' },
contribSub: { id: 'Developer, researcher, akademisi — semua welcome!', en: 'Developers, researchers, academics — all welcome!' },
contribNameLabel: { id: 'Nama Lengkap', en: 'Full Name' },
contribRoleLabel: { id: 'Peran Kamu', en: 'Your Role' },
contribInterestLabel: { id: 'Mau berkontribusi ke?', en: 'What will you contribute?' },
contribNewsletter: {
id: 'Saya mau dapat newsletter & update terbaru SIDIX via email',
en: 'I want to receive SIDIX newsletter & updates via email',
},
contribCancel: { id: 'Batal', en: 'Cancel' },
contribSubmit: { id: 'Daftar Sekarang', en: 'Join Now' },
aboutSubtitle: { id: 'AI Agent Gratis · Open Source · Self-Hosted', en: 'Free AI Agent · Open Source · Self-Hosted' },
aboutDesc1: {
id: 'SIDIX adalah AI agent gratis yang dibangun di atas prinsip <strong class="text-gold-400">Sidq</strong> (kejujuran), <strong class="text-gold-400">Sanad</strong> (sitasi sumber), dan <strong class="text-gold-400">Tabayyun</strong> (verifikasi).',
en: 'SIDIX is a free AI agent built on principles of <strong class="text-gold-400">Sidq</strong> (honesty), <strong class="text-gold-400">Sanad</strong> (source citation), and <strong class="text-gold-400">Tabayyun</strong> (verification).',
},
aboutDesc2: {
id: 'Open source sepenuhnya. Tidak ada biaya langganan. Data kamu aman di server kami.',
en: 'Fully open source. No subscription fee. Your data stays safe on our servers.',
},
aboutCta: { id: 'Kunjungi sidixlab.com', en: 'Visit sidixlab.com' },
mobContrib: { id: 'Kontributor', en: 'Contribute' },
mobAbout: { id: 'Tentang', en: 'About' },
} as const;
function t(key: keyof typeof T): string {
const entry = T[key] as { id: string; en: string };
return entry[LANG] ?? entry['en'];
}
function applyI18n(): void {
// Header
const labelAbout = document.getElementById('label-about');
const labelContrib = document.getElementById('label-contrib');
const labelAuth = document.getElementById('label-auth');
if (labelAbout) labelAbout.textContent = t('about');
if (labelContrib) labelContrib.textContent = t('contrib');
if (labelAuth) labelAuth.textContent = t('signIn');
// Empty state
const tagline = document.getElementById('empty-tagline');
const freeBadge = document.getElementById('free-badge');
if (tagline) tagline.textContent = t('tagline');
if (freeBadge) {
freeBadge.innerHTML = `<i data-lucide="zap" class="w-3 h-3 text-gold-600"></i><span>${t('freeBadge')}</span>`;
}
// Placeholder
const chatInput = document.getElementById('chat-input') as HTMLTextAreaElement | null;
if (chatInput) chatInput.placeholder = t('placeholder');
// Contributor modal
const contribTitle = document.getElementById('contrib-title');
const contribSub = document.getElementById('contrib-subtitle');
const labelFullname = document.getElementById('label-fullname');
const labelRole = document.getElementById('label-role');
const labelInterest = document.getElementById('label-interest');
const labelNewsletter = document.getElementById('label-newsletter');
const labelCancel = document.getElementById('label-cancel');
const labelSubmit = document.getElementById('label-submit');
if (contribTitle) contribTitle.textContent = t('contribTitle');
if (contribSub) contribSub.textContent = t('contribSub');
if (labelFullname) labelFullname.textContent = t('contribNameLabel');
if (labelRole) labelRole.textContent = t('contribRoleLabel');
if (labelInterest) labelInterest.textContent = t('contribInterestLabel');
if (labelNewsletter) labelNewsletter.textContent = t('contribNewsletter');
if (labelCancel) labelCancel.textContent = t('contribCancel');
if (labelSubmit) labelSubmit.textContent = t('contribSubmit');
// About modal
const aboutSub = document.getElementById('about-subtitle');
const aboutD1 = document.getElementById('about-desc1');
const aboutD2 = document.getElementById('about-desc2');
const aboutCta = document.getElementById('about-cta-main');
if (aboutSub) aboutSub.textContent = t('aboutSubtitle');
if (aboutD1) aboutD1.innerHTML = t('aboutDesc1');
if (aboutD2) aboutD2.textContent = t('aboutDesc2');
if (aboutCta) aboutCta.textContent = t('aboutCta');
// Mobile nav
const mobChat = document.getElementById('mob-label-chat');
const mobSettings = document.getElementById('mob-label-settings');
const mobAbout = document.getElementById('mob-label-about');
const mobAuth = document.getElementById('mob-label-auth');
if (mobChat) mobChat.textContent = t('chat');
if (mobSettings) mobSettings.textContent = t('settings');
if (mobAbout) mobAbout.textContent = t('mobAbout');
if (mobAuth) mobAuth.textContent = t('signIn');
initIcons();
}
// Apply i18n after DOM ready
applyI18n();
// ── About Modal ──────────────────────────────────────────────────────────────
function openAboutModal() {
const m = document.getElementById('about-modal');
if (m) m.classList.remove('hidden');
}
function closeAboutModal() {
const m = document.getElementById('about-modal');
if (m) m.classList.add('hidden');
}
document.getElementById('about-close')?.addEventListener('click', closeAboutModal);
document.getElementById('about-modal')?.addEventListener('click', (e) => {
if (e.target === document.getElementById('about-modal')) closeAboutModal();
});
// Header + mobile: About SIDIX
document.getElementById('btn-about-sidix')?.addEventListener('click', openAboutModal);
document.getElementById('mob-nav-about')?.addEventListener('click', openAboutModal);
// ── Contributor Modal ─────────────────────────────────────────────────────────
let selectedContribRole = 'developer';
function openContribModal() {
const m = document.getElementById('contrib-modal');
if (m) m.classList.remove('hidden');
}
function closeContribModal() {
const m = document.getElementById('contrib-modal');
if (m) m.classList.add('hidden');
}
document.getElementById('btn-contributor')?.addEventListener('click', openContribModal);
document.getElementById('mob-nav-contrib')?.addEventListener('click', openContribModal);
document.getElementById('contrib-cancel')?.addEventListener('click', closeContribModal);
document.getElementById('contrib-modal')?.addEventListener('click', (e) => {
if (e.target === document.getElementById('contrib-modal')) closeContribModal();
});
// Role buttons
document.querySelectorAll<HTMLButtonElement>('.role-btn').forEach(btn => {
btn.addEventListener('click', () => {
selectedContribRole = btn.dataset.role ?? 'developer';
document.querySelectorAll('.role-btn').forEach(b => {
b.classList.remove('border-gold-500', 'text-parchment-100', 'bg-warm-700/40');
});
btn.classList.add('border-gold-500', 'text-parchment-100', 'bg-warm-700/40');
});
// Default highlight
if (btn.dataset.role === 'developer') {
btn.classList.add('border-gold-500', 'text-parchment-100', 'bg-warm-700/40');
}
});
// Submit contributor form
document.getElementById('contrib-submit')?.addEventListener('click', async () => {
const nameEl = document.getElementById('contrib-name') as HTMLInputElement;
const emailEl = document.getElementById('contrib-email') as HTMLInputElement;
const interestEl = document.getElementById('contrib-interest') as HTMLTextAreaElement;
const newsletterEl = document.getElementById('contrib-newsletter') as HTMLInputElement;
const statusEl = document.getElementById('contrib-status');
const submitBtn = document.getElementById('contrib-submit') as HTMLButtonElement;
const name = nameEl?.value.trim();
const email = emailEl?.value.trim();
const interest = interestEl?.value.trim();
const wantsNewsletter = newsletterEl?.checked ?? true;
if (!name || !email || !email.includes('@')) {
if (!name) nameEl?.focus();
else emailEl?.focus();
return;
}
submitBtn.disabled = true;
submitBtn.textContent = LANG === 'id' ? 'Mendaftar…' : 'Joining…';
if (statusEl) statusEl.classList.add('hidden');
try {
// Subscribe newsletter if opted in
if (wantsNewsletter) {
await subscribeNewsletter(email).catch(() => {});
}
// Save contributor profile (own auth state)
const ownUserId = localStorage.getItem('sidix_user_id') || '';
if (ownUserId) {
const { saveDeveloperProfile } = await import('./lib/supabase');
await saveDeveloperProfile({
user_id: ownUserId,
skills: selectedContribRole,
availability: 'TBD',
motivation: interest,
}).catch(() => {});
}
// Save to Supabase contributors table directly
const { supabase } = await import('./lib/supabase');
if (supabase) {
await supabase.from('contributors').upsert({
name,
email: email.toLowerCase(),
role: selectedContribRole,
interest,
wants_newsletter: wantsNewsletter,
lang: LANG,
created_at: new Date().toISOString(),
}, { onConflict: 'email' }).catch(() => {});
}
// Success → close modal + redirect to sidixlab.com#contributor
if (statusEl) {
statusEl.textContent = LANG === 'id' ? '✓ Berhasil! Mengalihkan ke halaman kontributor…' : '✓ Success! Redirecting…';
statusEl.className = 'text-xs text-center text-status-ready mt-3';
statusEl.classList.remove('hidden');
}
setTimeout(() => {
closeContribModal();
window.open('https://sidixlab.com#contributor', '_blank', 'noopener');
}, 1200);
} catch (e) {
if (statusEl) {
statusEl.textContent = `Gagal: ${(e as Error).message}`;
statusEl.className = 'text-xs text-center text-status-failed mt-3';
statusEl.classList.remove('hidden');
}
submitBtn.disabled = false;
submitBtn.textContent = t('contribSubmit');
}
});
// ── Quota Counter + Limit Overlay ────────────────────────────────────────────
function updateQuotaBadge(used: number, limit: number, tier: string, unlimited?: boolean) {
const badge = document.getElementById('quota-badge');
const badgeText = document.getElementById('quota-badge-text');
if (!badge || !badgeText) return;
// Pivot 2026-04-26: hide badge untuk unlimited tier (whitelist / admin / sponsored).
// Display logic:
// guest → tampil "5/5", warna kuning saat ≤2, merah saat 0
// free → tampil "30/30"
// sponsored/whitelist/admin → hidden (no need lihat counter)
const isUnlimited = unlimited === true || tier === 'whitelist' || tier === 'admin' || tier === 'sponsored';
const showBadge = !isUnlimited && (tier === 'guest' || tier === 'free');
if (showBadge) {
const remaining = Math.max(0, limit - used);
badgeText.textContent = `${remaining}/${limit}`;
badge.title = LANG === 'id'
? `Sisa pesan gratis hari ini: ${remaining} dari ${limit}`
: `Remaining free messages today: ${remaining} of ${limit}`;
}
badge.classList.toggle('hidden', !showBadge);
badge.style.display = showBadge ? 'flex' : 'none';
// Untuk unlimited tier, tidak perlu set warna — badge hidden anyway
if (!showBadge) return;
const remaining = Math.max(0, limit - used);
// Warna badge berubah saat hampir habis
if (remaining === 0) {
badge.style.color = '#f87171'; // merah
badge.style.borderColor = 'rgba(248,113,113,0.3)';
} else if (remaining <= 2) {
badge.style.color = '#fbbf24'; // kuning
badge.style.borderColor = 'rgba(251,191,36,0.3)';
} else {
badge.style.color = '#a89b82'; // default
badge.style.borderColor = 'rgba(255,255,255,0.1)';
}
}
function showQuotaOverlay(info: { tier: string; used: number; limit: number; remaining: number; reset_at?: string; topup_url?: string; topup_wa?: string; message?: string }) {
const overlay = document.getElementById('quota-overlay');
const title = document.getElementById('quota-overlay-title');
const msg = document.getElementById('quota-overlay-msg');
const reset = document.getElementById('quota-overlay-reset');
const topupLink = document.getElementById('quota-topup-link') as HTMLAnchorElement | null;
const waLink = document.getElementById('quota-wa-link') as HTMLAnchorElement | null;
if (!overlay) return;
// Update teks
if (title) {
title.textContent = LANG === 'id' ? 'Quota Hari Ini Habis' : 'Daily Quota Reached';
}
if (msg && info.message) {
msg.textContent = info.message;
} else if (msg) {
msg.textContent = LANG === 'id'
? `Kamu sudah pakai ${info.used} dari ${info.limit} pesan gratis hari ini.`
: `You've used ${info.used} of ${info.limit} free messages today.`;
}
// Hitung waktu reset
if (reset && info.reset_at) {
try {
const resetDate = new Date(info.reset_at);
const now = new Date();
const diffMs = resetDate.getTime() - now.getTime();
const diffHrs = Math.ceil(diffMs / (1000 * 60 * 60));
reset.textContent = LANG === 'id' ? `~${diffHrs} jam lagi` : `~${diffHrs} hours`;
} catch {
reset.textContent = LANG === 'id' ? 'besok pagi' : 'tomorrow';
}
}
// Update links
if (topupLink && info.topup_url) topupLink.href = info.topup_url;
if (waLink && info.topup_wa) waLink.href = info.topup_wa;
overlay.classList.remove('hidden');
initIcons();
// Update badge
updateQuotaBadge(info.used, info.limit, info.tier);
}
function closeQuotaOverlay() {
document.getElementById('quota-overlay')?.classList.add('hidden');
}
// Wire quota overlay buttons
document.getElementById('quota-close-btn')?.addEventListener('click', closeQuotaOverlay);
document.getElementById('quota-badge')?.addEventListener('click', () => {
// Klik badge → fetch quota status dan tampilkan overlay jika habis
void fetch(`${BRAIN_QA_BASE}/quota/status`, {
headers: (() => {
const uid = localStorage.getItem('sidix_user_id') ?? '';
return uid ? { 'x-user-id': uid } : {};
})(),
}).then(r => r.json()).then((q: any) => {
if (q && !q.ok && q.remaining === 0) showQuotaOverlay(q);
else if (q) updateQuotaBadge(q.used ?? 0, q.limit ?? 5, q.tier ?? "guest", q.unlimited);
}).catch(() => {});
});
document.getElementById('quota-btn-login')?.addEventListener('click', () => {
closeQuotaOverlay();
openLoginModal();
});
document.getElementById('quota-btn-topup')?.addEventListener('click', () => {
window.open('https://trakteer.id/sidixlab', '_blank', 'noopener');
});
// ── Auth Button (Header + Mobile) ────────────────────────────────────────────
function _initialAvatarDataURL(name: string, bg = '#d4a853'): string {
// Generate SVG circle dengan initial letter (untuk user tanpa Google avatar)
const initial = (name?.[0] || '?').toUpperCase();
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 64 64">
<rect width="64" height="64" rx="32" fill="${bg}"/>
<text x="50%" y="50%" font-family="-apple-system,BlinkMacSystemFont,sans-serif" font-size="28" font-weight="600" fill="#0a0908" text-anchor="middle" dominant-baseline="central">${initial}</text>
</svg>`;
return 'data:image/svg+xml;base64,' + btoa(svg);
}
// ── Own Auth (Pivot 2026-04-26): Google Identity Services + JWT session ──
function ownAuthIsSignedIn(): boolean {
return !!localStorage.getItem('sidix_session_jwt');
}
function ownAuthLogout(): void {
['sidix_session_jwt', 'sidix_user_id', 'sidix_user_email', 'sidix_user_name', 'sidix_user_picture']
.forEach(k => localStorage.removeItem(k));
updateAuthButton(false);
window.location.reload();
}
async function loadOwnAuthUser(): Promise<void> {
const token = localStorage.getItem('sidix_session_jwt');
if (!token) return;
try {
const res = await fetch(`${BRAIN_QA_BASE}/auth/me`, {
headers: { 'Authorization': `Bearer ${token}` },
});
if (!res.ok) {
// Token expired / invalid → silent clear
['sidix_session_jwt', 'sidix_user_id', 'sidix_user_email', 'sidix_user_name', 'sidix_user_picture']
.forEach(k => localStorage.removeItem(k));
updateAuthButton(false);
return;
}
const user = await res.json();
// Update localStorage dengan latest data
localStorage.setItem('sidix_user_id', user.id);
localStorage.setItem('sidix_user_email', user.email);
localStorage.setItem('sidix_user_name', user.name || '');
localStorage.setItem('sidix_user_picture', user.picture || '');
// Sync in-memory state (digunakan oleh isLoggedIn / onboarding)
currentAuthUser = {
id: user.id,
email: user.email,
name: user.name || '',
picture: user.picture || '',
};
updateAuthButton(true, user.name || user.email, user.picture);
console.log('[SIDIX auth] own auth restored:', { name: user.name, email: user.email });
// Refresh quota status (mungkin tier berubah, e.g. whitelist auto-detected)
fetch(`${BRAIN_QA_BASE}/quota/status`, {
headers: {
'Authorization': `Bearer ${token}`,
'x-user-email': user.email,
'x-user-id': user.id,
},
}).then(r => r.json()).then((q: any) => {
if (q) updateQuotaBadge(q.used ?? 0, q.limit ?? 30, q.tier ?? 'free', q.unlimited);
}).catch(() => {});
} catch (e) {
console.warn('[SIDIX auth] /auth/me fail:', e);
}
}
// On page load, restore session kalau ada
if (typeof window !== 'undefined') {
void loadOwnAuthUser();
}
function updateAuthButton(isSignedIn: boolean, displayName?: string, avatarUrl?: string) {
const btnAuth = document.getElementById('btn-auth');
const labelAuth = document.getElementById('label-auth');
const mobAuth = document.getElementById('mob-label-auth');
const authAvatar = document.getElementById('auth-avatar') as HTMLImageElement | null;
const authIcon = document.getElementById('auth-icon');
if (btnAuth) {
btnAuth.classList.toggle('signed-in', isSignedIn);
}
// Pivot 2026-04-26: kalau login, ALWAYS tampilkan avatar (Google URL atau
// fallback initial letter SVG). Icon user generic hanya tampil kalau logout.
if (isSignedIn && authAvatar && authIcon) {
const url = avatarUrl || _initialAvatarDataURL(displayName || 'U');
authAvatar.src = url;
authAvatar.onerror = () => {
// Avatar URL gagal load (CORS, rate limit, dll) → fallback ke initial
authAvatar.src = _initialAvatarDataURL(displayName || 'U');
authAvatar.onerror = null;
};
authAvatar.classList.remove('hidden');
authIcon.classList.add('hidden');
} else if (authAvatar && authIcon) {
authAvatar.classList.add('hidden');
authIcon.classList.remove('hidden');
}
const txt = isSignedIn ? (displayName ? displayName.split(' ')[0] : t('signedIn')) : t('signIn');
if (labelAuth) labelAuth.textContent = txt;
if (mobAuth) mobAuth.textContent = isSignedIn ? '✓' : t('signIn');
}
// Pivot 2026-04-26: own auth via Google Identity Services (bukan Supabase modal).
// Kalau sudah login → show profile mini menu (logout option). Kalau belum → redirect /login.html.
document.getElementById('btn-auth')?.addEventListener('click', () => {
if (ownAuthIsSignedIn()) {
showProfileMenu();
} else {
const next = encodeURIComponent(window.location.pathname + window.location.search);
window.location.href = `/login.html?next=${next}`;
}
});
function showProfileMenu() {
const name = localStorage.getItem('sidix_user_name') || localStorage.getItem('sidix_user_email') || 'User';
const email = localStorage.getItem('sidix_user_email') || '';
if (confirm(`Login sebagai: ${name}\n${email}\n\nKlik OK untuk logout, Cancel untuk tutup.`)) {
ownAuthLogout();
}
}
document.getElementById('mob-nav-auth')?.addEventListener('click', () => {
openLoginModal();
});
// ── Mobile bottom nav wiring ──────────────────────────────────────────────────
const mobNavItems = ['mob-nav-chat', 'mob-nav-settings'] as const;
function setMobileActive(activeId: string) {
['mob-nav-chat', 'mob-nav-about', 'mob-nav-settings', 'mob-nav-auth'].forEach(id => {
const btn = document.getElementById(id);
if (!btn) return;
if (id === activeId) {
btn.classList.add('text-gold-400');
btn.classList.remove('text-parchment-500');
} else {
btn.classList.remove('text-gold-400');
btn.classList.add('text-parchment-500');
}
});
}
document.getElementById('mob-nav-chat')?.addEventListener('click', () => {
switchScreen('chat');
setMobileActive('mob-nav-chat');
});
document.getElementById('mob-nav-settings')?.addEventListener('click', () => {
switchScreen('settings');
setMobileActive('mob-nav-settings');
});
// Initialize mobile active state
setMobileActive('mob-nav-chat');
// ── Admin mode ───────────────────────────────────────────────────────────────
// Kredensial disimpan di sini — untuk keamanan lebih tinggi gunakan Nginx Basic Auth.
const ADMIN_USER = 'admin';
const ADMIN_PASS = 'sidix@ctrl2025';
const ADMIN_KEY = 'sidix_admin';
const IS_CTRL = window.location.hostname === 'ctrl.sidixlab.com'
|| window.location.hostname === 'localhost'; // localhost = dev mode
function isAdmin(): boolean {
return sessionStorage.getItem(ADMIN_KEY) === '1';
}
function setAdminMode(active: boolean) {
if (active) {
sessionStorage.setItem(ADMIN_KEY, '1');
} else {
sessionStorage.removeItem(ADMIN_KEY);
}
applyAdminUI();
}
function applyAdminUI() {
const admin = isAdmin();
const corpusBtn = document.getElementById('nav-corpus');
const lockBtn = document.getElementById('nav-admin-lock');
if (corpusBtn) corpusBtn.classList.toggle('hidden', !admin);
// Lock button hanya muncul di ctrl subdomain
if (lockBtn) {
if (IS_CTRL) {
lockBtn.classList.remove('hidden');
lockBtn.title = admin ? 'Logout dari admin' : 'Login admin';
lockBtn.innerHTML = admin
? '<i data-lucide="lock-open" class="w-4 h-4 text-gold-400"></i>'
: '<i data-lucide="lock" class="w-4 h-4"></i>';
initIcons();
} else {
// app.sidixlab.com — sembunyikan sepenuhnya
lockBtn.classList.add('hidden');
}
}
// Jika keluar dari admin mode saat di corpus screen, kembali ke chat
if (!admin) {
const corpusVisible = !document.getElementById('screen-corpus')?.classList.contains('hidden');
if (corpusVisible) switchScreen('chat');
}
}
// Admin login modal wiring
const pinModal = document.getElementById('admin-pin-modal');
const userInput = document.getElementById('admin-username-input') as HTMLInputElement;
const pinInput = document.getElementById('admin-pin-input') as HTMLInputElement;
const pinError = document.getElementById('admin-pin-error');
const pinConfirm = document.getElementById('admin-pin-confirm');
const pinCancel = document.getElementById('admin-pin-cancel');
function openPinModal() {
if (pinModal) pinModal.classList.remove('hidden');
if (userInput) { userInput.value = ''; userInput.focus(); }
if (pinInput) { pinInput.value = ''; }
if (pinError) pinError.classList.add('hidden');
}
function closePinModal() {
if (pinModal) pinModal.classList.add('hidden');
}
function confirmLogin() {
const u = userInput?.value.trim();
const p = pinInput?.value;
if (u === ADMIN_USER && p === ADMIN_PASS) {
setAdminMode(true);
closePinModal();
} else {
if (pinError) pinError.classList.remove('hidden');
if (pinInput) { pinInput.value = ''; pinInput.focus(); }
}
}
pinConfirm?.addEventListener('click', confirmLogin);
pinCancel?.addEventListener('click', () => {
closePinModal();
// Di ctrl subdomain, batalkan login → tetap di halaman tapi tanpa admin
});
pinInput?.addEventListener('keydown', (e) => { if (e.key === 'Enter') confirmLogin(); });
userInput?.addEventListener('keydown', (e) => { if (e.key === 'Enter') pinInput?.focus(); });
document.getElementById('nav-admin-lock')?.addEventListener('click', () => {
if (isAdmin()) {
setAdminMode(false);
} else {
openPinModal();
}
});
// Apply on load
applyAdminUI();
// ctrl subdomain: tampilkan login jika belum auth
if (IS_CTRL && !isAdmin()) {
openPinModal();
}
// ── User Auth & Login Gate ────────────────────────────────────────────────────
// Sistem: 1 chat gratis → paksa login → onboarding interview → lanjut
// Data dikumpulkan: nama, email, fitur request, review AI, ekspektasi
const CHAT_COUNT_KEY = 'sidix_chat_count';
const USER_ONBOARDED_KEY = 'sidix_onboarded';
// Limit chat anonim: 5 pesan gratis sebelum login modal muncul.
// Sebelumnya 1 — terlalu agresif (user terkesan dipaksa daftar dari awal).
// Sekarang user bisa coba ngobrol beberapa pesan dulu, baru disuruh login
// kalau ingin lanjut.
const FREE_CHAT_LIMIT = 5;
/** State current user (null = belum login) — own auth via JWT in localStorage */
interface OwnAuthUser {
id: string;
email: string;
name: string;
picture: string;
}
let currentAuthUser: OwnAuthUser | null = null;
/** Step onboarding: 0 = belum mulai, 1-7 = pertanyaan, 8 = selesai */
let onboardingStep = 0;
let onboardingAnswers: Record<string, string> = {};
const ONBOARDING_QUESTIONS = [
"Hei! Senang kamu mau coba SIDIX 🎉\n\nSebelum mulai, boleh bantu kami berkembang? Ada beberapa pertanyaan singkat.\n\n**Pertanyaan 1/5:** Fitur AI apa yang paling kamu butuhkan sehari-hari? (contoh: nulis, coding, riset, ngobrol, dll)",
"**Pertanyaan 2/5:** AI agent apa yang biasa kamu pakai? (ChatGPT, Claude, Gemini, Copilot, dll — atau belum pakai yang lain?)",
"**Pertanyaan 3/5:** Apa yang paling kamu suka dari AI yang ada sekarang?",
"**Pertanyaan 4/5:** Apa yang paling bikin frustrasi atau kurang dari AI yang ada?",
"**Pertanyaan 5/5:** Kalau SIDIX bisa tambah 1 fitur minggu ini khusus buat kamu, fitur apa itu?",
"Hampir selesai! **Kamu ini lebih cocok sebagai:**\n\n1️⃣ User biasa (mau pakai AI untuk produktivitas)\n2️⃣ Developer (mau ikut kontribusi code)\n3️⃣ Researcher/Akademisi (mau kolaborasi riset)\n\nJawab dengan angka 1, 2, atau 3 ya!",
"Terima kasih sudah meluangkan waktu! 🙏\n\nJawaban kamu sangat berarti untuk pengembangan SIDIX.\n\n**Kamu adalah salah satu beta tester pertama SIDIX!** 🚀\n\nSIDIX adalah free AI agent open source — dibangun untuk komunitas Indonesia & global, gratis sepenuhnya, tidak ada hidden cost.\n\nAda pertanyaan lain? Langsung tanya ke sini — saya siap membantu!",
];
function getChatCount(): number {
return parseInt(localStorage.getItem(CHAT_COUNT_KEY) || '0', 10);
}
function incrementChatCount(): number {
const n = getChatCount() + 1;
localStorage.setItem(CHAT_COUNT_KEY, String(n));
return n;
}
function isLoggedIn(): boolean {
return ownAuthIsSignedIn();
}
function isOnboarded(): boolean {
return localStorage.getItem(USER_ONBOARDED_KEY) === '1';
}
function markOnboarded(): void {
localStorage.setItem(USER_ONBOARDED_KEY, '1');
}
// ── Login redirect (Pivot 2026-04-26: own auth, no modal) ───────────────────
// Old modal removed — kita pakai dedicated /login.html dengan Google Identity
// Services button. Redirect dengan ?next=<current-url> untuk return setelah login.
function openLoginModal(): void {
const next = encodeURIComponent(window.location.pathname + window.location.search);
window.location.href = `/login.html?next=${next}`;
}
function closeLoginModal(): void {
// No-op untuk backward compat. /login.html adalah full page.
if (sendBtn) sendBtn.disabled = false;
}
// ── Onboarding Interview (auto-chat dari SIDIX setelah login) ─────────────────
async function startOnboardingIfNeeded(): Promise<void> {
if (!isLoggedIn() || isOnboarded()) return;
onboardingStep = 0;
const userId = localStorage.getItem('sidix_user_id') || (currentAuthUser?.id ?? '');
onboardingAnswers = { user_id: userId };
// Tunda 800ms biar UI settle
await new Promise(r => setTimeout(r, 800));
sendOnboardingMessage(ONBOARDING_QUESTIONS[0]);
onboardingStep = 1;
}
function sendOnboardingMessage(text: string): void {
appendMessage('ai', text);
}
async function handleOnboardingReply(userText: string): Promise<boolean> {
if (!isLoggedIn() || isOnboarded()) return false;
if (onboardingStep === 0 || onboardingStep >= ONBOARDING_QUESTIONS.length) return false;
// Simpan jawaban sesuai step
switch (onboardingStep) {
case 1: onboardingAnswers.ai_features_wanted = userText; break;
case 2: onboardingAnswers.ai_agents_used = userText; break;
case 3: onboardingAnswers.ai_liked = userText; break;
case 4: onboardingAnswers.ai_frustrations = userText; break;
case 5: onboardingAnswers.one_feature_request = userText; break;
case 6:
// Parse role dari angka (UserRole type di-deprecate; pakai literal string)
const roleMap: Record<string, 'user' | 'developer' | 'researcher'> = { '1': 'user', '2': 'developer', '3': 'researcher' };
const roleKey = userText.trim().charAt(0);
onboardingAnswers.role = roleMap[roleKey] || 'user';
onboardingAnswers.contribute_interest = userText;
break;
}
onboardingStep++;
if (onboardingStep < ONBOARDING_QUESTIONS.length) {
// Pertanyaan berikutnya
setTimeout(() => sendOnboardingMessage(ONBOARDING_QUESTIONS[onboardingStep - 1 >= 6 ? 6 : onboardingStep - 1 + 1 <= 6 ? onboardingStep : 6]), 600);
// Fix: tampilkan pertanyaan berikutnya
const nextIdx = onboardingStep - 1;
setTimeout(() => sendOnboardingMessage(ONBOARDING_QUESTIONS[nextIdx < ONBOARDING_QUESTIONS.length ? nextIdx : ONBOARDING_QUESTIONS.length - 1]), 600);
return true;
}
// Pivot 2026-04-26: onboarding storage di-pause sementara (Supabase tables
// di-deprecate). Bisa di-revive nanti kalau perlu, simpan ke /admin/onboarding
// endpoint baru atau aktivitas log JSONL. Untuk sekarang, tandai selesai supaya
// gak loop lagi.
markOnboarded();
// Tampilkan pesan terima kasih
setTimeout(() => sendOnboardingMessage(ONBOARDING_QUESTIONS[ONBOARDING_QUESTIONS.length - 1]), 600);
return true;
}
// ── Auth state listener (Pivot 2026-04-26: own auth, no Supabase) ───────────
// onAuthChange listener Supabase di-replace dengan loadOwnAuthUser() yang
// dipanggil di page-load (lihat line ~571). Listener tidak perlu karena flow
// own auth: redirect /login.html → callback simpan ke localStorage → reload →
// loadOwnAuthUser() restore session.
//
// Untuk sync currentAuthUser state setelah login.html callback, kita hook ke
// loadOwnAuthUser:
async function _syncCurrentAuthUserFromOwnAuth(): Promise<void> {
if (!ownAuthIsSignedIn()) {
currentAuthUser = null;
return;
}
const id = localStorage.getItem('sidix_user_id') || '';
const email = localStorage.getItem('sidix_user_email') || '';
const name = localStorage.getItem('sidix_user_name') || '';
const picture = localStorage.getItem('sidix_user_picture') || '';
if (!id) {
currentAuthUser = null;
return;
}
currentAuthUser = { id, email, name, picture };
}
// Run sync immediately on module load
void _syncCurrentAuthUserFromOwnAuth();
// ── Elements ─────────────────────────────────────────────────────────────────
const $ = <T extends HTMLElement>(id: string) => document.getElementById(id) as T;
const screens = { chat: $('screen-chat'), corpus: $('screen-corpus'), settings: $('screen-settings') };
const navBtns = { chat: $('nav-chat'), corpus: $('nav-corpus'), settings: $('nav-settings') };
const statusDot = $('status-dot');
const statusTxt = $('status-text');
// Chat
const chatMessages = $('chat-messages');
const chatInput = $<HTMLTextAreaElement>('chat-input');
const sendBtn = $<HTMLButtonElement>('send-btn');
const personaSel = $<HTMLSelectElement>('persona-selector');
const chatEmpty = $('chat-empty');
const optCorpusOnly = document.getElementById('opt-corpus-only') as HTMLInputElement | null;
const optAllowWeb = document.getElementById('opt-allow-web') as HTMLInputElement | null;
const optSimple = document.getElementById('opt-simple') as HTMLInputElement | null;
function collectAskOpts(): AskInferenceOpts {
const corpus_only = optCorpusOnly?.checked ?? false;
const allow_web_fallback = corpus_only ? false : (optAllowWeb?.checked ?? true);
return {
corpus_only,
allow_web_fallback,
simple_mode: optSimple?.checked ?? false,
};
}
optCorpusOnly?.addEventListener('change', () => {
if (optAllowWeb) optAllowWeb.disabled = optCorpusOnly?.checked ?? false;
});
const forgetSessionBtn = document.getElementById('forget-session-btn') as HTMLButtonElement | null;
/** Session ID terakhir dari stream (server-side trace). */
let lastServerSessionId: string | null = null;
/** Conversation ID untuk memory persistence antar chat. */
let currentConversationId: string | null = null;
function setLastSessionId(id: string | null) {
lastServerSessionId = id && id.length > 0 ? id : null;
if (forgetSessionBtn) {
if (lastServerSessionId) {
forgetSessionBtn.classList.remove('hidden');
} else {
forgetSessionBtn.classList.add('hidden');
}
}
}
function getCurrentConversationId(): string | null {
if (!currentConversationId) {
try {
currentConversationId = localStorage.getItem('sidix_conversation_id');
} catch { /* ignore */ }
}
return currentConversationId;
}
function setCurrentConversationId(id: string | null) {
currentConversationId = id && id.length > 0 ? id : null;
try {
if (currentConversationId) {
localStorage.setItem('sidix_conversation_id', currentConversationId);
} else {
localStorage.removeItem('sidix_conversation_id');
}
} catch { /* ignore */ }
}
forgetSessionBtn?.addEventListener('click', async () => {
if (!lastServerSessionId) return;
try {
await forgetAgentSession(lastServerSessionId);