Декодирует JWT payload (base64), показывает кнопку если role=admin. Для обычных users — скрыта. API проверяет role на сервере. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
505 lines
22 KiB
HTML
505 lines
22 KiB
HTML
<!DOCTYPE html>
|
||
<html lang="ru">
|
||
<head>
|
||
<meta charset="UTF-8">
|
||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||
<title>Сметный ИИ-ассистент</title>
|
||
<style>
|
||
:root {
|
||
--bg: #f5f0eb; --bg-card: #ffffff; --bg-input: #ffffff;
|
||
--text: #3a3a3a; --text-muted: #6b6b6b; --text-light: #8b7355;
|
||
--border: #d4c5b2; --border-light: #ede5db;
|
||
--accent: #c4463a; --accent-hover: #a83830; --accent-light: rgba(196,70,58,.08);
|
||
--user-bg: #2c2c2c; --user-text: #ffffff;
|
||
--ai-bg: #ffffff; --ai-border: #ede5db;
|
||
--file-bg: #f5f0eb; --file-border: #d4c5b2;
|
||
--error-bg: #fff1f2; --error-border: #fecdd3;
|
||
--system-bg: #f5f0eb; --system-text: #8b7355;
|
||
--shadow-sm: 0 1px 3px rgba(0,0,0,.05);
|
||
--shadow-md: 0 4px 16px rgba(0,0,0,.07);
|
||
--radius: 10px; --radius-lg: 16px;
|
||
}
|
||
|
||
* { box-sizing: border-box; margin: 0; padding: 0; }
|
||
body { font-family: 'Inter', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; background: var(--bg); height: 100vh; display: flex; flex-direction: column; color: var(--text); -webkit-font-smoothing: antialiased; }
|
||
|
||
/* Login */
|
||
#login-screen { display: flex; align-items: center; justify-content: center; height: 100vh; background: linear-gradient(135deg, #f5f0eb 0%, #ede5db 100%); }
|
||
#login-form { background: var(--bg-card); padding: 2.5rem 2rem; border-radius: var(--radius-lg); box-shadow: var(--shadow-md); width: 340px; }
|
||
#login-form h2 { margin-bottom: .3rem; text-align: center; font-size: 1.4rem; font-weight: 700; color: var(--text); }
|
||
#login-form .subtitle { text-align: center; color: var(--text-muted); font-size: .85rem; margin-bottom: 1.5rem; display: block; }
|
||
#login-form input { width: 100%; padding: .7rem .9rem; margin-bottom: .7rem; border: 1.5px solid var(--border); border-radius: var(--radius); font-size: .95rem; transition: border-color .2s; outline: none; background: var(--bg); }
|
||
#login-form input:focus { border-color: var(--accent); background: var(--bg-card); }
|
||
#login-form button { width: 100%; padding: .75rem; background: var(--accent); color: #fff; border: none; border-radius: var(--radius); font-size: .95rem; font-weight: 600; cursor: pointer; transition: background .2s; margin-top: .3rem; }
|
||
#login-form button:hover { background: var(--accent-hover); }
|
||
#login-error { color: #e03131; font-size: .8rem; margin-bottom: .5rem; display: none; text-align: center; }
|
||
|
||
/* Chat */
|
||
#chat-screen { display: none; flex-direction: column; height: 100vh; }
|
||
#header { background: var(--bg-card); padding: .7rem 1.2rem; border-bottom: 1px solid var(--border); display: flex; align-items: center; justify-content: space-between; box-shadow: var(--shadow-sm); }
|
||
#header h1 { font-size: 1rem; font-weight: 600; color: var(--text); letter-spacing: -.01em; }
|
||
.header-actions { display: flex; gap: .4rem; }
|
||
.header-actions button { padding: .35rem .75rem; background: transparent; border: 1.5px solid var(--border); border-radius: var(--radius); cursor: pointer; font-size: .78rem; color: var(--text-muted); font-weight: 500; transition: all .15s; }
|
||
.header-actions button:hover { background: var(--bg); border-color: var(--accent); color: var(--accent); }
|
||
|
||
#messages { flex: 1; overflow-y: auto; padding: 1.2rem 1rem; display: flex; flex-direction: column; gap: .7rem; max-width: 900px; width: 100%; margin: 0 auto; }
|
||
.msg { max-width: 85%; padding: .8rem 1.1rem; border-radius: var(--radius-lg); line-height: 1.6; white-space: pre-wrap; word-break: break-word; font-size: .9rem; box-shadow: var(--shadow-sm); position: relative; }
|
||
.msg-time { display: block; font-size: .65rem; color: var(--text-muted, #999); margin-bottom: .3rem; opacity: .7; }
|
||
.msg-user { align-self: flex-end; background: var(--user-bg); color: var(--user-text); border-bottom-right-radius: 4px; }
|
||
.msg-ai { align-self: flex-start; background: var(--ai-bg); border: 1px solid var(--ai-border); border-bottom-left-radius: 4px; }
|
||
|
||
.copy-btn { display: block; margin-top: .5rem; margin-left: auto; background: transparent; border: 1px solid var(--border); border-radius: 6px; cursor: pointer; font-size: .7rem; padding: .2rem .6rem; color: var(--text-light); width: fit-content; transition: all .15s; }
|
||
.copy-btn:hover { background: var(--bg); color: var(--text-muted); border-color: var(--text-light); }
|
||
.msg-user .copy-btn { border-color: rgba(255,255,255,.25); color: rgba(255,255,255,.6); }
|
||
.msg-user .copy-btn:hover { background: rgba(255,255,255,.15); color: rgba(255,255,255,.9); }
|
||
.copy-btn.copied { background: #d3f9d8; border-color: #69db7c; color: #2b8a3e; }
|
||
|
||
.msg-tool { align-self: flex-start; background: #fffbeb; border: 1px solid #fde68a; font-size: .78rem; font-family: 'SF Mono', Menlo, monospace; color: #92400e; box-shadow: none; }
|
||
.msg-file { align-self: flex-start; background: var(--file-bg); border: 1px solid var(--file-border); font-size: .85rem; }
|
||
.msg-file a { color: #16a34a; text-decoration: none; font-weight: 500; }
|
||
.msg-file a:hover { text-decoration: underline; }
|
||
.msg-error { align-self: center; background: var(--error-bg); border: 1px solid var(--error-border); color: #e03131; font-size: .85rem; box-shadow: none; }
|
||
.msg-system { align-self: center; background: var(--system-bg); border: none; font-size: .8rem; color: var(--system-text); box-shadow: none; padding: .4rem .8rem; }
|
||
.typing { align-self: flex-start; color: var(--text-light); font-style: italic; font-size: .85rem; padding: .4rem 0; }
|
||
|
||
/* Markdown rendered content */
|
||
.msg-ai { white-space: normal; }
|
||
.msg-ai h1, .msg-ai h2, .msg-ai h3, .msg-ai h4 { margin: .6rem 0 .3rem; font-size: .95rem; font-weight: 700; color: var(--text); }
|
||
.msg-ai h2 { font-size: 1rem; }
|
||
.msg-ai h3 { font-size: .95rem; }
|
||
.msg-ai h4 { font-size: .9rem; color: var(--text-muted); }
|
||
.msg-ai p { margin: .3rem 0; }
|
||
.msg-ai ul, .msg-ai ol { margin: .3rem 0 .3rem 1.2rem; }
|
||
.msg-ai li { margin: .15rem 0; }
|
||
.msg-ai strong { font-weight: 600; }
|
||
.msg-ai hr { border: none; border-top: 1px solid var(--border-light); margin: .6rem 0; }
|
||
.msg-ai table { border-collapse: collapse; margin: .4rem 0; font-size: .85rem; width: 100%; }
|
||
.msg-ai th, .msg-ai td { border: 1px solid var(--border); padding: .3rem .5rem; text-align: left; }
|
||
.msg-ai th { background: var(--bg); font-weight: 600; }
|
||
.msg-ai code { background: #f5f0eb; padding: .1rem .3rem; border-radius: 3px; font-size: .85em; font-family: 'SF Mono', Menlo, monospace; }
|
||
.msg-ai pre { background: #2c2c2c; color: #f5f0eb; padding: .6rem; border-radius: 6px; overflow-x: auto; margin: .4rem 0; }
|
||
.msg-ai pre code { background: none; padding: 0; color: inherit; }
|
||
.msg-ai blockquote { border-left: 3px solid var(--accent); padding-left: .8rem; color: var(--text-muted); margin: .3rem 0; }
|
||
|
||
/* Input */
|
||
#input-area { background: var(--bg-card); border-top: 1px solid var(--border); padding: .8rem 1rem; box-shadow: 0 -2px 8px rgba(0,0,0,.03); }
|
||
#input-area > div { max-width: 900px; margin: 0 auto; }
|
||
#drop-zone { border: 2px dashed transparent; border-radius: var(--radius); transition: all .2s; padding: .3rem; }
|
||
#drop-zone.dragover { border-color: var(--accent); background: var(--accent-light); }
|
||
#file-list { display: flex; gap: .3rem; flex-wrap: wrap; margin-bottom: .3rem; }
|
||
.file-badge { background: #ede5db; color: #2c2c2c; padding: .25rem .6rem; border-radius: 6px; font-size: .75rem; display: flex; align-items: center; gap: .3rem; font-weight: 500; }
|
||
.file-badge .remove { cursor: pointer; color: #e03131; font-weight: bold; }
|
||
#input-row { display: flex; gap: .5rem; align-items: flex-end; }
|
||
#msg-input { flex: 1; padding: .65rem .9rem; border: 1.5px solid var(--border); border-radius: var(--radius); font-size: .95rem; resize: none; min-height: 44px; max-height: 150px; font-family: inherit; outline: none; transition: border-color .2s; background: var(--bg); }
|
||
#msg-input:focus { border-color: var(--accent); background: var(--bg-card); }
|
||
#send-btn { padding: .65rem 1.3rem; background: var(--accent); color: #fff; border: none; border-radius: var(--radius); cursor: pointer; font-size: .95rem; font-weight: 600; white-space: nowrap; transition: background .15s; }
|
||
#send-btn:hover { background: var(--accent-hover); }
|
||
#send-btn:disabled { background: #d4c5b2; cursor: not-allowed; }
|
||
#file-btn { padding: .65rem .7rem; background: var(--bg); border: 1.5px solid var(--border); border-radius: var(--radius); cursor: pointer; font-size: 1.1rem; transition: all .15s; }
|
||
#file-btn:hover { border-color: var(--accent); background: var(--accent-light); }
|
||
</style>
|
||
</head>
|
||
<body>
|
||
|
||
<!-- Login Screen -->
|
||
<div id="login-screen">
|
||
<form id="login-form" onsubmit="return doLogin(event)">
|
||
<h2>Сметный ИИ</h2>
|
||
<span class="subtitle">Профессиональный ассистент</span>
|
||
<div id="login-error">Неверный логин или пароль</div>
|
||
<input type="text" id="login-user" placeholder="Email или логин" autocomplete="username" required>
|
||
<input type="password" id="login-pass" placeholder="Пароль" autocomplete="current-password" required>
|
||
<button type="submit">Войти</button>
|
||
<p style="text-align:center;margin-top:.8rem;font-size:.85rem;color:var(--text-muted)">Нет аккаунта? Попросите приглашение у администратора</p>
|
||
</form>
|
||
</div>
|
||
|
||
<!-- Chat Screen -->
|
||
<div id="chat-screen">
|
||
<div id="header">
|
||
<h1>Сметный ИИ-ассистент</h1>
|
||
<div class="header-actions">
|
||
<button id="btn-admin" style="display:none" onclick="window.open('/admin','_blank')">Админ</button>
|
||
<button onclick="window.open('/batch3','_blank')">Пакетная</button>
|
||
<button onclick="showSessions()">История</button>
|
||
<button onclick="resetSession()">Новый диалог</button>
|
||
<button onclick="listFiles()">Файлы</button>
|
||
<button onclick="logout()">Выйти</button>
|
||
</div>
|
||
</div>
|
||
|
||
<div id="messages"></div>
|
||
|
||
<div id="input-area">
|
||
<div id="drop-zone">
|
||
<div id="file-list"></div>
|
||
<div id="input-row">
|
||
<button id="file-btn" onclick="document.getElementById('file-input').click()" title="Прикрепить файл">📎</button>
|
||
<textarea id="msg-input" placeholder="Напишите сообщение..." rows="1" onkeydown="handleKey(event)"></textarea>
|
||
<button id="send-btn" onclick="sendMessage()">Отправить</button>
|
||
</div>
|
||
</div>
|
||
<input type="file" id="file-input" multiple hidden onchange="handleFiles(this.files)">
|
||
</div>
|
||
</div>
|
||
|
||
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
|
||
<script>
|
||
// Configure marked for safe rendering
|
||
if (typeof marked !== 'undefined') {
|
||
marked.setOptions({ breaks: true, gfm: true });
|
||
}
|
||
|
||
function renderMarkdown(text) {
|
||
if (typeof marked !== 'undefined') {
|
||
try { return marked.parse(text); } catch(e) {}
|
||
}
|
||
return text.replace(/</g, '<').replace(/\n/g, '<br>');
|
||
}
|
||
|
||
const API = '';
|
||
let token = localStorage.getItem('token');
|
||
let pendingFiles = [];
|
||
let streaming = false;
|
||
// Each tab gets its own session — allows multiple windows
|
||
// Support ?tab=UUID to open specific session
|
||
const urlTab = new URLSearchParams(window.location.search).get('tab');
|
||
let tabId = urlTab || sessionStorage.getItem('tabId') || crypto.randomUUID();
|
||
sessionStorage.setItem('tabId', tabId);
|
||
|
||
function checkAdmin() {
|
||
try {
|
||
if (!token) return;
|
||
const payload = JSON.parse(atob(token.split('.')[1]));
|
||
if (payload.role === 'admin') {
|
||
document.getElementById('btn-admin').style.display = '';
|
||
}
|
||
} catch(e) {}
|
||
}
|
||
|
||
// --- Init ---
|
||
if (token) { checkAdmin(); showChat(); } else showLogin();
|
||
|
||
function showLogin() {
|
||
document.getElementById('login-screen').style.display = 'flex';
|
||
document.getElementById('chat-screen').style.display = 'none';
|
||
}
|
||
function showChat() {
|
||
document.getElementById('login-screen').style.display = 'none';
|
||
document.getElementById('chat-screen').style.display = 'flex';
|
||
document.getElementById('msg-input').focus();
|
||
loadHistory();
|
||
}
|
||
|
||
// --- Auth ---
|
||
async function doLogin(e) {
|
||
e.preventDefault();
|
||
const user = document.getElementById('login-user').value;
|
||
const pass = document.getElementById('login-pass').value;
|
||
try {
|
||
const r = await fetch(API + '/api/login', {
|
||
method: 'POST',
|
||
headers: {'Content-Type': 'application/json'},
|
||
body: JSON.stringify({username: user, password: pass})
|
||
});
|
||
if (!r.ok) throw new Error();
|
||
const data = await r.json();
|
||
token = data.token;
|
||
localStorage.setItem('token', token);
|
||
checkAdmin();
|
||
showChat();
|
||
addMsg('system', 'Добро пожаловать! Напишите вопрос или прикрепите файл.');
|
||
} catch {
|
||
document.getElementById('login-error').style.display = 'block';
|
||
}
|
||
return false;
|
||
}
|
||
function logout() {
|
||
token = null;
|
||
localStorage.removeItem('token');
|
||
showLogin();
|
||
}
|
||
function authHeaders() {
|
||
return {'Authorization': 'Bearer ' + token, 'X-Tab-Id': tabId};
|
||
}
|
||
|
||
// --- Messages ---
|
||
const msgs = document.getElementById('messages');
|
||
function addMsg(type, text, ts) {
|
||
const div = document.createElement('div');
|
||
div.className = 'msg msg-' + type;
|
||
// Timestamp
|
||
const time = document.createElement('span');
|
||
time.className = 'msg-time';
|
||
const d = ts ? new Date(ts < 1e12 ? ts * 1000 : ts) : new Date();
|
||
time.textContent = d.toLocaleString('ru-RU', {day:'2-digit',month:'2-digit',year:'2-digit',hour:'2-digit',minute:'2-digit'});
|
||
div.appendChild(time);
|
||
// Store raw text for copy and streaming
|
||
div._rawText = text;
|
||
if (type === 'ai') {
|
||
div.innerHTML = renderMarkdown(text);
|
||
div.prepend(time);
|
||
} else {
|
||
div.textContent = text;
|
||
div.prepend(time);
|
||
}
|
||
if (type !== 'system') {
|
||
const btn = document.createElement('button');
|
||
btn.className = 'copy-btn';
|
||
btn.textContent = 'Копировать';
|
||
btn.onclick = () => {
|
||
navigator.clipboard.writeText(div._rawText || div.textContent);
|
||
btn.textContent = 'Скопировано';
|
||
btn.classList.add('copied');
|
||
setTimeout(() => { btn.textContent = 'Копировать'; btn.classList.remove('copied'); }, 1500);
|
||
};
|
||
div.appendChild(btn);
|
||
}
|
||
msgs.appendChild(div);
|
||
msgs.scrollTop = msgs.scrollHeight;
|
||
return div;
|
||
}
|
||
function addTyping() {
|
||
const div = document.createElement('div');
|
||
div.className = 'typing';
|
||
div.id = 'typing-indicator';
|
||
div.textContent = 'Claude думает...';
|
||
msgs.appendChild(div);
|
||
msgs.scrollTop = msgs.scrollHeight;
|
||
return div;
|
||
}
|
||
function removeTyping() {
|
||
const el = document.getElementById('typing-indicator');
|
||
if (el) el.remove();
|
||
}
|
||
|
||
// --- File Upload ---
|
||
const dropZone = document.getElementById('drop-zone');
|
||
dropZone.addEventListener('dragover', e => { e.preventDefault(); dropZone.classList.add('dragover'); });
|
||
dropZone.addEventListener('dragleave', () => dropZone.classList.remove('dragover'));
|
||
dropZone.addEventListener('drop', e => {
|
||
e.preventDefault();
|
||
dropZone.classList.remove('dragover');
|
||
handleFiles(e.dataTransfer.files);
|
||
});
|
||
|
||
function handleFiles(fileList) {
|
||
for (const f of fileList) pendingFiles.push(f);
|
||
renderFileList();
|
||
}
|
||
function renderFileList() {
|
||
const fl = document.getElementById('file-list');
|
||
fl.innerHTML = '';
|
||
pendingFiles.forEach((f, i) => {
|
||
const badge = document.createElement('span');
|
||
badge.className = 'file-badge';
|
||
badge.textContent = f.name + ' ';
|
||
const rm = document.createElement('span');
|
||
rm.className = 'remove';
|
||
rm.textContent = '×';
|
||
rm.onclick = () => removeFile(i);
|
||
badge.appendChild(rm);
|
||
fl.appendChild(badge);
|
||
});
|
||
}
|
||
function removeFile(i) { pendingFiles.splice(i, 1); renderFileList(); }
|
||
|
||
async function uploadFiles() {
|
||
const uploaded = [];
|
||
for (const f of pendingFiles) {
|
||
const fd = new FormData();
|
||
fd.append('file', f);
|
||
const r = await fetch(API + '/api/upload', {
|
||
method: 'POST',
|
||
headers: authHeaders(),
|
||
body: fd,
|
||
});
|
||
if (r.ok) {
|
||
const data = await r.json();
|
||
uploaded.push(data.filename);
|
||
}
|
||
}
|
||
pendingFiles = [];
|
||
renderFileList();
|
||
return uploaded;
|
||
}
|
||
|
||
// --- Send Message ---
|
||
function handleKey(e) {
|
||
if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); sendMessage(); }
|
||
}
|
||
|
||
async function sendMessage() {
|
||
if (streaming) return;
|
||
const input = document.getElementById('msg-input');
|
||
let text = input.value.trim();
|
||
if (!text && pendingFiles.length === 0) return;
|
||
|
||
// Upload files first
|
||
let uploaded = [];
|
||
if (pendingFiles.length > 0) {
|
||
uploaded = await uploadFiles();
|
||
if (uploaded.length > 0) {
|
||
const fileNote = 'Загружены файлы: ' + uploaded.join(', ');
|
||
addMsg('file', fileNote);
|
||
if (!text) text = 'Я загрузил файлы: ' + uploaded.join(', ') + '. Покажи их содержимое.';
|
||
else text = 'Файлы в рабочей директории: ' + uploaded.join(', ') + '\n\n' + text;
|
||
}
|
||
}
|
||
|
||
addMsg('user', text);
|
||
input.value = '';
|
||
input.style.height = 'auto';
|
||
|
||
streaming = true;
|
||
document.getElementById('send-btn').disabled = true;
|
||
addTyping();
|
||
|
||
try {
|
||
const r = await fetch(API + '/api/chat', {
|
||
method: 'POST',
|
||
headers: {...authHeaders(), 'Content-Type': 'application/json'},
|
||
body: JSON.stringify({message: text}),
|
||
});
|
||
|
||
if (r.status === 401) { logout(); return; }
|
||
if (!r.ok) { addMsg('error', 'Ошибка: ' + r.status); return; }
|
||
|
||
removeTyping();
|
||
let aiDiv = null;
|
||
let aiText = '';
|
||
const reader = r.body.getReader();
|
||
const decoder = new TextDecoder();
|
||
let buffer = '';
|
||
|
||
while (true) {
|
||
const {done, value} = await reader.read();
|
||
if (done) break;
|
||
buffer += decoder.decode(value, {stream: true});
|
||
|
||
const lines = buffer.split('\n');
|
||
buffer = lines.pop();
|
||
|
||
let eventType = '';
|
||
for (const line of lines) {
|
||
if (line.startsWith('event: ')) {
|
||
eventType = line.slice(7);
|
||
} else if (line.startsWith('data: ')) {
|
||
const data = JSON.parse(line.slice(6));
|
||
if (eventType === 'text') {
|
||
if (!aiDiv) {
|
||
aiDiv = addMsg('ai', '');
|
||
}
|
||
aiText += data.text;
|
||
aiDiv._rawText = aiText;
|
||
// Re-render markdown (keep time + copy button)
|
||
const copyBtn = aiDiv.querySelector('.copy-btn');
|
||
const timeEl = aiDiv.querySelector('.msg-time');
|
||
aiDiv.innerHTML = renderMarkdown(aiText);
|
||
if (timeEl) aiDiv.prepend(timeEl);
|
||
if (copyBtn) aiDiv.appendChild(copyBtn);
|
||
msgs.scrollTop = msgs.scrollHeight;
|
||
} else if (eventType === 'tool') {
|
||
// Show minimal status, not raw code
|
||
const toolNames = {Bash: 'Выполняю...', Read: 'Читаю файл...', Write: 'Создаю файл...', Edit: 'Редактирую...', Glob: 'Ищу файлы...', Grep: 'Ищу в файлах...'};
|
||
const label = toolNames[data.tool] || 'Обрабатываю...';
|
||
removeTyping();
|
||
addTyping().textContent = label;
|
||
} else if (eventType === 'done') {
|
||
removeTyping();
|
||
// Always show final result if we haven't shown text yet
|
||
if (!aiText && data.result) {
|
||
aiDiv = addMsg('ai', data.result);
|
||
}
|
||
}
|
||
eventType = '';
|
||
}
|
||
}
|
||
}
|
||
if (!aiDiv && !aiText) addMsg('ai', '(пустой ответ)');
|
||
|
||
} catch (err) {
|
||
removeTyping();
|
||
addMsg('error', 'Ошибка соединения: ' + err.message);
|
||
} finally {
|
||
streaming = false;
|
||
document.getElementById('send-btn').disabled = false;
|
||
input.focus();
|
||
}
|
||
}
|
||
|
||
// --- Session ---
|
||
async function resetSession() {
|
||
// Create new tab = new session, old one stays in DB
|
||
tabId = crypto.randomUUID();
|
||
sessionStorage.setItem('tabId', tabId);
|
||
msgs.innerHTML = '';
|
||
addMsg('system', 'Новый диалог начат.');
|
||
}
|
||
|
||
async function listFiles() {
|
||
const r = await fetch(API + '/api/files', {headers: authHeaders()});
|
||
if (!r.ok) return;
|
||
const files = await r.json();
|
||
if (files.length === 0) { addMsg('system', 'Файлов нет.'); return; }
|
||
const list = files.map(f => {
|
||
const kb = (f.size / 1024).toFixed(1);
|
||
return f.name + ' (' + kb + ' KB)';
|
||
}).join('\n');
|
||
const div = addMsg('file', 'Файлы в рабочей директории:\n' + list);
|
||
// Add download links
|
||
files.forEach(f => {
|
||
const a = document.createElement('a');
|
||
a.textContent = ' [скачать ' + f.name + ']';
|
||
a.href = API + '/api/files/' + encodeURIComponent(f.name);
|
||
a.onclick = e => {
|
||
e.preventDefault();
|
||
fetch(a.href, {headers: authHeaders()})
|
||
.then(r => r.blob())
|
||
.then(b => { const u = URL.createObjectURL(b); const l = document.createElement('a'); l.href = u; l.download = f.name; l.click(); });
|
||
};
|
||
div.appendChild(a);
|
||
});
|
||
}
|
||
|
||
// --- History ---
|
||
async function loadHistory() {
|
||
try {
|
||
const r = await fetch(API + '/api/history', {headers: authHeaders()});
|
||
if (!r.ok) return;
|
||
const history = await r.json();
|
||
if (history.length === 0) return;
|
||
msgs.innerHTML = '';
|
||
for (const m of history) {
|
||
if (m.role === 'user') addMsg('user', m.content, m.timestamp);
|
||
else if (m.role === 'assistant') addMsg('ai', m.content, m.timestamp);
|
||
else if (m.role === 'system') addMsg('system', m.content, m.timestamp);
|
||
}
|
||
} catch {}
|
||
}
|
||
|
||
async function showSessions() {
|
||
try {
|
||
const r = await fetch(API + '/api/sessions', {headers: authHeaders()});
|
||
if (!r.ok) return;
|
||
const sessions = await r.json();
|
||
if (sessions.length === 0) { addMsg('system', 'Нет сохранённых диалогов.'); return; }
|
||
let text = 'Прошлые диалоги:\n\n';
|
||
sessions.forEach((s, i) => {
|
||
const date = new Date(s.last_ts * 1000).toLocaleString('ru');
|
||
const preview = (s.last_question || '').slice(0, 60);
|
||
text += (i + 1) + '. ' + date + ' (' + s.msg_count + ' сообщ.) — ' + preview + '\n';
|
||
});
|
||
addMsg('system', text);
|
||
} catch {}
|
||
}
|
||
|
||
// Auto-resize textarea
|
||
document.getElementById('msg-input').addEventListener('input', function() {
|
||
this.style.height = 'auto';
|
||
this.style.height = Math.min(this.scrollHeight, 150) + 'px';
|
||
});
|
||
</script>
|
||
</body>
|
||
</html>
|