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

+3 -1
View File
@@ -8,10 +8,12 @@ pub mod anthropic;
pub mod formatter;
pub mod routes;
pub mod service;
mod sessions;
pub mod stop;
pub mod types;
mod web;
pub use formatter::{Decoder, Formatter, Piece, Prompt};
pub use routes::{router, router_with_auth, AuthConfig};
pub use routes::{router, router_with_auth, router_with_store, AuthConfig};
pub use service::ChatService;
pub use types::{ChatMessage, ChatRequest, ChatResponse, ModelList, Role};
+67 -9
View File
@@ -10,24 +10,67 @@ use axum::response::{sse::Event, sse::Sse, IntoResponse, Json};
use axum::routing::{get, post};
use axum::Router;
use serde::de::DeserializeOwned;
use std::sync::Arc;
use super::anthropic::{self, AnthropicRequest, AnthropicStream};
use super::service::ChatService;
use super::types::{ApiErrorEnvelope, ChatRequest, ModelCard, ModelList};
use super::{sessions, web};
use crate::store::Store;
/// Build the router. Mount this inside any axum `Router` or serve it directly.
pub fn router(service: ChatService) -> Router {
router_with_auth(service, AuthConfig::default())
}
/// Build the router with optional API-key auth and a Host allowlist.
/// Build the router with optional API-key auth and a Host allowlist (no GUI store).
pub fn router_with_auth(service: ChatService, auth: AuthConfig) -> Router {
Router::new()
build_router(
AppState {
service,
store: None,
},
auth,
)
}
/// Build the router with the session store + web GUI enabled, plus auth.
pub fn router_with_store(service: ChatService, store: Arc<dyn Store>, auth: AuthConfig) -> Router {
build_router(
AppState {
service,
store: Some(store),
},
auth,
)
}
fn build_router(state: AppState, auth: AuthConfig) -> Router {
let mut r = Router::new()
.route("/health", get(health))
.route("/v1/models", get(models))
.route("/v1/chat/completions", post(chat_completions))
.route("/v1/messages", post(messages))
.with_state(AppState { service })
.route("/v1/messages", post(messages));
// The session-aware API and the web GUI exist only when a store is configured.
if state.store.is_some() {
r = r
.route(
"/api/sessions",
get(sessions::list_sessions).post(sessions::create_session),
)
.route(
"/api/sessions/{id}",
get(sessions::get_session)
.delete(sessions::delete_session)
.patch(sessions::rename_session),
)
.route("/api/sessions/{id}/messages", get(sessions::get_messages))
.route("/api/sessions/{id}/chat", post(sessions::session_chat))
.route("/api/stats", get(sessions::stats))
.route("/", get(web::index))
.route("/assets/{*path}", get(web::asset));
}
r.with_state(state)
.layer(axum::middleware::from_fn_with_state(auth, auth_middleware))
}
@@ -110,8 +153,9 @@ async fn auth_middleware(
}
#[derive(Clone)]
struct AppState {
service: ChatService,
pub(crate) struct AppState {
pub(crate) service: ChatService,
pub(crate) store: Option<Arc<dyn Store>>,
}
/// An OpenAI error with the HTTP status the code implies.
@@ -121,12 +165,12 @@ pub struct Error {
}
impl Error {
fn new(status: StatusCode, body: ApiErrorEnvelope) -> Self {
pub(crate) fn new(status: StatusCode, body: ApiErrorEnvelope) -> Self {
Self { status, body }
}
/// Choose a status from the error's `code`; unknown codes are client 400s.
fn from_envelope(env: ApiErrorEnvelope) -> Self {
pub(crate) fn from_envelope(env: ApiErrorEnvelope) -> Self {
let status = match env.error.code.as_deref() {
Some("engine_unavailable") | Some("engine_startup") => StatusCode::SERVICE_UNAVAILABLE,
Some("engine_silent") => StatusCode::GATEWAY_TIMEOUT,
@@ -136,12 +180,26 @@ impl Error {
Self::new(status, env)
}
fn bad_request(msg: impl Into<String>) -> Self {
pub(crate) fn bad_request(msg: impl Into<String>) -> Self {
Self::new(
StatusCode::BAD_REQUEST,
ApiErrorEnvelope::new(msg, "invalid_request_error", None),
)
}
pub(crate) fn not_found(msg: impl Into<String>) -> Self {
Self::new(
StatusCode::NOT_FOUND,
ApiErrorEnvelope::new(msg, "invalid_request_error", Some("not_found".to_string())),
)
}
pub(crate) fn internal(msg: impl Into<String>) -> Self {
Self::new(
StatusCode::INTERNAL_SERVER_ERROR,
ApiErrorEnvelope::new(msg, "server_error", None),
)
}
}
impl IntoResponse for Error {
+380
View File
@@ -0,0 +1,380 @@
//! 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;
}
+47
View File
@@ -0,0 +1,47 @@
//! Serves the embedded web GUI (`web/`) from the binary via `rust-embed`.
//!
//! Single-binary and offline-capable: assets are compiled into the executable
//! (release) or read from `web/` (debug). Same-origin with the API, so no CORS.
use axum::extract::Path;
use axum::http::{header, StatusCode};
use axum::response::{IntoResponse, Response};
use rust_embed::RustEmbed;
#[derive(RustEmbed)]
#[folder = "web/"]
struct Assets;
/// `GET /` — the GUI shell.
pub(crate) async fn index() -> Response {
serve("index.html")
}
/// `GET /assets/{*path}` — CSS/JS/etc. under `web/assets/`.
pub(crate) async fn asset(Path(path): Path<String>) -> Response {
serve(&format!("assets/{path}"))
}
fn serve(path: &str) -> Response {
match Assets::get(path) {
Some(file) => (
[(header::CONTENT_TYPE, content_type(path))],
file.data.into_owned(),
)
.into_response(),
None => (StatusCode::NOT_FOUND, "not found").into_response(),
}
}
fn content_type(path: &str) -> &'static str {
match path.rsplit('.').next().unwrap_or("") {
"html" => "text/html; charset=utf-8",
"css" => "text/css; charset=utf-8",
"js" => "text/javascript; charset=utf-8",
"svg" => "image/svg+xml",
"png" => "image/png",
"ico" => "image/x-icon",
"json" => "application/json",
_ => "application/octet-stream",
}
}