"""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]