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

Generated
+212
View File
@@ -227,6 +227,15 @@ dependencies = [
"no_std_io2", "no_std_io2",
] ]
[[package]]
name = "block-buffer"
version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa"
dependencies = [
"hybrid-array",
]
[[package]] [[package]]
name = "built" name = "built"
version = "0.8.1" version = "0.8.1"
@@ -317,6 +326,21 @@ dependencies = [
"windows-sys 0.61.2", "windows-sys 0.61.2",
] ]
[[package]]
name = "const-oid"
version = "0.10.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a"
[[package]]
name = "cpufeatures"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566"
dependencies = [
"libc",
]
[[package]] [[package]]
name = "crc32fast" name = "crc32fast"
version = "1.5.5" version = "1.5.5"
@@ -357,6 +381,15 @@ version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5"
[[package]]
name = "crypto-common"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453"
dependencies = [
"hybrid-array",
]
[[package]] [[package]]
name = "daachorse" name = "daachorse"
version = "3.0.3" version = "3.0.3"
@@ -438,6 +471,17 @@ dependencies = [
"syn 2.0.119", "syn 2.0.119",
] ]
[[package]]
name = "digest"
version = "0.11.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2"
dependencies = [
"block-buffer",
"const-oid",
"crypto-common",
]
[[package]] [[package]]
name = "either" name = "either"
version = "1.19.0" version = "1.19.0"
@@ -505,6 +549,18 @@ dependencies = [
"zune-inflate", "zune-inflate",
] ]
[[package]]
name = "fallible-iterator"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649"
[[package]]
name = "fallible-streaming-iterator"
version = "0.1.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a"
[[package]] [[package]]
name = "fax" name = "fax"
version = "0.2.7" version = "0.2.7"
@@ -697,6 +753,24 @@ dependencies = [
"zerocopy", "zerocopy",
] ]
[[package]]
name = "hashbrown"
version = "0.14.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1"
dependencies = [
"ahash",
]
[[package]]
name = "hashlink"
version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ba4ff7128dee98c7dc9794b6a411377e1404dba1c97deb8d1a55297bd25d8af"
dependencies = [
"hashbrown",
]
[[package]] [[package]]
name = "http" name = "http"
version = "1.5.0" version = "1.5.0"
@@ -742,6 +816,15 @@ version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9"
[[package]]
name = "hybrid-array"
version = "0.4.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17"
dependencies = [
"typenum",
]
[[package]] [[package]]
name = "hyper" name = "hyper"
version = "1.13.0" version = "1.13.0"
@@ -910,6 +993,17 @@ dependencies = [
"cc", "cc",
] ]
[[package]]
name = "libsqlite3-sys"
version = "0.30.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2e99fb7a497b1e3339bc746195567ed8d3e24945ecd636e3619d20b9de9e9149"
dependencies = [
"cc",
"pkg-config",
"vcpkg",
]
[[package]] [[package]]
name = "lock_api" name = "lock_api"
version = "0.4.14" version = "0.4.14"
@@ -987,6 +1081,16 @@ version = "0.3.18"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d5848f5a9e8117cf94f2f90faac24a87ff81600ff8628c1e3deaab572e76bfa1" checksum = "d5848f5a9e8117cf94f2f90faac24a87ff81600ff8628c1e3deaab572e76bfa1"
[[package]]
name = "mime_guess"
version = "2.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f7c44f8e672c00fe5308fa235f821cb4198414e1c77935c1ab6948d3fd78550e"
dependencies = [
"mime",
"unicase",
]
[[package]] [[package]]
name = "minijinja" name = "minijinja"
version = "3.1.0" version = "3.1.0"
@@ -1539,6 +1643,55 @@ dependencies = [
"windows-sys 0.52.0", "windows-sys 0.52.0",
] ]
[[package]]
name = "rusqlite"
version = "0.32.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7753b721174eb8ff87a9a0e799e2d7bc3749323e773db92e0984debb00019d6e"
dependencies = [
"bitflags",
"fallible-iterator",
"fallible-streaming-iterator",
"hashlink",
"libsqlite3-sys",
"smallvec",
]
[[package]]
name = "rust-embed"
version = "8.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e98f580cf7a2863aeb6827800283f52cbe6fb3f3bb7c1843783f903c16dcb8ad"
dependencies = [
"rust-embed-impl",
"rust-embed-utils",
"walkdir",
]
[[package]]
name = "rust-embed-impl"
version = "8.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a93e2f69cf224a6c7df7509aa5ba4a23f56828ee41b040e92ac8762371eb9ba7"
dependencies = [
"mime_guess",
"proc-macro2",
"quote",
"rust-embed-utils",
"syn 2.0.119",
"walkdir",
]
[[package]]
name = "rust-embed-utils"
version = "8.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "915e33dccbe7deb2b8a342dc4c517503fe85e0230ddbae40a4fb0220493dad9b"
dependencies = [
"sha2",
"walkdir",
]
[[package]] [[package]]
name = "rustls" name = "rustls"
version = "0.23.46" version = "0.23.46"
@@ -1586,6 +1739,15 @@ version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f"
[[package]]
name = "same-file"
version = "1.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502"
dependencies = [
"winapi-util",
]
[[package]] [[package]]
name = "scopeguard" name = "scopeguard"
version = "1.2.0" version = "1.2.0"
@@ -1658,6 +1820,17 @@ dependencies = [
"serde", "serde",
] ]
[[package]]
name = "sha2"
version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19"
dependencies = [
"cfg-if",
"cpufeatures",
"digest",
]
[[package]] [[package]]
name = "sharded-slab" name = "sharded-slab"
version = "0.1.7" version = "0.1.7"
@@ -1755,6 +1928,8 @@ dependencies = [
"http-body-util", "http-body-util",
"image", "image",
"minijinja", "minijinja",
"rusqlite",
"rust-embed",
"serde", "serde",
"serde_json", "serde_json",
"thiserror", "thiserror",
@@ -2019,6 +2194,18 @@ dependencies = [
"tracing-log", "tracing-log",
] ]
[[package]]
name = "typenum"
version = "1.20.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
[[package]]
name = "unicase"
version = "2.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "357cc3acc6a036009fd6c973ed009037c732d60d0b4f6c673e9041497482a28f"
[[package]] [[package]]
name = "unicode-ident" name = "unicode-ident"
version = "1.0.27" version = "1.0.27"
@@ -2116,12 +2303,28 @@ version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65"
[[package]]
name = "vcpkg"
version = "0.2.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"
[[package]] [[package]]
name = "version_check" name = "version_check"
version = "0.9.5" version = "0.9.5"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
[[package]]
name = "walkdir"
version = "2.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b42e295b7452c4604982280d8586001fcad9b8b201cac67bca9771e7a7475403"
dependencies = [
"same-file",
"winapi-util",
]
[[package]] [[package]]
name = "wasi" name = "wasi"
version = "0.11.1+wasi-snapshot-preview1" version = "0.11.1+wasi-snapshot-preview1"
@@ -2206,6 +2409,15 @@ version = "0.1.12"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88" checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88"
[[package]]
name = "winapi-util"
version = "0.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
dependencies = [
"windows-sys 0.61.2",
]
[[package]] [[package]]
name = "windows-link" name = "windows-link"
version = "0.2.1" version = "0.2.1"
+5
View File
@@ -21,6 +21,11 @@ image = "0.25.10"
base64 = "0.23.1" base64 = "0.23.1"
ureq = "3.5.2" ureq = "3.5.2"
tracing-subscriber = { version = "0.3.23", features = ["env-filter"] } tracing-subscriber = { version = "0.3.23", features = ["env-filter"] }
# Embedded SQLite for the GUI's session/context store (bundled = compiled into the
# binary, no external service). Behind a `Store` trait so it can be swapped later.
rusqlite = { version = "0.32", features = ["bundled"] }
# Embeds the web/ GUI assets into the binary (single-binary, offline-capable).
rust-embed = "8"
[dev-dependencies] [dev-dependencies]
http-body-util = "0.1.5" http-body-util = "0.1.5"
+37 -8
View File
@@ -85,6 +85,30 @@ Operational hardening:
- Blocking image I/O runs off the async event loop; temp files are cleaned on every - Blocking image I/O runs off the async event loop; temp files are cleaned on every
exit path; image fetches have a timeout, a size cap and a basic SSRF guard. exit path; image fetches have a timeout, a size cap and a basic SSRF guard.
## Web GUI
A minimal, **mobile-first** chat GUI is served by the same binary at `GET /` (assets
under `/assets/...`, embedded via `rust-embed` — no Node, no build step, works
offline, same-origin so no CORS). It is a thin client over a **session-aware API**:
- `GET /` — the chat shell (responsive: an off-canvas session drawer on phones, a
persistent sidebar on wide screens; streaming answers with a collapsible
"thinking" panel; touch-friendly targets and safe-area insets).
- `POST /api/sessions`, `GET /api/sessions`, `GET/PATCH/DELETE /api/sessions/{id}`,
`GET /api/sessions/{id}/messages` — session CRUD and history.
- `POST /api/sessions/{id}/chat` — append a turn; the server loads the stored
context, runs inference (streaming SSE or not) and persists the new turns with
their token usage.
- `GET /api/stats` — aggregate counters (sessions, messages, prompt/completion tokens).
The standard `/v1` API stays **stateless**; conversation context lives server-side
in an embedded **SQLite** database (default `~/.config/strata-ctl/sessions.db`,
override with `db_path`). Storage sits behind a `Store` trait so it can be swapped
(the planned direction is **ArangoDB**, multi-model: KV / documents / graphs / vector
indexes) or complemented by another DBMS for advanced analytics later, without
touching the API or the GUI. This is the foundation for multi-session, statistics and
advanced settings to grow on top.
## Architecture ## Architecture
``` ```
@@ -100,7 +124,10 @@ shared JSON config ──► InklingFormatter ──► Engine supervisor ──
- `engine` — a pure protocol parser plus a supervisor that owns the child process, - `engine` — a pure protocol parser plus a supervisor that owns the child process,
serializes requests on its single control stream, and handles STOP/drain/QUIT. serializes requests on its single control stream, and handles STOP/drain/QUIT.
- `api` — request/response types, the `Formatter`/`Decoder` seam, the completion - `api` — request/response types, the `Formatter`/`Decoder` seam, the completion
service (stream + non-stream) and the axum router. service (stream + non-stream), the axum router, the session-aware GUI API and the
embedded web assets.
- `store` — the persistent session/context store: a `Store` trait with a bundled
SQLite implementation (WAL), used by the GUI API.
## Building and running ## Building and running
@@ -124,22 +151,24 @@ uses `tracing`; set `RUST_LOG` to control verbosity (default `info`).
The config is the same JSON the other Strata tools use. Keys acted on here include The config is the same JSON the other Strata tools use. Keys acted on here include
`exe`, `args`, `cwd`, `tokenizer`, `model_name`, `host`, `port`, `reasoning_effort`, `exe`, `args`, `cwd`, `tokenizer`, `model_name`, `host`, `port`, `reasoning_effort`,
`sampling`, `api_key`, `allowed_hosts`, and the optional `startup_timeout_secs` / `sampling`, `api_key`, `allowed_hosts`, `db_path` (GUI session database), and the
`silence_timeout_secs`. Everything else (`arch`, `mcp_servers`, `cors_origins`, …) optional `startup_timeout_secs` / `silence_timeout_secs`. Everything else (`arch`,
is preserved untouched and reported as ignored — unknown keys never break startup. `mcp_servers`, `cors_origins`, …) is preserved untouched and reported as ignored —
unknown keys never break startup.
## Status ## Status
Working and tested (87 tests, plus 2 real-file tests run on demand). Text, images Working and tested (94 tests, plus 2 real-file tests run on demand). Text, images,
and the full client-side tool loop have been validated live against the real the full client-side tool loop, the Anthropic endpoint and the web GUI (session
Inkling engine. context, streaming, stats) have been validated live against the real Inkling engine.
Not yet implemented (honest gaps): forced `tool_choice` (`required` / named function Not yet implemented (honest gaps): forced `tool_choice` (`required` / named function
returns a clear 400), multi-slot batching, logprobs / structured output, automatic returns a clear 400), multi-slot batching, logprobs / structured output, automatic
engine restart after a crash, a full SSRF guard against DNS rebinding, and the engine restart after a crash, a full SSRF guard against DNS rebinding, and the
OpenAI Responses native endpoint. The Anthropic adapter covers the core cases but OpenAI Responses native endpoint. The Anthropic adapter covers the core cases but
not yet the `defer_loading` / `tool_addition` / `tool_reference` tool machinery, the not yet the `defer_loading` / `tool_addition` / `tool_reference` tool machinery, the
thinking `budget_tokens` mapping, or prompt-cache token accounting. thinking `budget_tokens` mapping, or prompt-cache token accounting. The GUI is
text-chat first: images, tools and advanced settings in the GUI are still to come.
## License and credits ## License and credits
+3 -1
View File
@@ -8,10 +8,12 @@ pub mod anthropic;
pub mod formatter; pub mod formatter;
pub mod routes; pub mod routes;
pub mod service; pub mod service;
mod sessions;
pub mod stop; pub mod stop;
pub mod types; pub mod types;
mod web;
pub use formatter::{Decoder, Formatter, Piece, Prompt}; 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 service::ChatService;
pub use types::{ChatMessage, ChatRequest, ChatResponse, ModelList, Role}; 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::routing::{get, post};
use axum::Router; use axum::Router;
use serde::de::DeserializeOwned; use serde::de::DeserializeOwned;
use std::sync::Arc;
use super::anthropic::{self, AnthropicRequest, AnthropicStream}; use super::anthropic::{self, AnthropicRequest, AnthropicStream};
use super::service::ChatService; use super::service::ChatService;
use super::types::{ApiErrorEnvelope, ChatRequest, ModelCard, ModelList}; 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. /// Build the router. Mount this inside any axum `Router` or serve it directly.
pub fn router(service: ChatService) -> Router { pub fn router(service: ChatService) -> Router {
router_with_auth(service, AuthConfig::default()) 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 { 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("/health", get(health))
.route("/v1/models", get(models)) .route("/v1/models", get(models))
.route("/v1/chat/completions", post(chat_completions)) .route("/v1/chat/completions", post(chat_completions))
.route("/v1/messages", post(messages)) .route("/v1/messages", post(messages));
.with_state(AppState { service }) // 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)) .layer(axum::middleware::from_fn_with_state(auth, auth_middleware))
} }
@@ -110,8 +153,9 @@ async fn auth_middleware(
} }
#[derive(Clone)] #[derive(Clone)]
struct AppState { pub(crate) struct AppState {
service: ChatService, pub(crate) service: ChatService,
pub(crate) store: Option<Arc<dyn Store>>,
} }
/// An OpenAI error with the HTTP status the code implies. /// An OpenAI error with the HTTP status the code implies.
@@ -121,12 +165,12 @@ pub struct Error {
} }
impl Error { impl Error {
fn new(status: StatusCode, body: ApiErrorEnvelope) -> Self { pub(crate) fn new(status: StatusCode, body: ApiErrorEnvelope) -> Self {
Self { status, body } Self { status, body }
} }
/// Choose a status from the error's `code`; unknown codes are client 400s. /// 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() { let status = match env.error.code.as_deref() {
Some("engine_unavailable") | Some("engine_startup") => StatusCode::SERVICE_UNAVAILABLE, Some("engine_unavailable") | Some("engine_startup") => StatusCode::SERVICE_UNAVAILABLE,
Some("engine_silent") => StatusCode::GATEWAY_TIMEOUT, Some("engine_silent") => StatusCode::GATEWAY_TIMEOUT,
@@ -136,12 +180,26 @@ impl Error {
Self::new(status, env) Self::new(status, env)
} }
fn bad_request(msg: impl Into<String>) -> Self { pub(crate) fn bad_request(msg: impl Into<String>) -> Self {
Self::new( Self::new(
StatusCode::BAD_REQUEST, StatusCode::BAD_REQUEST,
ApiErrorEnvelope::new(msg, "invalid_request_error", None), 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 { 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",
}
}
+24
View File
@@ -96,6 +96,11 @@ pub struct Config {
#[serde(default)] #[serde(default)]
pub allowed_hosts: Option<Vec<String>>, pub allowed_hosts: Option<Vec<String>>,
/// Path to the GUI session database (SQLite). Defaults to
/// `~/.config/strata-ctl/sessions.db`.
#[serde(default)]
pub db_path: Option<String>,
/// Keys we understand but don't act on yet are NOT listed above, so they /// Keys we understand but don't act on yet are NOT listed above, so they
/// arrive here untouched — the "ignore what isn't ours" guarantee. /// arrive here untouched — the "ignore what isn't ours" guarantee.
#[serde(flatten)] #[serde(flatten)]
@@ -192,6 +197,15 @@ impl Config {
Duration::from_secs(self.silence_timeout_secs.unwrap_or(600)) Duration::from_secs(self.silence_timeout_secs.unwrap_or(600))
} }
/// Effective GUI database path: config > `~/.config/strata-ctl/sessions.db`.
pub fn gui_db_path(&self) -> PathBuf {
if let Some(p) = &self.db_path {
return PathBuf::from(p);
}
let home = std::env::var("HOME").unwrap_or_default();
PathBuf::from(home).join(".config/strata-ctl/sessions.db")
}
/// The top-level keys present in the file that we are not acting on — /// The top-level keys present in the file that we are not acting on —
/// reported by `--check` so the shared-file contract stays visible. /// reported by `--check` so the shared-file contract stays visible.
pub fn ignored_keys(&self) -> Vec<&str> { pub fn ignored_keys(&self) -> Vec<&str> {
@@ -337,4 +351,14 @@ mod tests {
assert_eq!(cfg2.startup_timeout(), Duration::from_secs(30)); assert_eq!(cfg2.startup_timeout(), Duration::from_secs(30));
assert_eq!(cfg2.silence_timeout(), Duration::from_secs(120)); assert_eq!(cfg2.silence_timeout(), Duration::from_secs(120));
} }
#[test]
fn gui_db_path_default_and_override() {
let cfg = Config::parse(REAL, "test").unwrap();
assert!(cfg
.gui_db_path()
.ends_with(".config/strata-ctl/sessions.db"));
let cfg2 = Config::parse(r#"{"exe":"/x/e","db_path":"/tmp/x.db"}"#, "test").unwrap();
assert_eq!(cfg2.gui_db_path(), PathBuf::from("/tmp/x.db"));
}
} }
+3 -3
View File
@@ -3,11 +3,11 @@
//! - [`engine`]: spawn `strata --serve` and speak its line protocol. //! - [`engine`]: spawn `strata --serve` and speak its line protocol.
//! - [`api`]: the OpenAI-compatible HTTP surface (types, formatter seam, //! - [`api`]: the OpenAI-compatible HTTP surface (types, formatter seam,
//! completion service, axum routes). //! completion service, axum routes).
//! //! - [`store`]: persistent session/context store for the web GUI (SQLite behind
//! Next: the Inkling formatter (chat template + tokenizer), then wiring a //! a swappable `Store` trait).
//! binary that reads the existing `strata-inkling.json` and serves.
pub mod api; pub mod api;
pub mod config; pub mod config;
pub mod engine; pub mod engine;
pub mod inkling; pub mod inkling;
pub mod store;
+20 -2
View File
@@ -8,10 +8,11 @@ use std::path::Path;
use std::process::ExitCode; use std::process::ExitCode;
use std::sync::Arc; use std::sync::Arc;
use strata_ctl::api::{router_with_auth, AuthConfig, ChatService}; use strata_ctl::api::{router_with_store, AuthConfig, ChatService};
use strata_ctl::config::{Config, ConfigError}; use strata_ctl::config::{Config, ConfigError};
use strata_ctl::engine::Engine; use strata_ctl::engine::Engine;
use strata_ctl::inkling::{ChatTemplate, InklingFormatter, InklingTokenizer}; use strata_ctl::inkling::{ChatTemplate, InklingFormatter, InklingTokenizer};
use strata_ctl::store::{SqliteStore, Store};
const USAGE: &str = "\ const USAGE: &str = "\
strata-ctl — Rust control layer for the Strata engine (OpenAI-compatible API) strata-ctl — Rust control layer for the Strata engine (OpenAI-compatible API)
@@ -175,7 +176,20 @@ async fn serve(cfg: &Config, cli_host: Option<&str>, cli_port: Option<u16>) -> E
api_key: cfg.api_key.clone(), api_key: cfg.api_key.clone(),
allowed_hosts: cfg.allowed_hosts.clone().unwrap_or_default(), allowed_hosts: cfg.allowed_hosts.clone().unwrap_or_default(),
}; };
let app = router_with_auth(svc, auth); // Open the GUI session store (SQLite). The web GUI + session API are mounted
// only when this succeeds; the standard /v1 API is unaffected either way.
let db_path = cfg.gui_db_path();
let store: Arc<dyn Store> = match SqliteStore::open(&db_path) {
Ok(s) => Arc::new(s),
Err(e) => {
eprintln!(
"error: cannot open session database {}: {e}",
db_path.display()
);
return ExitCode::FAILURE;
}
};
let app = router_with_store(svc, store, auth);
let host = cfg.bind_host(cli_host); let host = cfg.bind_host(cli_host);
let port = cfg.bind_port(cli_port); let port = cfg.bind_port(cli_port);
if !is_loopback_host(&host) && cfg.api_key.is_none() { if !is_loopback_host(&host) && cfg.api_key.is_none() {
@@ -194,6 +208,10 @@ async fn serve(cfg: &Config, cli_host: Option<&str>, cli_port: Option<u16>) -> E
} }
}; };
println!("listening on http://{addr} (Ctrl-C to stop)"); println!("listening on http://{addr} (Ctrl-C to stop)");
println!(
"web GUI: http://{addr}/ (sessions db: {})",
db_path.display()
);
let shutdown_engine = engine.clone(); let shutdown_engine = engine.clone();
let result = axum::serve(listener, app) let result = axum::serve(listener, app)
+369
View File
@@ -0,0 +1,369 @@
//! Persistent context store for the web GUI: sessions, messages and token usage.
//!
//! The standard `/v1` API stays stateless; this is a separate server-side layer
//! the GUI uses to hold conversation context across turns and devices. It sits
//! behind the [`Store`] trait so the backend can be swapped (e.g. SQLite today,
//! Postgres or an analytics DBMS later) without touching the API or the GUI.
//!
//! Implementations are synchronous and `Send + Sync`; async handlers call them
//! through `spawn_blocking` so DB work never blocks the tokio runtime.
use std::path::Path;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Mutex;
use std::time::{SystemTime, UNIX_EPOCH};
use anyhow::{Context, Result};
use rusqlite::{params, Connection};
/// A conversation session.
#[derive(Debug, Clone, serde::Serialize)]
pub struct Session {
pub id: String,
pub title: String,
pub model: String,
pub system_prompt: Option<String>,
pub created_at: i64,
pub updated_at: i64,
}
/// A persisted message (one turn) with its token usage.
#[derive(Debug, Clone, serde::Serialize)]
pub struct StoredMessage {
pub id: i64,
pub role: String,
pub content: String,
pub reasoning_content: Option<String>,
pub tool_calls_json: Option<String>,
pub prompt_tokens: u32,
pub completion_tokens: u32,
pub created_at: i64,
}
/// A message to append (borrowed fields; no allocation until persisted).
pub struct NewMessage<'a> {
pub role: &'a str,
pub content: &'a str,
pub reasoning_content: Option<&'a str>,
pub tool_calls_json: Option<&'a str>,
pub prompt_tokens: u32,
pub completion_tokens: u32,
}
/// Aggregate counters for the stats view.
#[derive(Debug, Clone, Default, serde::Serialize)]
pub struct Stats {
pub sessions: u64,
pub messages: u64,
pub prompt_tokens: u64,
pub completion_tokens: u64,
}
/// The storage interface. Synchronous; call via `spawn_blocking` from async code.
pub trait Store: Send + Sync {
fn create_session(
&self,
title: &str,
model: &str,
system_prompt: Option<&str>,
) -> Result<Session>;
fn list_sessions(&self) -> Result<Vec<Session>>;
fn get_session(&self, id: &str) -> Result<Option<Session>>;
fn rename_session(&self, id: &str, title: &str) -> Result<()>;
fn delete_session(&self, id: &str) -> Result<()>;
fn messages(&self, session_id: &str) -> Result<Vec<StoredMessage>>;
fn append_message(&self, session_id: &str, msg: NewMessage<'_>) -> Result<StoredMessage>;
fn stats(&self) -> Result<Stats>;
}
fn now_secs() -> i64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs() as i64)
.unwrap_or(0)
}
/// Unique, sortable-enough id without an extra dependency (nanos + counter).
fn new_id(prefix: &str) -> String {
static COUNTER: AtomicU64 = AtomicU64::new(0);
let nanos = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_nanos())
.unwrap_or(0);
let n = COUNTER.fetch_add(1, Ordering::Relaxed);
format!("{prefix}_{nanos:016x}{n:08x}")
}
const SCHEMA: &str = "
CREATE TABLE IF NOT EXISTS sessions (
id TEXT PRIMARY KEY,
title TEXT NOT NULL,
model TEXT NOT NULL,
system_prompt TEXT,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS messages (
id INTEGER PRIMARY KEY AUTOINCREMENT,
session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
role TEXT NOT NULL,
content TEXT NOT NULL,
reasoning_content TEXT,
tool_calls_json TEXT,
prompt_tokens INTEGER NOT NULL DEFAULT 0,
completion_tokens INTEGER NOT NULL DEFAULT 0,
created_at INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_messages_session ON messages(session_id, id);
";
/// SQLite-backed store (bundled SQLite, compiled into the binary). WAL mode for
/// concurrent reads; a single mutex serializes writes (already serialized by the
/// engine in practice). Replaceable via the [`Store`] trait.
pub struct SqliteStore {
conn: Mutex<Connection>,
}
impl SqliteStore {
/// Open (creating if needed) the database at `path`, initializing the schema.
pub fn open(path: &Path) -> Result<Self> {
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)
.with_context(|| format!("creating db dir {}", parent.display()))?;
}
let conn = Connection::open(path)
.with_context(|| format!("opening database {}", path.display()))?;
Self::init(conn)
}
/// In-memory database (tests).
pub fn open_in_memory() -> Result<Self> {
Self::init(Connection::open_in_memory()?)
}
fn init(conn: Connection) -> Result<Self> {
conn.pragma_update(None, "journal_mode", "WAL")?;
conn.pragma_update(None, "synchronous", "NORMAL")?;
conn.pragma_update(None, "foreign_keys", "ON")?;
conn.execute_batch(SCHEMA)?;
Ok(Self {
conn: Mutex::new(conn),
})
}
fn lock(&self) -> std::sync::MutexGuard<'_, Connection> {
self.conn.lock().unwrap_or_else(|e| e.into_inner())
}
}
fn row_to_session(row: &rusqlite::Row<'_>) -> rusqlite::Result<Session> {
Ok(Session {
id: row.get("id")?,
title: row.get("title")?,
model: row.get("model")?,
system_prompt: row.get("system_prompt")?,
created_at: row.get("created_at")?,
updated_at: row.get("updated_at")?,
})
}
impl Store for SqliteStore {
fn create_session(
&self,
title: &str,
model: &str,
system_prompt: Option<&str>,
) -> Result<Session> {
let id = new_id("sess");
let now = now_secs();
let conn = self.lock();
conn.execute(
"INSERT INTO sessions (id, title, model, system_prompt, created_at, updated_at)
VALUES (?1, ?2, ?3, ?4, ?5, ?5)",
params![id, title, model, system_prompt, now],
)?;
Ok(Session {
id,
title: title.to_string(),
model: model.to_string(),
system_prompt: system_prompt.map(str::to_string),
created_at: now,
updated_at: now,
})
}
fn list_sessions(&self) -> Result<Vec<Session>> {
let conn = self.lock();
let mut stmt =
conn.prepare("SELECT * FROM sessions ORDER BY updated_at DESC, created_at DESC")?;
let rows = stmt.query_map([], row_to_session)?;
Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?)
}
fn get_session(&self, id: &str) -> Result<Option<Session>> {
let conn = self.lock();
let mut stmt = conn.prepare("SELECT * FROM sessions WHERE id = ?1")?;
let mut rows = stmt.query_map(params![id], row_to_session)?;
Ok(rows.next().transpose()?)
}
fn rename_session(&self, id: &str, title: &str) -> Result<()> {
let conn = self.lock();
conn.execute(
"UPDATE sessions SET title = ?2, updated_at = ?3 WHERE id = ?1",
params![id, title, now_secs()],
)?;
Ok(())
}
fn delete_session(&self, id: &str) -> Result<()> {
let conn = self.lock();
conn.execute("DELETE FROM sessions WHERE id = ?1", params![id])?;
Ok(())
}
fn messages(&self, session_id: &str) -> Result<Vec<StoredMessage>> {
let conn = self.lock();
let mut stmt =
conn.prepare("SELECT * FROM messages WHERE session_id = ?1 ORDER BY id ASC")?;
let rows = stmt.query_map(params![session_id], |row| {
Ok(StoredMessage {
id: row.get("id")?,
role: row.get("role")?,
content: row.get("content")?,
reasoning_content: row.get("reasoning_content")?,
tool_calls_json: row.get("tool_calls_json")?,
prompt_tokens: row.get::<_, i64>("prompt_tokens")? as u32,
completion_tokens: row.get::<_, i64>("completion_tokens")? as u32,
created_at: row.get("created_at")?,
})
})?;
Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?)
}
fn append_message(&self, session_id: &str, msg: NewMessage<'_>) -> Result<StoredMessage> {
let now = now_secs();
let conn = self.lock();
conn.execute(
"INSERT INTO messages
(session_id, role, content, reasoning_content, tool_calls_json,
prompt_tokens, completion_tokens, created_at)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
params![
session_id,
msg.role,
msg.content,
msg.reasoning_content,
msg.tool_calls_json,
msg.prompt_tokens as i64,
msg.completion_tokens as i64,
now
],
)?;
let id = conn.last_insert_rowid();
conn.execute(
"UPDATE sessions SET updated_at = ?2 WHERE id = ?1",
params![session_id, now],
)?;
Ok(StoredMessage {
id,
role: msg.role.to_string(),
content: msg.content.to_string(),
reasoning_content: msg.reasoning_content.map(str::to_string),
tool_calls_json: msg.tool_calls_json.map(str::to_string),
prompt_tokens: msg.prompt_tokens,
completion_tokens: msg.completion_tokens,
created_at: now,
})
}
fn stats(&self) -> Result<Stats> {
let conn = self.lock();
let sessions: i64 = conn.query_row("SELECT COUNT(*) FROM sessions", [], |r| r.get(0))?;
let (messages, prompt, completion): (i64, i64, i64) = conn.query_row(
"SELECT COUNT(*), COALESCE(SUM(prompt_tokens),0), COALESCE(SUM(completion_tokens),0) FROM messages",
[],
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
)?;
Ok(Stats {
sessions: sessions as u64,
messages: messages as u64,
prompt_tokens: prompt as u64,
completion_tokens: completion as u64,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
fn store() -> SqliteStore {
SqliteStore::open_in_memory().unwrap()
}
#[test]
fn session_crud_and_message_order() {
let s = store();
let sess = s
.create_session("Chat", "Inkling-2-Mini", Some("be nice"))
.unwrap();
assert!(sess.id.starts_with("sess_"));
assert_eq!(s.list_sessions().unwrap().len(), 1);
s.append_message(
&sess.id,
NewMessage {
role: "user",
content: "ciao",
reasoning_content: None,
tool_calls_json: None,
prompt_tokens: 3,
completion_tokens: 0,
},
)
.unwrap();
s.append_message(
&sess.id,
NewMessage {
role: "assistant",
content: "ciao!",
reasoning_content: Some("think"),
tool_calls_json: None,
prompt_tokens: 3,
completion_tokens: 5,
},
)
.unwrap();
let msgs = s.messages(&sess.id).unwrap();
assert_eq!(msgs.len(), 2);
assert_eq!(msgs[0].role, "user");
assert_eq!(msgs[1].content, "ciao!");
assert_eq!(msgs[1].reasoning_content.as_deref(), Some("think"));
assert_eq!(msgs[1].completion_tokens, 5);
s.rename_session(&sess.id, "Nuovo titolo").unwrap();
assert_eq!(
s.get_session(&sess.id).unwrap().unwrap().title,
"Nuovo titolo"
);
let stats = s.stats().unwrap();
assert_eq!(stats.sessions, 1);
assert_eq!(stats.messages, 2);
assert_eq!(stats.prompt_tokens, 6);
assert_eq!(stats.completion_tokens, 5);
s.delete_session(&sess.id).unwrap();
assert!(s.messages(&sess.id).unwrap().is_empty()); // cascade
assert_eq!(s.list_sessions().unwrap().len(), 0);
}
#[test]
fn ids_are_unique() {
let a = new_id("sess");
let b = new_id("sess");
assert_ne!(a, b);
}
}
+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);
}
+174
View File
@@ -0,0 +1,174 @@
/* strata-ctl web GUI — mobile-first. Single column on phones; a persistent
session sidebar appears on wide screens. Touch-friendly targets, 16px inputs
(avoids iOS focus zoom), safe-area insets for notched phones. */
:root {
--bg: #0f1115;
--panel: #171a21;
--panel-2: #1f2430;
--border: #2a3040;
--text: #e6e9ef;
--muted: #9aa4b2;
--accent: #4f8cff;
--accent-press: #3a6fd6;
--user: #2b3a55;
--danger: #e5534b;
--radius: 14px;
--sidebar-w: 280px;
}
* { box-sizing: border-box; }
/* The `hidden` attribute must always win over author `display` rules (e.g. the
stats modal uses display:flex); otherwise toggling .hidden has no effect. */
[hidden] { display: none !important; }
html, body {
margin: 0;
height: 100%;
background: var(--bg);
color: var(--text);
font-family: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
font-size: 16px;
line-height: 1.5;
}
#app { display: flex; height: 100dvh; overflow: hidden; }
/* ---- Buttons ---- */
.btn {
appearance: none;
border: 1px solid var(--border);
background: var(--panel-2);
color: var(--text);
border-radius: 10px;
padding: 10px 14px;
font-size: 0.95rem;
cursor: pointer;
min-height: 44px;
transition: background 0.12s ease, transform 0.05s ease;
}
.btn:active { transform: scale(0.97); }
.btn.primary { background: var(--accent); border-color: var(--accent); color: #fff; }
.btn.primary:active { background: var(--accent-press); }
.btn.ghost { background: transparent; }
.btn.icon { padding: 8px 12px; font-size: 1.2rem; line-height: 1; }
.btn.danger { color: var(--danger); }
.btn:disabled { opacity: 0.5; cursor: default; }
/* ---- Drawer / sidebar ---- */
#drawer {
position: fixed;
inset: 0 auto 0 0;
width: min(82vw, var(--sidebar-w));
background: var(--panel);
border-right: 1px solid var(--border);
display: flex;
flex-direction: column;
transform: translateX(-100%);
transition: transform 0.2s ease;
z-index: 30;
padding-top: env(safe-area-inset-top);
}
#drawer.open { transform: translateX(0); }
#scrim {
position: fixed; inset: 0; background: rgba(0,0,0,0.5); z-index: 20;
}
.drawer-head {
display: flex; align-items: center; justify-content: space-between;
gap: 8px; padding: 12px;
border-bottom: 1px solid var(--border);
}
.brand { font-weight: 700; letter-spacing: 0.3px; }
#session-list { list-style: none; margin: 0; padding: 8px; overflow-y: auto; flex: 1; }
#session-list li {
padding: 12px; border-radius: 10px; cursor: pointer;
color: var(--muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
min-height: 44px; display: flex; align-items: center;
}
#session-list li:hover { background: var(--panel-2); }
#session-list li.active { background: var(--panel-2); color: var(--text); }
.drawer-foot { padding: 12px; border-top: 1px solid var(--border); }
/* ---- Main column ---- */
#main { flex: 1; display: flex; flex-direction: column; min-width: 0; height: 100dvh; }
#topbar {
display: flex; align-items: center; gap: 10px;
padding: 10px 12px; padding-top: calc(10px + env(safe-area-inset-top));
border-bottom: 1px solid var(--border); background: var(--panel);
}
.title-wrap { flex: 1; min-width: 0; display: flex; flex-direction: column; }
#session-title { font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.muted { color: var(--muted); font-size: 0.8rem; }
#transcript {
flex: 1; overflow-y: auto; padding: 16px 12px;
display: flex; flex-direction: column; gap: 14px;
scroll-behavior: smooth;
}
.empty { color: var(--muted); text-align: center; margin: auto; max-width: 28ch; }
/* ---- Message bubbles ---- */
.msg { max-width: 860px; width: 100%; margin: 0 auto; display: flex; flex-direction: column; }
.msg .role { font-size: 0.75rem; color: var(--muted); margin-bottom: 4px; }
.msg.user { align-items: flex-end; }
.msg.user .bubble {
background: var(--user); border-radius: var(--radius) var(--radius) 4px var(--radius);
padding: 10px 14px; max-width: 85%;
}
.msg.assistant .bubble {
background: var(--panel); border: 1px solid var(--border);
border-radius: var(--radius) var(--radius) var(--radius) 4px;
padding: 10px 14px; width: 100%;
}
.bubble .content { white-space: pre-wrap; word-wrap: break-word; }
.bubble .content:empty::after { content: "…"; color: var(--muted); }
details.thinking { margin-bottom: 8px; }
details.thinking summary {
cursor: pointer; color: var(--muted); font-size: 0.85rem; user-select: none;
}
details.thinking .reasoning {
white-space: pre-wrap; word-wrap: break-word; color: var(--muted);
font-size: 0.9rem; border-left: 2px solid var(--border);
padding-left: 10px; margin-top: 6px;
}
.usage { color: var(--muted); font-size: 0.72rem; margin-top: 6px; }
/* ---- Composer ---- */
#composer {
display: flex; gap: 8px; align-items: flex-end;
padding: 10px 12px; padding-bottom: calc(10px + env(safe-area-inset-bottom));
border-top: 1px solid var(--border); background: var(--panel);
}
#input {
flex: 1; resize: none; max-height: 40dvh;
background: var(--panel-2); color: var(--text);
border: 1px solid var(--border); border-radius: 12px;
padding: 12px 14px; font-size: 16px; font-family: inherit; line-height: 1.4;
}
#input:focus { outline: none; border-color: var(--accent); }
#send { min-width: 52px; font-size: 1.3rem; }
/* ---- Stats modal ---- */
#stats-modal {
position: fixed; inset: 0; z-index: 40;
background: rgba(0,0,0,0.6); display: flex; align-items: center; justify-content: center;
padding: 20px;
}
.modal-card {
background: var(--panel); border: 1px solid var(--border); border-radius: var(--radius);
padding: 20px; max-width: 420px; width: 100%;
}
.modal-card h2 { margin: 0 0 12px; font-size: 1.1rem; }
#stats-body { display: grid; grid-template-columns: 1fr auto; gap: 6px 16px; margin: 0 0 16px; }
#stats-body dt { color: var(--muted); }
#stats-body dd { margin: 0; font-variant-numeric: tabular-nums; }
/* ---- Wide screens: persistent sidebar ---- */
@media (min-width: 900px) {
#drawer { position: static; transform: none; width: var(--sidebar-w); flex-shrink: 0; }
#scrim { display: none !important; }
#menu { display: none; }
.msg.user .bubble { max-width: 70%; }
}
+258
View File
@@ -0,0 +1,258 @@
// strata-ctl web GUI — vanilla ES module, no build step, no dependencies.
// Talks to the session-aware API (/api/sessions...); the server owns context.
// Model output is always inserted via textContent (never innerHTML) to avoid
// injection. Mobile-first: the session list is an off-canvas drawer on phones.
const $ = (sel) => document.querySelector(sel);
const state = { sessions: [], current: null, busy: false };
// ---- API helpers ----------------------------------------------------------
async function getJSON(url) {
const r = await fetch(url);
if (!r.ok) throw new Error(await r.text());
return r.json();
}
async function sendJSON(url, method, body) {
const r = await fetch(url, {
method,
headers: { "Content-Type": "application/json" },
body: body === undefined ? undefined : JSON.stringify(body),
});
if (!r.ok) throw new Error(await r.text());
return r.status === 204 ? null : r.json();
}
// Stream a chat turn, invoking onDelta for each SSE chunk.
async function streamChat(id, content, onDelta) {
const r = await fetch(`/api/sessions/${id}/chat`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ content, stream: true }),
});
if (!r.ok) throw new Error(await r.text());
const reader = r.body.getReader();
const dec = new TextDecoder();
let buf = "";
for (;;) {
const { done, value } = await reader.read();
if (done) break;
buf += dec.decode(value, { stream: true });
let idx;
while ((idx = buf.indexOf("\n\n")) >= 0) {
const block = buf.slice(0, idx);
buf = buf.slice(idx + 2);
for (const line of block.split("\n")) {
if (!line.startsWith("data:")) continue;
const data = line.slice(5).trim();
if (data === "[DONE]") return;
try { onDelta(JSON.parse(data)); } catch { /* ignore partial */ }
}
}
}
}
// ---- DOM builders ---------------------------------------------------------
function el(tag, cls, text) {
const n = document.createElement(tag);
if (cls) n.className = cls;
if (text !== undefined) n.textContent = text;
return n;
}
function messageNode(role, content, reasoning, usage) {
const wrap = el("div", `msg ${role}`);
wrap.appendChild(el("div", "role", role === "user" ? "Tu" : "Assistente"));
const bubble = el("div", "bubble");
if (reasoning) {
const det = el("details", "thinking");
det.appendChild(el("summary", null, "Pensiero"));
det.appendChild(el("div", "reasoning", reasoning));
bubble.appendChild(det);
}
bubble.appendChild(el("div", "content", content || ""));
if (usage) bubble.appendChild(el("div", "usage", usage));
wrap.appendChild(bubble);
return wrap;
}
function scrollDown() {
const t = $("#transcript");
t.scrollTop = t.scrollHeight;
}
// ---- Rendering ------------------------------------------------------------
function renderSessions() {
const list = $("#session-list");
list.textContent = "";
for (const s of state.sessions) {
const li = el("li", s.id === state.current ? "active" : null, s.title);
li.addEventListener("click", () => { selectSession(s.id); closeDrawer(); });
list.appendChild(li);
}
}
function renderTranscript(messages) {
const t = $("#transcript");
t.textContent = "";
const visible = messages.filter((m) => m.role === "user" || m.role === "assistant");
if (visible.length === 0) {
t.appendChild(el("div", "empty", "Inizia una conversazione: scrivi un messaggio qui sotto."));
return;
}
for (const m of visible) {
const usage = m.role === "assistant" && m.completion_tokens
? `${m.prompt_tokens} + ${m.completion_tokens} token` : null;
t.appendChild(messageNode(m.role, m.content, m.reasoning_content, usage));
}
scrollDown();
}
// ---- Actions --------------------------------------------------------------
async function loadSessions(selectId) {
state.sessions = await getJSON("/api/sessions");
if (state.sessions.length === 0) {
const s = await sendJSON("/api/sessions", "POST", {});
state.sessions = [s];
}
const target = selectId || state.current || state.sessions[0].id;
renderSessions();
await selectSession(target);
}
async function selectSession(id) {
state.current = id;
const sess = state.sessions.find((s) => s.id === id);
$("#session-title").textContent = sess ? sess.title : "Conversazione";
$("#model-name").textContent = sess ? sess.model : "";
renderSessions();
const messages = await getJSON(`/api/sessions/${id}/messages`);
renderTranscript(messages);
}
async function newSession() {
const s = await sendJSON("/api/sessions", "POST", {});
state.sessions.unshift(s);
renderSessions();
await selectSession(s.id);
closeDrawer();
$("#input").focus();
}
async function deleteSession() {
if (!state.current) return;
if (!confirm("Eliminare questa conversazione?")) return;
await sendJSON(`/api/sessions/${state.current}`, "DELETE");
state.current = null;
await loadSessions();
}
async function sendMessage() {
const input = $("#input");
const content = input.value.trim();
if (!content || state.busy || !state.current) return;
state.busy = true;
$("#send").disabled = true;
input.value = "";
autoGrow(input);
const t = $("#transcript");
const empty = t.querySelector(".empty");
if (empty) empty.remove();
t.appendChild(messageNode("user", content));
// Live assistant bubble.
const wrap = el("div", "msg assistant");
wrap.appendChild(el("div", "role", "Assistente"));
const bubble = el("div", "bubble");
const det = el("details", "thinking");
det.appendChild(el("summary", null, "Pensiero"));
const reasoningNode = el("div", "reasoning", "");
det.appendChild(reasoningNode);
det.hidden = true;
const contentNode = el("div", "content", "");
bubble.appendChild(det);
bubble.appendChild(contentNode);
wrap.appendChild(bubble);
t.appendChild(wrap);
scrollDown();
let reasoning = "", text = "", usage = null;
try {
await streamChat(state.current, content, (chunk) => {
const d = chunk.choices && chunk.choices[0] && chunk.choices[0].delta;
if (d && d.reasoning_content) {
reasoning += d.reasoning_content;
reasoningNode.textContent = reasoning;
det.hidden = false;
}
if (d && d.content) {
text += d.content;
contentNode.textContent = text;
}
if (chunk.usage) usage = chunk.usage;
scrollDown();
});
if (usage) {
bubble.appendChild(el("div", "usage",
`${usage.prompt_tokens} + ${usage.completion_tokens} token`));
}
// Refresh ordering/titles without losing the live transcript.
state.sessions = await getJSON("/api/sessions");
renderSessions();
} catch (e) {
contentNode.textContent = text || `Errore: ${e.message}`;
} finally {
state.busy = false;
$("#send").disabled = false;
input.focus();
scrollDown();
}
}
async function showStats() {
const s = await getJSON("/api/stats");
const body = $("#stats-body");
body.textContent = "";
const rows = [
["Sessioni", s.sessions],
["Messaggi", s.messages],
["Token prompt", s.prompt_tokens],
["Token completati", s.completion_tokens],
];
for (const [k, v] of rows) {
body.appendChild(el("dt", null, k));
body.appendChild(el("dd", null, String(v)));
}
$("#stats-modal").hidden = false;
}
// ---- Drawer / input UX ----------------------------------------------------
function openDrawer() { $("#drawer").classList.add("open"); $("#scrim").hidden = false; }
function closeDrawer() { $("#drawer").classList.remove("open"); $("#scrim").hidden = true; }
function autoGrow(t) {
t.style.height = "auto";
t.style.height = Math.min(t.scrollHeight, window.innerHeight * 0.4) + "px";
}
function wire() {
$("#menu").addEventListener("click", openDrawer);
$("#scrim").addEventListener("click", closeDrawer);
$("#new-session").addEventListener("click", newSession);
$("#delete-session").addEventListener("click", deleteSession);
$("#send").addEventListener("click", sendMessage);
$("#show-stats").addEventListener("click", showStats);
$("#close-stats").addEventListener("click", () => { $("#stats-modal").hidden = true; });
const input = $("#input");
input.addEventListener("input", () => autoGrow(input));
input.addEventListener("keydown", (e) => {
if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); sendMessage(); }
});
}
wire();
loadSessions().catch((e) => {
$("#transcript").textContent = "";
$("#transcript").appendChild(el("div", "empty", `Impossibile caricare: ${e.message}`));
});
+56
View File
@@ -0,0 +1,56 @@
<!DOCTYPE html>
<html lang="it">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
<meta name="color-scheme" content="dark light" />
<title>strata-ctl</title>
<link rel="stylesheet" href="/assets/app.css" />
</head>
<body>
<div id="app">
<!-- Session drawer (off-canvas on mobile, sidebar on wide screens) -->
<aside id="drawer" aria-label="Sessioni">
<div class="drawer-head">
<span class="brand">strata&#8209;ctl</span>
<button id="new-session" class="btn primary" title="Nuova conversazione">+ Nuova</button>
</div>
<ul id="session-list"></ul>
<div class="drawer-foot">
<button id="show-stats" class="btn ghost">Statistiche</button>
</div>
</aside>
<div id="scrim" hidden></div>
<!-- Main column -->
<main id="main">
<header id="topbar">
<button id="menu" class="btn icon" aria-label="Apri sessioni">&#9776;</button>
<div class="title-wrap">
<span id="session-title">Conversazione</span>
<span id="model-name" class="muted"></span>
</div>
<button id="delete-session" class="btn icon danger" aria-label="Elimina sessione">&#128465;</button>
</header>
<section id="transcript" aria-live="polite"></section>
<footer id="composer">
<textarea id="input" rows="1" placeholder="Scrivi un messaggio…" autocomplete="off"></textarea>
<button id="send" class="btn primary" aria-label="Invia">&#10148;</button>
</footer>
</main>
</div>
<!-- Stats modal -->
<div id="stats-modal" hidden>
<div class="modal-card">
<h2>Statistiche</h2>
<dl id="stats-body"></dl>
<button id="close-stats" class="btn">Chiudi</button>
</div>
</div>
<script type="module" src="/assets/app.js"></script>
</body>
</html>