diff --git a/frontend/README.md b/frontend/README.md index fc0e8b2..e7deb96 100644 --- a/frontend/README.md +++ b/frontend/README.md @@ -116,6 +116,40 @@ Le bouton « Stopper » annule un `CancellationToken` (tokio-util) : la tâche d s'arrête immédiatement et la connexion HTTP est coupée, ce qui permet au backend d'interrompre la requête auprès d'Ollama (économie GPU/CPU). +### Projets et contexte + +La barre latérale de gauche pilote les **projets** du backend : une conversation = +une mémoire persistante. + +- **Sans projet** : chaque message part avec l'historique de la fenêtre (endpoint + `POST /api/chat`), rien n'est enregistré côté serveur. +- **Un projet sélectionné** : l'historique est rechargé depuis + `GET /api/projects/:id/messages`, et l'envoi passe par + `POST /api/projects/:id/chat/stream`. Le backend y rejoue le contexte stocké vers + Ollama, puis enregistre la question **et** la réponse — les événements SSE sont + alors nommés : + + | Événement reçu | Traitement | + | ------------------- | --------------------------------------------------- | + | `event: delta` | fragment ajouté à la bulle assistant | + | `event: done` | fin de génération + compteurs de la barre rafraîchis | + | `event: error` | erreur affichée dans la GUI | + +- Depuis la barre latérale : création (`POST /api/projects`), renommage + (`PATCH /api/projects/:id`), suppression (`DELETE /api/projects/:id`, avec + confirmation), ajout d'une **note système** au contexte (`POST + /api/projects/:id/messages`) et vidage de l'historique (`DELETE + /api/projects/:id/messages`). +- **⟳ Recharger** relit le contexte depuis le backend ; **🧠 Vérifier** demande à Jarvis de + **réciter** ce qu'il a reçu (`POST /api/projects/:id/context/recall`). Cette sonde + n'enregistre rien : l'événement `done` renvoie `contextMessages`, le nombre exact de + messages réellement renvoyés au modèle, affiché dans la bulle de légende. +- Le projet ouvert est mémorisé et rouvert au lancement suivant. + +La conversation est dessinée dans une **colonne centrée** de largeur bornée : le texte +est mis en page *avant* l'allocation de la bulle, ce qui garantit qu'une longue réponse +se replie au lieu de déborder de la fenêtre. + ### Gestion des erreurs - Backend injoignable → message réseau affiché dans la GUI. @@ -162,7 +196,8 @@ src/ config.rs # configuration (variables d'environnement) model.rs # structs serde partagées avec le backend api.rs # client HTTP : login, /me, flux SSE (eventsource-stream + CancellationToken) - app.rs # état de l'app, écran de connexion, chat egui, persistance, push-to-talk + app.rs # état de l'app, connexion, barre projets, chat egui, persistance + tamagotchi.rs # compagnon animé dont l'humeur suit l'état de l'app voice/ mod.rs # module voix audio.rs # micro (cpal) + lecture haut-parleur + rééchantillonnage @@ -170,7 +205,9 @@ src/ tts.rs # text-to-speech embarqué (piper-rs) engine.rs # thread dédié (chargement paresseux des modèles, commandes/évènements) tests/ - stream_sse.rs # tests d'intégration du client SSE contre un serveur HTTP local + stream_sse.rs # tests d'intégration du client SSE contre un serveur HTTP local + projects_api.rs # endpoints projets/contexte + SSE nommé du chat par projet + chat_layout.rs # mise en page headless : les bulles restent dans la colonne ``` ## Tests @@ -184,7 +221,11 @@ cargo test - **Intégration** : un petit serveur HTTP rejoue le contrat du backend et vérifie, à travers le vrai code `reqwest` + `eventsource-stream` : le body envoyé (`model` + `messages`), l'en-tête `Authorization`, l'assemblage des fragments, `[DONE]`, l'erreur inline `data: {"error":...}` - et le cas d'un statut HTTP non-200. + et le cas d'un statut HTTP non-200. Le même principe couvre les routes projets + (création, renommage, suppression, contexte, note système) et les événements nommés + `delta` / `done` / `error` du chat par projet. +- **Mise en page** : un passage `egui` sans fenêtre mesure les rectangles peints, et vérifie + qu'une longue réponse se replie **dans** la colonne centrée (y compris sur fenêtre étroite). ## Dépannage diff --git a/frontend/src/api.rs b/frontend/src/api.rs index 289d66c..b6ed35b 100644 --- a/frontend/src/api.rs +++ b/frontend/src/api.rs @@ -1,9 +1,10 @@ //! Asynchronous HTTP client for the Jarvise backend. //! -//! Handles authentication (`/api/auth/*`) and, most importantly, the streamed -//! chat: it opens `POST /api/chat`, reads the `text/event-stream` body chunk by -//! chunk and turns every `data:` line into a [`StreamEvent`]. Nothing here ever -//! touches the GUI thread; callers spawn these futures on a Tokio runtime. +//! Handles authentication (`/api/auth/*`), the projects and their message +//! context (`/api/projects*`) and, most importantly, the streamed chat: it +//! opens a `text/event-stream` request, reads the body chunk by chunk and turns +//! every event into a [`StreamEvent`]. Nothing here ever touches the GUI +//! thread; callers spawn these futures on a Tokio runtime. use std::fmt; @@ -13,7 +14,10 @@ use reqwest::StatusCode; use tokio_util::sync::CancellationToken; use crate::model::{ - ChatMessage, ChatRequest, LoginRequest, LoginResponse, MeResponse, PublicUser, StreamData, + AddMessageRequest, ChatMessage, ChatRequest, CreateProjectRequest, DeletedMessagesResponse, + LoginRequest, LoginResponse, MeResponse, MessagePage, MessageResponse, Project, + ProjectChatRequest, ProjectRecallRequest, ProjectResponse, ProjectsResponse, PublicUser, + RecallDoneData, StreamData, StoredMessage, UpdateProjectRequest, }; /// Errors surfaced to the GUI (which displays them as-is). @@ -52,6 +56,18 @@ pub enum StreamEvent { Error(String), } +/// Event of a context verification stream. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum RecallEvent { + /// A text fragment of the model's answer. + Delta(String), + /// Verification finished; the value is how many stored messages the backend + /// replayed to the model. + Done(usize), + /// An inline error reported by the backend. + Error(String), +} + /// Thin wrapper around `reqwest::Client` bound to one backend and one token. /// /// It is cheap to clone (the inner HTTP client is shared) which lets each @@ -121,33 +137,195 @@ impl ApiClient { /// Validates the current token and returns the associated user. Used at /// startup to check a cached token before showing the login screen. pub async fn me(&self) -> Result { - let token = self - .token - .clone() - .ok_or_else(|| ApiError::Network("aucun token enregistré".to_string()))?; + let response: MeResponse = self.send_json(self.http.get(self.url("/api/auth/me"))).await?; + Ok(response.user) + } - let response = self + /* ----------------------------------------------------------- projects */ + + /// All projects owned by the authenticated user. + pub async fn list_projects(&self) -> Result, ApiError> { + let response: ProjectsResponse = + self.send_json(self.http.get(self.url("/api/projects"))).await?; + Ok(response.projects) + } + + /// Creates a project and returns it as stored. + pub async fn create_project( + &self, + name: &str, + description: Option<&str>, + ) -> Result { + let request = CreateProjectRequest { name, description }; + let response: ProjectResponse = self + .send_json(self.http.post(self.url("/api/projects")).json(&request)) + .await?; + Ok(response.project) + } + + /// Renames a project and/or changes its description. + pub async fn update_project( + &self, + id: i64, + name: Option<&str>, + description: Option<&str>, + ) -> Result { + let request = UpdateProjectRequest { name, description }; + let response: ProjectResponse = self + .send_json( + self.http + .patch(self.url(&format!("/api/projects/{id}"))) + .json(&request), + ) + .await?; + Ok(response.project) + } + + /// Deletes a project and, by cascade, all of its messages. + pub async fn delete_project(&self, id: i64) -> Result<(), ApiError> { + self.send_empty(self.http.delete(self.url(&format!("/api/projects/{id}")))) + .await + } + + /// A page of the project's context, oldest message first. + pub async fn project_messages(&self, id: i64, limit: u32) -> Result { + let url = self.url(&format!("/api/projects/{id}/messages?limit={limit}")); + self.send_json(self.http.get(url)).await + } + + /// Appends a message to the project's context without calling the model + /// (a system note, for instance). + pub async fn add_project_message( + &self, + id: i64, + role: &str, + content: &str, + ) -> Result { + let request = AddMessageRequest { role, content }; + let response: MessageResponse = self + .send_json( + self.http + .post(self.url(&format!("/api/projects/{id}/messages"))) + .json(&request), + ) + .await?; + Ok(response.message) + } + + /// Empties the project's context; returns how many messages were removed. + pub async fn clear_project_messages(&self, id: i64) -> Result { + let response: DeletedMessagesResponse = self + .send_json( + self.http + .delete(self.url(&format!("/api/projects/{id}/messages"))), + ) + .await?; + Ok(response.deleted) + } + + /// Asks Jarvis inside a project: the backend replays the stored context to + /// Ollama, then persists both messages. Streamed like the stateless chat, + /// with the named `delta` / `done` / `error` events. + pub async fn stream_project_chat( + &self, + project_id: i64, + message: &str, + model: &str, + cancel: CancellationToken, + mut on_event: F, + ) -> Result<(), ApiError> + where + F: FnMut(StreamEvent), + { + let request = self .http - .get(self.url("/api/auth/me")) - .bearer_auth(token) - .send() - .await - .map_err(|error| ApiError::Network(error.to_string()))?; - - let status = response.status(); - if !status.is_success() { - return Err(ApiError::Status { - status, - message: read_error_message(response).await, + .post(self.url(&format!("/api/projects/{project_id}/chat/stream"))) + .bearer_auth(self.token()?) + .json(&ProjectChatRequest { + message, + model: Some(model), }); - } - let body = response - .json::() - .await - .map_err(|error| ApiError::Decode(error.to_string()))?; + self.pump_sse(request, cancel, move |event, data| { + match event { + "done" => { + on_event(StreamEvent::Done); + return false; + } + "error" => { + let message = serde_json::from_str::(data) + .ok() + .and_then(|payload| payload.error) + .unwrap_or_else(|| data.to_string()); + on_event(StreamEvent::Error(message)); + return false; + } + _ => { + if let Some(chunk) = serde_json::from_str::(data) + .ok() + .and_then(|payload| payload.content) + { + on_event(StreamEvent::Delta(chunk)); + } + } + } + true + }) + .await + } - Ok(body.user) + /// Asks the model to recite the project's stored context, so the user can + /// check that the history really reaches Ollama. Nothing is persisted on + /// the backend: this is a read-only probe, and `RecallEvent::Done` reports + /// how many messages were replayed. + pub async fn stream_project_recall( + &self, + project_id: i64, + model: &str, + cancel: CancellationToken, + mut on_event: F, + ) -> Result<(), ApiError> + where + F: FnMut(RecallEvent), + { + let request = self + .http + .post(self.url(&format!("/api/projects/{project_id}/context/recall"))) + .bearer_auth(self.token()?) + .json(&ProjectRecallRequest { + model: Some(model), + }); + + self.pump_sse(request, cancel, move |event, data| { + match event { + "done" => { + let context_messages = serde_json::from_str::(data) + .ok() + .and_then(|payload| payload.context_messages) + .unwrap_or(0); + on_event(RecallEvent::Done(context_messages)); + return false; + } + "error" => { + let message = serde_json::from_str::(data) + .ok() + .and_then(|payload| payload.error) + .unwrap_or_else(|| data.to_string()); + on_event(RecallEvent::Error(message)); + return false; + } + _ => { + if let Some(chunk) = serde_json::from_str::(data) + .ok() + .and_then(|payload| payload.content) + { + on_event(RecallEvent::Delta(chunk)); + } + } + } + true + }) + .await } /// Streams a chat completion. @@ -167,20 +345,51 @@ impl ApiClient { where F: FnMut(StreamEvent), { - let token = self - .token - .clone() - .ok_or_else(|| ApiError::Network("aucun token enregistré".to_string()))?; - let request = self .http .post(self.url("/api/chat")) - .bearer_auth(token) + .bearer_auth(self.token()?) .json(&ChatRequest { model: model.to_string(), messages, }); + self.pump_sse(request, cancel, move |_event, data| { + if data == "[DONE]" { + on_event(StreamEvent::Done); + return false; + } + + match serde_json::from_str::(data) { + Ok(payload) => { + if let Some(error) = payload.error { + on_event(StreamEvent::Error(error)); + return false; + } + if let Some(chunk) = payload.content { + on_event(StreamEvent::Delta(chunk)); + } + } + // Keep-alive comments or unknown events are ignored. + Err(_) => {} + } + true + }) + .await + } + + /// Reads an SSE response and forwards `(event name, data)` to `on_event`, + /// which returns `false` to stop reading. Shared by both chat endpoints: + /// they only differ in how their events are named and interpreted. + async fn pump_sse( + &self, + request: reqwest::RequestBuilder, + cancel: CancellationToken, + mut on_event: F, + ) -> Result<(), ApiError> + where + F: FnMut(&str, &str) -> bool, + { // The backend may take a while before sending the first byte (it opens // the Ollama stream first), so cancellation must also cover this phase. let response = tokio::select! { @@ -212,29 +421,13 @@ impl ApiClient { return Err(ApiError::Network(format!("flux interrompu : {error}"))); } Some(Ok(event)) => { - let data = event.data; - let data = data.trim(); + let data = event.data.trim().to_string(); if data.is_empty() { continue; } - if data == "[DONE]" { - on_event(StreamEvent::Done); + if !on_event(&event.event, &data) { return Ok(()); } - - match serde_json::from_str::(data) { - Ok(payload) => { - if let Some(error) = payload.error { - on_event(StreamEvent::Error(error)); - return Ok(()); - } - if let Some(chunk) = payload.content { - on_event(StreamEvent::Delta(chunk)); - } - } - // Keep-alive comments or unknown events are ignored. - Err(_) => continue, - } } } } @@ -242,6 +435,60 @@ impl ApiClient { } } + /* ------------------------------------------------------------ helpers */ + + /// Bearer token of the current session, or an error when logged out. + fn token(&self) -> Result { + self.token + .clone() + .ok_or_else(|| ApiError::Network("aucun token enregistré".to_string())) + } + + /// Sends an authenticated request and decodes its JSON body, turning a + /// non-success status into an [`ApiError::Status`]. + async fn send_json( + &self, + request: reqwest::RequestBuilder, + ) -> Result { + let response = request + .bearer_auth(self.token()?) + .send() + .await + .map_err(|error| ApiError::Network(error.to_string()))?; + + let status = response.status(); + if !status.is_success() { + return Err(ApiError::Status { + status, + message: read_error_message(response).await, + }); + } + + response + .json::() + .await + .map_err(|error| ApiError::Decode(error.to_string())) + } + + /// Same as [`Self::send_json`] for endpoints answering with `204 No Content`. + async fn send_empty(&self, request: reqwest::RequestBuilder) -> Result<(), ApiError> { + let response = request + .bearer_auth(self.token()?) + .send() + .await + .map_err(|error| ApiError::Network(error.to_string()))?; + + let status = response.status(); + if !status.is_success() { + return Err(ApiError::Status { + status, + message: read_error_message(response).await, + }); + } + + Ok(()) + } + fn url(&self, path: &str) -> String { format!("{}{}", self.base_url, path) } diff --git a/frontend/src/app.rs b/frontend/src/app.rs index 36039f3..ddc34f7 100644 --- a/frontend/src/app.rs +++ b/frontend/src/app.rs @@ -13,9 +13,10 @@ use serde::{Deserialize, Serialize}; use tokio::runtime::Runtime; use tokio_util::sync::CancellationToken; -use crate::api::{ApiClient, StreamEvent}; +use crate::api::{ApiClient, RecallEvent, StreamEvent}; use crate::config::AppConfig; -use crate::model::{ChatMessage, PublicUser}; +use crate::model::{ChatMessage, Project, PublicUser, StoredMessage}; +use crate::tamagotchi::{self, Mood}; use crate::voice::audio::Recorder; use crate::voice::engine::{self, VoiceConfig, VoiceEvent, VoiceHandle}; @@ -36,12 +37,42 @@ enum UiEvent { Delta(String), /// The stream finished cleanly. Done, - /// The stream failed (network, HTTP or inline SSE error). - StreamError(String), + /// A request failed (network, HTTP status or inline SSE error). + Error(String), + /// The project list was refreshed. + ProjectsLoaded(Vec), + /// A project was created or renamed. + ProjectCreated(Project), + /// A project was deleted. + ProjectDeleted(i64), + /// A project's context, oldest message first. Discarded if another project + /// was selected while it was loading. + ProjectMessages { + project_id: i64, + messages: Vec, + /// Older messages were left out by the backend's pagination. + truncated: bool, + }, + /// A project's context was emptied. + ProjectContextCleared(i64), + /// A note was appended to a project's context. + ContextNoteAdded { + project_id: i64, + message: ChatMessage, + }, + /// The context verification finished: the model recited what it received. + RecallDone { + project_id: i64, + /// Index of the caption bubble to complete with the real count. + caption_index: usize, + context_messages: usize, + }, /// Speech recognition produced a transcript. Transcribed(String), /// A voice job (STT or TTS) failed. VoiceError(String), + /// Text-to-speech playback finished. + Spoken, } /// What gets written to disk between runs (via eframe's persistence). @@ -51,6 +82,9 @@ struct Persisted { email: String, model: String, backend_url: String, + /// Project reopened on the next run, if it still exists. + #[serde(default)] + project_id: Option, } /// Cloneable bridge used by background tasks to talk to the UI: pushes an event @@ -85,6 +119,23 @@ pub struct JarviseApp { login_error: Option, login_busy: bool, + // Projects: the persisted conversation contexts. + projects: Vec, + current_project: Option, + /// Project waiting for a second click on its delete button. + confirm_delete: Option, + /// Context waiting for a confirmation before being emptied. + confirm_clear: bool, + /// Whether the create/rename form is shown. + form_open: bool, + /// Project being renamed (`None` while creating a new one). + editing: Option, + form_name: String, + form_description: String, + context_note: String, + /// The loaded context does not go back to the first message. + history_truncated: bool, + // Chat. model: String, messages: Vec, @@ -99,6 +150,10 @@ pub struct JarviseApp { recorder: Option, voice_status: Option, pending_transcript: Option, + + // Companion animation. + speaking: bool, + happy_timer: f32, } impl JarviseApp { @@ -139,6 +194,7 @@ impl JarviseApp { let voice = engine::spawn(voice_config, move |event| { voice_notifier.send(match event { VoiceEvent::Transcribed(text) => UiEvent::Transcribed(text), + VoiceEvent::Spoken => UiEvent::Spoken, VoiceEvent::TranscriptionError(message) | VoiceEvent::SpeechError(message) => { UiEvent::VoiceError(message) } @@ -161,6 +217,16 @@ impl JarviseApp { login_password: String::new(), login_error: None, login_busy: false, + projects: Vec::new(), + current_project: persisted.project_id, + confirm_delete: None, + confirm_clear: false, + form_open: false, + editing: None, + form_name: String::new(), + form_description: String::new(), + context_note: String::new(), + history_truncated: false, model, messages: Vec::new(), input: String::new(), @@ -172,6 +238,8 @@ impl JarviseApp { recorder: None, voice_status: None, pending_transcript: None, + speaking: false, + happy_timer: 0.0, }; // If a token was restored, validate it in the background before showing @@ -202,6 +270,201 @@ impl JarviseApp { }); } + /* ----------------------------------------------------------- projects */ + + /// Spawns `GET /api/projects`: the sidebar and its message counters are + /// built from this list. + fn load_projects(&mut self, ctx: &egui::Context) { + let api = self.api.clone(); + let notifier = self.notifier(ctx); + self.runtime.spawn(async move { + match api.list_projects().await { + Ok(projects) => notifier.send(UiEvent::ProjectsLoaded(projects)), + Err(error) => notifier.send(UiEvent::Error(error.to_string())), + } + }); + } + + /// Spawns `GET /api/projects/:id/messages` to display a stored context. + fn load_messages(&self, project_id: i64, ctx: &egui::Context) { + let api = self.api.clone(); + let notifier = self.notifier(ctx); + self.runtime.spawn(async move { + match api.project_messages(project_id, 200).await { + Ok(page) => { + let messages = page.messages.iter().map(StoredMessage::to_chat).collect(); + notifier.send(UiEvent::ProjectMessages { + project_id, + messages, + truncated: page.has_more, + }); + } + Err(error) => notifier.send(UiEvent::Error(error.to_string())), + } + }); + } + + /// Re-reads the stored context of the open project from the backend, which is + /// how a change made elsewhere (or a context probe) is discarded. + fn reload_context(&mut self, ctx: &egui::Context) { + if let Some(project_id) = self.current_project { + self.load_messages(project_id, ctx); + } + } + + /// Asks Jarvis to recite the stored context: a read-only probe proving the + /// history really reaches the model. The exchange is *not* persisted, so + /// « ⟳ Recharger » makes the bubbles disappear. + fn start_recall(&mut self, ctx: &egui::Context) { + let Some(project_id) = self.current_project else { + return; + }; + if self.streaming { + return; + } + + self.error = None; + let caption_index = self.messages.len(); + self.messages + .push(ChatMessage::system("🧠 Vérification du contexte…")); + // A placeholder assistant bubble receives the streamed fragments. + self.messages.push(ChatMessage::assistant(String::new())); + + let cancel = CancellationToken::new(); + self.cancel = Some(cancel.clone()); + self.streaming = true; + + let api = self.api.clone(); + let model = self.model.clone(); + let notifier = self.notifier(ctx); + + self.runtime.spawn(async move { + let callback = notifier.clone(); + let result = api + .stream_project_recall(project_id, &model, cancel, move |event| { + callback.send(match event { + RecallEvent::Delta(text) => UiEvent::Delta(text), + RecallEvent::Done(context_messages) => UiEvent::RecallDone { + project_id, + caption_index, + context_messages, + }, + RecallEvent::Error(message) => UiEvent::Error(message), + }); + }) + .await; + + if let Err(error) = result { + notifier.send(UiEvent::Error(error.to_string())); + } + }); + } + + /// Opens another conversation context; `None` is the stateless chat. + fn select_project(&mut self, target: Option, ctx: &egui::Context) { + if self.current_project == target { + return; + } + + self.stop_stream(); + self.current_project = target; + self.messages.clear(); + self.history_truncated = false; + self.error = None; + self.confirm_delete = None; + self.confirm_clear = false; + self.context_note.clear(); + + if let Some(project_id) = target { + self.load_messages(project_id, ctx); + } + } + + /// Creates the project described by the form, or renames the edited one. + fn save_project(&mut self, ctx: &egui::Context) { + let name = self.form_name.trim().to_string(); + if name.is_empty() { + return; + } + let description = self.form_description.trim().to_string(); + let description = (!description.is_empty()).then_some(description); + let editing = self.editing; + self.form_open = false; + + let api = self.api.clone(); + let notifier = self.notifier(ctx); + self.runtime.spawn(async move { + let result = match editing { + Some(project_id) => api + .update_project(project_id, Some(&name), description.as_deref()) + .await, + None => api.create_project(&name, description.as_deref()).await, + }; + match result { + Ok(project) => notifier.send(UiEvent::ProjectCreated(project)), + Err(error) => notifier.send(UiEvent::Error(error.to_string())), + } + }); + } + + /// Fills the form with the project's values so it can be renamed. + fn edit_project(&mut self, project_id: i64) { + let Some(project) = self.projects.iter().find(|item| item.id == project_id) else { + return; + }; + self.form_name = project.name.clone(); + self.form_description = project.description.clone().unwrap_or_default(); + self.editing = Some(project_id); + self.form_open = true; + } + + fn delete_project(&mut self, project_id: i64, ctx: &egui::Context) { + self.confirm_delete = None; + let api = self.api.clone(); + let notifier = self.notifier(ctx); + self.runtime.spawn(async move { + match api.delete_project(project_id).await { + Ok(()) => notifier.send(UiEvent::ProjectDeleted(project_id)), + Err(error) => notifier.send(UiEvent::Error(error.to_string())), + } + }); + } + + /// Empties a project's context on the backend, then locally. + fn clear_project_context(&mut self, project_id: i64, ctx: &egui::Context) { + self.confirm_clear = false; + let api = self.api.clone(); + let notifier = self.notifier(ctx); + self.runtime.spawn(async move { + match api.clear_project_messages(project_id).await { + Ok(_) => notifier.send(UiEvent::ProjectContextCleared(project_id)), + Err(error) => notifier.send(UiEvent::Error(error.to_string())), + } + }); + } + + /// Appends a system note to the context without calling the model, so the + /// user can pin an instruction Jarvis will read on the next exchange. + fn add_context_note(&mut self, project_id: i64, ctx: &egui::Context) { + let content = self.context_note.trim().to_string(); + if content.is_empty() { + return; + } + self.context_note.clear(); + + let api = self.api.clone(); + let notifier = self.notifier(ctx); + self.runtime.spawn(async move { + match api.add_project_message(project_id, "system", &content).await { + Ok(message) => notifier.send(UiEvent::ContextNoteAdded { + project_id, + message: message.to_chat(), + }), + Err(error) => notifier.send(UiEvent::Error(error.to_string())), + } + }); + } + /// Spawns the login request. fn start_login(&mut self, ctx: &egui::Context) { if self.login_busy { @@ -230,6 +493,9 @@ impl JarviseApp { } /// Sends the current input and starts streaming the answer. + /// + /// Inside a project the backend replays the stored context to the model and + /// persists the exchange; without one, the whole history is sent as-is. fn send_message(&mut self, ctx: &egui::Context) { let text = self.input.trim().to_string(); if text.is_empty() || self.streaming { @@ -237,10 +503,10 @@ impl JarviseApp { } self.error = None; - self.messages.push(ChatMessage::user(text)); + self.messages.push(ChatMessage::user(text.clone())); self.input.clear(); - // The history sent to the backend ends with the user's message. + // The history sent to the stateless endpoint ends with the user's message. let history = self.messages.clone(); // A placeholder assistant bubble receives the streamed fragments. @@ -252,22 +518,27 @@ impl JarviseApp { let api = self.api.clone(); let model = self.model.clone(); + let project_id = self.current_project; let notifier = self.notifier(ctx); self.runtime.spawn(async move { let callback = notifier.clone(); - let result = api - .stream_chat(&model, history, cancel, move |event| { - callback.send(match event { - StreamEvent::Delta(text) => UiEvent::Delta(text), - StreamEvent::Done => UiEvent::Done, - StreamEvent::Error(message) => UiEvent::StreamError(message), - }); - }) - .await; + let on_event = move |event| { + callback.send(match event { + StreamEvent::Delta(text) => UiEvent::Delta(text), + StreamEvent::Done => UiEvent::Done, + StreamEvent::Error(message) => UiEvent::Error(message), + }); + }; + let result = match project_id { + Some(project_id) => api + .stream_project_chat(project_id, &text, &model, cancel, on_event) + .await, + None => api.stream_chat(&model, history, cancel, on_event).await, + }; if let Err(error) = result { - notifier.send(UiEvent::StreamError(error.to_string())); + notifier.send(UiEvent::Error(error.to_string())); } }); } @@ -287,6 +558,8 @@ impl JarviseApp { self.user = None; self.api.set_token(None); self.messages.clear(); + self.projects.clear(); + self.current_project = None; self.input.clear(); self.error = None; self.login_password.clear(); @@ -326,7 +599,7 @@ impl JarviseApp { } /// Applies every event produced since the last frame. - fn drain_events(&mut self) { + fn drain_events(&mut self, ctx: &egui::Context) { while let Ok(event) = self.rx.try_recv() { match event { UiEvent::AuthOk { token, user } => { @@ -336,17 +609,116 @@ impl JarviseApp { self.login_busy = false; self.login_error = None; self.login_password.clear(); + self.load_projects(ctx); } UiEvent::AuthError(message) => { self.login_busy = false; self.login_error = Some(message); } - UiEvent::TokenValid(user) => self.user = Some(user), + UiEvent::TokenValid(user) => { + self.user = Some(user); + self.load_projects(ctx); + } UiEvent::TokenInvalid => { self.token = None; self.user = None; self.api.set_token(None); } + UiEvent::ProjectsLoaded(projects) => { + // A project remembered from the previous run may be gone. + if let Some(project_id) = self.current_project { + if !projects.iter().any(|project| project.id == project_id) { + self.current_project = None; + self.messages.clear(); + } + } + self.projects = projects; + + // Reopens the context that was on screen at the last run. + if let Some(project_id) = self.current_project { + if self.messages.is_empty() { + self.load_messages(project_id, ctx); + } + } + } + UiEvent::ProjectCreated(project) => { + let known = self.projects.iter().any(|item| item.id == project.id); + match self + .projects + .iter_mut() + .find(|item| item.id == project.id) + { + Some(slot) => *slot = project.clone(), + None => self.projects.push(project.clone()), + } + self.projects + .sort_by(|left, right| left.name.to_lowercase().cmp(&right.name.to_lowercase())); + self.editing = None; + + // A brand new project is worth opening straight away. + if !known { + self.select_project(Some(project.id), ctx); + } + } + UiEvent::ProjectDeleted(project_id) => { + self.projects.retain(|project| project.id != project_id); + if self.current_project == Some(project_id) { + self.current_project = None; + self.messages.clear(); + } + } + UiEvent::ProjectMessages { + project_id, + messages, + truncated, + } => { + // The user may have switched project while it was loading. + if self.current_project == Some(project_id) { + self.messages = messages; + self.history_truncated = truncated; + } + } + UiEvent::ProjectContextCleared(project_id) => { + if self.current_project == Some(project_id) { + self.messages.clear(); + self.history_truncated = false; + } + for project in &mut self.projects { + if project.id == project_id { + project.message_count = 0; + } + } + } + UiEvent::ContextNoteAdded { + project_id, + message, + } => { + if self.current_project == Some(project_id) { + self.messages.push(message); + } + for project in &mut self.projects { + if project.id == project_id { + project.message_count += 1; + } + } + } + UiEvent::RecallDone { + project_id, + caption_index, + context_messages, + } => { + self.streaming = false; + self.cancel = None; + if self.current_project == Some(project_id) { + if let Some(caption) = self.messages.get_mut(caption_index) { + caption.content = format!( + "🧠 Contexte vérifié : {} message(s) renvoyé(s) à Jarvis", + context_messages + ); + } + } + self.happy_timer = 1.5; + } UiEvent::Delta(text) => { if let Some(last) = self.messages.last_mut() { if last.role == "assistant" { @@ -370,10 +742,18 @@ impl JarviseApp { None }; if let Some(text) = speech { + self.speaking = true; self.voice.speak(text); } + self.happy_timer = 2.5; + + // In a project the exchange was persisted server-side, so + // the sidebar counters are refreshed from the backend. + if self.current_project.is_some() { + self.load_projects(ctx); + } } - UiEvent::StreamError(message) => { + UiEvent::Error(message) => { self.error = Some(message); self.streaming = false; self.cancel = None; @@ -388,12 +768,31 @@ impl JarviseApp { } UiEvent::VoiceError(message) => { self.voice_status = None; + self.speaking = false; self.error = Some(message); } + UiEvent::Spoken => self.speaking = false, } } } + /// Mood of the companion, derived from what the app is doing. + fn mood(&self) -> Mood { + if self.recorder.is_some() { + Mood::Listening + } else if self.streaming { + Mood::Thinking + } else if self.speaking { + Mood::Speaking + } else if self.happy_timer > 0.0 { + Mood::Happy + } else if self.error.is_some() { + Mood::Error + } else { + Mood::Idle + } + } + fn login_screen(&mut self, ui: &mut egui::Ui) { egui::CentralPanel::default().show(ui, |ui| { ui.add_space(70.0); @@ -465,136 +864,365 @@ impl JarviseApp { } fn chat_screen(&mut self, ui: &mut egui::Ui) { + self.project_panel(ui); + egui::Panel::top("top-bar").show(ui, |ui| { - ui.add_space(2.0); - ui.horizontal(|ui| { - ui.heading("Jarvise"); - ui.separator(); + egui::Frame::new() + .inner_margin(egui::Margin::symmetric(14, 10)) + .show(ui, |ui| { + // Shown in the bar so the current context is obvious. + let project_label = self + .current_project + .and_then(|id| self.projects.iter().find(|item| item.id == id)) + .map(|project| project.name.clone()); + let time = ui.input(|i| i.time); + let mood = self.mood(); + ui.horizontal(|ui| { + let pet = tamagotchi::draw(ui, mood, time); + pet.on_hover_text(mood.tooltip()); - ui.label("Modèle :"); - ui.add( - egui::TextEdit::singleline(&mut self.model) - .desired_width(150.0) - .hint_text("llama3.2"), - ); + ui.add_space(6.0); + ui.vertical(|ui| { + ui.strong("Jarvise"); + ui.add( + egui::Label::new( + egui::RichText::new(mood.label()) + .size(12.0) + .color(egui::Color32::from_gray(150)), + ) + .wrap(), + ); + }); - ui.separator(); - if let Some(user) = &self.user { - ui.label(user.display_name()); - } + ui.add_space(8.0); + ui.separator(); - ui.separator(); - let speak = ui.add_enabled( - self.voice.tts_ready(), - egui::Checkbox::new(&mut self.speak_replies, "🔊 Voix"), - ); - if !self.voice.tts_ready() { - speak.on_disabled_hover_text( - "TTS non configuré : définis PIPER_MODEL et PIPER_CONFIG", - ); - } + let context = egui::RichText::new( + project_label.clone().unwrap_or_else(|| "Sans projet".to_string()), + ) + .strong(); + ui.label(context); + ui.separator(); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - if ui.button("Déconnexion").clicked() { - self.logout(); - } - if ui.button("Effacer").clicked() { - self.stop_stream(); - self.messages.clear(); - self.error = None; - } + ui.label("Modèle"); + ui.add( + egui::TextEdit::singleline(&mut self.model) + .desired_width(140.0) + .hint_text("qwen2.5:3b"), + ); + + ui.separator(); + let speak = ui.add_enabled( + self.voice.tts_ready(), + egui::Checkbox::new(&mut self.speak_replies, "🔊 Voix"), + ); + if !self.voice.tts_ready() { + speak.on_disabled_hover_text( + "TTS non configuré : définis PIPER_MODEL et PIPER_CONFIG", + ); + } + + ui.with_layout( + egui::Layout::right_to_left(egui::Align::Center), + |ui| { + if ui.button("Déconnexion").clicked() { + self.logout(); + } + // In a project the history lives on the backend, so the only way to + // really clear it is the sidebar's « Vider ». + if self.current_project.is_none() + && ui.button("Effacer") + .on_hover_text("Effacer la conversation affichée") + .clicked() + { + self.stop_stream(); + self.messages.clear(); + self.error = None; + } + if let Some(user) = &self.user { + ui.add_space(4.0); + ui.label(user.display_name()); + } + }, + ); + }); }); - }); - ui.add_space(2.0); }); egui::Panel::bottom("input-bar").show(ui, |ui| { - ui.add_space(6.0); - - if let Some(error) = &self.error { - ui.colored_label(egui::Color32::from_rgb(0xff, 0x6b, 0x6b), error); - } - if let Some(status) = &self.voice_status { - ui.colored_label(egui::Color32::from_rgb(0x8a, 0xb4, 0xf8), status); - } - - ui.horizontal(|ui| { - let button_width = 96.0; - let mic_width = 46.0; - let input_width = - (ui.available_width() - button_width - mic_width - 16.0).max(120.0); - - // Push-to-talk: hold the mic button to record, release to send. - let mic = ui.add_enabled( - self.voice.stt_ready(), - egui::Button::new(if self.recorder.is_some() { "⏺" } else { "🎤" }) - .min_size(egui::vec2(mic_width, 52.0)), - ); - if mic.is_pointer_button_down_on() && self.recorder.is_none() { - self.start_recording(); - } - if !mic.is_pointer_button_down_on() && self.recorder.is_some() { - self.stop_recording(); - } - if self.voice.stt_ready() { - mic.on_hover_text("Maintenir pour parler (push-to-talk)"); - } else { - mic.on_disabled_hover_text("STT non configuré : définis WHISPER_MODEL"); - } - - let response = ui.add_sized( - [input_width, 52.0], - egui::TextEdit::multiline(&mut self.input) - .hint_text("Votre message… (Entrée pour envoyer, Maj+Entrée pour un saut de ligne)"), - ); - - let submitted = response.has_focus() - && ui.input(|i| i.key_pressed(egui::Key::Enter) && !i.modifiers.shift); - - if self.streaming { - if ui - .add_sized([button_width, 52.0], egui::Button::new("Stopper")) - .clicked() - { - self.stop_stream(); + egui::Frame::new() + .inner_margin(egui::Margin::symmetric(14, 10)) + .show(ui, |ui| { + if let Some(error) = &self.error { + ui.colored_label(egui::Color32::from_rgb(0xff, 0x6b, 0x6b), error); + } + if let Some(status) = &self.voice_status { + ui.colored_label(egui::Color32::from_rgb(0x8a, 0xb4, 0xf8), status); + } + if self.error.is_some() || self.voice_status.is_some() { + ui.add_space(4.0); } - } else if ui - .add_sized([button_width, 52.0], egui::Button::new("Envoyer")) - .clicked() - || submitted - { - self.send_message(ui.ctx()); - } - }); - ui.add_space(6.0); + ui.horizontal(|ui| { + let button_width = 96.0; + let mic_width = 46.0; + let input_width = + (ui.available_width() - button_width - mic_width - 20.0).max(120.0); + + // Push-to-talk: hold the mic button to record, release to send. + let mic = ui.add_enabled( + self.voice.stt_ready(), + egui::Button::new(if self.recorder.is_some() { "⏺" } else { "🎤" }) + .min_size(egui::vec2(mic_width, 52.0)), + ); + if mic.is_pointer_button_down_on() && self.recorder.is_none() { + self.start_recording(); + } + if !mic.is_pointer_button_down_on() && self.recorder.is_some() { + self.stop_recording(); + } + if self.voice.stt_ready() { + mic.on_hover_text("Maintenir pour parler (push-to-talk)"); + } else { + mic.on_disabled_hover_text("STT non configuré : définis WHISPER_MODEL"); + } + + let response = ui.add_sized( + [input_width, 52.0], + egui::TextEdit::multiline(&mut self.input).hint_text( + "Votre message… (Entrée pour envoyer, Maj+Entrée pour un saut de ligne)", + ), + ); + + let submitted = response.has_focus() + && ui.input(|i| i.key_pressed(egui::Key::Enter) && !i.modifiers.shift); + + if self.streaming { + if ui + .add_sized([button_width, 52.0], egui::Button::new("Stopper")) + .clicked() + { + self.stop_stream(); + } + } else if ui + .add_sized([button_width, 52.0], egui::Button::new("Envoyer")) + .clicked() + || submitted + { + self.send_message(ui.ctx()); + } + }); + }); }); egui::CentralPanel::default().show(ui, |ui| { - egui::ScrollArea::vertical() - .auto_shrink([false, false]) - .stick_to_bottom(true) - .show(ui, |ui| { - ui.add_space(8.0); - if self.messages.is_empty() { - ui.vertical_centered(|ui| { - ui.add_space(40.0); - ui.weak("Aucun message. Écris quelque chose à Jarvis pour commencer."); + chat_area(ui, &self.messages); + }); + } + + /// Sidebar listing the user's projects, with the tools that act on the + /// context of the selected one: renaming, clearing it, and pinning a system + /// note Jarvis will read on the next exchange. + fn project_panel(&mut self, ui: &mut egui::Ui) { + egui::Panel::left("projects-panel") + .resizable(false) + .exact_size(252.0) + .show(ui, |ui| { + ui.add_space(8.0); + + ui.horizontal(|ui| { + ui.strong("Projets"); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui + .small_button("✎") + .on_hover_text("Renommer le projet ouvert") + .clicked() + { + if let Some(project_id) = self.current_project { + self.edit_project(project_id); + } + } + if ui + .small_button("+") + .on_hover_text("Nouveau projet") + .clicked() + { + self.editing = None; + self.form_name.clear(); + self.form_description.clear(); + self.form_open = true; + } + }); + }); + ui.separator(); + + // The stateless conversation: no project, no persisted history. + if ui + .selectable_label(self.current_project.is_none(), "Sans projet") + .on_hover_text("Chaque message est envoyé sans historique") + .clicked() + { + self.select_project(None, ui.ctx()); + } + + for index in 0..self.projects.len() { + let project_id = self.projects[index].id; + let label = self.projects[index].subtitle(); + let selected = self.current_project == Some(project_id); + + let (open, trash) = ui + .horizontal(|ui| { + let open = ui + .add_sized( + [ui.available_width() - 36.0, 30.0], + egui::Button::selectable(selected, label), + ) + .clicked(); + let trash = ui + .add_sized([28.0, 30.0], egui::Button::new("🗑")) + .on_hover_text("Supprimer le projet") + .clicked(); + (open, trash) + }) + .inner; + + if open { + self.select_project(Some(project_id), ui.ctx()); + } + if trash { + // First click arms the deletion, second one confirms it. + if self.confirm_delete == Some(project_id) { + self.delete_project(project_id, ui.ctx()); + } else { + self.confirm_delete = Some(project_id); + } + } + } + + if let Some(project_id) = self.confirm_delete { + ui.add_space(6.0); + ui.separator(); + ui.label("Supprimer ce projet et tout son contexte ?"); + ui.horizontal(|ui| { + if ui.button("Oui, supprimer").clicked() { + self.delete_project(project_id, ui.ctx()); + } + if ui.button("Annuler").clicked() { + self.confirm_delete = None; + } + }); + } + + if self.form_open { + ui.add_space(6.0); + ui.separator(); + ui.strong(if self.editing.is_some() { + "Modifier le projet" + } else { + "Nouveau projet" + }); + ui.add( + egui::TextEdit::singleline(&mut self.form_name) + .hint_text("Nom du projet") + .desired_width(f32::INFINITY), + ); + ui.add( + egui::TextEdit::multiline(&mut self.form_description) + .hint_text("Description (facultative)") + .desired_rows(2) + .desired_width(f32::INFINITY), + ); + let can_save = !self.form_name.trim().is_empty(); + ui.horizontal(|ui| { + if ui + .add_enabled(can_save, egui::Button::new("Enregistrer")) + .clicked() + { + self.save_project(ui.ctx()); + } + if ui.button("Annuler").clicked() { + self.form_open = false; + self.editing = None; + } + }); + } + + if let Some(project_id) = self.current_project { + ui.add_space(6.0); + ui.separator(); + ui.label("Contexte"); + let note = ui.add( + egui::TextEdit::singleline(&mut self.context_note) + .hint_text("Note système (facultative)") + .desired_width(f32::INFINITY), + ); + let can_add = !self.context_note.trim().is_empty(); + let submitted = + note.has_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)); + + ui.horizontal(|ui| { + if ui + .button("⟳ Recharger") + .on_hover_text("Relire le contexte depuis le backend") + .clicked() + { + self.reload_context(ui.ctx()); + } + if ui + .add_enabled(!self.streaming, egui::Button::new("🧠 Vérifier")) + .on_hover_text( + "Demander à Jarvis de réciter le contexte (rien n'est enregistré)", + ) + .clicked() + { + self.start_recall(ui.ctx()); + } + }); + + ui.horizontal(|ui| { + if ui + .add_enabled(can_add, egui::Button::new("+ Ajouter")) + .on_hover_text("Ajouter une note au contexte, sans appeler le modèle") + .clicked() + { + self.add_context_note(project_id, ui.ctx()); + } + if ui.button("Vider").on_hover_text("Effacer l'historique").clicked() { + self.confirm_clear = true; + } + }); + + if submitted && can_add { + self.add_context_note(project_id, ui.ctx()); + } + + if self.confirm_clear { + ui.label("Tous les messages du projet seront supprimés."); + ui.horizontal(|ui| { + if ui.button("Oui, vider").clicked() { + self.clear_project_context(project_id, ui.ctx()); + } + if ui.button("Annuler").clicked() { + self.confirm_clear = false; + } }); } - for message in &self.messages { - render_bubble(ui, message); - ui.add_space(6.0); + + if let Some(project) = self.projects.iter().find(|item| item.id == project_id) + { + ui.small(format!("{} · {}", project.subtitle(), project.updated_label())); + if self.history_truncated { + ui.small("Historique tronqué : seuls les derniers messages sont chargés."); + } } - ui.add_space(8.0); - }); - }); + } + }); } } impl eframe::App for JarviseApp { fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) { - self.drain_events(); + self.drain_events(ui.ctx()); // A finished transcription is placed in the input then sent as-is. if let Some(text) = self.pending_transcript.take() { @@ -602,6 +1230,11 @@ impl eframe::App for JarviseApp { self.send_message(ui.ctx()); } + // Count down the companion's short celebration. + if self.happy_timer > 0.0 { + self.happy_timer = (self.happy_timer - ui.input(|i| i.stable_dt)).max(0.0); + } + if self.token.is_none() { self.login_screen(ui); } else if self.user.is_none() { @@ -615,6 +1248,9 @@ impl eframe::App for JarviseApp { }); }); } else { + // Keep the companion animation alive (~30 fps). + ui.ctx() + .request_repaint_after(std::time::Duration::from_millis(33)); self.chat_screen(ui); } } @@ -625,41 +1261,133 @@ impl eframe::App for JarviseApp { email: self.login_email.clone(), model: self.model.clone(), backend_url: self.backend_url.clone(), + project_id: self.current_project, }; eframe::set_value(storage, STORAGE_KEY, &persisted); } } -/// Draws a single message as an aligned chat bubble. -fn render_bubble(ui: &mut egui::Ui, message: &ChatMessage) { - let layout = if message.is_user() { - egui::Layout::right_to_left(egui::Align::TOP) +/// Widest the centred conversation column may become, and the margin kept on +/// its sides when the window is narrower than that. +pub const COLUMN_MAX_WIDTH: f32 = 880.0; +pub const COLUMN_MIN_MARGIN: f32 = 16.0; + +/// Draws the conversation in a centred, width-bounded column. +/// +/// Public so the layout can be exercised headlessly by the tests. +pub fn chat_area(ui: &mut egui::Ui, messages: &[ChatMessage]) { + let available = ui.available_width(); + let width = (available - 2.0 * COLUMN_MIN_MARGIN).min(COLUMN_MAX_WIDTH); + let side = ((available - width) / 2.0).max(0.0); + + // The column is an explicit rect rather than a `ui.horizontal`: a scroll + // area inherits the layout of the `Ui` it is added to, and in a horizontal + // one its bubbles were laid out side by side — which is exactly what pushed + // them past the right edge of the window. + let rect = egui::Rect::from_min_size( + ui.next_widget_position() + egui::vec2(side, 0.0), + egui::vec2(width, ui.available_height()), + ); + + ui.scope_builder( + egui::UiBuilder::new() + .max_rect(rect) + .layout(egui::Layout::top_down(egui::Align::Min)), + |ui| { + egui::ScrollArea::vertical() + .auto_shrink([false, false]) + .stick_to_bottom(true) + // Without an explicit maximum the scroll area grows to whatever + // its contents demand, which is what pushed bubbles past the window. + .max_width(width) + .show(ui, |ui| { + // Bubbles measure themselves against this value, so the + // constraint really reaches the text layout. + ui.set_max_width(width); + ui.add_space(14.0); + + if messages.is_empty() { + ui.add_space(60.0); + ui.vertical_centered(|ui| { + ui.label( + egui::RichText::new( + "Aucun message. Écris quelque chose à Jarvis pour commencer.", + ) + .color(egui::Color32::from_gray(150)), + ); + }); + } + + for message in messages { + render_bubble(ui, message); + ui.add_space(10.0); + } + + ui.add_space(14.0); + }); + }, + ); +} + +/// Draws a single message as a chat bubble and returns the rectangle it covers. +/// +/// The text is laid out *before* the bubble is allocated: `egui` only wraps a +/// label when the surrounding `Ui` already knows how wide it may grow, which is +/// not guaranteed inside a scroll area — long answers used to be cut off at the +/// window edge instead of wrapping. Computing the galley ourselves removes the +/// guesswork, and returns the space actually taken by the bubble. +pub fn render_bubble(ui: &mut egui::Ui, message: &ChatMessage) -> egui::Rect { + const PADDING: f32 = 12.0; + /// Bubbles stay narrower than the column so the exchange reads as a dialogue. + const BUBBLE_RATIO: f32 = 0.82; + + let max_bubble = (ui.available_width() * BUBBLE_RATIO).max(180.0); + let text_width = (max_bubble - 2.0 * PADDING).max(80.0); + + let (fill, text_color) = if message.is_user() { + ( + egui::Color32::from_rgb(0x2f, 0x6f, 0xb5), + egui::Color32::WHITE, + ) } else { - egui::Layout::left_to_right(egui::Align::TOP) + (egui::Color32::from_gray(58), egui::Color32::from_gray(238)) }; - ui.with_layout(layout, |ui| { - let (fill, text_color) = if message.is_user() { - ( - egui::Color32::from_rgb(0x2f, 0x6f, 0xb5), - egui::Color32::WHITE, - ) - } else { - (egui::Color32::from_gray(60), egui::Color32::from_gray(235)) - }; - - egui::Frame::new() - .fill(fill) - .inner_margin(10.0) - .corner_radius(10.0) - .show(ui, |ui| { - ui.set_max_width(ui.available_width().min(560.0)); - let text = if message.content.is_empty() { - "…" - } else { - message.content.as_str() - }; - ui.label(egui::RichText::new(text).color(text_color).size(15.0)); - }); + let text = if message.content.is_empty() { + "…" + } else { + message.content.as_str() + }; + let galley = ui.ctx().fonts_mut(|fonts| { + fonts.layout( + text.to_string(), + egui::FontId::proportional(15.0), + text_color, + text_width, + ) }); + let size = galley.size() + egui::vec2(2.0 * PADDING, 2.0 * PADDING); + + // The user hugs the right edge of the column, Jarvis hugs the left one. + let inset = if message.is_user() { + (ui.available_width() - size.x).max(0.0) + } else { + 0.0 + }; + + ui.horizontal(|ui| { + if inset > 0.0 { + ui.add_space(inset); + } + let (_id, rect) = ui.allocate_space(size); + let painter = ui.painter(); + painter.rect_filled(rect, egui::CornerRadius::same(12), fill); + painter.galley( + rect.min + egui::vec2(PADDING, PADDING), + galley, + text_color, + ); + rect + }) + .inner } diff --git a/frontend/src/lib.rs b/frontend/src/lib.rs index a5cca5b..8660197 100644 --- a/frontend/src/lib.rs +++ b/frontend/src/lib.rs @@ -8,4 +8,5 @@ pub mod api; pub mod app; pub mod config; pub mod model; +pub mod tamagotchi; pub mod voice; diff --git a/frontend/src/model.rs b/frontend/src/model.rs index fa06230..c900974 100644 --- a/frontend/src/model.rs +++ b/frontend/src/model.rs @@ -6,7 +6,7 @@ use serde::{Deserialize, Serialize}; /// A single conversation message, as expected in the `messages` array. -#[derive(Serialize, Deserialize, Clone, PartialEq, Eq)] +#[derive(Serialize, Deserialize, Clone, PartialEq, Eq, Debug)] pub struct ChatMessage { pub role: String, pub content: String, @@ -27,6 +27,13 @@ impl ChatMessage { } } + pub fn system(content: impl Into) -> Self { + Self { + role: "system".to_string(), + content: content.into(), + } + } + pub fn is_user(&self) -> bool { self.role == "user" } @@ -84,3 +91,153 @@ impl PublicUser { self.name.clone().unwrap_or_else(|| self.email.clone()) } } + +/* -------------------------------------------------------------- projects */ + +/// A conversation project: its messages are the context sent to Jarvis. +/// +/// The backend serialises the rows in camelCase (`messageCount`, `updatedAt`); +/// fields the UI does not need are simply ignored by `serde`. +#[derive(Serialize, Deserialize, Clone, PartialEq, Eq, Debug)] +#[serde(rename_all = "camelCase")] +pub struct Project { + pub id: i64, + pub name: String, + #[serde(default)] + pub description: Option, + #[serde(default)] + pub message_count: i64, + #[serde(default)] + pub updated_at: Option, +} + +impl Project { + /// `Projet · 12 messages`, shown in the project list. + pub fn subtitle(&self) -> String { + let count = if self.message_count > 1 { + "messages" + } else { + "message" + }; + format!("{} · {} {}", self.name, self.message_count, count) + } + + /// `modifié le 10-05 12:34`, extracted from the backend's + /// `YYYY-MM-DD HH:MM:SS` timestamps. + pub fn updated_label(&self) -> String { + match self.updated_at.as_deref().and_then(|stamp| stamp.get(5..16)) { + Some(short) => format!("modifié le {short}"), + None => "jamais modifié".to_string(), + } + } +} + +/// Body of `POST /api/projects`. +#[derive(Serialize)] +pub(crate) struct CreateProjectRequest<'a> { + pub name: &'a str, + #[serde(skip_serializing_if = "Option::is_none")] + pub description: Option<&'a str>, +} + +/// Body of `PATCH /api/projects/:id`; only the provided fields are sent. +#[derive(Serialize)] +pub(crate) struct UpdateProjectRequest<'a> { + #[serde(skip_serializing_if = "Option::is_none")] + pub name: Option<&'a str>, + #[serde(skip_serializing_if = "Option::is_none")] + pub description: Option<&'a str>, +} + +/* -------------------------------------------------------------- messages */ + +/// A stored message of a project context, as returned by the backend. +#[derive(Deserialize, Clone, PartialEq, Eq, Debug)] +#[serde(rename_all = "camelCase")] +pub struct StoredMessage { + pub id: i64, + pub role: String, + pub content: String, + #[serde(default)] + pub created_at: Option, +} + +impl StoredMessage { + /// Same message in the shape used by the chat buffer and the SSE payloads. + pub fn to_chat(&self) -> ChatMessage { + ChatMessage { + role: self.role.clone(), + content: self.content.clone(), + } + } + + /// `HH:MM` extracted from the backend's `YYYY-MM-DD HH:MM:SS` timestamps. + pub fn time_label(&self) -> Option<&str> { + let stamp = self.created_at.as_deref()?; + let time = stamp.get(11..)?; + Some(&time[..5]) + } +} + +/// Body of `POST /api/projects/:id/messages`: appends a message to the context. +#[derive(Serialize)] +pub(crate) struct AddMessageRequest<'a> { + pub role: &'a str, + pub content: &'a str, +} + +/// Body of `POST /api/projects/:id/chat` and `.../chat/stream`: the backend +/// reads the context from the database, so only the new prompt is sent. +#[derive(Serialize)] +pub(crate) struct ProjectChatRequest<'a> { + pub message: &'a str, + #[serde(skip_serializing_if = "Option::is_none")] + pub model: Option<&'a str>, +} + +/// Body of `POST /api/projects/:id/context/recall`: the question is optional, +/// the backend asks its own by default. +#[derive(Serialize)] +pub(crate) struct ProjectRecallRequest<'a> { + #[serde(skip_serializing_if = "Option::is_none")] + pub model: Option<&'a str>, +} + +/// `done` payload of the recall stream: how many stored messages were actually +/// replayed to the model (the backend caps the context it sends). +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +pub(crate) struct RecallDoneData { + pub context_messages: Option, +} + +/* -------------------------------------------------------- API envelopes */ + +#[derive(Deserialize)] +pub(crate) struct ProjectsResponse { + pub projects: Vec, +} + +#[derive(Deserialize)] +pub(crate) struct ProjectResponse { + pub project: Project, +} + +#[derive(Deserialize)] +pub(crate) struct MessageResponse { + pub message: StoredMessage, +} + +#[derive(Deserialize)] +pub(crate) struct DeletedMessagesResponse { + pub deleted: i64, +} + +/// One page of a project's context, oldest message first. +#[derive(Deserialize, Debug)] +pub struct MessagePage { + pub messages: Vec, + /// Older messages exist and were left out of this page. + #[serde(default)] + pub has_more: bool, +} diff --git a/frontend/src/tamagotchi.rs b/frontend/src/tamagotchi.rs new file mode 100644 index 0000000..83a042f --- /dev/null +++ b/frontend/src/tamagotchi.rs @@ -0,0 +1,233 @@ +//! A small animated companion (a "tamagotchi") drawn with egui shapes. +//! +//! It reacts to what the app is doing: idle, listening, thinking, speaking, +//! happy or worried — giving the interface a living, friendly touch without any +//! image asset. + +use std::f32::consts::PI; + +use eframe::egui::{self, Color32, Pos2, Sense, Stroke, Vec2}; + +/// What the companion is expressing right now. +#[derive(Clone, Copy, PartialEq, Eq)] +pub enum Mood { + /// Nothing special: gentle bob and occasional blink. + Idle, + /// The microphone is recording (push-to-talk held). + Listening, + /// Jarvis is generating an answer. + Thinking, + /// The answer is being read out loud (TTS). + Speaking, + /// Short celebration after a successful answer. + Happy, + /// The last operation failed. + Error, +} + +impl Mood { + /// Short French label shown under the title. + pub fn label(self) -> &'static str { + match self { + Mood::Idle => "au repos", + Mood::Listening => "je t'écoute…", + Mood::Thinking => "je réfléchis…", + Mood::Speaking => "je parle…", + Mood::Happy => "content !", + Mood::Error => "oups…", + } + } + + /// Tooltip text for the widget. + pub fn tooltip(self) -> String { + format!("Jarvibot — {}", self.label()) + } + + fn body_and_accent(self) -> (Color32, Color32) { + match self { + Mood::Idle => ( + Color32::from_rgb(0x4c, 0x8b, 0xf5), + Color32::from_rgb(0x1f, 0x4c, 0x9c), + ), + Mood::Listening => ( + Color32::from_rgb(0x2e, 0xc4, 0x8a), + Color32::from_rgb(0x18, 0x7a, 0x55), + ), + Mood::Thinking => ( + Color32::from_rgb(0xf5, 0xb0, 0x2e), + Color32::from_rgb(0xa8, 0x6f, 0x0f), + ), + Mood::Speaking => ( + Color32::from_rgb(0xa0, 0x6b, 0xf5), + Color32::from_rgb(0x63, 0x39, 0xa8), + ), + Mood::Happy => ( + Color32::from_rgb(0xf5, 0x6b, 0xa0), + Color32::from_rgb(0xa8, 0x33, 0x66), + ), + Mood::Error => ( + Color32::from_rgb(0xe5, 0x4b, 0x4b), + Color32::from_rgb(0x99, 0x28, 0x28), + ), + } + } +} + +/// Draws the companion in the current `ui`, animated with `time` (seconds). +/// +/// Returns the widget [`egui::Response`] so callers can attach a tooltip. +pub fn draw(ui: &mut egui::Ui, mood: Mood, time: f64) -> egui::Response { + let (rect, response) = ui.allocate_exact_size(Vec2::splat(40.0), Sense::hover()); + let painter = ui.painter(); + + let (body, accent) = mood.body_and_accent(); + let time = time as f32; + + // Gentle vertical bob; a bit livelier when the app is busy. + let bob = (time * 2.2).sin() * if mood == Mood::Idle { 1.0 } else { 1.8 }; + let center = Pos2::new(rect.center().x, rect.center().y + 3.0 + bob); + let radius = rect.height() * 0.33; + + // Ground shadow. + painter.circle_filled( + Pos2::new(center.x, rect.bottom() - 2.5), + radius * 0.7, + Color32::from_black_alpha(70), + ); + + // Antenna with a glowing tip. + let tip = Pos2::new(center.x, center.y - radius - 6.0); + painter.line_segment( + [Pos2::new(center.x, center.y - radius + 2.0), tip], + Stroke::new(1.6, accent), + ); + let glow = 1.5 + (time * 3.0).sin() * 0.6; + painter.circle_filled(tip, glow.max(1.0), body); + + // Listening: expanding pulse rings. + if mood == Mood::Listening { + for i in 0..2 { + let phase = ((time * 2.0 + i as f32 * 0.5) % 1.0 + 1.0) % 1.0; + painter.circle_stroke( + center, + radius + 2.0 + phase * 5.0, + Stroke::new(1.4, body.gamma_multiply(0.8 * (1.0 - phase))), + ); + } + } + + // Thinking: little dots orbiting above the head. + if mood == Mood::Thinking { + for i in 0..3 { + let angle = time * 3.0 + i as f32 * (2.0 * PI / 3.0); + let dot = Pos2::new( + center.x + angle.sin() * (radius + 6.0), + center.y - radius - 7.0 - angle.cos() * 3.0, + ); + painter.circle_filled(dot, 2.0, accent); + } + } + + // Body and outline. + painter.circle_filled(center, radius, body); + painter.circle_stroke(center, radius, Stroke::new(1.5, accent)); + + // Cheeks. + let cheek = Color32::from_white_alpha(46); + painter.circle_filled( + Pos2::new(center.x - radius * 0.56, center.y + radius * 0.12), + radius * 0.17, + cheek, + ); + painter.circle_filled( + Pos2::new(center.x + radius * 0.56, center.y + radius * 0.12), + radius * 0.17, + cheek, + ); + + // Eyes. + let eye_y = center.y - radius * 0.22; + let eye_dx = radius * 0.38; + let blinking = mood == Mood::Idle && (time % 3.2) < 0.12; + + if mood == Mood::Error { + // Crossed-out eyes. + for side in [-1.0_f32, 1.0] { + let c = Pos2::new(center.x + side * eye_dx, eye_y); + let d = radius * 0.16; + painter.line_segment( + [Pos2::new(c.x - d, c.y - d), Pos2::new(c.x + d, c.y + d)], + Stroke::new(2.0, Color32::WHITE), + ); + painter.line_segment( + [Pos2::new(c.x - d, c.y + d), Pos2::new(c.x + d, c.y - d)], + Stroke::new(2.0, Color32::WHITE), + ); + } + } else if blinking { + for side in [-1.0_f32, 1.0] { + let c = Pos2::new(center.x + side * eye_dx, eye_y); + painter.line_segment( + [ + Pos2::new(c.x - radius * 0.14, c.y), + Pos2::new(c.x + radius * 0.14, c.y), + ], + Stroke::new(2.0, Color32::WHITE), + ); + } + } else { + for side in [-1.0_f32, 1.0] { + painter.circle_filled( + Pos2::new(center.x + side * eye_dx, eye_y), + radius * 0.15, + Color32::WHITE, + ); + painter.circle_filled( + Pos2::new(center.x + side * eye_dx + radius * 0.05, eye_y), + radius * 0.07, + Color32::from_rgb(0x1c, 0x1c, 0x24), + ); + } + } + + // Mouth. + let mouth_y = center.y + radius * 0.34; + match mood { + Mood::Speaking => { + let open = (time * 12.0).sin().abs(); + painter.circle_filled( + Pos2::new(center.x, mouth_y), + radius * (0.10 + 0.12 * open), + Color32::from_rgb(0x2a, 0x18, 0x18), + ); + } + Mood::Happy | Mood::Listening => smile(painter, center.x, mouth_y, radius, false), + Mood::Error => smile(painter, center.x, mouth_y, radius, true), + Mood::Idle | Mood::Thinking => { + painter.line_segment( + [ + Pos2::new(center.x - radius * 0.16, mouth_y), + Pos2::new(center.x + radius * 0.16, mouth_y), + ], + Stroke::new(1.8, Color32::WHITE), + ); + } + } + + response +} + +/// Draws a curved mouth (a smile, or a frown when `inverted`). +fn smile(painter: &egui::Painter, cx: f32, y: f32, radius: f32, inverted: bool) { + let half = radius * 0.45; + let depth = radius * 0.5 * if inverted { -1.0 } else { 1.0 }; + let steps = 7; + let mut previous = Pos2::new(cx - half, y); + + for i in 1..=steps { + let f = i as f32 / steps as f32; + let point = Pos2::new(cx - half + 2.0 * half * f, y + (f * PI).sin() * depth); + painter.line_segment([previous, point], Stroke::new(1.8, Color32::WHITE)); + previous = point; + } +} diff --git a/frontend/src/voice/engine.rs b/frontend/src/voice/engine.rs index e6336a5..2ce15ac 100644 --- a/frontend/src/voice/engine.rs +++ b/frontend/src/voice/engine.rs @@ -63,6 +63,8 @@ fn is_file(path: &Path) -> bool { #[derive(Debug, Clone)] pub enum VoiceEvent { Transcribed(String), + /// Playback of a synthesized answer finished. + Spoken, TranscriptionError(String), SpeechError(String), } @@ -173,8 +175,11 @@ where } match tts.as_mut().expect("tts initialised above").synthesize(&text) { Ok((samples, sample_rate)) => { - if let Err(error) = audio::play_blocking(&samples, sample_rate) { - on_event(VoiceEvent::SpeechError(error.to_string())); + match audio::play_blocking(&samples, sample_rate) { + Ok(()) => on_event(VoiceEvent::Spoken), + Err(error) => { + on_event(VoiceEvent::SpeechError(error.to_string())) + } } } Err(error) => on_event(VoiceEvent::SpeechError(error.to_string())), diff --git a/frontend/tests/chat_layout.rs b/frontend/tests/chat_layout.rs new file mode 100644 index 0000000..f4a720a --- /dev/null +++ b/frontend/tests/chat_layout.rs @@ -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 { + 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 { + 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" + ); +} \ No newline at end of file diff --git a/frontend/tests/projects_api.rs b/frontend/tests/projects_api.rs new file mode 100644 index 0000000..d4cbdd9 --- /dev/null +++ b/frontend/tests/projects_api.rs @@ -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) -> Self { + Self { + status_line: "HTTP/1.1 200 OK", + content_type: "application/json", + body: body.into(), + } + } + + fn created(body: impl Into) -> 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) -> 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) -> Self { + Self { + status_line, + content_type: "application/json", + body: body.into(), + } + } +} + +struct FakeServer { + base_url: String, + requests: Arc>>, + stop: Arc, +} + +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 { + 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(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 { + 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")); +} \ No newline at end of file