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:
adm committed 2026-11-25 15:44:52 +01:00
1 parent 0123f41d99
commit 0568b92e06
9 files changed
+555 -99

No files matched your search

+14 -2
View File
@@ -321,7 +321,13 @@ mod tests {
#[tokio::test] #[tokio::test]
async fn loop_runs_tool_then_final_and_persists_trajectory() { async fn loop_runs_tool_then_final_and_persists_trajectory() {
let store: Arc<dyn Store> = Arc::new(SqliteStore::open_in_memory().unwrap()); let store: Arc<dyn Store> = 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<dyn ShellRunner> = Arc::new(HostShell); let runner: Arc<dyn ShellRunner> = Arc::new(HostShell);
let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel(); let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
@@ -378,7 +384,13 @@ mod tests {
#[tokio::test] #[tokio::test]
async fn loop_stops_at_max_iters() { async fn loop_stops_at_max_iters() {
let store: Arc<dyn Store> = Arc::new(SqliteStore::open_in_memory().unwrap()); let store: Arc<dyn Store> = 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<dyn ShellRunner> = Arc::new(HostShell); let runner: Arc<dyn ShellRunner> = Arc::new(HostShell);
// Model always asks for a tool -> never finishes. // Model always asks for a tool -> never finishes.
let model = move |_req: ChatRequest| async { Ok(tool_call_response()) }; let model = move |_req: ChatRequest| async { Ok(tool_call_response()) };
+5 -1
View File
@@ -62,10 +62,14 @@ fn build_router(state: AppState, auth: AuthConfig) -> Router {
"/api/sessions/{id}", "/api/sessions/{id}",
get(sessions::get_session) get(sessions::get_session)
.delete(sessions::delete_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}/messages", get(sessions::get_messages))
.route("/api/sessions/{id}/chat", post(sessions::session_chat)) .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("/api/stats", get(sessions::stats))
.route("/", get(web::index)) .route("/", get(web::index))
.route("/assets/{*path}", get(web::asset)); .route("/assets/{*path}", get(web::asset));
+84 -57
View File
@@ -19,7 +19,8 @@ use super::routes::{AppState, Error};
use super::types::{ChatChunk, ChatMessage, ChatRequest, FunctionCall, Role, ToolCall, Usage}; use super::types::{ChatChunk, ChatMessage, ChatRequest, FunctionCall, Role, ToolCall, Usage};
use crate::agent::shell::{HostShell, ShellRunner}; use crate::agent::shell::{HostShell, ShellRunner};
use crate::agent::{self, AgentEvent}; 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; use tokio_stream::wrappers::UnboundedReceiverStream;
/// Run a synchronous store operation off the async runtime. /// Run a synchronous store operation off the async runtime.
@@ -44,13 +45,19 @@ pub(crate) struct CreateSession {
title: Option<String>, title: Option<String>,
#[serde(default)] #[serde(default)]
model: Option<String>, model: Option<String>,
/// Optional overrides snapshotted on top of the global defaults.
#[serde(default)] #[serde(default)]
system_prompt: Option<String>, settings: Option<SessionSettings>,
} }
#[derive(Deserialize)] #[derive(Deserialize)]
pub(crate) struct Rename { pub(crate) struct SessionPatch {
title: String, /// Rename — rejected once the name is locked (after the first interaction).
#[serde(default)]
title: Option<String>,
/// Replace the session's own settings instance.
#[serde(default)]
settings: Option<SessionSettings>,
} }
#[derive(Deserialize)] #[derive(Deserialize)]
@@ -76,10 +83,21 @@ pub(crate) async fn create_session(
let model = body let model = body
.model .model
.unwrap_or_else(|| st.service.model_name().to_string()); .unwrap_or_else(|| st.service.model_name().to_string());
let title = body.title.unwrap_or_else(|| "Nuova chat".to_string()); let overrides = body.settings.unwrap_or_default();
let system = body.system_prompt; let title = body.title;
let sess = with_store(&st, move |s| { 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<String> = s.list_sessions()?.into_iter().map(|x| x.title).collect();
name::friendly_name(&taken)
}
};
s.create_session(&title, &model, &settings)
}) })
.await?; .await?;
Ok(Json(sess)) Ok(Json(sess))
@@ -106,12 +124,55 @@ pub(crate) async fn delete_session(
Ok(StatusCode::NO_CONTENT) Ok(StatusCode::NO_CONTENT)
} }
pub(crate) async fn rename_session( pub(crate) async fn patch_session(
State(st): State<AppState>, State(st): State<AppState>,
Path(id): Path<String>, Path(id): Path<String>,
Json(body): Json<Rename>, Json(body): Json<SessionPatch>,
) -> Result<StatusCode, Error> { ) -> Result<StatusCode, Error> {
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<AppState>,
) -> Result<Json<SessionSettings>, Error> {
Ok(Json(
with_store(&st, |s| s.get_defaults())
.await?
.unwrap_or_default(),
))
}
pub(crate) async fn put_defaults(
State(st): State<AppState>,
Json(body): Json<SessionSettings>,
) -> Result<StatusCode, Error> {
with_store(&st, move |s| s.set_defaults(&body)).await?;
Ok(StatusCode::OK) Ok(StatusCode::OK)
} }
@@ -126,19 +187,6 @@ pub(crate) async fn stats(State(st): State<AppState>) -> Result<Json<Stats>, Err
Ok(Json(with_store(&st, |s| s.stats()).await?)) 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::<Vec<_>>().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 { fn role_of(s: &str) -> Role {
match s { match s {
"system" | "developer" => Role::System, "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. /// Prior `reasoning_content` is deliberately NOT replayed into the prompt.
fn build_request(sess: &Session, history: &[StoredMessage], body: &SessionChat) -> ChatRequest { fn build_request(sess: &Session, history: &[StoredMessage], body: &SessionChat) -> ChatRequest {
let mut messages = Vec::new(); 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())); messages.push(text_message(Role::System, sp.clone()));
} }
for m in history { for m in history {
@@ -179,16 +227,16 @@ fn build_request(sess: &Session, history: &[StoredMessage], body: &SessionChat)
model: sess.model.clone(), model: sess.model.clone(),
messages, messages,
stream: body.stream, stream: body.stream,
temperature: body.temperature, temperature: body.temperature.or(sess.settings.temperature),
top_p: body.top_p, top_p: body.top_p.or(sess.settings.top_p),
max_tokens: body.max_tokens, max_tokens: body.max_tokens.or(sess.settings.max_tokens),
max_completion_tokens: None, max_completion_tokens: None,
frequency_penalty: None, frequency_penalty: sess.settings.frequency_penalty,
presence_penalty: None, presence_penalty: sess.settings.presence_penalty,
seed: None, seed: sess.settings.seed,
top_k: None, top_k: sess.settings.top_k,
min_p: None, min_p: sess.settings.min_p,
repetition_penalty: None, repetition_penalty: sess.settings.repetition_penalty,
stop: None, stop: None,
tools: None, tools: None,
tool_choice: None, tool_choice: None,
@@ -307,13 +355,12 @@ pub(crate) async fn session_chat(
return e.into_response(); return e.into_response();
} }
// Auto-title a fresh session from its first user message, so chats are // The first interaction locks the session name: it becomes the agent's
// distinguishable in the sidebar instead of all being "Nuova chat". // immutable identity (and names its personal folder, created next increment).
if history.is_empty() { if history.is_empty() {
let title = chat_title(&body.content);
let _ = with_store(&st, { let _ = with_store(&st, {
let id = id.clone(); let id = id.clone();
move |s| s.rename_session(&id, &title) move |s| s.set_name_locked(&id, true)
}) })
.await; .await;
} }
@@ -462,23 +509,3 @@ async fn persist_assistant(store: &Arc<dyn Store>, sid: &str, a: &Accum, prompt_
}) })
.await; .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);
}
}
+18
View File
@@ -80,6 +80,10 @@ pub struct Config {
#[serde(default)] #[serde(default)]
pub sampling: SamplingDefaults, pub sampling: SamplingDefaults,
/// General default System Prompt, snapshotted into each new GUI session.
#[serde(default)]
pub system_prompt: Option<String>,
/// Startup (wait for `READY`) and silence-watchdog timeouts, in seconds. /// Startup (wait for `READY`) and silence-watchdog timeouts, in seconds.
/// Optional: both default to 600s when absent. /// Optional: both default to 600s when absent.
#[serde(default)] #[serde(default)]
@@ -206,6 +210,20 @@ impl Config {
PathBuf::from(home).join(".config/strata-ctl/sessions.db") 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 — /// The top-level keys present in the file that we are not acting on —
/// reported by `--check` so the shared-file contract stays visible. /// reported by `--check` so the shared-file contract stays visible.
pub fn ignored_keys(&self) -> Vec<&str> { pub fn ignored_keys(&self) -> Vec<&str> {
+1
View File
@@ -11,4 +11,5 @@ pub mod api;
pub mod config; pub mod config;
pub mod engine; pub mod engine;
pub mod inkling; pub mod inkling;
pub mod name;
pub mod store; pub mod store;
+5
View File
@@ -189,6 +189,11 @@ async fn serve(cfg: &Config, cli_host: Option<&str>, cli_port: Option<u16>) -> E
return ExitCode::FAILURE; 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 app = router_with_store(svc, store, auth);
let host = cfg.bind_host(cli_host); let host = cfg.bind_host(cli_host);
let port = cfg.bind_port(cli_port); let port = cfg.bind_port(cli_port);
+99
View File
@@ -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<String> = 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");
}
}
+227 -22
View File
@@ -3,7 +3,7 @@
//! The standard `/v1` API stays stateless; this is a separate server-side layer //! 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 //! 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, //! 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 //! Implementations are synchronous and `Send + Sync`; async handlers call them
//! through `spawn_blocking` so DB work never blocks the tokio runtime. //! 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 anyhow::{Context, Result};
use rusqlite::{params, Connection}; 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. /// A conversation session.
#[derive(Debug, Clone, serde::Serialize)] #[derive(Debug, Clone, Serialize)]
pub struct Session { pub struct Session {
pub id: String, pub id: String,
pub title: String, pub title: String,
pub model: 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 created_at: i64,
pub updated_at: i64, pub updated_at: i64,
} }
/// A persisted message (one turn) with its token usage. /// A persisted message (one turn) with its token usage.
#[derive(Debug, Clone, serde::Serialize)] #[derive(Debug, Clone, Serialize)]
pub struct StoredMessage { pub struct StoredMessage {
pub id: i64, pub id: i64,
pub role: String, pub role: String,
@@ -53,7 +110,7 @@ pub struct NewMessage<'a> {
} }
/// Aggregate counters for the stats view. /// Aggregate counters for the stats view.
#[derive(Debug, Clone, Default, serde::Serialize)] #[derive(Debug, Clone, Default, Serialize)]
pub struct Stats { pub struct Stats {
pub sessions: u64, pub sessions: u64,
pub messages: u64, pub messages: u64,
@@ -67,15 +124,20 @@ pub trait Store: Send + Sync {
&self, &self,
title: &str, title: &str,
model: &str, model: &str,
system_prompt: Option<&str>, settings: &SessionSettings,
) -> Result<Session>; ) -> Result<Session>;
fn list_sessions(&self) -> Result<Vec<Session>>; fn list_sessions(&self) -> Result<Vec<Session>>;
fn get_session(&self, id: &str) -> Result<Option<Session>>; fn get_session(&self, id: &str) -> Result<Option<Session>>;
fn rename_session(&self, id: &str, title: &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 delete_session(&self, id: &str) -> Result<()>;
fn messages(&self, session_id: &str) -> Result<Vec<StoredMessage>>; fn messages(&self, session_id: &str) -> Result<Vec<StoredMessage>>;
fn append_message(&self, session_id: &str, msg: NewMessage<'_>) -> Result<StoredMessage>; fn append_message(&self, session_id: &str, msg: NewMessage<'_>) -> Result<StoredMessage>;
fn stats(&self) -> Result<Stats>; 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 { fn now_secs() -> i64 {
@@ -102,6 +164,8 @@ CREATE TABLE IF NOT EXISTS sessions (
title TEXT NOT NULL, title TEXT NOT NULL,
model TEXT NOT NULL, model TEXT NOT NULL,
system_prompt TEXT, system_prompt TEXT,
settings_json TEXT,
name_locked INTEGER NOT NULL DEFAULT 0,
created_at INTEGER NOT NULL, created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL updated_at INTEGER NOT NULL
); );
@@ -118,6 +182,10 @@ CREATE TABLE IF NOT EXISTS messages (
created_at INTEGER NOT NULL created_at INTEGER NOT NULL
); );
CREATE INDEX IF NOT EXISTS idx_messages_session ON messages(session_id, id); 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 /// 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 /// `CREATE TABLE IF NOT EXISTS` never alters an existing table, so new columns
/// must be added explicitly when missing. /// must be added explicitly when missing.
fn migrate(conn: &Connection) -> Result<()> { fn migrate(conn: &Connection) -> Result<()> {
let has_tool_call_id: i64 = conn let has_col = |table: &str, col: &str| -> Result<bool> {
.prepare("SELECT COUNT(*) FROM pragma_table_info('messages') WHERE name = 'tool_call_id'")? let n: i64 = conn
.prepare(&format!(
"SELECT COUNT(*) FROM pragma_table_info('{table}') WHERE name = '{col}'"
))?
.query_row([], |r| r.get(0))?; .query_row([], |r| r.get(0))?;
if has_tool_call_id == 0 { Ok(n > 0)
};
if !has_col("messages", "tool_call_id")? {
conn.execute_batch("ALTER TABLE messages ADD COLUMN tool_call_id TEXT;")?; 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(()) Ok(())
} }
fn row_to_session(row: &rusqlite::Row<'_>) -> rusqlite::Result<Session> { 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 { Ok(Session {
id: row.get("id")?, id: row.get("id")?,
title: row.get("title")?, title: row.get("title")?,
model: row.get("model")?, 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")?, created_at: row.get("created_at")?,
updated_at: row.get("updated_at")?, updated_at: row.get("updated_at")?,
}) })
@@ -189,21 +288,23 @@ impl Store for SqliteStore {
&self, &self,
title: &str, title: &str,
model: &str, model: &str,
system_prompt: Option<&str>, settings: &SessionSettings,
) -> Result<Session> { ) -> Result<Session> {
let id = new_id("sess"); let id = new_id("sess");
let now = now_secs(); let now = now_secs();
let settings_json = serde_json::to_string(settings)?;
let conn = self.lock(); let conn = self.lock();
conn.execute( conn.execute(
"INSERT INTO sessions (id, title, model, system_prompt, created_at, updated_at) "INSERT INTO sessions (id, title, model, settings_json, name_locked, created_at, updated_at)
VALUES (?1, ?2, ?3, ?4, ?5, ?5)", VALUES (?1, ?2, ?3, ?4, 0, ?5, ?5)",
params![id, title, model, system_prompt, now], params![id, title, model, settings_json, now],
)?; )?;
Ok(Session { Ok(Session {
id, id,
title: title.to_string(), title: title.to_string(),
model: model.to_string(), model: model.to_string(),
system_prompt: system_prompt.map(str::to_string), settings: settings.clone(),
name_locked: false,
created_at: now, created_at: now,
updated_at: now, updated_at: now,
}) })
@@ -233,6 +334,25 @@ impl Store for SqliteStore {
Ok(()) 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<()> { fn delete_session(&self, id: &str) -> Result<()> {
let conn = self.lock(); let conn = self.lock();
conn.execute("DELETE FROM sessions WHERE id = ?1", params![id])?; conn.execute("DELETE FROM sessions WHERE id = ?1", params![id])?;
@@ -312,6 +432,26 @@ impl Store for SqliteStore {
completion_tokens: completion as u64, 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)] #[cfg(test)]
@@ -325,10 +465,16 @@ mod tests {
#[test] #[test]
fn session_crud_and_message_order() { fn session_crud_and_message_order() {
let s = store(); let s = store();
let settings = SessionSettings {
system_prompt: Some("be nice".into()),
..Default::default()
};
let sess = s let sess = s
.create_session("Chat", "Inkling-2-Mini", Some("be nice")) .create_session("Chat", "Inkling-2-Mini", &settings)
.unwrap(); .unwrap();
assert!(sess.id.starts_with("sess_")); 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); assert_eq!(s.list_sessions().unwrap().len(), 1);
s.append_message( s.append_message(
@@ -382,6 +528,49 @@ mod tests {
assert_eq!(s.list_sessions().unwrap().len(), 0); 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] #[test]
fn ids_are_unique() { fn ids_are_unique() {
let a = new_id("sess"); let a = new_id("sess");
@@ -390,22 +579,38 @@ mod tests {
} }
#[test] #[test]
fn migration_adds_tool_call_id_to_old_schema() { fn migration_adds_columns_to_old_schema() {
// Simulate a pre-existing database without the tool_call_id column. // Simulate a pre-existing database without the newer columns.
let conn = Connection::open_in_memory().unwrap(); let conn = Connection::open_in_memory().unwrap();
conn.execute_batch( 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, content TEXT, reasoning_content TEXT, tool_calls_json TEXT,
prompt_tokens INTEGER, completion_tokens INTEGER, created_at INTEGER);", prompt_tokens INTEGER, completion_tokens INTEGER, created_at INTEGER);",
) )
.unwrap(); .unwrap();
migrate(&conn).unwrap(); migrate(&conn).unwrap();
let n: i64 = conn let has = |col: &str| -> i64 {
.prepare("SELECT COUNT(*) FROM pragma_table_info('messages') WHERE name='tool_call_id'") conn.prepare(&format!(
"SELECT COUNT(*) FROM pragma_table_info('sessions') WHERE name='{col}'"
))
.unwrap() .unwrap()
.query_row([], |r| r.get(0)) .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(); .unwrap();
assert_eq!(n, 1); assert!(sj.contains("old prompt"));
// Idempotent: running again does not error. // Idempotent: running again does not error.
migrate(&conn).unwrap(); migrate(&conn).unwrap();
} }
+102 -17
View File
@@ -301,25 +301,15 @@ async fn agent_mode_streams_events_and_persists() {
} }
#[tokio::test] #[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 (app, store) = build_app().await;
let id = create_session(&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. // Rename before the first interaction is allowed.
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.
let (st, _) = req( let (st, _) = req(
&app, &app,
Method::PATCH, Method::PATCH,
@@ -330,8 +320,103 @@ async fn first_message_auto_titles_and_rename_delete_work() {
assert_eq!(st, StatusCode::OK); assert_eq!(st, StatusCode::OK);
assert_eq!(store.get_session(&id).unwrap().unwrap().title, "Mio titolo"); 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; let (st, _) = req(&app, Method::DELETE, &format!("/api/sessions/{id}"), None).await;
assert_eq!(st, StatusCode::NO_CONTENT); assert_eq!(st, StatusCode::NO_CONTENT);
assert!(store.get_session(&id).unwrap().is_none()); 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)
);
}