feat(frontend): add native Rust client with SSE chat and local voice

Keep speech-to-text and text-to-speech on the machine so only text
travels to the backend while the backend still speaks JSON to Ollama.
This commit is contained in:
BlackAngelTV committed 2026-10-05 20:40:12 +02:00
1 parent 98c7c8cae2
commit 38f088c8fe
17 files changed
+8014

No files matched your search

+11
View File
@@ -0,0 +1,11 @@
# Configuration appliquée automatiquement par `cargo` lancé depuis ce dossier.
#
# whisper.cpp est livré avec des bindings pré-générés : on évite ainsi d'appeler
# `bindgen` (donc `libclang`) pour whisper. Cela accélère le build et supprime
# une cause d'échec.
#
# NB : `espeak-ng` (dépendance de Piper) appelle `bindgen` sans option pour le
# contourner et nécessite donc `libclang` malgré tout. Installer le paquet
# `clang` (voir le README) : `sudo pacman -S clang`.
[env]
WHISPER_DONT_GENERATE_BINDINGS = "1"
+1
View File
@@ -0,0 +1 @@
/target
+5746
View File
File diff suppressed because it is too large. Load diff
+34
View File
@@ -0,0 +1,34 @@
[package]
name = "jarvise-frontend"
version = "0.1.0"
edition = "2021"
description = "Client desktop natif (egui) qui streame les réponses de Jarvis via SSE, avec STT/TTS locaux."
license = "MIT"
publish = false
[dependencies]
# GUI immédiate 100% Rust. `persistence` active la sauvegarde du token/état.
eframe = { version = "0.36.2", features = ["persistence"] }
# Runtime asynchrone : la boucle réseau ne bloque jamais le thread de rendu.
tokio = { version = "1.53.2", features = ["rt-multi-thread", "macros", "time"] }
# Client HTTP avec support des flux (`.bytes_stream()`) et TLS portable (rustls).
reqwest = { version = "0.13.5", default-features = false, features = ["json", "stream", "rustls"] }
# Parseur SSE qui transforme le flux de bytes en évènements `data:`.
eventsource-stream = "0.2.3"
futures-util = "0.3.34"
serde = { version = "1.0.229", features = ["derive"] }
serde_json = "1.0.151"
# Annulation coopérative de la tâche de streaming (bouton « Stopper »).
tokio-util = { version = "0.7.19", features = ["rt"] }
# --- Voix (STT + TTS) : traitée localement par le client lourd ---------------
# Speech-to-text embarqué (whisper.cpp). Build : WHISPER_DONT_GENERATE_BINDINGS=1
# évite la dépendance à libclang.
whisper-rs = "0.16.0"
# Text-to-speech embarqué (Piper + espeak-ng + onnxruntime).
piper-rs = "0.2.0"
# Entrées/sorties audio (micro + haut-parleur), y compris sous Linux/ALSA.
cpal = "0.18.2"
[profile.release]
opt-level = 2
+207
View File
@@ -0,0 +1,207 @@
# Frontend Jarvise (desktop Rust)
Client desktop natif en **Rust + egui/eframe** qui dialogue avec le backend Jarvise
et affiche la réponse de Jarvis **en streaming temps réel** (SSE), token par token.
C'est un **client lourd** : la reconnaissance vocale (**STT**) et la synthèse vocale
(**TTS**) tournent **localement** sur la machine, et seulement du **texte** circule entre
le client et le backend (le backend, lui, parle en **JSON** avec Ollama).
```
micro (texte) (JSON)
Client Rust ──▶ STT (whisper) ──▶ texte ──HTTP POST SSE──▶ Backend ──▶ Ollama
▲ │
└──── haut-parleur ◀── TTS (Piper) ◀── texte ◀── SSE ───────┘
```
## Prérequis
- **Rust stable** (édition 2021) — installer via [rustup](https://rustup.rs) :
```bash
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
```
- **Chaîne de build C/C++** : `cmake`, `make`, `g++` (whisper.cpp et espeak-ng sont compilés
au build).
- **`libclang`** : **obligatoire**, car `espeak-ng` (dépendance de Piper) appelle `bindgen`.
```bash
# Arch / FWS ISO
sudo pacman -S clang
# Debian / Ubuntu : sudo apt install libclang-dev
# Fedora : sudo dnf install clang
```
*Sans droits root*, on peut récupérer `libclang` dans un venv et pointer `LIBCLANG_PATH`
dessus :
```bash
python3 -m venv /tmp/lcvenv && /tmp/lcvenv/bin/pip install libclang
export LIBCLANG_PATH=/tmp/lcvenv/lib/python3.*/site-packages/clang/native
```
(le flag whisper `WHISPER_DONT_GENERATE_BINDINGS=1` est déjà appliqué automatiquement via
`frontend/.cargo/config.toml`.)
- **ALSA** (Linux) : `pkg-config`, en-têtes `alsa` (`libasound2-dev` / `alsa-lib`).
- Sur Linux, les bibliothèques graphiques usuelles (X11 / Wayland, pilotes OpenGL/Vulkan)
sont nécessaires pour l'affichage.
- Le backend doit tourner (voir `../backend`). Par défaut il écoute sur
`http://localhost:3000`.
- **Modèles de voix** (voir [Voix](#voix-stt--tts-local)) : un modèle Whisper `.bin` et une
voix Piper `.onnx` + `.json`. Sans eux, l'app démarre et fonctionne en texte seul.
## Démarrage
```bash
cd frontend
cargo run # mode développement
# ou
cargo build --release
./target/release/jarvise-frontend
```
## Configuration
Tout est surchargeable par variable d'environnement :
| Variable | Défaut | Rôle |
| ---------------------- | ------------------------ | ----------------------------------------------- |
| `JARVIS_BACKEND_URL` | `http://localhost:3000` | URL de base du backend |
| `JARVIS_MODEL` | `llama3.2` | Modèle Ollama envoyé dans le body |
| `WHISPER_MODEL` | — | Chemin du modèle Whisper `.bin` (STT) |
| `PIPER_MODEL` | — | Chemin du modèle Piper `.onnx` (TTS) |
| `PIPER_CONFIG` | — | Chemin de la config Piper `.json` (TTS) |
| `JARVIS_STT_LANGUAGE` | `fr` | Langue de transcription (code whisper) |
| `JARVIS_SPEAK` | désactivé | `1`/`true` : lire les réponses à voix haute |
| `LIBCLANG_PATH` | — | (build) dossier contenant `libclang.so` |
L'URL du backend et le modèle sont aussi modifiables **dans l'interface** (champ
« Backend » sur l'écran de connexion, champ « Modèle » dans la barre du haut), ainsi que
la lecture vocale (case « 🔊 Voix »).
## Fonctionnement
### Connexion et cache du token
1. Au lancement, le client lit le token JWT mis en cache (via la persistance d'eframe,
stockée dans le dossier de configuration de l'OS).
2. Si un token existe, il est **validé** auprès de `GET /api/auth/me`. S'il est encore
valide, l'application ouvre directement le chat ; sinon elle revient à l'écran de
connexion.
3. Sinon, l'écran de connexion (**email + mot de passe**) envoie
`POST /api/auth/login` et met le token en cache pour les lancements suivants.
4. « Déconnexion » efface le token en cache.
### Streaming SSE
Le client envoie `POST /api/chat` avec :
```json
{
"model": "llama3.2",
"messages": [{ "role": "user", "content": "Salut Jarvis" }]
}
```
et lit la réponse `text/event-stream` avec `eventsource-stream` :
| Ligne reçue | Traitement |
| ------------------------------- | ------------------------------------------------- |
| `data: {"content": "mot"}` | ajouté à la bulle assistant (effet machine à écrire) |
| `data: [DONE]` | fin de génération, bouton « Envoyer » réactivé |
| `data: {"error": "..."}` | message d'erreur affiché dans la GUI |
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.
### Annulation
Le bouton « Stopper » annule un `CancellationToken` (tokio-util) : la tâche de streaming
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).
### Gestion des erreurs
- Backend injoignable → message réseau affiché dans la GUI.
- Statut HTTP non-200 (401, 502…) → message `{ error }` du backend affiché.
- Erreur en cours de flux → affichée via `data: {"error": ...}`.
## Voix (STT / TTS local)
La voix est traitée **entièrement côté client** : rien d'audio ne transite vers le backend.
- **STT** — bouton **push-to-talk** `🎤` dans la barre de saisie : maintiens pour parler,
relâche pour transcrire. Le micro est capturé via `cpal`, rééchantillonné à 16 kHz mono si
besoin, puis transcrit par **whisper.cpp** (`whisper-rs`). Le texte obtenu est placé dans le
champ puis envoyé automatiquement.
- **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).
- 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.
### Modèles
```bash
# Exemple : modèle Whisper (multilingue, léger)
export WHISPER_MODEL="$PWD/models/ggml-small.bin"
# Exemple : voix Piper française (.onnx + .json du même dossier)
export PIPER_MODEL="$PWD/models/fr_FR-siwis-medium.onnx"
export PIPER_CONFIG="$PWD/models/fr_FR-siwis-medium.onnx.json"
```
Les modèles Whisper (GGML) et les voix Piper (`.onnx`) s'obtiennent sur leurs dépôts
respectifs (whisper.cpp / Piper). Si `WHISPER_MODEL` ou `PIPER_MODEL`/`PIPER_CONFIG`
sont absents, le bouton micro / la case « Voix » sont désactivés et l'app reste utilisable
en texte.
## Architecture du code
```
src/
main.rs # bootstrap eframe + fenêtre (binaire)
lib.rs # surface de la librairie (rend les modules testables)
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
voice/
mod.rs # module voix
audio.rs # micro (cpal) + lecture haut-parleur + rééchantillonnage
stt.rs # speech-to-text embarqué (whisper-rs)
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
```
## Tests
```bash
cargo test
```
- **Unitaires** : rééchantillonnage audio (identité, sous-échantillonnage, signal constant) et
détection de la présence des modèles de voix.
- **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.
## Dépannage
- **`Unable to find libclang` / `espeak-rs-sys build failed`** : `libclang` n'est pas installé.
Faire `sudo pacman -S clang` (voir [Prérequis](#prérequis)) puis relancer `cargo run`.
- **`'stddef.h' file not found`** (bindgen) : le `libclang` fourni n'a pas ses en-têtes
internes ; installer le paquet `clang` complet, ou définir
`BINDGEN_EXTRA_CLANG_ARGS="-I$(gcc -print-file-name=include)"`.
- **`Connection refused` au login** : le backend n'est pas lancé, ou `JARVIS_BACKEND_URL`
ne pointe pas dessus.
- **`401`** : token expiré — reconnecte-toi (le client repasse automatiquement à l'écran
de connexion).
- **`502` en lançant un message** : Ollama est injoignable côté backend
(`OLLAMA_URL`, et le modèle doit être téléchargé).
- **Échec de build sur Linux** : installer les dépendances système de egui/winit
(ex. `libxkbcommon`, `libwayland-dev`, `libx11-dev` selon la distribution).
- **Micro/haut-parleur indisponible** : vérifier les permissions (accès micro) et qu'un
périphérique audio est présent ; l'app affiche l'erreur sans planter.
- **« STT non configuré »** : `WHISPER_MODEL` pointe vers un fichier inexistant.
- **« TTS non configuré »** : renseigner `PIPER_MODEL` et `PIPER_CONFIG`.
+271
View File
@@ -0,0 +1,271 @@
//! 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.
use std::fmt;
use eventsource_stream::Eventsource;
use futures_util::StreamExt;
use reqwest::StatusCode;
use tokio_util::sync::CancellationToken;
use crate::model::{
ChatMessage, ChatRequest, LoginRequest, LoginResponse, MeResponse, PublicUser, StreamData,
};
/// Errors surfaced to the GUI (which displays them as-is).
#[derive(Debug)]
pub enum ApiError {
/// Transport-level failure: connection refused, DNS, TLS, timeout…
Network(String),
/// The backend answered with a non-success HTTP status.
Status { status: StatusCode, message: String },
/// A successful response could not be decoded as JSON.
Decode(String),
}
impl fmt::Display for ApiError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ApiError::Network(message) => write!(f, "Réseau : {message}"),
ApiError::Status { status, message } => {
write!(f, "Erreur backend (HTTP {}) : {message}", status.as_u16())
}
ApiError::Decode(message) => write!(f, "Réponse illisible : {message}"),
}
}
}
impl std::error::Error for ApiError {}
/// A single meaningful event extracted from the SSE stream.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum StreamEvent {
/// A text fragment produced by the model.
Delta(String),
/// The `[DONE]` sentinel: generation finished cleanly.
Done,
/// An inline error reported by the backend (`data: {"error":...}`).
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
/// spawned task own a copy.
#[derive(Clone)]
pub struct ApiClient {
http: reqwest::Client,
base_url: String,
token: Option<String>,
}
impl ApiClient {
/// Builds a client. The token is injected later, once the user has logged in
/// or a cached one has been restored.
pub fn new(base_url: impl Into<String>) -> Self {
let http = reqwest::Client::builder()
.user_agent(concat!("jarvise-frontend/", env!("CARGO_PKG_VERSION")))
.build()
.expect("failed to build the HTTP client");
Self {
http,
base_url: normalize_base_url(base_url.into()),
token: None,
}
}
pub fn base_url(&self) -> &str {
&self.base_url
}
pub fn set_base_url(&mut self, base_url: impl Into<String>) {
self.base_url = normalize_base_url(base_url.into());
}
pub fn set_token(&mut self, token: Option<String>) {
self.token = token;
}
/// Logs in and returns the JWT together with the user profile.
pub async fn login(&self, email: &str, password: &str) -> Result<LoginResponse, ApiError> {
let response = self
.http
.post(self.url("/api/auth/login"))
.json(&LoginRequest {
email: email.to_string(),
password: password.to_string(),
})
.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::<LoginResponse>()
.await
.map_err(|error| ApiError::Decode(error.to_string()))
}
/// 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<PublicUser, ApiError> {
let token = self
.token
.clone()
.ok_or_else(|| ApiError::Network("aucun token enregistré".to_string()))?;
let response = 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,
});
}
let body = response
.json::<MeResponse>()
.await
.map_err(|error| ApiError::Decode(error.to_string()))?;
Ok(body.user)
}
/// Streams a chat completion.
///
/// `on_event` is called for every fragment as it arrives; it runs on the
/// worker thread, so it must stay cheap (the app only pushes into a channel
/// and asks the GUI to repaint). The future resolves once the backend sends
/// `[DONE]`, reports an error, or the stream ends. Cancelling `cancel` makes
/// it return promptly, dropping the HTTP connection so Ollama stops working.
pub async fn stream_chat<F>(
&self,
model: &str,
messages: Vec<ChatMessage>,
cancel: CancellationToken,
mut on_event: F,
) -> Result<(), ApiError>
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)
.json(&ChatRequest {
model: model.to_string(),
messages,
});
// 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! {
_ = cancel.cancelled() => return Ok(()),
result = request.send() => result.map_err(|error| ApiError::Network(error.to_string()))?,
};
// A non-200 before the stream starts is a plain JSON error (e.g. 401 or
// 502 when Ollama is down), not an SSE one.
let status = response.status();
if !status.is_success() {
return Err(ApiError::Status {
status,
message: read_error_message(response).await,
});
}
let mut stream = response.bytes_stream().eventsource();
loop {
// `select!` wakes up immediately on cancellation even if no new byte
// has arrived yet, so « Stopper » feels instant.
tokio::select! {
_ = cancel.cancelled() => return Ok(()),
item = stream.next() => {
match item {
None => return Ok(()),
Some(Err(error)) => {
return Err(ApiError::Network(format!("flux interrompu : {error}")));
}
Some(Ok(event)) => {
let data = event.data;
let data = data.trim();
if data.is_empty() {
continue;
}
if data == "[DONE]" {
on_event(StreamEvent::Done);
return Ok(());
}
match serde_json::from_str::<StreamData>(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,
}
}
}
}
}
}
}
fn url(&self, path: &str) -> String {
format!("{}{}", self.base_url, path)
}
}
fn normalize_base_url(url: String) -> String {
url.trim().trim_end_matches('/').to_string()
}
/// Extracts a readable message from an error response: the backend's `{ error }`
/// field when present, the raw body otherwise.
async fn read_error_message(response: reqwest::Response) -> String {
let status = response.status();
let text = response.text().await.unwrap_or_default();
if let Ok(value) = serde_json::from_str::<serde_json::Value>(&text) {
if let Some(message) = value.get("error").and_then(|value| value.as_str()) {
return message.to_string();
}
}
if text.trim().is_empty() {
format!("HTTP {}", status.as_u16())
} else {
text
}
}
+665
View File
@@ -0,0 +1,665 @@
//! The egui application: a login screen (with a cached token) and a streaming
//! chat window.
//!
//! Threading model: the UI runs on the main thread and must never block. Every
//! network operation is `spawn`ed on a persistent Tokio runtime and reports back
//! through a channel; each report also calls `Context::request_repaint()` so the
//! "typewriter" effect keeps flowing at full frame rate.
use std::sync::mpsc::{Receiver, Sender};
use eframe::egui;
use serde::{Deserialize, Serialize};
use tokio::runtime::Runtime;
use tokio_util::sync::CancellationToken;
use crate::api::{ApiClient, StreamEvent};
use crate::config::AppConfig;
use crate::model::{ChatMessage, PublicUser};
use crate::voice::audio::Recorder;
use crate::voice::engine::{self, VoiceConfig, VoiceEvent, VoiceHandle};
/// Key under which the state is persisted (token, email, model, backend URL).
const STORAGE_KEY: &str = "jarvise-session";
/// Messages sent from background tasks to the UI thread.
enum UiEvent {
/// Login succeeded: a token and the user profile are available.
AuthOk { token: String, user: PublicUser },
/// Login failed, with a message ready to display.
AuthError(String),
/// The cached token is still valid.
TokenValid(PublicUser),
/// The cached token is stale: fall back to the login screen.
TokenInvalid,
/// A text fragment to append to the current answer.
Delta(String),
/// The stream finished cleanly.
Done,
/// The stream failed (network, HTTP or inline SSE error).
StreamError(String),
/// Speech recognition produced a transcript.
Transcribed(String),
/// A voice job (STT or TTS) failed.
VoiceError(String),
}
/// What gets written to disk between runs (via eframe's persistence).
#[derive(Serialize, Deserialize, Default)]
struct Persisted {
token: Option<String>,
email: String,
model: String,
backend_url: String,
}
/// Cloneable bridge used by background tasks to talk to the UI: pushes an event
/// and asks egui to repaint.
#[derive(Clone)]
struct Notifier {
tx: Sender<UiEvent>,
ctx: egui::Context,
}
impl Notifier {
fn send(&self, event: UiEvent) {
// The receiver only disappears when the app is dropped; ignoring the
// error avoids a panic during shutdown.
let _ = self.tx.send(event);
self.ctx.request_repaint();
}
}
pub struct JarviseApp {
runtime: Runtime,
api: ApiClient,
tx: Sender<UiEvent>,
rx: Receiver<UiEvent>,
// Authentication.
backend_url: String,
token: Option<String>,
user: Option<PublicUser>,
login_email: String,
login_password: String,
login_error: Option<String>,
login_busy: bool,
// Chat.
model: String,
messages: Vec<ChatMessage>,
input: String,
streaming: bool,
cancel: Option<CancellationToken>,
error: Option<String>,
// Voice: local speech-to-text and text-to-speech.
voice: VoiceHandle,
speak_replies: bool,
recorder: Option<Recorder>,
voice_status: Option<String>,
pending_transcript: Option<String>,
}
impl JarviseApp {
pub fn new(cc: &eframe::CreationContext<'_>, config: AppConfig) -> Self {
let persisted: Persisted = cc
.storage
.and_then(|storage| eframe::get_value(storage, STORAGE_KEY))
.unwrap_or_default();
let backend_url = if persisted.backend_url.trim().is_empty() {
config.backend_url.clone()
} else {
persisted.backend_url.clone()
};
let model = if persisted.model.trim().is_empty() {
config.default_model.clone()
} else {
persisted.model.clone()
};
let mut api = ApiClient::new(backend_url);
api.set_token(persisted.token.clone());
let backend_url = api.base_url().to_string();
let (tx, rx) = std::sync::mpsc::channel();
let runtime = tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()
.expect("failed to start the Tokio runtime");
// Voice engines run on their own thread; their results flow through the
// same UI channel as the network events.
let voice_config = VoiceConfig::from_env();
let voice_notifier = Notifier {
tx: tx.clone(),
ctx: cc.egui_ctx.clone(),
};
let voice = engine::spawn(voice_config, move |event| {
voice_notifier.send(match event {
VoiceEvent::Transcribed(text) => UiEvent::Transcribed(text),
VoiceEvent::TranscriptionError(message) | VoiceEvent::SpeechError(message) => {
UiEvent::VoiceError(message)
}
});
});
let speak_replies = matches!(
std::env::var("JARVIS_SPEAK").ok().as_deref(),
Some("1") | Some("true")
);
let app = Self {
runtime,
api,
tx,
rx,
backend_url,
token: persisted.token.clone(),
user: None,
login_email: persisted.email.clone(),
login_password: String::new(),
login_error: None,
login_busy: false,
model,
messages: Vec::new(),
input: String::new(),
streaming: false,
cancel: None,
error: None,
voice,
speak_replies,
recorder: None,
voice_status: None,
pending_transcript: None,
};
// If a token was restored, validate it in the background before showing
// the chat, so an expired token falls back to the login screen.
if app.token.is_some() {
app.check_token(&cc.egui_ctx);
}
app
}
fn notifier(&self, ctx: &egui::Context) -> Notifier {
Notifier {
tx: self.tx.clone(),
ctx: ctx.clone(),
}
}
/// Spawns `GET /api/auth/me` to validate the cached token.
fn check_token(&self, ctx: &egui::Context) {
let api = self.api.clone();
let notifier = self.notifier(ctx);
self.runtime.spawn(async move {
match api.me().await {
Ok(user) => notifier.send(UiEvent::TokenValid(user)),
Err(_) => notifier.send(UiEvent::TokenInvalid),
}
});
}
/// Spawns the login request.
fn start_login(&mut self, ctx: &egui::Context) {
if self.login_busy {
return;
}
self.login_busy = true;
self.login_error = None;
// The backend URL can be edited at runtime on the login screen.
self.api.set_base_url(self.backend_url.clone());
let api = self.api.clone();
let notifier = self.notifier(ctx);
let email = self.login_email.trim().to_string();
let password = self.login_password.clone();
self.runtime.spawn(async move {
match api.login(&email, &password).await {
Ok(response) => notifier.send(UiEvent::AuthOk {
token: response.token,
user: response.user,
}),
Err(error) => notifier.send(UiEvent::AuthError(error.to_string())),
}
});
}
/// Sends the current input and starts streaming the answer.
fn send_message(&mut self, ctx: &egui::Context) {
let text = self.input.trim().to_string();
if text.is_empty() || self.streaming {
return;
}
self.error = None;
self.messages.push(ChatMessage::user(text));
self.input.clear();
// The history sent to the backend ends with the user's message.
let history = self.messages.clone();
// 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_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;
if let Err(error) = result {
notifier.send(UiEvent::StreamError(error.to_string()));
}
});
}
/// Asks the in-flight stream to stop; the HTTP connection is dropped so the
/// backend can abort Ollama.
fn stop_stream(&mut self) {
if let Some(cancel) = self.cancel.take() {
cancel.cancel();
}
self.streaming = false;
}
fn logout(&mut self) {
self.stop_stream();
self.token = None;
self.user = None;
self.api.set_token(None);
self.messages.clear();
self.input.clear();
self.error = None;
self.login_password.clear();
}
/// Starts capturing the microphone (push-to-talk press).
fn start_recording(&mut self) {
if self.recorder.is_some() {
return;
}
self.error = None;
match Recorder::start() {
Ok(recorder) => {
self.recorder = Some(recorder);
self.voice_status = Some("🎙️ Enregistrement… relâche pour transcrire".to_string());
}
Err(error) => self.error = Some(error.to_string()),
}
}
/// Stops the capture and queues the transcription (push-to-talk release).
fn stop_recording(&mut self) {
let Some(recorder) = self.recorder.take() else {
return;
};
let (samples, sample_rate) = recorder.stop();
let seconds = samples.len() as f32 / sample_rate.max(1) as f32;
if seconds < 0.3 {
self.voice_status = None;
self.error = Some("Enregistrement trop court.".to_string());
return;
}
self.voice_status = Some("Transcription en cours…".to_string());
self.voice.transcribe(samples, sample_rate);
}
/// Applies every event produced since the last frame.
fn drain_events(&mut self) {
while let Ok(event) = self.rx.try_recv() {
match event {
UiEvent::AuthOk { token, user } => {
self.api.set_token(Some(token.clone()));
self.token = Some(token);
self.user = Some(user);
self.login_busy = false;
self.login_error = None;
self.login_password.clear();
}
UiEvent::AuthError(message) => {
self.login_busy = false;
self.login_error = Some(message);
}
UiEvent::TokenValid(user) => self.user = Some(user),
UiEvent::TokenInvalid => {
self.token = None;
self.user = None;
self.api.set_token(None);
}
UiEvent::Delta(text) => {
if let Some(last) = self.messages.last_mut() {
if last.role == "assistant" {
last.content.push_str(&text);
}
}
}
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.voice.speak(text);
}
}
UiEvent::StreamError(message) => {
self.error = Some(message);
self.streaming = false;
self.cancel = None;
}
UiEvent::Transcribed(text) => {
self.voice_status = None;
if text.trim().is_empty() {
self.error = Some("Aucune parole détectée.".to_string());
} else {
self.pending_transcript = Some(text);
}
}
UiEvent::VoiceError(message) => {
self.voice_status = None;
self.error = Some(message);
}
}
}
}
fn login_screen(&mut self, ui: &mut egui::Ui) {
egui::CentralPanel::default().show(ui, |ui| {
ui.add_space(70.0);
ui.vertical_centered(|ui| {
ui.heading("Jarvise");
ui.add_space(18.0);
egui::Grid::new("login-grid")
.num_columns(2)
.spacing([10.0, 10.0])
.show(ui, |ui| {
ui.label("Backend");
ui.add(
egui::TextEdit::singleline(&mut self.backend_url)
.desired_width(240.0)
.hint_text("http://localhost:3000"),
);
ui.end_row();
ui.label("Email");
ui.add(
egui::TextEdit::singleline(&mut self.login_email)
.desired_width(240.0)
.hint_text("tony@stark.com"),
);
ui.end_row();
ui.label("Mot de passe");
let password = ui.add(
egui::TextEdit::singleline(&mut self.login_password)
.password(true)
.desired_width(240.0),
);
ui.end_row();
// Enter anywhere confirms the form.
if password.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter))
{
self.start_login(ui.ctx());
}
});
ui.add_space(14.0);
let can_submit = !self.login_busy
&& !self.login_email.trim().is_empty()
&& !self.login_password.is_empty();
ui.horizontal(|ui| {
// Keep the button roughly centred despite the horizontal layout.
ui.add_space(ui.available_width() / 2.0 - 70.0);
if ui
.add_enabled(can_submit, egui::Button::new("Se connecter"))
.clicked()
{
self.start_login(ui.ctx());
}
if self.login_busy {
ui.spinner();
}
});
if let Some(error) = &self.login_error {
ui.add_space(10.0);
ui.colored_label(egui::Color32::from_rgb(0xff, 0x6b, 0x6b), error);
}
});
});
}
fn chat_screen(&mut self, ui: &mut egui::Ui) {
egui::Panel::top("top-bar").show(ui, |ui| {
ui.add_space(2.0);
ui.horizontal(|ui| {
ui.heading("Jarvise");
ui.separator();
ui.label("Modèle :");
ui.add(
egui::TextEdit::singleline(&mut self.model)
.desired_width(150.0)
.hint_text("llama3.2"),
);
ui.separator();
if let Some(user) = &self.user {
ui.label(user.display_name());
}
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();
}
if ui.button("Effacer").clicked() {
self.stop_stream();
self.messages.clear();
self.error = None;
}
});
});
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();
}
} 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);
});
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.");
});
}
for message in &self.messages {
render_bubble(ui, message);
ui.add_space(6.0);
}
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();
// A finished transcription is placed in the input then sent as-is.
if let Some(text) = self.pending_transcript.take() {
self.input = text;
self.send_message(ui.ctx());
}
if self.token.is_none() {
self.login_screen(ui);
} else if self.user.is_none() {
// The cached token is being validated.
egui::CentralPanel::default().show(ui, |ui| {
ui.vertical_centered(|ui| {
ui.add_space(120.0);
ui.spinner();
ui.add_space(8.0);
ui.label("Connexion à Jarvis…");
});
});
} else {
self.chat_screen(ui);
}
}
fn save(&mut self, storage: &mut dyn eframe::Storage) {
let persisted = Persisted {
token: self.token.clone(),
email: self.login_email.clone(),
model: self.model.clone(),
backend_url: self.backend_url.clone(),
};
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)
} else {
egui::Layout::left_to_right(egui::Align::TOP)
};
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));
});
});
}
+29
View File
@@ -0,0 +1,29 @@
//! Runtime configuration, read from environment variables with sensible
//! defaults so the app works out of the box against a local backend.
/// Values needed to reach the backend. Everything is overridable via env vars:
/// `JARVIS_BACKEND_URL` and `JARVIS_MODEL`.
#[derive(Clone)]
pub struct AppConfig {
pub backend_url: String,
pub default_model: String,
}
impl AppConfig {
pub fn from_env() -> Self {
let backend_url = std::env::var("JARVIS_BACKEND_URL")
.ok()
.filter(|value| !value.trim().is_empty())
.unwrap_or_else(|| "http://localhost:3000".to_string());
let default_model = std::env::var("JARVIS_MODEL")
.ok()
.filter(|value| !value.trim().is_empty())
.unwrap_or_else(|| "qwen2.5:3b".to_string());
Self {
backend_url: backend_url.trim_end_matches('/').to_string(),
default_model,
}
}
}
+11
View File
@@ -0,0 +1,11 @@
//! Library surface of the Jarvise desktop client.
//!
//! The modules live in a library (rather than only in the binary) so the API
//! layer — authentication and SSE streaming — can be exercised by integration
//! tests without booting a window.
pub mod api;
pub mod app;
pub mod config;
pub mod model;
pub mod voice;
+34
View File
@@ -0,0 +1,34 @@
//! Jarvis desktop client.
//!
//! A native egui application that logs in to the Jarvise backend and streams the
//! Ollama answer token by token over Server-Sent Events.
//!
//! Configuration is read from the environment:
//! * `JARVIS_BACKEND_URL` (default `http://localhost:3000`)
//! * `JARVIS_MODEL` (default `llama3.2`)
//!
//! Run with `cargo run` (dev) or `cargo build --release` then the produced binary.
use eframe::egui;
use jarvise_frontend::app::JarviseApp;
use jarvise_frontend::config::AppConfig;
fn main() -> eframe::Result {
let config = AppConfig::from_env();
let options = eframe::NativeOptions {
viewport: egui::ViewportBuilder::default()
.with_inner_size([900.0, 680.0])
.with_min_inner_size([560.0, 420.0])
.with_title("Jarvise"),
..Default::default()
};
let app_config = config.clone();
eframe::run_native(
"Jarvise",
options,
Box::new(move |cc| Ok(Box::new(JarviseApp::new(cc, app_config)))),
)
}
+86
View File
@@ -0,0 +1,86 @@
//! Data structures exchanged with the Jarvise backend.
//!
//! These mirror the JSON contracts of `POST /api/chat` and the auth routes, so
//! that `serde` can (de)serialize them without any manual glue.
use serde::{Deserialize, Serialize};
/// A single conversation message, as expected in the `messages` array.
#[derive(Serialize, Deserialize, Clone, PartialEq, Eq)]
pub struct ChatMessage {
pub role: String,
pub content: String,
}
impl ChatMessage {
pub fn user(content: impl Into<String>) -> Self {
Self {
role: "user".to_string(),
content: content.into(),
}
}
pub fn assistant(content: impl Into<String>) -> Self {
Self {
role: "assistant".to_string(),
content: content.into(),
}
}
pub fn is_user(&self) -> bool {
self.role == "user"
}
}
/// Body sent to `POST /api/chat`.
#[derive(Serialize)]
pub struct ChatRequest {
pub model: String,
pub messages: Vec<ChatMessage>,
}
/// Payload of a `data: {...}` SSE line.
///
/// Both fields are optional: an event carries either a text fragment
/// (`content`) or an error description (`error`).
#[derive(Deserialize)]
pub struct StreamData {
pub content: Option<String>,
pub error: Option<String>,
}
/// Body sent to `POST /api/auth/login`.
#[derive(Serialize)]
pub struct LoginRequest {
pub email: String,
pub password: String,
}
/// Response of `POST /api/auth/login`.
#[derive(Deserialize, Clone)]
pub struct LoginResponse {
pub token: String,
pub user: PublicUser,
}
/// Response of `GET /api/auth/me`.
#[derive(Deserialize)]
pub struct MeResponse {
pub user: PublicUser,
}
/// Public user object returned by the backend. Unknown fields (e.g. `id`) are
/// ignored by `serde`, so only what the UI needs is kept.
#[derive(Deserialize, Clone)]
pub struct PublicUser {
pub email: String,
#[serde(default)]
pub name: Option<String>,
}
impl PublicUser {
/// Human-friendly label shown in the top bar.
pub fn display_name(&self) -> String {
self.name.clone().unwrap_or_else(|| self.email.clone())
}
}
+311
View File
@@ -0,0 +1,311 @@
//! Audio input (microphone) and output (speaker) through `cpal`.
//!
//! Callbacks run on the audio thread and only push/pull samples to/from a shared
//! buffer, so nothing here blocks for long.
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
use cpal::{FromSample, Sample, SampleFormat, SizedSample, StreamConfig};
/// Anything that can go wrong when opening or using an audio device.
#[derive(Debug)]
pub enum AudioError {
NoInputDevice,
NoOutputDevice,
Config(String),
Build(String),
Play(String),
}
impl std::fmt::Display for AudioError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
AudioError::NoInputDevice => write!(f, "aucun micro détecté"),
AudioError::NoOutputDevice => write!(f, "aucun haut-parleur détecté"),
AudioError::Config(message) => write!(f, "configuration audio : {message}"),
AudioError::Build(message) => write!(f, "ouverture du flux audio : {message}"),
AudioError::Play(message) => write!(f, "lecture audio : {message}"),
}
}
}
impl std::error::Error for AudioError {}
/// An active microphone recording. Drop it (via [`Recorder::stop`]) to end the
/// capture; the samples are mono `f32` at [`Recorder::sample_rate`].
pub struct Recorder {
stream: cpal::Stream,
sink: Arc<Mutex<Vec<f32>>>,
sample_rate: u32,
}
impl Recorder {
/// Opens the default microphone and starts capturing.
pub fn start() -> Result<Self, AudioError> {
let host = cpal::default_host();
let device = host
.default_input_device()
.ok_or(AudioError::NoInputDevice)?;
let supported = device
.default_input_config()
.map_err(|error| AudioError::Config(error.to_string()))?;
let sample_rate = supported.sample_rate();
let format = supported.sample_format();
let config = supported.config();
let sink = Arc::new(Mutex::new(Vec::new()));
let stream = build_input(&device, config, format, sink.clone())?;
stream
.play()
.map_err(|error| AudioError::Play(error.to_string()))?;
Ok(Self {
stream,
sink,
sample_rate,
})
}
/// Stops the capture and returns the recorded mono samples and their rate.
pub fn stop(self) -> (Vec<f32>, u32) {
drop(self.stream);
let samples = self
.sink
.lock()
.map(|guard| guard.clone())
.unwrap_or_default();
(samples, self.sample_rate)
}
}
/// Plays `samples` (mono `f32`) at `sample_rate`, blocking until playback ends.
///
/// Callers run this on a background thread (the voice engine), never on the GUI
/// thread.
pub fn play_blocking(samples: &[f32], sample_rate: u32) -> Result<(), AudioError> {
if samples.is_empty() {
return Ok(());
}
let host = cpal::default_host();
let device = host
.default_output_device()
.ok_or(AudioError::NoOutputDevice)?;
let supported = device
.default_output_config()
.map_err(|error| AudioError::Config(error.to_string()))?;
let output_rate = supported.sample_rate();
let format = supported.sample_format();
let config = supported.config();
// Resample once so the callback is a simple copy.
let source = Arc::new(resample_linear(samples, sample_rate, output_rate));
let position = Arc::new(AtomicUsize::new(0));
let finished = Arc::new(AtomicBool::new(false));
let stream = build_output(
&device,
config,
format,
source,
position.clone(),
finished.clone(),
)?;
stream
.play()
.map_err(|error| AudioError::Play(error.to_string()))?;
while !finished.load(Ordering::SeqCst) {
std::thread::sleep(Duration::from_millis(20));
}
// Give the device a moment to flush the last buffer.
std::thread::sleep(Duration::from_millis(80));
drop(stream);
Ok(())
}
/// Linear resampling between two sample rates (good enough for speech).
pub fn resample_linear(input: &[f32], source_rate: u32, target_rate: u32) -> Vec<f32> {
if input.is_empty() || source_rate == target_rate || source_rate == 0 {
return input.to_vec();
}
let ratio = source_rate as f64 / target_rate as f64;
let out_len = ((input.len() as f64) / ratio).max(1.0) as usize;
let last = input.len() - 1;
(0..out_len)
.map(|i| {
let src = i as f64 * ratio;
let index = src.floor() as usize;
let frac = (src - index as f64) as f32;
let a = input[index.min(last)];
let b = input[(index + 1).min(last)];
a + (b - a) * frac
})
.collect()
}
fn build_input(
device: &cpal::Device,
config: StreamConfig,
format: SampleFormat,
sink: Arc<Mutex<Vec<f32>>>,
) -> Result<cpal::Stream, AudioError> {
match format {
SampleFormat::F32 => input_stream::<f32>(device, config, sink),
SampleFormat::I16 => input_stream::<i16>(device, config, sink),
SampleFormat::U16 => input_stream::<u16>(device, config, sink),
SampleFormat::I32 => input_stream::<i32>(device, config, sink),
other => Err(AudioError::Config(format!(
"format d'entrée non pris en charge : {other:?}"
))),
}
}
fn input_stream<T>(
device: &cpal::Device,
config: StreamConfig,
sink: Arc<Mutex<Vec<f32>>>,
) -> Result<cpal::Stream, AudioError>
where
T: SizedSample + 'static,
f32: FromSample<T>,
{
let channels = config.channels as usize;
device
.build_input_stream::<T, _, _>(
config,
move |data, _| push_mono::<T>(data, channels, &sink),
|_error| {},
None,
)
.map_err(|error| AudioError::Build(error.to_string()))
}
fn push_mono<T>(data: &[T], channels: usize, sink: &Arc<Mutex<Vec<f32>>>)
where
T: Sample,
f32: FromSample<T>,
{
if channels == 0 {
return;
}
let mut out = match sink.lock() {
Ok(guard) => guard,
Err(poisoned) => poisoned.into_inner(),
};
for frame in data.chunks(channels) {
let sum: f32 = frame.iter().map(|sample| sample.to_sample::<f32>()).sum();
out.push(sum / channels as f32);
}
}
fn build_output(
device: &cpal::Device,
config: StreamConfig,
format: SampleFormat,
source: Arc<Vec<f32>>,
position: Arc<AtomicUsize>,
finished: Arc<AtomicBool>,
) -> Result<cpal::Stream, AudioError> {
match format {
SampleFormat::F32 => output_stream::<f32>(device, config, source, position, finished),
SampleFormat::I16 => output_stream::<i16>(device, config, source, position, finished),
SampleFormat::U16 => output_stream::<u16>(device, config, source, position, finished),
SampleFormat::I32 => output_stream::<i32>(device, config, source, position, finished),
other => Err(AudioError::Config(format!(
"format de sortie non pris en charge : {other:?}"
))),
}
}
fn output_stream<T>(
device: &cpal::Device,
config: StreamConfig,
source: Arc<Vec<f32>>,
position: Arc<AtomicUsize>,
finished: Arc<AtomicBool>,
) -> Result<cpal::Stream, AudioError>
where
T: SizedSample + 'static,
T: FromSample<f32>,
{
let channels = config.channels as usize;
device
.build_output_stream::<T, _, _>(
config,
move |data, _| fill_from_source::<T>(data, channels, &source, &position, &finished),
|_error| {},
None,
)
.map_err(|error| AudioError::Build(error.to_string()))
}
fn fill_from_source<T>(
output: &mut [T],
channels: usize,
source: &Arc<Vec<f32>>,
position: &Arc<AtomicUsize>,
finished: &Arc<AtomicBool>,
) where
T: Sample,
T: FromSample<f32>,
{
if channels == 0 {
return;
}
let len = source.len();
let mut index = position.load(Ordering::Relaxed);
for frame in output.chunks_mut(channels) {
let value = if index < len { source[index] } else { 0.0 };
let sample = T::from_sample(value);
for out in frame.iter_mut() {
*out = sample;
}
if index < len {
index += 1;
}
}
position.store(index, Ordering::Relaxed);
if index >= len {
finished.store(true, Ordering::SeqCst);
}
}
#[cfg(test)]
mod tests {
use super::resample_linear;
#[test]
fn resample_is_identity_at_the_same_rate() {
let input = vec![0.1, -0.2, 0.3];
assert_eq!(resample_linear(&input, 16_000, 16_000), input);
}
#[test]
fn resample_downsamples_to_the_expected_length() {
let input: Vec<f32> = (0..48_000).map(|i| (i as f32 / 48_000.0).sin()).collect();
let output = resample_linear(&input, 48_000, 16_000);
assert_eq!(output.len(), 16_000);
}
#[test]
fn resample_preserves_constant_signal() {
let input = vec![0.5_f32; 44_100];
let output = resample_linear(&input, 44_100, 16_000);
assert!(output.iter().all(|sample| (sample - 0.5).abs() < 1e-3));
}
#[test]
fn resample_handles_empty_input() {
assert!(resample_linear(&[], 44_100, 16_000).is_empty());
}
}
+219
View File
@@ -0,0 +1,219 @@
//! The voice engine: a dedicated thread owning the (heavy) whisper and Piper
//! models, so loading a model or running inference never freezes the GUI.
//!
//! The GUI sends commands through [`VoiceHandle`] and receives results as
//! [`VoiceEvent`]s.
use std::path::{Path, PathBuf};
use std::sync::mpsc::{channel, Sender};
use super::audio;
use super::stt::WhisperStt;
use super::tts::PiperTts;
/// Paths to the local voice models, read from the environment:
/// `WHISPER_MODEL`, `PIPER_MODEL`, `PIPER_CONFIG`, `JARVIS_STT_LANGUAGE`.
#[derive(Clone, Default)]
pub struct VoiceConfig {
pub whisper_model: Option<PathBuf>,
pub piper_model: Option<PathBuf>,
pub piper_config: Option<PathBuf>,
pub language: String,
}
impl VoiceConfig {
pub fn from_env() -> Self {
let path = |key: &str| {
std::env::var(key)
.ok()
.filter(|value| !value.trim().is_empty())
.map(PathBuf::from)
};
let language = std::env::var("JARVIS_STT_LANGUAGE")
.ok()
.filter(|value| !value.trim().is_empty())
.unwrap_or_else(|| "fr".to_string());
Self {
whisper_model: path("WHISPER_MODEL"),
piper_model: path("PIPER_MODEL"),
piper_config: path("PIPER_CONFIG"),
language,
}
}
/// Whether a usable speech-to-text model is configured.
pub fn stt_ready(&self) -> bool {
self.whisper_model.as_deref().is_some_and(is_file)
}
/// Whether a usable text-to-speech voice is configured.
pub fn tts_ready(&self) -> bool {
self.piper_model.as_deref().is_some_and(is_file)
&& self.piper_config.as_deref().is_some_and(is_file)
}
}
fn is_file(path: &Path) -> bool {
path.is_file()
}
/// Result of a voice job, delivered back to the GUI thread.
#[derive(Debug, Clone)]
pub enum VoiceEvent {
Transcribed(String),
TranscriptionError(String),
SpeechError(String),
}
enum VoiceCommand {
Transcribe { samples: Vec<f32>, sample_rate: u32 },
Speak { text: String },
}
/// GUI-side handle to the voice engine. Cheap to clone (it holds a channel).
#[derive(Clone)]
pub struct VoiceHandle {
tx: Sender<VoiceCommand>,
stt_ready: bool,
tts_ready: bool,
}
impl VoiceHandle {
pub fn stt_ready(&self) -> bool {
self.stt_ready
}
pub fn tts_ready(&self) -> bool {
self.tts_ready
}
/// Queues a transcription job (safe to call from the GUI thread).
pub fn transcribe(&self, samples: Vec<f32>, sample_rate: u32) {
let _ = self.tx.send(VoiceCommand::Transcribe {
samples,
sample_rate,
});
}
/// Queues a synthesis + playback job.
pub fn speak(&self, text: String) {
let _ = self.tx.send(VoiceCommand::Speak { text });
}
}
/// Starts the voice thread. `on_event` is invoked from that thread for every
/// result; the app wraps it to push into its UI channel and repaint.
pub fn spawn<F>(config: VoiceConfig, on_event: F) -> VoiceHandle
where
F: Fn(VoiceEvent) + Send + 'static,
{
let (tx, rx) = channel::<VoiceCommand>();
let worker_config = config.clone();
std::thread::Builder::new()
.name("jarvise-voice".to_string())
.spawn(move || {
// Models are loaded lazily on first use and kept for later jobs.
let mut stt: Option<WhisperStt> = None;
let mut tts: Option<PiperTts> = None;
while let Ok(command) = rx.recv() {
match command {
VoiceCommand::Transcribe {
samples,
sample_rate,
} => {
let Some(model) = worker_config.whisper_model.as_deref() else {
on_event(VoiceEvent::TranscriptionError(
"Whisper non configuré (variable WHISPER_MODEL).".to_string(),
));
continue;
};
if stt.is_none() {
match WhisperStt::load(model) {
Ok(engine) => stt = Some(engine),
Err(error) => {
on_event(VoiceEvent::TranscriptionError(error.to_string()));
continue;
}
}
}
match stt
.as_ref()
.expect("stt initialised above")
.transcribe(&samples, sample_rate, &worker_config.language)
{
Ok(text) => on_event(VoiceEvent::Transcribed(text)),
Err(error) => {
on_event(VoiceEvent::TranscriptionError(error.to_string()))
}
}
}
VoiceCommand::Speak { text } => {
let (Some(model), Some(config_path)) = (
worker_config.piper_model.as_deref(),
worker_config.piper_config.as_deref(),
) else {
on_event(VoiceEvent::SpeechError(
"Piper non configuré (variables PIPER_MODEL / PIPER_CONFIG)."
.to_string(),
));
continue;
};
if tts.is_none() {
match PiperTts::load(model, config_path) {
Ok(engine) => tts = Some(engine),
Err(error) => {
on_event(VoiceEvent::SpeechError(error.to_string()));
continue;
}
}
}
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()));
}
}
Err(error) => on_event(VoiceEvent::SpeechError(error.to_string())),
}
}
}
}
})
.expect("failed to spawn the voice thread");
VoiceHandle {
tx,
stt_ready: config.stt_ready(),
tts_ready: config.tts_ready(),
}
}
#[cfg(test)]
mod tests {
use std::path::PathBuf;
use super::VoiceConfig;
#[test]
fn default_config_is_not_ready() {
let config = VoiceConfig::default();
assert!(!config.stt_ready());
assert!(!config.tts_ready());
}
#[test]
fn readiness_requires_existing_files() {
let config = VoiceConfig {
whisper_model: Some(PathBuf::from("/nope/absent.bin")),
piper_model: Some(PathBuf::from("/nope/absent.onnx")),
piper_config: Some(PathBuf::from("/nope/absent.json")),
language: "fr".to_string(),
};
assert!(!config.stt_ready());
assert!(!config.tts_ready());
}
}
+12
View File
@@ -0,0 +1,12 @@
//! Local voice capabilities of the "thick client".
//!
//! The backend only ever exchanges **text** (client↔backend) and **JSON**
//! (backend↔Ollama): speech-to-text and text-to-speech are performed entirely on
//! this machine, by [`audio`] (microphone/speaker), [`stt`] (whisper.cpp) and
//! [`tts`] (Piper). [`engine`] wires them together on a dedicated thread so the
//! GUI never blocks.
pub mod audio;
pub mod engine;
pub mod stt;
pub mod tts;
+92
View File
@@ -0,0 +1,92 @@
//! Speech-to-text using the embedded whisper.cpp (via `whisper-rs`).
//!
//! Whisper expects 16 kHz mono `f32` audio, so the incoming samples are
//! resampled here when needed.
use std::path::Path;
use whisper_rs::{FullParams, SamplingStrategy, WhisperContext, WhisperContextParameters};
use super::audio::resample_linear;
/// Sample rate whisper.cpp works with.
pub const WHISPER_SAMPLE_RATE: u32 = 16_000;
#[derive(Debug)]
pub struct SttError(pub String);
impl std::fmt::Display for SttError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
impl std::error::Error for SttError {}
/// Loaded whisper model, reused across transcriptions.
pub struct WhisperStt {
context: WhisperContext,
threads: i32,
}
impl WhisperStt {
/// Loads a GGML model (`.bin`) from disk. This can take a moment, hence it
/// runs on the voice thread and is cached afterwards.
pub fn load(model_path: &Path) -> Result<Self, SttError> {
let path = model_path
.to_str()
.ok_or_else(|| SttError("chemin de modèle Whisper invalide".to_string()))?;
let context = WhisperContext::new_with_params(path, WhisperContextParameters::default())
.map_err(|error| SttError(format!("chargement du modèle Whisper : {error}")))?;
let threads = std::thread::available_parallelism()
.map(|count| count.get() as i32)
.unwrap_or(4)
.max(1);
Ok(Self { context, threads })
}
/// Transcribes mono `f32` samples. `language` follows whisper's codes
/// (`"fr"`, `"en"`, …).
pub fn transcribe(
&self,
samples: &[f32],
sample_rate: u32,
language: &str,
) -> Result<String, SttError> {
let pcm = if sample_rate == WHISPER_SAMPLE_RATE {
samples.to_vec()
} else {
resample_linear(samples, sample_rate, WHISPER_SAMPLE_RATE)
};
let mut state = self
.context
.create_state()
.map_err(|error| SttError(format!("état Whisper : {error}")))?;
let mut params = FullParams::new(SamplingStrategy::Greedy { best_of: 1 });
params.set_n_threads(self.threads);
params.set_translate(false);
params.set_language(Some(language));
params.set_print_special(false);
params.set_print_progress(false);
params.set_print_realtime(false);
params.set_print_timestamps(false);
state
.full(params, &pcm)
.map_err(|error| SttError(format!("transcription : {error}")))?;
let mut text = String::new();
for index in 0..state.full_n_segments() {
if let Some(segment) = state.get_segment(index) {
text.push_str(segment.to_str().unwrap_or(""));
}
}
Ok(text.trim().to_string())
}
}
+40
View File
@@ -0,0 +1,40 @@
//! Text-to-speech using the embedded Piper engine (via `piper-rs`).
//!
//! Piper produces raw `f32` PCM plus its sample rate; playback is handled by the
//! [`super::audio`] module.
use std::path::Path;
use piper_rs::Piper;
#[derive(Debug)]
pub struct TtsError(pub String);
impl std::fmt::Display for TtsError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
impl std::error::Error for TtsError {}
/// Loaded Piper voice, reused across syntheses.
pub struct PiperTts {
piper: Piper,
}
impl PiperTts {
/// Loads a Piper voice from its `.onnx` model and `.json` config.
pub fn load(model_path: &Path, config_path: &Path) -> Result<Self, TtsError> {
let piper = Piper::new(model_path, config_path)
.map_err(|error| TtsError(format!("chargement de la voix Piper : {error}")))?;
Ok(Self { piper })
}
/// Synthesizes `text` into mono `f32` samples and their sample rate.
pub fn synthesize(&mut self, text: &str) -> Result<(Vec<f32>, u32), TtsError> {
self.piper
.create(text, false, None, None, None, None)
.map_err(|error| TtsError(format!("synthèse Piper : {error}")))
}
}
+245
View File
@@ -0,0 +1,245 @@
//! Integration tests for the SSE client.
//!
//! A tiny one-shot HTTP server stands in for the backend, so the real reqwest +
//! eventsource-stream code path is exercised end to end (request body, auth
//! header, chunk parsing, `[DONE]`, inline errors and non-200 responses).
use std::io::{Read, Write};
use std::net::{TcpListener, TcpStream};
use std::sync::{Arc, Mutex};
use std::thread;
use jarvise_frontend::api::{ApiClient, ApiError, StreamEvent};
use jarvise_frontend::model::ChatMessage;
use tokio_util::sync::CancellationToken;
/// What the fake server received, so tests can assert on the outgoing request.
#[derive(Default)]
struct CapturedRequest {
head: String,
body: String,
}
/// Starts a one-shot server answering `status_line` + `headers` + `body` to the
/// first connection, and returns its base URL plus the captured request.
fn start_server(
status_line: &'static str,
extra_headers: &'static str,
body: &'static str,
) -> (String, Arc<Mutex<CapturedRequest>>) {
let listener = TcpListener::bind("127.0.0.1:0").expect("bind");
let url = format!("http://{}", listener.local_addr().expect("addr"));
let captured = Arc::new(Mutex::new(CapturedRequest::default()));
let sink = captured.clone();
thread::spawn(move || {
if let Ok((mut socket, _)) = listener.accept() {
let request = read_request(&mut socket);
*sink.lock().expect("lock") = request;
let response = format!(
"{status_line}\r\n{extra_headers}Connection: close\r\n\r\n{body}"
);
let _ = socket.write_all(response.as_bytes());
let _ = socket.flush();
}
});
(url, captured)
}
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();
return CapturedRequest { head, body };
}
}
}
}
CapturedRequest::default()
}
fn find(haystack: &[u8], needle: &[u8]) -> Option<usize> {
haystack
.windows(needle.len())
.position(|window| window == needle)
}
fn content_length(head: &str) -> usize {
head.lines()
.find_map(|line| {
let (name, value) = line.split_once(':')?;
name.eq_ignore_ascii_case("content-length")
.then(|| value.trim().parse().ok())
.flatten()
})
.unwrap_or(0)
}
struct Collected(Arc<Mutex<Vec<StreamEvent>>>);
impl Collected {
fn new() -> Self {
Self(Arc::new(Mutex::new(Vec::new())))
}
fn callback(&self) -> impl FnMut(StreamEvent) + 'static {
let events = self.0.clone();
move |event| events.lock().expect("lock").push(event)
}
fn events(&self) -> Vec<StreamEvent> {
self.0.lock().expect("lock").clone()
}
}
#[tokio::test]
async fn streams_content_then_done_and_sends_spec_body() {
let (url, captured) = start_server(
"HTTP/1.1 200 OK",
"Content-Type: text/event-stream\r\nCache-Control: no-cache\r\n",
"data: {\"content\":\"Bonjour\"}\n\ndata: {\"content\":\" Tony\"}\n\ndata: [DONE]\n\n",
);
let mut client = ApiClient::new(url);
client.set_token(Some("test-token".to_string()));
let collected = Collected::new();
let result = client
.stream_chat(
"llama3.2",
vec![ChatMessage::user("Salut")],
CancellationToken::new(),
collected.callback(),
)
.await;
result.expect("stream should succeed");
assert_eq!(
collected.events(),
vec![
StreamEvent::Delta("Bonjour".to_string()),
StreamEvent::Delta(" Tony".to_string()),
StreamEvent::Done,
]
);
let request = captured.lock().expect("lock");
assert!(
request.head.to_ascii_lowercase().contains("authorization: bearer test-token"),
"auth header missing in: {}",
request.head
);
let body: serde_json::Value = serde_json::from_str(&request.body).expect("valid JSON body");
assert_eq!(body["model"], "llama3.2");
assert_eq!(body["messages"][0]["role"], "user");
assert_eq!(body["messages"][0]["content"], "Salut");
}
#[tokio::test]
async fn reports_inline_error_event() {
let (url, _captured) = start_server(
"HTTP/1.1 200 OK",
"Content-Type: text/event-stream\r\n",
"data: {\"error\":\"modèle introuvable\"}\n\n",
);
let mut client = ApiClient::new(url);
client.set_token(Some("t".to_string()));
let collected = Collected::new();
client
.stream_chat(
"llama3.2",
vec![ChatMessage::user("hi")],
CancellationToken::new(),
collected.callback(),
)
.await
.expect("stream should succeed with an inline error event");
assert_eq!(
collected.events(),
vec![StreamEvent::Error("modèle introuvable".to_string())]
);
}
#[tokio::test]
async fn surfaces_http_error_before_stream() {
let (url, _captured) = start_server(
"HTTP/1.1 502 Bad Gateway",
"Content-Type: application/json\r\n",
"{\"error\":\"Ollama injoignable\"}",
);
let mut client = ApiClient::new(url);
client.set_token(Some("t".to_string()));
let error = client
.stream_chat(
"llama3.2",
vec![ChatMessage::user("hi")],
CancellationToken::new(),
Collected::new().callback(),
)
.await
.expect_err("a 502 must be an error");
match error {
ApiError::Status { status, message } => {
assert_eq!(status.as_u16(), 502);
assert_eq!(message, "Ollama injoignable");
}
other => panic!("expected a status error, got {other:?}"),
}
}
#[tokio::test]
async fn cancellation_stops_the_stream() {
// The server never answers; cancellation must still resolve promptly.
let listener = TcpListener::bind("127.0.0.1:0").expect("bind");
let url = format!("http://{}", listener.local_addr().expect("addr"));
thread::spawn(move || {
let _ = listener.accept();
// Hold the connection open without responding.
thread::sleep(std::time::Duration::from_secs(5));
});
let mut client = ApiClient::new(url);
client.set_token(Some("t".to_string()));
let cancel = CancellationToken::new();
cancel.cancel();
let collected = Collected::new();
let result = client
.stream_chat(
"llama3.2",
vec![ChatMessage::user("hi")],
cancel,
collected.callback(),
)
.await;
assert!(result.is_ok());
assert!(collected.events().is_empty());
}