- agent:🐚 native shell_exec (bash -lc, cwd, timeout, 64 KiB output cap)
behind a ShellRunner seam — base/host mode now; an isolated Docker-MCP runner
plugs in later without touching the loop. OpenAI function declaration included.
- agent::run_loop: bounded model<->tool orchestration, generic over the model
step so it is unit-testable without the engine. Persists the full trajectory
(assistant tool-call turns + role:tool results + final answer) and emits
tool_call / tool_result / final / error progress events.
- api::sessions: POST .../chat with agent:true drives the loop and streams the
events as SSE; the GUI shows commands + output inline (observability, no gate).
- store: messages gains tool_call_id; an idempotent migration adds the column to
pre-existing databases (CREATE TABLE IF NOT EXISTS does not alter them).
- web: robot agent toggle, tool-call/output blocks, history rendering of tool
turns; inline favicon to silence the favicon 404.
Validated LIVE on engine 0.1.67: the model called shell_exec('uname -a'), the
host executed it, and the model reported the output; trajectory persisted; GUI
verified by browser (toggle, tool block, output, final answer). 106 tests +
2 ignored green, clippy/fmt clean. Isolated mode (user-provided Docker container)
is the next step.
302 lines
9.5 KiB
Rust
302 lines
9.5 KiB
Rust
//! End-to-end tests of the session-aware GUI API (`/api/sessions...`): the
|
|
//! server holds context across turns, persists messages + usage, streams, and
|
|
//! serves the embedded web GUI. Driven through the mock engine + a byte
|
|
//! formatter, with an in-memory SQLite store.
|
|
|
|
use std::sync::Arc;
|
|
use std::time::Duration;
|
|
|
|
use axum::body::Body;
|
|
use axum::http::{header::CONTENT_TYPE, Method, Request, StatusCode};
|
|
use tower::ServiceExt;
|
|
|
|
use strata_ctl::api::formatter::{Decoder, Formatter, Piece, Prompt};
|
|
use strata_ctl::api::service::ChatService;
|
|
use strata_ctl::api::types::{ApiErrorEnvelope, ChatRequest};
|
|
use strata_ctl::api::{router_with_store, AuthConfig};
|
|
use strata_ctl::engine::Engine;
|
|
use strata_ctl::store::{SqliteStore, Store};
|
|
|
|
const MOCK: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/tests/mock_engine.py");
|
|
|
|
struct ByteFormatter;
|
|
impl Formatter for ByteFormatter {
|
|
fn model_name(&self) -> &str {
|
|
"test-model"
|
|
}
|
|
fn build_prompt(&self, req: &ChatRequest) -> Result<Prompt, ApiErrorEnvelope> {
|
|
let text = req
|
|
.messages
|
|
.iter()
|
|
.rev()
|
|
.find_map(|m| m.text())
|
|
.unwrap_or("")
|
|
.to_string();
|
|
Ok(Prompt {
|
|
ids: text.bytes().map(u32::from).collect(),
|
|
max_new: req.max_new(64),
|
|
sampling: Default::default(),
|
|
temp_files: Vec::new(),
|
|
})
|
|
}
|
|
fn decoder(&self) -> Box<dyn Decoder> {
|
|
Box::new(ByteDecoder)
|
|
}
|
|
}
|
|
struct ByteDecoder;
|
|
impl Decoder for ByteDecoder {
|
|
fn push(&mut self, id: u32) -> Vec<Piece> {
|
|
if id < 256 {
|
|
vec![Piece::Content(char::from(id as u8).to_string())]
|
|
} else {
|
|
Vec::new()
|
|
}
|
|
}
|
|
fn finish(&mut self, _reason: Option<&str>) -> Vec<Piece> {
|
|
Vec::new()
|
|
}
|
|
}
|
|
|
|
async fn build_app() -> (axum::Router, Arc<SqliteStore>) {
|
|
let engine = Arc::new(
|
|
Engine::start(
|
|
"python3",
|
|
&[MOCK.to_string()],
|
|
None,
|
|
Duration::from_secs(10),
|
|
)
|
|
.await
|
|
.expect("mock engine starts"),
|
|
);
|
|
let svc = ChatService::new(engine, Arc::new(ByteFormatter));
|
|
let store = Arc::new(SqliteStore::open_in_memory().unwrap());
|
|
let 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);
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn agent_mode_streams_events_and_persists() {
|
|
let (app, store) = build_app().await;
|
|
let id = create_session(&app).await;
|
|
// The mock answers directly (no tool calls), exercising the agent final path.
|
|
let (st, text) = req(
|
|
&app,
|
|
Method::POST,
|
|
&format!("/api/sessions/{id}/chat"),
|
|
Some(serde_json::json!({"content": "hi", "agent": true})),
|
|
)
|
|
.await;
|
|
assert_eq!(st, StatusCode::OK, "{text}");
|
|
let data: Vec<&str> = text
|
|
.lines()
|
|
.filter(|l| l.starts_with("data: "))
|
|
.map(|l| &l["data: ".len()..])
|
|
.collect();
|
|
assert_eq!(data.last().copied(), Some("[DONE]"));
|
|
let mut saw_final = false;
|
|
for line in &data[..data.len() - 1] {
|
|
let v: serde_json::Value = serde_json::from_str(line).unwrap();
|
|
if v["type"] == "final" {
|
|
saw_final = true;
|
|
assert_eq!(v["response"]["choices"][0]["message"]["content"], "efghi");
|
|
}
|
|
}
|
|
assert!(saw_final, "no final agent event: {text}");
|
|
// The final assistant turn is persisted.
|
|
let msgs = store.messages(&id).unwrap();
|
|
assert_eq!(msgs.last().unwrap().role, "assistant");
|
|
assert_eq!(msgs.last().unwrap().content, "efghi");
|
|
}
|