Split the client into two tabs so the user can either write to Jarvis or talk to it. The companion screen centres the animated avatar and exposes a large push-to-talk button; the transcript from local Whisper is sent to the backend as text JSON exactly like a typed message, so the network contract stays text-only. Give the avatar a distinct expression per mood (thinking, listening, speaking, happy, error, idle) and apply one dark, rounded theme so the app looks consistent everywhere.
1782 lines
68 KiB
Rust
1782 lines
68 KiB
Rust
//! 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, RecallEvent, StreamEvent};
|
|
use crate::config::AppConfig;
|
|
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};
|
|
|
|
/// Key under which the state is persisted (token, email, model, backend URL).
|
|
const STORAGE_KEY: &str = "jarvise-session";
|
|
|
|
/// Accent colour of the primary actions: tabs, titles and the mic button.
|
|
pub const ACCENT: egui::Color32 = egui::Color32::from_rgb(0x5b, 0x8d, 0xff);
|
|
/// Softer accent for text that has to stay readable on the dark background.
|
|
pub const ACCENT_SOFT: egui::Color32 = egui::Color32::from_rgb(0x9d, 0xbc, 0xff);
|
|
/// Colour of the running status line (recording, transcribing…).
|
|
const STATUS: egui::Color32 = egui::Color32::from_rgb(0x8a, 0xb4, 0xf8);
|
|
/// Colour of error messages.
|
|
const ERROR: egui::Color32 = egui::Color32::from_rgb(0xff, 0x6b, 0x6b);
|
|
/// Background of the top and bottom strips.
|
|
const BAR_FILL: egui::Color32 = egui::Color32::from_rgb(0x16, 0x19, 0x21);
|
|
|
|
/// 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,
|
|
/// A request failed (network, HTTP status or inline SSE error).
|
|
Error(String),
|
|
/// The project list was refreshed.
|
|
ProjectsLoaded(Vec<Project>),
|
|
/// A project was created or renamed.
|
|
ProjectCreated(Project),
|
|
/// A project was deleted.
|
|
ProjectDeleted(i64),
|
|
/// A project's context, oldest message first. Discarded if another project
|
|
/// was selected while it was loading.
|
|
ProjectMessages {
|
|
project_id: i64,
|
|
messages: Vec<ChatMessage>,
|
|
/// Older messages were left out by the backend's pagination.
|
|
truncated: bool,
|
|
},
|
|
/// A project's context was emptied.
|
|
ProjectContextCleared(i64),
|
|
/// A note was appended to a project's context.
|
|
ContextNoteAdded {
|
|
project_id: i64,
|
|
message: ChatMessage,
|
|
},
|
|
/// The context verification finished: the model recited what it received.
|
|
RecallDone {
|
|
project_id: i64,
|
|
/// Index of the caption bubble to complete with the real count.
|
|
caption_index: usize,
|
|
context_messages: usize,
|
|
},
|
|
/// Speech recognition produced a transcript.
|
|
Transcribed(String),
|
|
/// A voice job (STT or TTS) failed.
|
|
VoiceError(String),
|
|
/// Text-to-speech playback finished.
|
|
Spoken,
|
|
}
|
|
|
|
/// What gets written to disk between runs (via eframe's persistence).
|
|
#[derive(Serialize, Deserialize, Default)]
|
|
struct Persisted {
|
|
token: Option<String>,
|
|
email: String,
|
|
model: String,
|
|
backend_url: String,
|
|
/// Project reopened on the next run, if it still exists.
|
|
#[serde(default)]
|
|
project_id: Option<i64>,
|
|
/// Reopens the companion screen on the next run.
|
|
#[serde(default)]
|
|
companion: bool,
|
|
}
|
|
|
|
/// The two faces of the app, switched from the tabs at the top of the window.
|
|
#[derive(Clone, Copy, PartialEq, Eq)]
|
|
pub enum Mode {
|
|
/// Text conversation: project sidebar, bubbles, keyboard input.
|
|
Chat,
|
|
/// Voice conversation: the avatar is centred and a big button talks to it.
|
|
Companion,
|
|
}
|
|
|
|
impl Mode {
|
|
fn label(self) -> &'static str {
|
|
match self {
|
|
Mode::Chat => "💬 Chat",
|
|
Mode::Companion => "🗣️ Compagnon",
|
|
}
|
|
}
|
|
|
|
/// One-line explanation shown as a tooltip on each tab.
|
|
fn hint(self) -> &'static str {
|
|
match self {
|
|
Mode::Chat => "Écrire à Jarvis, avec les projets et l'historique",
|
|
Mode::Companion => "Parler à Jarvis : l'avatar transcrit ta voix et envoie le texte",
|
|
}
|
|
}
|
|
}
|
|
|
|
/// 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,
|
|
|
|
// Projects: the persisted conversation contexts.
|
|
projects: Vec<Project>,
|
|
current_project: Option<i64>,
|
|
/// Project waiting for a second click on its delete button.
|
|
confirm_delete: Option<i64>,
|
|
/// Context waiting for a confirmation before being emptied.
|
|
confirm_clear: bool,
|
|
/// Whether the create/rename form is shown.
|
|
form_open: bool,
|
|
/// Project being renamed (`None` while creating a new one).
|
|
editing: Option<i64>,
|
|
form_name: String,
|
|
form_description: String,
|
|
context_note: String,
|
|
/// The loaded context does not go back to the first message.
|
|
history_truncated: bool,
|
|
|
|
// Chat.
|
|
mode: Mode,
|
|
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>,
|
|
|
|
// Companion animation.
|
|
speaking: bool,
|
|
happy_timer: f32,
|
|
}
|
|
|
|
impl JarviseApp {
|
|
pub fn new(cc: &eframe::CreationContext<'_>, config: AppConfig) -> Self {
|
|
// A single dark theme, applied once: the app should look the same on
|
|
// every desktop rather than follow the OS colours.
|
|
apply_theme(&cc.egui_ctx);
|
|
|
|
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::Spoken => UiEvent::Spoken,
|
|
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,
|
|
projects: Vec::new(),
|
|
current_project: persisted.project_id,
|
|
confirm_delete: None,
|
|
confirm_clear: false,
|
|
form_open: false,
|
|
editing: None,
|
|
form_name: String::new(),
|
|
form_description: String::new(),
|
|
context_note: String::new(),
|
|
history_truncated: false,
|
|
mode: if persisted.companion {
|
|
Mode::Companion
|
|
} else {
|
|
Mode::Chat
|
|
},
|
|
model,
|
|
messages: Vec::new(),
|
|
input: String::new(),
|
|
streaming: false,
|
|
cancel: None,
|
|
error: None,
|
|
voice,
|
|
speak_replies,
|
|
recorder: None,
|
|
voice_status: None,
|
|
pending_transcript: None,
|
|
speaking: false,
|
|
happy_timer: 0.0,
|
|
};
|
|
|
|
// If a token was restored, validate it in the background before showing
|
|
// 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),
|
|
}
|
|
});
|
|
}
|
|
|
|
/* ----------------------------------------------------------- projects */
|
|
|
|
/// Spawns `GET /api/projects`: the sidebar and its message counters are
|
|
/// built from this list.
|
|
fn load_projects(&mut self, ctx: &egui::Context) {
|
|
let api = self.api.clone();
|
|
let notifier = self.notifier(ctx);
|
|
self.runtime.spawn(async move {
|
|
match api.list_projects().await {
|
|
Ok(projects) => notifier.send(UiEvent::ProjectsLoaded(projects)),
|
|
Err(error) => notifier.send(UiEvent::Error(error.to_string())),
|
|
}
|
|
});
|
|
}
|
|
|
|
/// Spawns `GET /api/projects/:id/messages` to display a stored context.
|
|
fn load_messages(&self, project_id: i64, ctx: &egui::Context) {
|
|
let api = self.api.clone();
|
|
let notifier = self.notifier(ctx);
|
|
self.runtime.spawn(async move {
|
|
match api.project_messages(project_id, 200).await {
|
|
Ok(page) => {
|
|
let messages = page.messages.iter().map(StoredMessage::to_chat).collect();
|
|
notifier.send(UiEvent::ProjectMessages {
|
|
project_id,
|
|
messages,
|
|
truncated: page.has_more,
|
|
});
|
|
}
|
|
Err(error) => notifier.send(UiEvent::Error(error.to_string())),
|
|
}
|
|
});
|
|
}
|
|
|
|
/// Re-reads the stored context of the open project from the backend, which is
|
|
/// how a change made elsewhere (or a context probe) is discarded.
|
|
fn reload_context(&mut self, ctx: &egui::Context) {
|
|
if let Some(project_id) = self.current_project {
|
|
self.load_messages(project_id, ctx);
|
|
}
|
|
}
|
|
|
|
/// Asks Jarvis to recite the stored context: a read-only probe proving the
|
|
/// history really reaches the model. The exchange is *not* persisted, so
|
|
/// « ⟳ Recharger » makes the bubbles disappear.
|
|
fn start_recall(&mut self, ctx: &egui::Context) {
|
|
let Some(project_id) = self.current_project else {
|
|
return;
|
|
};
|
|
if self.streaming {
|
|
return;
|
|
}
|
|
|
|
self.error = None;
|
|
let caption_index = self.messages.len();
|
|
self.messages
|
|
.push(ChatMessage::system("🧠 Vérification du contexte…"));
|
|
// A placeholder assistant bubble receives the streamed fragments.
|
|
self.messages.push(ChatMessage::assistant(String::new()));
|
|
|
|
let cancel = CancellationToken::new();
|
|
self.cancel = Some(cancel.clone());
|
|
self.streaming = true;
|
|
|
|
let api = self.api.clone();
|
|
let model = self.model.clone();
|
|
let notifier = self.notifier(ctx);
|
|
|
|
self.runtime.spawn(async move {
|
|
let callback = notifier.clone();
|
|
let result = api
|
|
.stream_project_recall(project_id, &model, cancel, move |event| {
|
|
callback.send(match event {
|
|
RecallEvent::Delta(text) => UiEvent::Delta(text),
|
|
RecallEvent::Done(context_messages) => UiEvent::RecallDone {
|
|
project_id,
|
|
caption_index,
|
|
context_messages,
|
|
},
|
|
RecallEvent::Error(message) => UiEvent::Error(message),
|
|
});
|
|
})
|
|
.await;
|
|
|
|
if let Err(error) = result {
|
|
notifier.send(UiEvent::Error(error.to_string()));
|
|
}
|
|
});
|
|
}
|
|
|
|
/// Opens another conversation context; `None` is the stateless chat.
|
|
fn select_project(&mut self, target: Option<i64>, ctx: &egui::Context) {
|
|
if self.current_project == target {
|
|
return;
|
|
}
|
|
|
|
self.stop_stream();
|
|
self.current_project = target;
|
|
self.messages.clear();
|
|
self.history_truncated = false;
|
|
self.error = None;
|
|
self.confirm_delete = None;
|
|
self.confirm_clear = false;
|
|
self.context_note.clear();
|
|
|
|
if let Some(project_id) = target {
|
|
self.load_messages(project_id, ctx);
|
|
}
|
|
}
|
|
|
|
/// Creates the project described by the form, or renames the edited one.
|
|
fn save_project(&mut self, ctx: &egui::Context) {
|
|
let name = self.form_name.trim().to_string();
|
|
if name.is_empty() {
|
|
return;
|
|
}
|
|
let description = self.form_description.trim().to_string();
|
|
let description = (!description.is_empty()).then_some(description);
|
|
let editing = self.editing;
|
|
self.form_open = false;
|
|
|
|
let api = self.api.clone();
|
|
let notifier = self.notifier(ctx);
|
|
self.runtime.spawn(async move {
|
|
let result = match editing {
|
|
Some(project_id) => api
|
|
.update_project(project_id, Some(&name), description.as_deref())
|
|
.await,
|
|
None => api.create_project(&name, description.as_deref()).await,
|
|
};
|
|
match result {
|
|
Ok(project) => notifier.send(UiEvent::ProjectCreated(project)),
|
|
Err(error) => notifier.send(UiEvent::Error(error.to_string())),
|
|
}
|
|
});
|
|
}
|
|
|
|
/// Fills the form with the project's values so it can be renamed.
|
|
fn edit_project(&mut self, project_id: i64) {
|
|
let Some(project) = self.projects.iter().find(|item| item.id == project_id) else {
|
|
return;
|
|
};
|
|
self.form_name = project.name.clone();
|
|
self.form_description = project.description.clone().unwrap_or_default();
|
|
self.editing = Some(project_id);
|
|
self.form_open = true;
|
|
}
|
|
|
|
fn delete_project(&mut self, project_id: i64, ctx: &egui::Context) {
|
|
self.confirm_delete = None;
|
|
let api = self.api.clone();
|
|
let notifier = self.notifier(ctx);
|
|
self.runtime.spawn(async move {
|
|
match api.delete_project(project_id).await {
|
|
Ok(()) => notifier.send(UiEvent::ProjectDeleted(project_id)),
|
|
Err(error) => notifier.send(UiEvent::Error(error.to_string())),
|
|
}
|
|
});
|
|
}
|
|
|
|
/// Empties a project's context on the backend, then locally.
|
|
fn clear_project_context(&mut self, project_id: i64, ctx: &egui::Context) {
|
|
self.confirm_clear = false;
|
|
let api = self.api.clone();
|
|
let notifier = self.notifier(ctx);
|
|
self.runtime.spawn(async move {
|
|
match api.clear_project_messages(project_id).await {
|
|
Ok(_) => notifier.send(UiEvent::ProjectContextCleared(project_id)),
|
|
Err(error) => notifier.send(UiEvent::Error(error.to_string())),
|
|
}
|
|
});
|
|
}
|
|
|
|
/// Appends a system note to the context without calling the model, so the
|
|
/// user can pin an instruction Jarvis will read on the next exchange.
|
|
fn add_context_note(&mut self, project_id: i64, ctx: &egui::Context) {
|
|
let content = self.context_note.trim().to_string();
|
|
if content.is_empty() {
|
|
return;
|
|
}
|
|
self.context_note.clear();
|
|
|
|
let api = self.api.clone();
|
|
let notifier = self.notifier(ctx);
|
|
self.runtime.spawn(async move {
|
|
match api.add_project_message(project_id, "system", &content).await {
|
|
Ok(message) => notifier.send(UiEvent::ContextNoteAdded {
|
|
project_id,
|
|
message: message.to_chat(),
|
|
}),
|
|
Err(error) => notifier.send(UiEvent::Error(error.to_string())),
|
|
}
|
|
});
|
|
}
|
|
|
|
/// Spawns the login request.
|
|
fn start_login(&mut self, ctx: &egui::Context) {
|
|
if self.login_busy {
|
|
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.
|
|
///
|
|
/// Inside a project the backend replays the stored context to the model and
|
|
/// persists the exchange; without one, the whole history is sent as-is.
|
|
fn send_message(&mut self, ctx: &egui::Context) {
|
|
let text = self.input.trim().to_string();
|
|
if text.is_empty() || self.streaming {
|
|
return;
|
|
}
|
|
|
|
self.error = None;
|
|
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();
|
|
|
|
// 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 project_id = self.current_project;
|
|
let notifier = self.notifier(ctx);
|
|
|
|
self.runtime.spawn(async move {
|
|
let callback = notifier.clone();
|
|
let on_event = move |event| {
|
|
callback.send(match event {
|
|
StreamEvent::Delta(text) => UiEvent::Delta(text),
|
|
StreamEvent::Done => UiEvent::Done,
|
|
StreamEvent::Error(message) => UiEvent::Error(message),
|
|
});
|
|
};
|
|
let result = match project_id {
|
|
Some(project_id) => api
|
|
.stream_project_chat(project_id, &text, &model, cancel, on_event)
|
|
.await,
|
|
None => api.stream_chat(&model, history, cancel, on_event).await,
|
|
};
|
|
|
|
if let Err(error) = result {
|
|
notifier.send(UiEvent::Error(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.projects.clear();
|
|
self.current_project = None;
|
|
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, ctx: &egui::Context) {
|
|
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();
|
|
self.load_projects(ctx);
|
|
}
|
|
UiEvent::AuthError(message) => {
|
|
self.login_busy = false;
|
|
self.login_error = Some(message);
|
|
}
|
|
UiEvent::TokenValid(user) => {
|
|
self.user = Some(user);
|
|
self.load_projects(ctx);
|
|
}
|
|
UiEvent::TokenInvalid => {
|
|
self.token = None;
|
|
self.user = None;
|
|
self.api.set_token(None);
|
|
}
|
|
UiEvent::ProjectsLoaded(projects) => {
|
|
// A project remembered from the previous run may be gone.
|
|
if let Some(project_id) = self.current_project {
|
|
if !projects.iter().any(|project| project.id == project_id) {
|
|
self.current_project = None;
|
|
self.messages.clear();
|
|
}
|
|
}
|
|
self.projects = projects;
|
|
|
|
// Reopens the context that was on screen at the last run.
|
|
if let Some(project_id) = self.current_project {
|
|
if self.messages.is_empty() {
|
|
self.load_messages(project_id, ctx);
|
|
}
|
|
}
|
|
}
|
|
UiEvent::ProjectCreated(project) => {
|
|
let known = self.projects.iter().any(|item| item.id == project.id);
|
|
match self
|
|
.projects
|
|
.iter_mut()
|
|
.find(|item| item.id == project.id)
|
|
{
|
|
Some(slot) => *slot = project.clone(),
|
|
None => self.projects.push(project.clone()),
|
|
}
|
|
self.projects
|
|
.sort_by(|left, right| left.name.to_lowercase().cmp(&right.name.to_lowercase()));
|
|
self.editing = None;
|
|
|
|
// A brand new project is worth opening straight away.
|
|
if !known {
|
|
self.select_project(Some(project.id), ctx);
|
|
}
|
|
}
|
|
UiEvent::ProjectDeleted(project_id) => {
|
|
self.projects.retain(|project| project.id != project_id);
|
|
if self.current_project == Some(project_id) {
|
|
self.current_project = None;
|
|
self.messages.clear();
|
|
}
|
|
}
|
|
UiEvent::ProjectMessages {
|
|
project_id,
|
|
messages,
|
|
truncated,
|
|
} => {
|
|
// The user may have switched project while it was loading.
|
|
if self.current_project == Some(project_id) {
|
|
self.messages = messages;
|
|
self.history_truncated = truncated;
|
|
}
|
|
}
|
|
UiEvent::ProjectContextCleared(project_id) => {
|
|
if self.current_project == Some(project_id) {
|
|
self.messages.clear();
|
|
self.history_truncated = false;
|
|
}
|
|
for project in &mut self.projects {
|
|
if project.id == project_id {
|
|
project.message_count = 0;
|
|
}
|
|
}
|
|
}
|
|
UiEvent::ContextNoteAdded {
|
|
project_id,
|
|
message,
|
|
} => {
|
|
if self.current_project == Some(project_id) {
|
|
self.messages.push(message);
|
|
}
|
|
for project in &mut self.projects {
|
|
if project.id == project_id {
|
|
project.message_count += 1;
|
|
}
|
|
}
|
|
}
|
|
UiEvent::RecallDone {
|
|
project_id,
|
|
caption_index,
|
|
context_messages,
|
|
} => {
|
|
self.streaming = false;
|
|
self.cancel = None;
|
|
if self.current_project == Some(project_id) {
|
|
if let Some(caption) = self.messages.get_mut(caption_index) {
|
|
caption.content = format!(
|
|
"🧠 Contexte vérifié : {} message(s) renvoyé(s) à Jarvis",
|
|
context_messages
|
|
);
|
|
}
|
|
}
|
|
self.happy_timer = 1.5;
|
|
}
|
|
UiEvent::Delta(text) => {
|
|
if let Some(last) = self.messages.last_mut() {
|
|
if last.role == "assistant" {
|
|
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.speaking = true;
|
|
self.voice.speak(text);
|
|
}
|
|
self.happy_timer = 2.5;
|
|
|
|
// In a project the exchange was persisted server-side, so
|
|
// the sidebar counters are refreshed from the backend.
|
|
if self.current_project.is_some() {
|
|
self.load_projects(ctx);
|
|
}
|
|
}
|
|
UiEvent::Error(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.speaking = false;
|
|
self.error = Some(message);
|
|
}
|
|
UiEvent::Spoken => self.speaking = false,
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Mood of the companion, derived from what the app is doing.
|
|
fn mood(&self) -> Mood {
|
|
if self.recorder.is_some() {
|
|
Mood::Listening
|
|
} else if self.streaming {
|
|
Mood::Thinking
|
|
} else if self.speaking {
|
|
Mood::Speaking
|
|
} else if self.happy_timer > 0.0 {
|
|
Mood::Happy
|
|
} else if self.error.is_some() {
|
|
Mood::Error
|
|
} else {
|
|
Mood::Idle
|
|
}
|
|
}
|
|
|
|
fn login_screen(&mut self, ui: &mut egui::Ui) {
|
|
egui::CentralPanel::default().show(ui, |ui| {
|
|
ui.add_space(70.0);
|
|
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) {
|
|
// The project sidebar is a text-mode tool: the companion screen is a
|
|
// calm, centred stage for the avatar, so it gets the full width.
|
|
if self.mode == Mode::Chat {
|
|
self.project_panel(ui);
|
|
}
|
|
|
|
self.top_bar(ui);
|
|
|
|
match self.mode {
|
|
Mode::Chat => {
|
|
self.input_bar(ui);
|
|
egui::CentralPanel::default().show(ui, |ui| {
|
|
chat_area(ui, &self.messages);
|
|
});
|
|
}
|
|
Mode::Companion => {
|
|
self.companion_bar(ui);
|
|
self.companion_screen(ui);
|
|
}
|
|
}
|
|
}
|
|
|
|
/// The window's top strip: identity, the two mode tabs, and the session
|
|
/// controls (context, model, voice output, account).
|
|
fn top_bar(&mut self, ui: &mut egui::Ui) {
|
|
egui::Panel::top("top-bar").show(ui, |ui| {
|
|
egui::Frame::new()
|
|
.fill(BAR_FILL)
|
|
.inner_margin(egui::Margin::symmetric(14, 10))
|
|
.show(ui, |ui| {
|
|
// Shown in the bar so the current context is obvious, even
|
|
// when the sidebar is hidden on the companion screen.
|
|
let project_label = self
|
|
.current_project
|
|
.and_then(|id| self.projects.iter().find(|item| item.id == id))
|
|
.map(|project| project.name.clone());
|
|
let time = ui.input(|i| i.time);
|
|
let mood = self.mood();
|
|
// Narrow windows drop the least important labels instead of
|
|
// letting the bar overflow.
|
|
let wide = ui.available_width() > 720.0;
|
|
ui.horizontal(|ui| {
|
|
let pet = tamagotchi::draw(ui, mood, time);
|
|
pet.on_hover_text(mood.tooltip());
|
|
|
|
ui.add_space(6.0);
|
|
ui.vertical(|ui| {
|
|
ui.strong("Jarvise");
|
|
ui.add(
|
|
egui::Label::new(
|
|
egui::RichText::new(mood.label())
|
|
.size(12.0)
|
|
.color(egui::Color32::from_gray(150)),
|
|
)
|
|
.wrap(),
|
|
);
|
|
});
|
|
|
|
ui.add_space(16.0);
|
|
|
|
// The two modes, side by side — the app's main switch.
|
|
for mode in [Mode::Chat, Mode::Companion] {
|
|
let selected = self.mode == mode;
|
|
let button = egui::Button::new(
|
|
egui::RichText::new(mode.label()).size(15.0).color(if selected {
|
|
egui::Color32::WHITE
|
|
} else {
|
|
egui::Color32::from_gray(190)
|
|
}),
|
|
)
|
|
.fill(if selected {
|
|
ACCENT
|
|
} else {
|
|
egui::Color32::TRANSPARENT
|
|
})
|
|
.corner_radius(egui::CornerRadius::same(9))
|
|
.min_size(egui::vec2(0.0, 34.0));
|
|
if ui.add(button).on_hover_text(mode.hint()).clicked() {
|
|
self.mode = mode;
|
|
}
|
|
}
|
|
|
|
if wide {
|
|
ui.add_space(10.0);
|
|
ui.separator();
|
|
|
|
// Context in use by the next exchange.
|
|
let context = egui::RichText::new(
|
|
project_label.clone().unwrap_or_else(|| "Sans projet".to_string()),
|
|
)
|
|
.strong()
|
|
.color(ACCENT_SOFT);
|
|
ui.label(context).on_hover_text("Contexte utilisé par Jarvis");
|
|
}
|
|
|
|
ui.with_layout(
|
|
egui::Layout::right_to_left(egui::Align::Center),
|
|
|ui| {
|
|
if ui.button("Déconnexion").clicked() {
|
|
self.logout();
|
|
}
|
|
// In a project the history lives on the backend, so the only way to
|
|
// really clear it is the sidebar's « Vider ».
|
|
if self.mode == Mode::Chat
|
|
&& self.current_project.is_none()
|
|
&& ui.button("Effacer")
|
|
.on_hover_text("Effacer la conversation affichée")
|
|
.clicked()
|
|
{
|
|
self.stop_stream();
|
|
self.messages.clear();
|
|
self.error = None;
|
|
}
|
|
if let Some(user) = &self.user {
|
|
ui.add_space(4.0);
|
|
ui.label(user.display_name());
|
|
}
|
|
|
|
ui.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.add(
|
|
egui::TextEdit::singleline(&mut self.model)
|
|
.desired_width(130.0)
|
|
.hint_text("qwen2.5:3b"),
|
|
)
|
|
.on_hover_text("Modèle Ollama");
|
|
},
|
|
);
|
|
});
|
|
});
|
|
});
|
|
}
|
|
|
|
/// Bottom strip of the text mode: the compose box and its send button.
|
|
fn input_bar(&mut self, ui: &mut egui::Ui) {
|
|
egui::Panel::bottom("input-bar").show(ui, |ui| {
|
|
egui::Frame::new()
|
|
.fill(BAR_FILL)
|
|
.inner_margin(egui::Margin::symmetric(14, 10))
|
|
.show(ui, |ui| {
|
|
if let Some(error) = &self.error {
|
|
ui.colored_label(ERROR, error);
|
|
}
|
|
if let Some(status) = &self.voice_status {
|
|
ui.colored_label(STATUS, status);
|
|
}
|
|
if self.error.is_some() || self.voice_status.is_some() {
|
|
ui.add_space(4.0);
|
|
}
|
|
|
|
ui.horizontal(|ui| {
|
|
let button_width = 96.0;
|
|
let mic_width = 46.0;
|
|
let input_width =
|
|
(ui.available_width() - button_width - mic_width - 20.0).max(120.0);
|
|
|
|
// Push-to-talk: hold the mic button to record, release to send.
|
|
let mic = ui.add_enabled(
|
|
self.voice.stt_ready(),
|
|
egui::Button::new(if self.recorder.is_some() { "⏺" } else { "🎤" })
|
|
.min_size(egui::vec2(mic_width, 52.0)),
|
|
);
|
|
if mic.is_pointer_button_down_on() && self.recorder.is_none() {
|
|
self.start_recording();
|
|
}
|
|
if !mic.is_pointer_button_down_on() && self.recorder.is_some() {
|
|
self.stop_recording();
|
|
}
|
|
if self.voice.stt_ready() {
|
|
mic.on_hover_text("Maintenir pour parler (push-to-talk)");
|
|
} else {
|
|
mic.on_disabled_hover_text("STT non configuré : définis WHISPER_MODEL");
|
|
}
|
|
|
|
let response = ui.add_sized(
|
|
[input_width, 52.0],
|
|
egui::TextEdit::multiline(&mut self.input).hint_text(
|
|
"Votre message… (Entrée pour envoyer, Maj+Entrée pour un saut de ligne)",
|
|
),
|
|
);
|
|
|
|
let submitted = response.has_focus()
|
|
&& ui.input(|i| i.key_pressed(egui::Key::Enter) && !i.modifiers.shift);
|
|
|
|
if self.streaming {
|
|
if ui
|
|
.add_sized([button_width, 52.0], egui::Button::new("Stopper"))
|
|
.clicked()
|
|
{
|
|
self.stop_stream();
|
|
}
|
|
} else if ui
|
|
.add_sized([button_width, 52.0], egui::Button::new("Envoyer"))
|
|
.clicked()
|
|
|| submitted
|
|
{
|
|
self.send_message(ui.ctx());
|
|
}
|
|
});
|
|
});
|
|
});
|
|
}
|
|
|
|
/// Bottom strip of the companion screen: the status/error line and a text
|
|
/// fallback for when the microphone is not configured.
|
|
fn companion_bar(&mut self, ui: &mut egui::Ui) {
|
|
egui::Panel::bottom("companion-bar").show(ui, |ui| {
|
|
egui::Frame::new()
|
|
.fill(BAR_FILL)
|
|
.inner_margin(egui::Margin::symmetric(14, 10))
|
|
.show(ui, |ui| {
|
|
if let Some(error) = &self.error {
|
|
ui.colored_label(ERROR, error);
|
|
ui.add_space(4.0);
|
|
}
|
|
|
|
ui.horizontal(|ui| {
|
|
let button_width = 96.0;
|
|
let input_width = (ui.available_width() - button_width - 10.0).max(120.0);
|
|
let response = ui.add_sized(
|
|
[input_width, 40.0],
|
|
egui::TextEdit::singleline(&mut self.input)
|
|
.hint_text("Ou écris à Jarvis…"),
|
|
);
|
|
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, 40.0], egui::Button::new("Stopper"))
|
|
.clicked()
|
|
{
|
|
self.stop_stream();
|
|
}
|
|
} else if ui
|
|
.add_sized([button_width, 40.0], egui::Button::new("Envoyer"))
|
|
.clicked()
|
|
|| submitted
|
|
{
|
|
self.send_message(ui.ctx());
|
|
}
|
|
});
|
|
});
|
|
});
|
|
}
|
|
|
|
/// The companion stage: the avatar in the middle, the mood underneath, the
|
|
/// last exchange as subtitles, and the large push-to-talk button. Talking
|
|
/// produces a transcript, which is sent to the backend as plain text JSON
|
|
/// exactly like a typed message.
|
|
fn companion_screen(&mut self, ui: &mut egui::Ui) {
|
|
egui::CentralPanel::default().show(ui, |ui| {
|
|
let available = ui.available_size();
|
|
let time = ui.input(|i| i.time);
|
|
let mood = self.mood();
|
|
let subtitle_width = (available.x * 0.82).min(640.0);
|
|
|
|
ui.vertical_centered(|ui| {
|
|
ui.add_space((available.y * 0.05).max(6.0));
|
|
|
|
let diameter = (available.x * 0.30).clamp(120.0, 230.0);
|
|
let pet = tamagotchi::draw_sized(ui, mood, time, diameter);
|
|
pet.on_hover_text(mood.tooltip());
|
|
|
|
ui.add_space(10.0);
|
|
ui.label(egui::RichText::new(mood.label()).size(20.0).color(ACCENT_SOFT));
|
|
|
|
ui.add_space(6.0);
|
|
if let Some(status) = &self.voice_status {
|
|
ui.colored_label(STATUS, status);
|
|
} else if !self.voice.stt_ready() {
|
|
ui.small("Micro non configuré : définis WHISPER_MODEL pour parler à Jarvis.");
|
|
}
|
|
|
|
ui.add_space((available.y * 0.04).max(6.0));
|
|
|
|
// Subtitles: what was just said, then Jarvis' live answer.
|
|
if let Some(last_user) = self.messages.iter().rev().find(|m| m.is_user()) {
|
|
subtitle(ui, "Vous", &last_user.content, subtitle_width, false);
|
|
ui.add_space(6.0);
|
|
}
|
|
let live_reply = self
|
|
.messages
|
|
.iter()
|
|
.rev()
|
|
.find(|m| m.role == "assistant" && !m.content.trim().is_empty());
|
|
match live_reply {
|
|
Some(reply) => subtitle(ui, "Jarvis", &reply.content, subtitle_width, true),
|
|
None if self.streaming => subtitle(ui, "Jarvis", "…", subtitle_width, true),
|
|
None => {}
|
|
}
|
|
|
|
ui.add_space((available.y * 0.06).max(10.0));
|
|
|
|
// Push-to-talk: hold to record, release to transcribe + send.
|
|
let mic = mic_button(ui, self.recorder.is_some(), self.voice.stt_ready());
|
|
let down = mic.is_pointer_button_down_on();
|
|
if self.voice.stt_ready() {
|
|
if down && self.recorder.is_none() {
|
|
self.start_recording();
|
|
}
|
|
if !down && self.recorder.is_some() {
|
|
self.stop_recording();
|
|
}
|
|
mic.on_hover_text("Maintenir pour parler — relâche pour transcrire et envoyer");
|
|
} else {
|
|
mic.on_hover_text("STT non configuré : définis WHISPER_MODEL");
|
|
}
|
|
});
|
|
});
|
|
}
|
|
|
|
/// Sidebar listing the user's projects, with the tools that act on the
|
|
/// context of the selected one: renaming, clearing it, and pinning a system
|
|
/// note Jarvis will read on the next exchange.
|
|
fn project_panel(&mut self, ui: &mut egui::Ui) {
|
|
egui::Panel::left("projects-panel")
|
|
.resizable(false)
|
|
.exact_size(252.0)
|
|
.show(ui, |ui| {
|
|
ui.add_space(8.0);
|
|
|
|
ui.horizontal(|ui| {
|
|
ui.strong("Projets");
|
|
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
|
if ui
|
|
.small_button("✎")
|
|
.on_hover_text("Renommer le projet ouvert")
|
|
.clicked()
|
|
{
|
|
if let Some(project_id) = self.current_project {
|
|
self.edit_project(project_id);
|
|
}
|
|
}
|
|
if ui
|
|
.small_button("+")
|
|
.on_hover_text("Nouveau projet")
|
|
.clicked()
|
|
{
|
|
self.editing = None;
|
|
self.form_name.clear();
|
|
self.form_description.clear();
|
|
self.form_open = true;
|
|
}
|
|
});
|
|
});
|
|
ui.separator();
|
|
|
|
// The stateless conversation: no project, no persisted history.
|
|
if ui
|
|
.selectable_label(self.current_project.is_none(), "Sans projet")
|
|
.on_hover_text("Chaque message est envoyé sans historique")
|
|
.clicked()
|
|
{
|
|
self.select_project(None, ui.ctx());
|
|
}
|
|
|
|
for index in 0..self.projects.len() {
|
|
let project_id = self.projects[index].id;
|
|
let label = self.projects[index].subtitle();
|
|
let selected = self.current_project == Some(project_id);
|
|
|
|
let (open, trash) = ui
|
|
.horizontal(|ui| {
|
|
let open = ui
|
|
.add_sized(
|
|
[ui.available_width() - 36.0, 30.0],
|
|
egui::Button::selectable(selected, label),
|
|
)
|
|
.clicked();
|
|
let trash = ui
|
|
.add_sized([28.0, 30.0], egui::Button::new("🗑"))
|
|
.on_hover_text("Supprimer le projet")
|
|
.clicked();
|
|
(open, trash)
|
|
})
|
|
.inner;
|
|
|
|
if open {
|
|
self.select_project(Some(project_id), ui.ctx());
|
|
}
|
|
if trash {
|
|
// First click arms the deletion, second one confirms it.
|
|
if self.confirm_delete == Some(project_id) {
|
|
self.delete_project(project_id, ui.ctx());
|
|
} else {
|
|
self.confirm_delete = Some(project_id);
|
|
}
|
|
}
|
|
}
|
|
|
|
if let Some(project_id) = self.confirm_delete {
|
|
ui.add_space(6.0);
|
|
ui.separator();
|
|
ui.label("Supprimer ce projet et tout son contexte ?");
|
|
ui.horizontal(|ui| {
|
|
if ui.button("Oui, supprimer").clicked() {
|
|
self.delete_project(project_id, ui.ctx());
|
|
}
|
|
if ui.button("Annuler").clicked() {
|
|
self.confirm_delete = None;
|
|
}
|
|
});
|
|
}
|
|
|
|
if self.form_open {
|
|
ui.add_space(6.0);
|
|
ui.separator();
|
|
ui.strong(if self.editing.is_some() {
|
|
"Modifier le projet"
|
|
} else {
|
|
"Nouveau projet"
|
|
});
|
|
ui.add(
|
|
egui::TextEdit::singleline(&mut self.form_name)
|
|
.hint_text("Nom du projet")
|
|
.desired_width(f32::INFINITY),
|
|
);
|
|
ui.add(
|
|
egui::TextEdit::multiline(&mut self.form_description)
|
|
.hint_text("Description (facultative)")
|
|
.desired_rows(2)
|
|
.desired_width(f32::INFINITY),
|
|
);
|
|
let can_save = !self.form_name.trim().is_empty();
|
|
ui.horizontal(|ui| {
|
|
if ui
|
|
.add_enabled(can_save, egui::Button::new("Enregistrer"))
|
|
.clicked()
|
|
{
|
|
self.save_project(ui.ctx());
|
|
}
|
|
if ui.button("Annuler").clicked() {
|
|
self.form_open = false;
|
|
self.editing = None;
|
|
}
|
|
});
|
|
}
|
|
|
|
if let Some(project_id) = self.current_project {
|
|
ui.add_space(6.0);
|
|
ui.separator();
|
|
ui.label("Contexte");
|
|
let note = ui.add(
|
|
egui::TextEdit::singleline(&mut self.context_note)
|
|
.hint_text("Note système (facultative)")
|
|
.desired_width(f32::INFINITY),
|
|
);
|
|
let can_add = !self.context_note.trim().is_empty();
|
|
let submitted =
|
|
note.has_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter));
|
|
|
|
ui.horizontal(|ui| {
|
|
if ui
|
|
.button("⟳ Recharger")
|
|
.on_hover_text("Relire le contexte depuis le backend")
|
|
.clicked()
|
|
{
|
|
self.reload_context(ui.ctx());
|
|
}
|
|
if ui
|
|
.add_enabled(!self.streaming, egui::Button::new("🧠 Vérifier"))
|
|
.on_hover_text(
|
|
"Demander à Jarvis de réciter le contexte (rien n'est enregistré)",
|
|
)
|
|
.clicked()
|
|
{
|
|
self.start_recall(ui.ctx());
|
|
}
|
|
});
|
|
|
|
ui.horizontal(|ui| {
|
|
if ui
|
|
.add_enabled(can_add, egui::Button::new("+ Ajouter"))
|
|
.on_hover_text("Ajouter une note au contexte, sans appeler le modèle")
|
|
.clicked()
|
|
{
|
|
self.add_context_note(project_id, ui.ctx());
|
|
}
|
|
if ui.button("Vider").on_hover_text("Effacer l'historique").clicked() {
|
|
self.confirm_clear = true;
|
|
}
|
|
});
|
|
|
|
if submitted && can_add {
|
|
self.add_context_note(project_id, ui.ctx());
|
|
}
|
|
|
|
if self.confirm_clear {
|
|
ui.label("Tous les messages du projet seront supprimés.");
|
|
ui.horizontal(|ui| {
|
|
if ui.button("Oui, vider").clicked() {
|
|
self.clear_project_context(project_id, ui.ctx());
|
|
}
|
|
if ui.button("Annuler").clicked() {
|
|
self.confirm_clear = false;
|
|
}
|
|
});
|
|
}
|
|
|
|
if let Some(project) = self.projects.iter().find(|item| item.id == project_id)
|
|
{
|
|
ui.small(format!("{} · {}", project.subtitle(), project.updated_label()));
|
|
if self.history_truncated {
|
|
ui.small("Historique tronqué : seuls les derniers messages sont chargés.");
|
|
}
|
|
}
|
|
}
|
|
});
|
|
}
|
|
}
|
|
|
|
impl eframe::App for JarviseApp {
|
|
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
|
|
self.drain_events(ui.ctx());
|
|
|
|
// A finished transcription is placed in the input then sent as-is.
|
|
if let Some(text) = self.pending_transcript.take() {
|
|
self.input = text;
|
|
self.send_message(ui.ctx());
|
|
}
|
|
|
|
// Count down the companion's short celebration.
|
|
if self.happy_timer > 0.0 {
|
|
self.happy_timer = (self.happy_timer - ui.input(|i| i.stable_dt)).max(0.0);
|
|
}
|
|
|
|
if self.token.is_none() {
|
|
self.login_screen(ui);
|
|
} else if self.user.is_none() {
|
|
// 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 {
|
|
// Keep the companion animation alive (~30 fps).
|
|
ui.ctx()
|
|
.request_repaint_after(std::time::Duration::from_millis(33));
|
|
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(),
|
|
project_id: self.current_project,
|
|
companion: self.mode == Mode::Companion,
|
|
};
|
|
eframe::set_value(storage, STORAGE_KEY, &persisted);
|
|
}
|
|
}
|
|
|
|
/// Applies the app's single dark theme: a deep, slightly blue background with
|
|
/// rounded widgets, so the interface looks the same on every desktop instead of
|
|
/// following the operating system colours.
|
|
fn apply_theme(ctx: &egui::Context) {
|
|
use egui::{Color32, CornerRadius, Stroke};
|
|
|
|
let mut visuals = egui::Visuals::dark();
|
|
visuals.panel_fill = Color32::from_rgb(0x12, 0x14, 0x1a);
|
|
visuals.window_fill = Color32::from_rgb(0x1a, 0x1d, 0x26);
|
|
visuals.extreme_bg_color = Color32::from_rgb(0x0d, 0x0f, 0x14);
|
|
visuals.faint_bg_color = Color32::from_rgb(0x1e, 0x22, 0x2c);
|
|
visuals.hyperlink_color = ACCENT;
|
|
visuals.selection.bg_fill = ACCENT.gamma_multiply(0.40);
|
|
visuals.window_corner_radius = CornerRadius::same(12);
|
|
visuals.menu_corner_radius = CornerRadius::same(10);
|
|
|
|
for widget in [
|
|
&mut visuals.widgets.inactive,
|
|
&mut visuals.widgets.hovered,
|
|
&mut visuals.widgets.active,
|
|
&mut visuals.widgets.open,
|
|
] {
|
|
widget.corner_radius = CornerRadius::same(9);
|
|
}
|
|
visuals.widgets.inactive.weak_bg_fill = Color32::from_rgb(0x22, 0x27, 0x33);
|
|
visuals.widgets.hovered.weak_bg_fill = Color32::from_rgb(0x2c, 0x33, 0x42);
|
|
visuals.widgets.active.weak_bg_fill = ACCENT.gamma_multiply(0.55);
|
|
visuals.widgets.hovered.bg_stroke = Stroke::new(1.0, ACCENT.gamma_multiply(0.7));
|
|
|
|
// Force dark regardless of what the desktop prefers.
|
|
ctx.set_theme(egui::ThemePreference::Dark);
|
|
ctx.set_visuals(visuals);
|
|
}
|
|
|
|
/// One line of the companion's subtitles: a rounded card holding who spoke and
|
|
/// what was said.
|
|
fn subtitle(ui: &mut egui::Ui, who: &str, text: &str, width: f32, from_jarvis: bool) {
|
|
let fill = if from_jarvis {
|
|
egui::Color32::from_rgb(0x1e, 0x22, 0x2c)
|
|
} else {
|
|
egui::Color32::from_rgb(0x24, 0x2c, 0x3d)
|
|
};
|
|
|
|
egui::Frame::new()
|
|
.fill(fill)
|
|
.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));
|
|
ui.vertical(|ui| {
|
|
ui.label(
|
|
egui::RichText::new(who)
|
|
.size(11.0)
|
|
.strong()
|
|
.color(ACCENT_SOFT),
|
|
);
|
|
ui.label(text);
|
|
});
|
|
});
|
|
}
|
|
|
|
/// A large circular push-to-talk button, painted by hand so it reads as a real
|
|
/// button. Returns the response the caller senses pointer state on.
|
|
fn mic_button(ui: &mut egui::Ui, active: bool, enabled: bool) -> egui::Response {
|
|
let diameter = (ui.available_width() * 0.20).clamp(80.0, 124.0);
|
|
let sense = if enabled {
|
|
egui::Sense::click()
|
|
} else {
|
|
egui::Sense::hover()
|
|
};
|
|
let (rect, response) = ui.allocate_exact_size(egui::Vec2::splat(diameter), sense);
|
|
let painter = ui.painter();
|
|
let center = rect.center();
|
|
let radius = diameter / 2.0;
|
|
|
|
let base = if active {
|
|
egui::Color32::from_rgb(0xe5, 0x54, 0x54)
|
|
} else if enabled {
|
|
ACCENT
|
|
} else {
|
|
egui::Color32::from_gray(70)
|
|
};
|
|
let fill = if response.hovered() && enabled {
|
|
base.gamma_multiply(1.12)
|
|
} else {
|
|
base
|
|
};
|
|
|
|
// Pulsing rings while recording.
|
|
if active {
|
|
let time = ui.input(|i| i.time) as f32;
|
|
for i in 0..2 {
|
|
let phase = ((time * 1.6 + i as f32 * 0.5) % 1.0 + 1.0) % 1.0;
|
|
painter.circle_stroke(
|
|
center,
|
|
radius * (1.0 + phase * 0.35),
|
|
egui::Stroke::new(2.0, base.gamma_multiply(0.7 * (1.0 - phase))),
|
|
);
|
|
}
|
|
}
|
|
|
|
painter.circle_filled(center, radius, fill);
|
|
painter.circle_stroke(
|
|
center,
|
|
radius,
|
|
egui::Stroke::new(2.0, base.gamma_multiply(0.6)),
|
|
);
|
|
painter.text(
|
|
center,
|
|
egui::Align2::CENTER_CENTER,
|
|
if active { "⏺" } else { "🎤" },
|
|
egui::FontId::proportional(radius * 0.85),
|
|
egui::Color32::WHITE,
|
|
);
|
|
|
|
response
|
|
}
|
|
|
|
/// Widest the centred conversation column may become, and the margin kept on
|
|
/// its sides when the window is narrower than that.
|
|
pub const COLUMN_MAX_WIDTH: f32 = 880.0;
|
|
pub const COLUMN_MIN_MARGIN: f32 = 16.0;
|
|
|
|
/// Draws the conversation in a centred, width-bounded column.
|
|
///
|
|
/// Public so the layout can be exercised headlessly by the tests.
|
|
pub fn chat_area(ui: &mut egui::Ui, messages: &[ChatMessage]) {
|
|
let available = ui.available_width();
|
|
let width = (available - 2.0 * COLUMN_MIN_MARGIN).min(COLUMN_MAX_WIDTH);
|
|
let side = ((available - width) / 2.0).max(0.0);
|
|
|
|
// The column is an explicit rect rather than a `ui.horizontal`: a scroll
|
|
// area inherits the layout of the `Ui` it is added to, and in a horizontal
|
|
// one its bubbles were laid out side by side — which is exactly what pushed
|
|
// them past the right edge of the window.
|
|
let rect = egui::Rect::from_min_size(
|
|
ui.next_widget_position() + egui::vec2(side, 0.0),
|
|
egui::vec2(width, ui.available_height()),
|
|
);
|
|
|
|
ui.scope_builder(
|
|
egui::UiBuilder::new()
|
|
.max_rect(rect)
|
|
.layout(egui::Layout::top_down(egui::Align::Min)),
|
|
|ui| {
|
|
egui::ScrollArea::vertical()
|
|
.auto_shrink([false, false])
|
|
.stick_to_bottom(true)
|
|
// Without an explicit maximum the scroll area grows to whatever
|
|
// its contents demand, which is what pushed bubbles past the window.
|
|
.max_width(width)
|
|
.show(ui, |ui| {
|
|
// Bubbles measure themselves against this value, so the
|
|
// constraint really reaches the text layout.
|
|
ui.set_max_width(width);
|
|
ui.add_space(14.0);
|
|
|
|
if messages.is_empty() {
|
|
ui.add_space(60.0);
|
|
ui.vertical_centered(|ui| {
|
|
ui.label(
|
|
egui::RichText::new(
|
|
"Aucun message. Écris quelque chose à Jarvis pour commencer.",
|
|
)
|
|
.color(egui::Color32::from_gray(150)),
|
|
);
|
|
});
|
|
}
|
|
|
|
for message in messages {
|
|
render_bubble(ui, message);
|
|
ui.add_space(10.0);
|
|
}
|
|
|
|
ui.add_space(14.0);
|
|
});
|
|
},
|
|
);
|
|
}
|
|
|
|
/// Draws a single message as a chat bubble and returns the rectangle it covers.
|
|
///
|
|
/// The text is laid out *before* the bubble is allocated: `egui` only wraps a
|
|
/// label when the surrounding `Ui` already knows how wide it may grow, which is
|
|
/// not guaranteed inside a scroll area — long answers used to be cut off at the
|
|
/// window edge instead of wrapping. Computing the galley ourselves removes the
|
|
/// guesswork, and returns the space actually taken by the bubble.
|
|
pub fn render_bubble(ui: &mut egui::Ui, message: &ChatMessage) -> egui::Rect {
|
|
const PADDING: f32 = 12.0;
|
|
/// Bubbles stay narrower than the column so the exchange reads as a dialogue.
|
|
const BUBBLE_RATIO: f32 = 0.82;
|
|
|
|
let max_bubble = (ui.available_width() * BUBBLE_RATIO).max(180.0);
|
|
let text_width = (max_bubble - 2.0 * PADDING).max(80.0);
|
|
|
|
let (fill, text_color) = if message.is_user() {
|
|
(
|
|
egui::Color32::from_rgb(0x2f, 0x6f, 0xb5),
|
|
egui::Color32::WHITE,
|
|
)
|
|
} else {
|
|
(egui::Color32::from_gray(58), egui::Color32::from_gray(238))
|
|
};
|
|
|
|
let text = if message.content.is_empty() {
|
|
"…"
|
|
} else {
|
|
message.content.as_str()
|
|
};
|
|
let galley = ui.ctx().fonts_mut(|fonts| {
|
|
fonts.layout(
|
|
text.to_string(),
|
|
egui::FontId::proportional(15.0),
|
|
text_color,
|
|
text_width,
|
|
)
|
|
});
|
|
let size = galley.size() + egui::vec2(2.0 * PADDING, 2.0 * PADDING);
|
|
|
|
// The user hugs the right edge of the column, Jarvis hugs the left one.
|
|
let inset = if message.is_user() {
|
|
(ui.available_width() - size.x).max(0.0)
|
|
} else {
|
|
0.0
|
|
};
|
|
|
|
ui.horizontal(|ui| {
|
|
if inset > 0.0 {
|
|
ui.add_space(inset);
|
|
}
|
|
let (_id, rect) = ui.allocate_space(size);
|
|
let painter = ui.painter();
|
|
painter.rect_filled(rect, egui::CornerRadius::same(12), fill);
|
|
painter.galley(
|
|
rect.min + egui::vec2(PADDING, PADDING),
|
|
galley,
|
|
text_color,
|
|
);
|
|
rect
|
|
})
|
|
.inner
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn theme_is_dark_and_wears_the_accent() {
|
|
let ctx = egui::Context::default();
|
|
apply_theme(&ctx);
|
|
|
|
let visuals = ctx.style_of(egui::Theme::Dark).visuals.clone();
|
|
assert!(visuals.dark_mode);
|
|
assert_eq!(visuals.panel_fill, egui::Color32::from_rgb(0x12, 0x14, 0x1a));
|
|
assert_eq!(visuals.selection.bg_fill, ACCENT.gamma_multiply(0.40));
|
|
}
|
|
|
|
/// The companion screen is a hand-painted stage; a headless pass proves the
|
|
/// avatar, the subtitles and the microphone button all lay out cleanly.
|
|
#[test]
|
|
fn companion_widgets_paint_without_panicking() {
|
|
let ctx = egui::Context::default();
|
|
ctx.set_fonts(egui::FontDefinitions::default());
|
|
|
|
let input = egui::RawInput {
|
|
screen_rect: Some(egui::Rect::from_min_size(
|
|
egui::Pos2::ZERO,
|
|
egui::vec2(900.0, 700.0),
|
|
)),
|
|
..Default::default()
|
|
};
|
|
|
|
let output = ctx.run_ui(input, |ui| {
|
|
egui::CentralPanel::default().show(ui, |ui| {
|
|
ui.vertical_centered(|ui| {
|
|
let pet = tamagotchi::draw_sized(ui, Mood::Listening, 1.0, 180.0);
|
|
assert_eq!(pet.rect.width(), 180.0);
|
|
subtitle(ui, "Vous", "Bonjour Jarvis", 600.0, false);
|
|
subtitle(ui, "Jarvis", "Bonjour, que puis-je faire ?", 600.0, true);
|
|
let mic = mic_button(ui, false, true);
|
|
assert!(mic.rect.width() >= 80.0);
|
|
});
|
|
});
|
|
});
|
|
// Nothing rasterises the fonts here, so the texture deltas can be dropped.
|
|
output.drop_without_applying_deltas();
|
|
}
|
|
|
|
#[test]
|
|
fn modes_have_distinct_tabs() {
|
|
assert_ne!(Mode::Chat.label(), Mode::Companion.label());
|
|
assert!(Mode::Chat.hint().to_lowercase().contains("écrire"));
|
|
assert!(Mode::Companion.hint().to_lowercase().contains("parler"));
|
|
}
|
|
}
|