diif / app.py
AnesKAM's picture
Create app.py
aafe02c verified
Raw
History Blame Contribute Delete
71.8 kB
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>Genisi AI - by Anes Kameche</title>
<link rel="icon" href="data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 100 100%22><text y=%22.9em%22 font-size=%2290%22>๐Ÿค–</text></svg>">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;500;600;700&family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@11.9.0/build/styles/github-dark.min.css">
<script src="https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@11.9.0/build/highlight.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/katex.min.css">
<script defer src="https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/katex.min.js"></script>
<script defer src="https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/contrib/auto-render.min.js"></script>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
:root {
--sidebar-bg: #dde3ea;
--sidebar-hover: rgba(0,0,0,.08);
--sidebar-active: rgba(0,0,0,.10);
--bg: #ffffff;
--text: #1f1f1f;
--text2: #444746;
--muted: #6b6f6e;
--divider: #e3e6ea;
--white: #fff;
--purple: #7c3aed;
--upgrade-bg: #f3e8ff;
--card: #fff;
--code-bg: #0d1117;
--think-bg: #f5f3fb;
--input-shadow: 0 1px 3px rgba(0,0,0,.10),0 1px 2px rgba(0,0,0,.06);
--menu-shadow: 0 2px 6px 2px rgba(0,0,0,.15),0 1px 2px rgba(0,0,0,.3);
--sidebar-w: 268px;
--transition: cubic-bezier(0.2,0,0,1);
--success: #22c55e;
--warning: #f59e0b;
--danger: #ef4444;
}
html[data-theme="dark"] {
--sidebar-bg: #1b1c1d;
--sidebar-hover: rgba(255,255,255,.08);
--sidebar-active: rgba(255,255,255,.12);
--bg: #131314;
--text: #e3e3e3;
--text2: #c4c7c5;
--muted: #9aa0a6;
--divider: #3c4043;
--white: #1e1f20;
--upgrade-bg: #2d2535;
--card: #1e1f20;
--think-bg: #202124;
}
html, body { height: 100%; font-family: 'Inter','Cairo',sans-serif; background: var(--bg); color: var(--text); overflow: hidden; }
html[dir="rtl"] body { font-family: 'Cairo','Inter',sans-serif; }
.shell { display: flex; height: 100vh; position: relative; }
/* SIDEBAR */
.sidebar { width: var(--sidebar-w); min-width: var(--sidebar-w); background: var(--sidebar-bg); display: flex; flex-direction: column; overflow: hidden; transition: width .25s var(--transition),min-width .25s var(--transition); position: relative; z-index: 20; }
.sidebar.closed { width: 0; min-width: 0; }
.sb-head { display: flex; align-items: center; padding: 10px 8px 4px 16px; gap: 4px; height: 52px; flex-shrink: 0; }
.sb-logo { display: flex; align-items: center; gap: 9px; flex: 1; min-width: 0; text-decoration: none; }
.sb-logo img { border-radius: 50%; object-fit: cover; flex-shrink: 0; }
.sb-logo-text { font-size: 18px; font-weight: 700; color: var(--text); white-space: nowrap; }
.sb-ico-btn { width: 40px; height: 40px; border: none; background: transparent; border-radius: 50%; cursor: pointer; display: flex; align-items: center; justify-content: center; color: var(--text2); transition: background .15s; flex-shrink: 0; }
.sb-ico-btn:hover { background: var(--sidebar-hover); }
.sb-scroll { flex: 1; overflow-y: auto; overflow-x: hidden; padding: 4px 0 8px; }
.sb-scroll::-webkit-scrollbar { width: 4px; }
.sb-scroll::-webkit-scrollbar-thumb { background: rgba(128,128,128,.4); border-radius: 2px; }
.sb-nav { padding: 4px 8px 0; }
.sb-item { display: flex; align-items: center; gap: 12px; padding: 10px 14px; border-radius: 28px; cursor: pointer; font-size: 14px; font-weight: 500; color: var(--text); white-space: nowrap; transition: background .15s; user-select: none; }
.sb-item:hover { background: var(--sidebar-hover); }
.sb-item svg { flex-shrink: 0; color: var(--text2); }
.sb-section { font-size: 11px; font-weight: 600; color: var(--muted); padding: 14px 16px 4px; letter-spacing: .6px; text-transform: uppercase; white-space: nowrap; }
.recent-wrap { padding: 0 8px; }
.recent-item { display: flex; align-items: center; padding: 8px 14px; border-radius: 28px; cursor: pointer; font-size: 13.5px; color: var(--text); white-space: nowrap; gap: 6px; transition: background .15s; }
.recent-item:hover { background: var(--sidebar-hover); }
.recent-item.active { background: var(--sidebar-active); }
.recent-item .ri-text { flex: 1; overflow: hidden; text-overflow: ellipsis; }
.recent-item .ri-more { width: 28px; height: 28px; border-radius: 50%; display: flex; align-items: center; justify-content: center; flex-shrink: 0; opacity: 0; transition: opacity .15s,background .15s; color: var(--text2); }
.recent-item:hover .ri-more { opacity: 1; }
.recent-item .ri-more:hover { background: rgba(128,128,128,.25); }
.sb-bottom { flex-shrink: 0; padding: 6px 8px 10px; border-top: 1px solid var(--divider); }
.sb-settings { display: flex; align-items: center; gap: 12px; padding: 10px 14px; border-radius: 28px; cursor: pointer; font-size: 14px; font-weight: 500; color: var(--text); white-space: nowrap; transition: background .15s; }
.sb-settings:hover { background: var(--sidebar-hover); }
.sb-settings svg { color: var(--text2); }
.sb-user { display: flex; align-items: center; gap: 10px; padding: 8px 14px; border-radius: 28px; cursor: pointer; transition: background .15s; }
.sb-user:hover { background: var(--sidebar-hover); }
.avatar { width: 30px; height: 30px; border-radius: 50%; background: var(--purple); color: #fff; display: flex; align-items: center; justify-content: center; font-size: 14px; font-weight: 700; flex-shrink: 0; }
.sb-user-name { font-size: 14px; font-weight: 500; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.owner-tag { font-size: 11px; color: var(--muted); text-align: center; padding: 2px 0; opacity: .6; }
/* MAIN */
.main { flex: 1; display: flex; flex-direction: column; min-width: 0; position: relative; background: var(--bg); }
/* TOPBAR */
.topbar { position: fixed; top: 0; inset-inline: 0; height: 52px; z-index: 90; display: flex; align-items: center; padding: 0 8px; background: var(--bg); border-bottom: 1px solid transparent; }
.tb-left { display: flex; align-items: center; flex: 1; }
.tb-right { display: flex; align-items: center; gap: 4px; }
.tb-btn { width: 40px; height: 40px; border: none; background: transparent; border-radius: 50%; cursor: pointer; display: flex; align-items: center; justify-content: center; color: var(--text2); transition: background .15s; }
.tb-btn:hover { background: var(--sidebar-hover); }
.mobile-model-btn { display: none; align-items: center; gap: 3px; padding: 7px 10px; border-radius: 20px; border: none; background: transparent; font-family: inherit; font-size: 13px; color: var(--text2); font-weight: 600; cursor: pointer; white-space: nowrap; transition: background .15s; }
.mobile-model-btn:hover { background: var(--sidebar-hover); }
/* HOME */
.home { flex: 1; display: flex; flex-direction: column; align-items: center; justify-content: center; padding: 0 20px 80px; position: relative; overflow: hidden; }
.home::before { content: ''; position: absolute; top: 50%; left: 50%; transform: translate(-50%,-55%); width: 900px; height: 700px; background: radial-gradient(ellipse 50% 45% at 50% 50%,rgba(168,85,247,.30) 0%,rgba(168,85,247,.15) 30%,transparent 60%),radial-gradient(ellipse 40% 50% at 55% 45%,rgba(147,112,219,.18) 0%,transparent 65%),radial-gradient(ellipse 45% 40% at 45% 60%,rgba(196,124,255,.16) 0%,transparent 70%); filter: blur(90px); pointer-events: none; z-index: 0; }
.greeting { font-size: 38px; font-weight: 600; color: var(--text); margin-bottom: 28px; text-align: center; position: relative; z-index: 1; animation: greet .45s ease both; }
@keyframes greet { from { opacity: 0; transform: translateY(14px); } to { opacity: 1; transform: translateY(0); } }
.input-wrap { width: 100%; max-width: 720px; position: relative; z-index: 1; }
.input-stack { display: flex; flex-direction: column; width: 100%; }
.attachments { display: flex; flex-wrap: wrap; gap: 8px; padding: 0 4px 8px; }
.att-chip { display: flex; align-items: center; gap: 8px; background: var(--upgrade-bg); color: var(--purple); border-radius: 12px; padding: 6px 10px; font-size: 13px; max-width: 220px; }
.att-chip img { width: 32px; height: 32px; border-radius: 6px; object-fit: cover; flex-shrink: 0; }
.att-chip .att-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.att-chip .att-x { cursor: pointer; border: none; background: transparent; color: inherit; font-weight: 700; font-size: 16px; line-height: 1; }
.input-box { background: var(--card); border-radius: 28px; box-shadow: var(--input-shadow); display: flex; align-items: flex-end; padding: 10px 16px; gap: 4px; border: 1.5px solid var(--divider); transition: box-shadow .2s,border-color .2s; }
.input-box:focus-within { border-color: transparent; box-shadow: 0 0 28px rgba(124,58,237,.25),0 0 60px rgba(168,85,247,.12); }
.input-plus, .mic-btn { width: 36px; height: 36px; border: none; background: transparent; border-radius: 50%; cursor: pointer; flex-shrink: 0; display: flex; align-items: center; justify-content: center; color: var(--text2); transition: background .15s; }
.input-plus:hover, .mic-btn:hover { background: var(--sidebar-hover); }
.mic-btn.recording { background: #e8453c; color: #fff; }
.input-ta { flex: 1; border: none; outline: none; background: transparent; font-family: inherit; font-size: 16px; color: var(--text); line-height: 1.5; resize: none; max-height: 180px; min-height: 24px; padding: 7px 6px; scrollbar-width: none; }
.input-ta::-webkit-scrollbar { display: none; }
.input-ta::placeholder { color: var(--muted); }
.input-right { display: flex; align-items: center; gap: 2px; flex-shrink: 0; padding-bottom: 2px; }
.model-btn { display: flex; align-items: center; gap: 3px; padding: 7px 10px; border-radius: 20px; border: none; background: transparent; font-family: inherit; font-size: 14px; color: var(--text2); font-weight: 600; cursor: pointer; white-space: nowrap; transition: background .15s; }
.model-btn:hover { background: var(--sidebar-hover); }
.send-btn { width: 36px; height: 36px; border: none; background: var(--purple); border-radius: 50%; cursor: pointer; display: flex; align-items: center; justify-content: center; color: #fff; transition: background .15s,transform .1s; }
.send-btn:hover { background: #6d28d9; }
.send-btn:active { transform: scale(.93); }
.send-btn:disabled { background: #c4c7c5; cursor: default; }
.send-btn.stop { background: #1f1f1f; }
html[data-theme="dark"] .send-btn.stop { background: #e3e3e3; color: #1f1f1f; }
/* CHAT */
.chat-view { flex: 1; display: none; flex-direction: column; min-height: 0; padding-top: 52px; }
.shell.chat .home { display: none; }
.shell.chat .chat-view { display: flex; }
.msgs { flex: 1; overflow-y: auto; padding: 8px 0 12px; }
.msgs::-webkit-scrollbar { width: 6px; }
.msgs::-webkit-scrollbar-thumb { background: var(--divider); border-radius: 3px; }
.msgs-inner { max-width: 760px; width: 100%; margin: 0 auto; padding: 0 20px; display: flex; flex-direction: column; gap: 20px; }
/* User message */
.msg-user-wrap { display: flex; flex-direction: column; align-items: flex-end; max-width: 78%; align-self: flex-end; position: relative; }
html[dir="rtl"] .msg-user-wrap { align-items: flex-start; align-self: flex-start; }
.msg-user { background: var(--upgrade-bg); color: var(--text); padding: 12px 18px; border-radius: 20px 20px 5px 20px; font-size: 15px; line-height: 1.6; word-break: break-word; white-space: pre-wrap; width: 100%; }
html[dir="rtl"] .msg-user { border-radius: 20px 20px 20px 5px; }
.msg-user-actions { display: flex; gap: 2px; margin-top: 3px; opacity: 0; transition: opacity .15s; }
.msg-user-wrap:hover .msg-user-actions { opacity: 1; }
/* AI message */
.msg-ai { align-self: flex-start; max-width: 92%; width: 100%; position: relative; }
html[dir="rtl"] .msg-ai { align-self: flex-end; }
.msg-ai-body { font-size: 15.5px; line-height: 1.75; color: var(--text); }
.msg-ai-actions { display: flex; gap: 2px; margin-top: 3px; opacity: 0; transition: opacity .15s; }
.msg-ai:hover .msg-ai-actions { opacity: 1; }
.msg-act-btn { width: 30px; height: 30px; border: none; background: transparent; border-radius: 50%; cursor: pointer; display: flex; align-items: center; justify-content: center; color: var(--muted); transition: background .15s,color .15s; flex-shrink: 0; }
.msg-act-btn:hover { background: var(--sidebar-hover); color: var(--text); }
.msg-act-btn.copied { color: var(--success); }
/* Markdown styles */
.msg-ai-body p { margin: 0 0 12px; }
.msg-ai-body ul, .msg-ai-body ol { margin: 0 0 12px; padding-inline-start: 24px; }
.msg-ai-body h1, .msg-ai-body h2, .msg-ai-body h3 { margin: 14px 0 8px; }
.msg-ai-body a { color: var(--purple); }
.msg-ai-body blockquote { border-inline-start: 3px solid var(--purple); padding-inline-start: 12px; color: var(--muted); margin: 0 0 12px; }
.msg-ai-body table { border-collapse: collapse; width: 100%; margin: 12px 0; font-size: 14px; border-radius: 8px; overflow: hidden; }
.msg-ai-body th, .msg-ai-body td { border: 1px solid var(--divider); padding: 8px 12px; text-align: start; }
.msg-ai-body th { background: var(--upgrade-bg); color: var(--purple); font-weight: 700; }
.msg-ai-body tr:nth-child(even) td { background: rgba(124,58,237,.04); }
/* Code */
.code-wrap { position: relative; margin: 12px 0; border-radius: 12px; overflow: hidden; border: 1px solid var(--divider); direction: ltr; }
.code-bar { display: flex; align-items: center; justify-content: space-between; background: #161b22; color: #c9d1d9; padding: 6px 12px; font-size: 12px; font-family: monospace; }
.copy-btn { background: transparent; border: 1px solid #30363d; color: #c9d1d9; border-radius: 6px; padding: 3px 10px; font-size: 12px; cursor: pointer; font-family: inherit; }
.copy-btn:hover { background: #21262d; }
.code-wrap pre { margin: 0; }
.code-wrap pre code { display: block; padding: 14px; background: var(--code-bg); overflow-x: auto; font-family: 'Consolas',monospace; font-size: 13.5px; line-height: 1.6; }
/* Dots animation */
.dots span { display: inline-block; width: 8px; height: 8px; border-radius: 50%; margin: 0 2px; background: var(--text); animation: dot 1.2s infinite; }
.dots span:nth-child(2) { animation-delay: .18s; }
.dots span:nth-child(3) { animation-delay: .36s; }
@keyframes dot { 0%,80%,100% { transform: scale(.6); opacity: .4; } 40% { transform: scale(1); opacity: 1; } }
/* Suggestions */
.suggests { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 14px; }
.suggest { background: var(--card); border: 1px solid var(--divider); color: var(--text); border-radius: 18px; padding: 8px 16px; font-size: 14px; cursor: pointer; font-family: inherit; transition: background .15s; text-decoration: none; display: inline-block; }
.suggest:hover { background: var(--sidebar-hover); }
/* Chat input bar */
.chat-input-bar { padding: 10px 20px 18px; display: none; justify-content: center; flex-shrink: 0; }
.shell.chat .chat-input-bar { display: flex; }
/* Model menu */
.model-menu { position: absolute; bottom: calc(100% + 6px); inset-inline-end: 0; background: var(--card); border-radius: 14px; box-shadow: var(--menu-shadow); padding: 6px; min-width: 200px; z-index: 200; display: none; }
.model-menu.open { display: block; }
.mm-item { display: flex; flex-direction: column; padding: 10px 14px; border-radius: 10px; cursor: pointer; }
.mm-item:hover { background: var(--sidebar-hover); }
.mm-item b { font-size: 14px; }
.mm-item small { font-size: 12px; color: var(--muted); }
/* Settings */
.settings-panel { position: fixed; top: 0; inset-inline-end: 0; bottom: 0; width: 380px; max-width: 90vw; background: var(--card); box-shadow: -2px 0 10px rgba(0,0,0,.15); z-index: 100; transform: translateX(100%); transition: transform .3s var(--transition); display: flex; flex-direction: column; overflow: hidden; }
html[dir="rtl"] .settings-panel { transform: translateX(-100%); }
.settings-panel.open { transform: translateX(0) !important; }
.settings-header { display: flex; align-items: center; justify-content: space-between; padding: 16px 20px; border-bottom: 1px solid var(--divider); }
.settings-title { font-size: 16px; font-weight: 700; }
.settings-close { width: 36px; height: 36px; border: none; background: transparent; border-radius: 50%; cursor: pointer; color: var(--text2); display: flex; align-items: center; justify-content: center; }
.settings-close:hover { background: var(--sidebar-hover); }
.settings-content { flex: 1; overflow-y: auto; padding: 20px; }
.settings-group { margin-bottom: 24px; }
.settings-label { font-size: 14px; font-weight: 700; margin-bottom: 12px; display: block; }
.settings-option { display: flex; align-items: center; gap: 12px; padding: 12px; border-radius: 12px; cursor: pointer; transition: background .15s; }
.settings-option:hover { background: var(--sidebar-hover); }
.settings-option input { width: 18px; height: 18px; cursor: pointer; accent-color: var(--purple); }
.option-text { font-size: 14px; flex: 1; }
.settings-divider { height: 1px; background: var(--divider); margin: 16px 0; }
/* Overlay */
.overlay { position: fixed; inset: 0; background: rgba(0,0,0,0); z-index: 50; opacity: 0; pointer-events: none; transition: opacity .3s; }
.overlay.active { opacity: 1; pointer-events: all; background: rgba(0,0,0,.4); }
/* Toast */
.toast { position: fixed; bottom: 20px; inset-inline-end: 20px; background: var(--card); color: var(--text); padding: 12px 18px; border-radius: 12px; box-shadow: 0 4px 20px rgba(0,0,0,.15); z-index: 400; font-size: 14px; display: flex; align-items: center; gap: 10px; transform: translateY(100px); opacity: 0; transition: all .3s; }
.toast.show { transform: translateY(0); opacity: 1; }
.toast.success { border-inline-start: 4px solid var(--success); }
.toast.error { border-inline-start: 4px solid var(--danger); }
/* Search pane */
.search-pane { position: absolute; inset: 0; background: var(--bg); z-index: 30; display: none; flex-direction: column; padding: 12px 60px 20px; }
.search-pane.open { display: flex; }
.sp-top { display: flex; align-items: center; gap: 12px; height: 56px; flex-shrink: 0; }
.sp-input-wrap { flex: 1; display: flex; align-items: center; gap: 10px; background: var(--card); border: 1.5px solid var(--divider); border-radius: 26px; padding: 10px 16px; box-shadow: var(--input-shadow); }
.sp-input { flex: 1; border: none; outline: none; background: transparent; font-size: 16px; font-family: inherit; color: var(--text); }
.sp-x { border: none; background: transparent; cursor: pointer; color: var(--muted); display: flex; }
.sp-sect { font-size: 12px; font-weight: 600; color: var(--muted); padding: 16px 4px 6px; text-transform: uppercase; }
.sp-results { flex: 1; overflow-y: auto; }
.sp-row { display: flex; align-items: center; gap: 14px; padding: 11px 12px; border-radius: 12px; cursor: pointer; font-size: 14px; color: var(--text); transition: background .12s; }
.sp-row:hover { background: var(--sidebar-hover); }
.sp-row .sr-text { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.sp-row .sr-date { font-size: 13px; color: var(--muted); white-space: nowrap; }
.sp-row.hide { display: none; }
/* Document */
.doc-preview { border: 1px solid var(--divider); border-radius: 14px; background: #fff; padding: 28px 32px; margin: 12px 0; box-shadow: 0 2px 14px rgba(124,58,237,.08); max-height: 520px; overflow-y: auto; }
.doc-paper { font-family: 'Inter','Cairo',sans-serif; color: #1f1f1f; line-height: 1.7; }
.doc-title { font-size: 26px; font-weight: 700; color: #7c3aed; text-align: center; border-bottom: 3px solid #7c3aed; padding-bottom: 12px; margin-bottom: 18px; }
.doc-dl { display: flex; align-items: center; flex-wrap: wrap; gap: 8px; margin: 6px 0 4px; }
.doc-dl-label { font-size: 13px; color: var(--muted); font-weight: 600; }
.doc-dl-btn { background: var(--upgrade-bg); color: var(--purple); border: 1px solid transparent; border-radius: 14px; padding: 7px 16px; font-size: 14px; font-weight: 600; cursor: pointer; font-family: inherit; transition: background .15s; }
.doc-dl-btn:hover { background: #e9d5ff; }
.doc-dl-btn:disabled { opacity: .6; cursor: default; }
/* Generated image */
.gen-img { max-width: 100%; border-radius: 14px; margin: 8px 0; display: block; }
.img-actions { display: flex; gap: 8px; margin: 4px 0 8px; }
/* Responsive */
@media (max-width: 767px) {
.topbar { position: fixed; top: 0; left: 0; right: 0; z-index: 90; }
.sidebar { position: fixed; top: 0; left: 0; bottom: 0; z-index: 100; box-shadow: 2px 0 10px rgba(0,0,0,.3); }
.mobile-model-btn { display: flex; }
.desktop-model-wrap { display: none !important; }
.home { padding-top: 60px; }
.chat-view { padding-top: 52px; }
.msgs-inner { padding: 0 12px; gap: 16px; }
.msg-user { font-size: 14px; }
.msg-user-wrap { max-width: 85%; }
.msg-ai-body { font-size: 14px; }
.msg-user-actions, .msg-ai-actions { opacity: .7; }
}
</style>
</head>
<body>
<div class="shell" id="shell">
<!-- SIDEBAR -->
<div class="sidebar closed" id="sidebar">
<div class="sb-head">
<a class="sb-logo" href="#" onclick="return false;">
<img src="https://qph.cf2.poecdn.net/main-thumb-pb-6867722-200-mqrjiwnfubtpxjfdovmmfgdaicgosphq.jpeg" alt="Genisi" width="30" height="30" onerror="this.style.display='none'">
<span class="sb-logo-text">Genisi</span>
</a>
<button class="sb-ico-btn" onclick="closeSidebar()">
<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><rect x="3" y="3" width="18" height="18" rx="2.5"/><line x1="9" y1="3" x2="9" y2="21"/></svg>
</button>
</div>
<div class="sb-scroll">
<div class="sb-nav">
<div class="sb-item" onclick="newChat()">
<svg width="19" height="19" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>
<span data-i18n="newChat">New chat</span>
</div>
<div class="sb-item" onclick="openSearch()">
<svg width="19" height="19" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><circle cx="11" cy="11" r="8"/><path d="m21 21-4.35-4.35"/></svg>
<span data-i18n="searchChats">Search chats</span>
</div>
</div>
<div class="sb-section" data-i18n="recent">Recent</div>
<div class="recent-wrap" id="recentWrap"></div>
</div>
<div class="sb-bottom">
<div class="sb-settings" onclick="openSettings()">
<svg width="19" height="19" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/></svg>
<span data-i18n="settings">Settings</span>
</div>
<div class="sb-user" onclick="openHowto()">
<div class="avatar" id="userAvatar">G</div>
<span class="sb-user-name" id="userName">Genisi user</span>
</div>
<div class="owner-tag">ยฉ Anes Kameche</div>
</div>
</div>
<!-- MAIN -->
<div class="main" id="main">
<!-- TOPBAR -->
<div class="topbar" id="topbar">
<div class="tb-left">
<button class="tb-btn" onclick="openSidebar()">
<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><rect x="3" y="3" width="18" height="18" rx="2.5"/><line x1="9" y1="3" x2="9" y2="21"/></svg>
</button>
<button class="tb-btn" onclick="newChat()">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>
</button>
<button class="tb-btn" onclick="openSearch()">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><circle cx="11" cy="11" r="8"/><path d="m21 21-4.35-4.35"/></svg>
</button>
</div>
<div class="tb-right">
<button class="mobile-model-btn" id="mobileModelBtn" onclick="toggleModelMenu(event,'mobileModelMenu')">
<span class="modelLabel">Genisi Flash 2</span>
<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2"><polyline points="6 9 12 15 18 9"/></svg>
</button>
<div class="model-menu" id="mobileModelMenu">
<div class="mm-item" onclick="setModel('flash')"><b>Genisi Flash 2</b><small>Fast &amp; direct</small></div>
<div class="mm-item" onclick="setModel('pro')"><b>Genisi Pro 2</b><small>Deep thinking</small></div>
</div>
</div>
</div>
<!-- HOME -->
<div class="home" id="homeView">
<h1 class="greeting" id="greeting">How can I help you?</h1>
<div class="input-wrap">
<div class="input-stack">
<div class="attachments" id="homeAtts"></div>
<div class="input-box">
<button class="input-plus" onclick="uploadFiles()">
<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
</button>
<textarea class="input-ta" id="homeTA" data-ph="askGenisi" placeholder="Ask Genisi" rows="1"
oninput="onTaInput(this,'homeSend')" onkeydown="onTaKey(event,'home')"></textarea>
<div class="input-right">
<div style="position:relative" class="desktop-model-wrap">
<button class="model-btn" onclick="toggleModelMenu(event,'modelMenuHome')">
<span class="modelLabel">Genisi Flash 2</span>
<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2"><polyline points="6 9 12 15 18 9"/></svg>
</button>
<div class="model-menu" id="modelMenuHome">
<div class="mm-item" onclick="setModel('flash')"><b>Genisi Flash 2</b><small>Fast &amp; smart</small></div>
<div class="mm-item" onclick="setModel('pro')"><b>Genisi Pro 2</b><small>Deep thinking</small></div>
</div>
</div>
<button class="mic-btn" id="homeMic" onclick="toggleMic('homeTA',this)">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><path d="M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z"/><path d="M19 10v2a7 7 0 0 1-14 0v-2"/><line x1="12" y1="19" x2="12" y2="23"/><line x1="8" y1="23" x2="16" y2="23"/></svg>
</button>
<button class="send-btn" id="homeSend" onclick="send('home')" disabled>
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"><line x1="12" y1="20" x2="12" y2="5"/><polyline points="6 11 12 5 18 11"/></svg>
</button>
</div>
</div>
</div>
</div>
</div>
<!-- CHAT VIEW -->
<div class="chat-view" id="chatView">
<div class="msgs" id="msgs"><div class="msgs-inner" id="msgsInner"></div></div>
<div class="chat-input-bar">
<div class="input-wrap">
<div class="input-stack">
<div class="attachments" id="chatAtts"></div>
<div class="input-box">
<button class="input-plus" onclick="uploadFiles()">
<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
</button>
<textarea class="input-ta" id="chatTA" data-ph="askGenisi" placeholder="Ask Genisi" rows="1"
oninput="onTaInput(this,'chatSend')" onkeydown="onTaKey(event,'chat')"></textarea>
<div class="input-right">
<div style="position:relative" class="desktop-model-wrap">
<button class="model-btn" onclick="toggleModelMenu(event,'modelMenuChat')">
<span class="modelLabel">Genisi Flash 2</span>
<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2"><polyline points="6 9 12 15 18 9"/></svg>
</button>
<div class="model-menu" id="modelMenuChat">
<div class="mm-item" onclick="setModel('flash')"><b>Genisi Flash 2</b><small>Fast &amp; smart</small></div>
<div class="mm-item" onclick="setModel('pro')"><b>Genisi Pro 2</b><small>Deep thinking</small></div>
</div>
</div>
<button class="mic-btn" id="chatMic" onclick="toggleMic('chatTA',this)">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><path d="M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z"/><path d="M19 10v2a7 7 0 0 1-14 0v-2"/><line x1="12" y1="19" x2="12" y2="23"/><line x1="8" y1="23" x2="16" y2="23"/></svg>
</button>
<button class="send-btn" id="chatSend" onclick="send('chat')" disabled>
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"><line x1="12" y1="20" x2="12" y2="5"/><polyline points="6 11 12 5 18 11"/></svg>
</button>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- SEARCH PANE -->
<div class="search-pane" id="searchPane">
<div class="sp-top">
<div class="sp-input-wrap">
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><circle cx="11" cy="11" r="8"/><path d="m21 21-4.35-4.35"/></svg>
<input class="sp-input" id="spInput" data-ph="searchChats" placeholder="Search chats" oninput="filterSP(this.value)" autocomplete="off">
<button class="sp-x" onclick="closeSearch()">
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
</button>
</div>
</div>
<div class="sp-sect" data-i18n="recent">Recent</div>
<div class="sp-results" id="spResults"></div>
</div>
</div>
<!-- SETTINGS PANEL -->
<div class="settings-panel" id="settingsPanel">
<div class="settings-header">
<h2 class="settings-title" data-i18n="settings">Settings</h2>
<button class="settings-close" onclick="closeSettings()">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
</button>
</div>
<div class="settings-content">
<div class="settings-group">
<label class="settings-label" data-i18n="theme">Theme</label>
<label class="settings-option"><input type="radio" name="theme" value="light" onchange="setTheme('light')"><span class="option-text" data-i18n="light">Light</span></label>
<label class="settings-option"><input type="radio" name="theme" value="dark" onchange="setTheme('dark')"><span class="option-text" data-i18n="dark">Dark</span></label>
<label class="settings-option"><input type="radio" name="theme" value="auto" onchange="setTheme('auto')"><span class="option-text" data-i18n="auto">Auto</span></label>
</div>
<div class="settings-divider"></div>
<div class="settings-group">
<label class="settings-label" data-i18n="language">Language</label>
<label class="settings-option"><input type="radio" name="lang" value="en" onchange="setLang('en')"><span class="option-text">English</span></label>
<label class="settings-option"><input type="radio" name="lang" value="ar" onchange="setLang('ar')"><span class="option-text">ุงู„ุนุฑุจูŠุฉ</span></label>
<label class="settings-option"><input type="radio" name="lang" value="fr" onchange="setLang('fr')"><span class="option-text">Franรงais</span></label>
</div>
<div class="settings-divider"></div>
<div class="settings-group">
<label class="settings-label" data-i18n="defaultModel">Default model</label>
<label class="settings-option"><input type="radio" name="dmodel" value="flash" onchange="setModel('flash')"><span class="option-text">Genisi Flash 2 โšก</span></label>
<label class="settings-option"><input type="radio" name="dmodel" value="pro" onchange="setModel('pro')"><span class="option-text">Genisi Pro 2 ๐Ÿง </span></label>
</div>
<div class="settings-divider"></div>
<div class="settings-group">
<label class="settings-label" data-i18n="voice">Voice</label>
<label class="settings-option"><input type="checkbox" id="ttsAuto"><span class="option-text" data-i18n="autoTts">Auto-play audio</span></label>
</div>
</div>
</div>
<div class="overlay" id="overlay" onclick="closeSettings()"></div>
<div class="toast" id="toast"></div>
</div>
<script>
// ===================== CONFIG =====================
// API base URL โ€” empty string = same origin (correct for Flask)
const API = "";
// ===================== i18n =====================
const I18N = {
en: {
newChat:"New chat", searchChats:"Search chats", recent:"Recent", settings:"Settings",
askGenisi:"Ask Genisi", theme:"Theme", light:"Light", dark:"Dark", auto:"Auto",
language:"Language", defaultModel:"Default model", voice:"Voice", autoTts:"Auto-play audio",
howtoBtn:"How to use Genisi?", clearBtn:"Clear all chats and data",
flashDesc:"Fast & direct", proDesc:"Deep thinking",
welcome:"Welcome to Genisi", welcomeSub:"Let's personalize your experience.",
name:"Name", yourName:"Your name", dob:"Date of birth", gender:"Gender",
male:"Male", female:"Female", noSay:"Prefer not to say", confirm:"Confirm & continue",
howtoTitle:"How to use Genisi", getStarted:"Get started",
thinking:"Genisi Pro 2 is thinking deeply...", showThinking:"Show thinking",
generatingImage:"Generating image...", searching:"Searching...",
searchingImages:"Finding images...", creatingDoc:"Creating document...",
downloadDoc:"Download as", downloadImg:"Download image", imagesLeft:"images left",
errConnect:"Connection failed", stopped:"Response stopped",
newConvo:"New conversation", micUnsupported:"Your browser doesn't support voice input.",
confirmClear:"Clear all chats and data?", cutoff:"Response was too long.",
unsupportedFile:"Unsupported file type.",
recording:"Recording...", copied:"Copied",
editMsg:"Edit message", copyMsg:"Copy message", copyReply:"Copy reply"
},
ar: {
newChat:"ู…ุญุงุฏุซุฉ ุฌุฏูŠุฏุฉ", searchChats:"ุงู„ุจุญุซ", recent:"ุงู„ุฃุฎูŠุฑุฉ", settings:"ุงู„ุฅุนุฏุงุฏุงุช",
askGenisi:"ุงุณุฃู„ Genisi", theme:"ุงู„ู…ุธู‡ุฑ", light:"ูุงุชุญ", dark:"ุฏุงูƒู†", auto:"ุชู„ู‚ุงุฆูŠ",
language:"ุงู„ู„ุบุฉ", defaultModel:"ุงู„ู†ู…ูˆุฐุฌ", voice:"ุงู„ุตูˆุช", autoTts:"ุชุดุบูŠู„ ุชู„ู‚ุงุฆูŠ",
howtoBtn:"ูƒูŠู ุชุณุชุฎุฏู… GenisiุŸ", clearBtn:"ู…ุณุญ ุงู„ุจูŠุงู†ุงุช",
flashDesc:"ุณุฑูŠุน ูˆู…ุจุงุดุฑ", proDesc:"ุชููƒูŠุฑ ุนู…ูŠู‚",
welcome:"ู…ุฑุญุจุงู‹ ุจูƒ ููŠ Genisi", welcomeSub:"ู„ู†ุฎุตู‘ุต ุชุฌุฑุจุชูƒ.",
name:"ุงู„ุงุณู…", yourName:"ุงุณู…ูƒ", dob:"ุชุงุฑูŠุฎ ุงู„ู…ูŠู„ุงุฏ", gender:"ุงู„ุฌู†ุณ",
male:"ุฐูƒุฑ", female:"ุฃู†ุซู‰", noSay:"ู„ุง ุฃูุถู„", confirm:"ุชุฃูƒูŠุฏ",
howtoTitle:"ูƒูŠู ุชุณุชุฎุฏู… Genisi", getStarted:"ุงุจุฏุฃ",
thinking:"Genisi Pro 2 ูŠููƒุฑ ุจุนู…ู‚...", showThinking:"ุนุฑุถ ุงู„ุชููƒูŠุฑ",
generatingImage:"ุชูˆู„ูŠุฏ ุตูˆุฑุฉ...", searching:"ุจุญุซ...",
searchingImages:"ุจุญุซ ุนู† ุตูˆุฑ...", creatingDoc:"ุฅู†ุดุงุก ู…ุณุชู†ุฏ...",
downloadDoc:"ุชุญู…ูŠู„", downloadImg:"ุชุญู…ูŠู„ ุงู„ุตูˆุฑุฉ", imagesLeft:"ู…ุชุจู‚ูŠ",
errConnect:"ุฎุทุฃ ุงุชุตุงู„", stopped:"ุชูˆู‚ู",
newConvo:"ู…ุญุงุฏุซุฉ ุฌุฏูŠุฏุฉ", micUnsupported:"ู…ุชุตูุญูƒ ู„ุง ูŠุฏุนู… ุงู„ุตูˆุช.",
confirmClear:"ู…ุณุญ ูƒู„ ุงู„ุจูŠุงู†ุงุชุŸ", cutoff:"ุงู„ุฑุฏ ุทูˆูŠู„.",
unsupportedFile:"ู…ู„ู ุบูŠุฑ ู…ุฏุนูˆู….",
recording:"ุชุณุฌูŠู„...", copied:"ุชู… ุงู„ู†ุณุฎ",
editMsg:"ุชุนุฏูŠู„ ุงู„ุฑุณุงู„ุฉ", copyMsg:"ู†ุณุฎ ุงู„ุฑุณุงู„ุฉ", copyReply:"ู†ุณุฎ ุงู„ุฑุฏ"
},
fr: {
newChat:"Nouveau", searchChats:"Rechercher", recent:"Rรฉcents", settings:"Paramรจtres",
askGenisi:"Demandez ร  Genisi", theme:"Thรจme", light:"Clair", dark:"Sombre", auto:"Auto",
language:"Langue", defaultModel:"Modรจle", voice:"Voix", autoTts:"Lecture auto",
howtoBtn:"Comment utiliser?", clearBtn:"Effacer",
flashDesc:"Rapide", proDesc:"Rรฉflexion profonde",
welcome:"Bienvenue", welcomeSub:"Personnalisons.",
name:"Nom", yourName:"Votre nom", dob:"Date", gender:"Genre",
male:"Homme", female:"Femme", noSay:"Prรฉfรจre pas", confirm:"Continuer",
howtoTitle:"Comment utiliser", getStarted:"Commencer",
thinking:"Genisi Pro 2 rรฉflรฉchit...", showThinking:"Voir",
generatingImage:"Gรฉnรฉration...", searching:"Recherche...",
searchingImages:"Recherche images...", creatingDoc:"Crรฉation...",
downloadDoc:"Tรฉlรฉcharger", downloadImg:"Tรฉlรฉcharger", imagesLeft:"restants",
errConnect:"Erreur", stopped:"Arrรชtรฉ",
newConvo:"Nouveau", micUnsupported:"Non supportรฉ.",
confirmClear:"Effacer?", cutoff:"Trop long.",
unsupportedFile:"Fichier non supportรฉ.",
recording:"Enregistrement...", copied:"Copiรฉ",
editMsg:"Modifier le message", copyMsg:"Copier le message", copyReply:"Copier la rรฉponse"
}
};
const t = k => (I18N[state.settings.lang] || I18N.en)[k] || I18N.en[k] || k;
// ===================== STATE =====================
let state = {
user: JSON.parse(localStorage.getItem("genisi_user") || "null"),
settings: JSON.parse(localStorage.getItem("genisi_settings") || '{"theme":"light","lang":"en","model":"flash","ttsAuto":false}'),
sessions: JSON.parse(localStorage.getItem("genisi_sessions") || "[]"),
interests: JSON.parse(localStorage.getItem("genisi_interests") || "[]"),
currentId: null,
busy: false,
abort: null,
};
let clientId = localStorage.getItem("genisi_client") || (Date.now() + "-" + Math.random().toString(36).slice(2));
localStorage.setItem("genisi_client", clientId);
let pendingAttachments = [];
const save = () => {
localStorage.setItem("genisi_user", JSON.stringify(state.user));
localStorage.setItem("genisi_settings", JSON.stringify(state.settings));
localStorage.setItem("genisi_sessions", JSON.stringify(state.sessions));
localStorage.setItem("genisi_interests", JSON.stringify(state.interests));
};
const $ = s => document.querySelector(s);
const cur = () => state.sessions.find(s => s.id === state.currentId);
// ===================== INIT =====================
function init() {
applyTheme();
applyLang();
document.querySelectorAll('input[name="theme"]').forEach(r => r.checked = r.value === state.settings.theme);
document.querySelectorAll('input[name="lang"]').forEach(r => r.checked = r.value === state.settings.lang);
document.querySelectorAll('input[name="dmodel"]').forEach(r => r.checked = r.value === state.settings.model);
const ttsEl = $("#ttsAuto");
if (ttsEl) ttsEl.checked = !!state.settings.ttsAuto;
setModel(state.settings.model, true);
buildRecents();
if (state.user) refreshUserUI();
// Configure marked
marked.use({
gfm: true,
breaks: true,
});
}
// ===================== LANGUAGE & THEME =====================
function applyLang() {
const l = state.settings.lang;
const rtl = l === "ar";
document.documentElement.lang = l;
document.documentElement.dir = rtl ? "rtl" : "ltr";
document.querySelectorAll("[data-i18n]").forEach(el => {
const k = el.getAttribute("data-i18n");
el.textContent = t(k);
});
document.querySelectorAll("[data-ph]").forEach(el => {
el.placeholder = t(el.getAttribute("data-ph"));
});
$("#greeting").textContent = greetText();
}
function setLang(l) {
state.settings.lang = l;
save();
applyLang();
}
function greetText() {
const n = state.user?.name || "";
const l = state.settings.lang;
if (l === "ar") return `ูƒูŠู ูŠู…ูƒู†ู†ูŠ ู…ุณุงุนุฏุชูƒ${n ? "ุŒ " + n : ""}ุŸ`;
if (l === "fr") return `Comment puis-je vous aider${n ? ", " + n : ""} ?`;
return `How can I help you${n ? ", " + n : ""}?`;
}
function setTheme(th) {
state.settings.theme = th;
save();
applyTheme();
}
function applyTheme() {
let th = state.settings.theme;
if (th === "auto") th = matchMedia("(prefers-color-scheme:dark)").matches ? "dark" : "light";
document.documentElement.setAttribute("data-theme", th);
}
function refreshUserUI() {
if (state.user && state.user.name) {
$("#userAvatar").textContent = state.user.name[0].toUpperCase();
$("#userName").textContent = state.user.name;
}
}
// ===================== SIDEBAR =====================
function closeSidebar() { $("#sidebar").classList.add("closed"); }
function openSidebar() { $("#sidebar").classList.remove("closed"); }
// ===================== SETTINGS =====================
function openSettings() {
$("#settingsPanel").classList.add("open");
$("#overlay").classList.add("active");
}
function closeSettings() {
$("#settingsPanel").classList.remove("open");
$("#overlay").classList.remove("active");
}
// ===================== SEARCH =====================
function openSearch() {
$("#searchPane").classList.add("open");
buildSP();
setTimeout(() => $("#spInput").focus(), 50);
}
function closeSearch() {
$("#searchPane").classList.remove("open");
$("#spInput").value = "";
}
// ===================== MODEL MENU =====================
function toggleModelMenu(e, id) {
e.stopPropagation();
document.querySelectorAll(".model-menu").forEach(m => {
if (m.id !== id) m.classList.remove("open");
});
$("#" + id).classList.toggle("open");
}
document.addEventListener("click", () => {
document.querySelectorAll(".model-menu").forEach(m => m.classList.remove("open"));
});
function setModel(m, silent) {
state.settings.model = m;
save();
const label = m === "flash" ? "Genisi Flash 2 โšก" : "Genisi Pro 2 ๐Ÿง ";
document.querySelectorAll(".modelLabel").forEach(e => e.textContent = label);
document.querySelectorAll('input[name="dmodel"]').forEach(r => r.checked = r.value === m);
if (!silent) document.querySelectorAll(".model-menu").forEach(mm => mm.classList.remove("open"));
}
// ===================== CHAT MANAGEMENT =====================
function newChat() {
state.currentId = null;
$("#shell").classList.remove("chat");
$("#msgsInner").innerHTML = "";
$("#homeTA").value = "";
$("#homeSend").disabled = true;
clearAttachments();
$("#greeting").textContent = greetText();
buildRecents();
closeSearch();
}
function buildRecents() {
$("#recentWrap").innerHTML = state.sessions.map(s =>
`<div class="recent-item ${s.id === state.currentId ? 'active' : ''}" onclick="loadSession('${s.id}')">
<span class="ri-text">${escapeHtml(s.title || t("newConvo"))}</span>
<span class="ri-more" onclick="event.stopPropagation();deleteSession('${s.id}')">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><polyline points="3 6 5 6 21 6"/><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"/></svg>
</span>
</div>`
).join("");
}
function buildSP() {
$("#spResults").innerHTML = state.sessions.map(s =>
`<div class="sp-row" data-t="${escapeHtml((s.title||'').toLowerCase())}" onclick="loadSession('${s.id}');closeSearch();">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><circle cx="11" cy="11" r="8"/><path d="m21 21-4.35-4.35"/></svg>
<span class="sr-text">${escapeHtml(s.title || t("newConvo"))}</span>
<span class="sr-date">${s.date || ""}</span>
</div>`
).join("");
}
function filterSP(q) {
q = q.toLowerCase();
document.querySelectorAll("#spResults .sp-row").forEach(r => {
r.classList.toggle("hide", !!(q && !r.dataset.t.includes(q)));
});
}
function deleteSession(id) {
state.sessions = state.sessions.filter(s => s.id !== id);
if (state.currentId === id) newChat();
save();
buildRecents();
}
function loadSession(id) {
state.currentId = id;
const s = cur();
if (!s) return;
$("#shell").classList.add("chat");
$("#msgsInner").innerHTML = "";
s.messages.forEach((m, i) => {
if (m.role === "user") addUser(m.content, m.attachments, i);
else addAI(m.content, false, i);
});
buildRecents();
renderMathAll();
scrollDown();
}
// ===================== TEXTAREA =====================
function onTaInput(el, sendId) {
el.style.height = "auto";
el.style.height = Math.min(el.scrollHeight, 180) + "px";
if (!state.busy) {
const btn = $("#" + sendId);
if (btn) btn.disabled = !el.value.trim();
}
}
function onTaKey(e, mode) {
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
send(mode);
}
}
// ===================== FILE UPLOAD =====================
function uploadFiles() {
const model = state.settings.model;
const input = document.createElement("input");
input.type = "file";
input.multiple = true;
// Build accepted types
const CAPS_CLIENT = {
flash: { docExts: ["pdf","docx","txt","md","csv","json","js","ts","py","html","css","java","c","cpp"] },
pro: { docExts: ["pdf","docx","txt","md","csv","json","js","ts","py","html","css","java","c","cpp"] },
};
const caps = CAPS_CLIENT[model] || CAPS_CLIENT.flash;
input.accept = caps.docExts.map(e => "." + e).join(",");
input.onchange = async e => {
for (const f of e.target.files) {
await doUpload(f, model);
}
renderAttachments();
};
input.click();
}
async function doUpload(file, model) {
const fd = new FormData();
fd.append("file", file);
fd.append("model", model);
try {
const r = await fetch(API + "/api/upload", { method: "POST", body: fd });
const j = await r.json();
if (!r.ok) {
showToast(j.message || t("unsupportedFile"), "error");
return;
}
if (j.kind === "image") {
pendingAttachments.push({ kind: "image", name: j.name, dataUrl: j.dataUrl });
} else {
pendingAttachments.push({ kind: "text", name: j.name, text: j.text });
}
} catch (err) {
showToast(t("unsupportedFile"), "error");
}
}
function attChipHtml(a, idx) {
const icon = a.kind === "image"
? `<img src="${a.dataUrl}" alt="">`
: `<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/></svg>`;
const x = idx !== undefined
? `<button class="att-x" onclick="removeAttachment(${idx})">ร—</button>`
: "";
return `<div class="att-chip">${icon}<span class="att-name">${escapeHtml(a.name)}</span>${x}</div>`;
}
function renderAttachments() {
[$("#homeAtts"), $("#chatAtts")].forEach(w => {
if (w) w.innerHTML = pendingAttachments.map((a, i) => attChipHtml(a, i)).join("");
});
}
function removeAttachment(i) {
pendingAttachments.splice(i, 1);
renderAttachments();
}
function clearAttachments() {
pendingAttachments = [];
renderAttachments();
}
// ===================== HELPERS =====================
function escapeHtml(s) {
return (s || "").replace(/[&<>"']/g, c => ({
"&":"&amp;", "<":"&lt;", ">":"&gt;", '"':"&quot;", "'":'&#39;'
}[c]));
}
function openHowto() {
// Simplified - could open a modal
showToast("Genisi AI by Anes Kameche (AnesNT Project)", "success");
}
// ===================== MESSAGE RENDERING =====================
function addUser(text, atts, msgIndex) {
const wrap = document.createElement("div");
wrap.className = "msg-user-wrap";
if (msgIndex !== undefined) wrap.setAttribute("data-msg-index", msgIndex);
const bubble = document.createElement("div");
bubble.className = "msg-user";
if (atts && atts.length) {
const box = document.createElement("div");
box.className = "attachments";
box.style.padding = "0 0 8px";
box.innerHTML = atts.map(a => attChipHtml(a)).join("");
bubble.appendChild(box);
}
const tx = document.createElement("div");
tx.className = "msg-user-text";
tx.textContent = text;
bubble.appendChild(tx);
wrap.appendChild(bubble);
// Action buttons
const actions = document.createElement("div");
actions.className = "msg-user-actions";
actions.innerHTML = `
<button class="msg-act-btn" title="${t('copyMsg')}" onclick="copyUserMessage(this)">
<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>
</button>
<button class="msg-act-btn" title="${t('editMsg')}" onclick="editUserMessage(this)">
<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>
</button>`;
wrap.appendChild(actions);
$("#msgsInner").appendChild(wrap);
scrollDown();
return wrap;
}
function copyUserMessage(btn) {
const wrap = btn.closest(".msg-user-wrap");
const textEl = wrap.querySelector(".msg-user-text");
const text = textEl ? textEl.textContent : "";
navigator.clipboard.writeText(text).then(() => {
btn.classList.add("copied");
showToast(t("copied"), "success");
setTimeout(() => btn.classList.remove("copied"), 1500);
}).catch(() => showToast("Failed to copy", "error"));
}
function editUserMessage(btn) {
const wrap = btn.closest(".msg-user-wrap");
const textEl = wrap.querySelector(".msg-user-text");
const text = textEl ? textEl.textContent : "";
const msgIndexStr = wrap.getAttribute("data-msg-index");
const msgIndex = msgIndexStr !== null ? parseInt(msgIndexStr) : null;
const s = cur();
// Truncate session messages up to this point
if (s && msgIndex !== null && msgIndex >= 0) {
s.messages = s.messages.slice(0, msgIndex);
save();
}
// Remove DOM elements from this message onward
let el = wrap;
while (el) {
const next = el.nextElementSibling;
el.remove();
el = next;
}
// Populate chat textarea
const ta = $("#chatTA");
if (ta) {
ta.value = text;
ta.style.height = "auto";
ta.style.height = Math.min(ta.scrollHeight, 180) + "px";
const sendBtn = $("#chatSend");
if (sendBtn) sendBtn.disabled = !ta.value.trim();
ta.focus();
ta.setSelectionRange(ta.value.length, ta.value.length);
}
// Go back to home if no messages left
if (s && s.messages.length === 0) {
newChat();
}
buildRecents();
}
function addAI(md, skipRender, msgIndex) {
const wrap = document.createElement("div");
wrap.className = "msg-ai";
if (msgIndex !== undefined) wrap.setAttribute("data-msg-index", msgIndex);
const body = document.createElement("div");
body.className = "msg-ai-body";
wrap.appendChild(body);
if (md !== undefined && !skipRender) {
renderInto(body, md);
}
const actions = document.createElement("div");
actions.className = "msg-ai-actions";
actions.innerHTML = `
<button class="msg-act-btn" title="${t('copyReply')}" onclick="copyAIReply(this)">
<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>
</button>`;
wrap.appendChild(actions);
$("#msgsInner").appendChild(wrap);
if (md !== undefined && !skipRender) scrollDown();
return { wrap, body };
}
function copyAIReply(btn) {
const wrap = btn.closest(".msg-ai");
const body = wrap ? wrap.querySelector(".msg-ai-body") : null;
const text = body ? body.innerText : "";
navigator.clipboard.writeText(text).then(() => {
btn.classList.add("copied");
showToast(t("copied"), "success");
setTimeout(() => btn.classList.remove("copied"), 1500);
}).catch(() => showToast("Failed to copy", "error"));
}
// ===================== RENDER =====================
function renderInto(body, md) {
const cleaned = cleanForRender(md || "");
body.innerHTML = marked.parse(cleaned);
enhanceCode(body);
renderMath(body);
}
function cleanForRender(text) {
if (!text) return "";
let out = text;
// Remove tool JSON objects
out = out.replace(/\{[^{}]*"tool"\s*:[^{}]*\}/gs, "");
// Remove JSON code blocks with tool
out = out.replace(/```(?:json)?\s*\{[\s\S]*?"tool"[\s\S]*?\}\s*```/g, "");
// Remove SUGGESTIONS block
out = out.replace(/\nSUGGESTIONS:\s*\[[\s\S]*?\]\s*$/m, "");
out = out.replace(/SUGGESTIONS:\s*\[[\s\S]*?\]\s*$/m, "");
return out.trim();
}
function extractSuggestions(text) {
const m = text.match(/SUGGESTIONS:\s*(\[[\s\S]*?\])/);
if (!m) return [];
try {
const arr = JSON.parse(m[1]);
return Array.isArray(arr) ? arr.slice(0, 4) : [];
} catch (e) {
return [];
}
}
function enhanceCode(scope) {
scope.querySelectorAll("pre code").forEach(code => {
if (code.dataset.done) return;
code.dataset.done = "1";
const pre = code.parentElement;
const lang = (code.className.match(/language-(\w+)/) || [])[1] || "code";
const wrap = document.createElement("div");
wrap.className = "code-wrap";
const bar = document.createElement("div");
bar.className = "code-bar";
const langSpan = document.createElement("span");
langSpan.textContent = lang;
bar.appendChild(langSpan);
const btn = document.createElement("button");
btn.className = "copy-btn";
btn.textContent = "Copy";
btn.onclick = () => {
navigator.clipboard.writeText(code.innerText).then(() => {
btn.textContent = "Copied!";
setTimeout(() => btn.textContent = "Copy", 1500);
});
};
bar.appendChild(btn);
pre.parentNode.insertBefore(wrap, pre);
wrap.appendChild(bar);
wrap.appendChild(pre);
try { hljs.highlightElement(code); } catch (e) {}
});
}
function renderMath(scope) {
if (window.renderMathInElement) {
try {
renderMathInElement(scope, {
delimiters: [
{ left: "$$", right: "$$", display: true },
{ left: "\\[", right: "\\]", display: true },
{ left: "\\(", right: "\\)", display: false },
{ left: "$", right: "$", display: false }
],
throwOnError: false
});
} catch (e) {}
}
}
function renderMathAll() {
document.querySelectorAll(".msg-ai-body").forEach(renderMath);
}
function scrollDown() {
const m = $("#msgs");
if (m) m.scrollTop = m.scrollHeight;
}
// ===================== SEND BUTTON STATE =====================
function setSendButtons(stop) {
[["#homeSend","home"],["#chatSend","chat"]].forEach(([sel, mode]) => {
const b = $(sel);
if (!b) return;
if (stop) {
b.classList.add("stop");
b.disabled = false;
b.innerHTML = `<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><rect x="5" y="5" width="14" height="14" rx="2"/></svg>`;
b.onclick = stopResponse;
} else {
b.classList.remove("stop");
b.innerHTML = `<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round"><line x1="12" y1="20" x2="12" y2="5"/><polyline points="6 11 12 5 18 11"/></svg>`;
b.onclick = () => send(mode);
}
});
}
function stopResponse() {
if (state.abort) state.abort.abort();
}
// ===================== SSE PARSER =====================
/**
* Properly parse SSE stream.
* SSE format: each event ends with double newline (\n\n)
* Each line can be: "data: ...", "event: ...", etc.
*/
function parseSSEChunk(buf) {
const events = [];
// Split on double newline (event separator)
const rawEvents = buf.split(/\n\n/);
const remaining = rawEvents.pop(); // Last might be incomplete
for (const rawEvent of rawEvents) {
const lines = rawEvent.split(/\n/);
let data = null;
for (const line of lines) {
if (line.startsWith("data: ")) {
data = line.slice(6).trim();
}
}
if (data && data !== "[DONE]") {
events.push(data);
}
}
return { events, remaining };
}
// ===================== MAIN SEND =====================
async function send(mode) {
const ta = mode === "home" ? $("#homeTA") : $("#chatTA");
const text = (ta ? ta.value : "").trim();
if ((!text && !pendingAttachments.length) || state.busy) return;
// Create session if needed
if (!state.currentId) {
const id = Date.now() + "-" + Math.random().toString(36).slice(2);
state.sessions.unshift({
id,
title: "",
date: new Date().toLocaleDateString(),
messages: []
});
state.currentId = id;
}
const s = cur();
if (!s) return;
// Switch to chat view
$("#shell").classList.add("chat");
// If transitioning from home, render existing messages
if (mode === "home" && $("#msgsInner").children.length === 0) {
s.messages.forEach((m, i) => {
if (m.role === "user") addUser(m.content, m.attachments, i);
else addAI(m.content, false, i);
});
}
// Clear input
if (ta) {
ta.value = "";
ta.style.height = "auto";
}
// Prepare attachments & message
const atts = pendingAttachments.slice();
const userMsgIndex = s.messages.length;
// Build content with attachments
let userContent = text;
if (atts.length) {
const textAtts = atts.filter(a => a.kind === "text");
if (textAtts.length) {
userContent += "\n\n" + textAtts.map(a => `[File: ${a.name}]\n${a.text}`).join("\n\n");
}
}
s.messages.push({ role: "user", content: userContent, attachments: atts });
addUser(text, atts, userMsgIndex);
clearAttachments();
buildRecents();
// Add AI response placeholder
const aiMsgIndex = s.messages.length;
const { wrap, body } = addAI(undefined, true, aiMsgIndex);
const answer = document.createElement("div");
answer.innerHTML = `<div class="dots"><span></span><span></span><span></span></div>`;
body.appendChild(answer);
state.busy = true;
setSendButtons(true);
state.abort = new AbortController();
let full = "";
let rafPending = false;
const paint = () => {
rafPending = false;
const cleaned = cleanForRender(full);
answer.innerHTML = marked.parse(cleaned);
enhanceCode(answer);
renderMath(answer);
scrollDown();
};
try {
const res = await fetch(API + "/api/chat", {
method: "POST",
headers: { "Content-Type": "application/json" },
signal: state.abort.signal,
body: JSON.stringify({
messages: s.messages,
model: state.settings.model,
user: state.user || {},
interests: state.interests,
think: state.settings.model === "pro"
})
});
if (!res.ok) {
const errText = await res.text();
throw new Error(`HTTP ${res.status}: ${errText.slice(0, 200)}`);
}
const reader = res.body.getReader();
const dec = new TextDecoder();
let buf = "";
while (true) {
const { value, done } = await reader.read();
if (done) break;
buf += dec.decode(value, { stream: true });
// Parse SSE properly
const { events, remaining } = parseSSEChunk(buf);
buf = remaining;
for (const dataStr of events) {
let j;
try {
j = JSON.parse(dataStr);
} catch (e) {
continue;
}
if (j.error) {
answer.innerHTML = `<p style="color:var(--danger)">${escapeHtml(j.error)}</p>`;
continue;
}
if (j.done) continue;
// Handle image tool signal from backend
if (j.tool === "image" && j.prompt) {
const imgNode = document.createElement("p");
imgNode.textContent = t("generatingImage");
answer.appendChild(imgNode);
generateImage(j.prompt, imgNode);
continue;
}
if (j.delta) {
full += j.delta;
if (!rafPending) {
rafPending = true;
requestAnimationFrame(paint);
}
}
}
}
// Final render
const cleaned = cleanForRender(full);
answer.innerHTML = marked.parse(cleaned);
enhanceCode(answer);
renderMath(answer);
// Handle suggestions
const sugg = extractSuggestions(full);
if (sugg.length) renderSuggestions(answer, sugg);
// Save to session
s.messages.push({ role: "assistant", content: full });
// Auto TTS
if (state.settings.ttsAuto) speak(stripForTTS(full));
// Generate title
maybeTitle(s);
// Learn user interests
learnInterests(text);
save();
buildRecents();
} catch (err) {
if (err.name === "AbortError") {
const cleaned = cleanForRender(full);
answer.innerHTML = full.trim()
? marked.parse(cleaned)
: `<p style="color:var(--muted)">${t("stopped")}</p>`;
enhanceCode(answer);
renderMath(answer);
if (full.trim()) {
s.messages.push({ role: "assistant", content: full });
}
maybeTitle(s);
save();
buildRecents();
} else {
console.error("[send]", err);
answer.innerHTML = `<p style="color:var(--danger)">${t("errConnect")}: ${escapeHtml(String(err.message || err))}</p>`;
}
} finally {
state.busy = false;
state.abort = null;
setSendButtons(false);
// Disable send buttons (no text)
const hBtn = $("#homeSend");
const cBtn = $("#chatSend");
if (hBtn) hBtn.disabled = true;
if (cBtn) cBtn.disabled = true;
}
}
// ===================== IMAGE GENERATION =====================
async function generateImage(prompt, placeholder) {
try {
const r = await fetch(API + "/api/image", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ prompt, clientId })
});
const j = await r.json();
if (j.image) {
const fname = "genisi-" + Date.now() + ".png";
const container = document.createElement("div");
container.innerHTML = `
<img class="gen-img" src="${j.image}" alt="Generated image">
<div class="img-actions">
<button class="suggest" onclick="downloadDataUrl('${j.image}','${fname}')">${t("downloadImg")}</button>
</div>
<p style="color:var(--muted);font-size:13px">${j.remaining ?? 0} ${t("imagesLeft")}</p>`;
placeholder.replaceWith(container);
showToast("Image generated!", "success");
} else {
placeholder.textContent = j.message || "Image generation failed";
showToast(j.message || "Failed", "error");
}
} catch (e) {
placeholder.textContent = "Image generation error";
showToast("Image generation failed", "error");
}
}
// ===================== DOCUMENT TOOLS =====================
function renderDocPreview(cmd, scope) {
const wrap = document.createElement("div");
wrap.className = "doc-preview";
wrap.innerHTML = docToHtml(cmd);
scope.appendChild(wrap);
const bar = document.createElement("div");
bar.className = "doc-dl";
bar.innerHTML = `<span class="doc-dl-label">${t("downloadDoc")}:</span>`;
[["pdf","PDF"],["docx","Word"],["pptx","PowerPoint"],["xlsx","Excel"]].forEach(([fmt, label]) => {
const b = document.createElement("button");
b.className = "doc-dl-btn";
b.textContent = label;
b.onclick = () => downloadDoc({ ...cmd, format: fmt }, b);
bar.appendChild(b);
});
scope.appendChild(bar);
}
function docToHtml(cmd) {
const c = cmd.content || {};
const esc = escapeHtml;
const blocks = [];
if (c.heading) blocks.push(`<h2>${esc(c.heading)}</h2>`);
(c.paragraphs || []).forEach(p => blocks.push(`<p>${esc(as_text_js(p))}</p>`));
(c.sections || []).forEach(s => {
if (s.title) blocks.push(`<h3>${esc(s.title)}</h3>`);
const b = s.body || s.content || s.text;
if (b) blocks.push(`<p>${esc(as_text_js(b))}</p>`);
(s.bullets || s.points || []).forEach(x => blocks.push(`<li>${esc(as_text_js(x))}</li>`));
});
if (c.headers) {
blocks.push(`<table><thead><tr>${c.headers.map(h => `<th>${esc(as_text_js(h))}</th>`).join("")}</tr></thead><tbody>${(c.rows||[]).map(r => `<tr>${r.map(x => `<td>${esc(as_text_js(x))}</td>`).join("")}</tr>`).join("")}</tbody></table>`);
}
return `<div class="doc-paper"><h1 class="doc-title">${esc(cmd.title||"Document")}</h1>${blocks.join("")}</div>`;
}
function as_text_js(v) {
if (v == null) return "";
if (typeof v === "string") return v;
if (Array.isArray(v)) return v.map(as_text_js).join("\n");
if (typeof v === "object") return v.text || v.body || v.content || "";
return String(v);
}
function renderSuggestions(scope, list) {
const box = document.createElement("div");
box.className = "suggests";
list.forEach(txt => {
const b = document.createElement("button");
b.className = "suggest";
b.textContent = txt;
b.onclick = () => {
const ta = $("#chatTA");
if (ta) {
ta.value = txt;
onTaInput(ta, "chatSend");
send("chat");
}
};
box.appendChild(b);
});
scope.appendChild(box);
}
async function downloadDoc(cmd, btn) {
const old = btn.textContent;
btn.textContent = "...";
btn.disabled = true;
try {
const r = await fetch(API + "/api/document", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(cmd)
});
if (!r.ok) throw new Error(`HTTP ${r.status}`);
const blob = await r.blob();
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = (cmd.title || "genisi") + "." + cmd.format;
document.body.appendChild(a);
a.click();
a.remove();
URL.revokeObjectURL(url);
showToast(`${cmd.format.toUpperCase()} downloaded!`, "success");
} catch (e) {
showToast("Download error", "error");
} finally {
btn.textContent = old;
btn.disabled = false;
}
}
function downloadDataUrl(dataUrl, filename) {
const a = document.createElement("a");
a.href = dataUrl;
a.download = filename;
document.body.appendChild(a);
a.click();
a.remove();
}
// ===================== TITLE GENERATION =====================
function maybeTitle(s) {
const userCount = s.messages.filter(m => m.role === "user").length;
if (userCount !== 1 && userCount !== 3) return;
fetch(API + "/api/title", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ messages: s.messages })
})
.then(r => r.json())
.then(j => {
if (j.title) {
s.title = j.title;
save();
buildRecents();
}
})
.catch(() => {});
}
// ===================== INTERESTS LEARNING =====================
function learnInterests(text) {
const words = (text || "").toLowerCase().match(/[\u0600-\u06FF\w]{4,}/g) || [];
const stopWords = new Set(["this","that","with","please","about","what","when","where","how","ู‡ุฐุง","ู‡ุฐู‡","ุงู„ุชูŠ","ุงู„ุฐูŠ","ูƒูŠู","ู‡ู„","ู…ู†"]);
words
.filter(w => !stopWords.has(w))
.slice(0, 3)
.forEach(w => {
if (!state.interests.includes(w)) state.interests.push(w);
});
state.interests = state.interests.slice(-30);
save();
}
// ===================== TTS =====================
function stripForTTS(text) {
return text
.replace(/```[\s\S]*?```/g, "")
.replace(/\{[\s\S]*?\}/g, "")
.replace(/SUGGESTIONS:[\s\S]*$/, "")
.replace(/[#*_`]/g, "")
.trim();
}
async function speak(text) {
if (!text.trim()) return;
try {
const r = await fetch(API + "/api/tts", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ text })
});
if (!r.ok || r.status === 204) throw new Error("TTS unavailable");
const blob = await r.blob();
new Audio(URL.createObjectURL(blob)).play();
} catch (e) {
// Fallback to browser TTS
if (window.speechSynthesis) {
const utt = new SpeechSynthesisUtterance(text);
utt.lang = state.settings.lang === "ar" ? "ar-SA" : state.settings.lang === "fr" ? "fr-FR" : "en-US";
speechSynthesis.speak(utt);
}
}
}
// ===================== MIC =====================
let recog = null;
function toggleMic(taId, btn) {
const SR = window.SpeechRecognition || window.webkitSpeechRecognition;
if (!SR) {
showToast(t("micUnsupported"), "error");
return;
}
if (recog) {
recog.stop();
recog = null;
btn.classList.remove("recording");
return;
}
recog = new SR();
recog.lang = state.settings.lang === "ar" ? "ar-SA" : state.settings.lang === "fr" ? "fr-FR" : "en-US";
recog.continuous = false;
recog.interimResults = true;
btn.classList.add("recording");
const base = ($("#" + taId) || {}).value || "";
recog.onresult = e => {
let tx = "";
for (const r of e.results) tx += r[0].transcript;
const ta = $("#" + taId);
if (ta) {
ta.value = (base ? base + " " : "") + tx;
onTaInput(ta, taId === "homeTA" ? "homeSend" : "chatSend");
}
};
recog.onend = () => {
btn.classList.remove("recording");
recog = null;
};
recog.onerror = () => {
btn.classList.remove("recording");
recog = null;
};
recog.start();
}
// ===================== CLEAR ALL =====================
function clearAll() {
if (confirm(t("confirmClear"))) {
localStorage.clear();
location.reload();
}
}
// ===================== TOAST =====================
function showToast(msg, type = "success") {
const toast = $("#toast");
if (!toast) return;
toast.textContent = msg;
toast.className = `toast ${type} show`;
setTimeout(() => toast.classList.remove("show"), 3000);
}
// ===================== EVENT LISTENERS =====================
const ttsEl = $("#ttsAuto");
if (ttsEl) {
ttsEl.addEventListener("change", e => {
state.settings.ttsAuto = e.target.checked;
save();
});
}
// Auto theme on system change
matchMedia("(prefers-color-scheme:dark)").addEventListener("change", () => {
if (state.settings.theme === "auto") applyTheme();
});
// ===================== START =====================
init();
</script>
</body>
</html>