Spaces:
Running

AHMDRTAP / src /components /ChatBot.tsx
Z User
security(cfskill-run3): deep audit fixes + SonarCloud quality pass
700d33c
Raw History Blame Contribute Delete
125 kB
import { Bot, Brain, ChevronDown, Copy, ImagePlus, KeyRound, Loader2, MonitorUp, MonitorX, RotateCcw, Send, Square, ThumbsDown, ThumbsUp, Trash2, User, X, } from "lucide-react"; import { forwardRef, memo, useCallback, useEffect, useImperativeHandle, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from "react"; import { useLocation, useNavigate } from "react-router"; import { toast } from "sonner"; import ByokSettingsPanel from "@/components/chatbot/ByokSettingsPanel"; import { useAuth } from "@/hooks/useAuth"; import { useChatFabAnimation } from "@/hooks/useChatFabAnimation"; import { useFabScrollVisibility } from "@/hooks/useFabScrollVisibility"; import { useTranslation } from "@/hooks/useTranslation"; import { resolveAfterAttempts, type StreamAttemptOutcome, shouldAttemptNext } from "@/lib/chat-stop-flow"; import { buildChatPageContext, pushTrail, type ScreenAuth } from "@/lib/screen-context"; import { captureScreenFrame, captureScreenPreview, getScreenShareState, screenShareSupported, startScreenShare, stopScreenShare, subscribeScreenShare, } from "@/lib/screen-share"; // ─── Types ─────────────────────────────────────────────────────────────────── interface Message { id: string; role: "user" | "assistant" | "error"; content: string; timestamp: Date; model?: string; isError?: boolean; /** 👍/👎 vote on this assistant reply — one-shot, sent to /api/chatbot/feedback. */ feedback?: "up" | "down"; /** Attached image — dataUrl lives in memory only; localStorage keeps the thumb. */ image?: MessageImage; } interface MessageImage { dataUrl?: string; thumb?: string; name?: string; /** "screen_capture" — the frame came from the live screen-share lane. */ source?: "screen_capture"; } // ─── localStorage persistence ─────────────────────────────────────────────── // ✅ SECURITY FIX (audit run-1, chatbot.localstorage-history): the storage key // is per-identity — a shared browser profile can no longer leak the previous // account's conversation to the next one. Legacy global-key entries are purged // on first write; useAuth.logout() additionally removes the active key. const MODE_STORAGE_KEY = "elbaz_chat_mode"; const LEGACY_CHAT_STORAGE_KEY = "elbaz_chat_history"; function chatStorageKey(userId: number | null | undefined): string { return `elbaz_chat_history:${userId != null ? String(userId) : "guest"}`; } const MAX_STORAGE_MESSAGES = 50; // Max time a FAB click waits for the auth check before treating the visitor // as logged out (dead-man switch — guarantees the FAB can never be a dead // button, even if the auth check hangs or loops). const AUTH_LOADING_DEADMAN_MS = 4000; type ChatMode = "thinking" | "instant"; // Single API origin — same pattern as the two chat fetch sites (native builds // must hit the absolute production URL, web builds use same-origin). const API_BASE = globalThis.Capacitor?.isNativePlatform() ? (import.meta.env.VITE_API_URL || "https://ahmedelbaz.qzz.io") : ""; function loadChatMode(): ChatMode { try { const stored = localStorage.getItem(MODE_STORAGE_KEY); if (stored === "instant" || stored === "thinking") return stored; } catch { // Intentionally ignored: localStorage unavailable — default to thinking. — SonarCloud S2486 } return "thinking"; } function saveChatMode(mode: ChatMode): void { try { localStorage.setItem(MODE_STORAGE_KEY, mode); } catch { // Intentionally ignored: localStorage unavailable — mode won't persist. — SonarCloud S2486 } } // Toast copy shown when the user flips the brain toggle (module-level to keep // the component body simple — SonarCloud S3358). function modeChangeToast(mode: ChatMode, lang: string): string { if (mode === "thinking") { return lang === "ar" ? "تم تفعيل وضع التفكير العميق — إجابات أدق للمسائل المعقدة" : "Thinking mode enabled — deeper analysis for complex problems"; } return lang === "ar" ? "تم التحويل إلى الوضع السريع — ردود فورية مختصرة" : "Instant mode enabled — fast, concise replies"; } // Tooltip for the header brain toggle (SonarCloud S3358). function brainToggleTitle(thinking: boolean, lang: string): string { if (thinking) { return lang === "ar" ? "وضع التفكير العميق مفعّل — اضغط للتبديل إلى الوضع السريع" : "Thinking mode ON — click to switch to Instant"; } return lang === "ar" ? "الوضع السريع — اضغط لتفعيل وضع التفكير العميق" : "Instant mode — click to enable Thinking"; } // Glow tone + tooltip for the header BYOK toggle (SonarCloud S3358 — module-level // helpers keep nested ternaries out of the component body). function byokToggleClass(active: boolean, panelOpen: boolean): string { if (active && !panelOpen) { return "text-cyan-300 drop-shadow-[0_0_7px_rgba(6,182,212,0.75)]"; } if (panelOpen) { return "text-cyan-300 bg-cyan-400/10"; } return "text-slate-500 hover:text-cyan-300"; } function byokToggleTitle(active: boolean, lang: string): string { if (active) { return lang === "ar" ? "النموذج الخاص بك مفعّل — اضغط للإعدادات" : "Your own model is active — click for settings"; } return lang === "ar" ? "استخدم نموذجك الخاص ومفتاح API" : "Use your own model and API key"; } // ✅ react-best-practices client-* (localStorage versioning): persisted arrays // previously had no schema marker — the next shape evolution could not be // detected. Write a { v, items } envelope; the reader stays tolerant of BOTH // the legacy bare array and the envelope, so nothing breaks on upgrade. const CHAT_STORAGE_VERSION = 1; function saveMessagesToStorage(msgs: Message[], key: string): void { try { const serializable = msgs.slice(-MAX_STORAGE_MESSAGES).map((m) => ({ id: m.id, role: m.role, content: m.content, timestamp: m.timestamp instanceof Date ? m.timestamp.toISOString() : m.timestamp, model: m.model || undefined, isError: m.isError || undefined, feedback: m.feedback || undefined, // NEVER persist the full dataUrl (localStorage budget) — the 160px // thumb is enough for history display after a reload. image: m.image ? { thumb: m.image.thumb, name: m.image.name, source: m.image.source } : undefined, })); try { localStorage.removeItem(LEGACY_CHAT_STORAGE_KEY); } catch { /* pre-fix entry */ } localStorage.setItem(key, JSON.stringify({ v: CHAT_STORAGE_VERSION, items: serializable })); } catch { // Intentionally ignored: localStorage may be full or unavailable — chat history is non-critical. — SonarCloud S2486 } } function loadMessagesFromStorage(key: string): Message[] | null { try { const raw = localStorage.getItem(key); if (!raw) return null; const parsed = JSON.parse(raw); // Accept both the versioned envelope and the legacy bare array. const legacyItems = Array.isArray(parsed) ? parsed : null; const envelopeItems = legacyItems === null && Array.isArray(parsed?.items) ? parsed.items : null; const items = legacyItems ?? envelopeItems; if (!items || items.length === 0) return null; return items.map((m: any) => ({ // eslint-disable-line @typescript-eslint/no-explicit-any id: m.id || crypto.randomUUID(), role: m.role || "assistant", content: m.content || "", timestamp: new Date(m.timestamp || Date.now()), model: m.model || undefined, isError: m.isError || undefined, feedback: m.feedback || undefined, image: m.image ? { thumb: m.image.thumb, name: m.image.name, source: m.image.source } : undefined, })); } catch { // Intentionally ignored: corrupt or unreadable storage — return null so caller re-initializes. — SonarCloud S2486 return null; } } // ─── Text direction + Markdown to HTML ────────────────────────────────────── // The renderer lives in src/lib/chat-render.ts (pure + unit-tested). SECURITY // INVARIANT (audit run-1): every text segment is HTML-escaped before any // markdown transformation — only renderer-synthesized tags survive. import { ARABIC_RE, detectUnfulfilledDiagramPromise, renderMarkdown } from "@/lib/chat-render"; // ─── Constants ─────────────────────────────────────────────────────────────── const WELCOME_MESSAGES: Record<string, Message> = { en: { id: "welcome", role: "assistant", content: "Welcome to Elbaz Bot — your electrical engineering AI assistant.\n\nI can help you with:\n• Power systems analysis (load flow, short circuit, arc flash)\n• ETAP, SKM Power*Tools & DIgSILENT PowerFactory\n• Relay coordination & protection systems\n• Network analysis & fault studies\n• IEEE / IEC standards\n\nAsk me any electrical engineering question.", timestamp: new Date(), }, ar: { id: "welcome", role: "assistant", content: "مرحباً بك في بوت الباز — مساعدك الذكي للهندسة الكهربية.\n\nأستطيع مساعدتك في:\n• تحليل أنظمة القوى (تدفق الأحمال، الدوائر القصيرة، القوس الكهربي)\n• برنامج ETAP و SKM Power*Tools و DIgSILENT PowerFactory\n• تنسيق الريليه وأنظمة الحماية\n• تحليل الشبكات ودراسات الأعطال\n• معايير IEEE و IEC\n\nاسألني أي سؤال في الهندسة الكهربية.", timestamp: new Date(), }, }; const MAX_HISTORY = typeof import.meta.env.VITE_CHATBOT_MAX_HISTORY === "string" ? Math.max(10, Math.min(200, Number(import.meta.env.VITE_CHATBOT_MAX_HISTORY) || 50)) : 50; // ─── Image attachment (vision) — browser-side compression ─────────────────── // The image is downscaled + re-encoded to JPEG in the browser so every upload // lands far below the server's 1MB payload guard: longest edge steps 1024px → // 768px → 640px until the base64 data URL fits a 300KB budget. A 160px thumb // is produced alongside for bubble display + localStorage persistence. interface AttachedImage { dataUrl: string; // compressed full image → sent to the API as image_url part thumb: string; // 160px preview → bubble display + localStorage name?: string; /** "screen_capture" — live frame from the screen-share lane (server flag). */ source?: "screen_capture"; } const IMAGE_MAX_DIM_STEPS: readonly number[] = [1024, 768, 640]; const IMAGE_QUALITY_STEPS: readonly number[] = [0.75, 0.6, 0.55]; const IMAGE_DATAURL_BUDGET = 300_000; // ~300KB base64 → safely under the 1MB shield const THUMB_DIM = 160; function loadImageElement(file: File): Promise<HTMLImageElement> { return new Promise((resolve, reject) => { const url = URL.createObjectURL(file); const img = new Image(); img.onload = () => { URL.revokeObjectURL(url); resolve(img); }; img.onerror = () => { URL.revokeObjectURL(url); reject(new Error("image-decode-failed")); }; img.src = url; }); } function drawToDataUrl(img: HTMLImageElement, maxDim: number, quality: number): string { const scale = Math.min(1, maxDim / Math.max(img.naturalWidth, img.naturalHeight)); const w = Math.max(1, Math.round(img.naturalWidth * scale)); const h = Math.max(1, Math.round(img.naturalHeight * scale)); const canvas = document.createElement("canvas"); canvas.width = w; canvas.height = h; const ctx = canvas.getContext("2d"); if (!ctx) throw new Error("canvas-unavailable"); // White background flattens transparency (diagrams stay readable in JPEG). ctx.fillStyle = "#ffffff"; ctx.fillRect(0, 0, w, h); ctx.drawImage(img, 0, 0, w, h); return canvas.toDataURL("image/jpeg", quality); } async function compressImageFile(file: File): Promise<AttachedImage> { if (!file.type.startsWith("image/")) throw new Error("not-an-image"); const img = await loadImageElement(file); let dataUrl = ""; for (let i = 0; i < IMAGE_MAX_DIM_STEPS.length; i++) { dataUrl = drawToDataUrl(img, IMAGE_MAX_DIM_STEPS[i], IMAGE_QUALITY_STEPS[i]); if (dataUrl.length <= IMAGE_DATAURL_BUDGET) break; } const thumb = drawToDataUrl(img, THUMB_DIM, 0.6); return { dataUrl, thumb, name: file.name }; } // ─── Live screen-share (vision) — the "teacher beside you" lane ──────────── // While sharing is active, EVERY message auto-carries a fresh frame of the // user's real screen (captured at send time), so the bot answers from the // actual program UI (menus, buttons, values) — never from guesses. A manual // file attachment still wins (explicit user intent). const SCREEN_READ_PROMPT_AR = "اقرأ الشاشة المرفقة بعناية: ما البرنامج والنافذة المفتوحة أمامي الآن، وما الخطوة التالية التي عليّ عملها بالضبط؟ اذكر أسماء القوائم والأزرار كما تظهر على الشاشة حرفياً، ووجهني خطوة بخطوة."; const SCREEN_READ_PROMPT_EN = "Read the attached screen carefully: which program and window do I have open right now, and what exact next step should I take? Use the menu and button names exactly as they appear on screen and guide me step by step."; /** * Live share bar — preview + status + one-tap "read my screen" action. * Isolated + memoized: its 2fps preview ticker re-renders ONLY this bar, * never the composer or the conversation. */ const ScreenShareBar = memo(function ScreenShareBar({ lang, active, starting, label, onToggle, onReadNow, readDisabled }: Readonly<{ lang: string; active: boolean; starting: boolean; label: string; onToggle: () => void; onReadNow: () => void; readDisabled: boolean; }>) { const [preview, setPreview] = useState<string | null>(null); useEffect(() => { if (!active) return undefined; // bar unmounts its body when idle — no stale reset needed const tick = () => setPreview(captureScreenPreview()); tick(); // first frame immediately (captureScreenPreview() returns null when not live — honest) const iv = setInterval(tick, 500); return () => clearInterval(iv); }, [active]); if (starting) { return ( <div className="mb-2 flex items-center gap-2 rounded-xl border border-[#1e2d3d] bg-[#111827] p-2"> <Loader2 className="h-4 w-4 animate-spin text-cyan-400" /> <span className="text-[12px] text-slate-400"> {lang === "ar" ? "جارٍ فتح نافذة مشاركة الشاشة..." : "Opening the screen-share picker..."} </span> </div> ); } if (!active) return null; return ( <div className="mb-2 flex items-center gap-2 rounded-xl border border-red-500/30 bg-red-500/5 p-2"> {preview ? ( <img src={preview} alt="" aria-hidden="true" draggable={false} className="h-12 w-20 flex-shrink-0 rounded-lg border border-white/10 object-cover" /> ) : ( <div className="flex h-12 w-20 flex-shrink-0 items-center justify-center rounded-lg border border-white/10 bg-black/40"> <MonitorUp className="h-4 w-4 text-slate-500" /> </div> )} <div className="min-w-0 flex-1"> <p className="flex items-center gap-1.5 text-[12px] font-medium text-red-300"> <span className="relative flex h-2 w-2"> <span className="absolute inline-flex h-full w-full animate-ping rounded-full bg-red-400 opacity-75" /> <span className="relative inline-flex h-2 w-2 rounded-full bg-red-500" /> </span> {lang === "ar" ? "مباشر من شاشتك" : "Live from your screen"} {label ? <span className="ms-1 truncate font-normal text-slate-400">— {label}</span> : null} </p> <p className="truncate text-[10px] text-slate-400"> {lang === "ar" ? "كل رسالة سترسل لقطة حية — البوت يقرأ برنامجك ويوجهك خطوة بخطوة" : "Every message sends a live frame — the bot reads your program and guides you step by step"} </p> </div> <button onClick={onReadNow} disabled={readDisabled} className="flex h-8 flex-shrink-0 items-center gap-1.5 rounded-lg border border-cyan-400/30 bg-cyan-400/10 px-2.5 text-[11.5px] font-semibold text-cyan-300 transition-colors hover:border-cyan-300/50 hover:bg-cyan-400/20 disabled:cursor-not-allowed disabled:opacity-40" title={lang === "ar" ? "اقرأ شاشتي الآن ووجهني" : "Read my screen now and guide me"} aria-label={lang === "ar" ? "اقرأ شاشتي الآن ووجهني" : "Read my screen now and guide me"} > <MonitorUp className="h-3.5 w-3.5" /> {lang === "ar" ? "اقرأ الآن" : "Read now"} </button> <button onClick={onToggle} className="flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-lg text-red-300 transition-colors hover:bg-red-400/10 hover:text-red-400" title={lang === "ar" ? "إيقاف مشاركة الشاشة" : "Stop screen sharing"} aria-label={lang === "ar" ? "إيقاف مشاركة الشاشة" : "Stop screen sharing"} > <MonitorX className="h-4 w-4" /> </button> </div> ); }); /** * Drain one SSE response into onPayload until the stream ends or the chat is * cleared. Lines without the `data: ` prefix (keepalive pings, comments) are * silently skipped — the typing indicator stays untouched. onBytes fires on * every successful read (liveness watchdog evidence, pings included). * Returns the leftover incomplete trailing line (caller processes it). */ async function readSseUntilDone( reader: ReadableStreamDefaultReader<Uint8Array>, opts: { isStale: () => boolean; onBytes: () => void; onPayload: (payload: string) => void }, ): Promise<string> { const decoder = new TextDecoder(); let buffer = ""; while (true) { if (opts.isStale()) return buffer; // chat was cleared mid-stream — stop consuming const result = await reader.read(); opts.onBytes(); // any bytes (pings included) prove liveness if (result.done) return buffer; buffer += decoder.decode(result.value, { stream: true }); const lines = buffer.split("\n"); buffer = lines.pop() || ""; // keep incomplete line in buffer for (const rawLine of lines) { const line = rawLine.trim(); // `: ping` keepalives and comments never start with "data: " — // silently ignored, the typing indicator stays untouched. if (!line.startsWith("data: ")) continue; opts.onPayload(line.slice(6).trim()); } } } // ─── Chat input area (ISOLATED component) ───────────────────────────────────── // Typing lag fix: the text value lives in THIS component's state, so every // keystroke re-renders only this small subtree — not the whole chat window // (bubbles + markdown re-parsing). This was the root cause of the delayed // text appearance while typing/deleting on mobile and desktop. interface ChatInputHandle { setTextAndFocus: (text: string) => void; focus: () => void; } interface ChatInputAreaProps { // Sonar S6767 FP: all six props are consumed inside the memo(forwardRef()) // component below — the analyzer loses prop tracking through the // forwardRef wrapper, hence the inline suppressions on each property. lang: string; // NOSONAR: destructured + used in the component body (toast, labels) isLoading: boolean; // NOSONAR: destructured + used in canSend/doSend/disabled kbOpen: boolean; // NOSONAR: destructured + used in the footer hint visibility isMobileViewport: boolean; // NOSONAR: destructured + used in the safe-area style onSend: (text: string, image: AttachedImage | null) => void; // NOSONAR: destructured + called in doSend onStop: () => void; // NOSONAR: destructured + forwarded to ComposerRow (stop button) } /** Attachment preview / compressing indicator row (extracted for clarity). */ function AttachmentArea({ attachment, compressing, lang, onRemove }: Readonly<{ attachment: AttachedImage | null; compressing: boolean; lang: string; onRemove: () => void; }>) { if (compressing) { return ( <div className="mb-2 flex items-center gap-2 rounded-xl border border-[#1e2d3d] bg-[#111827] p-2"> <div className="flex items-center gap-2 text-[12px] text-slate-400"> <Loader2 className="h-4 w-4 animate-spin text-cyan-400" /> <span>{lang === "ar" ? "جارٍ تجهيز الصورة..." : "Preparing image..."}</span> </div> </div> ); } if (!attachment) return null; // narrows the type for the preview below let displayName: string; if (attachment.source === "screen_capture") { displayName = lang === "ar" ? "لقطة مباشرة من شاشتك" : "Live screen capture"; } else { displayName = attachment.name || (lang === "ar" ? "صورة" : "Image"); } return ( <div className="mb-2 flex items-center gap-2 rounded-xl border border-[#1e2d3d] bg-[#111827] p-2"> <img src={attachment.thumb} alt={displayName} className="h-12 w-12 flex-shrink-0 rounded-lg border border-white/10 object-cover" draggable={false} /> <div className="min-w-0 flex-1"> <p className="truncate text-[12px] text-slate-300">{displayName}</p> <p className="text-[10px] text-cyan-400/70"> {lang === "ar" ? "سيتم تحليل الصورة بالذكاء الاصطناعي" : "The image will be analyzed by AI"} </p> </div> <button onClick={onRemove} className="flex h-7 w-7 flex-shrink-0 items-center justify-center rounded-lg text-slate-500 transition-colors hover:bg-red-400/10 hover:text-red-400" title={lang === "ar" ? "إزالة الصورة" : "Remove image"} aria-label={lang === "ar" ? "إزالة الصورة" : "Remove image"} > <X className="h-3.5 w-3.5" /> </button> </div> ); } // Localized strings / icon for the composer (SonarCloud S3358 — module-level // helpers keep nested ternaries out of the component body). function composerPlaceholder(screenActive: boolean, lang: string): string { if (screenActive) { return lang === "ar" ? "اسأل عن أي شيء يظهر على شاشتك..." : "Ask about anything on your screen..."; } return lang === "ar" ? "اسأل سؤالك الهندسي..." : "Ask your engineering question..."; } function screenShareToggleTitle(active: boolean, lang: string): string { if (active) { return lang === "ar" ? "إيقاف مشاركة الشاشة" : "Stop screen sharing"; } return lang === "ar" ? "مشاركة شاشتك — البوت يقرأ برنامجك ويوجهك" : "Share your screen — the bot reads your program and guides you"; } function screenShareToggleAriaLabel(active: boolean, lang: string): string { if (active) { return lang === "ar" ? "إيقاف مشاركة الشاشة" : "Stop screen sharing"; } return lang === "ar" ? "مشاركة شاشتك" : "Share your screen"; } function screenShareToggleIcon(screenStarting: boolean, screenActive: boolean): React.ReactNode { if (screenStarting) return <Loader2 className="h-4 w-4 animate-spin" />; if (screenActive) return <MonitorX className="h-4 w-4" />; return <MonitorUp className="h-4 w-4" />; } /** Localized failure toast for a failed screen-share start (SonarCloud S3358/S3776). */ function screenShareFailureToast(reason: string | undefined, lang: string): string { if (reason === "denied") { return lang === "ar" ? "تم رفض إذن مشاركة الشاشة — اسمح بالمشاركة من شريط المتصفح وحاول مجدداً" : "Screen share permission was denied — allow it from the browser bar and try again"; } if (reason === "unsupported") { return lang === "ar" ? "مشاركة الشاشة غير مدعومة في هذا المتصفح — استخدم كروم أو إيدج على الكمبيوتر" : "Screen sharing isn't supported in this browser — use Chrome or Edge on desktop"; } return lang === "ar" ? "تعذر بدء مشاركة الشاشة — حاول مجدداً" : "Couldn't start screen sharing — please try again"; } /** Attach + screen-share buttons, textarea, send button (extracted for clarity). */ function ComposerRow({ value, onValueChange, onKeyDown, taRef, fileInputRef, onPickFile, onFilePicked, canSend, isLoading, compressing, doSend, onStop, lang, screenSupported, screenActive, screenStarting, onToggleScreenShare }: Readonly<{ value: string; onValueChange: (v: string) => void; onKeyDown: (e: React.KeyboardEvent<HTMLTextAreaElement>) => void; taRef: React.RefObject<HTMLTextAreaElement | null>; fileInputRef: React.RefObject<HTMLInputElement | null>; onPickFile: () => void; onFilePicked: (e: React.ChangeEvent<HTMLInputElement>) => void; canSend: boolean; isLoading: boolean; compressing: boolean; doSend: () => void; onStop: () => void; lang: string; screenSupported: boolean; screenActive: boolean; screenStarting: boolean; onToggleScreenShare: () => void; }>) { const placeholder = composerPlaceholder(screenActive, lang); const shareIcon = screenShareToggleIcon(screenStarting, screenActive); return ( <div className="flex items-end gap-2"> {/* Attach image (vision) button */} <input ref={fileInputRef} type="file" accept="image/jpeg,image/png,image/webp,image/gif" className="hidden" onChange={onFilePicked} aria-hidden="true" tabIndex={-1} /> <button onClick={onPickFile} disabled={isLoading || compressing} className="flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-xl border border-[#1e2d3d] bg-[#111827] text-slate-400 transition-all hover:border-cyan-500/40 hover:text-cyan-300 active:scale-95 disabled:cursor-not-allowed disabled:opacity-40" title={lang === "ar" ? "إرفاق صورة للتحليل" : "Attach an image for analysis"} aria-label={lang === "ar" ? "إرفاق صورة للتحليل" : "Attach an image for analysis"} > {compressing ? <Loader2 className="h-4 w-4 animate-spin" /> : <ImagePlus className="h-4 w-4" />} </button> {/* Live screen share (vision) — desktop browsers with getDisplayMedia */} {screenSupported && ( <button onClick={onToggleScreenShare} disabled={isLoading || screenStarting} className={screenActive ? "flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-xl border border-red-500/40 bg-red-500/10 text-red-300 transition-all hover:border-red-400/60 hover:text-red-300 active:scale-95 disabled:cursor-not-allowed disabled:opacity-40" : "flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-xl border border-[#1e2d3d] bg-[#111827] text-slate-400 transition-all hover:border-cyan-500/40 hover:text-cyan-300 active:scale-95 disabled:cursor-not-allowed disabled:opacity-40"} title={screenShareToggleTitle(screenActive, lang)} aria-label={screenShareToggleAriaLabel(screenActive, lang)} > {shareIcon} </button> )} <div className="relative flex-1"> <textarea ref={taRef} value={value} onChange={(e) => { onValueChange(e.target.value); }} onKeyDown={onKeyDown} placeholder={placeholder} rows={1} // ✅ Type-ahead (professional parity): the textarea stays ENABLED // while the assistant is replying so the user can prepare their // next question instead of staring at a frozen input. Sending // mid-stream is already impossible — doSend/isLoading guards it, // and while loading this slot hosts the ⏹ stop button anyway. dir={ARABIC_RE.test(value) ? "rtl" : "ltr"} aria-label={lang === "ar" ? "اكتب رسالتك" : "Type your message"} className="w-full resize-none rounded-xl border border-[#1e2d3d] bg-[#111827] px-3.5 py-2.5 text-[13.5px] text-[#e8f0fe] transition-all placeholder:text-slate-500 focus:border-cyan-500/50 focus:outline-none focus:ring-1 focus:ring-cyan-500/20 disabled:opacity-50" style={{ minHeight: "40px", maxHeight: "120px" }} /> </div> {isLoading ? ( /* ⏹ STOP (owner request, 2026-11-14): the send button transforms the moment a message is sent. Pressing it aborts the in-flight request for real — the fetch dies, the server's stream cancel() propagates the disconnect into the provider walk (no quota keeps burning) — and whatever text already streamed in is frozen as the reply. */ <button onClick={onStop} className="flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-xl bg-gradient-to-br from-red-500 to-rose-600 text-white transition-all hover:shadow-lg hover:shadow-red-500/25 active:scale-95" title={lang === "ar" ? "إيقاف رد المساعد" : "Stop the assistant's response"} aria-label={lang === "ar" ? "إيقاف رد المساعد" : "Stop the assistant's response"} > <Square className="h-3.5 w-3.5 fill-current" /> </button> ) : ( <button onClick={doSend} disabled={!canSend} className="flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-xl bg-gradient-to-br from-cyan-700 to-blue-600 text-white transition-all hover:shadow-lg hover:shadow-cyan-500/25 active:scale-95 disabled:cursor-not-allowed disabled:opacity-40 disabled:hover:shadow-none" aria-label={lang === "ar" ? "إرسال" : "Send"} > <Send className="h-4 w-4" /> </button> )} </div> ); } const ChatInputArea = memo(forwardRef<ChatInputHandle, ChatInputAreaProps>(function ChatInputArea( { lang, isLoading, kbOpen, isMobileViewport, onSend, onStop }, ref, ) { const [value, setValue] = useState(""); const [attachment, setAttachment] = useState<AttachedImage | null>(null); const [compressing, setCompressing] = useState(false); const taRef = useRef<HTMLTextAreaElement>(null); const fileInputRef = useRef<HTMLInputElement>(null); // ─── Live screen-share state (external store — no re-render coupling) ─── const screenState = useSyncExternalStore(subscribeScreenShare, getScreenShareState); const [screenSupported] = useState(screenShareSupported); // feature detection never changes within a page const [screenStarting, setScreenStarting] = useState(false); const [capturing, setCapturing] = useState(false); // frame grab in flight (few ms) — blocks double-sends const screenActive = screenState.status === "active"; const autoresize = useCallback(() => { const el = taRef.current; if (!el) return; el.style.height = "auto"; el.style.height = `${Math.min(el.scrollHeight, 120)}px`; }, []); useImperativeHandle(ref, () => ({ setTextAndFocus: (text: string) => { setValue(text); requestAnimationFrame(() => { autoresize(); taRef.current?.focus(); }); }, focus: () => { taRef.current?.focus(); }, }), [autoresize]); const canSend = (value.trim().length > 0 || attachment !== null) && !isLoading && !compressing && !capturing; // ─── Toggle live screen sharing (browser picker → live frame lane) ─── const toggleScreenShare = useCallback(async () => { if (screenStarting) return; if (screenActive) { stopScreenShare(); toast(lang === "ar" ? "تم إيقاف مشاركة الشاشة" : "Screen sharing stopped", { duration: 1800 }); return; } setScreenStarting(true); const res = await startScreenShare(); setScreenStarting(false); if (res.ok) { toast( lang === "ar" ? "تم ربط شاشتك مباشرة — اسألني عن أي شيء يظهر عليها وسأوجهك خطوة بخطوة كأنني جالس بجانبك" : "Your screen is live — ask me about anything on it and I'll guide you step by step, like a teacher sitting beside you", { duration: 4000 }, ); return; } const msg = screenShareFailureToast(res.reason, lang); toast(msg, { duration: 3200 }); }, [screenStarting, screenActive, lang]); // ─── One-tap "read my screen now" — fresh frame + guidance prompt ─── const readScreenNow = useCallback(() => { if (isLoading || capturing) return; const frame = captureScreenFrame(); if (!frame) { toast( lang === "ar" ? "تعذر التقاط الشاشة — تأكد أن المشاركة ما زالت نشطة" : "Couldn't capture the screen — make sure sharing is still active", { duration: 2500 }, ); return; } onSend( lang === "ar" ? SCREEN_READ_PROMPT_AR : SCREEN_READ_PROMPT_EN, { dataUrl: frame.dataUrl, thumb: frame.thumb, name: "screen-capture.jpg", source: "screen_capture" }, ); }, [isLoading, capturing, lang, onSend]); const doSend = useCallback(() => { if (isLoading || compressing || capturing) return; if (!value.trim() && !attachment) return; // LIVE SCREEN: while sharing is active every send carries the CURRENT // frame (a manual file attachment still wins). Capture failure degrades // honestly — the message goes text-only with an explicit notice, the bot // is never told it saw a frame it did not receive. let finalAttachment: AttachedImage | null = attachment; if (!finalAttachment && screenActive) { setCapturing(true); const frame = captureScreenFrame(); setCapturing(false); if (frame) { finalAttachment = { dataUrl: frame.dataUrl, thumb: frame.thumb, name: "screen-capture.jpg", source: "screen_capture" }; } else { toast( lang === "ar" ? "تعذر التقاط الشاشة — سيتم إرسال رسالتك نصاً فقط" : "Screen capture failed — your message will be sent as text only", { duration: 2500 }, ); } } onSend(value, finalAttachment); setValue(""); setAttachment(null); requestAnimationFrame(autoresize); }, [value, attachment, isLoading, compressing, capturing, screenActive, lang, onSend, autoresize]); const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); doSend(); } }; const handleFilePicked = async (e: React.ChangeEvent<HTMLInputElement>) => { const file = e.target.files?.[0]; e.target.value = ""; // allow re-picking the same file later if (!file) return; setCompressing(true); try { const compressed = await compressImageFile(file); setAttachment(compressed); } catch { toast( lang === "ar" ? "تعذر تجهيز الصورة — جرب صورة أخرى" : "Couldn't process that image — try another one", { duration: 2500 }, ); } finally { setCompressing(false); } }; return ( <div className="flex-shrink-0 px-3 py-3 border-t border-[#1e2d3d] bg-[#0a1019]" style={isMobileViewport ? { paddingBottom: "max(env(safe-area-inset-bottom, 0px) + 0.5rem, 0.75rem)" } : undefined} > {/* Live screen-share bar (preview + status + "read now") — mounts only while starting/active, its 2fps ticker re-renders only itself */} <ScreenShareBar lang={lang} active={screenActive} starting={screenState.status === "starting"} label={screenState.label} onToggle={() => { void toggleScreenShare(); }} onReadNow={readScreenNow} readDisabled={isLoading || capturing} /> {/* Attachment preview / compressing indicator (extracted component) */} <AttachmentArea attachment={attachment} compressing={compressing} lang={lang} onRemove={() => setAttachment(null)} /> <ComposerRow value={value} onValueChange={(v) => { setValue(v); autoresize(); }} onKeyDown={handleKeyDown} taRef={taRef} fileInputRef={fileInputRef} onPickFile={() => fileInputRef.current?.click()} onFilePicked={handleFilePicked} canSend={canSend} isLoading={isLoading} compressing={compressing} doSend={() => { doSend(); }} onStop={onStop} lang={lang} screenSupported={screenSupported} screenActive={screenActive} screenStarting={screenStarting} onToggleScreenShare={() => { void toggleScreenShare(); }} /> <p className={`mt-2 text-center text-[10px] text-slate-600 ${kbOpen ? "hidden" : ""}`}> {lang === "ar" ? "بوت الباز الذكي — متخصص في الهندسة الكهربائية فقط" : "Elbaz AI Bot — Electrical Engineering Specialist Only"} </p> </div> ); })); // ─── Message bubble (memoized) ─────────────────────────────────────────────── // Extracted + memoized so streaming chunks / keystrokes never re-run the // markdown parser for old messages — only a NEW message re-renders its bubble. /** Attach one-shot error fallbacks to broken SLD diagram images inside a * rendered bubble (SonarCloud S3776 — the per-image scan lives here instead * of inside the component's effect). Returns the cleanup list. */ function attachDiagramFallbacks(span: HTMLElement, lang: string): Array<() => void> { const imgs = Array.from(span.querySelectorAll("img[src*='/api/diagrams/sld']")); const offs: Array<() => void> = []; const fail = (img: HTMLImageElement) => { const note = document.createElement("div"); note.className = "my-1.5 rounded-lg border border-amber-500/30 bg-amber-500/10 px-2.5 py-2 text-[12px] leading-5 text-amber-300"; note.textContent = lang === "ar" ? "تعذر تحميل الرسمة — أعد إرسال رسالتك وستُرسم من جديد." : "The diagram failed to load — resend your message and it will be redrawn."; img.replaceWith(note); }; for (const img of imgs) { if (!(img instanceof HTMLImageElement)) continue; if (img.complete && img.naturalWidth > 0) continue; // healthy diagram if (img.complete && img.naturalWidth === 0) { fail(img); continue; } // already failed const onError = () => fail(img); img.addEventListener("error", onError, { once: true }); offs.push(() => img.removeEventListener("error", onError)); } return offs; } /** Avatar chip for one message bubble (SonarCloud S3358/S3776 — extracted): * user messages wear the real profile photo when available, the bot wears * the site logo. */ function BubbleAvatar({ role, userAvatar }: Readonly<{ role: Message["role"]; userAvatar?: string | null; }>) { if (role !== "user") { return ( <img src="/logo-circle.png?v=2" alt="" aria-hidden="true" draggable={false} decoding="async" className="mt-0.5 h-7 w-7 flex-shrink-0 rounded-full object-cover border border-cyan-500/30" /> ); } return userAvatar ? ( <img src={userAvatar} alt="" aria-hidden="true" draggable={false} decoding="async" className="mt-0.5 h-7 w-7 flex-shrink-0 rounded-full object-cover border border-blue-500/40" /> ) : ( <div className="mt-0.5 flex h-7 w-7 flex-shrink-0 items-center justify-center rounded-lg bg-blue-600/20 border border-blue-500/30"> <User className="h-3.5 w-3.5 text-blue-400" /> </div> ); } /** 👍/👎 feedback buttons for assistant replies (SonarCloud S3776 — extracted). * One-shot vote per message; rendered only for real assistant replies. */ function FeedbackControls({ msg, lang, onFeedback }: Readonly<{ msg: Message; lang: string; onFeedback: (msgId: string, rating: "up" | "down") => void; }>) { if (msg.role !== "assistant" || msg.isError || msg.id === "welcome") return null; return ( <fieldset className="mt-1.5 ms-1 flex items-center gap-1.5 border-0 p-0 m-0 min-w-0" aria-label={lang === "ar" ? "تقييم الرد" : "Rate reply"}> <button onClick={() => onFeedback(msg.id, "up")} disabled={msg.feedback !== undefined} aria-pressed={msg.feedback === "up"} className={msg.feedback === "up" ? "rounded-md p-1 text-emerald-400 bg-emerald-400/10" : "rounded-md p-1 text-slate-500 transition-colors hover:text-emerald-400 hover:bg-white/5 disabled:hover:bg-transparent"} title={lang === "ar" ? "رد مفيد" : "Helpful reply"} > <ThumbsUp className="h-3 w-3" /> </button> <button onClick={() => onFeedback(msg.id, "down")} disabled={msg.feedback !== undefined} aria-pressed={msg.feedback === "down"} className={msg.feedback === "down" ? "rounded-md p-1 text-red-400 bg-red-400/10" : "rounded-md p-1 text-slate-500 transition-colors hover:text-red-400 hover:bg-white/5 disabled:hover:bg-transparent"} title={lang === "ar" ? "الرد مش دقيق" : "Not an accurate reply"} > <ThumbsDown className="h-3 w-3" /> </button> {msg.feedback && ( <span className="text-[10px] text-slate-500">{lang === "ar" ? "شكراً لتقييمك" : "Thanks for the feedback"}</span> )} </fieldset> ); } interface MessageBubbleProps { msg: Message; lang: string; copied: boolean; onCopy: (msgId: string, content: string) => void; onRetry: (msgId: string) => void; onFeedback: (msgId: string, rating: "up" | "down") => void; /** 📐 draw-now chip: this assistant reply promised a diagram but carried none. */ showDrawNow: boolean; onDrawNow: (msgId: string) => void; /** Owner request (2026-11-26): user bubbles wear the real profile photo * (users.avatar via auth.me) instead of the generic icon chip. The icon * chip stays as the fallback for users without a photo. */ userAvatar?: string | null; } const MessageBubble = memo(function MessageBubble({ msg, lang, copied, onCopy, onRetry, onFeedback, showDrawNow, onDrawNow, userAvatar }: MessageBubbleProps) { const sldBodyRef = useRef<HTMLSpanElement | null>(null); const errorBubbleClass = msg.isError ? "bg-red-500/10 border border-red-500/30 text-red-300 rounded-ss-md" : "bg-[#111827] border border-[#1e2d3d] text-[#e8f0fe] rounded-ss-md"; const bubbleClass = msg.role === "user" ? "bg-gradient-to-br from-cyan-600 to-blue-600 text-white rounded-ee-md" : errorBubbleClass; const imageSrc = msg.image?.dataUrl || msg.image?.thumb; // ── SLD img load-failure fallback (defence-in-depth) ── // The server repairs specs before rendering, so a diagram almost always // loads; this catches the residual cases (network hiccup, edge cache) and // swaps the broken-image icon for an explicit, localized note. The node is // built with createElement + textContent ONLY — no model content passes // through (same invariant as the renderer above). // biome-ignore lint/correctness/useExhaustiveDependencies: msg.content is deliberately listed — streamed appends inject NEW <img> nodes into the DOM and the error listeners must re-attach for each render change useEffect(() => { const span = sldBodyRef.current; if (!span || msg.role !== "assistant" || msg.isError) return undefined; const offs = attachDiagramFallbacks(span, lang); return () => offs.forEach((off) => { off(); }); }, [msg.content, msg.role, msg.isError, lang]); return ( <div className={`flex gap-2.5 ${msg.role === "user" ? "flex-row-reverse" : "flex-row"}`}> {/* Avatar — user wears their real profile photo (owner request 2026-11-26); the icon chip remains only for users without one. Bot wears the site logo. */} <BubbleAvatar role={msg.role} userAvatar={userAvatar} /> {/* Message Bubble */} <div className="flex min-w-0 max-w-[85%] flex-col"> <div dir={ARABIC_RE.test(msg.content) ? "rtl" : "ltr"} className={"chatbot-bubble relative group px-3.5 py-2.5 rounded-2xl text-[13.5px] leading-relaxed break-words overflow-wrap-anywhere whitespace-pre-wrap word-break-break-word " + bubbleClass } > {/* Attached image (vision) */} {imageSrc && ( <img src={imageSrc} alt={msg.image?.name || (lang === "ar" ? "صورة مرفقة" : "Attached image")} className="mb-2 max-h-44 w-auto max-w-full rounded-lg border border-white/15" draggable={false} /> )} {msg.role === "assistant" && msg.isError ? ( <span className="whitespace-pre-wrap">{msg.content}</span> ) : ( // biome-ignore lint/security/noDangerouslySetInnerHtml: renderMarkdown() escapes all HTML entities first, only re-adds safe markdown formatting tags <span ref={sldBodyRef} dangerouslySetInnerHTML={{ __html: renderMarkdown(msg.content) }} /> )} {/* Copy button (assistant messages, only on hover) */} {msg.role === "assistant" && !msg.isError && msg.id !== "welcome" && ( <button onClick={() => onCopy(msg.id, msg.content)} className="absolute top-1.5 end-1.5 p-1 rounded-md opacity-100 md:opacity-0 md:group-hover:opacity-100 transition-opacity text-slate-500 hover:text-cyan-400 hover:bg-white/5" title={lang === "ar" ? "نسخ" : "Copy"} > <Copy className="h-3 w-3" /> </button> )} {/* Copied tooltip */} {copied && ( <span className="absolute top-1.5 end-8 rounded border border-cyan-400/20 bg-cyan-400/10 px-1.5 py-0.5 text-[10px] text-cyan-400"> {lang === "ar" ? "تم النسخ!" : "Copied!"} </span> )} </div> {/* (No model label by design — engine identity is private.) */} {/* 👍/👎 feedback (assistant replies) — fuels the prompt evolution loop */} <FeedbackControls msg={msg} lang={lang} onFeedback={onFeedback} /> {/* 📐 Draw-now chip — the reply promised a diagram but delivered none (token-cap cut / broken spec fence / bare offer). One tap sends the follow-up instead of making the user retype their request. */} {showDrawNow && ( <button onClick={() => onDrawNow(msg.id)} className="mt-2 ms-1 inline-flex items-center gap-1.5 self-start rounded-full border border-cyan-400/30 bg-cyan-400/10 px-3 py-1.5 text-[11.5px] font-semibold text-cyan-300 transition-colors hover:border-cyan-300/50 hover:bg-cyan-400/20" title={lang === "ar" ? "ابعت متابعة بتخلّي البوت يرسمها فوراً" : "Send a follow-up so the bot draws it now"} > 📐 {lang === "ar" ? "ارسمها دلوقتي" : "Draw it now"} </button> )} {/* Retry button (error messages) */} {msg.isError && ( <button onClick={() => onRetry(msg.id)} className="mt-2 ms-1 flex items-center gap-1.5 text-[11px] text-red-400/70 transition-colors hover:text-red-400" > <RotateCcw className="h-3 w-3" /> {lang === "ar" ? "إعادة المحاولة" : "Retry"} </button> )} </div> </div> ); }); // ─── Component ─────────────────────────────────────────────────────────────── /** * History flag for the mobile back-button gate (owner report 2026-11-26). * While the fullscreen chat is open on mobile, the pinned history entry * carries this flag in its state object — it marks the entry that must be * popped by the FIRST back press (closing the chat) instead of leaving the * site. Preserved alongside the router's own state (idx) on push. */ const CHATBOT_HISTORY_FLAG = "__ahmdrChatbotOpen"; export default function ChatBot() { // NOSONAR — chatbot component with SSE streaming, abort, copy, minimize, scroll-sync, localStorage; extraction would require prop-drilling many refs/state const { lang } = useTranslation(); const { isAuthenticated, isLoading: authLoading, user } = useAuth(); const navigate = useNavigate(); const [isOpen, setIsOpen] = useState(false); const [messages, setMessages] = useState<Message[]>(() => loadMessagesFromStorage(chatStorageKey(user?.id)) || [WELCOME_MESSAGES[lang]]); const [isLoading, setIsLoading] = useState(false); const [isMinimized, setIsMinimized] = useState(false); const [streamingContent, setStreamingContent] = useState<string>(""); const [copiedId, setCopiedId] = useState<string>(""); const [chatMode, setChatMode] = useState<ChatMode>(loadChatMode); // ✅ BYOK (bring-your-own-key): the chatbot's own-model menu. When open it // replaces the messages area (a small settings screen inside the chat // window); byokActive lights the header key badge so the user always sees // whether their custom model is in charge. const [byokPanelOpen, setByokPanelOpen] = useState(false); const [byokActive, setByokActive] = useState(false); const messagesEndRef = useRef<HTMLDivElement>(null); const chatContainerRef = useRef<HTMLDivElement>(null); // Typing-lag fix: the textarea lives inside the isolated ChatInputArea — // the parent no longer holds input state, so keystrokes never re-render // the conversation. The ref exposes setTextAndFocus for the quick chips. const chatInputRef = useRef<ChatInputHandle>(null); const chatIdRef = useRef<string>(crypto.randomUUID()); // Snapshot of `messages` for callbacks that must read the CURRENT list // without re-creating on every keystroke (feedback votes need the question // snapshot above the rated reply). Synced after every render. const messagesRef = useRef<Message[]>(messages); useLayoutEffect(() => { messagesRef.current = messages; }, [messages]); // ─── Identity-change reload (security, root-cure 2026-11-13) ─── // The state initializer above runs ONCE, before the auth check settles — // on a shared browser it loads the GUEST key even though a session cookie // exists. Without this effect those guest messages stay in the UI AND get // written into the logged-in user's storage key by the persist effect // (cross-identity leak the per-identity keys were designed to prevent). // When the identity flips (login settles / logout), the conversation is // reloaded from the CORRECT identity key. Guarded by identity only, so a // language switch can never wipe an active conversation. const identityRef = useRef<number | null | undefined>(user?.id ?? null); useEffect(() => { const identity = user?.id ?? null; if (identity === identityRef.current) return; identityRef.current = identity; setMessages(loadMessagesFromStorage(chatStorageKey(identity)) || [WELCOME_MESSAGES[lang] ?? WELCOME_MESSAGES.en]); }, [user?.id, lang]); const abortControllerRef = useRef<AbortController | null>(null); // Bumped on clearChat — any in-flight sendMessage with an older generation // becomes stale and must NOT touch state afterwards (prevents the cleared // conversation from being partially re-populated by a late stream). const generationRef = useRef(0); const fabRef = useChatFabAnimation(); // YouTube-style scroll hide for the FAB button — suspended while the chat // window (or its minimized bubble) is open so an active chat never dips away. const fabHidden = useFabScrollVisibility(isOpen); const typingTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null); const typingExitStartedRef = useRef(false); // ─── SCREEN CONTEXT tracker (owner requirement 2026-11: the bot must see // the user's CURRENT open screen while they navigate) ─── // Every route change records the visited path into the session trail, and // the live path/auth are kept in refs so sendMessage composes a FRESH // pageContext snapshot per send attempt — no stale closure, no extra // re-creation of the giant callback on navigation. const location = useLocation(); const locationRef = useRef(location.pathname); const authRef = useRef<ScreenAuth>("guest"); useLayoutEffect(() => { locationRef.current = location.pathname; pushTrail(location.pathname); if (user?.role === "admin") authRef.current = "admin"; else if (isAuthenticated) authRef.current = "user"; else authRef.current = "guest"; }, [location.pathname, user?.role, isAuthenticated]); // ─── BYOK badge state (fail-open): when the chat opens for an // authenticated user, one cheap GET lights the header key badge if a // custom model is saved AND enabled. Never blocks the chat — any failure // just leaves the badge off. ─── useEffect(() => { if (!isOpen || !isAuthenticated) return; let cancelled = false; fetch(`${API_BASE}/api/user-ai-provider`) .then((res) => (res.ok ? res.json() : null)) .then((data: { success?: boolean; config?: { enabled?: boolean } | null } | null) => { if (!cancelled && data?.success) setByokActive(!!data.config?.enabled); }) .catch(() => { /* badge stays off — the panel refetches on open */ }); return () => { cancelled = true; }; }, [isOpen, isAuthenticated]); // ─── Typing indicator visibility (handles enter/exit animations) ─── const [typingVisible, setTypingVisible] = useState(false); const [typingExiting, setTypingExiting] = useState(false); // ─── Scroll-follow state ─── const stickToBottomRef = useRef(true); const [showJumpToLatest, setShowJumpToLatest] = useState(false); // ─── Stick-to-bottom auto-scroll (streaming + new messages) ─── // useLayoutEffect runs BEFORE paint, so text growth and the scroll land in // the same frame — the conversation follows the streaming cursor with zero // flicker. If the user scrolls up to read, auto-follow pauses and a // "jump to latest" chip appears instead. // biome-ignore lint/correctness/useExhaustiveDependencies: streamingContent / typingVisible / messages.length are intentional TRIGGERS — the effect re-pins the scroll position whenever any of them changes (refs are read on purpose) useLayoutEffect(() => { if (!chatContainerRef.current || !stickToBottomRef.current) return; chatContainerRef.current.scrollTop = chatContainerRef.current.scrollHeight; }, [streamingContent, typingVisible, messages.length]); // ─── Smooth streaming reveal (professional typing feel) ─── // Incoming text (SSE deltas OR a full non-streaming reply) lands in a // pending buffer; a 30ms ticker drains it into the visible bubble at an // adaptive rate — small trickles render glyph-by-glyph, big bursts catch // up fast so the reveal finishes with the stream. The blinking caret and // the stick-to-bottom scroll are therefore ALWAYS in sync with the text // the user actually sees — even when the upstream delivers one huge chunk // or long bursts (owner requirement: typing must look live, never "all at // once"). const pendingTextRef = useRef(""); const revealTimerRef = useRef<ReturnType<typeof setInterval> | null>(null); const stopReveal = useCallback(() => { if (revealTimerRef.current) { clearInterval(revealTimerRef.current); revealTimerRef.current = null; } }, []); const startReveal = useCallback(() => { if (revealTimerRef.current) return; revealTimerRef.current = setInterval(() => { const pending = pendingTextRef.current; if (!pending) return; // Adaptive step: ~1 glyph on trickles, 8 chars on bursts, and up to 16 // chars for very long backlogs — ANY reply (even 6k chars) finishes its // reveal in ≲10s while small trickles still render glyph-by-glyph. const step = Math.max(1, Math.min(pending.length > 4000 ? 16 : 8, Math.ceil(pending.length / 12))); pendingTextRef.current = pending.slice(step); setStreamingContent((prev) => prev + pending.slice(0, step)); }, 30); }, []); /** * Resolve once the reveal caught up with everything received (bounded). * ✅ STOP BUTTON (2026-11-14): `shouldAbort` lets a user stop interrupt the * cosmetic typewriter too — pressing stop freezes the reply INSTANTLY * instead of waiting for the adaptive reveal to finish (up to 45s for long * replies). The full received text is committed by the caller either way. */ const drainReveal = useCallback(async (maxMs = 10_000, shouldAbort?: () => boolean) => { const deadline = Date.now() + maxMs; // Timed poll by design: the reveal ticker runs on its own 30ms interval, // so draining means “wake up every 30ms and check” — not a batch of // parallel awaits. NOSONAR while (pendingTextRef.current && Date.now() < deadline && !(shouldAbort?.() ?? false)) { await new Promise((r) => setTimeout(r, 30)); // NOSONAR: deliberate 30ms poll — see comment above. } }, []); // Component teardown safety (the widget effectively never unmounts, but // an interval must never outlive its owner). useEffect(() => () => stopReveal(), [stopReveal]); // ─── Docgen download cards (event delegation) ─── // renderMarkdown() emits the file cards as innerHTML (no React handlers), // so ONE document-level listener decodes the base64 spec from the card and // POSTs it to /api/docs/gen (public, deterministic, same-origin — the // /api/diagrams/sld contract) and triggers a blob download with the // server-provided filename. Busy/error states live on the button itself. useEffect(() => { const handler = (ev: MouseEvent) => { const target = ev.target; if (!(target instanceof HTMLElement)) return; const btn = target.closest<HTMLButtonElement>("[data-docgen-dl]"); if (!btn) return; const card = btn.closest<HTMLElement>("[data-docgen]"); if (!card?.dataset.docgen) return; ev.preventDefault(); ev.stopPropagation(); if (btn.dataset.busy === "1") return; const original = btn.textContent; const restore = (ms = 0) => { if (ms) window.setTimeout(() => { btn.textContent = original; }, ms); else btn.textContent = original; }; btn.dataset.busy = "1"; btn.textContent = lang === "ar" ? "⏳ جارٍ البناء…" : "⏳ Building…"; btn.style.opacity = "0.75"; void (async () => { try { const bin = atob(card.dataset.docgen ?? ""); const bytes = new Uint8Array(bin.length); for (let i = 0; i < bin.length; i++) bytes[i] = bin.codePointAt(i) ?? 0; const payload = JSON.parse(new TextDecoder().decode(bytes)) as { spec: unknown; format: string }; const res = await fetch(`${API_BASE}/api/docs/gen`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(payload), }); if (!res.ok) throw new Error(`docs/gen ${res.status}`); const blob = await res.blob(); const disposition = res.headers.get("Content-Disposition") ?? ""; const utf8Match = /filename\*=UTF-8''([^;]+)/i.exec(disposition); const asciiMatch = /filename="([^"]+)"/i.exec(disposition); let filename = "elbaz-document"; if (utf8Match) filename = decodeURIComponent(utf8Match[1]); else if (asciiMatch) filename = asciiMatch[1]; const url = URL.createObjectURL(blob); const a = document.createElement("a"); a.href = url; a.download = filename; document.body.appendChild(a); a.click(); a.remove(); window.setTimeout(() => URL.revokeObjectURL(url), 4000); btn.textContent = lang === "ar" ? "✓ تم التحميل" : "✓ Downloaded"; restore(2200); } catch { btn.textContent = lang === "ar" ? "✕ تعذر التحميل" : "✕ Download failed"; restore(2600); } finally { btn.dataset.busy = "0"; btn.style.opacity = "1"; } })(); }; document.addEventListener("click", handler, true); return () => document.removeEventListener("click", handler, true); // lang is read at click time via closure refresh; re-bind on lang change. }, [lang]); const historySyncedRef = useRef(false); // ─── Server history sync (logged-in users) ─── // On first open after login: pull the last 50 rounds from chatMessages. // SERVER WINS over localStorage whenever it has content (requirement) — // localStorage stays as the instant cache + guest fallback. Fails open: // any network error keeps the local conversation untouched. useEffect(() => { if (isAuthenticated === false) { historySyncedRef.current = false; return; } if (!isOpen || isAuthenticated !== true || historySyncedRef.current) return; historySyncedRef.current = true; void (async () => { try { const res = await fetch(`${API_BASE}/api/chatbot/history`); if (!res.ok) return; const data = await res.json(); if (!data?.success || !Array.isArray(data.messages) || data.messages.length === 0) return; const serverMsgs: Message[] = data.messages.map((m: { id?: string; role?: string; content?: string; createdAt?: string; model?: string }) => ({ id: m.id || crypto.randomUUID(), role: m.role === "user" ? "user" : "assistant", content: m.content || "", timestamp: new Date(m.createdAt || Date.now()), model: m.model || undefined, })); const restored = serverMsgs.slice(-MAX_STORAGE_MESSAGES); setMessages(restored); saveMessagesToStorage(restored, chatStorageKey(user?.id)); } catch { // History sync is best-effort — the local conversation keeps working. } })(); }, [isOpen, isAuthenticated, user?.id]); const scrollToBottom = useCallback((smooth = false) => { const el = chatContainerRef.current; if (!el) return; stickToBottomRef.current = true; setShowJumpToLatest(false); if (smooth) el.scrollTo({ top: el.scrollHeight, behavior: "smooth" }); else el.scrollTop = el.scrollHeight; }, []); // Track whether the user detached from the bottom (scrolled up to read). // A scroll event fired right after the container was RESIZED is a layout // clamp (the browser adjusting scrollTop during reflow — e.g. keyboard // open/close), not a user gesture — it must not break stick-to-bottom. const lastClientHeightRef = useRef(0); const handleMessagesScroll = useCallback(() => { const el = chatContainerRef.current; if (!el) return; if (el.clientHeight !== lastClientHeightRef.current) { lastClientHeightRef.current = el.clientHeight; return; } const distance = el.scrollHeight - el.scrollTop - el.clientHeight; stickToBottomRef.current = distance < 80; setShowJumpToLatest(distance > 140); }, []); // ─── Focus input when chat opens ─── // (The textarea is inside ChatInputArea — focus it via the exposed ref.) useEffect(() => { if (isOpen && !isMinimized) { const t = setTimeout(() => { chatInputRef.current?.focus(); }, 300); return () => clearTimeout(t); } return undefined; }, [isOpen, isMinimized]); // ─── Scroll to latest when the chat opens ─── useEffect(() => { if (isOpen && !isMinimized) { const t = setTimeout(() => scrollToBottom(false), 60); return () => clearTimeout(t); } return undefined; }, [isOpen, isMinimized, scrollToBottom]); // ─── Keyboard-aware mobile sizing (visualViewport API) ─── // When the on-screen keyboard opens, a fixed bottom-anchored window gets // covered on iOS (layout viewport unchanged) and squeezed on Android. We // track the visual viewport and, while the chat is open on a small screen, // pin the window's bottom just above the keyboard and give it the full // visual height — the conversation and whatever the user types stay visible. const [kb, setKb] = useState({ open: false, height: 0, offsetBottom: 0, small: false }); useEffect(() => { const vv = window.visualViewport; if (!vv) return undefined; let maxSeen = Math.max(window.innerHeight, vv.height); const update = () => { maxSeen = Math.max(maxSeen, window.innerHeight, vv.height); const small = window.innerWidth < 768; const open = small && vv.height < maxSeen - 100; const offsetBottom = Math.max(0, Math.round(window.innerHeight - vv.height - vv.offsetTop)); setKb((prev) => { const next = { open, height: Math.round(vv.height), offsetBottom, small }; return (prev.open === next.open && prev.height === next.height && prev.offsetBottom === next.offsetBottom && prev.small === next.small) ? prev : next; }); }; // rAF keeps the initial measurement out of the effect body (React 19 lint) const raf = requestAnimationFrame(update); // ✅ vercel-react-best-practices (client-passive-event-listeners): these // handlers only READ viewport metrics — passive keeps scrolling smooth. vv.addEventListener("resize", update, { passive: true }); vv.addEventListener("scroll", update, { passive: true }); window.addEventListener("resize", update, { passive: true }); window.addEventListener("orientationchange", update, { passive: true }); return () => { cancelAnimationFrame(raf); vv.removeEventListener("resize", update); vv.removeEventListener("scroll", update); window.removeEventListener("resize", update); window.removeEventListener("orientationchange", update); }; }, []); // ─── Mobile fullscreen chat (owner request) ─── // On phones the chat opens edge-to-edge over the whole screen so the // reading area is as large and as clear as possible. Desktop is unchanged. const [isMobileViewport, setIsMobileViewport] = useState( () => typeof window !== "undefined" && window.matchMedia("(max-width: 767px)").matches, ); useEffect(() => { const mq = window.matchMedia("(max-width: 767px)"); const onChange = (e: MediaQueryListEvent) => setIsMobileViewport(e.matches); mq.addEventListener("change", onChange); return () => mq.removeEventListener("change", onChange); }, []); // ─── ANDROID BACK GATE (owner report 2026-11-26) ─── // On mobile the chat is fullscreen, so users reach for the hardware back // button to leave the chat — and used to exit the whole site instead of // just closing the chat window. Cure: while the fullscreen chat is open on // mobile we pin ONE extra history entry (same URL, flagged state). The // first back press pops THAT entry — a same-URL popstate the router reads // as a no-op — and the handler closes the chat instead of leaving. The X // button consumes the pinned entry via history.back() so the stack never // grows stale entries, and minimize unpins too (the bubble does not cover // the screen, so back must navigate normally while it shows). const suppressNextPopRef = useRef(false); /** Consume the pinned entry (X close / minimize). No-op when flagless. */ const unpinChatHistory = useCallback(() => { if (typeof window === "undefined") return; if (!window.history.state?.[CHATBOT_HISTORY_FLAG]) return; if (window.history.length > 1) { suppressNextPopRef.current = true; window.history.back(); } else { // Pinned entry is the only entry (chat opened as the very first action // in a fresh tab) — nothing to pop; the flag stays until a later // navigation replaces the entry. suppressNextPopRef.current = false; } }, []); const closeChat = useCallback(() => { setIsOpen(false); unpinChatHistory(); }, [unpinChatHistory]); useEffect(() => { const fullscreen = isOpen && !isMinimized && isMobileViewport; if (!fullscreen) return; // Idempotent: skip when the current entry is already pinned (React // StrictMode double-invoke in dev, or a reload restored the pinned // entry — in the reload case the stale entry is the one to consume, so // skipping the duplicate push is exactly right). if (window.history.state?.[CHATBOT_HISTORY_FLAG]) { // The listener below is still required — without it the pinned entry // restored by a reload would navigate on back instead of closing. } else { try { // Preserve the router's state (idx) so direction detection and the // router's own popstate handling stay fully intact. window.history.pushState( { ...window.history.state, [CHATBOT_HISTORY_FLAG]: true }, "", ); } catch { // History unavailable (sandboxed iframe etc.) — native behavior persists. return; } } const onPopState = () => { if (suppressNextPopRef.current) { suppressNextPopRef.current = false; // entry consumed by an explicit close return; } // Back pressed while the fullscreen chat is open → close the chat only. // After this pop the pinned entry is gone, so closeChat's unpin is a // no-op here (never a double-back). closeChat(); }; window.addEventListener("popstate", onPopState); return () => window.removeEventListener("popstate", onPopState); }, [isOpen, isMinimized, isMobileViewport, closeChat]); // When the keyboard opens, keep the latest message + the caret in view const prevKbOpenRef = useRef(false); useEffect(() => { if (kb.open && !prevKbOpenRef.current && isOpen) { requestAnimationFrame(() => { if (stickToBottomRef.current) scrollToBottom(false); }); } prevKbOpenRef.current = kb.open; }, [kb.open, isOpen, scrollToBottom]); // Re-stick to bottom whenever the messages viewport itself resizes // (keyboard open/close, orientation change): the window height changes // without a scroll event, so a plain scroll listener would miss it. useEffect(() => { const el = chatContainerRef.current; if (!isOpen || isMinimized || !el || typeof ResizeObserver === "undefined") return undefined; const ro = new ResizeObserver(() => { if (stickToBottomRef.current) { el.scrollTop = el.scrollHeight; } }); ro.observe(el); return () => ro.disconnect(); }, [isOpen, isMinimized]); // ─── Typing indicator: show with enter animation / hide with exit animation ─── useEffect(() => { if (isLoading && !streamingContent) { // Cancel any pending exit timer & reset guard if (typingTimerRef.current) { clearTimeout(typingTimerRef.current); typingTimerRef.current = null; } typingExitStartedRef.current = false; setTypingExiting(false); // eslint-disable-line react-hooks/set-state-in-effect // Small RAF delay ensures DOM is ready for the enter animation to play requestAnimationFrame(() => { setTypingVisible(true); }); } else if (streamingContent && typingVisible && !typingExitStartedRef.current) { // First chunk arrived — start exit animation (only ONCE) typingExitStartedRef.current = true; setTypingExiting(true); typingTimerRef.current = setTimeout(() => { setTypingVisible(false); setTypingExiting(false); }, 250); // match exit animation duration } else if (!isLoading) { setTypingVisible(false); setTypingExiting(false); } return () => { if (typingTimerRef.current) { clearTimeout(typingTimerRef.current); typingTimerRef.current = null; } }; }, [isLoading, streamingContent, typingVisible]); // ─── Clear copied tooltip after 2s ─── useEffect(() => { if (copiedId) { const timer = setTimeout(() => setCopiedId(""), 2000); return () => clearTimeout(timer); } return undefined; }, [copiedId]); // ─── Copy message to clipboard ─── const copyMessage = useCallback((msgId: string, content: string) => { navigator.clipboard.writeText(content).then(() => { setCopiedId(msgId); }).catch(() => { // Fallback: use textarea trick const ta = document.createElement("textarea"); ta.value = content; document.body.appendChild(ta); ta.select(); // NOSONAR — S1874: fallback for non-secure contexts (HTTP) where // navigator.clipboard is unavailable. The primary path uses the // async Clipboard API above. document.execCommand("copy"); // NOSONAR — deprecated API used as fallback for non-secure contexts ta.remove(); setCopiedId(msgId); }); }, []); // ─── 👍/👎 feedback on an assistant reply ─── // One-shot vote per message: flips the local state immediately (fail-open — // the vote UI never blocks on the network) and fires the POST with a // question/answer snapshot so the admin panel can review WHY it was rated. const handleFeedback = useCallback((msgId: string, rating: "up" | "down") => { const msgs = messagesRef.current; const idx = msgs.findIndex((m) => m.id === msgId); const target = idx >= 0 ? msgs[idx] : undefined; if (target?.role !== "assistant" || target.feedback === rating) return; let question = ""; for (let i = idx - 1; i >= 0; i--) { const m = msgs[i]; if (m?.role === "user") { question = m.content; break; } } setMessages((prev) => prev.map((m) => (m.id === msgId ? { ...m, feedback: rating } : m))); // ✅ ROOT-CURE (2026-11-13, mobile builds): the vote used to fetch the // RELATIVE url "/api/chatbot/feedback" — on native (Capacitor) builds the // other chat call sites use API_BASE (absolute production origin), so the // relative fetch hit the local app origin and EVERY feedback vote from // the mobile app silently vanished. Same origin contract as history/send. void fetch(`${API_BASE}/api/chatbot/feedback`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ chatId: chatIdRef.current, rating, question: question || target.content.slice(0, 500), answer: target.content, language: lang === "en" ? "en" : "ar", mode: chatMode, model: target.model || undefined, }), }).catch(() => { /* fail-open — the vote already flipped locally */ }); }, [lang, chatMode]); // ─── Send message (with streaming + optional image → vision routing) ─── const sendMessage = useCallback(async (overrideText?: string, image?: AttachedImage | null) => { // NOSONAR — orchestrates silent retries + streaming reveal + fallback + abort + UI state; extraction would split inter-dependent closures across helpers, risking regressions const trimmed = (overrideText ?? "").trim(); if ((!trimmed && !image) || isLoading) return; const generation = generationRef.current; const isStale = () => generationRef.current !== generation; const userMessage: Message = { id: crypto.randomUUID(), role: "user", content: trimmed, timestamp: new Date(), image: image ? { dataUrl: image.dataUrl, thumb: image.thumb, name: image.name, source: image.source } : undefined, }; // Update messages state setMessages((prev) => [...prev.slice(-MAX_HISTORY), userMessage]); setIsLoading(true); setStreamingContent(""); pendingTextRef.current = ""; // Build API messages — history stays plain text; ONLY the new message may // carry image parts (OpenAI-compatible multimodal format). The server // re-validates and flattens anything that is not the last user message. // ✅ FIX (pre-launch audit run-2): error / soft-busy assistant bubbles are // UI-only notifications, not real answers — replaying them into provider // history made the next reply see fake "assistant" turns (and occasionally // echo the busy copy back). // ✅ ROOT-CURE (2026-11-13, retry duplicated the retried question): the // history used to be built from the render-time `messages` closure — during // a retry that closure still contained BOTH the old error bubble's user // question AND the freshly re-appended one, so the provider saw the question // twice. messagesRef.current is synced after every render, so by the time // the retry's 100ms deferred send fires it holds the FILTERED list. const historyMessages = messagesRef.current .slice(-20) .filter((m) => m.id !== "welcome" && !m.isError); type ApiContent = string | Array< | { type: "text"; text: string } | { type: "image_url"; image_url: { url: string }; source?: "screen_capture" } >; const apiMessages: { role: "user" | "assistant"; content: ApiContent }[] = []; for (const m of historyMessages) { apiMessages.push({ role: m.role as "user" | "assistant", content: m.content }); } if (image) { const contentParts: Exclude<ApiContent, string> = []; if (trimmed) contentParts.push({ type: "text", text: trimmed }); // `source: "screen_capture"` — the server validates this flag and arms // the LIVE SCREEN TEACHER prompt (grounded step-by-step guidance, zero // guessing about anything not visible in the frame). contentParts.push({ type: "image_url", image_url: { url: image.dataUrl }, source: image.source }); apiMessages.push({ role: "user", content: contentParts }); } else { apiMessages.push({ role: "user", content: trimmed }); } // Language mirror: reply in the language of the user's actual message, // not the site UI language (Arabic message → Arabic reply, etc.) let replyLang: string = lang; if (trimmed) replyLang = ARABIC_RE.test(trimmed) ? "ar" : "en"; // SCREEN CONTEXT: a getter — the snapshot is composed per ATTEMPT, so a // silent retry that happens after the user navigated reports the NEW // screen, and every request grounds the model in the CURRENT screen // (page name from the navbar map + registered entity title + trail + UI). const buildRequestBody = () => ({ messages: apiMessages, language: replyLang, chatId: chatIdRef.current, mode: chatMode, pageContext: buildChatPageContext({ pathname: locationRef.current, lang: lang === "en" ? "en" : "ar", auth: authRef.current, }), }); // Create abort controller abortControllerRef.current = new AbortController(); // ⏹ STOP BUTTON (owner request, 2026-11-14): the stop button aborts THIS // controller WITHOUT bumping the generation (only clearChat bumps it). // The signal is captured as a local so every decision gate below reads a // stable value even after the finally block nulls the ref. Distinguishing // the stop from a clear is what makes "stop" actually stop: without it // the silent-retry chain would classify the abort as "unreachable" and // resurrect the request — the non-stream fallback would even launch a // brand-new fetch (a listener attached to an already-aborted signal // never fires). const stopSignal = abortControllerRef.current.signal; const isUserStopped = () => !isStale() && stopSignal.aborted; const apiOrigin = globalThis.Capacitor?.isNativePlatform() ? (import.meta.env.VITE_API_URL || "https://ahmedelbaz.qzz.io") : ""; // NEVER-BUSY UX contract (owner requirement): the user must never see a // failure. The server already persists through provider storms (SSE-first // + keepalives + in-stream walk rounds); this loop adds the client-side // layer — silent retries behind the calm "thinking" indicator, and only a // soft, non-error-looking note if EVERY attempt everywhere is exhausted. const SOFT_BUSY = lang === "ar" ? "الخدمة تمر بضغط عالٍ في هذه اللحظات — أعد إرسال سؤالك بعد لحظة وسأجيبك فوراً ⚡" : "The service is under heavy load right now — please send your question again in a moment and I'll answer right away ⚡"; const MAX_STREAM_ATTEMPTS = 3; const sleep = (ms: number) => new Promise<void>((r) => setTimeout(r, ms)); // Full received text of the CURRENT attempt — a ref object so the SSE // consume closures below can mutate it across attempt boundaries. const accumulatedRef = { current: "" }; const resetAttemptBuffers = () => { accumulatedRef.current = ""; pendingTextRef.current = ""; setStreamingContent(""); }; // Every assistant commit funnels through ONE once-guarded helper — a stop // can commit from several sites (mid-stream catch, post-reveal, after the // loop) and the guard makes a double commit structurally impossible. let assistantCommitted = false; const commitAssistantText = (content: string, model?: string) => { const text = content.trim(); if (!text || assistantCommitted) return; assistantCommitted = true; setMessages((prev) => [...prev, { id: crypto.randomUUID(), role: "assistant", content: text, timestamp: new Date(), model, }]); }; /** One silent retry attempt — outcome contract lives in chat-stop-flow.ts. */ const tryStreamOnce = async (): Promise<StreamAttemptOutcome> => { // ⏹ STOP: if the user already pressed stop (abort during the backoff // sleep between attempts), refuse to launch anything new. if (isUserStopped()) return "stopped"; // Per-attempt controller: chained to the main abort (clearChat / stop // button) AND to a liveness watchdog. The server emits `: ping` // keepalives every 4s — TOTAL silence for 45s means the transport is // dead (dying server / stalled proxy / black-holed connection). Without // this watchdog a half-dead connection used to hold the user on // "thinking…" forever; now the attempt aborts and the silent retry // loop takes over. const attemptCtrl = new AbortController(); const mainSignal = abortControllerRef.current?.signal ?? null; const onMainAbort = () => attemptCtrl.abort(); mainSignal?.addEventListener("abort", onMainAbort, { once: true }); let lastByteAt = Date.now(); const watchdog = setInterval(() => { if (Date.now() - lastByteAt > 45_000) attemptCtrl.abort(); }, 5_000); // Hoisted so the stop path (catch) can commit with the model identity. let receivedModel = ""; try { const streamResponse = await fetch(`${apiOrigin}/api/chatbot/stream`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(buildRequestBody()), signal: attemptCtrl.signal, }); if (!streamResponse.ok) return "unreachable"; const reader = streamResponse.body?.getReader(); if (!reader) return "unreachable"; let receivedAny = false; const consumePayload = (payload: string) => { if (payload === "[DONE]") return; try { const parsed = JSON.parse(payload); if (parsed.model) { receivedModel = parsed.model; // Model identity stays server-side — never surfaced in the UI. } else if (parsed.text) { accumulatedRef.current += parsed.text; pendingTextRef.current += parsed.text; startReveal(); receivedAny = true; } // parsed.error events are IGNORED here on purpose: the server // only emits them pre-content, the attempt simply ends with no // text and the retry loop handles it — no error UI, ever. } catch { // Intentionally ignored: SSE payload is not valid JSON — treat as raw text chunk. — SonarCloud S2486 accumulatedRef.current += payload; pendingTextRef.current += payload; startReveal(); receivedAny = true; } }; const leftover = await readSseUntilDone(reader, { isStale, onBytes: () => { lastByteAt = Date.now(); }, onPayload: consumePayload, }); // Process remaining buffer (the helper returns the incomplete line) if (leftover.trim()) { const remainingLine = leftover.trim(); if (remainingLine.startsWith("data: ")) consumePayload(remainingLine.slice(6).trim()); } if (isStale()) return "ok"; // cleared — nothing more to do if (receivedAny) { // Let the reveal catch up so the committed bubble continues the // exact text the user watched being typed. The cap scales with the // backlog: even a 6k-char reply reveals ≲10s — the deadline exists // only as a pathological-case safety net (never a mid-commit jump). // ⏹ STOP: the stop button interrupts the cosmetic reveal too — the // FULL received text is committed instantly (ChatGPT-style freeze). await drainReveal(45_000, isUserStopped); if (isStale()) return "ok"; if (isUserStopped()) { commitAssistantText(accumulatedRef.current, receivedModel || undefined); return "stopped"; } commitAssistantText(accumulatedRef.current, receivedModel || undefined); return "ok"; } return "failed"; // no content — server walk exhausted; retry silently } catch { // Aborted (stop button, clearChat, liveness watchdog) or the network // layer itself failed. // ⏹ STOP: a mid-stream user stop freezes what the user already saw — // the accumulated text is committed ONCE (the helper guards against // the post-loop commit repeating it) and "stopped" ends the loop // before any silent retry can resurrect the killed request. if (isUserStopped()) { commitAssistantText(accumulatedRef.current, receivedModel || undefined); return "stopped"; } return "unreachable"; } finally { clearInterval(watchdog); mainSignal?.removeEventListener("abort", onMainAbort); } }; /** Non-streaming fallback — used when the stream transport is unreachable. */ const tryNonStreamOnce = async (): Promise<boolean> => { // ⏹ STOP: never launch a new request after the user pressed stop. This // guard is the deepest part of the root cure: the old chaining below // attaches a listener to the main signal — a listener added AFTER the // signal already aborted never fires — so without this pre-check a stop // pressed during the stream phase ended up HERE with a brand-new fetch // (the user pressed stop and the bot silently started over). if (isUserStopped()) return false; // Same per-attempt protection as the stream: chained to the main abort // (clearChat / stop) + a hard 60s cap — a black-holed non-stream request // must never park the silent retry chain forever. const attemptCtrl = new AbortController(); const mainSignal = abortControllerRef.current?.signal ?? null; const onMainAbort = () => attemptCtrl.abort(); mainSignal?.addEventListener("abort", onMainAbort, { once: true }); const hardCap = setTimeout(() => attemptCtrl.abort(), 60_000); try { const response = await fetch(`${apiOrigin}/api/chatbot`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(buildRequestBody()), signal: attemptCtrl.signal, }); const data = await response.json().catch(() => null); if (data?.success && data.reply) { // Full reply through the SAME reveal queue — the caret, pacing and // auto-scroll stay identical to the streaming experience. accumulatedRef.current = data.reply; pendingTextRef.current += data.reply; startReveal(); await drainReveal(60_000, isUserStopped); if (isStale()) return true; if (isUserStopped()) { commitAssistantText(accumulatedRef.current, data.model || undefined); return true; } commitAssistantText(data.reply, data.model || undefined); return true; } // Specific product notices (image quota / rate limit — localized by // the router) are legitimate user-facing messages, not "busy" noise. if (response.status === 429 && typeof data?.error === "string" && data.error && !/heavy load|ضغط عالٍ/.test(data.error)) { if (!isStale()) { setMessages((prev) => [...prev, { id: crypto.randomUUID(), role: "assistant", content: data.error, timestamp: new Date(), isError: true, }]); } return true; // handled — do not retry a deliberate notice } return false; // soft-busy 503 or unknown — retryable } catch { return false; } finally { clearTimeout(hardCap); mainSignal?.removeEventListener("abort", onMainAbort); } }; try { let handled = false; let attempt = 0; // ⏹ STOP: the loop gate is the unit-tested decision table — a user stop // (abort WITHOUT a generation bump) ends the chain exactly like a clear // does; nothing may resurrect the killed request. while (shouldAttemptNext({ attempt, maxAttempts: MAX_STREAM_ATTEMPTS, handled, stale: isStale(), userStopped: isUserStopped(), })) { attempt++; if (attempt > 1) resetAttemptBuffers(); const outcome = await tryStreamOnce(); if (outcome === "ok") { handled = true; break; } if (outcome === "stopped" || isStale() || isUserStopped()) break; if (outcome === "unreachable") { // Transport-level failure — try the non-stream endpoint once. handled = await tryNonStreamOnce(); if (handled || isStale() || isUserStopped()) break; // Serial backoff between silent retries BY DESIGN — parallel // retries would hammer a struggling server. NOSONAR await sleep(2500); // NOSONAR: intentional retry backoff, see comment above. continue; } // "failed" — the server exhausted its own persistence deadline. // Brief pause (cooldown rotation benefits) then retry silently. // Serial backoff by design (same contract as above). NOSONAR if (shouldAttemptNext({ attempt, maxAttempts: MAX_STREAM_ATTEMPTS, handled, stale: isStale(), userStopped: isUserStopped(), })) { await sleep(attempt === 1 ? 1500 : 4000); // NOSONAR: intentional retry backoff. } } // ⏹ STOP: the after-loop decision table (pure, unit-tested module). // A user stop with received text freezes that text; a user stop with // nothing received stays silent; only a genuine all-attempts failure // (no stop, no clear) shows the calm soft-busy note. const after = resolveAfterAttempts({ handled, stale: isStale(), userStopped: isUserStopped(), partialText: accumulatedRef.current, }); if (after.kind === "commit-partial") { // Freeze exactly what the user watched being typed (the once-guarded // helper no-ops when the attempt already committed richer context). commitAssistantText(after.text); } else if (after.kind === "soft-busy") { // Every silent attempt everywhere failed — one calm note styled as a // normal assistant message (never a red error screen). // ✅ ARCH-AUDIT FIX (SOFT_BUSY bubble replayed into provider history): // mark it isError so the history replay filter excludes it — the // busy copy must never ship to the model as a real assistant turn. setMessages((prev) => [...prev, { id: crypto.randomUUID(), role: "assistant", content: SOFT_BUSY, timestamp: new Date(), isError: true, }]); } } catch (error) { console.warn("ChatBot send failed:", error); // After clearChat the aborted request lands here — never surface a // bubble into the freshly cleared conversation. if (!isStale()) { setMessages((prev) => [...prev, { id: crypto.randomUUID(), role: "assistant", content: SOFT_BUSY, timestamp: new Date(), isError: true, // ✅ ARCH-AUDIT FIX: never replay the busy copy into provider history }]); } } finally { stopReveal(); pendingTextRef.current = ""; setIsLoading(false); setStreamingContent(""); abortControllerRef.current = null; } }, [isLoading, lang, chatMode, startReveal, stopReveal, drainReveal]); // ─── 📐 "ارسمها دلوقتي" chip → one-tap follow-up ─── // The bot promised a diagram but the reply carried no SLD board: one tap // sends a follow-up that re-anchors the immediate-draw rule (spec board // now, sensible assumption if data is missing) — no retyping. The follow-up // language mirrors the promising reply itself, and deliberately says "sld // spec board" IN WORDS (no backticks) so it survives markdown rendering. const handleDrawNow = useCallback((msgId: string) => { if (isLoading) return; const target = messagesRef.current.find((m) => m.id === msgId); const ar = target ? ARABIC_RE.test(target.content) : lang !== "en"; const followUp = ar ? "كمّل اللي بدأته: ارسم مخطط الـ SLD فوراً في ردك ده كلوحة مواصفات sld كاملة من غير أي مقدمات ولا وعود — ولو فيه بيانات ناقصة اعتمد افتراض هندسي منطقي واكتبه في سطر واحد بعد اللوحة." : "Follow through: draw the SLD diagram right now in this reply as a complete sld spec board — no preamble, no promises. If any data is missing, use a sound engineering assumption and state it in one line after the board."; void sendMessage(followUp); }, [isLoading, lang, sendMessage]); // The chip renders ONLY on the LAST message: the moment any follow-up reply // lands (with or without a board) the stale chip disappears with it. While // streaming/loading it stays hidden — there is nothing to follow up on yet. const drawNowMsgId = (() => { if (isLoading || messages.length === 0) return ""; const last = messages.at(-1); if (last?.role !== "assistant" || last.isError || last.id === "welcome") return ""; return detectUnfulfilledDiagramPromise(last.content) ? last.id : ""; })(); // ─── Persist messages to localStorage when they change ─── useEffect(() => { if (messages.length > 0 && !isLoading) { saveMessagesToStorage(messages, chatStorageKey(user?.id)); } }, [messages, isLoading, user?.id]); // ─── Clear chat ─── // Must fully reset the conversation even while a response is streaming: // 1) bump generation → any in-flight sendMessage becomes stale and can no // longer append messages/errors or resurrect old streamed text // 2) abort the active fetch → the SSE reader/typewriter stops immediately // 3) wipe state + storage const clearChat = () => { generationRef.current += 1; abortControllerRef.current?.abort(); chatIdRef.current = crypto.randomUUID(); setMessages([WELCOME_MESSAGES[lang]]); setStreamingContent(""); setCopiedId(""); try { localStorage.removeItem(chatStorageKey(user?.id)); localStorage.removeItem(LEGACY_CHAT_STORAGE_KEY); } catch { /* Intentionally ignored: clearChat must proceed even if localStorage is unavailable. — SonarCloud S2486 */ } // Logged-in users: clear the persisted server history too, otherwise the // rounds come straight back on the next chat open (server wins). if (isAuthenticated === true) { fetch(`${API_BASE}/api/chatbot/history`, { method: "DELETE" }).catch(() => { /* best-effort */ }); } }; // ─── ⏹ Stop button (owner request, 2026-11-14) ─── // The send button transforms into a stop button the moment a message is // sent; pressing it aborts the in-flight request WITHOUT bumping the // generation (unlike clearChat): the fetch dies, the server's stream // cancel() propagates the disconnect into the provider walk — no tokens // keep burning server-side — and the client freezes whatever text the user // already watched being typed (decision table: src/lib/chat-stop-flow.ts). const stopGeneration = useCallback(() => { abortControllerRef.current?.abort(); }, []); // ─── Toggle chat mode (Thinking/Instant) ─── const toggleChatMode = useCallback((mode: ChatMode) => { setChatMode(mode); saveChatMode(mode); if (mode !== chatMode) { toast(modeChangeToast(mode, lang), { duration: 2000 }); } }, [chatMode, lang]); // ─── Handle FAB click: auth gate ─── // ✅ FIX (mobile refresh): clicking the FAB while the auth check was still // running used to misclassify logged-in users as guests once the deadman // timer fired (slow mobile networks / cold server). The click is now QUEUED: // it auto-resolves the moment auth settles — opens the chat for a signed-in // user, redirects to /login only when they are genuinely signed out. const [pendingOpen, setPendingOpen] = useState(false); const pendingSinceRef = useRef<number | null>(null); useEffect(() => { if (pendingOpen) { pendingSinceRef.current ??= Date.now(); } else { pendingSinceRef.current = null; } }, [pendingOpen]); // Resolve the queued click as soon as the auth check settles. useEffect(() => { if (authLoading || !pendingOpen) return; setPendingOpen(false); // eslint-disable-line react-hooks/set-state-in-effect if (isAuthenticated) { setIsOpen(true); setIsMinimized(false); return; } const redirectMsg = lang === "ar" ? "يجب تسجيل الدخول أولاً لاستخدام المساعد الذكي" : "Please log in to use the AI assistant"; toast(redirectMsg, { duration: 2500 }); navigate("/login"); // NOSONAR: S9383 — fire-and-forget by framework contract (void|Promise union) }, [authLoading, pendingOpen, isAuthenticated, navigate, lang]); // Deadman: if the auth check somehow never settles, cancel the queued click // instead of leaving the user waiting forever (no guest misclassification). useEffect(() => { if (!pendingOpen || !authLoading) return; const waited = pendingSinceRef.current ? Date.now() - pendingSinceRef.current : 0; const remaining = Math.max(0, AUTH_LOADING_DEADMAN_MS - waited); const timer = setTimeout(() => { setPendingOpen(false); const stuckMsg = lang === "ar" ? "تعذر التحقق من تسجيل الدخول — تحقق من الاتصال وحاول مرة أخرى" : "Couldn't verify login — check your connection and try again"; toast(stuckMsg, { duration: 2500 }); }, remaining); return () => clearTimeout(timer); }, [pendingOpen, authLoading, lang]); const handleFabClick = useCallback(() => { // While auth state is loading, queue the click — it auto-opens (or // redirects) the instant the check resolves. No clicks are swallowed. if (authLoading) { const loadingMsg = lang === "ar" ? "جارٍ التحقق من تسجيل الدخول..." : "Checking login status..."; toast(loadingMsg, { duration: 1500 }); setPendingOpen(true); return; } // Auth gate: redirect to login if not authenticated if (!isAuthenticated) { const redirectMsg = lang === "ar" ? "يجب تسجيل الدخول أولاً لاستخدام المساعد الذكي" : "Please log in to use the AI assistant"; toast(redirectMsg, { duration: 2500 }); navigate("/login"); // NOSONAR: S9383 — fire-and-forget by framework contract (void|Promise union) return; } setIsOpen(true); setIsMinimized(false); }, [authLoading, isAuthenticated, navigate, lang]); // ─── Retry handler that actually re-sends ─── const handleRetry = useCallback((failedMsgId: string) => { // Remove error message and find the last user message to re-send setMessages((prev) => { const withoutError = prev.filter((m) => m.id !== failedMsgId); // Find last user message let lastUserMsg: Message | null = null; let lastUserIdx = -1; for (let i = withoutError.length - 1; i >= 0; i--) { if (withoutError[i].role === "user") { lastUserMsg = withoutError[i]; lastUserIdx = i; break; } } if (lastUserMsg && lastUserIdx >= 0) { // Remove user message from list (sendMessage will re-add it) const filtered = withoutError.filter((m) => m.id !== lastUserMsg!.id); // Trigger send after state update. // ✅ ROOT-CURE (vision retry blindness): the retry used to re-send // ONLY the text — the attached image (uploaded file OR live screen // frame) was silently dropped, so a retried vision question got an // answer from a model that could no longer SEE anything. The image is // now carried back into the re-send: in-memory messages keep the full // dataUrl; messages restored from localStorage carry the persisted // thumb (160px) as the dataUrl so the model still sees the frame and // the `screen_capture` source re-arms the LIVE SCREEN TEACHER prompt. const img = lastUserMsg.image; const imageForApi: AttachedImage | null = (img?.dataUrl || img?.thumb) ? { dataUrl: img!.dataUrl || img!.thumb!, thumb: img?.thumb || img?.dataUrl || "", name: img?.name, source: img?.source } : null; setTimeout(() => { sendMessage(lastUserMsg!.content, imageForApi).catch(() => {}).catch(() => {}); }, 100); return filtered; } return withoutError; }); }, [sendMessage]); // ─── Unread count (assistant messages received while chat was closed) ─── const [lastSeenCount, setLastSeenCount] = useState(messages.length); useEffect(() => { if (isOpen) { setLastSeenCount(messages.length); // eslint-disable-line react-hooks/set-state-in-effect } }, [isOpen, messages.length]); // ✅ PERF (react-best-practices js-* / rerender-*): the two filter passes over // `messages` used to re-run on EVERY render — and ChatBot re-renders every // 30ms while the streaming-reveal ticker appends text. Single O(n) pass, // memoized on [messages, lastSeenCount]; `unreadCount` stays a derived value. const { assistantCount, innerSeenCount } = useMemo(() => { let assistantCount = 0; let innerSeenCount = 0; for (let i = 0; i < messages.length; i++) { const m = messages[i]; if (m.role === "assistant" && !m.isError) { assistantCount++; if (i < lastSeenCount) innerSeenCount++; } } return { assistantCount, innerSeenCount }; }, [messages, lastSeenCount]); const unreadCount = isOpen ? 0 : Math.max(0, assistantCount - innerSeenCount); // ─── Streaming model display ─── // Neutral typing label — deliberately says nothing about which model or // provider powers the bot (owner request: professional + private; the // engine identity must never appear in the UI). const thinkingLabel = lang === "ar" ? "\u062c\u0627\u0631\u064d \u0627\u0644\u062a\u0641\u0643\u064a\u0631..." : "Thinking..."; // ─── Chat window sizing/shape classes (computed once, no nested ternaries) ─── let windowShellClass = "fixed z-[100] transition-all duration-300 ease-out chatbot-window "; if (isMinimized) windowShellClass += "chatbot-min w-10 h-10 md:w-14 md:h-14 rounded-full"; else if (isMobileViewport) windowShellClass += "chatbot-fullscreen w-screen max-w-full h-[100dvh] rounded-none"; else windowShellClass += "w-[420px] h-[600px] rounded-2xl"; let windowInnerClass = "relative h-full flex flex-col overflow-hidden "; if (isMinimized) windowInnerClass += "bg-gradient-to-br from-cyan-700 to-blue-600 rounded-full cursor-pointer"; else { windowInnerClass += "bg-[#0a1019] border border-[#1e2d3d] shadow-2xl shadow-black/50 "; windowInnerClass += isMobileViewport ? "rounded-none" : "rounded-2xl"; } return ( <> {/* ─── Floating Button ─── */} {!isOpen && ( <button ref={fabRef} onClick={handleFabClick} className={"fixed z-[100] w-10 h-10 md:w-14 md:h-14 rounded-full bg-gradient-to-br from-cyan-700 to-blue-600 text-white shadow-lg shadow-cyan-500/25 flex items-center justify-center transition-all duration-300 hover:scale-110 hover:shadow-cyan-500/40 active:scale-95 chatbot-fab transform-gpu will-change-transform" + (fabHidden ? " fab-scroll-hidden" : "")} aria-label={lang === "ar" ? "\u0641\u062a\u062d \u0627\u0644\u0645\u0633\u0627\u0639\u062f \u0627\u0644\u0630\u0643\u064a" : "Open AI Assistant"} > <div className="relative"> <Bot className="w-5 h-5 md:w-6 md:h-6" /> {unreadCount > 0 && ( <span className="absolute -top-2 -right-2 w-4 h-4 bg-red-600 text-white text-[10px] font-bold rounded-full flex items-center justify-center"> {unreadCount > 9 ? "9+" : unreadCount} </span> )} </div> {/* Pulse ring — only when there are unread messages: a constant ping on every idle FAB was visual noise (declutter). */} {unreadCount > 0 && ( <span className="absolute inset-0 rounded-full bg-cyan-400/30 animate-ping" /> )} </button> )} {/* ─── Chat Window ─── */} {isOpen && ( <div className={windowShellClass} style={(() => { if (isMinimized) return undefined; if (isMobileViewport) { // Fullscreen on phones: cover the viewport edge-to-edge. With // the keyboard open, pin the bottom to the keyboard's top edge // (iOS layout viewport does not shrink; Android does) and take // the full visual height. transition:none keeps the window // glued to the keyboard during its slide animation. if (kb.open && kb.height > 0) { return { bottom: `${Math.max(kb.offsetBottom, 0)}px`, height: `${kb.height}px`, right: '0px', left: '0px', width: '100%', maxWidth: '100%', borderRadius: '0px', transition: 'none', }; } return { bottom: '0px', right: '0px', left: '0px', width: '100%', maxWidth: '100%', height: '100dvh', borderRadius: '0px', }; } if (kb.open && kb.small && kb.height > 0) { // Keyboard is open on a small window — pin the window just // above the keyboard and use the full visual viewport height // (works on both iOS Safari and Android Chrome). return { bottom: `${Math.max(kb.offsetBottom, 0) + 8}px`, height: `${kb.height - 16}px`, right: '1rem', maxWidth: '420px', transition: 'none', }; } return { bottom: 'max(env(safe-area-inset-bottom, 0px) + 1rem, 1rem)', right: '1rem', maxWidth: '420px' }; })()} > <div className={windowInnerClass} > {/* ─── Minimized: Just the button ─── */} {isMinimized && ( <button onClick={() => setIsMinimized(false)} className="w-full h-full flex items-center justify-center text-white" aria-label={lang === "ar" ? "\u0641\u062a\u062d \u0627\u0644\u0634\u0627\u062a" : "Open chat"} > <Bot className="w-5 h-5 md:w-6 md:h-6" /> <span className="absolute -top-1 -right-1 w-3 h-3 bg-green-400 rounded-full border-2 border-[#0a1019]" /> </button> )} {/* ─── Expanded Chat UI ─── */} {!isMinimized && ( <> {/* ─── Header (compact — every vertical px goes to the chat) ─── */} <div className="chatbot-header flex-shrink-0 px-3 py-2 bg-gradient-to-r from-cyan-600/20 to-blue-600/20 border-b border-[#1e2d3d]"> <div className="flex items-center justify-between"> <div className="flex items-center gap-2"> <div className="relative"> {/* Site logo as the bot identity (owner request — replaces the lightning icon) */} <img src="/logo-circle.png?v=2" alt="" aria-hidden="true" draggable={false} decoding="async" className="w-8 h-8 rounded-full object-cover border border-cyan-500/30" /> <span className="absolute -bottom-0.5 -end-0.5 w-2.5 h-2.5 bg-green-400 rounded-full border-2 border-[#0a1019]" /> </div> <div> <h3 className="text-[13px] font-semibold leading-tight text-white"> {lang === "ar" ? "\u0628\u0648\u062a \u0627\u0644\u0628\u0627\u0632 \u0627\u0644\u0630\u0643\u064a" : "Elbaz AI Bot"} </h3> <p className="text-[10px] leading-tight text-cyan-400/70"> {lang === "ar" ? "\u0645\u0633\u0627\u0639\u062f \u0627\u0644\u0647\u0646\u062f\u0633\u0629 \u0627\u0644\u0643\u0647\u0631\u0628\u064a\u0629" : "Electrical Engineering Assistant"} </p> </div> </div> <div className="flex items-center gap-0.5"> {/* ─── Thinking/Instant brain toggle — frameless icon that GLOWS in the site's orange (#F97316) when active ─── */} <button onClick={() => toggleChatMode(chatMode === "thinking" ? "instant" : "thinking")} disabled={isLoading} aria-pressed={chatMode === "thinking"} className={ "flex h-8 w-8 items-center justify-center rounded-lg transition-all disabled:opacity-50 disabled:cursor-not-allowed " + (chatMode === "thinking" ? "text-[#f97316] drop-shadow-[0_0_7px_rgba(249,115,22,0.75)]" : "text-slate-500 hover:text-cyan-300") } title={brainToggleTitle(chatMode === "thinking", lang)} > <Brain className="h-[18px] w-[18px]" /> </button> {/* ─── BYOK: the user's own model menu — glows cyan while a custom model is saved AND active, so the user always knows which engine is answering ─── */} <button onClick={() => setByokPanelOpen((v) => !v)} disabled={isLoading} aria-pressed={byokPanelOpen} className={ "flex h-8 w-8 items-center justify-center rounded-lg transition-all disabled:opacity-50 disabled:cursor-not-allowed " + byokToggleClass(byokActive, byokPanelOpen) } title={byokToggleTitle(byokActive, lang)} > <KeyRound className="h-4 w-4" /> </button> {/* Clear chat button */} <button onClick={clearChat} className="flex h-8 w-8 items-center justify-center rounded-lg text-slate-400 transition-colors hover:bg-red-400/10 hover:text-red-400" title={lang === "ar" ? "\u0645\u0633\u062d \u0627\u0644\u0645\u062d\u0627\u062f\u062b\u0629" : "Clear chat"} > <Trash2 className="w-4 h-4" /> </button> {/* Minimize button — unpin the history entry too: the bubble does not cover the screen, so back must navigate normally while it shows. */} <button onClick={() => { setIsMinimized(true); unpinChatHistory(); }} className="flex h-8 w-8 items-center justify-center rounded-lg text-slate-400 transition-colors hover:bg-cyan-400/10 hover:text-cyan-400" title={lang === "ar" ? "\u062a\u0635\u063a\u064a\u0631" : "Minimize"} > <ChevronDown className="w-4 h-4" /> </button> {/* Close button — closeChat also consumes the pinned history entry so the NEXT back press leaves cleanly. */} <button onClick={closeChat} className="flex h-8 w-8 items-center justify-center rounded-lg text-slate-400 transition-colors hover:bg-red-400/10 hover:text-red-400" title={lang === "ar" ? "\u0625\u063a\u0644\u0627\u0642" : "Close"} > <X className="w-4 h-4" /> </button> </div> </div> </div> {/* ─── BYOK panel — replaces the messages area when open ─── */} {byokPanelOpen ? ( <ByokSettingsPanel lang={lang} onClose={() => setByokPanelOpen(false)} onActiveChange={setByokActive} /> ) : ( <> {/* ─── Messages Area ─── */} <div ref={chatContainerRef} onScroll={handleMessagesScroll} role="log" aria-label={lang === "ar" ? "\u0631\u0633\u0627\u0626\u0644 \u0627\u0644\u0645\u062d\u0627\u062f\u062b\u0629" : "Chat messages"} aria-live="polite" className="flex-1 overflow-y-auto overscroll-contain px-4 py-3 space-y-4 chatbot-messages"> {messages.map((msg) => ( <MessageBubble key={msg.id} msg={msg} lang={lang} copied={copiedId === msg.id} onCopy={copyMessage} onRetry={handleRetry} onFeedback={handleFeedback} showDrawNow={msg.id === drawNowMsgId} onDrawNow={handleDrawNow} userAvatar={user?.avatar ?? null} /> ))} {/* Streaming content (incremental text display) */} {isLoading && streamingContent && ( <div className="flex gap-2.5"> <img src="/logo-circle.png?v=2" alt="" aria-hidden="true" draggable={false} decoding="async" className="flex-shrink-0 w-7 h-7 rounded-full object-cover border border-cyan-500/30" /> <div className="flex flex-col max-w-[85%] min-w-0"> <div dir={ARABIC_RE.test(streamingContent) ? "rtl" : "ltr"} className="chatbot-bubble px-3.5 py-2.5 rounded-2xl rounded-ss-md bg-[#111827] border border-[#1e2d3d] text-[#e8f0fe] text-[13.5px] leading-relaxed break-words overflow-wrap-anywhere whitespace-pre-wrap word-break-break-word"> {/* biome-ignore lint/security/noDangerouslySetInnerHtml: renderMarkdown() escapes all HTML entities first; only safe markdown tags are re-added */} <span dangerouslySetInnerHTML={{ __html: renderMarkdown(streamingContent) }} /> {/* Blinking caret */} <span className="inline-block w-[2px] h-[1.1em] ms-0.5 bg-cyan-400/90 rounded-sm animate-typing-cursor align-text-bottom shadow-[0_0_6px_rgba(6,182,212,0.5)]" /> </div> </div> </div> )} {/* Typing indicator (with enter/exit animations) */} {typingVisible && ( <div className={`flex gap-2.5 ${typingExiting ? "animate-typing-exit" : "animate-typing-enter"}`}> <img src="/logo-circle.png?v=2" alt="" aria-hidden="true" draggable={false} decoding="async" className="flex-shrink-0 w-7 h-7 rounded-full object-cover border border-cyan-500/30" /> <div className="bg-[#111827] border border-[#1e2d3d] px-4 py-3 rounded-2xl rounded-ss-md"> <div className="flex items-center gap-1.5"> <div className="flex gap-1"> <span className="w-1.5 h-1.5 bg-cyan-400 rounded-full animate-bounce" style={{ animationDelay: "0ms" }} /> <span className="w-1.5 h-1.5 bg-cyan-400 rounded-full animate-bounce" style={{ animationDelay: "150ms" }} /> <span className="w-1.5 h-1.5 bg-cyan-400 rounded-full animate-bounce" style={{ animationDelay: "300ms" }} /> </div> <span className="text-[11px] text-slate-500 ms-1"> {thinkingLabel} </span> </div> </div> </div> )} <div ref={messagesEndRef} /> </div> {/* ─── Jump to latest (appears when the user scrolled up mid-stream) ─── */} {showJumpToLatest && ( <button onClick={() => scrollToBottom(true)} className="absolute bottom-[110px] left-1/2 -translate-x-1/2 z-20 flex items-center gap-1 px-3 py-1.5 rounded-full bg-cyan-500/90 text-white text-[11px] font-medium shadow-lg shadow-cyan-500/30 active:scale-95 transition-transform" aria-label={lang === "ar" ? "\u0627\u0644\u0627\u0646\u062a\u0642\u0627\u0644 \u0644\u0623\u062d\u062f\u062b \u0631\u0633\u0627\u0644\u0629" : "Jump to latest message"} > <ChevronDown className="w-3.5 h-3.5" /> {lang === "ar" ? "\u0623\u062d\u062f\u062b \u0631\u0633\u0627\u0644\u0629" : "Latest"} </button> )} {/* ─── Quick Suggestions (show only on first open) ─── */} {messages.length <= 1 && !isLoading && ( <div className="flex-shrink-0 px-4 pb-2"> <div className="flex flex-wrap gap-1.5"> {(lang === "ar" ? [ "\u0627\u064a\u0647 \u0641\u0627\u064a\u062f\u0629 ETAP\u061f", "\u0643\u064a\u0641 \u0623\u0639\u0645\u0644 load flow analysis\u061f", "\u0627\u0644\u0641\u0631\u0642 \u0628\u064a\u0646 SKM \u0648 PowerFactory", "\u0627\u064a\u0647 \u0647\u0648 arc flash study\u061f", ] : [ "What is ETAP used for?", "How to do load flow analysis?", "SKM vs PowerFactory comparison", "What is an arc flash study?", ] ).map((suggestion) => ( <button key={suggestion} onClick={() => { chatInputRef.current?.setTextAndFocus(suggestion); }} className="px-2.5 py-1.5 text-[11px] text-cyan-400/80 bg-cyan-400/5 border border-cyan-400/10 rounded-lg hover:bg-cyan-400/10 hover:border-cyan-400/20 transition-colors truncate max-w-[180px]" > {suggestion} </button> ))} </div> </div> )} {/* ─── Input Area (isolated component — typing never re-renders the conversation; carries the image-attach button) ─── */} <ChatInputArea ref={chatInputRef} lang={lang} isLoading={isLoading} kbOpen={kb.open} isMobileViewport={isMobileViewport} onSend={sendMessage} onStop={stopGeneration} /> </> )} </> )} </div> </div> )} </> ); }
import {
Bot,
Brain,
ChevronDown,
Copy,
ImagePlus,
KeyRound,
Loader2,
MonitorUp,
MonitorX,
RotateCcw,
Send,
Square,
ThumbsDown,
ThumbsUp,
Trash2,
User,
X,
} from "lucide-react";
import { forwardRef, memo, useCallback, useEffect, useImperativeHandle, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
import { useLocation, useNavigate } from "react-router";
import { toast } from "sonner";
import ByokSettingsPanel from "@/components/chatbot/ByokSettingsPanel";
import { useAuth } from "@/hooks/useAuth";
import { useChatFabAnimation } from "@/hooks/useChatFabAnimation";
import { useFabScrollVisibility } from "@/hooks/useFabScrollVisibility";
import { useTranslation } from "@/hooks/useTranslation";
import { resolveAfterAttempts, type StreamAttemptOutcome, shouldAttemptNext } from "@/lib/chat-stop-flow";
import { buildChatPageContext, pushTrail, type ScreenAuth } from "@/lib/screen-context";
import {
captureScreenFrame,
captureScreenPreview,
getScreenShareState,
screenShareSupported,
startScreenShare,
stopScreenShare,
subscribeScreenShare,
} from "@/lib/screen-share";
// ─── Types ───────────────────────────────────────────────────────────────────
interface Message {
id: string;
role: "user" | "assistant" | "error";
content: string;
timestamp: Date;
model?: string;
isError?: boolean;
/** 👍/👎 vote on this assistant reply — one-shot, sent to /api/chatbot/feedback. */
feedback?: "up" | "down";
/** Attached image — dataUrl lives in memory only; localStorage keeps the thumb. */
image?: MessageImage;
}
interface MessageImage {
dataUrl?: string;
thumb?: string;
name?: string;
/** "screen_capture" — the frame came from the live screen-share lane. */
source?: "screen_capture";
}
// ─── localStorage persistence ───────────────────────────────────────────────
// ✅ SECURITY FIX (audit run-1, chatbot.localstorage-history): the storage key
// is per-identity — a shared browser profile can no longer leak the previous
// account's conversation to the next one. Legacy global-key entries are purged
// on first write; useAuth.logout() additionally removes the active key.
const MODE_STORAGE_KEY = "elbaz_chat_mode";
const LEGACY_CHAT_STORAGE_KEY = "elbaz_chat_history";
function chatStorageKey(userId: number | null | undefined): string {
return `elbaz_chat_history:${userId != null ? String(userId) : "guest"}`;
}
const MAX_STORAGE_MESSAGES = 50;
// Max time a FAB click waits for the auth check before treating the visitor
// as logged out (dead-man switch — guarantees the FAB can never be a dead
// button, even if the auth check hangs or loops).
const AUTH_LOADING_DEADMAN_MS = 4000;
type ChatMode = "thinking" | "instant";
// Single API origin — same pattern as the two chat fetch sites (native builds
// must hit the absolute production URL, web builds use same-origin).
const API_BASE = globalThis.Capacitor?.isNativePlatform()
? (import.meta.env.VITE_API_URL || "https://ahmedelbaz.qzz.io")
: "";
function loadChatMode(): ChatMode {
try {
const stored = localStorage.getItem(MODE_STORAGE_KEY);
if (stored === "instant" || stored === "thinking") return stored;
} catch {
// Intentionally ignored: localStorage unavailable — default to thinking. — SonarCloud S2486
}
return "thinking";
}
function saveChatMode(mode: ChatMode): void {
try {
localStorage.setItem(MODE_STORAGE_KEY, mode);