- src/mcp: streamable-HTTP client (rmcp v3.12) negotiating Initialize +
LATEST_WITH_INITIALIZE; namespaced mcp__{connector}__{tool} surface, write
badges from ToolAnnotations, persisted discovery (tools_json) so the agent
tool declarations stay byte-stable for KV-cache reuse.
- store: mcp_connectors catalog + tools_json column (idempotent migration) and
set_mcp_tools; per-session per-tool allowlist (SessionSettings.mcp_enabled).
- agent: execute_mcp routes namespaced calls, gated on the session allowlist
before any network call; Bearer token comes from the DB catalog, never echoed.
- api/sessions: build the MCP surface into Ambient + the agent tool declarations
on both the turn and prewarm paths (identical rebuild keeps the prefix stable).
- api/mcp + GUI: connector CRUD, tool-discovery picker, per-session enable.
- examples/mcp_probe: read-only CLI discovery spike.
Live-verified: 22 gmail tools discovered, gmail_labels returned 25 labels, and a
full model-driven GUI turn (7 enabled tools) with a 9197-token RESUME cache hit.
1393 lines
55 KiB
Rust
1393 lines
55 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::collections::BTreeMap;
|
|
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, OptionalExtension};
|
|
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>,
|
|
/// Per-session MCP opt-in: connector name -> the explicit list of enabled
|
|
/// tool NAMES (the allowlist). Empty/absent = no MCP surface for this
|
|
/// session. The connector catalog (url/token) is global; only the
|
|
/// curated tool selection lives here, copy-on-create like other settings.
|
|
#[serde(default)]
|
|
pub mcp_enabled: BTreeMap<String, Vec<String>>,
|
|
}
|
|
|
|
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),
|
|
mcp_enabled: if self.mcp_enabled.is_empty() {
|
|
base.mcp_enabled.clone()
|
|
} else {
|
|
self.mcp_enabled.clone()
|
|
},
|
|
}
|
|
}
|
|
}
|
|
|
|
/// 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,
|
|
/// Current inference context: prompt tokens of the most recent assistant
|
|
/// turn (the actual prompt last sent to the engine). Unlike `prompt_tokens`
|
|
/// — a cumulative sum that re-counts the whole window every turn — this is
|
|
/// the size of the context we are actually sending to inference now.
|
|
pub last_prompt_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,
|
|
}
|
|
|
|
/// One labelled entry of a session's persistent notepad: a stable `key` the
|
|
/// agent addresses (upsert/remove) and a short `text`. Per-session; injected as
|
|
/// the pinned <NOTEPAD> section above DIALOG, ordered by key for a deterministic
|
|
/// block. Nothing is evicted automatically — the agent curates it.
|
|
#[derive(Debug, Clone, Serialize)]
|
|
pub struct NotepadEntry {
|
|
pub key: String,
|
|
pub text: String,
|
|
pub updated_at: i64,
|
|
}
|
|
|
|
/// One external MCP server in the GLOBAL connector catalog (shared across
|
|
/// sessions). Connection parameters, including the Bearer `token`, live in the
|
|
/// database like all other persistent state (no env vars / files: that would
|
|
/// break cloud deployments). Which tools a session actually exposes is curated
|
|
/// separately in `SessionSettings.mcp_enabled`.
|
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
|
pub struct McpConnector {
|
|
/// Stable connector id (namespace segment in `mcp__{name}__{tool}`).
|
|
pub name: String,
|
|
/// Streamable-HTTP endpoint URL.
|
|
pub url: String,
|
|
/// Bearer token for the connector (stored in the local DB, never in chat).
|
|
pub token: String,
|
|
/// Persisted discovery: the server's tools as a JSON array (rmcp `Tool`),
|
|
/// refreshed by the picker's live `tools/list`. The agent builds its curated
|
|
/// surface from this synchronously, so the real turn and the cache pre-warm
|
|
/// share a byte-identical prefix with no network on the generation path.
|
|
/// Internal only (not serialized to the GUI catalog); None until discovered.
|
|
#[serde(default, skip_serializing)]
|
|
pub tools_json: Option<String>,
|
|
#[serde(default)]
|
|
pub created_at: i64,
|
|
#[serde(default)]
|
|
pub updated_at: 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_PRE_NOTEPAD: &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.";
|
|
const TOOL_USE_SECTION_PRE_SHARE: &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. notepad(action, key?, text?) gestisce il tuo blocco appunti persistente, sempre visibile sopra il dialogo: action=set crea o aggiorna la entry etichettata `key` con `text` (upsert idempotente); action=remove cancella la entry `key`; action=clear svuota tutto. Fissa qui ciò che deve sopravvivere allo scorrere della finestra di contesto: goal, decisioni e razionale, stato/next-step, vincoli, pitfall, path e identificatori chiave. Non usarlo per log o documenti lunghi né per dati effimeri del singolo task. È bounded: quando si avvicina al limite consolida le entry vecchie; non c'è eviction automatica, decidi tu cosa tenere. Tieni le entry brevi.";
|
|
/// Prose appended to the notepad-era TOOL_USE manual to document `share_file`.
|
|
/// Kept separate so the seed can refresh untouched older rows without duplicating
|
|
/// the long notepad text (and never clobber a user-edited section).
|
|
const SHARE_FILE_SUFFIX: &str = " share_file(path, name?) espone un file che hai su disco come link di scaricamento cliccabile nella chat web: restituisce un link Markdown già pronto da incollare testualmente nella risposta per l'utente. Usalo quando produci un file che l'utente deve scaricare (report, script, dati, immagini, archivi). Sono ammessi solo file regolari dentro la tua cartella personale o la cartella uploads condivisa, entro 64 MiB; `path` può essere assoluto o relativo alla tua cartella personale, `name` opzionalmente sostituisce il nome del file scaricato.";
|
|
|
|
/// 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<()>;
|
|
/// First retained history message id for the sliding DIALOG window (0 = all).
|
|
fn window_start(&self, id: &str) -> Result<i64>;
|
|
fn set_window_start(&self, id: &str, start: i64) -> Result<()>;
|
|
fn delete_session(&self, id: &str) -> Result<()>;
|
|
fn messages(&self, session_id: &str) -> Result<Vec<StoredMessage>>;
|
|
/// The GUI's sliding-window view: messages at/after `start_id` (the persisted
|
|
/// window start) plus the total stored message count. Filtered in SQL so a
|
|
/// months-long history is never loaded whole just to render the recent window.
|
|
fn message_window(&self, session_id: &str, start_id: i64) -> Result<(Vec<StoredMessage>, u64)>;
|
|
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<()>;
|
|
/// The session's notepad entries, ordered by key (deterministic block).
|
|
fn notepad(&self, session_id: &str) -> Result<Vec<NotepadEntry>>;
|
|
/// Create or update (upsert) the entry labelled `key`.
|
|
fn set_notepad_entry(&self, session_id: &str, key: &str, text: &str) -> Result<()>;
|
|
/// Remove the entry `key`; returns whether it existed.
|
|
fn remove_notepad_entry(&self, session_id: &str, key: &str) -> Result<bool>;
|
|
/// Empty the session's notepad.
|
|
fn clear_notepad(&self, session_id: &str) -> Result<()>;
|
|
fn save_upload(&self, meta: &UploadMeta) -> Result<()>;
|
|
fn get_upload(&self, id: &str) -> Result<Option<UploadMeta>>;
|
|
/// The global MCP connector catalog, ordered by name.
|
|
fn mcp_connectors(&self) -> Result<Vec<McpConnector>>;
|
|
/// Create or update (upsert by name) a connector's connection parameters.
|
|
fn upsert_mcp_connector(&self, connector: &McpConnector) -> Result<()>;
|
|
/// Remove a connector from the catalog; returns whether it existed.
|
|
fn delete_mcp_connector(&self, name: &str) -> Result<bool>;
|
|
/// Persist the discovered tool surface (JSON array of rmcp `Tool`) for a
|
|
/// connector, refreshed by live discovery. No-op if the connector is absent.
|
|
fn set_mcp_tools(&self, name: &str, tools_json: &str) -> Result<()>;
|
|
}
|
|
|
|
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,
|
|
window_start INTEGER NOT NULL DEFAULT 0,
|
|
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
|
|
);
|
|
CREATE TABLE IF NOT EXISTS notepad_entries (
|
|
session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
|
|
key TEXT NOT NULL,
|
|
text TEXT NOT NULL,
|
|
updated_at INTEGER NOT NULL,
|
|
PRIMARY KEY (session_id, key)
|
|
);
|
|
CREATE TABLE IF NOT EXISTS mcp_connectors (
|
|
name TEXT PRIMARY KEY,
|
|
url TEXT NOT NULL,
|
|
token TEXT NOT NULL,
|
|
tools_json TEXT,
|
|
created_at INTEGER NOT NULL,
|
|
updated_at 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")?;
|
|
// Wait briefly for a concurrent writer (e.g. an external reader/tool in
|
|
// WAL) instead of failing immediately with SQLITE_BUSY.
|
|
conn.pragma_update(None, "busy_timeout", 5000)?;
|
|
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;")?;
|
|
}
|
|
if !has_col("sessions", "window_start")? {
|
|
conn.execute_batch(
|
|
"ALTER TABLE sessions ADD COLUMN window_start INTEGER NOT NULL DEFAULT 0;",
|
|
)?;
|
|
}
|
|
// The MCP catalog originally stored an env-var NAME (token_env); the token
|
|
// now lives directly in the DB. Rename the column in place, preserving rows.
|
|
if has_col("mcp_connectors", "token_env")? && !has_col("mcp_connectors", "token")? {
|
|
conn.execute_batch("ALTER TABLE mcp_connectors RENAME COLUMN token_env TO token;")?;
|
|
}
|
|
// Persisted tool discovery (the agent's curated surface is built from this).
|
|
// Guard on the table existing: very old databases (and the migration unit
|
|
// test) predate mcp_connectors entirely; SCHEMA creates it with tools_json.
|
|
if has_col("mcp_connectors", "name")? && !has_col("mcp_connectors", "tools_json")? {
|
|
conn.execute_batch("ALTER TABLE mcp_connectors ADD COLUMN tools_json TEXT;")?;
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
/// Seed the static context sections once (idempotent); afterwards the stored
|
|
/// rows are authoritative and editable.
|
|
fn seed_context_sections(conn: &Connection) -> Result<()> {
|
|
// The current TOOL_USE manual = notepad-era prose + the share_file paragraph.
|
|
let tool_use = format!("{TOOL_USE_SECTION_PRE_SHARE}{SHARE_FILE_SUFFIX}");
|
|
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],
|
|
)?;
|
|
// Refresh an untouched pre-notepad TOOL_USE row so the notepad manual reaches
|
|
// existing databases; a user-edited row (content differs) is left alone.
|
|
conn.execute(
|
|
"UPDATE context_sections SET content = ?1 WHERE name = 'TOOL_USE' AND content = ?2",
|
|
params![tool_use, TOOL_USE_SECTION_PRE_NOTEPAD],
|
|
)?;
|
|
// Likewise refresh an untouched notepad-era row so the share_file manual
|
|
// reaches databases created before share_file existed.
|
|
conn.execute(
|
|
"UPDATE context_sections SET content = ?1 WHERE name = 'TOOL_USE' AND content = ?2",
|
|
params![tool_use, TOOL_USE_SECTION_PRE_SHARE],
|
|
)?;
|
|
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 window_start(&self, id: &str) -> Result<i64> {
|
|
let conn = self.lock();
|
|
let v = conn
|
|
.query_row(
|
|
"SELECT window_start FROM sessions WHERE id = ?1",
|
|
params![id],
|
|
|r| r.get::<_, i64>(0),
|
|
)
|
|
.optional()?;
|
|
Ok(v.unwrap_or(0))
|
|
}
|
|
|
|
fn set_window_start(&self, id: &str, start: i64) -> Result<()> {
|
|
let conn = self.lock();
|
|
conn.execute(
|
|
"UPDATE sessions SET window_start = ?2 WHERE id = ?1",
|
|
params![id, start],
|
|
)?;
|
|
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 message_window(&self, session_id: &str, start_id: i64) -> Result<(Vec<StoredMessage>, u64)> {
|
|
let conn = self.lock();
|
|
let total: i64 = conn.query_row(
|
|
"SELECT COUNT(*) FROM messages WHERE session_id = ?1",
|
|
params![session_id],
|
|
|r| r.get(0),
|
|
)?;
|
|
let mut stmt = conn
|
|
.prepare("SELECT * FROM messages WHERE session_id = ?1 AND id >= ?2 ORDER BY id ASC")?;
|
|
let rows = stmt.query_map(params![session_id, start_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")?,
|
|
})
|
|
})?;
|
|
let msgs = rows.collect::<rusqlite::Result<Vec<_>>>()?;
|
|
Ok((msgs, total as u64))
|
|
}
|
|
|
|
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 a JSON array
|
|
// of calls (or NULL); guard with json_valid/json_type so one corrupt or
|
|
// non-array row cannot fail the whole stats query.
|
|
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
|
|
AND json_valid(tool_calls_json)
|
|
AND json_type(tool_calls_json) = 'array'
|
|
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)?)),
|
|
)?;
|
|
|
|
// Current context = the prompt of the latest assistant turn (the size
|
|
// actually sent to inference last). The cumulative SUM(prompt_tokens)
|
|
// above re-counts the whole retained window every turn, so it is NOT
|
|
// the context size; this single latest value is.
|
|
let last_prompt: i64 = conn
|
|
.query_row(
|
|
"SELECT prompt_tokens FROM messages
|
|
WHERE role = 'assistant' AND prompt_tokens > 0
|
|
ORDER BY id DESC LIMIT 1",
|
|
[],
|
|
|r| r.get(0),
|
|
)
|
|
.optional()?
|
|
.unwrap_or(0);
|
|
|
|
// 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,
|
|
last_prompt_tokens: last_prompt 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 notepad(&self, session_id: &str) -> Result<Vec<NotepadEntry>> {
|
|
let conn = self.lock();
|
|
let mut stmt = conn.prepare(
|
|
"SELECT key, text, updated_at FROM notepad_entries WHERE session_id = ?1 ORDER BY key ASC",
|
|
)?;
|
|
let rows = stmt.query_map(params![session_id], |r| {
|
|
Ok(NotepadEntry {
|
|
key: r.get(0)?,
|
|
text: r.get(1)?,
|
|
updated_at: r.get(2)?,
|
|
})
|
|
})?;
|
|
Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?)
|
|
}
|
|
|
|
fn set_notepad_entry(&self, session_id: &str, key: &str, text: &str) -> Result<()> {
|
|
let conn = self.lock();
|
|
conn.execute(
|
|
"INSERT INTO notepad_entries (session_id, key, text, updated_at) VALUES (?1, ?2, ?3, ?4)
|
|
ON CONFLICT(session_id, key) DO UPDATE SET text = ?3, updated_at = ?4",
|
|
params![session_id, key, text, now_secs()],
|
|
)?;
|
|
Ok(())
|
|
}
|
|
|
|
fn remove_notepad_entry(&self, session_id: &str, key: &str) -> Result<bool> {
|
|
let conn = self.lock();
|
|
let n = conn.execute(
|
|
"DELETE FROM notepad_entries WHERE session_id = ?1 AND key = ?2",
|
|
params![session_id, key],
|
|
)?;
|
|
Ok(n > 0)
|
|
}
|
|
|
|
fn clear_notepad(&self, session_id: &str) -> Result<()> {
|
|
let conn = self.lock();
|
|
conn.execute(
|
|
"DELETE FROM notepad_entries WHERE session_id = ?1",
|
|
params![session_id],
|
|
)?;
|
|
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()?)
|
|
}
|
|
|
|
fn mcp_connectors(&self) -> Result<Vec<McpConnector>> {
|
|
let conn = self.lock();
|
|
let mut stmt = conn.prepare(
|
|
"SELECT name, url, token, tools_json, created_at, updated_at FROM mcp_connectors ORDER BY name ASC",
|
|
)?;
|
|
let rows = stmt.query_map([], |r| {
|
|
Ok(McpConnector {
|
|
name: r.get(0)?,
|
|
url: r.get(1)?,
|
|
token: r.get(2)?,
|
|
tools_json: r.get(3)?,
|
|
created_at: r.get(4)?,
|
|
updated_at: r.get(5)?,
|
|
})
|
|
})?;
|
|
Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?)
|
|
}
|
|
|
|
fn upsert_mcp_connector(&self, connector: &McpConnector) -> Result<()> {
|
|
let now = now_secs();
|
|
let conn = self.lock();
|
|
// Preserve the original created_at on update; set it on first insert.
|
|
conn.execute(
|
|
"INSERT INTO mcp_connectors (name, url, token, created_at, updated_at)
|
|
VALUES (?1, ?2, ?3, ?4, ?4)
|
|
ON CONFLICT(name) DO UPDATE SET url = ?2, token = ?3, updated_at = ?4",
|
|
params![connector.name, connector.url, connector.token, now],
|
|
)?;
|
|
Ok(())
|
|
}
|
|
|
|
fn delete_mcp_connector(&self, name: &str) -> Result<bool> {
|
|
let conn = self.lock();
|
|
let n = conn.execute("DELETE FROM mcp_connectors WHERE name = ?1", params![name])?;
|
|
Ok(n > 0)
|
|
}
|
|
|
|
fn set_mcp_tools(&self, name: &str, tools_json: &str) -> Result<()> {
|
|
let conn = self.lock();
|
|
conn.execute(
|
|
"UPDATE mcp_connectors SET tools_json = ?2, updated_at = ?3 WHERE name = ?1",
|
|
params![name, tools_json, now_secs()],
|
|
)?;
|
|
Ok(())
|
|
}
|
|
}
|
|
|
|
#[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);
|
|
assert_eq!(stats.last_prompt_tokens, 3); // latest assistant turn, not the sum
|
|
|
|
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 mcp_connector_catalog_and_session_allowlist() {
|
|
let s = store();
|
|
assert!(s.mcp_connectors().unwrap().is_empty());
|
|
let c = McpConnector {
|
|
name: "gmail".into(),
|
|
url: "http://192.168.50.117:8080/".into(),
|
|
token: "test-token-value".into(),
|
|
tools_json: None,
|
|
created_at: 0,
|
|
updated_at: 0,
|
|
};
|
|
s.upsert_mcp_connector(&c).unwrap();
|
|
// Upsert updates url/token, keeps a single row, stamps created_at.
|
|
let c2 = McpConnector {
|
|
url: "https://mcp1.uncino.eu".into(),
|
|
..c.clone()
|
|
};
|
|
s.upsert_mcp_connector(&c2).unwrap();
|
|
let list = s.mcp_connectors().unwrap();
|
|
assert_eq!(list.len(), 1);
|
|
assert_eq!(list[0].url, "https://mcp1.uncino.eu");
|
|
assert_eq!(list[0].token, "test-token-value");
|
|
assert!(list[0].created_at > 0);
|
|
|
|
// Persisted discovery round-trips and survives a url/token upsert.
|
|
assert!(list[0].tools_json.is_none());
|
|
s.set_mcp_tools("gmail", "[{\"name\":\"gmail_search\"}]")
|
|
.unwrap();
|
|
assert_eq!(
|
|
s.mcp_connectors().unwrap()[0].tools_json.as_deref(),
|
|
Some("[{\"name\":\"gmail_search\"}]")
|
|
);
|
|
s.upsert_mcp_connector(&c2).unwrap();
|
|
assert_eq!(
|
|
s.mcp_connectors().unwrap()[0].tools_json.as_deref(),
|
|
Some("[{\"name\":\"gmail_search\"}]"),
|
|
"a url/token upsert must not clobber the persisted discovery"
|
|
);
|
|
|
|
// The per-session allowlist round-trips through settings_json.
|
|
let mut settings = SessionSettings::default();
|
|
settings.mcp_enabled.insert(
|
|
"gmail".into(),
|
|
vec!["search_messages".into(), "read_message".into()],
|
|
);
|
|
let sess = s.create_session("Chat", "m", &settings).unwrap();
|
|
let got = s.get_session(&sess.id).unwrap().unwrap();
|
|
assert_eq!(
|
|
got.settings.mcp_enabled.get("gmail").unwrap(),
|
|
&vec!["search_messages".to_string(), "read_message".to_string()]
|
|
);
|
|
// A session created with default settings has an empty allowlist
|
|
// (backward compatible: old settings_json without the field).
|
|
let plain = s
|
|
.create_session("Plain", "m", &SessionSettings::default())
|
|
.unwrap();
|
|
assert!(plain.settings.mcp_enabled.is_empty());
|
|
|
|
assert!(s.delete_mcp_connector("gmail").unwrap());
|
|
assert!(!s.delete_mcp_connector("gmail").unwrap());
|
|
assert!(s.mcp_connectors().unwrap().is_empty());
|
|
}
|
|
|
|
#[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);
|
|
// Current context tracks the latest assistant turn (Beta, pt=2), not
|
|
// the cumulative prompt sum (24) which re-counts every turn's window.
|
|
assert_eq!(st.last_prompt_tokens, 2);
|
|
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 stats_survives_a_corrupt_tool_calls_row() {
|
|
let s = store();
|
|
let sess = s
|
|
.create_session("Chat", "m", &SessionSettings::default())
|
|
.unwrap();
|
|
// A corrupt (non-JSON) tool_calls_json row must not fail the whole query.
|
|
s.append_message(
|
|
&sess.id,
|
|
NewMessage {
|
|
role: "assistant",
|
|
content: "x",
|
|
reasoning_content: None,
|
|
tool_calls_json: Some("not-json"),
|
|
tool_call_id: None,
|
|
prompt_tokens: 1,
|
|
completion_tokens: 1,
|
|
},
|
|
)
|
|
.unwrap();
|
|
// A valid array still counts.
|
|
s.append_message(
|
|
&sess.id,
|
|
NewMessage {
|
|
role: "assistant",
|
|
content: "y",
|
|
reasoning_content: None,
|
|
tool_calls_json: Some(r#"[{"id":"1"}]"#),
|
|
tool_call_id: None,
|
|
prompt_tokens: 1,
|
|
completion_tokens: 1,
|
|
},
|
|
)
|
|
.unwrap();
|
|
let st = s.stats().unwrap();
|
|
assert_eq!(st.messages, 2);
|
|
assert_eq!(st.tool_calls, 1); // corrupt row skipped, valid array counted
|
|
}
|
|
|
|
#[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);
|
|
CREATE TABLE mcp_connectors (name TEXT PRIMARY KEY, url TEXT, token TEXT,
|
|
created_at INTEGER, updated_at INTEGER);
|
|
INSERT INTO mcp_connectors VALUES ('gmail','http://x/','tok',0,0);",
|
|
)
|
|
.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);
|
|
assert_eq!(has("window_start"), 1);
|
|
// The MCP catalog gains tools_json on an old DB that predates it, and the
|
|
// existing row is preserved.
|
|
let tj: i64 = conn
|
|
.prepare(
|
|
"SELECT COUNT(*) FROM pragma_table_info('mcp_connectors') WHERE name='tools_json'",
|
|
)
|
|
.unwrap()
|
|
.query_row([], |r| r.get(0))
|
|
.unwrap();
|
|
assert_eq!(tj, 1);
|
|
let tok: String = conn
|
|
.query_row(
|
|
"SELECT token FROM mcp_connectors WHERE name='gmail'",
|
|
[],
|
|
|r| r.get(0),
|
|
)
|
|
.unwrap();
|
|
assert_eq!(tok, "tok");
|
|
// 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();
|
|
}
|
|
|
|
#[test]
|
|
fn notepad_upsert_remove_clear_and_cascade() {
|
|
let s = store();
|
|
let sess = s
|
|
.create_session("Chat", "m", &SessionSettings::default())
|
|
.unwrap();
|
|
assert!(s.notepad(&sess.id).unwrap().is_empty());
|
|
s.set_notepad_entry(&sess.id, "goal", "ship the notepad")
|
|
.unwrap();
|
|
s.set_notepad_entry(&sess.id, "state", "coding").unwrap();
|
|
// Upsert by key replaces, does not duplicate.
|
|
s.set_notepad_entry(&sess.id, "goal", "ship + dogfood")
|
|
.unwrap();
|
|
let np = s.notepad(&sess.id).unwrap();
|
|
assert_eq!(np.len(), 2);
|
|
assert_eq!(np[0].key, "goal"); // ordered by key
|
|
assert_eq!(np[0].text, "ship + dogfood");
|
|
assert_eq!(np[1].key, "state");
|
|
assert!(s.remove_notepad_entry(&sess.id, "state").unwrap());
|
|
assert!(!s.remove_notepad_entry(&sess.id, "state").unwrap());
|
|
assert_eq!(s.notepad(&sess.id).unwrap().len(), 1);
|
|
s.clear_notepad(&sess.id).unwrap();
|
|
assert!(s.notepad(&sess.id).unwrap().is_empty());
|
|
// Per-session isolation + cascade on delete.
|
|
s.set_notepad_entry(&sess.id, "k", "v").unwrap();
|
|
let other = s
|
|
.create_session("Other", "m", &SessionSettings::default())
|
|
.unwrap();
|
|
assert!(s.notepad(&other.id).unwrap().is_empty());
|
|
s.delete_session(&sess.id).unwrap();
|
|
assert!(s.notepad(&sess.id).unwrap().is_empty());
|
|
}
|
|
|
|
#[test]
|
|
fn tool_use_section_includes_notepad_manual() {
|
|
let s = store();
|
|
let secs = s.context_sections().unwrap();
|
|
let tool_use = secs.iter().find(|x| x.name == "TOOL_USE").unwrap();
|
|
assert!(tool_use.content.contains("notepad("));
|
|
}
|
|
|
|
#[test]
|
|
fn window_start_default_and_roundtrip() {
|
|
let s = store();
|
|
let sess = s
|
|
.create_session("Chat", "m", &SessionSettings::default())
|
|
.unwrap();
|
|
assert_eq!(s.window_start(&sess.id).unwrap(), 0);
|
|
s.set_window_start(&sess.id, 42).unwrap();
|
|
assert_eq!(s.window_start(&sess.id).unwrap(), 42);
|
|
// Missing session -> 0, no panic.
|
|
assert_eq!(s.window_start("nope").unwrap(), 0);
|
|
}
|
|
}
|