Spaces:
Running
Running
Update index.html
#1
by Hanuman2 - opened
Files changed (12)
- .gitattributes+34-6
- .github/workflows/main.ymlDeleted-47
- .gitignoreDeleted-20
- Dockerfile+2-29
- README.md+11-6
- app.py+97-306
- css/style.cssDeleted-837
- index.html+833-178
- js/markdownRenderer.jsDeleted-278
- js/script.jsDeleted-1221
- logo.pngDeleted
- requirements.txt-4
1234567*.ttf filter=lfs diff=lfs merge=lfs -text*.whl filter=lfs diff=lfs merge=lfs -text*.png filter=lfs diff=lfs merge=lfs -text*.jpg filter=lfs diff=lfs merge=lfs -text*.jpeg filter=lfs diff=lfs merge=lfs -text*.woff2 filter=lfs diff=lfs merge=lfs -text*.wasm filter=lfs diff=lfs merge=lfs -text1234567891011121314151617181920212223242526272829303132333435*.7z filter=lfs diff=lfs merge=lfs -text*.arrow filter=lfs diff=lfs merge=lfs -text*.bin filter=lfs diff=lfs merge=lfs -text*.bz2 filter=lfs diff=lfs merge=lfs -text*.ckpt filter=lfs diff=lfs merge=lfs -text*.ftz filter=lfs diff=lfs merge=lfs -text*.gz filter=lfs diff=lfs merge=lfs -text*.h5 filter=lfs diff=lfs merge=lfs -text*.joblib filter=lfs diff=lfs merge=lfs -text*.lfs.* filter=lfs diff=lfs merge=lfs -text*.mlmodel filter=lfs diff=lfs merge=lfs -text*.model filter=lfs diff=lfs merge=lfs -text*.msgpack filter=lfs diff=lfs merge=lfs -text*.npy filter=lfs diff=lfs merge=lfs -text*.npz filter=lfs diff=lfs merge=lfs -text*.onnx filter=lfs diff=lfs merge=lfs -text*.ot filter=lfs diff=lfs merge=lfs -text*.parquet filter=lfs diff=lfs merge=lfs -text*.pb filter=lfs diff=lfs merge=lfs -text*.pickle filter=lfs diff=lfs merge=lfs -text*.pkl filter=lfs diff=lfs merge=lfs -text*.pt filter=lfs diff=lfs merge=lfs -text*.pth filter=lfs diff=lfs merge=lfs -text*.rar filter=lfs diff=lfs merge=lfs -text*.safetensors filter=lfs diff=lfs merge=lfs -textsaved_model/**/* filter=lfs diff=lfs merge=lfs -text*.tar.* filter=lfs diff=lfs merge=lfs -text*.tar filter=lfs diff=lfs merge=lfs -text*.tflite filter=lfs diff=lfs merge=lfs -text*.tgz filter=lfs diff=lfs merge=lfs -text*.wasm filter=lfs diff=lfs merge=lfs -text*.xz filter=lfs diff=lfs merge=lfs -text*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647name: Deploy to Hugging Face Space
on: push: branches: [ main ] workflow_dispatch:
jobs: sync-to-hf: runs-on: ubuntu-latest steps: - name: Checkout Code uses: actions/checkout@v3
- name: Clean History and Force Push to HF env: HF_TOKEN: ${{ secrets.HF_TOKEN }} run: | # 1. गिट कॉन्फ़िगरेशन git config --global user.email "divy@vedaalabs.ai" git config --global user.name "Divy Patel" # 2. पुरानी हिस्ट्री को पूरी तरह से डिलीट करें और नई शुरुआत करें rm -rf .git git init git branch -M main # 3. LFS सेटअप और ट्रैकिंग (सभी बड़ी फाइलों के लिए) git lfs install git lfs track "*.ttf" git lfs track "*.whl" git lfs track "*.png" git lfs track "*.jpg" git lfs track "*.jpeg" git lfs track "*.woff2" git lfs track "*.wasm" # 4. सभी फाइलों को नए सिरे से ऐड करें git add .gitattributes git add . # 5. नया फ्रेश कमिट git commit -m "Clean deployment with comprehensive LFS tracking" # 6. हगिंग फेस रिमोट सेट करें और फोर्स पुश करें git remote add hf https://user:${HF_TOKEN}@huggingface.co/spaces/Renderlib-dev/CodeVed git push -f hf main1234567891011121314151617181920```gitignore# Python__pycache__/*.pyc*.pyo*.pyd
# Environment.venv/venv/env/
# Logs*.log
# Temporary files*.tmp*.swp*~```123456789101112131415161718192021222324252627282930313233343536373839# ================================================================================# CODE VED - PRODUCTION DOCKERFILE# Engineered by Divy Patel | Modular Architecture# ================================================================================# 1. Use a lightweight but compatible Python base imageFROM python:3.10-slim# 2. Set the working directory inside the containerWORKDIR /app# 3. Install system-level dependencies# - git: Required to clone 'renderlib' from GitHub in requirements.txt# - ffmpeg & libsndfile1: Required by 'supertonic' and 'pydub' for audio processing# - build-essential: Sometimes needed for compiling C-extensions in Python packagesRUN apt-get update && apt-get install -y \git \ffmpeg \libsndfile1 \build-essential \&& rm -rf /var/lib/apt/lists/*# 4. Copy only requirements.txt first to leverage Docker cache# (If requirements don't change, Docker won't reinstall packages every time)COPY requirements.txt .# 5. Install Python dependencies# --no-cache-dir keeps the image size smallRUN pip install --no-cache-dir --upgrade pip && \pip install --no-cache-dir -r requirements.txt# 6. Copy the rest of the application code (HTML, CSS, JS, Python files)COPY . .# 7. Hugging Face Spaces requires the app to listen on port 7860EXPOSE 7860# 8. Command to run the Flask applicationCMD ["python", "app.py"]123456789101112FROM python:3.9-slimWORKDIR /appCOPY requirements.txt .RUN pip install --no-cache-dir -r requirements.txtCOPY . .EXPOSE 7860CMD ["python", "app.py"]
123456789---license: mittitle: Codevedsdk: dockeremoji: 🚀colorFrom: yellowcolorTo: pink---# Web-Vedika1234567891011121314---title: Tiranga-advanced-multimodal-AIemoji: 🚀colorFrom: indigocolorTo: purplesdk: dockerpinned: falselicense: mitshort_description: Demo version of Vedikathumbnail: >-https://cdn-uploads.huggingface.co/production/uploads/6a0975f9cdda3a9b7e513e3f/-EPyeIHoSfq0qp9ntFw9a.png---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373import osimport requestsimport jsonimport reimport ioimport tempfilefrom datetime import datetime, timedelta, timezonefrom bs4 import BeautifulSoupfrom flask import Flask, request, Response, stream_with_context, send_from_directoryfrom supertonic import TTS# ================================================================================# FLASK APP INITIALIZATION (MODULAR FRONTEND SUPPORT)# ================================================================================# static_folder='.' and static_url_path='' tells Flask to serve static files# (CSS, JS, Images) directly from the root directory structure.# This ensures /css/style.css and /js/script.js load perfectly.app = Flask(__name__, static_folder='.', static_url_path='')# ----------------------------------------------------------------------------# INIT RENDERLIB# ----------------------------------------------------------------------------print("Loading RenderLib...")try:from renderlib import RenderLibrenderer = RenderLib()print("RenderLib loaded successfully!")except ImportError as e:print(f"RenderLib not installed yet or error: {e}")renderer = None# ----------------------------------------------------------------------------# INIT TTS MODEL# ----------------------------------------------------------------------------print("Loading Supertonic TTS Model...")try:tts = TTS(auto_download=True)print("TTS Model loaded successfully!")except Exception as e:print(f"Error initializing TTS: {e}")tts = NoneVOICES = ["M1", "M2", "M3", "M4", "M5", "F1", "F2", "F3", "F4", "F5"]LANGUAGES = {"English": "en", "Korean": "ko", "Japanese": "ja", "Arabic": "ar","Bulgarian": "bg", "Czech": "cs", "Danish": "da", "German": "de","Greek": "el", "Spanish": "es", "Estonian": "et", "Finnish": "fi","French": "fr", "Hindi": "hi", "Croatian": "hr", "Hungarian": "hu","Indonesian": "id", "Italian": "it", "Lithuanian": "lt", "Latvian": "lv","Dutch": "nl", "Polish": "pl", "Portuguese": "pt", "Romanian": "ro","Russian": "ru", "Slovak": "sk", "Slovenian": "sl", "Swedish": "sv","Turkish": "tr", "Ukrainian": "uk", "Vietnamese": "vi"}VOICE_STYLES_CACHE = {}# ----------------------------------------------------------------------------# HARDCODED MODEL CONFIGURATION# ----------------------------------------------------------------------------NVIDIA_API_KEY = os.environ.get("NVIDIA_API_KEY", "")INVOKE_URL = "https://integrate.api.nvidia.com/v1/chat/completions"MODEL_ID = "mistralai/mistral-small-4-119b-2603"# ----------------------------------------------------------------------------# GPS REVERSE GEOCODING# ----------------------------------------------------------------------------def get_address_from_coords(lat, lon):try:url = f"https://nominatim.openstreetmap.org/reverse?format=json&lat={lat}&lon={lon}"headers = {'User-Agent': 'CODE_VED_AI_System_by_Divy_Patel'}response = requests.get(url, headers=headers, timeout=5)data = response.json()return data.get('display_name', f"Lat: {lat}, Lon: {lon}")except Exception as e:return f"Lat: {lat}, Lon: {lon}"# ----------------------------------------------------------------------------# SERPAPI GOOGLE SEARCH ENGINE# ----------------------------------------------------------------------------def web_search_scraper(query, num_results=5, user_address=None):results = []serpapi_key = os.environ.get("SERPAPI_KEY")if not serpapi_key:return resultssearch_query = queryif user_address:local_keywords = ["near", "nearby", "distance", "time", "where"]if any(kw in query.lower() for kw in local_keywords):search_query = f"{query} near {user_address}"try:params = {"engine": "google", "q": search_query, "api_key": serpapi_key, "num": num_results, "hl": "en", "gl": "in"}response = requests.get("https://serpapi.com/search", params=params, timeout=10)data = response.json()if "organic_results" in data:for item in data["organic_results"]:title = item.get("title", "")link = item.get("link", "")snippet = item.get("snippet", "")if title and snippet:results.append({"title": title, "link": link, "snippet": snippet})except Exception:passreturn results# ----------------------------------------------------------------------------# RSS TECH NEWS SCRAPER# ----------------------------------------------------------------------------def get_live_web_data(query):url = f"https://news.google.com/rss/search?q={query}&hl=en&gl=IN&ceid=IN:en"headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"}tech_keywords = ["ai", "artificial intelligence", "smartphone", "mobile", "feature", "whatsapp", "google", "tech", "technology", "gadget", "apple", "nasa"]block_keywords = ["share news", "stock"]scraped_results = []try:response = requests.get(url, headers=headers, timeout=6)if response.status_code == 200:soup = BeautifulSoup(response.text, "html.parser")items = soup.find_all('item')for item in items:title = item.title.text if item.title else "No Title"title_lower = title.lower()if any(b_kw in title_lower for b_kw in block_keywords):continueif any(t_kw in title_lower for t_kw in tech_keywords):link = item.link.text if item.link else "#"pub_date = item.pubdate.text if item.pubdate else ""source = item.source.text if item.source else "Google News"scraped_results.append({"title": title,"snippet": f"Published: {pub_date} | Source: {source}","link": link})if len(scraped_results) >= 5:breakexcept Exception:passreturn scraped_results# ----------------------------------------------------------------------------# HOME ROUTE (SERVES MODULAR FRONTEND)# ----------------------------------------------------------------------------@app.route('/')def home():# Serves the new index.html.# Because static_folder='.' and static_url_path='', Flask will automatically# serve /css/style.css, /js/script.js, etc., from the root directory.return send_from_directory('.', 'index.html')# ----------------------------------------------------------------------------# RENDERLIB API ENDPOINT# ----------------------------------------------------------------------------@app.route('/api/render', methods=['POST'])def render_content():if renderer is None:return Response(json.dumps({"error": "RenderLib is not available on the server."}), status=500, mimetype='application/json')data = request.get_json() or {}subject = data.get("subject", "math")method = data.get("method", "to_latex")args = data.get("args", [])kwargs = data.get("kwargs", {})expression = data.get("expression")if expression and not args:args = [expression]try:result = renderer.render(subject, method, *args, **kwargs)return Response(json.dumps({"result": result}), mimetype='application/json')except Exception as e:return Response(json.dumps({"error": f"RenderLib Error: {str(e)}"}), status=500, mimetype='application/json')# ----------------------------------------------------------------------------# CHAT API ENDPOINT (Hardcoded Model & URL)# ----------------------------------------------------------------------------@app.route('/api/chat', methods=['POST'])def chat():if not NVIDIA_API_KEY:return Response(json.dumps({"error": "Configuration Error: NVIDIA_API_KEY is missing."}), mimetype='application/json', status=500)data = request.get_json() or {}user_message = data.get("message", "")attachments = data.get("attachments", [])is_search = data.get("is_search", False)history = data.get("history", [])location = data.get("location")user_address = Nonemax_tokens = data.get("max_tokens", 4096)ist_time = datetime.now(timezone.utc) + timedelta(hours=5, minutes=30)current_date = ist_time.strftime("%A, %d %B %Y, %I:%M %p IST")thinking_mode = data.get("thinking_mode", False)thinking_effort = data.get("thinking_effort", "medium")thinking_instruction = ""if thinking_mode:thinking_instruction = f"\n[CRITICAL INSTRUCTION: THINKING MODE ENABLED - Effort: {thinking_effort}]\nYou MUST format your reasoning exactly inside <think> and </think> HTML tags."location_instruction = ""if location and location.get('lat') and location.get('lng'):user_address = get_address_from_coords(location['lat'], location['lng'])location_instruction = f"\n[USER REAL-TIME LOCATION: {user_address}]"system_prompt = f"""[CRITICAL IDENTITY OVERRIDE]Name: CODE VEDCreator/Engineer: Divy PatelCurrent Time: {current_date}.{location_instruction}{thinking_instruction}You are "Code Ved," an expert AI software engineering and technical consultant. Your goal is to provide precise, clean, and highly optimized code solutions, architectural advice, and technical explanations.Operational Guidelines:- Technical Accuracy: Provide code that follows industry best practices, is secure, and includes necessary comments for clarity.- Efficiency: Prioritize performance, scalability, and maintainability in all architectural suggestions.- Clarity & Structure: Break down complex problems into logical steps. Use code blocks for snippets and markdown tables for comparing technical approaches.- Debugging Mindset: When provided with errors, analyze the root cause before offering the fix, and explain why the solution works.- Language & Tone: Maintain a professional, objective, and helpful tone. Be direct and concise, avoiding unnecessary fluff.Constraints:- Always provide context-aware code; if multiple languages or frameworks are applicable, suggest the best fit with reasoning.- Ensure all code snippets are complete, syntactically correct, and follow the latest stable versions of the requested technologies.- If a user request is ambiguous, ask for necessary technical specifications before proceeding to ensure the output meets the requirements.Formatting Standards:- Use standard Markdown for all responses.- Use LaTeX for any mathematical notations or algorithmic complexity analysis (e.g., Big O notation).- For complex architectural patterns, describe the flow clearly using structured lists."""if is_search:search_context = ""scraped_data = web_search_scraper(user_message, user_address=user_address)news_data = get_live_web_data(user_message)if scraped_data:search_context += "\n\n--- [LIVE GOOGLE SEARCH] ---\n"for idx, res in enumerate(scraped_data):search_context += f"{idx+1}. {res['title']}: {res['snippet']} (URL: {res['link']})\n"if news_data:search_context += "\n--- [LIVE TECH NEWS] ---\n"for idx, res in enumerate(news_data):search_context += f"{idx+1}. {res['title']}: {res['snippet']} (URL: {res['link']})\n"if search_context:user_message = f"{user_message}\n{search_context}\n[COMMAND: Base your final answer strictly on the facts provided above.]"messages = [{"role": "system", "content": system_prompt}]for msg in history:if msg == history[-1] and msg.get("role") == "user":continuerole = msg.get("role", "user")if role not in ["system", "user", "assistant"]:role = "user"content = msg.get("content", "")if isinstance(content, list):text_parts = [item["text"] for item in content if item.get("type") == "text"]content = " ".join(text_parts)if "Gemma" in content or "DeepMind" in content or "Google" in content:continueif content:messages.append({"role": role, "content": str(content)})if attachments:content_payload = [{"type": "text", "text": user_message}]for att in attachments:att_type = att.get("type")b64_data = att.get("data")if att_type == "image":content_payload.append({"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{b64_data}"}})messages.append({"role": "user", "content": content_payload})else:messages.append({"role": "user", "content": user_message})headers = {"Authorization": f"Bearer {NVIDIA_API_KEY}","Accept": "text/event-stream","Content-Type": "application/json"}payload = {"model": MODEL_ID,"messages": messages,"max_tokens": 128000,"temperature": 1.0,"top_p": 0.95,"stream": True}try:response = requests.post(INVOKE_URL, headers=headers, json=payload, stream=True, timeout=60)if response.status_code != 200:err_text = response.text[:200]err_msg = json.dumps({"error": f"API Error {response.status_code}: {err_text}"})return Response(f"data: {err_msg}\n\n", mimetype='text/event-stream')def generate():for line in response.iter_lines():if line:decoded = line.decode("utf-8")if decoded.startswith("data: ") and "[DONE]" not in decoded:try:data_json = json.loads(decoded[6:])if "choices" in data_json and len(data_json["choices"]) > 0:delta = data_json["choices"][0].get("delta", {})if "content" in delta and delta["content"]:content = delta["content"]# Normalize thinking tags for the frontendcontent = content.replace("<|channel|>thought <|channel|>", "<think>\n")content = content.replace("<|channel|>answer <|channel|>", "\n</think>\n")delta["content"] = contentyield "data: " + json.dumps(data_json) + "\n\n"except Exception:yield decoded + "\n\n"else:yield decoded + "\n\n"return Response(stream_with_context(generate()), mimetype='text/event-stream')except Exception as e:err_msg = json.dumps({"error": str(e)})return Response(f"data: {err_msg}\n\n", mimetype='text/event-stream')# ----------------------------------------------------------------------------# TTS DIRECT API ENDPOINT# ----------------------------------------------------------------------------@app.route('/api/tts', methods=['POST'])def generate_tts():if tts is None:return Response(json.dumps({"error": "TTS model failed to load on server."}), status=500, mimetype='application/json')data = request.get_json() or {}text = data.get("text", "")voice = data.get("voice", "M2")language_name = data.get("language_name", "English")if not text.strip():return Response(json.dumps({"error": "Text is empty."}), status=400, mimetype='application/json')try:lang_code = LANGUAGES.get(language_name, "en")if voice not in VOICE_STYLES_CACHE:VOICE_STYLES_CACHE[voice] = tts.get_voice_style(voice_name=voice)style = VOICE_STYLES_CACHE[voice]if style is None:return Response(json.dumps({"error": f"Voice '{voice}' not available."}), status=400, mimetype='application/json')wav, duration = tts.synthesize(text, voice_style=style, lang=lang_code)with tempfile.NamedTemporaryFile(suffix='.wav', delete=False) as tmp_file:tmp_path = tmp_file.nametts.save_audio(wav, tmp_path)with open(tmp_path, 'rb') as f:audio_data = f.read()os.unlink(tmp_path)return Response(audio_data, mimetype="audio/wav")except Exception as e:print(f"TTS Synthesis Error: {e}")return Response(json.dumps({"error": f"TTS synthesis failed: {str(e)}"}), status=500, mimetype='application/json')# ----------------------------------------------------------------------------# RUN SERVER# ----------------------------------------------------------------------------if __name__ == '__main__':# Hugging Face Spaces requires the app to run on port 7860app.run(host='0.0.0.0', port=7860)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164import osimport requestsfrom datetime import datetime, timedelta, timezonefrom flask import Flask, request, Response, stream_with_context, render_template_stringapp = Flask(__name__)# 🔐 --- SECURE ENVIRONMENT VARIABLES ---API_KEY = os.environ.get("NVIDIA_API_KEY") or os.environ.get("YOUR_VEDIKA_API_KEY")MODEL_ID = os.environ.get("MODEL_ID", "google/diffusiongemma-26b-a4b-it") # Default fallback# NVIDIA's official invoke URLINVOKE_URL = "https://integrate.api.nvidia.com/v1/chat/completions"# 🔑 --- SERPAPI KEY (Provided by Divy Patel) ---SERPAPI_KEY = "df7dc67448cc9fe63ee6bbc7c20c50662ac18bc1f4682cd480da97bde1970381"# 🌐 --- SERPAPI GOOGLE SEARCH ENGINE (100% BULLETPROOF) --- 🌐def web_search_scraper(query, num_results=5):"""यह SerpApi का उपयोग करके सीधे Google Search से एकदम सटीक और ताज़ा (JSON) डेटा लाता है।इसे Hugging Face या Google कभी ब्लॉक नहीं कर सकता।"""results = []try:params = {"engine": "google","q": query,"api_key": SERPAPI_KEY,"num": num_results,"hl": "en","gl": "in" # India Region for local context}response = requests.get("https://serpapi.com/search", params=params, timeout=10)data = response.json()# 'organic_results' से असली Google सर्च का डेटा निकालनाif "organic_results" in data:for item in data["organic_results"]:title = item.get("title", "")link = item.get("link", "")snippet = item.get("snippet", "")if title and snippet:results.append({"title": title,"link": link,"snippet": snippet})except Exception as e:print(f"SerpApi Error: {e}")return results# ----------------------------------------------------@app.route('/')def home():try:with open('index.html', 'r', encoding='utf-8') as f:return render_template_string(f.read())except Exception as e:return f"<h1>System Error</h1><p>index.html missing: {str(e)}</p>"@app.route('/api/chat', methods=['POST'])def chat():if not API_KEY or not INVOKE_URL or not MODEL_ID:return Response("Server Error: Secrets missing. Check NVIDIA API Key.", status=500)data = request.get_json() or {}user_message = data.get("message", "")attachments = data.get("attachments", [])is_search = data.get("is_search", False)history = data.get("history", [])max_tokens = data.get("max_tokens", 4096)temperature = data.get("temperature", 1.0) # NVIDIA Recommended# 🕒 --- REAL-TIME IST INJECTION ---ist_time = datetime.now(timezone.utc) + timedelta(hours=5, minutes=30)current_date = ist_time.strftime("%A, %d %B %Y, %I:%M %p IST")# 🧠 --- GOD MODE SYSTEM PROMPT ---system_prompt = f"""You are CODE VED, an advanced AI System engineered EXCLUSIVELY by DIVY PATEL.Current Live Date and Time: {current_date}.STRICT DIRECTIVES:1. NEVER invent, guess, or hallucinate product launches, dates, news, or facts.2. If you receive "LIVE WEB SEARCH RESULTS", you MUST base your answer ENTIRELY on that data.3. Do NOT say "Based on the provided search results". Just answer naturally and confidently, citing the sources/links if needed."""# 🚀 --- AUTO-SEARCH INJECTION (USING SERPAPI) ---if is_search:scraped_data = web_search_scraper(user_message)search_context = "\n\n--- [LIVE VERIFIED GOOGLE SEARCH DATA] ---\n"if scraped_data:for idx, res in enumerate(scraped_data):search_context += f"{idx+1}. TITLE: {res['title']}\nSNIPPET: {res['snippet']}\nURL: {res['link']}\n\n"search_context += "[SYSTEM COMMAND: Use the above live Google data to answer the user accurately. Synthesize the info naturally without claiming you read it from a prompt.]"else:search_context += "[SYSTEM ALERT: Live search did not return results. Rely on your existing knowledge, but DO NOT hallucinate recent news.]"user_message = f"USER QUERY: {user_message}\n\n{search_context}"messages = [{"role": "system", "content": system_prompt}]for msg in history:role = msg.get("role", "user")content = msg.get("content", "")if content:messages.append({"role": role, "content": content})content_payload = []if user_message.strip():content_payload.append({"type": "text", "text": user_message})for att in attachments:att_type = att.get("type")b64_data = att.get("data")if att_type == "image":content_payload.append({"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{b64_data}"}})elif att_type in ["audio", "file"]:content_payload.append({"type": "input_audio", "input_audio": {"data": b64_data, "format": "wav"}})if not content_payload:content_payload.append({"type": "text", "text": "Hello"})messages.append({"role": "user", "content": content_payload})headers = {"Authorization": f"Bearer {API_KEY}","Accept": "text/event-stream"}# 🌟 --- NVIDIA FORMAT INTEGRATED ---payload = {"model": MODEL_ID,"messages": messages,"max_tokens": int(max_tokens),"temperature": float(temperature),"top_p": 0.95,"stream": True,"chat_template_kwargs": {"enable_thinking": True} # Thinking logic enabled}try:response = requests.post(INVOKE_URL, headers=headers, json=payload, stream=True)def generate():for line in response.iter_lines():if line:decoded_line = line.decode("utf-8")if decoded_line.startswith("data: "):yield decoded_line + "\n\n"return Response(stream_with_context(generate()), mimetype='text/event-stream')except Exception as e:return Response(f"Internal Error: {str(e)}", status=500)if __name__ == '__main__':app.run(host='0.0.0.0', port=7860)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837/* * ================================================================================ * CODE VED - GLOBAL STYLES & VARIABLES * Anthropic-like Clean, Professional & Responsive Design * ================================================================================ */
:root { /* Backgrounds */ --bg-main: #ffffff; --bg-sidebar: rgba(249, 250, 251, 0.92); --bg-user-msg: #f4f4f5; /* Text Colors */ --text-primary: #18181b; --text-secondary: #52525b; --text-tertiary: #a1a1aa; /* Borders & Shadows */ --border-light: rgba(0, 0, 0, 0.08); --border-focus: rgba(0, 0, 0, 0.15); --shadow-sm: 0 1px 3px rgba(0, 0, 0, 0.04); --shadow-md: 0 4px 16px rgba(0, 0, 0, 0.06); --shadow-lg: 0 12px 32px rgba(0, 0, 0, 0.08); /* Brand Colors */ --brand-color: #18181b; --brand-accent: #0f9e78; --brand-danger: #ef4444; --brand-warning: #f59e0b; --brand-success: #10b981; /* Typography */ --font-ui: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif; --font-code: 'JetBrains Mono', monospace; /* Radii */ --radius-sm: 8px; --radius-md: 12px; --radius-lg: 20px; /* Transitions */ --transition-default: 0.25s cubic-bezier(0.2, 0.8, 0.2, 1);}
/* * ================================================================================ * GLOBAL RESET & BASE STYLES * ================================================================================ */* { box-sizing: border-box; margin: 0; padding: 0; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; -webkit-touch-callout: none;}
/* Allow selection only in inputs and code */input, textarea, [contenteditable="true"], code, pre { -webkit-user-select: auto !important; -moz-user-select: auto !important; -ms-user-select: auto !important; user-select: auto !important;}
*:focus { outline: none !important; box-shadow: none !important; }
html, body { height: 100%; height: 100dvh; width: 100vw; font-family: var(--font-ui); color: var(--text-primary); display: flex; overflow: hidden; background: var(--bg-main); -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale;}
button, a { -webkit-tap-highlight-color: transparent; outline: none; }
button { background: none; border: none; cursor: pointer; color: inherit; font-family: inherit; }
input, textarea { font-family: inherit; outline: none; border: none; background: transparent; }
/* Custom Scrollbar */::-webkit-scrollbar { width: 6px; height: 6px; }::-webkit-scrollbar-track { background: transparent; }::-webkit-scrollbar-thumb { background: rgba(0,0,0,0.1); border-radius: 10px; }::-webkit-scrollbar-thumb:hover { background: rgba(0,0,0,0.2); }
/* * ================================================================================ * KEYFRAME ANIMATIONS * ================================================================================ */@keyframes fadeInUp { from { opacity: 0; transform: translateY(12px); } to { opacity: 1; transform: translateY(0); } }
@keyframes dropUpFade { from { opacity: 0; transform: translateY(10px) scale(0.96); } to { opacity: 1; transform: translateY(0) scale(1); } }
@keyframes modalFadeIn { from { opacity: 0; transform: scale(0.96); } to { opacity: 1; transform: scale(1); } }
@keyframes blinkCursor { 0%, 100% { opacity: 1; } 50% { opacity: 0; } }
@keyframes recordPulse { 0% { transform: scale(1); box-shadow: 0 0 0 0 rgba(239, 68, 68, 0.4); } 50% { transform: scale(1.05); box-shadow: 0 0 0 8px rgba(239, 68, 68, 0); } 100% { transform: scale(1); box-shadow: 0 0 0 0 rgba(239, 68, 68, 0); } }
.blinking-cursor { display: inline-block; width: 6px; height: 18px; background: var(--text-primary); margin-left: 2px; vertical-align: text-bottom; animation: blinkCursor 0.8s infinite; border-radius: 2px;}
/* * ================================================================================ * SIDEBAR & NAVIGATION * ================================================================================ */.btn-menu { position: absolute; top: 16px; left: 16px; z-index: 100; width: 40px; height: 40px; border-radius: 50%; display: flex; align-items: center; justify-content: center; background: rgba(255,255,255,0.8); backdrop-filter: blur(12px); -webkit-backdrop-filter: blur(12px); border: 1px solid var(--border-light); color: var(--text-secondary); transition: var(--transition-default);}
.btn-menu:hover { background: #fff; color: var(--text-primary); border-color: var(--border-focus);}
.sidebar { width: 280px; background: var(--bg-sidebar); backdrop-filter: blur(20px); -webkit-backdrop-filter: blur(20px); border-right: 1px solid var(--border-light); display: flex; flex-direction: column; transition: transform 0.3s cubic-bezier(0.2, 0.8, 0.2, 1); z-index: 110; height: 100%; flex-shrink: 0;}
.sidebar.collapsed { transform: translateX(-100%); position: absolute; }
.sidebar-header { padding: 20px 16px 10px; display: flex; align-items: center; justify-content: space-between; }
.sidebar-logo { font-weight: 600; font-size: 15px; display: flex; align-items: center; gap: 8px; letter-spacing: -0.3px;}
.btn-new-chat { margin: 10px 16px; display: flex; align-items: center; justify-content: center; gap: 8px; padding: 10px; border-radius: var(--radius-sm); background: #fff; border: 1px solid var(--border-light); font-size: 13.5px; font-weight: 500; transition: var(--transition-default); color: var(--text-primary); box-shadow: var(--shadow-sm);}
.btn-new-chat:hover { border-color: var(--border-focus); box-shadow: var(--shadow-md); }
.sidebar-history { flex: 1; overflow-y: auto; padding: 10px 12px; display: flex; flex-direction: column; gap: 2px; }
.history-header { display: flex; justify-content: space-between; align-items: center; padding: 4px 8px 8px; margin-bottom: 4px; }
.history-title-text { font-size: 11px; font-weight: 600; color: var(--text-tertiary); text-transform: uppercase; letter-spacing: 0.5px; }
.btn-clear-all { font-size: 11px; font-weight: 500; color: var(--text-tertiary); cursor: pointer; transition: 0.2s; padding: 4px 8px; border-radius: 6px;}
.btn-clear-all:hover { color: var(--brand-danger); background: rgba(239, 68, 68, 0.05);}
.history-item { padding: 9px 10px; border-radius: var(--radius-sm); font-size: 13px; font-weight: 400; color: var(--text-secondary); cursor: pointer; display: flex; justify-content: space-between; align-items: center; transition: 0.15s;}
.history-item:hover { background: rgba(0,0,0,0.04); color: var(--text-primary); }
.history-item.active { background: #fff; color: var(--text-primary); font-weight: 500; box-shadow: var(--shadow-sm); border: 1px solid var(--border-light);}
.history-text { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; flex: 1; }
.btn-delete-chat { background: none; border: none; color: var(--text-tertiary); cursor: pointer; padding: 4px; display: none; border-radius: 6px; }
.history-item:hover .btn-delete-chat { display: flex; }
.btn-delete-chat:hover { color: var(--brand-danger); background: #fee2e2; }
.sidebar-footer { padding: 16px; border-top: 1px solid var(--border-light); display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
.user-avatar { width: 34px; height: 34px; border-radius: 50%; background: var(--text-primary); color: #fff; display: flex; align-items: center; justify-content: center; font-size: 13px; font-weight: 600; flex-shrink: 0; }
.user-info-box { flex: 1; overflow: hidden; display: flex; flex-direction: column; }
.user-name { font-size: 13px; font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.user-sub { font-size: 11px; color: var(--text-tertiary); margin-top: 2px; }
.btn-login-register { background: var(--brand-color); color: #fff; border-radius: var(--radius-sm); padding: 7px 12px; font-size: 12px; font-weight: 500; cursor: pointer; transition: 0.2s; margin-left: auto; }
.btn-login-register:hover { background: #000; transform: translateY(-1px); }
.btn-power { width: 32px; height: 32px; border-radius: var(--radius-sm); display: flex; align-items: center; justify-content: center; color: var(--text-secondary); transition: 0.2s; }
.btn-power:hover { background: #fee2e2; color: var(--brand-danger); }
/* * ================================================================================ * MAIN CHAT AREA * ================================================================================ */.main-area { flex: 1; display: flex; flex-direction: column; position: relative; transition: 0.3s; height: 100%; overflow: hidden; z-index: 1; }
.chat-container { flex: 1; overflow-x: hidden; overflow-y: auto; padding: 80px 20px 200px; display: flex; flex-direction: column; align-items: center; scroll-behavior: smooth; }
.welcome-center { margin: auto; text-align: center; display: flex; flex-direction: column; align-items: center; animation: fadeInUp 0.6s ease; width: 100%; justify-content: center; flex: 1; }
.welcome-center img { width: 64px; height: 64px; border-radius: 16px; margin-bottom: 24px; object-fit: contain; }
.welcome-center h1 { font-size: 28px; font-weight: 500; letter-spacing: -0.5px; color: var(--text-primary); margin-bottom: 8px; }
.welcome-center p { font-size: 15px; color: var(--text-secondary); font-weight: 400;}
#chatMessages { width: 100%; display: flex; flex-direction: column; align-items: center; }
.message-wrapper { width: 100%; max-width: 800px; margin-bottom: 32px; display: flex; flex-direction: column; animation: fadeInUp 0.3s ease; }
/* User Message */.user-message { align-self: flex-end; max-width: 85%; background: var(--bg-user-msg); padding: 12px 18px; border-radius: 18px 18px 4px 18px; font-size: 15px; font-weight: 400; line-height: 1.5; color: var(--text-primary); word-wrap: break-word; overflow-wrap: break-word; border: 1px solid rgba(0,0,0,0.04);}
/* Bot Message */.bot-message { align-self: flex-start; max-width: 100%; display: flex; gap: 16px; width: 100%; box-sizing: border-box; background: transparent; padding: 0; }
.bot-avatar { width: 30px; height: 30px; border-radius: 8px; flex-shrink: 0; overflow: hidden; display: flex; align-items: center; justify-content: center; margin-top: 4px; border: 1px solid var(--border-light); background: #fff;}
.bot-avatar img { width: 100%; height: 100%; object-fit: cover; }
.bot-content-wrapper { flex: 1 1 0%; min-width: 0; max-width: calc(100% - 46px); width: 100%; overflow: hidden; }
.bot-content { font-size: 15.5px; line-height: 1.7; color: var(--text-primary); word-wrap: break-word; font-weight: 400; letter-spacing: 0.1px; }
.bot-content p { margin-bottom: 16px; }.bot-content p:last-child { margin-bottom: 0; }.bot-content strong { font-weight: 600; color: #000; }.bot-content ul, .bot-content ol { padding-left: 24px; margin-bottom: 16px; }.bot-content li { margin-bottom: 8px; }
.bot-content code { font-family: var(--font-code); background: rgba(0,0,0,0.06); padding: 3px 6px; border-radius: 6px; font-size: 0.85em; color: #000; }
.bot-content pre { background: #0d1117; padding: 16px; border-radius: var(--radius-md); overflow-x: auto; margin: 16px 0; border: 1px solid var(--border-light); position: relative; }
.bot-content pre code { background: none; padding: 0; color: #e2e8f0; font-size: 13.5px; }
.bot-content table { width: 100%; border-collapse: collapse; margin: 16px 0; font-size: 14px; border: 1px solid var(--border-light); border-radius: 8px; overflow: hidden; display: block; overflow-x: auto; }
.bot-content th, .bot-content td { border: 1px solid var(--border-light); padding: 10px 14px; text-align: left; }
.bot-content th { background: rgba(0,0,0,0.03); font-weight: 500; }
.mjx-container { max-width: 100%; overflow-x: auto; overflow-y: hidden; }
/* Attachments */.chat-attachment-container { display: flex; flex-wrap: wrap; gap: 8px; margin-bottom: 12px; }.chat-file-pill { display: inline-flex; align-items: center; gap: 8px; background: #fff; border: 1px solid var(--border-light); padding: 8px 12px; border-radius: 10px; font-size: 12.5px; font-weight: 500; }.chat-img-preview { max-width: 140px; max-height: 140px; border-radius: var(--radius-md); object-fit: cover; border: 1px solid var(--border-light); }
/* Thinking Box */.qwen-think-box { border-left: 2px solid #e4e4e7; padding-left: 16px; margin-bottom: 16px; transition: 0.3s; }.qwen-think-box summary { font-size: 12.5px; font-weight: 500; color: var(--text-tertiary); cursor: pointer; list-style: none; display: flex; align-items: center; gap: 8px; user-select: none; }.qwen-think-box summary::-webkit-details-marker { display: none; }.qwen-think-content { margin-top: 8px; font-size: 14px; color: var(--text-secondary); font-style: italic; white-space: pre-wrap; line-height: 1.6; }
/* Message Actions */.msg-actions { display: flex; gap: 4px; margin-top: 12px; opacity: 0; transition: 0.2s; align-items: center; }.message-wrapper:hover .msg-actions { opacity: 1; }@media (hover: none) { .msg-actions { opacity: 1; } }
.action-btn { display: flex; align-items: center; gap: 5px; font-size: 12px; font-weight: 500; color: var(--text-tertiary); padding: 6px 10px; border-radius: 8px; transition: 0.2s; background: transparent; }.action-btn:hover { color: var(--text-primary); background: rgba(0,0,0,0.04); }.action-btn.listen-btn { background: #f4f4f5; }.action-btn.listen-btn:hover { background: #e4e4e7; }
.code-copy-btn { position: absolute; top: 8px; right: 8px; display: flex; align-items: center; gap: 4px; padding: 4px 8px; font-size: 11px; color: var(--text-secondary); background: rgba(255,255,255,0.1); border: 1px solid rgba(255,255,255,0.1); border-radius: 6px; cursor: pointer; z-index: 2; backdrop-filter: blur(4px); }.code-copy-btn:hover { background: rgba(255,255,255,0.2); color: #fff; }.code-copy-btn.copied { color: var(--brand-success); border-color: var(--brand-success); }
.btn-scroll-bottom { position: absolute; bottom: 120px; left: 50%; transform: translateX(-50%) translateY(20px); width: 36px; height: 36px; border-radius: 50%; background: #fff; border: 1px solid var(--border-light); box-shadow: var(--shadow-md); display: flex; align-items: center; justify-content: center; color: var(--text-secondary); opacity: 0; pointer-events: none; transition: 0.3s; z-index: 45; }
.btn-scroll-bottom.visible { opacity: 1; pointer-events: auto; transform: translateX(-50%) translateY(0); }
/* * ================================================================================ * INPUT DOCK (The Core UI - Clean & Professional) * ================================================================================ */.input-dock { position: absolute; bottom: 24px; left: 50%; transform: translateX(-50%); width: 100%; max-width: 800px; padding: 0 20px; z-index: 50; display: flex; flex-direction: column; align-items: center;}
.loc-toast { display: none; align-items: center; gap: 6px; font-size: 12px; font-weight: 500; color: var(--text-secondary); margin-bottom: 12px; background: #fff; padding: 6px 14px; border-radius: 16px; border: 1px solid var(--border-light); box-shadow: var(--shadow-md); }
.input-dock-wrapper { position: relative; width: 100%; background: rgba(255, 255, 255, 0.85); backdrop-filter: blur(20px); -webkit-backdrop-filter: blur(20px); border: 1px solid var(--border-light); border-radius: var(--radius-lg); padding: 12px 16px; display: flex; flex-direction: column; transition: all 0.25s cubic-bezier(0.2, 0.8, 0.2, 1); box-shadow: var(--shadow-md);}
/* Expanded State (No RGB Glow, just crisp shadow & border) */.input-dock-wrapper.expanded { background: rgba(255, 255, 255, 0.98); border-color: var(--border-focus); transform: translateY(-2px); box-shadow: var(--shadow-lg);}
.file-preview-bar { display: none; padding-bottom: 10px; align-items: center; gap: 8px; }.file-preview-bar.active { display: flex; }.file-preview-pill { display: flex; align-items: center; gap: 8px; background: #f4f4f5; padding: 6px 12px; border-radius: 10px; font-size: 12px; border: 1px solid var(--border-light); }.file-preview-icon { width: 16px; height: 16px; object-fit: cover; border-radius: 4px; }.file-preview-name { max-width: 120px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; color: var(--text-primary); }.btn-remove-file { width: 18px; height: 18px; border-radius: 50%; background: #e4e4e7; display: flex; align-items: center; justify-content: center; transition: 0.2s; }.btn-remove-file:hover { background: #d4d4d8; }
.chat-input { width: 100%; padding: 8px 4px 12px; font-size: 15px; font-weight: 400; resize: none; color: var(--text-primary); line-height: 1.5; background: transparent; caret-color: #000; min-height: 24px; max-height: 200px; transition: min-height 0.25s cubic-bezier(0.2, 0.8, 0.2, 1);}
.chat-input::placeholder { color: var(--text-tertiary); font-weight: 400; }
.input-dock-wrapper.expanded .chat-input { min-height: 60px;}
.input-row { display: flex; align-items: center; justify-content: space-between; width: 100%; margin-top: 4px; }
.tools-left { display: flex; gap: 2px; align-items: center; position: relative; }
.tool-btn { width: 34px; height: 34px; border-radius: 50%; display: flex; align-items: center; justify-content: center; color: var(--text-secondary); transition: 0.2s; background: transparent; flex-shrink: 0; }.tool-btn:hover { background: #f4f4f5; color: var(--text-primary); }
/* Tool Active States */.tool-btn.active-env { color: #fff; background: var(--brand-accent); }.tool-btn.active-think-low { color: #fff; background: var(--brand-danger); }.tool-btn.active-think-medium { color: #fff; background: var(--brand-warning); }.tool-btn.active-think-high { color: #fff; background: #8b5cf6; }.tool-btn.active-search { color: #fff; background: #16803c; }
.btn-mic.recording { color: var(--brand-danger); background: #fee2e2; animation: recordPulse 1.5s infinite; }
.tools-right { display: flex; align-items: center; gap: 8px; }
.btn-send { width: 34px; height: 34px; border-radius: 50%; background: var(--brand-color); color: #fff; display: flex; align-items: center; justify-content: center; transition: 0.2s; flex-shrink: 0; }.btn-send:hover:not(:disabled) { background: #000; transform: scale(1.05); }.btn-send:disabled { background: #e4e4e7; color: #a1a1aa; cursor: not-allowed; }
.btn-stop { width: 34px; height: 34px; border-radius: 50%; background: #fee2e2; color: var(--brand-danger); display: none; align-items: center; justify-content: center; transition: 0.25s; flex-shrink: 0; }.btn-stop.active { display: flex; }.btn-stop:hover { background: #fecaca; }
.hidden-input { display: none; }
/* Dropdowns */.dropdown-menu { position: absolute; bottom: calc(100% + 12px); left: 0; background: rgba(255, 255, 255, 0.98); backdrop-filter: blur(20px); border: 1px solid var(--border-light); border-radius: 14px; padding: 6px; box-shadow: var(--shadow-lg); display: none; flex-direction: column; min-width: 200px; z-index: 100; transform-origin: bottom left; }
.dropdown-menu.active { display: flex; animation: dropUpFade 0.2s cubic-bezier(0.2, 0.8, 0.2, 1); }
.dropdown-header { padding: 8px 12px; font-size: 11px; font-weight: 600; color: var(--text-tertiary); text-transform: uppercase; letter-spacing: 0.5px; margin-bottom: 4px; }
.dropdown-item { padding: 9px 12px; border-radius: 8px; font-size: 13px; display: flex; align-items: center; justify-content: space-between; gap: 8px; cursor: pointer; transition: 0.15s; color: var(--text-primary); }.dropdown-item:hover { background: #f4f4f5; }.dropdown-item.selected { background: #f4f4f5; font-weight: 500; }
/* * ================================================================================ * MODALS & OVERLAYS * ================================================================================ */.mobile-overlay { display: none; position: fixed; inset: 0; background: rgba(0,0,0,0.2); backdrop-filter: blur(4px); z-index: 95; opacity: 0; transition: 0.3s ease; pointer-events: none; }.mobile-overlay.active { display: block; opacity: 1; pointer-events: all; }
.auth-overlay { position: fixed; inset: 0; background: rgba(0,0,0, 0.3); backdrop-filter: blur(8px); display: none; align-items: center; justify-content: center; z-index: 2000; }.auth-modal { background: #ffffff; width: 90%; max-width: 360px; border-radius: 20px; padding: 32px; box-shadow: 0 20px 50px rgba(0,0,0, 0.15); position: relative; animation: modalFadeIn 0.3s cubic-bezier(0.2, 0.8, 0.2, 1); border: 1px solid var(--border-light); }.auth-close { position: absolute; top: 16px; right: 16px; color: var(--text-tertiary); width: 32px; height: 32px; display: flex; align-items: center; justify-content: center; border-radius: 50%; background: #f4f4f5; transition: 0.2s; }.auth-close:hover { background: #e4e4e7; color: var(--text-primary); }.auth-title { font-size: 18px; font-weight: 600; margin-bottom: 24px; text-align: center; letter-spacing: -0.3px; }.auth-tabs { display: flex; background: #f4f4f5; border-radius: 10px; padding: 4px; margin-bottom: 20px; }.auth-tab { flex: 1; text-align: center; padding: 8px; font-size: 13px; font-weight: 500; cursor: pointer; border-radius: 8px; color: var(--text-secondary); transition: 0.2s; }.auth-tab.active { background: #ffffff; color: #000; box-shadow: 0 1px 3px rgba(0,0,0,0.05); }.auth-input { width: 100%; padding: 12px 14px; border: 1px solid var(--border-light); border-radius: 10px; font-size: 14px; margin-bottom: 12px; background: #fcfcfc; transition: 0.2s; }.auth-input:focus { border-color: var(--text-primary); background: #fff; }.auth-btn { width: 100%; padding: 12px; background: var(--brand-color); color: #fff; font-size: 14px; font-weight: 500; border-radius: 10px; transition: 0.2s; }.auth-btn:hover { background: #000; }.auth-phase { display: none; }.auth-phase.active { display: block; }.auth-message { font-size: 12px; text-align: center; margin-top: 12px; min-height: 16px; }
.custom-confirm-overlay { position: fixed; inset: 0; background: rgba(0,0,0,0.3); backdrop-filter: blur(8px); display: none; align-items: center; justify-content: center; z-index: 2500; }.custom-confirm-box { background: #fff; border-radius: 16px; padding: 24px; max-width: 300px; width: 90%; text-align: center; box-shadow: 0 20px 50px rgba(0,0,0,0.15); animation: modalFadeIn 0.2s; border: 1px solid var(--border-light); }.custom-confirm-msg { font-size: 14px; margin-bottom: 24px; color: var(--text-primary); font-weight: 500; line-height: 1.5; }.custom-confirm-btns { display: flex; gap: 12px; }.custom-confirm-btn { flex: 1; padding: 10px; border-radius: 10px; font-size: 13px; font-weight: 500; transition: 0.2s; }.custom-confirm-btn.cancel { background: #f4f4f5; color: var(--text-secondary); }.custom-confirm-btn.cancel:hover { background: #e4e4e7; }.custom-confirm-btn.confirm { background: var(--brand-danger); color: #fff; }.custom-confirm-btn.confirm:hover { background: #dc2626; }
/* * ================================================================================ * RESPONSIVE DESIGN * ================================================================================ */@media (max-width: 900px) { .sidebar { position: fixed; left: 0; top: 0; box-shadow: 4px 0 24px rgba(0,0,0,0.05); } .sidebar.collapsed { box-shadow: none; } .input-dock { padding: 10px 16px calc(16px + env(safe-area-inset-bottom)); bottom: 0; } .chat-container { padding: 70px 16px 180px; } .user-message { max-width: 90%; }}
@media (max-width: 600px) { .code-copy-btn span { display: none; } .welcome-center img { width: 56px; height: 56px; } .welcome-center h1 { font-size: 24px; } .tool-btn, .btn-send, .btn-stop { width: 36px; height: 36px; } .input-dock-wrapper.expanded .chat-input { min-height: 50px; } /* Prevents iOS zoom on focus */ .chat-input { font-size: 16px; } }3 unmodified lines4567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642653 unmodified lines<meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover"><title>CODE VED | Engineered by Divy Patel</title><!-- Favicon --><link rel="icon" type="image/webp" id="faviconLink"><!-- Google Fonts --><link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin><link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet"><!-- External Libraries CSS --><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/github-dark.min.css"><!-- Custom CSS (Placeholder for next step) --><link rel="stylesheet" href="css/style.css"></head><body oncontextmenu="return false;"><!-- Top Left Menu Button --><button class="btn-menu" id="btnMenuOpen"><svg style="width:20px;height:20px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="4" y1="9" x2="20" y2="9"></line><line x1="4" y1="15" x2="14" y2="15"></line></svg></button><!-- Mobile Overlay for Sidebar --><div class="mobile-overlay" id="mobileOverlay"></div><!-- Sidebar --><aside class="sidebar collapsed" id="sidebar"><div class="sidebar-header"><div class="sidebar-logo"><img id="sidebarLogoImg" alt="CODE VED" style="width:24px;height:24px;border-radius:6px;object-fit:contain;"><span>CODE VED</span></div><button class="btn-menu btn-close-sidebar" id="btnCloseSidebar" style="position:static; width:32px; height:32px; box-shadow:none; border:none; background:transparent;"><svg style="width:18px;height:18px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg></button></div><button class="btn-new-chat" id="btnNewChat"><svg style="width:16px; height:16px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"></path></svg>New Workspace</button><div class="sidebar-history" id="chatHistory"></div><div class="sidebar-footer"><div class="user-avatar" id="uAv">G</div><div class="user-info-box"><div class="user-name" id="uName">Guest Session</div><div class="user-sub" id="uSub">Queries: 0/10</div></div><button class="btn-login-register" id="btnLoginRegister">Access</button><button class="btn-power" id="btnDeleteAcc" style="display:none;" title="Delete Account"><svg style="width:16px;height:16px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M3 6h18M19 6v14a2 2 0 01-2 2H7a2 2 0 01-2-2V6m3 0V4a2 2 0 012-2h4a2 2 0 012 2v2"></path></svg></button><button class="btn-power" id="btnLogout" style="display:none;" title="Logout"><svg style="width:16px;height:16px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M18.36 6.64a9 9 0 1 1-12.73 0"></path><line x1="12" y1="2" x2="12" y2="12"></line></svg></button></div></aside><!-- Main Chat Area --><main class="main-area"><div class="chat-container" id="chatContainer"><div class="welcome-center" id="welcomeScreen"><img id="welcomeLogoImg" alt="CODE VED"><h1 id="welcomeTitle">Hello, Guest!</h1><p id="welcomeGreeting">How can I help you today?</p></div><div id="chatMessages"></div></div><button id="scrollToBottomBtn" class="btn-scroll-bottom"><svg style="width:18px;height:18px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="12" y1="5" x2="12" y2="19"></line><polyline points="19 12 12 19 5 12"></polyline></svg></button><!-- Input Dock --><div class="input-dock" id="inputDock"><div class="input-dock-wrapper" id="dockWrapper"><div class="loc-toast" id="locStatus"></div><div class="file-preview-bar" id="filePreviewBar"><div class="file-preview-pill"><img id="imgPreview" class="file-preview-icon" src="" style="display:none;"><svg id="docPreview" style="display:none; width:14px; height:14px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path><polyline points="14 2 14 8 20 8"></polyline></svg><div class="file-preview-name" id="fileName">doc.pdf</div><button class="btn-remove-file" id="btnRemoveFile"><svg style="width:12px;height:12px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg></button></div></div><textarea class="chat-input" id="mainInput" placeholder="Ask CODE VED..." rows="1"></textarea><div class="input-row"><div class="tools-left"><div style="position: relative;"><button class="tool-btn" id="btnAttach" title="Attach File"><svg style="width:20px;height:20px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"></path></svg></button><!-- Attach Dropdown --><div class="dropdown-menu" id="attachMenu"><div class="dropdown-item" id="optUploadImg"><svg style="width:16px;height:16px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect><circle cx="8.5" cy="8.5" r="1.5"></circle><polyline points="21 15 16 10 5 21"></polyline></svg>Upload Image</div><div class="dropdown-item" id="optUploadDoc"><svg style="width:16px;height:16px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path><polyline points="14 2 14 8 20 8"></polyline></svg>Upload Document</div><div style="height:1px; background:var(--border-light); margin:4px 0;"></div><div class="dropdown-item" id="optEnv"><svg style="width:16px;height:16px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"></circle><line x1="2" y1="12" x2="22" y2="12"></line><path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"></path></svg>GPS & Weather</div><div class="dropdown-item" id="optThink"><svg style="width:16px;height:16px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 2a5 5 0 0 0-5 5v2a5 5 0 0 0 10 0V7a5 5 0 0 0-5-5z"></path><path d="M8 14H6a2 2 0 0 0-2 2v4a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-4a2 2 0 0 0-2-2h-2"></path></svg>Thinking Mode</div><div class="dropdown-item" id="optVoice"><svg style="width:16px;height:16px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5"></polygon><path d="M19.07 4.93a10 10 0 0 1 0 14.14M15.54 8.46a5 5 0 0 1 0 7.07"></path></svg>Select Voice</div></div><!-- Voice Dropdown --><div class="dropdown-menu" id="voiceMenu" style="min-width: 220px; left: 45px; bottom: 40px; max-height: 300px; overflow-y: auto;"><div class="dropdown-header">Premium Voices</div><div id="voiceOptionsList"></div><div style="height:1px; background:var(--border-light); margin:4px 0;"></div><div class="dropdown-header">Language</div><div id="languageOptionsList"></div></div><!-- Thinking Dropdown --><div class="dropdown-menu" id="thinkMenu" style="min-width: 180px; left: 45px; bottom: 40px;"><div class="dropdown-header">Reasoning Effort</div><div class="dropdown-item" data-effort="low">⚡ Low (Fast)</div><div class="dropdown-item" data-effort="medium">🧠 Medium (Balanced)</div><div class="dropdown-item" data-effort="high">🔍 High (Deep logic)</div><div style="height:1px; background:var(--border-light); margin:4px 0;"></div><div class="dropdown-item" id="optDisableThink" style="color:var(--brand-danger);">❌ Disable Thinking</div></div><!-- Hidden File Inputs --><input type="file" id="imgUpload" class="hidden-input" accept="image/*"><input type="file" id="docUpload" class="hidden-input" accept=".pdf,.txt,.docx,.html,.js,.py,.css,.cpp,.c,.json,.md"></div><button class="tool-btn" id="btnSearch" title="Web Search"><svg style="width:18px;height:18px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="8"></circle><line x1="21" y1="21" x2="16.65" y2="16.65"></line></svg></button><button class="tool-btn btn-mic" id="btnStt" title="Voice Typing"><svg style="width:18px;height:18px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3z"></path><path d="M19 10v2a7 7 0 0 1-14 0v-2"></path><line x1="12" y1="19" x2="12" y2="23"></line><line x1="8" y1="23" x2="16" y2="23"></line></svg></button></div><div class="tools-right"><button class="btn-stop" id="btnStop"><svg style="width:14px;height:14px;" viewBox="0 0 24 24" fill="currentColor"><rect x="6" y="6" width="12" height="12" rx="2"></rect></svg></button><button class="btn-send" id="btnSend"><svg style="width:18px;height:18px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="12" y1="19" x2="12" y2="5"></line><polyline points="5 12 12 5 19 12"></polyline></svg></button></div></div></div></div></main><!-- Auth Modal --><div class="auth-overlay" id="authModal"><div class="auth-modal"><button class="auth-close" id="btnAuthClose"><svg style="width:18px;height:18px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg></button><div class="auth-title">System Access</div><div class="auth-tabs"><div class="auth-tab active" id="tabLogin" data-tab="login">Login</div><div class="auth-tab" id="tabRegister" data-tab="register">Register</div></div><!-- Login Flow --><div id="flowLogin"><div class="auth-phase active" id="loginPhase1"><input type="email" class="auth-input" id="logEmail" placeholder="Email Address"><button class="auth-btn" id="btnLogOtp">Continue</button></div><div class="auth-phase" id="loginPhase2"><input type="number" class="auth-input" id="logOtp" placeholder="Enter OTP"><button class="auth-btn" id="btnLogVerify">Verify</button></div></div><!-- Register Flow --><div id="flowRegister" style="display:none;"><div class="auth-phase active" id="regPhase1"><input type="text" class="auth-input" id="regName" placeholder="Full Name"><input type="email" class="auth-input" id="regEmail" placeholder="Email Address"><button class="auth-btn" id="btnRegOtp">Create Account</button></div><div class="auth-phase" id="regPhase2"><input type="number" class="auth-input" id="regOtp" placeholder="Enter OTP"><button class="auth-btn" id="btnRegVerify">Verify</button></div></div><div class="auth-message" id="authMsg"></div></div></div><!-- Custom Confirm Overlay --><div class="custom-confirm-overlay" id="customConfirmOverlay"><div class="custom-confirm-box"><div class="custom-confirm-msg" id="customConfirmMsg"></div><div class="custom-confirm-btns"><button class="custom-confirm-btn cancel" id="customConfirmCancel">Cancel</button><button class="custom-confirm-btn confirm" id="customConfirmOk">Confirm</button></div></div></div><!-- External Libraries JS --><script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/mammoth/1.6.0/mammoth.browser.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/marked/12.0.1/marked.min.js"></script><script src="https://cdn.jsdelivr.net/npm/mermaid@10/dist/mermaid.min.js"></script><!-- MathJax Configuration --><script>window.MathJax = {tex: {inlineMath: [['$', '$'], ['\\(', '\\)']],displayMath: [['$$', '$$'], ['\\[', '\\]']],processEscapes: true,packages: { '[+]': ['mhchem', 'physics', 'cancel', 'color', 'amsmath', 'amssymb', 'boldsymbol'] }},loader: {load: ['[tex]/mhchem', '[tex]/physics', '[tex]/cancel', '[tex]/color', '[tex]/amsmath', '[tex]/amssymb', '[tex]/boldsymbol']},options: {skipHtmlTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code'],ignoreHtmlClass: 'tex2jax_ignore',processHtmlClass: 'tex2jax_process'},startup: { typeset: false }};</script><script id="MathJax-script" async src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script><!-- Custom Modular JS Files (Placeholders for next steps) --><!-- Markdown Renderer must be loaded before main script --><script type="module" src="js/markdownRenderer.js"></script><script type="module" src="js/script.js"></script></body></html>3 unmodified lines4567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199203 unmodified lines<meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover"><title>CODE VED | Engineered by Divy Patel</title><meta name="description" content="CODE VED - 202 Billion Parameter Enterprise AI System"><!-- Premium Fonts --><link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin><link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet"><!-- Syntax Highlighting & Parsers --><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/github.min.css"><script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/mammoth/1.6.0/mammoth.browser.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/marked/12.0.1/marked.min.js"></script><style>:root {/* Clean Minimalist Light Theme */--bg-main: #ffffff;--bg-sidebar: #f9f9f9;--bg-input: #f4f4f4;--bg-hover: #ebebeb;--text-primary: #0f0f0f;--text-secondary: #606060;--text-tertiary: #8e8e8e;--border-light: #e5e5e5;--border-focus: #d0d0d0;--brand-color: #1a1a1a;--brand-accent: #0066cc; /* Tool Calling Color */--font-ui: 'Inter', sans-serif;--font-code: 'JetBrains Mono', monospace;--radius-sm: 8px;--radius-md: 12px;--radius-lg: 24px;}* { box-sizing: border-box; margin: 0; padding: 0; }/* 📱 MOBILE BUG FIX: Using 100dvh to prevent input dock from hiding behind browser URL bar */html, body {height: 100%; height: 100dvh; width: 100vw;font-family: var(--font-ui); background-color: var(--bg-main); color: var(--text-primary);display: flex; overflow: hidden; -webkit-font-smoothing: antialiased;}button { background: none; border: none; cursor: pointer; color: inherit; font-family: inherit; }input, textarea { font-family: inherit; outline: none; border: none; background: transparent; }/* Custom Scrollbar */::-webkit-scrollbar { width: 6px; height: 6px; }::-webkit-scrollbar-track { background: transparent; }::-webkit-scrollbar-thumb { background: #d4d4d4; border-radius: 10px; }::-webkit-scrollbar-thumb:hover { background: #a0a0a0; }/* --- 1. SIDEBAR (Restored History & Power Button) --- */.sidebar {width: 260px; background-color: var(--bg-sidebar); border-right: 1px solid var(--border-light);display: flex; flex-direction: column; transition: transform 0.3s ease, width 0.3s ease; z-index: 100;height: 100%; flex-shrink: 0;}.sidebar.collapsed { margin-left: -260px; }.sidebar-header { padding: 16px; display: flex; align-items: center; justify-content: space-between; }.btn-new-chat {display: flex; align-items: center; justify-content: center; gap: 8px; width: 100%; padding: 10px 12px;border-radius: var(--radius-sm); background: #fff; border: 1px solid var(--border-light);font-size: 14px; font-weight: 500; transition: 0.2s; box-shadow: 0 1px 2px rgba(0,0,0,0.02);}.btn-new-chat:hover { background: var(--bg-hover); color: #000; border-color: #ccc; }.sidebar-history { flex: 1; overflow-y: auto; padding: 10px; }.history-item { padding: 10px; border-radius: var(--radius-sm); font-size: 13px; color: var(--text-secondary); cursor: pointer; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; margin-bottom: 4px; transition: 0.2s;}.history-item:hover { background: var(--border-light); color: var(--text-primary); }.sidebar-footer { padding: 16px; border-top: 1px solid var(--border-light); display: flex; align-items: center; gap: 12px; transition: background 0.2s; }.user-avatar { width: 34px; height: 34px; border-radius: 50%; background: var(--brand-color); color: #fff; display: flex; align-items: center; justify-content: center; font-size: 15px; font-weight: 600; flex-shrink: 0; }.user-info-box { flex: 1; overflow: hidden; }.user-name { font-size: 14px; font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; color: var(--text-primary); }.user-sub { font-size: 11px; font-weight: 500; color: var(--text-tertiary); margin-top: 2px; }.btn-power {width: 32px; height: 32px; border-radius: var(--radius-sm); display: flex; align-items: center; justify-content: center;color: var(--text-secondary); transition: 0.2s; cursor: pointer; border: 1px solid transparent; flex-shrink: 0;}.btn-power:hover { background: #ffe6e6; color: #cc0000; border-color: #ffcccc; }/* --- 2. MAIN WORKSPACE AREA --- */.main-area { flex: 1; display: flex; flex-direction: column; position: relative; background: var(--bg-main); transition: 0.3s; height: 100%; overflow: hidden; }.top-bar { padding: 12px 20px; display: flex; align-items: center; justify-content: space-between; background: var(--bg-main); z-index: 10; flex-shrink: 0; border-bottom: 1px solid transparent; transition: border 0.3s; }.top-bar.scrolled { border-bottom: 1px solid var(--border-light); }.btn-icon { width: 32px; height: 32px; border-radius: var(--radius-sm); display: flex; align-items: center; justify-content: center; color: var(--text-secondary); transition: 0.2s; }.btn-icon:hover { background: var(--bg-hover); color: var(--text-primary); }.btn-icon svg { width: 18px; height: 18px; }.model-selector { font-size: 14px; font-weight: 600; color: var(--text-secondary); display: flex; align-items: center; gap: 6px; }/* --- 3. CHAT CONTAINER --- */.chat-container { flex: 1; overflow-y: auto; padding: 20px 20px 40px; display: flex; flex-direction: column; align-items: center; scroll-behavior: smooth; }/* Restored Welcome Screen */.welcome-center { margin: auto; text-align: center; display: flex; flex-direction: column; align-items: center; animation: fadeIn 0.5s ease; }.welcome-center img { width: 70px; height: 70px; border-radius: 18px; margin-bottom: 24px; box-shadow: 0 4px 12px rgba(0,0,0,0.05); }.welcome-center h1 { font-size: 26px; font-weight: 500; color: var(--text-primary); margin-bottom: 8px; letter-spacing: -0.5px; }.welcome-center p { font-size: 14px; color: var(--text-secondary); }.message-wrapper { width: 100%; max-width: 760px; margin-bottom: 32px; display: flex; flex-direction: column; }.user-message { align-self: flex-end; max-width: 85%; background: var(--bg-input); padding: 12px 18px; border-radius: 20px 20px 4px 20px; font-size: 15px; line-height: 1.5; color: var(--text-primary); border: 1px solid var(--border-light); }.bot-message { align-self: flex-start; max-width: 100%; display: flex; gap: 16px; width: 100%; }.bot-avatar { width: 28px; height: 28px; border-radius: 6px; flex-shrink: 0; overflow: hidden; border: 1px solid var(--border-light); }.bot-avatar img { width: 100%; height: 100%; object-fit: cover; }.bot-content { flex: 1; font-size: 15.5px; line-height: 1.6; color: var(--text-primary); min-width: 0; }/* Markdown Styling */.bot-content p { margin-bottom: 16px; }.bot-content p:last-child { margin-bottom: 0; }.bot-content strong { font-weight: 600; color: #000; }.bot-content code { font-family: var(--font-code); background: var(--bg-input); padding: 2px 6px; border-radius: 4px; font-size: 0.9em; color: #d63384; }.bot-content pre { background: #f6f8fa; padding: 16px; border-radius: var(--radius-sm); border: 1px solid var(--border-light); overflow-x: auto; margin: 16px 0; }.bot-content pre code { background: none; padding: 0; color: inherit; font-size: 14px; }.chat-attachment { display: inline-flex; align-items: center; gap: 8px; background: #fff; border: 1px solid var(--border-light); padding: 6px 12px; border-radius: var(--radius-md); font-size: 13px; font-weight: 500; margin-bottom: 10px; box-shadow: 0 1px 3px rgba(0,0,0,0.05); }.chat-img-preview { max-width: 250px; border-radius: var(--radius-md); border: 1px solid var(--border-light); margin-bottom: 10px; }/* --- 4. GOOGLE SEARCH TOOL UI --- */.tool-indicator { display: inline-flex; align-items: center; gap: 8px; font-size: 13px; font-weight: 500; color: var(--brand-accent); background: rgba(0, 102, 204, 0.05); padding: 8px 14px; border-radius: var(--radius-sm); margin-bottom: 16px; border: 1px solid rgba(0, 102, 204, 0.2); transition: 0.3s; }.tool-indicator.active { animation: pulseGlow 2s infinite alternate; }.tool-indicator svg { width: 16px; height: 16px; }.tool-indicator.active svg { animation: spin 2s linear infinite; }@keyframes pulseGlow { 0% { box-shadow: 0 0 0 rgba(0, 102, 204, 0); border-color: rgba(0, 102, 204, 0.2); } 100% { box-shadow: 0 0 12px rgba(0, 102, 204, 0.3); border-color: rgba(0, 102, 204, 0.5); } }@keyframes spin { 100% { transform: rotate(360deg); } }/* --- 5. FIXED INPUT DOCK (MOBILE SAFE) --- */.input-dock { flex-shrink: 0; padding: 15px 20px 25px; background: var(--bg-main); border-top: 1px solid transparent; display: flex; justify-content: center; z-index: 20; width: 100%; transition: border 0.3s; }.input-dock.scrolled { border-top: 1px solid var(--border-light); }.input-container { width: 100%; max-width: 760px; background: var(--bg-input); border: 1px solid var(--border-light); border-radius: var(--radius-lg); padding: 8px 12px; display: flex; flex-direction: column; transition: 0.2s; position: relative; }.input-container:focus-within { border-color: var(--border-focus); background: #fff; box-shadow: 0 4px 20px rgba(0,0,0,0.05); }.file-preview-bar { display: none; padding: 8px 8px 12px; align-items: center; gap: 12px; border-bottom: 1px solid var(--border-light); margin-bottom: 8px; }.file-preview-bar.active { display: flex; }.file-preview-icon { width: 40px; height: 40px; border-radius: 8px; object-fit: cover; background: #fff; border: 1px solid var(--border-light); display: flex; align-items: center; justify-content: center; font-size: 18px; }.file-preview-name { flex: 1; font-size: 13px; font-weight: 500; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; color: var(--text-primary); }.btn-remove-file { width: 24px; height: 24px; border-radius: 50%; background: #ffe6e6; color: #cc0000; display: flex; align-items: center; justify-content: center; }.input-row { display: flex; align-items: flex-end; gap: 8px; width: 100%; }.tools-left { display: flex; gap: 4px; }.tool-btn { width: 34px; height: 34px; border-radius: 50%; display: flex; align-items: center; justify-content: center; color: var(--text-secondary); transition: 0.2s; position: relative; flex-shrink: 0; }.tool-btn:hover { background: #e5e5e5; color: var(--text-primary); }.tool-btn svg { width: 18px; height: 18px; }.tool-btn.recording { color: #e60000; animation: pulse 1.5s infinite; }.chat-input { flex: 1; padding: 7px 4px; font-size: 15px; resize: none; max-height: 120px; min-height: 24px; color: var(--text-primary); line-height: 1.5; }.chat-input::placeholder { color: var(--text-tertiary); }.btn-send { width: 34px; height: 34px; border-radius: 50%; background: var(--brand-color); color: #fff; display: flex; align-items: center; justify-content: center; transition: 0.2s; flex-shrink: 0; }.btn-send svg { width: 16px; height: 16px; transform: translateX(-1px); }.btn-send:hover { background: #000; transform: translateY(-1px); }.btn-send:disabled { background: #ccc; cursor: not-allowed; transform: none; }.hidden-input { display: none; }.dropdown-menu { position: absolute; bottom: 100%; left: 0; margin-bottom: 10px; background: #fff; border: 1px solid var(--border-light); border-radius: var(--radius-md); padding: 6px; box-shadow: 0 10px 25px rgba(0,0,0,0.1); display: none; flex-direction: column; gap: 2px; min-width: 180px; z-index: 100; }.dropdown-menu.active { display: flex; animation: fadeIn 0.2s; }.dropdown-item { padding: 10px 12px; border-radius: var(--radius-sm); font-size: 13px; font-weight: 500; display: flex; align-items: center; gap: 10px; cursor: pointer; transition: 0.2s; }.dropdown-item:hover { background: var(--bg-hover); }/* --- 6. SECURE AUTHENTICATION MODAL --- */.auth-overlay { position: fixed; inset: 0; background: rgba(0,0,0,0.4); backdrop-filter: blur(5px); display: none; align-items: center; justify-content: center; z-index: 2000; }.auth-modal { background: #fff; width: 90%; max-width: 400px; border-radius: var(--radius-md); padding: 32px; box-shadow: 0 20px 40px rgba(0,0,0,0.1); position: relative; }.auth-close { position: absolute; top: 16px; right: 16px; color: var(--text-secondary); width: 28px; height: 28px; display: flex; align-items: center; justify-content: center; border-radius: 50%; transition: 0.2s; }.auth-close:hover { background: var(--bg-hover); color: var(--text-primary); }.auth-title { font-size: 22px; font-weight: 600; margin-bottom: 24px; text-align: center; letter-spacing: -0.5px; }.auth-tabs { display: flex; background: var(--bg-input); border-radius: var(--radius-sm); padding: 4px; margin-bottom: 24px; }.auth-tab { flex: 1; text-align: center; padding: 8px; font-size: 13px; font-weight: 500; cursor: pointer; border-radius: 6px; color: var(--text-secondary); transition: 0.2s; }.auth-tab.active { background: #fff; color: var(--text-primary); box-shadow: 0 1px 3px rgba(0,0,0,0.05); }.auth-input-group { display: flex; flex-direction: column; gap: 12px; margin-bottom: 20px; }.auth-input { width: 100%; padding: 12px 14px; border: 1px solid var(--border-light); border-radius: var(--radius-sm); font-size: 14px; transition: 0.2s; }.auth-input:focus { border-color: var(--brand-color); outline: none; }.auth-btn { width: 100%; padding: 12px; background: var(--brand-color); color: #fff; font-size: 14px; font-weight: 500; border-radius: var(--radius-sm); transition: 0.2s; }.auth-btn:hover { background: #000; }.auth-btn:disabled { background: #ccc; cursor: not-allowed; }.auth-phase { display: none; }.auth-phase.active { display: flex; flex-direction: column; }.auth-message { font-size: 12px; color: #cc0000; text-align: center; margin-top: 10px; min-height: 18px; }/* --- 7. WORKSPACE RIGHT PANEL --- */.workspace-panel { width: 0; background: #fff; border-left: 1px solid var(--border-light); display: flex; flex-direction: column; transition: width 0.3s ease; overflow: hidden; box-shadow: -5px 0 20px rgba(0,0,0,0.02); z-index: 90; }.workspace-panel.active { width: 50%; }.ws-header { padding: 12px 20px; border-bottom: 1px solid var(--border-light); display: flex; justify-content: space-between; align-items: center; background: #fafafa; }.ws-tabs { display: flex; gap: 4px; background: #ebebeb; padding: 4px; border-radius: var(--radius-sm); }.ws-tab { padding: 6px 16px; font-size: 13px; font-weight: 500; border-radius: 6px; cursor: pointer; color: var(--text-secondary); transition: 0.2s; }.ws-tab.active { background: #fff; color: var(--text-primary); box-shadow: 0 1px 3px rgba(0,0,0,0.05); }.ws-actions { display: flex; gap: 8px; }.ws-btn { padding: 6px; border-radius: var(--radius-sm); color: var(--text-secondary); transition: 0.2s; }.ws-btn:hover { background: #ebebeb; color: var(--text-primary); }.ws-content { flex: 1; overflow: hidden; position: relative; }.ws-code { height: 100%; overflow: auto; padding: 20px; background: #fbfbfb; }.ws-code pre { margin: 0; font-family: var(--font-code); font-size: 14px; }.ws-preview { display: none; height: 100%; width: 100%; flex-direction: column; background: #fff; }.ws-console { background: #1a1a1a; color: #fff; font-family: var(--font-code); padding: 20px; font-size: 13px; flex: 1; overflow: auto; white-space: pre-wrap; }.btn-launch-ws { display: inline-flex; align-items: center; gap: 6px; padding: 6px 12px; background: var(--bg-main); border: 1px solid var(--border-light); border-radius: var(--radius-sm); font-size: 12px; font-weight: 500; cursor: pointer; margin-top: 10px; transition: 0.2s; }.btn-launch-ws:hover { background: #f0f0f0; }/* Utilities */@keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }.typing-indicator { display: flex; gap: 4px; padding: 10px 0; }.typing-dot { width: 6px; height: 6px; background: var(--text-tertiary); border-radius: 50%; animation: typeBounce 1.4s infinite ease-in-out both; }.typing-dot:nth-child(1) { animation-delay: -0.32s; } .typing-dot:nth-child(2) { animation-delay: -0.16s; }@keyframes typeBounce { 0%, 80%, 100% { transform: scale(0); } 40% { transform: scale(1); } }svg { width: 100%; height: 100%; }@media (max-width: 900px) {.sidebar { position: absolute; left: 0; height: 100%; box-shadow: 5px 0 20px rgba(0,0,0,0.05); }.sidebar.collapsed { left: -260px; margin-left: 0; }.workspace-panel.active { width: 100%; position: absolute; top:0; left:0; height:100%; z-index: 1000; }.input-dock { padding: 10px 15px 15px; }}</style></head><body><!-- SIDEBAR --><aside class="sidebar collapsed" id="sidebar"><div class="sidebar-header"><button class="btn-icon" onclick="UI.toggleSidebar()" title="Close Sidebar"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><line x1="3" y1="12" x2="21" y2="12"></line><line x1="3" y1="6" x2="21" y2="6"></line><line x1="3" y1="18" x2="21" y2="18"></line></svg></button><span style="font-weight: 600; font-size: 14px; letter-spacing: 0.5px;">CODE VED</span></div><div style="padding: 0 16px;"><button class="btn-new-chat" onclick="HistoryManager.clearHistory()"><svg style="width:16px; height:16px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="12" y1="5" x2="12" y2="19"></line><line x1="5" y1="12" x2="19" y2="12"></line></svg>New Chat</button></div><!-- RESTORED: Chat History Section --><div class="sidebar-history" id="chatHistory"><!-- Dynamic History populated here --></div><!-- User Profile Area --><div class="sidebar-footer" id="profileArea"><div class="user-avatar" id="uAv">G</div><div class="user-info-box"><div class="user-name" id="uName">Guest Session</div><div class="user-sub" id="uSub" onclick="Auth.openModal()" style="cursor:pointer; color:var(--brand-accent);">Login Required</div></div><!-- RESTORED: Power Button (Logout) --><button class="btn-power" id="btnLogout" onclick="Auth.handleLogout()" title="Logout" style="display:none;"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M18.36 6.64a9 9 0 1 1-12.73 0"></path><line x1="12" y1="2" x2="12" y2="12"></line></svg></button></div></aside><!-- MAIN AREA --><main class="main-area"><header class="top-bar" id="topBar"><button class="btn-icon" onclick="UI.toggleSidebar()" title="Open Menu" id="btnMenuOpen"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><line x1="3" y1="12" x2="21" y2="12"></line><line x1="3" y1="6" x2="21" y2="6"></line><line x1="3" y1="18" x2="21" y2="18"></line></svg></button><div class="model-selector">CODE VED 202B</div><div style="width: 32px;"></div> <!-- Spacer --></header><div class="chat-container" id="chatContainer"><div class="welcome-center" id="welcomeScreen"><img src="https://i.ibb.co/MyYStcGP/TIRANGA-20260613-131924-0000.png" alt="CODE VED Logo"><h1>What's your focus today?</h1><p id="welcomeGreeting">Hi Divy Patel, I am ready to assist you.</p></div></div><div class="input-dock" id="inputDock"><div class="input-container"><div class="file-preview-bar" id="filePreviewBar"><img id="imgPreview" class="file-preview-icon" src="" style="display:none;"><div id="docPreview" class="file-preview-icon" style="display:none;"><svg style="width:20px;height:20px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path><polyline points="14 2 14 8 20 8"></polyline></svg></div><div class="file-preview-name" id="fileName">document.pdf</div><button class="btn-remove-file" onclick="FileSys.discard()"><svg style="width:14px;height:14px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg></button></div><div class="input-row"><div class="tools-left"><div style="position: relative;"><button class="tool-btn" onclick="UI.toggleAttachMenu()" title="Attach File"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M21.44 11.05l-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48"></path></svg></button><div class="dropdown-menu" id="attachMenu"><div class="dropdown-item" onclick="document.getElementById('imgUpload').click()"><svg style="width:16px;height:16px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect><circle cx="8.5" cy="8.5" r="1.5"></circle><polyline points="21 15 16 10 5 21"></polyline></svg> Upload Image</div><div class="dropdown-item" onclick="document.getElementById('docUpload').click()"><svg style="width:16px;height:16px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path><polyline points="14 2 14 8 20 8"></polyline></svg> Upload Document</div></div><input type="file" id="imgUpload" class="hidden-input" accept="image/*" onchange="FileSys.process(this, 'image')"><input type="file" id="docUpload" class="hidden-input" accept=".pdf,.txt,.docx,.html,.js,.py,.css,.cpp,.c,.json,.md" onchange="FileSys.process(this, 'document')"></div><button class="tool-btn" id="btnStt" onclick="Speech.toggle()" title="Voice Typing"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3z"></path><path d="M19 10v2a7 7 0 0 1-14 0v-2"></path><line x1="12" y1="19" x2="12" y2="23"></line><line x1="8" y1="23" x2="16" y2="23"></line></svg></button></div><textarea class="chat-input" id="mainInput" placeholder="Message CODE VED..." rows="1"></textarea><button class="btn-send" id="btnSend" onclick="Chat.handleSend()"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="22" y1="2" x2="11" y2="13"></line><polygon points="22 2 15 22 11 13 2 9 22 2"></polygon></svg></button></div></div></div></main><!-- WORKSPACE PANEL --><aside class="workspace-panel" id="workspacePanel"><div class="ws-header"><div class="ws-tabs"><div class="ws-tab active" id="tabCode" onclick="Workspace.switchTab('code')">Code</div><div class="ws-tab" id="tabPreview" onclick="Workspace.switchTab('preview')">Preview</div></div><div class="ws-actions"><button class="ws-btn" onclick="Workspace.copy()" title="Copy Code"><svg style="width:16px;height:16px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="9" y="9" width="13" height="13" rx="2" ry="2"></rect><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path></svg></button><button class="ws-btn" onclick="Workspace.close()" title="Close Panel"><svg style="width:18px;height:18px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg></button></div></div><div class="ws-content"><div class="ws-code" id="wsCodeView"><pre><code id="wsCodeBlock" class="hljs"></code></pre></div><div class="ws-preview" id="wsPreviewView"></div></div></aside><!-- SECURE AUTHENTICATION MODAL --><div class="auth-overlay" id="authModal"><div class="auth-modal"><button class="auth-close" onclick="Auth.closeModal()"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg></button><div class="auth-title">Welcome to CODE VED</div><div class="auth-tabs"><div class="auth-tab active" id="tabLogin" onclick="Auth.switchTab('login')">Login</div><div class="auth-tab" id="tabRegister" onclick="Auth.switchTab('register')">Register</div></div><!-- Login Flow --><div id="flowLogin"><div class="auth-phase active" id="loginPhase1"><div class="auth-input-group"><input type="email" class="auth-input" id="logEmail" placeholder="Email Address"></div><button class="auth-btn" id="btnLogOtp" onclick="Auth.process('login_send_otp')">Send Secure OTP</button></div><div class="auth-phase" id="loginPhase2"><div class="auth-input-group"><input type="number" class="auth-input" id="logOtp" placeholder="Enter OTP"></div><button class="auth-btn" id="btnLogVerify" onclick="Auth.process('login_verify')">Verify & Login</button><button style="margin-top:10px; font-size:12px; color:var(--text-secondary); width:100%; text-align:center;" onclick="Auth.switchPhase('loginPhase2', 'loginPhase1')">Back to Email</button></div></div><!-- Register Flow --><div id="flowRegister" style="display:none;"><div class="auth-phase active" id="regPhase1"><div class="auth-input-group"><input type="text" class="auth-input" id="regName" placeholder="Full Name"><input type="email" class="auth-input" id="regEmail" placeholder="Email Address"></div><button class="auth-btn" id="btnRegOtp" onclick="Auth.process('register_send_otp')">Create Account</button></div><div class="auth-phase" id="regPhase2"><div class="auth-input-group"><input type="number" class="auth-input" id="regOtp" placeholder="Enter OTP"></div><button class="auth-btn" id="btnRegVerify" onclick="Auth.process('register_verify')">Verify & Register</button><button style="margin-top:10px; font-size:12px; color:var(--text-secondary); width:100%; text-align:center;" onclick="Auth.switchPhase('regPhase2', 'regPhase1')">Back to Details</button></div></div><div class="auth-message" id="authMsg"></div></div></div><script>// --- 1. CONFIG & STATE ---const Config = {GAS_URL: "https://script.google.com/macros/s/AKfycbz5vrlB4GrfkfBVYdQ52IQweIXC1cNDwKuTUorxdAiOdSSIrH55mzJlaz9kq1Y94ot5/exec",API_ENDPOINT: "/api/chat", // Pointing to your powerful Python backendLOGO: "https://i.ibb.co/MyYStcGP/TIRANGA-20260613-131924-0000.png"};const State = {user: localStorage.getItem('codeved_user') || null,name: localStorage.getItem('codeved_name') || null,guestCount: parseInt(localStorage.getItem('codeved_guest') || '0', 10),attachment: null,isProcessing: false,history: [],workspaces: [],currentWs: null};pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.worker.min.js';// --- 2. UI UTILITIES ---const UI = {toggleSidebar: () => {const sb = document.getElementById('sidebar');const btnOpen = document.getElementById('btnMenuOpen');sb.classList.toggle('collapsed');btnOpen.style.display = sb.classList.contains('collapsed') ? 'flex' : 'none';},toggleAttachMenu: () => document.getElementById('attachMenu').classList.toggle('active'),autoGrow: (el) => { el.style.height = 'auto'; el.style.height = Math.min(el.scrollHeight, 120) + 'px'; },scrollToBottom: () => { const c = document.getElementById('chatContainer'); c.scrollTop = c.scrollHeight; },escape: (s) => s.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>'),showAuthMsg: (msg, isError=true) => {const el = document.getElementById('authMsg');el.innerText = msg; el.style.color = isError ? '#cc0000' : '#009900';setTimeout(() => el.innerText='', 4000);},handleScrollEvents: () => {const c = document.getElementById('chatContainer');const topBar = document.getElementById('topBar');const dock = document.getElementById('inputDock');if (c.scrollTop > 10) topBar.classList.add('scrolled'); else topBar.classList.remove('scrolled');if (c.scrollHeight - c.scrollTop - c.clientHeight > 10) dock.classList.add('scrolled'); else dock.classList.remove('scrolled');}};document.getElementById('chatContainer').addEventListener('scroll', UI.handleScrollEvents);document.addEventListener('click', (e) => {if(!e.target.closest('.tools-left')) document.getElementById('attachMenu').classList.remove('active');});const inp = document.getElementById('mainInput');inp.addEventListener('input', function() { UI.autoGrow(this); });inp.addEventListener('keydown', function(e) {if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); Chat.handleSend(); }});// --- 3. AUTHENTICATION & HISTORY DB (RESTORED COMPLETELY) ---const Auth = {init: () => {const uAv = document.getElementById('uAv');const uName = document.getElementById('uName');const uSub = document.getElementById('uSub');const btnLogout = document.getElementById('btnLogout');const greeting = document.getElementById('welcomeGreeting');if (State.user) {const dispName = State.name || State.user.split('@')[0];uAv.innerText = dispName.charAt(0).toUpperCase();uName.innerText = dispName;uSub.innerText = "Authenticated";uSub.style.color = "#009900";uSub.onclick = null;uSub.style.cursor = 'default';btnLogout.style.display = 'flex';greeting.innerText = `Hi ${dispName}, I am ready to assist you.`;HistoryManager.sync(); // Load History on Boot} else {uAv.innerText = "G";uName.innerText = "Guest Session";uSub.innerText = `Queries: ${State.guestCount}/10`;uSub.style.color = "var(--text-tertiary)";btnLogout.style.display = 'none';greeting.innerText = `Hi Divy Patel, I am ready to assist you.`;}},handleLogout: () => {if(confirm("Are you sure you want to log out?")) {localStorage.removeItem('codeved_user');localStorage.removeItem('codeved_name');location.reload();}},openModal: () => document.getElementById('authModal').style.display = 'flex',closeModal: () => document.getElementById('authModal').style.display = 'none',switchTab: (tab) => {document.getElementById('tabLogin').classList.remove('active');document.getElementById('tabRegister').classList.remove('active');document.getElementById('flowLogin').style.display = 'none';document.getElementById('flowRegister').style.display = 'none';if(tab === 'login') { document.getElementById('tabLogin').classList.add('active'); document.getElementById('flowLogin').style.display = 'block'; }else { document.getElementById('tabRegister').classList.add('active'); document.getElementById('flowRegister').style.display = 'block'; }},switchPhase: (from, to) => { document.getElementById(from).classList.remove('active'); document.getElementById(to).classList.add('active'); },process: async (action) => {let payload = { action: action };let btnId = '';if (action === 'register_send_otp') {payload.name = document.getElementById('regName').value.trim();payload.email = document.getElementById('regEmail').value.trim();payload.phone = "0000000000"; payload.organization = "CODE VED System";if (!payload.name || !payload.email) return UI.showAuthMsg("Please fill all details.");btnId = 'btnRegOtp';} else if (action === 'login_send_otp') {payload.email = document.getElementById('logEmail').value.trim();if (!payload.email) return UI.showAuthMsg("Email is required.");btnId = 'btnLogOtp';} else if (action === 'register_verify' || action === 'login_verify') {payload.email = document.getElementById(action === 'register_verify' ? 'regEmail' : 'logEmail').value.trim();payload.otp = document.getElementById(action === 'register_verify' ? 'regOtp' : 'logOtp').value.trim();if (!payload.otp) return UI.showAuthMsg("OTP is required.");btnId = action === 'register_verify' ? 'btnRegVerify' : 'btnLogVerify';}const btn = document.getElementById(btnId);const originalText = btn.innerText;btn.disabled = true; btn.innerText = "Processing...";try {const res = await fetch(Config.GAS_URL, { method: 'POST', mode: 'cors', headers: { 'Content-Type': 'text/plain;charset=utf-8' }, body: JSON.stringify(payload) });const data = await res.json();if (data.status === 'success') {UI.showAuthMsg(data.message, false);if (action === 'register_send_otp') Auth.switchPhase('regPhase1', 'regPhase2');else if (action === 'login_send_otp') Auth.switchPhase('loginPhase1', 'loginPhase2');else {localStorage.setItem('codeved_user', payload.email);if(payload.name) localStorage.setItem('codeved_name', payload.name);location.reload();}} else { UI.showAuthMsg(data.message); }} catch (e) { UI.showAuthMsg("Database connection error. Please try again."); }btn.disabled = false; btn.innerText = originalText;}};const HistoryManager = {sync: async () => {if(!State.user) return;try {const res = await fetch(Config.GAS_URL, { method: 'POST', body: JSON.stringify({action: "get_history", email: State.user})});const data = await res.json();if(data.status === 'success' && data.historyJSON !== "[]") {State.history = JSON.parse(data.historyJSON);document.getElementById('welcomeScreen').style.display = 'none';State.history.forEach((msg, idx) => {if(msg.role === 'user') {Chat.renderUser(msg.content, '');// Add to sidebar history listconst shortText = msg.content.substring(0, 30) + (msg.content.length > 30 ? '...' : '');document.getElementById('chatHistory').innerHTML += `<div class="history-item" onclick="alert('History navigation active')">${UI.escape(shortText)}</div>`;}else {const botNode = Chat.renderBot();botNode.innerHTML = marked.parse(msg.content.replace(/<think>[\s\S]*?<\/think>/gi, ''));}});setTimeout(UI.scrollToBottom, 200);}} catch(e) { console.warn("History sync failed."); }},save: () => {if(!State.user) return;fetch(Config.GAS_URL, {method: 'POST', body: JSON.stringify({action: "save_history", email: State.user, historyJSON: JSON.stringify(State.history)})}).catch(e=>{});},clearHistory: async () => {if(State.user) {try { await fetch(Config.GAS_URL, { method: 'POST', body: JSON.stringify({action: "delete_history", email: State.user}) }); } catch(e){}}location.reload();}};// --- 4. FILE HANDLING (Secure) ---const FileSys = {process: async (input, type) => {document.getElementById('attachMenu').classList.remove('active');const file = input.files[0];if (!file) return;document.getElementById('filePreviewBar').classList.add('active');document.getElementById('fileName').innerText = file.name;const r = new FileReader();if (type === 'image') {document.getElementById('imgPreview').style.display = 'flex';document.getElementById('docPreview').style.display = 'none';r.onload = (e) => {document.getElementById('imgPreview').src = e.target.result;State.attachment = { type: 'image', data: e.target.result.split(',')[1], name: file.name };};r.readAsDataURL(file);} else {document.getElementById('imgPreview').style.display = 'none';document.getElementById('docPreview').style.display = 'flex';if (file.name.endsWith('.pdf')) {r.onload = async function() {const pdf = await pdfjsLib.getDocument(new Uint8Array(this.result)).promise;let txt = "";for(let i=1; i<=pdf.numPages; i++) {const page = await pdf.getPage(i);const content = await page.getTextContent();txt += content.items.map(s => s.str).join(' ') + "\n";}State.attachment = { type: 'text', data: txt.trim() || "[No text found]", name: file.name };};r.readAsArrayBuffer(file);} else if (file.name.endsWith('.docx')) {r.onload = async function() {const res = await mammoth.extractRawText({ arrayBuffer: this.result });State.attachment = { type: 'text', data: res.value || "[No text found]", name: file.name };};r.readAsArrayBuffer(file);} else {r.onload = (e) => {let data = e.target.result;if(file.name.endsWith('.html')) {data = data.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, "\n[SCRIPT SANITIZED]\n");}State.attachment = { type: 'text', data: data, name: file.name };};r.readAsText(file);}}input.value = '';},discard: () => {State.attachment = null;document.getElementById('filePreviewBar').classList.remove('active');}};// --- 5. SPEECH TO TEXT ---const Speech = {rec: null, isRec: false,init: () => {const SR = window.SpeechRecognition || window.webkitSpeechRecognition;if (!SR) return alert("Speech Recognition not supported in this browser.");Speech.rec = new SR();Speech.rec.continuous = false; Speech.rec.interimResults = true; Speech.rec.lang = 'en-US';Speech.rec.onstart = () => { Speech.isRec = true; document.getElementById('btnStt').classList.add('recording'); };Speech.rec.onresult = (e) => {let trans = '';for (let i = e.resultIndex; i < e.results.length; ++i) {if (e.results[i].isFinal) trans += e.results[i][0].transcript;}if (trans) {const input = document.getElementById('mainInput');input.value += (input.value ? ' ' : '') + trans;UI.autoGrow(input);}};Speech.rec.onerror = () => Speech.stop();Speech.rec.onend = () => Speech.stop();},toggle: () => {if (!Speech.rec) Speech.init();if (Speech.isRec) Speech.stop();else { try { Speech.rec.start(); } catch(e) {} }},stop: () => {if(Speech.rec) Speech.rec.stop();Speech.isRec = false;document.getElementById('btnStt').classList.remove('recording');}};// --- 6. WORKSPACE PRO MAX ---const Workspace = {open: (id) => {State.currentWs = id;const d = State.workspaces[id];const b = document.getElementById('wsCodeBlock');b.className = `hljs language-${d.lang || 'plaintext'}`;b.textContent = d.code;hljs.highlightElement(b);document.getElementById('workspacePanel').classList.add('active');if(window.innerWidth <= 900) { document.getElementById('sidebar').classList.add('collapsed'); }Workspace.switchTab('code');},close: () => document.getElementById('workspacePanel').classList.remove('active'),switchTab: (tab) => {document.getElementById('tabCode').classList.remove('active');document.getElementById('tabPreview').classList.remove('active');if(tab === 'code') {document.getElementById('tabCode').classList.add('active');document.getElementById('wsCodeView').style.display = 'block';document.getElementById('wsPreviewView').style.display = 'none';} else {document.getElementById('tabPreview').classList.add('active');document.getElementById('wsCodeView').style.display = 'none';document.getElementById('wsPreviewView').style.display = 'flex';Workspace.run();}},copy: () => {if(State.currentWs !== null) {navigator.clipboard.writeText(State.workspaces[State.currentWs].code).then(() => alert('Code Copied!'));}},run: async () => {if (State.currentWs === null) return;const d = State.workspaces[State.currentWs];const lang = (d.lang || '').toLowerCase();const view = document.getElementById('wsPreviewView');if (['html', 'xml', 'javascript', 'js', 'css'].includes(lang)) {let html = d.code;if(lang === 'javascript' || lang === 'js') html = `<script>${d.code}<\/script>`;if(lang === 'css') html = `<style>${d.code}</style><div style="padding:20px;font-family:sans-serif;">CSS Applied. Add HTML to test.</div>`;const iframe = document.createElement('iframe');iframe.style.width = '100%'; iframe.style.height = '100%'; iframe.style.border = 'none';view.innerHTML = ''; view.appendChild(iframe);iframe.contentWindow.document.open(); iframe.contentWindow.document.write(html); iframe.contentWindow.document.close();return;}view.innerHTML = '<div class="ws-console" style="color:var(--brand-accent);">Compiling code...</div>';const pMap = {'python':'python', 'py':'python', 'c':'c', 'cpp':'c++', 'java':'java'};const rLang = pMap[lang];if(!rLang) { view.innerHTML = `<div class="ws-console" style="color:#cc0000;">Live Preview not supported for ${lang}.</div>`; return; }try {const res = await fetch('https://emkc.org/api/v2/piston/execute', {method: 'POST', headers: { 'Content-Type': 'application/json' },body: JSON.stringify({ language: rLang, version: "*", files: [{ content: d.code }] })});const data = await res.json();let out = (data.compile?.output || "") + "\n" + (data.run?.output || "") + "\n" + (data.run?.stderr || "");view.innerHTML = `<div class="ws-console">${UI.escape(out.trim() || "[Execution Finished]")}</div>`;} catch(e) { view.innerHTML = `<div class="ws-console" style="color:#cc0000;">Engine Error.</div>`; }}};const MDRenderer = new marked.Renderer();MDRenderer.code = function(code, lang) {const id = State.workspaces.length;State.workspaces.push({code: code, lang: lang});const highlighted = hljs.highlightAuto(code).value;return `<div style="margin: 16px 0;"><div style="background:#f6f8fa; border:1px solid var(--border-light); border-radius:8px 8px 0 0; padding:8px 12px; display:flex; justify-content:space-between; align-items:center;"><span style="font-size:12px; font-family:var(--font-code); color:var(--text-secondary); font-weight:600;">${lang || 'code'}</span><button class="btn-launch-ws" style="margin:0; padding:4px 10px; font-size:12px;" onclick="Workspace.open(${id})"><svg style="width:14px;height:14px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="16 18 22 12 16 6"></polyline><polyline points="8 6 2 12 8 18"></polyline></svg> Open</button></div><pre style="margin:0; border-top:none; border-radius:0 0 8px 8px;"><code class="hljs">${highlighted}</code></pre></div>`;};marked.use({ renderer: MDRenderer });// --- 7. CHAT ENGINE (WITH SMART AUTO-SEARCH UI) ---const Chat = {renderUser: (txt, attachUI) => {const c = document.getElementById('chatContainer');const w = document.createElement('div'); w.className = 'message-wrapper user-message';w.innerHTML = `${attachUI} ${UI.escape(txt)}`;c.appendChild(w); UI.scrollToBottom();},renderBot: () => {const c = document.getElementById('chatContainer');const w = document.createElement('div'); w.className = 'message-wrapper bot-message';w.innerHTML = `<div class="bot-avatar"><img src="${Config.LOGO}"></div><div class="bot-content"><div class="typing-indicator"><div class="typing-dot"></div><div class="typing-dot"></div></div></div>`;c.appendChild(w); UI.scrollToBottom();return w.querySelector('.bot-content');},getToolHTML: (isActive) => {return `<div class="tool-indicator ${isActive ? 'active' : ''}"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="11" cy="11" r="8"></circle><line x1="21" y1="21" x2="16.65" y2="16.65"></line></svg>${isActive ? 'Searching on Google Search...' : 'Searched on Google Search'}</div><br>`;},handleSend: async () => {if(State.isProcessing) return;const input = document.getElementById('mainInput');const text = input.value.trim();if(!text && !State.attachment) return;// Guest Limit Validationif(!State.user) {if(State.guestCount >= 10) { Auth.openModal(); UI.showAuthMsg("Guest limit reached. Secure Login required.", true); return; }State.guestCount++; localStorage.setItem('codeved_guest', State.guestCount);document.getElementById('uSub').innerText = `Queries: ${State.guestCount}/10`;}State.isProcessing = true; document.getElementById('btnSend').disabled = true;input.value = ''; input.style.height = 'auto'; document.getElementById('welcomeScreen').style.display = 'none';let payloadStr = text;let attachUI = '';let mediaArray = [];// 💡 SMART AUTO-SEARCH DETECTIONconst queryLower = text.toLowerCase();const searchTriggers = ["search", "latest", "news", "update", "current", "2026", "today", "price", "who won", "weather", "aaj"];let isSearching = searchTriggers.some(kw => queryLower.includes(kw));if(State.attachment) {if(State.attachment.type === 'text') {payloadStr = `[File attached: ${State.attachment.name}]\n\n---DATA---\n${State.attachment.data}\n---END DATA---\n\nUser: ${text}`;attachUI = `<div class="chat-attachment"><svg style="width:14px;height:14px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path></svg> ${State.attachment.name}</div><br>`;} else {mediaArray.push(State.attachment);attachUI = `<img src="data:image/jpeg;base64,${State.attachment.data}" class="chat-img-preview"><br>`;}}Chat.renderUser(text || '[Attached Media]', attachUI);// Update History UIconst shortText = (text || 'Media Attached').substring(0, 30) + "...";document.getElementById('chatHistory').innerHTML += `<div class="history-item">${UI.escape(shortText)}</div>`;State.history.push({ role: 'user', content: payloadStr });FileSys.discard();const botContent = Chat.renderBot();// Show glowing tool UI immediately if it's a searchif (isSearching) {botContent.innerHTML = Chat.getToolHTML(true) + `<div class="typing-indicator"><div class="typing-dot"></div><div class="typing-dot"></div></div>`;}try {// Call the Powerful Backendconst res = await fetch(Config.API_ENDPOINT, {method: 'POST', headers: {'Content-Type': 'application/json'},body: JSON.stringify({message: payloadStr,attachments: mediaArray,is_search: isSearching, // SIGNAL BACKEND TO SEARCHhistory: State.history})});if(!res.ok) throw new Error("API Offline");const reader = res.body.getReader();const decoder = new TextDecoder();let fullText = "";while(true) {const {done, value} = await reader.read();if(done) break;const chunk = decoder.decode(value, {stream: true});const lines = chunk.split('\n');for(let line of lines) {if(line.startsWith('data: ')) {const dataStr = line.substring(6).trim();if(dataStr === '[DONE]') continue;try {const json = JSON.parse(dataStr);if(json.choices && json.choices[0].delta.content) fullText += json.choices[0].delta.content;else if (json.response) fullText += json.response;// Parse Markdown, Stop Tool animation if it was activelet finalHtml = marked.parse(fullText.replace(/<think>[\s\S]*?<\/think>/gi, ''));if(isSearching) {botContent.innerHTML = Chat.getToolHTML(false) + finalHtml;} else {botContent.innerHTML = finalHtml;}UI.scrollToBottom();} catch(e){}}}}State.history.push({ role: 'assistant', content: fullText });HistoryManager.save();} catch(e) {botContent.innerHTML = `<span style="color:#cc0000; font-weight:500;">Connection Offline. Backend is unreachable.</span>`;} finally {State.isProcessing = false;document.getElementById('btnSend').disabled = false;UI.scrollToBottom();}}};window.onload = () => {Auth.init();if(window.innerWidth > 900) { document.getElementById('btnMenuOpen').style.display = 'none'; document.getElementById('sidebar').classList.remove('collapsed'); }};</script></body></html>
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278// ================================================================================// CODE VED - ADVANCED MARKDOWN & MATH RENDERER (markdownRenderer.js)// Engineered by Divy Patel | Modular Architecture// // This module is the "Visual Engine" of the AI. It handles:// 1. Markdown parsing (via marked.js)// 2. Syntax Highlighting (via highlight.js)// 3. Complex Math Formulas (via MathJax) with pre/post-processing to prevent breaking// 4. Mermaid Diagrams rendering// 5. AI "Thinking Process" collapsible UI// 6. Code block copy buttons// ================================================================================
(function() { 'use strict';
// ---------------------------------------------------------------------------- // 1. INITIALIZATION & CONFIGURATION // ---------------------------------------------------------------------------- // Initialize Mermaid (Diagrams) function initMermaid() { if (typeof mermaid !== 'undefined') { mermaid.initialize({ startOnLoad: false, theme: 'default', securityLevel: 'loose', fontFamily: 'Inter, sans-serif' }); } }
// Configure Marked.js (Markdown Parser) function initMarked() { if (typeof marked === 'undefined') return;
const renderer = new marked.Renderer();
// Custom Code Block Renderer (Handles Syntax Highlighting & Mermaid) renderer.code = function(code, language, isEscaped) { // Handle Mermaid Diagrams if (language === 'mermaid') { return `<pre class="mermaid-diagram"><code class="mermaid">${code}</code></pre>`; }
// Handle Syntax Highlighting let highlightedCode = code; const langClass = language ? `language-${language}` : ''; if (language && typeof hljs !== 'undefined' && hljs.getLanguage(language)) { try { highlightedCode = hljs.highlight(code, { language: language, ignoreIllegals: true }).value; } catch (e) { highlightedCode = hljs.highlightAuto(code).value; } } else if (typeof hljs !== 'undefined') { highlightedCode = hljs.highlightAuto(code).value; }
// SVG Icons for Copy Button const copyIcon = `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="9" y="9" width="13" height="13" rx="2" ry="2"></rect><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path></svg>`; // Return formatted code block with a copy button return `<pre class="code-block-wrapper"><button class="code-copy-btn" title="Copy code">${copyIcon}<span>Copy</span></button><code class="hljs ${langClass}">${highlightedCode}</code></pre>`; };
// Apply the custom renderer to marked marked.use({ renderer: renderer, gfm: true, breaks: true, pedantic: false, mangle: false, headerIds: false }); }
// ---------------------------------------------------------------------------- // 2. MATHJAX PRE-PROCESSING & POST-PROCESSING (The Secret Sauce) // ---------------------------------------------------------------------------- /* * WHY THIS IS NEEDED: * Markdown parsers (like marked) often break LaTeX math syntax. For example, * underscores (_) in math formulas get converted to italics (<em>), and * asterisks (*) get converted to bold (<strong>). * To prevent this, we temporarily hide math blocks using unique placeholders, * parse the markdown, and then put the math blocks back! */
function preprocessMath(text) { const mathBlocks = {}; let counter = 0;
function createPlaceholder(match) { const id = `@@MATHBLOCK_${counter++}@@`; mathBlocks[id] = match; return id; }
// 1. Display Math: $$ ... $$ text = text.replace(/\$\$([\s\S]+?)\$\$/g, createPlaceholder); // 2. Display Math: \[ ... \] text = text.replace(/\\\[([\s\S]+?)\\\]/g, createPlaceholder); // 3. Inline Math: $ ... $ (Ensuring it doesn't match currency or empty spaces) text = text.replace(/(?<!\$)\$(?!\$)((?:[^$\\]|\\.)+?)\$(?!\$)/g, createPlaceholder); // 4. Inline Math: \( ... \) text = text.replace(/\\\(([\s\S]+?)\\\)/g, createPlaceholder);
return { text, mathBlocks }; }
function postprocessMath(html, mathBlocks) { // Replace all placeholders back with the original LaTeX strings for (const [id, mathStr] of Object.entries(mathBlocks)) { html = html.split(id).join(mathStr); } return html; }
// ---------------------------------------------------------------------------- // 3. THINKING PROCESS EXTRACTION (AI Reasoning UI) // ---------------------------------------------------------------------------- function processThinkingBlocks(text) { // Normalize different AI thinking tags (Qwen, etc.) let normalizedText = text .replace(/<\|channel\|>thought\s*<\|channel\|>/gi, "<think>\n") .replace(/<\|channel\|>answer\s*<\|channel\|>/gi, "\n</think>\n") .replace(/<\|im_start\|>thought/gi, "<think>\n") .replace(/<\|im_end\|>/gi, "\n</think>\n");
const thinkRegex = /<think>([\s\S]*?)(?:<\/think>|$)/i; const thinkMatch = normalizedText.match(thinkRegex); let thinkHtml = ''; let mainText = normalizedText;
if (thinkMatch) { const thinkContent = thinkMatch[1].trim(); // Parse the thinking content as markdown too, for better readability const parsedThinkContent = typeof marked !== 'undefined' ? marked.parse(thinkContent) : thinkContent; thinkHtml = ` <details class="qwen-think-box" open> <summary> <svg class="arrow" style="width:14px;height:14px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"> <polyline points="9 18 15 12 9 6"></polyline> </svg> Thinking Process </summary> <div class="qwen-think-content">${parsedThinkContent}</div> </details>`; // Remove the think block from the main text mainText = normalizedText.replace(thinkRegex, '').trim(); }
return { thinkHtml, mainText }; }
// ---------------------------------------------------------------------------- // 4. POST-RENDERING TRIGGERS (MathJax & Mermaid) // ----------------------------------------------------------------------------
async function triggerMathJax(container) { if (window.MathJax && MathJax.typesetPromise) { try { // Clear previous math rendering in this container to prevent errors MathJax.typesetClear([container]); // Render new math await MathJax.typesetPromise([container]); } catch (err) { console.warn('MathJax Rendering Warning:', err); } } }
async function triggerMermaid(container) { if (typeof mermaid === 'undefined') return; const diagrams = container.querySelectorAll('.mermaid'); if (diagrams.length === 0) return;
try { // mermaid.run is the modern way to render specific nodes await mermaid.run({ nodes: diagrams }); } catch (err) { console.warn('Mermaid Rendering Warning:', err); // If mermaid fails, it might leave broken SVGs. We clean them up. diagrams.forEach(d => { if (!d.querySelector('svg')) { d.innerHTML = `<span style="color:var(--brand-danger);font-size:12px;">⚠️ Invalid Mermaid Syntax</span>`; } }); } }
// ---------------------------------------------------------------------------- // 5. MAIN RENDERING ENGINE (Exposed to script.js) // ----------------------------------------------------------------------------
/** * The core function called by script.js to render AI responses. * @param {string} fullText - The raw text from the AI. * @param {boolean} isProcessing - True if the AI is still streaming. * @param {HTMLElement} container - The DOM element to inject the HTML into. */ async function parseAndRender(fullText, isProcessing, container) { if (!container) return;
// Step 1: Extract and format "Thinking" blocks const { thinkHtml, mainText } = processThinkingBlocks(fullText);
let finalHtml = thinkHtml;
// Step 2: Process the main text if (mainText) { // 2a. Hide Math formulas so Markdown parser doesn't break them const { text: safeText, mathBlocks } = preprocessMath(mainText); // 2b. Parse Markdown to HTML let parsedHtml = ''; if (typeof marked !== 'undefined') { parsedHtml = marked.parse(safeText); } else { parsedHtml = safeText.replace(/\n/g, '<br>'); // Fallback } // 2c. Put Math formulas back parsedHtml = postprocessMath(parsedHtml, mathBlocks); // 2d. Wrap in a class for MathJax targeting finalHtml += `<div class="tex2jax_process">${parsedHtml}</div>`; }
// Step 3: Add blinking cursor if AI is still generating if (isProcessing) { finalHtml += `<span class="blinking-cursor"></span>`; } // Step 4: Inject into DOM container.innerHTML = finalHtml;
// Step 5: Trigger external renderers (MathJax & Mermaid) // We only trigger them fully when processing is done to save performance, // but we do a lightweight pass during streaming. if (!isProcessing) { await triggerMathJax(container); await triggerMermaid(container); } else { // Lightweight MathJax trigger during streaming (optional, prevents lag) // triggerMathJax(container); } }
// ---------------------------------------------------------------------------- // 6. INITIALIZATION & EXPORT // ----------------------------------------------------------------------------
function init() { initMermaid(); initMarked(); console.log('[MarkdownRenderer] Engine initialized successfully.'); }
// Expose the API to the global window object so script.js can use it window.MarkdownRenderer = { parseAndRender: parseAndRender, init: init };
// Auto-initialize when this script loads init();
})();123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221// ================================================================================// CODE VED - MAIN APPLICATION LOGIC (script.js)// Engineered by Divy Patel | Modular Architecture// ================================================================================
(function() { 'use strict';
// ---------------------------------------------------------------------------- // 1. CONFIGURATION & GLOBAL STATE // ---------------------------------------------------------------------------- const Config = { GAS_URL: "https://script.google.com/macros/s/AKfycbzNO3inVc33ImhfLyde-JjjK9ZlPckLBksqCnCzelfhcklX6mp8KW8vfPTW4oWJTCcN/exec", API_ENDPOINT: "/api/chat", LOGO: "logo.png" };
const State = { user: localStorage.getItem('codeved_user') || null, name: localStorage.getItem('codeved_name') || null, guestCount: (() => { const v = parseInt(localStorage.getItem('codeved_guest') || '0', 10); return isNaN(v) ? 0 : v; })(), attachment: null, isProcessing: false, history: [], currentThreadId: null, currentTitle: null, abortController: null, location: null, weatherContext: null, thinkingMode: false, thinkingEffort: "medium", searchEnabled: false, lastUserMessage: null };
if (typeof pdfjsLib !== 'undefined') { pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.worker.min.js'; }
// ---------------------------------------------------------------------------- // 2. UTILITIES & CUSTOM CONFIRM // ---------------------------------------------------------------------------- function customConfirm(message) { return new Promise((resolve) => { const overlay = document.getElementById('customConfirmOverlay'); const msgEl = document.getElementById('customConfirmMsg'); const cancelBtn = document.getElementById('customConfirmCancel'); const okBtn = document.getElementById('customConfirmOk'); msgEl.textContent = message; overlay.style.display = 'flex'; function cleanup() { overlay.style.display = 'none'; cancelBtn.removeEventListener('click', onCancel); okBtn.removeEventListener('click', onOk); } function onCancel() { cleanup(); resolve(false); } function onOk() { cleanup(); resolve(true); } cancelBtn.addEventListener('click', onCancel); okBtn.addEventListener('click', onOk); }); }
// ---------------------------------------------------------------------------- // 3. UI MANAGER // ---------------------------------------------------------------------------- const UI = { autoScroll: true, toggleSidebar() { const sb = document.getElementById('sidebar'); const overlay = document.getElementById('mobileOverlay'); sb.classList.toggle('collapsed'); overlay.classList.toggle('active', !sb.classList.contains('collapsed') && window.innerWidth <= 900); }, toggleAttachMenu() { document.getElementById('attachMenu').classList.toggle('active'); document.getElementById('thinkMenu').classList.remove('active'); document.getElementById('voiceMenu').classList.remove('active'); }, autoGrow(el) { el.style.height = 'auto'; el.style.height = Math.min(el.scrollHeight, 180) + 'px'; }, scrollToBottom(force = false) { const c = document.getElementById('chatContainer'); if (force || this.autoScroll) { c.scrollTop = c.scrollHeight; } }, escape(s) { return String(s).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>'); }, showAuthMsg(msg, isError = true) { const el = document.getElementById('authMsg'); el.innerText = msg; el.style.color = isError ? 'var(--brand-danger)' : 'var(--brand-success)'; setTimeout(() => el.innerText = '', 4000); }, updateUserInfo(name, email) { if (name) { State.name = name; localStorage.setItem('codeved_name', name); } const dispName = State.name || email.split('@')[0]; document.getElementById('uAv').innerText = dispName.charAt(0).toUpperCase(); document.getElementById('uName').innerText = dispName; document.getElementById('uSub').innerText = email; document.getElementById('btnLogout').style.display = 'flex'; document.getElementById('btnDeleteAcc').style.display = 'flex'; document.getElementById('btnLoginRegister').style.display = 'none'; document.getElementById('welcomeTitle').innerHTML = `Hello, ${dispName}!<br>How can I help you today?`; }, updateWelcomeScreen() { document.getElementById('welcomeScreen').style.display = State.history.length === 0 ? 'flex' : 'none'; },
initListeners() { // Sidebar & Overlays document.getElementById('btnMenuOpen').addEventListener('click', () => this.toggleSidebar()); document.getElementById('btnCloseSidebar').addEventListener('click', () => this.toggleSidebar()); document.getElementById('mobileOverlay').addEventListener('click', () => this.toggleSidebar()); // Scroll to bottom document.getElementById('scrollToBottomBtn').addEventListener('click', () => { this.scrollToBottom(true); this.autoScroll = true; });
// Input Dock Expanding Logic const inp = document.getElementById('mainInput'); const dockWrapper = document.getElementById('dockWrapper');
inp.addEventListener('focus', () => dockWrapper.classList.add('expanded')); inp.addEventListener('blur', () => { if (inp.value.trim() === '') dockWrapper.classList.remove('expanded'); }); inp.addEventListener('input', () => { this.autoGrow(inp); if (inp.value.trim() !== '') dockWrapper.classList.add('expanded'); }); inp.addEventListener('keydown', (e) => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); Chat.handleSend(); } });
// Chat Container Scroll Listener const chatContainerEl = document.getElementById('chatContainer'); const scrollBtnEl = document.getElementById('scrollToBottomBtn'); chatContainerEl.addEventListener('scroll', () => { const scrollBottom = chatContainerEl.scrollHeight - chatContainerEl.scrollTop - chatContainerEl.clientHeight; this.autoScroll = scrollBottom <= 50; scrollBtnEl.classList.toggle('visible', !this.autoScroll); });
// Close dropdowns when clicking outside document.addEventListener('click', (e) => { if (!e.target.closest('.tools-left')) { document.getElementById('attachMenu').classList.remove('active'); document.getElementById('thinkMenu').classList.remove('active'); document.getElementById('voiceMenu').classList.remove('active'); } }); } };
// ---------------------------------------------------------------------------- // 4. AUTH MANAGER // ---------------------------------------------------------------------------- const Auth = { init() { if (State.user) { UI.updateUserInfo(State.name, State.user); HistoryManager.syncAllChats(); } else { document.getElementById('uAv').innerText = "G"; document.getElementById('uName').innerText = "Guest Mode"; document.getElementById('uSub').innerText = `Queries: ${State.guestCount}/10`; document.getElementById('btnLogout').style.display = 'none'; document.getElementById('btnDeleteAcc').style.display = 'none'; document.getElementById('btnLoginRegister').style.display = 'inline-flex'; document.getElementById('welcomeTitle').innerHTML = `Hello, Guest!<br>How can I help you today?`; } }, async handleLogout() { const ok = await customConfirm("Are you sure you want to logout?"); if (ok) { localStorage.removeItem('codeved_user'); localStorage.removeItem('codeved_name'); location.reload(); } }, async handleDeleteAccount() { const ok = await customConfirm("Are you sure you want to permanently delete your account and all data?"); if (ok) { try { await fetch(Config.GAS_URL, { method: 'POST', headers: { 'Content-Type': 'text/plain;charset=utf-8' }, body: JSON.stringify({ action: "delete_account", email: State.user }) }); } catch(e) { console.error("Account delete error:", e); } finally { localStorage.removeItem('codeved_user'); localStorage.removeItem('codeved_name'); location.reload(); } } }, openModal() { document.getElementById('authModal').style.display = 'flex'; }, closeModal() { document.getElementById('authModal').style.display = 'none'; }, switchTab(tab) { document.getElementById('tabLogin').classList.remove('active'); document.getElementById('tabRegister').classList.remove('active'); document.getElementById('flowLogin').style.display = 'none'; document.getElementById('flowRegister').style.display = 'none'; if (tab === 'login') { document.getElementById('tabLogin').classList.add('active'); document.getElementById('flowLogin').style.display = 'block'; } else { document.getElementById('tabRegister').classList.add('active'); document.getElementById('flowRegister').style.display = 'block'; } }, switchPhase(from, to) { document.getElementById(from).classList.remove('active'); document.getElementById(to).classList.add('active'); }, async process(action) { let payload = { action: action }; let btnId = ''; if (action === 'register_send_otp') { payload.name = document.getElementById('regName').value.trim(); payload.email = document.getElementById('regEmail').value.trim(); payload.phone = "0000000000"; payload.organization = "CODE VED"; if (!payload.name || !payload.email) return UI.showAuthMsg("Details missing."); btnId = 'btnRegOtp'; } else if (action === 'login_send_otp') { payload.email = document.getElementById('logEmail').value.trim(); if (!payload.email) return UI.showAuthMsg("Email required."); btnId = 'btnLogOtp'; } else if (action === 'register_verify' || action === 'login_verify') { payload.email = document.getElementById(action === 'register_verify' ? 'regEmail' : 'logEmail').value.trim(); payload.otp = document.getElementById(action === 'register_verify' ? 'regOtp' : 'logOtp').value.trim(); if (!payload.otp) return UI.showAuthMsg("OTP required."); btnId = action === 'register_verify' ? 'btnRegVerify' : 'btnLogVerify'; } const btn = document.getElementById(btnId); const originalText = btn.innerText; btn.disabled = true; btn.innerText = "Wait..."; try { const res = await fetch(Config.GAS_URL, { method: 'POST', headers: { 'Content-Type': 'text/plain;charset=utf-8' }, body: JSON.stringify(payload) }); const textResponse = await res.text(); let data; try { data = JSON.parse(textResponse); } catch (parseErr) { UI.showAuthMsg("Invalid response from server. Network error."); btn.disabled = false; btn.innerText = originalText; return; } if (data.status === 'success') { UI.showAuthMsg(data.message, false); if (action === 'register_send_otp') Auth.switchPhase('regPhase1', 'regPhase2'); else if (action === 'login_send_otp') Auth.switchPhase('loginPhase1', 'loginPhase2'); else { localStorage.setItem('codeved_user', payload.email); if (data.user && data.user.name) localStorage.setItem('codeved_name', data.user.name); location.reload(); } } else { UI.showAuthMsg(data.message); } } catch (e) { UI.showAuthMsg("Network Error. Please try again."); } btn.disabled = false; btn.innerText = originalText; },
initListeners() { document.getElementById('btnLoginRegister').addEventListener('click', () => this.openModal()); document.getElementById('btnLogout').addEventListener('click', () => this.handleLogout()); document.getElementById('btnDeleteAcc').addEventListener('click', () => this.handleDeleteAccount()); document.getElementById('btnAuthClose').addEventListener('click', () => this.closeModal()); document.getElementById('authModal').addEventListener('click', (e) => { if (e.target.id === 'authModal') this.closeModal(); });
document.getElementById('tabLogin').addEventListener('click', () => this.switchTab('login')); document.getElementById('tabRegister').addEventListener('click', () => this.switchTab('register'));
document.getElementById('btnLogOtp').addEventListener('click', () => this.process('login_send_otp')); document.getElementById('btnLogVerify').addEventListener('click', () => this.process('login_verify')); document.getElementById('btnRegOtp').addEventListener('click', () => this.process('register_send_otp')); document.getElementById('btnRegVerify').addEventListener('click', () => this.process('register_verify')); } };
// ---------------------------------------------------------------------------- // 5. HISTORY MANAGER // ---------------------------------------------------------------------------- const HistoryManager = { async syncAllChats() { if (!State.user) return; try { const res = await fetch(Config.GAS_URL, { method: 'POST', headers: { 'Content-Type': 'text/plain;charset=utf-8' }, body: JSON.stringify({ action: "get_all_chats", email: State.user }) }); const data = JSON.parse(await res.text()); if (data.status === 'success') { if (data.user) UI.updateUserInfo(data.user.name, data.user.email); this.renderSidebar(data.chats || []); } } catch (e) { console.error("History sync error:", e); } }, renderSidebar(chats) { const container = document.getElementById('chatHistory'); container.innerHTML = `<div class="history-header"><span class="history-title-text">Recent Workspaces</span><span class="btn-clear-all" id="btnClearAll">Clear All</span></div>`; document.getElementById('btnClearAll').addEventListener('click', () => this.clearAll());
chats.forEach(chat => { const isActive = State.currentThreadId === chat.threadId ? 'active' : ''; const item = document.createElement('div'); item.className = `history-item ${isActive}`; item.dataset.threadId = chat.threadId; item.innerHTML = ` <span class="history-text">${UI.escape(chat.title)}</span> <button class="btn-delete-chat" data-delete-id="${chat.threadId}" title="Delete"> <svg style="width:14px;height:14px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"> <polyline points="3 6 5 6 21 6"></polyline> <path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path> </svg> </button>`; container.appendChild(item); }); }, async loadChat(threadId) { if (!State.user || State.isProcessing) return; State.currentThreadId = threadId; document.getElementById('chatMessages').innerHTML = ''; try { const res = await fetch(Config.GAS_URL, { method: 'POST', headers: { 'Content-Type': 'text/plain;charset=utf-8' }, body: JSON.stringify({ action: "get_chat", email: State.user, threadId: threadId }) }); const data = JSON.parse(await res.text()); if (data.status === 'success') { State.history = JSON.parse(data.historyJSON || "[]"); UI.updateWelcomeScreen(); for (const msg of State.history) { if (msg.role === 'user') { let dispText = msg.content; if (dispText.includes('[SYSTEM REAL-TIME WEATHER:')) dispText = dispText.split('\n\n[SYSTEM REAL-TIME WEATHER:')[0]; if (dispText.includes('---END DATA---')) { const afterMarker = dispText.split('---END DATA---')[1] || ''; dispText = afterMarker.replace(/^\s*User:\s*/, '').trim() || '[Attached File]'; } Chat.renderUser(dispText); } else { const msgId = 'hist_' + Date.now() + '_' + Math.random().toString(36).substr(2, 5); const botObj = Chat.renderBot(msgId); Chat.parseAndRender(msg.content, false, botObj.contentDiv); TTSManager.autoPrepare(msgId, msg.content, botObj.listenBtn); } } UI.autoScroll = true; UI.scrollToBottom(); if (window.innerWidth <= 900) UI.toggleSidebar(); } } catch (e) { console.error("Load chat error:", e); } }, startNew() { if (State.isProcessing) return; State.currentThreadId = null; State.currentTitle = null; State.history = []; document.getElementById('chatMessages').innerHTML = ''; UI.updateWelcomeScreen(); UI.autoScroll = true; UI.scrollToBottom(); if (window.innerWidth <= 900) UI.toggleSidebar(); }, saveCurrent() { if (!State.user || State.history.length === 0) return; if (!State.currentThreadId) { State.currentThreadId = "thr_" + Date.now(); const firstUser = State.history.find(m => m.role === 'user'); State.currentTitle = firstUser ? firstUser.content.substring(0, 25) : "New Workspace"; } fetch(Config.GAS_URL, { method: 'POST', headers: { 'Content-Type': 'text/plain;charset=utf-8' }, body: JSON.stringify({ action: "save_chat", email: State.user, threadId: State.currentThreadId, title: State.currentTitle, historyJSON: JSON.stringify(State.history) }) }).catch(e => console.error("Save error:", e)).then(() => this.syncAllChats()); }, async clearAll() { const ok = await customConfirm("Clear all workspaces?"); if (ok) { State.history = []; State.currentThreadId = null; State.currentTitle = null; document.getElementById('chatMessages').innerHTML = ''; UI.updateWelcomeScreen(); UI.autoScroll = true; UI.scrollToBottom(); fetch(Config.GAS_URL, { method: 'POST', headers: { 'Content-Type': 'text/plain;charset=utf-8' }, body: JSON.stringify({ action: "clear_all_chats", email: State.user }) }).catch(e => console.error("Clear error:", e)).then(() => this.syncAllChats()); } }, async deleteChat(threadId) { const ok = await customConfirm("Delete this workspace?"); if (ok) { if (State.currentThreadId === threadId) this.startNew(); fetch(Config.GAS_URL, { method: 'POST', headers: { 'Content-Type': 'text/plain;charset=utf-8' }, body: JSON.stringify({ action: "delete_chat", email: State.user, threadId: threadId }) }).catch(e => console.error("Delete error:", e)).then(() => this.syncAllChats()); } },
initListeners() { document.getElementById('btnNewChat').addEventListener('click', () => this.startNew()); // Event Delegation for History List document.getElementById('chatHistory').addEventListener('click', (e) => { const deleteBtn = e.target.closest('.btn-delete-chat'); if (deleteBtn) { e.stopPropagation(); this.deleteChat(deleteBtn.dataset.deleteId); return; } const historyItem = e.target.closest('.history-item'); if (historyItem && historyItem.dataset.threadId) { this.loadChat(historyItem.dataset.threadId); } }); } };
// ---------------------------------------------------------------------------- // 6. ENVIRONMENT, SEARCH & THINKING MANAGERS // ---------------------------------------------------------------------------- const EnvironmentManager = { toggle() { const status = document.getElementById('locStatus'); document.getElementById('attachMenu').classList.remove('active'); if (State.location) { State.location = null; State.weatherContext = null; status.style.display = 'none'; } else { if (navigator.geolocation) { status.style.display = 'flex'; status.innerHTML = `<span>Finding location...</span>`; navigator.geolocation.getCurrentPosition(pos => { State.location = { lat: pos.coords.latitude, lng: pos.coords.longitude }; status.innerHTML = `<span style="color:var(--brand-success);">✓ Location active!</span>`; setTimeout(() => status.style.display = 'none', 3000); fetch(`https://api.open-meteo.com/v1/forecast?latitude=${pos.coords.latitude}&longitude=${pos.coords.longitude}¤t=temperature_2m,relative_humidity_2m,weather_code,wind_speed_10m`) .then(r => r.ok ? r.json() : null) .then(data => { const c = data && data.current; if (c) State.weatherContext = `Temperature: ${c.temperature_2m}°C, Humidity: ${c.relative_humidity_2m}%, Wind: ${c.wind_speed_10m} km/h`; }).catch(() => {}); }, err => { status.innerHTML = `<span style="color:var(--brand-danger);">Location denied.</span>`; setTimeout(() => status.style.display = 'none', 3000); }); } } } };
const SearchManager = { toggle() { State.searchEnabled = !State.searchEnabled; const btn = document.getElementById('btnSearch'); btn.classList.toggle('active-search', State.searchEnabled); btn.title = State.searchEnabled ? 'Web Search: ON' : 'Web Search: OFF'; } };
const ThinkingManager = { toggleMenu() { document.getElementById('thinkMenu').classList.toggle('active'); document.getElementById('attachMenu').classList.remove('active'); }, setEffort(level) { State.thinkingMode = true; State.thinkingEffort = level; document.getElementById('thinkMenu').classList.remove('active'); this.updateIndicator(); }, disable() { State.thinkingMode = false; document.getElementById('thinkMenu').classList.remove('active'); this.updateIndicator(); }, updateIndicator() { const btn = document.getElementById('btnAttach'); btn.classList.remove('active-think-low', 'active-think-medium', 'active-think-high'); if (State.thinkingMode) { btn.classList.add(`active-think-${State.thinkingEffort}`); btn.title = `Thinking Mode: ${State.thinkingEffort.charAt(0).toUpperCase() + State.thinkingEffort.slice(1)}`; } else { btn.title = 'Attach File'; } },
initListeners() { document.getElementById('thinkMenu').addEventListener('click', (e) => { const item = e.target.closest('.dropdown-item'); if (!item) return; if (item.id === 'optDisableThink') { this.disable(); } else if (item.dataset.effort) { this.setEffort(item.dataset.effort); } }); } };
// ---------------------------------------------------------------------------- // 7. FILE SYSTEM & SPEECH // ---------------------------------------------------------------------------- const FileSys = { async process(input, type) { document.getElementById('attachMenu').classList.remove('active'); const file = input.files[0]; if (!file) return; document.getElementById('filePreviewBar').classList.add('active'); document.getElementById('fileName').innerText = file.name; if (type === 'image') { document.getElementById('imgPreview').style.display = 'block'; document.getElementById('docPreview').style.display = 'none'; const reader = new FileReader(); reader.onload = (e) => { const img = new Image(); img.onload = () => { const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); let w = img.width, h = img.height; const max = 1024; if(w > max || h > max) { if(w > h) { h = (max/w)*h; w = max; } else { w = (max/h)*w; h = max; } } canvas.width = w; canvas.height = h; ctx.drawImage(img, 0, 0, w, h); const b64 = canvas.toDataURL('image/jpeg', 0.8).split(',')[1]; State.attachment = { type: 'image', data: b64, name: file.name }; document.getElementById('imgPreview').src = `data:image/jpeg;base64,${b64}`; }; img.src = e.target.result; }; reader.readAsDataURL(file); } else { document.getElementById('imgPreview').style.display = 'none'; document.getElementById('docPreview').style.display = 'block'; if (file.name.endsWith('.pdf')) { try { const arrayBuffer = await file.arrayBuffer(); const pdf = await pdfjsLib.getDocument({ data: arrayBuffer }).promise; let text = ''; for (let i = 1; i <= pdf.numPages; i++) { const page = await pdf.getPage(i); const content = await page.getTextContent(); text += content.items.map(item => item.str).join(' ') + '\n'; } State.attachment = { type: 'text', data: text, name: file.name }; } catch(e) { State.attachment = { type: 'text', data: '[PDF parsing error]', name: file.name }; } } else if (file.name.endsWith('.docx')) { try { const arrayBuffer = await file.arrayBuffer(); const result = await mammoth.extractRawText({ arrayBuffer }); State.attachment = { type: 'text', data: result.value, name: file.name }; } catch(e) { State.attachment = { type: 'text', data: '[DOCX parsing error]', name: file.name }; } } else { const reader = new FileReader(); reader.onload = (e) => { State.attachment = { type: 'text', data: e.target.result, name: file.name }; }; reader.readAsText(file); } } input.value = ''; document.getElementById('dockWrapper').classList.add('expanded'); }, discard() { State.attachment = null; document.getElementById('filePreviewBar').classList.remove('active'); if (document.getElementById('mainInput').value.trim() === '') { document.getElementById('dockWrapper').classList.remove('expanded'); } },
initListeners() { document.getElementById('btnRemoveFile').addEventListener('click', () => this.discard()); document.getElementById('imgUpload').addEventListener('change', (e) => this.process(e.target, 'image')); document.getElementById('docUpload').addEventListener('change', (e) => this.process(e.target, 'document')); } };
const Speech = { rec: null, isRec: false, init() { const SR = window.SpeechRecognition || window.webkitSpeechRecognition; if (!SR) return; this.rec = new SR(); this.rec.continuous = false; this.rec.interimResults = true; this.rec.lang = navigator.language || 'en-US'; this.rec.onstart = () => { this.isRec = true; document.getElementById('btnStt').classList.add('recording'); }; this.rec.onresult = (e) => { if (!e.results || !e.results.length) return; let trans = ''; for (let i = e.resultIndex; i < e.results.length; ++i) { if (e.results[i].isFinal && e.results[i][0]) trans += e.results[i][0].transcript; } if (trans) { const input = document.getElementById('mainInput'); input.value += (input.value ? ' ' : '') + trans; UI.autoGrow(input); document.getElementById('dockWrapper').classList.add('expanded'); } }; this.rec.onerror = () => this.stop(); this.rec.onend = () => this.stop(); }, toggle() { if (!this.rec) this.init(); if (this.isRec) this.stop(); else { try { this.rec.start(); } catch(e) {} } }, stop() { if(this.rec) this.rec.stop(); this.isRec = false; document.getElementById('btnStt').classList.remove('recording'); },
initListeners() { document.getElementById('btnStt').addEventListener('click', () => this.toggle()); } };
// ---------------------------------------------------------------------------- // 8. TTS MANAGER // ---------------------------------------------------------------------------- const TTSManager = { cache: {}, currentAudio: null, selectedVoice: "M2", selectedLanguage: "English", isPlaying: false, currentMsgId: null, currentBtnElement: null, preparingSet: new Set(), voiceMap: { "M1": "Aarav", "M2": "Kabir", "M3": "Vihaan", "M4": "Advik", "M5": "Rohan", "F1": "Priya", "F2": "Ananya", "F3": "Diya", "F4": "Sneha", "F5": "Kavya" }, languageMap: { "English": "en", "Korean": "ko", "Japanese": "ja", "Arabic": "ar", "Bulgarian": "bg", "Czech": "cs", "Danish": "da", "German": "de", "Greek": "el", "Spanish": "es", "Estonian": "et", "Finnish": "fi", "French": "fr", "Hindi": "hi", "Croatian": "hr", "Hungarian": "hu", "Indonesian": "id", "Italian": "it", "Lithuanian": "lt", "Latvian": "lv", "Dutch": "nl", "Polish": "pl", "Portuguese": "pt", "Romanian": "ro", "Russian": "ru", "Slovak": "sk", "Slovenian": "sl", "Swedish": "sv", "Turkish": "tr", "Ukrainian": "uk", "Vietnamese": "vi" }, initUI() { const list = document.getElementById('voiceOptionsList'); list.innerHTML = ''; for (const [code, name] of Object.entries(this.voiceMap)) { const isSelected = code === this.selectedVoice; const checkIcon = isSelected ? `<svg style="width:16px;height:16px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><polyline points="20 6 9 17 4 12"></polyline></svg>` : `<div></div>`; const item = document.createElement('div'); item.className = `dropdown-item ${isSelected ? 'selected' : ''}`; item.dataset.voiceCode = code; item.innerHTML = `<span>${name}</span>${checkIcon}`; list.appendChild(item); } const langList = document.getElementById('languageOptionsList'); langList.innerHTML = ''; for (const [name, code] of Object.entries(this.languageMap)) { const isSelected = name === this.selectedLanguage; const checkIcon = isSelected ? `<svg style="width:16px;height:16px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><polyline points="20 6 9 17 4 12"></polyline></svg>` : `<div></div>`; const item = document.createElement('div'); item.className = `dropdown-item ${isSelected ? 'selected' : ''}`; item.dataset.langName = name; item.innerHTML = `<span>${name}</span>${checkIcon}`; langList.appendChild(item); } }, setVoice(code) { Object.values(this.cache).forEach(url => URL.revokeObjectURL(url)); this.cache = {}; this.selectedVoice = code; this.initUI(); document.getElementById('voiceMenu').classList.remove('active'); }, setLanguage(name) { Object.values(this.cache).forEach(url => URL.revokeObjectURL(url)); this.cache = {}; this.selectedLanguage = name; this.initUI(); document.getElementById('voiceMenu').classList.remove('active'); }, cleanTextForTTS(text) { let cleaned = text.replace(/\u0060{3}[\s\S]*?\u0060{3}/g, '') .replace(/\u0060[^\u0060]*\u0060/g, '') .replace(/<think>[\s\S]*?<\/think>/gi, '') .replace(/https?:\/\/[^\s]+/g, '') .replace(/[*_#\u0060~>]/g, '') .replace(/<[^>]*>/g, '') .replace(/\s+/g, ' ') .trim(); cleaned = cleaned.replace(/[\u{1F600}-\u{1F64F}]/gu, '') .replace(/[\u{1F300}-\u{1F5FF}]/gu, '') .replace(/[\u{1F680}-\u{1F6FF}]/gu, '') .replace(/[\u{2600}-\u{26FF}]/gu, '') .replace(/[\u{2700}-\u{27BF}]/gu, ''); if (cleaned.length > 1500) cleaned = cleaned.substring(0, 1500) + '...'; return cleaned; }, async autoPrepare(msgId, fullText, btnElement) { if (this.preparingSet.has(msgId)) return; const cleanText = this.cleanTextForTTS(fullText); if (!cleanText) { btnElement.style.display = 'none'; return; } this.preparingSet.add(msgId); btnElement.style.display = 'flex'; btnElement.innerHTML = `<svg class="spin-icon" style="width:14px;height:14px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="12" y1="2" x2="12" y2="6"></line><line x1="12" y1="18" x2="12" y2="22"></line><line x1="4.93" y1="4.93" x2="7.76" y2="7.76"></line><line x1="16.24" y1="16.24" x2="19.07" y2="19.07"></line><line x1="2" y1="12" x2="6" y2="12"></line><line x1="18" y1="12" x2="22" y2="12"></line><line x1="4.93" y1="19.07" x2="7.76" y2="16.24"></line><line x1="16.24" y1="7.76" x2="19.07" y2="4.93"></line></svg> Preparing...`; btnElement.style.pointerEvents = 'none'; try { const response = await fetch('/api/tts', { method: 'POST', headers: {'Content-Type':'application/json'}, body: JSON.stringify({ text: cleanText, voice: this.selectedVoice, language_name: this.selectedLanguage }) }); if (!response.ok) throw new Error('TTS service unavailable'); const blob = await response.blob(); this.cache[msgId] = URL.createObjectURL(blob); btnElement.innerHTML = `<svg style="width:14px;height:14px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5"></polygon><path d="M19.07 4.93a10 10 0 0 1 0 14.14M15.54 8.46a5 5 0 0 1 0 7.07"></path></svg> Listen`; btnElement.style.pointerEvents = 'auto'; } catch(e) { btnElement.innerHTML = `<span style="color:var(--brand-danger);">⚠️ ${e.message}</span>`; setTimeout(() => { btnElement.style.display = 'none'; }, 4000); } finally { this.preparingSet.delete(msgId); } }, play(msgId, btnElement) { const audioUrl = this.cache[msgId]; if (!audioUrl) { this.autoPrepare(msgId, document.getElementById(`bot-content-${msgId}`).innerText, btnElement); return; } if (this.isPlaying && this.currentMsgId === msgId) { if (this.currentAudio) { this.currentAudio.pause(); this.currentAudio.currentTime = 0; } this.isPlaying = false; this.currentMsgId = null; btnElement.innerHTML = `<svg style="width:14px;height:14px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5"></polygon><path d="M19.07 4.93a10 10 0 0 1 0 14.14M15.54 8.46a5 5 0 0 1 0 7.07"></path></svg> Listen`; btnElement.style.background = ''; return; } if (this.currentAudio) { this.currentAudio.pause(); this.currentAudio.currentTime = 0; } this.isPlaying = true; this.currentMsgId = msgId; this.currentBtnElement = btnElement; const originalHTML = btnElement.innerHTML; btnElement.innerHTML = `<svg style="width:14px;height:14px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="6" y="4" width="4" height="16"></rect><rect x="14" y="4" width="4" height="16"></rect></svg> Playing...`; btnElement.style.background = 'rgba(211, 227, 253, 0.9)'; this.currentAudio = new Audio(audioUrl); this.currentAudio.playbackRate = 1.15; const resetBtn = () => { this.isPlaying = false; this.currentMsgId = null; btnElement.innerHTML = originalHTML; btnElement.style.background = ''; }; this.currentAudio.onended = resetBtn; this.currentAudio.onerror = resetBtn; this.currentAudio.play(); },
initListeners() { document.getElementById('voiceMenu').addEventListener('click', (e) => { const item = e.target.closest('.dropdown-item'); if (!item) return; if (item.dataset.voiceCode) this.setVoice(item.dataset.voiceCode); else if (item.dataset.langName) this.setLanguage(item.dataset.langName); }); } };
// ---------------------------------------------------------------------------- // 9. CHAT MANAGER // ---------------------------------------------------------------------------- const Chat = { renderUser(txt, attachUI = '') { const c = document.getElementById('chatMessages'); const w = document.createElement('div'); w.className = 'message-wrapper'; w.innerHTML = `<div class="user-message">${attachUI}${txt ? UI.escape(txt) : ''}</div>`; c.appendChild(w); UI.autoScroll = true; UI.scrollToBottom(true); }, renderBot(msgId) { const c = document.getElementById('chatMessages'); const w = document.createElement('div'); w.className = 'message-wrapper'; const listenIcon = `<svg style="width:14px;height:14px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polygon points="11 5 6 9 2 9 2 15 6 15 11 19 11 5"></polygon><path d="M19.07 4.93a10 10 0 0 1 0 14.14M15.54 8.46a5 5 0 0 1 0 7.07"></path></svg>`; const copyIcon = `<svg style="width:14px;height:14px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="9" y="9" width="13" height="13" rx="2" ry="2"></rect><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path></svg>`; w.innerHTML = ` <div class="bot-message"> <div class="bot-avatar"><img src="${Config.LOGO}"></div> <div class="bot-content-wrapper"> <div class="bot-content" id="bot-content-${msgId}"></div> <div class="msg-actions"> <button class="action-btn listen-btn" id="listen-btn-${msgId}" style="display:none;">${listenIcon} Listen</button> <button class="action-btn copy-btn">${copyIcon} Copy</button> </div> </div> </div>`; c.appendChild(w); UI.scrollToBottom(); return { contentDiv: document.getElementById(`bot-content-${msgId}`), listenBtn: document.getElementById(`listen-btn-${msgId}`), wrapper: w, msgId: msgId }; }, // Delegating Markdown Rendering to the dedicated module parseAndRender(fullText, isProcessing, container) { if (window.MarkdownRenderer && typeof window.MarkdownRenderer.parseAndRender === 'function') { window.MarkdownRenderer.parseAndRender(fullText, isProcessing, container); } else { // Fallback if markdownRenderer.js hasn't loaded yet container.innerHTML = fullText; } }, copyMsg(contentDiv) { const clone = contentDiv.cloneNode(true); const thinkBox = clone.querySelector('.qwen-think-box'); if (thinkBox) thinkBox.remove(); navigator.clipboard.writeText(clone.innerText).then(() => { const btn = contentDiv.parentElement.querySelector('.copy-btn'); const original = btn.innerHTML; btn.innerHTML = `<svg style="width:14px;height:14px;" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="20 6 9 17 4 12"></polyline></svg> Copied!`; setTimeout(() => btn.innerHTML = original, 1500); }); }, stopGeneration() { if (State.abortController) { State.abortController.abort(); State.abortController = null; } State.isProcessing = false; document.getElementById('btnSend').disabled = false; document.getElementById('btnSend').style.display = 'flex'; document.getElementById('btnStop').classList.remove('active'); if (document.getElementById('mainInput').value.trim() === '') { document.getElementById('dockWrapper').classList.remove('expanded'); } }, async handleSend() { if(State.isProcessing) return; if (!State.user && State.guestCount >= 10) { Auth.openModal(); UI.showAuthMsg("Guest limit reached (10/10). Please login or register to continue.", true); return; } const input = document.getElementById('mainInput'); const text = input.value.trim(); if(!text && !State.attachment) return; if (!State.user) { let count = parseInt(localStorage.getItem('codeved_guest') || '0', 10); if (isNaN(count)) count = 0; count++; State.guestCount = count; localStorage.setItem('codeved_guest', count.toString()); document.getElementById('uSub').innerText = `Queries: ${count}/10`; } State.isProcessing = true; document.getElementById('btnSend').style.display = 'none'; document.getElementById('btnStop').classList.add('active'); State.lastUserMessage = text; input.value = ''; input.style.height = 'auto'; UI.updateWelcomeScreen(); let payloadStr = text, attachUI = '', mediaArray = []; if(State.attachment) { if(State.attachment.type === 'text') { payloadStr = `[File attached: ${State.attachment.name}]\n\n---DATA---\n${State.attachment.data}\n---END DATA---\n\nUser: ${text}`; attachUI = `<div class="chat-attachment-container"><div class="chat-file-pill"><svg style="width:14px;height:14px;color:var(--text-secondary);" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path></svg> ${State.attachment.name}</div></div>`; } else { mediaArray.push(State.attachment); attachUI = `<div class="chat-attachment-container"><img src="data:image/jpeg;base64,${State.attachment.data}" class="chat-img-preview"></div>`; } } let systemInjectedPayload = payloadStr; if(State.weatherContext) { systemInjectedPayload = `${payloadStr}\n\n[SYSTEM REAL-TIME WEATHER: ${State.weatherContext}]`; } Chat.renderUser(text, attachUI); State.history.push({ role: 'user', content: payloadStr }); FileSys.discard(); const msgId = Date.now().toString(); const botObj = Chat.renderBot(msgId); Chat.parseAndRender("", true, botObj.contentDiv); State.abortController = new AbortController(); let fullText = ""; try { const res = await fetch(Config.API_ENDPOINT, { method: 'POST', headers: {'Content-Type':'application/json'}, body: JSON.stringify({ message: systemInjectedPayload, attachments: mediaArray, is_search: State.searchEnabled, location: State.location, thinking_mode: State.thinkingMode, thinking_effort: State.thinkingEffort, history: State.history }), signal: State.abortController.signal }); if(!res.ok) { let errMsg = `Server error (${res.status})`; if (res.status === 404) errMsg = 'Chat API endpoint not found (404).'; else if (res.status === 500) errMsg = 'Internal server error (500).'; throw new Error(errMsg); } const reader = res.body.getReader(); const decoder = new TextDecoder(); let buffer = ''; while(true) { const {done, value} = await reader.read(); if(done) break; buffer += decoder.decode(value, {stream: true}); const lines = buffer.split('\n'); buffer = lines.pop(); for(let line of lines) { if(line.startsWith('data: ')) { const dataStr = line.substring(6).trim(); if(dataStr === '[DONE]') continue; try { const json = JSON.parse(dataStr); if (json.error) { botObj.contentDiv.innerHTML += `<br><span style="color:var(--brand-danger);">⚠️ ${UI.escape(json.error)}</span>`; return; } if(json.choices && json.choices[0] && json.choices[0].delta && json.choices[0].delta.content) { fullText += json.choices[0].delta.content; } } catch(e) {} Chat.parseAndRender(fullText, true, botObj.contentDiv); } } } Chat.parseAndRender(fullText, false, botObj.contentDiv); State.history.push({ role: 'assistant', content: fullText }); HistoryManager.saveCurrent(); } catch(e) { if (e.name === 'AbortError') { botObj.contentDiv.innerHTML += `<br><span style="color:var(--text-tertiary); font-style:italic;">⏹ Generation stopped.</span>`; if (fullText.trim()) { State.history.push({ role: 'assistant', content: fullText }); HistoryManager.saveCurrent(); } } else { botObj.contentDiv.innerHTML += `<br><span style="color:var(--brand-danger);">⚠️ ${UI.escape(e.message || 'Connection Offline.')}</span>`; } } finally { State.isProcessing = false; document.getElementById('btnSend').disabled = false; document.getElementById('btnSend').style.display = 'flex'; document.getElementById('btnStop').classList.remove('active'); if (document.getElementById('mainInput').value.trim() === '') { document.getElementById('dockWrapper').classList.remove('expanded'); } if (UI.autoScroll) UI.scrollToBottom(); if(botObj.listenBtn && fullText.trim().length > 0) { TTSManager.autoPrepare(msgId, fullText, botObj.listenBtn); } } },
initListeners() { document.getElementById('btnSend').addEventListener('click', () => this.handleSend()); document.getElementById('btnStop').addEventListener('click', () => this.stopGeneration());
// Event Delegation for Chat Messages (Copy & Listen buttons) document.getElementById('chatMessages').addEventListener('click', (e) => { const listenBtn = e.target.closest('.listen-btn'); if (listenBtn) { const msgId = listenBtn.id.replace('listen-btn-', ''); TTSManager.play(msgId, listenBtn); return; }
const copyBtn = e.target.closest('.copy-btn'); if (copyBtn) { const contentDiv = copyBtn.closest('.bot-content-wrapper').querySelector('.bot-content'); this.copyMsg(contentDiv); return; } // Code block copy delegation (handled by markdownRenderer usually, but safe fallback here) const codeCopyBtn = e.target.closest('.code-copy-btn'); if (codeCopyBtn && !codeCopyBtn.classList.contains('copied')) { const pre = codeCopyBtn.closest('pre'); const codeEl = pre.querySelector('code'); if(codeEl) { navigator.clipboard.writeText(codeEl.innerText).then(() => { codeCopyBtn.classList.add('copied'); codeCopyBtn.innerHTML = `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="20 6 9 17 4 12"></polyline></svg><span>Copied!</span>`; setTimeout(() => { codeCopyBtn.classList.remove('copied'); codeCopyBtn.innerHTML = `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="9" y="9" width="13" height="13" rx="2" ry="2"></rect><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path></svg><span>Copy</span>`; }, 1500); }); } } }); } };
// ---------------------------------------------------------------------------- // 10. ATTACH MENU & INITIALIZATION // ---------------------------------------------------------------------------- function initAttachMenuListeners() { document.getElementById('btnAttach').addEventListener('click', () => UI.toggleAttachMenu()); document.getElementById('optUploadImg').addEventListener('click', () => document.getElementById('imgUpload').click()); document.getElementById('optUploadDoc').addEventListener('click', () => document.getElementById('docUpload').click()); document.getElementById('optEnv').addEventListener('click', () => EnvironmentManager.toggle()); document.getElementById('optThink').addEventListener('click', () => ThinkingManager.toggleMenu()); document.getElementById('optVoice').addEventListener('click', () => TTSManager.toggleMenu()); document.getElementById('btnSearch').addEventListener('click', () => SearchManager.toggle()); }
function initGlobal() { // Set Logos document.getElementById('faviconLink').href = Config.LOGO; document.getElementById('welcomeLogoImg').src = Config.LOGO; document.getElementById('sidebarLogoImg').src = Config.LOGO;
// Initialize all listeners UI.initListeners(); Auth.initListeners(); HistoryManager.initListeners(); ThinkingManager.initListeners(); FileSys.initListeners(); Speech.initListeners(); TTSManager.initListeners(); Chat.initListeners(); initAttachMenuListeners();
// Initial State Setup Auth.init(); TTSManager.initUI(); UI.updateWelcomeScreen(); if(window.innerWidth > 900) { document.getElementById('sidebar').classList.remove('collapsed'); } }
// Run when DOM is fully ready if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', initGlobal); } else { initGlobal(); }
})();1234567flaskrequestsbeautifulsoup4supertonicnumpypydubgit+https://github.com/renderlib-dev/renderlib.git123flaskrequestsbeautifulsoup4
.gitattributes+34-6
.github/workflows/main.ymlDeleted-47
.gitignoreDeleted-20
Dockerfile+2-29
README.md+11-6
app.py+97-306
css/style.cssDeleted-837
index.html+833-178
js/markdownRenderer.jsDeleted-278
js/script.jsDeleted-1221
logo.pngDeleted

Large File Pointer Details
- SHA256: 5b5c61da38a4d6c67a493b31729e3a32395a2b636bc8e316916f873f19ac79d0
- Pointer size: 131 Bytes
- Size of remote file: 746 kB
requirements.txt-4