Session settings copy-on-create + immutable friendly names
- SessionSettings instance per session (system_prompt, notes, sampling), snapshotted from global defaults at creation (copy-on-create); editing a session affects only it, editing globals affects only future sessions. Global defaults template stored in DB, seeded from config; GET/PUT /api/settings/defaults. - Framework-assigned evocative names (word list, src/name.rs) replace the auto-title (removed). Name editable only before the first interaction, then locked (name_locked); PATCH rejects post-lock rename. Session notes carry the user-defined purpose. - Idempotent migration adds settings_json/name_locked and backfills old sessions; build_request uses the session's own settings snapshot. 112 tests green, clippy/fmt clean; verified live (migration, name lock, settings isolation).
This commit is contained in:
1 parent
0123f41d99
commit
0568b92e06
9 files changed
+556
-100
No files matched your search
+228
-23
@@ -3,7 +3,7 @@
|
||||
//! 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.
|
||||
//! 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.
|
||||
@@ -15,20 +15,77 @@ 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>,
|
||||
#[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()),
|
||||
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, serde::Serialize)]
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct Session {
|
||||
pub id: String,
|
||||
pub title: String,
|
||||
pub model: String,
|
||||
pub system_prompt: Option<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,
|
||||
pub created_at: i64,
|
||||
pub updated_at: i64,
|
||||
}
|
||||
|
||||
/// A persisted message (one turn) with its token usage.
|
||||
#[derive(Debug, Clone, serde::Serialize)]
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct StoredMessage {
|
||||
pub id: i64,
|
||||
pub role: String,
|
||||
@@ -53,7 +110,7 @@ pub struct NewMessage<'a> {
|
||||
}
|
||||
|
||||
/// Aggregate counters for the stats view.
|
||||
#[derive(Debug, Clone, Default, serde::Serialize)]
|
||||
#[derive(Debug, Clone, Default, Serialize)]
|
||||
pub struct Stats {
|
||||
pub sessions: u64,
|
||||
pub messages: u64,
|
||||
@@ -67,15 +124,20 @@ pub trait Store: Send + Sync {
|
||||
&self,
|
||||
title: &str,
|
||||
model: &str,
|
||||
system_prompt: Option<&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 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<()>;
|
||||
}
|
||||
|
||||
fn now_secs() -> i64 {
|
||||
@@ -102,6 +164,8 @@ CREATE TABLE IF NOT EXISTS sessions (
|
||||
title TEXT NOT NULL,
|
||||
model TEXT NOT NULL,
|
||||
system_prompt TEXT,
|
||||
settings_json TEXT,
|
||||
name_locked INTEGER NOT NULL DEFAULT 0,
|
||||
created_at INTEGER NOT NULL,
|
||||
updated_at INTEGER NOT NULL
|
||||
);
|
||||
@@ -118,6 +182,10 @@ CREATE TABLE IF NOT EXISTS messages (
|
||||
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
|
||||
);
|
||||
";
|
||||
|
||||
/// SQLite-backed store (bundled SQLite, compiled into the binary). WAL mode for
|
||||
@@ -164,21 +232,52 @@ impl SqliteStore {
|
||||
/// `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_tool_call_id: i64 = conn
|
||||
.prepare("SELECT COUNT(*) FROM pragma_table_info('messages') WHERE name = 'tool_call_id'")?
|
||||
.query_row([], |r| r.get(0))?;
|
||||
if has_tool_call_id == 0 {
|
||||
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;",
|
||||
)?;
|
||||
}
|
||||
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")?,
|
||||
system_prompt: row.get("system_prompt")?,
|
||||
settings,
|
||||
name_locked: row.get::<_, i64>("name_locked")? != 0,
|
||||
created_at: row.get("created_at")?,
|
||||
updated_at: row.get("updated_at")?,
|
||||
})
|
||||
@@ -189,21 +288,23 @@ impl Store for SqliteStore {
|
||||
&self,
|
||||
title: &str,
|
||||
model: &str,
|
||||
system_prompt: Option<&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, system_prompt, created_at, updated_at)
|
||||
VALUES (?1, ?2, ?3, ?4, ?5, ?5)",
|
||||
params![id, title, model, system_prompt, now],
|
||||
"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(),
|
||||
system_prompt: system_prompt.map(str::to_string),
|
||||
settings: settings.clone(),
|
||||
name_locked: false,
|
||||
created_at: now,
|
||||
updated_at: now,
|
||||
})
|
||||
@@ -233,6 +334,25 @@ impl Store for SqliteStore {
|
||||
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 delete_session(&self, id: &str) -> Result<()> {
|
||||
let conn = self.lock();
|
||||
conn.execute("DELETE FROM sessions WHERE id = ?1", params![id])?;
|
||||
@@ -312,6 +432,26 @@ impl Store for SqliteStore {
|
||||
completion_tokens: completion as u64,
|
||||
})
|
||||
}
|
||||
|
||||
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(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -325,10 +465,16 @@ mod tests {
|
||||
#[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", Some("be nice"))
|
||||
.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(
|
||||
@@ -382,6 +528,49 @@ mod tests {
|
||||
assert_eq!(s.list_sessions().unwrap().len(), 0);
|
||||
}
|
||||
|
||||
#[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 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");
|
||||
@@ -390,22 +579,38 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn migration_adds_tool_call_id_to_old_schema() {
|
||||
// Simulate a pre-existing database without the tool_call_id column.
|
||||
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 messages (id INTEGER PRIMARY KEY, session_id TEXT, role TEXT,
|
||||
"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 n: i64 = conn
|
||||
.prepare("SELECT COUNT(*) FROM pragma_table_info('messages') WHERE name='tool_call_id'")
|
||||
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_eq!(n, 1);
|
||||
assert!(sj.contains("old prompt"));
|
||||
// Idempotent: running again does not error.
|
||||
migrate(&conn).unwrap();
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user