Per-session notepad: agent-curated labelled entries via the notepad tool
(set/remove/clear), injected as a pinned <NOTEPAD> section above DIALOG,
char-budgeted with a consolidate ceiling, exposed in a read-only GUI panel.
Sliding DIALOG window (src/window.rs): retains recent messages by count in
two tiers (MAIN_AREA=40 + BUFFER=10), append-only while the buffer fills so
the prompt prefix stays byte-stable for KV reuse, then stepped hysteresis
eviction snapping to user-turn boundaries (never splits a tool exchange).
window_start persisted per session; full history never deleted.
Engine prefix-cache reuse: leave DIALOG open (a moving </DIALOG> closer broke
the engine prompt_ckpt_prefix every user turn, forcing full re-prefill);
surface usage.cached_tokens as a GUI badge; fix the PerfMeter prefill gauge to
gauge over non-cached tokens; add a static sliding-window marker after the
opener so the model knows older turns are omitted.
Stats clarity: distinguish the current inference context (last_prompt_tokens,
new "Contesto attuale" card) from the cumulative lifetime token total
(relabeled "Token cumulativi ... su tutti i turni"); /api/stats carries both.
Windowed browser transcript: GET /api/sessions/{id}/messages returns only the
retained window (SQL-filtered by window_start, never loads the full history)
plus the total count, wrapped as {messages, window_start, total}; the GUI shows
a banner noting older turns are preserved server-side. Full-chat export deferred.
Settings: the session scope re-reads the persisted instance fresh from the store
(like the general scope already did), fixing a stale-cache display that looked
like the session System Prompt was not being kept.
Docs (README) refreshed; 158 tests + 3 ignored green, clippy and fmt clean.
1018 lines
35 KiB
Rust
1018 lines
35 KiB
Rust
//! Session-aware API for the web GUI: `/api/sessions...` and `/api/stats`.
|
|
//!
|
|
//! The standard `/v1` surface stays stateless; here the server owns the
|
|
//! conversation context (via the [`Store`]) so the GUI can be a thin client and
|
|
//! so multi-session, statistics and settings can grow on top. The chat endpoint
|
|
//! loads a session's history, reuses [`ChatService`] for inference (no duplicated
|
|
//! engine-driving), and persists the new turns with their token usage.
|
|
|
|
use std::collections::BTreeMap;
|
|
use std::sync::{Arc, Mutex};
|
|
|
|
use axum::extract::{Path, State};
|
|
use axum::http::StatusCode;
|
|
use axum::response::{sse::Event, sse::Sse, IntoResponse, Json};
|
|
use futures::StreamExt;
|
|
use serde::{Deserialize, Serialize};
|
|
|
|
use super::routes::{AppState, Error};
|
|
use super::service::PerfSnapshot;
|
|
use super::types::{
|
|
completion_id, now_unix, ChatChunk, ChatMessage, ChatRequest, ChatResponse, Choice,
|
|
FinishReason, FunctionCall, Role, ToolCall, Usage,
|
|
};
|
|
use super::uploads;
|
|
use crate::agent::shell::{HostShell, ShellRunner};
|
|
use crate::agent::{self, AgentEvent};
|
|
use crate::context;
|
|
use crate::i18n::t;
|
|
use crate::name;
|
|
use crate::render;
|
|
use crate::store::{
|
|
ContextSection, NewMessage, NotepadEntry, Session, SessionSettings, Stats, Store, StoredMessage,
|
|
};
|
|
use crate::window;
|
|
use tokio_stream::wrappers::UnboundedReceiverStream;
|
|
|
|
/// Run a synchronous store operation off the async runtime.
|
|
pub(crate) async fn with_store<T, F>(st: &AppState, f: F) -> Result<T, Error>
|
|
where
|
|
F: FnOnce(Arc<dyn Store>) -> anyhow::Result<T> + Send + 'static,
|
|
T: Send + 'static,
|
|
{
|
|
let store = st
|
|
.store
|
|
.clone()
|
|
.ok_or_else(|| Error::internal("no store configured"))?;
|
|
tokio::task::spawn_blocking(move || f(store))
|
|
.await
|
|
.map_err(|e| Error::internal(format!("store task failed: {e}")))?
|
|
.map_err(|e| Error::internal(format!("store error: {e}")))
|
|
}
|
|
|
|
#[derive(Deserialize)]
|
|
pub(crate) struct CreateSession {
|
|
#[serde(default)]
|
|
title: Option<String>,
|
|
#[serde(default)]
|
|
model: Option<String>,
|
|
/// Optional overrides snapshotted on top of the global defaults.
|
|
#[serde(default)]
|
|
settings: Option<SessionSettings>,
|
|
}
|
|
|
|
#[derive(Deserialize)]
|
|
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)]
|
|
pub(crate) struct SessionChat {
|
|
content: String,
|
|
#[serde(default)]
|
|
stream: bool,
|
|
/// Run the model as an agent with the `shell_exec` tool (host mode).
|
|
#[serde(default)]
|
|
agent: bool,
|
|
/// Uploaded file ids to attach to this turn (routed by kind/token count).
|
|
#[serde(default)]
|
|
attachments: Vec<String>,
|
|
#[serde(default)]
|
|
max_tokens: Option<u32>,
|
|
#[serde(default)]
|
|
temperature: Option<f64>,
|
|
#[serde(default)]
|
|
top_p: Option<f64>,
|
|
}
|
|
|
|
pub(crate) async fn create_session(
|
|
State(st): State<AppState>,
|
|
Json(body): Json<CreateSession>,
|
|
) -> Result<Json<Session>, Error> {
|
|
let model = body
|
|
.model
|
|
.unwrap_or_else(|| st.service.model_name().to_string());
|
|
let overrides = body.settings.unwrap_or_default();
|
|
let title = body.title;
|
|
let sess = with_store(&st, move |s| {
|
|
// 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))
|
|
}
|
|
|
|
pub(crate) async fn list_sessions(State(st): State<AppState>) -> Result<Json<Vec<Session>>, Error> {
|
|
Ok(Json(with_store(&st, |s| s.list_sessions()).await?))
|
|
}
|
|
|
|
pub(crate) async fn get_session(
|
|
State(st): State<AppState>,
|
|
Path(id): Path<String>,
|
|
) -> Result<Json<Session>, Error> {
|
|
let sess = with_store(&st, move |s| s.get_session(&id)).await?;
|
|
sess.map(Json)
|
|
.ok_or_else(|| Error::not_found("session not found"))
|
|
}
|
|
|
|
pub(crate) async fn delete_session(
|
|
State(st): State<AppState>,
|
|
Path(id): Path<String>,
|
|
) -> Result<StatusCode, Error> {
|
|
with_store(&st, move |s| s.delete_session(&id)).await?;
|
|
Ok(StatusCode::NO_CONTENT)
|
|
}
|
|
|
|
pub(crate) async fn patch_session(
|
|
State(st): State<AppState>,
|
|
Path(id): Path<String>,
|
|
Json(body): Json<SessionPatch>,
|
|
) -> Result<StatusCode, Error> {
|
|
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(t("error.name_locked", &[])));
|
|
}
|
|
let title = title.trim().to_string();
|
|
if title.is_empty() {
|
|
return Err(Error::bad_request(t("error.name_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)
|
|
}
|
|
|
|
/// A stored message plus, for assistant turns, server-rendered safe HTML
|
|
/// (`content_html`) so the GUI can show Markdown/LaTeX without a JS toolchain.
|
|
#[derive(Serialize)]
|
|
pub(crate) struct MessageView {
|
|
#[serde(flatten)]
|
|
msg: StoredMessage,
|
|
#[serde(skip_serializing_if = "Option::is_none")]
|
|
content_html: Option<String>,
|
|
}
|
|
|
|
/// The GUI transcript payload: the sliding-window messages (the same recent view
|
|
/// the model sees) plus metadata so the UI can tell the user older turns are
|
|
/// omitted but preserved. The full history is never shipped to the browser — an
|
|
/// agent active for months could accumulate tens of millions of tokens.
|
|
#[derive(Serialize)]
|
|
pub(crate) struct MessagesView {
|
|
messages: Vec<MessageView>,
|
|
/// First retained message id (the persisted window start; 0 = from the start).
|
|
window_start: i64,
|
|
/// Total stored messages; exceeds `messages.len()` when older turns slid out.
|
|
total: u64,
|
|
}
|
|
|
|
pub(crate) async fn get_messages(
|
|
State(st): State<AppState>,
|
|
Path(id): Path<String>,
|
|
) -> Result<Json<MessagesView>, Error> {
|
|
// The browser sees the SAME sliding window the model sees: only messages at
|
|
// or after the persisted window start, filtered in SQL (the full history is
|
|
// never loaded whole). Older turns stay in the store for a future export.
|
|
let (msgs, total, window_start) = with_store(&st, move |s| {
|
|
let ws = s.window_start(&id)?;
|
|
let (m, total) = s.message_window(&id, ws)?;
|
|
Ok((m, total, ws))
|
|
})
|
|
.await?;
|
|
let messages = msgs
|
|
.into_iter()
|
|
.map(|mut m| {
|
|
// The [SPEAKER] tag is model-context metadata; if a reply echoed it,
|
|
// hide it from the GUI (and from the rendered HTML).
|
|
if m.role == "assistant" {
|
|
m.content = context::strip_speaker_tags(&m.content);
|
|
}
|
|
let content_html = (m.role == "assistant" && !m.content.is_empty())
|
|
.then(|| render::markdown_to_safe_html(&m.content));
|
|
MessageView {
|
|
msg: m,
|
|
content_html,
|
|
}
|
|
})
|
|
.collect();
|
|
Ok(Json(MessagesView {
|
|
messages,
|
|
window_start,
|
|
total,
|
|
}))
|
|
}
|
|
|
|
/// `GET /api/sessions/{id}/notepad` — the session's pinned notepad entries
|
|
/// (read-only observability; the agent writes them via the notepad tool).
|
|
pub(crate) async fn get_notepad(
|
|
State(st): State<AppState>,
|
|
Path(id): Path<String>,
|
|
) -> Result<Json<Vec<NotepadEntry>>, Error> {
|
|
Ok(Json(with_store(&st, move |s| s.notepad(&id)).await?))
|
|
}
|
|
|
|
/// The stats dashboard payload: persistent history aggregates (from the store)
|
|
/// plus a live engine status and the since-startup performance gauge, in one
|
|
/// JSON object so the GUI renders the whole view from a single poll.
|
|
#[derive(Serialize)]
|
|
pub(crate) struct StatsResponse {
|
|
#[serde(flatten)]
|
|
totals: Stats,
|
|
engine: EngineStatus,
|
|
perf: PerfSnapshot,
|
|
}
|
|
|
|
#[derive(Serialize)]
|
|
struct EngineStatus {
|
|
model: String,
|
|
max_context: u32,
|
|
busy: bool,
|
|
}
|
|
|
|
pub(crate) async fn stats(State(st): State<AppState>) -> Result<Json<StatsResponse>, Error> {
|
|
let totals = with_store(&st, |s| s.stats()).await?;
|
|
let engine = EngineStatus {
|
|
model: st.service.model_name().to_string(),
|
|
max_context: st.service.max_context(),
|
|
busy: !st.service.is_idle(),
|
|
};
|
|
Ok(Json(StatsResponse {
|
|
totals,
|
|
engine,
|
|
perf: st.service.perf(),
|
|
}))
|
|
}
|
|
|
|
/// Ambient context inputs resolved from the store + global defaults for one
|
|
/// turn: the human speaker name, the static sections and the session notepad.
|
|
/// Bundled so `build_request` stays within the argument-count lint.
|
|
struct Ambient<'a> {
|
|
user_name: &'a str,
|
|
sections: &'a [ContextSection],
|
|
notepad: &'a [NotepadEntry],
|
|
}
|
|
|
|
/// Rebuild a stateless [`ChatRequest`] from the stored history plus the new turn.
|
|
/// Prior `reasoning_content` is deliberately NOT replayed into the prompt.
|
|
fn build_request(
|
|
sess: &Session,
|
|
history: &[StoredMessage],
|
|
body: &SessionChat,
|
|
extra: &str,
|
|
images: &[serde_json::Value],
|
|
ambient: Ambient<'_>,
|
|
) -> ChatRequest {
|
|
let user_content = format!("{}{}", body.content, extra);
|
|
let messages = context::compose(
|
|
sess,
|
|
history,
|
|
&user_content,
|
|
images,
|
|
ambient.user_name,
|
|
ambient.sections,
|
|
ambient.notepad,
|
|
);
|
|
ChatRequest {
|
|
model: sess.model.clone(),
|
|
messages,
|
|
stream: body.stream,
|
|
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: 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,
|
|
}
|
|
}
|
|
|
|
/// Accumulates the assistant turn while streaming, for persistence at the end.
|
|
#[derive(Default, Clone)]
|
|
struct Accum {
|
|
content: String,
|
|
reasoning: String,
|
|
tools: BTreeMap<u64, ToolCall>,
|
|
usage: Option<Usage>,
|
|
}
|
|
|
|
fn accumulate(a: &mut Accum, chunk: &ChatChunk) {
|
|
if let Some(u) = &chunk.usage {
|
|
a.usage = Some(u.clone());
|
|
}
|
|
let Some(ch) = chunk.choices.first() else {
|
|
return;
|
|
};
|
|
let d = &ch.delta;
|
|
if let Some(c) = &d.content {
|
|
a.content.push_str(c);
|
|
}
|
|
if let Some(r) = &d.reasoning_content {
|
|
a.reasoning.push_str(r);
|
|
}
|
|
if let Some(tc) = &d.tool_calls {
|
|
if let Some(arr) = tc.as_array() {
|
|
for item in arr {
|
|
let idx = item.get("index").and_then(|v| v.as_u64()).unwrap_or(0);
|
|
let entry = a.tools.entry(idx).or_insert_with(|| ToolCall {
|
|
id: String::new(),
|
|
kind: "function".to_string(),
|
|
function: FunctionCall {
|
|
name: String::new(),
|
|
arguments: String::new(),
|
|
},
|
|
});
|
|
if let Some(id) = item.get("id").and_then(|v| v.as_str()) {
|
|
if !id.is_empty() {
|
|
entry.id = id.to_string();
|
|
}
|
|
}
|
|
if let Some(f) = item.get("function") {
|
|
if let Some(n) = f.get("name").and_then(|v| v.as_str()) {
|
|
entry.function.name.push_str(n);
|
|
}
|
|
if let Some(args) = f.get("arguments").and_then(|v| v.as_str()) {
|
|
entry.function.arguments.push_str(args);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
/// `POST /api/sessions/{id}/chat` — append a user turn, run inference over the
|
|
/// stored context, persist the assistant turn (with usage), and reply (SSE when
|
|
/// `stream`).
|
|
pub(crate) async fn session_chat(
|
|
State(st): State<AppState>,
|
|
Path(id): Path<String>,
|
|
Json(body): Json<SessionChat>,
|
|
) -> axum::response::Response {
|
|
let store = match st.store.clone() {
|
|
Some(s) => s,
|
|
None => return Error::internal("no store configured").into_response(),
|
|
};
|
|
|
|
let mut sess = match with_store(&st, {
|
|
let id = id.clone();
|
|
move |s| s.get_session(&id)
|
|
})
|
|
.await
|
|
{
|
|
Ok(Some(s)) => s,
|
|
Ok(None) => return Error::not_found("session not found").into_response(),
|
|
Err(e) => return e.into_response(),
|
|
};
|
|
let history = match with_store(&st, {
|
|
let id = id.clone();
|
|
move |s| s.messages(&id)
|
|
})
|
|
.await
|
|
{
|
|
Ok(h) => h,
|
|
Err(e) => return e.into_response(),
|
|
};
|
|
|
|
// The first interaction locks the name and creates the session's personal
|
|
// workspace folder (its identity). Done before building the prompt so the
|
|
// identity reminder can reference the folder.
|
|
if history.is_empty() {
|
|
let root = st.workspace_root.join("sessions");
|
|
let title = sess.title.clone();
|
|
let idc = id.clone();
|
|
if let Ok(folder) = with_store(&st, move |s| {
|
|
s.set_name_locked(&idc, true)?;
|
|
let slug = name::slug(&title);
|
|
let mut candidate = root.join(&slug);
|
|
let mut n = 2;
|
|
while candidate.exists() {
|
|
candidate = root.join(format!("{slug}-{n}"));
|
|
n += 1;
|
|
}
|
|
std::fs::create_dir_all(&candidate)?;
|
|
let path = candidate.to_string_lossy().into_owned();
|
|
s.set_folder(&idc, &path)?;
|
|
Ok(path)
|
|
})
|
|
.await
|
|
{
|
|
sess.folder = Some(folder);
|
|
}
|
|
}
|
|
|
|
// Resolve attachments (upload ids) into metadata and route by kind/tokens.
|
|
let mut metas = Vec::new();
|
|
for aid in &body.attachments {
|
|
let aid = aid.clone();
|
|
if let Ok(Some(m)) = with_store(&st, move |s| s.get_upload(&aid)).await {
|
|
metas.push(m);
|
|
}
|
|
}
|
|
let extra = uploads::context_text(&metas);
|
|
let images = uploads::image_parts(&metas);
|
|
// The human speaker name is global and read live (the same person across
|
|
// every chat), not the session's copy-on-create snapshot. Empty -> "User".
|
|
let defaults = match with_store(&st, |s| s.get_defaults()).await {
|
|
Ok(d) => d,
|
|
Err(e) => return e.into_response(),
|
|
};
|
|
let user_name = defaults
|
|
.and_then(|d| d.user_name)
|
|
.map(|n| n.trim().to_string())
|
|
.filter(|n| !n.is_empty())
|
|
.unwrap_or_else(|| "User".to_string());
|
|
let sections = match with_store(&st, |s| s.context_sections()).await {
|
|
Ok(v) => v,
|
|
Err(e) => return e.into_response(),
|
|
};
|
|
let notepad = match with_store(&st, {
|
|
let id = id.clone();
|
|
move |s| s.notepad(&id)
|
|
})
|
|
.await
|
|
{
|
|
Ok(v) => v,
|
|
Err(e) => return e.into_response(),
|
|
};
|
|
// Sliding DIALOG window: retain the most recent messages by COUNT (main area
|
|
// + buffer headroom), with stepped eviction so the prefix stays byte-stable
|
|
// for KV-cache reuse. Full history stays in SQLite; the agent pins what
|
|
// matters in the notepad. A total-size (char/token) cut is deferred.
|
|
let user_content = format!("{}{}", body.content, extra);
|
|
let window_start = match with_store(&st, {
|
|
let id = id.clone();
|
|
move |s| s.window_start(&id)
|
|
})
|
|
.await
|
|
{
|
|
Ok(v) => v,
|
|
Err(e) => return e.into_response(),
|
|
};
|
|
let sel = window::select(&history, window_start);
|
|
if sel.start_id != window_start {
|
|
let start_id = sel.start_id;
|
|
let idc = id.clone();
|
|
if let Err(e) = with_store(&st, move |s| s.set_window_start(&idc, start_id)).await {
|
|
return e.into_response();
|
|
}
|
|
}
|
|
let mut req = build_request(
|
|
&sess,
|
|
&history[sel.start..],
|
|
&body,
|
|
&extra,
|
|
&images,
|
|
Ambient {
|
|
user_name: &user_name,
|
|
sections: §ions,
|
|
notepad: ¬epad,
|
|
},
|
|
);
|
|
|
|
// Persist the user turn (text + attachment context) before generating.
|
|
if let Err(e) = with_store(&st, {
|
|
let id = id.clone();
|
|
move |s| {
|
|
s.append_message(
|
|
&id,
|
|
NewMessage {
|
|
role: "user",
|
|
content: &user_content,
|
|
reasoning_content: None,
|
|
tool_calls_json: None,
|
|
tool_call_id: None,
|
|
prompt_tokens: 0,
|
|
completion_tokens: 0,
|
|
},
|
|
)
|
|
}
|
|
})
|
|
.await
|
|
{
|
|
return e.into_response();
|
|
}
|
|
|
|
// Agent mode: drive the model↔shell_exec loop, streaming progress events.
|
|
if body.agent {
|
|
req.tools = Some(agent::agent_tools());
|
|
req.tool_choice = Some(serde_json::json!("auto"));
|
|
let (tx, rx) = tokio::sync::mpsc::unbounded_channel::<AgentEvent>();
|
|
let svc = st.service.clone();
|
|
let store2 = store.clone();
|
|
let sid = id.clone();
|
|
let folder = sess.folder.clone();
|
|
let tx_model = tx.clone();
|
|
tokio::spawn(async move {
|
|
// Streaming model step: emit Delta events while generating (so the GUI
|
|
// shows thinking + final answer live), then return the accumulated
|
|
// response for the loop's tool detection and persistence.
|
|
let model = move |r: ChatRequest| {
|
|
let svc = svc.clone();
|
|
let tx = tx_model.clone();
|
|
async move {
|
|
let (mut stream, prompt_len) = svc.stream(&r).await?;
|
|
let mut acc = Accum::default();
|
|
let mut finish = FinishReason::Stop;
|
|
while let Some(chunk) = stream.next().await {
|
|
if let Some(ch) = chunk.choices.first() {
|
|
let d = &ch.delta;
|
|
if d.content.is_some() || d.reasoning_content.is_some() {
|
|
let _ = tx.send(AgentEvent::Delta {
|
|
content: d.content.clone(),
|
|
reasoning: d.reasoning_content.clone(),
|
|
});
|
|
}
|
|
if let Some(f) = &ch.finish_reason {
|
|
finish = *f;
|
|
}
|
|
}
|
|
accumulate(&mut acc, &chunk);
|
|
}
|
|
let tools: Vec<ToolCall> = acc.tools.values().cloned().collect();
|
|
let has_tools = !tools.is_empty();
|
|
let usage = acc.usage.unwrap_or_else(|| Usage::new(prompt_len, 0));
|
|
Ok(ChatResponse {
|
|
id: completion_id(),
|
|
object: "chat.completion",
|
|
created: now_unix(),
|
|
model: r.model.clone(),
|
|
choices: vec![Choice {
|
|
index: 0,
|
|
message: ChatMessage {
|
|
role: Role::Assistant,
|
|
content: (!acc.content.is_empty()).then(|| {
|
|
serde_json::Value::String(context::strip_speaker_tags(
|
|
&acc.content,
|
|
))
|
|
}),
|
|
tool_call_id: None,
|
|
tool_calls: has_tools.then_some(tools),
|
|
name: None,
|
|
reasoning_content: (!acc.reasoning.is_empty())
|
|
.then_some(acc.reasoning),
|
|
},
|
|
finish_reason: if has_tools {
|
|
FinishReason::ToolCalls
|
|
} else {
|
|
finish
|
|
},
|
|
}],
|
|
usage,
|
|
})
|
|
}
|
|
};
|
|
// The host shell behind the ShellRunner seam (no per-tool sandbox:
|
|
// protection is where the framework runs). Commands default to the
|
|
// session's personal folder (its home base).
|
|
let runner: Arc<dyn ShellRunner> = Arc::new(HostShell);
|
|
if let Err(env) = agent::run_loop(
|
|
model,
|
|
agent::LoopContext {
|
|
runner,
|
|
store: store2,
|
|
default_cwd: folder,
|
|
max_iters: agent::MAX_ITERS,
|
|
progress: Some(tx.clone()),
|
|
},
|
|
&sid,
|
|
req,
|
|
)
|
|
.await
|
|
{
|
|
let _ = tx.send(AgentEvent::Error {
|
|
message: env.error.message,
|
|
});
|
|
}
|
|
});
|
|
let events = UnboundedReceiverStream::new(rx)
|
|
.map(|ev| {
|
|
let mut val = match serde_json::to_value(&ev) {
|
|
Ok(v) => v,
|
|
Err(e) => {
|
|
tracing::error!(error = %e, "failed to serialize agent event");
|
|
return Ok(Event::default().data("{}"));
|
|
}
|
|
};
|
|
// The final answer carries server-rendered safe HTML so the GUI
|
|
// can swap the streamed plain text for Markdown/LaTeX at the end.
|
|
if let AgentEvent::Final { response } = &ev {
|
|
let html = response
|
|
.choices
|
|
.first()
|
|
.and_then(|c| c.message.text())
|
|
.filter(|t| !t.is_empty())
|
|
.map(render::markdown_to_safe_html);
|
|
if let (Some(html), Some(obj)) = (html, val.as_object_mut()) {
|
|
obj.insert("content_html".to_string(), serde_json::Value::String(html));
|
|
}
|
|
}
|
|
match Event::default().json_data(&val) {
|
|
Ok(e) => Ok::<_, std::convert::Infallible>(e),
|
|
Err(e) => {
|
|
tracing::error!(error = %e, "failed to serialize agent event");
|
|
Ok(Event::default().data("{}"))
|
|
}
|
|
}
|
|
})
|
|
.chain(futures::stream::once(async {
|
|
Ok::<_, std::convert::Infallible>(Event::default().data("[DONE]"))
|
|
}));
|
|
return Sse::new(events)
|
|
.keep_alive(
|
|
axum::response::sse::KeepAlive::new()
|
|
.interval(std::time::Duration::from_secs(10))
|
|
.text("ping"),
|
|
)
|
|
.into_response();
|
|
}
|
|
|
|
if body.stream {
|
|
match st.service.stream(&req).await {
|
|
Ok((stream, prompt_len)) => {
|
|
let acc = Arc::new(Mutex::new(Accum::default()));
|
|
let acc_map = acc.clone();
|
|
let events = stream.map(move |chunk| {
|
|
accumulate(&mut acc_map.lock().unwrap(), &chunk);
|
|
match Event::default().json_data(&chunk) {
|
|
Ok(ev) => Ok::<_, std::convert::Infallible>(ev),
|
|
Err(e) => {
|
|
tracing::error!(error = %e, "failed to serialize SSE chunk");
|
|
Ok(Event::default().data("{}"))
|
|
}
|
|
}
|
|
});
|
|
let acc_end = acc.clone();
|
|
let sid = id.clone();
|
|
let tail = futures::stream::once(async move {
|
|
let a = acc_end.lock().unwrap().clone();
|
|
persist_assistant(&store, &sid, &a, prompt_len).await;
|
|
Ok::<_, std::convert::Infallible>(Event::default().data("[DONE]"))
|
|
});
|
|
Sse::new(events.chain(tail))
|
|
.keep_alive(
|
|
axum::response::sse::KeepAlive::new()
|
|
.interval(std::time::Duration::from_secs(10))
|
|
.text("ping"),
|
|
)
|
|
.into_response()
|
|
}
|
|
Err(env) => Error::from_envelope(env).into_response(),
|
|
}
|
|
} else {
|
|
match st.service.complete(&req).await {
|
|
Ok(resp) => {
|
|
let msg = &resp.choices[0].message;
|
|
let a = Accum {
|
|
content: msg.text().unwrap_or("").to_string(),
|
|
reasoning: msg.reasoning_content.clone().unwrap_or_default(),
|
|
tools: msg
|
|
.tool_calls
|
|
.clone()
|
|
.unwrap_or_default()
|
|
.into_iter()
|
|
.enumerate()
|
|
.map(|(i, t)| (i as u64, t))
|
|
.collect(),
|
|
usage: Some(resp.usage.clone()),
|
|
};
|
|
persist_assistant(&store, &id, &a, resp.usage.prompt_tokens).await;
|
|
Json(resp).into_response()
|
|
}
|
|
Err(env) => Error::from_envelope(env).into_response(),
|
|
}
|
|
}
|
|
}
|
|
|
|
async fn persist_assistant(store: &Arc<dyn Store>, sid: &str, a: &Accum, prompt_len: u32) {
|
|
let tool_json = if a.tools.is_empty() {
|
|
None
|
|
} else {
|
|
serde_json::to_string(&a.tools.values().collect::<Vec<_>>()).ok()
|
|
};
|
|
let (pt, ct) = a
|
|
.usage
|
|
.as_ref()
|
|
.map(|u| (u.prompt_tokens, u.completion_tokens))
|
|
.unwrap_or((prompt_len, 0));
|
|
let content = context::strip_speaker_tags(&a.content);
|
|
let reasoning = if a.reasoning.is_empty() {
|
|
None
|
|
} else {
|
|
Some(a.reasoning.clone())
|
|
};
|
|
let sid = sid.to_string();
|
|
let store = store.clone();
|
|
let _ = tokio::task::spawn_blocking(move || {
|
|
store.append_message(
|
|
&sid,
|
|
NewMessage {
|
|
role: "assistant",
|
|
content: &content,
|
|
reasoning_content: reasoning.as_deref(),
|
|
tool_calls_json: tool_json.as_deref(),
|
|
tool_call_id: None,
|
|
prompt_tokens: pt,
|
|
completion_tokens: ct,
|
|
},
|
|
)
|
|
})
|
|
.await;
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn build_request_prepends_identity_reminder_then_sp() {
|
|
let sess = Session {
|
|
id: "s".into(),
|
|
title: "Pippo".into(),
|
|
model: "m".into(),
|
|
settings: SessionSettings {
|
|
system_prompt: Some("sii breve".into()),
|
|
..Default::default()
|
|
},
|
|
name_locked: true,
|
|
folder: Some("/tmp/pippo".into()),
|
|
created_at: 0,
|
|
updated_at: 0,
|
|
};
|
|
let body = SessionChat {
|
|
content: "ciao".into(),
|
|
stream: false,
|
|
agent: false,
|
|
attachments: Vec::new(),
|
|
max_tokens: None,
|
|
temperature: None,
|
|
top_p: None,
|
|
};
|
|
let req = build_request(
|
|
&sess,
|
|
&[],
|
|
&body,
|
|
"",
|
|
&[],
|
|
Ambient {
|
|
user_name: "Federico",
|
|
sections: &[sp_section()],
|
|
notepad: &[],
|
|
},
|
|
);
|
|
// SYSTEM_PROMPT section wraps identity + session SP; DIALOG opens (no closer).
|
|
assert!(matches!(req.messages[0].role, Role::System));
|
|
let t0 = req.messages[0].text().unwrap();
|
|
assert!(t0.starts_with("<SYSTEM_PROMPT>"));
|
|
assert!(t0.contains("Pippo") && t0.contains("/tmp/pippo"));
|
|
assert!(t0.contains("sii breve"));
|
|
assert!(t0.ends_with("</SYSTEM_PROMPT>\n\n"));
|
|
assert_eq!(req.messages[1].text().unwrap(), "<DIALOG>\n");
|
|
let user = &req.messages[req.messages.len() - 1];
|
|
assert!(matches!(user.role, Role::User));
|
|
// The new user turn carries the human speaker tag.
|
|
assert!(user.text().unwrap().starts_with("[SPEAKER: Federico - "));
|
|
assert!(user.text().unwrap().ends_with("ciao"));
|
|
// DIALOG stays open: no moving </DIALOG> closer (it would break the
|
|
// engine's prefix checkpoint every user turn).
|
|
assert!(!req
|
|
.messages
|
|
.iter()
|
|
.any(|m| m.text().unwrap_or("").contains("</DIALOG>")));
|
|
}
|
|
|
|
fn sp_section() -> ContextSection {
|
|
ContextSection {
|
|
name: "SYSTEM_PROMPT".into(),
|
|
content: "{identity}{speaker_note}\n{session_prompt}".into(),
|
|
position: 0,
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn build_request_tags_history_with_speaker_and_time() {
|
|
let sess = Session {
|
|
id: "s".into(),
|
|
title: "Nebula".into(),
|
|
model: "m".into(),
|
|
settings: SessionSettings::default(),
|
|
name_locked: true,
|
|
folder: None,
|
|
created_at: 0,
|
|
updated_at: 0,
|
|
};
|
|
let history = vec![
|
|
StoredMessage {
|
|
id: 1,
|
|
role: "user".into(),
|
|
content: "domanda".into(),
|
|
reasoning_content: None,
|
|
tool_calls_json: None,
|
|
tool_call_id: None,
|
|
prompt_tokens: 0,
|
|
completion_tokens: 0,
|
|
created_at: 1_000_000_000,
|
|
},
|
|
StoredMessage {
|
|
id: 2,
|
|
role: "assistant".into(),
|
|
content: "risposta".into(),
|
|
reasoning_content: None,
|
|
tool_calls_json: None,
|
|
tool_call_id: None,
|
|
prompt_tokens: 0,
|
|
completion_tokens: 0,
|
|
created_at: 1_000_000_001,
|
|
},
|
|
];
|
|
let body = SessionChat {
|
|
content: "ok".into(),
|
|
stream: false,
|
|
agent: false,
|
|
attachments: Vec::new(),
|
|
max_tokens: None,
|
|
temperature: None,
|
|
top_p: None,
|
|
};
|
|
let req = build_request(
|
|
&sess,
|
|
&history,
|
|
&body,
|
|
"",
|
|
&[],
|
|
Ambient {
|
|
user_name: "User",
|
|
sections: &[sp_section()],
|
|
notepad: &[],
|
|
},
|
|
);
|
|
// messages: [SYSTEM_PROMPT, <DIALOG>, window-marker, user(hist), assistant(hist), user(new)]
|
|
let u = req.messages[3].text().unwrap();
|
|
assert!(u.starts_with("[SPEAKER: User - "));
|
|
assert!(u.ends_with("domanda"));
|
|
let a = req.messages[4].text().unwrap();
|
|
assert!(a.starts_with("[SPEAKER: Nebula - "));
|
|
assert!(a.ends_with("risposta"));
|
|
}
|
|
|
|
#[test]
|
|
fn build_request_does_not_stack_echoed_speaker_tag() {
|
|
let sess = Session {
|
|
id: "s".into(),
|
|
title: "Nebula".into(),
|
|
model: "m".into(),
|
|
settings: SessionSettings::default(),
|
|
name_locked: true,
|
|
folder: None,
|
|
created_at: 0,
|
|
updated_at: 0,
|
|
};
|
|
let history = vec![StoredMessage {
|
|
id: 1,
|
|
role: "assistant".into(),
|
|
content: "[SPEAKER: Nebula - 2026-11-25 21:09] risposta".into(),
|
|
reasoning_content: None,
|
|
tool_calls_json: None,
|
|
tool_call_id: None,
|
|
prompt_tokens: 0,
|
|
completion_tokens: 0,
|
|
created_at: 1_000_000_001,
|
|
}];
|
|
let body = SessionChat {
|
|
content: "ok".into(),
|
|
stream: false,
|
|
agent: false,
|
|
attachments: Vec::new(),
|
|
max_tokens: None,
|
|
temperature: None,
|
|
top_p: None,
|
|
};
|
|
let req = build_request(
|
|
&sess,
|
|
&history,
|
|
&body,
|
|
"",
|
|
&[],
|
|
Ambient {
|
|
user_name: "User",
|
|
sections: &[sp_section()],
|
|
notepad: &[],
|
|
},
|
|
);
|
|
let a = req.messages[3].text().unwrap();
|
|
assert_eq!(a.matches("[SPEAKER:").count(), 1, "exactly one tag: {a}");
|
|
assert!(a.ends_with("risposta"));
|
|
}
|
|
|
|
#[test]
|
|
fn build_request_wraps_static_sections_and_dialog() {
|
|
let sess = Session {
|
|
id: "s".into(),
|
|
title: "Nebula".into(),
|
|
model: "m".into(),
|
|
settings: SessionSettings::default(),
|
|
name_locked: true,
|
|
folder: None,
|
|
created_at: 0,
|
|
updated_at: 0,
|
|
};
|
|
let body = SessionChat {
|
|
content: "ciao".into(),
|
|
stream: false,
|
|
agent: false,
|
|
attachments: Vec::new(),
|
|
max_tokens: None,
|
|
temperature: None,
|
|
top_p: None,
|
|
};
|
|
let sections = vec![
|
|
sp_section(),
|
|
ContextSection {
|
|
name: "TOOL_USE".into(),
|
|
content: "manuale".into(),
|
|
position: 1,
|
|
},
|
|
];
|
|
let req = build_request(
|
|
&sess,
|
|
&[],
|
|
&body,
|
|
"",
|
|
&[],
|
|
Ambient {
|
|
user_name: "User",
|
|
sections: §ions,
|
|
notepad: &[],
|
|
},
|
|
);
|
|
assert!(req.messages[0]
|
|
.text()
|
|
.unwrap()
|
|
.starts_with("<SYSTEM_PROMPT>"));
|
|
assert!(req.messages[0]
|
|
.text()
|
|
.unwrap()
|
|
.ends_with("</SYSTEM_PROMPT>\n\n"));
|
|
assert_eq!(
|
|
req.messages[1].text().unwrap(),
|
|
"<TOOL_USE>\nmanuale\n</TOOL_USE>\n\n"
|
|
);
|
|
assert_eq!(req.messages[2].text().unwrap(), "<DIALOG>\n");
|
|
// The new user turn is last; DIALOG is left open (no moving closer).
|
|
assert!(matches!(req.messages.last().unwrap().role, Role::User));
|
|
assert!(!req
|
|
.messages
|
|
.iter()
|
|
.any(|m| m.text().unwrap_or("").contains("</DIALOG>")));
|
|
}
|
|
}
|