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:
adm committed 2026-11-24 20:38:24 +01:00
1 parent 9e6d44fa1a
commit 1e13caa4ed
15 files changed
+1922 -23

No files matched your search

+3 -1
View File
@@ -8,10 +8,12 @@ pub mod anthropic;
pub mod formatter;
pub mod routes;
pub mod service;
mod sessions;
pub mod stop;
pub mod types;
mod web;
pub use formatter::{Decoder, Formatter, Piece, Prompt};
pub use routes::{router, router_with_auth, AuthConfig};
pub use routes::{router, router_with_auth, router_with_store, AuthConfig};
pub use service::ChatService;
pub use types::{ChatMessage, ChatRequest, ChatResponse, ModelList, Role};
+67 -9
View File
@@ -10,24 +10,67 @@ use axum::response::{sse::Event, sse::Sse, IntoResponse, Json};
use axum::routing::{get, post};
use axum::Router;
use serde::de::DeserializeOwned;
use std::sync::Arc;
use super::anthropic::{self, AnthropicRequest, AnthropicStream};
use super::service::ChatService;
use super::types::{ApiErrorEnvelope, ChatRequest, ModelCard, ModelList};
use super::{sessions, web};
use crate::store::Store;
/// Build the router. Mount this inside any axum `Router` or serve it directly.
pub fn router(service: ChatService) -> Router {
router_with_auth(service, AuthConfig::default())
}
/// Build the router with optional API-key auth and a Host allowlist.
/// Build the router with optional API-key auth and a Host allowlist (no GUI store).
pub fn router_with_auth(service: ChatService, auth: AuthConfig) -> Router {
Router::new()
build_router(
AppState {
service,
store: None,
},
auth,
)
}
/// Build the router with the session store + web GUI enabled, plus auth.
pub fn router_with_store(service: ChatService, store: Arc<dyn Store>, auth: AuthConfig) -> Router {
build_router(
AppState {
service,
store: Some(store),
},
auth,
)
}
fn build_router(state: AppState, auth: AuthConfig) -> Router {
let mut r = Router::new()
.route("/health", get(health))
.route("/v1/models", get(models))
.route("/v1/chat/completions", post(chat_completions))
.route("/v1/messages", post(messages))
.with_state(AppState { service })
.route("/v1/messages", post(messages));
// The session-aware API and the web GUI exist only when a store is configured.
if state.store.is_some() {
r = r
.route(
"/api/sessions",
get(sessions::list_sessions).post(sessions::create_session),
)
.route(
"/api/sessions/{id}",
get(sessions::get_session)
.delete(sessions::delete_session)
.patch(sessions::rename_session),
)
.route("/api/sessions/{id}/messages", get(sessions::get_messages))
.route("/api/sessions/{id}/chat", post(sessions::session_chat))
.route("/api/stats", get(sessions::stats))
.route("/", get(web::index))
.route("/assets/{*path}", get(web::asset));
}
r.with_state(state)
.layer(axum::middleware::from_fn_with_state(auth, auth_middleware))
}
@@ -110,8 +153,9 @@ async fn auth_middleware(
}
#[derive(Clone)]
struct AppState {
service: ChatService,
pub(crate) struct AppState {
pub(crate) service: ChatService,
pub(crate) store: Option<Arc<dyn Store>>,
}
/// An OpenAI error with the HTTP status the code implies.
@@ -121,12 +165,12 @@ pub struct Error {
}
impl Error {
fn new(status: StatusCode, body: ApiErrorEnvelope) -> Self {
pub(crate) fn new(status: StatusCode, body: ApiErrorEnvelope) -> Self {
Self { status, body }
}
/// Choose a status from the error's `code`; unknown codes are client 400s.
fn from_envelope(env: ApiErrorEnvelope) -> Self {
pub(crate) fn from_envelope(env: ApiErrorEnvelope) -> Self {
let status = match env.error.code.as_deref() {
Some("engine_unavailable") | Some("engine_startup") => StatusCode::SERVICE_UNAVAILABLE,
Some("engine_silent") => StatusCode::GATEWAY_TIMEOUT,
@@ -136,12 +180,26 @@ impl Error {
Self::new(status, env)
}
fn bad_request(msg: impl Into<String>) -> Self {
pub(crate) fn bad_request(msg: impl Into<String>) -> Self {
Self::new(
StatusCode::BAD_REQUEST,
ApiErrorEnvelope::new(msg, "invalid_request_error", None),
)
}
pub(crate) fn not_found(msg: impl Into<String>) -> Self {
Self::new(
StatusCode::NOT_FOUND,
ApiErrorEnvelope::new(msg, "invalid_request_error", Some("not_found".to_string())),
)
}
pub(crate) fn internal(msg: impl Into<String>) -> Self {
Self::new(
StatusCode::INTERNAL_SERVER_ERROR,
ApiErrorEnvelope::new(msg, "server_error", None),
)
}
}
impl IntoResponse for Error {
+380
View File
@@ -0,0 +1,380 @@
//! Session-aware API for the web GUI: `/api/sessions...` and `/api/stats`.
//!
//! The standard `/v1` surface stays stateless; here the server owns the
//! conversation context (via the [`Store`]) so the GUI can be a thin client and
//! so multi-session, statistics and settings can grow on top. The chat endpoint
//! loads a session's history, reuses [`ChatService`] for inference (no duplicated
//! engine-driving), and persists the new turns with their token usage.
use std::collections::BTreeMap;
use std::sync::{Arc, Mutex};
use axum::extract::{Path, State};
use axum::http::StatusCode;
use axum::response::{sse::Event, sse::Sse, IntoResponse, Json};
use futures::StreamExt;
use serde::Deserialize;
use super::routes::{AppState, Error};
use super::types::{ChatChunk, ChatMessage, ChatRequest, FunctionCall, Role, ToolCall, Usage};
use crate::store::{NewMessage, Session, Stats, Store, StoredMessage};
/// Run a synchronous store operation off the async runtime.
async fn with_store<T, F>(st: &AppState, f: F) -> Result<T, Error>
where
F: FnOnce(Arc<dyn Store>) -> anyhow::Result<T> + Send + 'static,
T: Send + 'static,
{
let store = st
.store
.clone()
.ok_or_else(|| Error::internal("no store configured"))?;
tokio::task::spawn_blocking(move || f(store))
.await
.map_err(|e| Error::internal(format!("store task failed: {e}")))?
.map_err(|e| Error::internal(format!("store error: {e}")))
}
#[derive(Deserialize)]
pub(crate) struct CreateSession {
#[serde(default)]
title: Option<String>,
#[serde(default)]
model: Option<String>,
#[serde(default)]
system_prompt: Option<String>,
}
#[derive(Deserialize)]
pub(crate) struct Rename {
title: String,
}
#[derive(Deserialize)]
pub(crate) struct SessionChat {
content: String,
#[serde(default)]
stream: bool,
#[serde(default)]
max_tokens: Option<u32>,
#[serde(default)]
temperature: Option<f64>,
#[serde(default)]
top_p: Option<f64>,
}
pub(crate) async fn create_session(
State(st): State<AppState>,
Json(body): Json<CreateSession>,
) -> Result<Json<Session>, Error> {
let model = body
.model
.unwrap_or_else(|| st.service.model_name().to_string());
let title = body.title.unwrap_or_else(|| "Nuova chat".to_string());
let system = body.system_prompt;
let sess = with_store(&st, move |s| {
s.create_session(&title, &model, system.as_deref())
})
.await?;
Ok(Json(sess))
}
pub(crate) async fn list_sessions(State(st): State<AppState>) -> Result<Json<Vec<Session>>, Error> {
Ok(Json(with_store(&st, |s| s.list_sessions()).await?))
}
pub(crate) async fn get_session(
State(st): State<AppState>,
Path(id): Path<String>,
) -> Result<Json<Session>, Error> {
let sess = with_store(&st, move |s| s.get_session(&id)).await?;
sess.map(Json)
.ok_or_else(|| Error::not_found("session not found"))
}
pub(crate) async fn delete_session(
State(st): State<AppState>,
Path(id): Path<String>,
) -> Result<StatusCode, Error> {
with_store(&st, move |s| s.delete_session(&id)).await?;
Ok(StatusCode::NO_CONTENT)
}
pub(crate) async fn rename_session(
State(st): State<AppState>,
Path(id): Path<String>,
Json(body): Json<Rename>,
) -> Result<StatusCode, Error> {
with_store(&st, move |s| s.rename_session(&id, &body.title)).await?;
Ok(StatusCode::OK)
}
pub(crate) async fn get_messages(
State(st): State<AppState>,
Path(id): Path<String>,
) -> Result<Json<Vec<StoredMessage>>, Error> {
Ok(Json(with_store(&st, move |s| s.messages(&id)).await?))
}
pub(crate) async fn stats(State(st): State<AppState>) -> Result<Json<Stats>, Error> {
Ok(Json(with_store(&st, |s| s.stats()).await?))
}
fn role_of(s: &str) -> Role {
match s {
"system" | "developer" => Role::System,
"assistant" => Role::Assistant,
"tool" => Role::Tool,
_ => Role::User,
}
}
fn text_message(role: Role, text: String) -> ChatMessage {
ChatMessage {
role,
content: Some(serde_json::Value::String(text)),
tool_call_id: None,
tool_calls: None,
name: None,
reasoning_content: None,
}
}
/// Rebuild a stateless [`ChatRequest`] from the stored history plus the new turn.
/// Prior `reasoning_content` is deliberately NOT replayed into the prompt.
fn build_request(sess: &Session, history: &[StoredMessage], body: &SessionChat) -> ChatRequest {
let mut messages = Vec::new();
if let Some(sp) = &sess.system_prompt {
messages.push(text_message(Role::System, sp.clone()));
}
for m in history {
let mut msg = text_message(role_of(&m.role), m.content.clone());
msg.tool_calls = m
.tool_calls_json
.as_deref()
.and_then(|s| serde_json::from_str(s).ok());
messages.push(msg);
}
messages.push(text_message(Role::User, body.content.clone()));
ChatRequest {
model: sess.model.clone(),
messages,
stream: body.stream,
temperature: body.temperature,
top_p: body.top_p,
max_tokens: body.max_tokens,
max_completion_tokens: None,
frequency_penalty: None,
presence_penalty: None,
seed: None,
top_k: None,
min_p: None,
repetition_penalty: None,
stop: None,
tools: None,
tool_choice: None,
}
}
/// Accumulates the assistant turn while streaming, for persistence at the end.
#[derive(Default, Clone)]
struct Accum {
content: String,
reasoning: String,
tools: BTreeMap<u64, ToolCall>,
usage: Option<Usage>,
}
fn accumulate(a: &mut Accum, chunk: &ChatChunk) {
if let Some(u) = &chunk.usage {
a.usage = Some(u.clone());
}
let Some(ch) = chunk.choices.first() else {
return;
};
let d = &ch.delta;
if let Some(c) = &d.content {
a.content.push_str(c);
}
if let Some(r) = &d.reasoning_content {
a.reasoning.push_str(r);
}
if let Some(tc) = &d.tool_calls {
if let Some(arr) = tc.as_array() {
for item in arr {
let idx = item.get("index").and_then(|v| v.as_u64()).unwrap_or(0);
let entry = a.tools.entry(idx).or_insert_with(|| ToolCall {
id: String::new(),
kind: "function".to_string(),
function: FunctionCall {
name: String::new(),
arguments: String::new(),
},
});
if let Some(id) = item.get("id").and_then(|v| v.as_str()) {
if !id.is_empty() {
entry.id = id.to_string();
}
}
if let Some(f) = item.get("function") {
if let Some(n) = f.get("name").and_then(|v| v.as_str()) {
entry.function.name.push_str(n);
}
if let Some(args) = f.get("arguments").and_then(|v| v.as_str()) {
entry.function.arguments.push_str(args);
}
}
}
}
}
}
/// `POST /api/sessions/{id}/chat` — append a user turn, run inference over the
/// stored context, persist the assistant turn (with usage), and reply (SSE when
/// `stream`).
pub(crate) async fn session_chat(
State(st): State<AppState>,
Path(id): Path<String>,
Json(body): Json<SessionChat>,
) -> axum::response::Response {
let store = match st.store.clone() {
Some(s) => s,
None => return Error::internal("no store configured").into_response(),
};
let sess = match with_store(&st, {
let id = id.clone();
move |s| s.get_session(&id)
})
.await
{
Ok(Some(s)) => s,
Ok(None) => return Error::not_found("session not found").into_response(),
Err(e) => return e.into_response(),
};
let history = match with_store(&st, {
let id = id.clone();
move |s| s.messages(&id)
})
.await
{
Ok(h) => h,
Err(e) => return e.into_response(),
};
let req = build_request(&sess, &history, &body);
// Persist the user turn before generating.
let user_content = body.content.clone();
if let Err(e) = with_store(&st, {
let id = id.clone();
move |s| {
s.append_message(
&id,
NewMessage {
role: "user",
content: &user_content,
reasoning_content: None,
tool_calls_json: None,
prompt_tokens: 0,
completion_tokens: 0,
},
)
}
})
.await
{
return e.into_response();
}
if body.stream {
match st.service.stream(&req).await {
Ok((stream, prompt_len)) => {
let acc = Arc::new(Mutex::new(Accum::default()));
let acc_map = acc.clone();
let events = stream.map(move |chunk| {
accumulate(&mut acc_map.lock().unwrap(), &chunk);
match Event::default().json_data(&chunk) {
Ok(ev) => Ok::<_, std::convert::Infallible>(ev),
Err(e) => {
tracing::error!(error = %e, "failed to serialize SSE chunk");
Ok(Event::default().data("{}"))
}
}
});
let acc_end = acc.clone();
let sid = id.clone();
let tail = futures::stream::once(async move {
let a = acc_end.lock().unwrap().clone();
persist_assistant(&store, &sid, &a, prompt_len).await;
Ok::<_, std::convert::Infallible>(Event::default().data("[DONE]"))
});
Sse::new(events.chain(tail))
.keep_alive(
axum::response::sse::KeepAlive::new()
.interval(std::time::Duration::from_secs(10))
.text("ping"),
)
.into_response()
}
Err(env) => Error::from_envelope(env).into_response(),
}
} else {
match st.service.complete(&req).await {
Ok(resp) => {
let msg = &resp.choices[0].message;
let a = Accum {
content: msg.text().unwrap_or("").to_string(),
reasoning: msg.reasoning_content.clone().unwrap_or_default(),
tools: msg
.tool_calls
.clone()
.unwrap_or_default()
.into_iter()
.enumerate()
.map(|(i, t)| (i as u64, t))
.collect(),
usage: Some(resp.usage.clone()),
};
persist_assistant(&store, &id, &a, resp.usage.prompt_tokens).await;
Json(resp).into_response()
}
Err(env) => Error::from_envelope(env).into_response(),
}
}
}
async fn persist_assistant(store: &Arc<dyn Store>, sid: &str, a: &Accum, prompt_len: u32) {
let tool_json = if a.tools.is_empty() {
None
} else {
serde_json::to_string(&a.tools.values().collect::<Vec<_>>()).ok()
};
let (pt, ct) = a
.usage
.as_ref()
.map(|u| (u.prompt_tokens, u.completion_tokens))
.unwrap_or((prompt_len, 0));
let content = a.content.clone();
let reasoning = if a.reasoning.is_empty() {
None
} else {
Some(a.reasoning.clone())
};
let sid = sid.to_string();
let store = store.clone();
let _ = tokio::task::spawn_blocking(move || {
store.append_message(
&sid,
NewMessage {
role: "assistant",
content: &content,
reasoning_content: reasoning.as_deref(),
tool_calls_json: tool_json.as_deref(),
prompt_tokens: pt,
completion_tokens: ct,
},
)
})
.await;
}
+47
View File
@@ -0,0 +1,47 @@
//! Serves the embedded web GUI (`web/`) from the binary via `rust-embed`.
//!
//! Single-binary and offline-capable: assets are compiled into the executable
//! (release) or read from `web/` (debug). Same-origin with the API, so no CORS.
use axum::extract::Path;
use axum::http::{header, StatusCode};
use axum::response::{IntoResponse, Response};
use rust_embed::RustEmbed;
#[derive(RustEmbed)]
#[folder = "web/"]
struct Assets;
/// `GET /` — the GUI shell.
pub(crate) async fn index() -> Response {
serve("index.html")
}
/// `GET /assets/{*path}` — CSS/JS/etc. under `web/assets/`.
pub(crate) async fn asset(Path(path): Path<String>) -> Response {
serve(&format!("assets/{path}"))
}
fn serve(path: &str) -> Response {
match Assets::get(path) {
Some(file) => (
[(header::CONTENT_TYPE, content_type(path))],
file.data.into_owned(),
)
.into_response(),
None => (StatusCode::NOT_FOUND, "not found").into_response(),
}
}
fn content_type(path: &str) -> &'static str {
match path.rsplit('.').next().unwrap_or("") {
"html" => "text/html; charset=utf-8",
"css" => "text/css; charset=utf-8",
"js" => "text/javascript; charset=utf-8",
"svg" => "image/svg+xml",
"png" => "image/png",
"ico" => "image/x-icon",
"json" => "application/json",
_ => "application/octet-stream",
}
}
+24
View File
@@ -96,6 +96,11 @@ pub struct Config {
#[serde(default)]
pub allowed_hosts: Option<Vec<String>>,
/// Path to the GUI session database (SQLite). Defaults to
/// `~/.config/strata-ctl/sessions.db`.
#[serde(default)]
pub db_path: Option<String>,
/// Keys we understand but don't act on yet are NOT listed above, so they
/// arrive here untouched — the "ignore what isn't ours" guarantee.
#[serde(flatten)]
@@ -192,6 +197,15 @@ impl Config {
Duration::from_secs(self.silence_timeout_secs.unwrap_or(600))
}
/// Effective GUI database path: config > `~/.config/strata-ctl/sessions.db`.
pub fn gui_db_path(&self) -> PathBuf {
if let Some(p) = &self.db_path {
return PathBuf::from(p);
}
let home = std::env::var("HOME").unwrap_or_default();
PathBuf::from(home).join(".config/strata-ctl/sessions.db")
}
/// The top-level keys present in the file that we are not acting on —
/// reported by `--check` so the shared-file contract stays visible.
pub fn ignored_keys(&self) -> Vec<&str> {
@@ -337,4 +351,14 @@ mod tests {
assert_eq!(cfg2.startup_timeout(), Duration::from_secs(30));
assert_eq!(cfg2.silence_timeout(), Duration::from_secs(120));
}
#[test]
fn gui_db_path_default_and_override() {
let cfg = Config::parse(REAL, "test").unwrap();
assert!(cfg
.gui_db_path()
.ends_with(".config/strata-ctl/sessions.db"));
let cfg2 = Config::parse(r#"{"exe":"/x/e","db_path":"/tmp/x.db"}"#, "test").unwrap();
assert_eq!(cfg2.gui_db_path(), PathBuf::from("/tmp/x.db"));
}
}
+3 -3
View File
@@ -3,11 +3,11 @@
//! - [`engine`]: spawn `strata --serve` and speak its line protocol.
//! - [`api`]: the OpenAI-compatible HTTP surface (types, formatter seam,
//! completion service, axum routes).
//!
//! Next: the Inkling formatter (chat template + tokenizer), then wiring a
//! binary that reads the existing `strata-inkling.json` and serves.
//! - [`store`]: persistent session/context store for the web GUI (SQLite behind
//! a swappable `Store` trait).
pub mod api;
pub mod config;
pub mod engine;
pub mod inkling;
pub mod store;
+20 -2
View File
@@ -8,10 +8,11 @@ use std::path::Path;
use std::process::ExitCode;
use std::sync::Arc;
use strata_ctl::api::{router_with_auth, AuthConfig, ChatService};
use strata_ctl::api::{router_with_store, AuthConfig, ChatService};
use strata_ctl::config::{Config, ConfigError};
use strata_ctl::engine::Engine;
use strata_ctl::inkling::{ChatTemplate, InklingFormatter, InklingTokenizer};
use strata_ctl::store::{SqliteStore, Store};
const USAGE: &str = "\
strata-ctl — Rust control layer for the Strata engine (OpenAI-compatible API)
@@ -175,7 +176,20 @@ async fn serve(cfg: &Config, cli_host: Option<&str>, cli_port: Option<u16>) -> E
api_key: cfg.api_key.clone(),
allowed_hosts: cfg.allowed_hosts.clone().unwrap_or_default(),
};
let app = router_with_auth(svc, auth);
// Open the GUI session store (SQLite). The web GUI + session API are mounted
// only when this succeeds; the standard /v1 API is unaffected either way.
let db_path = cfg.gui_db_path();
let store: Arc<dyn Store> = match SqliteStore::open(&db_path) {
Ok(s) => Arc::new(s),
Err(e) => {
eprintln!(
"error: cannot open session database {}: {e}",
db_path.display()
);
return ExitCode::FAILURE;
}
};
let app = router_with_store(svc, store, auth);
let host = cfg.bind_host(cli_host);
let port = cfg.bind_port(cli_port);
if !is_loopback_host(&host) && cfg.api_key.is_none() {
@@ -194,6 +208,10 @@ async fn serve(cfg: &Config, cli_host: Option<&str>, cli_port: Option<u16>) -> E
}
};
println!("listening on http://{addr} (Ctrl-C to stop)");
println!(
"web GUI: http://{addr}/ (sessions db: {})",
db_path.display()
);
let shutdown_engine = engine.clone();
let result = axum::serve(listener, app)
+369
View File
@@ -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);
}
}