RamshaAnwar commited on
Commit
bc2b07b
·
unverified ·
1 Parent(s): 0358051

feat(web): add vanilla JS one-file console with CORS, PDF upload, and custom themeFeat/web console (#18)

Browse files

* fix(cors): allow live server origins and expose idempotency headers

* feat(web): build one-file console with custom theme, pdf upload, and settings

Files changed (3) hide show
  1. .env.example +2 -2
  2. app/main.py +11 -1
  3. frontend/index.html +641 -0
.env.example CHANGED
@@ -11,7 +11,7 @@ CHUNK_SIZE_TOKENS=500
11
  CHUNK_OVERLAP_TOKENS=50
12
  INLINE_SYNC_MAX_CHARS=20000
13
  RAG_TOP_K=5
14
- RAG_MIN_SIMILARITY=0.55
15
  RAG_FAITHFULNESS_MIN=0.70
16
  RAG_RELEVANCY_MIN=0.70
17
- CORS_ORIGINS=http://localhost:3000
 
11
  CHUNK_OVERLAP_TOKENS=50
12
  INLINE_SYNC_MAX_CHARS=20000
13
  RAG_TOP_K=5
14
+ RAG_MIN_SIMILARITY=0.25
15
  RAG_FAITHFULNESS_MIN=0.70
16
  RAG_RELEVANCY_MIN=0.70
17
+ CORS_ORIGINS=http://localhost:3000,http://127.0.0.1:3000
app/main.py CHANGED
@@ -4,6 +4,7 @@ from fastapi import FastAPI, Request, Depends
4
  from fastapi.middleware.cors import CORSMiddleware
5
  from fastapi.exceptions import RequestValidationError
6
  from starlette.exceptions import HTTPException as StarletteHTTPException
 
7
  from transparent_fastapi import install
8
 
9
  from app.config import settings
@@ -28,10 +29,19 @@ def create_app() -> FastAPI:
28
 
29
  app.add_middleware(
30
  CORSMiddleware,
31
- allow_origins=settings.cors_origins_list,
 
 
 
 
 
 
 
 
32
  allow_credentials=True,
33
  allow_methods=["*"],
34
  allow_headers=["*"],
 
35
  )
36
 
37
  app.include_router(auth.router, prefix="/api/v1")
 
4
  from fastapi.middleware.cors import CORSMiddleware
5
  from fastapi.exceptions import RequestValidationError
6
  from starlette.exceptions import HTTPException as StarletteHTTPException
7
+ import app
8
  from transparent_fastapi import install
9
 
10
  from app.config import settings
 
29
 
30
  app.add_middleware(
31
  CORSMiddleware,
32
+ allow_origins=[
33
+ "http://localhost:3000",
34
+ "http://127.0.0.1:3000",
35
+ "http://localhost:8000",
36
+ "http://127.0.0.1:8000",
37
+ "http://localhost:5500", # <-- Add this (Live Server localhost)
38
+ "http://127.0.0.1:5500",
39
+ "null", # <--- THIS IS CRITICAL FOR LOCAL FILE TESTING
40
+ ],
41
  allow_credentials=True,
42
  allow_methods=["*"],
43
  allow_headers=["*"],
44
+ expose_headers=["X-Request-ID", "Idempotent-Replayed", "Retry-After"],
45
  )
46
 
47
  app.include_router(auth.router, prefix="/api/v1")
frontend/index.html ADDED
@@ -0,0 +1,641 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>ContextQuery AI</title>
7
+
8
+ <!-- Miranda Sans Font -->
9
+ <link rel="preconnect" href="https://fonts.googleapis.com">
10
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
11
+ <link href="https://fonts.googleapis.com/css2?family=Miranda+Sans:ital,wght@0,400..700;1,400..700&display=swap" rel="stylesheet">
12
+
13
+ <style>
14
+ :root {
15
+ --deep-navy: #010736;
16
+ --dark-navy: #0D1C42;
17
+ --med-blue: #22396F;
18
+ --cream: #FCF1D0;
19
+
20
+ --bg: var(--cream);
21
+ --sidebar: var(--deep-navy);
22
+ --primary: var(--med-blue);
23
+ --primary-hover: var(--dark-navy);
24
+ --text-main: var(--deep-navy);
25
+ --text-sidebar: var(--cream);
26
+ --text-muted: var(--dark-navy);
27
+ --border: rgba(34, 57, 111, 0.2);
28
+ --danger: #ef4444;
29
+ }
30
+
31
+ * { box-sizing: border-box; margin: 0; padding: 0; font-family: "Miranda Sans", sans-serif; }
32
+ body { background: var(--bg); color: var(--text-main); height: 100vh; display: flex; overflow: hidden; }
33
+
34
+ /* Layout */
35
+ .sidebar { width: 320px; background: var(--sidebar); border-right: 1px solid var(--deep-navy); display: flex; flex-direction: column; transition: all 0.3s; color: var(--text-sidebar); }
36
+ .main-content { flex: 1; display: flex; flex-direction: column; position: relative; background: var(--bg); }
37
+
38
+ /* Sidebar Elements */
39
+ .sidebar-header { padding: 24px 20px; border-bottom: 1px solid rgba(252, 241, 208, 0.1); }
40
+ .sidebar-header h1 { font-size: 20px; font-weight: 700; color: var(--cream); display: flex; align-items: center; gap: 8px; }
41
+
42
+ .hub-list { flex: 1; overflow-y: auto; padding: 10px; }
43
+ .hub-item { padding: 14px 16px; border-radius: 8px; cursor: pointer; margin-bottom: 4px; transition: background 0.2s; border: 1px solid transparent; }
44
+ .hub-item:hover { background: var(--dark-navy); }
45
+ .hub-item.active { background: var(--med-blue); border-color: var(--cream); }
46
+ .hub-item h3 { font-size: 14px; font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; color: var(--cream); margin: 0; }
47
+
48
+ .sidebar-footer { padding: 20px; border-top: 1px solid rgba(252, 241, 208, 0.1); }
49
+
50
+ /* Buttons & Inputs */
51
+ button { width: 100%; padding: 10px 16px; border-radius: 8px; border: none; background: var(--primary); color: var(--cream); font-weight: 600; cursor: pointer; transition: background 0.2s; display: flex; justify-content: center; align-items: center; gap: 8px; }
52
+ button:hover { background: var(--primary-hover); }
53
+ button:disabled { opacity: 0.6; cursor: not-allowed; }
54
+
55
+ button.secondary { background: transparent; color: var(--cream); border: 1px solid var(--cream); }
56
+ button.secondary:hover { background: rgba(252, 241, 208, 0.1); }
57
+ .auth-card button.secondary { color: var(--med-blue); border: 1px solid var(--med-blue); }
58
+ .auth-card button.secondary:hover { background: rgba(34, 57, 111, 0.05); }
59
+
60
+ /* Top Header Actions */
61
+ .header-actions { display: flex; gap: 10px; align-items: center; }
62
+ .btn-icon { background: transparent; border: 1px solid var(--med-blue); color: var(--med-blue); padding: 8px 12px; border-radius: 8px; cursor: pointer; transition: all 0.2s; font-size: 16px; width: auto; display: flex; align-items: center; justify-content: center; }
63
+ .btn-icon:hover { background: rgba(34, 57, 111, 0.1); }
64
+ .btn-icon.danger { color: var(--danger); border-color: var(--danger); }
65
+ .btn-icon.danger:hover { background: rgba(239, 68, 68, 0.1); }
66
+
67
+ input, textarea { width: 100%; padding: 12px; border: 1px solid var(--border); border-radius: 8px; font-size: 14px; outline: none; transition: border 0.2s; background: white; color: var(--deep-navy); }
68
+ input:focus, textarea:focus { border-color: var(--med-blue); box-shadow: 0 0 0 3px rgba(34, 57, 111, 0.1); }
69
+
70
+ /* Auth Screen */
71
+ .auth-overlay {
72
+ position: fixed; inset: 0;
73
+ background: linear-gradient(-45deg, #FCF1D0, #22396F, #0D1C42, #010736);
74
+ background-size: 400% 400%;
75
+ animation: gradientBG 15s ease infinite;
76
+ display: flex; justify-content: center; align-items: center; z-index: 50;
77
+ }
78
+ @keyframes gradientBG { 0% { background-position: 0% 50%; } 50% { background-position: 100% 50%; } 100% { background-position: 0% 50%; } }
79
+
80
+ .auth-card { background: #ffffff; padding: 40px; border-radius: 16px; box-shadow: 0 10px 25px rgba(1, 7, 54, 0.15); width: 100%; max-width: 400px; border: 1px solid rgba(34, 57, 111, 0.1); position: relative; color: var(--deep-navy); }
81
+ .auth-card h2 { margin-bottom: 24px; text-align: center; font-size: 24px; font-weight: 700; color: var(--deep-navy); }
82
+ .auth-card input { margin-bottom: 16px; border-color: rgba(34, 57, 111, 0.3); }
83
+ .auth-card textarea { margin-bottom: 16px; resize: vertical; border-color: rgba(34, 57, 111, 0.3); }
84
+ .auth-card .btn-group { display: flex; gap: 12px; margin-top: 16px; }
85
+
86
+ .password-wrapper { position: relative; margin-bottom: 16px; }
87
+ .password-wrapper input { margin-bottom: 0; padding-right: 40px; }
88
+ .eye-icon { position: absolute; right: 12px; top: 50%; transform: translateY(-50%); cursor: pointer; font-size: 18px; color: var(--med-blue); user-select: none; }
89
+
90
+ .file-upload-wrapper { margin-bottom: 16px; border: 1px dashed var(--med-blue); padding: 16px; border-radius: 8px; text-align: center; background: rgba(34, 57, 111, 0.02); }
91
+ .file-upload-wrapper label { font-size: 14px; font-weight: 600; color: var(--med-blue); cursor: pointer; display: block; }
92
+ .file-upload-wrapper input[type="file"] { display: none; }
93
+
94
+ /* Chat Area */
95
+ .chat-header { padding: 20px; border-bottom: 1px solid var(--border); background: var(--cream); display: flex; justify-content: space-between; align-items: center; }
96
+ .chat-header h2 { font-size: 18px; color: var(--deep-navy); }
97
+ .chat-history { flex: 1; overflow-y: auto; padding: 24px; display: flex; flex-direction: column; gap: 20px; }
98
+
99
+ .message { max-width: 80%; padding: 16px; border-radius: 12px; font-size: 15px; line-height: 1.5; animation: fadeIn 0.3s ease; }
100
+ .message.user { align-self: flex-end; background: var(--med-blue); color: var(--cream); border-bottom-right-radius: 4px; }
101
+ .message.ai { align-self: flex-start; background: white; color: var(--deep-navy); border: 1px solid var(--border); border-bottom-left-radius: 4px; box-shadow: 0 2px 5px rgba(1, 7, 54, 0.05); }
102
+ .message pre { white-space: pre-wrap; font-family: inherit; }
103
+
104
+ .evidence-badge { display: inline-block; margin-top: 10px; padding: 4px 8px; background: var(--cream); border-radius: 4px; font-size: 12px; color: var(--dark-navy); border: 1px solid rgba(34, 57, 111, 0.3); }
105
+
106
+ .doc-chip { display: inline-flex; align-items: center; gap: 8px; background: #f1f5f9; border: 1px solid #cbd5e1; padding: 8px 12px; border-radius: 8px; font-size: 13px; color: var(--dark-navy); font-weight: 600; margin-bottom: 8px; align-self: flex-end; animation: fadeIn 0.3s ease; }
107
+
108
+ .chat-input-area { padding: 20px; background: var(--cream); border-top: 1px solid var(--border); }
109
+ .chat-input-wrapper { display: flex; gap: 12px; align-items: center; background: white; padding: 8px; border-radius: 12px; border: 1px solid rgba(34, 57, 111, 0.3); box-shadow: 0 2px 6px rgba(0,0,0,0.02); }
110
+ .chat-input-wrapper input { border: none; box-shadow: none; padding: 8px; flex: 1; }
111
+ .chat-input-wrapper input:focus { box-shadow: none; }
112
+
113
+ .btn-attach { background: transparent; border: none; color: var(--med-blue); font-size: 20px; padding: 8px; cursor: pointer; width: auto; border-radius: 8px; transition: background 0.2s; }
114
+ .btn-attach:hover { background: rgba(34, 57, 111, 0.1); }
115
+ .btn-send { background: var(--med-blue); border: none; color: var(--cream); padding: 10px 20px; border-radius: 8px; font-weight: 600; cursor: pointer; transition: background 0.2s; width: auto; margin-left: 8px; }
116
+ .btn-send:hover { background: var(--dark-navy); }
117
+
118
+ /* Suggested Questions */
119
+ .suggestions-container { display: flex; flex-direction: column; gap: 10px; margin-top: 20px; align-self: center; max-width: 600px; text-align: center; }
120
+ .suggestion-chip { background: white; border: 1px solid var(--med-blue); color: var(--med-blue); padding: 12px 20px; border-radius: 20px; cursor: pointer; transition: all 0.2s; font-weight: 600; }
121
+ .suggestion-chip:hover { background: var(--med-blue); color: var(--cream); }
122
+
123
+ /* Empty State */
124
+ .empty-state { flex: 1; display: flex; flex-direction: column; justify-content: center; align-items: center; color: var(--text-muted); text-align: center; padding: 40px; }
125
+ .empty-state h2 { font-size: 24px; color: var(--deep-navy); margin-bottom: 8px; }
126
+
127
+ /* Utilities */
128
+ .hidden { display: none !important; }
129
+ .error-msg { color: var(--danger); font-size: 13px; margin-top: 8px; text-align: center; font-weight: 600; }
130
+ .toast { position: fixed; bottom: 20px; right: 20px; padding: 12px 24px; border-radius: 8px; background: var(--deep-navy); color: var(--cream); font-size: 14px; box-shadow: 0 4px 12px rgba(1, 7, 54, 0.3); z-index: 100; transform: translateY(100px); opacity: 0; transition: all 0.3s; }
131
+ .toast.show { transform: translateY(0); opacity: 1; }
132
+ .spinner { width: 16px; height: 16px; border: 2px solid rgba(34, 57, 111, 0.3); border-top-color: var(--med-blue); border-radius: 50%; animation: spin 0.8s linear infinite; }
133
+ .spinner-light { border: 2px solid rgba(252, 241, 208, 0.3); border-top-color: var(--cream); }
134
+
135
+ @keyframes spin { to { transform: rotate(360deg); } }
136
+ @keyframes fadeIn { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } }
137
+ </style>
138
+ </head>
139
+ <body>
140
+
141
+ <!-- AUTH SCREEN -->
142
+ <div id="auth-screen" class="auth-overlay">
143
+ <div class="auth-card">
144
+ <h2>Welcome to ContextQuery</h2>
145
+ <input type="email" id="auth-email" placeholder="Email" value="user@test.com">
146
+ <div class="password-wrapper">
147
+ <input type="password" id="auth-password" placeholder="Password" value="Password123">
148
+ <span class="eye-icon" onclick="togglePassword('auth-password', 'eye-auth')" id="eye-auth">👁️</span>
149
+ </div>
150
+ <div class="btn-group">
151
+ <button onclick="login()" id="login-btn">Login</button>
152
+ <button onclick="signup()" class="secondary" id="signup-btn">Sign Up</button>
153
+ </div>
154
+ <div id="auth-error" class="error-msg hidden"></div>
155
+ </div>
156
+ </div>
157
+
158
+ <!-- MAIN DASHBOARD -->
159
+ <div id="dashboard" class="hidden" style="display:flex; width:100%; height:100%;">
160
+ <!-- SIDEBAR -->
161
+ <div class="sidebar">
162
+ <div class="sidebar-header">
163
+ <h1>🧠 ContextQuery</h1>
164
+ </div>
165
+ <div class="hub-list" id="hub-list"></div>
166
+ <div class="sidebar-footer">
167
+ <button onclick="openCreateModal()" class="secondary">+ New Hub</button>
168
+ </div>
169
+ </div>
170
+
171
+ <!-- MAIN CHAT AREA -->
172
+ <div class="main-content">
173
+ <div id="empty-state" class="empty-state">
174
+ <h2>No Hub Selected</h2>
175
+ <p>Select a hub from the sidebar or create a new one to start asking questions.</p>
176
+ </div>
177
+
178
+ <div id="chat-container" class="hidden" style="display:flex; flex-direction:column; height:100%;">
179
+ <div class="chat-header">
180
+ <h2 id="chat-title">Hub Name</h2>
181
+ <!-- Top Right Actions -->
182
+ <div class="header-actions">
183
+ <button class="btn-icon" onclick="refreshHub()" title="Sync Data">🔄</button>
184
+ <button class="btn-icon danger" onclick="deleteHub()" title="Delete Hub">🗑️</button>
185
+ <button class="btn-icon" onclick="openSettingsModal()" title="Account Settings">⚙️</button>
186
+ <button class="btn-icon" onclick="logout()" title="Logout">🚪</button>
187
+ </div>
188
+ </div>
189
+
190
+ <div class="chat-history" id="chat-history"></div>
191
+
192
+ <div class="chat-input-area">
193
+ <div class="chat-input-wrapper">
194
+ <input type="file" id="pdf-upload" accept=".pdf,.txt,.md" style="display:none" onchange="uploadDocument(event)">
195
+ <button class="btn-attach" onclick="document.getElementById('pdf-upload').click()" id="attach-btn" title="Attach Document">📎</button>
196
+
197
+ <input type="text" id="query-input" placeholder="Ask a question or attach a document..." onkeypress="handleKeyPress(event)">
198
+
199
+ <button class="btn-send" onclick="askQuestion()" id="ask-btn">Ask</button>
200
+ </div>
201
+ </div>
202
+ </div>
203
+ </div>
204
+ </div>
205
+
206
+ <!-- CREATE HUB MODAL -->
207
+ <div id="create-modal" class="auth-overlay hidden" style="background: rgba(1, 7, 54, 0.6); backdrop-filter: blur(4px);">
208
+ <div class="auth-card">
209
+ <h2>Create New Hub</h2>
210
+ <input type="text" id="new-hub-name" placeholder="Hub Name (e.g., HR Policies)">
211
+ <textarea id="new-hub-content" rows="3" placeholder="Paste text data here (Optional)..."></textarea>
212
+
213
+ <div class="file-upload-wrapper">
214
+ <label for="new-hub-file">📄 Or click to upload a PDF / Text file</label>
215
+ <input type="file" id="new-hub-file" accept=".pdf,.txt,.md">
216
+ <div id="file-name-display" style="font-size: 12px; color: var(--text-muted); margin-top: 8px;">No file selected</div>
217
+ </div>
218
+
219
+ <div class="btn-group">
220
+ <button onclick="createHub()" id="create-hub-btn">Create Hub</button>
221
+ <button onclick="closeCreateModal()" class="secondary">Cancel</button>
222
+ </div>
223
+ <div id="create-error" class="error-msg hidden"></div>
224
+ </div>
225
+ </div>
226
+
227
+ <!-- SETTINGS / CHANGE PASSWORD MODAL -->
228
+ <div id="settings-modal" class="auth-overlay hidden" style="background: rgba(1, 7, 54, 0.6); backdrop-filter: blur(4px);">
229
+ <div class="auth-card">
230
+ <h2>Account Settings</h2>
231
+ <div style="margin-bottom: 16px;">
232
+ <label style="font-size: 14px; font-weight: 600; margin-bottom: 8px; display: block;">Change Password</label>
233
+ <div class="password-wrapper">
234
+ <input type="password" id="current-password" placeholder="Current Password">
235
+ </div>
236
+ <div class="password-wrapper">
237
+ <input type="password" id="new-password" placeholder="New Password">
238
+ </div>
239
+ </div>
240
+ <div class="btn-group">
241
+ <button onclick="changePassword()" id="change-pass-btn">Update Password</button>
242
+ <button onclick="closeSettingsModal()" class="secondary">Cancel</button>
243
+ </div>
244
+ <div id="settings-error" class="error-msg hidden"></div>
245
+ <div id="settings-success" class="error-msg hidden" style="color: #16a34a;"></div>
246
+ </div>
247
+ </div>
248
+
249
+ <div id="toast" class="toast">Notification</div>
250
+
251
+ <script>
252
+ const API = "http://localhost:8000/api/v1";
253
+ let currentHubId = null;
254
+ let allHubs = [];
255
+ let chatHistories = {};
256
+
257
+ // --- UTILS & UI ---
258
+ function showToast(msg) { const toast = document.getElementById("toast"); toast.textContent = msg; toast.classList.add("show"); setTimeout(() => toast.classList.remove("show"), 3000); }
259
+ function showError(id, msg) { const el = document.getElementById(id); el.textContent = msg; el.classList.remove("hidden"); el.style.color = "var(--danger)"; }
260
+ function showSuccess(id, msg) { const el = document.getElementById(id); el.textContent = msg; el.classList.remove("hidden"); el.style.color = "#16a34a"; }
261
+ function hideError(id) { document.getElementById(id).classList.add("hidden"); }
262
+
263
+ function togglePassword(inputId, iconId) {
264
+ const input = document.getElementById(inputId);
265
+ const icon = document.getElementById(iconId);
266
+ if (input.type === "password") { input.type = "text"; icon.textContent = "🙈"; }
267
+ else { input.type = "password"; icon.textContent = "👁️"; }
268
+ }
269
+
270
+ function setLoading(btnId, isLoading, text = "Loading...", isLight = false) {
271
+ const btn = document.getElementById(btnId);
272
+ if (isLoading) {
273
+ btn.dataset.original = btn.innerHTML;
274
+ btn.innerHTML = `<div class="spinner ${isLight ? 'spinner-light' : ''}"></div> ${text}`;
275
+ btn.disabled = true;
276
+ } else {
277
+ btn.innerHTML = btn.dataset.original;
278
+ btn.disabled = false;
279
+ }
280
+ }
281
+
282
+ // --- AUTHENTICATION ---
283
+ function getToken() { return sessionStorage.getItem("token"); }
284
+ function setToken(token) { sessionStorage.setItem("token", token); showDashboard(); }
285
+ function logout() { sessionStorage.removeItem("token"); location.reload(); }
286
+
287
+ async function apiFetch(path, options = {}) {
288
+ const token = getToken();
289
+ const headers = { ...(token && { "Authorization": `Bearer ${token}` }), ...options.headers };
290
+ if (!(options.body instanceof FormData)) headers["Content-Type"] = "application/json";
291
+
292
+ try {
293
+ const res = await fetch(`${API}${path}`, { ...options, headers });
294
+ if (res.status === 401) { logout(); return; }
295
+ if (res.status === 204) return {}; // Handle DELETE success
296
+ const data = await res.json();
297
+ if (!res.ok) throw new Error(data.error?.message || "Request failed");
298
+ return data;
299
+ } catch (err) {
300
+ if (err.message === "Failed to fetch") throw new Error("Failed to fetch. Is the backend running?");
301
+ throw err;
302
+ }
303
+ }
304
+
305
+ async function login() {
306
+ const email = document.getElementById("auth-email").value;
307
+ const password = document.getElementById("auth-password").value;
308
+ hideError("auth-error"); setLoading("login-btn", true, "Logging in...", true);
309
+ try {
310
+ const data = await apiFetch("/auth/login", { method: "POST", body: JSON.stringify({ email, password }) });
311
+ setToken(data.access_token);
312
+ } catch (e) { showError("auth-error", e.message); setLoading("login-btn", false, "", true); }
313
+ }
314
+
315
+ async function signup() {
316
+ const email = document.getElementById("auth-email").value;
317
+ const password = document.getElementById("auth-password").value;
318
+ hideError("auth-error"); setLoading("signup-btn", true, "Signing up...");
319
+ try {
320
+ await apiFetch("/auth/signup", { method: "POST", body: JSON.stringify({ email, password }) });
321
+ showToast("Account created! Please log in.");
322
+ document.getElementById("login-btn").click();
323
+ } catch (e) { showError("auth-error", e.message); setLoading("signup-btn", false); }
324
+ }
325
+
326
+ function showDashboard() {
327
+ document.getElementById("auth-screen").classList.add("hidden");
328
+ document.getElementById("dashboard").classList.remove("hidden");
329
+ loadHubs();
330
+ }
331
+
332
+ // --- SETTINGS & PASSWORD ---
333
+ function openSettingsModal() {
334
+ document.getElementById("settings-modal").classList.remove("hidden");
335
+ document.getElementById("current-password").value = "";
336
+ document.getElementById("new-password").value = "";
337
+ hideError("settings-error");
338
+ hideError("settings-success");
339
+ }
340
+ function closeSettingsModal() { document.getElementById("settings-modal").classList.add("hidden"); }
341
+
342
+ async function changePassword() {
343
+ const currentPass = document.getElementById("current-password").value;
344
+ const newPass = document.getElementById("new-password").value;
345
+ hideError("settings-error"); hideError("settings-success");
346
+
347
+ if (!currentPass || !newPass) return showError("settings-error", "Both fields are required");
348
+
349
+ setLoading("change-pass-btn", true, "Updating...");
350
+ try {
351
+ await apiFetch("/auth/change-password", {
352
+ method: "POST",
353
+ body: JSON.stringify({ current_password: currentPass, new_password: newPass })
354
+ });
355
+ showSuccess("settings-success", "Password updated successfully!");
356
+ setTimeout(closeSettingsModal, 1500);
357
+ } catch (e) {
358
+ showError("settings-error", e.message);
359
+ } finally {
360
+ setLoading("change-pass-btn", false);
361
+ }
362
+ }
363
+
364
+ // --- HUBS & CREATION ---
365
+ function openCreateModal() {
366
+ document.getElementById("create-modal").classList.remove("hidden");
367
+ document.getElementById("new-hub-file").value = "";
368
+ document.getElementById("file-name-display").textContent = "No file selected";
369
+ }
370
+ function closeCreateModal() {
371
+ document.getElementById("create-modal").classList.add("hidden");
372
+ hideError("create-error");
373
+ }
374
+
375
+ document.getElementById("new-hub-file").addEventListener("change", (e) => {
376
+ const fileName = e.target.files[0] ? e.target.files[0].name : "No file selected";
377
+ document.getElementById("file-name-display").textContent = fileName;
378
+ });
379
+
380
+ async function createHub() {
381
+ const name = document.getElementById("new-hub-name").value;
382
+ const content = document.getElementById("new-hub-content").value;
383
+ const file = document.getElementById("new-hub-file").files[0];
384
+
385
+ if (!name) return showError("create-error", "Name is required");
386
+
387
+ hideError("create-error");
388
+ setLoading("create-hub-btn", true, "Creating Hub...", true);
389
+
390
+ try {
391
+ const key = crypto.randomUUID();
392
+ const hubRes = await apiFetch("/hubs", {
393
+ method: "POST",
394
+ headers: { "X-Idempotency-Key": key },
395
+ body: JSON.stringify({ name, content })
396
+ });
397
+ const newHubId = hubRes.id;
398
+
399
+ if (file) {
400
+ setLoading("create-hub-btn", true, "Uploading File...", true);
401
+ const formData = new FormData();
402
+ formData.append("file", file);
403
+ const uploadKey = crypto.randomUUID();
404
+ const uploadRes = await apiFetch(`/hubs/${newHubId}/documents`, {
405
+ method: "POST",
406
+ headers: { "X-Idempotency-Key": uploadKey },
407
+ body: formData
408
+ });
409
+ await pollDocumentProcess(newHubId, uploadRes.id, "create-hub-btn", true);
410
+ }
411
+
412
+ showToast("Hub created successfully!");
413
+ closeCreateModal();
414
+ document.getElementById("new-hub-name").value = "";
415
+ document.getElementById("new-hub-content").value = "";
416
+
417
+ await loadHubs();
418
+ const newHubObj = allHubs.find(h => h.id === newHubId);
419
+ if (newHubObj) selectHub(newHubObj);
420
+
421
+ } catch (e) {
422
+ showError("create-error", e.message);
423
+ } finally {
424
+ setLoading("create-hub-btn", false);
425
+ }
426
+ }
427
+
428
+ async function loadHubs() {
429
+ try {
430
+ const data = await apiFetch("/hubs");
431
+ allHubs = data.items;
432
+ const list = document.getElementById("hub-list"); list.innerHTML = "";
433
+ if (allHubs.length === 0) {
434
+ list.textContent = "No hubs yet. Create one below!"; list.style.padding = "20px"; list.style.color = "rgba(252, 241, 208, 0.5)"; list.style.textAlign = "center"; return;
435
+ }
436
+
437
+ allHubs.forEach(hub => {
438
+ const div = document.createElement("div");
439
+ div.className = "hub-item" + (currentHubId === hub.id ? " active" : "");
440
+ const title = document.createElement("h3"); title.textContent = hub.name;
441
+ div.appendChild(title);
442
+ div.onclick = () => selectHub(hub);
443
+ list.appendChild(div);
444
+ });
445
+ } catch (e) { showToast("Error loading hubs: " + e.message); }
446
+ }
447
+
448
+ function selectHub(hub) {
449
+ currentHubId = hub.id;
450
+ document.getElementById("empty-state").classList.add("hidden");
451
+ document.getElementById("chat-container").classList.remove("hidden");
452
+ document.getElementById("chat-title").textContent = hub.name;
453
+ loadHubs();
454
+ renderChat(hub.id, hub.suggested_questions);
455
+ }
456
+
457
+ // --- DELETE & REFRESH ---
458
+ async function deleteHub() {
459
+ if (!currentHubId) return;
460
+ if (!confirm("Are you sure you want to delete this hub? This will permanently delete all documents and embeddings inside it.")) return;
461
+
462
+ try {
463
+ await apiFetch(`/hubs/${currentHubId}`, { method: "DELETE" });
464
+ showToast("Hub deleted successfully.");
465
+ currentHubId = null;
466
+ document.getElementById("chat-container").classList.add("hidden");
467
+ document.getElementById("empty-state").classList.remove("hidden");
468
+ loadHubs();
469
+ } catch (e) {
470
+ showToast("Failed to delete hub: " + e.message);
471
+ }
472
+ }
473
+
474
+ async function refreshHub() {
475
+ if (!currentHubId) return;
476
+ showToast("Syncing latest data...");
477
+ await loadHubs();
478
+ const hub = allHubs.find(h => h.id === currentHubId);
479
+ if (hub) {
480
+ document.getElementById("chat-title").textContent = hub.name;
481
+ }
482
+ showToast("Synced.");
483
+ }
484
+
485
+ // --- CHAT RENDERING ---
486
+ function renderChat(hubId, suggestedQuestions = []) {
487
+ const history = document.getElementById("chat-history");
488
+ history.innerHTML = "";
489
+
490
+ if (chatHistories[hubId] && chatHistories[hubId].length > 0) {
491
+ chatHistories[hubId].forEach(msg => {
492
+ if (msg.role === "doc") appendDocChipToDOM(msg.filename);
493
+ else appendMessageToDOM(msg.role, msg.text, msg.evidence);
494
+ });
495
+ }
496
+ else if (suggestedQuestions && suggestedQuestions.length > 0) {
497
+ const suggestionsDiv = document.createElement("div");
498
+ suggestionsDiv.className = "suggestions-container";
499
+
500
+ const header = document.createElement("p");
501
+ header.textContent = "Try asking one of these to get started:";
502
+ header.style.color = "var(--text-muted)";
503
+ header.style.fontWeight = "600";
504
+ suggestionsDiv.appendChild(header);
505
+
506
+ suggestedQuestions.forEach(q => {
507
+ const btn = document.createElement("button");
508
+ btn.className = "suggestion-chip";
509
+ btn.textContent = q;
510
+ btn.onclick = () => {
511
+ document.getElementById("query-input").value = q;
512
+ askQuestion();
513
+ };
514
+ suggestionsDiv.appendChild(btn);
515
+ });
516
+ history.appendChild(suggestionsDiv);
517
+ }
518
+ }
519
+
520
+ function appendMessageToDOM(role, text, evidence = null) {
521
+ const history = document.getElementById("chat-history");
522
+ const msgDiv = document.createElement("div");
523
+ msgDiv.className = `message ${role}`;
524
+
525
+ const pre = document.createElement("pre");
526
+ pre.textContent = text;
527
+ msgDiv.appendChild(pre);
528
+
529
+ if (evidence) {
530
+ const badge = document.createElement("span");
531
+ badge.className = "evidence-badge";
532
+ badge.textContent = `Evidence: "${evidence}"`;
533
+ msgDiv.appendChild(badge);
534
+ }
535
+ history.appendChild(msgDiv);
536
+ history.scrollTop = history.scrollHeight;
537
+ }
538
+
539
+ function appendDocChipToDOM(filename) {
540
+ const history = document.getElementById("chat-history");
541
+ const chip = document.createElement("div");
542
+ chip.className = "doc-chip";
543
+ chip.innerHTML = `<span>📄</span> <span>${filename}</span>`;
544
+ history.appendChild(chip);
545
+ history.scrollTop = history.scrollHeight;
546
+ }
547
+
548
+ // --- UPLOAD & POLLING ---
549
+ async function uploadDocument(event) {
550
+ const file = event.target.files[0];
551
+ if (!file || !currentHubId) return;
552
+
553
+ setLoading("attach-btn", true, "⏳");
554
+ const formData = new FormData();
555
+ formData.append("file", file);
556
+
557
+ try {
558
+ const key = crypto.randomUUID();
559
+ const uploadRes = await apiFetch(`/hubs/${currentHubId}/documents`, {
560
+ method: "POST",
561
+ headers: { "X-Idempotency-Key": key },
562
+ body: formData
563
+ });
564
+
565
+ if (!chatHistories[currentHubId]) chatHistories[currentHubId] = [];
566
+ chatHistories[currentHubId].push({ role: "doc", filename: file.name });
567
+ appendDocChipToDOM(file.name);
568
+
569
+ showToast("Document uploaded. Processing...");
570
+ await pollDocumentProcess(currentHubId, uploadRes.id, "attach-btn");
571
+
572
+ } catch (e) {
573
+ showToast("Upload failed: " + e.message);
574
+ setLoading("attach-btn", false, "📎");
575
+ }
576
+ event.target.value = "";
577
+ }
578
+
579
+ async function pollDocumentProcess(hubId, docId, btnId, isLight = false) {
580
+ let isReady = false;
581
+ while (!isReady) {
582
+ setLoading(btnId, true, isLight ? "Processing..." : "⏳", isLight);
583
+ try {
584
+ const doc = await apiFetch(`/hubs/${hubId}/documents/${docId}/process`, { method: "POST" });
585
+
586
+ if (doc.status === "ready") {
587
+ isReady = true;
588
+ showToast("Document ready!");
589
+ } else if (doc.status === "failed") {
590
+ throw new Error(doc.error_message || "Processing failed");
591
+ } else {
592
+ await new Promise(r => setTimeout(r, 2000));
593
+ }
594
+ } catch (e) {
595
+ showToast("Processing error: " + e.message);
596
+ break;
597
+ }
598
+ }
599
+ setLoading(btnId, false, isLight ? "" : "📎", isLight);
600
+ if(!isLight) document.getElementById(btnId).innerHTML = "📎";
601
+ loadHubs();
602
+ }
603
+
604
+ // --- QUERY ---
605
+ function handleKeyPress(e) { if (e.key === "Enter") askQuestion(); }
606
+
607
+ async function askQuestion() {
608
+ const input = document.getElementById("query-input");
609
+ const question = input.value.trim();
610
+ if (!question || !currentHubId) return;
611
+
612
+ input.value = "";
613
+
614
+ if (!chatHistories[currentHubId]) chatHistories[currentHubId] = [];
615
+ if (chatHistories[currentHubId].length === 0) {
616
+ document.getElementById("chat-history").innerHTML = "";
617
+ }
618
+
619
+ chatHistories[currentHubId].push({ role: "user", text: question });
620
+ appendMessageToDOM("user", question);
621
+
622
+ setLoading("ask-btn", true, "Thinking...");
623
+ try {
624
+ const data = await apiFetch(`/hubs/${currentHubId}/query`, {
625
+ method: "POST", body: JSON.stringify({ question })
626
+ });
627
+
628
+ chatHistories[currentHubId].push({ role: "ai", text: data.answer, evidence: data.evidence });
629
+ appendMessageToDOM("ai", data.answer, data.evidence);
630
+
631
+ } catch (e) {
632
+ appendMessageToDOM("ai", "Error: " + e.message);
633
+ } finally {
634
+ setLoading("ask-btn", false);
635
+ }
636
+ }
637
+
638
+ if (getToken()) showDashboard();
639
+ </script>
640
+ </body>
641
+ </html>