- At the first interaction the session name locks and a personal folder is created under the workspace root (default ~/.strata-ctl/<slug>, configurable via workspace_root); slug is filesystem-safe and unique. Stored in sessions.folder (idempotent migration).
- build_request always prepends a structural identity reminder ('Il tuo nome è X. La tua cartella personale è Y.') before the session SP — not an editable setting; gives the agent awareness of its workspace. router_with_store takes the workspace root. 114 tests green; verified live (folder created, name locked).
449 lines
14 KiB
Rust
449 lines
14 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);
|
|
}
|
|
|
|
#[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!(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)
|
|
);
|
|
}
|