From 0568b92e06c9a4abe2c0f8b966f5e20fb8c3126e Mon Sep 17 00:00:00 2001 From: iz0eyj Date: Wed, 25 Nov 2026 15:44:52 +0100 Subject: [PATCH] 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). --- src/agent/mod.rs | 16 ++- src/api/routes.rs | 6 +- src/api/sessions.rs | 141 ++++++++++++++---------- src/config.rs | 18 +++ src/lib.rs | 1 + src/main.rs | 5 + src/name.rs | 99 +++++++++++++++++ src/store.rs | 251 ++++++++++++++++++++++++++++++++++++++---- tests/api_sessions.rs | 119 +++++++++++++++++--- 9 files changed, 556 insertions(+), 100 deletions(-) create mode 100644 src/name.rs diff --git a/src/agent/mod.rs b/src/agent/mod.rs index 51ea169..9f4045b 100644 --- a/src/agent/mod.rs +++ b/src/agent/mod.rs @@ -321,7 +321,13 @@ mod tests { #[tokio::test] async fn loop_runs_tool_then_final_and_persists_trajectory() { let store: Arc = Arc::new(SqliteStore::open_in_memory().unwrap()); - let sess = store.create_session("Agent", "test-model", None).unwrap(); + let sess = store + .create_session( + "Agent", + "test-model", + &crate::store::SessionSettings::default(), + ) + .unwrap(); let runner: Arc = Arc::new(HostShell); let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel(); @@ -378,7 +384,13 @@ mod tests { #[tokio::test] async fn loop_stops_at_max_iters() { let store: Arc = Arc::new(SqliteStore::open_in_memory().unwrap()); - let sess = store.create_session("Agent", "test-model", None).unwrap(); + let sess = store + .create_session( + "Agent", + "test-model", + &crate::store::SessionSettings::default(), + ) + .unwrap(); let runner: Arc = Arc::new(HostShell); // Model always asks for a tool -> never finishes. let model = move |_req: ChatRequest| async { Ok(tool_call_response()) }; diff --git a/src/api/routes.rs b/src/api/routes.rs index c44b943..c988eb4 100644 --- a/src/api/routes.rs +++ b/src/api/routes.rs @@ -62,10 +62,14 @@ fn build_router(state: AppState, auth: AuthConfig) -> Router { "/api/sessions/{id}", get(sessions::get_session) .delete(sessions::delete_session) - .patch(sessions::rename_session), + .patch(sessions::patch_session), ) .route("/api/sessions/{id}/messages", get(sessions::get_messages)) .route("/api/sessions/{id}/chat", post(sessions::session_chat)) + .route( + "/api/settings/defaults", + get(sessions::get_defaults).put(sessions::put_defaults), + ) .route("/api/stats", get(sessions::stats)) .route("/", get(web::index)) .route("/assets/{*path}", get(web::asset)); diff --git a/src/api/sessions.rs b/src/api/sessions.rs index 1b78d8e..5b4fb0a 100644 --- a/src/api/sessions.rs +++ b/src/api/sessions.rs @@ -19,7 +19,8 @@ use super::routes::{AppState, Error}; use super::types::{ChatChunk, ChatMessage, ChatRequest, FunctionCall, Role, ToolCall, Usage}; use crate::agent::shell::{HostShell, ShellRunner}; use crate::agent::{self, AgentEvent}; -use crate::store::{NewMessage, Session, Stats, Store, StoredMessage}; +use crate::name; +use crate::store::{NewMessage, Session, SessionSettings, Stats, Store, StoredMessage}; use tokio_stream::wrappers::UnboundedReceiverStream; /// Run a synchronous store operation off the async runtime. @@ -44,13 +45,19 @@ pub(crate) struct CreateSession { title: Option, #[serde(default)] model: Option, + /// Optional overrides snapshotted on top of the global defaults. #[serde(default)] - system_prompt: Option, + settings: Option, } #[derive(Deserialize)] -pub(crate) struct Rename { - title: String, +pub(crate) struct SessionPatch { + /// Rename — rejected once the name is locked (after the first interaction). + #[serde(default)] + title: Option, + /// Replace the session's own settings instance. + #[serde(default)] + settings: Option, } #[derive(Deserialize)] @@ -76,10 +83,21 @@ pub(crate) async fn create_session( let model = body .model .unwrap_or_else(|| st.service.model_name().to_string()); - let title = body.title.unwrap_or_else(|| "Nuova chat".to_string()); - let system = body.system_prompt; + let overrides = body.settings.unwrap_or_default(); + let title = body.title; let sess = with_store(&st, move |s| { - s.create_session(&title, &model, system.as_deref()) + // Copy-on-create: snapshot the global defaults, apply any overrides. + let defaults = s.get_defaults()?.unwrap_or_default(); + let settings = overrides.overlay(&defaults); + // Framework-assigned friendly name when none is given; unique vs existing. + let title = match title { + Some(t) if !t.trim().is_empty() => t, + _ => { + let taken: Vec = s.list_sessions()?.into_iter().map(|x| x.title).collect(); + name::friendly_name(&taken) + } + }; + s.create_session(&title, &model, &settings) }) .await?; Ok(Json(sess)) @@ -106,12 +124,55 @@ pub(crate) async fn delete_session( Ok(StatusCode::NO_CONTENT) } -pub(crate) async fn rename_session( +pub(crate) async fn patch_session( State(st): State, Path(id): Path, - Json(body): Json, + Json(body): Json, ) -> Result { - with_store(&st, move |s| s.rename_session(&id, &body.title)).await?; + let sess = with_store(&st, { + let id = id.clone(); + move |s| s.get_session(&id) + }) + .await? + .ok_or_else(|| Error::not_found("session not found"))?; + if let Some(title) = body.title { + if sess.name_locked { + return Err(Error::bad_request( + "the session name is immutable after the first interaction", + )); + } + let title = title.trim().to_string(); + if title.is_empty() { + return Err(Error::bad_request("name must not be empty")); + } + with_store(&st, { + let id = id.clone(); + move |s| s.rename_session(&id, &title) + }) + .await?; + } + if let Some(settings) = body.settings { + with_store(&st, move |s| s.update_settings(&id, &settings)).await?; + } + Ok(StatusCode::OK) +} + +/// The global default settings template (snapshotted into each new session). +pub(crate) async fn get_defaults( + State(st): State, +) -> Result, Error> { + Ok(Json( + with_store(&st, |s| s.get_defaults()) + .await? + .unwrap_or_default(), + )) +} + +pub(crate) async fn put_defaults( + State(st): State, + Json(body): Json, +) -> Result { + with_store(&st, move |s| s.set_defaults(&body)).await?; Ok(StatusCode::OK) } @@ -126,19 +187,6 @@ pub(crate) async fn stats(State(st): State) -> Result, Err Ok(Json(with_store(&st, |s| s.stats()).await?)) } -/// A short, single-line title derived from the first user message. -fn chat_title(content: &str) -> String { - let line = content.split_whitespace().collect::>().join(" "); - let mut t: String = line.chars().take(48).collect(); - if line.chars().count() > 48 { - t.push('…'); - } - if t.is_empty() { - t = "Nuova chat".to_string(); - } - t -} - fn role_of(s: &str) -> Role { match s { "system" | "developer" => Role::System, @@ -163,7 +211,7 @@ fn text_message(role: Role, text: String) -> ChatMessage { /// Prior `reasoning_content` is deliberately NOT replayed into the prompt. fn build_request(sess: &Session, history: &[StoredMessage], body: &SessionChat) -> ChatRequest { let mut messages = Vec::new(); - if let Some(sp) = &sess.system_prompt { + if let Some(sp) = &sess.settings.system_prompt { messages.push(text_message(Role::System, sp.clone())); } for m in history { @@ -179,16 +227,16 @@ fn build_request(sess: &Session, history: &[StoredMessage], body: &SessionChat) model: sess.model.clone(), messages, stream: body.stream, - temperature: body.temperature, - top_p: body.top_p, - max_tokens: body.max_tokens, + temperature: body.temperature.or(sess.settings.temperature), + top_p: body.top_p.or(sess.settings.top_p), + max_tokens: body.max_tokens.or(sess.settings.max_tokens), max_completion_tokens: None, - frequency_penalty: None, - presence_penalty: None, - seed: None, - top_k: None, - min_p: None, - repetition_penalty: None, + frequency_penalty: sess.settings.frequency_penalty, + presence_penalty: sess.settings.presence_penalty, + seed: sess.settings.seed, + top_k: sess.settings.top_k, + min_p: sess.settings.min_p, + repetition_penalty: sess.settings.repetition_penalty, stop: None, tools: None, tool_choice: None, @@ -307,13 +355,12 @@ pub(crate) async fn session_chat( return e.into_response(); } - // Auto-title a fresh session from its first user message, so chats are - // distinguishable in the sidebar instead of all being "Nuova chat". + // The first interaction locks the session name: it becomes the agent's + // immutable identity (and names its personal folder, created next increment). if history.is_empty() { - let title = chat_title(&body.content); let _ = with_store(&st, { let id = id.clone(); - move |s| s.rename_session(&id, &title) + move |s| s.set_name_locked(&id, true) }) .await; } @@ -462,23 +509,3 @@ async fn persist_assistant(store: &Arc, sid: &str, a: &Accum, prompt_ }) .await; } - -#[cfg(test)] -mod tests { - use super::chat_title; - - #[test] - fn title_collapses_whitespace_and_truncates() { - assert_eq!(chat_title(" ciao mondo "), "ciao mondo"); - assert_eq!(chat_title(""), "Nuova chat"); - assert_eq!(chat_title(" "), "Nuova chat"); - let long = "a".repeat(80); - let t = chat_title(&long); - assert_eq!(t.chars().count(), 49); // 48 + ellipsis - assert!(t.ends_with('…')); - // multibyte truncation stays on char boundaries - let emoji = "😀".repeat(60); - let t2 = chat_title(&emoji); - assert!(t2.chars().count() <= 49); - } -} diff --git a/src/config.rs b/src/config.rs index 61eb904..346eed0 100644 --- a/src/config.rs +++ b/src/config.rs @@ -80,6 +80,10 @@ pub struct Config { #[serde(default)] pub sampling: SamplingDefaults, + /// General default System Prompt, snapshotted into each new GUI session. + #[serde(default)] + pub system_prompt: Option, + /// Startup (wait for `READY`) and silence-watchdog timeouts, in seconds. /// Optional: both default to 600s when absent. #[serde(default)] @@ -206,6 +210,20 @@ impl Config { PathBuf::from(home).join(".config/strata-ctl/sessions.db") } + /// The global default settings template for new GUI sessions, seeded from + /// the config's general system prompt and sampling defaults. Each session + /// snapshots this at creation (copy-on-create) and then owns its instance. + pub fn default_settings(&self) -> crate::store::SessionSettings { + crate::store::SessionSettings { + system_prompt: self.system_prompt.clone(), + temperature: self.sampling.temperature, + top_p: self.sampling.top_p, + min_p: self.sampling.min_p, + repetition_penalty: self.sampling.repetition_penalty, + ..Default::default() + } + } + /// The top-level keys present in the file that we are not acting on — /// reported by `--check` so the shared-file contract stays visible. pub fn ignored_keys(&self) -> Vec<&str> { diff --git a/src/lib.rs b/src/lib.rs index ded3c4f..2fd0fc7 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -11,4 +11,5 @@ pub mod api; pub mod config; pub mod engine; pub mod inkling; +pub mod name; pub mod store; diff --git a/src/main.rs b/src/main.rs index 6df6e5b..0257ec7 100644 --- a/src/main.rs +++ b/src/main.rs @@ -189,6 +189,11 @@ async fn serve(cfg: &Config, cli_host: Option<&str>, cli_port: Option) -> E return ExitCode::FAILURE; } }; + // Seed the global default settings template from the config (once). Each + // new session snapshots these defaults at creation (copy-on-create). + if matches!(store.get_defaults(), Ok(None)) { + let _ = store.set_defaults(&cfg.default_settings()); + } let app = router_with_store(svc, store, auth); let host = cfg.bind_host(cli_host); let port = cfg.bind_port(cli_port); diff --git a/src/name.rs b/src/name.rs new file mode 100644 index 0000000..bd1bb3a --- /dev/null +++ b/src/name.rs @@ -0,0 +1,99 @@ +//! Framework-assigned session names: memorable, evocative identifiers (a curated +//! word list, adjective–noun) rather than anonymous hex or sequential numbers. +//! The name is the session's identity: user-editable only before the first +//! interaction, immutable afterwards, and it names the personal folder. The +//! descriptive "purpose" lives in the session notes instead, not in the name. + +use std::sync::atomic::{AtomicU64, Ordering}; +use std::time::{SystemTime, UNIX_EPOCH}; + +// Masculine nouns + masculine/invariant adjectives so the combinations agree. +const NOUN: &[&str] = &[ + "lupo", "fiume", "bosco", "vento", "mare", "falco", "sasso", "ramo", "fuoco", "gelso", "pino", + "scoglio", "sentiero", "prato", "lago", "monte", "colle", "porto", "faro", "ponte", +]; +const ADJ: &[&str] = &[ + "rosso", "dorato", "quieto", "antico", "veloce", "luminoso", "ombroso", "felice", "saggio", + "ribelle", "solare", "notturno", "fermo", "vivace", "placido", "rapido", "saldo", "gentile", + "fiero", "curioso", +]; + +/// A pseudo-random index without a `rand` dependency (nanos + counter mixed). +fn pick(len: usize) -> usize { + 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); + let mixed = (nanos as u64).wrapping_mul(31).wrapping_add(n); + (mixed as usize) % len +} + +/// Generate a friendly name not already present in `taken`. On collision a +/// numeric suffix is appended (`lupo-rosso-2`, `-3`, …). +pub fn friendly_name(taken: &[String]) -> String { + let base = format!("{}-{}", NOUN[pick(NOUN.len())], ADJ[pick(ADJ.len())]); + if !taken.iter().any(|t| t == &base) { + return base; + } + let mut n = 2; + loop { + let candidate = format!("{base}-{n}"); + if !taken.iter().any(|t| t == &candidate) { + return candidate; + } + n += 1; + } +} + +/// A filesystem-safe slug derived from a name: lowercase ASCII alphanumerics, +/// every other run collapsed to a single `-`, trimmed. Used for folder names. +pub fn slug(name: &str) -> String { + let mut out = String::new(); + let mut dash = false; + for c in name.chars() { + if c.is_ascii_alphanumeric() { + out.push(c.to_ascii_lowercase()); + dash = false; + } else if !dash && !out.is_empty() { + out.push('-'); + dash = true; + } + } + while out.ends_with('-') { + out.pop(); + } + if out.is_empty() { + out.push_str("sessione"); + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn name_is_friendly_and_unique() { + let mut taken: Vec = vec![]; + for _ in 0..60 { + let n = friendly_name(&taken); + assert!(n.contains('-')); + assert!(n + .chars() + .all(|c| c.is_ascii_lowercase() || c == '-' || c.is_ascii_digit())); + assert!(!taken.contains(&n), "duplicate name {n}"); + taken.push(n); + } + } + + #[test] + fn slug_is_filesystem_safe() { + assert_eq!(slug("Lupo Rosso"), "lupo-rosso"); + assert_eq!(slug(" Ciao!! Mondo "), "ciao-mondo"); + assert_eq!(slug("a/b\\c"), "a-b-c"); + assert_eq!(slug("---"), "sessione"); + assert_eq!(slug("lupo-rosso"), "lupo-rosso"); + } +} diff --git a/src/store.rs b/src/store.rs index 1cd0bf6..9c47d87 100644 --- a/src/store.rs +++ b/src/store.rs @@ -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, + /// Free-form user notes describing the purpose of this chat. + #[serde(default)] + pub notes: Option, + #[serde(default)] + pub temperature: Option, + #[serde(default)] + pub top_p: Option, + #[serde(default)] + pub top_k: Option, + #[serde(default)] + pub min_p: Option, + #[serde(default)] + pub repetition_penalty: Option, + #[serde(default)] + pub frequency_penalty: Option, + #[serde(default)] + pub presence_penalty: Option, + #[serde(default)] + pub max_tokens: Option, + #[serde(default)] + pub seed: Option, +} + +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, + 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; fn list_sessions(&self) -> Result>; fn get_session(&self, id: &str) -> Result>; 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>; fn append_message(&self, session_id: &str, msg: NewMessage<'_>) -> Result; fn stats(&self) -> Result; + /// The global default settings template (None until seeded). + fn get_defaults(&self) -> Result>; + 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 { + 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 { + let settings_json: Option = 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 = 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 { 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> { + 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(); } diff --git a/tests/api_sessions.rs b/tests/api_sessions.rs index 3bd26b2..2937827 100644 --- a/tests/api_sessions.rs +++ b/tests/api_sessions.rs @@ -301,25 +301,15 @@ async fn agent_mode_streams_events_and_persists() { } #[tokio::test] -async fn first_message_auto_titles_and_rename_delete_work() { +async fn name_is_generated_editable_then_locked() { let (app, store) = build_app().await; let id = create_session(&app).await; - assert_eq!(store.get_session(&id).unwrap().unwrap().title, "Nuova chat"); + let sess = store.get_session(&id).unwrap().unwrap(); + // Framework-assigned friendly name (not the old "Nuova chat"), unlocked. + assert!(sess.title.contains('-'), "title: {}", sess.title); + assert!(!sess.name_locked); - // First user message auto-titles the session. - req( - &app, - Method::POST, - &format!("/api/sessions/{id}/chat"), - Some(serde_json::json!({"content": "Qual è la capitale?"})), - ) - .await; - assert_eq!( - store.get_session(&id).unwrap().unwrap().title, - "Qual è la capitale?" - ); - - // Rename via PATCH. + // Rename before the first interaction is allowed. let (st, _) = req( &app, Method::PATCH, @@ -330,8 +320,103 @@ async fn first_message_auto_titles_and_rename_delete_work() { assert_eq!(st, StatusCode::OK); assert_eq!(store.get_session(&id).unwrap().unwrap().title, "Mio titolo"); - // Delete via DELETE. + // The first interaction locks the name. + req( + &app, + Method::POST, + &format!("/api/sessions/{id}/chat"), + Some(serde_json::json!({"content": "ciao"})), + ) + .await; + assert!(store.get_session(&id).unwrap().unwrap().name_locked); + + // Rename after the first interaction is rejected; the name is unchanged. + let (st, _) = req( + &app, + Method::PATCH, + &format!("/api/sessions/{id}"), + Some(serde_json::json!({"title": "Troppo tardi"})), + ) + .await; + assert_eq!(st, StatusCode::BAD_REQUEST); + assert_eq!(store.get_session(&id).unwrap().unwrap().title, "Mio titolo"); + + // Delete still works. let (st, _) = req(&app, Method::DELETE, &format!("/api/sessions/{id}"), None).await; assert_eq!(st, StatusCode::NO_CONTENT); assert!(store.get_session(&id).unwrap().is_none()); } + +#[tokio::test] +async fn settings_are_copied_on_create_and_isolated() { + let (app, store) = build_app().await; + // Seed the global defaults template. + let (st, _) = req( + &app, + Method::PUT, + "/api/settings/defaults", + Some(serde_json::json!({"system_prompt": "base", "temperature": 0.9})), + ) + .await; + assert_eq!(st, StatusCode::OK); + + // A new session snapshots the defaults. + let (st, text) = req( + &app, + Method::POST, + "/api/sessions", + Some(serde_json::json!({})), + ) + .await; + assert_eq!(st, StatusCode::OK, "{text}"); + let v: serde_json::Value = serde_json::from_str(&text).unwrap(); + let id = v["id"].as_str().unwrap().to_string(); + assert_eq!(v["settings"]["system_prompt"], "base"); + assert_eq!(v["settings"]["temperature"], 0.9); + + // Editing this session's settings affects only it. + let (st, _) = req( + &app, + Method::PATCH, + &format!("/api/sessions/{id}"), + Some(serde_json::json!({"settings": {"notes": "scopo: test", "temperature": 0.2}})), + ) + .await; + assert_eq!(st, StatusCode::OK); + let s = store.get_session(&id).unwrap().unwrap(); + assert_eq!(s.settings.notes.as_deref(), Some("scopo: test")); + assert_eq!(s.settings.temperature, Some(0.2)); + // The global defaults are untouched. + assert_eq!( + store.get_defaults().unwrap().unwrap().temperature, + Some(0.9) + ); + + // Changing the globals affects only FUTURE sessions, not the existing one. + req( + &app, + Method::PUT, + "/api/settings/defaults", + Some(serde_json::json!({"temperature": 0.5})), + ) + .await; + assert_eq!( + store + .get_session(&id) + .unwrap() + .unwrap() + .settings + .temperature, + Some(0.2) + ); + let id2 = create_session(&app).await; + assert_eq!( + store + .get_session(&id2) + .unwrap() + .unwrap() + .settings + .temperature, + Some(0.5) + ); +}