Files
Jarvise-project/frontend/tests/projects_api.rs
T
BlackAngelTV 9226500a56 feat(frontend): render Markdown answers and speak them while they stream
Two things made Jarvis feel worse than it was. Its Markdown arrived as raw
syntax, because egui has no Markdown widget and the bundled fonts have a
single weight per family; the renderer therefore builds its own styled
LayoutJob, which keeps the bubble sizing already in place and tolerates a
half-streamed answer instead of printing markers. And the voice only started
once the whole answer was generated, so a long reply was read out after a
silence as long as the reply itself; the stream is now cut into sentences as
soon as their punctuation arrives, and the spoken text drops the Markdown and
the code blocks, since nobody wants asterisks and backticks read aloud.

The client also wakes the model on the first keystroke of a draft or when
recording starts, so the load happens while the sentence is still being
written, and it now sends a history the backend accepts: empty assistant
bubbles left by an abandoned answer are dropped, and only the last fifty
messages travel, which a long conversation used to overflow.
2026-10-06 20:03:41 +02:00

545 lines
17 KiB
Rust

//! Integration tests for the projects and their message context.
//!
//! A fake HTTP server stands in for the backend, so the real reqwest code path
//! is exercised end to end: request method and path, JSON bodies, camelCase
//! decoding, the `204 No Content` of a deletion and the named SSE events of
//! `POST /api/projects/:id/chat/stream`.
use std::io::{Read, Write};
use std::net::{TcpListener, TcpStream};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::thread;
use jarvise_frontend::api::{ApiClient, ApiError, RecallEvent, StreamEvent};
use jarvise_frontend::model::{Project, StoredMessage};
use tokio_util::sync::CancellationToken;
/// What the fake server received.
#[derive(Clone, Debug)]
struct CapturedRequest {
method: String,
target: String,
body: String,
}
/// Answer of the fake server.
struct FakeReply {
status_line: &'static str,
content_type: &'static str,
body: String,
}
impl FakeReply {
fn json(body: impl Into<String>) -> Self {
Self {
status_line: "HTTP/1.1 200 OK",
content_type: "application/json",
body: body.into(),
}
}
fn created(body: impl Into<String>) -> Self {
Self {
status_line: "HTTP/1.1 201 Created",
content_type: "application/json",
body: body.into(),
}
}
fn empty() -> Self {
Self {
status_line: "HTTP/1.1 204 No Content",
content_type: "application/json",
body: String::new(),
}
}
fn sse(body: impl Into<String>) -> Self {
Self {
status_line: "HTTP/1.1 200 OK",
content_type: "text/event-stream",
body: body.into(),
}
}
fn status(status_line: &'static str, body: impl Into<String>) -> Self {
Self {
status_line,
content_type: "application/json",
body: body.into(),
}
}
}
struct FakeServer {
base_url: String,
requests: Arc<Mutex<Vec<CapturedRequest>>>,
stop: Arc<AtomicBool>,
}
impl FakeServer {
fn client(&self) -> ApiClient {
let mut client = ApiClient::new(self.base_url.clone());
client.set_token(Some("test-token".to_string()));
client
}
/// Requests received so far, in order.
fn requests(&self) -> Vec<CapturedRequest> {
self.requests.lock().expect("lock").clone()
}
}
impl Drop for FakeServer {
fn drop(&mut self) {
self.stop.store(true, Ordering::SeqCst);
}
}
/// Starts a server answering every request through `handler` until dropped.
fn start_server<H>(handler: H) -> FakeServer
where
H: Fn(&CapturedRequest) -> FakeReply + Send + Sync + 'static,
{
let listener = TcpListener::bind("127.0.0.1:0").expect("bind");
listener.set_nonblocking(true).expect("nonblocking");
let base_url = format!("http://{}", listener.local_addr().expect("addr"));
let requests = Arc::new(Mutex::new(Vec::new()));
let stop = Arc::new(AtomicBool::new(false));
let sink = requests.clone();
let flag = stop.clone();
thread::spawn(move || {
while !flag.load(Ordering::SeqCst) {
match listener.accept() {
Ok((mut socket, _)) => {
socket.set_nonblocking(false).expect("blocking socket");
let request = read_request(&mut socket);
let reply = handler(&request);
sink.lock().expect("lock").push(request);
let response = format!(
"{}\r\nContent-Type: {}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
reply.status_line,
reply.content_type,
reply.body.len(),
reply.body
);
let _ = socket.write_all(response.as_bytes());
let _ = socket.flush();
}
Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
thread::sleep(std::time::Duration::from_millis(2));
}
Err(_) => break,
}
}
});
FakeServer {
base_url,
requests,
stop,
}
}
fn read_request(socket: &mut TcpStream) -> CapturedRequest {
let mut data = Vec::new();
let mut buffer = [0u8; 1024];
loop {
match socket.read(&mut buffer) {
Ok(0) | Err(_) => break,
Ok(n) => {
data.extend_from_slice(&buffer[..n]);
if let Some(header_end) = find(&data, b"\r\n\r\n") {
let head = String::from_utf8_lossy(&data[..header_end]).to_string();
let length = content_length(&head);
let body_start = header_end + 4;
while data.len() < body_start + length {
match socket.read(&mut buffer) {
Ok(0) | Err(_) => break,
Ok(n) => data.extend_from_slice(&buffer[..n]),
}
}
let body = String::from_utf8_lossy(&data[body_start..]).to_string();
let mut lines = head.lines();
let mut start = lines.next().unwrap_or_default().split_whitespace();
let method = start.next().unwrap_or_default().to_string();
let target = start.next().unwrap_or_default().to_string();
return CapturedRequest {
method,
target,
body,
};
}
}
}
}
CapturedRequest {
method: String::new(),
target: String::new(),
body: String::new(),
}
}
fn find(haystack: &[u8], needle: &[u8]) -> Option<usize> {
haystack
.windows(needle.len())
.position(|window| window == needle)
}
fn content_length(head: &str) -> usize {
head.lines()
.find_map(|line| {
let (name, value) = line.split_once(':')?;
name.eq_ignore_ascii_case("content-length")
.then(|| value.trim().parse().ok())
.flatten()
})
.unwrap_or(0)
}
fn body_json(request: &CapturedRequest) -> serde_json::Value {
serde_json::from_str(&request.body).expect("the request body must be JSON")
}
fn sample_project() -> &'static str {
r#"{
"id": 3,
"userId": 1,
"name": "Jarvise",
"description": "The assistant itself",
"messageCount": 7,
"createdAt": "2026-10-05 10:00:00",
"updatedAt": "2026-10-05 12:34:00"
}"#
}
#[tokio::test]
async fn lists_projects_and_decodes_camel_case() {
let server = start_server(|_| {
FakeReply::json(format!("{{\"projects\":[{}]}}", sample_project()))
});
let projects = server.client().list_projects().await.expect("list projects");
assert_eq!(
projects,
vec![Project {
id: 3,
name: "Jarvise".to_string(),
description: Some("The assistant itself".to_string()),
message_count: 7,
updated_at: Some("2026-10-05 12:34:00".to_string()),
}]
);
let requests = server.requests();
assert_eq!(requests[0].method, "GET");
assert_eq!(requests[0].target, "/api/projects");
}
#[tokio::test]
async fn creates_a_project_with_its_description() {
let server = start_server(|_| FakeReply::created(format!("{{\"project\":{}}}", sample_project())));
let project = server
.client()
.create_project("Jarvise", Some("The assistant itself"))
.await
.expect("create project");
assert_eq!(project.id, 3);
assert_eq!(project.message_count, 7);
let requests = server.requests();
assert_eq!(requests[0].method, "POST");
assert_eq!(requests[0].target, "/api/projects");
let body = body_json(&requests[0]);
assert_eq!(body["name"], "Jarvise");
assert_eq!(body["description"], "The assistant itself");
}
#[tokio::test]
async fn renames_then_deletes_a_project() {
let server = start_server(|request| {
if request.method == "DELETE" {
FakeReply::empty()
} else {
FakeReply::json(format!("{{\"project\":{}}}", sample_project()))
}
});
let client = server.client();
let renamed = client
.update_project(3, Some("Jarvise 2"), None)
.await
.expect("rename project");
assert_eq!(renamed.name, "Jarvise");
client.delete_project(3).await.expect("delete project");
let requests = server.requests();
assert_eq!(requests[0].method, "PATCH");
assert_eq!(requests[0].target, "/api/projects/3");
// `description` is left out so the backend keeps the stored value.
assert_eq!(body_json(&requests[0]), serde_json::json!({"name": "Jarvise 2"}));
assert_eq!(requests[1].method, "DELETE");
assert_eq!(requests[1].target, "/api/projects/3");
}
#[tokio::test]
async fn loads_the_message_context_of_a_project() {
let server = start_server(|_| {
FakeReply::json(
r#"{
"projectId": 3,
"messages": [
{"id": 10, "projectId": 3, "role": "user", "content": "Bonjour", "createdAt": "2026-10-05 12:00:00"},
{"id": 11, "projectId": 3, "role": "assistant", "content": "Bonjour !", "createdAt": "2026-10-05 12:00:09"}
],
"hasMore": false,
"oldestId": 10
}"#,
)
});
let page = server
.client()
.project_messages(3, 200)
.await
.expect("load messages");
assert!(!page.has_more);
assert_eq!(page.messages.len(), 2);
assert_eq!(page.messages[0].role, "user");
assert_eq!(page.messages[0].to_chat().content, "Bonjour");
assert_eq!(page.messages[1].time_label(), Some("12:00"));
let requests = server.requests();
assert_eq!(requests[0].method, "GET");
assert_eq!(requests[0].target, "/api/projects/3/messages?limit=200");
}
#[tokio::test]
async fn adds_a_note_to_the_context_and_clears_it() {
let server = start_server(|request| {
if request.method == "DELETE" {
FakeReply::json(r#"{"deleted": 4}"#)
} else {
FakeReply::created(
r#"{"message":{"id": 12, "projectId": 3, "role": "system", "content": "Réponds en français.", "createdAt": "2026-10-05 12:40:00"}}"#,
)
}
});
let client = server.client();
let note = client
.add_project_message(3, "system", "Réponds en français.")
.await
.expect("add message");
assert_eq!(note.role, "system");
assert_eq!(note.to_chat().content, "Réponds en français.");
let deleted = client
.clear_project_messages(3)
.await
.expect("clear messages");
assert_eq!(deleted, 4);
let requests = server.requests();
assert_eq!(requests[0].method, "POST");
assert_eq!(requests[0].target, "/api/projects/3/messages");
assert_eq!(
body_json(&requests[0]),
serde_json::json!({"role": "system", "content": "Réponds en français."})
);
assert_eq!(requests[1].method, "DELETE");
assert_eq!(requests[1].target, "/api/projects/3/messages");
}
#[tokio::test]
async fn streams_a_project_chat_with_named_events() {
let server = start_server(|_| {
FakeReply::sse(concat!(
": stream open\n\n",
"event: delta\ndata: {\"content\":\"Bonjour\"}\n\n",
"event: delta\ndata: {\"content\":\" Tony\"}\n\n",
"event: done\ndata: {\"reply\":\"Bonjour Tony\",\"model\":\"qwen2.5:3b\",\"projectId\":3,\"messages\":[]}\n\n",
))
});
let events = Arc::new(Mutex::new(Vec::new()));
let sink = events.clone();
let result = server
.client()
.stream_project_chat(
3,
"Salut",
"qwen2.5:3b",
CancellationToken::new(),
move |event| sink.lock().expect("lock").push(event),
)
.await;
result.expect("the project stream should succeed");
assert_eq!(
*events.lock().expect("lock"),
vec![
StreamEvent::Delta("Bonjour".to_string()),
StreamEvent::Delta(" Tony".to_string()),
StreamEvent::Done,
]
);
let requests = server.requests();
assert_eq!(requests[0].method, "POST");
assert_eq!(requests[0].target, "/api/projects/3/chat/stream");
// The context lives in the backend: only the new prompt travels.
assert_eq!(
body_json(&requests[0]),
serde_json::json!({"message": "Salut", "model": "qwen2.5:3b"})
);
}
#[tokio::test]
async fn reports_an_inline_error_event_of_a_project_chat() {
let server = start_server(|_| {
FakeReply::sse("event: error\ndata: {\"error\":\"Ollama injoignable\",\"partial\":\"\"}\n\n")
});
let events = Arc::new(Mutex::new(Vec::new()));
let sink = events.clone();
server
.client()
.stream_project_chat(
3,
"Salut",
"qwen2.5:3b",
CancellationToken::new(),
move |event| sink.lock().expect("lock").push(event),
)
.await
.expect("an inline error is not a transport failure");
assert_eq!(
*events.lock().expect("lock"),
vec![StreamEvent::Error("Ollama injoignable".to_string())]
);
}
#[tokio::test]
async fn recites_the_context_and_reports_the_message_count() {
let server = start_server(|_| {
FakeReply::sse(concat!(
": stream open\n\n",
"event: delta\ndata: {\"content\":\"Le frontend est en Rust\"}\n\n",
"event: done\ndata: {\"reply\":\"Le frontend est en Rust\",\"model\":\"qwen2.5:3b\",\"contextMessages\":2}\n\n",
))
});
let events = Arc::new(Mutex::new(Vec::new()));
let sink = events.clone();
server
.client()
.stream_project_recall(3, "qwen2.5:3b", CancellationToken::new(), move |event| {
sink.lock().expect("lock").push(event)
})
.await
.expect("the recall stream should succeed");
assert_eq!(
*events.lock().expect("lock"),
vec![
RecallEvent::Delta("Le frontend est en Rust".to_string()),
// How many stored messages the backend actually replayed.
RecallEvent::Done(2),
]
);
let requests = server.requests();
assert_eq!(requests[0].method, "POST");
assert_eq!(requests[0].target, "/api/projects/3/context/recall");
assert_eq!(
body_json(&requests[0]),
serde_json::json!({"model": "qwen2.5:3b"})
);
}
#[tokio::test]
async fn surfaces_a_missing_project() {
let server = start_server(|_| {
FakeReply::status("HTTP/1.1 404 Not Found", r#"{"error":"Project not found."}"#)
});
let error = server
.client()
.project_messages(42, 50)
.await
.expect_err("a 404 must be an error");
match error {
ApiError::Status { status, message } => {
assert_eq!(status.as_u16(), 404);
assert_eq!(message, "Project not found.");
}
other => panic!("expected a status error, got {other:?}"),
}
}
#[tokio::test]
async fn fails_when_no_token_is_set() {
let server = start_server(|_| FakeReply::json("{\"projects\":[]}"));
let client = ApiClient::new(server.base_url.clone());
// The client is not authenticated: nothing should reach the network.
client.list_projects().await.expect_err("expected an error");
assert!(server.requests().is_empty());
}
/// Warm-up: the client asks for the model to be loaded before the question that
/// needs it, so the several-second load happens while the user is still typing.
#[tokio::test]
async fn warms_the_model_before_the_question() {
let server = start_server(|_| FakeReply::json(r#"{"model":"qwen2.5:3b","warmed":true}"#));
server
.client()
.warm_model("qwen2.5:3b")
.await
.expect("the warm-up should be accepted");
let requests = server.requests();
assert_eq!(requests.len(), 1);
assert_eq!(requests[0].method, "POST");
assert_eq!(requests[0].target, "/api/chat/warm");
assert_eq!(body_json(&requests[0])["model"], "qwen2.5:3b");
}
/// Guards the `StoredMessage` -> `ChatMessage` conversion used by the sidebar.
#[test]
fn converts_a_stored_message_into_a_chat_message() {
let stored = StoredMessage {
id: 1,
role: "assistant".to_string(),
content: "Bonjour !".to_string(),
created_at: Some("2026-10-05 12:34:56".to_string()),
};
assert_eq!(
stored.to_chat(),
jarvise_frontend::model::ChatMessage::assistant("Bonjour !")
);
assert_eq!(stored.time_label(), Some("12:34"));
}