~firefoxphpai-chat
17 items • Download ./*

..
ajax.php
ana-ai-chat.png
atom-one-dark.min.css
convert-databases-v1.0.2-to-v1.0.3.php
db-browser.php
emoji.json
favicon.ico
highlight.min.js
index.php
note.txt
pair-all-chat-times.php
readme.txt
rebuild-chats-json.php
recalculate-chat-count.php
setup.php
setup_and_launch.py
worker.php


ai-chatindex.php
141 KB• 58•  1 week ago•  DownloadRawClose
1 week ago•  58

{}
<!DOCTYPE html>
<!--

    Author:        Twily  2015 - 2021
    Website:       http://twily.info/

-->
<?php
include('./setup.php');
?>
<html lang="en">
<head>
    <title>&gt;_ AI Terminal</title>
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link id="favicon" rel="shortcut icon" href="./favicon.ico?v-3" />

    <link rel="stylesheet" href="./atom-one-dark.min.css?v=11.9.0">
    <script type="text/javascript" src="./highlight.min.js?v=11.9.0"></script>
    <style type="text/css">
        html, body {
            width: 100%; height: 100%; margin: 0; padding: 0; overflow: hidden;
            font-family: "Droid Sans", "Liberation Sans", "DejaVu Sans", "Segoe UI", Sans;
            font-size: 11pt; background: #17181A; color: /*#AAABAD*/ #C7C9CE; box-sizing: border-box;
        }
        *, *:before, *:after { box-sizing: inherit; }
        *:focus { outline: none !important; }

        a:link, a:visited { color: #715f71; text-decoration: none; }
        a:hover, a:active { color: #bdadbd; }
        
        .app-layout { display: flex; width: 100%; height: 100%; }
        
        /* Sidebar styling */
        #sidebar { width: 280px; min-width: 280px; background: #111113; border-right: 1px solid #606163; display: flex; flex-direction: column; transition: width 0.2s ease, min-width 0.2s ease; }
        #sidebarContain { width: 280px; min-width: 280px; overflow: hidden; }
        #sidebar.collapsed { width: 0px; min-width: 0px; overflow: hidden; border: none; }
        
        .sidebar-tabs { display: flex; background: #0a0b0d; border-bottom: 1px solid #333; }
        .tab-btn { flex: 1; padding: 10px; background: none; border: none; color: #777; cursor: pointer; font-weight: bold; font-size: 9pt; }
        .tab-btn.active { color: #fff; /*background: #111113; border-bottom: 2px solid #EA75BC*/; }
        #btn-tab-chats.active    { background: #170d17; border-bottom: 2px solid #EA75BC }
        #btn-tab-settings.active { background: #101020; border-bottom: 2px solid #4A90E2 }
        
        .tab-pane { display: none; flex: 1; overflow-y: auto; padding: 10px; flex-direction: column; gap: 8px; height: 100%; /*height: calc(100% - 39px);*/ }
        .tab-pane.active { display: /*flex*/ block; }
        
        .sidebar-header { padding: 4px 0; border: none; display: flex; justify-content: space-between; align-items: center; }
        .chat-list { flex: 1; /*overflow-y: auto;*/ display: flex; flex-direction: column; gap: 5px; height: auto; }
        .chat-item { padding: 8px 10px; background: #1c1d21; border: 1px solid #333; cursor: pointer; font-size: 10pt; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; user-select: none; min-height: 34px; max-height: 34px; }
        .chat-item:hover, .chat-item.active { border-color: #EA75BC; background: #25262c; }
        #queue-list { flex: 1; display: flex; flex-direction: column; gap: 5px; height: auto; line-height: 34px; }
        #media-chat-btn { display: none; }
        #media-chat-btn.active { border-color: #EA75BC; background: #25262c; }
        .chat-item.error     { border-color: #F00; /*background: #25262c;*/ }
        #btn-tab-chats.error { background: #170d0d; border-bottom: 2px solid #F00 }
        
        .setting-group { display: flex; flex-direction: column; gap: 4px; margin-bottom: 12px; font-size: 10pt; }
        .setting-group label { color: #888; }
        .setting-help { font-size: 9.5pt; color: #606163; margin-top: 4px; line-height: 1.3; }
        
        /* Generating indicator in sidebar */
        .chat-item.generating {
            border-color: #4a90e2 /*!important*/;
            background: #25262c /*!important*/;
            position: relative;
        }
        .chat-item-generating-dots {
            float: right;
            font-weight: bold;
            color: #4a90e2;
            animation: blink 1.4s infinite both;
        }
        .chat-item-msg-count {
            float: right;
            font-weight: bold;
            /*color: #4a90e2;*/
            color: #606163;
        }

        /* Main pane */
        .main-pane { flex: 1; display: flex; flex-direction: column; padding: 10px; gap: 10px; height: 100%; }
        .top-bar { display: flex; gap: 10px; align-items: center; background: #111113; padding: 10px; border: 1px solid #606163; }
        .chat-box { flex: 1; background: #111113; border: 1px solid #606163; overflow-y: auto; padding: 15px; display: flex; flex-direction: column; gap: 12px; box-shadow: inset 0 0 2px 2px #000; }
        .media-box { flex: 1; background: #111113; border: 1px solid #606163; overflow-y: auto; padding: 15px; flex-flow: row wrap; gap: 12px; box-shadow: inset 0 0 2px 2px #000; display: none; /*align-items: center; align-content: center;*/ }
        .queue-box { flex: 1; background: #111113; border: 1px solid #606163; overflow-y: auto; padding: 15px; flex-flow: row wrap; gap: 12px; box-shadow: inset 0 0 2px 2px #000; display: none; /*align-items: center; align-content: center;*/ }
        
        /* Input & Vibe Bar */
        .input-container { display: flex; flex-direction: column; gap: 5px; background: #111113; border: 1px solid #606163; padding: 8px; }
        .vibe-bar { display: flex; gap: 8px; align-items: center; padding-bottom: 5px; border-bottom: 1px solid #222; font-size: 10pt; }
        .emoji-btn { background: #1c1d21; border: 1px solid #333; color: #fff; padding: 2px 6px; cursor: pointer; border-radius: 3px; user-select: none; }
        .emoji-btn:hover { background: #25262c; border-color: #EA75BC; }
        .file-upload-lbl { font-size: 9pt; color: #aaa; cursor: pointer; background: #1c1d21; border: 1px solid #333; padding: 2px 8px; border-radius: 3px; user-select: none; }
        .file-upload-lbl:hover { border-color: #EA75BC; color: #fff; }

        /* Emoji Picker Modal */
        #emoji-modal {
            display: none; position: absolute; bottom: 90px; left: 10px; width: 320px; height: 220px;
            background: #111113; border: 1px solid #606163; border-radius: 4px; box-shadow: 0 4px 12px rgba(0,0,0,0.5);
            z-index: 99; flex-direction: column; overflow: hidden; user-select: none; 
        }
        #emoji-modal.open { display: flex; }
        .emoji-modal-header { padding: 6px 10px; background: #1a1b1e; border-bottom: 1px solid #333; font-size: 9pt; display: flex; justify-content: space-between; align-items: center; }
        .emoji-grid { flex: 1; overflow-y: auto; padding: 8px; display: grid; grid-template-columns: repeat(8, 1fr); gap: 4px; font-size: 14pt; text-align: center; }
        .emoji-cell { cursor: pointer; padding: 4px; border-radius: 3px; }
        .emoji-cell:hover { background: #25262c; }

        /* Lightbox Overlay */
        #image-lightbox {
            display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%;
            background: rgba(0, 0, 0, 0.88); z-index: 999; justify-content: center; align-items: center; padding: 30px;
            box-sizing: border-box;
        }
        #image-lightbox.open { display: flex; }

        #lightbox-wrap { position: relative; }
        #lightbox-img {
            display: block;
            object-fit: contain;
            border: 2px solid #606163;
            box-shadow: 0 0 25px rgba(0,0,0,0.9);
            cursor: pointer;
            /* Dimensions will be dynamically injected via JS scaling */
        }

        .tbl { display: table; width: 100%; height: 100%; }
        .tr { display: table-row; }
        .td { display: table-cell; vertical-align: middle; /*border: 1px solid #606163; box-shadow: inset 0 0 2px 2px #000;*/ }
        
        /* table style for formatText */
        table {
            width: 100%;
            border-collapse: collapse;
            margin: 0.75rem 0;
            font-size: 0.92em;
        }
        th, td {
            padding: 0.55rem 0.75rem;
            border: 1px solid rgba(128, 128, 128, 0.25);
        }
        thead th {
            background: rgba(128, 128, 128, 0.1);
            font-weight: 600;
        }
        tbody tr:nth-child(even) {
            background: rgba(128, 128, 128, 0.04);
        }

        .input-area { display: flex; gap: 10px; }
        textarea { background: #000; color: #fff; border: 1px solid #666; resize: none; padding: 10px; font-family: inherit; font-size: inherit; flex: 1; height: 82px; }
        
        select, input[type="text"], button { background: #222; color: #fff; border: 1px solid #666; padding: 6px 12px; cursor: pointer; font-weight: bold; user-select: none; }
        button:hover { background: #333; border-color: #EA75BC; }
        
        .message { padding: 10px; border-left: 3px solid #606163; background: #1a1b1e; word-break: break-word; position: relative; }
        .message.user { border-left-color: #EA75BC; background: #1e1a1e; color: #AAABAD; }
        .message.ai { border-left-color: #4a90e2; line-height: 1.5;/* color: #e0e0e0;*/ }
        /* Headings inside AI messages */
        .message.ai h1, .message.ai h2, .message.ai h3 {
            margin: 3px 0 3px 0;
            color: #fff;
            font-weight: 600;
            border-bottom: 1px solid #333;
            padding-bottom: 4px;
        }
        
        .message.ai h1 { font-size: 13pt; }
        .message.ai h2 { font-size: 12pt; }
        .message.ai h3 { font-size: 11pt; }

        .message.ai h4 {
            margin: 10px 0 4px 0;
            color: #d1d5db;
            font-size: 10pt;
            font-weight: 600;
        }
        
        .message.ai ol {
            margin: 6px 0 6px 20px;
            padding: 0;
        }
        
        /* Paragraphs & Lists */
        .message.ai p {
            margin: 4px 0; /* Reduced from 6px to keep vertical flow tight */
        }
        
        .message.ai ul, .message.ai ol {
            margin: 4px 0 4px 20px;
            padding: 0;
        }
        
        .message.ai li {
            margin-bottom: 2px;
        }

        /* Style for inline state markers like *UI:* or *Action:* */
        .message.ai em {
            color: #61afef;
            font-style: normal;
            font-weight: 600;
        }
        
        /* Inline code or technical highlights outside pre blocks */
        .message.ai code:not(pre code) {
            background: rgba(255, 255, 255, 0.08);
            padding: 2px 4px;
            border-radius: 3px;
            font-family: monospace;
            font-size: 90%;
            color: #e5c07b;
        }
        
        /* Styled Blockquotes */
        .message.ai blockquote {
            border-left: 3px solid #61afef;
            margin: 8px 0;
            padding-left: 10px;
            color: #abb2bf;
            background: rgba(97, 175, 239, 0.05);
        }
        .message.system-error { border-left-color: #e74c3c; color: #e74c3c; }
        .image-actions {
            display: block;
            position: absolute;
            width: 100%; height: 100%;
            text-align: center;
            left: 0; top: 0;
        }
        .image-actions2 {
            position: absolute;
            width: /*100%*/ auto;
            text-align: /*center*/ left;
            left: 10px; bottom: 10px;
            z-index: 20;
            /*opacity: 1;*/
            /*transition: opacity 5s ease;*/
            transition: opacity 2s ease;
        }
        .lightbox-actions.fade:hover, .image-actions2.fade:hover {
            opacity: 1;
        }
        .lightbox-actions.fade, .image-actions2.fade {
            opacity: 0;
        }
        .image-actions button {
            width: 100%; height: 100%;
            background: rgba(255,255,255,.0);
            border: 0;
            font-size: 24pt;
        }
        /*.image-actions .next, .image-actions .prev {
        }*/
        .image-actions .next:hover, .image-actions .prev:hover {
            background: rgba(255,255,255,.1);
        }

        .lightbox-actions {
            display: block;
            position: absolute;
            top: 4px;
            right: 8px;
            background: rgba(30, 30, 36, 0.85);
            border: 1px solid #444;
            border-radius: 4px;
            padding: 2px 4px;
            gap: 4px;
            transition: opacity 2s ease;
            z-index: 20;
        }

        .message-actions {
            display: none;
            position: absolute;
            top: 4px;
            right: 8px;
            background: rgba(30, 30, 36, 0.85);
            border: 1px solid #444;
            border-radius: 4px;
            padding: 2px 4px;
            gap: 4px;
        }
        
        .message:hover .message-actions { display: flex; }
        
        .message-actions button {
            background: transparent;
            border: none;
            color: #ccc;
            font-size: 8pt;
            cursor: pointer;
            padding: 2px 6px;
            border-radius: 2px;
        }
        
        .message-actions button:hover { background: #444; color: #fff; }
        
        .smlnk {visibility: hidden; }
        .smlnk a:link, .smlnk a:visited { color: #715f71; text-decoration: none; }
        .smlnk a:hover, .smlnk a:active { color: #bdadbd; }
        .message:hover .smlnk { visibility: visible; }
        
        .attachment { color: /*#4f4f4f*/ #bd7ab0; font-size: 10pt; }
        
        pre { background: #0b0c0e !important; padding: 10px; border: 1px solid #333; overflow-x: auto; white-space: pre-wrap; word-break: break-all; max-width: 100%; position: relative; }
        code { font-family: monospace; white-space: pre-wrap; word-break: break-all; }
        img.generated-art { max-width: 400px; border: 1px solid #444; margin-top: 8px; }

        .code-copy-btn {
            position: absolute;
            top: 6px;
            right: 6px;
            background: rgba(40, 40, 48, 0.9);
            color: #bbb;
            border: 1px solid #555;
            border-radius: 3px;
            padding: 2px 6px;
            font-size: 7.5pt;
            cursor: pointer;
            z-index: 10;
            user-select: none;
        }
        .code-copy-btn:hover { background: #555; color: #fff; }

        .media { display: inline-block; }
        .media .thumb {
            max-width:128px; width: 128px;
            border:1px solid #444;
            margin-top:6px;
            display:inline-block;
            cursor:pointer;
        }

        .message .prev {
            max-width:256px; width: 256px;
            border:1px solid #444;
            margin-top:6px;
            display:block;
            cursor:pointer;
        }

        .typing-dots span { animation: blink 1.4s infinite both; font-size: 16pt; line-height: 5px; }
        .typing-dots span:nth-child(2) { animation-delay: .2s; }
        .typing-dots span:nth-child(3) { animation-delay: .4s; }
        @keyframes blink { 0% { opacity: .2; } 20% { opacity: 1; } 100% { opacity: .2; } }
    </style>
    <script type="text/javascript">
        var $ = function(id) { return document.getElementById(id); };
        var enableLS=(typeof(Storage)!=="undefined")?true:false;
        var rndMinMax=function(min,max) { return Math.floor(Math.random()*(max-min+1)+min); }
        var IsJsonString=function(str) { try { JSON.parse(str); } catch(e) { return false; } return true; }
        var currentChatId = null;

        function b64Enc(str) {
            return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function(match, p1) {
                return String.fromCharCode(parseInt(p1, 16));
            }));
        }

        function sendAjax(action, dataObj, cb) {
            var xhr = new XMLHttpRequest();
            xhr.open("POST", "./ajax.php", true);
            xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            
            xhr.onreadystatechange = function() {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    //try {
                        const rawData = xhr.responseText;
                        //console.log(rawData); // debug raw json
                        const cleanData = rawData.trim().replace(/^\uFEFF/, '');
                        
                        //try {
                        //  JSON.parse(rawString);
                        //} catch (e) {
                        //  console.error("Error Message:", e.message);
                        //
                        //  // Extract the position if provided in the error message
                        //  const posMatch = e.message.match(/position (\d+)/);
                        //  if (posMatch) {
                        //    const pos = parseInt(posMatch[1], 10);
                        //    console.log("Problem context:", rawString.substring(Math.max(0, pos - 20), pos + 20));
                        //  }
                        //}
                        const res = JSON.parse(cleanData);
                        if (typeof cb === 'function') cb(res);
                    //} catch(e) {
                    //    console.error("Invalid JSON response", xhr.responseText); // issue can mask other error culprits
                    //}
                }
            };
            xhr.send("action=" + action + "&payload=" + b64Enc(JSON.stringify(dataObj)));
        }

        function toggleSidebar() { $('sidebar').classList.toggle('collapsed'); }

        var currentTab="chats";
        function switchTab(tabName) {
            if(tabName==currentTab) toggleSidebar();
            currentTab=tabName;

            document.querySelectorAll('.tab-pane').forEach(el => el.classList.remove('active'));
            document.querySelectorAll('.tab-btn').forEach(el => el.classList.remove('active'));
            $('pane-' + tabName).classList.add('active');$('btn-tab-' + tabName).classList.add('active');
            if(tabName === 'settings') {
                loadSdModels();
            }
        }

        let searchOn=false;
        var searchQ="*";
        function toggleSearch() {
            searchOn=!searchOn;

            if(searchOn) {
                $('lbHist').innerHTML="<input type=\"text\" value=\"\" id=\"txtQ\" onblur=\"toggleSearch();\" style=\"width: 125px;\" onkeyup=\"searchList(this.value);\" onchange=\"toggleSearch();\" placeholder=\"Search...\" />";
                $('txtQ').focus();
                searchQ="*";
            } else {
                $('lbHist').innerHTML="HISTORY";
                searchQ="*";
            }
        }

        function searchList(val) {
            searchQ=val;
            if(searchQ=="") searchQ="*";

            drawChatList();
        }

        var firstdraw=true;
        function drawChatList() {
            var listContainer = $('chat-list');
            listContainer.innerHTML = '';
            var isGenerating=false;
            var isThinking=false;
            var found=false;
            $('stat-media-count').innerHTML="";
            $('media-chat-btn').style.display="";
            chatCopy.forEach(function(chat) {
                var div = document.createElement('div');
                if(chatStatus.hasOwnProperty(chat.id)) {
                    isGenerating=chatStatus[chat.id]['generating']>0?true:false;
                    isThinking=chatStatus[chat.id]['thinking']>0?true:false;
                } else {
                    isGenerating=false;
                    isThinking=false;
                }
                
                let divclass="chat-item";
                if(chat.id==currentChatId) {
                    divclass+=" active"; // pink border
                    if(chat.hasOwnProperty('stats')) {
                        if(chat.stats.media>0) {
                            $('stat-media-count').innerHTML="["+chat.stats.media+"]";
                            $('media-chat-btn').style.display="inline-block";
                        }
                    }
                    found = true;
                } else if(isGenerating || isThinking) {
                    divclass+=" generating"; // blue border
                }
                div.className=divclass;
                
                // Set base display title
                var titleText = chat.title || chat.id;
                div.setAttribute('data-name',titleText);
                div.setAttribute('data-id',chat.id);

                if(searchQ=="*" || titleText.indexOf(searchQ)!==-1) {
                
                    if (isGenerating || isThinking) { // loading dots in chat list
                        div.innerHTML = titleText + '<span class="chat-item-generating-dots">...</span>';
                        //addChatListLoading();
                    } else {
                        // clears and generating state visual
                        if(chat.hasOwnProperty('stats')) {
                            let iconchats="🖺";
                            //let iconmedia="🖻";
                            let iconmedia="🖼";
                            let icon=(chat.stats.media>0)?iconmedia:iconchats;
                            //div.innerHTML = titleText + '<span class="chat-item-msg-count">'+icon+' '+(chat.stats.chats+chat.stats.media)+'</span>';
                            div.innerHTML = titleText + '<span class="chat-item-msg-count">'+(chat.stats.chats+chat.stats.media)+' '+icon+'</span>';
                        } else {
                            div.innerText = titleText;
                        }
                    }
                    
                    div.onclick = function() { switchChat(chat.id); };
                    listContainer.appendChild(div);

                    // add live view for any device
                    if(currentChatId==chat.id && !$('loading-bubble')) {
                        if(isGenerating) {
                            // If it's an image generation state, ensure it boots up with the Imagine tag
                            //var isImgGen = res.is_image_generating || true; // Or check your active session flag
                            var isImgGen = true;
                            appendMessage('loading', '', [], false, true, isImgGen);
                        } else if(isThinking) {
                            appendMessage('loading', '', [], false, true, false);
                        }
                    }
                }
            });
            if(firstdraw) {
                firstdraw=false;
                triggerChatIdDebug();
            }
        }
        
        function triggerChatIdDebug() {
            var elms=$('chat-list').getElementsByClassName('chat-item');
            var output="triggerChatIdDebug()\n";
            for(let i=0;i<elms.length;i++) {
                output+="./chats/"+elms[i].getAttribute('data-id')+".log | "+elms[i].getAttribute('data-name')+"\n";
            }
            output+="---\nother relevant files:\n";
            output+="./chats.json\n";
            output+="./queue.json\n";
            output+="./worker.lock\n";
            output+="./worker.log\n";
            output+="./ollama_debug.log\n";
            output+="./upscalers_debug.json\n";
            output+="./buildlock.log\n";
            output+="./buildprompt.log\n";
            output+="./memoryprofile.log\n";
            output+="---";
            console.log(output);
        }

        var lmtime=0; // chat list
        var lfsizec=0; // chat-
        var chatCopy=[];
        var primaryActive=false;
        function loadChatList() {
            let chatBox=$('chat-box');
            let oldScrollHeight = chatBox.scrollHeight;
            let oldScrollTop = chatBox.scrollTop + chatBox.clientHeight;
            sendAjax('load_history_list', {chat_id: currentChatId, lmtime: lmtime}, function(res) {
                if (res.status === 'success') {
                    //console.dir(res);
                    if(res.hasOwnProperty('unchanged')) {
                        //return;
                    } else {
                        lmtime=res.mtime;
                        chatCopy=res.chats;
                    }
                    if(lfsizec!=0 && res.fsizec<lfsizec) {
                        // something deleted on other device? refresh with switchChat?

                        let newScrollHeight = chatBox.scrollHeight;
                        //chatBox.scrollTop = (oldScrollTop - msgHeight) + (newScrollHeight - oldScrollHeight);
                        chatBox.scrollTop = oldScrollTop + (newScrollHeight - oldScrollHeight);
                        
                        switchChat(currentChatId,false,true); // Reload chat ledger view cleanly
                    }
                    lfsizec=res.fsizec;
                    // Sort chats by time descending (newest/most recent first)
                    // may be sorted on php already fixed time
                    //console.log(res);
                    //res.chats.sort(function(a, b) {
                    //    return (b.time || 0) - (a.time || 0);
                    //});
                    //primaryActive=false; // do not reset here as new chat doesnt exist instantly

                    drawChatList();
                    
                    //if(!found) {
                    //    primaryActive remains its potential submitquery state?
                    //}
                }
            });
        }

        function loadCurrentSdModel() {
            sendAjax('get_current_sd_model', {}, function(res) {
                console.dir(res);
                if (res.status === 'success' && res.current_model) {
                    let modelname=res.current_model.replace(/\.safetensors/,'');
                    console.log(modelname);
                    
                    var select = $('sd-model-select');
                    select.value = modelname;
                    
                    //loadLoraModels();
                }
            });
        }

        function loadSdModels() {
            sendAjax('get_sd_models', {}, function(res) {
                //console.dir(res);
                if (res.status === 'success') {
                    var select = $('sd-model-select');
                    select.innerHTML = '';
                    res.models.forEach(function(m) {
                        if(m.model_name.toLowerCase().includes('flux')) return;
                        var opt = document.createElement('option');
                        //opt.value = m.title;
                        opt.value = m.model_name;
                        opt.innerText = m.model_name;
                        select.appendChild(opt);
                    });

                    loadCurrentSdModel();
                }
            });
        }

        function updateSdModel() {
            var val = $('sd-model-select').value;
            sendAjax('set_sd_model', { title: val }, function(res) {
                alert('Stable Diffusion Checkpoint switched successfully!');
            });
        }
        
        function loadLoraModels() {
            sendAjax('get_lora_models', {}, function(res) {
                if (res.status === 'success') {
                    var select = $('lora-model-select');
                    select.innerHTML = '';
                    //console.dir(res);
                    res.models.forEach(function(m) {
                        if(m.name.toLowerCase().includes('flux')) return;
                        var opt = document.createElement('option');
                        opt.value = m.alias;
                        opt.innerText = m.name;
                        select.appendChild(opt);
                    });
                }
            });
        }
        
        function insertLoraModel() {
            var lora=$('lora-model-select').value;
            var str="<lora:"+lora+":1>,";
            var input = $('user-input');
            if (!input.value.startsWith('/imagine ')) {
                input.value="/imagine "+str+input.value;
            } else {
                let tmpin=input.value.substr(9);
                input.value="/imagine "+str+tmpin;
            }
            input.focus();
        }

        function insertIMG2IMG(btnIm,v=false) {
            let chatId=currentChatId;
            // skip download/upload process and direct link to img2img
            // chatId included to function cross chats-
            // php will handle uploading relevant file on back to ai
            var img=null;
            var src="";
            var msgTime=0;
            var msgPrompt="";
            if(v) {
                img=btnIm.closest(".open").getElementsByTagName('img')[0];
                msgTime=img.getAttribute('data-time');
            } else {
                img=btnIm.closest(".message").getElementsByTagName('img')[0];
                msgTime=img.parentNode.getAttribute('data-time'); 
            }
            // auto set image aspect ratio
            if(img.clientWidth>img.clientHeight) { // wide
                if($('sd-resolution').value!="768x512") {
                    $('sd-resolution').value="768x512";
                }
            } else if(img.clientHeight>img.clientWidth) { // port
                if($('sd-resolution').value!="512x768") {
                    $('sd-resolution').value="512x768";
                }
            } else { // square
                if($('sd-resolution').value!="512x512" && $('sd-resolution')!="768x768") {
                    $('sd-resolution').value="512x512";
                    //$('sd-resolution').value="768x768"; // alternative
                }
            }
            //console.log("img.clientWidth = "+img.clientWidth+", img.clientHeight = "+img.clientHeight);
            //console.log("msgTime = "+msgTime);
            src=img.getAttribute('data-src');

            sendAjax('show_more', { chat_id: currentChatId, message_time: msgTime }, function(res) {
                if (res.status === 'success') {
                    msgPrompt=res.message;
                }
                var file=src.substr(src.lastIndexOf("/")+1);
                var str="<img:"+file+":"+chatId+">"+msgPrompt;
                var input = $('user-input');
                if (!input.value.startsWith('/imagine ')) {
                    input.value="/imagine "+str+input.value;
                } else {
                    let tmpin=input.value.substr(9);
                    input.value="/imagine "+str+tmpin;
                }
                input.focus();

                if(v) {
                    $('image-lightbox').classList.remove('open');
                    currentLightboxSrc = '';

                    if(lightboxPlayOn) {
                        stopLightboxPlay();
                    }
                }
                if(mediaOn) {
                    closeChatMedia();
                }
            });
        }
        
        function nl2br(str) {
            return str.replace(/\n/g,'<br>');
        }

        function formatAttachments(attachment) {
            //console.log(attachment);
            var att=[];
            if(typeof attachment==="string") {
                if(attachment) {
                    let a=attachment.substr(attachment.lastIndexOf("/")+1)
                    att.push(a.replace(/\d+_\d+_/, ""));
                }
            } else if(Array.isArray(attachment) && attachment.length>0) { // array type is "object"
                for(let i=0;i<attachment.length;i++) {
                    if(attachment[i]) {
                        let a=attachment[i].substr(attachment[i].lastIndexOf("/")+1)
                        att.push(a.replace(/\d+_\d+_/, ""));
                    }
                }
            }

            //console.log(att);
            return att;
        }

        // Global state maps in outer scope
        var activePollers = {}; // Stores timeout IDs keyed by chatId
        var chatDrafts = {};    // Stores un-sent textarea input drafts keyed by chatId
        var mediaStore = {};
        
        // 1. Hook up chat switching to save and restore drafts
        function switchChat(chatId,sTB=true,ovr=false) {
            var chatBox = $('chat-box');
            var mediaBox = $('media-box');
            closeQueuePage();

            if(chatId==currentChatId && !ovr) {
                if(mediaOn) {
                    if (currentChatId) {
                        if(mediaStore.hasOwnProperty(currentChatId)) {
                            mediaStore[currentChatId]['mediascroll'] = mediaBox.scrollTop;
                            mediaStore[currentChatId]['msload'] = mediascrollloads;
                        } else {
                            mediaStore[currentChatId] = { mediascroll: mediaBox.scrollTop, msload: mediascrollloads };
                        }
                    }
                    closeChatMedia();
                    return;
                } else {
                    scrollToBottom(chatBox, true);
                    return;
                }
            } else if(chatId!=currentChatId) {
                closeChatMedia();
            }
            
            if (currentChatId) {
                //console.log(currentChatId+'] saving scroll top = '+chatBox.scrollTop);
                //console.log(currentChatId+'] saving scroll loads = '+scrollloads);
                if(chatDrafts.hasOwnProperty(currentChatId)) {
                    chatDrafts[currentChatId]['input'] = $('user-input').value;
                    chatDrafts[currentChatId]['scroll'] = chatBox.scrollTop;
                    chatDrafts[currentChatId]['sload'] = scrollloads;
                } else {
                    chatDrafts[currentChatId] = { input: $('user-input').value, scroll: chatBox.scrollTop, sload: scrollloads };
                }
            }
        
            currentChatId = chatId;
            if(chatDrafts.hasOwnProperty(currentChatId)) {
                $('user-input').value = chatDrafts[currentChatId]['input'] || '';
                // + scroll and page load count?
                // processes in load_chat *
                //console.log("scrollload = "+chatDrafts[currentChatId]['sload']);
                //console.log("scrolltop = "+chatDrafts[currentChatId]['scroll']);
            } else {
                $('user-input').value = '';
            }

            let curscroll=chatBox.scrollTop;
            sendAjax('load_chat', { chat_id: chatId, limit: <?php echo $loadLimit; ?> }, function(res) {
                if(chatPaginationState.hasOwnProperty(currentChatId)) {
                    chatPaginationState[currentChatId]['offset']=<?php echo $loadLimit; ?>;
                    chatPaginationState[currentChatId]['hasMore']=true;
                    chatPaginationState[currentChatId]['isLoading']=false;
                }

                lfsizec=res.fsizec;
                
                scrollloads = 0;
                mediascrollloads = 0;
                
                //mediaOn = true; // false
                //console.log('toggle media test');
                //toggleChatMedia(); // data test move later to btn

                //console.log(res);
                if (res.status === 'success') {
                    ltime=Date.now();
                    
                    chatBox.innerHTML = '';

                    //ltime=Date.now();

                    var isGenerating=false;
                    var isThinking=false;
                    let msgIdx=0;
                    res.messages.forEach(function(msg) {
                        let attachment=[];
                        if(msg.hasOwnProperty('attachment')) {
                            attachment = formatAttachments(msg.attachment);
                        }

                        appendMessage(
                            msg.role === 'user' ? 'user' : 'assistant',
                            msg.content,
                            attachment,
                            msg.is_image || false,
                            true,
                            false, //isGeneratingImage
                            msg.is_upscaled || false, // Pass optional key here!
                            msg.time, // new id instead of index
                            msg.metadata || {width: 512, height: 512}
                        );
                        msgIdx++;
                    });
        
                    $('chat-title-input').value = res.title || chatId;

                    if(chatStatus.hasOwnProperty(chatId)) {
                        isGenerating=chatStatus[chatId]['generating']>0?true:false;
                        isThinking=chatStatus[chatId]['thinking']>0?true:false;
                    } else {
                        isGenerating=false;
                        isThinking=false;
                    }
        
                    // RESTORE GENERATING STATE IF REFRESHED/SWITCHED MID-STREAM
                    if (isGenerating) {
                        if (!$('loading-bubble')) {
                            // If it's an image generation state, ensure it boots up with the Imagine tag
                            //var isImgGen = res.is_image_generating || true; // Or check your active session flag
                            var isImgGen = true;
                            appendMessage('loading', '', [], false, true, isImgGen);
                        }
                        pollImageProgress(currentChatId);
                    } else if(isThinking) {
                        if (!$('loading-bubble')) {
                            appendMessage('loading', '', [], false, true, false);
                        }
                    }

                    if(sTB) {
                        scrollToBottom(chatBox,true);
                    } else {
                        setTimeout(function() { chatBox.scrollTop=curscroll; }, 100);
                    }
                    //loadChatList();
                    clearTimeout(kAT);
                    kATC=0;
                    keepAlive();

                    if(chatDrafts.hasOwnProperty(currentChatId) && !sTB) {
                        if(chatDrafts[currentChatId]['sload']>0) {
                            console.log(currentChatId+'] autoload loadinit sload = '+chatDrafts[currentChatId]['sload']);
                            chatDrafts[currentChatId]['sload']--;
                            loadMoreMessages(currentChatId,true); // autoload
                        } else {
                            //console.log(currentChatId+'] auto scroll init top to = '+chatDrafts[currentChatId]['scroll']);
                            setTimeout(function() {
                                // Use smooth behavior on desktop, instant on mobile to avoid render lag
                                chatBox.scrollTo({
                                    top: chatDrafts[currentChatId]['scroll'],
                                    behavior: 'auto'
                                });
                                //box.scrollTop = box.scrollHeight;
                                chatDrafts[currentChatId]['scroll'] = 0;
                            }, 100);
                        }
                    }
                }

                lazyChatLoad();
            });
        }

        // State tracking for pagination per chats
        var chatPaginationState = {};
        var mediaPaginationState = {};
        var cLL,mLL;
        function initChatScrollListener() {
            var chatBox = $('chat-box');
        
            // Clean up any existing listener to prevent duplicate binding on switchChat
            chatBox.onscroll = function() {
                // Trigger when scrolled within 50px of the top
                if (chatBox.scrollTop <= (chatBox.clientHeight * .5)) {
                    if (!currentChatId) return;
        
                    // Initialize state if missing
                    if (!chatPaginationState[currentChatId]) {
                        chatPaginationState[currentChatId] = { offset: <?php echo $loadLimit; ?>, hasMore: true, isLoading: false };
                    }
        
                    let state = chatPaginationState[currentChatId];
                    if (state.hasMore && !state.isLoading) {
                        loadMoreMessages(currentChatId,false,true);
                    }
                }

                lazyChatLoad();
            };
        }

        function initMediaScrollListener() {
            var mediaBox = $('media-box');

            // Clean up any existing listener to prevent duplicate binding on switchChat
            mediaBox.onscroll = function() {
                // Trigger when scrolled within 50px of the top
                //console.log("mediaBox.scrollTop = "+mediaBox.scrollTop+", mediaBox.clientHeight = "+mediaBox.scrollHeight);
                if (mediaBox.scrollTop >= mediaBox.scrollHeight - (mediaBox.clientHeight * 5)) {
                    if (!currentChatId) return;
        
                    // Initialize state if missing
                    if (!mediaPaginationState[currentChatId]) {
                        mediaPaginationState[currentChatId] = { offset: <?php echo $loadLimitMedia; ?>, hasMore: true, isLoading: false };
                    }
        
                    let state = mediaPaginationState[currentChatId];
                    if (state.hasMore && !state.isLoading) {
                        getChatMedia(true);
                    }
                }

                lazyMediaLoad(); 
            }
        }

        function lazyChatLoad() {
            var chatBox = $('chat-box');

            // track img tags here disable/enable preview within the scope of the view? for large chat view
            clearTimeout(cLL);
            cLL=setTimeout(function() {
                var elms=chatBox.getElementsByTagName("img");
                var chatHeight=chatBox.clientHeight;
                var scrollHeight=chatBox.scrollHeight;
                var scrollTop=chatBox.scrollTop;
                var scrollMin=scrollTop-1000;
                var scrollMax=scrollTop+chatHeight+1000;
                var elmsTop=0;
                var elmsBot=0;
                //console.log("scrollMin: "+scrollMin+", scrollMax: "+scrollMax+", elms.length = "+elms.length);
                var bounds=null;
                for(let i=elms.length-1;i>=0;i--) {
                    if(elms[i].getAttribute('data-src')) {
                        bounds=elms[i].getBoundingClientRect();
                        elmsTop=-bounds.top+(scrollHeight-scrollTop);
                        elmsTop=scrollHeight-elmsTop;
                        elmsBot=elmsTop+bounds.height;

                        
                        //console.log("elms["+i+"].offsetTop = "+elmsTop);
                        if((elmsTop<=scrollMax && elmsTop>=scrollMin) || (elmsBot<=scrollMax && elmsBot>=scrollMin)) {
                            //
                            var previewSrc = elms[i].getAttribute('data-src').replace('/generated/', '/generated_prev/').replace('.png', '.jpg');
                            //console.log("show img index "+i+" within view, previewSrc = "+previewSrc);
                            elms[i].src=previewSrc;
                            //console.log(elms[i]);
                            if(elms[i].getAttribute('data-hidden')) {

                                elms[i].setAttribute('data-hidden',0);
                                elms[i].removeAttribute('data-hidden');
                            }
                        } else {
                            //
                            //console.log("hide img index "+i+" outside view");
                            elms[i].src="";
                            if(!elms[i].getAttribute('data-hidden')) {
                                elms[i].setAttribute('data-hidden',1);

                            }
                        }
                    }
                }
            }, 50);
        }

        function lazyMediaLoad() {
            var mediaBox = $('media-box');
            // track img tags here disable/enable preview within the scope of the view? for large chat view
            clearTimeout(mLL);
            mLL=setTimeout(function() {
                var elms=mediaBox.getElementsByTagName("img");
                var mediaHeight=mediaBox.clientHeight;
                var scrollHeight=mediaBox.scrollHeight;
                var scrollTop=mediaBox.scrollTop;
                var scrollMin=scrollTop-500;
                var scrollMax=scrollTop+mediaHeight+500;
                var elmsTop=0;
                var elmsBot=0;
                //console.log("scrollMin: "+scrollMin+", scrollMax: "+scrollMax+", elms.length = "+elms.length);
                var bounds=null;
                for(let i=elms.length-1;i>=0;i--) {
                    if(elms[i].getAttribute('data-src')) {
                        bounds=elms[i].getBoundingClientRect();
                        elmsTop=-bounds.top+(scrollHeight-scrollTop);
                        elmsTop=scrollHeight-elmsTop;
                        elmsBot=elmsTop+bounds.height;

                        
                        //console.log("elms["+i+"].offsetTop = "+elmsTop);
                        if((elmsTop<=scrollMax && elmsTop>=scrollMin) || (elmsBot<=scrollMax && elmsBot>=scrollMin)) {
                            //
                            var thumbSrc = elms[i].getAttribute('data-src').replace('/generated/', '/generated_thumb/').replace('.png', '.jpg');
                            //console.log("show img index "+i+" within view, previewSrc = "+previewSrc);
                            elms[i].src=thumbSrc;
                            //console.log(elms[i]);
                            if(elms[i].getAttribute('data-hidden')) {

                                elms[i].setAttribute('data-hidden',0);
                                elms[i].removeAttribute('data-hidden');
                            }
                        } else {
                            //
                            //console.log("hide img index "+i+" outside view");
                            elms[i].src="";
                            if(!elms[i].getAttribute('data-hidden')) {
                                elms[i].setAttribute('data-hidden',1);

                            }
                        }
                    }
                }
            }, 50);
        }

        var scrollloads=0;
        var mediascrollloads=0;
        function loadMoreMessages(chatId,ovr=false,blk=false) {
            ldtime=Date.now()-ltime;
            if(ldtime<1000 && !ovr) return;

            let state = chatPaginationState[chatId];
            state.isLoading = true;
            var chatBox = $('chat-box');
        
            // Capture pre-load scroll height and position to anchor mobile viewport
            let oldScrollHeight = chatBox.scrollHeight;
            let oldScrollTop = chatBox.scrollTop + chatBox.clientHeight;
        
            sendAjax('load_chat', { chat_id: chatId, limit: <?php echo $loadLimit; ?>, offset: state.offset }, function(res) {
                if (res.status === 'success' && res.messages && res.messages.length > 0) {
                    state.offset += res.messages.length;
                    state.hasMore = res.has_more;
                    
                    scrollloads++;
        
                    // Build temporary container for older messages to prepend safely
                    var fragment = document.createDocumentFragment();
        
                    res.messages.forEach(function(msg) {
                        // Re-run your attachment formatters here if needed
                        let attachment=[];
                        if(msg.hasOwnProperty('attachment')) {
                            attachment = formatAttachments(msg.attachment);
                        }
        
                        var msgDiv = createMessageElement(
                            msg.role === 'user' ? 'user' : 'assistant',
                            msg.content,
                            attachment,
                            msg.is_image || false,
                            true,
                            false, //isGeneratingImage
                            msg.is_upscaled || false, // Pass optional key here!
                            msg.time, // new id instead of index
                            msg.metadata || {width: 512, height: 512}
                        );
                        fragment.appendChild(msgDiv);
                    });
        
                    // Prepend to top of chat box
                    chatBox.insertBefore(fragment, chatBox.firstChild);
        
                    // MOBILE STABILITY FIX: Adjust scrollTop by the height difference
                    // so the user's view doesn't get violently thrown around
                    let newScrollHeight = chatBox.scrollHeight;
                    chatBox.scrollTop = oldScrollTop + (newScrollHeight - oldScrollHeight);
        
                    //console.dir(chatDrafts);
                    if(chatDrafts.hasOwnProperty(currentChatId)) {
                        if(chatDrafts[currentChatId]['sload']>0) {
                            console.log(currentChatId+'] autoload loadmore sload = '+chatDrafts[currentChatId]['sload']);
                            chatDrafts[currentChatId]['sload']--;
                            loadMoreMessages(currentChatId,true); // autoload more
                        } else if(!blk) {
                            console.log(currentChatId+'] auto scroll more top to = '+chatDrafts[currentChatId]['scroll']);
                            setTimeout(function() {
                                // Use smooth behavior on desktop, instant on mobile to avoid render lag
                                chatBox.scrollTo({
                                    top: chatDrafts[currentChatId]['scroll'],
                                    behavior: 'auto'
                                });
                                //box.scrollTop = box.scrollHeight;
                                chatDrafts[currentChatId]['scroll'] = 0;
                            }, 100);
                        }
                    }
                    
                    state.isLoading = false;
                } else {
                    state.hasMore = false;
                    state.isLoading = false;
                }
            });
        }
        
        function build_pp() { // memory profile
            sendAjax('build_personality_profile', { },
            function(res) {
                console.log('sent personality data for profile building');
                console.log(res);
            });
        }
        
        var ppT = 2; // trigger early onload

        var kATT = 3;
        var kATC = 0;
        var kAT;

        var totalQueue=0;
        var indexQueue=-1;

        var chatStatus={};
        
        var upscaleQueue=[];
        var queueCopy=[];
        function keepAlive() {
            clearTimeout(kAT);

            if(lightboxPlayOn) {
                if(lbTC==0) {
                    lightboxPlayRandom();
                    lbTC=lbT;
                }
                lbTC--;
            }

            if (kATC === 0) {
                // Run background history sync / queue state check
                loadChatList();

                // Fetch queue status to calculate position and update indicators
                sendAjax('check_queue_status', { chat_id: currentChatId }, function(res) {
                    //console.dir(res);
                    indexQueue=-1;
                    if (res.status === 'success' && res.queue) {
                        var chatBox = $('chat-box');

                        //let thinking = res.queue.filter(j => j.type === 'ai_chat');
                        //let generating = res.queue.filter(j => j.type === 'generate_image');

                        //chatStatus.forEach(chat => {
                        queueCopy=res.queue;
						let queuepagetext="Queue page";
                        if(res.queue.length>0) {
                            queuepagetext="Queue page ["+res.queue.length+"]";
                        }
						$('queue-page-link').innerHTML=queuepagetext;
						$('queue-page-link2').innerHTML=queuepagetext;
                        if(queuePageOn) {
                            updateQueuePage();
                        }
                        //
                        Object.entries(chatStatus).forEach(([key, value]) => {
                            value['thinking']=0;
                            value['generating']=0;
                            value['error']=0;
                        });
                        //
                        var isGenerating=false;
                        var isThinking=false;
                        primaryActive=false;
                        for(let i=0;i<res.queue.length;i++) {
                            let chatId=res.queue[i]['chat_id'];
                            if(!chatStatus.hasOwnProperty(chatId)) {
                                chatStatus[chatId]={thinking: 0,generating:0,error:0,completed:0};
                            }

                            let msgType=res.queue[i]['type'];

                            isGenerating=false;
                            isThinking=false;

                            const ff=$('chat-list').querySelector(`.chat-item[data-id="${chatId}"]`);
                            if(ff!=null) if(ff.classList.contains("error")) ff.classList.remove("error");
                            if(res.queue[i]['status']=="error" ) {
                                chatStatus[chatId]['error']+=1;
                                console.log('queue error -> '+res.queue[i]['type']+" ("+chatId+")");
                                if(ff!=null) ff.classList.add("error");
                                if(currentTab!="chats") {
                                    $('btn-tab-chats').classList.toggle('error');
                                }
                            } else if(res.queue[i]['status']=="completed" ) {
                                chatStatus[chatId]['completed']+=1;
                            } else {
                                // non error non complete
                                switch(msgType) {
                                    case "ai_chat":
                                        chatStatus[chatId]['thinking']+=1;
                                        isThinking=true;
                                        break;
                                    case "generate_image":
                                        chatStatus[chatId]['generating']+=1;
                                        isGenerating=true;
                                        break;

                                }
                                if(chatId==currentChatId) {
                                    if(isGenerating || isThinking) {
                                        primaryActive=true;
                                    } else {
                                        primaryActive=false;
                                    }
                                    //if(msgType=="upscale_image") {
                                    //    //
                                    //}
                                }
                                //
                            }
                        }

                        // 1. Key by job_id (or chat_id + message_time)
                        const getKey = (item) => item.job_id; 

                        // 2. Index only the old items relevant to the active chat
                        const oldMap = new Map(
                            upscaleQueue
                                .filter(item => item.chat_id === currentChatId)
                                .map(item => [getKey(item), item])
                        );

                        // 3. Update the global queue with the new fetch
                        upscaleQueue = res.queue.filter(j => j.type === 'upscale_image');

                        // 4. Helper using payload's message_role and message_time
                        const getMessageEl = (payload) => 
                            chatBox.querySelector(`.message[data-role="${payload.message_role}"][data-time="${payload.message_time}"]`);
                            
                        //console.dir(upscaleQueue);

                        // 5. Process active & newly added items for the current chat
                        for (const item of upscaleQueue) {
                            if (item.chat_id !== currentChatId) continue;

                            const key = getKey(item);
                            if (oldMap.has(key)) {
                                // Still processing: remove from oldMap so it isn't marked as removed
                                oldMap.delete(key);
                            } else {
                                // Newly added in this pull
                            }
                            
                            const msgEl = getMessageEl(item.payload);
                            if (msgEl) {
                                let btn = msgEl.getElementsByTagName("button")[2];
                                if (btn) {
                                    btn.disabled = true;
                                    btn.innerHTML = 'Upscaling...';
                                    msgEl.getElementsByTagName("button")[0].style.display="none";
                                    msgEl.getElementsByTagName("button")[1].style.display="none";
                                    msgEl.getElementsByTagName("button")[3].style.display="none";

                                    //img2imgBtnHtml = 0
                                    //copyBtnHtml = none
                                    //downloadBtnHtml = 1
                                    //upscaleBtnHtml = 2
                                    //deleteBtnHtml = 3
                                }
                                //console.log('marking button processing');
                            }
                        }

                        // 6. Process items that disappeared (finished/cleared out)
                        for (const item of oldMap.values()) {
                            const msgEl = getMessageEl(item.payload);
                            if (msgEl) {
                                const strongEl = msgEl.getElementsByTagName("strong")[0];
                                if (strongEl) strongEl.innerHTML = "Imagine Upscaled:";
                                
                                const img = msgEl.getElementsByTagName("img")[0];
                                if (img && item.payload.png_path) {
                                    // Convert "./chats/.../img-1794762619.png" -> "./chats/.../img-1794762619-upscaled.png"
                                    const upscaledPath = item.payload.png_path.replace(/\.png$/i, '-upscaled.png');
                                    
                                    img.src = upscaledPath;
                                    img.setAttribute('data-src', upscaledPath);
                                    // Update onerror too so a retry doesn't fall back to the old low-res image
                                    img.setAttribute('onerror', `this.src='${upscaledPath}'`);
                                }
                                
                                const btn = msgEl.getElementsByTagName("button")[2];
                                if (btn) {
                                    msgEl.getElementsByTagName("button")[0].style.display="";
                                    msgEl.getElementsByTagName("button")[1].style.display="";
                                    msgEl.getElementsByTagName("button")[3].style.display="";
                                    btn.remove();
                                }
                                
                                //console.log("removing button swapping pic");
                            }
                        }
                        
                        let pendingJobs = res.queue.filter(j => j.status === 'pending' || j.status === 'processing');
                        totalQueue=pendingJobs.length;
                        
                        //console.log(currentChatId);
                        //console.dir(res);

                        if (currentChatId) {
                            let myIndex = pendingJobs.findIndex(j => j.chat_id === currentChatId);
                            let activeIndex = pendingJobs.findIndex(j => j.status === "processing");
                            let loader = $('loading-bubble');
                            if (loader) {
                                if (pendingJobs[myIndex]?.status==="pending") {
                                    let myPosition=myIndex;
                                    if(activeIndex>myIndex) myPosition+=1;
                                    indexQueue=myPosition;
                                    loader.querySelector('.typing-dots').innerText = "Queued position: #" + myPosition;
                                }
                            }

                            // Check if current chat job completed in background
                            let curChatCompleted = res.queue.find(j => j.chat_id === currentChatId && j.status === 'completed') || false;
                            //console.log("--"+curChatCompleted+"--");
                            if (curChatCompleted && loader) {
                                switchChat(currentChatId, true, true); // Refresh chat to pull completed content
                                console.log("switchChat curChatComplete && loader");
                            } else if(loader && !primaryActive) {
                                switchChat(currentChatId, true, true); // Refresh for other device if in feed
                                console.log("switchChat loader && !primaryActive");
                            }
                        }
                    }
                });
        
                kATC = kATT;
            } else {
                kATC--;
            }
            
            ppT--;
            if(ppT<=0) {
                build_pp(); // memoryprofile
                ppT=1800;
            }
        
            kAT = setTimeout(keepAlive, 1000);
        }

        var sTB;
        function scrollToBottom(box, f = false) {
            clearTimeout(sTB);
            //console.log('scrollToBottom(box, f = '+f);
            let cont = true;
            if (!f) {
                cont = false;
                let chatheight = box.clientHeight;
                let maxscroll = box.scrollHeight - chatheight;
                let curscroll = box.scrollTop;
        
                // If user is within half a screen of the bottom, keep auto-scrolling
                if (curscroll > maxscroll - (chatheight * 0.5)) {
                    cont = true;
                }
            }
        
            if (cont) {
                sTB = setTimeout(function() {
                    // Use smooth behavior on desktop, instant on mobile to avoid render lag
                    box.scrollTo({
                        top: box.scrollHeight,
                        behavior: 'auto'
                    });
                    //box.scrollTop = box.scrollHeight;
                }, 100);
            }
        }
        
        function newChat() {
            closeQueuePage();

            currentChatId = 'chat-' + Math.floor(Date.now() / 1000);
            $('chat-box').innerHTML = '<div class="message ai"><strong>SYSTEM:</strong><br>New session initialized.</div>';
            $('chat-title-input').value = "New Chat";

            lfsizec=0;

            loadChatList();
        }

        function deleteCurrentChat() {
            if (!currentChatId) return;
            if (confirm("Are you sure you want to delete this chat session? (deletes entry but keeps content)")) {
                sendAjax('delete_chat', { chat_id: currentChatId }, function(res) {
                    if (res.status === 'success') {
                        newChat();
                    }
                });
            }
        }

        var chatMediaLoaded=0; // reset on close media? or switchChat
        function getChatMedia(more=false,first=false) {
            var mediaBox = $('media-box');
            if(!more) {
                //mediaList=[];
                mediaBox.innerHTML="";
                //console.log('get chat media init');
            } else {
                //console.log('get chat media more');
            }
            
            let state = mediaPaginationState[currentChatId];
            state.isLoading = true;
            sendAjax('get_media', { chat_id: currentChatId, limit: <?php echo $loadLimitMedia; ?>, offset: state.offset }, function(res) {
                if (res.status === 'success' && res.images && res.images.length > 0) {
                    state.offset += res.images.length;
                    state.hasMore = res.has_more;

                    if(more) {
                        mediascrollloads++;
                    }

                    var fragment = document.createDocumentFragment();
        
                    res.images.forEach(function(img) {
                        var aspect=img.width/img.height;

                        //mediaList[]=img; // keep track?

                        var fullSrc=img.image;
                        var thumbSrc = fullSrc.replace('/generated/', '/generated_thumb/').replace('.png', '.jpg');

                        var imgDiv = document.createElement('div');
                        imgDiv.className="media image";

                        var imgElem = document.createElement('img');
                        //imgElem.src=thumbSrc;
                        imgElem.src=""; // lazyload onscroll
                        imgElem.className="thumb";
                        imgElem.style.width="128px";
                        imgElem.style.height=(128/aspect)+"px";
                        imgElem.setAttribute('data-time',img.time);
                        imgElem.setAttribute('data-src',fullSrc);
                        imgElem.onclick=function() { openLightbox(this.getAttribute('data-src'),this.getAttribute('data-time')); };

                        imgDiv.appendChild(imgElem);

                        fragment.appendChild(imgDiv);
                    });
        
                    // Prepend to top of chat box
                    //mediaBox.insertBefore(img, mediaBox.firstChild);
                    mediaBox.appendChild(fragment);
                } else {
                    mediaBox.style.display="block";
                    mediaBox.innerHTML="No media found in this chat. <a href=\"javascript:closeChatMedia();\" target=\"_self\">[close]</a>";
                }
                //
                state.isLoading=false;

                if(currentChatId && (first)) { 
                    if(mediaStore.hasOwnProperty(currentChatId)) {
                        if(mediaStore[currentChatId]['msload']>0) {
                            console.log(currentChatId+'] autoload loadinit msload = '+mediaStore[currentChatId]['msload']);
                            mediaStore[currentChatId]['msload']--;
                            getChatMedia(true,true);
                        } else {
                            //console.log(currentChatId+'] auto scroll init top to = '+mediaStore[currentChatId]['scroll']);
                            setTimeout(function() {
                                // Use smooth behavior on desktop, instant on mobile to avoid render lag
                                mediaBox.scrollTo({
                                    top: mediaStore[currentChatId]['mediascroll'],
                                    behavior: 'auto'
                                });
                                //box.scrollTop = box.scrollHeight;
                                mediaStore[currentChatId]['mediascroll'] = 0;
                            }, 100);    
                        }
                    }
                    if(first) {
                        lazyMediaLoad(); // init lazy
                    }
                }
            });
        }

        var mediaOn=false;
        //var mediaList=[];
        function toggleChatMedia() {
            var iconmedia="↩";

            mediaOn=!mediaOn; // set false on leaving / reload chats?

            if(!mediaPaginationState.hasOwnProperty(currentChatId)) {
                mediaPaginationState[currentChatId]={offset: 0,  hasMore: true, isLoading: false};
            }

            //console.log('mediaon = '+mediaOn);
            // for media page in chats not yet implemented
            if(mediaOn) {
                closeQueuePage();

                $('media-chat-btn').innerHTML=iconmedia;
                $('media-chat-btn').className="active";

                //console.log("opening chat media");
                $('chat-box').style.display="none";
                $('media-box').style.display="flex";

                getChatMedia(false,true);
            } else {
                //
                closeChatMedia();
            }
        }

        function closeChatMedia() {
            var iconchat="⊞";
            $('media-chat-btn').innerHTML=iconchat;
            $('media-chat-btn').className="";

            var mediaBox = $('media-box');
            var chatBox = $('chat-box');

            if(currentChatId) {
                if(mediaPaginationState.hasOwnProperty(currentChatId)) {
                    let state = mediaPaginationState[currentChatId];
                    state.isLoading = false;
                    state.hasMore = true;
                    state.offset = 0;
                }
                // store on close media page?
                if(mediaStore.hasOwnProperty(currentChatId)) {
                    mediaStore[currentChatId]['mediascroll'] = mediaBox.scrollTop;
                    mediaStore[currentChatId]['msload'] = mediascrollloads;
                } else {
                    mediaStore[currentChatId] = { mediascroll: mediaBox.scrollTop, msload: mediascrollloads };
                }
            }
            
            mediascrollloads = 0;

            //console.log("closing chat media");
            mediaBox.style.display="";
            chatBox.style.display="";

            mediaOn=false;
            //mediaList=[];
            mediaBox.innerHTML="";
        }

        function updateChatTitle() {
            var newTitle = $('chat-title-input').value.trim();
            if (!currentChatId || !newTitle) return;
            sendAjax('rename_chat', { chat_id: currentChatId, title: newTitle }, function(res) {
                if (res.status === 'success') {
                    loadChatList();
                }
            });
        }

        function insertEmoji(emoji) {
            var input = $('user-input');
            input.value += emoji;
            input.focus();
        }

        function showmore(msgTime) {
            let ccid = currentChatId;

            sendAjax('show_more', { chat_id: currentChatId, message_time: msgTime }, function(res) {
                if (res.status === 'success') {
                    //alert(res.message);
                    let msg=res.message;
                    msg=msg.replace(/</g,'&lt;');
                    msg=msg.replace(/>/g,'&gt;');
                    
                    let mtime=res.message_time;
                    let elm_messages=document.getElementsByClassName('message');
                    for(let i=0;i<elm_messages.length;i++) {
                        if(elm_messages[i].getAttribute('data-time')==mtime) {
                            let elm_msg=elm_messages[i].getElementsByClassName('msg')[0];
                            elm_msg.innerHTML = nl2br(msg);

                            if(copyFull==1) {
                                copyFull=2;
                                copyMessageText(copyBtn,true);
                            }
                            break;
                        }
                    }
                } else {
                    alert("Error: could not find the message!");
                }
            });
        }
        
        var ltime=0;
        var ldtime=0;
        function imgready() {
            if(chatDrafts.hasOwnProperty(currentChatId)) {
                if(chatDrafts[currentChatId]['scroll']!=0) {
                    return;
                }
            }
            ldtime=Date.now()-ltime;

            if(ldtime<1000) {
                scrollToBottom($('chat-box'),true);
            }
        }

        function createMessageElement(sender, text, attachment = [], isImage = false, sTB = true, isGeneratingImage = false, isUpscaled = false, msgTime = 0, msgMeta = {}) {
            var chatBox = $('chat-box');
            var msgDiv = document.createElement('div');
            var sender_t=sender;
            if(sender=="user-prev") sender="user";

            msgDiv.className = "message " + ((sender==='user')?'user':'ai');
            msgDiv.setAttribute('data-time',msgTime);
            msgDiv.setAttribute('data-role',sender);
            if(text==null) return msgDiv;

            if(sender=="user") {
                text=text.replace(/</g,'&lt;');
                text=text.replace(/>/g,'&gt;');
            }

            // --- START: Feature 4 Truncation Implementation ---
            let displayContent = '';
            let smlnk = '';
            const MAX_MESSAGE_LENGTH = 300; // Define a reasonable limit for readability
            let isTruncated = false;

            //if (text.length > MAX_MESSAGE_LENGTH && (sender_t == "user" || sender_t=="user-prev")) {
            if (text.length > MAX_MESSAGE_LENGTH && sender_t == "user") {
                displayContent = text.substring(0, MAX_MESSAGE_LENGTH) + '...';
                if(sender_t=="user") {
                    smlnk = "<span class=\"smlnk\"><a href=\"javascript:showmore("+msgTime+");\" target=\"_self\">Show more</a></span>";
                }
                isTruncated = true;
            }
            // --- END: Feature 4 Truncation Implementation ---

            // Build Action Toolbar, injecting msgTime safely if available
            var copyBtnHtml = (!isImage && sender_t!="user-prev")?'<button onclick="copyMessageText(this)" title="Copy text">Copy</button>':'';
            var downloadBtnHtml = (isImage)?'<button onclick="downloadImage(this)" title="Download image">Download</button>':'';
            var deleteBtnHtml = (msgTime !== 0) ? '<button onclick="deleteMessage(\'' + currentChatId + '\', this)" title="Delete message">Del</button>' : '';
            // Add Upscale button only if it's an image and NOT already upscaled or upload?
            //var upscaleBtnHtml = (isImage && !isUpload && !isUpscaled && msgTime !== null)
            var upscaleBtnHtml = (isImage && !isUpscaled && msgTime !== 0)
                ? '<button onclick="triggerUpscale(\'' + currentChatId + '\', this)" title="Upscale 2x with SD">Upscale</button>'
                : '';


            var img2imgBtnHtml = (isImage && msgTime !== 0)
                ? '<button onclick="insertIMG2IMG(this)" title="Insert as image2image">IMG2IMG</button>'
                : '';

            var actionsHtml = '<div class="message-actions">' +
                              img2imgBtnHtml +
                              copyBtnHtml +
                              downloadBtnHtml +
                              upscaleBtnHtml +
                              deleteBtnHtml +
                              '</div>';

            if (isImage) {
                var fullSrc = text;
                var previewSrc = text.replace('/generated/', '/generated_prev/').replace('.png', '.jpg');
                var labelPrefix = isUpscaled ? 'Imagine Upscaled:' : 'Imagine:';

                var iw=window.innerWidth-10-10-15-15-3-10-10;
                var maxsize=512+10+10+15+15+3+10+10;
                if(iw<maxsize) {
                    maxsize=iw;
                } else {
                    maxsize=512;
                }
                var aspect=msgMeta['width']/msgMeta['height'];
                //'onload="imgready();" ' +
                //'src="' + previewSrc + '" ' +
                //'onerror="this.src=\'' + fullSrc + '\'" ' +
                msgDiv.innerHTML = actionsHtml + '<strong>' + labelPrefix + '</strong><br>' +
                                   '<img class="generated-art" ' +
                                   'onclick="openLightbox(this.getAttribute(\'data-src\'),parentNode.getAttribute(\'data-time\'));" ' +
                                   'data-src="' + fullSrc + '" ' +
                                   'title="Click to view full-res PNG" ' +
                                   'style="max-width:'+maxsize+'px; width:100%; height:auto; cursor:pointer; border:1px solid #444; border-radius:4px; margin-top:6px; display:block; width: '+maxsize+'px; height: '+(maxsize/aspect)+'px;">';
            } else if (sender_t === 'loading') {
                msgDiv.className = "message ai";
                msgDiv.id = "loading-bubble";
                
                // Check if this loading bubble is for an image generation or standard AI chat text
                if (isGeneratingImage) {
                    msgDiv.innerHTML = '<strong>Imagine:</strong><br><div class="typing-dots">Initializing render...</div>';
                    pollImageProgress(currentChatId);
                } else {
                    msgDiv.innerHTML = '<strong>AI:</strong><br><div class="typing-dots"><span>.</span><span>.</span><span>.</span></div>';
                }
            } else {                
                let att='';
                if(attachment.length>0) {
                    att="<span class=\"attachment\">[Attachment:";
                    for(let i=0;i<attachment.length;i++) {
                        if(attachment[i]) {
                            att+=" "+attachment[i];
                        }
                    }
                    att+="]</span><br>";
                }
                if(isTruncated) {
                    msgDiv.innerHTML = actionsHtml + '<strong>' + (sender === 'user' ? 'You:' : 'AI:') + '</strong><br>'+att+'<span class="msg">' + nl2br(displayContent) + smlnk + '</span>';
                } else {
                    if(sender === 'user') {
                        msgDiv.innerHTML = actionsHtml + '<strong>' + 'You:' + '</strong><br>'+att+'<span class="msg">' + nl2br(text) + '</span>';
                    } else {
                        msgDiv.innerHTML = actionsHtml + '<strong>' + 'AI:' + '</strong><br>'+att+'<span class="msg">' + formatText(text) + '</span>';
                    }
                }
            }

            return msgDiv;
        }

        function appendMessage(sender, text, attachment = [], isImage = false, sTB = true, isGeneratingImage = false, isUpscaled = false, msgTime = 0, msgMeta = {}) {
            var chatBox = $('chat-box'); 

            var msgDiv=createMessageElement(sender, text, attachment, isImage, sTB, isGeneratingImage, isUpscaled, msgTime, msgMeta);
        
            chatBox.appendChild(msgDiv);

            // Only highlight code blocks that haven't been processed yet
            document.querySelectorAll('pre code:not([data-highlighted])').forEach((block) => {
                hljs.highlightElement(block);
            });

            // Inside appendMessage, right after code highlighting:
            document.querySelectorAll('pre:not([data-copy-wired])').forEach((pre) => {
                pre.setAttribute('data-copy-wired', 'true');
            
                var copyBtn = document.createElement('button');
                copyBtn.innerText = 'Copy';
                copyBtn.className = 'code-copy-btn';
                copyBtn.title = 'Copy code snippet';
            
                copyBtn.onclick = function() {
                    var codeEl = pre.querySelector('code');
                    var textToCopy = codeEl ? codeEl.innerText : pre.innerText;
            
                    // Use our robust fallback/clipboard handler
                    if (navigator.clipboard && navigator.clipboard.writeText) {
                        navigator.clipboard.writeText(textToCopy).then(function() {
                            showCopiedFeedback(copyBtn);
                        }).catch(function() {
                            fallbackCopyText(textToCopy, copyBtn);
                        });
                    } else {
                        fallbackCopyText(textToCopy, copyBtn);
                    }
                };
            
                pre.appendChild(copyBtn);
            });
            
            if (sTB) scrollToBottom(chatBox,true);
        }

        function removeLoading() {
            var loader = $('loading-bubble');
            if (loader) loader.remove();
        }

        function formatText(text, ebr = true) {
            if (!text) return '';

            // 1. Extract and protect fenced code blocks first
            var codeBlocks = [];
            var protectedText = text.replace(/```([\s\S]*?)```/g, function(match) {
                var placeholder = '___CODE_BLOCK_' + codeBlocks.length + '___';
                codeBlocks.push(match);
                return placeholder;
            });

            // Escape HTML on surrounding text
            var safe = protectedText
                .replace(/&/g, "&amp;")
                .replace(/</g, "&lt;")
                .replace(/>/g, "&gt;");

            // 2. Extract and protect inline code (`code`) BEFORE bold/italic
            var inlineCodes = [];
            safe = safe.replace(/`([^`\n]+)`/g, function(match, code) {
                var placeholder = '___INLINE_CODE_' + inlineCodes.length + '___';
                inlineCodes.push('<code>' + code + '</code>');
                return placeholder;
            });

            // Headers (#, ##, ###, ####)
            safe = safe.replace(/^#### (.*$)/gim, '<h4>$1</h4>');
            safe = safe.replace(/^### (.*$)/gim, '<h3>$1</h3>');
            safe = safe.replace(/^## (.*$)/gim, '<h2>$1</h2>');
            safe = safe.replace(/^# (.*$)/gim, '<h1>$1</h1>');

            // Bold & Italic
            safe = safe.replace(/\*\*([^\*\n]+)\*\*/g, '<strong>$1</strong>');
            safe = safe.replace(/\*([^\*\n]+)\*/g, '<em>$1</em>');

            // Catch floating state labels like "UI:*" or "Action:*"
            safe = safe.replace(/(UI|Action|Status):\*/gi, '<em>$1:</em>');

            // Line breaks, lists, tables, and horizontal rules
            var lines = safe.split('\n');
            var inUl = false;
            var inOl = false;
            var tableRows = [];
            var result = '';

            function parseTableCells(row) {
                return row.replace(/^\||\|$/g, '').split('|').map(function(cell) {
                    return cell.trim();
                });
            }

            function flushTable() {
                if (tableRows.length === 0) return;

                var isValidTable = tableRows.length >= 2 &&
                    /^\|?\s*:?-{3,}:?\s*(\|\s*:?-{3,}:?\s*)*\|?$/.test(tableRows[1]);

                if (isValidTable) {
                    var headers = parseTableCells(tableRows[0]);
                    var alignments = parseTableCells(tableRows[1]).map(function(sep) {
                        if (sep.startsWith(':') && sep.endsWith(':')) return 'center';
                        if (sep.endsWith(':')) return 'right';
                        return 'left';
                    });

                    var tableHtml = '<table><thead><tr>';
                    headers.forEach(function(header, i) {
                        var align = alignments[i] || 'left';
                        tableHtml += '<th style="text-align:' + align + '">' + header + '</th>';
                    });
                    tableHtml += '</tr></thead><tbody>';

                    for (var r = 2; r < tableRows.length; r++) {
                        var cells = parseTableCells(tableRows[r]);
                        tableHtml += '<tr>';
                        headers.forEach(function(_, i) {
                            var align = alignments[i] || 'left';
                            tableHtml += '<td style="text-align:' + align + '">' + (cells[i] || '') + '</td>';
                        });
                        tableHtml += '</tr>';
                    }

                    tableHtml += '</tbody></table>';
                    result += tableHtml;
                } else {
                    // Not a valid markdown table; output buffered lines normally
                    tableRows.forEach(function(rawLine) {
                        result += ebr ? rawLine + '<br>' : rawLine;
                    });
                }

                tableRows = [];
            }

            lines.forEach(function(line) {
                var trimmed = line.trim();

                // Buffer potential table rows (must contain a pipe and not be a list item or heading)
                var isListItem = trimmed.startsWith('- ') || trimmed.startsWith('* ') || /^\d+\.\s/.test(trimmed);
                var isBlockPlaceholder = /^<h[1-4]>/.test(trimmed) || /^___CODE_BLOCK_\d+___$/.test(trimmed);

                if (trimmed.includes('|') && !isListItem && !isBlockPlaceholder) {
                    if (inUl) { inUl = false; result += '</ul>'; }
                    if (inOl) { inOl = false; result += '</ol>'; }
                    tableRows.push(trimmed);
                    return;
                }

                // Flush any buffered table before handling non-table lines
                flushTable();

                // Horizontal rule
                if (/^(-{3,}|\*{3,}|_{3,})$/.test(trimmed)) {
                    if (inUl) { inUl = false; result += '</ul>'; }
                    if (inOl) { inOl = false; result += '</ol>'; }
                    result += '<hr>';
                    return;
                }

                // Skip empty or dangling bullet dashes
                if (trimmed === '-' || trimmed === '*') return;

                // Bullet list
                if (trimmed.startsWith('- ') || trimmed.startsWith('* ')) {
                    if (inOl) { inOl = false; result += '</ol>'; }
                    if (!inUl) { inUl = true; result += '<ul>'; }
                    result += '<li>' + trimmed.substring(2) + '</li>';
                    return;
                }

                // Numbered list
                if (/^\d+\.\s/.test(trimmed)) {
                    if (inUl) { inUl = false; result += '</ul>'; }
                    if (!inOl) { inOl = true; result += '<ol>'; }
                    result += '<li>' + trimmed.replace(/^\d+\.\s*/, '') + '</li>';
                    return;
                }

                // Close any open lists before normal lines or headings
                if (inUl) { inUl = false; result += '</ul>'; }
                if (inOl) { inOl = false; result += '</ol>'; }

                // Block elements don't need trailing <br>
                if (isBlockPlaceholder) {
                    result += trimmed;
                } else if (trimmed === '') {
                    if (!result.endsWith('<br>') && !result.endsWith('</table>') && result !== '' && ebr) {
                        result += '<br>';
                    }
                } else if (ebr) {
                    result += line + '<br>';
                } else {
                    result += line;
                }
            });

            flushTable();
            if (inUl) result += '</ul>';
            if (inOl) result += '</ol>';

            // Clean up trailing <br> at the very end
            result = result.replace(/(<br>)+$/, '');

            // 3. Restore inline code safely
            inlineCodes.forEach(function(html, index) {
                result = result.replace('___INLINE_CODE_' + index + '___', function() {
                    return html;
                });
            });

            // 4. Restore fenced code blocks safely
            codeBlocks.forEach(function(block, index) {
                var innerMatch = block.match(/```([a-zA-Z0-9_-]*)\n([\s\S]*?)```/);
                var lang = innerMatch && innerMatch[1] ? innerMatch[1] : '';
                var codeContent = innerMatch ? innerMatch[2] : block.replace(/```/g, '').trim();

                var safeCode = codeContent
                    .replace(/&/g, "&amp;")
                    .replace(/</g, "&lt;")
                    .replace(/>/g, "&gt;");

                var replacement = '<pre><code' + (lang ? ' class="language-' + lang + '"' : '') + '>' + safeCode + '</code></pre>';
                result = result.replace('___CODE_BLOCK_' + index + '___', function() {
                    return replacement;
                });
            });

            return result;
        }

        let selectedFileObjects = [];

        function submitQuery() {
            var loader = $('loading-bubble');
            if(loader || primaryActive) {
                alert("This chat already has primary task in progress!");
                return;
            }
            var input = $('user-input');
            var val = input.value.trim();
            if (!val && selectedFileObjects.length==0) return; // Allow sending file with or without text prompt
            if (!currentChatId) currentChatId = 'chat-' + Math.floor(Date.now() / 1000);
            
            // Display preview text locally
            var displayVal = "";
            //displayVal = nl2br(val);
            displayVal = val;
            
            const attachment = selectedFileObjects.map(f => f.name);
            appendMessage('user-prev', displayVal, attachment, false, true);
            input.value = '';
            
            var textModel = $('text-model-select').value;
            var visionModel = $('vision-model-select').value;
            
            // catches mistypes like /image ...
            if (val.startsWith('/i')) val="/imagine "+val.substr(val.indexOf(" ")+1);
            
            // Check if it's an image generation command
            if (val.startsWith('/imagine ')) {
                var imgPrompt = val.replace('/imagine ', '');

                var resVal = $('sd-resolution').value.split('x');
                var baseWidth = parseInt(resVal[0]);
                var baseHeight = parseInt(resVal[1]);
                var is2x = $('sd-multiplier-2x').checked;

                var width = is2x ? baseWidth * 2 : baseWidth;
                var height = is2x ? baseHeight * 2 : baseHeight;
                var steps = parseInt($('sd-steps').value);
                
                var imgModel = $("sd-model-select").value;

                // Pack into FormData to support optional image attachments for img2img
                var formData = new FormData();
                formData.append('action', 'generate_image');
                formData.append('prompt', imgPrompt);
                formData.append('chat_id', currentChatId);
                formData.append('width', width);
                formData.append('height', height);
                formData.append('steps', steps);
                formData.append("model",imgModel);

                if (selectedFileObjects.length > 0) {
                    selectedFileObjects.forEach(function(file) {
                        formData.append('attachment[]', file);
                    });
                }

                var xhr = new XMLHttpRequest();
                xhr.open('POST', 'ajax.php', true);
                xhr.onload = function() {
                    if (activePollers[currentChatId]) {
                        clearTimeout(activePollers[currentChatId].timer);
                        delete activePollers[currentChatId];
                    }
                    if (xhr.status === 200) {
                        try {
                            var res = JSON.parse(xhr.responseText);
                            if (res.status === 'success') {
                                appendMessage('loading', '', [], false, true, true);
                                
                                primaryActive=true;
                            } else {
                                removeLoading();
                                appendMessage('system-error', 'Error generating image: ' + (res.message || 'Unknown error'), [], false, true);
                                loadChatList();
                            }
                        } catch(e) {
                            removeLoading();
                            appendMessage('system-error', 'Invalid JSON response from server.', [], false, true);
                        }
                    } else {
                        removeLoading();
                        appendMessage('system-error', 'HTTP Error: ' + xhr.status, [], false, true);
                    }
                };
                xhr.send(formData);

                // Start polling immediately to catch live frames & %
                pollImageProgress(currentChatId);

                // Update sidebar generator badge indicator
                addChatListLoading();
            } else {
                // Standard chat or multimodal file analysis request using FormData
                var formData = new FormData();
                formData.append('action', 'chat');
                formData.append('chat_id', currentChatId);
                formData.append('prompt', val);
                formData.append('model', textModel);
                formData.append('vmodel', visionModel);
                
                if (selectedFileObjects.length > 0) {
                    selectedFileObjects.forEach(function(file) {
                        formData.append('attachment[]', file);
                    });
                }
                
                var xhr = new XMLHttpRequest();
                xhr.open('POST', 'ajax.php', true);
                xhr.onload = function() {
                    removeLoading();
                    if (xhr.status === 200) {
                        try {
                            //console.log(xhr.responseText);
                            var res = JSON.parse(xhr.responseText);
                            
                            if (res.status === 'success') {
                                appendMessage('loading', '', [], false, true);
                                
                                primaryActive=true;
                            } else {
                                appendMessage('system-error', 'Backend Error: ' + res.message, [], false, true);
                            }
                        } catch(e) {
                            appendMessage('system-error', 'Invalid JSON response from server.', [], false, true);
                        }
                    } else {
                        appendMessage('system-error', 'HTTP Error: ' + xhr.status, [], false, true);
                    }
                };
                xhr.send(formData);

                addChatListLoading();
            }
            clearAttachedFile(); // Clear file input & preview UI
        }

        function addChatListLoading() {
            // loadChatList clears and resets if generating
            let div = $('chat-list').getElementsByClassName("active")[0];
            if (div) {
                let titleText = div.getAttribute('data-name') || div.innerText;
                div.innerHTML = titleText + '<span class="chat-item-generating-dots">...</span>';
            }
        }

        var copyFull=0;
        var copyBtn=null;
        function copyMessageText(btn,sm=false) {
            var msgDiv = btn.closest('.message');

            if(!sm) {
                var smlnks=msgDiv.getElementsByClassName('smlnk');
                if(smlnks.length>0) {
                    var msgTime=msgDiv.getAttribute('data-time');
                    copyFull=1;
                    copyBtn=btn;
                    showmore(msgTime);
                    return;
                }
            }
            if(copyFull>=2) {
                copyFull=0;
                copyBtn=null;
            }

            var clone = msgDiv.cloneNode(true);
            var actions = clone.querySelector('.message-actions');
            if (actions) actions.remove();
        
            //var textToCopy = clone.innerText.replace(/^(You:|AI:|Imagine:)\s*/, '').trim();
            var textToCopy = clone.getElementsByClassName('msg')[0].innerText.replace(/^(You:|AI:|Imagine:)\s*/, '').trim();
            
            // Modern clipboard API with HTTP LAN fallback
            if (navigator.clipboard && navigator.clipboard.writeText) {
                navigator.clipboard.writeText(textToCopy).then(function() {
                    showCopiedFeedback(btn);
                }).catch(function() {
                    fallbackCopyText(textToCopy, btn);
                });
            } else {
                fallbackCopyText(textToCopy, btn);
            }
        }
        
        async function downloadImage(btn,v=false) {
            var msgDiv=null;
            var imageUrl="";
            if(v) {
                msgDiv = btn.closest('.open');
                imageUrl=msgDiv.getElementsByTagName('img')[0].getAttribute('data-src');
            } else {
                msgDiv = btn.closest('.message');
                imageUrl=msgDiv.getElementsByClassName('generated-art')[0].getAttribute('data-src');
            }
            var fileName = imageUrl.substr(imageUrl.lastIndexOf('/')+1);
            
            try {
                // 1. Fetch the image data
                const response = await fetch(imageUrl);
                const blob = await response.blob();

                // 2. Create a temporary local URL for the Blob
                const blobUrl = URL.createObjectURL(blob);

                // 3. Create a hidden <a> tag and trigger the download
                const link = document.createElement('a');
                link.href = blobUrl;
                link.download = fileName;
                document.body.appendChild(link);
                link.click();

                // 4. Clean up the DOM and memory
                document.body.removeChild(link);
                URL.revokeObjectURL(blobUrl);
              } catch (error) {
                console.error('Failed to download image:', error);
              }
        }
        
        function fallbackCopyText(text, btn) {
            var textArea = document.createElement("textarea");
            textArea.value = text;
            textArea.style.position = "fixed";  // Avoid scrolling to bottom
            textArea.style.opacity = "0";
            document.body.appendChild(textArea);
            textArea.focus();
            textArea.select();
        
            try {
                var successful = document.execCommand('copy');
                if (successful) {
                    showCopiedFeedback(btn);
                } else {
                    alert('Failed to copy text.');
                }
            } catch (err) {
                alert('Browser does not support copying from unsecure LAN contexts.');
            }
        
            document.body.removeChild(textArea);
        }
        
        function showCopiedFeedback(btn) {
            var originalText = btn.innerText;
            btn.innerText = 'Copied!';
            setTimeout(function() { btn.innerText = originalText; }, 1500);
        }
        
        function deleteMessage(chatId, btnDe) {
            if (!confirm("Delete this message? (deletes message and its content)")) return;

            var chatBox = $('chat-box');
            // Capture pre-load scroll height and position to anchor mobile viewport
            let oldScrollHeight = chatBox.scrollHeight;
            let oldScrollTop = chatBox.scrollTop + chatBox.clientHeight;
            
            var msgDiv=btnDe.closest(".message");
            //let msgHeight = msgDiv.clientHeight;
            if(msgDiv.getAttribute('data-role')) {
                var msgTime=msgDiv.getAttribute('data-time');
                var msgRole=msgDiv.getAttribute('data-role');
                sendAjax('delete_message', { chat_id: chatId, message_time: msgTime, message_role: msgRole }, function(res) {
                    if (res.status === 'success') {
                        // MOBILE STABILITY FIX: Adjust scrollTop by the height difference
                        // so the user's view doesn't get violently thrown around
                        let newScrollHeight = chatBox.scrollHeight;
                        //chatBox.scrollTop = (oldScrollTop - msgHeight) + (newScrollHeight - oldScrollHeight);
                        chatBox.scrollTop = oldScrollTop + (newScrollHeight - oldScrollHeight);
                        
                        switchChat(chatId,false,true); // Reload chat ledger view cleanly
                    } else {
                        alert("Error deleting message: " + res.message);
                    }
                });
            } else {
                alert("Error: could not find the message!");
            }
        }

        function triggerUpscaleDebug() {
            sendAjax('upscale_debug', { }, function(res) {
                alert('output should be in ./upscalers_debug.json');
            });
        }

        function triggerUpscale(chatId, btnEl) {
            if (btnEl.classList.contains('loading')) return;
            //--if (!confirm("Upscale this image 2x using Stable Diffusion?")) return;
            
            btnEl.classList.add('loading');
            var originalText = btnEl.innerText;
            btnEl.innerText = 'Upscaling...';
            btnEl.disabled = true;

            var msgDiv=btnEl.closest(".message");
            var msgTime=msgDiv.getAttribute('data-time');

            let btn = msgDiv.getElementsByTagName("button")[2];
            if (btn) {
                btn.disabled = true;
                btn.innerHTML = 'Upscaling...';
                msgDiv.getElementsByTagName("button")[0].style.display="none";
                msgDiv.getElementsByTagName("button")[1].style.display="none";
                msgDiv.getElementsByTagName("button")[3].style.display="none";
            }

            sendAjax('upscale_image', { chat_id: chatId, message_time: msgTime }, function(res) {
                if (res.status === 'success') {
                    // Keep button locked as Upscaling until keepAlive/load_chat refreshes it
                } else {
                    alert("Upscale failed: " + (res.message || "Unknown error"));
                    btnEl.classList.remove('loading');
                    btnEl.innerText = originalText;
                    btnEl.disabled = false;
                }
            });
        }

        function handleMultipleFileSelected(input) {
            if (input.files && input.files.length > 0) {
                // Store the array of File objects
                selectedFileObjects = Array.from(input.files);

                // Update the visible preview bar
                $('fileNameDisplay').innerText = selectedFileObjects.map(f => f.name).join(', ');
                $('filePreviewContainer').style.display = 'flex';
            } else {
                $('filePreviewContainer').style.display = 'none';
            }
        }
        
        function clearAttachedFile() {
            selectedFileObjects = [];
            $('chatFileInput').value = '';
            $('filePreviewContainer').style.display = 'none';
        }

        // Keep track of active XHR requests per chat to allow cancellation
        var activeXhrRequests = {};
        
        function cancelGeneration(chatId) {
            if (activeXhrRequests[chatId]) {
                activeXhrRequests[chatId].abort();
                delete activeXhrRequests[chatId];
            }
            if (activePollers[chatId]) {
                clearTimeout(activePollers[chatId].timer);
                delete activePollers[chatId];
            }
            removeLoading();
            appendMessage('system-error', 'Generation cancelled by user.', [], false, true);
            
            // Notify backend to clear any hanging generating state
            sendAjax('cancel_chat_state', { chat_id: chatId });
        }

        function triggerImagineMode() {
            var input = $('user-input');
            if (!input.value.startsWith('/imagine ')) {
                input.value = '/imagine ' + input.value;
            }
            input.focus();
        }

        var pollActive=false;
        function pollImageProgress(chatId) {
            //console.log("poll pull"+Date.now());
            if (activePollers[chatId] && activePollers[chatId]['timer']) {
                clearTimeout(activePollers[chatId]['timer']);
            }
        
            var pollFn = function() {
                sendAjax('image_progress', { chat_id: chatId }, function(res) {
                    try {
                        //var res = JSON.parse(xhr.responseText);
                        var pct = Math.round(res.progress * 100);
        
                        if (!activePollers[chatId]) return;
                        if (pct < activePollers[chatId]['lpct'] && activePollers[chatId]['lpct'] > 50) {
                            pct = 100;
                        }
                        activePollers[chatId]['lpct'] = pct;
        
                        // Force live update if we are looking at this exact chat
                        if (currentChatId === chatId) {
                            requestAnimationFrame(function() {
                                //console.log("poll inner"+Date.now());
                                var loader = $('loading-bubble');
                                if (loader && pct<100) {
                                    var progressText = pct > 1 ? ('Generating... ' + pct + '%') : 'Rendering image...';
                                    if(indexQueue>-1) progressText = "Queued position: #"+indexQueue;
                                    var liveImgHtml = '';
                                    let sTB=false;
                                    var skip=true;
                                    if(activePollers.hasOwnProperty(chatId)) {
                                        activePollers[chatId]['dt']=Date.now()-activePollers[chatId]['lt'];
                                        if(activePollers[chatId]['dt']>=1000) {
                                            skip=false;
                                            activePollers[chatId]['lt']=Date.now();
                                        }
                                        if(!res.current_image && activePollers[chatId]['prev']) {
                                            skip=true;
                                        }
                                        if(!skip) {
                                            if (res.current_image && indexQueue==-1) {
                                                activePollers[chatId]['img']=new Image();
                                                activePollers[chatId]['img'].chatId=chatId;
                                                activePollers[chatId]['img'].onload=function() {
                                                    let chatId=this.chatId;
                                                    if(!activePollers[chatId]['prev']) {
                                                        sTB=true;
                                                        activePollers[chatId]['prev']=true;
                                                    }
                                                    liveImgHtml = '<img src="' + activePollers[chatId]['img'].src + '" onclick="openLightbox(this.src,0,false)" class="prev">';
                                                    
                                                    loader.innerHTML = '<strong>Imagine:</strong><br><div class="typing-dots">' + progressText + '</div>' +
                                                        liveImgHtml;// + // cancel not been updated since queue system
                                        
                                                        //'<button onclick="cancelGeneration(\'' + chatId + '\')" style="margin-top:6px; font-size:8pt; background:#311; border-color:#833; padding:2px 6px;">Cancel</button>';

                                                    var chatBox = $('chat-box');
                                                    if (sTB && chatBox) scrollToBottom(chatBox,true);
                                                }
                                                activePollers[chatId]['img'].src="data:image/png;base64,"+res.current_image;
                                            } else if(!activePollers[chatId]['init']) {
                                                sTB=true;
                                                activePollers[chatId]['init']=true;
                                            }

                                            if(!res.current_image || indexQueue>-1) {
                                                loader.innerHTML = '<strong>Imagine:</strong><br><div class="typing-dots">' + progressText + '</div>' +
                                                    liveImgHtml;// + // cancel not been updated since queue system
                                            
                                                    //'<button onclick="cancelGeneration(\'' + chatId + '\')" style="margin-top:6px; font-size:8pt; background:#311; border-color:#833; padding:2px 6px;">Cancel</button>';

                                                var chatBox = $('chat-box');
                                                if (sTB && chatBox) scrollToBottom(chatBox);
                                            }
                                        }
                                    }
                                }
                            });
                        }

                       // Completion check based on actual Forge progress values
                        if (pct >= 100 || res.progress >= 0.99 || (res.state && (res.state.interrupted || res.state.skipped)) || (pct >= 50 && !primaryActive)) {
                            if (activePollers[chatId] && activePollers[chatId]['timer']) {
                                clearTimeout(activePollers[chatId]['timer']);
                            }
                            delete activePollers[chatId];
                        } else {
                            activePollers[chatId]['timer'] = setTimeout(pollFn, 600); // Poll every 600ms for smooth live updates
                        }
                    } catch(e) {
                        activePollers[chatId]['timer'] = setTimeout(pollFn, 1000);
                    }
                });
            };

            if (!activePollers[chatId]) {
                activePollers[chatId] = { lpct: 0, timer: null, prev: false, init: false, dt: 0, lt: 0, img: null };
                pollActive=false;
            }
            activePollers[chatId]['timer'] = setTimeout(pollFn, 200);
        }

        var cachedEmojiData = [];

        function initEmojiPicker() {
            var grid = $('emoji-grid');
            if (cachedEmojiData.length > 0) {
                renderEmojiGrid(cachedEmojiData);
                return;
            }
        
            fetch('./emoji.json')
                .then(response => response.json())
                .then(data => {
                    cachedEmojiData = data;
                    renderEmojiGrid(cachedEmojiData);
                })
                .catch(err => {
                    console.error("Failed to load local ./emoji.json", err);
                });
        }
        
        function renderEmojiGrid(items) {
            var grid = $('emoji-grid');
            grid.innerHTML = '';
            items.forEach(item => {
                var span = document.createElement('span');
                span.className = 'emoji-cell';
                var charStr = item.char || item.emoji || '';
                span.innerText = charStr;
                span.title = item.name || '';
                span.onclick = function() {
                    insertEmoji(charStr);
                    $('emoji-modal').classList.remove('open');
                };
                grid.appendChild(span);
            });
        }
        
        function filterEmojis(query) {
            var q = query.toLowerCase().trim();
            if (!q) {
                renderEmojiGrid(cachedEmojiData);
                return;
            }
            var filtered = cachedEmojiData.filter(item => {
                var name = (item.name || '').toLowerCase();
                var cat = (item.category || '').toLowerCase();
                var group = (item.group || '').toLowerCase();
                var sub = (item.subgroup || '').toLowerCase();
                var codes = (item.codes || '').toLowerCase();
                return name.includes(q) || cat.includes(q) || group.includes(q) || sub.includes(q) || codes.includes(q);
            });
            renderEmojiGrid(filtered);
        }

        function changeLightboxPlayTime(x) {
            saveLS(x);

            //$('lightbox-play-wrap').style.transition="opacity "+x.value+"s ease";

            lbT=x.value;
            lbTC=lbT;
        }

        var lightboxPlayOn=false;
        var lbT=5; // slideshow timer (seconds)
        var lbTC=0;
        function toggleLightboxPlay() {
            lightboxPlayOn=!lightboxPlayOn;
            lbT=$('select-play-time').value;
            lbTC=lbT;

            //var iconstop="⏹";
            var iconstop="■";

            if(lightboxPlayOn) {
                $('lightbox-play-btn').innerHTML=iconstop;
                $('lightbox-nav').style.display="none";

                $('lightbox-play-wrap').classList.add('fade');
                $('image-lightbox').getElementsByClassName('lightbox-actions')[0].classList.add('fade');
            } else {
                stopLightboxPlay();
            }
        }

        function stopLightboxPlay() {
            lightboxPlayOn=false;

            var iconplay="▶";
            
            $('lightbox-play-btn').innerHTML=iconplay;
            $('lightbox-nav').style.display="";
            
            $('lightbox-play-wrap').classList.remove('fade');
            $('image-lightbox').getElementsByClassName('lightbox-actions')[0].classList.remove('fade');
        }

        var lastnI=-1;
        function lightboxPlayRandom() {
            lbT=$('select-play-time').value;
            // either use nav next/prev or pick random by default?
            var elms=[];
            if(mediaOn) {
                elms=$('media-box').getElementsByClassName('thumb');
            } else {
                elms=$('chat-box').getElementsByClassName('generated-art');
            }

            let nI=rndMinMax(0,elms.length-1);
            while(nI==lastnI && elms.length>1) {
                nI=rndMinMax(0,elms.length-1);
            }
            lastnI=nI;
            
            let srcN=elms[nI].getAttribute('data-src');
            let timeN=0;
            let p=null;
            if(mediaOn) {
                p=elms[nI].parentNode;
                timeN=elms[nI].getAttribute('data-time');
            } else { // message
                p=elms[nI].parentNode;
                timeN=p.getAttribute('data-time');
            }

            if(timeN!=0) {
                openLightbox(srcN,timeN,true);
                if(p) {
                    p.scrollIntoView();
                }
            }
        }

        function lightboxNav(d="next") {
            // find next in relevant list
            var elms=[];
            var dN=0;
            if(mediaOn) {
                elms=$('media-box').getElementsByClassName('thumb');
                dN=(d=='next')?1:-1
            } else {
                elms=$('chat-box').getElementsByClassName('generated-art');
                dN=(d=='next')?1:-1
            }
            for(let i=0;i<elms.length;i++) {
                let time=0;
                if(mediaOn) {
                    time=elms[i].getAttribute('data-time');
                } else {
                    time=elms[i].parentNode.getAttribute('data-time');
                }

                if(time==currentLightboxTime && time!=0) {
                    if((i+dN)>=-1 && (i+dN)<elms.length) {
                        if((i+dN)==-1) i=elms.length;
                        let srcN=elms[i+dN].getAttribute('data-src');
                        let timeN=0;
                        let p=null;
                        if(mediaOn) {
                            p=elms[i+dN].parentNode;
                            timeN=elms[i+dN].getAttribute('data-time');
                        } else { // message
                            p=elms[i+dN].parentNode;
                            timeN=p.getAttribute('data-time');
                        }

                        if(timeN!=0) {
                            openLightbox(srcN,timeN,true);
                            if(p) {
                                p.scrollIntoView();
                            }
                        }
                        //console.log('lightbox i = '+i+' ('+d+') [i+'+dN+'], timeN = '+timeN+', srcN = '+srcN);
                        break; // first found
                    } else {
                        //console.log('out of range i = '+i+' ('+d+') [i+'+dN+']');
                        let nI=i+dN;
                        if(nI<0) {
                            nI=elms.length-1;
                        } else {
                            nI=0;
                        }

                        let srcN=elms[nI].getAttribute('data-src');
                        let timeN=0;
                        let p=null;
                        if(mediaOn) {
                            p=elms[nI].parentNode;
                            timeN=elms[nI].getAttribute('data-time');
                        } else { // message
                            p=elms[nI].parentNode;
                            timeN=p.getAttribute('data-time');
                        }

                        if(timeN!=0) {
                            openLightbox(srcN,timeN,true);
                            if(p) {
                                p.scrollIntoView();
                            }
                        }
                    }
                }
            }
        }

        var currentLightboxSrc = '';
        var currentLightboxTime = 0;

        function openLightbox(imgSrc,t=0,eb=true) {
            currentLightboxSrc = imgSrc;
            currentLightboxTime = t;
            var lbImg = $('lightbox-img');
            lbImg.src = imgSrc;
            lbImg.setAttribute('data-src',imgSrc);
            lbImg.setAttribute('data-time',t);
            
            if(eb) {
                $('image-lightbox').getElementsByClassName('lightbox-actions')[0].style.display="";
                if(!lightboxPlayOn) {
                    $('lightbox-nav').style.display="";
                }
                $('lightbox-play-wrap').style.display="";
            } else {
                $('image-lightbox').getElementsByClassName('lightbox-actions')[0].style.display="none";
                $('lightbox-nav').style.display="none";
                $('lightbox-play-wrap').style.display="none";
            }
            
            // Create an invisible image object to read native natural width/height
            var tempImg = new Image();
            tempImg.onload = function() {
                scaleLightboxImage(tempImg.naturalWidth, tempImg.naturalHeight);
                $('image-lightbox').classList.add('open');
            };
            tempImg.src = imgSrc;
        }
        
        function scaleLightboxImage(natWidth, natHeight) {
            var lbImg = $('lightbox-img');
            
            // Get available window viewport dimensions with a 60px total margin buffer
            var SCR_W = window.innerWidth - 60;
            var SCR_H = window.innerHeight - 60;
            
            var imgAspect = natWidth / natHeight;
            var scrAspect = SCR_W / SCR_H;
            
            var finalW, finalH;
            
            if (imgAspect > scrAspect) {
                // Image is wider relative to screen
                finalW = SCR_W;
                finalH = SCR_W / imgAspect;
            } else {
                // Image is taller relative to screen
                finalH = SCR_H;
                finalW = SCR_H * imgAspect;
            }
            
            // Apply calculated dimensions to force scaling up or down to fit viewport
            lbImg.style.width = finalW + 'px';
            lbImg.style.height = finalH + 'px';
        }
        
        // Window resize handler with debounce timeout check
        var resizeTimer;
        window.addEventListener('resize', function() {
            if (!$('image-lightbox').classList.contains('open')) return;
            clearTimeout(resizeTimer);
            resizeTimer = setTimeout(function() {
                if (currentLightboxSrc) {
                    var tempImg = new Image();
                    tempImg.onload = function() {
                        scaleLightboxImage(tempImg.naturalWidth, tempImg.naturalHeight);
                    };
                    tempImg.src = currentLightboxSrc;
                }
            }, 100);
        });
        
        function closeLightbox(e) {
            if (e.target.id === 'image-lightbox') {
                $('image-lightbox').classList.remove('open');
                currentLightboxSrc = '';

                if(lightboxPlayOn) {
                    stopLightboxPlay();
                }
            }
        }
        
        function openInNewTab(e) {
            e.stopPropagation();
            window.open($('lightbox-img').src, '_blank');

            if(lightboxPlayOn) {
                stopLightboxPlay();
            }
        }

        // Clear search input and reset filter when closing modal
        function closeEmojiModal() {
            $('emoji-modal').classList.remove('open');
            var searchInput = $('emoji-search');
            if (searchInput) {
                searchInput.value = '';
                renderEmojiGrid(cachedEmojiData); // Reset grid back to full set
            }
        }

        function enhancePrompt() {
            if(totalQueue>0) {
                alert("Heavy load: enhance is currently not available!");
                return;
            }
            var input = $('user-input');
            var rawPrompt = input.value.trim();
            if (!rawPrompt) {
                rawPrompt = "a cinematic masterpiece landscape scene"; // Fallback if empty
            }
        
            // Strip out /imagine prefix temporarily if present so the LLM focuses purely on descriptive tags
            var cleanPrompt = rawPrompt.replace(/^\/imagine\s*/i, '');
            input.value = "Enhancing prompt...";
        
            var textModel = $('text-model-select') ? $('text-model-select').value : '<?php echo $text_model; ?>';

            // Construct request to local Ollama instance
            var payload = {
                model: textModel,
                prompt: "Rewrite the following short idea into a rich, highly detailed Stable Diffusion prompt with descriptive visual tokens, lighting details, and art style tags. Output ONLY the final prompt text without conversational filler: " + cleanPrompt,
                stream: false
            };

            sendAjax('enhance_prompt', payload, function(res) {
                try {
                    var enhancedTextFull = res.response ? res.response.trim() : cleanPrompt;
                    // Restore /imagine prefix if it was there
                    var enhancedText=enhancedTextFull.substr(enhancedTextFull.lastIndexOf('<channel|>')+10);
                    input.value = '/imagine ' + enhancedText;
                } catch(e) {
                    input.value = '/imagine ' + cleanPrompt;
                }
                input.focus();
            });
        }

        function closeQueuePage() {
            queuePageOn=false
                
            $('queue-box').style.display="none";
            if(mediaOn) {
                $('media-box').style.display="flex";
            } else {
                $('chat-box').style.display="flex";
            }
        }

        var queuePageOn=false;
        function showQueue() {
            queuePageOn=!queuePageOn;
            updateQueuePage();
            kATC=0;
            if(queuePageOn) {
                $('chat-box').style.display="none";
                $('media-box').style.display="none";
                $('queue-box').style.display="flex";
            } else {
                closeQueuePage();
            }
        }

        function updateQueuePage() {
            if(queueCopy.length==0) {
                $('queue-list').innerHTML="No jobs in queue.";
                return;
            } else {
                $('queue-list').innerHTML="";
            }
            for(let i=0;i<queueCopy.length;i++) {
                var elm=document.createElement('div');
                elm.id="queue-"+queueCopy[i]['job_id'];
                elm.setAttribute('data-id',queueCopy[i]['job_id']);
                //var qtime=document.createTextNode(queueCopy[i]['time'] + " | ");
                var jobid=document.createTextNode(queueCopy[i]['job_id'] + " | ");
                var chatid=document.createTextNode(queueCopy[i]['chat_id'] + " | ");
                var qtype=document.createTextNode(queueCopy[i]['type'] + " | ");
                var qstatus=document.createTextNode(queueCopy[i]['status'] + " ");
                var qbtn=document.createElement('button');
                var qbtndel=document.createElement('button');

                //elm.appendChild(qtime);
                elm.appendChild(jobid);
                elm.appendChild(chatid);
                elm.appendChild(qtype);
                elm.appendChild(qstatus);

                qbtndel.appendChild(document.createTextNode("Del"));
                qbtndel.style.background="#502";
                qbtndel.style.borderColor="#834";
                if(queueCopy[i]['status']=="error") {
                    qbtn.appendChild(document.createTextNode("Unjam / retry"));
                    elm.style.color="#F00";
                    elm.appendChild(qbtn);
                    elm.appendChild(qbtndel);
                } else if(queueCopy[i]['status']!="processing") {
                    elm.appendChild(qbtndel);
                } else {
                    elm.style.color="#4a90e2"; // active
                }
                qbtn.onclick=function() {
                    var jobid=this.parentNode.getAttribute('data-id');
                    // swap status back to pending
                    //
                    console.log('sending queue_unstuck { job_id: "'+jobid+'" }');
                    sendAjax('queue_unstuck', { job_id: jobid }, function(res) {
                        console.log('queue_unstuck res.status = "'+res.status+'"');
                        kATC=0;
                    });
                    //
                    // remove buttons
                    var btn=$('queue-'+jobid).getElementsByTagName("button");
                    for(let i=0;i<btn.length;i++) {
                        btn[i].parentNode.removeChild(btn[i]);
                        i--;
                    }
                };
                qbtndel.onclick=function() {
                    var jobid=this.parentNode.getAttribute('data-id');
                    // delete queue not started yet
                    //
                    sendAjax('queue_delete', { job_id: jobid }, function(res) {
                        kATC=0;
                    });
                    //
                    // remove buttons
                    var btn=$('queue-'+jobid).getElementsByTagName("button");
                    for(let i=0;i<btn.length;i++) {
                        btn.parentNode.removeChild(btn);
                        i--;
                    }
                };

                $('queue-list').appendChild(elm);
            }
        }

        function saveLS(elm) {
            if(!enableLS) return;

            var state="";
            switch(elm.id) {
                case "sd-multiplier-2x":
                    state=elm.checked?1:0;
                    break;
                case "sd-steps":
                    state=elm.value;
                    break;
                case "sd-resolution":
                    state=elm.value;
                    break;
                case "select-play-time":
                    state=elm.value
                    break;
            }

            localStorage.setItem(elm.id, state);
        }

        function loadLS() {
            if(!enableLS) return;

            var list=[
                ["sd-multiplier-2x","chk"],
                ["sd-steps","val"],
                ["sd-resolution","val"],
                ["select-play-time","val"]
            ];

            var state="";
            for(let i=0;i<list.length;i++) {
                if(localStorage.getItem(list[i][0])) {
                    state=localStorage.getItem(list[i][0]);

                    switch(list[i][1]) {
                        case "chk":
                            if(state==1) $(list[i][0]).checked=true;
                            else $(list[i][0]).checked=false;
                            break;
                        case "val":
                            $(list[i][0]).value=state;
                            break;
                    }
                }
            }
        }
        
        // Close modal when clicking outside
        window.onclick = function(event) {
            var modal = $('emoji-modal');
            if (!modal.contains(event.target) && event.target.id !== 'toggle-emoji-picker') {
                closeEmojiModal();
            }
        };

        window.onload = function() {
            currentChatId = 'chat-' + Math.floor(Date.now() / 1000);
            keepAlive();
            initChatScrollListener();
            initMediaScrollListener();
            
            $('toggle-sidebar').onclick = toggleSidebar;
            $('btn-tab-chats').onclick = function() { switchTab('chats'); };
            $('btn-tab-settings').onclick = function() { switchTab('settings'); };$('new-chat-btn').onclick = newChat;
            $('delete-chat-btn').onclick = deleteCurrentChat;
            $('media-chat-btn').onclick = toggleChatMedia;
            $('send-btn').onclick = submitQuery;
            //$('update-model-btn').onclick = updateSdModel; // using override json instead
            $('chat-title-input').onchange = updateChatTitle;
            $('insert-lora-btn').onclick = insertLoraModel;
            
            loadLoraModels();
            
            $('user-input').onkeydown = function(e) {
                if (e.keyCode === 13 && !e.shiftKey) {
                    e.preventDefault();
                    submitQuery();
                }
            };

            $('toggle-emoji-picker').onclick = function(e) {
                e.stopPropagation();
                var modal = $('emoji-modal');
                //var btn = $('toggle-emoji-picker');
                var btn2 = $('imagine-button');
                
                if (!modal.classList.contains('open')) {
                    var rect = btn2.getBoundingClientRect();
                    // Position modal left edge aligned with button left, or offset it
                    var nleft=(rect.left + rect.width) - 320;
                    if(nleft<0) nleft=0;

                    modal.style.left = nleft + 'px';
                    modal.style.bottom = (window.innerHeight - rect.top + 8) + 'px';
                    modal.classList.add('open');
                    initEmojiPicker();
                } else {
                    closeEmojiModal();
                }
            };
            
            loadLS();
        };
    </script>
</head>
<body>
    <div class="app-layout">
        <!-- Sidebar -->
        <div id="sidebar">
        <div id="sidebarContain"> <!-- prevent squishing content on toggle sidebar -->
            <div class="sidebar-tabs">
                <button id="btn-tab-chats" class="tab-btn active">Chats</button>
                <button id="btn-tab-settings" class="tab-btn">Settings</button>
            </div>
            
            <!-- Chats Tab Pane -->
            <div id="pane-chats" class="tab-pane active">
                <div class="sidebar-header">
                    <span id="lbHist" style="font-size:9pt; color:#888; cursor: pointer;" onclick="toggleSearch();">HISTORY</span>
                    <button id="new-chat-btn" style="padding: 2px 8px; font-size: 9pt;">+ New</button>
                </div>
                <div id="chat-list" class="chat-list"></div>
                <br />
                <div style="width: 100%; text-align: center; margin-bottom: 40px;"><a href="javascript:showQueue();" target="_self" id="queue-page-link">Queue page</a></div>
            </div>
            
            <!-- Settings Tab Pane -->
            <div id="pane-settings" class="tab-pane">
                <div class="setting-group">
                    <label>Text Model (Ollama):</label>
                    <select id="text-model-select">
                    <option value="<?php echo $text_model; ?>"><?php echo $text_model; ?></option>
                        <!--<option value="qwen3">Qwen 2.5 (7B Instruct)</option>
                        <option value="twil-8b">TwIL-8B Reason Model</option>
                        <option value="liquid-1.7b">Liquid-1.7B Local Agent</option>-->
                    </select>
                    <label>Vision Model (Ollama):</label>
                    <select id="vision-model-select">
                        <option value="<?php echo $vision_model; ?>"><?php echo $vision_model; ?></option>
                        <!--<option value="llama3.2-vision">llama3.2-vision</option>-->
                    </select>
                </div>
                <!-- sd models auto populate -->
                <div class="setting-group" style="margin-top: 24px;">
                    <label>Active SD Checkpoint:</label>
                    <select id="sd-model-select"></select>
                    <!--<button id="update-model-btn" style="margin-top: 5px; font-size: 9pt;">Apply SD Model</button>-->
                    <label>Image Resolution:</label>
                    <select id="sd-resolution" style="width:100%; background:#1e1e24; color:#fff; border:1px solid #444; padding:4px; margin-bottom:6px;" onchange="saveLS(this);">
                        <option value="512x512" selected>512 x 512 (Standard)</option>
                        <option value="768x512">768 x 512 (Landscape)</option>
                        <option value="512x768">512 x 768 (Portrait)</option>
                        <option value="768x768">768 x 768 (Square Large)</option>
                    </select>
                    
                    <!-- 2x Multiplier Toggle -->
                    <label style="font-size: 8.5pt; color: #aaa; display: flex; align-items: center; cursor: pointer; margin-bottom: 8px;">
                        <input type="checkbox" id="sd-multiplier-2x" style="margin-right: 6px;" checked="checked" onchange="saveLS(this);"> 2x Scale Multiplier (Double dimensions)
                    </label>
                
                    <label>Generation Steps:</label>
                    <select id="sd-steps" style="width:100%; background:#1e1e24; color:#fff; border:1px solid #444; padding:4px;" onchange="saveLS(this);">
                        <option value="10" selected>10 Steps (Fast)</option>
                        <option value="15">15 Steps</option>
                        <option value="20">20 Steps (Balanced)</option>
                        <option value="25">25 Steps</option>
                        <option value="30">30 Steps (Detailed)</option>
                        <option value="40">40 Steps</option>
                        <option value="50">50 Steps (Overkill)</option>
                    </select>
                </div>
                
                <div class="setting-group" style="margin-top: 15px;">
                    <label>Image Generation Help:</label>
                    <div class="setting-help">Type <code>/imagine [prompt]</code> directly in the chat box to trigger Stable Diffusion image generation.</div>
                </div>
                
                <div class="setting-group" style="margin-bottom: 0px;">
                    <label>Available Loras:</label>
                    <select id="lora-model-select"></select>
                    <button id="insert-lora-btn" style="margin-top: 5px; font-size: 9pt;">Insert Lora Model &gt;</button>
                </div>
				<br />
                <div style="width: 100%; text-align: center; margin-bottom: 40px;"><a href="javascript:showQueue();" target="_self" id="queue-page-link2">Queue page</a></div>
            </div>
        </div> <!-- sidebarContain -->
        </div> <!-- sidebar -->
        
        <!-- Main Pane -->
        <div class="main-pane">
            <div class="top-bar">
                <button id="toggle-sidebar">☰</button>
                <input type="text" id="chat-title-input" value="New Chat" style="width: 250px;" title="Click to rename chat title">
                <button id="media-chat-btn">⊞</button>
                <span id="stat-media-count" style="color: #606163; font-size: 10pt;"></span>
                <button id="delete-chat-btn" style="background: #502; border-color: #834; margin-left: auto;">Delete</button>
            </div>
            
            <div id="chat-box" class="chat-box">
                <div class="message ai">
                    <strong>SYSTEM:</strong><br>Terminal initialized. Ready.
                </div>
            </div>
            <div id="media-box" class="media-box">
                <div class="media image">
                    <img src="" onclick="openLightbox(this.src)" class="thumb">;

                </div>
            </div>
            <div id="queue-box" class="queue-box">
                <div id="queue-list">

                </div>
            </div>
            
            <!-- Vibe & Input Container -->
            <div class="vibe-bar">
                <span style="font-size:8.5pt; color:#666;">VIBE:</span>
                <button class="emoji-btn" onclick="insertEmoji(' x)')"> x)</button>
                <button class="emoji-btn" onclick="insertEmoji(' ✨')"> ✨</button>
                <button class="emoji-btn" onclick="insertEmoji(' 🚀')"> 🚀</button>
                <button class="emoji-btn" onclick="insertEmoji(' 💡')"> 💡</button>
                <button class="emoji-btn" id="toggle-emoji-picker" style="background:#25262c; border-color:#EA75BC;">😊 All</button>
                <button class="emoji-btn" id="imagine-button" onclick="triggerImagineMode()" style="background:#25262c; border-color:#4a90e2;" title="Quick Image Generation Mode">🖼️ Img</button>
                
                <!-- New Prompt Enhancer Button -->
                <button class="emoji-btn" onclick="enhancePrompt()" style="background:#25262c; border-color:#9b59b6;" title="Expand prompt into detailed descriptive tags using local LLM">🪄 Enhance</button>

                <!-- Hidden file input + Styled Label -->
                <input type="file" id="chatFileInput" multiple style="display: none;" onchange="handleMultipleFileSelected(this)">
                <label for="chatFileInput" class="file-upload-lbl" style="margin-left: auto;" title="Upload image or text file" ontouchup="handleMultipleFileSelected($('chatFileInput'))">📂 Upload File (+)</label>
            </div>

            <!-- Dynamic File Preview Bar (Place just above or inside your prompt area) -->
            <div id="filePreviewContainer" style="display: none; padding: 4px 8px; background: #1c1d21; border-top: 1px solid #333; font-size: 8.5pt; color: #61afef; align-items: center; gap: 8px;">
                <span>Attached: <strong id="fileNameDisplay"></strong></span>
                <button onclick="clearAttachedFile()" style="background: none; border: none; color: #e06c75; cursor: pointer; font-weight: bold;" title="Remove file">✕ Remove</button>
            </div>
            
            <!-- Popup Emoji Drawer Modal -->
            <div id="emoji-modal">
                <div class="emoji-modal-header" style="flex-direction: column; gap: 6px; align-items: stretch;">
                    <div style="display: flex; justify-content: space-between; align-items: center;">
                        <span style="font-weight:bold;">Select Emoji</span>
                        <button onclick="closeEmojiModal()" style="background:none; border:none; color:#aaa; cursor:pointer; font-weight:bold; font-size:11pt;">&times;</button>
                    </div>
                    <!-- Search filter input -->
                    <input type="text" id="emoji-search" placeholder="Search emojis (e.g. cat, smile, fire)..." oninput="filterEmojis(this.value)" style="background:#000; color:#fff; border:1px solid #444; padding:4px 8px; font-size:9pt; width:100%;">
                </div>
                <div id="emoji-grid" class="emoji-grid"></div>
            </div>
                <div class="input-area">
                    <textarea id="user-input" placeholder="Type your prompt here... (Shift+Enter for new line)"></textarea>
                    <button id="send-btn">SEND</button>
                </div>
            </div>
        </div>
    </div>

<!-- Lightbox Modal Container -->
<div id="image-lightbox" onclick="closeLightbox(event)">
    <div class="lightbox-actions">
        <button onclick="insertIMG2IMG(this,true)" title="Insert as image2image">IMG2IMG</button>
        <button onclick="downloadImage(this,true)" title="Download image">Download</button>
        <button onclick="openInNewTab(event);" title="Open in new tab">Open Full</button>
        <!--<button onclick="triggerUpscale(currentChatId, this)" title="Upscale 2x with SD">Upscale</button>
        <button onclick="deleteMessage(currentChatId, this)" title="Delete message">Del</button>-->
    </div>

    <div id="lightbox-play-wrap"  class="image-actions2">
        <select id="select-play-time" onchange="changeLightboxPlayTime(this);">
            <option value="2">2</option>
            <option value="2">3</option>
            <option value="4">4</option>
            <option value="5" selected>5</option>
            <option value="6">6</option>
            <option value="6">7</option>
            <option value="8">8</option>
            <option value="10">10</option>
            <option value="15">15</option>
            <option value="30">30</option>
        </select>
        <button id="lightbox-play-btn" class="play" onclick="toggleLightboxPlay();" title="Play slideshow">▶</button>
    </div>

    <div id="lightbox-wrap">
        <div id="lightbox-nav" class="image-actions">
            <div class="tbl">
                <div class="tr" style="height: 100%;">
                    <div class="td" style="width: 50%;">
                        <button id="lightbox-prev-btn" class="prev" onclick="lightboxNav('prev');" style="text-align: left;">&lt;</button>
                    </div>
                    <!--<div class="td" style="width: 34%; height: 100%;">
                        <button class="open" onclick="openInNewTab(event);"></button>
                    </div>-->
                    <div class="td" style="width: 50%;">
                        <button id="lightbox-next-btn" class="next" onclick="lightboxNav('next');" style="text-align: right;">&gt;</button>
                    </div>
                </div>
            </div>
        </div>

        <img id="lightbox-img" src="" onclick="openInNewTab(event)">
    </div>
</div>
</body>
</html>

Top
©twily.info 2013 - 2026
twily at twily dot info



3 946 536 visits
... ^ v