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

+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));
});
});
}