feat: история диалогов — SQLite + UI
- db.py: SQLite хранилище (messages таблица) - Все сообщения (user/assistant/system) сохраняются на диск - GET /api/history — история текущей вкладки - GET /api/sessions — список всех диалогов с превью - UI: история загружается при обновлении страницы - UI: кнопка "История" показывает прошлые диалоги - "Новый диалог" создаёт новый tabId (старый остаётся в БД) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,66 @@
|
|||||||
|
"""SQLite storage for chat history."""
|
||||||
|
|
||||||
|
import os
|
||||||
|
import sqlite3
|
||||||
|
import time
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
DB_PATH = Path(os.environ.get("DB_PATH", "./smeta-web.db"))
|
||||||
|
|
||||||
|
_CREATE = """
|
||||||
|
CREATE TABLE IF NOT EXISTS messages (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
session_id TEXT NOT NULL,
|
||||||
|
username TEXT NOT NULL,
|
||||||
|
tab_id TEXT NOT NULL,
|
||||||
|
role TEXT NOT NULL,
|
||||||
|
content TEXT NOT NULL,
|
||||||
|
timestamp REAL NOT NULL
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_session ON messages(username, tab_id);
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
def _conn() -> sqlite3.Connection:
|
||||||
|
conn = sqlite3.connect(str(DB_PATH))
|
||||||
|
conn.row_factory = sqlite3.Row
|
||||||
|
return conn
|
||||||
|
|
||||||
|
|
||||||
|
def init_db():
|
||||||
|
with _conn() as conn:
|
||||||
|
conn.executescript(_CREATE)
|
||||||
|
|
||||||
|
|
||||||
|
def save_message(username: str, tab_id: str, role: str, content: str):
|
||||||
|
"""Save a user or assistant message."""
|
||||||
|
with _conn() as conn:
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO messages (session_id, username, tab_id, role, content, timestamp) "
|
||||||
|
"VALUES (?, ?, ?, ?, ?, ?)",
|
||||||
|
(f"{username}/{tab_id}", username, tab_id, role, content, time.time()),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def get_history(username: str, tab_id: str, limit: int = 100) -> list[dict]:
|
||||||
|
"""Get chat history for a specific tab."""
|
||||||
|
with _conn() as conn:
|
||||||
|
rows = conn.execute(
|
||||||
|
"SELECT role, content, timestamp FROM messages "
|
||||||
|
"WHERE username = ? AND tab_id = ? ORDER BY id DESC LIMIT ?",
|
||||||
|
(username, tab_id, limit),
|
||||||
|
).fetchall()
|
||||||
|
return [dict(r) for r in reversed(rows)]
|
||||||
|
|
||||||
|
|
||||||
|
def list_sessions(username: str) -> list[dict]:
|
||||||
|
"""List all chat sessions for a user with last message preview."""
|
||||||
|
with _conn() as conn:
|
||||||
|
rows = conn.execute(
|
||||||
|
"SELECT tab_id, MAX(timestamp) as last_ts, COUNT(*) as msg_count, "
|
||||||
|
"(SELECT content FROM messages m2 WHERE m2.username = messages.username "
|
||||||
|
" AND m2.tab_id = messages.tab_id AND m2.role = 'user' ORDER BY m2.id DESC LIMIT 1) as last_question "
|
||||||
|
"FROM messages WHERE username = ? GROUP BY tab_id ORDER BY last_ts DESC",
|
||||||
|
(username,),
|
||||||
|
).fetchall()
|
||||||
|
return [dict(r) for r in rows]
|
||||||
@@ -16,16 +16,21 @@ from claude_bridge import (
|
|||||||
list_user_files,
|
list_user_files,
|
||||||
stream_claude,
|
stream_claude,
|
||||||
)
|
)
|
||||||
|
from db import get_history, init_db, list_sessions, save_message
|
||||||
|
|
||||||
app = FastAPI(title="smeta-web")
|
app = FastAPI(title="smeta-web")
|
||||||
app.mount("/static", StaticFiles(directory="static"), name="static")
|
app.mount("/static", StaticFiles(directory="static"), name="static")
|
||||||
|
|
||||||
MAX_UPLOAD_SIZE = 50 * 1024 * 1024 # 50 MB
|
MAX_UPLOAD_SIZE = 50 * 1024 * 1024 # 50 MB
|
||||||
MAX_MESSAGE_LEN = 10_000 # #14 DoS: limit prompt length
|
MAX_MESSAGE_LEN = 10_000
|
||||||
|
|
||||||
|
|
||||||
|
@app.on_event("startup")
|
||||||
|
async def startup():
|
||||||
|
init_db()
|
||||||
|
|
||||||
|
|
||||||
def _get_user(request: Request) -> str:
|
def _get_user(request: Request) -> str:
|
||||||
"""Extract and verify user from Authorization header."""
|
|
||||||
auth = request.headers.get("authorization", "")
|
auth = request.headers.get("authorization", "")
|
||||||
token = auth.removeprefix("Bearer ").strip()
|
token = auth.removeprefix("Bearer ").strip()
|
||||||
if not token:
|
if not token:
|
||||||
@@ -37,7 +42,6 @@ def _get_user(request: Request) -> str:
|
|||||||
|
|
||||||
|
|
||||||
def _get_tab(request: Request, body: dict | None = None) -> str:
|
def _get_tab(request: Request, body: dict | None = None) -> str:
|
||||||
"""Extract tab_id from request header or body."""
|
|
||||||
if body and "tab_id" in body:
|
if body and "tab_id" in body:
|
||||||
return body["tab_id"]
|
return body["tab_id"]
|
||||||
return request.headers.get("x-tab-id", "default")
|
return request.headers.get("x-tab-id", "default")
|
||||||
@@ -60,6 +64,36 @@ async def login(request: Request):
|
|||||||
return {"token": token, "username": username}
|
return {"token": token, "username": username}
|
||||||
|
|
||||||
|
|
||||||
|
async def _stream_and_save(message: str, user: str, tab_id: str):
|
||||||
|
"""Wrap stream_claude to save messages to DB."""
|
||||||
|
save_message(user, tab_id, "user", message)
|
||||||
|
full_response = ""
|
||||||
|
async for chunk in stream_claude(message, user, tab_id):
|
||||||
|
yield chunk
|
||||||
|
# Collect text for saving
|
||||||
|
if "event: text" in chunk:
|
||||||
|
import json
|
||||||
|
for line in chunk.split("\n"):
|
||||||
|
if line.startswith("data: "):
|
||||||
|
try:
|
||||||
|
d = json.loads(line[6:])
|
||||||
|
full_response += d.get("text", "")
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
elif "event: done" in chunk:
|
||||||
|
import json
|
||||||
|
for line in chunk.split("\n"):
|
||||||
|
if line.startswith("data: "):
|
||||||
|
try:
|
||||||
|
d = json.loads(line[6:])
|
||||||
|
if not full_response and d.get("result"):
|
||||||
|
full_response = d["result"]
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
if full_response:
|
||||||
|
save_message(user, tab_id, "assistant", full_response)
|
||||||
|
|
||||||
|
|
||||||
@app.post("/api/chat")
|
@app.post("/api/chat")
|
||||||
async def chat(request: Request):
|
async def chat(request: Request):
|
||||||
user = _get_user(request)
|
user = _get_user(request)
|
||||||
@@ -72,7 +106,7 @@ async def chat(request: Request):
|
|||||||
raise HTTPException(400, f"Message too long (max {MAX_MESSAGE_LEN} chars)")
|
raise HTTPException(400, f"Message too long (max {MAX_MESSAGE_LEN} chars)")
|
||||||
|
|
||||||
return StreamingResponse(
|
return StreamingResponse(
|
||||||
stream_claude(message, user, tab_id),
|
_stream_and_save(message, user, tab_id),
|
||||||
media_type="text/event-stream",
|
media_type="text/event-stream",
|
||||||
headers={
|
headers={
|
||||||
"Cache-Control": "no-cache",
|
"Cache-Control": "no-cache",
|
||||||
@@ -81,6 +115,19 @@ async def chat(request: Request):
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/history")
|
||||||
|
async def history(request: Request):
|
||||||
|
user = _get_user(request)
|
||||||
|
tab_id = request.headers.get("x-tab-id", "default")
|
||||||
|
return get_history(user, tab_id)
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/api/sessions")
|
||||||
|
async def sessions(request: Request):
|
||||||
|
user = _get_user(request)
|
||||||
|
return list_sessions(user)
|
||||||
|
|
||||||
|
|
||||||
@app.post("/api/upload")
|
@app.post("/api/upload")
|
||||||
async def upload(request: Request, file: UploadFile):
|
async def upload(request: Request, file: UploadFile):
|
||||||
user = _get_user(request)
|
user = _get_user(request)
|
||||||
@@ -91,18 +138,16 @@ async def upload(request: Request, file: UploadFile):
|
|||||||
if not safe_name or safe_name.startswith("."):
|
if not safe_name or safe_name.startswith("."):
|
||||||
raise HTTPException(400, "Invalid filename")
|
raise HTTPException(400, "Invalid filename")
|
||||||
|
|
||||||
# #6 HIGH: whitelist file extensions
|
|
||||||
if not is_allowed_file(safe_name):
|
if not is_allowed_file(safe_name):
|
||||||
raise HTTPException(
|
raise HTTPException(
|
||||||
400,
|
400,
|
||||||
f"File type not allowed. Allowed: xlsx, docx, pdf, csv, txt, xml, json, yaml",
|
f"File type not allowed. Allowed: xlsx, docx, pdf, csv, txt, xml, json, yaml",
|
||||||
)
|
)
|
||||||
|
|
||||||
# #15: read in chunks to avoid OOM on huge files
|
|
||||||
chunks = []
|
chunks = []
|
||||||
total = 0
|
total = 0
|
||||||
while True:
|
while True:
|
||||||
chunk = await file.read(1024 * 1024) # 1MB chunks
|
chunk = await file.read(1024 * 1024)
|
||||||
if not chunk:
|
if not chunk:
|
||||||
break
|
break
|
||||||
total += len(chunk)
|
total += len(chunk)
|
||||||
@@ -112,6 +157,7 @@ async def upload(request: Request, file: UploadFile):
|
|||||||
|
|
||||||
dest = work_dir / safe_name
|
dest = work_dir / safe_name
|
||||||
dest.write_bytes(b"".join(chunks))
|
dest.write_bytes(b"".join(chunks))
|
||||||
|
save_message(user, tab_id, "system", f"Загружен файл: {safe_name} ({total} байт)")
|
||||||
return {"filename": safe_name, "size": total}
|
return {"filename": safe_name, "size": total}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
+38
-2
@@ -68,6 +68,7 @@ body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-
|
|||||||
<div id="header">
|
<div id="header">
|
||||||
<h1>Сметный ИИ-ассистент</h1>
|
<h1>Сметный ИИ-ассистент</h1>
|
||||||
<div class="header-actions">
|
<div class="header-actions">
|
||||||
|
<button onclick="showSessions()">История</button>
|
||||||
<button onclick="resetSession()">Новый диалог</button>
|
<button onclick="resetSession()">Новый диалог</button>
|
||||||
<button onclick="listFiles()">Файлы</button>
|
<button onclick="listFiles()">Файлы</button>
|
||||||
<button onclick="logout()">Выйти</button>
|
<button onclick="logout()">Выйти</button>
|
||||||
@@ -95,7 +96,7 @@ let token = localStorage.getItem('token');
|
|||||||
let pendingFiles = [];
|
let pendingFiles = [];
|
||||||
let streaming = false;
|
let streaming = false;
|
||||||
// Each tab gets its own session — allows multiple windows
|
// Each tab gets its own session — allows multiple windows
|
||||||
const tabId = sessionStorage.getItem('tabId') || crypto.randomUUID();
|
let tabId = sessionStorage.getItem('tabId') || crypto.randomUUID();
|
||||||
sessionStorage.setItem('tabId', tabId);
|
sessionStorage.setItem('tabId', tabId);
|
||||||
|
|
||||||
// --- Init ---
|
// --- Init ---
|
||||||
@@ -109,6 +110,7 @@ function showChat() {
|
|||||||
document.getElementById('login-screen').style.display = 'none';
|
document.getElementById('login-screen').style.display = 'none';
|
||||||
document.getElementById('chat-screen').style.display = 'flex';
|
document.getElementById('chat-screen').style.display = 'flex';
|
||||||
document.getElementById('msg-input').focus();
|
document.getElementById('msg-input').focus();
|
||||||
|
loadHistory();
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- Auth ---
|
// --- Auth ---
|
||||||
@@ -315,7 +317,9 @@ async function sendMessage() {
|
|||||||
|
|
||||||
// --- Session ---
|
// --- Session ---
|
||||||
async function resetSession() {
|
async function resetSession() {
|
||||||
await fetch(API + '/api/reset', {method: 'POST', headers: {...authHeaders(), 'Content-Type': 'application/json'}, body: '{}'});
|
// Create new tab = new session, old one stays in DB
|
||||||
|
tabId = crypto.randomUUID();
|
||||||
|
sessionStorage.setItem('tabId', tabId);
|
||||||
msgs.innerHTML = '';
|
msgs.innerHTML = '';
|
||||||
addMsg('system', 'Новый диалог начат.');
|
addMsg('system', 'Новый диалог начат.');
|
||||||
}
|
}
|
||||||
@@ -345,6 +349,38 @@ async function listFiles() {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// --- 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
|
// Auto-resize textarea
|
||||||
document.getElementById('msg-input').addEventListener('input', function() {
|
document.getElementById('msg-input').addEventListener('input', function() {
|
||||||
this.style.height = 'auto';
|
this.style.height = 'auto';
|
||||||
|
|||||||
Reference in New Issue
Block a user