Files
smeta-web/static/chat.html
T
anorandClaude Opus 4.6 398218b8dd fix: кнопка Копировать видна при стриминге (не затирается textContent)
Проблема: aiDiv.textContent = aiText перезаписывал весь контент включая
кнопку. Теперь обновляется только текстовая нода (firstChild).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-24 21:44:31 +10:00

413 lines
16 KiB
HTML
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Сметный ИИ-ассистент</title>
<style>
* { box-sizing: border-box; margin: 0; padding: 0; }
body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; background: #f5f5f5; height: 100vh; display: flex; flex-direction: column; }
/* Login */
#login-screen { display: flex; align-items: center; justify-content: center; height: 100vh; }
#login-form { background: #fff; padding: 2rem; border-radius: 12px; box-shadow: 0 2px 12px rgba(0,0,0,.1); width: 320px; }
#login-form h2 { margin-bottom: 1rem; text-align: center; }
#login-form input { width: 100%; padding: .6rem; margin-bottom: .8rem; border: 1px solid #ddd; border-radius: 6px; font-size: 1rem; }
#login-form button { width: 100%; padding: .7rem; background: #2563eb; color: #fff; border: none; border-radius: 6px; font-size: 1rem; cursor: pointer; }
#login-form button:hover { background: #1d4ed8; }
#login-error { color: #dc2626; font-size: .85rem; margin-bottom: .5rem; display: none; }
/* Chat */
#chat-screen { display: none; flex-direction: column; height: 100vh; }
#header { background: #fff; padding: .6rem 1rem; border-bottom: 1px solid #e5e7eb; display: flex; align-items: center; justify-content: space-between; }
#header h1 { font-size: 1.1rem; font-weight: 600; }
.header-actions { display: flex; gap: .5rem; }
.header-actions button { padding: .3rem .8rem; background: #f3f4f6; border: 1px solid #d1d5db; border-radius: 6px; cursor: pointer; font-size: .8rem; }
.header-actions button:hover { background: #e5e7eb; }
#messages { flex: 1; overflow-y: auto; padding: 1rem; display: flex; flex-direction: column; gap: .6rem; }
.msg { max-width: 80%; padding: .7rem 1rem; border-radius: 12px; line-height: 1.5; white-space: pre-wrap; word-break: break-word; font-size: .95rem; }
.msg-user { align-self: flex-end; background: #2563eb; color: #fff; }
.msg-ai { align-self: flex-start; background: #fff; border: 1px solid #e5e7eb; }
.copy-btn { display: block; margin-top: .4rem; margin-left: auto; background: #f3f4f6; border: 1px solid #d1d5db; border-radius: 4px; cursor: pointer; font-size: .7rem; padding: .2rem .5rem; color: #6b7280; width: fit-content; }
.copy-btn:hover { background: #e5e7eb; }
.msg-user .copy-btn { background: rgba(255,255,255,.2); border-color: rgba(255,255,255,.4); color: rgba(255,255,255,.8); }
.msg-user .copy-btn:hover { background: rgba(255,255,255,.3); }
.copy-btn.copied { background: #d1fae5; border-color: #6ee7b7; color: #065f46; }
.msg-tool { align-self: flex-start; background: #fef3c7; border: 1px solid #fcd34d; font-size: .8rem; font-family: monospace; }
.msg-file { align-self: flex-start; background: #ecfdf5; border: 1px solid #6ee7b7; font-size: .85rem; }
.msg-file a { color: #059669; text-decoration: underline; cursor: pointer; }
.msg-error { align-self: center; background: #fef2f2; border: 1px solid #fca5a5; color: #dc2626; }
.msg-system { align-self: center; background: #f0f9ff; border: 1px solid #93c5fd; font-size: .8rem; color: #1e40af; }
.typing { align-self: flex-start; color: #9ca3af; font-style: italic; font-size: .85rem; }
/* Input */
#input-area { background: #fff; border-top: 1px solid #e5e7eb; padding: .8rem 1rem; }
#drop-zone { border: 2px dashed transparent; border-radius: 8px; transition: border-color .2s; padding: .3rem; }
#drop-zone.dragover { border-color: #2563eb; background: #eff6ff; }
#file-list { display: flex; gap: .3rem; flex-wrap: wrap; margin-bottom: .3rem; }
.file-badge { background: #e0f2fe; padding: .2rem .5rem; border-radius: 4px; font-size: .75rem; display: flex; align-items: center; gap: .3rem; }
.file-badge .remove { cursor: pointer; color: #dc2626; font-weight: bold; }
#input-row { display: flex; gap: .5rem; }
#msg-input { flex: 1; padding: .6rem; border: 1px solid #d1d5db; border-radius: 8px; font-size: 1rem; resize: none; min-height: 42px; max-height: 150px; font-family: inherit; }
#send-btn { padding: .6rem 1.2rem; background: #2563eb; color: #fff; border: none; border-radius: 8px; cursor: pointer; font-size: 1rem; white-space: nowrap; }
#send-btn:disabled { background: #93c5fd; cursor: not-allowed; }
#file-btn { padding: .6rem; background: #f3f4f6; border: 1px solid #d1d5db; border-radius: 8px; cursor: pointer; font-size: 1.1rem; }
</style>
</head>
<body>
<!-- Login Screen -->
<div id="login-screen">
<form id="login-form" onsubmit="return doLogin(event)">
<h2>Сметный ИИ</h2>
<div id="login-error">Неверный логин или пароль</div>
<input type="text" id="login-user" placeholder="Логин" autocomplete="username" required>
<input type="password" id="login-pass" placeholder="Пароль" autocomplete="current-password" required>
<button type="submit">Войти</button>
</form>
</div>
<!-- Chat Screen -->
<div id="chat-screen">
<div id="header">
<h1>Сметный ИИ-ассистент</h1>
<div class="header-actions">
<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>
const API = '';
let token = localStorage.getItem('token');
let pendingFiles = [];
let streaming = false;
// Each tab gets its own session — allows multiple windows
let tabId = sessionStorage.getItem('tabId') || crypto.randomUUID();
sessionStorage.setItem('tabId', tabId);
// --- Init ---
if (token) 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);
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) {
const div = document.createElement('div');
div.className = 'msg msg-' + type;
div.textContent = text;
if (type !== 'system') {
const btn = document.createElement('button');
btn.className = 'copy-btn';
btn.textContent = 'Копировать';
btn.onclick = () => {
const text = div.firstChild ? div.firstChild.textContent.trim() : div.textContent.replace('Копировать', '').trim();
navigator.clipboard.writeText(text);
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', '');
aiDiv._textNode = aiDiv.firstChild; // text node before copy button
}
aiText += data.text;
if (aiDiv._textNode) aiDiv._textNode.textContent = aiText;
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);
else if (m.role === 'assistant') addMsg('ai', m.content);
else if (m.role === 'system') addMsg('system', m.content);
}
} 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>