CBV01 commited on
Commit
2084ad0
·
1 Parent(s): 504c45c

feat: anti-ban pool protection, AI model pricing & rate limit alerts, admin View DMs tab, mobile layout & DM scroll fixes

Browse files
backend/main.py CHANGED
@@ -1623,12 +1623,24 @@ def _dialogs_match(a: Dict[str, Any], b: Dict[str, Any]) -> bool:
1623
  @app.post("/api/telegram/compare")
1624
  async def compare_accounts(req: CompareAccountsRequest, user_id: str = Depends(get_current_user_id)):
1625
  """Compare groups and channels between two logged-in accounts."""
1626
- # Verify user plan - Fleet Compare requires an upgraded plan
1627
- conn_chk = get_db_connection()
1628
- u_chk = conn_chk.execute("SELECT plan FROM users WHERE id = ?", (user_id,)).fetchone()
1629
- if hasattr(conn_chk, "close"): conn_chk.close()
1630
- u_plan = u_chk[0] if u_chk and u_chk[0] else "free"
1631
- if u_plan == "free":
 
 
 
 
 
 
 
 
 
 
 
 
1632
  raise HTTPException(
1633
  status_code=403,
1634
  detail="Fleet Compare is only available on upgraded plans (Growth Basic, Pro Standard, or Enterprise Premium). Please upgrade to unlock."
@@ -4159,7 +4171,8 @@ async def get_user_status(user_id: str = Depends(get_current_user_id)):
4159
  if hasattr(conn, "close"): conn.close()
4160
 
4161
  # Tier mapping
4162
- active_plan = row["plan"] or "free"
 
4163
  p_cfg = get_plan_configs().get(active_plan, get_plan_configs()["free"])
4164
 
4165
  allowed_speeds = ["balanced"]
@@ -5403,11 +5416,18 @@ async def get_openrouter_models():
5403
  for m in raw_models:
5404
  m_id = m.get("id")
5405
  if m_id:
 
5406
  models.append({
5407
  "id": m_id,
5408
  "name": m.get("name") or m_id,
5409
  "context_length": m.get("context_length", 0),
5410
- "description": (m.get("description") or "")[:140]
 
 
 
 
 
 
5411
  })
5412
 
5413
  def sort_key(item):
@@ -5426,16 +5446,16 @@ async def get_openrouter_models():
5426
 
5427
  # Fallback default models if network error
5428
  fallback = [
5429
- {"id": "meta-llama/llama-3.3-70b-instruct", "name": "Meta: Llama 3.3 70B Instruct", "context_length": 131072},
5430
- {"id": "anthropic/claude-3.5-sonnet", "name": "Anthropic: Claude 3.5 Sonnet", "context_length": 200000},
5431
- {"id": "deepseek/deepseek-chat", "name": "DeepSeek: DeepSeek V3", "context_length": 64000},
5432
- {"id": "deepseek/deepseek-r1", "name": "DeepSeek: DeepSeek R1", "context_length": 64000},
5433
- {"id": "openai/gpt-4o-mini", "name": "OpenAI: GPT-4o Mini", "context_length": 128000},
5434
- {"id": "openai/gpt-4o", "name": "OpenAI: GPT-4o", "context_length": 128000},
5435
- {"id": "google/gemini-2.0-flash-exp:free", "name": "Google: Gemini 2.0 Flash Exp (free)", "context_length": 1048576},
5436
- {"id": "google/gemini-flash-1.5", "name": "Google: Gemini Flash 1.5", "context_length": 1000000},
5437
- {"id": "mistralai/mistral-nemo", "name": "Mistral: Mistral Nemo", "context_length": 128000},
5438
- {"id": "qwen/qwen-2.5-72b-instruct", "name": "Qwen: Qwen 2.5 72B Instruct", "context_length": 131072}
5439
  ]
5440
  return {"models": _openrouter_models_cache["models"] or fallback}
5441
 
@@ -5586,7 +5606,11 @@ async def suggest_ai_keywords(req: AISuggestRequest, user_id: str = Depends(get_
5586
  err_msg = err_json.get("error", {}).get("message") or res.text[:120]
5587
  except Exception:
5588
  err_msg = res.text[:120]
5589
- error_note = f"OpenRouter error ({res.status_code}): {err_msg}"
 
 
 
 
5590
  except Exception as e:
5591
  error_note = f"AI request exception: {str(e)}"
5592
 
@@ -5629,7 +5653,9 @@ async def suggest_ai_keywords(req: AISuggestRequest, user_id: str = Depends(get_
5629
  "max_allowed": max_allowed,
5630
  "plan": user_plan,
5631
  "source": "openrouter",
5632
- "model": selected_model
 
 
5633
  }
5634
 
5635
  class AISpintaxRequest(BaseModel):
@@ -5785,6 +5811,12 @@ async def generate_ai_spintax(req: AISpintaxRequest, user_id: str = Depends(get_
5785
  err_msg = res.json().get("error", {}).get("message") or res.text[:120]
5786
  except Exception:
5787
  err_msg = res.text[:120]
 
 
 
 
 
 
5788
  raise HTTPException(status_code=res.status_code, detail=f"OpenRouter error: {err_msg}")
5789
  except HTTPException:
5790
  raise
@@ -6150,6 +6182,12 @@ async def generate_template_variations(req: AITemplateVariationsRequest, user_id
6150
  err_msg = err_data.get("error", {}).get("message") or res.text[:200]
6151
  except Exception:
6152
  err_msg = res.text[:200]
 
 
 
 
 
 
6153
  raise HTTPException(status_code=res.status_code, detail=f"OpenRouter error ({res.status_code}): {err_msg}")
6154
  except httpx.TimeoutException:
6155
  raise HTTPException(status_code=504, detail="AI generation timed out. OpenRouter is experiencing latency. Please try again.")
@@ -6212,19 +6250,13 @@ async def check_account_spambot(phone: str, user_id: str = Depends(get_current_u
6212
 
6213
  @app.get("/api/telegram/accounts/{phone}/dms")
6214
  async def get_account_dms(phone: str, user_id: str = Depends(get_current_user_id)):
6215
- """Safely fetches up to 60 recent 1-on-1 private DMs on-demand across up to 300 dialogs."""
6216
- conn = get_db_connection()
6217
- row = conn.execute("SELECT session_string, api_id, api_hash FROM accounts WHERE phone_number = ? AND user_id = ?", (phone, user_id)).fetchone()
6218
- if hasattr(conn, "close"): conn.close()
6219
- if not row:
6220
- raise HTTPException(status_code=404, detail="Account not found")
6221
-
6222
- session_str, api_id, api_hash = row[0], int(row[1]), row[2]
6223
- client = TelegramClient(StringSession(session_str), api_id, api_hash)
6224
- await client.connect()
6225
- if not await client.is_user_authorized():
6226
- await client.disconnect()
6227
- raise HTTPException(status_code=401, detail="Account session expired. Please re-login.")
6228
 
6229
  dms = []
6230
  try:
@@ -6256,24 +6288,16 @@ async def get_account_dms(phone: str, user_id: str = Depends(get_current_user_id
6256
  return {"dms": dms, "phone": phone, "total": len(dms)}
6257
  except Exception as e:
6258
  raise HTTPException(status_code=400, detail=f"Failed to fetch DMs: {str(e)}")
6259
- finally:
6260
- await client.disconnect()
6261
 
6262
  @app.get("/api/telegram/accounts/{phone}/dms/{contact_id}/messages")
6263
  async def get_dm_messages(phone: str, contact_id: int, access_hash: Optional[str] = None, user_id: str = Depends(get_current_user_id)):
6264
  """Fetches the last 50 messages of a private DM conversation with robust entity resolution."""
6265
- conn = get_db_connection()
6266
- row = conn.execute("SELECT session_string, api_id, api_hash FROM accounts WHERE phone_number = ? AND user_id = ?", (phone, user_id)).fetchone()
6267
- if hasattr(conn, "close"): conn.close()
6268
- if not row:
6269
- raise HTTPException(status_code=404, detail="Account not found")
6270
-
6271
- session_str, api_id, api_hash = row[0], int(row[1]), row[2]
6272
- client = TelegramClient(StringSession(session_str), api_id, api_hash)
6273
- await client.connect()
6274
- if not await client.is_user_authorized():
6275
- await client.disconnect()
6276
- raise HTTPException(status_code=401, detail="Account session expired.")
6277
 
6278
  try:
6279
  from telethon.tl.types import InputPeerUser
@@ -6333,8 +6357,6 @@ async def get_dm_messages(phone: str, contact_id: int, access_hash: Optional[str
6333
  except Exception as e:
6334
  log_debug(f"DM_FETCH_MSGS_ERR: {str(e)}")
6335
  raise HTTPException(status_code=400, detail=f"Failed to load messages: {str(e)}")
6336
- finally:
6337
- await client.disconnect()
6338
 
6339
 
6340
  class DMSendRequest(BaseModel):
@@ -6348,18 +6370,12 @@ async def send_dm_message(phone: str, contact_id: int, req: DMSendRequest, user_
6348
  if not text:
6349
  raise HTTPException(status_code=400, detail="Message text is required")
6350
 
6351
- conn = get_db_connection()
6352
- row = conn.execute("SELECT session_string, api_id, api_hash FROM accounts WHERE phone_number = ? AND user_id = ?", (phone, user_id)).fetchone()
6353
- if hasattr(conn, "close"): conn.close()
6354
- if not row:
6355
- raise HTTPException(status_code=404, detail="Account not found")
6356
-
6357
- session_str, api_id, api_hash = row[0], int(row[1]), row[2]
6358
- client = TelegramClient(StringSession(session_str), api_id, api_hash)
6359
- await client.connect()
6360
- if not await client.is_user_authorized():
6361
- await client.disconnect()
6362
- raise HTTPException(status_code=401, detail="Account session expired.")
6363
 
6364
  try:
6365
  from telethon.tl.types import InputPeerUser
@@ -6395,10 +6411,8 @@ async def send_dm_message(phone: str, contact_id: int, req: DMSendRequest, user_
6395
  }
6396
  }
6397
  except Exception as e:
6398
- log_debug(f"DM_SEND_REPLY_ERR: {str(e)}")
6399
- raise HTTPException(status_code=400, detail=f"Failed to send reply: {str(e)}")
6400
- finally:
6401
- await client.disconnect()
6402
 
6403
 
6404
  # ==========================================
@@ -6607,6 +6621,12 @@ async def analyze_dm_conversation(req: AIAnalyzeDmRequest, user_id: str = Depend
6607
  except Exception:
6608
  err_detail = res.text[:200]
6609
  log_debug(f"OPENROUTER_DM_ERR ({res.status_code}): {err_detail}")
 
 
 
 
 
 
6610
  raise HTTPException(status_code=400, detail=f"OpenRouter Error ({res.status_code}): {err_detail}")
6611
 
6612
  data = res.json()
 
1623
  @app.post("/api/telegram/compare")
1624
  async def compare_accounts(req: CompareAccountsRequest, user_id: str = Depends(get_current_user_id)):
1625
  """Compare groups and channels between two logged-in accounts."""
1626
+ # Verify user plan - Fleet Compare requires an upgraded plan (Admins have unlimited access)
1627
+ is_admin = (user_id == "admin_virtual_id")
1628
+ u_plan = "unlimited" if is_admin else "free"
1629
+ if not is_admin:
1630
+ conn_chk = get_db_connection()
1631
+ try:
1632
+ u_chk = conn_chk.execute("SELECT plan, role FROM users WHERE id = ?", (user_id,)).fetchone()
1633
+ if u_chk:
1634
+ u_plan = u_chk[0] or "free"
1635
+ u_role = u_chk[1] if len(u_chk) > 1 else "user"
1636
+ if u_role == "admin" or u_plan == "unlimited":
1637
+ is_admin = True
1638
+ else:
1639
+ u_plan = "free"
1640
+ finally:
1641
+ if hasattr(conn_chk, "close"): conn_chk.close()
1642
+
1643
+ if not is_admin and u_plan == "free":
1644
  raise HTTPException(
1645
  status_code=403,
1646
  detail="Fleet Compare is only available on upgraded plans (Growth Basic, Pro Standard, or Enterprise Premium). Please upgrade to unlock."
 
4171
  if hasattr(conn, "close"): conn.close()
4172
 
4173
  # Tier mapping
4174
+ user_role = row["role"] if ("role" in row.keys() and row["role"]) else "user"
4175
+ active_plan = "unlimited" if user_role == "admin" else (row["plan"] or "free")
4176
  p_cfg = get_plan_configs().get(active_plan, get_plan_configs()["free"])
4177
 
4178
  allowed_speeds = ["balanced"]
 
5416
  for m in raw_models:
5417
  m_id = m.get("id")
5418
  if m_id:
5419
+ p_raw = m.get("pricing") or {}
5420
  models.append({
5421
  "id": m_id,
5422
  "name": m.get("name") or m_id,
5423
  "context_length": m.get("context_length", 0),
5424
+ "description": (m.get("description") or "")[:140],
5425
+ "pricing": {
5426
+ "prompt": str(p_raw.get("prompt", "0")),
5427
+ "completion": str(p_raw.get("completion", "0")),
5428
+ "request": str(p_raw.get("request", "0")),
5429
+ "image": str(p_raw.get("image", "0"))
5430
+ }
5431
  })
5432
 
5433
  def sort_key(item):
 
5446
 
5447
  # Fallback default models if network error
5448
  fallback = [
5449
+ {"id": "meta-llama/llama-3.3-70b-instruct", "name": "Meta: Llama 3.3 70B Instruct", "context_length": 131072, "pricing": {"prompt": "0.00000012", "completion": "0.0000003"}},
5450
+ {"id": "anthropic/claude-3.5-sonnet", "name": "Anthropic: Claude 3.5 Sonnet", "context_length": 200000, "pricing": {"prompt": "0.000003", "completion": "0.000015"}},
5451
+ {"id": "deepseek/deepseek-chat", "name": "DeepSeek: DeepSeek V3", "context_length": 64000, "pricing": {"prompt": "0.00000014", "completion": "0.00000028"}},
5452
+ {"id": "deepseek/deepseek-r1", "name": "DeepSeek: DeepSeek R1", "context_length": 64000, "pricing": {"prompt": "0.00000055", "completion": "0.00000219"}},
5453
+ {"id": "openai/gpt-4o-mini", "name": "OpenAI: GPT-4o Mini", "context_length": 128000, "pricing": {"prompt": "0.00000015", "completion": "0.0000006"}},
5454
+ {"id": "openai/gpt-4o", "name": "OpenAI: GPT-4o", "context_length": 128000, "pricing": {"prompt": "0.0000025", "completion": "0.00001"}},
5455
+ {"id": "google/gemini-2.0-flash-exp:free", "name": "Google: Gemini 2.0 Flash Exp (free)", "context_length": 1048576, "pricing": {"prompt": "0", "completion": "0"}},
5456
+ {"id": "google/gemini-flash-1.5", "name": "Google: Gemini Flash 1.5", "context_length": 1000000, "pricing": {"prompt": "0.000000075", "completion": "0.0000003"}},
5457
+ {"id": "mistralai/mistral-nemo", "name": "Mistral: Mistral Nemo", "context_length": 128000, "pricing": {"prompt": "0.00000013", "completion": "0.00000013"}},
5458
+ {"id": "qwen/qwen-2.5-72b-instruct", "name": "Qwen: Qwen 2.5 72B Instruct", "context_length": 131072, "pricing": {"prompt": "0.00000035", "completion": "0.0000004"}}
5459
  ]
5460
  return {"models": _openrouter_models_cache["models"] or fallback}
5461
 
 
5606
  err_msg = err_json.get("error", {}).get("message") or res.text[:120]
5607
  except Exception:
5608
  err_msg = res.text[:120]
5609
+ is_rate_limit = (res.status_code in (429, 402)) or any(w in str(err_msg).lower() for w in ("rate limit", "quota", "credit", "free tier", "limit exceeded"))
5610
+ if is_rate_limit:
5611
+ error_note = f"FREE_MODEL_LIMIT: The model '{selected_model}' has reached OpenRouter's free tier rate limit or daily quota. Please select another free model or add credits."
5612
+ else:
5613
+ error_note = f"OpenRouter error ({res.status_code}): {err_msg}"
5614
  except Exception as e:
5615
  error_note = f"AI request exception: {str(e)}"
5616
 
 
5653
  "max_allowed": max_allowed,
5654
  "plan": user_plan,
5655
  "source": "openrouter",
5656
+ "model": selected_model,
5657
+ "error_note": error_note,
5658
+ "is_free_limit": bool(error_note and "FREE_MODEL_LIMIT" in str(error_note))
5659
  }
5660
 
5661
  class AISpintaxRequest(BaseModel):
 
5811
  err_msg = res.json().get("error", {}).get("message") or res.text[:120]
5812
  except Exception:
5813
  err_msg = res.text[:120]
5814
+ is_rate_limit = (res.status_code in (429, 402)) or any(w in str(err_msg).lower() for w in ("rate limit", "quota", "credit", "free tier", "limit exceeded"))
5815
+ if is_rate_limit:
5816
+ raise HTTPException(
5817
+ status_code=429,
5818
+ detail=f"FREE_MODEL_LIMIT: The model '{selected_model}' has reached OpenRouter's free tier rate limit or daily quota. Please select another free model or add credits."
5819
+ )
5820
  raise HTTPException(status_code=res.status_code, detail=f"OpenRouter error: {err_msg}")
5821
  except HTTPException:
5822
  raise
 
6182
  err_msg = err_data.get("error", {}).get("message") or res.text[:200]
6183
  except Exception:
6184
  err_msg = res.text[:200]
6185
+ is_rate_limit = (res.status_code in (429, 402)) or any(w in str(err_msg).lower() for w in ("rate limit", "quota", "credit", "free tier", "limit exceeded"))
6186
+ if is_rate_limit:
6187
+ raise HTTPException(
6188
+ status_code=429,
6189
+ detail=f"FREE_MODEL_LIMIT: The model '{selected_model}' has reached OpenRouter's free tier rate limit or daily quota. Please select another free model or add credits."
6190
+ )
6191
  raise HTTPException(status_code=res.status_code, detail=f"OpenRouter error ({res.status_code}): {err_msg}")
6192
  except httpx.TimeoutException:
6193
  raise HTTPException(status_code=504, detail="AI generation timed out. OpenRouter is experiencing latency. Please try again.")
 
6250
 
6251
  @app.get("/api/telegram/accounts/{phone}/dms")
6252
  async def get_account_dms(phone: str, user_id: str = Depends(get_current_user_id)):
6253
+ """Safely fetches recent 1-on-1 private DMs using the managed connection pool."""
6254
+ try:
6255
+ client = await POOL.get_client(user_id, phone)
6256
+ except HTTPException:
6257
+ raise
6258
+ except Exception as e:
6259
+ raise HTTPException(status_code=400, detail=f"Account connection failed: {str(e)}")
 
 
 
 
 
 
6260
 
6261
  dms = []
6262
  try:
 
6288
  return {"dms": dms, "phone": phone, "total": len(dms)}
6289
  except Exception as e:
6290
  raise HTTPException(status_code=400, detail=f"Failed to fetch DMs: {str(e)}")
 
 
6291
 
6292
  @app.get("/api/telegram/accounts/{phone}/dms/{contact_id}/messages")
6293
  async def get_dm_messages(phone: str, contact_id: int, access_hash: Optional[str] = None, user_id: str = Depends(get_current_user_id)):
6294
  """Fetches the last 50 messages of a private DM conversation with robust entity resolution."""
6295
+ try:
6296
+ client = await POOL.get_client(user_id, phone)
6297
+ except HTTPException:
6298
+ raise
6299
+ except Exception as e:
6300
+ raise HTTPException(status_code=400, detail=f"Account connection failed: {str(e)}")
 
 
 
 
 
 
6301
 
6302
  try:
6303
  from telethon.tl.types import InputPeerUser
 
6357
  except Exception as e:
6358
  log_debug(f"DM_FETCH_MSGS_ERR: {str(e)}")
6359
  raise HTTPException(status_code=400, detail=f"Failed to load messages: {str(e)}")
 
 
6360
 
6361
 
6362
  class DMSendRequest(BaseModel):
 
6370
  if not text:
6371
  raise HTTPException(status_code=400, detail="Message text is required")
6372
 
6373
+ try:
6374
+ client = await POOL.get_client(user_id, phone)
6375
+ except HTTPException:
6376
+ raise
6377
+ except Exception as e:
6378
+ raise HTTPException(status_code=400, detail=f"Account connection failed: {str(e)}")
 
 
 
 
 
 
6379
 
6380
  try:
6381
  from telethon.tl.types import InputPeerUser
 
6411
  }
6412
  }
6413
  except Exception as e:
6414
+ log_debug(f"DM_SEND_ERR: {str(e)}")
6415
+ raise HTTPException(status_code=400, detail=f"Failed to send DM: {str(e)}")
 
 
6416
 
6417
 
6418
  # ==========================================
 
6621
  except Exception:
6622
  err_detail = res.text[:200]
6623
  log_debug(f"OPENROUTER_DM_ERR ({res.status_code}): {err_detail}")
6624
+ is_rate_limit = (res.status_code in (429, 402)) or any(w in str(err_detail).lower() for w in ("rate limit", "quota", "credit", "free tier", "limit exceeded"))
6625
+ if is_rate_limit:
6626
+ raise HTTPException(
6627
+ status_code=429,
6628
+ detail=f"FREE_MODEL_LIMIT: The model '{selected_model}' has reached OpenRouter's free tier rate limit or daily quota. Please select another free model (such as Gemini 2.0 Flash or LLaMA 3.3) or add OpenRouter credits."
6629
+ )
6630
  raise HTTPException(status_code=400, detail=f"OpenRouter Error ({res.status_code}): {err_detail}")
6631
 
6632
  data = res.json()
frontend/src/app/admin/page.tsx CHANGED
@@ -49,6 +49,7 @@ const ADMIN_TABS = [
49
  { id: 'overview', label: 'Overview', icon: Activity },
50
  { id: 'users', label: 'Users', icon: Users },
51
  { id: 'fleet-compare', label: 'Fleet Compare', icon: ArrowLeftRight },
 
52
  { id: 'packages', label: 'Packages', icon: Database },
53
  { id: 'monetization', label: 'Monetization', icon: CreditCard },
54
  { id: 'templates', label: 'Templates', icon: FileText },
@@ -119,6 +120,20 @@ export default function AdminDashboard() {
119
  const [testingEmail, setTestingEmail] = useState(false);
120
  const [smtpStatusMsg, setSmtpStatusMsg] = useState('');
121
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
122
  // --- Pagination & Search States ---
123
  // 1. Manage Users (Strictly 15 per page as requested)
124
  const [usersPage, setUsersPage] = useState(1);
@@ -334,6 +349,8 @@ export default function AdminDashboard() {
334
  fetchGlobalTemplates();
335
  } else if (activeTab === 'search-logs') {
336
  fetchKeywordLogs();
 
 
337
  }
338
  }, [activeTab]);
339
 
@@ -418,6 +435,124 @@ export default function AdminDashboard() {
418
  }
419
  }, [activeTab, vpsAutoRefresh]);
420
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
421
  const updatePasskey = async () => {
422
  if (!passkey) return;
423
  const res = await apiFetch(`/api/admin/settings?key=global_passkey&value=${passkey}`, {
@@ -723,7 +858,7 @@ export default function AdminDashboard() {
723
  }
724
 
725
  return (
726
- <div className="w-full max-w-full overflow-hidden space-y-6 animate-in fade-in duration-500">
727
  {errorMsg && (
728
  <div className="fixed top-8 right-8 z-[100] bg-red-500/10 border border-red-500/20 text-red-500 px-6 py-4 rounded-2xl shadow-2xl flex items-center gap-3">
729
  <X className="shrink-0" size={20} />
@@ -738,24 +873,24 @@ export default function AdminDashboard() {
738
  </div>
739
  )}
740
 
741
- {/* Fixed Sticky Header & Two-Line Navigation */}
742
- <div className="sticky top-16 md:top-0 z-30 bg-[#090b0e]/95 backdrop-blur-2xl border-b border-white/10 pb-4 pt-2 -mx-4 px-4 md:-mx-8 md:px-8 space-y-3.5 shadow-2xl shadow-black/70">
743
  {/* Line 1: Platform Authority Title & System Telemetry Bar */}
744
- <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3">
745
  <div>
746
- <div className="inline-flex items-center gap-2 px-3 py-0.5 rounded-full bg-red-500/10 border border-red-500/20 mb-1.5 animate-in fade-in slide-in-from-left duration-700">
747
- <span className="w-2 h-2 rounded-full bg-red-500 animate-pulse" />
748
- <span className="text-[10px] font-bold text-red-500 uppercase tracking-[0.2em]">Security Control Center</span>
749
  </div>
750
- <h1 className="text-2xl md:text-3xl font-extrabold tracking-tight bg-gradient-to-r from-red-500 via-orange-400 to-indigo-500 bg-clip-text text-transparent">
751
  Platform <span className="text-foreground">Authority</span>
752
  </h1>
753
- <p className="text-foreground/50 text-xs mt-0.5 font-medium">Global management of multi-tenant infrastructure and secure gateways</p>
754
  </div>
755
 
756
  {/* Quick Telemetry & Sync Data Action */}
757
- <div className="flex items-center gap-2.5 self-stretch sm:self-center justify-between sm:justify-end shrink-0">
758
- <div className="flex items-center gap-2 px-2.5 sm:px-3 py-1.5 rounded-xl bg-white/[0.03] border border-white/5 text-xs text-foreground/60 font-medium">
759
  <span className="flex items-center gap-1.5 text-emerald-400">
760
  <span className="w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse" />
761
  <span>{users.length} Users</span>
@@ -778,20 +913,22 @@ export default function AdminDashboard() {
778
  if (activeTab === 'packages') fetchPlans();
779
  if (activeTab === 'templates') fetchGlobalTemplates();
780
  if (activeTab === 'search-logs') fetchKeywordLogs();
 
781
  }}
782
  disabled={loading}
783
- className="px-3.5 py-1.5 sm:py-2 rounded-xl bg-white/5 hover:bg-white/10 border border-white/10 text-xs font-semibold text-foreground/80 hover:text-foreground transition-all flex items-center gap-2 active:scale-95 cursor-pointer shadow-sm disabled:opacity-50"
784
  title="Re-synchronize Platform Matrix"
785
  >
786
  <RefreshCw size={13} className={loading ? "animate-spin text-red-400" : "text-foreground/60"} />
787
- <span>Sync Telemetry</span>
 
788
  </button>
789
  </div>
790
  </div>
791
 
792
- {/* Line 2: Navigation Tabs Bar (2-Line Wrap Layout so all tabs including Maintenance are visible) */}
793
- <div className="w-full py-1">
794
- <div className="flex flex-wrap items-center gap-1.5 bg-white/[0.03] p-1.5 rounded-2xl border border-white/5 w-full">
795
  {ADMIN_TABS.map((tab) => {
796
  const isActive = activeTab === tab.id;
797
  const Icon = tab.icon;
@@ -799,7 +936,7 @@ export default function AdminDashboard() {
799
  <button
800
  key={tab.id}
801
  onClick={() => setActiveTab(tab.id)}
802
- className={`flex items-center gap-2 px-3 py-1.5 md:px-3 md:py-1.5 rounded-xl text-xs font-bold transition-all duration-200 cursor-pointer ${
803
  isActive
804
  ? 'bg-red-500 text-white shadow-lg shadow-red-500/25 active:scale-95'
805
  : 'text-foreground/50 hover:text-foreground hover:bg-white/5'
@@ -821,6 +958,13 @@ export default function AdminDashboard() {
821
  Sync
822
  </span>
823
  )}
 
 
 
 
 
 
 
824
  </button>
825
  );
826
  })}
@@ -830,9 +974,9 @@ export default function AdminDashboard() {
830
 
831
  {/* TAB 1: OVERVIEW */}
832
  {activeTab === 'overview' && (
833
- <div className="space-y-8">
834
  {/* Global Stats Grid with SVG Sparklines and Dynamic Trend Pills */}
835
- <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
836
  {[
837
  {
838
  label: 'Total Users',
@@ -1929,11 +2073,279 @@ export default function AdminDashboard() {
1929
  </div>
1930
  )}
1931
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1932
  {/* TAB 4: PACKAGES */}
1933
  {activeTab === 'packages' && (
1934
- <div className="space-y-8">
1935
- <div className="bg-white/5 border border-white/10 rounded-3xl p-8">
1936
- <div className="flex items-center justify-between mb-8">
1937
  <div className="flex items-center gap-3">
1938
  <div className="p-3 bg-indigo-500/10 rounded-2xl text-indigo-400">
1939
  <Database size={24} />
@@ -3093,8 +3505,8 @@ export default function AdminDashboard() {
3093
 
3094
  {/* TAB 8: SETTINGS */}
3095
  {activeTab === 'settings' && (
3096
- <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
3097
- <div className="bg-white/5 border border-white/10 p-8 rounded-3xl space-y-6">
3098
  <div className="flex items-center gap-3">
3099
  <div className="p-3 rounded-2xl bg-indigo-500/10 text-indigo-400">
3100
  <Shield size={24} />
@@ -3346,9 +3758,9 @@ export default function AdminDashboard() {
3346
 
3347
  {/* TAB 9: MAINTENANCE (CREATIVELY REDESIGNED OPERATIONS & DIAGNOSTICS CENTER) */}
3348
  {activeTab === 'maintenance' && (
3349
- <div className="space-y-8 animate-in fade-in duration-300">
3350
  {/* 1. Infrastructure Diagnostics & Real-Time Telemetry Matrix */}
3351
- <div className="bg-white/5 border border-white/10 p-8 rounded-3xl shadow-2xl relative overflow-hidden">
3352
  <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-6">
3353
  <div className="flex items-center gap-3">
3354
  <div className="p-3 bg-indigo-500/10 rounded-2xl text-indigo-400">
 
49
  { id: 'overview', label: 'Overview', icon: Activity },
50
  { id: 'users', label: 'Users', icon: Users },
51
  { id: 'fleet-compare', label: 'Fleet Compare', icon: ArrowLeftRight },
52
+ { id: 'view-dms', label: 'View DMs', icon: MessageSquare },
53
  { id: 'packages', label: 'Packages', icon: Database },
54
  { id: 'monetization', label: 'Monetization', icon: CreditCard },
55
  { id: 'templates', label: 'Templates', icon: FileText },
 
120
  const [testingEmail, setTestingEmail] = useState(false);
121
  const [smtpStatusMsg, setSmtpStatusMsg] = useState('');
122
 
123
+ // --- Fleet DMs Inspection States ---
124
+ const [fleetAccounts, setFleetAccounts] = useState<any[]>([]);
125
+ const [loadingFleetAccounts, setLoadingFleetAccounts] = useState(false);
126
+ const [selectedAdminPhone, setSelectedAdminPhone] = useState<string>('');
127
+ const [adminDms, setAdminDms] = useState<any[]>([]);
128
+ const [loadingAdminDms, setLoadingAdminDms] = useState(false);
129
+ const [selectedAdminContact, setSelectedAdminContact] = useState<any | null>(null);
130
+ const [adminMessages, setAdminMessages] = useState<any[]>([]);
131
+ const [loadingAdminMessages, setLoadingAdminMessages] = useState(false);
132
+ const [adminDmSearch, setAdminDmSearch] = useState('');
133
+ const [adminMobileDmView, setAdminMobileDmView] = useState<'list' | 'chat'>('list');
134
+ const [adminReplyText, setAdminReplyText] = useState('');
135
+ const [sendingAdminReply, setSendingAdminReply] = useState(false);
136
+
137
  // --- Pagination & Search States ---
138
  // 1. Manage Users (Strictly 15 per page as requested)
139
  const [usersPage, setUsersPage] = useState(1);
 
349
  fetchGlobalTemplates();
350
  } else if (activeTab === 'search-logs') {
351
  fetchKeywordLogs();
352
+ } else if (activeTab === 'view-dms') {
353
+ fetchFleetAccounts();
354
  }
355
  }, [activeTab]);
356
 
 
435
  }
436
  }, [activeTab, vpsAutoRefresh]);
437
 
438
+ // --- Fleet DMs Inspection Handlers ---
439
+ const fetchFleetAccounts = async () => {
440
+ setLoadingFleetAccounts(true);
441
+ try {
442
+ const res = await apiFetch('/api/telegram/accounts');
443
+ if (res.ok) {
444
+ const data = await res.json();
445
+ const accs = data.accounts || [];
446
+ setFleetAccounts(accs);
447
+ if (accs.length > 0 && !selectedAdminPhone) {
448
+ const firstPhone = accs[0].phone_number;
449
+ setSelectedAdminPhone(firstPhone);
450
+ fetchAdminDms(firstPhone);
451
+ }
452
+ }
453
+ } catch (err) {
454
+ console.error("Failed to load fleet accounts for DMs", err);
455
+ } finally {
456
+ setLoadingFleetAccounts(false);
457
+ }
458
+ };
459
+
460
+ const fetchAdminDms = async (phone: string) => {
461
+ if (!phone) return;
462
+ setLoadingAdminDms(true);
463
+ setSelectedAdminContact(null);
464
+ setAdminMessages([]);
465
+ try {
466
+ const res = await apiFetch(`/api/telegram/accounts/${encodeURIComponent(phone)}/dms`);
467
+ if (res.ok) {
468
+ const data = await res.json();
469
+ const list = data.dms || [];
470
+ setAdminDms(list);
471
+ if (list.length > 0) {
472
+ setSelectedAdminContact(list[0]);
473
+ fetchAdminMessages(phone, list[0]);
474
+ }
475
+ } else {
476
+ const errData = await res.json().catch(() => ({}));
477
+ setErrorMsg(errData.detail || `Failed to fetch DMs for ${phone}`);
478
+ setTimeout(() => setErrorMsg(''), 5000);
479
+ }
480
+ } catch (err: any) {
481
+ setErrorMsg(err.message || `Failed to fetch DMs for ${phone}`);
482
+ setTimeout(() => setErrorMsg(''), 5000);
483
+ } finally {
484
+ setLoadingAdminDms(false);
485
+ }
486
+ };
487
+
488
+ const fetchAdminMessages = async (phone: string, contact: any) => {
489
+ if (!phone || !contact) return;
490
+ setLoadingAdminMessages(true);
491
+ try {
492
+ const hashParam = contact.access_hash ? `?access_hash=${encodeURIComponent(contact.access_hash)}` : '';
493
+ const res = await apiFetch(`/api/telegram/accounts/${encodeURIComponent(phone)}/dms/${contact.id}/messages${hashParam}`);
494
+ if (res.ok) {
495
+ const data = await res.json();
496
+ setAdminMessages(data.messages || []);
497
+ } else {
498
+ const errData = await res.json().catch(() => ({}));
499
+ setErrorMsg(errData.detail || `Failed to fetch messages for ${contact.name}`);
500
+ setTimeout(() => setErrorMsg(''), 5000);
501
+ }
502
+ } catch (err: any) {
503
+ setErrorMsg(err.message || `Failed to fetch messages for ${contact.name}`);
504
+ setTimeout(() => setErrorMsg(''), 5000);
505
+ } finally {
506
+ setLoadingAdminMessages(false);
507
+ }
508
+ };
509
+
510
+ const handleSendAdminReply = async () => {
511
+ if (!adminReplyText.trim() || !selectedAdminPhone || !selectedAdminContact) return;
512
+ setSendingAdminReply(true);
513
+ try {
514
+ const res = await apiFetch(`/api/telegram/accounts/${encodeURIComponent(selectedAdminPhone)}/dms/${selectedAdminContact.id}/send`, {
515
+ method: 'POST',
516
+ body: JSON.stringify({
517
+ message: adminReplyText.trim(),
518
+ access_hash: selectedAdminContact.access_hash || ''
519
+ })
520
+ });
521
+ if (res.ok) {
522
+ const newMsg = {
523
+ id: Date.now(),
524
+ text: adminReplyText.trim(),
525
+ is_out: true,
526
+ date: new Date().toISOString()
527
+ };
528
+ setAdminMessages(prev => [...prev, newMsg]);
529
+ setAdminReplyText('');
530
+ setSuccessMsg(`Reply sent as ${selectedAdminPhone}`);
531
+ setTimeout(() => setSuccessMsg(''), 4000);
532
+ } else {
533
+ const errData = await res.json().catch(() => ({}));
534
+ setErrorMsg(errData.detail || "Failed to transmit message via Telegram node");
535
+ setTimeout(() => setErrorMsg(''), 5000);
536
+ }
537
+ } catch (err: any) {
538
+ setErrorMsg(err.message || "Failed to send DM message");
539
+ setTimeout(() => setErrorMsg(''), 5000);
540
+ } finally {
541
+ setSendingAdminReply(false);
542
+ }
543
+ };
544
+
545
+ const filteredAdminDms = useMemo(() => {
546
+ if (!adminDmSearch.trim()) return adminDms;
547
+ const q = adminDmSearch.toLowerCase();
548
+ return adminDms.filter(d =>
549
+ d.name?.toLowerCase().includes(q) ||
550
+ d.username?.toLowerCase().includes(q) ||
551
+ d.last_message?.toLowerCase().includes(q) ||
552
+ d.phone?.toLowerCase().includes(q)
553
+ );
554
+ }, [adminDms, adminDmSearch]);
555
+
556
  const updatePasskey = async () => {
557
  if (!passkey) return;
558
  const res = await apiFetch(`/api/admin/settings?key=global_passkey&value=${passkey}`, {
 
858
  }
859
 
860
  return (
861
+ <div className="w-full max-w-full overflow-hidden space-y-3 md:space-y-6 animate-in fade-in duration-500">
862
  {errorMsg && (
863
  <div className="fixed top-8 right-8 z-[100] bg-red-500/10 border border-red-500/20 text-red-500 px-6 py-4 rounded-2xl shadow-2xl flex items-center gap-3">
864
  <X className="shrink-0" size={20} />
 
873
  </div>
874
  )}
875
 
876
+ {/* Fixed Sticky Header on Desktop & Compact Natural Flow on Mobile */}
877
+ <div className="relative md:sticky md:top-0 z-20 bg-[#090b0e]/95 backdrop-blur-2xl border-b border-white/10 pb-2.5 pt-1.5 md:pb-4 md:pt-2 -mx-4 px-4 md:-mx-8 md:px-8 space-y-2 md:space-y-3.5 shadow-xl md:shadow-2xl shadow-black/70">
878
  {/* Line 1: Platform Authority Title & System Telemetry Bar */}
879
+ <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-2.5 md:gap-3">
880
  <div>
881
+ <div className="inline-flex items-center gap-2 px-2.5 py-0.5 rounded-full bg-red-500/10 border border-red-500/20 mb-1 animate-in fade-in slide-in-from-left duration-700">
882
+ <span className="w-1.5 h-1.5 rounded-full bg-red-500 animate-pulse" />
883
+ <span className="text-[9px] md:text-[10px] font-bold text-red-500 uppercase tracking-[0.2em]">Security Control Center</span>
884
  </div>
885
+ <h1 className="text-xl md:text-3xl font-extrabold tracking-tight bg-gradient-to-r from-red-500 via-orange-400 to-indigo-500 bg-clip-text text-transparent">
886
  Platform <span className="text-foreground">Authority</span>
887
  </h1>
888
+ <p className="text-foreground/50 text-[11px] md:text-xs mt-0.5 font-medium line-clamp-1 sm:line-clamp-none">Global management of multi-tenant infrastructure and secure gateways</p>
889
  </div>
890
 
891
  {/* Quick Telemetry & Sync Data Action */}
892
+ <div className="flex items-center gap-2 self-stretch sm:self-center justify-between sm:justify-end shrink-0">
893
+ <div className="flex items-center gap-1.5 sm:gap-2 px-2.5 sm:px-3 py-1.5 rounded-xl bg-white/[0.03] border border-white/5 text-[11px] sm:text-xs text-foreground/60 font-medium">
894
  <span className="flex items-center gap-1.5 text-emerald-400">
895
  <span className="w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse" />
896
  <span>{users.length} Users</span>
 
913
  if (activeTab === 'packages') fetchPlans();
914
  if (activeTab === 'templates') fetchGlobalTemplates();
915
  if (activeTab === 'search-logs') fetchKeywordLogs();
916
+ if (activeTab === 'view-dms') fetchFleetAccounts();
917
  }}
918
  disabled={loading}
919
+ className="px-3 py-1.5 sm:py-2 rounded-xl bg-white/5 hover:bg-white/10 border border-white/10 text-xs font-semibold text-foreground/80 hover:text-foreground transition-all flex items-center gap-1.5 sm:gap-2 active:scale-95 cursor-pointer shadow-sm disabled:opacity-50"
920
  title="Re-synchronize Platform Matrix"
921
  >
922
  <RefreshCw size={13} className={loading ? "animate-spin text-red-400" : "text-foreground/60"} />
923
+ <span className="hidden xs:inline">Sync Telemetry</span>
924
+ <span className="xs:hidden">Sync</span>
925
  </button>
926
  </div>
927
  </div>
928
 
929
+ {/* Line 2: Navigation Tabs Bar (Single-Row Horizontal Swipe on Mobile, Multi-column on Desktop) */}
930
+ <div className="w-full py-0.5 md:py-1">
931
+ <div className="flex items-center gap-1 md:gap-1.5 bg-white/[0.03] p-1 md:p-1.5 rounded-xl md:rounded-2xl border border-white/5 w-full overflow-x-auto no-scrollbar scroll-smooth flex-nowrap md:flex-wrap">
932
  {ADMIN_TABS.map((tab) => {
933
  const isActive = activeTab === tab.id;
934
  const Icon = tab.icon;
 
936
  <button
937
  key={tab.id}
938
  onClick={() => setActiveTab(tab.id)}
939
+ className={`flex items-center gap-1.5 md:gap-2 px-2.5 py-1.5 md:px-3 md:py-1.5 rounded-lg md:rounded-xl text-xs font-bold transition-all duration-200 cursor-pointer shrink-0 whitespace-nowrap ${
940
  isActive
941
  ? 'bg-red-500 text-white shadow-lg shadow-red-500/25 active:scale-95'
942
  : 'text-foreground/50 hover:text-foreground hover:bg-white/5'
 
958
  Sync
959
  </span>
960
  )}
961
+ {tab.id === 'view-dms' && adminDms.length > 0 && (
962
+ <span className={`text-[9px] px-1.5 py-0.2 rounded-full font-bold ${
963
+ isActive ? 'bg-black/30 text-white' : 'bg-cyan-500/20 text-cyan-400'
964
+ }`}>
965
+ {adminDms.length}
966
+ </span>
967
+ )}
968
  </button>
969
  );
970
  })}
 
974
 
975
  {/* TAB 1: OVERVIEW */}
976
  {activeTab === 'overview' && (
977
+ <div className="space-y-4 md:space-y-8 mt-1 md:mt-2">
978
  {/* Global Stats Grid with SVG Sparklines and Dynamic Trend Pills */}
979
+ <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3 md:gap-6">
980
  {[
981
  {
982
  label: 'Total Users',
 
2073
  </div>
2074
  )}
2075
 
2076
+ {/* TAB: VIEW FLEET DMS */}
2077
+ {activeTab === 'view-dms' && (
2078
+ <div className="space-y-4 md:space-y-6 animate-in fade-in duration-300">
2079
+ {/* Top Account Picker & Telemetry Bar */}
2080
+ <div className="bg-white/5 border border-white/10 rounded-2xl md:rounded-3xl p-4 md:p-5 flex flex-col md:flex-row md:items-center justify-between gap-3 shadow-xl">
2081
+ <div className="flex items-center gap-3">
2082
+ <div className="w-10 h-10 rounded-2xl bg-cyan-500/10 border border-cyan-500/20 text-cyan-400 flex items-center justify-center shrink-0">
2083
+ <MessageSquare size={20} />
2084
+ </div>
2085
+ <div>
2086
+ <h2 className="text-sm md:text-base font-extrabold text-foreground flex items-center gap-2">
2087
+ <span>Fleet Telegram DMs</span>
2088
+ <span className="text-[10px] px-2 py-0.5 rounded-full bg-cyan-500/15 text-cyan-400 border border-cyan-500/30 font-bold uppercase tracking-wider">
2089
+ Admin Inspector
2090
+ </span>
2091
+ </h2>
2092
+ <p className="text-xs text-foreground/50 mt-0.5">
2093
+ Live session inspection and direct 1-on-1 message threads across all nodes
2094
+ </p>
2095
+ </div>
2096
+ </div>
2097
+
2098
+ {/* Account Selector Dropdown & Refresh */}
2099
+ <div className="flex items-center gap-2.5 w-full md:w-auto">
2100
+ <div className="relative flex-1 md:w-72">
2101
+ <select
2102
+ value={selectedAdminPhone}
2103
+ onChange={(e) => {
2104
+ setSelectedAdminPhone(e.target.value);
2105
+ fetchAdminDms(e.target.value);
2106
+ }}
2107
+ disabled={loadingFleetAccounts}
2108
+ className="w-full bg-white/5 border border-white/10 hover:border-cyan-500/40 rounded-xl px-3 py-2 text-xs font-bold text-foreground outline-none cursor-pointer truncate transition-colors disabled:opacity-50"
2109
+ >
2110
+ {fleetAccounts.length > 0 ? (
2111
+ fleetAccounts.map((acc) => (
2112
+ <option key={acc.phone_number} value={acc.phone_number} className="bg-card text-foreground">
2113
+ {acc.phone_number} • {acc.first_name || 'Account'} {acc.username ? `(@${acc.username})` : ''} [{acc.owner_name || 'System'}]
2114
+ </option>
2115
+ ))
2116
+ ) : (
2117
+ <option value="" className="bg-card text-foreground">No accounts found in fleet</option>
2118
+ )}
2119
+ </select>
2120
+ </div>
2121
+
2122
+ <button
2123
+ onClick={() => {
2124
+ if (selectedAdminPhone) {
2125
+ fetchAdminDms(selectedAdminPhone);
2126
+ } else {
2127
+ fetchFleetAccounts();
2128
+ }
2129
+ }}
2130
+ disabled={loadingAdminDms || loadingFleetAccounts}
2131
+ className="px-3 py-2 rounded-xl bg-cyan-500/10 hover:bg-cyan-500/20 text-cyan-400 border border-cyan-500/30 text-xs font-bold transition-all flex items-center gap-1.5 cursor-pointer disabled:opacity-50 shrink-0"
2132
+ title="Refresh conversations from account"
2133
+ >
2134
+ <RefreshCw size={13} className={loadingAdminDms ? 'animate-spin' : ''} />
2135
+ <span className="hidden sm:inline">Refresh</span>
2136
+ </button>
2137
+ </div>
2138
+ </div>
2139
+
2140
+ {/* Main Two-Panel Layout */}
2141
+ <div className="bg-card border border-border/80 rounded-2xl md:rounded-3xl shadow-2xl overflow-hidden h-[75vh] md:h-[calc(100vh-250px)] min-h-[500px] flex flex-col md:flex-row">
2142
+ {/* LEFT COLUMN: CONTACTS LIST */}
2143
+ <div className={`w-full md:w-80 lg:w-96 border-b md:border-b-0 md:border-r border-border/80 flex flex-col bg-card/60 shrink-0 h-full min-h-0 ${adminMobileDmView === 'chat' ? 'hidden md:flex' : 'flex'}`}>
2144
+ {/* Search box & Count */}
2145
+ <div className="p-3 border-b border-border/70 flex items-center justify-between gap-2 bg-card/80 shrink-0">
2146
+ <div className="relative flex-1">
2147
+ <Search size={13} className="absolute left-3 top-1/2 -translate-y-1/2 text-foreground/40 pointer-events-none" />
2148
+ <input
2149
+ type="text"
2150
+ placeholder="Search contacts & messages..."
2151
+ value={adminDmSearch}
2152
+ onChange={(e) => setAdminDmSearch(e.target.value)}
2153
+ className="w-full bg-background/80 border border-border/70 rounded-xl pl-8.5 pr-3 py-1.5 text-xs text-foreground placeholder:text-foreground/35 outline-none focus:border-cyan-500/40"
2154
+ />
2155
+ </div>
2156
+ <span className="px-2 py-1 rounded-lg bg-cyan-500/10 text-cyan-400 border border-cyan-500/20 text-[10px] font-mono font-bold shrink-0">
2157
+ {filteredAdminDms.length} DMs
2158
+ </span>
2159
+ </div>
2160
+
2161
+ {/* Contact list with independent scroll */}
2162
+ <div className="flex-1 min-h-0 overflow-y-auto divide-y divide-border/40 custom-scrollbar overscroll-contain">
2163
+ {loadingAdminDms && (
2164
+ <div className="py-16 text-center text-foreground/40 text-xs">
2165
+ <RefreshCw size={20} className="animate-spin mx-auto mb-2 text-cyan-400" />
2166
+ <span>Reading active Telegram dialogs...</span>
2167
+ </div>
2168
+ )}
2169
+
2170
+ {!loadingAdminDms && filteredAdminDms.length === 0 && (
2171
+ <div className="py-16 text-center text-foreground/40 text-xs px-4">
2172
+ <MessageSquare size={24} className="mx-auto mb-2 opacity-30" />
2173
+ <span>{adminDmSearch ? "No contacts matching search query." : "No personal 1-on-1 conversations on this account."}</span>
2174
+ </div>
2175
+ )}
2176
+
2177
+ {!loadingAdminDms && filteredAdminDms.map((contact) => {
2178
+ const isSelected = selectedAdminContact?.id === contact.id;
2179
+ const initials = contact.name ? contact.name.slice(0, 2).toUpperCase() : 'TG';
2180
+ return (
2181
+ <button
2182
+ key={contact.id}
2183
+ onClick={() => {
2184
+ setSelectedAdminContact(contact);
2185
+ fetchAdminMessages(selectedAdminPhone, contact);
2186
+ setAdminMobileDmView('chat');
2187
+ }}
2188
+ className={`w-full text-left p-3 md:p-3.5 transition-all flex items-start gap-3 cursor-pointer ${
2189
+ isSelected
2190
+ ? 'bg-cyan-500/10 border-l-4 border-cyan-400'
2191
+ : 'hover:bg-white/[0.03]'
2192
+ }`}
2193
+ >
2194
+ <div className="w-10 h-10 rounded-full bg-gradient-to-br from-blue-600 to-indigo-700 flex items-center justify-center text-white font-extrabold text-xs shadow-md shrink-0">
2195
+ {initials}
2196
+ </div>
2197
+ <div className="min-w-0 flex-1">
2198
+ <div className="flex items-center justify-between gap-1">
2199
+ <span className="text-xs font-bold text-foreground truncate">
2200
+ {contact.name}
2201
+ </span>
2202
+ <span className="text-[10px] text-foreground/40 font-mono shrink-0">
2203
+ {contact.date ? new Date(contact.date).toLocaleDateString([], { month: 'short', day: 'numeric' }) : ''}
2204
+ </span>
2205
+ </div>
2206
+ <div className="text-[10px] text-cyan-400/80 font-medium truncate mt-0.5">
2207
+ {contact.username ? `@${contact.username}` : (contact.phone || `ID: ${contact.id}`)}
2208
+ </div>
2209
+ <p className="text-[11px] text-foreground/60 truncate mt-1 leading-snug">
2210
+ {contact.last_message || 'No messages'}
2211
+ </p>
2212
+ </div>
2213
+ {contact.unread_count > 0 && (
2214
+ <span className="w-4 h-4 rounded-full bg-cyan-500 text-white text-[9px] font-black flex items-center justify-center shrink-0">
2215
+ {contact.unread_count}
2216
+ </span>
2217
+ )}
2218
+ </button>
2219
+ );
2220
+ })}
2221
+ </div>
2222
+ </div>
2223
+
2224
+ {/* RIGHT COLUMN: MESSAGE STREAM */}
2225
+ <div className={`flex-1 min-w-0 flex flex-col bg-background h-full min-h-0 overflow-hidden ${adminMobileDmView === 'list' ? 'hidden md:flex' : 'flex'}`}>
2226
+ {selectedAdminContact ? (
2227
+ <>
2228
+ {/* Header bar */}
2229
+ <div className="p-3 md:p-4 px-4 md:px-6 border-b border-border/80 bg-card/60 flex items-center justify-between gap-3 shrink-0">
2230
+ <div className="flex items-center gap-3 min-w-0">
2231
+ <button
2232
+ onClick={() => setAdminMobileDmView('list')}
2233
+ className="md:hidden p-1.5 -ml-1.5 rounded-xl text-foreground/60 hover:text-foreground hover:bg-white/5 transition-all cursor-pointer"
2234
+ title="Back to Contact List"
2235
+ >
2236
+ <ChevronLeft size={18} />
2237
+ </button>
2238
+ <div className="w-9 h-9 md:w-10 md:h-10 rounded-full bg-gradient-to-br from-blue-600 to-indigo-700 flex items-center justify-center text-white font-extrabold text-xs md:text-sm shadow-md shrink-0">
2239
+ {selectedAdminContact.name ? selectedAdminContact.name.slice(0, 2).toUpperCase() : 'TG'}
2240
+ </div>
2241
+ <div className="min-w-0">
2242
+ <h3 className="text-xs md:text-sm font-extrabold text-foreground truncate">
2243
+ {selectedAdminContact.name}
2244
+ </h3>
2245
+ <div className="text-[10px] md:text-[11px] text-foreground/50 flex items-center gap-2 mt-0.5">
2246
+ <span>{selectedAdminContact.username ? `@${selectedAdminContact.username}` : `ID: ${selectedAdminContact.id}`}</span>
2247
+ <span>•</span>
2248
+ <span className="text-emerald-400 font-semibold flex items-center gap-1">
2249
+ <span className="w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse" />
2250
+ Via {selectedAdminPhone}
2251
+ </span>
2252
+ </div>
2253
+ </div>
2254
+ </div>
2255
+
2256
+ <button
2257
+ onClick={() => fetchAdminMessages(selectedAdminPhone, selectedAdminContact)}
2258
+ disabled={loadingAdminMessages}
2259
+ className="px-2.5 py-1.5 rounded-xl bg-white/5 hover:bg-white/10 text-foreground/70 hover:text-foreground text-xs font-semibold flex items-center gap-1.5 transition-all cursor-pointer border border-white/10 shrink-0"
2260
+ title="Reload message thread"
2261
+ >
2262
+ <RefreshCw size={12} className={loadingAdminMessages ? 'animate-spin' : ''} />
2263
+ <span className="hidden sm:inline">Refresh Thread</span>
2264
+ </button>
2265
+ </div>
2266
+
2267
+ {/* Message Stream with independent scroll */}
2268
+ <div className="flex-1 min-h-0 p-4 md:p-6 overflow-y-auto space-y-3.5 custom-scrollbar overscroll-contain bg-radial from-background via-background to-card/20">
2269
+ {loadingAdminMessages && (
2270
+ <div className="py-16 text-center text-foreground/40 text-xs">
2271
+ <RefreshCw size={20} className="animate-spin mx-auto mb-2 text-cyan-400" />
2272
+ <span>Loading message history...</span>
2273
+ </div>
2274
+ )}
2275
+
2276
+ {!loadingAdminMessages && adminMessages.length === 0 && (
2277
+ <div className="py-16 text-center text-foreground/40 text-xs">
2278
+ <span>No messages exchanged yet in this thread.</span>
2279
+ </div>
2280
+ )}
2281
+
2282
+ {!loadingAdminMessages && adminMessages.map((msg) => (
2283
+ <div
2284
+ key={msg.id}
2285
+ className={`flex flex-col ${msg.is_out ? 'items-end' : 'items-start'}`}
2286
+ >
2287
+ <div className={`max-w-[85%] md:max-w-xl p-3 md:p-3.5 rounded-2xl shadow-sm text-xs md:text-sm leading-relaxed whitespace-pre-wrap ${
2288
+ msg.is_out
2289
+ ? 'bg-gradient-to-r from-blue-600 to-indigo-600 text-white rounded-tr-xs'
2290
+ : 'bg-card border border-border/80 text-foreground rounded-tl-xs shadow-md'
2291
+ }`}>
2292
+ {msg.text}
2293
+ </div>
2294
+ <span className="text-[9px] font-mono text-foreground/40 mt-1 px-1">
2295
+ {msg.date ? new Date(msg.date).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) : ''}
2296
+ {msg.is_out && ' • Outgoing'}
2297
+ </span>
2298
+ </div>
2299
+ ))}
2300
+ </div>
2301
+
2302
+ {/* Admin Quick Reply Bar */}
2303
+ <div className="p-3 md:p-4 border-t border-border/80 bg-card/70 flex items-center gap-2 shrink-0">
2304
+ <input
2305
+ type="text"
2306
+ placeholder={`Reply to ${selectedAdminContact.name} as ${selectedAdminPhone}...`}
2307
+ value={adminReplyText}
2308
+ onChange={(e) => setAdminReplyText(e.target.value)}
2309
+ onKeyDown={(e) => {
2310
+ if (e.key === 'Enter' && !e.shiftKey) {
2311
+ e.preventDefault();
2312
+ handleSendAdminReply();
2313
+ }
2314
+ }}
2315
+ disabled={sendingAdminReply}
2316
+ className="flex-1 bg-background/80 border border-border/80 rounded-xl px-3.5 py-2 text-xs md:text-sm text-foreground placeholder:text-foreground/35 outline-none focus:border-cyan-500/40"
2317
+ />
2318
+ <button
2319
+ onClick={handleSendAdminReply}
2320
+ disabled={sendingAdminReply || !adminReplyText.trim()}
2321
+ className="px-4 py-2 rounded-xl bg-gradient-to-r from-cyan-500 to-blue-600 hover:from-cyan-400 hover:to-blue-500 text-white text-xs font-bold transition-all flex items-center gap-1.5 cursor-pointer disabled:opacity-40 shrink-0 shadow-md shadow-cyan-500/20"
2322
+ >
2323
+ {sendingAdminReply ? <RefreshCw size={13} className="animate-spin" /> : <Send size={13} />}
2324
+ <span className="hidden sm:inline">Send</span>
2325
+ </button>
2326
+ </div>
2327
+ </>
2328
+ ) : (
2329
+ <div className="h-full flex flex-col items-center justify-center text-foreground/40 p-6 text-center">
2330
+ <div className="w-14 h-14 rounded-2xl bg-white/5 border border-white/10 flex items-center justify-center text-foreground/30 mb-3">
2331
+ <MessageSquare size={24} />
2332
+ </div>
2333
+ <h4 className="text-sm font-bold text-foreground/70">No Conversation Selected</h4>
2334
+ <p className="text-xs text-foreground/40 max-w-sm mt-1">
2335
+ Select any contact thread from the list on the left to inspect conversation history or send replies.
2336
+ </p>
2337
+ </div>
2338
+ )}
2339
+ </div>
2340
+ </div>
2341
+ </div>
2342
+ )}
2343
+
2344
  {/* TAB 4: PACKAGES */}
2345
  {activeTab === 'packages' && (
2346
+ <div className="space-y-4 md:space-y-8 animate-in fade-in duration-300">
2347
+ <div className="bg-white/5 border border-white/10 rounded-2xl md:rounded-3xl p-4 sm:p-6 md:p-8">
2348
+ <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-4 md:mb-8">
2349
  <div className="flex items-center gap-3">
2350
  <div className="p-3 bg-indigo-500/10 rounded-2xl text-indigo-400">
2351
  <Database size={24} />
 
3505
 
3506
  {/* TAB 8: SETTINGS */}
3507
  {activeTab === 'settings' && (
3508
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-4 md:gap-8 animate-in fade-in duration-300">
3509
+ <div className="bg-white/5 border border-white/10 p-4 sm:p-6 md:p-8 rounded-2xl md:rounded-3xl space-y-4 md:space-y-6">
3510
  <div className="flex items-center gap-3">
3511
  <div className="p-3 rounded-2xl bg-indigo-500/10 text-indigo-400">
3512
  <Shield size={24} />
 
3758
 
3759
  {/* TAB 9: MAINTENANCE (CREATIVELY REDESIGNED OPERATIONS & DIAGNOSTICS CENTER) */}
3760
  {activeTab === 'maintenance' && (
3761
+ <div className="space-y-4 md:space-y-8 animate-in fade-in duration-300">
3762
  {/* 1. Infrastructure Diagnostics & Real-Time Telemetry Matrix */}
3763
+ <div className="bg-white/5 border border-white/10 p-4 sm:p-6 md:p-8 rounded-2xl md:rounded-3xl shadow-2xl relative overflow-hidden">
3764
  <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-6">
3765
  <div className="flex items-center gap-3">
3766
  <div className="p-3 bg-indigo-500/10 rounded-2xl text-indigo-400">
frontend/src/app/ai-assistant/page.tsx CHANGED
@@ -483,7 +483,12 @@ export default function AiAssistantPage() {
483
  if (res.ok) {
484
  setDmAnalysis(data);
485
  } else {
486
- setDmAnalysisError(data.detail || 'Could not generate suggestions for this conversation.');
 
 
 
 
 
487
  }
488
  } catch (e: any) {
489
  setDmAnalysisError(e.message || 'Error communicating with AI service.');
@@ -527,11 +532,11 @@ export default function AiAssistantPage() {
527
  });
528
 
529
  return (
530
- <div className="h-[calc(100dvh-5.5rem)] md:h-full flex-1 min-h-0 overflow-hidden bg-background text-foreground flex font-sans rounded-2xl border border-border/80 shadow-xl">
531
  {/* ------------------------------------------------ */}
532
  {/* LEFT PANEL: ACCOUNT SELECTOR & INBOX DMS LIST */}
533
  {/* ------------------------------------------------ */}
534
- <div className={`${mobileView === 'chat' ? 'hidden lg:flex' : 'flex'} w-full lg:w-80 shrink-0 h-full flex-col border-r border-border/80 bg-card/40 overflow-hidden`}>
535
  {/* 1. Account Selector & AI Settings Control Bar */}
536
  <div className="p-3 border-b border-border/70 bg-card/60 flex items-center justify-between gap-2 shrink-0">
537
  {/* Account Selector Dropdown */}
@@ -611,7 +616,7 @@ export default function AiAssistantPage() {
611
  </div>
612
 
613
  {/* 4. Contacts / Leads List (Independent Scroll) */}
614
- <div className="flex-1 overflow-y-auto divide-y divide-border/40 custom-scrollbar">
615
  {fetchingDms && (
616
  <div className="p-8 text-center text-foreground/40 text-xs">
617
  <Loader2 size={18} className="animate-spin mx-auto mb-2 text-cyan-400" />
@@ -683,7 +688,7 @@ export default function AiAssistantPage() {
683
  {/* ------------------------------------------------ */}
684
  {/* RIGHT PANEL: CONVERSATION STREAM & AI SLIDE-UP */}
685
  {/* ------------------------------------------------ */}
686
- <div className={`${mobileView === 'list' ? 'hidden lg:flex' : 'flex'} flex-1 flex flex-col bg-background h-full overflow-hidden relative`}>
687
  {selectedContact ? (
688
  <>
689
  {/* TOP CONTACT HEADER BAR */}
@@ -794,7 +799,7 @@ export default function AiAssistantPage() {
794
  )}
795
 
796
  {/* CONVERSATION STREAM (INDEPENDENT SCROLL) */}
797
- <div className="flex-1 p-4 sm:p-5 overflow-y-auto space-y-4 custom-scrollbar bg-radial from-background via-background to-card/20">
798
  {fetchingMessages && (
799
  <div className="py-12 text-center text-foreground/40 text-xs">
800
  <Loader2 size={20} className="animate-spin mx-auto mb-2 text-cyan-400" />
 
483
  if (res.ok) {
484
  setDmAnalysis(data);
485
  } else {
486
+ const errDetail = data.detail || 'Could not generate suggestions for this conversation.';
487
+ if (res.status === 429 || errDetail.includes('FREE_MODEL_LIMIT') || errDetail.toLowerCase().includes('rate limit')) {
488
+ setDmAnalysisError(`⚠️ Free Model Rate Limit Reached: The model '${currentModel}' has hit OpenRouter's free tier rate limit. Click "Connect AI" in the left panel to switch to another free model (e.g. Gemini 2.0 Flash) or add credits.`);
489
+ } else {
490
+ setDmAnalysisError(errDetail);
491
+ }
492
  }
493
  } catch (e: any) {
494
  setDmAnalysisError(e.message || 'Error communicating with AI service.');
 
532
  });
533
 
534
  return (
535
+ <div className="h-full max-h-full w-full flex-1 min-h-0 overflow-hidden bg-background text-foreground flex font-sans rounded-2xl border border-border/80 shadow-xl">
536
  {/* ------------------------------------------------ */}
537
  {/* LEFT PANEL: ACCOUNT SELECTOR & INBOX DMS LIST */}
538
  {/* ------------------------------------------------ */}
539
+ <div className={`${mobileView === 'chat' ? 'hidden lg:flex' : 'flex'} w-full lg:w-80 shrink-0 h-full max-h-full min-h-0 flex-col border-r border-border/80 bg-card/40 overflow-hidden`}>
540
  {/* 1. Account Selector & AI Settings Control Bar */}
541
  <div className="p-3 border-b border-border/70 bg-card/60 flex items-center justify-between gap-2 shrink-0">
542
  {/* Account Selector Dropdown */}
 
616
  </div>
617
 
618
  {/* 4. Contacts / Leads List (Independent Scroll) */}
619
+ <div className="flex-1 min-h-0 overflow-y-auto divide-y divide-border/40 custom-scrollbar overscroll-contain">
620
  {fetchingDms && (
621
  <div className="p-8 text-center text-foreground/40 text-xs">
622
  <Loader2 size={18} className="animate-spin mx-auto mb-2 text-cyan-400" />
 
688
  {/* ------------------------------------------------ */}
689
  {/* RIGHT PANEL: CONVERSATION STREAM & AI SLIDE-UP */}
690
  {/* ------------------------------------------------ */}
691
+ <div className={`${mobileView === 'list' ? 'hidden lg:flex' : 'flex'} flex-1 min-w-0 flex flex-col bg-background h-full max-h-full min-h-0 overflow-hidden relative`}>
692
  {selectedContact ? (
693
  <>
694
  {/* TOP CONTACT HEADER BAR */}
 
799
  )}
800
 
801
  {/* CONVERSATION STREAM (INDEPENDENT SCROLL) */}
802
+ <div className="flex-1 min-h-0 p-4 sm:p-5 overflow-y-auto space-y-4 custom-scrollbar overscroll-contain bg-radial from-background via-background to-card/20">
803
  {fetchingMessages && (
804
  <div className="py-12 text-center text-foreground/40 text-xs">
805
  <Loader2 size={20} className="animate-spin mx-auto mb-2 text-cyan-400" />
frontend/src/app/compare/page.tsx CHANGED
@@ -179,9 +179,19 @@ export default function ComparePage({ isEmbedded = false }: { isEmbedded?: boole
179
  }
180
  };
181
 
 
 
182
  // Fetch accounts on mount
183
  useEffect(() => {
184
  fetchAccounts();
 
 
 
 
 
 
 
 
185
  }, []);
186
 
187
  const fetchAccounts = async () => {
@@ -1576,7 +1586,7 @@ export default function ComparePage({ isEmbedded = false }: { isEmbedded?: boole
1576
  </div>
1577
  );
1578
 
1579
- if (isEmbedded) {
1580
  return content;
1581
  }
1582
 
 
179
  }
180
  };
181
 
182
+ const [isAdmin, setIsAdmin] = useState(false);
183
+
184
  // Fetch accounts on mount
185
  useEffect(() => {
186
  fetchAccounts();
187
+ apiFetch('/api/auth/me')
188
+ .then(res => res.ok ? res.json() : null)
189
+ .then(u => {
190
+ if (u && (u.role === 'admin' || u.id === 'admin_virtual_id')) {
191
+ setIsAdmin(true);
192
+ }
193
+ })
194
+ .catch(() => {});
195
  }, []);
196
 
197
  const fetchAccounts = async () => {
 
1586
  </div>
1587
  );
1588
 
1589
+ if (isEmbedded || isAdmin) {
1590
  return content;
1591
  }
1592
 
frontend/src/app/scraper/page.tsx CHANGED
@@ -10,26 +10,57 @@ import { apiFetch, getApiBase } from '@/lib/auth';
10
  import { Preloader } from '@/components/Preloader';
11
  import { MonetizationOverlay } from '@/components/MonetizationOverlay';
12
 
13
- const DEFAULT_FALLBACK_MODELS = [
14
- { id: 'meta-llama/llama-3.3-70b-instruct', name: 'Meta: Llama 3.3 70B Instruct', context_length: 131072 },
15
- { id: 'anthropic/claude-3.5-sonnet', name: 'Anthropic: Claude 3.5 Sonnet', context_length: 200000 },
16
- { id: 'deepseek/deepseek-chat', name: 'DeepSeek: DeepSeek V3', context_length: 64000 },
17
- { id: 'deepseek/deepseek-r1', name: 'DeepSeek: DeepSeek R1', context_length: 64000 },
18
- { id: 'openai/gpt-4o-mini', name: 'OpenAI: GPT-4o Mini', context_length: 128000 },
19
- { id: 'openai/gpt-4o', name: 'OpenAI: GPT-4o', context_length: 128000 },
20
- { id: 'google/gemini-2.0-flash-exp:free', name: 'Google: Gemini 2.0 Flash Exp (free)', context_length: 1048576 },
21
- { id: 'google/gemini-flash-1.5', name: 'Google: Gemini Flash 1.5', context_length: 1000000 },
22
- { id: 'mistralai/mistral-nemo', name: 'Mistral: Mistral Nemo', context_length: 128000 },
23
- { id: 'qwen/qwen-2.5-72b-instruct', name: 'Qwen: Qwen 2.5 72B Instruct', context_length: 131072 }
 
 
 
 
 
 
 
 
 
 
 
 
 
24
  ];
25
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26
  const POPULAR_MODEL_PRESETS = [
27
  { id: 'meta-llama/llama-3.3-70b-instruct', label: 'Llama 3.3 70B' },
28
  { id: 'anthropic/claude-3.5-sonnet', label: 'Claude 3.5 Sonnet' },
29
  { id: 'deepseek/deepseek-chat', label: 'DeepSeek V3' },
30
  { id: 'deepseek/deepseek-r1', label: 'DeepSeek R1' },
31
  { id: 'openai/gpt-4o-mini', label: 'GPT-4o Mini' },
32
- { id: 'google/gemini-flash-1.5', label: 'Gemini Flash 1.5' }
33
  ];
34
 
35
  const getShortModelName = (id: string) => {
@@ -113,9 +144,11 @@ export default function ScraperPage() {
113
  const [aiValidationResult, setAiValidationResult] = useState<{ valid: boolean; message: string } | null>(null);
114
 
115
  // Available OpenRouter Models State
116
- const [availableModels, setAvailableModels] = useState<{ id: string; name: string; context_length?: number; description?: string }[]>([]);
117
  const [isLoadingModels, setIsLoadingModels] = useState(false);
118
  const [modelSearch, setModelSearch] = useState('');
 
 
119
 
120
  const [isSuggesting, setIsSuggesting] = useState(false);
121
  const [suggestions, setSuggestions] = useState<string[]>([]);
@@ -189,7 +222,8 @@ export default function ScraperPage() {
189
  id: m.id,
190
  name: m.name || m.id,
191
  context_length: m.context_length || 0,
192
- description: (m.description || '').slice(0, 140)
 
193
  }));
194
  }
195
  }
@@ -376,13 +410,20 @@ export default function ScraperPage() {
376
  setSuggestionsPlan(data.plan || 'free');
377
  setIsSuggestionsPanelOpen(true);
378
  setIsSuggestionsMinimized(false);
 
 
 
379
  const capNotice = data.max_allowed && data.max_allowed < 100
380
  ? ` (${(data.plan || 'Free').toUpperCase()} plan cap: ${data.max_allowed})`
381
  : '';
382
  setSuccessMsg(`Generated ${data.keywords.length} AI keywords${capNotice}!`);
383
  setTimeout(() => setSuccessMsg(''), 4500);
384
  } else {
385
- setError(data.detail || data.note || 'Failed to suggest keywords.');
 
 
 
 
386
  }
387
  } catch (e: any) {
388
  setError(e.message || 'Failed to generate keyword suggestions.');
@@ -2000,10 +2041,10 @@ export default function ScraperPage() {
2000
  </div>
2001
 
2002
  {/* Dynamic Model Catalogue (Search & Select from 400+ OpenRouter models) */}
2003
- <div className="space-y-2 pt-1">
2004
  <div className="flex items-center justify-between">
2005
  <label className="text-[11px] font-bold text-foreground/60 uppercase tracking-wider flex items-center gap-1.5">
2006
- <span>All Available Models</span>
2007
  {availableModels.length > 0 && (
2008
  <span className="text-[10px] px-1.5 py-0.2 rounded-full bg-indigo-500/15 text-indigo-400 font-mono font-bold">
2009
  {availableModels.length}
@@ -2022,6 +2063,57 @@ export default function ScraperPage() {
2022
  </button>
2023
  </div>
2024
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2025
  {/* Search Input */}
2026
  <div className="relative">
2027
  <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none text-foreground/40">
@@ -2037,7 +2129,7 @@ export default function ScraperPage() {
2037
  </div>
2038
 
2039
  {/* Scrollable Model List */}
2040
- <div className="border border-border/70 rounded-xl overflow-hidden max-h-48 overflow-y-auto custom-scrollbar divide-y divide-border/40 bg-foreground/[0.01]">
2041
  {isLoadingModels ? (
2042
  <div className="p-6 flex flex-col items-center justify-center text-foreground/40 gap-2">
2043
  <Loader2 size={16} className="animate-spin text-indigo-400" />
@@ -2056,15 +2148,25 @@ export default function ScraperPage() {
2056
  </div>
2057
  ) : (
2058
  availableModels
2059
- .filter(m =>
2060
- !modelSearch.trim() ||
2061
- m.name.toLowerCase().includes(modelSearch.toLowerCase()) ||
2062
- m.id.toLowerCase().includes(modelSearch.toLowerCase()) ||
2063
- (m.description && m.description.toLowerCase().includes(modelSearch.toLowerCase()))
2064
- )
 
 
 
 
 
 
2065
  .slice(0, 200)
2066
  .map((m) => {
2067
  const isSelected = aiModel === m.id;
 
 
 
 
2068
  return (
2069
  <button
2070
  key={m.id}
@@ -2080,9 +2182,27 @@ export default function ScraperPage() {
2080
  >
2081
  <div className="min-w-0 pr-2">
2082
  <div className="text-xs font-semibold truncate flex items-center gap-1.5">
2083
- {m.name || m.id}
 
 
 
 
 
 
 
 
 
2084
  </div>
2085
  <div className="text-[10px] text-foreground/40 font-mono truncate">{m.id}</div>
 
 
 
 
 
 
 
 
 
2086
  </div>
2087
  <div className="flex items-center gap-2 shrink-0">
2088
  {m.context_length ? (
 
10
  import { Preloader } from '@/components/Preloader';
11
  import { MonetizationOverlay } from '@/components/MonetizationOverlay';
12
 
13
+ interface OpenRouterModel {
14
+ id: string;
15
+ name: string;
16
+ context_length?: number;
17
+ description?: string;
18
+ pricing?: {
19
+ prompt?: string;
20
+ completion?: string;
21
+ request?: string;
22
+ image?: string;
23
+ };
24
+ }
25
+
26
+ const DEFAULT_FALLBACK_MODELS: OpenRouterModel[] = [
27
+ { id: 'meta-llama/llama-3.3-70b-instruct', name: 'Meta: Llama 3.3 70B Instruct', context_length: 131072, pricing: { prompt: '0.00000012', completion: '0.0000003' } },
28
+ { id: 'anthropic/claude-3.5-sonnet', name: 'Anthropic: Claude 3.5 Sonnet', context_length: 200000, pricing: { prompt: '0.000003', completion: '0.000015' } },
29
+ { id: 'deepseek/deepseek-chat', name: 'DeepSeek: DeepSeek V3', context_length: 64000, pricing: { prompt: '0.00000014', completion: '0.00000028' } },
30
+ { id: 'deepseek/deepseek-r1', name: 'DeepSeek: DeepSeek R1', context_length: 64000, pricing: { prompt: '0.00000055', completion: '0.00000219' } },
31
+ { id: 'openai/gpt-4o-mini', name: 'OpenAI: GPT-4o Mini', context_length: 128000, pricing: { prompt: '0.00000015', completion: '0.0000006' } },
32
+ { id: 'openai/gpt-4o', name: 'OpenAI: GPT-4o', context_length: 128000, pricing: { prompt: '0.0000025', completion: '0.00001' } },
33
+ { id: 'google/gemini-2.0-flash-exp:free', name: 'Google: Gemini 2.0 Flash Exp (free)', context_length: 1048576, pricing: { prompt: '0', completion: '0' } },
34
+ { id: 'google/gemini-flash-1.5', name: 'Google: Gemini Flash 1.5', context_length: 1000000, pricing: { prompt: '0.000000075', completion: '0.0000003' } },
35
+ { id: 'mistralai/mistral-nemo', name: 'Mistral: Mistral Nemo', context_length: 128000, pricing: { prompt: '0.00000013', completion: '0.00000013' } },
36
+ { id: 'qwen/qwen-2.5-72b-instruct', name: 'Qwen: Qwen 2.5 72B Instruct', context_length: 131072, pricing: { prompt: '0.00000035', completion: '0.0000004' } }
37
  ];
38
 
39
+ export const isModelFree = (m: { id: string; pricing?: { prompt?: string; completion?: string } }): boolean => {
40
+ if (!m) return false;
41
+ if (m.id.endsWith(':free')) return true;
42
+ const pPrompt = parseFloat(m.pricing?.prompt || '0');
43
+ const pComp = parseFloat(m.pricing?.completion || '0');
44
+ return pPrompt === 0 && pComp === 0;
45
+ };
46
+
47
+ export const formatTokenPrice = (valStr?: string): string => {
48
+ if (!valStr) return '$0.00';
49
+ const num = parseFloat(valStr);
50
+ if (isNaN(num) || num === 0) return '$0.00';
51
+ const perMillion = num * 1000000;
52
+ if (perMillion < 0.01) return `$${perMillion.toFixed(3)}`;
53
+ if (perMillion < 1) return `$${perMillion.toFixed(2)}`;
54
+ return `$${perMillion.toFixed(2)}`;
55
+ };
56
+
57
  const POPULAR_MODEL_PRESETS = [
58
  { id: 'meta-llama/llama-3.3-70b-instruct', label: 'Llama 3.3 70B' },
59
  { id: 'anthropic/claude-3.5-sonnet', label: 'Claude 3.5 Sonnet' },
60
  { id: 'deepseek/deepseek-chat', label: 'DeepSeek V3' },
61
  { id: 'deepseek/deepseek-r1', label: 'DeepSeek R1' },
62
  { id: 'openai/gpt-4o-mini', label: 'GPT-4o Mini' },
63
+ { id: 'google/gemini-2.0-flash-exp:free', label: 'Gemini 2.0 Free' }
64
  ];
65
 
66
  const getShortModelName = (id: string) => {
 
144
  const [aiValidationResult, setAiValidationResult] = useState<{ valid: boolean; message: string } | null>(null);
145
 
146
  // Available OpenRouter Models State
147
+ const [availableModels, setAvailableModels] = useState<OpenRouterModel[]>([]);
148
  const [isLoadingModels, setIsLoadingModels] = useState(false);
149
  const [modelSearch, setModelSearch] = useState('');
150
+ const [modelPricingFilter, setModelPricingFilter] = useState<'all' | 'free' | 'paid'>('all');
151
+ const [freeModelLimitAlert, setFreeModelLimitAlert] = useState<string>('');
152
 
153
  const [isSuggesting, setIsSuggesting] = useState(false);
154
  const [suggestions, setSuggestions] = useState<string[]>([]);
 
222
  id: m.id,
223
  name: m.name || m.id,
224
  context_length: m.context_length || 0,
225
+ description: (m.description || '').slice(0, 140),
226
+ pricing: m.pricing || null
227
  }));
228
  }
229
  }
 
410
  setSuggestionsPlan(data.plan || 'free');
411
  setIsSuggestionsPanelOpen(true);
412
  setIsSuggestionsMinimized(false);
413
+ if (data.is_free_limit || (data.error_note && data.error_note.includes('FREE_MODEL_LIMIT'))) {
414
+ setFreeModelLimitAlert(data.error_note || `The free model '${storedModel}' has reached OpenRouter's free tier rate limit. Fallback keyword intelligence was provided.`);
415
+ }
416
  const capNotice = data.max_allowed && data.max_allowed < 100
417
  ? ` (${(data.plan || 'Free').toUpperCase()} plan cap: ${data.max_allowed})`
418
  : '';
419
  setSuccessMsg(`Generated ${data.keywords.length} AI keywords${capNotice}!`);
420
  setTimeout(() => setSuccessMsg(''), 4500);
421
  } else {
422
+ const errMsg = data.detail || data.note || 'Failed to suggest keywords.';
423
+ if (errMsg.includes('FREE_MODEL_LIMIT') || errMsg.toLowerCase().includes('rate limit') || errMsg.toLowerCase().includes('free model')) {
424
+ setFreeModelLimitAlert(`⚠️ Free Model Rate Limit Reached: The selected model has reached OpenRouter's free tier rate limit or quota. Please switch to another free model or add credits.`);
425
+ }
426
+ setError(errMsg);
427
  }
428
  } catch (e: any) {
429
  setError(e.message || 'Failed to generate keyword suggestions.');
 
2041
  </div>
2042
 
2043
  {/* Dynamic Model Catalogue (Search & Select from 400+ OpenRouter models) */}
2044
+ <div className="space-y-2.5 pt-1">
2045
  <div className="flex items-center justify-between">
2046
  <label className="text-[11px] font-bold text-foreground/60 uppercase tracking-wider flex items-center gap-1.5">
2047
+ <span>All AI Models</span>
2048
  {availableModels.length > 0 && (
2049
  <span className="text-[10px] px-1.5 py-0.2 rounded-full bg-indigo-500/15 text-indigo-400 font-mono font-bold">
2050
  {availableModels.length}
 
2063
  </button>
2064
  </div>
2065
 
2066
+ {/* Free Model Limit Warning Banner */}
2067
+ {freeModelLimitAlert && (
2068
+ <div className="p-3 rounded-xl bg-amber-500/10 border border-amber-500/30 text-amber-300 text-xs flex items-start justify-between gap-2.5 animate-in fade-in duration-300">
2069
+ <div className="flex items-start gap-2">
2070
+ <AlertCircle size={15} className="text-amber-400 shrink-0 mt-0.5" />
2071
+ <div className="space-y-1">
2072
+ <div className="font-bold text-amber-200">Free Tier Limit Reached</div>
2073
+ <div className="text-[11px] text-amber-300/80 leading-snug">{freeModelLimitAlert}</div>
2074
+ </div>
2075
+ </div>
2076
+ <button
2077
+ type="button"
2078
+ onClick={() => setFreeModelLimitAlert('')}
2079
+ className="text-amber-400/60 hover:text-amber-300 cursor-pointer p-0.5"
2080
+ >
2081
+ <X size={13} />
2082
+ </button>
2083
+ </div>
2084
+ )}
2085
+
2086
+ {/* Pricing & Tier Filter Tabs */}
2087
+ <div className="flex items-center gap-1.5 p-1 rounded-xl bg-background/60 border border-border/60">
2088
+ {[
2089
+ { id: 'all', label: 'All Models' },
2090
+ { id: 'free', label: '100% Free' },
2091
+ { id: 'paid', label: 'Paid Models' }
2092
+ ].map(tab => (
2093
+ <button
2094
+ key={tab.id}
2095
+ type="button"
2096
+ onClick={() => setModelPricingFilter(tab.id as any)}
2097
+ className={`flex-1 py-1 px-2 rounded-lg text-[10px] font-bold transition-all cursor-pointer text-center ${
2098
+ modelPricingFilter === tab.id
2099
+ ? tab.id === 'free'
2100
+ ? 'bg-emerald-500/20 text-emerald-400 border border-emerald-500/30'
2101
+ : tab.id === 'paid'
2102
+ ? 'bg-amber-500/20 text-amber-400 border border-amber-500/30'
2103
+ : 'bg-card text-foreground shadow-xs border border-border/80'
2104
+ : 'text-foreground/50 hover:text-foreground hover:bg-foreground/5'
2105
+ }`}
2106
+ >
2107
+ {tab.label}
2108
+ {tab.id === 'free' && availableModels.length > 0 && (
2109
+ <span className="ml-1 opacity-70 font-mono">
2110
+ ({availableModels.filter(isModelFree).length})
2111
+ </span>
2112
+ )}
2113
+ </button>
2114
+ ))}
2115
+ </div>
2116
+
2117
  {/* Search Input */}
2118
  <div className="relative">
2119
  <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none text-foreground/40">
 
2129
  </div>
2130
 
2131
  {/* Scrollable Model List */}
2132
+ <div className="border border-border/70 rounded-xl overflow-hidden max-h-56 overflow-y-auto custom-scrollbar divide-y divide-border/40 bg-foreground/[0.01]">
2133
  {isLoadingModels ? (
2134
  <div className="p-6 flex flex-col items-center justify-center text-foreground/40 gap-2">
2135
  <Loader2 size={16} className="animate-spin text-indigo-400" />
 
2148
  </div>
2149
  ) : (
2150
  availableModels
2151
+ .filter(m => {
2152
+ const free = isModelFree(m);
2153
+ if (modelPricingFilter === 'free' && !free) return false;
2154
+ if (modelPricingFilter === 'paid' && free) return false;
2155
+ if (!modelSearch.trim()) return true;
2156
+ const q = modelSearch.toLowerCase();
2157
+ return (
2158
+ m.name.toLowerCase().includes(q) ||
2159
+ m.id.toLowerCase().includes(q) ||
2160
+ (m.description && m.description.toLowerCase().includes(q))
2161
+ );
2162
+ })
2163
  .slice(0, 200)
2164
  .map((m) => {
2165
  const isSelected = aiModel === m.id;
2166
+ const free = isModelFree(m);
2167
+ const promptPriceStr = formatTokenPrice(m.pricing?.prompt);
2168
+ const compPriceStr = formatTokenPrice(m.pricing?.completion);
2169
+
2170
  return (
2171
  <button
2172
  key={m.id}
 
2182
  >
2183
  <div className="min-w-0 pr-2">
2184
  <div className="text-xs font-semibold truncate flex items-center gap-1.5">
2185
+ <span>{m.name || m.id}</span>
2186
+ {free ? (
2187
+ <span className="px-1.5 py-0.2 rounded text-[9px] font-black uppercase tracking-wider bg-emerald-500/20 text-emerald-400 border border-emerald-500/30 shrink-0">
2188
+ FREE
2189
+ </span>
2190
+ ) : (
2191
+ <span className="px-1.5 py-0.2 rounded text-[9px] font-black uppercase tracking-wider bg-amber-500/20 text-amber-400 border border-amber-500/30 shrink-0">
2192
+ PAID
2193
+ </span>
2194
+ )}
2195
  </div>
2196
  <div className="text-[10px] text-foreground/40 font-mono truncate">{m.id}</div>
2197
+ <div className="mt-0.5 text-[10px] font-mono flex items-center gap-2">
2198
+ {free ? (
2199
+ <span className="text-emerald-400/90 font-bold">$0.00 In • $0.00 Out (Free Plan)</span>
2200
+ ) : (
2201
+ <span className="text-foreground/50">
2202
+ In: <strong className="text-foreground/75">{promptPriceStr}/1M</strong> • Out: <strong className="text-foreground/75">{compPriceStr}/1M</strong>
2203
+ </span>
2204
+ )}
2205
+ </div>
2206
  </div>
2207
  <div className="flex items-center gap-2 shrink-0">
2208
  {m.context_length ? (
frontend/src/components/Sidebar.tsx CHANGED
@@ -513,7 +513,7 @@ export function Sidebar({ children }: { children: React.ReactNode }) {
513
  onOpenSupport={() => setShowSupportModal(true)}
514
  onOpenEntitlements={() => setShowEntitlementsFlyout(true)}
515
  />
516
- <div className={pathname === '/ai-assistant' ? 'p-1.5 md:p-2.5 max-w-[105rem] mx-auto h-[calc(100dvh-55px)] md:h-[calc(100vh-55px)] flex flex-col flex-1 w-full min-w-0 overflow-x-hidden' : 'p-4 md:p-8 max-w-7xl mx-auto flex-1 w-full min-w-0'}>
517
  {children}
518
  </div>
519
  </main>
 
513
  onOpenSupport={() => setShowSupportModal(true)}
514
  onOpenEntitlements={() => setShowEntitlementsFlyout(true)}
515
  />
516
+ <div className={pathname === '/ai-assistant' ? 'p-1.5 md:p-2.5 max-w-[105rem] mx-auto h-[calc(100dvh-7.5rem)] md:h-[calc(100vh-4rem)] flex flex-col flex-1 w-full min-w-0 overflow-hidden' : 'p-4 md:p-8 max-w-7xl mx-auto flex-1 w-full min-w-0'}>
517
  {children}
518
  </div>
519
  </main>