Files
strata-ctl/tests/api_sessions.rs
T
adm 765c197b95 Add a live statistics dashboard over persistent history
Replace the four-row stats modal with a real dashboard — our own angle on
the reference's ephemeral request monitor: because our context lives in
SQLite we can aggregate over ALL history, not just the last N requests.

Backend:
- Usage carries the engine's prompt_ms/decode_ms (from DONE); a token-
  weighted in-memory PerfMeter in ChatService records every served
  request (complete + stream) and exposes decode/prefill tok/s.
- store::Stats grows total_tokens, tool_calls (json_array_length over
  assistant tool_calls_json), a per-session breakdown (busiest first)
  and a per-UTC-day token series; all over existing columns, no schema
  change, still behind the Store trait.
- GET /api/stats returns the store aggregates flattened plus a live
  engine status (model, max_context, busy) and the perf gauge.

Frontend (mobile-first, vanilla, i18n catalog):
- Overview cards: engine state dot + model + context, decode speed
  (run average) + prefill, total/prompt/completion tokens, sessions +
  messages, tool calls, requests served.
- Daily stacked prompt/completion bar chart (continuous zero-filled
  UTC window, last 30 days) and per-session token-share bars.
- Polls every 2s while open, re-renders only on change; closes via
  button, backdrop or Escape.

Tests: new store breakdown test + extended stats integration assertions
(124 passed, 2 ignored). Verified live on the real engine: decode/prefill
gauge populated from DONE timings; dashboard renders on desktop.
2026-11-25 17:52:38 +01:00

560 lines
18 KiB
Rust

//! End-to-end tests of the session-aware GUI API (`/api/sessions...`): the
//! server holds context across turns, persists messages + usage, streams, and
//! serves the embedded web GUI. Driven through the mock engine + a byte
//! formatter, with an in-memory SQLite store.
use std::sync::Arc;
use std::time::Duration;
use axum::body::Body;
use axum::http::{header::CONTENT_TYPE, Method, Request, StatusCode};
use tower::ServiceExt;
use strata_ctl::api::formatter::{Decoder, Formatter, Piece, Prompt};
use strata_ctl::api::service::ChatService;
use strata_ctl::api::types::{ApiErrorEnvelope, ChatRequest};
use strata_ctl::api::{router_with_store, AuthConfig};
use strata_ctl::engine::Engine;
use strata_ctl::store::{SqliteStore, Store};
const MOCK: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/tests/mock_engine.py");
struct ByteFormatter;
impl Formatter for ByteFormatter {
fn model_name(&self) -> &str {
"test-model"
}
fn build_prompt(&self, req: &ChatRequest) -> Result<Prompt, ApiErrorEnvelope> {
let text = req
.messages
.iter()
.rev()
.find_map(|m| m.text())
.unwrap_or("")
.to_string();
Ok(Prompt {
ids: text.bytes().map(u32::from).collect(),
max_new: req.max_new(64),
sampling: Default::default(),
temp_files: Vec::new(),
})
}
fn decoder(&self) -> Box<dyn Decoder> {
Box::new(ByteDecoder)
}
}
struct ByteDecoder;
impl Decoder for ByteDecoder {
fn push(&mut self, id: u32) -> Vec<Piece> {
if id < 256 {
vec![Piece::Content(char::from(id as u8).to_string())]
} else {
Vec::new()
}
}
fn finish(&mut self, _reason: Option<&str>) -> Vec<Piece> {
Vec::new()
}
}
async fn build_app() -> (axum::Router, Arc<SqliteStore>) {
let engine = Arc::new(
Engine::start(
"python3",
&[MOCK.to_string()],
None,
Duration::from_secs(10),
)
.await
.expect("mock engine starts"),
);
let svc = ChatService::new(engine, Arc::new(ByteFormatter));
let store = Arc::new(SqliteStore::open_in_memory().unwrap());
let nanos = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos();
let root = std::env::temp_dir().join(format!("strata-ctl-test-{nanos}"));
let app = router_with_store(svc, store.clone(), AuthConfig::default(), root);
(app, store)
}
async fn req(
app: &axum::Router,
method: Method,
uri: &str,
body: Option<serde_json::Value>,
) -> (StatusCode, String) {
let mut b = Request::builder().method(method).uri(uri);
if body.is_some() {
b = b.header(CONTENT_TYPE, "application/json");
}
let r = b
.body(match body {
Some(v) => Body::from(v.to_string()),
None => Body::empty(),
})
.unwrap();
let resp = app.clone().oneshot(r).await.unwrap();
let status = resp.status();
let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
.await
.unwrap();
(status, String::from_utf8_lossy(&bytes).into_owned())
}
async fn create_session(app: &axum::Router) -> String {
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();
v["id"].as_str().unwrap().to_string()
}
#[tokio::test]
async fn session_holds_context_and_persists_usage() {
let (app, _store) = build_app().await;
let id = create_session(&app).await;
assert!(id.starts_with("sess_"));
// Turn 1 (non-stream): the mock emits 'efghi'.
let (st, text) = req(
&app,
Method::POST,
&format!("/api/sessions/{id}/chat"),
Some(serde_json::json!({"content": "hi"})),
)
.await;
assert_eq!(st, StatusCode::OK, "{text}");
let v: serde_json::Value = serde_json::from_str(&text).unwrap();
assert_eq!(v["choices"][0]["message"]["content"], "efghi");
// Persisted: user + assistant, with usage on the assistant turn.
let (st, text) = req(
&app,
Method::GET,
&format!("/api/sessions/{id}/messages"),
None,
)
.await;
assert_eq!(st, StatusCode::OK);
let msgs: serde_json::Value = serde_json::from_str(&text).unwrap();
assert_eq!(msgs.as_array().unwrap().len(), 2);
assert_eq!(msgs[0]["role"], "user");
assert_eq!(msgs[0]["content"], "hi");
assert_eq!(msgs[1]["role"], "assistant");
assert_eq!(msgs[1]["content"], "efghi");
assert_eq!(msgs[1]["completion_tokens"], 5);
// Turn 2: context is retained server-side (4 messages now).
let (st, _) = req(
&app,
Method::POST,
&format!("/api/sessions/{id}/chat"),
Some(serde_json::json!({"content": "again"})),
)
.await;
assert_eq!(st, StatusCode::OK);
let (_, text) = req(
&app,
Method::GET,
&format!("/api/sessions/{id}/messages"),
None,
)
.await;
let msgs: serde_json::Value = serde_json::from_str(&text).unwrap();
assert_eq!(msgs.as_array().unwrap().len(), 4);
assert_eq!(msgs[2]["content"], "again");
// Stats aggregate across the session.
let (st, text) = req(&app, Method::GET, "/api/stats", None).await;
assert_eq!(st, StatusCode::OK);
let s: serde_json::Value = serde_json::from_str(&text).unwrap();
assert_eq!(s["sessions"], 1);
assert_eq!(s["messages"], 4);
assert_eq!(s["completion_tokens"], 10);
// Expanded dashboard payload: totals, per-session/daily breakdown, and the
// live engine status + since-startup performance gauge layered on top.
assert_eq!(
s["total_tokens"],
s["prompt_tokens"].as_u64().unwrap() + s["completion_tokens"].as_u64().unwrap()
);
assert_eq!(s["tool_calls"], 0);
assert_eq!(s["by_session"].as_array().unwrap().len(), 1);
assert_eq!(s["by_session"][0]["messages"], 4);
assert_eq!(s["daily"].as_array().unwrap().len(), 1);
assert_eq!(s["engine"]["model"], "test-model");
assert_eq!(s["engine"]["max_context"], 8192);
assert_eq!(s["engine"]["busy"], false);
// Two non-stream completions were served and recorded by the perf meter,
// whose token-weighted decode speed comes from the mock's DONE timings.
assert_eq!(s["perf"]["requests"], 2);
assert!(s["perf"]["decode_tps"].as_f64().unwrap() > 0.0);
}
#[tokio::test]
async fn session_stream_persists_and_ends_with_done() {
let (app, _store) = build_app().await;
let id = create_session(&app).await;
let (st, text) = req(
&app,
Method::POST,
&format!("/api/sessions/{id}/chat"),
Some(serde_json::json!({"content": "hi", "stream": true})),
)
.await;
assert_eq!(st, StatusCode::OK, "{text}");
let data: Vec<&str> = text
.lines()
.filter(|l| l.starts_with("data: "))
.map(|l| &l["data: ".len()..])
.collect();
assert_eq!(data.last().copied(), Some("[DONE]"));
let mut content = String::new();
for line in &data[..data.len() - 1] {
let v: serde_json::Value = serde_json::from_str(line).unwrap();
if let Some(c) = v["choices"][0]["delta"]["content"].as_str() {
content.push_str(c);
}
}
assert_eq!(content, "efghi");
// The streamed assistant turn was persisted too.
let (_, text) = req(
&app,
Method::GET,
&format!("/api/sessions/{id}/messages"),
None,
)
.await;
let msgs: serde_json::Value = serde_json::from_str(&text).unwrap();
assert_eq!(msgs.as_array().unwrap().len(), 2);
assert_eq!(msgs[1]["content"], "efghi");
assert_eq!(msgs[1]["completion_tokens"], 5);
}
#[tokio::test]
async fn gui_is_served_and_delete_cascades() {
let (app, store) = build_app().await;
let id = create_session(&app).await;
req(
&app,
Method::POST,
&format!("/api/sessions/{id}/chat"),
Some(serde_json::json!({"content": "hi"})),
)
.await;
// The GUI shell and its assets are served from the binary.
let resp = app
.clone()
.oneshot(Request::builder().uri("/").body(Body::empty()).unwrap())
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(resp.headers()[CONTENT_TYPE], "text/html; charset=utf-8");
let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
.await
.unwrap();
assert!(String::from_utf8_lossy(&body).contains("strata"));
let (st, _) = req(&app, Method::GET, "/assets/app.js", None).await;
assert_eq!(st, StatusCode::OK);
// Deleting the session cascades to its messages.
let (st, _) = req(&app, Method::DELETE, &format!("/api/sessions/{id}"), None).await;
assert_eq!(st, StatusCode::NO_CONTENT);
assert!(store.messages(&id).unwrap().is_empty());
assert!(store.list_sessions().unwrap().is_empty());
}
#[tokio::test]
async fn unknown_session_is_404() {
let (app, _store) = build_app().await;
let (st, _) = req(&app, Method::GET, "/api/sessions/nope", None).await;
assert_eq!(st, StatusCode::NOT_FOUND);
let (st, _) = req(
&app,
Method::POST,
"/api/sessions/nope/chat",
Some(serde_json::json!({"content": "hi"})),
)
.await;
assert_eq!(st, StatusCode::NOT_FOUND);
}
#[tokio::test]
async fn agent_mode_streams_events_and_persists() {
let (app, store) = build_app().await;
let id = create_session(&app).await;
// The mock answers directly (no tool calls), exercising the agent final path.
let (st, text) = req(
&app,
Method::POST,
&format!("/api/sessions/{id}/chat"),
Some(serde_json::json!({"content": "hi", "agent": true})),
)
.await;
assert_eq!(st, StatusCode::OK, "{text}");
let data: Vec<&str> = text
.lines()
.filter(|l| l.starts_with("data: "))
.map(|l| &l["data: ".len()..])
.collect();
assert_eq!(data.last().copied(), Some("[DONE]"));
let mut saw_final = false;
for line in &data[..data.len() - 1] {
let v: serde_json::Value = serde_json::from_str(line).unwrap();
if v["type"] == "final" {
saw_final = true;
assert_eq!(v["response"]["choices"][0]["message"]["content"], "efghi");
}
}
assert!(saw_final, "no final agent event: {text}");
// The final assistant turn is persisted.
let msgs = store.messages(&id).unwrap();
assert_eq!(msgs.last().unwrap().role, "assistant");
assert_eq!(msgs.last().unwrap().content, "efghi");
}
#[tokio::test]
async fn first_interaction_creates_personal_folder() {
let (app, store) = build_app().await;
let id = create_session(&app).await;
assert!(store.get_session(&id).unwrap().unwrap().folder.is_none());
req(
&app,
Method::POST,
&format!("/api/sessions/{id}/chat"),
Some(serde_json::json!({"content": "ciao"})),
)
.await;
let s = store.get_session(&id).unwrap().unwrap();
let folder = s
.folder
.expect("personal folder created at first interaction");
assert!(std::path::Path::new(&folder).is_dir());
assert!(
folder.contains("/sessions/"),
"folder under sessions/: {folder}"
);
assert!(s.name_locked);
let _ = std::fs::remove_dir_all(&folder);
}
#[tokio::test]
async fn name_is_generated_editable_then_locked() {
let (app, store) = build_app().await;
let id = create_session(&app).await;
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);
// Rename before the first interaction is allowed.
let (st, _) = req(
&app,
Method::PATCH,
&format!("/api/sessions/{id}"),
Some(serde_json::json!({"title": "Mio titolo"})),
)
.await;
assert_eq!(st, StatusCode::OK);
assert_eq!(store.get_session(&id).unwrap().unwrap().title, "Mio titolo");
// 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)
);
}
#[tokio::test]
async fn upload_routes_by_kind_and_attaches_to_chat() {
use base64::Engine;
let (app, store) = build_app().await;
let b64 = |bytes: &[u8]| base64::engine::general_purpose::STANDARD.encode(bytes);
// Small text file -> kind "text", tokens measured, bytes on disk under uploads/.
let (st, text) = req(
&app,
Method::POST,
"/api/uploads",
Some(serde_json::json!({"name": "nota.txt", "data": b64(b"contenuto di prova")})),
)
.await;
assert_eq!(st, StatusCode::OK, "{text}");
let meta: serde_json::Value = serde_json::from_str(&text).unwrap();
assert_eq!(meta["kind"], "text");
assert!(meta["tokens"].as_u64().unwrap() > 0);
let path = meta["path"].as_str().unwrap().to_string();
assert!(std::path::Path::new(&path).is_file());
assert!(path.contains("/uploads/"), "shared upload dir: {path}");
let text_id = meta["id"].as_str().unwrap().to_string();
// Binary (NUL / invalid UTF-8) -> kind "binary", never inlined.
let (st, text) = req(
&app,
Method::POST,
"/api/uploads",
Some(serde_json::json!({"name": "dat.bin", "data": b64(&[0u8, 1, 2, 255])})),
)
.await;
assert_eq!(st, StatusCode::OK, "{text}");
let bin: serde_json::Value = serde_json::from_str(&text).unwrap();
assert_eq!(bin["kind"], "binary");
let bin_id = bin["id"].as_str().unwrap().to_string();
// Image (PNG magic) -> kind "image" (routed through Vision, not inline text).
let png = [0x89u8, b'P', b'N', b'G', b'\r', b'\n', 0x1a, b'\n', 0, 0];
let (st, text) = req(
&app,
Method::POST,
"/api/uploads",
Some(serde_json::json!({"name": "foto.png", "data": b64(&png)})),
)
.await;
assert_eq!(st, StatusCode::OK, "{text}");
let img: serde_json::Value = serde_json::from_str(&text).unwrap();
assert_eq!(img["kind"], "image");
// Chat attaching text + binary: the persisted user turn carries the inline
// text and the binary path reminder — never the binary bytes themselves.
let id = create_session(&app).await;
let (st, _) = req(
&app,
Method::POST,
&format!("/api/sessions/{id}/chat"),
Some(serde_json::json!({"content": "vedi allegati", "attachments": [text_id, bin_id]})),
)
.await;
assert_eq!(st, StatusCode::OK);
let msgs = store.messages(&id).unwrap();
let user = &msgs[0].content;
assert!(user.contains("contenuto di prova"), "inline text: {user}");
assert!(user.contains("dat.bin"), "binary path reminder: {user}");
assert!(user.contains("/uploads/"), "path present: {user}");
let _ = std::fs::remove_file(&path);
}
#[tokio::test]
async fn upload_accepts_large_binary_over_default_body_limit() {
use base64::Engine;
let (app, _store) = build_app().await;
// ~3 MiB of binary -> ~4 MiB of base64, above axum's 2 MiB default body limit
// (which used to 413-reject images/PDFs/exes before reaching the handler).
let bytes = vec![0u8; 3 * 1024 * 1024];
let data = base64::engine::general_purpose::STANDARD.encode(&bytes);
let (st, text) = req(
&app,
Method::POST,
"/api/uploads",
Some(serde_json::json!({"name": "big.bin", "data": data})),
)
.await;
assert_eq!(st, StatusCode::OK, "{text}");
let meta: serde_json::Value = serde_json::from_str(&text).unwrap();
assert_eq!(meta["kind"], "binary");
let _ = std::fs::remove_file(meta["path"].as_str().unwrap());
}