Skip to content

Distributed Peer-to-Peer Web Search Engine and Intranet Search Appliance

103 KB
Raw Blame
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <title>YaCy '#[clientname]#': Chat</title>
    #%env/templates/metas.template%#
    <link rel="stylesheet" href="js/styles/a11y-dark.min.css" type="text/css" />
    <link rel="stylesheet" href="env/markdown.css" type="text/css" />
    <style type="text/css">
      /* 1. Global Container */
      .chat-panel {
        width: 100%;
        color: #333333;
        padding: 0 0 32px 0; 
      }
    
      /* 2. Layout Structure */
      .chat-flow {
        display: flex;
        flex-direction: column;
        gap: 15px;
      }
      
      .chat-messages {
        display: flex;
        flex-direction: column;
        gap: 10px;
      }
    
      /* 3. The Message Blocks - Structural Look */
      .chat-turn {
        position: relative;
        border: 1px solid #e0e0e0;
        border-radius: 0px; 
        padding-top: 2px;
        padding-bottom: 12px;
        padding-left: 20px;
        padding-right: 20px;
        margin: 0;
        box-shadow: 2px 2px 0px rgba(0,0,0,0.1);
        transition: all 0.2s;
      }
      .chat-turn:hover {
        box-shadow: 3px 3px 0px rgba(0,0,0,0.15); 
      }
    
      /* 4. Labels (User/Assistant Headers) - Headline Font Consistency */
      .chat-turn legend {
        font-family: inherit; 
        padding: 4px 10px;
        font-size: 0.95rem;
        font-weight: 700;
        letter-spacing: 0.5px;
        text-transform: uppercase;
        border: 1px solid transparent;
        margin-bottom: 8px; /* Increased spacing */
      }
    
      /* --- USER: Lighter Grey Input --- */
      .chat-turn.user {
        background-color: #ECF1F8;
        border-left-width: 5px;
        border-left-style: solid;
        border-color: #d1d9e6;
        color: #2c3e50;
      }
      
      .chat-turn.user legend {
        background: #5092CF; 
        color: #ffffff;
        border: 1px solid #5092CF;
      }
    
      /* --- ASSISTANT: Darker Grey Output --- */
      .chat-turn.assistant {
        background-color: #DEE7F3;
        border-left-width: 5px;
        border-left-style: solid;
        border-color: #bbccdd;
        color: #000;
      }

      .chat-turn.assistant legend {
        background: #2c3e50; 
        color: #ffffff;
        border: 1px solid #2c3e50;
      }

      /* --- TOOL: Tool Call Output --- */
      .chat-turn.tool {
        background-color: #f0f7e8;
        border-left-width: 5px;
        border-left-style: solid;
        border-color: #b7d7a8;
        color: #24421a;
      }

      .chat-turn.tool legend {
        background: #3d6b2f;
        color: #ffffff;
        border: 1px solid #3d6b2f;
      }
    
      /* --- SYSTEM: Log Entry Style --- */
      .chat-turn.system {
        background: #fff3cd; 
        border: 1px solid #ffeeba;
        border-left: 5px solid #ffc107;
        color: #856404;
        font-family: 'Roboto Mono', 'Menlo', 'Consolas', monospace;
        font-size: 1.2rem;
      }
    
      /* 5. Typography - All Chat Content is MONOSPACE */
      .chat-body {
        line-height: 1.6;
        font-size: 1.2rem; /* Larger font size */
        font-family: 'Roboto Mono', 'Menlo', 'Consolas', monospace;
      }

      .chat-body.plain-text {
        white-space: pre-wrap;
        font-family: 'Roboto Mono', 'Menlo', 'Consolas', monospace;
      }

      /* markdown output styles come from the shared env/markdown.css (.markdown-body);
         only the chat-specific container properties are set here */
      .chat-body.markdown-body {
        max-width: 100%;
        padding: 0;
      }

      .think-block {
        margin: 8px 0;
        border: 1px solid #d6dbe5;
        border-radius: 8px;
        background: #f5f7fb;
        padding: 6px 10px;
      }

      .think-block summary {
        cursor: pointer;
        font-weight: 700;
        list-style: none;
      }

      .think-block summary::-webkit-details-marker {
        display: none;
      }

      .think-block[open] summary {
        margin-bottom: 6px;
      }

      .think-content {
        color: #394b59;
        font-size: 0.85rem;
      }

      .toolcalls-popover {
        position: absolute;
        z-index: 20;
        top: 24px;
        right: 8px;
        min-width: 280px;
        max-width: min(560px, calc(100vw - 40px));
        max-height: 380px;
        overflow: auto;
        border: 1px solid #c3cbd9;
        border-radius: 6px;
        background: #eef2f7;
        box-shadow: 3px 3px 0px rgba(0,0,0,0.15);
        padding: 8px 10px;
      }

      .toolcalls-popover-header {
        font-weight: 700;
        margin-bottom: 6px;
      }

      .toolcalls-list {
        margin-top: 6px;
        display: flex;
        flex-direction: column;
        gap: 6px;
      }

      .toolcall-item {
        border: 1px solid #d6dbe5;
        border-radius: 4px;
        background: #f5f7fb;
        padding: 6px 8px;
      }

      .toolcall-name {
        font-weight: 700;
        margin-bottom: 4px;
      }

      .toolcall-args {
        margin: 0;
        white-space: pre-wrap;
        word-break: break-word;
        font-size: 0.95rem;
        line-height: 1.4;
      }

      .toolcall-result-title {
        margin-top: 6px;
        margin-bottom: 4px;
        font-weight: 700;
      }

      .toolcall-result {
        margin: 0;
        white-space: pre-wrap;
        word-break: break-word;
        font-size: 0.95rem;
        line-height: 1.4;
      }

      /* 6. Composer Row (inside User fieldset) */
      .composer {
        display: flex;
        gap: 10px;
        align-items: stretch;
      }

      .chat-turn.user:focus-within {
        background-color: #ECF1F8;
        border-left-width: 5px;
        border-left-style: solid;
        border-color: #d1d9e6;
        color: #2c3e50;
      }

      .search-default-control {
        display: flex;
        align-items: center;
        flex-wrap: wrap;
        gap: 8px;
        margin: 1px 0 2px 0;
      }

      .search-default-options {
        --segments: 2;
        --active: 0;
        position: relative;
        display: flex;
        align-items: center;
        gap: 0px;
        padding: 0px;
        border: 1px solid #c3cbd9;
        border-radius: 999px;
        background: #eef2f7;
        overflow: hidden;
        width: 500px;
        max-width: 100%;
        height: 22px;
      }

      .search-default-options input {
        position: absolute;
        opacity: 0;
        pointer-events: none;
      }

      .search-default-options label {
        flex: 1;
        padding: 0;
        text-align: center;
        font-size: 1.1rem;
        font-weight: 500;
        line-height: 1.1;
        color: #2c3e50;
        cursor: pointer;
        position: relative;
        z-index: 1;
        display: flex;
        align-items: center;
        justify-content: center;
        height: 100%;
        box-sizing: border-box;
        transform: translateY(2px);
      }

      .search-default-options input:checked + label {
        color: #ffffff;
      }

      .search-default-options .search-default-slider {
        position: absolute;
        top: 1px;
        bottom: 1px;
        left: 1px;
        width: calc((100% - 2px) / var(--segments, 2));
        background: #5092CF;
        border-radius: 999px;
        transform: translateX(calc(var(--active, 0) * 100%));
        transition: transform 0.2s;
        z-index: 0;
      }

      .search-default-options .is-future {
        display: none;
      }

      .search-default-options .global-option,
      .search-default-options .global-label {
        display: none;
      }

      .search-default-options.has-global .global-option,
      .search-default-options.has-global .global-label {
        display: flex;
      }

      .composer-main {
        flex: 1;
        display: flex;
        flex-direction: column;
        gap: 8px;
      }

      .composer textarea {
        flex: 0 0 auto;
        resize: none;
        border: none;
        background: transparent;
        padding: 0;
        margin: 0;
        outline: none;
        overflow-y: hidden;
      }

      .attachment-row {
        display: flex;
        align-items: center;
        gap: 10px;
        font-size: 0.95rem;
        color: #2c3e50;
        position: relative;
      }

      .attachment-row.loading .attachment-filename {
        font-style: italic;
        color: #6b7a90;
      }
      .attachment-button,
      .search-button,
      .copy-button,
      .user-trim-button,
      .toolcalls-button {
        width: 24px;
        height: 24px;
        border: none;
        border-radius: 4px;
        background: #d1d9e6;
        color: #2c3e50;
        font-weight: 800;
        font-size: 1.25rem;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        transition: background 0.15s, border-color 0.15s;
      }

      .attachment-button:hover,
      .search-button:hover,
      .copy-button:hover,
      .user-trim-button:hover,
      .toolcalls-button:hover {
        background: #c3cbd9;
      }
      .toolcalls-button.pending {
        cursor: default;
        opacity: 0.75;
        animation: toolcall-pulse 1s ease-in-out infinite;
      }
      .toolcalls-button.pending:hover {
        background: #d1d9e6;
      }
      @keyframes toolcall-pulse {
        0%, 100% { opacity: 0.45; }
        50% { opacity: 1; }
      }
      .button-active {
        background: #337ab7;
        color: #fff;
      }
      .button-active:hover {
        background: #2b669a;
      }

      .attachment-filename {
        font-family: 'Roboto Mono', 'Menlo', 'Consolas', monospace;
        font-size: 0.95rem;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }

      .search-hint {
        font-family: 'Roboto Mono', 'Menlo', 'Consolas', monospace;
        font-size: 0.95rem;
        white-space: nowrap;
        color: #2c3e50;
      }

      .copy-button,
      .user-trim-button {
        position: absolute;
        top: -6px;
        right: 8px;
      }

      .toolcalls-button {
        position: static;
      }

      .toolcall-toolbar {
        position: absolute;
        top: -6px;
        right: 36px;
        display: inline-flex;
        flex-direction: row;
        gap: 4px;
        align-items: center;
      }

      .user-delete-button {
        position: absolute;
        top: -6px;
        right: 36px;
        width: 24px;
        height: 24px;
        border: none;
        border-radius: 4px;
        background: #d1d9e6;
        color: #2c3e50;
        font-weight: 800;
        font-size: 1.1rem;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        transition: background 0.15s, border-color 0.15s, color 0.15s;
      }

      .user-delete-button:hover {
        background: #c3cbd9;
      }

      .hidden-file-input {
        position: absolute;
        left: -9999px;
        width: 1px;
        height: 1px;
        opacity: 0;
        pointer-events: none;
      }

      .attachment-chip {
        position: relative;
        display: inline-flex;
        align-items: center;
        gap: 6px;
        margin-top: 8px;
        padding: 6px 10px;
        background: #d1d9e6;
        color: #2c3e50;
        border-radius: 4px;
        border: 1px solid #c3cbd9;
        font-family: 'Roboto Mono', 'Menlo', 'Consolas', monospace;
        cursor: pointer;
        transition: background 0.15s, border-color 0.15s;
      }

      .attachment-chip:hover,
      .attachment-chip:focus {
        background: #c3cbd9;
        outline: none;
      }

      .attachment-chip .glyphicon {
        font-size: 1.05rem;
      }

      .attachment-chip .attachment-label {
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        max-width: 260px;
      }

      .attachment-preview {
        position: absolute;
        z-index: 30;
        min-width: 280px;
        max-width: 420px;
        background: #ffffff;
        color: #2c3e50;
        border: 1px solid #c3cbd9;
        box-shadow: 3px 3px 0px rgba(0,0,0,0.15);
        border-radius: 6px;
        padding: 10px 12px;
        top: calc(100% + 6px);
        left: 0;
      }

      .attachment-preview.above {
        top: auto;
        bottom: calc(100% + 6px);
      }

      .attachment-preview h5 {
        margin: 0 0 6px 0;
        font-size: 1rem;
        font-weight: 700;
      }

      .attachment-preview .meta {
        font-size: 0.9rem;
        margin-bottom: 8px;
        color: #40536a;
      }

      .attachment-preview .preview-body {
        max-height: 240px;
        overflow: auto;
        background: #f5f7fb;
        border: 1px solid #e0e6f0;
        padding: 8px;
        border-radius: 4px;
        font-family: 'Roboto Mono', 'Menlo', 'Consolas', monospace;
        font-size: 1rem;
        white-space: pre-wrap;
      }

      .attachment-preview .preview-image {
        max-width: 100%;
        max-height: 220px;
        display: block;
        margin: 0 auto;
        border: 1px solid #e0e6f0;
        border-radius: 4px;
        background: #fff;
      }

      .attachment-preview .actions {
        display: flex;
        gap: 6px;
        margin-top: 8px;
        flex-wrap: wrap;
      }

      .attachment-preview .preview-action {
        display: inline-flex;
        align-items: center;
        gap: 4px;
        padding: 4px 8px;
        border: 1px solid #c3cbd9;
        background: #d1d9e6;
        color: #2c3e50;
        border-radius: 4px;
        cursor: pointer;
        font-size: 0.9rem;
        transition: background 0.15s, border-color 0.15s;
      }

      .attachment-preview .preview-action:hover {
        background: #c3cbd9;
      }

      .attachment-preview .preview-note {
        margin-top: 6px;
        font-size: 0.85rem;
        color: #6b7a90;
      }

      .attachment-modal-backdrop {
        position: fixed;
        inset: 0;
        background: rgba(0,0,0,0.65);
        z-index: 50;
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 20px;
      }

      .attachment-modal {
        background: #ffffff;
        color: #2c3e50;
        max-width: 800px;
        width: 100%;
        max-height: 90vh;
        border-radius: 8px;
        box-shadow: 4px 4px 0px rgba(0,0,0,0.2);
        padding: 16px;
        overflow: hidden;
        position: relative;
      }

      .attachment-modal .modal-header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 10px;
      }

      .attachment-modal .modal-header h4 {
        margin: 0;
        font-size: 1.1rem;
      }

      .attachment-modal .modal-body {
        max-height: 70vh;
        overflow: auto;
        border: 1px solid #e0e6f0;
        border-radius: 4px;
        padding: 10px;
        background: #f5f7fb;
      }

      .attachment-modal .modal-body pre {
        margin: 0;
        white-space: pre-wrap;
        word-break: break-word;
      }

      .attachment-modal .close-modal {
        border: none;
        background: #d1d9e6;
        color: #2c3e50;
        border-radius: 4px;
        width: 28px;
        height: 28px;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
      }
    
      /* 7. The Button - Industrial Action */
      .composer .btn {
        align-self: stretch; 
        padding: 0 24px;
        border: 2px solid #555; 
        background: #333; 
        color: #fff;
        font-family: 'Roboto Mono', 'Menlo', 'Consolas', monospace;
        font-weight: bold;
        text-transform: uppercase;
        cursor: pointer;
        transition: all 0.2s;
        display: flex;
        align-items: center;
      }
    
      .composer .btn:hover {
        background: #0056b3;
        border-color: #0056b3;
      }
      
      .composer .btn:active {
        background: #004494;
      }
    
      @media (max-width: 900px) {
        .composer {
          flex-direction: column;
        }
        .composer .btn {
          width: 100%;
          border: 2px solid #555;
        }
      }

      .clear-chat-row {
        display: flex;
        visibility: hidden;
        pointer-events: none;
        margin-top: 12px;
        gap: 10px;
        align-items: center;
      }

      .clear-chat-row .btn {
        display: inline-flex;
        align-items: center;
        gap: 6px;
      }
    </style>
  </head>
  <body id="IndexControl">
	#(topmenu)#
      #%env/templates/embeddedheader.template%#
    ::
      #%env/templates/simpleheader.template%#
	::
      #%env/templates/header.template%#
	  #%env/templates/submenuAI.template%#
    #(/topmenu)#

    #(topmenu)#
      <script>document.getElementById("greeting-icon").src="env/grafics/invisible.png"</script>
      <h2 class="yacy"><a href="#[promoteSearchPageGreeting.homepage]#" class="yacylogo"><img src="#[promoteSearchPageGreeting.largeImage]#" alt="#[promoteSearchPageGreeting.imageAlt]#" style="margin: auto;"/></a></h2>
      <h2 class="yacy">#[promoteChatPageGreeting]#</h2>
    ::
      <script>document.getElementById("greeting-icon").src="env/grafics/invisible.png"</script>
      <h2 class="yacy"><a href="#[promoteSearchPageGreeting.homepage]#" class="yacylogo"><img src="#[promoteSearchPageGreeting.largeImage]#" alt="#[promoteSearchPageGreeting.imageAlt]#" style="margin: auto;"/></a></h2>
      <h2 class="yacy">#[promoteChatPageGreeting]#</h2>
    ::
    #(/topmenu)#

    <h2>YaCy Chat</h2>
    <p>This Chat is private. YaCy does not keep any history — only your browser remembers the current conversation.</p>

      <div class="chat-panel">
        <div class="chat-flow">
          <div class="search-default-control">
            <span>Default Dialog Augmentation:</span>
<div class="search-default-options" id="searchDefaultOptions" role="radiogroup" aria-label="Attach search results by default">
               <input type="radio" id="searchDefaultNone" name="searchDefault" value="no"/>
               <label for="searchDefaultNone">no search, allow attachments</label>
               <input type="radio" id="searchDefaultLocal" name="searchDefault" value="local" checked="checked"/>
               <label for="searchDefaultLocal">use local search</label>
               <input type="radio" id="searchDefaultGlobal" name="searchDefault" value="global" class="global-option"/>
               <label for="searchDefaultGlobal" class="global-label">use global search</label>
               <span class="search-default-slider" aria-hidden="true"></span>
             </div>
          </div>
          <div class="chat-messages" id="chatMessages" aria-live="polite"></div>
          <form id="chatForm">
            <fieldset class="chat-turn user">
              <legend>User</legend>
              <div class="composer">
                <div class="composer-main" id="composerMain">
                  <textarea class="chat-body" id="userInput" rows="3" placeholder="Ask me anything..." required="required"></textarea>
                  <div class="attachment-row" id="attachmentRow">
                    <button type="button" class="search-button" id="searchButton" aria-label="Search">
                      <span class="glyphicon glyphicon-search" aria-hidden="true"></span>
                    </button>
                    <span class="search-hint" id="searchHint">Attach Search Results</span>
                    <button type="button" class="attachment-button" id="addFileButton" aria-label="Attach a file">
                      <span class="glyphicon glyphicon-paperclip" aria-hidden="true"></span>
                    </button>
                    <span class="attachment-filename" id="attachmentFilename">Attach PNG/JPG or text (.txt/.md/.tex)</span>
                    <input type="file" id="fileInput" class="hidden-file-input" accept="image/png,image/jpeg,text/plain,text/markdown,text/x-tex,application/x-tex,application/x-latex,text/*,.png,.jpg,.jpeg,.txt,.md,.markdown,.tex"/>
                  </div>
                </div>
                <input type="submit" class="btn btn-primary" id="sendButton" value="Send"/>
              </div>
            </fieldset>
          </form>
          <div class="clear-chat-row" id="clearChatRow">
            <button type="button" class="btn btn-inverse label-warning" id="clearChatButton" aria-label="Clear chat">
              <span class="glyphicon glyphicon-trash" aria-hidden="true"></span>
              Clear Chat
            </button>
            <button type="button" class="btn btn-inverse label-success" id="downloadChatButton" aria-label="Download chat">
              <span class="glyphicon glyphicon-download" aria-hidden="true"></span>
              Download Chat
            </button>
            <button type="button" class="btn btn-inverse label-primary" id="uploadChatButton" aria-label="Upload chat">
              <span class="glyphicon glyphicon-upload" aria-hidden="true"></span>
              Upload Chat
            </button>
            <input type="file" id="uploadChatInput" class="hidden-file-input" accept="application/json"/>
            <button type="button" class="btn btn-inverse label-info" id="toggleSystemButton" aria-label="Show system prompt">
              <span class="glyphicon glyphicon-star" aria-hidden="true"></span>
              <span class="toggle-label">Show System</span>
            </button>
          </div>
        </div>
      </div>

    <script src="js/highlight.min.js"></script>
    <script src="js/marked.umd.js"></script>
    <script src="js/yacy-markdown.js"></script>
    <script src="js/index.umd.min.js"></script>
    <script src="js/vfs.js"></script>
    <script type="text/javascript">
    const SYSTEM_PROMPT = '#[system_prompt]#';
    const defaultApiHost = '';
    const P2P_MODE = #[p2p_mode]# === 1;

    const CHAT_VFS_PATH = '/yacy/chat/chat.json';
    const SETTINGS_VFS_PATH = '/yacy/chat/settings.json';
    const SEARCH_DEFAULTS = {
        none: 'no',
        local: 'local',
        global: 'global'
    };
    const SEARCH_OPTIONS = P2P_MODE ? SEARCH_DEFAULTS : { none: 'no', local: 'local' };

    const state = {
        messages: [],
        config: {
            apiHost: defaultApiHost,
            model: 'chat',
            systemPrompt: SYSTEM_PROMPT
        },
        busy: false,
        attachment: null,
        searchMode: SEARCH_DEFAULTS.none,
        searchDefault: P2P_MODE ? SEARCH_DEFAULTS.local : SEARCH_DEFAULTS.local,
        assistantSeen: false,
        showSystem: false
    };

    const dom = {
        messages: document.getElementById('chatMessages'),
        form: document.getElementById('chatForm'),
        input: document.getElementById('userInput'),
        sendButton: document.getElementById('sendButton'),
        fileInput: document.getElementById('fileInput'),
        searchButton: document.getElementById('searchButton'),
        addFileButton: document.getElementById('addFileButton'),
        attachmentFilename: document.getElementById('attachmentFilename'),
        attachmentRow: document.getElementById('attachmentRow'),
        clearChatRow: document.getElementById('clearChatRow'),
        clearChatButton: document.getElementById('clearChatButton'),
        downloadChatButton: document.getElementById('downloadChatButton'),
        uploadChatButton: document.getElementById('uploadChatButton'),
        uploadChatInput: document.getElementById('uploadChatInput'),
        toggleSystemButton: document.getElementById('toggleSystemButton'),
        composerMain: document.getElementById('composerMain'),
        searchDefaultOptions: document.getElementById('searchDefaultOptions'),
        searchDefaultNone: document.getElementById('searchDefaultNone'),
        searchDefaultLocal: document.getElementById('searchDefaultLocal'),
        searchDefaultGlobal: document.getElementById('searchDefaultGlobal')
    };

    // configure search default options based on P2P mode
    if (dom.searchDefaultOptions) {
        if (P2P_MODE) {
            dom.searchDefaultOptions.classList.add('has-global');
        } else {
            dom.searchDefaultOptions.classList.remove('has-global');
        }
    }

    const IMAGE_MIME_TYPES = new Set(['image/png', 'image/jpeg']);
    const TEXT_MIME_TYPES = new Set(['text/plain', 'text/markdown', 'text/x-tex', 'application/x-tex', 'application/x-latex']);
    const IMAGE_EXTENSIONS = new Set(['.png', '.jpg', '.jpeg']);
    const TEXT_EXTENSIONS = new Set(['.txt', '.md', '.markdown', '.tex']);
    const ALLOWED_MIME_TYPES = new Set([...IMAGE_MIME_TYPES, ...TEXT_MIME_TYPES, 'text/*']);
    const ALLOWED_EXTENSIONS = new Set([...IMAGE_EXTENSIONS, ...TEXT_EXTENSIONS]);
    const FILE_ACCEPT_TYPES = [...ALLOWED_MIME_TYPES, ...ALLOWED_EXTENSIONS].join(',');


    if (dom.fileInput) {
        dom.fileInput.setAttribute('accept', FILE_ACCEPT_TYPES);
    }

    if (dom.attachmentFilename) {
        dom.attachmentFilename.tabIndex = 0;
        setupAttachmentPreviewTrigger(dom.attachmentFilename, () => state.attachment);
    }

    if (typeof hljs !== 'undefined') {
        hljs.configure({ ignoreUnescapedHTML: true });
    }

    const languageAlias = {
        js: 'javascript',
        jsx: 'javascript',
        ts: 'typescript',
        tsx: 'typescript',
        sh: 'bash',
        shell: 'bash',
        bash: 'bash',
        csharp: 'csharp',
        'c#': 'csharp',
        'c++': 'cpp',
        py: 'python',
        rb: 'ruby',
        rs: 'rust',
        md: 'markdown',
        yml: 'yaml'
    };

    const languagePromises = {};

    function normalizeLanguage(lang) {
        if (!lang || typeof lang !== 'string') return '';
        const key = lang.trim().toLowerCase();
        return languageAlias[key] || key;
    }

    function ensureLanguage(lang) {
        if (typeof hljs === 'undefined') return Promise.resolve(false);
        const normalized = normalizeLanguage(lang);
        if (!normalized) return Promise.resolve(false);
        if (hljs.getLanguage(normalized)) return Promise.resolve(true);
        if (languagePromises[normalized]) return languagePromises[normalized];
        const loadScript = path => new Promise(resolve => {
            const script = document.createElement('script');
            script.src = path;
            script.async = true;
            script.onload = () => resolve(!!hljs.getLanguage(normalized));
            script.onerror = () => {
                console.warn('Failed to load highlight.js language file:', path);
                resolve(false);
            };
            document.head.appendChild(script);
        });
        const base = (window.location && window.location.origin) ? window.location.origin : '';
        const minSrc = `${base}/js/languages/${normalized}.min.js`;
        const fullSrc = `${base}/js/languages/${normalized}.js`;
        languagePromises[normalized] = loadScript(minSrc).then(success => {
            if (success) return true;
            return loadScript(fullSrc);
        }).then(success => success || !!hljs.getLanguage(normalized));
        return languagePromises[normalized];
    }

    function rehighlightCode(container) {
        if (!container || typeof hljs === 'undefined') return;
        const codeBlocks = Array.from(container.querySelectorAll('pre code'));
        if (!codeBlocks.length) return;
        const tasks = codeBlocks
            .map(block => Array.from(block.classList).find(cls => cls.startsWith('language-')))
            .map(match => match ? normalizeLanguage(match.replace(/^language-/, '')) : '')
            .filter(Boolean)
            .map(lang => ensureLanguage(lang));
        Promise.all(tasks).then(() => {
            codeBlocks.forEach(block => {
                try {
                    hljs.highlightElement(block);
                } catch (err) {
                    // ignore highlight failures
                }
            });
        });
    }

    const markdownSupport = (() => {
        if (typeof marked === 'undefined') {
            return { enabled: false };
        }
        try {
            if (window.markedHighlight && typeof window.markedHighlight.markedHighlight === 'function' && typeof hljs !== 'undefined') {
                marked.use(window.markedHighlight.markedHighlight({
                    langPrefix: 'hljs language-',
                    highlight: (code, lang) => {
                        const language = normalizeLanguage(lang);
                        ensureLanguage(language);
                        if (language && hljs.getLanguage(language)) {
                            return hljs.highlight(code, { language }).value;
                        }
                        // kick off lazy load; will rehighlight after render
                        return escapeHTML(code);
                    }
                }));
            }
        } catch (err) {
            console.warn('Failed to initialize syntax highlighting', err);
        }
        marked.setOptions(YaCyMarkdown.markedOptions);
        return { enabled: true };
    })();

    // shared markdown helpers from js/yacy-markdown.js, also used by LogReports_p.html
    const escapeHTML = YaCyMarkdown.escapeHTML;
    const sanitizeHTML = YaCyMarkdown.sanitizeHTML;

    function renderMarkdown(content) {
        const source = typeof content === 'string' ? content : '';
        if (!markdownSupport.enabled || typeof marked === 'undefined') {
            return escapeHTML(source);
        }
        try {
            return sanitizeHTML(marked.parse(source));
        } catch (err) {
            console.warn('Markdown rendering failed', err);
            return escapeHTML(source);
        }
    }

    function stripThinkBlocks(text) {
        if (!text || typeof text !== 'string') return text || '';
        const ranges = buildFenceRanges(text);
        const openPattern = /<think\s*>/ig;
        const closePattern = /<\/think\s*>/ig;
        let result = '';
        let cursor = 0;
        while (cursor < text.length) {
            const open = findTagOutsideFences(text, cursor, openPattern, ranges);
            if (!open) {
                result += text.slice(cursor);
                break;
            }
            result += text.slice(cursor, open.index);
            const close = findTagOutsideFences(text, open.end, closePattern, ranges);
            if (!close) {
                break;
            }
            cursor = close.end;
        }
        return result;
    }

    function stripToolProtocolMarkup(text) {
        if (!text || typeof text !== 'string') return text || '';
        // Remove legacy/model-emitted tool protocol snippets like:
        // <function=name>
        // <parameter=key>
        // value
        let cleaned = text.replace(/^\s*<function=[^>\n]+>\s*$[\s\S]*?(?=^\s*$|$)/gim, '');
        cleaned = cleaned.replace(/^\s*<parameter=[^>\n]+>\s*$[\s\S]*?(?=^\s*$|$)/gim, '');
        // Collapse excessive blank lines introduced by stripping.
        cleaned = cleaned.replace(/\n{3,}/g, '\n\n');
        return cleaned;
    }

    function stripThinkFromContent(content) {
        if (typeof content === 'string') return stripToolProtocolMarkup(stripThinkBlocks(content));
        if (Array.isArray(content)) {
            return content.map(part => {
                if (part?.type === 'text' && typeof part.text === 'string') {
                    return { ...part, text: stripToolProtocolMarkup(stripThinkBlocks(part.text)) };
                }
                return part;
            });
        }
        if (content && typeof content === 'object' && typeof content.text === 'string') {
            return { ...content, text: stripToolProtocolMarkup(stripThinkBlocks(content.text)) };
        }
        return content;
    }

    function resolveThinkDefaultOpen(container) {
        const index = Number.parseInt(container?.dataset?.messageIndex || '', 10);
        const message = Number.isNaN(index) ? null : state.messages[index];
        const explicitOpen = container?.dataset?.thinkOpen;
        if (explicitOpen === 'true') return true;
        if (explicitOpen === 'false') return false;
        if (typeof message?.thinkOpen === 'boolean') return message.thinkOpen;
        if (container?.dataset?.thinkAutoClosed === 'true') return false;
        return container?.dataset?.streaming === 'true';
    }

    function buildFenceRanges(text) {
        const ranges = [];
        if (!text || typeof text !== 'string') return ranges;
        let inFence = false;
        let fenceChar = '';
        let fenceStart = 0;
        let offset = 0;
        const lines = text.split('\n');
        for (let i = 0; i < lines.length; i++) {
            const line = lines[i];
            const fenceMatch = line.match(/^\s*(```+|~~~+)/);
            if (fenceMatch) {
                const marker = fenceMatch[1];
                if (!inFence) {
                    inFence = true;
                    fenceChar = marker[0];
                    fenceStart = offset;
                } else if (marker[0] === fenceChar) {
                    inFence = false;
                    ranges.push([fenceStart, offset + line.length + 1]);
                    fenceChar = '';
                }
            }
            offset += line.length + 1;
        }
        if (inFence) {
            ranges.push([fenceStart, text.length]);
        }
        return ranges;
    }

    function isIndexInFence(index, ranges) {
        return ranges.some(range => index >= range[0] && index < range[1]);
    }

    function findTagOutsideFences(text, start, pattern, ranges) {
        const regex = new RegExp(pattern.source, pattern.flags);
        regex.lastIndex = start;
        let match = regex.exec(text);
        while (match) {
            if (!isIndexInFence(match.index, ranges)) {
                return { index: match.index, end: regex.lastIndex, match };
            }
            regex.lastIndex = match.index + 1;
            match = regex.exec(text);
        }
        return null;
    }

    function hasThinkCloseOutsideFences(text) {
        if (!text || typeof text !== 'string') return false;
        const ranges = buildFenceRanges(text);
        return !!findTagOutsideFences(text, 0, /<\/think\s*>/ig, ranges);
    }

    function renderAssistantContent(text, defaultOpen) {
        const source = typeof text === 'string' ? text : '';
        if (!source) return '';
        const openRe = /<think\s*>/ig;
        const closeRe = /<\/think\s*>/ig;
        const ranges = buildFenceRanges(source);
        let html = '';
        let cursor = 0;
        while (cursor < source.length) {
            const openMatch = findTagOutsideFences(source, cursor, openRe, ranges);
            if (!openMatch) {
                html += renderMarkdown(source.slice(cursor));
                break;
            }
            const openIndex = openMatch.index;
            const openEnd = openMatch.end;
            if (openIndex > cursor) {
                html += renderMarkdown(source.slice(cursor, openIndex));
            }
            const closeMatch = findTagOutsideFences(source, openEnd, closeRe, ranges);
            const closeIndex = closeMatch ? closeMatch.index : -1;
            const thinkBody = closeIndex === -1
                ? source.slice(openEnd)
                : source.slice(openEnd, closeIndex);
            const openAttr = defaultOpen ? ' open="open"' : '';
            html += `<details class="think-block"${openAttr}><summary>Model thoughts</summary><div class="think-content">${renderMarkdown(thinkBody)}</div></details>`;
            if (!closeMatch) {
                break;
            }
            cursor = closeMatch.end;
        }
        return html;
    }

    function bindThinkToggles(container) {
        if (!container) return;
        const detailsNodes = Array.from(container.querySelectorAll('details.think-block'));
        if (!detailsNodes.length) return;
        const index = Number.parseInt(container.dataset.messageIndex || '', 10);
        detailsNodes.forEach(details => {
            details.addEventListener('toggle', () => {
                if (!Number.isNaN(index)) {
                    const targetMessage = state.messages[index];
                    if (targetMessage) {
                        targetMessage.thinkOpen = details.open;
                        persistConversation();
                    }
                } else {
                    container.dataset.thinkOpen = details.open ? 'true' : 'false';
                }
            });
        });
    }

    function applyMessageContent(target, role, text) {
        if (!target) return;
        if (role === 'assistant') {
            target.classList.add('markdown', 'markdown-body');
            target.classList.remove('plain-text');
            target.dataset.rawMarkdown = text || '';
            const defaultOpen = resolveThinkDefaultOpen(target);
            target.innerHTML = renderAssistantContent(text, defaultOpen);
            bindThinkToggles(target);
            rehighlightCode(target);
        } else {
            target.classList.add('plain-text');
            target.classList.remove('markdown');
            target.textContent = text || '';
        }
    }

    function scrollToBottom(smooth = true) {
        window.requestAnimationFrame(() => {
            const behavior = smooth ? 'smooth' : 'auto';
            window.scrollTo({ top: document.documentElement.scrollHeight, behavior });
        });
    }

    function formatTimestamp() {
        const now = new Date();
        const pad = (n, len = 2) => n.toString().padStart(len, '0');
        return `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}-${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}`;
    }

    function updateSystemToggleButton() {
        if (!dom.toggleSystemButton) return;
        const icon = dom.toggleSystemButton.querySelector('.glyphicon');
        if (icon) {
            icon.className = `glyphicon ${state.showSystem ? 'glyphicon-star-empty' : 'glyphicon-star'}`;
        }
        const label = state.showSystem ? 'Hide System' : 'Show System';
        dom.toggleSystemButton.querySelector('.toggle-label').textContent = label;
    }

    function appendMessage(role, text, opts = {}) {
        const { skipScroll = false, skipVisibilityUpdate = false, attachment = null, messageIndex = undefined, toolCalls = null, toolResults = null } = opts;
        const entry = document.createElement('fieldset');
        entry.className = `chat-turn ${role}`;
        if (role === 'assistant' || role === 'user') {
            entry.style.position = 'relative';
        }
        const legend = document.createElement('legend');
        if (role === 'assistant') {
            legend.textContent = 'Assistant';
        } else if (role === 'user') {
            legend.textContent = 'User';
        } else if (role === 'tool') {
            legend.textContent = 'Tool';
        } else {
            legend.textContent = 'System';
        }
        entry.appendChild(legend);

        const body = document.createElement('div');
        body.className = 'chat-body';
        if (typeof messageIndex === 'number') {
            body.dataset.messageIndex = String(messageIndex);
        }
        applyMessageContent(body, role, text);
        entry.appendChild(body);

        if (attachment && role === 'user') {
            const attachmentContainer = document.createElement('div');
            attachmentContainer.appendChild(createAttachmentChip(attachment));
            entry.appendChild(attachmentContainer);
        }
        dom.messages.appendChild(entry);
        if (typeof opts.messageIndex === 'number') {
            entry.dataset.messageIndex = String(opts.messageIndex);
        }
        if (role === 'assistant') {
            const copyBtn = document.createElement('button');
            copyBtn.type = 'button';
            copyBtn.className = 'copy-button';
            copyBtn.title = 'Copy answer';
            copyBtn.innerHTML = '<span class="glyphicon glyphicon-copy" aria-hidden="true"></span>';
            copyBtn.addEventListener('click', () => copyAssistant(body));
            entry.appendChild(copyBtn);
            renderToolCallControls(entry, toolCalls, toolResults);
        }
        if (role === 'user' && typeof messageIndex === 'number') {
            const trimBtn = document.createElement('button');
            trimBtn.type = 'button';
            trimBtn.className = 'user-trim-button';
            trimBtn.title = 'Reuse from here';
            trimBtn.innerHTML = '<span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>';
            trimBtn.addEventListener('click', () => trimConversationFromIndex(messageIndex, body.textContent));
            entry.appendChild(trimBtn);
            const deleteBtn = document.createElement('button');
            deleteBtn.type = 'button';
            deleteBtn.className = 'user-delete-button';
            deleteBtn.title = 'Delete this turn';
            deleteBtn.innerHTML = '<span class="glyphicon glyphicon-trash" aria-hidden="true"></span>';
            deleteBtn.addEventListener('click', () => deleteConversationPair(messageIndex));
            entry.appendChild(deleteBtn);
        }
        if (!skipScroll && !state.busy) {
            scrollToBottom();
        }
        if (!skipVisibilityUpdate && role === 'assistant') {
            state.assistantSeen = true;
            updateClearChatVisibility();
        }
        return body;
    }

    function renderToolCallControls(entry, toolCalls, toolResults, pendingToolCalls = []) {
        if (!entry) return;
        if (entry._toolcallOutsideClickHandler) {
            document.removeEventListener('click', entry._toolcallOutsideClickHandler);
            entry._toolcallOutsideClickHandler = null;
        }
        Array.prototype.slice.call(entry.children).forEach(node => {
            if (node.classList && (node.classList.contains('toolcall-toolbar') || node.classList.contains('toolcalls-popover'))) {
                node.remove();
            }
        });
        if (!Array.isArray(toolCalls) || toolCalls.length === 0) return;

        const toolbar = document.createElement('div');
        toolbar.className = 'toolcall-toolbar';
        const panels = [];
        const resultsById = new Map();
        const resultsByName = new Map();
        if (Array.isArray(toolResults)) {
            for (const result of toolResults) {
                if (!result) continue;
                if (result.id) resultsById.set(result.id, result);
                if (result.tool_call_id) resultsById.set(result.tool_call_id, result);
                const rname = result?.name || result?.function?.name;
                if (rname && !resultsByName.has(rname)) resultsByName.set(rname, result);
            }
        }

        for (let i = 0; i < toolCalls.length; i++) {
            const call = toolCalls[i];
            if (!call) continue;
            const fnName = call?.function?.name || call?.name || 'tool';
            const matchedResult = (call.id && resultsById.get(call.id)) || resultsByName.get(fnName) || null;
            const pending = isPendingToolCall(call, pendingToolCalls);

            const toolBtn = document.createElement('button');
            toolBtn.type = 'button';
            toolBtn.className = pending ? 'toolcalls-button pending' : 'toolcalls-button';
            toolBtn.title = pending ? `Preparing tool: ${fnName}` : `Tool: ${fnName}`;
            toolBtn.disabled = pending;
            toolBtn.innerHTML = '<span class="glyphicon glyphicon-wrench" aria-hidden="true"></span>';

            if (!pending) {
                const toolPanel = createToolCallPanel(call, matchedResult, toolCalls.length, i);
                toolPanel.style.display = 'none';
                toolPanel.addEventListener('click', evt => evt.stopPropagation());
                entry.appendChild(toolPanel);
                panels.push(toolPanel);

                toolBtn.addEventListener('click', event => {
                    event.stopPropagation();
                    const open = toolPanel.style.display !== 'none';
                    for (const panel of panels) panel.style.display = 'none';
                    toolPanel.style.display = open ? 'none' : 'block';
                });
            }
            toolbar.appendChild(toolBtn);
        }
        entry.appendChild(toolbar);

        entry._toolcallOutsideClickHandler = evt => {
            if (!entry.contains(evt.target)) {
                for (const panel of panels) panel.style.display = 'none';
            }
        };
        document.addEventListener('click', entry._toolcallOutsideClickHandler);
    }

    function isPendingToolCall(call, pendingToolCalls) {
        if (!call || !Array.isArray(pendingToolCalls)) return false;
        return pendingToolCalls.some(pending => sameToolCall(call, pending));
    }

    function sameToolCall(a, b) {
        if (!a || !b) return false;
        if (a.id && b.id) return a.id === b.id;
        const an = a?.function?.name || a?.name || '';
        const bn = b?.function?.name || b?.name || '';
        const aa = a?.function?.arguments || a?.arguments || '';
        const ba = b?.function?.arguments || b?.arguments || '';
        return an === bn && aa === ba;
    }

    function clearAttachment(options = {}) {
        const { applyDefault = true } = options;
        state.attachment = null;
        state.searchMode = SEARCH_DEFAULTS.none;
        dom.fileInput.value = '';
        dom.attachmentFilename.textContent = 'Attach PNG/JPG or text (.txt/.md/.tex)';
        dom.attachmentRow.classList.remove('has-attachment');
        dom.attachmentRow.classList.remove('search-mode');
        dom.searchButton?.classList.remove('button-active');
        dom.addFileButton?.classList.remove('button-active');
        closeAttachmentPopover();
        if (applyDefault) {
            applySearchDefaultToComposer();
        }
    }

    function setComposerAttachment(attachment) {
        state.searchMode = SEARCH_DEFAULTS.none;
        dom.attachmentRow.classList.remove('search-mode');
        dom.searchButton?.classList.remove('button-active');
        state.attachment = attachment ? cloneAttachment(attachment) : null;
        if (state.attachment) {
            dom.attachmentFilename.textContent = `Attach File: ${state.attachment.name || 'Attachment'}`;
            dom.attachmentRow.classList.add('has-attachment');
            dom.addFileButton?.classList.add('button-active');
        } else {
            dom.addFileButton?.classList.remove('button-active');
            clearAttachment();
        }
    }

    function setAttachmentLoading(isLoading) {
        if (!dom.attachmentRow || !dom.attachmentFilename) return;
        dom.attachmentRow.classList.toggle('loading', !!isLoading);
        if (isLoading) {
            dom.attachmentFilename.textContent = 'Loading attachment...';
        } else if (!state.attachment) {
            dom.attachmentFilename.textContent = 'Attach PNG/JPG or text (.txt/.md/.tex)';
        }
    }

    function setSearchModeActive(mode) {
        let nextMode = mode;
        if (mode === true) {
            // validate against available options
            if (P2P_MODE) {
                nextMode = state.searchDefault === SEARCH_DEFAULTS.none ? SEARCH_DEFAULTS.local : state.searchDefault;
            } else {
                nextMode = state.searchDefault === SEARCH_DEFAULTS.global ? SEARCH_DEFAULTS.local : state.searchDefault;
            }
        }
        if (!nextMode || nextMode === false) {
            nextMode = SEARCH_DEFAULTS.none;
        }
        // reject global mode when not in P2P
        if (!P2P_MODE && nextMode === SEARCH_DEFAULTS.global) {
            nextMode = SEARCH_DEFAULTS.local;
        }
        state.searchMode = nextMode;
        state.attachment = null;
        dom.fileInput.value = '';
        dom.attachmentRow.classList.remove('has-attachment');
        dom.searchButton?.classList.toggle('button-active', state.searchMode !== SEARCH_DEFAULTS.none);
        dom.addFileButton?.classList.remove('button-active');
        if (state.searchMode !== SEARCH_DEFAULTS.none) {
            dom.attachmentRow.classList.add('search-mode');
            dom.attachmentFilename.textContent = 'Attach PNG/JPG or text (.txt/.md/.tex)';
        } else {
            dom.attachmentRow.classList.remove('search-mode');
            dom.attachmentFilename.textContent = 'Attach PNG/JPG or text (.txt/.md/.tex)';
        }
    }

    function applySearchDefaultToComposer() {
        if (!dom.attachmentRow || state.attachment) return;
        if (state.searchDefault !== SEARCH_DEFAULTS.none) {
            // validate search default against available options
            const validDefault = P2P_MODE ? state.searchDefault : state.searchDefault === SEARCH_DEFAULTS.global ? SEARCH_DEFAULTS.local : state.searchDefault;
            setSearchModeActive(validDefault);
        } else {
            setSearchModeActive(SEARCH_DEFAULTS.none);
        }
    }

    function updateSearchDefaultSlider() {
        if (!dom.searchDefaultOptions) return;
        // count only visible inputs (exclude hidden global option)
        const inputs = Array.from(dom.searchDefaultOptions.querySelectorAll('input[name="searchDefault"]'));
        const visibleInputs = inputs.filter(input => {
            if (input === dom.searchDefaultGlobal) {
                return dom.searchDefaultOptions.classList.contains('has-global');
            }
            return true;
        });
        const activeIndex = visibleInputs.findIndex(input => input.checked);
        const segments = visibleInputs.length || 2;
        dom.searchDefaultOptions.style.setProperty('--segments', segments);
        // map checked input to its index among visible inputs
        let displayIndex = 0;
        for (const input of inputs) {
            if (input === dom.searchDefaultGlobal && !dom.searchDefaultOptions.classList.contains('has-global')) {
                continue;
            }
            if (input.checked) break;
            displayIndex++;
        }
        dom.searchDefaultOptions.style.setProperty('--active', displayIndex);
    }

    async function getVfsClient() {
        if (window.vfs) return window.vfs;
        if (window.vfsReady) return await window.vfsReady;
        throw new Error('VFS unavailable');
    }

    async function readVfsJson(path) {
        try {
            const vfs = await getVfsClient();
            const value = await vfs.get(path);
            if (value && typeof value === 'object') return value;
            if (typeof value === 'string' && value.trim()) {
                if (value.trim() === '[object Object]') return null;
                try {
                    return JSON.parse(value);
                } catch (err) {
                    return null;
                }
            }
            return null;
        } catch (err) {
            if (String(err) === 'Key not found') return null;
            throw err;
        }
    }

    async function writeVfsJson(path, value) {
        const vfs = await getVfsClient();
        await vfs.put(path, JSON.stringify(value, null, 2));
    }

    async function removeVfsPath(path) {
        const vfs = await getVfsClient();
        await vfs.rm(path);
    }

    function persistSearchDefault() {
        writeVfsJson(SETTINGS_VFS_PATH, { search_default: state.searchDefault }).catch(err => {
            console.warn('Failed to persist search default', err);
        });
    }

    async function loadSearchDefault() {
        let stored = null;
        try {
            const settings = await readVfsJson(SETTINGS_VFS_PATH);
            stored = settings?.search_default || null;
        } catch (err) {
            console.warn('Failed to load search default', err);
        }
        if (stored === 'none') stored = SEARCH_DEFAULTS.none;
        // validate stored default against available options
        if (!P2P_MODE && stored === SEARCH_DEFAULTS.global) {
            stored = SEARCH_DEFAULTS.local;
        }
        if (stored && Object.values(SEARCH_OPTIONS).includes(stored)) {
            state.searchDefault = stored;
        }
        // update radio buttons to reflect stored state
        if (dom.searchDefaultNone && state.searchDefault === SEARCH_DEFAULTS.none) {
            dom.searchDefaultNone.checked = true;
        } else if (dom.searchDefaultLocal && state.searchDefault === SEARCH_DEFAULTS.local) {
            dom.searchDefaultLocal.checked = true;
        } else if (dom.searchDefaultGlobal && !P2P_MODE) {
            // global not available, fallback to local
            dom.searchDefaultLocal.checked = true;
            state.searchDefault = SEARCH_DEFAULTS.local;
        } else if (dom.searchDefaultGlobal && state.searchDefault === SEARCH_DEFAULTS.global) {
            dom.searchDefaultGlobal.checked = true;
        }
        updateSearchDefaultSlider();
        applySearchDefaultToComposer();
    }

    async function copyAssistant(target) {
        const raw = target?.dataset?.rawMarkdown;
        const source = typeof raw === 'string' ? raw : (target?.textContent || '');
        const cleaned = stripThinkBlocks(source);
        try {
            await navigator.clipboard.writeText(cleaned || '');
        } catch (err) {
            console.warn('Clipboard copy failed', err);
        }
    }

    function trimConversationFromIndex(index, reuseText) {
        if (typeof index !== 'number' || index < 0) return;
        const targetMessage = state.messages[index];
        state.messages = state.messages.slice(0, index);
        state.assistantSeen = state.messages.some(m => m.role === 'assistant');
        state.showSystem = false;
        renderConversation();
        persistConversation();
        updateClearChatVisibility();
        updateSystemToggleButton();
        setComposerAttachment(inferAttachmentFromContent(targetMessage?.content) || null);
        dom.input.value = reuseText || '';
        resizeComposer();
        showComposer();
    }

    function deleteConversationPair(userIndex) {
        if (typeof userIndex !== 'number' || userIndex < 0) return;
        if (!state.messages[userIndex] || state.messages[userIndex].role !== 'user') return;
        const nextMessage = state.messages[userIndex + 1];
        const removeCount = nextMessage && nextMessage.role === 'assistant' ? 2 : 1;
        state.messages.splice(userIndex, removeCount);
        state.assistantSeen = state.messages.some(m => m.role === 'assistant');
        renderConversation();
        persistConversation();
        updateClearChatVisibility();
        updateSystemToggleButton();
        showComposer();
    }

    function hideComposer() {
        if (dom.form) {
            dom.form.style.visibility = 'hidden';
            dom.form.style.pointerEvents = 'none';
        }
    }

    function showComposer() {
        if (dom.form) {
            dom.form.style.visibility = '';
            dom.form.style.pointerEvents = '';
        }
        if (dom.input) {
            try {
                dom.input.focus({ preventScroll: true });
            } catch (err) {
                dom.input.focus();
            }
        }
    }

    function updateClearChatVisibility() {
        if (!dom.clearChatRow) return;
        dom.clearChatRow.style.visibility = state.assistantSeen ? 'visible' : 'hidden';
        dom.clearChatRow.style.pointerEvents = state.assistantSeen ? 'auto' : 'none';
    }

    function ensureComposerVisible(evt) {
        if (evt && evt.isTrusted === false) return;
        scrollToBottom(true);
    }

    function clearChatHistory() {
        dom.messages.innerHTML = '';
        state.messages = [];
        state.assistantSeen = false;
        state.showSystem = false;
        removeVfsPath(CHAT_VFS_PATH).catch(err => {
            console.warn('Failed to clear chat history', err);
        });
        closeAttachmentPopover();
        closeAttachmentModal();
        updateClearChatVisibility();
        updateSystemToggleButton();
        dom.input.value = '';
        clearAttachment();
        resizeComposer();
    }

    function downloadChat() {
        const payload = buildRequestPayload();
        const blob = new Blob([JSON.stringify(payload, null, 2)], { type: 'application/json' });
        const url = URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.download = `yacychat-${formatTimestamp()}.json`;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        URL.revokeObjectURL(url);
    }

    function applyUploadedChat(payload) {
        if (!payload || !Array.isArray(payload.messages)) {
            appendMessage('system', 'Invalid chat file.');
            return;
        }
        clearChatHistory();
        if (payload.model) {
            state.config.model = payload.model;
        }
        for (const msg of payload.messages) {
            if (!msg?.role || msg.content === undefined) continue;
            state.messages.push({ ...msg });
        }
        renderConversation();
        persistConversation();
    }

    async function handleUploadChatFile(event) {
        const file = event.target.files && event.target.files[0];
        dom.uploadChatInput.value = '';
        if (!file) return;
        try {
            const text = await file.text();
            const parsed = JSON.parse(text);
            applyUploadedChat(parsed);
        } catch (err) {
            appendMessage('system', `Failed to load chat file: ${err.message}`);
        }
    }

    function ensureSystemMessage() {
        if (!state.messages.length || state.messages[0].role !== 'system') {
            state.messages.unshift({ role: 'system', content: state.config.systemPrompt });
        }
    }

    async function streamChat(userMessage, assistantNode, options = {}) {
        const { onFirstToken, includeUserInPayload = true, pushUserToState = true, currentUserIndex = -1 } = options;
        const requestStart = performance.now();
        ensureSystemMessage();
        const sanitizedMessages = state.messages
            .map((msg, index) => {
                const hasAttachment = msg?.role === 'user' && Array.isArray(msg.content);
                const textOnly = index !== currentUserIndex && !hasAttachment;
                return stripMessageForApi(msg, { textOnly });
            })
            .filter(Boolean);
        const sanitizedUserMessage = includeUserInPayload ? stripMessageForApi(userMessage) : null;
        const payload = {
            model: state.config.model,
            messages: sanitizedUserMessage ? [...sanitizedMessages, sanitizedUserMessage] : sanitizedMessages,
            stream: true
        };
        const headers = { 'Content-Type': 'application/json' };
        const response = await fetch(state.config.apiHost.replace(/\/$/, '') + '/v1/chat/completions', {
            method: 'POST',
            headers,
            body: JSON.stringify(payload)
        });
        if (!response.ok) {
            if (response.status === 429) {
                throw new Error('Rate limit reached: please wait and try again. The server is protecting itself from overload.');
            }
            throw new Error(`Request failed: ${response.status} ${response.statusText}`);
        }
        if (!response.body) {
            throw new Error('Streaming not supported by this browser.');
        }
        const reader = response.body.getReader();
        const decoder = new TextDecoder('utf-8');
        let assistantText = '';
        let roundToolCalls = [];
        let collectedToolCalls = [];
        let collectedToolResults = [];
        let sawFirstDelta = false;
        let focusShown = false;
        let searchApplied = false;
        let thinkAutoClosed = false;
        let thinkAutoCloseFired = false;
        let thinkAutoCloseTimer = null;
        if (assistantNode) {
            assistantNode.dataset.streaming = 'true';
        }
        if (typeof onFirstToken === 'function' && !focusShown) {
            focusShown = true;
            onFirstToken();
        }
        let autoScroll = true;
        let pending = '';

        const applySearchAttachment = parsed => {
            if (searchApplied) return;
            if (!parsed) return;
            const searchName = parsed['search-filename'];
            const searchBase64 = parsed['search-text-base64'];
            if (!searchName || !searchBase64) return;
            const dataUrl = `data:text/markdown;base64,${searchBase64}`;
            const textContent = base64ToUtf8(searchBase64);
            for (let i = state.messages.length - 1; i >= 0; i--) {
                const msg = state.messages[i];
                if (msg && msg.role === 'user' && msg.search && msg.search !== SEARCH_DEFAULTS.none) {
                    const attachment = {
                        kind: 'text',
                        name: searchName,
                        dataUrl,
                        mime: 'text/markdown',
                        textContent
                    };
                    msg.content = buildContentWithAttachment(messageText(msg.content), attachment);
                    delete msg.search;
                    searchApplied = true;
                    break;
                }
            }
        };

        const performAutoScroll = () => {
            if (!autoScroll) return;
            scrollToBottom(false);
            const rect = assistantNode?.getBoundingClientRect();
            if (rect && rect.top <= 110) {
                autoScroll = false;
            }
        };

        const renderLiveToolControls = () => {
            if (!assistantNode || collectedToolResults.length === 0 || collectedToolCalls.length === 0) return;
            const entry = assistantNode.closest('.chat-turn.assistant');
            if (!entry) return;
            renderToolCallControls(entry, collectedToolCalls, collectedToolResults);
        };

        const renderPendingToolControls = () => {
            if (!assistantNode || roundToolCalls.length === 0) return;
            const entry = assistantNode.closest('.chat-turn.assistant');
            if (!entry) return;
            const pendingCalls = normalizeToolCalls(roundToolCalls);
            const visibleCalls = appendToolCalls(collectedToolCalls, pendingCalls);
            renderToolCallControls(entry, visibleCalls, collectedToolResults, pendingCalls);
        };

        const processLine = line => {
            const trimmed = (line || '').trim();
            if (!trimmed) return false;
            if (trimmed === 'data: [DONE]' || trimmed === '[DONE]') return true;
            if (!trimmed.startsWith('data:')) return false;
            const clean = trimmed.replace(/^data:\s*/i, '');
            if (!clean) return false;
            try {
                const parsed = JSON.parse(clean);
                let toolMetadataChanged = false;
                applySearchAttachment(parsed);
                if (Array.isArray(parsed['tool-calls']) && parsed['tool-calls'].length > 0) {
                    const injectedToolCalls = normalizeToolCalls(parsed['tool-calls']);
                    if (injectedToolCalls.length > 0) {
                        collectedToolCalls = appendToolCalls(collectedToolCalls, injectedToolCalls);
                        roundToolCalls = [];
                        toolMetadataChanged = true;
                    }
                }
                if (Array.isArray(parsed['tool-results']) && parsed['tool-results'].length > 0) {
                    const normalizedResults = normalizeToolResults(parsed['tool-results']);
                    collectedToolResults = collectedToolResults.concat(normalizedResults);
                    toolMetadataChanged = true;
                }
                if (toolMetadataChanged) {
                    renderLiveToolControls();
                }
                const choice = parsed?.choices?.[0];
                const delta = choice?.delta;
                const finishReason = choice?.finish_reason;
                const toolDelta = delta?.tool_calls;
                if (toolDelta) {
                    roundToolCalls = mergeToolCalls(roundToolCalls, toolDelta);
                    renderPendingToolControls();
                }
                if (delta?.function_call) {
                    roundToolCalls = mergeToolCalls(roundToolCalls, [{
                        index: 0,
                        type: 'function',
                        function: delta.function_call
                    }]);
                    renderPendingToolControls();
                }
                if (finishReason === 'tool_calls' || finishReason === 'function_call') {
                    const finalized = normalizeToolCalls(roundToolCalls);
                    if (finalized.length) {
                        collectedToolCalls = collectedToolCalls.concat(finalized);
                    }
                    roundToolCalls = [];
                }
                const contentDelta = delta?.content;
                if (delta) {
                    if (!sawFirstDelta) {
                        sawFirstDelta = true;
                        applyMessageContent(assistantNode, 'assistant', 'waiting for an answer...');
                        if (!focusShown && typeof onFirstToken === 'function') {
                            focusShown = true;
                            onFirstToken();
                        }
                    }
                    if (contentDelta) {
                        assistantText += contentDelta;
                        assistantText = stripToolProtocolMarkup(assistantText);
                    }
                    if (!thinkAutoClosed && hasThinkCloseOutsideFences(assistantText)) {
                        thinkAutoClosed = true;
                        if (assistantNode) {
                            assistantNode.dataset.thinkAutoClosing = 'true';
                        }
                        if (thinkAutoCloseTimer) {
                            clearTimeout(thinkAutoCloseTimer);
                        }
                        thinkAutoCloseTimer = window.setTimeout(() => {
                            thinkAutoCloseFired = true;
                            if (assistantNode) {
                                assistantNode.dataset.thinkAutoClosing = 'false';
                                assistantNode.dataset.thinkAutoClosed = 'true';
                                assistantNode.dataset.thinkOpen = 'false';
                                applyMessageContent(assistantNode, 'assistant', assistantText);
                            }
                            const last = state.messages[state.messages.length - 1];
                            if (last && last.role === 'assistant' && last.content === assistantText) {
                                last.thinkOpen = false;
                                persistConversation();
                                renderConversation({ skipScroll: true });
                            }
                        }, 2000);
                    }
                    if (assistantText) {
                        applyMessageContent(assistantNode, 'assistant', assistantText);
                    }
                    performAutoScroll();
                }
            } catch (err) {
                console.warn('Failed to parse line', trimmed, err);
            }
            return false;
        };

        const parseChunk = chunk => {
            pending += chunk;
            const lines = pending.split(/\r?\n/);
            pending = lines.pop() || '';
            for (const line of lines) {
                if (processLine(line)) return true;
            }
            return false;
        };
        let done = false;
        while (!done) {
            const { value, done: readerDone } = await reader.read();
            if (readerDone) break;
            const chunk = decoder.decode(value, { stream: true });
            if (!focusShown && chunk && chunk.trim() && typeof onFirstToken === 'function') {
                focusShown = true;
                onFirstToken();
            }
            done = parseChunk(chunk);
        }
        if (!done && pending.trim()) {
            parseChunk('\n');
        }
        if (!focusShown && typeof onFirstToken === 'function') {
            focusShown = true;
            onFirstToken();
        }
        if (pushUserToState) {
            state.messages.push(userMessage);
        }
        const explicitThinkOpen = assistantNode?.dataset?.thinkOpen;
        const storedThinkOpen = explicitThinkOpen === 'true'
            ? true
            : explicitThinkOpen === 'false'
                ? false
                : (thinkAutoClosed && !thinkAutoCloseFired);
        const normalizedToolCalls = normalizeToolCalls(collectedToolCalls.concat(roundToolCalls));
        const assistantMessage = {
            role: 'assistant',
            content: assistantText,
            thinkOpen: storedThinkOpen
        };
        if (normalizedToolCalls.length) {
            assistantMessage.tool_calls = normalizedToolCalls;
            if (collectedToolResults.length) {
                assistantMessage.tool_results = collectedToolResults;
            }
            assistantMessage.display = assistantText && assistantText.trim()
                ? assistantText
                : `Tool call: ${normalizedToolCalls.map(call => call?.function?.name || 'tool').join(', ')}`;
        }
        state.messages.push(assistantMessage);
        state.assistantSeen = true;
        persistConversation();
        updateClearChatVisibility();
        updateSystemToggleButton();
        renderConversation({ skipScroll: true });
    }

    function resizeComposer() {
        const minHeight = 24;
        dom.input.style.height = 'auto';
        const measured = dom.input.scrollHeight || minHeight;
        dom.input.style.height = `${Math.max(minHeight, measured)}px`;
    }

    function buildContentWithAttachment(promptText, attachment) {
        const parts = [{ type: 'text', text: promptText }];
        if (attachment?.dataUrl) {
            parts.push({
                type: 'image_url',
                image_url: { url: attachment.dataUrl },
                filename: attachment.name
            });
        }
        return parts;
    }

    function buildUserMessage(promptText) {
        if (state.attachment) {
            const message = { role: 'user', content: buildContentWithAttachment(promptText, state.attachment) };
            if (state.searchMode !== SEARCH_DEFAULTS.none) {
                message.search = state.searchMode;
            }
            return message;
        }
        const message = { role: 'user', content: promptText };
        if (state.searchMode !== SEARCH_DEFAULTS.none) {
            message.search = state.searchMode;
        }
        return message;
    }

    function stripMessageForApi(message, options = {}) {
        if (!message) return null;
        const { textOnly = false } = options;
        let content = message.content;
        if (textOnly) {
            content = messageText(content);
        }
        if (message.role === 'assistant') {
            if (textOnly || typeof content === 'string') {
                content = stripToolProtocolMarkup(stripThinkBlocks(String(content || '')));
            } else {
                content = stripThinkFromContent(content);
            }
        }
        const sanitized = { role: message.role, content };
        if (message.tool_calls) {
            sanitized.tool_calls = message.tool_calls;
        }
        if (message.tool_results) {
            sanitized.tool_results = message.tool_results;
        }
        if (message.tool_call_id) {
            sanitized.tool_call_id = message.tool_call_id;
        }
        if (message.name) {
            sanitized.name = message.name;
        }
        if (message.search === true) {
            sanitized.search = SEARCH_DEFAULTS.local;
        } else if (message.search === SEARCH_DEFAULTS.local || message.search === SEARCH_DEFAULTS.global) {
            sanitized.search = message.search;
        }
        return sanitized;
    }

    function buildRequestPayload() {
        ensureSystemMessage();
        return {
            model: state.config.model,
            messages: state.messages.map(stripMessageForApi).filter(Boolean),
            stream: true
        };
    }

    function messageText(content) {
        if (typeof content === 'string') return content;
        if (Array.isArray(content)) {
            const textPart = content.find(part => part?.type === 'text');
            return textPart?.text || '';
        }
        if (content && typeof content === 'object' && typeof content.text === 'string') {
            return content.text;
        }
        return '';
    }

    function initialAssistantPlaceholder(message) {
        return message?.search && message.search !== SEARCH_DEFAULTS.none
            ? 'searching for content...'
            : 'waiting for an answer...';
    }

    function inferAttachmentFromContent(content) {
        if (!Array.isArray(content)) return null;
        const mediaPart = content.find(part => part?.type === 'image_url' && part?.image_url?.url);
        if (!mediaPart) return null;
        const dataUrl = String(mediaPart.image_url.url || '');
        const mimeMatch = dataUrl.match(/^data:([^;]+);/i);
        const mime = mimeMatch?.[1] || 'application/octet-stream';
        const name = mediaPart.filename || 'Attachment';
        const kind = mime.startsWith('image/') ? 'image' : 'text';
        return { kind, name, mime, dataUrl };
    }

    function attachmentTextContent(attachment) {
        if (!attachment || attachment.kind !== 'text') return '';
        if (typeof attachment.textContent === 'string' && attachment.textContent) return attachment.textContent;
        if (!attachment.dataUrl || !attachment.dataUrl.startsWith('data:')) return '';
        const base64 = attachment.dataUrl.split(',', 2)[1] || '';
        return base64 ? base64ToUtf8(base64) : '';
    }

    function parseStructuredToolResult(result) {
        const raw = result?.content || result?.function?.content || '';
        if (typeof raw !== 'string' || !raw.trim()) return null;
        try {
            return JSON.parse(raw);
        } catch (err) {
            return null;
        }
    }

    function inferAttachmentFromToolResult(result) {
        const payload = parseStructuredToolResult(result);
        const name = payload?.['search-filename'];
        const base64 = payload?.['search-text-base64'];
        if (!name || !base64) return null;
        return {
            kind: 'text',
            name,
            dataUrl: `data:text/markdown;base64,${base64}`,
            mime: 'text/markdown',
            textContent: base64ToUtf8(base64)
        };
    }

    function messageDisplayText(message) {
        if (!message) return '';
        if (typeof message.display === 'string') return message.display;
        return messageText(message.content);
    }

    function renderConversation(options = {}) {
        const { skipScroll = false } = options;
        closeAttachmentPopover();
        dom.messages.innerHTML = '';
        state.assistantSeen = state.messages.some(m => m.role === 'assistant');
        for (let i = 0; i < state.messages.length; i++) {
            const msg = state.messages[i];
            if (msg.role === 'system' && !state.showSystem) continue;
            appendMessage(msg.role, messageDisplayText(msg), { skipScroll: true, skipVisibilityUpdate: true, messageIndex: i, attachment: inferAttachmentFromContent(msg.content), toolCalls: msg.tool_calls, toolResults: msg.tool_results });
        }
        updateClearChatVisibility();
        updateSystemToggleButton();
        if (!skipScroll && !state.busy) {
            scrollToBottom();
        }
    }

    function normalizeToolCalls(calls) {
        if (!Array.isArray(calls)) return [];
        const stamp = Date.now();
        return calls
            .filter(Boolean)
            .map((call, index) => {
                const fn = call.function || {};
                return {
                    id: call.id || `toolcall_${stamp}_${index}`,
                    type: call.type || 'function',
                    function: {
                        name: fn.name || call.name || 'unknown',
                        arguments: typeof fn.arguments === 'string' ? fn.arguments : (call.arguments || '')
                    }
                };
            });
    }

    function normalizeToolResults(results) {
        if (!Array.isArray(results)) return [];
        const stamp = Date.now();
        return results
            .filter(Boolean)
            .map((result, index) => ({
                id: result.id || result.tool_call_id || `toolres_${stamp}_${index}`,
                tool_call_id: result.tool_call_id || result.id || '',
                name: result.name || result?.function?.name || 'unknown',
                content: typeof result.content === 'string'
                    ? result.content
                    : (result?.function?.content ? String(result.function.content) : '')
            }));
    }

    function appendToolCalls(existing, incoming) {
        const result = Array.isArray(existing) ? [...existing] : [];
        if (!Array.isArray(incoming)) return result;
        for (const call of incoming) {
            if (!call) continue;
            const id = call.id || '';
            if (id && result.some(existingCall => existingCall && existingCall.id === id)) continue;
            if (!id && result.some(existingCall => sameToolCall(existingCall, call))) continue;
            result.push(call);
        }
        return result;
    }

    function mergeToolCalls(existing, deltaCalls) {
        const result = Array.isArray(existing) ? [...existing] : [];
        if (!Array.isArray(deltaCalls)) return result;
        for (const delta of deltaCalls) {
            if (!delta) continue;
            const index = readToolCallIndex(delta);
            if (index === null || index < 0) continue;
            if (!result[index]) {
                result[index] = { id: '', type: delta.type || 'function', function: { name: '', arguments: '' } };
            }
            const target = result[index];
            if (delta.id) target.id = delta.id;
            if (delta.type) target.type = delta.type;
            if (delta.function?.name) target.function.name = delta.function.name;
            if (typeof delta.function?.arguments === 'string' && delta.function.arguments.length > 0) {
                target.function.arguments = (target.function.arguments || '') + delta.function.arguments;
            }
        }
        return result;
    }

    function readToolCallIndex(delta) {
        if (!delta || typeof delta !== 'object' || !Object.prototype.hasOwnProperty.call(delta, 'index')) {
            return null;
        }
        return Number.isInteger(delta.index) ? delta.index : null;
    }

    function formatToolArguments(raw) {
        if (typeof raw !== 'string' || !raw.trim()) return '(no arguments)';
        try {
            return JSON.stringify(JSON.parse(raw), null, 2);
        } catch (err) {
            return raw;
        }
    }

    function createToolCallPanel(call, result, totalCount, index) {
        const panel = document.createElement('div');
        panel.className = 'toolcalls-popover';
        panel.style.right = `${36 + (index * 28)}px`;

        const header = document.createElement('div');
        header.className = 'toolcalls-popover-header';
        header.textContent = `Tool ${index + 1}/${totalCount}`;
        panel.appendChild(header);

        const list = document.createElement('div');
        list.className = 'toolcalls-list';
        const item = document.createElement('div');
        item.className = 'toolcall-item';

        const fnName = call?.function?.name || call?.name || 'unknown';
        const name = document.createElement('div');
        name.className = 'toolcall-name';
        name.textContent = fnName;
        item.appendChild(name);

        const args = document.createElement('pre');
        args.className = 'toolcall-args';
        args.textContent = formatToolArguments(call?.function?.arguments || call?.arguments || '');
        item.appendChild(args);

        if (result) {
            const responseTitle = document.createElement('div');
            responseTitle.className = 'toolcall-result-title';
            responseTitle.textContent = 'Response';
            item.appendChild(responseTitle);

            const attachment = inferAttachmentFromToolResult(result);
            if (attachment) {
                const attachmentContainer = document.createElement('div');
                attachmentContainer.appendChild(createAttachmentChip(attachment));
                item.appendChild(attachmentContainer);
            }

            const responseBody = document.createElement('pre');
            responseBody.className = 'toolcall-result';
            responseBody.textContent = attachment
                ? attachmentTextContent(attachment)
                : formatToolArguments(result?.content || result?.function?.content || '');
            item.appendChild(responseBody);
        }

        list.appendChild(item);
        panel.appendChild(list);
        return panel;
    }

    function persistConversation() {
        const payload = buildRequestPayload();
        writeVfsJson(CHAT_VFS_PATH, payload).catch(err => {
            console.warn('Failed to persist conversation', err);
        });
    }

    async function hydrateConversation() {
        let stored = null;
        try {
            stored = await readVfsJson(CHAT_VFS_PATH);
        } catch (err) {
            console.warn('Failed to parse stored conversation', err);
        }
        if (stored && Array.isArray(stored.messages)) {
            state.messages = stored.messages.map(msg => ({ ...msg }));
            if (stored.model) {
                state.config.model = stored.model;
            }
        }
        ensureSystemMessage();
        renderConversation();
    }

    function formatUserPreview(promptText) {
        return promptText;
    }

    async function handleFileChange(event) {
        const file = event.target.files && event.target.files[0];
        dom.fileInput.value = '';
        if (!file) {
            clearAttachment();
            return;
        }
        try {
            setAttachmentLoading(true);
            const attachment = await buildAttachment(file);
            if (!attachment) {
                appendMessage('system', 'Please upload a PNG/JPG image or a text file (.txt, .md, .tex, or other plain text).');
                clearAttachment();
                return;
            }
            setComposerAttachment(attachment);
        } catch (err) {
            appendMessage('system', `Failed to read file: ${err.message}`);
            clearAttachment();
        } finally {
            setAttachmentLoading(false);
        }
    }

    function readFileAsDataURL(file) {
        return new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.onload = () => resolve(reader.result);
            reader.onerror = () => reject(reader.error);
            reader.readAsDataURL(file);
        });
    }

    function readFileAsText(file) {
        return new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.onload = () => resolve(reader.result);
            reader.onerror = () => reject(reader.error);
            reader.readAsText(file);
        });
    }

    function textToDataUrl(text, mime = 'text/plain') {
        const safeMime = mime || 'text/plain';
        const encoded = btoa(unescape(encodeURIComponent(text || '')));
        return `data:${safeMime};base64,${encoded}`;
    }

    function base64ToUtf8(base64) {
        try {
            return decodeURIComponent(escape(atob(base64)));
        } catch (err) {
            return '';
        }
    }

    function getFileExtension(name) {
        if (!name) return '';
        const dot = name.lastIndexOf('.');
        return dot >= 0 ? name.slice(dot).toLowerCase() : '';
    }

    function isAllowedByMime(mime) {
        if (!mime) return false;
        return ALLOWED_MIME_TYPES.has(mime) || (mime.startsWith('text/') && ALLOWED_MIME_TYPES.has('text/*'));
    }

    function isAllowedByExtension(ext) {
        if (!ext) return false;
        return ALLOWED_EXTENSIONS.has(ext);
    }

    function detectAttachmentKind(mime, ext) {
        const lowerMime = mime || '';
        if (IMAGE_MIME_TYPES.has(lowerMime) || IMAGE_EXTENSIONS.has(ext)) return 'image';
        if (lowerMime.startsWith('text/') || TEXT_MIME_TYPES.has(lowerMime) || TEXT_EXTENSIONS.has(ext)) return 'text';
        return null;
    }

    function formatFileSize(size) {
        if (typeof size !== 'number' || size <= 0) return '';
        const units = ['B', 'KB', 'MB', 'GB'];
        let value = size;
        let unitIndex = 0;
        while (value >= 1024 && unitIndex < units.length - 1) {
            value /= 1024;
            unitIndex++;
        }
        return `${value.toFixed(value >= 10 ? 0 : 1)} ${units[unitIndex]}`;
    }

    function cloneAttachment(src) {
        if (!src) return null;
        return {
            kind: src.kind,
            name: src.name,
            dataUrl: src.dataUrl || null,
            textContent: src.textContent || '',
            mime: src.mime || '',
            size: typeof src.size === 'number' ? src.size : null
        };
    }

    function buildTextPreview(text) {
        const maxChars = 1200;
        const maxLines = 20;
        const lines = (text || '').split(/\r?\n/);
        let snippet = lines.slice(0, maxLines).join('\n');
        let truncated = lines.length > maxLines;
        if (snippet.length > maxChars) {
            snippet = snippet.slice(0, maxChars);
            truncated = true;
        }
        return { snippet, truncated };
    }

    function makePreviewData(attachment) {
        if (!attachment) return null;
        const ext = getFileExtension(attachment.name);
        const isMarkdown = ext === '.md' || ext === '.markdown';
        const isTex = ext === '.tex';
        if (attachment.kind === 'image' && attachment.dataUrl) {
            return {
                kind: 'image',
                name: attachment.name,
                mime: attachment.mime || 'image/*',
                size: attachment.size,
                imageUrl: attachment.dataUrl,
                note: 'Image preview. Click to open larger view.'
            };
        }
        if (attachment.kind === 'text') {
            const { snippet, truncated } = buildTextPreview(attachmentTextContent(attachment));
            return {
                kind: isMarkdown || isTex ? 'markdown' : 'text',
                name: attachment.name,
                mime: attachment.mime || 'text/plain',
                size: attachment.size,
                text: snippet,
                truncated,
                isMarkdown,
                isTex,
                note: truncated ? 'Preview truncated for brevity.' : 'Full text available.'
            };
        }
        return {
            kind: 'unknown',
            name: attachment.name,
            mime: attachment.mime || 'application/octet-stream',
            size: attachment.size,
            note: 'Preview not available. Download to view.'
        };
    }

    let activePopover = null;
    let popoverAnchor = null;
    let hidePopoverTimer = null;
    let activeModal = null;

    function closeAttachmentPopover() {
        if (activePopover && activePopover.parentNode) {
            activePopover.parentNode.removeChild(activePopover);
        }
        activePopover = null;
        popoverAnchor = null;
    }

    function scheduleHidePopover(delay = 120) {
        clearTimeout(hidePopoverTimer);
        hidePopoverTimer = setTimeout(() => {
            closeAttachmentPopover();
        }, delay);
    }

    function createActionButton(icon, label, handler) {
        const btn = document.createElement('button');
        btn.type = 'button';
        btn.className = 'preview-action';
        btn.innerHTML = `<span class="glyphicon ${icon}" aria-hidden="true"></span><span>${label}</span>`;
        btn.addEventListener('click', handler);
        return btn;
    }

    function downloadAttachment(attachment) {
        if (!attachment) return;
        try {
            const name = attachment.name || 'attachment';
            if (attachment.dataUrl) {
                const link = document.createElement('a');
                link.href = attachment.dataUrl;
                link.download = name;
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
                return;
            }
            const text = attachmentTextContent(attachment);
            const blob = new Blob([text], { type: attachment.mime || 'text/plain' });
            const url = URL.createObjectURL(blob);
            const link = document.createElement('a');
            link.href = url;
            link.download = name;
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            URL.revokeObjectURL(url);
        } catch (err) {
            console.warn('Download failed', err);
        }
    }

    async function copyToClipboard(text) {
        try {
            await navigator.clipboard.writeText(text || '');
        } catch (err) {
            console.warn('Clipboard copy failed', err);
        }
    }

    function openInNewTab(attachment) {
        if (!attachment) return;
        if (attachment.kind === 'image' && attachment.dataUrl) {
            const popup = window.open('', '_blank');
            if (!popup) return;
            const safeTitle = escapeHTML(attachment.name || 'Image');
            popup.document.write(`
                <html>
                  <head>
                    <title>${safeTitle}</title>
                    <style>
                      body { margin: 0; display: flex; align-items: center; justify-content: center; background: #111; }
                      img { max-width: 100vw; max-height: 100vh; }
                    </style>
                  </head>
                  <body>
                    <img src="${attachment.dataUrl}" alt="${safeTitle}"/>
                  </body>
                </html>
            `);
            popup.document.close();
        } else if (attachment.kind === 'text') {
            const blob = new Blob([attachmentTextContent(attachment)], { type: attachment.mime || 'text/plain' });
            const url = URL.createObjectURL(blob);
            window.open(url, '_blank');
            setTimeout(() => URL.revokeObjectURL(url), 2000);
        }
    }

    function closeAttachmentModal() {
        if (activeModal && activeModal.parentNode) {
            activeModal.parentNode.removeChild(activeModal);
        }
        activeModal = null;
    }

    function openAttachmentModal(preview, attachment) {
        closeAttachmentModal();
        if (!preview) return;
        const backdrop = document.createElement('div');
        backdrop.className = 'attachment-modal-backdrop';
        backdrop.addEventListener('click', event => {
            if (event.target === backdrop) closeAttachmentModal();
        });

        const modal = document.createElement('div');
        modal.className = 'attachment-modal';

        const header = document.createElement('div');
        header.className = 'modal-header';

        const title = document.createElement('h4');
        title.textContent = preview.name || 'Attachment';
        header.appendChild(title);

        const closeBtn = document.createElement('button');
        closeBtn.type = 'button';
        closeBtn.className = 'close-modal';
        closeBtn.innerHTML = '<span class="glyphicon glyphicon-remove" aria-hidden="true"></span>';
        closeBtn.addEventListener('click', closeAttachmentModal);
        header.appendChild(closeBtn);

        const body = document.createElement('div');
        body.className = 'modal-body';

        if (preview.kind === 'image' && preview.imageUrl) {
            const img = document.createElement('img');
            img.src = preview.imageUrl;
            img.alt = preview.name || 'Attachment image';
            img.style.maxWidth = '100%';
            img.style.display = 'block';
            body.appendChild(img);
        } else {
            const content = attachmentTextContent(attachment) || preview.text || '';
            if (preview.kind === 'markdown' && markdownSupport.enabled) {
                const div = document.createElement('div');
                div.innerHTML = renderMarkdown(content);
                body.appendChild(div);
            } else {
                const pre = document.createElement('pre');
                pre.textContent = content;
                body.appendChild(pre);
            }
        }

        modal.appendChild(header);
        modal.appendChild(body);
        backdrop.appendChild(modal);
        document.body.appendChild(backdrop);
        activeModal = backdrop;

        window.addEventListener('keydown', function escHandler(event) {
            if (event.key === 'Escape') {
                closeAttachmentModal();
                window.removeEventListener('keydown', escHandler);
            }
        }, { once: true });
    }

    function renderPreviewBody(container, preview) {
        if (!container || !preview) return;
        if (preview.kind === 'image' && preview.imageUrl) {
            const img = document.createElement('img');
            img.src = preview.imageUrl;
            img.alt = preview.name || 'Attachment image';
            img.className = 'preview-image';
            container.appendChild(img);
            return;
        }
        const body = document.createElement('div');
        body.className = 'preview-body';
        if (preview.kind === 'markdown' && markdownSupport.enabled) {
            body.innerHTML = renderMarkdown(preview.text || '');
        } else {
            body.textContent = preview.text || 'Preview unavailable.';
        }
        container.appendChild(body);
    }

    function showAttachmentPopover(anchor, attachment) {
        if (!anchor || !attachment) return;
        const preview = makePreviewData(attachment);
        if (!preview) return;
        clearTimeout(hidePopoverTimer);
        closeAttachmentPopover();
        const host = anchor.parentElement || anchor;
        const hostStyle = window.getComputedStyle(host);
        if (hostStyle.position === 'static') {
            host.style.position = 'relative';
        }
        const popover = document.createElement('div');
        popover.className = 'attachment-preview';
        popover.setAttribute('role', 'dialog');
        const title = document.createElement('h5');
        title.textContent = preview.name || 'Attachment';
        popover.appendChild(title);

        const meta = document.createElement('div');
        meta.className = 'meta';
        const parts = [];
        if (preview.mime) parts.push(preview.mime);
        if (preview.size) parts.push(formatFileSize(preview.size));
        meta.textContent = parts.join(' • ');
        popover.appendChild(meta);

        renderPreviewBody(popover, preview);

        const actions = document.createElement('div');
        actions.className = 'actions';
        actions.appendChild(createActionButton('glyphicon-new-window', 'Full preview', () => openAttachmentModal(preview, attachment)));
        actions.appendChild(createActionButton('glyphicon-download', 'Download', () => downloadAttachment(attachment)));
        if (preview.kind === 'image') {
            actions.appendChild(createActionButton('glyphicon-picture', 'Open tab', () => openInNewTab(attachment)));
        }
        if (preview.kind === 'text' || preview.kind === 'markdown') {
            actions.appendChild(createActionButton('glyphicon-copy', 'Copy snippet', () => copyToClipboard(preview.text || '')));
            actions.appendChild(createActionButton('glyphicon-list-alt', 'Copy all', () => copyToClipboard(attachmentTextContent(attachment) || preview.text || '')));
        }
        popover.appendChild(actions);

        if (preview.note) {
            const note = document.createElement('div');
            note.className = 'preview-note';
            note.textContent = preview.note;
            popover.appendChild(note);
        }

        popover.addEventListener('mouseenter', () => clearTimeout(hidePopoverTimer));
        popover.addEventListener('mouseleave', () => scheduleHidePopover());
        host.appendChild(popover);

        const rect = anchor.getBoundingClientRect();
        const viewportMid = window.innerHeight / 2;
        const placeAbove = rect.top > viewportMid;
        if (placeAbove) {
            popover.classList.add('above');
        } else {
            popover.classList.remove('above');
        }

        activePopover = popover;
        popoverAnchor = anchor;
    }

    function setupAttachmentPreviewTrigger(anchor, attachmentProvider) {
        if (!anchor) return;
        const handler = () => {
            const attachment = typeof attachmentProvider === 'function' ? attachmentProvider() : attachmentProvider;
            if (!attachment) return;
            showAttachmentPopover(anchor, attachment);
        };
        anchor.addEventListener('mouseenter', handler);
        anchor.addEventListener('focus', handler);
        anchor.addEventListener('mouseleave', () => scheduleHidePopover());
        anchor.addEventListener('blur', () => scheduleHidePopover());
    }

    function createAttachmentChip(attachment) {
        const chip = document.createElement('div');
        chip.className = 'attachment-chip';
        chip.tabIndex = 0;
        const icon = document.createElement('span');
        const iconClass = attachment?.kind === 'image' ? 'glyphicon-picture' : (attachment?.kind === 'text' ? 'glyphicon-file' : 'glyphicon-paperclip');
        icon.className = `glyphicon ${iconClass}`;
        chip.appendChild(icon);
        const label = document.createElement('span');
        label.className = 'attachment-label';
        label.textContent = attachment?.name || 'Attachment';
        chip.appendChild(label);
        setupAttachmentPreviewTrigger(chip, () => attachment);
        return chip;
    }

    async function buildAttachment(file) {
        const name = file.name || 'attachment';
        const mime = (file.type || '').toLowerCase();
        const ext = getFileExtension(name);
        const allowed = isAllowedByMime(mime) || isAllowedByExtension(ext);
        const kind = detectAttachmentKind(mime, ext);
        if (!allowed || !kind) return null;
        if (kind === 'image') {
            const dataUrl = await readFileAsDataURL(file);
            return { kind: 'image', name, dataUrl, mime, size: file.size };
        }
        if (kind === 'text') {
            const textContent = await readFileAsText(file);
            const dataUrl = textToDataUrl(textContent, mime || 'text/plain');
            return { kind: 'text', name, textContent, dataUrl, mime, size: file.size };
        }
        return null;
    }

    dom.form.addEventListener('submit', async event => {
        event.preventDefault();
        if (state.busy) return;
        const prompt = dom.input.value.trim();
        if (!prompt) return;
        ensureSystemMessage();
        const userMessage = buildUserMessage(prompt);
        // add user message to state immediately so edit/trim is available right away
        const userEntry = { ...userMessage };
        state.messages.push(userEntry);
        const userIndex = state.messages.length - 1;
        const preview = formatUserPreview(prompt);
        state.busy = true;
        dom.sendButton.disabled = true;
        appendMessage('user', preview, { attachment: inferAttachmentFromContent(userEntry.content), messageIndex: userIndex });
        dom.input.value = '';
        clearAttachment();
        resizeComposer();
        const assistantNode = appendMessage('assistant', initialAssistantPlaceholder(userMessage));
        try {
            await streamChat(userMessage, assistantNode, { onFirstToken: showComposer, includeUserInPayload: false, pushUserToState: false, currentUserIndex: userIndex });
        } catch (err) {
            appendMessage('system', `Error: ${err.message}`);
            showComposer();
        } finally {
            state.busy = false;
            dom.sendButton.disabled = false;
            showComposer();
        }
    });

    dom.addFileButton.addEventListener('click', () => {
        if (state.attachment) {
            clearAttachment({ applyDefault: false });
            return;
        }
        if (state.searchMode !== SEARCH_DEFAULTS.none) {
            setSearchModeActive(SEARCH_DEFAULTS.none);
        }
        dom.addFileButton.classList.add('button-active');
        dom.fileInput.click();
        window.setTimeout(() => {
            window.addEventListener('focus', () => {
                if (!state.attachment && !dom.fileInput.value) {
                    dom.addFileButton.classList.remove('button-active');
                }
            }, { once: true });
        }, 0);
    });
    dom.searchButton?.addEventListener('click', () => {
        if (state.searchMode !== SEARCH_DEFAULTS.none) {
            clearAttachment({ applyDefault: false });
            return;
        }
        const mode = state.searchDefault === SEARCH_DEFAULTS.none ? SEARCH_DEFAULTS.local : state.searchDefault;
        setSearchModeActive(mode);
    });
    dom.fileInput.addEventListener('change', handleFileChange);
    dom.clearChatButton?.addEventListener('click', clearChatHistory);
    dom.downloadChatButton?.addEventListener('click', downloadChat);
    dom.uploadChatButton?.addEventListener('click', () => dom.uploadChatInput?.click());
    dom.uploadChatInput?.addEventListener('change', handleUploadChatFile);
    dom.toggleSystemButton?.addEventListener('click', () => {
        state.showSystem = !state.showSystem;
        renderConversation();
    });
    dom.searchDefaultOptions?.addEventListener('change', event => {
        const target = event.target;
        if (!(target instanceof HTMLInputElement)) return;
        if (target.name !== 'searchDefault') return;
        if (!Object.values(SEARCH_OPTIONS).includes(target.value)) return;
        state.searchDefault = target.value;
        updateSearchDefaultSlider();
        persistSearchDefault();
        applySearchDefaultToComposer();
    });
    window.addEventListener('scroll', closeAttachmentPopover);

    dom.input.addEventListener('input', resizeComposer);
    dom.input.addEventListener('input', ensureComposerVisible);
    dom.input.addEventListener('keydown', event => {
        if (event.isComposing) return;
        if (event.key === 'Enter' && !event.shiftKey) {
            event.preventDefault();
            if (typeof dom.form.requestSubmit === 'function') {
                dom.form.requestSubmit(dom.sendButton);
            } else {
                dom.form.dispatchEvent(new Event('submit', { bubbles: true, cancelable: true }));
            }
        }
    });
    dom.composerMain?.addEventListener('dragover', event => {
        event.preventDefault();
    });
    dom.composerMain?.addEventListener('drop', async event => {
        event.preventDefault();
        const file = event.dataTransfer?.files && event.dataTransfer.files[0];
        if (!file) return;
        try {
            setAttachmentLoading(true);
            const attachment = await buildAttachment(file);
            if (!attachment) {
                appendMessage('system', 'Please drop a PNG/JPG image or a text file (.txt, .md, .tex, or other plain text).');
                return;
            }
            setComposerAttachment(attachment);
        } catch (err) {
            appendMessage('system', `Failed to read file: ${err.message}`);
            clearAttachment();
        } finally {
            setAttachmentLoading(false);
        }
    });
    window.addEventListener('resize', resizeComposer);

    async function initializeChat() {
        await loadSearchDefault();
        await hydrateConversation();
        updateSystemToggleButton();
        resizeComposer();
        updateClearChatVisibility();
    }

    initializeChat().catch(err => {
        console.warn('Failed to initialize chat from VFS', err);
        updateSystemToggleButton();
        resizeComposer();
        updateClearChatVisibility();
    });
    </script>

    #%env/templates/footer.template%#
  </body>
</html>