CBV01 commited on
Commit
4d5557c
·
1 Parent(s): 60de0ac

fix(dms): fit conversation container to screen, natural mouse wheel scroll, rich attachments & word-wrap in bubbles

Browse files
backend/main.py CHANGED
@@ -6,7 +6,7 @@ load_dotenv() # Load .env file before anything else
6
 
7
  import shutil
8
  from fastapi import FastAPI, HTTPException, Depends, status, Request, UploadFile, File # type: ignore
9
- from fastapi.responses import JSONResponse, StreamingResponse # type: ignore
10
  from pydantic import BaseModel # type: ignore
11
  from fastapi.middleware.cors import CORSMiddleware # type: ignore
12
  from database import get_db_connection # type: ignore
@@ -379,14 +379,17 @@ _STATIC_DIR = os.path.join(_BASE_DIR, "static")
379
  _AVATARS_DIR = os.path.join(_STATIC_DIR, "avatars")
380
  _PREVIEWS_DIR = os.path.join(_STATIC_DIR, "previews")
381
  _UPLOADS_DIR = os.path.join(_STATIC_DIR, "uploads")
 
382
  os.makedirs(_AVATARS_DIR, exist_ok=True)
383
  os.makedirs(_PREVIEWS_DIR, exist_ok=True)
384
  os.makedirs(_UPLOADS_DIR, exist_ok=True)
 
385
  _ROOT_STATIC_DIR = os.path.abspath("static")
386
  if os.path.abspath(_STATIC_DIR) != _ROOT_STATIC_DIR:
387
  os.makedirs(os.path.join(_ROOT_STATIC_DIR, "avatars"), exist_ok=True)
388
  os.makedirs(os.path.join(_ROOT_STATIC_DIR, "previews"), exist_ok=True)
389
  os.makedirs(os.path.join(_ROOT_STATIC_DIR, "uploads"), exist_ok=True)
 
390
 
391
  app.mount("/static", StaticFiles(directory=_STATIC_DIR), name="static")
392
 
@@ -6340,11 +6343,62 @@ async def get_dm_messages(phone: str, contact_id: int, access_hash: Optional[str
6340
  messages_list = []
6341
  async for msg in client.iter_messages(entity, limit=50):
6342
  is_out = msg.out or (me_id is not None and msg.sender_id == me_id)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6343
  messages_list.append({
6344
  "id": msg.id,
6345
- "text": msg.text or ("(Media/Attachment)" if msg.media else ""),
6346
  "is_out": is_out,
6347
- "date": msg.date.isoformat() if msg.date else None
 
 
 
 
 
6348
  })
6349
  messages_list.reverse()
6350
  return {
@@ -6360,6 +6414,53 @@ async def get_dm_messages(phone: str, contact_id: int, access_hash: Optional[str
6360
  raise HTTPException(status_code=400, detail=f"Failed to load messages: {str(e)}")
6361
 
6362
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6363
  class DMSendRequest(BaseModel):
6364
  message: str
6365
  access_hash: Optional[str] = None
 
6
 
7
  import shutil
8
  from fastapi import FastAPI, HTTPException, Depends, status, Request, UploadFile, File # type: ignore
9
+ from fastapi.responses import JSONResponse, StreamingResponse, FileResponse # type: ignore
10
  from pydantic import BaseModel # type: ignore
11
  from fastapi.middleware.cors import CORSMiddleware # type: ignore
12
  from database import get_db_connection # type: ignore
 
379
  _AVATARS_DIR = os.path.join(_STATIC_DIR, "avatars")
380
  _PREVIEWS_DIR = os.path.join(_STATIC_DIR, "previews")
381
  _UPLOADS_DIR = os.path.join(_STATIC_DIR, "uploads")
382
+ _DM_MEDIA_DIR = os.path.join(_STATIC_DIR, "dm_media")
383
  os.makedirs(_AVATARS_DIR, exist_ok=True)
384
  os.makedirs(_PREVIEWS_DIR, exist_ok=True)
385
  os.makedirs(_UPLOADS_DIR, exist_ok=True)
386
+ os.makedirs(_DM_MEDIA_DIR, exist_ok=True)
387
  _ROOT_STATIC_DIR = os.path.abspath("static")
388
  if os.path.abspath(_STATIC_DIR) != _ROOT_STATIC_DIR:
389
  os.makedirs(os.path.join(_ROOT_STATIC_DIR, "avatars"), exist_ok=True)
390
  os.makedirs(os.path.join(_ROOT_STATIC_DIR, "previews"), exist_ok=True)
391
  os.makedirs(os.path.join(_ROOT_STATIC_DIR, "uploads"), exist_ok=True)
392
+ os.makedirs(os.path.join(_ROOT_STATIC_DIR, "dm_media"), exist_ok=True)
393
 
394
  app.mount("/static", StaticFiles(directory=_STATIC_DIR), name="static")
395
 
 
6343
  messages_list = []
6344
  async for msg in client.iter_messages(entity, limit=50):
6345
  is_out = msg.out or (me_id is not None and msg.sender_id == me_id)
6346
+ has_media = bool(msg.media)
6347
+ att_type = None
6348
+ att_name = None
6349
+ att_size = None
6350
+ att_url = None
6351
+
6352
+ if has_media:
6353
+ file_obj = getattr(msg, 'file', None)
6354
+ mime = getattr(file_obj, 'mime_type', '') or ''
6355
+ ext = getattr(file_obj, 'ext', '') or ''
6356
+ size_bytes = getattr(file_obj, 'size', None)
6357
+ if size_bytes and size_bytes > 0:
6358
+ if size_bytes < 1024:
6359
+ att_size = f"{size_bytes} B"
6360
+ elif size_bytes < 1024 * 1024:
6361
+ att_size = f"{size_bytes / 1024:.1f} KB"
6362
+ elif size_bytes < 1024 * 1024 * 1024:
6363
+ att_size = f"{size_bytes / (1024 * 1024):.1f} MB"
6364
+ else:
6365
+ att_size = f"{size_bytes / (1024 * 1024 * 1024):.2f} GB"
6366
+
6367
+ if getattr(msg, 'photo', None) or mime.startswith('image/'):
6368
+ att_type = 'image'
6369
+ att_name = getattr(file_obj, 'name', None) or f"Photo_{msg.id}{ext or '.jpg'}"
6370
+ elif getattr(msg, 'voice', None) or 'audio/ogg' in mime:
6371
+ att_type = 'voice'
6372
+ att_name = getattr(file_obj, 'name', None) or f"Voice_Note_{msg.id}{ext or '.ogg'}"
6373
+ elif getattr(msg, 'video', None) or mime.startswith('video/'):
6374
+ att_type = 'video'
6375
+ att_name = getattr(file_obj, 'name', None) or f"Video_{msg.id}{ext or '.mp4'}"
6376
+ elif getattr(msg, 'audio', None) or mime.startswith('audio/'):
6377
+ att_type = 'audio'
6378
+ att_name = getattr(file_obj, 'name', None) or f"Audio_{msg.id}{ext or '.mp3'}"
6379
+ elif getattr(msg, 'document', None):
6380
+ att_type = 'document'
6381
+ att_name = getattr(file_obj, 'name', None) or f"Document_{msg.id}{ext}"
6382
+ else:
6383
+ att_type = 'file'
6384
+ att_name = getattr(file_obj, 'name', None) or f"Attachment_{msg.id}{ext}"
6385
+
6386
+ att_url = f"/api/telegram/accounts/{phone}/dms/{contact_id}/messages/{msg.id}/media"
6387
+
6388
+ display_text = msg.text or ""
6389
+ if not display_text and has_media:
6390
+ display_text = f"[{att_type.capitalize() if att_type else 'Attachment'}: {att_name or 'Attached File'}]"
6391
+
6392
  messages_list.append({
6393
  "id": msg.id,
6394
+ "text": display_text,
6395
  "is_out": is_out,
6396
+ "date": msg.date.isoformat() if msg.date else None,
6397
+ "has_attachment": has_media,
6398
+ "attachment_type": att_type,
6399
+ "attachment_name": att_name,
6400
+ "attachment_size": att_size,
6401
+ "attachment_url": att_url
6402
  })
6403
  messages_list.reverse()
6404
  return {
 
6414
  raise HTTPException(status_code=400, detail=f"Failed to load messages: {str(e)}")
6415
 
6416
 
6417
+ @app.get("/api/telegram/accounts/{phone}/dms/{contact_id}/messages/{message_id}/media")
6418
+ async def get_dm_message_media(
6419
+ phone: str,
6420
+ contact_id: int,
6421
+ message_id: int,
6422
+ user_id: str = Depends(get_current_user_id)
6423
+ ):
6424
+ """Downloads or serves cached media for a specific Telegram direct message."""
6425
+ try:
6426
+ dm_media_dir = os.path.join(_STATIC_DIR, "dm_media")
6427
+ os.makedirs(dm_media_dir, exist_ok=True)
6428
+
6429
+ # Check if already cached on disk
6430
+ pattern = f"{phone}_{contact_id}_{message_id}_"
6431
+ for fname in os.listdir(dm_media_dir):
6432
+ if fname.startswith(pattern):
6433
+ fpath = os.path.join(dm_media_dir, fname)
6434
+ return FileResponse(fpath, filename=fname[len(pattern):])
6435
+
6436
+ client = await POOL.get_client(user_id, phone)
6437
+ try:
6438
+ entity = await client.get_input_entity(contact_id)
6439
+ except Exception:
6440
+ entity = await client.get_entity(contact_id)
6441
+
6442
+ msg = await client.get_messages(entity, ids=message_id)
6443
+ if not msg or not msg.media:
6444
+ raise HTTPException(status_code=404, detail="Message media not found")
6445
+
6446
+ file_obj = getattr(msg, 'file', None)
6447
+ orig_name = getattr(file_obj, 'name', None) or f"media_{message_id}{getattr(file_obj, 'ext', '')}"
6448
+ safe_name = "".join(c for c in orig_name if c.isalnum() or c in "._-") or f"media_{message_id}"
6449
+ save_path = os.path.join(dm_media_dir, f"{pattern}{safe_name}")
6450
+
6451
+ downloaded_path = await client.download_media(msg, file=save_path)
6452
+ if not downloaded_path or not os.path.exists(downloaded_path):
6453
+ raise HTTPException(status_code=500, detail="Failed to download media")
6454
+
6455
+ mime = getattr(file_obj, 'mime_type', None)
6456
+ return FileResponse(downloaded_path, media_type=mime, filename=safe_name)
6457
+ except HTTPException:
6458
+ raise
6459
+ except Exception as e:
6460
+ log_debug(f"DM_MEDIA_ERR: {str(e)}")
6461
+ raise HTTPException(status_code=500, detail=f"Media error: {str(e)}")
6462
+
6463
+
6464
  class DMSendRequest(BaseModel):
6465
  message: str
6466
  access_hash: Optional[str] = None
frontend/src/app/admin/page.tsx CHANGED
@@ -1,7 +1,7 @@
1
  'use client';
2
 
3
  import React, { useState, useEffect, useMemo } from 'react';
4
- import { apiFetch } from '@/lib/auth';
5
  import {
6
  Users,
7
  MessageSquare,
@@ -40,7 +40,12 @@ import {
40
  Filter,
41
  Check,
42
  Mail,
43
- Send
 
 
 
 
 
44
  } from 'lucide-react';
45
  import { Preloader } from '@/components/Preloader';
46
  import ComparePage from '@/app/compare/page';
@@ -2159,7 +2164,7 @@ export default function AdminDashboard() {
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" />
@@ -2265,7 +2270,7 @@ export default function AdminDashboard() {
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" />
@@ -2279,24 +2284,101 @@ export default function AdminDashboard() {
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 */}
 
1
  'use client';
2
 
3
  import React, { useState, useEffect, useMemo } from 'react';
4
+ import { apiFetch, getApiBase } from '@/lib/auth';
5
  import {
6
  Users,
7
  MessageSquare,
 
40
  Filter,
41
  Check,
42
  Mail,
43
+ Send,
44
+ File,
45
+ Download,
46
+ Music,
47
+ Video,
48
+ Paperclip
49
  } from 'lucide-react';
50
  import { Preloader } from '@/components/Preloader';
51
  import ComparePage from '@/app/compare/page';
 
2164
  </div>
2165
 
2166
  {/* Contact list with independent scroll */}
2167
+ <div className="flex-1 min-h-0 overflow-y-auto divide-y divide-border/40 custom-scrollbar">
2168
  {loadingAdminDms && (
2169
  <div className="py-16 text-center text-foreground/40 text-xs">
2170
  <RefreshCw size={20} className="animate-spin mx-auto mb-2 text-cyan-400" />
 
2270
  </div>
2271
 
2272
  {/* Message Stream with independent scroll */}
2273
+ <div className="flex-1 min-h-0 p-4 md:p-6 overflow-y-auto space-y-3.5 custom-scrollbar bg-radial from-background via-background to-card/20">
2274
  {loadingAdminMessages && (
2275
  <div className="py-16 text-center text-foreground/40 text-xs">
2276
  <RefreshCw size={20} className="animate-spin mx-auto mb-2 text-cyan-400" />
 
2284
  </div>
2285
  )}
2286
 
2287
+ {!loadingAdminMessages && adminMessages.map((msg) => {
2288
+ const hasAttachment = Boolean(msg.has_attachment || msg.attachment_url || msg.attachment_name);
2289
+ const isImage = msg.attachment_type === 'image' || (msg.attachment_name && /\.(jpg|jpeg|png|webp|gif)$/i.test(msg.attachment_name));
2290
+ const fullMediaUrl = msg.attachment_url ? `${getApiBase()}${msg.attachment_url}` : null;
2291
+
2292
+ return (
2293
+ <div
2294
+ key={msg.id}
2295
+ className={`flex flex-col ${msg.is_out ? 'items-end' : 'items-start'}`}
2296
+ >
2297
+ <div className={`max-w-[88%] md:max-w-xl p-3 md:p-3.5 rounded-2xl shadow-sm text-xs md:text-sm leading-relaxed whitespace-pre-wrap break-words [overflow-wrap:anywhere] space-y-2.5 ${
2298
+ msg.is_out
2299
+ ? 'bg-gradient-to-r from-blue-600 to-indigo-600 text-white rounded-tr-xs'
2300
+ : 'bg-card border border-border/80 text-foreground rounded-tl-xs shadow-md'
2301
+ }`}>
2302
+ {/* Attached File / Media Rendering */}
2303
+ {hasAttachment && (
2304
+ <div className="pb-1">
2305
+ {isImage && fullMediaUrl ? (
2306
+ <div className="space-y-1.5">
2307
+ <a
2308
+ href={fullMediaUrl}
2309
+ target="_blank"
2310
+ rel="noopener noreferrer"
2311
+ className="block group relative overflow-hidden rounded-xl border border-white/20 bg-black/20 max-w-sm"
2312
+ >
2313
+ <img
2314
+ src={fullMediaUrl}
2315
+ alt={msg.attachment_name || "Attachment"}
2316
+ className="max-h-56 w-auto max-w-full rounded-xl object-cover transition-transform group-hover:scale-[1.02]"
2317
+ loading="lazy"
2318
+ />
2319
+ <div className="absolute inset-0 bg-black/40 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center gap-1.5 text-white text-xs font-bold">
2320
+ <Download size={13} />
2321
+ <span>Open Full Size</span>
2322
+ </div>
2323
+ </a>
2324
+ {msg.attachment_name && (
2325
+ <div className="text-[10px] opacity-75 font-mono flex items-center gap-2">
2326
+ <span className="truncate max-w-[200px]">{msg.attachment_name}</span>
2327
+ {msg.attachment_size && <span>• {msg.attachment_size}</span>}
2328
+ </div>
2329
+ )}
2330
+ </div>
2331
+ ) : (
2332
+ <a
2333
+ href={fullMediaUrl || '#'}
2334
+ target={fullMediaUrl ? "_blank" : undefined}
2335
+ rel="noopener noreferrer"
2336
+ download={msg.attachment_name || undefined}
2337
+ className={`flex items-center gap-2.5 p-2.5 rounded-xl border transition-all group w-fit max-w-sm cursor-pointer ${
2338
+ msg.is_out
2339
+ ? 'bg-white/10 border-white/20 hover:bg-white/15 text-white'
2340
+ : 'bg-background/80 border-border/80 hover:border-cyan-500/50 hover:bg-foreground/[0.03] text-foreground'
2341
+ }`}
2342
+ >
2343
+ <div className={`w-8 h-8 rounded-lg flex items-center justify-center shrink-0 ${
2344
+ msg.is_out ? 'bg-white/20 text-white' : 'bg-cyan-500/15 text-cyan-400 border border-cyan-500/30'
2345
+ }`}>
2346
+ {msg.attachment_type === 'video' ? <Video size={15} /> :
2347
+ msg.attachment_type === 'audio' || msg.attachment_type === 'voice' ? <Music size={15} /> :
2348
+ <File size={15} />}
2349
+ </div>
2350
+ <div className="min-w-0 pr-1">
2351
+ <span className="text-xs font-bold block truncate max-w-[180px]">
2352
+ {msg.attachment_name || "Attachment"}
2353
+ </span>
2354
+ <span className="text-[10px] opacity-60 font-mono">
2355
+ {msg.attachment_size || (msg.attachment_type ? msg.attachment_type.toUpperCase() : "File")}
2356
+ </span>
2357
+ </div>
2358
+ {fullMediaUrl && (
2359
+ <div className="w-6 h-6 rounded-lg bg-black/10 flex items-center justify-center opacity-60 group-hover:opacity-100 shrink-0 ml-auto">
2360
+ <Download size={12} />
2361
+ </div>
2362
+ )}
2363
+ </a>
2364
+ )}
2365
+ </div>
2366
+ )}
2367
+
2368
+ {/* Text message content */}
2369
+ {msg.text && (!hasAttachment || !msg.text.startsWith('[')) && (
2370
+ <div className="break-words [overflow-wrap:anywhere]">
2371
+ {msg.text}
2372
+ </div>
2373
+ )}
2374
+ </div>
2375
+ <span className="text-[9px] font-mono text-foreground/40 mt-1 px-1">
2376
+ {msg.date ? new Date(msg.date).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) : ''}
2377
+ {msg.is_out && ' • Outgoing'}
2378
+ </span>
2379
  </div>
2380
+ );
2381
+ })}
 
 
 
 
2382
  </div>
2383
 
2384
  {/* Admin Quick Reply Bar */}
frontend/src/app/ai-assistant/page.tsx CHANGED
@@ -23,9 +23,13 @@ import {
23
  MessageSquare,
24
  Target,
25
  ChevronLeft,
26
- ChevronRight
 
 
 
 
27
  } from 'lucide-react';
28
- import { apiFetch } from '@/lib/auth';
29
 
30
  interface DmContact {
31
  id: number;
@@ -54,8 +58,11 @@ interface ChatMessage {
54
  is_out: boolean;
55
  date?: string | null;
56
  sender_name?: string;
 
57
  attachment_name?: string;
 
58
  attachment_size?: string;
 
59
  }
60
 
61
  interface DmAnalysisResult {
@@ -236,7 +243,7 @@ export default function AiAssistantPage() {
236
  const [scannedMsgIndex, setScannedMsgIndex] = useState<number>(-1);
237
  const [scanPhaseText, setScanPhaseText] = useState<string>('');
238
 
239
- const messagesEndRef = useRef<HTMLDivElement | null>(null);
240
 
241
  // Load initial settings and accounts
242
  useEffect(() => {
@@ -255,8 +262,8 @@ export default function AiAssistantPage() {
255
  }, []);
256
 
257
  useEffect(() => {
258
- if (messagesEndRef.current) {
259
- messagesEndRef.current.scrollIntoView({ behavior: 'smooth' });
260
  }
261
  }, [messages]);
262
 
@@ -409,7 +416,12 @@ export default function AiAssistantPage() {
409
  text: m.text,
410
  is_out: m.is_out,
411
  date: m.date ? new Date(m.date).toLocaleString([], { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' }) : undefined,
412
- sender_name: m.is_out ? "ArkiTel Agent" : contact.name
 
 
 
 
 
413
  }));
414
  setMessages(formatted);
415
  }
@@ -625,7 +637,7 @@ export default function AiAssistantPage() {
625
  </div>
626
 
627
  {/* 4. Contacts / Leads List (Fixed viewport height, scrolls within 10 items) */}
628
- <div className="flex-1 min-h-0 overflow-y-auto divide-y divide-border/40 custom-scrollbar overscroll-contain">
629
  {fetchingDms && (
630
  <div className="p-8 text-center text-foreground/40 text-xs">
631
  <Loader2 size={18} className="animate-spin mx-auto mb-2 text-cyan-400" />
@@ -722,7 +734,7 @@ export default function AiAssistantPage() {
722
  {/* ------------------------------------------------ */}
723
  <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`}>
724
  {selectedContact ? (
725
- <>
726
  {/* TOP CONTACT HEADER BAR */}
727
  <div className="p-3 px-4 sm:px-5 border-b border-border/80 bg-card/60 flex items-center justify-between flex-wrap gap-2.5 shrink-0">
728
  <div className="flex items-center gap-2.5">
@@ -831,7 +843,10 @@ export default function AiAssistantPage() {
831
  )}
832
 
833
  {/* CONVERSATION STREAM (INDEPENDENT SCROLL) */}
834
- <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">
 
 
 
835
  {fetchingMessages && (
836
  <div className="py-12 text-center text-foreground/40 text-xs">
837
  <Loader2 size={20} className="animate-spin mx-auto mb-2 text-cyan-400" />
@@ -849,6 +864,9 @@ export default function AiAssistantPage() {
849
  const isCurrentlyScanning = isAnalyzingDm && (scannedMsgIndex === idx || (scannedMsgIndex >= messages.length && idx === messages.length - 1));
850
  const isAlreadyScanned = isAnalyzingDm && scannedMsgIndex > idx;
851
  const isKeyLastMsg = idx === messages.length - 1;
 
 
 
852
 
853
  return (
854
  <div key={msg.id} className="space-y-1.5 transition-all duration-300">
@@ -896,23 +914,69 @@ export default function AiAssistantPage() {
896
  </span>
897
  </div>
898
 
899
- <div className="text-xs text-foreground/90 leading-relaxed font-sans whitespace-pre-wrap">
900
- {msg.text}
901
- </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
902
 
903
- {msg.attachment_name && (
904
- <div className="flex items-center gap-2.5 p-2.5 rounded-xl bg-background/80 border border-border/80 hover:border-cyan-500/40 transition-colors w-fit">
905
- <div className="w-7 h-7 rounded-lg bg-cyan-500/15 border border-cyan-500/30 text-cyan-400 flex items-center justify-center">
906
- <File size={14} />
907
- </div>
908
- <div>
909
- <span className="text-xs font-bold text-foreground block">
910
- {msg.attachment_name}
911
- </span>
912
- <span className="text-[10px] text-foreground/40 font-mono">
913
- {msg.attachment_size || "2.4 MB"}
914
- </span>
915
- </div>
916
  </div>
917
  )}
918
 
@@ -935,24 +999,86 @@ export default function AiAssistantPage() {
935
  <span className="text-[10px] text-foreground/40 font-mono">{msg.date || "Recent"}</span>
936
  </div>
937
 
938
- <div className={`rounded-2xl bg-card border shadow-sm p-3.5 text-xs text-foreground/90 leading-relaxed whitespace-pre-wrap transition-all duration-300 ${
939
  isCurrentlyScanning
940
  ? 'ring-2 ring-cyan-400 border-cyan-400 shadow-xl shadow-cyan-500/20 bg-cyan-500/[0.08] scale-[1.01]'
941
  : isAlreadyScanned
942
  ? 'border-emerald-500/30 bg-emerald-500/[0.02]'
943
  : 'border-border/80'
944
  }`}>
945
- {msg.text}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
946
  </div>
947
  </div>
948
  )}
949
  </div>
950
  );
951
  })}
952
- <div ref={messagesEndRef} />
953
  </div>
954
-
955
- </>
956
  ) : (
957
  <div className="flex-1 flex flex-col items-center justify-center text-center p-8 space-y-3 text-foreground/40">
958
  <MessageSquare size={36} className="opacity-40" />
 
23
  MessageSquare,
24
  Target,
25
  ChevronLeft,
26
+ ChevronRight,
27
+ Download,
28
+ Music,
29
+ Video,
30
+ Paperclip
31
  } from 'lucide-react';
32
+ import { apiFetch, getApiBase } from '@/lib/auth';
33
 
34
  interface DmContact {
35
  id: number;
 
58
  is_out: boolean;
59
  date?: string | null;
60
  sender_name?: string;
61
+ has_attachment?: boolean;
62
  attachment_name?: string;
63
+ attachment_type?: string;
64
  attachment_size?: string;
65
+ attachment_url?: string;
66
  }
67
 
68
  interface DmAnalysisResult {
 
243
  const [scannedMsgIndex, setScannedMsgIndex] = useState<number>(-1);
244
  const [scanPhaseText, setScanPhaseText] = useState<string>('');
245
 
246
+ const messagesContainerRef = useRef<HTMLDivElement | null>(null);
247
 
248
  // Load initial settings and accounts
249
  useEffect(() => {
 
262
  }, []);
263
 
264
  useEffect(() => {
265
+ if (messagesContainerRef.current) {
266
+ messagesContainerRef.current.scrollTop = messagesContainerRef.current.scrollHeight;
267
  }
268
  }, [messages]);
269
 
 
416
  text: m.text,
417
  is_out: m.is_out,
418
  date: m.date ? new Date(m.date).toLocaleString([], { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' }) : undefined,
419
+ sender_name: m.is_out ? "ArkiTel Agent" : contact.name,
420
+ has_attachment: m.has_attachment,
421
+ attachment_name: m.attachment_name,
422
+ attachment_type: m.attachment_type,
423
+ attachment_size: m.attachment_size,
424
+ attachment_url: m.attachment_url
425
  }));
426
  setMessages(formatted);
427
  }
 
637
  </div>
638
 
639
  {/* 4. Contacts / Leads List (Fixed viewport height, scrolls within 10 items) */}
640
+ <div className="flex-1 min-h-0 overflow-y-auto divide-y divide-border/40 custom-scrollbar">
641
  {fetchingDms && (
642
  <div className="p-8 text-center text-foreground/40 text-xs">
643
  <Loader2 size={18} className="animate-spin mx-auto mb-2 text-cyan-400" />
 
734
  {/* ------------------------------------------------ */}
735
  <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`}>
736
  {selectedContact ? (
737
+ <div className="flex-1 min-h-0 flex flex-col h-full overflow-hidden">
738
  {/* TOP CONTACT HEADER BAR */}
739
  <div className="p-3 px-4 sm:px-5 border-b border-border/80 bg-card/60 flex items-center justify-between flex-wrap gap-2.5 shrink-0">
740
  <div className="flex items-center gap-2.5">
 
843
  )}
844
 
845
  {/* CONVERSATION STREAM (INDEPENDENT SCROLL) */}
846
+ <div
847
+ ref={messagesContainerRef}
848
+ className="flex-1 min-h-0 p-4 sm:p-5 overflow-y-auto space-y-4 custom-scrollbar bg-radial from-background via-background to-card/20"
849
+ >
850
  {fetchingMessages && (
851
  <div className="py-12 text-center text-foreground/40 text-xs">
852
  <Loader2 size={20} className="animate-spin mx-auto mb-2 text-cyan-400" />
 
864
  const isCurrentlyScanning = isAnalyzingDm && (scannedMsgIndex === idx || (scannedMsgIndex >= messages.length && idx === messages.length - 1));
865
  const isAlreadyScanned = isAnalyzingDm && scannedMsgIndex > idx;
866
  const isKeyLastMsg = idx === messages.length - 1;
867
+ const hasAttachment = Boolean(msg.has_attachment || msg.attachment_url || msg.attachment_name);
868
+ const isImage = msg.attachment_type === 'image' || (msg.attachment_name && /\.(jpg|jpeg|png|webp|gif)$/i.test(msg.attachment_name));
869
+ const fullMediaUrl = msg.attachment_url ? `${getApiBase()}${msg.attachment_url}` : null;
870
 
871
  return (
872
  <div key={msg.id} className="space-y-1.5 transition-all duration-300">
 
914
  </span>
915
  </div>
916
 
917
+ {/* Attached File / Media Rendering */}
918
+ {hasAttachment && (
919
+ <div className="pb-1">
920
+ {isImage && fullMediaUrl ? (
921
+ <div className="space-y-1.5">
922
+ <a
923
+ href={fullMediaUrl}
924
+ target="_blank"
925
+ rel="noopener noreferrer"
926
+ className="block group relative overflow-hidden rounded-xl border border-border/80 bg-background/50 max-w-sm"
927
+ >
928
+ <img
929
+ src={fullMediaUrl}
930
+ alt={msg.attachment_name || "Attachment"}
931
+ className="max-h-56 w-auto max-w-full rounded-xl object-cover transition-transform group-hover:scale-[1.02]"
932
+ loading="lazy"
933
+ />
934
+ <div className="absolute inset-0 bg-black/40 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center gap-1.5 text-white text-xs font-bold">
935
+ <Download size={13} />
936
+ <span>Open Full Size</span>
937
+ </div>
938
+ </a>
939
+ {msg.attachment_name && (
940
+ <div className="text-[10px] text-foreground/50 font-mono flex items-center gap-2">
941
+ <span className="truncate max-w-[200px]">{msg.attachment_name}</span>
942
+ {msg.attachment_size && <span>• {msg.attachment_size}</span>}
943
+ </div>
944
+ )}
945
+ </div>
946
+ ) : (
947
+ <a
948
+ href={fullMediaUrl || '#'}
949
+ target={fullMediaUrl ? "_blank" : undefined}
950
+ rel="noopener noreferrer"
951
+ download={msg.attachment_name || undefined}
952
+ className="flex items-center gap-2.5 p-2.5 rounded-xl bg-background/80 border border-border/80 hover:border-cyan-500/50 hover:bg-foreground/[0.03] transition-all group w-fit max-w-sm cursor-pointer"
953
+ >
954
+ <div className="w-8 h-8 rounded-lg bg-cyan-500/15 border border-cyan-500/30 text-cyan-400 flex items-center justify-center shrink-0">
955
+ {msg.attachment_type === 'video' ? <Video size={15} /> :
956
+ msg.attachment_type === 'audio' || msg.attachment_type === 'voice' ? <Music size={15} /> :
957
+ <File size={15} />}
958
+ </div>
959
+ <div className="min-w-0 pr-1">
960
+ <span className="text-xs font-bold text-foreground block truncate max-w-[180px]">
961
+ {msg.attachment_name || "Attachment"}
962
+ </span>
963
+ <span className="text-[10px] text-foreground/40 font-mono">
964
+ {msg.attachment_size || (msg.attachment_type ? msg.attachment_type.toUpperCase() : "File")}
965
+ </span>
966
+ </div>
967
+ {fullMediaUrl && (
968
+ <div className="w-6 h-6 rounded-lg bg-foreground/5 flex items-center justify-center text-foreground/40 group-hover:text-cyan-400 shrink-0 ml-auto">
969
+ <Download size={12} />
970
+ </div>
971
+ )}
972
+ </a>
973
+ )}
974
+ </div>
975
+ )}
976
 
977
+ {msg.text && (!hasAttachment || !msg.text.startsWith('[')) && (
978
+ <div className="text-xs text-foreground/90 leading-relaxed font-sans whitespace-pre-wrap break-words [overflow-wrap:anywhere]">
979
+ {msg.text}
 
 
 
 
 
 
 
 
 
 
980
  </div>
981
  )}
982
 
 
999
  <span className="text-[10px] text-foreground/40 font-mono">{msg.date || "Recent"}</span>
1000
  </div>
1001
 
1002
+ <div className={`rounded-2xl bg-card border shadow-sm p-3.5 text-xs text-foreground/90 leading-relaxed whitespace-pre-wrap break-words [overflow-wrap:anywhere] transition-all duration-300 space-y-2.5 ${
1003
  isCurrentlyScanning
1004
  ? 'ring-2 ring-cyan-400 border-cyan-400 shadow-xl shadow-cyan-500/20 bg-cyan-500/[0.08] scale-[1.01]'
1005
  : isAlreadyScanned
1006
  ? 'border-emerald-500/30 bg-emerald-500/[0.02]'
1007
  : 'border-border/80'
1008
  }`}>
1009
+ {/* Attached File / Media Rendering for incoming */}
1010
+ {hasAttachment && (
1011
+ <div className="pb-1">
1012
+ {isImage && fullMediaUrl ? (
1013
+ <div className="space-y-1.5">
1014
+ <a
1015
+ href={fullMediaUrl}
1016
+ target="_blank"
1017
+ rel="noopener noreferrer"
1018
+ className="block group relative overflow-hidden rounded-xl border border-border/80 bg-background/50 max-w-sm"
1019
+ >
1020
+ <img
1021
+ src={fullMediaUrl}
1022
+ alt={msg.attachment_name || "Attachment"}
1023
+ className="max-h-56 w-auto max-w-full rounded-xl object-cover transition-transform group-hover:scale-[1.02]"
1024
+ loading="lazy"
1025
+ />
1026
+ <div className="absolute inset-0 bg-black/40 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center gap-1.5 text-white text-xs font-bold">
1027
+ <Download size={13} />
1028
+ <span>Open Full Size</span>
1029
+ </div>
1030
+ </a>
1031
+ {msg.attachment_name && (
1032
+ <div className="text-[10px] text-foreground/50 font-mono flex items-center gap-2">
1033
+ <span className="truncate max-w-[200px]">{msg.attachment_name}</span>
1034
+ {msg.attachment_size && <span>• {msg.attachment_size}</span>}
1035
+ </div>
1036
+ )}
1037
+ </div>
1038
+ ) : (
1039
+ <a
1040
+ href={fullMediaUrl || '#'}
1041
+ target={fullMediaUrl ? "_blank" : undefined}
1042
+ rel="noopener noreferrer"
1043
+ download={msg.attachment_name || undefined}
1044
+ className="flex items-center gap-2.5 p-2.5 rounded-xl bg-background/80 border border-border/80 hover:border-cyan-500/50 hover:bg-foreground/[0.03] transition-all group w-fit max-w-sm cursor-pointer"
1045
+ >
1046
+ <div className="w-8 h-8 rounded-lg bg-cyan-500/15 border border-cyan-500/30 text-cyan-400 flex items-center justify-center shrink-0">
1047
+ {msg.attachment_type === 'video' ? <Video size={15} /> :
1048
+ msg.attachment_type === 'audio' || msg.attachment_type === 'voice' ? <Music size={15} /> :
1049
+ <File size={15} />}
1050
+ </div>
1051
+ <div className="min-w-0 pr-1">
1052
+ <span className="text-xs font-bold text-foreground block truncate max-w-[180px]">
1053
+ {msg.attachment_name || "Attachment"}
1054
+ </span>
1055
+ <span className="text-[10px] text-foreground/40 font-mono">
1056
+ {msg.attachment_size || (msg.attachment_type ? msg.attachment_type.toUpperCase() : "File")}
1057
+ </span>
1058
+ </div>
1059
+ {fullMediaUrl && (
1060
+ <div className="w-6 h-6 rounded-lg bg-foreground/5 flex items-center justify-center text-foreground/40 group-hover:text-cyan-400 shrink-0 ml-auto">
1061
+ <Download size={12} />
1062
+ </div>
1063
+ )}
1064
+ </a>
1065
+ )}
1066
+ </div>
1067
+ )}
1068
+
1069
+ {msg.text && (!hasAttachment || !msg.text.startsWith('[')) && (
1070
+ <div className="leading-relaxed">
1071
+ {msg.text}
1072
+ </div>
1073
+ )}
1074
  </div>
1075
  </div>
1076
  )}
1077
  </div>
1078
  );
1079
  })}
 
1080
  </div>
1081
+ </div>
 
1082
  ) : (
1083
  <div className="flex-1 flex flex-col items-center justify-center text-center p-8 space-y-3 text-foreground/40">
1084
  <MessageSquare size={36} className="opacity-40" />
frontend/src/components/Sidebar.tsx CHANGED
@@ -504,16 +504,19 @@ export function Sidebar({ children }: { children: React.ReactNode }) {
504
 
505
  {/* Main Content Wrapper */}
506
  <main className={`
507
- flex-1 min-h-screen min-w-0 max-w-full overflow-x-hidden pt-16 md:pt-0 transition-all duration-300 flex flex-col
 
508
  ${isCollapsed ? "md:ml-20 md:max-w-[calc(100vw-5rem)]" : "md:ml-50 md:max-w-[calc(100vw-12.5rem)]"}
509
  `}>
510
- <Header
511
- user={user}
512
- status={status}
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>
 
504
 
505
  {/* Main Content Wrapper */}
506
  <main className={`
507
+ flex-1 min-w-0 max-w-full transition-all duration-300 flex flex-col
508
+ ${pathname === '/ai-assistant' ? 'h-screen max-h-screen overflow-hidden pt-16 md:pt-0' : 'min-h-screen overflow-x-hidden pt-16 md:pt-0'}
509
  ${isCollapsed ? "md:ml-20 md:max-w-[calc(100vw-5rem)]" : "md:ml-50 md:max-w-[calc(100vw-12.5rem)]"}
510
  `}>
511
+ <div className="shrink-0">
512
+ <Header
513
+ user={user}
514
+ status={status}
515
+ onOpenSupport={() => setShowSupportModal(true)}
516
+ onOpenEntitlements={() => setShowEntitlementsFlyout(true)}
517
+ />
518
+ </div>
519
+ <div className={pathname === '/ai-assistant' ? 'p-2 md:p-3 max-w-[110rem] mx-auto flex flex-col flex-1 min-h-0 w-full overflow-hidden' : 'p-4 md:p-8 max-w-7xl mx-auto flex-1 w-full min-w-0'}>
520
  {children}
521
  </div>
522
  </main>