Subh775 commited on
Commit
4ca0250
·
1 Parent(s): b711541

simplified str; model routing & retrying; cleanup..

Browse files
Files changed (9) hide show
  1. app.py +15 -146
  2. auth.py +0 -1
  3. config.py +1 -6
  4. db.py +1 -53
  5. graph.py +42 -36
  6. requirements.txt +0 -1
  7. static/app.js +91 -11
  8. static/index.html +29 -3
  9. static/style.css +164 -29
app.py CHANGED
@@ -1,11 +1,10 @@
1
  """
2
- FastAPI application — routes for chat (SSE streaming), auth, settings, analytics, and static files.
3
  """
4
 
5
  import os
6
  import json
7
  import time
8
- import hashlib
9
  from fastapi import FastAPI, Request
10
  from fastapi.responses import FileResponse, StreamingResponse, JSONResponse
11
  from fastapi.staticfiles import StaticFiles
@@ -17,7 +16,7 @@ import db
17
  import guard
18
  import retriever
19
  import auth as auth_module
20
- from config import EXPORT_SECRET, REDIS_URI, GOOGLE_CLIENT_ID
21
  from graph import chatbot
22
 
23
 
@@ -35,25 +34,6 @@ STATIC_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "static")
35
  ASSETS_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "assets")
36
 
37
 
38
- # --- Redis cache ---
39
- _redis = None
40
- if REDIS_URI:
41
- try:
42
- import redis as _redis_lib
43
- _redis = _redis_lib.from_url(REDIS_URI, decode_responses=True)
44
- _redis.ping()
45
- except Exception:
46
- _redis = None
47
-
48
- CACHE_TTL = 86400 # 24 hours
49
-
50
-
51
- def _cache_key(query: str, persona: str, language: str) -> str:
52
- normalized = query.strip().lower()
53
- raw = f"{normalized}|{persona}|{language}"
54
- return f"stemcopilot:{hashlib.sha256(raw.encode()).hexdigest()}"
55
-
56
-
57
  # --- Request / Response models ---
58
 
59
  class GoogleAuthRequest(BaseModel):
@@ -99,10 +79,6 @@ async def submit_feedback(req: FeedbackRequest):
99
 
100
  # --- SSE helpers ---
101
 
102
- def sse_status(message: str) -> str:
103
- return f"data: {json.dumps({'status': 'thinking', 'message': message})}\n\n"
104
-
105
-
106
  def sse_token(token: str) -> str:
107
  return f"data: {json.dumps({'token': token})}\n\n"
108
 
@@ -207,7 +183,6 @@ def get_history(thread_id: str):
207
  @app.post("/chat")
208
  def chat(request: ChatRequest, req: Request):
209
  now = time.time()
210
- user_agent = req.headers.get("user-agent", "")
211
  db.upsert_thread(request.thread_id, request.message, now, request.user_id)
212
 
213
  # Resolve user-specific data
@@ -221,48 +196,18 @@ def chat(request: ChatRequest, req: Request):
221
 
222
  def stream():
223
  # Step 1: Guard
224
- yield sse_status("Reading your question...")
225
  is_ok, rejection = guard.check_input(request.message)
226
 
227
  if not is_ok:
228
  yield sse_token(rejection)
229
  yield sse_done()
230
- db.log_exchange(
231
- thread_id=request.thread_id, timestamp=now,
232
- user_message=request.message, assistant_response=rejection,
233
- persona=request.persona, language=request.language,
234
- username=request.username, user_agent=user_agent,
235
- user_id=request.user_id,
236
- )
237
  return
238
 
239
- # Step 2: Redis cache check (text-only queries without images)
240
- cache_hit = None
241
- cache_k = _cache_key(request.message, request.persona, request.language)
242
- if _redis and not request.image:
243
- try:
244
- cache_hit = _redis.get(cache_k)
245
- except Exception:
246
- pass
247
-
248
- if cache_hit:
249
- yield sse_token(cache_hit)
250
- yield sse_done()
251
- db.log_exchange(
252
- thread_id=request.thread_id, timestamp=now,
253
- user_message=request.message, assistant_response=cache_hit,
254
- persona=request.persona, language=request.language,
255
- username=request.username, user_agent=user_agent,
256
- user_id=request.user_id, model_used="cache", cached=True,
257
- )
258
- return
259
-
260
- # Step 3: Retrieve context from Pinecone
261
- yield sse_status("Searching NCERT chapters...")
262
  results = retriever.search(request.message)
263
  context = retriever.format_context(results)
264
 
265
- # Step 4: Build message (text or multimodal with image)
266
  if request.image:
267
  msg_content = [
268
  {"type": "text", "text": request.message},
@@ -274,10 +219,8 @@ def chat(request: ChatRequest, req: Request):
274
  else:
275
  msg_content = request.message
276
 
277
- # Step 5: Stream LLM response via LangGraph
278
- yield sse_status("Preparing the explanation...")
279
  has_image = bool(request.image)
280
- model_used = "auto-routed"
281
  config = {
282
  "configurable": {
283
  "thread_id": request.thread_id,
@@ -291,7 +234,6 @@ def chat(request: ChatRequest, req: Request):
291
  }
292
  }
293
 
294
- full_response = []
295
  try:
296
  for chunk, _metadata in chatbot.stream(
297
  {"messages": [HumanMessage(content=msg_content)]},
@@ -299,61 +241,29 @@ def chat(request: ChatRequest, req: Request):
299
  stream_mode="messages",
300
  ):
301
  if isinstance(chunk, AIMessage) and chunk.content:
302
- full_response.append(chunk.content)
303
  yield sse_token(chunk.content)
304
  except Exception as e:
305
  error_str = str(e).lower()
306
  if "429" in str(e) or "rate" in error_str:
307
- yield sse_error(
308
- "I'm getting a lot of questions right now. "
309
- "Please try again in a few seconds."
310
- )
311
  elif "402" in str(e) or "payment" in error_str or "credits" in error_str:
312
- yield sse_error(
313
- "Free credits exhausted. Please add credits at openrouter.ai/settings/credits "
314
- "or update your API key in Settings."
315
- )
316
  elif "404" in str(e) or "not found" in error_str or "no endpoints" in error_str:
317
- yield sse_error(
318
- "The selected model is temporarily unavailable. "
319
- "Retrying may route to a different model. Please try again."
320
- )
321
  elif "401" in str(e) or "unauthorized" in error_str or "invalid" in error_str:
322
- yield sse_error(
323
- "API key issue. Please check your OpenRouter API key in Settings."
324
- )
325
  else:
326
- yield sse_error(
327
- "Something went wrong. Please try sending your question again."
328
- )
329
  yield sse_done()
330
  return
331
 
332
  yield sse_done()
333
 
334
- # Step 6: Cache the response in Redis
335
- response_text = "".join(full_response)
336
- if _redis and response_text and not request.image:
337
- try:
338
- _redis.setex(cache_k, CACHE_TTL, response_text)
339
- except Exception:
340
- pass
341
-
342
- # Step 7: Log the exchange
343
- sources = [
344
- {"subject": r["subject"], "class": r["class_level"], "chapter": r["chapter"]}
345
- for r in results
346
- ]
347
- db.log_exchange(
348
- thread_id=request.thread_id, timestamp=now,
349
- user_message=request.message, assistant_response=response_text,
350
- persona=request.persona, language=request.language,
351
- username=request.username, user_agent=user_agent,
352
- sources=sources, user_id=request.user_id,
353
- model_used=model_used,
354
- )
355
-
356
- return StreamingResponse(stream(), media_type="text/event-stream")
357
 
358
 
359
  @app.post("/rename")
@@ -368,47 +278,6 @@ def delete_thread(thread_id: str):
368
  return {"ok": True}
369
 
370
 
371
- # --- Export / Analytics ---
372
-
373
- @app.get("/export/logs")
374
- def export_logs(key: str = ""):
375
- """Download chat logs as JSON. Requires EXPORT_SECRET."""
376
- if not EXPORT_SECRET or key != EXPORT_SECRET:
377
- return JSONResponse({"error": "unauthorized"}, status_code=403)
378
-
379
- cursor = db.conn.execute(
380
- """SELECT thread_id, timestamp, user_message, assistant_response,
381
- persona, language, username, user_agent, sources,
382
- user_id, model_used, cached
383
- FROM chat_logs ORDER BY timestamp DESC"""
384
- )
385
- columns = [
386
- "thread_id", "timestamp", "user_message", "assistant_response",
387
- "persona", "language", "username", "user_agent", "sources",
388
- "user_id", "model_used", "cached",
389
- ]
390
- rows = [dict(zip(columns, row)) for row in cursor]
391
- for row in rows:
392
- if row["sources"]:
393
- row["sources"] = json.loads(row["sources"])
394
- return JSONResponse({"count": len(rows), "logs": rows})
395
-
396
-
397
- @app.get("/export/users")
398
- def export_users(key: str = ""):
399
- """Download user list as JSON. Requires EXPORT_SECRET."""
400
- if not EXPORT_SECRET or key != EXPORT_SECRET:
401
- return JSONResponse({"error": "unauthorized"}, status_code=403)
402
-
403
- cursor = db.conn.execute(
404
- "SELECT google_id, email, name, created_at, last_login FROM users "
405
- "ORDER BY last_login DESC"
406
- )
407
- columns = ["google_id", "email", "name", "created_at", "last_login"]
408
- rows = [dict(zip(columns, row)) for row in cursor]
409
- return JSONResponse({"count": len(rows), "users": rows})
410
-
411
-
412
  # --- Health check ---
413
 
414
  @app.get("/health")
 
1
  """
2
+ FastAPI application — routes for chat (SSE streaming), auth, settings, and static files.
3
  """
4
 
5
  import os
6
  import json
7
  import time
 
8
  from fastapi import FastAPI, Request
9
  from fastapi.responses import FileResponse, StreamingResponse, JSONResponse
10
  from fastapi.staticfiles import StaticFiles
 
16
  import guard
17
  import retriever
18
  import auth as auth_module
19
+ from config import GOOGLE_CLIENT_ID
20
  from graph import chatbot
21
 
22
 
 
34
  ASSETS_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "assets")
35
 
36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
  # --- Request / Response models ---
38
 
39
  class GoogleAuthRequest(BaseModel):
 
79
 
80
  # --- SSE helpers ---
81
 
 
 
 
 
82
  def sse_token(token: str) -> str:
83
  return f"data: {json.dumps({'token': token})}\n\n"
84
 
 
183
  @app.post("/chat")
184
  def chat(request: ChatRequest, req: Request):
185
  now = time.time()
 
186
  db.upsert_thread(request.thread_id, request.message, now, request.user_id)
187
 
188
  # Resolve user-specific data
 
196
 
197
  def stream():
198
  # Step 1: Guard
 
199
  is_ok, rejection = guard.check_input(request.message)
200
 
201
  if not is_ok:
202
  yield sse_token(rejection)
203
  yield sse_done()
 
 
 
 
 
 
 
204
  return
205
 
206
+ # Step 2: Retrieve context from Pinecone
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
207
  results = retriever.search(request.message)
208
  context = retriever.format_context(results)
209
 
210
+ # Step 3: Build message (text or multimodal with image)
211
  if request.image:
212
  msg_content = [
213
  {"type": "text", "text": request.message},
 
219
  else:
220
  msg_content = request.message
221
 
222
+ # Step 4: Stream LLM response via LangGraph
 
223
  has_image = bool(request.image)
 
224
  config = {
225
  "configurable": {
226
  "thread_id": request.thread_id,
 
234
  }
235
  }
236
 
 
237
  try:
238
  for chunk, _metadata in chatbot.stream(
239
  {"messages": [HumanMessage(content=msg_content)]},
 
241
  stream_mode="messages",
242
  ):
243
  if isinstance(chunk, AIMessage) and chunk.content:
 
244
  yield sse_token(chunk.content)
245
  except Exception as e:
246
  error_str = str(e).lower()
247
  if "429" in str(e) or "rate" in error_str:
248
+ yield sse_error("Rate limited. Please wait a moment and try again.")
 
 
 
249
  elif "402" in str(e) or "payment" in error_str or "credits" in error_str:
250
+ yield sse_error("Free credits exhausted on OpenRouter.")
 
 
 
251
  elif "404" in str(e) or "not found" in error_str or "no endpoints" in error_str:
252
+ yield sse_error("Model unavailable. Please try again.")
 
 
 
253
  elif "401" in str(e) or "unauthorized" in error_str or "invalid" in error_str:
254
+ yield sse_error("Invalid API key.")
 
 
255
  else:
256
+ yield sse_error("Something went wrong. Please try again.")
 
 
257
  yield sse_done()
258
  return
259
 
260
  yield sse_done()
261
 
262
+ return StreamingResponse(
263
+ stream(),
264
+ media_type="text/event-stream",
265
+ headers={"X-Accel-Buffering": "no"},
266
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
267
 
268
 
269
  @app.post("/rename")
 
278
  return {"ok": True}
279
 
280
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
281
  # --- Health check ---
282
 
283
  @app.get("/health")
auth.py CHANGED
@@ -8,7 +8,6 @@ def verify_google_token(token: str) -> dict | None:
8
  Returns the user info dict if valid, otherwise None.
9
  """
10
  if not GOOGLE_CLIENT_ID:
11
- # For local dev/demo without client ID, we might mock it or just fail
12
  return None
13
  try:
14
  # Specify the CLIENT_ID of the app that accesses the backend
 
8
  Returns the user info dict if valid, otherwise None.
9
  """
10
  if not GOOGLE_CLIENT_ID:
 
11
  return None
12
  try:
13
  # Specify the CLIENT_ID of the app that accesses the backend
config.py CHANGED
@@ -3,21 +3,16 @@ import os
3
  # --- API Keys & Secrets ---
4
  GOOGLE_API_KEY = os.environ.get("GOOGLE_API_KEY", "")
5
  PINECONE_API_KEY = os.environ.get("PINECONE_API_KEY", "")
6
- EXPORT_SECRET = os.environ.get("EXPORT_SECRET", "")
7
  GOOGLE_CLIENT_ID = os.environ.get("GOOGLE_CLIENT_ID", "")
8
 
9
  # Optional: shared fallback key (users bring their own via BYOK)
10
  OPENROUTER_API_KEY = os.environ.get("OPENROUTER_API_KEY", "")
11
 
12
- # --- LangSmith (optional — tracing & analytics) ---
13
  os.environ["LANGCHAIN_TRACING_V2"] = os.environ.get("LANGSMITH_TRACING", "true")
14
  os.environ["LANGCHAIN_API_KEY"] = os.environ.get("LANGSMITH_API_KEY", "")
15
  os.environ["LANGCHAIN_PROJECT"] = os.environ.get("LANGCHAIN_PROJECT", "stemcopilot-prod")
16
 
17
- # --- Redis (optional — caching to save API calls) ---
18
- REDIS_URI = os.environ.get("REDIS_URI", "")
19
-
20
-
21
  # --- Pinecone ---
22
  PINECONE_INDEX = "stem-embed"
23
 
 
3
  # --- API Keys & Secrets ---
4
  GOOGLE_API_KEY = os.environ.get("GOOGLE_API_KEY", "")
5
  PINECONE_API_KEY = os.environ.get("PINECONE_API_KEY", "")
 
6
  GOOGLE_CLIENT_ID = os.environ.get("GOOGLE_CLIENT_ID", "")
7
 
8
  # Optional: shared fallback key (users bring their own via BYOK)
9
  OPENROUTER_API_KEY = os.environ.get("OPENROUTER_API_KEY", "")
10
 
11
+ # --- LangSmith (tracing & analytics) ---
12
  os.environ["LANGCHAIN_TRACING_V2"] = os.environ.get("LANGSMITH_TRACING", "true")
13
  os.environ["LANGCHAIN_API_KEY"] = os.environ.get("LANGSMITH_API_KEY", "")
14
  os.environ["LANGCHAIN_PROJECT"] = os.environ.get("LANGCHAIN_PROJECT", "stemcopilot-prod")
15
 
 
 
 
 
16
  # --- Pinecone ---
17
  PINECONE_INDEX = "stem-embed"
18
 
db.py CHANGED
@@ -1,10 +1,9 @@
1
  """
2
- Database layer — SQLite for user data, threads, and chat logs.
3
  LangGraph checkpointing also uses SQLite (configured in graph.py).
4
  """
5
 
6
  import sqlite3
7
- import json
8
  import time
9
  from config import DB_PATH
10
 
@@ -35,24 +34,6 @@ conn.execute("""
35
  )
36
  """)
37
 
38
- conn.execute("""
39
- CREATE TABLE IF NOT EXISTS chat_logs (
40
- id INTEGER PRIMARY KEY AUTOINCREMENT,
41
- thread_id TEXT NOT NULL,
42
- timestamp REAL NOT NULL,
43
- user_message TEXT NOT NULL,
44
- assistant_response TEXT NOT NULL,
45
- persona TEXT,
46
- language TEXT,
47
- username TEXT,
48
- user_agent TEXT,
49
- sources TEXT,
50
- user_id TEXT,
51
- model_used TEXT,
52
- cached INTEGER DEFAULT 0
53
- )
54
- """)
55
-
56
  conn.commit()
57
 
58
 
@@ -162,36 +143,3 @@ def rename_thread(thread_id: str, title: str):
162
  def delete_thread(thread_id: str):
163
  conn.execute("DELETE FROM thread_titles WHERE thread_id = ?", (thread_id,))
164
  conn.commit()
165
-
166
-
167
- # --- Chat log operations ---
168
-
169
- def log_exchange(
170
- thread_id: str,
171
- timestamp: float,
172
- user_message: str,
173
- assistant_response: str,
174
- persona: str = "",
175
- language: str = "",
176
- username: str = "",
177
- user_agent: str = "",
178
- sources: list[dict] | None = None,
179
- user_id: str = "",
180
- model_used: str = "",
181
- cached: bool = False,
182
- ):
183
- """Log a complete user-assistant exchange for analytics."""
184
- conn.execute(
185
- """INSERT INTO chat_logs
186
- (thread_id, timestamp, user_message, assistant_response,
187
- persona, language, username, user_agent, sources,
188
- user_id, model_used, cached)
189
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
190
- (
191
- thread_id, timestamp, user_message, assistant_response,
192
- persona, language, username, user_agent,
193
- json.dumps(sources) if sources else None,
194
- user_id, model_used, 1 if cached else 0,
195
- ),
196
- )
197
- conn.commit()
 
1
  """
2
+ Database layer — SQLite for user data and thread metadata.
3
  LangGraph checkpointing also uses SQLite (configured in graph.py).
4
  """
5
 
6
  import sqlite3
 
7
  import time
8
  from config import DB_PATH
9
 
 
34
  )
35
  """)
36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
  conn.commit()
38
 
39
 
 
143
  def delete_thread(thread_id: str):
144
  conn.execute("DELETE FROM thread_titles WHERE thread_id = ?", (thread_id,))
145
  conn.commit()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
graph.py CHANGED
@@ -9,13 +9,15 @@ Routes queries to the best free OpenRouter model based on intent:
9
 
10
  Model pools are fetched from the OpenRouter API, cached for 10 min,
11
  and rotated per-category to avoid per-model rate limits.
 
 
12
  """
13
 
14
  from langgraph.graph import StateGraph, START, END
15
  from langgraph.graph.message import add_messages
16
  from langchain_core.messages import BaseMessage, SystemMessage, HumanMessage, AIMessage
17
  from langchain_core.runnables import RunnableConfig
18
- from langchain_openrouter import ChatOpenRouter #type:ignore
19
  from typing import TypedDict, Annotated
20
 
21
  import sqlite3
@@ -23,7 +25,7 @@ import time
23
  import json
24
  import urllib.request
25
  import threading
26
- from langgraph.checkpoint.sqlite import SqliteSaver #type:ignore
27
  from config import OPENROUTER_API_KEY, DB_PATH, LLM_TIMEOUT
28
  import prompts
29
 
@@ -37,23 +39,11 @@ checkpointer = SqliteSaver(conn=_conn)
37
  DEFAULT_MODEL = "openai/gpt-oss-120b:free"
38
  MODELS_TTL = 10 * 60 # seconds
39
 
40
- # Models that are safety classifiers / guardrail models — they output
41
- # "User Safety: safe\nResponse Safety: safe" instead of actual answers.
42
- _BLACKLISTED_MODELS = frozenset([
43
- "meta-llama/llama-guard",
44
- "meta-llama/llama-guard-2",
45
- "meta-llama/llama-guard-3",
46
- "meta-llama/llama-guard-4",
47
- ])
48
 
49
- def _is_blacklisted(model_id: str) -> bool:
50
- """Check if model is a known guardrail/safety classifier."""
51
- mid = model_id.lower()
52
- for bl in _BLACKLISTED_MODELS:
53
- if mid.startswith(bl):
54
- return True
55
- base = mid.split(':')[0]
56
- return any(kw in base for kw in ('guard', 'shield', 'safety', 'moderation'))
57
 
58
 
59
  # ── Query Classification ─────────────────────────────────────
@@ -178,7 +168,7 @@ def _fetch_pools() -> dict:
178
  mid = m.get("id", "")
179
  if not mid.endswith(":free"):
180
  continue
181
- if _is_blacklisted(mid):
182
  continue
183
 
184
  arch = m.get("architecture", {})
@@ -225,21 +215,23 @@ def _fetch_pools() -> dict:
225
 
226
  # ── Model Picker (round-robin) ────────────────────────────────
227
 
228
- def _pick(category: str, has_image: bool = False) -> tuple[str, str]:
229
  """
230
  Return (model_id, actual_category).
231
  If has_image but no vision model exists, falls back to text category.
 
232
  """
233
  pools = _fetch_pools()
 
234
 
235
  if has_image:
236
- v = pools.get("vision", [])
237
  if v:
238
  idx = _counters.get("vision", 0) % len(v)
239
  _counters["vision"] = idx + 1
240
  return v[idx]["id"], "vision"
241
 
242
- pool = pools.get(category) or pools.get("general") or []
243
  if not pool:
244
  return DEFAULT_MODEL, category
245
 
@@ -293,7 +285,7 @@ def _make_llm(api_key: str, model_id: str):
293
  openrouter_api_key=key,
294
  temperature=0.5,
295
  max_tokens=4096,
296
- max_retries=1,
297
  streaming=True,
298
  )
299
 
@@ -318,15 +310,7 @@ def chat_node(state: ChatState, config: RunnableConfig):
318
  user_text = _extract_text(state["messages"])
319
  category = _classify(user_text)
320
 
321
- if override:
322
- model_id, actual = override, category
323
- else:
324
- model_id, actual = _pick(category, has_image=has_image)
325
-
326
  messages = state["messages"]
327
- if actual != "vision":
328
- messages = _strip_images(messages)
329
-
330
  base_prompt = prompts.build(persona, context, language, username, profile)
331
 
332
  if has_image:
@@ -337,11 +321,34 @@ def chat_node(state: ChatState, config: RunnableConfig):
337
  )
338
 
339
  sys = SystemMessage(content=base_prompt)
340
- print(f"[ROUTER] category={category} model={model_id} vision={actual == 'vision'}")
341
 
342
- llm = _make_llm(api_key, model_id)
343
- resp = llm.invoke([sys] + messages)
344
- return {"messages": [resp]}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
345
 
346
 
347
  # ── Compile graph ─────────────────────────────────────────────
@@ -352,4 +359,3 @@ _g.add_edge(START, "chat_node")
352
  _g.add_edge("chat_node", END)
353
 
354
  chatbot = _g.compile(checkpointer=checkpointer)
355
-
 
9
 
10
  Model pools are fetched from the OpenRouter API, cached for 10 min,
11
  and rotated per-category to avoid per-model rate limits.
12
+ On 429 errors, the failed model is skipped and the next model in the
13
+ pool is tried automatically (up to 2 retries).
14
  """
15
 
16
  from langgraph.graph import StateGraph, START, END
17
  from langgraph.graph.message import add_messages
18
  from langchain_core.messages import BaseMessage, SystemMessage, HumanMessage, AIMessage
19
  from langchain_core.runnables import RunnableConfig
20
+ from langchain_openrouter import ChatOpenRouter # type:ignore
21
  from typing import TypedDict, Annotated
22
 
23
  import sqlite3
 
25
  import json
26
  import urllib.request
27
  import threading
28
+ from langgraph.checkpoint.sqlite import SqliteSaver # type:ignore
29
  from config import OPENROUTER_API_KEY, DB_PATH, LLM_TIMEOUT
30
  import prompts
31
 
 
39
  DEFAULT_MODEL = "openai/gpt-oss-120b:free"
40
  MODELS_TTL = 10 * 60 # seconds
41
 
 
 
 
 
 
 
 
 
42
 
43
+ def _is_guardrail(model_id: str) -> bool:
44
+ """Auto-filter safety classifiers / guardrail models."""
45
+ base = model_id.lower().split(":")[0]
46
+ return any(kw in base for kw in ("guard", "shield", "safety", "moderation"))
 
 
 
 
47
 
48
 
49
  # ── Query Classification ─────────────────────────────────────
 
168
  mid = m.get("id", "")
169
  if not mid.endswith(":free"):
170
  continue
171
+ if _is_guardrail(mid):
172
  continue
173
 
174
  arch = m.get("architecture", {})
 
215
 
216
  # ── Model Picker (round-robin) ────────────────────────────────
217
 
218
+ def _pick(category: str, has_image: bool = False, skip_models: set | None = None) -> tuple[str, str]:
219
  """
220
  Return (model_id, actual_category).
221
  If has_image but no vision model exists, falls back to text category.
222
+ skip_models: set of model IDs to skip (e.g. after a 429).
223
  """
224
  pools = _fetch_pools()
225
+ skip = skip_models or set()
226
 
227
  if has_image:
228
+ v = [m for m in pools.get("vision", []) if m["id"] not in skip]
229
  if v:
230
  idx = _counters.get("vision", 0) % len(v)
231
  _counters["vision"] = idx + 1
232
  return v[idx]["id"], "vision"
233
 
234
+ pool = [m for m in (pools.get(category) or pools.get("general") or []) if m["id"] not in skip]
235
  if not pool:
236
  return DEFAULT_MODEL, category
237
 
 
285
  openrouter_api_key=key,
286
  temperature=0.5,
287
  max_tokens=4096,
288
+ max_retries=0,
289
  streaming=True,
290
  )
291
 
 
310
  user_text = _extract_text(state["messages"])
311
  category = _classify(user_text)
312
 
 
 
 
 
 
313
  messages = state["messages"]
 
 
 
314
  base_prompt = prompts.build(persona, context, language, username, profile)
315
 
316
  if has_image:
 
321
  )
322
 
323
  sys = SystemMessage(content=base_prompt)
 
324
 
325
+ # Try up to 3 models on 429 errors
326
+ skip_models: set[str] = set()
327
+ last_error = None
328
+
329
+ for attempt in range(3):
330
+ if override and attempt == 0:
331
+ model_id, actual = override, category
332
+ else:
333
+ model_id, actual = _pick(category, has_image=has_image, skip_models=skip_models)
334
+
335
+ send_messages = messages if actual == "vision" else _strip_images(messages)
336
+ print(f"[ROUTER] attempt={attempt+1} category={category} model={model_id} vision={actual == 'vision'}")
337
+
338
+ try:
339
+ llm = _make_llm(api_key, model_id)
340
+ resp = llm.invoke([sys] + send_messages, config=config)
341
+ return {"messages": [resp]}
342
+ except Exception as e:
343
+ err_str = str(e)
344
+ last_error = e
345
+ if "429" in err_str or "TooManyRequests" in err_str or "rate" in err_str.lower():
346
+ print(f"[ROUTER] 429 on {model_id}, rotating...")
347
+ skip_models.add(model_id)
348
+ continue
349
+ raise
350
+
351
+ raise last_error
352
 
353
 
354
  # ── Compile graph ─────────────────────────────────────────────
 
359
  _g.add_edge("chat_node", END)
360
 
361
  chatbot = _g.compile(checkpointer=checkpointer)
 
requirements.txt CHANGED
@@ -9,5 +9,4 @@ pinecone
9
  sentence-transformers
10
  torch --index-url https://download.pytorch.org/whl/cpu
11
  google-auth
12
- redis
13
  langsmith
 
9
  sentence-transformers
10
  torch --index-url https://download.pytorch.org/whl/cpu
11
  google-auth
 
12
  langsmith
static/app.js CHANGED
@@ -365,12 +365,23 @@ function enterHeroMode() {
365
  _updateHeroTitle();
366
  }
367
 
 
 
 
 
 
 
 
 
 
 
368
  function _updateHeroTitle() {
369
  const el = document.getElementById('heroTitle');
370
  if (!el) return;
371
  const name = currentUsername || (currentUser ? currentUser.name : '');
372
- if (name) el.innerHTML = `What should we study today, <span class="hero-name">${escapeHtml(name)}</span>?`;
373
- else el.textContent = 'What should we study today?';
 
374
  }
375
 
376
  function exitHeroMode() {
@@ -513,7 +524,8 @@ function createWelcomeScreen() {
513
  div.id = 'welcomeScreen';
514
 
515
  const name = currentUsername || (currentUser ? currentUser.name : '');
516
- const titleHtml = name ? `What should we study today, <span class="hero-name">${escapeHtml(name)}</span>?` : `What should we study today?`;
 
517
  const styleLabel = _PERSONA_LABELS[currentPersona] || 'Vidyut';
518
 
519
  div.innerHTML = `
@@ -668,7 +680,19 @@ function loadThread(threadId) {
668
  exitHeroMode();
669
  if (window.innerWidth <= 768) closeSidebar();
670
 
 
 
 
 
 
 
 
 
 
 
671
  fetch('/history/' + threadId).then(res => res.json()).then(data => {
 
 
672
  data.messages.forEach(msg => {
673
  const sender = msg.role === 'user' ? 'user' : 'ai';
674
  let textContent = msg.content;
@@ -676,6 +700,8 @@ function loadThread(threadId) {
676
  const el = appendMessage(sender, textContent);
677
  if (sender === 'ai') renderFinalContent(el, textContent);
678
  });
 
 
679
  });
680
  }
681
 
@@ -1042,7 +1068,7 @@ function streamResponse(text) {
1042
  <div class="ai-avatar pulsing" id="avatarThinking"></div>
1043
  <div style="flex:1; min-width:0;">
1044
  <div class="thinking-indicator" id="currentThinking" style="padding-top:4px;">
1045
- <span class="thinking-text">Reading your question...</span>
1046
  </div>
1047
  <div class="message-content" style="display:none;"></div>
1048
  <div class="msg-actions" style="display:none;"></div>
@@ -1053,7 +1079,6 @@ function streamResponse(text) {
1053
  _showStopBtn();
1054
 
1055
  const thinkingEl = rowDiv.querySelector('#currentThinking');
1056
- const thinkingText = thinkingEl.querySelector('.thinking-text');
1057
  const contentEl = rowDiv.querySelector('.message-content');
1058
  const actionsEl = rowDiv.querySelector('.msg-actions');
1059
  let rawText = '';
@@ -1107,7 +1132,6 @@ function streamResponse(text) {
1107
  if (pl === '[DONE]') { finishStream(thinkingEl, contentEl, rawText, currentRenderTimer, actionsEl); currentStreamStopped = true; return; }
1108
  try {
1109
  const data = JSON.parse(pl);
1110
- if (data.status === 'thinking') { thinkingText.textContent = data.message; continue; }
1111
  if (data.error) {
1112
  thinkingEl.style.display = 'none';
1113
  contentEl.style.display = 'block';
@@ -1161,11 +1185,9 @@ function finishStream(thinkingEl, contentEl, rawText, timer, actionsEl) {
1161
  actionsEl.innerHTML = `
1162
  <button class="msg-action-btn" data-action="copy" title="Copy">
1163
  <svg viewBox="0 0 24 24" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="13" height="13" rx="2" ry="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>
1164
- Copy
1165
  </button>
1166
  <button class="msg-action-btn" data-action="regenerate" title="Regenerate">
1167
  <svg viewBox="0 0 24 24" stroke-linecap="round" stroke-linejoin="round"><polyline points="23 4 23 10 17 10"/><polyline points="1 20 1 14 7 14"/><path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"/></svg>
1168
- Regenerate
1169
  </button>
1170
  `;
1171
  const copyBtn = actionsEl.querySelector('[data-action="copy"]');
@@ -1173,8 +1195,7 @@ function finishStream(thinkingEl, contentEl, rawText, timer, actionsEl) {
1173
  if (copyBtn) {
1174
  copyBtn.addEventListener('click', () => {
1175
  navigator.clipboard.writeText(rawText).then(() => {
1176
- copyBtn.querySelector('svg + *').textContent = 'Copied';
1177
- setTimeout(() => { copyBtn.querySelector('svg + *').textContent = 'Copy'; }, 1500);
1178
  }).catch(() => showToast('Could not copy.', 'error'));
1179
  });
1180
  }
@@ -1184,7 +1205,18 @@ function finishStream(thinkingEl, contentEl, rawText, timer, actionsEl) {
1184
  if (userMessages.length) {
1185
  const lastUser = userMessages[userMessages.length - 1];
1186
  const mc = lastUser.querySelector('.message-content');
1187
- if (mc) { row.remove(); const lastText = mc.textContent.trim(); if (lastText) streamResponse(lastText); }
 
 
 
 
 
 
 
 
 
 
 
1188
  }
1189
  });
1190
  }
@@ -1277,4 +1309,52 @@ try { if (screen.orientation && screen.orientation.lock) screen.orientation.lock
1277
  window.addEventListener('load', () => {
1278
  checkExistingSession();
1279
  _bindFeedbackSubmit();
 
1280
  });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
365
  _updateHeroTitle();
366
  }
367
 
368
+ const _HERO_GREETINGS = [
369
+ 'What should we study today',
370
+ 'Ready to learn something new',
371
+ 'What topic are you curious about',
372
+ 'Let\'s tackle a concept together',
373
+ 'What can I help you understand',
374
+ 'Pick a subject and let\'s dive in',
375
+ 'Got a question? Fire away',
376
+ ];
377
+
378
  function _updateHeroTitle() {
379
  const el = document.getElementById('heroTitle');
380
  if (!el) return;
381
  const name = currentUsername || (currentUser ? currentUser.name : '');
382
+ const greeting = _HERO_GREETINGS[Math.floor(Math.random() * _HERO_GREETINGS.length)];
383
+ if (name) el.innerHTML = `${greeting}, <span class="hero-name">${escapeHtml(name)}</span>?`;
384
+ else el.textContent = greeting + '?';
385
  }
386
 
387
  function exitHeroMode() {
 
524
  div.id = 'welcomeScreen';
525
 
526
  const name = currentUsername || (currentUser ? currentUser.name : '');
527
+ const greeting = _HERO_GREETINGS[Math.floor(Math.random() * _HERO_GREETINGS.length)];
528
+ const titleHtml = name ? `${greeting}, <span class="hero-name">${escapeHtml(name)}</span>?` : `${greeting}?`;
529
  const styleLabel = _PERSONA_LABELS[currentPersona] || 'Vidyut';
530
 
531
  div.innerHTML = `
 
680
  exitHeroMode();
681
  if (window.innerWidth <= 768) closeSidebar();
682
 
683
+ // Show skeleton while loading
684
+ chatContainer.innerHTML = `
685
+ <div class="chat-skeleton">
686
+ <div class="chat-skeleton-row right"><div class="chat-skeleton-bubble"></div></div>
687
+ <div class="chat-skeleton-row left"><div class="chat-skeleton-bubble"></div></div>
688
+ <div class="chat-skeleton-row right"><div class="chat-skeleton-bubble"></div></div>
689
+ <div class="chat-skeleton-row left"><div class="chat-skeleton-bubble"></div></div>
690
+ </div>
691
+ `;
692
+
693
  fetch('/history/' + threadId).then(res => res.json()).then(data => {
694
+ chatContainer.innerHTML = '';
695
+ chatContainer.classList.add('history-loading');
696
  data.messages.forEach(msg => {
697
  const sender = msg.role === 'user' ? 'user' : 'ai';
698
  let textContent = msg.content;
 
700
  const el = appendMessage(sender, textContent);
701
  if (sender === 'ai') renderFinalContent(el, textContent);
702
  });
703
+ scrollToBottom();
704
+ requestAnimationFrame(() => chatContainer.classList.remove('history-loading'));
705
  });
706
  }
707
 
 
1068
  <div class="ai-avatar pulsing" id="avatarThinking"></div>
1069
  <div style="flex:1; min-width:0;">
1070
  <div class="thinking-indicator" id="currentThinking" style="padding-top:4px;">
1071
+ <div class="thinking-dots"><span></span><span></span><span></span></div>
1072
  </div>
1073
  <div class="message-content" style="display:none;"></div>
1074
  <div class="msg-actions" style="display:none;"></div>
 
1079
  _showStopBtn();
1080
 
1081
  const thinkingEl = rowDiv.querySelector('#currentThinking');
 
1082
  const contentEl = rowDiv.querySelector('.message-content');
1083
  const actionsEl = rowDiv.querySelector('.msg-actions');
1084
  let rawText = '';
 
1132
  if (pl === '[DONE]') { finishStream(thinkingEl, contentEl, rawText, currentRenderTimer, actionsEl); currentStreamStopped = true; return; }
1133
  try {
1134
  const data = JSON.parse(pl);
 
1135
  if (data.error) {
1136
  thinkingEl.style.display = 'none';
1137
  contentEl.style.display = 'block';
 
1185
  actionsEl.innerHTML = `
1186
  <button class="msg-action-btn" data-action="copy" title="Copy">
1187
  <svg viewBox="0 0 24 24" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="13" height="13" rx="2" ry="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>
 
1188
  </button>
1189
  <button class="msg-action-btn" data-action="regenerate" title="Regenerate">
1190
  <svg viewBox="0 0 24 24" stroke-linecap="round" stroke-linejoin="round"><polyline points="23 4 23 10 17 10"/><polyline points="1 20 1 14 7 14"/><path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"/></svg>
 
1191
  </button>
1192
  `;
1193
  const copyBtn = actionsEl.querySelector('[data-action="copy"]');
 
1195
  if (copyBtn) {
1196
  copyBtn.addEventListener('click', () => {
1197
  navigator.clipboard.writeText(rawText).then(() => {
1198
+ showToast('Copied!', 'success');
 
1199
  }).catch(() => showToast('Could not copy.', 'error'));
1200
  });
1201
  }
 
1205
  if (userMessages.length) {
1206
  const lastUser = userMessages[userMessages.length - 1];
1207
  const mc = lastUser.querySelector('.message-content');
1208
+ if (mc) {
1209
+ const lastText = mc.textContent.trim();
1210
+ // Remove both the AI response and user message
1211
+ row.remove();
1212
+ lastUser.remove();
1213
+ // Restore prompt into input field
1214
+ userInput.value = lastText;
1215
+ userInput.style.height = '54px';
1216
+ userInput.style.height = userInput.scrollHeight + 'px';
1217
+ if (adaptiveBtn) adaptiveBtn.classList.toggle('has-text', lastText.length > 0);
1218
+ userInput.focus();
1219
+ }
1220
  }
1221
  });
1222
  }
 
1309
  window.addEventListener('load', () => {
1310
  checkExistingSession();
1311
  _bindFeedbackSubmit();
1312
+ _initCustomSelects();
1313
  });
1314
+
1315
+ /* ── Custom Select Dropdowns ────────────────────────────────── */
1316
+
1317
+ function _initCustomSelects() {
1318
+ const pairs = [
1319
+ { btn: 'languageSelectBtn', list: 'languageSelectList', native: 'languageSelect' },
1320
+ { btn: 'feedbackCategoryBtn', list: 'feedbackCategoryList', native: 'feedbackCategory' },
1321
+ ];
1322
+
1323
+ pairs.forEach(({ btn, list, native }) => {
1324
+ const btnEl = document.getElementById(btn);
1325
+ const listEl = document.getElementById(list);
1326
+ const nativeEl = document.getElementById(native);
1327
+ if (!btnEl || !listEl) return;
1328
+
1329
+ btnEl.addEventListener('click', (e) => {
1330
+ e.stopPropagation();
1331
+ const isOpen = listEl.classList.contains('show');
1332
+ _closeAllCustomSelects();
1333
+ if (!isOpen) {
1334
+ listEl.classList.add('show');
1335
+ btnEl.classList.add('open');
1336
+ }
1337
+ });
1338
+
1339
+ listEl.querySelectorAll('.custom-select-option').forEach(opt => {
1340
+ opt.addEventListener('click', () => {
1341
+ const val = opt.dataset.value;
1342
+ const label = opt.textContent;
1343
+ btnEl.querySelector('span').textContent = label;
1344
+ listEl.querySelectorAll('.custom-select-option').forEach(o => o.classList.remove('active'));
1345
+ opt.classList.add('active');
1346
+ listEl.classList.remove('show');
1347
+ btnEl.classList.remove('open');
1348
+ if (nativeEl) { nativeEl.value = val; nativeEl.dispatchEvent(new Event('change')); }
1349
+ });
1350
+ });
1351
+ });
1352
+
1353
+ document.addEventListener('click', () => _closeAllCustomSelects());
1354
+ }
1355
+
1356
+ function _closeAllCustomSelects() {
1357
+ document.querySelectorAll('.custom-select-list.show').forEach(l => l.classList.remove('show'));
1358
+ document.querySelectorAll('.custom-select-btn.open').forEach(b => b.classList.remove('open'));
1359
+ }
1360
+
static/index.html CHANGED
@@ -391,7 +391,7 @@
391
  </button>
392
  </div>
393
  <div class="disclaimer-text">
394
- STEM Copilot is an AI tutor grounded in NCERT material. It can still make mistakes.
395
  </div>
396
  </div>
397
  </main>
@@ -462,7 +462,7 @@
462
  <!-- General Tab -->
463
  <div class="tab-content active" id="tab-general">
464
  <h3 class="settings-section-title">Language</h3>
465
- <select class="settings-select" id="languageSelect">
466
  <option value="auto">Auto-detect</option>
467
  <option value="english">English</option>
468
  <option value="hinglish">Hinglish</option>
@@ -471,6 +471,21 @@
471
  <option value="marathi">Marathi</option>
472
  <option value="french">French</option>
473
  </select>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
474
  </div>
475
 
476
  <!-- Appearance Tab -->
@@ -527,11 +542,22 @@
527
  <!-- Feedback Tab -->
528
  <div class="tab-content" id="tab-feedback">
529
  <h3 class="settings-section-title">Category</h3>
530
- <select class="settings-select" id="feedbackCategory">
531
  <option value="bug">Report a Bug</option>
532
  <option value="improvement">Suggest Improvement</option>
533
  <option value="other">Other</option>
534
  </select>
 
 
 
 
 
 
 
 
 
 
 
535
  <h3 class="settings-section-title" style="margin-top:16px;">Message</h3>
536
  <textarea class="settings-textarea" id="feedbackMessage" rows="5"
537
  placeholder="Tell us how we can improve..."></textarea>
 
391
  </button>
392
  </div>
393
  <div class="disclaimer-text">
394
+ STEM Copilot is AI and can make mistakes.
395
  </div>
396
  </div>
397
  </main>
 
462
  <!-- General Tab -->
463
  <div class="tab-content active" id="tab-general">
464
  <h3 class="settings-section-title">Language</h3>
465
+ <select class="settings-select" id="languageSelect" style="display:none;">
466
  <option value="auto">Auto-detect</option>
467
  <option value="english">English</option>
468
  <option value="hinglish">Hinglish</option>
 
471
  <option value="marathi">Marathi</option>
472
  <option value="french">French</option>
473
  </select>
474
+ <div class="custom-select-wrap" id="languageSelectWrap">
475
+ <button type="button" class="custom-select-btn" id="languageSelectBtn">
476
+ <span>Auto-detect</span>
477
+ <svg viewBox="0 0 24 24" stroke-linecap="round" stroke-linejoin="round"><polyline points="6 9 12 15 18 9" /></svg>
478
+ </button>
479
+ <div class="custom-select-list" id="languageSelectList">
480
+ <div class="custom-select-option active" data-value="auto">Auto-detect</div>
481
+ <div class="custom-select-option" data-value="english">English</div>
482
+ <div class="custom-select-option" data-value="hinglish">Hinglish</div>
483
+ <div class="custom-select-option" data-value="hindi">Hindi</div>
484
+ <div class="custom-select-option" data-value="gujarati">Gujarati</div>
485
+ <div class="custom-select-option" data-value="marathi">Marathi</div>
486
+ <div class="custom-select-option" data-value="french">French</div>
487
+ </div>
488
+ </div>
489
  </div>
490
 
491
  <!-- Appearance Tab -->
 
542
  <!-- Feedback Tab -->
543
  <div class="tab-content" id="tab-feedback">
544
  <h3 class="settings-section-title">Category</h3>
545
+ <select class="settings-select" id="feedbackCategory" style="display:none;">
546
  <option value="bug">Report a Bug</option>
547
  <option value="improvement">Suggest Improvement</option>
548
  <option value="other">Other</option>
549
  </select>
550
+ <div class="custom-select-wrap" id="feedbackCategoryWrap">
551
+ <button type="button" class="custom-select-btn" id="feedbackCategoryBtn">
552
+ <span>Report a Bug</span>
553
+ <svg viewBox="0 0 24 24" stroke-linecap="round" stroke-linejoin="round"><polyline points="6 9 12 15 18 9" /></svg>
554
+ </button>
555
+ <div class="custom-select-list" id="feedbackCategoryList">
556
+ <div class="custom-select-option active" data-value="bug">Report a Bug</div>
557
+ <div class="custom-select-option" data-value="improvement">Suggest Improvement</div>
558
+ <div class="custom-select-option" data-value="other">Other</div>
559
+ </div>
560
+ </div>
561
  <h3 class="settings-section-title" style="margin-top:16px;">Message</h3>
562
  <textarea class="settings-textarea" id="feedbackMessage" rows="5"
563
  placeholder="Tell us how we can improve..."></textarea>
static/style.css CHANGED
@@ -29,7 +29,7 @@
29
  --transition: 0.35s cubic-bezier(0.4, 0, 0.2, 1);
30
  --sidebar-width: 280px;
31
  --rail-width: 56px;
32
- --topbar-height: 52px;
33
  }
34
 
35
  /* ── Light Mode ── */
@@ -381,8 +381,8 @@ textarea, input, select {
381
  }
382
 
383
  .topbar-avatar {
384
- width: 32px;
385
- height: 32px;
386
  border-radius: 50%;
387
  object-fit: cover;
388
  border: 2px solid var(--border-color);
@@ -395,7 +395,7 @@ textarea, input, select {
395
  }
396
 
397
  .topbar-logo {
398
- height: 28px;
399
  object-fit: contain;
400
  position: absolute;
401
  left: 50%;
@@ -408,8 +408,8 @@ textarea, input, select {
408
  }
409
 
410
  .topbar-icon-btn {
411
- width: 36px;
412
- height: 36px;
413
  border-radius: 10px;
414
  background: transparent;
415
  border: none;
@@ -1148,18 +1148,40 @@ textarea, input, select {
1148
  50% { opacity: 1; transform: scale(1.05); }
1149
  }
1150
 
1151
- /* Thinking indicator */
1152
  .thinking-indicator {
1153
  display: flex;
1154
  align-items: center;
1155
- gap: 10px;
1156
  padding: 8px 0;
1157
  animation: fadeIn 0.3s ease-out;
1158
  }
1159
 
1160
  .thinking-indicator.hidden { display: none; }
1161
 
1162
- .thinking-text { font-size: 13px; color: var(--text-secondary); font-style: italic; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1163
 
1164
  /* Rendered markdown */
1165
  .message-content h1, .message-content h2, .message-content h3 {
@@ -1235,28 +1257,27 @@ textarea, input, select {
1235
  .message-row.ai:hover .msg-actions, .msg-actions.visible { opacity: 1; }
1236
 
1237
  .msg-action-btn {
1238
- background: var(--bg-card);
1239
- border: 1px solid var(--border-color);
1240
- border-radius: 6px;
1241
- padding: 4px 10px;
1242
- font-size: 11px;
1243
- font-family: inherit;
1244
- font-weight: 500;
1245
- color: var(--text-secondary);
1246
  cursor: pointer;
1247
  display: inline-flex;
1248
  align-items: center;
1249
- gap: 5px;
1250
- transition: background 0.2s, color 0.2s, border-color 0.2s;
1251
  }
1252
 
1253
  .msg-action-btn:hover {
1254
  background: var(--bg-hover);
1255
- color: var(--text-primary);
1256
- border-color: var(--brand);
1257
  }
1258
 
1259
- .msg-action-btn svg { width: 13px; height: 13px; stroke: currentColor; fill: none; stroke-width: 2; }
1260
 
1261
 
1262
  /* ============================================================
@@ -1491,9 +1512,9 @@ textarea, input, select {
1491
  .adaptive-action-btn.has-text .icon-mic { display: none; }
1492
  .adaptive-action-btn.has-text .icon-send { display: block; }
1493
 
1494
- /* Listening state */
1495
  .adaptive-action-btn.listening {
1496
- color: #EA4335 !important;
1497
  animation: micPulse 1.5s infinite ease-in-out;
1498
  }
1499
 
@@ -1797,14 +1818,128 @@ textarea, input, select {
1797
  ============================================================ */
1798
 
1799
  .error-message {
1800
- color: #ff6b6b;
1801
- font-style: italic;
1802
- padding: 10px 14px;
1803
- background: rgba(255, 75, 75, 0.08);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1804
  border-radius: 8px;
1805
- border-left: 3px solid #ff4a4a;
 
 
 
 
1806
  }
1807
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1808
 
1809
  /* ============================================================
1810
  SIDEBAR OVERLAY (mobile edge-swipe)
 
29
  --transition: 0.35s cubic-bezier(0.4, 0, 0.2, 1);
30
  --sidebar-width: 280px;
31
  --rail-width: 56px;
32
+ --topbar-height: 60px;
33
  }
34
 
35
  /* ── Light Mode ── */
 
381
  }
382
 
383
  .topbar-avatar {
384
+ width: 38px;
385
+ height: 38px;
386
  border-radius: 50%;
387
  object-fit: cover;
388
  border: 2px solid var(--border-color);
 
395
  }
396
 
397
  .topbar-logo {
398
+ height: 34px;
399
  object-fit: contain;
400
  position: absolute;
401
  left: 50%;
 
408
  }
409
 
410
  .topbar-icon-btn {
411
+ width: 40px;
412
+ height: 40px;
413
  border-radius: 10px;
414
  background: transparent;
415
  border: none;
 
1148
  50% { opacity: 1; transform: scale(1.05); }
1149
  }
1150
 
1151
+ /* Thinking indicator — bouncing dots */
1152
  .thinking-indicator {
1153
  display: flex;
1154
  align-items: center;
1155
+ gap: 6px;
1156
  padding: 8px 0;
1157
  animation: fadeIn 0.3s ease-out;
1158
  }
1159
 
1160
  .thinking-indicator.hidden { display: none; }
1161
 
1162
+ .thinking-text { display: none; }
1163
+
1164
+ .thinking-dots {
1165
+ display: flex;
1166
+ gap: 4px;
1167
+ align-items: center;
1168
+ }
1169
+
1170
+ .thinking-dots span {
1171
+ width: 7px;
1172
+ height: 7px;
1173
+ border-radius: 50%;
1174
+ background: var(--text-muted);
1175
+ animation: dotBounce 1.4s ease-in-out infinite;
1176
+ }
1177
+
1178
+ .thinking-dots span:nth-child(2) { animation-delay: 0.16s; }
1179
+ .thinking-dots span:nth-child(3) { animation-delay: 0.32s; }
1180
+
1181
+ @keyframes dotBounce {
1182
+ 0%, 80%, 100% { transform: scale(0.6); opacity: 0.4; }
1183
+ 40% { transform: scale(1); opacity: 1; }
1184
+ }
1185
 
1186
  /* Rendered markdown */
1187
  .message-content h1, .message-content h2, .message-content h3 {
 
1257
  .message-row.ai:hover .msg-actions, .msg-actions.visible { opacity: 1; }
1258
 
1259
  .msg-action-btn {
1260
+ background: none;
1261
+ border: none;
1262
+ border-radius: 50%;
1263
+ width: 28px;
1264
+ height: 28px;
1265
+ padding: 0;
1266
+ font-size: 0;
1267
+ color: var(--text-muted);
1268
  cursor: pointer;
1269
  display: inline-flex;
1270
  align-items: center;
1271
+ justify-content: center;
1272
+ transition: background 0.2s, color 0.2s;
1273
  }
1274
 
1275
  .msg-action-btn:hover {
1276
  background: var(--bg-hover);
1277
+ color: var(--brand);
 
1278
  }
1279
 
1280
+ .msg-action-btn svg { width: 14px; height: 14px; stroke: currentColor; fill: none; stroke-width: 2; }
1281
 
1282
 
1283
  /* ============================================================
 
1512
  .adaptive-action-btn.has-text .icon-mic { display: none; }
1513
  .adaptive-action-btn.has-text .icon-send { display: block; }
1514
 
1515
+ /* Listening state — green to signal active recording */
1516
  .adaptive-action-btn.listening {
1517
+ color: #10b981 !important;
1518
  animation: micPulse 1.5s infinite ease-in-out;
1519
  }
1520
 
 
1818
  ============================================================ */
1819
 
1820
  .error-message {
1821
+ color: #ff4a4a;
1822
+ font-family: 'Montserrat', sans-serif;
1823
+ font-weight: 600;
1824
+ font-style: normal;
1825
+ font-size: 14px;
1826
+ padding: 0;
1827
+ background: none;
1828
+ border: none;
1829
+ border-radius: 0;
1830
+ }
1831
+
1832
+ /* Chat skeleton loading */
1833
+ .chat-skeleton {
1834
+ display: flex;
1835
+ flex-direction: column;
1836
+ gap: 16px;
1837
+ padding: 20px 0;
1838
+ max-width: 800px;
1839
+ margin: 0 auto;
1840
+ }
1841
+
1842
+ .chat-skeleton-row {
1843
+ display: flex;
1844
+ gap: 12px;
1845
+ align-items: flex-start;
1846
+ }
1847
+
1848
+ .chat-skeleton-row.right { justify-content: flex-end; }
1849
+
1850
+ .chat-skeleton-bubble {
1851
+ border-radius: 12px;
1852
+ background: var(--bg-hover);
1853
+ animation: skeletonPulse 1.5s ease-in-out infinite;
1854
+ }
1855
+
1856
+ .chat-skeleton-row.left .chat-skeleton-bubble {
1857
+ width: 65%;
1858
+ height: 48px;
1859
+ }
1860
+
1861
+ .chat-skeleton-row.right .chat-skeleton-bubble {
1862
+ width: 45%;
1863
+ height: 32px;
1864
+ }
1865
+
1866
+ @keyframes skeletonPulse {
1867
+ 0%, 100% { opacity: 0.4; }
1868
+ 50% { opacity: 0.8; }
1869
+ }
1870
+
1871
+ /* Custom select dropdown (PWA-native replacement for <select>) */
1872
+ .custom-select-wrap {
1873
+ position: relative;
1874
+ width: 100%;
1875
+ }
1876
+
1877
+ .custom-select-btn {
1878
+ width: 100%;
1879
+ padding: 11px 14px;
1880
+ background: var(--bg-input);
1881
+ border: 1px solid var(--border-color);
1882
+ border-radius: 8px;
1883
+ color: var(--text-primary);
1884
+ font-family: inherit;
1885
+ font-size: 14px;
1886
+ cursor: pointer;
1887
+ display: flex;
1888
+ justify-content: space-between;
1889
+ align-items: center;
1890
+ transition: border-color 0.2s;
1891
+ outline: none;
1892
+ text-align: left;
1893
+ }
1894
+
1895
+ .custom-select-btn:focus,
1896
+ .custom-select-btn.open {
1897
+ border-color: var(--brand);
1898
+ }
1899
+
1900
+ .custom-select-btn svg {
1901
+ width: 14px;
1902
+ height: 14px;
1903
+ stroke: var(--text-muted);
1904
+ fill: none;
1905
+ stroke-width: 2;
1906
+ flex-shrink: 0;
1907
+ transition: transform 0.2s;
1908
+ }
1909
+
1910
+ .custom-select-btn.open svg { transform: rotate(180deg); }
1911
+
1912
+ .custom-select-list {
1913
+ display: none;
1914
+ position: absolute;
1915
+ top: calc(100% + 4px);
1916
+ left: 0;
1917
+ right: 0;
1918
+ background: var(--bg-elevated);
1919
+ border: 1px solid var(--border-color);
1920
  border-radius: 8px;
1921
+ box-shadow: 0 8px 24px rgba(0,0,0,0.4);
1922
+ z-index: 200;
1923
+ max-height: 220px;
1924
+ overflow-y: auto;
1925
+ animation: fadeIn 0.15s ease-out;
1926
  }
1927
 
1928
+ .custom-select-list.show { display: block; }
1929
+
1930
+ .custom-select-option {
1931
+ padding: 10px 14px;
1932
+ font-size: 14px;
1933
+ color: var(--text-secondary);
1934
+ cursor: pointer;
1935
+ transition: background 0.15s, color 0.15s;
1936
+ border-bottom: 1px solid var(--border-subtle);
1937
+ }
1938
+
1939
+ .custom-select-option:last-child { border-bottom: none; }
1940
+ .custom-select-option:hover { background: var(--bg-hover); color: var(--text-primary); }
1941
+ .custom-select-option.active { background: var(--brand-glow); color: var(--brand); font-weight: 600; }
1942
+
1943
 
1944
  /* ============================================================
1945
  SIDEBAR OVERLAY (mobile edge-swipe)