Files
strata-ctl/src/store.rs
T
adm a4722b7379 Add context compositor: named sections from SQLite + DIALOG region
The model context is now composed by a dedicated module (src/context.rs) from named sections wrapped in <NAME>...</NAME>. Static sections (SYSTEM_PROMPT, TOOL_USE) live in a new context_sections SQLite table (seeded once, editable/extensible without recompiling); SYSTEM_PROMPT injects identity/speaker-note/session-SP via placeholders. DIALOG wraps the real role messages (history + new turn) with opener/closer markers so the engine keeps turn structure. Provenance/time helpers moved into the compositor; build_request now only assembles sampling. +tests (140 green), clippy/fmt clean; live probe confirms the model sees the sections.
2026-11-25 21:40:31 +01:00

923 lines
34 KiB
Rust

//! 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,
//! ArangoDB 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};
use serde::{Deserialize, Serialize};
/// A session's own settings instance. Global defaults are only a *template*:
/// each session receives a copy at creation (copy-on-create) and owns it
/// independently. Editing the globals affects only future sessions; editing a
/// session affects only that session. At runtime the session uses its own
/// snapshot — there is no live layering.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct SessionSettings {
#[serde(default)]
pub system_prompt: Option<String>,
/// Free-form user notes describing the purpose of this chat.
#[serde(default)]
pub notes: Option<String>,
/// The human speaker's name, shown to the model in per-turn [SPEAKER: …]
/// tags. Global-authoritative: read live from the global defaults at turn
/// time (the per-session copy is inert), so it applies to every chat.
/// Absent/empty -> "User".
#[serde(default)]
pub user_name: Option<String>,
#[serde(default)]
pub temperature: Option<f64>,
#[serde(default)]
pub top_p: Option<f64>,
#[serde(default)]
pub top_k: Option<u32>,
#[serde(default)]
pub min_p: Option<f64>,
#[serde(default)]
pub repetition_penalty: Option<f64>,
#[serde(default)]
pub frequency_penalty: Option<f64>,
#[serde(default)]
pub presence_penalty: Option<f64>,
#[serde(default)]
pub max_tokens: Option<u32>,
#[serde(default)]
pub seed: Option<u64>,
}
impl SessionSettings {
/// Apply `self`'s set fields on top of `base` (a `Some` value wins). Used to
/// snapshot the global defaults into a new session, applying any overrides
/// supplied at creation.
pub fn overlay(&self, base: &SessionSettings) -> SessionSettings {
SessionSettings {
system_prompt: self.system_prompt.clone().or(base.system_prompt.clone()),
notes: self.notes.clone().or(base.notes.clone()),
user_name: self.user_name.clone().or(base.user_name.clone()),
temperature: self.temperature.or(base.temperature),
top_p: self.top_p.or(base.top_p),
top_k: self.top_k.or(base.top_k),
min_p: self.min_p.or(base.min_p),
repetition_penalty: self.repetition_penalty.or(base.repetition_penalty),
frequency_penalty: self.frequency_penalty.or(base.frequency_penalty),
presence_penalty: self.presence_penalty.or(base.presence_penalty),
max_tokens: self.max_tokens.or(base.max_tokens),
seed: self.seed.or(base.seed),
}
}
}
/// A conversation session.
#[derive(Debug, Clone, Serialize)]
pub struct Session {
pub id: String,
pub title: String,
pub model: String,
pub settings: SessionSettings,
/// Once the first message is sent the name becomes immutable (it is the
/// agent's identity and names its personal folder).
pub name_locked: bool,
/// Personal workspace folder, created at the first interaction (None until then).
pub folder: Option<String>,
pub created_at: i64,
pub updated_at: i64,
}
/// A persisted message (one turn) with its token usage.
#[derive(Debug, Clone, 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 tool_call_id: 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 tool_call_id: Option<&'a str>,
pub prompt_tokens: u32,
pub completion_tokens: u32,
}
/// Aggregate counters for the stats view, computed over the whole persistent
/// history (the advantage over an in-memory request monitor). The live engine
/// gauge is layered on top by the API handler, not stored here.
#[derive(Debug, Clone, Default, Serialize)]
pub struct Stats {
pub sessions: u64,
pub messages: u64,
pub prompt_tokens: u64,
pub completion_tokens: u64,
pub total_tokens: u64,
/// Tool calls requested across all assistant turns (agent activity).
pub tool_calls: u64,
/// Per-session breakdown, busiest (most tokens) first.
pub by_session: Vec<SessionStat>,
/// Token activity per UTC day, oldest first (bounded to recent days).
pub daily: Vec<DailyStat>,
}
/// One session's share of the persistent totals.
#[derive(Debug, Clone, Serialize)]
pub struct SessionStat {
pub id: String,
pub title: String,
pub messages: u64,
pub prompt_tokens: u64,
pub completion_tokens: u64,
pub updated_at: i64,
}
/// One UTC day's activity (`day` = unix seconds at midnight).
#[derive(Debug, Clone, Serialize)]
pub struct DailyStat {
pub day: i64,
pub messages: u64,
pub prompt_tokens: u64,
pub completion_tokens: u64,
}
/// Metadata for an uploaded file (bytes live on disk under the shared upload dir).
#[derive(Debug, Clone, Serialize)]
pub struct UploadMeta {
/// Stored filename (uuid + extension), unique; resolves the on-disk path.
pub id: String,
pub original_name: String,
pub path: String,
/// "image" | "text" | "binary" — decided by content sniff, not extension.
pub kind: String,
/// Token count for text (0 otherwise), measured with the model tokenizer.
pub tokens: u32,
pub size: u64,
pub created_at: i64,
}
/// One named, ordered section of the model context whose STATIC template lives
/// in the store (editable without recompiling). Rendered wrapped in
/// `<name>…</name>`; placeholders ({identity}, {speaker_note}, {session_prompt})
/// are filled per request. The dynamic DIALOG region is not a stored section.
#[derive(Debug, Clone, Serialize)]
pub struct ContextSection {
pub name: String,
pub content: String,
pub position: i64,
}
/// Bootstrap templates for the static context sections (seeded once into SQLite;
/// the DB rows are the source of truth afterwards).
const SYSTEM_PROMPT_SECTION: &str = "{identity}{speaker_note}\n{session_prompt}";
const TOOL_USE_SECTION: &str = "Strumenti: shell_exec(command, cwd?, timeout?) esegue un comando shell nell'ambiente host e restituisce stdout/stderr ed exit code; la cartella predefinita è la tua cartella personale. Usalo per ispezionare o modificare file e per verificare i risultati invece di inventarli. Fai riferimento alle dichiarazioni dei tool fornite per gli argomenti esatti.";
/// The storage interface. Synchronous; call via `spawn_blocking` from async code.
pub trait Store: Send + Sync {
fn create_session(
&self,
title: &str,
model: &str,
settings: &SessionSettings,
) -> 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 update_settings(&self, id: &str, settings: &SessionSettings) -> Result<()>;
fn set_name_locked(&self, id: &str, locked: bool) -> Result<()>;
fn set_folder(&self, id: &str, folder: &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>;
/// The global default settings template (None until seeded).
fn get_defaults(&self) -> Result<Option<SessionSettings>>;
fn set_defaults(&self, settings: &SessionSettings) -> Result<()>;
/// The static context sections, ordered (SYSTEM_PROMPT, TOOL_USE, ...).
fn context_sections(&self) -> Result<Vec<ContextSection>>;
fn set_context_section(&self, name: &str, content: &str, position: i64) -> Result<()>;
fn save_upload(&self, meta: &UploadMeta) -> Result<()>;
fn get_upload(&self, id: &str) -> Result<Option<UploadMeta>>;
}
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,
settings_json TEXT,
name_locked INTEGER NOT NULL DEFAULT 0,
folder 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,
tool_call_id 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);
CREATE TABLE IF NOT EXISTS defaults (
id INTEGER PRIMARY KEY CHECK (id = 1),
settings_json TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS uploads (
id TEXT PRIMARY KEY,
original_name TEXT NOT NULL,
path TEXT NOT NULL,
kind TEXT NOT NULL,
tokens INTEGER NOT NULL DEFAULT 0,
size INTEGER NOT NULL DEFAULT 0,
created_at INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS context_sections (
name TEXT PRIMARY KEY,
content TEXT NOT NULL,
position INTEGER NOT NULL
);
";
/// 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)?;
migrate(&conn)?;
seed_context_sections(&conn)?;
Ok(Self {
conn: Mutex::new(conn),
})
}
fn lock(&self) -> std::sync::MutexGuard<'_, Connection> {
self.conn.lock().unwrap_or_else(|e| e.into_inner())
}
}
/// Idempotent schema migrations for databases created by older versions.
/// `CREATE TABLE IF NOT EXISTS` never alters an existing table, so new columns
/// must be added explicitly when missing.
fn migrate(conn: &Connection) -> Result<()> {
let has_col = |table: &str, col: &str| -> Result<bool> {
let n: i64 = conn
.prepare(&format!(
"SELECT COUNT(*) FROM pragma_table_info('{table}') WHERE name = '{col}'"
))?
.query_row([], |r| r.get(0))?;
Ok(n > 0)
};
if !has_col("messages", "tool_call_id")? {
conn.execute_batch("ALTER TABLE messages ADD COLUMN tool_call_id TEXT;")?;
}
if !has_col("sessions", "settings_json")? {
conn.execute_batch("ALTER TABLE sessions ADD COLUMN settings_json TEXT;")?;
// Backfill existing sessions: their settings instance is just the old
// system_prompt column (everything else defaults).
conn.execute_batch(
"UPDATE sessions SET settings_json = json_object('system_prompt', system_prompt)
WHERE settings_json IS NULL;",
)?;
}
if !has_col("sessions", "name_locked")? {
conn.execute_batch(
"ALTER TABLE sessions ADD COLUMN name_locked INTEGER NOT NULL DEFAULT 0;",
)?;
}
if !has_col("sessions", "folder")? {
conn.execute_batch("ALTER TABLE sessions ADD COLUMN folder TEXT;")?;
}
Ok(())
}
/// Seed the static context sections once (idempotent); afterwards the stored
/// rows are authoritative and editable.
fn seed_context_sections(conn: &Connection) -> Result<()> {
conn.execute(
"INSERT OR IGNORE INTO context_sections (name, content, position) VALUES ('SYSTEM_PROMPT', ?1, 0)",
params![SYSTEM_PROMPT_SECTION],
)?;
conn.execute(
"INSERT OR IGNORE INTO context_sections (name, content, position) VALUES ('TOOL_USE', ?1, 1)",
params![TOOL_USE_SECTION],
)?;
Ok(())
}
fn row_to_session(row: &rusqlite::Row<'_>) -> rusqlite::Result<Session> {
let settings_json: Option<String> = row.get("settings_json")?;
let settings = match settings_json {
Some(s) if !s.is_empty() => serde_json::from_str(&s).unwrap_or_default(),
_ => {
let sp: Option<String> = row.get("system_prompt")?;
SessionSettings {
system_prompt: sp,
..Default::default()
}
}
};
Ok(Session {
id: row.get("id")?,
title: row.get("title")?,
model: row.get("model")?,
settings,
name_locked: row.get::<_, i64>("name_locked")? != 0,
folder: row.get("folder")?,
created_at: row.get("created_at")?,
updated_at: row.get("updated_at")?,
})
}
impl Store for SqliteStore {
fn create_session(
&self,
title: &str,
model: &str,
settings: &SessionSettings,
) -> Result<Session> {
let id = new_id("sess");
let now = now_secs();
let settings_json = serde_json::to_string(settings)?;
let conn = self.lock();
conn.execute(
"INSERT INTO sessions (id, title, model, settings_json, name_locked, created_at, updated_at)
VALUES (?1, ?2, ?3, ?4, 0, ?5, ?5)",
params![id, title, model, settings_json, now],
)?;
Ok(Session {
id,
title: title.to_string(),
model: model.to_string(),
settings: settings.clone(),
name_locked: false,
folder: None,
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 update_settings(&self, id: &str, settings: &SessionSettings) -> Result<()> {
let settings_json = serde_json::to_string(settings)?;
let conn = self.lock();
conn.execute(
"UPDATE sessions SET settings_json = ?2, updated_at = ?3 WHERE id = ?1",
params![id, settings_json, now_secs()],
)?;
Ok(())
}
fn set_name_locked(&self, id: &str, locked: bool) -> Result<()> {
let conn = self.lock();
conn.execute(
"UPDATE sessions SET name_locked = ?2 WHERE id = ?1",
params![id, locked as i64],
)?;
Ok(())
}
fn set_folder(&self, id: &str, folder: &str) -> Result<()> {
let conn = self.lock();
conn.execute(
"UPDATE sessions SET folder = ?2 WHERE id = ?1",
params![id, folder],
)?;
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")?,
tool_call_id: row.get("tool_call_id")?,
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,
tool_call_id, prompt_tokens, completion_tokens, created_at)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)",
params![
session_id,
msg.role,
msg.content,
msg.reasoning_content,
msg.tool_calls_json,
msg.tool_call_id,
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),
tool_call_id: msg.tool_call_id.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))?;
// Totals + tool-call count in one pass. tool_calls_json is always a JSON
// array of calls (or NULL); json_array_length counts the calls themselves.
let (messages, prompt, completion, tool_calls): (i64, i64, i64, i64) = conn.query_row(
"SELECT COUNT(*),
COALESCE(SUM(prompt_tokens),0),
COALESCE(SUM(completion_tokens),0),
COALESCE(SUM(CASE WHEN tool_calls_json IS NOT NULL
THEN json_array_length(tool_calls_json) ELSE 0 END),0)
FROM messages",
[],
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?)),
)?;
// Per-session breakdown (LEFT JOIN keeps empty sessions visible), busiest first.
let mut stmt = conn.prepare(
"SELECT s.id, s.title, COUNT(m.id),
COALESCE(SUM(m.prompt_tokens),0), COALESCE(SUM(m.completion_tokens),0),
s.updated_at
FROM sessions s LEFT JOIN messages m ON m.session_id = s.id
GROUP BY s.id
ORDER BY (COALESCE(SUM(m.prompt_tokens),0)+COALESCE(SUM(m.completion_tokens),0)) DESC,
s.updated_at DESC",
)?;
let by_session = stmt
.query_map([], |r| {
Ok(SessionStat {
id: r.get(0)?,
title: r.get(1)?,
messages: r.get::<_, i64>(2)? as u64,
prompt_tokens: r.get::<_, i64>(3)? as u64,
completion_tokens: r.get::<_, i64>(4)? as u64,
updated_at: r.get(5)?,
})
})?
.collect::<rusqlite::Result<Vec<_>>>()?;
// Daily activity (UTC day buckets): the 30 most recent active days, oldest first.
let mut stmt = conn.prepare(
"SELECT (created_at/86400)*86400 AS day, COUNT(*),
COALESCE(SUM(prompt_tokens),0), COALESCE(SUM(completion_tokens),0)
FROM messages GROUP BY day ORDER BY day DESC LIMIT 30",
)?;
let mut daily = stmt
.query_map([], |r| {
Ok(DailyStat {
day: r.get(0)?,
messages: r.get::<_, i64>(1)? as u64,
prompt_tokens: r.get::<_, i64>(2)? as u64,
completion_tokens: r.get::<_, i64>(3)? as u64,
})
})?
.collect::<rusqlite::Result<Vec<_>>>()?;
daily.reverse();
Ok(Stats {
sessions: sessions as u64,
messages: messages as u64,
prompt_tokens: prompt as u64,
completion_tokens: completion as u64,
total_tokens: (prompt + completion) as u64,
tool_calls: tool_calls as u64,
by_session,
daily,
})
}
fn get_defaults(&self) -> Result<Option<SessionSettings>> {
let conn = self.lock();
let mut stmt = conn.prepare("SELECT settings_json FROM defaults WHERE id = 1")?;
let mut rows = stmt.query_map([], |r| r.get::<_, String>(0))?;
match rows.next().transpose()? {
Some(s) => Ok(Some(serde_json::from_str(&s).unwrap_or_default())),
None => Ok(None),
}
}
fn set_defaults(&self, settings: &SessionSettings) -> Result<()> {
let settings_json = serde_json::to_string(settings)?;
let conn = self.lock();
conn.execute(
"INSERT OR REPLACE INTO defaults (id, settings_json) VALUES (1, ?1)",
params![settings_json],
)?;
Ok(())
}
fn context_sections(&self) -> Result<Vec<ContextSection>> {
let conn = self.lock();
let mut stmt = conn.prepare(
"SELECT name, content, position FROM context_sections ORDER BY position ASC, name ASC",
)?;
let rows = stmt.query_map([], |r| {
Ok(ContextSection {
name: r.get(0)?,
content: r.get(1)?,
position: r.get(2)?,
})
})?;
Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?)
}
fn set_context_section(&self, name: &str, content: &str, position: i64) -> Result<()> {
let conn = self.lock();
conn.execute(
"INSERT OR REPLACE INTO context_sections (name, content, position) VALUES (?1, ?2, ?3)",
params![name, content, position],
)?;
Ok(())
}
fn save_upload(&self, meta: &UploadMeta) -> Result<()> {
let conn = self.lock();
conn.execute(
"INSERT OR REPLACE INTO uploads (id, original_name, path, kind, tokens, size, created_at)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
params![
meta.id,
meta.original_name,
meta.path,
meta.kind,
meta.tokens as i64,
meta.size as i64,
meta.created_at
],
)?;
Ok(())
}
fn get_upload(&self, id: &str) -> Result<Option<UploadMeta>> {
let conn = self.lock();
let mut stmt = conn.prepare("SELECT * FROM uploads WHERE id = ?1")?;
let mut rows = stmt.query_map(params![id], |r| {
Ok(UploadMeta {
id: r.get("id")?,
original_name: r.get("original_name")?,
path: r.get("path")?,
kind: r.get("kind")?,
tokens: r.get::<_, i64>("tokens")? as u32,
size: r.get::<_, i64>("size")? as u64,
created_at: r.get("created_at")?,
})
})?;
Ok(rows.next().transpose()?)
}
}
#[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 settings = SessionSettings {
system_prompt: Some("be nice".into()),
..Default::default()
};
let sess = s
.create_session("Chat", "Inkling-2-Mini", &settings)
.unwrap();
assert!(sess.id.starts_with("sess_"));
assert!(!sess.name_locked);
assert_eq!(sess.settings.system_prompt.as_deref(), Some("be nice"));
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,
tool_call_id: 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,
tool_call_id: 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 stats_breakdown_counts_tools_and_orders_sessions() {
let s = store();
let a = s
.create_session("Alpha", "m", &SessionSettings::default())
.unwrap();
let b = s
.create_session("Beta", "m", &SessionSettings::default())
.unwrap();
let add = |sid: &str, role: &'static str, tc: Option<&'static str>, pt: u32, ct: u32| {
s.append_message(
sid,
NewMessage {
role,
content: "x",
reasoning_content: None,
tool_calls_json: tc,
tool_call_id: None,
prompt_tokens: pt,
completion_tokens: ct,
},
)
.unwrap();
};
// Alpha: a user turn + an assistant turn requesting TWO tool calls.
add(&a.id, "user", None, 10, 0);
add(
&a.id,
"assistant",
Some(r#"[{"id":"1"},{"id":"2"}]"#),
10,
4,
);
// Beta: a smaller plain exchange.
add(&b.id, "user", None, 2, 0);
add(&b.id, "assistant", None, 2, 1);
let st = s.stats().unwrap();
assert_eq!(st.sessions, 2);
assert_eq!(st.messages, 4);
assert_eq!(st.prompt_tokens, 24);
assert_eq!(st.completion_tokens, 5);
assert_eq!(st.total_tokens, 29);
assert_eq!(st.tool_calls, 2); // two calls inside Alpha's single turn
// Busiest first: Alpha (24 tokens) ahead of Beta (5).
assert_eq!(st.by_session.len(), 2);
assert_eq!(st.by_session[0].id, a.id);
assert_eq!(st.by_session[0].messages, 2);
assert_eq!(st.by_session[1].id, b.id);
// All four messages fall in today's UTC bucket.
assert_eq!(st.daily.len(), 1);
assert_eq!(st.daily[0].messages, 4);
assert_eq!(st.daily[0].completion_tokens, 5);
}
#[test]
fn settings_instance_and_name_lock() {
let s = store();
let sess = s
.create_session("Chat", "m", &SessionSettings::default())
.unwrap();
// Update the session's own settings (notes + sampling).
let mut updated = sess.settings.clone();
updated.notes = Some("scopo: test".into());
updated.temperature = Some(0.7);
s.update_settings(&sess.id, &updated).unwrap();
let got = s.get_session(&sess.id).unwrap().unwrap();
assert_eq!(got.settings.notes.as_deref(), Some("scopo: test"));
assert_eq!(got.settings.temperature, Some(0.7));
// Lock the name.
s.set_name_locked(&sess.id, true).unwrap();
assert!(s.get_session(&sess.id).unwrap().unwrap().name_locked);
}
#[test]
fn context_sections_seeded_editable_and_extensible() {
let s = store();
let secs = s.context_sections().unwrap();
assert_eq!(secs.len(), 2);
assert_eq!(secs[0].name, "SYSTEM_PROMPT");
assert_eq!(secs[1].name, "TOOL_USE");
// Edits persist and reorder by position; new sections can be added.
s.set_context_section("SYSTEM_PROMPT", "custom {identity}", 5)
.unwrap();
s.set_context_section("EXTRA", "x", 2).unwrap();
let secs = s.context_sections().unwrap();
assert_eq!(secs.len(), 3);
assert_eq!(secs[0].name, "TOOL_USE"); // position 1
assert_eq!(secs[1].name, "EXTRA"); // position 2
assert_eq!(secs[2].name, "SYSTEM_PROMPT"); // position 5
assert_eq!(secs[2].content, "custom {identity}");
}
#[test]
fn defaults_roundtrip_and_overlay() {
let s = store();
assert!(s.get_defaults().unwrap().is_none());
let def = SessionSettings {
system_prompt: Some("base".into()),
temperature: Some(1.0),
..Default::default()
};
s.set_defaults(&def).unwrap();
assert_eq!(
s.get_defaults().unwrap().unwrap().system_prompt.as_deref(),
Some("base")
);
// A creation override snapshots the defaults and wins on set fields.
let over = SessionSettings {
temperature: Some(0.2),
..Default::default()
};
let snap = over.overlay(&def);
assert_eq!(snap.system_prompt.as_deref(), Some("base"));
assert_eq!(snap.temperature, Some(0.2));
}
#[test]
fn ids_are_unique() {
let a = new_id("sess");
let b = new_id("sess");
assert_ne!(a, b);
}
#[test]
fn migration_adds_columns_to_old_schema() {
// Simulate a pre-existing database without the newer columns.
let conn = Connection::open_in_memory().unwrap();
conn.execute_batch(
"CREATE TABLE sessions (id TEXT PRIMARY KEY, title TEXT, model TEXT,
system_prompt TEXT, created_at INTEGER, updated_at INTEGER);
INSERT INTO sessions VALUES ('s1','t','m','old prompt',0,0);
CREATE TABLE messages (id INTEGER PRIMARY KEY, session_id TEXT, role TEXT,
content TEXT, reasoning_content TEXT, tool_calls_json TEXT,
prompt_tokens INTEGER, completion_tokens INTEGER, created_at INTEGER);",
)
.unwrap();
migrate(&conn).unwrap();
let has = |col: &str| -> i64 {
conn.prepare(&format!(
"SELECT COUNT(*) FROM pragma_table_info('sessions') WHERE name='{col}'"
))
.unwrap()
.query_row([], |r| r.get(0))
.unwrap()
};
assert_eq!(has("settings_json"), 1);
assert_eq!(has("name_locked"), 1);
// The old system_prompt was backfilled into the settings instance.
let sj: String = conn
.query_row(
"SELECT settings_json FROM sessions WHERE id='s1'",
[],
|r| r.get(0),
)
.unwrap();
assert!(sj.contains("old prompt"));
// Idempotent: running again does not error.
migrate(&conn).unwrap();
}
}