feat(frontend): manage projects and their context in the desktop client

A conversation that only lives in memory is lost when the window closes, and
long answers used to be cut off at the window edge because a scroll area
inherits the layout of the parent it is added to. Projects give each exchange a
durable context, the reload and verification actions make that context
observable instead of a black box, and laying the text out before drawing the
bubble keeps every answer inside the column.
This commit is contained in:
BlackAngelTV committed 2026-10-05 21:39:55 +02:00
1 parent 6ebf550eb0
commit b9e23cf975
9 files changed
+2284 -212

No files matched your search

+134
View File
@@ -0,0 +1,134 @@
//! Headless layout tests of the conversation area.
//!
//! `egui` runs fine without a window: a pass is fed a `RawInput` with a fixed
//! screen size and the painted shapes come back in the `FullOutput`. Bubbles
//! are painted as filled rectangles with their own colours, so they can be
//! measured to prove that long answers wrap *inside* the centred column instead
//! of running past the edge of the window.
use eframe::egui;
use jarvise_frontend::app::{COLUMN_MAX_WIDTH, COLUMN_MIN_MARGIN, chat_area};
use jarvise_frontend::model::ChatMessage;
/// Colour of the user's bubbles.
const USER_FILL: egui::Color32 = egui::Color32::from_rgb(0x2f, 0x6f, 0xb5);
/// Colour of Jarvis' bubbles.
const JARVIS_FILL: egui::Color32 = egui::Color32::from_gray(58);
/// A paragraph long enough to need several lines in a bubble.
fn long_text() -> String {
"Jarvise garde le contexte de chaque projet et le renvoie au modèle à chaque tour de parole. "
.repeat(8)
}
/// Column `chat_area` builds inside a window of `screen_width`.
fn column(screen_width: f32) -> (f32, f32) {
let width = (screen_width - 2.0 * COLUMN_MIN_MARGIN).min(COLUMN_MAX_WIDTH);
let side = ((screen_width - width) / 2.0).max(0.0);
(side, side + width)
}
/// Runs one egui pass on a window of the given width and returns what was painted.
fn painted(screen_width: f32, messages: &[ChatMessage]) -> Vec<egui::epaint::ClippedShape> {
let ctx = egui::Context::default();
ctx.set_fonts(egui::FontDefinitions::default());
let input = egui::RawInput {
screen_rect: Some(egui::Rect::from_min_size(
egui::Pos2::ZERO,
egui::vec2(screen_width, 900.0),
)),
..Default::default()
};
let mut output = ctx.run_ui(input, |ui| chat_area(ui, messages));
let shapes = std::mem::take(&mut output.shapes);
// Nothing rasterises the fonts here, so the texture deltas can be dropped.
output.drop_without_applying_deltas();
shapes
}
/// Filled rectangles painted with a bubble colour, i.e. the bubbles themselves.
fn bubbles(shapes: &[egui::epaint::ClippedShape]) -> Vec<egui::Rect> {
shapes
.iter()
.filter_map(|clipped| match &clipped.shape {
egui::Shape::Rect(rect) if rect.fill == USER_FILL || rect.fill == JARVIS_FILL => {
Some(rect.rect)
}
_ => None,
})
.collect()
}
#[test]
fn long_answers_wrap_inside_the_centred_column() {
let messages = vec![
ChatMessage::assistant(long_text()),
ChatMessage::user(long_text()),
];
let shapes = painted(1400.0, &messages);
let rects = bubbles(&shapes);
assert_eq!(rects.len(), 2, "one bubble per message, got {rects:?}");
let (left, right) = column(1400.0);
for rect in &rects {
assert!(
rect.min.x >= left - 1.0 && rect.max.x <= right + 1.0,
"bubble {rect:?} escapes the column [{left}, {right}]"
);
assert!(
rect.width() <= (right - left) * 0.83,
"bubble {rect:?} is wider than the column"
);
// A single line would be ~20 pt high: several lines prove the text wrapped.
assert!(
rect.height() > 40.0,
"long text was not wrapped, bubble {rect:?} is one line high"
);
}
}
#[test]
fn bubbles_stay_on_screen_in_a_narrow_window() {
let messages = vec![
ChatMessage::user(long_text()),
ChatMessage::assistant(long_text()),
];
let shapes = painted(420.0, &messages);
let (left, right) = column(420.0);
for rect in bubbles(&shapes) {
assert!(
rect.min.x >= left - 1.0 && rect.max.x <= right + 1.0,
"bubble {rect:?} escapes the column [{left}, {right}] of a 420 pt window"
);
assert!(rect.max.x <= 420.0, "bubble {rect:?} runs off the window");
}
}
#[test]
fn user_bubbles_hug_the_right_and_jarvis_the_left() {
let messages = vec![
ChatMessage::assistant("Salut"),
ChatMessage::user("Salut"),
];
let shapes = painted(1400.0, &messages);
let rects = bubbles(&shapes);
assert_eq!(rects.len(), 2);
let jarvis = rects.iter().find(|rect| rect.width() > 0.0 && rect.min.x < 300.0);
assert!(jarvis.is_some(), "Jarvis' bubble must start at the left: {rects:?}");
}
#[test]
fn an_empty_conversation_paints_no_bubble() {
let shapes = painted(1400.0, &[]);
assert!(
bubbles(&shapes).is_empty(),
"the placeholder must not look like a message"
);
}
+526
View File
@@ -0,0 +1,526 @@
//! 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());
}
/// 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"));
}