Add mobile-first web GUI with a server-side session store (SQLite)
- store: a swappable Store trait + bundled-SQLite implementation (WAL,
sessions/messages with per-turn token usage, cascade delete). The standard
/v1 API stays stateless; conversation context lives server-side so
multi-session, statistics and advanced settings can grow on top. DB path
configurable (db_path, default ~/.config/strata-ctl/sessions.db).
- api::sessions: session-aware GUI API — session CRUD, history, POST .../chat
(loads stored context, reuses the completion service, persists new turns with
usage; streaming accumulates the assistant turn and persists before [DONE]),
and /api/stats.
- api::web + web/: a mobile-first chat GUI (vanilla ES modules, no build step),
embedded via rust-embed and served at GET / (same-origin, offline, single
binary). Off-canvas session drawer on phones, persistent sidebar on wide
screens; live streaming with a collapsible thinking panel; model output is
inserted via textContent only.
- router_with_store mounts the GUI + session API only when a store is configured;
router()/router_with_auth() are unchanged (API-only).
- Fix: a global [hidden]{display:none!important} reset so an author display rule
(the stats modal's display:flex) cannot defeat the hidden attribute.
7 new tests (2 store unit + 4 session HTTP end-to-end + 1 config); 94 green +
2 ignored; clippy/fmt clean. Validated live on engine 0.1.67 (context retention,
streaming, stats) and via a browser check (modal, send/render, stats open/close).
Future: the Store backend is intended to move to ArangoDB (multi-model).
This commit is contained in:
1 parent
9e6d44fa1a
commit
1e13caa4ed
15 files changed
+1922
-23
No files matched your search
+369
@@ -0,0 +1,369 @@
|
||||
//! Persistent context store for the web GUI: sessions, messages and token usage.
|
||||
//!
|
||||
//! The standard `/v1` API stays stateless; this is a separate server-side layer
|
||||
//! the GUI uses to hold conversation context across turns and devices. It sits
|
||||
//! behind the [`Store`] trait so the backend can be swapped (e.g. SQLite today,
|
||||
//! Postgres or an analytics DBMS later) without touching the API or the GUI.
|
||||
//!
|
||||
//! Implementations are synchronous and `Send + Sync`; async handlers call them
|
||||
//! through `spawn_blocking` so DB work never blocks the tokio runtime.
|
||||
|
||||
use std::path::Path;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::Mutex;
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use rusqlite::{params, Connection};
|
||||
|
||||
/// A conversation session.
|
||||
#[derive(Debug, Clone, serde::Serialize)]
|
||||
pub struct Session {
|
||||
pub id: String,
|
||||
pub title: String,
|
||||
pub model: String,
|
||||
pub system_prompt: Option<String>,
|
||||
pub created_at: i64,
|
||||
pub updated_at: i64,
|
||||
}
|
||||
|
||||
/// A persisted message (one turn) with its token usage.
|
||||
#[derive(Debug, Clone, serde::Serialize)]
|
||||
pub struct StoredMessage {
|
||||
pub id: i64,
|
||||
pub role: String,
|
||||
pub content: String,
|
||||
pub reasoning_content: Option<String>,
|
||||
pub tool_calls_json: Option<String>,
|
||||
pub prompt_tokens: u32,
|
||||
pub completion_tokens: u32,
|
||||
pub created_at: i64,
|
||||
}
|
||||
|
||||
/// A message to append (borrowed fields; no allocation until persisted).
|
||||
pub struct NewMessage<'a> {
|
||||
pub role: &'a str,
|
||||
pub content: &'a str,
|
||||
pub reasoning_content: Option<&'a str>,
|
||||
pub tool_calls_json: Option<&'a str>,
|
||||
pub prompt_tokens: u32,
|
||||
pub completion_tokens: u32,
|
||||
}
|
||||
|
||||
/// Aggregate counters for the stats view.
|
||||
#[derive(Debug, Clone, Default, serde::Serialize)]
|
||||
pub struct Stats {
|
||||
pub sessions: u64,
|
||||
pub messages: u64,
|
||||
pub prompt_tokens: u64,
|
||||
pub completion_tokens: u64,
|
||||
}
|
||||
|
||||
/// The storage interface. Synchronous; call via `spawn_blocking` from async code.
|
||||
pub trait Store: Send + Sync {
|
||||
fn create_session(
|
||||
&self,
|
||||
title: &str,
|
||||
model: &str,
|
||||
system_prompt: Option<&str>,
|
||||
) -> Result<Session>;
|
||||
fn list_sessions(&self) -> Result<Vec<Session>>;
|
||||
fn get_session(&self, id: &str) -> Result<Option<Session>>;
|
||||
fn rename_session(&self, id: &str, title: &str) -> Result<()>;
|
||||
fn delete_session(&self, id: &str) -> Result<()>;
|
||||
fn messages(&self, session_id: &str) -> Result<Vec<StoredMessage>>;
|
||||
fn append_message(&self, session_id: &str, msg: NewMessage<'_>) -> Result<StoredMessage>;
|
||||
fn stats(&self) -> Result<Stats>;
|
||||
}
|
||||
|
||||
fn now_secs() -> i64 {
|
||||
SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map(|d| d.as_secs() as i64)
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
/// Unique, sortable-enough id without an extra dependency (nanos + counter).
|
||||
fn new_id(prefix: &str) -> String {
|
||||
static COUNTER: AtomicU64 = AtomicU64::new(0);
|
||||
let nanos = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map(|d| d.as_nanos())
|
||||
.unwrap_or(0);
|
||||
let n = COUNTER.fetch_add(1, Ordering::Relaxed);
|
||||
format!("{prefix}_{nanos:016x}{n:08x}")
|
||||
}
|
||||
|
||||
const SCHEMA: &str = "
|
||||
CREATE TABLE IF NOT EXISTS sessions (
|
||||
id TEXT PRIMARY KEY,
|
||||
title TEXT NOT NULL,
|
||||
model TEXT NOT NULL,
|
||||
system_prompt TEXT,
|
||||
created_at INTEGER NOT NULL,
|
||||
updated_at INTEGER NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS messages (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
|
||||
role TEXT NOT NULL,
|
||||
content TEXT NOT NULL,
|
||||
reasoning_content TEXT,
|
||||
tool_calls_json TEXT,
|
||||
prompt_tokens INTEGER NOT NULL DEFAULT 0,
|
||||
completion_tokens INTEGER NOT NULL DEFAULT 0,
|
||||
created_at INTEGER NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_messages_session ON messages(session_id, id);
|
||||
";
|
||||
|
||||
/// SQLite-backed store (bundled SQLite, compiled into the binary). WAL mode for
|
||||
/// concurrent reads; a single mutex serializes writes (already serialized by the
|
||||
/// engine in practice). Replaceable via the [`Store`] trait.
|
||||
pub struct SqliteStore {
|
||||
conn: Mutex<Connection>,
|
||||
}
|
||||
|
||||
impl SqliteStore {
|
||||
/// Open (creating if needed) the database at `path`, initializing the schema.
|
||||
pub fn open(path: &Path) -> Result<Self> {
|
||||
if let Some(parent) = path.parent() {
|
||||
std::fs::create_dir_all(parent)
|
||||
.with_context(|| format!("creating db dir {}", parent.display()))?;
|
||||
}
|
||||
let conn = Connection::open(path)
|
||||
.with_context(|| format!("opening database {}", path.display()))?;
|
||||
Self::init(conn)
|
||||
}
|
||||
|
||||
/// In-memory database (tests).
|
||||
pub fn open_in_memory() -> Result<Self> {
|
||||
Self::init(Connection::open_in_memory()?)
|
||||
}
|
||||
|
||||
fn init(conn: Connection) -> Result<Self> {
|
||||
conn.pragma_update(None, "journal_mode", "WAL")?;
|
||||
conn.pragma_update(None, "synchronous", "NORMAL")?;
|
||||
conn.pragma_update(None, "foreign_keys", "ON")?;
|
||||
conn.execute_batch(SCHEMA)?;
|
||||
Ok(Self {
|
||||
conn: Mutex::new(conn),
|
||||
})
|
||||
}
|
||||
|
||||
fn lock(&self) -> std::sync::MutexGuard<'_, Connection> {
|
||||
self.conn.lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
}
|
||||
|
||||
fn row_to_session(row: &rusqlite::Row<'_>) -> rusqlite::Result<Session> {
|
||||
Ok(Session {
|
||||
id: row.get("id")?,
|
||||
title: row.get("title")?,
|
||||
model: row.get("model")?,
|
||||
system_prompt: row.get("system_prompt")?,
|
||||
created_at: row.get("created_at")?,
|
||||
updated_at: row.get("updated_at")?,
|
||||
})
|
||||
}
|
||||
|
||||
impl Store for SqliteStore {
|
||||
fn create_session(
|
||||
&self,
|
||||
title: &str,
|
||||
model: &str,
|
||||
system_prompt: Option<&str>,
|
||||
) -> Result<Session> {
|
||||
let id = new_id("sess");
|
||||
let now = now_secs();
|
||||
let conn = self.lock();
|
||||
conn.execute(
|
||||
"INSERT INTO sessions (id, title, model, system_prompt, created_at, updated_at)
|
||||
VALUES (?1, ?2, ?3, ?4, ?5, ?5)",
|
||||
params![id, title, model, system_prompt, now],
|
||||
)?;
|
||||
Ok(Session {
|
||||
id,
|
||||
title: title.to_string(),
|
||||
model: model.to_string(),
|
||||
system_prompt: system_prompt.map(str::to_string),
|
||||
created_at: now,
|
||||
updated_at: now,
|
||||
})
|
||||
}
|
||||
|
||||
fn list_sessions(&self) -> Result<Vec<Session>> {
|
||||
let conn = self.lock();
|
||||
let mut stmt =
|
||||
conn.prepare("SELECT * FROM sessions ORDER BY updated_at DESC, created_at DESC")?;
|
||||
let rows = stmt.query_map([], row_to_session)?;
|
||||
Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?)
|
||||
}
|
||||
|
||||
fn get_session(&self, id: &str) -> Result<Option<Session>> {
|
||||
let conn = self.lock();
|
||||
let mut stmt = conn.prepare("SELECT * FROM sessions WHERE id = ?1")?;
|
||||
let mut rows = stmt.query_map(params![id], row_to_session)?;
|
||||
Ok(rows.next().transpose()?)
|
||||
}
|
||||
|
||||
fn rename_session(&self, id: &str, title: &str) -> Result<()> {
|
||||
let conn = self.lock();
|
||||
conn.execute(
|
||||
"UPDATE sessions SET title = ?2, updated_at = ?3 WHERE id = ?1",
|
||||
params![id, title, now_secs()],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn delete_session(&self, id: &str) -> Result<()> {
|
||||
let conn = self.lock();
|
||||
conn.execute("DELETE FROM sessions WHERE id = ?1", params![id])?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn messages(&self, session_id: &str) -> Result<Vec<StoredMessage>> {
|
||||
let conn = self.lock();
|
||||
let mut stmt =
|
||||
conn.prepare("SELECT * FROM messages WHERE session_id = ?1 ORDER BY id ASC")?;
|
||||
let rows = stmt.query_map(params![session_id], |row| {
|
||||
Ok(StoredMessage {
|
||||
id: row.get("id")?,
|
||||
role: row.get("role")?,
|
||||
content: row.get("content")?,
|
||||
reasoning_content: row.get("reasoning_content")?,
|
||||
tool_calls_json: row.get("tool_calls_json")?,
|
||||
prompt_tokens: row.get::<_, i64>("prompt_tokens")? as u32,
|
||||
completion_tokens: row.get::<_, i64>("completion_tokens")? as u32,
|
||||
created_at: row.get("created_at")?,
|
||||
})
|
||||
})?;
|
||||
Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?)
|
||||
}
|
||||
|
||||
fn append_message(&self, session_id: &str, msg: NewMessage<'_>) -> Result<StoredMessage> {
|
||||
let now = now_secs();
|
||||
let conn = self.lock();
|
||||
conn.execute(
|
||||
"INSERT INTO messages
|
||||
(session_id, role, content, reasoning_content, tool_calls_json,
|
||||
prompt_tokens, completion_tokens, created_at)
|
||||
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
|
||||
params![
|
||||
session_id,
|
||||
msg.role,
|
||||
msg.content,
|
||||
msg.reasoning_content,
|
||||
msg.tool_calls_json,
|
||||
msg.prompt_tokens as i64,
|
||||
msg.completion_tokens as i64,
|
||||
now
|
||||
],
|
||||
)?;
|
||||
let id = conn.last_insert_rowid();
|
||||
conn.execute(
|
||||
"UPDATE sessions SET updated_at = ?2 WHERE id = ?1",
|
||||
params![session_id, now],
|
||||
)?;
|
||||
Ok(StoredMessage {
|
||||
id,
|
||||
role: msg.role.to_string(),
|
||||
content: msg.content.to_string(),
|
||||
reasoning_content: msg.reasoning_content.map(str::to_string),
|
||||
tool_calls_json: msg.tool_calls_json.map(str::to_string),
|
||||
prompt_tokens: msg.prompt_tokens,
|
||||
completion_tokens: msg.completion_tokens,
|
||||
created_at: now,
|
||||
})
|
||||
}
|
||||
|
||||
fn stats(&self) -> Result<Stats> {
|
||||
let conn = self.lock();
|
||||
let sessions: i64 = conn.query_row("SELECT COUNT(*) FROM sessions", [], |r| r.get(0))?;
|
||||
let (messages, prompt, completion): (i64, i64, i64) = conn.query_row(
|
||||
"SELECT COUNT(*), COALESCE(SUM(prompt_tokens),0), COALESCE(SUM(completion_tokens),0) FROM messages",
|
||||
[],
|
||||
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
|
||||
)?;
|
||||
Ok(Stats {
|
||||
sessions: sessions as u64,
|
||||
messages: messages as u64,
|
||||
prompt_tokens: prompt as u64,
|
||||
completion_tokens: completion as u64,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn store() -> SqliteStore {
|
||||
SqliteStore::open_in_memory().unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn session_crud_and_message_order() {
|
||||
let s = store();
|
||||
let sess = s
|
||||
.create_session("Chat", "Inkling-2-Mini", Some("be nice"))
|
||||
.unwrap();
|
||||
assert!(sess.id.starts_with("sess_"));
|
||||
assert_eq!(s.list_sessions().unwrap().len(), 1);
|
||||
|
||||
s.append_message(
|
||||
&sess.id,
|
||||
NewMessage {
|
||||
role: "user",
|
||||
content: "ciao",
|
||||
reasoning_content: None,
|
||||
tool_calls_json: None,
|
||||
prompt_tokens: 3,
|
||||
completion_tokens: 0,
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
s.append_message(
|
||||
&sess.id,
|
||||
NewMessage {
|
||||
role: "assistant",
|
||||
content: "ciao!",
|
||||
reasoning_content: Some("think"),
|
||||
tool_calls_json: None,
|
||||
prompt_tokens: 3,
|
||||
completion_tokens: 5,
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let msgs = s.messages(&sess.id).unwrap();
|
||||
assert_eq!(msgs.len(), 2);
|
||||
assert_eq!(msgs[0].role, "user");
|
||||
assert_eq!(msgs[1].content, "ciao!");
|
||||
assert_eq!(msgs[1].reasoning_content.as_deref(), Some("think"));
|
||||
assert_eq!(msgs[1].completion_tokens, 5);
|
||||
|
||||
s.rename_session(&sess.id, "Nuovo titolo").unwrap();
|
||||
assert_eq!(
|
||||
s.get_session(&sess.id).unwrap().unwrap().title,
|
||||
"Nuovo titolo"
|
||||
);
|
||||
|
||||
let stats = s.stats().unwrap();
|
||||
assert_eq!(stats.sessions, 1);
|
||||
assert_eq!(stats.messages, 2);
|
||||
assert_eq!(stats.prompt_tokens, 6);
|
||||
assert_eq!(stats.completion_tokens, 5);
|
||||
|
||||
s.delete_session(&sess.id).unwrap();
|
||||
assert!(s.messages(&sess.id).unwrap().is_empty()); // cascade
|
||||
assert_eq!(s.list_sessions().unwrap().len(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ids_are_unique() {
|
||||
let a = new_id("sess");
|
||||
let b = new_id("sess");
|
||||
assert_ne!(a, b);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user