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).
This commit is contained in:
adm committed 2026-11-24 20:38:24 +01:00
1 parent 9e6d44fa1a
commit 1e13caa4ed
15 files changed
+1922 -23

No files matched your search

+267
View File
@@ -0,0 +1,267 @@
//! 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 app = router_with_store(svc, store.clone(), AuthConfig::default());
(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);
}