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
+84
-57
@@ -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<String>,
|
||||
#[serde(default)]
|
||||
model: Option<String>,
|
||||
/// Optional overrides snapshotted on top of the global defaults.
|
||||
#[serde(default)]
|
||||
system_prompt: Option<String>,
|
||||
settings: Option<SessionSettings>,
|
||||
}
|
||||
|
||||
#[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<String>,
|
||||
/// Replace the session's own settings instance.
|
||||
#[serde(default)]
|
||||
settings: Option<SessionSettings>,
|
||||
}
|
||||
|
||||
#[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<String> = 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<AppState>,
|
||||
Path(id): Path<String>,
|
||||
Json(body): Json<Rename>,
|
||||
Json(body): Json<SessionPatch>,
|
||||
) -> 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)
|
||||
}
|
||||
|
||||
@@ -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?))
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
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<dyn Store>, 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);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user