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 = { 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 { 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 { 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(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 (
{lang === "ar" ? "جارٍ فتح نافذة مشاركة الشاشة..." : "Opening the screen-share picker..."}
); } if (!active) return null; return (
{preview ? ( ) : (
)}

{lang === "ar" ? "مباشر من شاشتك" : "Live from your screen"} {label ? — {label} : null}

{lang === "ar" ? "كل رسالة سترسل لقطة حية — البوت يقرأ برنامجك ويوجهك خطوة بخطوة" : "Every message sends a live frame — the bot reads your program and guides you step by step"}

); }); /** * 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, opts: { isStale: () => boolean; onBytes: () => void; onPayload: (payload: string) => void }, ): Promise { 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 (
{lang === "ar" ? "جارٍ تجهيز الصورة..." : "Preparing image..."}
); } 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 (
{displayName}

{displayName}

{lang === "ar" ? "سيتم تحليل الصورة بالذكاء الاصطناعي" : "The image will be analyzed by AI"}

); } // 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 ; if (screenActive) return ; return ; } /** 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) => void; taRef: React.RefObject; fileInputRef: React.RefObject; onPickFile: () => void; onFilePicked: (e: React.ChangeEvent) => 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 (
{/* Attach image (vision) button */} {/* Live screen share (vision) — desktop browsers with getDisplayMedia */} {screenSupported && ( )}