diff --git a/db.py b/db.py new file mode 100644 index 0000000..6f3aec5 --- /dev/null +++ b/db.py @@ -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] diff --git a/main.py b/main.py index e66065f..adf726d 100644 --- a/main.py +++ b/main.py @@ -16,16 +16,21 @@ from claude_bridge import ( list_user_files, stream_claude, ) +from db import get_history, init_db, list_sessions, save_message app = FastAPI(title="smeta-web") app.mount("/static", StaticFiles(directory="static"), name="static") 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: - """Extract and verify user from Authorization header.""" auth = request.headers.get("authorization", "") token = auth.removeprefix("Bearer ").strip() if not token: @@ -37,7 +42,6 @@ def _get_user(request: Request) -> 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: return body["tab_id"] return request.headers.get("x-tab-id", "default") @@ -60,6 +64,36 @@ async def login(request: Request): 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") async def chat(request: 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)") return StreamingResponse( - stream_claude(message, user, tab_id), + _stream_and_save(message, user, tab_id), media_type="text/event-stream", headers={ "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") async def upload(request: Request, file: UploadFile): user = _get_user(request) @@ -91,18 +138,16 @@ async def upload(request: Request, file: UploadFile): if not safe_name or safe_name.startswith("."): raise HTTPException(400, "Invalid filename") - # #6 HIGH: whitelist file extensions if not is_allowed_file(safe_name): raise HTTPException( 400, 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 = [] total = 0 while True: - chunk = await file.read(1024 * 1024) # 1MB chunks + chunk = await file.read(1024 * 1024) if not chunk: break total += len(chunk) @@ -112,6 +157,7 @@ async def upload(request: Request, file: UploadFile): dest = work_dir / safe_name dest.write_bytes(b"".join(chunks)) + save_message(user, tab_id, "system", f"Загружен файл: {safe_name} ({total} байт)") return {"filename": safe_name, "size": total} diff --git a/static/chat.html b/static/chat.html index 6ac4bfc..b862bf4 100644 --- a/static/chat.html +++ b/static/chat.html @@ -68,6 +68,7 @@ body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-