diff --git a/README.md b/README.md index 8b7b3aa..d503340 100644 --- a/README.md +++ b/README.md @@ -19,8 +19,14 @@ service externe. - **Projets** : une conversation = une mémoire persistante, rejouée vers le modèle à chaque tour, avec plafond de taille et bouton de vérification. - **Voix locale** : un appui sur le bouton micro lance l'enregistrement, un second - appui (`Ctrl+Espace` au clavier) l'arrête et lance la transcription, réponse lue à - voix haute. + appui (`Ctrl+Espace` au clavier) l'arrête et lance la transcription. La réponse est lue + à voix haute **phrase par phrase, pendant qu'elle s'écrit**, et sans jamais prononcer la + syntaxe Markdown. +- **Réponses rendues** : le Markdown renvoyé par le modèle est mis en forme dans l'app + (titres, listes, tableaux, code, gras/italique) au lieu d'être affiché brut. +- **Démarrage à chaud** : le modèle Ollama est réveillé dès la première frappe ou le début + d'un enregistrement (`POST /api/chat/warm`) et maintenu en mémoire entre deux questions, + pour ne pas payer le chargement au moment de la réponse. - **Deux modes** : un onglet **💬 Chat** (écrire) et un onglet **🗣️ Compagnon** (parler à l'avatar centré) ; la transcription part vers le backend en **texte JSON**, jamais en audio. diff --git a/docs/api.md b/docs/api.md index 0a06535..d503646 100644 --- a/docs/api.md +++ b/docs/api.md @@ -94,7 +94,9 @@ aussi de sonde de disponibilité. ## 3. Chat sans état -L'historique est fourni par le client et n'est **jamais** enregistré. +L'historique est fourni par le client et n'est **jamais** enregistré. Le client envoie tout +l'échange en cours, en écartant les bulles vides (une réponse interrompue avant son premier +fragment en laisse une) et en ne gardant que les 50 derniers messages, la limite du schéma. ### `POST /api/chat` — protégée · contrat minimal @@ -120,6 +122,27 @@ data: [DONE] `history` : 0 à 50 éléments, rôles `user` / `assistant`. Réponse **SSE** nommée, avec `event: done` contenant `{ reply, model }`. +### `POST /api/chat/warm` — protégée · chargement anticipé + +```json +{ "model": "qwen2.5:3b" } +``` + +Demande à Ollama de **charger le modèle en mémoire** sans rien générer (`/api/generate`, +réponse `done_reason: "load"`). Le client l'appelle dès que l'utilisateur commence à +écrire ou à enregistrer : un modèle froid met plusieurs secondes à charger, alors qu'un +modèle résident répond immédiatement. + +`model` est optionnel (défaut : `OLLAMA_MODEL`). **200** → +`{ "model": "qwen2.5:3b", "warmed": true }`. + +Le réveil est **au mieux** : si Ollama est injoignable ou refuse le chargement, la route +répond quand même **200** avec `"warmed": false` — la requête de chat qui suit remontera la +vraie erreur. + +Chaque requête de chat envoie par ailleurs `keep_alive` (`OLLAMA_KEEP_ALIVE`, défaut `30m`) +pour que les poids restent en mémoire entre deux questions. + ### `GET /api/chat/models` — protégée ```json @@ -309,6 +332,7 @@ s'arrête côté serveur. | Messages rejoués au modèle | 40 | `CONTEXT_LIMIT` (`routes/projects.js`) | | Taille d'un message | 32 000 caractères | schéma | | `messages` / `history` par requête | 50 | schéma | +| Maintien du modèle en mémoire | `30m` | `OLLAMA_KEEP_ALIVE` | | Page de contexte | 200 | borne du schéma | | Requêtes | 300 / min (20 / min sur `/api/auth/*`) | `RATE_LIMIT_MAX`, `RATE_LIMIT_WINDOW` | | Durée du jeton | 7 jours | `JWT_EXPIRES_IN` | diff --git a/docs/architecture.md b/docs/architecture.md index e166576..c317ee7 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -54,6 +54,7 @@ change **qui** porte l'historique. | Chat + historique client | `POST /api/chat/stream` | le client (body `history`) | aucune | | Chat de projet | `POST /api/projects/:id/chat[/stream]` | **la base** | persistante | | Vérification du contexte | `POST /api/projects/:id/context/recall` | — | lecture seule | +| Chargement anticipé | `POST /api/chat/warm` | — | sans mémoire | ### 2.1 Chat de projet (le mode principal) @@ -172,7 +173,7 @@ client ne reste pas sans octet pendant que le modèle démarre. | En-têtes | `helmet` + CORS configurable (`CORS_ORIGIN`) | | Validation | schémas JSON-strict (`additionalProperties: false`) sur chaque body/querystring | | Injection SQL | exclusivement des requêtes préparées | -| Ollama | `OLLAMA_URL` (ou `OLLAMA_HOST`), timeout et `502` explicite | +| Ollama | `OLLAMA_URL` (ou `OLLAMA_HOST`), timeout et `502` explicite ; `keep_alive` (`OLLAMA_KEEP_ALIVE`) pour garder les poids en mémoire | > Le serveur écoute sur `0.0.0.0:3000` par défaut : sur un réseau local de confiance, > c'est pratique ; sinon, passer `HOST=127.0.0.1` et `CORS_ORIGIN` restreint. @@ -200,7 +201,14 @@ Conséquencesdirectes : - « Stopper » annule un `CancellationToken` ; le `select!` du client HTTP coupe la connexion, ce qui fait abandonner la génération à Ollama. - La voix vit sur son propre thread, avec **chargement paresseux** des modèles : l'app - démarre instantanément même sans Whisper/Piper installés. + démarre instantanément même sans Whisper/Piper installés. Ce thread est une **file** : + les phrases d'une même réponse y sont déposées au fur et à mesure et sortent dans + l'ordre. +- Le modèle Ollama est **réveillé avant d'en avoir besoin** : dès la première frappe d'un + brouillon ou le début d'un enregistrement, `POST /api/chat/warm` charge les poids + pendant que la phrase s'écrit. Chaque requête de chat porte aussi `keep_alive` (30 min) + pour qu'Ollama ne les décharge pas entre deux questions : c'est le même principe que le + chargement paresseux des modèles de voix, appliqué au modèle de langage. ### 4.2 Modules @@ -210,10 +218,12 @@ frontend/src/ lib.rs surface de librairie (rend l'app testable sans fenêtre) config.rs configuration par variables d'environnement model.rs contrats serde partagés avec le backend - api.rs client HTTP : auth, projets, messages, les deux SSE + api.rs client HTTP : auth, projets, messages, les deux SSE, le réveil app.rs état de l'app, écrans, mise en page + markdown.rs rendu Markdown des réponses (galley stylée) tamagotchi.rs compagnon dessiné, dont l'humeur suit l'état - voice/ audio (cpal), stt (whisper-rs), tts (piper-rs), engine (thread) + voice/ audio (cpal), stt (whisper-rs), tts (piper-rs), engine (thread), + speech (découpage en phrases d'une réponse en cours) ``` `api.rs` ne connaît pas l'UI et l'UI ne connaît pas `reqwest` : les tests d'intégration @@ -236,6 +246,19 @@ message tapé (`POST /api/chat` sans projet, `POST /api/projects/:id/chat/stream projet). Le backend ne reçoit jamais d'audio — seul le texte de la question traverse le réseau. +### 4.5 Deux flux qui partent du même fragment + +Un fragment `event: delta` nourrit deux consommateurs en parallèle : + +- la **bulle**, qui met le Markdown en forme (un `LayoutJob` stylé, cf. `markdown.rs`) ; +- la **voix**, qui accumule le texte et parle chaque phrase dès sa ponctuation finale + (`voice/speech.rs`). Attendre `done` revenait à faire patienter l'utilisateur pendant + toute la réponse ; découper en phrases rend la première seconde utile. + +Ce qui est *dit* n'est pas ce qui est *affiché* : `to_plain_text` retire les marqueurs +Markdown et saute les blocs de code, pour qu'aucun astérisque ni triple backtick ne soit +prononcé. + ### 4.3 Mise en page : pourquoi les réponses débordaient Bug réel, reproduit par un test headless : **un `ScrollArea` hérite du layout du `Ui` qui diff --git a/frontend/README.md b/frontend/README.md index 7b5cef5..365e2a6 100644 --- a/frontend/README.md +++ b/frontend/README.md @@ -120,6 +120,10 @@ et lit la réponse `text/event-stream` avec `eventsource-stream` : | `data: [DONE]` | fin de génération, bouton « Envoyer » réactivé | | `data: {"error": "..."}` | message d'erreur affiché dans la GUI | +L'historique envoyé est l'échange complet **nettoyé** : les bulles vides sont écartées (une +réponse stoppée avant son premier fragment en laisse une) et seuls les 50 derniers messages +partent, la limite du schéma backend. + Tout le réseau tourne dans une tâche `tokio::spawn` : la boucle de rendu egui n'est **jamais bloquée**. Chaque fragment reçu déclenche `Context::request_repaint()`, ce qui fait progresser l'affichage en continu, avec **scroll automatique** vers le bas. @@ -164,6 +168,43 @@ La conversation est dessinée dans une **colonne centrée** de largeur bornée : 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. +### Rendu Markdown des réponses + +Jarvis répond en Markdown : ses bulles (et ses sous-titres en mode Compagnon) sont +**rendues** au lieu d'afficher la syntaxe. `egui` n'a pas de widget Markdown, et les +polices embarquées n'ont qu'une graisse par famille, donc `src/markdown.rs` construit lui +même un `LayoutJob` stylé — ce qui garde la mise en page et le dimensionnement des bulles +déjà en place. Le sous-ensemble couvert est celui qu'utilisent vraiment les réponses : + +| Élément | Rendu | +| --- | --- | +| `# … ######` | taille décroissante, couleur d'accent | +| `**gras**`, `*italique*`, `~~barré~~` | gras = couleur plus claire (une seule graisse disponible), italique et barré réels | +| `` `code` ``, blocs ```` ``` ```` | police monospace sur un fond dédié | +| `-`, `*`, `1.` | puces `•` et numéros, indentation conservée | +| `>`, `---` | citation et filet | +| `| a | b |` | cellules séparées par `•`, ligne `|---|` ignorée | +| `[texte](url)` | le texte en accent souligné | + +Le rendu est **tolérant au streaming** : une réponse à moitié écrite est remise en page à +chaque fragment, donc un `**` ou un bloc de code non fermé stylise la suite au lieu +d'afficher des marqueurs. Ce que l'utilisateur écrit, en revanche, reste affiché +verbatim — ses astérisques sont des astérisques. + +### Réveil du modèle + +Ollama décharge un modèle resté inactif (son défaut est `5m`) et le recharger coûte +plusieurs secondes. Deux mesures, côté client et côté backend : + +- dès que l'utilisateur **commence à écrire** (première modification du brouillon) ou + **démarre un enregistrement**, le client appelle `POST /api/chat/warm` : le modèle est + chargé pendant que la phrase s'écrit, pas après ; +- chaque requête de chat envoie `keep_alive` (défaut `30m`, réglable par + `OLLAMA_KEEP_ALIVE`), pour qu'Ollama garde les poids en mémoire entre deux questions. + +L'appel est **au mieux**, une seule fois par brouillon : son échec est ignoré, la requête +de chat qui suit remonte la vraie erreur. + ### Gestion des erreurs - Backend injoignable → message réseau affiché dans la GUI. @@ -181,9 +222,16 @@ La voix est traitée **entièrement côté client** : rien d'audio ne transite v micro est capturé via `cpal`, rééchantillonné à 16 kHz mono si besoin, puis transcrit par **whisper.cpp** (`whisper-rs`). Le texte obtenu est envoyé automatiquement au backend — même requête JSON qu'un message tapé. -- **TTS** — coche « 🔊 Voix » (ou `JARVIS_SPEAK=1`) : à la fin du streaming, la réponse est - synthétisée par **Piper** (`piper-rs`) et jouée sur le haut-parleur (rééchantillonnage vers - la fréquence du périphérique de sortie). +- **TTS** — coche « 🔊 Voix » (ou `JARVIS_SPEAK=1`) : la réponse est synthétisée par + **Piper** (`piper-rs`) et jouée sur le haut-parleur (rééchantillonnage vers la fréquence + du périphérique de sortie). La lecture **commence sans attendre la fin de la génération** : + `voice/speech.rs` découpe le flux en phrases dès qu'elles sont complètes (ponctuation + finale, ou coupure au dernier espace pour un pavé sans ponctuation) et les envoie à la + file du moteur, qui les dit dans l'ordre, bout à bout. Le texte parlé est du **texte + brut** : les marqueurs Markdown sont retirés et les blocs de code ne sont pas lus — on + n'entend ni astérisque ni ` ``` `. +- Le compagnon affiche « Parle » tant qu'il reste des phrases en file, et repasse au repos + à la dernière. - Les moteurs (modèles Whisper/Piper) sont chargés **paresseusement** sur un thread dédié (`jarvise-voice`) et réutilisés : ni le chargement du modèle ni l'inférence ne bloquent l'interface. diff --git a/frontend/src/api.rs b/frontend/src/api.rs index b6ed35b..a494498 100644 --- a/frontend/src/api.rs +++ b/frontend/src/api.rs @@ -17,7 +17,7 @@ use crate::model::{ AddMessageRequest, ChatMessage, ChatRequest, CreateProjectRequest, DeletedMessagesResponse, LoginRequest, LoginResponse, MeResponse, MessagePage, MessageResponse, Project, ProjectChatRequest, ProjectRecallRequest, ProjectResponse, ProjectsResponse, PublicUser, - RecallDoneData, StreamData, StoredMessage, UpdateProjectRequest, + RecallDoneData, StreamData, StoredMessage, UpdateProjectRequest, WarmModelRequest, }; /// Errors surfaced to the GUI (which displays them as-is). @@ -328,6 +328,20 @@ impl ApiClient { .await } + /// Asks the backend to load `model` into memory ahead of the real request. + /// + /// Ollama drops an idle model after a few minutes, and loading it back costs + /// seconds, so this is fired as soon as the user starts typing or recording. + /// Best effort: the caller ignores the result, since the chat request that + /// follows reports any real failure. + pub async fn warm_model(&self, model: &str) -> Result<(), ApiError> { + let request = self + .http + .post(self.url("/api/chat/warm")) + .json(&WarmModelRequest { model: Some(model) }); + self.send_empty(request).await + } + /// Streams a chat completion. /// /// `on_event` is called for every fragment as it arrives; it runs on the diff --git a/frontend/src/app.rs b/frontend/src/app.rs index 7ea6ecf..2077521 100644 --- a/frontend/src/app.rs +++ b/frontend/src/app.rs @@ -15,10 +15,12 @@ use tokio_util::sync::CancellationToken; use crate::api::{ApiClient, RecallEvent, StreamEvent}; use crate::config::AppConfig; +use crate::markdown; 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}; +use crate::voice::speech::SentenceChunker; /// Key under which the state is persisted (token, email, model, backend URL). const STORAGE_KEY: &str = "jarvise-session"; @@ -200,6 +202,15 @@ pub struct JarviseApp { recorder: Option, voice_status: Option, pending_transcript: Option, + /// Reassembles the streamed answer into sentences to speak as it arrives, + /// instead of waiting for the whole message. + speech: SentenceChunker, + /// Sentences still queued in the voice thread: the companion only stops + /// showing « Speaking » once the last one has been read out. + speech_pending: usize, + /// Whether the draft being typed already asked the backend to warm the + /// model. Keeps a single request per draft instead of one per keystroke. + draft_warmed: bool, // Companion animation. speaking: bool, @@ -297,6 +308,9 @@ impl JarviseApp { recorder: None, voice_status: None, pending_transcript: None, + speech: SentenceChunker::new(), + speech_pending: 0, + draft_warmed: false, speaking: false, happy_timer: 0.0, }; @@ -562,11 +576,15 @@ impl JarviseApp { } self.error = None; + // A new answer starts from a clean slate: nothing left over from the + // previous one may be spoken, and the next draft may warm the model. + self.speech.clear(); + self.draft_warmed = false; self.messages.push(ChatMessage::user(text.clone())); self.input.clear(); // The history sent to the stateless endpoint ends with the user's message. - let history = self.messages.clone(); + let history = stateless_history(&self.messages); // A placeholder assistant bubble receives the streamed fragments. self.messages.push(ChatMessage::assistant(String::new())); @@ -609,6 +627,29 @@ impl JarviseApp { cancel.cancel(); } self.streaming = false; + // The rest of that answer will never arrive: forget it rather than say + // a random half-sentence later. + self.speech.clear(); + } + + /// Asks the backend to load the model into memory before the request that + /// will need it. Ollama unloads an idle model after a few minutes and a + /// cold load costs several seconds; firing this as soon as the user starts + /// typing or recording hides that cost behind the sentence being written. + /// + /// Best effort — the result is ignored, and the real chat request reports + /// any genuine failure. At most one call per draft. + fn warm_model(&mut self) { + if self.draft_warmed || self.streaming { + return; + } + self.draft_warmed = true; + + let api = self.api.clone(); + let model = self.model.clone(); + self.runtime.spawn(async move { + let _ = api.warm_model(&model).await; + }); } fn logout(&mut self) { @@ -630,6 +671,9 @@ impl JarviseApp { return; } self.error = None; + // The user is about to speak: start loading the model now, so it is + // resident by the time the transcript reaches the backend. + self.warm_model(); match Recorder::start() { Ok(recorder) => { self.recorder = Some(recorder); @@ -808,25 +852,30 @@ impl JarviseApp { last.content.push_str(&text); } } + // Speak each sentence as soon as it is complete: waiting for + // `done` would leave the user in silence for the whole + // answer. + if self.speak_replies { + for sentence in self.speech.push(&text) { + self.speech_pending += 1; + self.voice.speak(sentence); + } + // The companion only shows « Speaking » once something is + // actually queued. + self.speaking = self.speech_pending > 0; + } } UiEvent::Done => { self.streaming = false; self.cancel = None; - // Read the answer out loud when voice output is enabled. - let speech = if self.speak_replies { - self.messages - .last() - .filter(|message| { - message.role == "assistant" && !message.content.trim().is_empty() - }) - .map(|message| message.content.clone()) - } else { - None - }; - if let Some(text) = speech { - self.speaking = true; - self.voice.speak(text); + // The answer may end mid-sentence: speak what is left over. + if self.speak_replies { + for sentence in self.speech.flush() { + self.speech_pending += 1; + self.voice.speak(sentence); + } + self.speaking = self.speech_pending > 0; } self.happy_timer = 2.5; @@ -851,10 +900,15 @@ impl JarviseApp { } UiEvent::VoiceError(message) => { self.voice_status = None; + self.speech_pending = 0; self.speaking = false; self.error = Some(message); } - UiEvent::Spoken => self.speaking = false, + // One sentence finished playing; others may still be queued. + UiEvent::Spoken => { + self.speech_pending = self.speech_pending.saturating_sub(1); + self.speaking = self.speech_pending > 0; + } } } } @@ -1141,6 +1195,12 @@ impl JarviseApp { let submitted = response.has_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter) && !i.modifiers.shift); + // First keystroke of a draft: load the model while the + // sentence is still being written. + if response.changed() && !self.input.trim().is_empty() { + self.warm_model(); + } + if self.streaming { if ui .add_sized([button_width, 52.0], egui::Button::new("Stopper")) @@ -1184,6 +1244,10 @@ impl JarviseApp { let submitted = response.has_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter) && !i.modifiers.shift); + if response.changed() && !self.input.trim().is_empty() { + self.warm_model(); + } + if self.streaming { if ui .add_sized([button_width, 40.0], egui::Button::new("Stopper")) @@ -1567,7 +1631,8 @@ fn subtitle(ui: &mut egui::Ui, who: &str, text: &str, width: f32, from_jarvis: b .corner_radius(egui::CornerRadius::same(12)) .inner_margin(egui::Margin::symmetric(14, 10)) .show(ui, |ui| { - ui.set_max_width((width - 30.0).max(120.0)); + let inner_width = (width - 30.0).max(120.0); + ui.set_max_width(inner_width); ui.vertical(|ui| { ui.label( egui::RichText::new(who) @@ -1575,11 +1640,33 @@ fn subtitle(ui: &mut egui::Ui, who: &str, text: &str, width: f32, from_jarvis: b .strong() .color(ACCENT_SOFT), ); - ui.label(text); + if from_jarvis { + ui.label(markdown::layout( + text, + &assistant_markdown(), + inner_width - 28.0, + )); + } else { + ui.label(text); + } }); }); } +/// How Jarvis' Markdown is painted inside a bubble or a subtitle: prose in the +/// app's reading colour, headings and bullets on the accent, code on its own +/// slab. Emphasis is a brighter colour because the bundled fonts have a single +/// weight per family. +fn assistant_markdown() -> markdown::MarkdownStyle { + markdown::MarkdownStyle { + text: egui::Color32::from_gray(238), + strong: egui::Color32::WHITE, + accent: ACCENT_SOFT, + base_size: 15.0, + ..markdown::MarkdownStyle::default() + } +} + /// Consumes the microphone shortcut from the current frame's input and reports /// whether it fired. Consuming it keeps the `Ctrl+Espace` press away from the /// compose box, and makes a single press toggle the capture only once. @@ -1706,6 +1793,31 @@ pub fn chat_area(ui: &mut egui::Ui, messages: &[ChatMessage]) { ); } +/// Turns handed back to the model by `POST /api/chat`: everything that carries +/// text, capped at the backend's contract and keeping the most recent exchange. +/// +/// Two bubbles have to be left out, or the request is rejected before it ever +/// reaches the model: an abandoned answer leaves an **empty** assistant message +/// (the schema requires `minLength: 1`), and a long conversation exceeds the +/// 50-message cap. The last entry is always the question, so trimming the +/// oldest turns keeps the model's context as recent as the window allows. +fn stateless_history(messages: &[ChatMessage]) -> Vec { + let mut history: Vec = messages + .iter() + .filter(|message| !message.content.trim().is_empty()) + .cloned() + .collect(); + + if history.len() > MAX_HISTORY_MESSAGES { + history.drain(..history.len() - MAX_HISTORY_MESSAGES); + } + + history +} + +/// Longest history `POST /api/chat` accepts (see the backend's JSON schema). +const MAX_HISTORY_MESSAGES: usize = 50; + /// 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 @@ -1735,14 +1847,22 @@ pub fn render_bubble(ui: &mut egui::Ui, message: &ChatMessage) -> egui::Rect { } 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, - ) - }); + // Jarvis answers in Markdown: render it (headings, lists, code, emphasis) + // instead of showing the syntax. What the user typed stays verbatim — they + // write plain prose, and asterisks there mean asterisks. + let job = if message.is_user() { + let mut job = egui::text::LayoutJob::default(); + job.wrap.max_width = text_width; + job.append( + text, + 0.0, + egui::TextFormat::simple(egui::FontId::proportional(15.0), text_color), + ); + job + } else { + markdown::layout(text, &assistant_markdown(), text_width) + }; + let galley = ui.ctx().fonts_mut(|fonts| fonts.layout_job(job)); 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. @@ -1858,6 +1978,38 @@ mod tests { assert!(!repeated, "un appui ne doit basculer le micro qu'une fois"); } + /// The model only answers well when it gets the whole conversation, but two + /// details of the backend contract decide what may be sent. + #[test] + fn the_history_sent_back_is_usable() { + let mut messages = vec![ + ChatMessage::user("Bonjour"), + ChatMessage::assistant("Bonjour, que puis-je faire ?"), + // An answer stopped before its first fragment leaves an empty bubble. + ChatMessage::assistant(String::new()), + ChatMessage::user("Ouvre le fichier"), + ]; + + let history = stateless_history(&messages); + assert_eq!(history.len(), 3, "the empty bubble must not be sent"); + assert!(history.last().expect("a question").is_user()); + assert!(history.iter().all(|m| !m.content.trim().is_empty())); + + // A long conversation is trimmed from the oldest turn, never from the + // question that is being asked right now. + messages.clear(); + for i in 0..80 { + messages.push(ChatMessage::user(format!("question {i}"))); + messages.push(ChatMessage::assistant(format!("réponse {i}"))); + } + messages.push(ChatMessage::user("dernière question")); + + let history = stateless_history(&messages); + assert_eq!(history.len(), MAX_HISTORY_MESSAGES); + assert_eq!(history.last().expect("the question").content, "dernière question"); + assert_eq!(history[0].content, "réponse 55"); + } + #[test] fn modes_have_distinct_tabs() { assert_ne!(Mode::Chat.label(), Mode::Companion.label()); diff --git a/frontend/src/lib.rs b/frontend/src/lib.rs index 8660197..522bde1 100644 --- a/frontend/src/lib.rs +++ b/frontend/src/lib.rs @@ -7,6 +7,7 @@ pub mod api; pub mod app; pub mod config; +pub mod markdown; pub mod model; pub mod tamagotchi; pub mod voice; diff --git a/frontend/src/markdown.rs b/frontend/src/markdown.rs new file mode 100644 index 0000000..fb06eb2 --- /dev/null +++ b/frontend/src/markdown.rs @@ -0,0 +1,564 @@ +//! A small Markdown renderer for the answers Jarvis streams back. +//! +//! `egui` has no Markdown widget, and the bundled fonts ship a single weight per +//! family — there is no bold face to switch to. So instead of pulling in a full +//! parser (which would hit the same font limit), the renderer keeps what the +//! app already does well: one [`LayoutJob`] laid out at a known width, painted +//! by the caller's bubble. It styles the blocks the answers actually use — +//! headings, lists, quotes, rules, tables, fenced code, and inline emphasis, +//! code and links — and drops the syntax markers, so `**gras**` shows as +//! *gras* and not as asterisks. +//! +//! Everything tolerates a half-written answer: an unclosed `**` or code fence +//! styles the rest of the message instead of printing the markers, because the +//! bubble is laid out again on every streamed fragment. + +use eframe::egui; +use egui::text::{LayoutJob, TextFormat}; +use egui::{Color32, FontId, Stroke}; + +/// Colours and base size the renderer paints with. Kept explicit rather than +/// read from the egui style so a bubble stays readable whatever the theme does. +#[derive(Clone, Copy, Debug)] +pub struct MarkdownStyle { + /// Ordinary prose. + pub text: Color32, + /// Emphasis. `egui` has one weight per font family, so bold is carried by a + /// brighter colour instead of a heavier face. + pub strong: Color32, + /// Headings, bullets, table separators and links. + pub accent: Color32, + /// Inline code and fenced blocks, painted on [`Self::code_background`]. + pub code: Color32, + pub code_background: Color32, + /// Size of ordinary prose; every other size is derived from it. + pub base_size: f32, +} + +impl Default for MarkdownStyle { + fn default() -> Self { + Self { + text: Color32::from_gray(238), + strong: Color32::WHITE, + accent: Color32::from_rgb(0x9d, 0xbc, 0xff), + code: Color32::from_rgb(0xd8, 0xe2, 0xf0), + code_background: Color32::from_rgb(0x2a, 0x2f, 0x3b), + base_size: 15.0, + } + } +} + +/// Lays `markdown` out into a galley job wrapped at `wrap_width`. +pub fn layout(markdown: &str, style: &MarkdownStyle, wrap_width: f32) -> LayoutJob { + let mut job = LayoutJob::default(); + job.wrap.max_width = wrap_width.max(1.0); + job.break_on_newline = true; + + let size = style.base_size; + let mut in_fence = false; + + for raw in markdown.lines() { + let line = raw.trim_end(); + let trimmed = line.trim_start(); + // Indented items keep a visual step. The answers nest one level deep at + // most, so capping the indent is enough. + let indent = " ".repeat((line.len() - trimmed.len()).min(6) / 2); + + // A fence toggles with its own marker line, which is never painted. + if trimmed.starts_with("```") { + in_fence = !in_fence; + continue; + } + + if in_fence { + job.append(line, 0.0, code_format(style, size * 0.92)); + push_newline(&mut job, size, style.code); + continue; + } + + if trimmed.is_empty() { + push_newline(&mut job, size, style.text); + continue; + } + + if let Some(level) = heading_level(trimmed) { + let heading_size = size * heading_scale(level); + push_inline(&mut job, &trimmed[level..].trim_start(), style, heading_size, style.accent); + push_newline(&mut job, heading_size, style.accent); + continue; + } + + if is_rule(trimmed) { + let format = prose_format(size, style.code); + job.append(&"─".repeat(28), 0.0, format); + push_newline(&mut job, size, style.code); + continue; + } + + if let Some(row) = table_row(trimmed) { + match row { + // `|---|---|` only marks the header; it carries no content. + TableRow::Separator => {} + TableRow::Cells(cells) => { + push_table_row(&mut job, &cells, style, size); + push_newline(&mut job, size, style.text); + } + } + continue; + } + + if let Some(rest) = trimmed.strip_prefix('>') { + let format = prose_format(size, style.accent); + job.append(&format!("{indent}│ "), 0.0, format); + push_inline(&mut job, rest.trim_start(), style, size, style.code); + push_newline(&mut job, size, style.text); + continue; + } + + if let Some(rest) = bullet_rest(trimmed) { + let format = prose_format(size, style.accent); + job.append(&format!("{indent}• "), 0.0, format); + push_inline(&mut job, rest, style, size, style.text); + push_newline(&mut job, size, style.text); + continue; + } + + if let Some((marker, rest)) = ordered_parts(trimmed) { + let format = prose_format(size, style.accent); + job.append(&format!("{indent}{marker} "), 0.0, format); + push_inline(&mut job, rest, style, size, style.text); + push_newline(&mut job, size, style.text); + continue; + } + + push_inline(&mut job, trimmed, style, size, style.text); + push_newline(&mut job, size, style.text); + } + + job +} + +/// What to speak out loud: the same Markdown without its syntax. +/// +/// Fenced blocks are left out entirely — reading code, indentation and +/// backticks aloud is noise — while everything else keeps its words. Used only +/// by the speech path, never for display. +pub fn to_plain_text(markdown: &str) -> String { + let mut out = String::new(); + let mut in_fence = false; + + for raw in markdown.lines() { + let trimmed = raw.trim(); + if trimmed.starts_with("```") { + in_fence = !in_fence; + continue; + } + if in_fence || is_rule(trimmed) { + continue; + } + + let mut line = trimmed; + if let Some(level) = heading_level(line) { + line = line[level..].trim_start(); + } else if let Some(rest) = bullet_rest(line) { + line = rest; + } else if let Some((_, rest)) = ordered_parts(line) { + line = rest; + } else if let Some(rest) = line.strip_prefix('>') { + line = rest.trim_start(); + } + + if let Some(row) = table_row(line) { + if let TableRow::Cells(cells) = row { + out.push_str(&cells.join(", ")); + out.push('\n'); + } + continue; + } + + let spoken = strip_inline(line); + if !spoken.is_empty() { + out.push_str(&spoken); + out.push('\n'); + } + } + + // Markers leave doubled spaces behind; a synthesiser reads them as pauses. + out.split_whitespace().collect::>().join(" ") +} + +/* --------------------------------------------------------------- blocks */ + +fn heading_level(line: &str) -> Option { + let hashes = line.chars().take_while(|c| *c == '#').count(); + if hashes == 0 || hashes > 6 { + return None; + } + // `#hashtag` is not a heading: a heading marker is followed by a space. + let rest = &line[hashes..]; + (rest.is_empty() || rest.starts_with(' ')).then_some(hashes) +} + +fn heading_scale(level: usize) -> f32 { + match level { + 1 => 1.55, + 2 => 1.35, + 3 => 1.20, + 4 => 1.12, + _ => 1.05, + } +} + +fn bullet_rest(line: &str) -> Option<&str> { + ["- ", "* ", "+ "] + .into_iter() + .find_map(|marker| line.strip_prefix(marker)) +} + +/// Splits `12. text` into its marker (`12.`) and the text that follows. +fn ordered_parts(line: &str) -> Option<(&str, &str)> { + let digits = line.chars().take_while(|c| c.is_ascii_digit()).count(); + if digits == 0 { + return None; + } + let rest = line[digits..].strip_prefix(". ")?; + Some((&line[..=digits], rest)) +} + +/// `---`, `***` or `___` on a line of their own: a horizontal rule. +fn is_rule(line: &str) -> bool { + let trimmed = line.trim(); + let mut chars = trimmed.chars(); + let Some(first) = chars.next() else { + return false; + }; + if !matches!(first, '-' | '*' | '_' | '=') { + return false; + } + trimmed.chars().count() >= 3 && trimmed.chars().all(|c| c == first || c == ' ') +} + +enum TableRow<'a> { + /// `|---|---|`: the line that underlines a header. + Separator, + Cells(Vec<&'a str>), +} + +fn table_row(line: &str) -> Option> { + let inner = line.strip_prefix('|')?.strip_suffix('|')?; + let cells: Vec<&str> = inner.split('|').map(str::trim).collect(); + if cells.iter().all(|cell| { + !cell.is_empty() && cell.chars().all(|c| c == '-' || c == ':') + }) { + return Some(TableRow::Separator); + } + Some(TableRow::Cells(cells)) +} + +fn push_table_row(job: &mut LayoutJob, cells: &[&str], style: &MarkdownStyle, size: f32) { + let separator = prose_format(size, style.accent); + for (index, cell) in cells.iter().enumerate() { + if index > 0 { + job.append(" • ", 0.0, separator.clone()); + } + push_inline(job, cell, style, size, style.text); + } +} + +/* --------------------------------------------------------------- inline */ + +/// Emphasis state while scanning a line. +#[derive(Default, Clone, Copy)] +struct Emphasis { + bold: bool, + italic: bool, + strike: bool, +} + +fn push_inline(job: &mut LayoutJob, text: &str, style: &MarkdownStyle, size: f32, color: Color32) { + // Inside a heading the text is already accented, so bold would be invisible: + // keep the heading colour rather than switching to [`MarkdownStyle::strong`]. + let emphasis = if color == style.text { + style.strong + } else { + color + }; + + let mut state = Emphasis::default(); + let mut run_start = 0; + let mut i = 0; + + while i < text.len() { + let rest = &text[i..]; + let Some(c) = rest.chars().next() else { + break; + }; + + match c { + // Inline code, recognised only once its closing backtick has + // arrived: a half-streamed answer must not turn the rest of the + // line into code. + '`' => match rest[1..].find('`') { + Some(end) => { + push_run(job, &text[run_start..i], size, color, emphasis, state); + job.append(&rest[1..1 + end], 0.0, code_format(style, size * 0.94)); + i += end + 2; + run_start = i; + } + None => i += 1, + }, + '*' | '_' if rest.starts_with("**") || rest.starts_with("__") => { + push_run(job, &text[run_start..i], size, color, emphasis, state); + state.bold = !state.bold; + i += 2; + run_start = i; + } + // A lone `*` opens emphasis only when a word follows it, so `2 * 3` + // stays arithmetic instead of italicising the rest of the line. + '*' | '_' => { + let opens = rest[1..].chars().next().is_some_and(|n| !n.is_whitespace()); + if opens || state.italic { + push_run(job, &text[run_start..i], size, color, emphasis, state); + state.italic = !state.italic; + i += 1; + run_start = i; + } else { + i += 1; + } + } + '~' if rest.starts_with("~~") => { + push_run(job, &text[run_start..i], size, color, emphasis, state); + state.strike = !state.strike; + i += 2; + run_start = i; + } + '[' => match parse_link(rest) { + Some((label, consumed)) => { + push_run(job, &text[run_start..i], size, color, emphasis, state); + let mut format = prose_format(size, style.accent); + format.italics = state.italic; + format.underline = Stroke::new(1.0, style.accent); + job.append(label, 0.0, format); + i += consumed; + run_start = i; + } + None => i += 1, + }, + _ => i += c.len_utf8(), + } + } + + push_run(job, &text[run_start..], size, color, emphasis, state); +} + +/// `[label](target)` → the label and how many bytes it occupies. An image +/// falls back to its alt text, which is the only part worth showing. +fn parse_link(text: &str) -> Option<(&str, usize)> { + let close = text.find("](")?; + let end = text[close + 2..].find(')')?; + let label = &text[1..close]; + if label.is_empty() { + return None; + } + Some((label, close + 2 + end + 1)) +} + +/// Drops the inline markers of one line, keeping only what is read out. +fn strip_inline(text: &str) -> String { + let mut out = String::new(); + let mut chars = text.chars().peekable(); + + while let Some(c) = chars.next() { + match c { + // Markers carry no sound: only the words around them are spoken. + '*' | '_' | '`' | '~' => {} + '[' => { + let mut label = String::new(); + let mut closed = false; + for n in chars.by_ref() { + if n == ']' { + closed = true; + break; + } + label.push(n); + } + // Skip the target, keeping the readable label. + if closed && chars.peek() == Some(&'(') { + chars.next(); + for n in chars.by_ref() { + if n == ')' { + break; + } + } + } + out.push_str(&label); + } + _ => out.push(c), + } + } + + out +} + +/* -------------------------------------------------------------- formats */ + +fn prose_format(size: f32, color: Color32) -> TextFormat { + TextFormat::simple(FontId::proportional(size), color) +} + +fn code_format(style: &MarkdownStyle, size: f32) -> TextFormat { + let mut format = TextFormat::simple(FontId::monospace(size), style.code); + format.background = style.code_background; + format +} + +fn push_newline(job: &mut LayoutJob, size: f32, color: Color32) { + job.append("\n", 0.0, prose_format(size, color)); +} + +fn push_run( + job: &mut LayoutJob, + slice: &str, + size: f32, + color: Color32, + emphasis: Color32, + state: Emphasis, +) { + if slice.is_empty() { + return; + } + let mut format = prose_format(size, if state.bold { emphasis } else { color }); + format.italics = state.italic; + if state.strike { + format.strikethrough = Stroke::new(1.0, format.color); + } + job.append(slice, 0.0, format); +} + +#[cfg(test)] +mod tests { + use super::*; + + fn dark() -> MarkdownStyle { + MarkdownStyle { + base_size: 15.0, + ..Default::default() + } + } + + #[test] + fn headings_grow_and_lose_their_hashes() { + let job = layout("# Titre\n\n## Sous-titre", &dark(), 600.0); + + assert!(!job.text.contains('#'), "text was: {:?}", job.text); + assert!(job.text.contains("Titre")); + + let sizes: Vec = job.sections.iter().map(|s| s.format.font_id.size).collect(); + assert!(sizes.iter().cloned().fold(f32::MIN, f32::max) > 20.0); + } + + #[test] + fn emphasis_is_styled_instead_of_printed() { + let job = layout("du **gras**, de l'*italique* et du ~~barré~~", &dark(), 600.0); + + assert_eq!(job.text.trim_end(), "du gras, de l'italique et du barré"); + + let style = dark(); + assert!( + job.sections.iter().any(|s| s.format.color == style.strong), + "bold should be brighter than the body text" + ); + assert!(job.sections.iter().any(|s| s.format.italics)); + assert!(job.sections.iter().any(|s| s.format.strikethrough != Stroke::NONE)); + } + + #[test] + fn a_lone_star_stays_arithmetic() { + let job = layout("2 * 3 = 6", &dark(), 600.0); + + assert_eq!(job.text.trim_end(), "2 * 3 = 6"); + assert!(job.sections.iter().all(|s| !s.format.italics)); + } + + #[test] + fn fence_markers_are_dropped_and_code_is_monospace() { + let job = layout("avant\n```rust\nlet x = 1;\n```\naprès", &dark(), 600.0); + + assert!(!job.text.contains("```")); + assert!(job.text.contains("let x = 1;")); + + let style = dark(); + let code = job + .sections + .iter() + .find(|s| s.format.font_id.family == FontId::monospace(15.0).family) + .expect("the code line should keep a monospace font"); + assert_eq!(code.format.background, style.code_background); + } + + #[test] + fn an_unclosed_fence_styles_what_has_arrived() { + // Mid-stream: the closing fence is still missing. + let job = layout("voici :\n```\nlet x", &dark(), 600.0); + + assert!(job.text.contains("let x")); + assert!(!job.text.contains("```")); + assert!( + job.sections + .iter() + .any(|s| s.format.background == dark().code_background), + "an unclosed fence must not print its marker" + ); + } + + #[test] + fn bullets_and_numbers_keep_their_text() { + let job = layout("- un\n- deux\n\n1. premier\n2. second", &dark(), 600.0); + + assert!(job.text.contains("• un"), "text was: {:?}", job.text); + assert!(job.text.contains("1. premier")); + assert!(!job.text.contains("- un")); + } + + #[test] + fn table_rows_lose_their_pipes() { + let job = layout("| Nom | Rôle |\n|---|---|\n| Jarvis | assistant |", &dark(), 600.0); + + assert!(!job.text.contains('|'), "text was: {:?}", job.text); + assert!(job.text.contains("Nom")); + assert!(job.text.contains("•")); + // The `|---|` marker line only underlines the header. + assert!(!job.text.contains("---")); + } + + #[test] + fn links_show_their_label() { + let job = layout("voir [la doc](https://example.com/x) pour ça", &dark(), 600.0); + + assert_eq!(job.text.trim_end(), "voir la doc pour ça"); + assert!(job.sections.iter().any(|s| s.format.underline != Stroke::NONE)); + } + + #[test] + fn spoken_text_has_no_markers_and_no_code() { + let spoken = to_plain_text( + "## Titre\n\n**gras** et `code`\n\n```sh\ncargo run\n```\n\n- un élément\n> cité", + ); + + assert_eq!(spoken, "Titre gras et code un élément cité"); + } + + #[test] + fn a_half_written_answer_still_lays_out() { + for partial in [ + "**gras inachevé", + "*italique inachevé", + "`code inachevé", + "~~barré inachevé", + "[lien inachevé](", + ] { + let job = layout(partial, &dark(), 400.0); + assert!(!job.text.is_empty(), "{partial:?} should not vanish"); + } + } +} diff --git a/frontend/src/model.rs b/frontend/src/model.rs index c900974..2f38567 100644 --- a/frontend/src/model.rs +++ b/frontend/src/model.rs @@ -203,6 +203,14 @@ pub(crate) struct ProjectRecallRequest<'a> { pub model: Option<&'a str>, } +/// Body of `POST /api/chat/warm`: asks the backend to load the model into +/// memory before the request that will actually need it. +#[derive(Serialize)] +pub(crate) struct WarmModelRequest<'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)] diff --git a/frontend/src/voice/mod.rs b/frontend/src/voice/mod.rs index b67a84c..ca735ef 100644 --- a/frontend/src/voice/mod.rs +++ b/frontend/src/voice/mod.rs @@ -8,5 +8,6 @@ pub mod audio; pub mod engine; +pub mod speech; pub mod stt; pub mod tts; diff --git a/frontend/src/voice/speech.rs b/frontend/src/voice/speech.rs new file mode 100644 index 0000000..41d8186 --- /dev/null +++ b/frontend/src/voice/speech.rs @@ -0,0 +1,234 @@ +//! Splits a streamed answer into sentences the voice can start on immediately. +//! +//! Waiting for `done` before the first word is spoken means waiting for the +//! whole answer: a long reply is read out only once it is complete, and the +//! user sits in silence the entire time. Instead, [`SentenceChunker`] is fed +//! the same fragments that fill the bubble, and hands back every sentence as +//! soon as its final punctuation arrives. The sentences come out in order, and +//! the voice thread is a queue, so they are spoken back to back. +//! +//! The text handed back is already readable aloud: Markdown markers are gone +//! and fenced code is skipped ([`crate::markdown::to_plain_text`]). + +use crate::markdown; + +/// A unit longer than this is cut at the next space: a wall of text with no +/// punctuation at all (a code-free list, a long URL) must not keep the voice +/// silent until the very end. +const MAX_UNIT_BYTES: usize = 240; + +/// Shortest unit worth speaking on its own. List numbers, `--` and stray +/// punctuation land here and are dropped instead of being read as grunts. +const MIN_LETTERS: usize = 2; + +/// Reassembles streamed Markdown fragments into speakable sentences. +#[derive(Default)] +pub struct SentenceChunker { + /// Fragments seen so far minus the sentences already handed out. + buffer: String, + /// Whether the scan so far has left a fenced code block open. + in_fence: bool, + /// Fence state at the very start of [`Self::buffer`], restored before each + /// scan because everything before it has already been consumed. + tail_in_fence: bool, +} + +impl SentenceChunker { + pub fn new() -> Self { + Self::default() + } + + /// Adds a fragment and returns the sentences that are now complete. + pub fn push(&mut self, fragment: &str) -> Vec { + self.buffer.push_str(fragment); + // The buffer is rescanned from its start, so start from the state that + // belonged to that position. + self.in_fence = self.tail_in_fence; + + let mut sentences = Vec::new(); + let mut unit_start = 0; + let mut fence_at_start = self.in_fence; + let mut i = 0; + + while i < self.buffer.len() { + if self.buffer[i..].starts_with("```") { + self.in_fence = !self.in_fence; + i += 3; + continue; + } + + let Some(c) = self.buffer[i..].chars().next() else { + break; + }; + let end = match c { + '\n' => Some(i + 1), + '.' | '!' | '?' | '…' => { + let next = self.buffer[i + c.len_utf8()..].chars().next(); + // `3.14` and `...` are not the end of a sentence: the + // punctuation has to be followed by a space or nothing. + match next { + None | Some(' ') | Some('\n') | Some('\t') => Some(i + c.len_utf8()), + _ => None, + } + } + ' ' if i - unit_start >= MAX_UNIT_BYTES => Some(i), + _ => None, + }; + + if let Some(end) = end { + self.emit(unit_start, end, fence_at_start, &mut sentences); + unit_start = end; + fence_at_start = self.in_fence; + } + + i += c.len_utf8(); + } + + self.buffer.drain(..unit_start); + self.tail_in_fence = fence_at_start; + sentences + } + + /// Sentences still buffered when the answer ends mid-sentence. + pub fn flush(&mut self) -> Vec { + let mut sentences = Vec::new(); + let end = self.buffer.len(); + self.emit(0, end, self.tail_in_fence, &mut sentences); + self.clear(); + sentences + } + + /// Forgets everything: the next answer starts from a clean slate. + pub fn clear(&mut self) { + self.buffer.clear(); + self.in_fence = false; + self.tail_in_fence = false; + } + + /// Turns one completed unit into a sentence, unless it is code or noise. + fn emit(&self, start: usize, end: usize, in_code: bool, out: &mut Vec) { + if in_code { + return; + } + let spoken = markdown::to_plain_text(&self.buffer[start..end]); + // `to_plain_text` collapses whitespace, so a fence marker or a lone + // "-" comes back empty. + if spoken.chars().filter(|c| c.is_alphabetic()).count() < MIN_LETTERS { + return; + } + out.push(spoken); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_sentence_is_ready_as_soon_as_it_ends() { + let mut chunker = SentenceChunker::new(); + + assert_eq!(chunker.push("Bonjour Jarvis."), vec!["Bonjour Jarvis.".to_string()]); + // Only the finished sentence is handed out, not the fragment after it. + assert!(chunker.push(" Peux-tu").is_empty()); + + let rest = chunker.push(" ouvrir le fichier ?"); + assert_eq!(rest, vec!["Peux-tu ouvrir le fichier ?".to_string()]); + } + + #[test] + fn fragments_are_reassembled_across_pushes() { + let mut chunker = SentenceChunker::new(); + + assert!(chunker.push("Le pro").is_empty()); + assert!(chunker.push("jet est").is_empty()); + assert_eq!( + chunker.push(" prêt. Ensuite."), + vec!["Le projet est prêt.".to_string(), "Ensuite.".to_string()] + ); + } + + #[test] + fn a_decimal_point_does_not_cut_a_sentence() { + let mut chunker = SentenceChunker::new(); + + assert!(chunker.push("Pi vaut 3.14 environ").is_empty()); + assert_eq!( + chunker.flush(), + vec!["Pi vaut 3.14 environ".to_string()], + "the version number must stay in one piece" + ); + } + + #[test] + fn fenced_code_is_never_read_aloud() { + let mut chunker = SentenceChunker::new(); + + let spoken = chunker.push("Voici :\n```sh\ncargo run --release\n```\nEt voilà."); + let spoken = spoken.join(" | "); + + assert!(spoken.contains("Voici"), "spoken was: {spoken}"); + assert!(spoken.contains("Et voilà"), "spoken was: {spoken}"); + assert!(!spoken.contains("cargo"), "gone to the voice: {spoken}"); + assert!(!spoken.contains("```"), "gone to the voice: {spoken}"); + } + + #[test] + fn markdown_markers_are_not_spoken() { + let mut chunker = SentenceChunker::new(); + + let spoken = chunker.push("## Bilan\n\n**Bravo**, c'est `prêt` !\n").join(" | "); + + assert!(spoken.contains("Bilan"), "spoken was: {spoken}"); + assert!(spoken.contains("Bravo"), "spoken was: {spoken}"); + assert!(spoken.contains("prêt"), "spoken was: {spoken}"); + for marker in ["#", "*", "`"] { + assert!(!spoken.contains(marker), "{marker} reached the voice: {spoken}"); + } + } + + #[test] + fn a_tail_is_spoken_when_the_answer_stops() { + let mut chunker = SentenceChunker::new(); + + assert!(chunker.push("Une phrase sans ponctuation").is_empty()); + assert_eq!( + chunker.flush(), + vec!["Une phrase sans ponctuation".to_string()] + ); + // The buffer is empty again, so nothing is repeated on the next answer. + assert!(chunker.flush().is_empty()); + } + + #[test] + fn a_wall_of_text_is_cut_before_the_end() { + let mut chunker = SentenceChunker::new(); + let wall = "mot ".repeat(200); // 800 bytes, no punctuation at all + + let pieces = chunker.push(&wall); + assert!( + !pieces.is_empty(), + "a long answer must start speaking before the end" + ); + for piece in &pieces { + assert!( + piece.len() <= MAX_UNIT_BYTES + "mot ".len(), + "each piece stays around the cap, got {} bytes", + piece.len() + ); + } + // Nothing is lost: the tail is still buffered for the next flush. + let spoken: usize = pieces.iter().map(|p| p.split_whitespace().count()).sum(); + let rest = chunker.flush().join(" "); + assert_eq!(spoken + rest.split_whitespace().count(), 200); + } + + #[test] + fn clear_drops_an_abandoned_answer() { + let mut chunker = SentenceChunker::new(); + chunker.push("Une réponse interrompue"); + + chunker.clear(); + assert!(chunker.flush().is_empty()); + } +} diff --git a/frontend/tests/chat_layout.rs b/frontend/tests/chat_layout.rs index f4a720a..75e2753 100644 --- a/frontend/tests/chat_layout.rs +++ b/frontend/tests/chat_layout.rs @@ -48,6 +48,18 @@ fn painted(screen_width: f32, messages: &[ChatMessage]) -> Vec String { + shapes + .iter() + .filter_map(|clipped| match &clipped.shape { + egui::Shape::Text(text) => Some(text.galley.text()), + _ => None, + }) + .collect::>() + .join("\n") +} + /// Filled rectangles painted with a bubble colour, i.e. the bubbles themselves. fn bubbles(shapes: &[egui::epaint::ClippedShape]) -> Vec { shapes @@ -123,6 +135,45 @@ fn user_bubbles_hug_the_right_and_jarvis_the_left() { assert!(jarvis.is_some(), "Jarvis' bubble must start at the left: {rects:?}"); } +/// Jarvis answers in Markdown: what reaches the screen is the *rendered* +/// answer — headings, emphasis, code — never the syntax that produced it. +#[test] +fn jarvis_markdown_is_rendered_instead_of_shown_raw() { + let messages = vec![ChatMessage::assistant( + "# Titre\n\n**Gras** et `code`\n\n```rust\nlet x = 1;\n```", + )]; + + let shapes = painted(900.0, &messages); + let text = painted_text(&shapes); + + assert!(text.contains("Titre"), "laid out text was: {text:?}"); + assert!(text.contains("Gras"), "laid out text was: {text:?}"); + assert!(text.contains("let x = 1;"), "laid out text was: {text:?}"); + for marker in ["#", "**", "`"] { + assert!(!text.contains(marker), "{marker} was painted: {text:?}"); + } + + // A rendered answer still respects the conversation column. + let rects = bubbles(&shapes); + assert_eq!(rects.len(), 1, "one bubble, got {rects:?}"); + let (left, right) = column(900.0); + assert!( + rects[0].min.x >= left - 1.0 && rects[0].max.x <= right + 1.0, + "bubble {:?} escapes the column [{left}, {right}]", + rects[0] + ); +} + +/// The bubble is laid out again on every streamed fragment, so a half-written +/// answer must render (and never panic) at any moment. +#[test] +fn a_still_streaming_answer_lays_out() { + for partial in ["## Titre en cours", "```rust\nlet x", "**gras inachevé", "| a | b"] { + let shapes = painted(700.0, &[ChatMessage::assistant(partial)]); + assert_eq!(bubbles(&shapes).len(), 1, "partial answer {partial:?}"); + } +} + #[test] fn an_empty_conversation_paints_no_bubble() { let shapes = painted(1400.0, &[]); diff --git a/frontend/tests/projects_api.rs b/frontend/tests/projects_api.rs index d4cbdd9..faa5435 100644 --- a/frontend/tests/projects_api.rs +++ b/frontend/tests/projects_api.rs @@ -508,6 +508,25 @@ async fn fails_when_no_token_is_set() { assert!(server.requests().is_empty()); } +/// Warm-up: the client asks for the model to be loaded before the question that +/// needs it, so the several-second load happens while the user is still typing. +#[tokio::test] +async fn warms_the_model_before_the_question() { + let server = start_server(|_| FakeReply::json(r#"{"model":"qwen2.5:3b","warmed":true}"#)); + + server + .client() + .warm_model("qwen2.5:3b") + .await + .expect("the warm-up should be accepted"); + + let requests = server.requests(); + assert_eq!(requests.len(), 1); + assert_eq!(requests[0].method, "POST"); + assert_eq!(requests[0].target, "/api/chat/warm"); + assert_eq!(body_json(&requests[0])["model"], "qwen2.5:3b"); +} + /// Guards the `StoredMessage` -> `ChatMessage` conversion used by the sidebar. #[test] fn converts_a_stored_message_into_a_chat_message() {