Files
strata-ctl/src/api/sessions.rs
T
adm 1e13caa4ed Add mobile-first web GUI with a server-side session store (SQLite)
- store: a swappable Store trait + bundled-SQLite implementation (WAL,
  sessions/messages with per-turn token usage, cascade delete). The standard
  /v1 API stays stateless; conversation context lives server-side so
  multi-session, statistics and advanced settings can grow on top. DB path
  configurable (db_path, default ~/.config/strata-ctl/sessions.db).
- api::sessions: session-aware GUI API — session CRUD, history, POST .../chat
  (loads stored context, reuses the completion service, persists new turns with
  usage; streaming accumulates the assistant turn and persists before [DONE]),
  and /api/stats.
- api::web + web/: a mobile-first chat GUI (vanilla ES modules, no build step),
  embedded via rust-embed and served at GET / (same-origin, offline, single
  binary). Off-canvas session drawer on phones, persistent sidebar on wide
  screens; live streaming with a collapsible thinking panel; model output is
  inserted via textContent only.
- router_with_store mounts the GUI + session API only when a store is configured;
  router()/router_with_auth() are unchanged (API-only).
- Fix: a global [hidden]{display:none!important} reset so an author display rule
  (the stats modal's display:flex) cannot defeat the hidden attribute.

7 new tests (2 store unit + 4 session HTTP end-to-end + 1 config); 94 green +
2 ignored; clippy/fmt clean. Validated live on engine 0.1.67 (context retention,
streaming, stats) and via a browser check (modal, send/render, stats open/close).
Future: the Store backend is intended to move to ArangoDB (multi-model).
2026-11-24 20:38:24 +01:00

381 lines
12 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;
use super::routes::{AppState, Error};
use super::types::{ChatChunk, ChatMessage, ChatRequest, FunctionCall, Role, ToolCall, Usage};
use crate::store::{NewMessage, Session, Stats, Store, StoredMessage};
/// Run a synchronous store operation off the async runtime.
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>,
#[serde(default)]
system_prompt: Option<String>,
}
#[derive(Deserialize)]
pub(crate) struct Rename {
title: String,
}
#[derive(Deserialize)]
pub(crate) struct SessionChat {
content: String,
#[serde(default)]
stream: bool,
#[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 title = body.title.unwrap_or_else(|| "Nuova chat".to_string());
let system = body.system_prompt;
let sess = with_store(&st, move |s| {
s.create_session(&title, &model, system.as_deref())
})
.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 rename_session(
State(st): State<AppState>,
Path(id): Path<String>,
Json(body): Json<Rename>,
) -> Result<StatusCode, Error> {
with_store(&st, move |s| s.rename_session(&id, &body.title)).await?;
Ok(StatusCode::OK)
}
pub(crate) async fn get_messages(
State(st): State<AppState>,
Path(id): Path<String>,
) -> Result<Json<Vec<StoredMessage>>, Error> {
Ok(Json(with_store(&st, move |s| s.messages(&id)).await?))
}
pub(crate) async fn stats(State(st): State<AppState>) -> Result<Json<Stats>, Error> {
Ok(Json(with_store(&st, |s| s.stats()).await?))
}
fn role_of(s: &str) -> Role {
match s {
"system" | "developer" => Role::System,
"assistant" => Role::Assistant,
"tool" => Role::Tool,
_ => Role::User,
}
}
fn text_message(role: Role, text: String) -> ChatMessage {
ChatMessage {
role,
content: Some(serde_json::Value::String(text)),
tool_call_id: None,
tool_calls: None,
name: None,
reasoning_content: None,
}
}
/// 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) -> ChatRequest {
let mut messages = Vec::new();
if let Some(sp) = &sess.system_prompt {
messages.push(text_message(Role::System, sp.clone()));
}
for m in history {
let mut msg = text_message(role_of(&m.role), m.content.clone());
msg.tool_calls = m
.tool_calls_json
.as_deref()
.and_then(|s| serde_json::from_str(s).ok());
messages.push(msg);
}
messages.push(text_message(Role::User, body.content.clone()));
ChatRequest {
model: sess.model.clone(),
messages,
stream: body.stream,
temperature: body.temperature,
top_p: body.top_p,
max_tokens: body.max_tokens,
max_completion_tokens: None,
frequency_penalty: None,
presence_penalty: None,
seed: None,
top_k: None,
min_p: None,
repetition_penalty: None,
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 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(),
};
let req = build_request(&sess, &history, &body);
// Persist the user turn before generating.
let user_content = body.content.clone();
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,
prompt_tokens: 0,
completion_tokens: 0,
},
)
}
})
.await
{
return e.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 = a.content.clone();
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(),
prompt_tokens: pt,
completion_tokens: ct,
},
)
})
.await;
}