feat(frontend): manage projects and their context in the desktop client
A conversation that only lives in memory is lost when the window closes, and long answers used to be cut off at the window edge because a scroll area inherits the layout of the parent it is added to. Projects give each exchange a durable context, the reload and verification actions make that context observable instead of a black box, and laying the text out before drawing the bubble keeps every answer inside the column.
This commit is contained in:
9 files changed
+2284
-212
No files matched your search
+298
-51
@@ -1,9 +1,10 @@
|
||||
//! Asynchronous HTTP client for the Jarvise backend.
|
||||
//!
|
||||
//! Handles authentication (`/api/auth/*`) and, most importantly, the streamed
|
||||
//! chat: it opens `POST /api/chat`, reads the `text/event-stream` body chunk by
|
||||
//! chunk and turns every `data:` line into a [`StreamEvent`]. Nothing here ever
|
||||
//! touches the GUI thread; callers spawn these futures on a Tokio runtime.
|
||||
//! Handles authentication (`/api/auth/*`), the projects and their message
|
||||
//! context (`/api/projects*`) and, most importantly, the streamed chat: it
|
||||
//! opens a `text/event-stream` request, reads the body chunk by chunk and turns
|
||||
//! every event into a [`StreamEvent`]. Nothing here ever touches the GUI
|
||||
//! thread; callers spawn these futures on a Tokio runtime.
|
||||
|
||||
use std::fmt;
|
||||
|
||||
@@ -13,7 +14,10 @@ use reqwest::StatusCode;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
use crate::model::{
|
||||
ChatMessage, ChatRequest, LoginRequest, LoginResponse, MeResponse, PublicUser, StreamData,
|
||||
AddMessageRequest, ChatMessage, ChatRequest, CreateProjectRequest, DeletedMessagesResponse,
|
||||
LoginRequest, LoginResponse, MeResponse, MessagePage, MessageResponse, Project,
|
||||
ProjectChatRequest, ProjectRecallRequest, ProjectResponse, ProjectsResponse, PublicUser,
|
||||
RecallDoneData, StreamData, StoredMessage, UpdateProjectRequest,
|
||||
};
|
||||
|
||||
/// Errors surfaced to the GUI (which displays them as-is).
|
||||
@@ -52,6 +56,18 @@ pub enum StreamEvent {
|
||||
Error(String),
|
||||
}
|
||||
|
||||
/// Event of a context verification stream.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum RecallEvent {
|
||||
/// A text fragment of the model's answer.
|
||||
Delta(String),
|
||||
/// Verification finished; the value is how many stored messages the backend
|
||||
/// replayed to the model.
|
||||
Done(usize),
|
||||
/// An inline error reported by the backend.
|
||||
Error(String),
|
||||
}
|
||||
|
||||
/// Thin wrapper around `reqwest::Client` bound to one backend and one token.
|
||||
///
|
||||
/// It is cheap to clone (the inner HTTP client is shared) which lets each
|
||||
@@ -121,33 +137,195 @@ impl ApiClient {
|
||||
/// Validates the current token and returns the associated user. Used at
|
||||
/// startup to check a cached token before showing the login screen.
|
||||
pub async fn me(&self) -> Result<PublicUser, ApiError> {
|
||||
let token = self
|
||||
.token
|
||||
.clone()
|
||||
.ok_or_else(|| ApiError::Network("aucun token enregistré".to_string()))?;
|
||||
let response: MeResponse = self.send_json(self.http.get(self.url("/api/auth/me"))).await?;
|
||||
Ok(response.user)
|
||||
}
|
||||
|
||||
let response = self
|
||||
/* ----------------------------------------------------------- projects */
|
||||
|
||||
/// All projects owned by the authenticated user.
|
||||
pub async fn list_projects(&self) -> Result<Vec<Project>, ApiError> {
|
||||
let response: ProjectsResponse =
|
||||
self.send_json(self.http.get(self.url("/api/projects"))).await?;
|
||||
Ok(response.projects)
|
||||
}
|
||||
|
||||
/// Creates a project and returns it as stored.
|
||||
pub async fn create_project(
|
||||
&self,
|
||||
name: &str,
|
||||
description: Option<&str>,
|
||||
) -> Result<Project, ApiError> {
|
||||
let request = CreateProjectRequest { name, description };
|
||||
let response: ProjectResponse = self
|
||||
.send_json(self.http.post(self.url("/api/projects")).json(&request))
|
||||
.await?;
|
||||
Ok(response.project)
|
||||
}
|
||||
|
||||
/// Renames a project and/or changes its description.
|
||||
pub async fn update_project(
|
||||
&self,
|
||||
id: i64,
|
||||
name: Option<&str>,
|
||||
description: Option<&str>,
|
||||
) -> Result<Project, ApiError> {
|
||||
let request = UpdateProjectRequest { name, description };
|
||||
let response: ProjectResponse = self
|
||||
.send_json(
|
||||
self.http
|
||||
.patch(self.url(&format!("/api/projects/{id}")))
|
||||
.json(&request),
|
||||
)
|
||||
.await?;
|
||||
Ok(response.project)
|
||||
}
|
||||
|
||||
/// Deletes a project and, by cascade, all of its messages.
|
||||
pub async fn delete_project(&self, id: i64) -> Result<(), ApiError> {
|
||||
self.send_empty(self.http.delete(self.url(&format!("/api/projects/{id}"))))
|
||||
.await
|
||||
}
|
||||
|
||||
/// A page of the project's context, oldest message first.
|
||||
pub async fn project_messages(&self, id: i64, limit: u32) -> Result<MessagePage, ApiError> {
|
||||
let url = self.url(&format!("/api/projects/{id}/messages?limit={limit}"));
|
||||
self.send_json(self.http.get(url)).await
|
||||
}
|
||||
|
||||
/// Appends a message to the project's context without calling the model
|
||||
/// (a system note, for instance).
|
||||
pub async fn add_project_message(
|
||||
&self,
|
||||
id: i64,
|
||||
role: &str,
|
||||
content: &str,
|
||||
) -> Result<StoredMessage, ApiError> {
|
||||
let request = AddMessageRequest { role, content };
|
||||
let response: MessageResponse = self
|
||||
.send_json(
|
||||
self.http
|
||||
.post(self.url(&format!("/api/projects/{id}/messages")))
|
||||
.json(&request),
|
||||
)
|
||||
.await?;
|
||||
Ok(response.message)
|
||||
}
|
||||
|
||||
/// Empties the project's context; returns how many messages were removed.
|
||||
pub async fn clear_project_messages(&self, id: i64) -> Result<i64, ApiError> {
|
||||
let response: DeletedMessagesResponse = self
|
||||
.send_json(
|
||||
self.http
|
||||
.delete(self.url(&format!("/api/projects/{id}/messages"))),
|
||||
)
|
||||
.await?;
|
||||
Ok(response.deleted)
|
||||
}
|
||||
|
||||
/// Asks Jarvis inside a project: the backend replays the stored context to
|
||||
/// Ollama, then persists both messages. Streamed like the stateless chat,
|
||||
/// with the named `delta` / `done` / `error` events.
|
||||
pub async fn stream_project_chat<F>(
|
||||
&self,
|
||||
project_id: i64,
|
||||
message: &str,
|
||||
model: &str,
|
||||
cancel: CancellationToken,
|
||||
mut on_event: F,
|
||||
) -> Result<(), ApiError>
|
||||
where
|
||||
F: FnMut(StreamEvent),
|
||||
{
|
||||
let request = self
|
||||
.http
|
||||
.get(self.url("/api/auth/me"))
|
||||
.bearer_auth(token)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|error| ApiError::Network(error.to_string()))?;
|
||||
|
||||
let status = response.status();
|
||||
if !status.is_success() {
|
||||
return Err(ApiError::Status {
|
||||
status,
|
||||
message: read_error_message(response).await,
|
||||
.post(self.url(&format!("/api/projects/{project_id}/chat/stream")))
|
||||
.bearer_auth(self.token()?)
|
||||
.json(&ProjectChatRequest {
|
||||
message,
|
||||
model: Some(model),
|
||||
});
|
||||
}
|
||||
|
||||
let body = response
|
||||
.json::<MeResponse>()
|
||||
.await
|
||||
.map_err(|error| ApiError::Decode(error.to_string()))?;
|
||||
self.pump_sse(request, cancel, move |event, data| {
|
||||
match event {
|
||||
"done" => {
|
||||
on_event(StreamEvent::Done);
|
||||
return false;
|
||||
}
|
||||
"error" => {
|
||||
let message = serde_json::from_str::<StreamData>(data)
|
||||
.ok()
|
||||
.and_then(|payload| payload.error)
|
||||
.unwrap_or_else(|| data.to_string());
|
||||
on_event(StreamEvent::Error(message));
|
||||
return false;
|
||||
}
|
||||
_ => {
|
||||
if let Some(chunk) = serde_json::from_str::<StreamData>(data)
|
||||
.ok()
|
||||
.and_then(|payload| payload.content)
|
||||
{
|
||||
on_event(StreamEvent::Delta(chunk));
|
||||
}
|
||||
}
|
||||
}
|
||||
true
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
Ok(body.user)
|
||||
/// Asks the model to recite the project's stored context, so the user can
|
||||
/// check that the history really reaches Ollama. Nothing is persisted on
|
||||
/// the backend: this is a read-only probe, and `RecallEvent::Done` reports
|
||||
/// how many messages were replayed.
|
||||
pub async fn stream_project_recall<F>(
|
||||
&self,
|
||||
project_id: i64,
|
||||
model: &str,
|
||||
cancel: CancellationToken,
|
||||
mut on_event: F,
|
||||
) -> Result<(), ApiError>
|
||||
where
|
||||
F: FnMut(RecallEvent),
|
||||
{
|
||||
let request = self
|
||||
.http
|
||||
.post(self.url(&format!("/api/projects/{project_id}/context/recall")))
|
||||
.bearer_auth(self.token()?)
|
||||
.json(&ProjectRecallRequest {
|
||||
model: Some(model),
|
||||
});
|
||||
|
||||
self.pump_sse(request, cancel, move |event, data| {
|
||||
match event {
|
||||
"done" => {
|
||||
let context_messages = serde_json::from_str::<RecallDoneData>(data)
|
||||
.ok()
|
||||
.and_then(|payload| payload.context_messages)
|
||||
.unwrap_or(0);
|
||||
on_event(RecallEvent::Done(context_messages));
|
||||
return false;
|
||||
}
|
||||
"error" => {
|
||||
let message = serde_json::from_str::<StreamData>(data)
|
||||
.ok()
|
||||
.and_then(|payload| payload.error)
|
||||
.unwrap_or_else(|| data.to_string());
|
||||
on_event(RecallEvent::Error(message));
|
||||
return false;
|
||||
}
|
||||
_ => {
|
||||
if let Some(chunk) = serde_json::from_str::<StreamData>(data)
|
||||
.ok()
|
||||
.and_then(|payload| payload.content)
|
||||
{
|
||||
on_event(RecallEvent::Delta(chunk));
|
||||
}
|
||||
}
|
||||
}
|
||||
true
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Streams a chat completion.
|
||||
@@ -167,20 +345,51 @@ impl ApiClient {
|
||||
where
|
||||
F: FnMut(StreamEvent),
|
||||
{
|
||||
let token = self
|
||||
.token
|
||||
.clone()
|
||||
.ok_or_else(|| ApiError::Network("aucun token enregistré".to_string()))?;
|
||||
|
||||
let request = self
|
||||
.http
|
||||
.post(self.url("/api/chat"))
|
||||
.bearer_auth(token)
|
||||
.bearer_auth(self.token()?)
|
||||
.json(&ChatRequest {
|
||||
model: model.to_string(),
|
||||
messages,
|
||||
});
|
||||
|
||||
self.pump_sse(request, cancel, move |_event, data| {
|
||||
if data == "[DONE]" {
|
||||
on_event(StreamEvent::Done);
|
||||
return false;
|
||||
}
|
||||
|
||||
match serde_json::from_str::<StreamData>(data) {
|
||||
Ok(payload) => {
|
||||
if let Some(error) = payload.error {
|
||||
on_event(StreamEvent::Error(error));
|
||||
return false;
|
||||
}
|
||||
if let Some(chunk) = payload.content {
|
||||
on_event(StreamEvent::Delta(chunk));
|
||||
}
|
||||
}
|
||||
// Keep-alive comments or unknown events are ignored.
|
||||
Err(_) => {}
|
||||
}
|
||||
true
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Reads an SSE response and forwards `(event name, data)` to `on_event`,
|
||||
/// which returns `false` to stop reading. Shared by both chat endpoints:
|
||||
/// they only differ in how their events are named and interpreted.
|
||||
async fn pump_sse<F>(
|
||||
&self,
|
||||
request: reqwest::RequestBuilder,
|
||||
cancel: CancellationToken,
|
||||
mut on_event: F,
|
||||
) -> Result<(), ApiError>
|
||||
where
|
||||
F: FnMut(&str, &str) -> bool,
|
||||
{
|
||||
// The backend may take a while before sending the first byte (it opens
|
||||
// the Ollama stream first), so cancellation must also cover this phase.
|
||||
let response = tokio::select! {
|
||||
@@ -212,29 +421,13 @@ impl ApiClient {
|
||||
return Err(ApiError::Network(format!("flux interrompu : {error}")));
|
||||
}
|
||||
Some(Ok(event)) => {
|
||||
let data = event.data;
|
||||
let data = data.trim();
|
||||
let data = event.data.trim().to_string();
|
||||
if data.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if data == "[DONE]" {
|
||||
on_event(StreamEvent::Done);
|
||||
if !on_event(&event.event, &data) {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
match serde_json::from_str::<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,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -242,6 +435,60 @@ impl ApiClient {
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------ helpers */
|
||||
|
||||
/// Bearer token of the current session, or an error when logged out.
|
||||
fn token(&self) -> Result<String, ApiError> {
|
||||
self.token
|
||||
.clone()
|
||||
.ok_or_else(|| ApiError::Network("aucun token enregistré".to_string()))
|
||||
}
|
||||
|
||||
/// Sends an authenticated request and decodes its JSON body, turning a
|
||||
/// non-success status into an [`ApiError::Status`].
|
||||
async fn send_json<T: serde::de::DeserializeOwned>(
|
||||
&self,
|
||||
request: reqwest::RequestBuilder,
|
||||
) -> Result<T, ApiError> {
|
||||
let response = request
|
||||
.bearer_auth(self.token()?)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|error| ApiError::Network(error.to_string()))?;
|
||||
|
||||
let status = response.status();
|
||||
if !status.is_success() {
|
||||
return Err(ApiError::Status {
|
||||
status,
|
||||
message: read_error_message(response).await,
|
||||
});
|
||||
}
|
||||
|
||||
response
|
||||
.json::<T>()
|
||||
.await
|
||||
.map_err(|error| ApiError::Decode(error.to_string()))
|
||||
}
|
||||
|
||||
/// Same as [`Self::send_json`] for endpoints answering with `204 No Content`.
|
||||
async fn send_empty(&self, request: reqwest::RequestBuilder) -> Result<(), ApiError> {
|
||||
let response = request
|
||||
.bearer_auth(self.token()?)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|error| ApiError::Network(error.to_string()))?;
|
||||
|
||||
let status = response.status();
|
||||
if !status.is_success() {
|
||||
return Err(ApiError::Status {
|
||||
status,
|
||||
message: read_error_message(response).await,
|
||||
});
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn url(&self, path: &str) -> String {
|
||||
format!("{}{}", self.base_url, path)
|
||||
}
|
||||
|
||||
+883
-155
File diff suppressed because it is too large.
Load diff
@@ -8,4 +8,5 @@ pub mod api;
|
||||
pub mod app;
|
||||
pub mod config;
|
||||
pub mod model;
|
||||
pub mod tamagotchi;
|
||||
pub mod voice;
|
||||
+158
-1
@@ -6,7 +6,7 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// A single conversation message, as expected in the `messages` array.
|
||||
#[derive(Serialize, Deserialize, Clone, PartialEq, Eq)]
|
||||
#[derive(Serialize, Deserialize, Clone, PartialEq, Eq, Debug)]
|
||||
pub struct ChatMessage {
|
||||
pub role: String,
|
||||
pub content: String,
|
||||
@@ -27,6 +27,13 @@ impl ChatMessage {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn system(content: impl Into<String>) -> Self {
|
||||
Self {
|
||||
role: "system".to_string(),
|
||||
content: content.into(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_user(&self) -> bool {
|
||||
self.role == "user"
|
||||
}
|
||||
@@ -84,3 +91,153 @@ impl PublicUser {
|
||||
self.name.clone().unwrap_or_else(|| self.email.clone())
|
||||
}
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------- projects */
|
||||
|
||||
/// A conversation project: its messages are the context sent to Jarvis.
|
||||
///
|
||||
/// The backend serialises the rows in camelCase (`messageCount`, `updatedAt`);
|
||||
/// fields the UI does not need are simply ignored by `serde`.
|
||||
#[derive(Serialize, Deserialize, Clone, PartialEq, Eq, Debug)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Project {
|
||||
pub id: i64,
|
||||
pub name: String,
|
||||
#[serde(default)]
|
||||
pub description: Option<String>,
|
||||
#[serde(default)]
|
||||
pub message_count: i64,
|
||||
#[serde(default)]
|
||||
pub updated_at: Option<String>,
|
||||
}
|
||||
|
||||
impl Project {
|
||||
/// `Projet · 12 messages`, shown in the project list.
|
||||
pub fn subtitle(&self) -> String {
|
||||
let count = if self.message_count > 1 {
|
||||
"messages"
|
||||
} else {
|
||||
"message"
|
||||
};
|
||||
format!("{} · {} {}", self.name, self.message_count, count)
|
||||
}
|
||||
|
||||
/// `modifié le 10-05 12:34`, extracted from the backend's
|
||||
/// `YYYY-MM-DD HH:MM:SS` timestamps.
|
||||
pub fn updated_label(&self) -> String {
|
||||
match self.updated_at.as_deref().and_then(|stamp| stamp.get(5..16)) {
|
||||
Some(short) => format!("modifié le {short}"),
|
||||
None => "jamais modifié".to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Body of `POST /api/projects`.
|
||||
#[derive(Serialize)]
|
||||
pub(crate) struct CreateProjectRequest<'a> {
|
||||
pub name: &'a str,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub description: Option<&'a str>,
|
||||
}
|
||||
|
||||
/// Body of `PATCH /api/projects/:id`; only the provided fields are sent.
|
||||
#[derive(Serialize)]
|
||||
pub(crate) struct UpdateProjectRequest<'a> {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub name: Option<&'a str>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub description: Option<&'a str>,
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------- messages */
|
||||
|
||||
/// A stored message of a project context, as returned by the backend.
|
||||
#[derive(Deserialize, Clone, PartialEq, Eq, Debug)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct StoredMessage {
|
||||
pub id: i64,
|
||||
pub role: String,
|
||||
pub content: String,
|
||||
#[serde(default)]
|
||||
pub created_at: Option<String>,
|
||||
}
|
||||
|
||||
impl StoredMessage {
|
||||
/// Same message in the shape used by the chat buffer and the SSE payloads.
|
||||
pub fn to_chat(&self) -> ChatMessage {
|
||||
ChatMessage {
|
||||
role: self.role.clone(),
|
||||
content: self.content.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
/// `HH:MM` extracted from the backend's `YYYY-MM-DD HH:MM:SS` timestamps.
|
||||
pub fn time_label(&self) -> Option<&str> {
|
||||
let stamp = self.created_at.as_deref()?;
|
||||
let time = stamp.get(11..)?;
|
||||
Some(&time[..5])
|
||||
}
|
||||
}
|
||||
|
||||
/// Body of `POST /api/projects/:id/messages`: appends a message to the context.
|
||||
#[derive(Serialize)]
|
||||
pub(crate) struct AddMessageRequest<'a> {
|
||||
pub role: &'a str,
|
||||
pub content: &'a str,
|
||||
}
|
||||
|
||||
/// Body of `POST /api/projects/:id/chat` and `.../chat/stream`: the backend
|
||||
/// reads the context from the database, so only the new prompt is sent.
|
||||
#[derive(Serialize)]
|
||||
pub(crate) struct ProjectChatRequest<'a> {
|
||||
pub message: &'a str,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub model: Option<&'a str>,
|
||||
}
|
||||
|
||||
/// Body of `POST /api/projects/:id/context/recall`: the question is optional,
|
||||
/// the backend asks its own by default.
|
||||
#[derive(Serialize)]
|
||||
pub(crate) struct ProjectRecallRequest<'a> {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub model: Option<&'a str>,
|
||||
}
|
||||
|
||||
/// `done` payload of the recall stream: how many stored messages were actually
|
||||
/// replayed to the model (the backend caps the context it sends).
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub(crate) struct RecallDoneData {
|
||||
pub context_messages: Option<usize>,
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------- API envelopes */
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub(crate) struct ProjectsResponse {
|
||||
pub projects: Vec<Project>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub(crate) struct ProjectResponse {
|
||||
pub project: Project,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub(crate) struct MessageResponse {
|
||||
pub message: StoredMessage,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub(crate) struct DeletedMessagesResponse {
|
||||
pub deleted: i64,
|
||||
}
|
||||
|
||||
/// One page of a project's context, oldest message first.
|
||||
#[derive(Deserialize, Debug)]
|
||||
pub struct MessagePage {
|
||||
pub messages: Vec<StoredMessage>,
|
||||
/// Older messages exist and were left out of this page.
|
||||
#[serde(default)]
|
||||
pub has_more: bool,
|
||||
}
|
||||
@@ -0,0 +1,233 @@
|
||||
//! A small animated companion (a "tamagotchi") drawn with egui shapes.
|
||||
//!
|
||||
//! It reacts to what the app is doing: idle, listening, thinking, speaking,
|
||||
//! happy or worried — giving the interface a living, friendly touch without any
|
||||
//! image asset.
|
||||
|
||||
use std::f32::consts::PI;
|
||||
|
||||
use eframe::egui::{self, Color32, Pos2, Sense, Stroke, Vec2};
|
||||
|
||||
/// What the companion is expressing right now.
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Mood {
|
||||
/// Nothing special: gentle bob and occasional blink.
|
||||
Idle,
|
||||
/// The microphone is recording (push-to-talk held).
|
||||
Listening,
|
||||
/// Jarvis is generating an answer.
|
||||
Thinking,
|
||||
/// The answer is being read out loud (TTS).
|
||||
Speaking,
|
||||
/// Short celebration after a successful answer.
|
||||
Happy,
|
||||
/// The last operation failed.
|
||||
Error,
|
||||
}
|
||||
|
||||
impl Mood {
|
||||
/// Short French label shown under the title.
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
Mood::Idle => "au repos",
|
||||
Mood::Listening => "je t'écoute…",
|
||||
Mood::Thinking => "je réfléchis…",
|
||||
Mood::Speaking => "je parle…",
|
||||
Mood::Happy => "content !",
|
||||
Mood::Error => "oups…",
|
||||
}
|
||||
}
|
||||
|
||||
/// Tooltip text for the widget.
|
||||
pub fn tooltip(self) -> String {
|
||||
format!("Jarvibot — {}", self.label())
|
||||
}
|
||||
|
||||
fn body_and_accent(self) -> (Color32, Color32) {
|
||||
match self {
|
||||
Mood::Idle => (
|
||||
Color32::from_rgb(0x4c, 0x8b, 0xf5),
|
||||
Color32::from_rgb(0x1f, 0x4c, 0x9c),
|
||||
),
|
||||
Mood::Listening => (
|
||||
Color32::from_rgb(0x2e, 0xc4, 0x8a),
|
||||
Color32::from_rgb(0x18, 0x7a, 0x55),
|
||||
),
|
||||
Mood::Thinking => (
|
||||
Color32::from_rgb(0xf5, 0xb0, 0x2e),
|
||||
Color32::from_rgb(0xa8, 0x6f, 0x0f),
|
||||
),
|
||||
Mood::Speaking => (
|
||||
Color32::from_rgb(0xa0, 0x6b, 0xf5),
|
||||
Color32::from_rgb(0x63, 0x39, 0xa8),
|
||||
),
|
||||
Mood::Happy => (
|
||||
Color32::from_rgb(0xf5, 0x6b, 0xa0),
|
||||
Color32::from_rgb(0xa8, 0x33, 0x66),
|
||||
),
|
||||
Mood::Error => (
|
||||
Color32::from_rgb(0xe5, 0x4b, 0x4b),
|
||||
Color32::from_rgb(0x99, 0x28, 0x28),
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Draws the companion in the current `ui`, animated with `time` (seconds).
|
||||
///
|
||||
/// Returns the widget [`egui::Response`] so callers can attach a tooltip.
|
||||
pub fn draw(ui: &mut egui::Ui, mood: Mood, time: f64) -> egui::Response {
|
||||
let (rect, response) = ui.allocate_exact_size(Vec2::splat(40.0), Sense::hover());
|
||||
let painter = ui.painter();
|
||||
|
||||
let (body, accent) = mood.body_and_accent();
|
||||
let time = time as f32;
|
||||
|
||||
// Gentle vertical bob; a bit livelier when the app is busy.
|
||||
let bob = (time * 2.2).sin() * if mood == Mood::Idle { 1.0 } else { 1.8 };
|
||||
let center = Pos2::new(rect.center().x, rect.center().y + 3.0 + bob);
|
||||
let radius = rect.height() * 0.33;
|
||||
|
||||
// Ground shadow.
|
||||
painter.circle_filled(
|
||||
Pos2::new(center.x, rect.bottom() - 2.5),
|
||||
radius * 0.7,
|
||||
Color32::from_black_alpha(70),
|
||||
);
|
||||
|
||||
// Antenna with a glowing tip.
|
||||
let tip = Pos2::new(center.x, center.y - radius - 6.0);
|
||||
painter.line_segment(
|
||||
[Pos2::new(center.x, center.y - radius + 2.0), tip],
|
||||
Stroke::new(1.6, accent),
|
||||
);
|
||||
let glow = 1.5 + (time * 3.0).sin() * 0.6;
|
||||
painter.circle_filled(tip, glow.max(1.0), body);
|
||||
|
||||
// Listening: expanding pulse rings.
|
||||
if mood == Mood::Listening {
|
||||
for i in 0..2 {
|
||||
let phase = ((time * 2.0 + i as f32 * 0.5) % 1.0 + 1.0) % 1.0;
|
||||
painter.circle_stroke(
|
||||
center,
|
||||
radius + 2.0 + phase * 5.0,
|
||||
Stroke::new(1.4, body.gamma_multiply(0.8 * (1.0 - phase))),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Thinking: little dots orbiting above the head.
|
||||
if mood == Mood::Thinking {
|
||||
for i in 0..3 {
|
||||
let angle = time * 3.0 + i as f32 * (2.0 * PI / 3.0);
|
||||
let dot = Pos2::new(
|
||||
center.x + angle.sin() * (radius + 6.0),
|
||||
center.y - radius - 7.0 - angle.cos() * 3.0,
|
||||
);
|
||||
painter.circle_filled(dot, 2.0, accent);
|
||||
}
|
||||
}
|
||||
|
||||
// Body and outline.
|
||||
painter.circle_filled(center, radius, body);
|
||||
painter.circle_stroke(center, radius, Stroke::new(1.5, accent));
|
||||
|
||||
// Cheeks.
|
||||
let cheek = Color32::from_white_alpha(46);
|
||||
painter.circle_filled(
|
||||
Pos2::new(center.x - radius * 0.56, center.y + radius * 0.12),
|
||||
radius * 0.17,
|
||||
cheek,
|
||||
);
|
||||
painter.circle_filled(
|
||||
Pos2::new(center.x + radius * 0.56, center.y + radius * 0.12),
|
||||
radius * 0.17,
|
||||
cheek,
|
||||
);
|
||||
|
||||
// Eyes.
|
||||
let eye_y = center.y - radius * 0.22;
|
||||
let eye_dx = radius * 0.38;
|
||||
let blinking = mood == Mood::Idle && (time % 3.2) < 0.12;
|
||||
|
||||
if mood == Mood::Error {
|
||||
// Crossed-out eyes.
|
||||
for side in [-1.0_f32, 1.0] {
|
||||
let c = Pos2::new(center.x + side * eye_dx, eye_y);
|
||||
let d = radius * 0.16;
|
||||
painter.line_segment(
|
||||
[Pos2::new(c.x - d, c.y - d), Pos2::new(c.x + d, c.y + d)],
|
||||
Stroke::new(2.0, Color32::WHITE),
|
||||
);
|
||||
painter.line_segment(
|
||||
[Pos2::new(c.x - d, c.y + d), Pos2::new(c.x + d, c.y - d)],
|
||||
Stroke::new(2.0, Color32::WHITE),
|
||||
);
|
||||
}
|
||||
} else if blinking {
|
||||
for side in [-1.0_f32, 1.0] {
|
||||
let c = Pos2::new(center.x + side * eye_dx, eye_y);
|
||||
painter.line_segment(
|
||||
[
|
||||
Pos2::new(c.x - radius * 0.14, c.y),
|
||||
Pos2::new(c.x + radius * 0.14, c.y),
|
||||
],
|
||||
Stroke::new(2.0, Color32::WHITE),
|
||||
);
|
||||
}
|
||||
} else {
|
||||
for side in [-1.0_f32, 1.0] {
|
||||
painter.circle_filled(
|
||||
Pos2::new(center.x + side * eye_dx, eye_y),
|
||||
radius * 0.15,
|
||||
Color32::WHITE,
|
||||
);
|
||||
painter.circle_filled(
|
||||
Pos2::new(center.x + side * eye_dx + radius * 0.05, eye_y),
|
||||
radius * 0.07,
|
||||
Color32::from_rgb(0x1c, 0x1c, 0x24),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Mouth.
|
||||
let mouth_y = center.y + radius * 0.34;
|
||||
match mood {
|
||||
Mood::Speaking => {
|
||||
let open = (time * 12.0).sin().abs();
|
||||
painter.circle_filled(
|
||||
Pos2::new(center.x, mouth_y),
|
||||
radius * (0.10 + 0.12 * open),
|
||||
Color32::from_rgb(0x2a, 0x18, 0x18),
|
||||
);
|
||||
}
|
||||
Mood::Happy | Mood::Listening => smile(painter, center.x, mouth_y, radius, false),
|
||||
Mood::Error => smile(painter, center.x, mouth_y, radius, true),
|
||||
Mood::Idle | Mood::Thinking => {
|
||||
painter.line_segment(
|
||||
[
|
||||
Pos2::new(center.x - radius * 0.16, mouth_y),
|
||||
Pos2::new(center.x + radius * 0.16, mouth_y),
|
||||
],
|
||||
Stroke::new(1.8, Color32::WHITE),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
response
|
||||
}
|
||||
|
||||
/// Draws a curved mouth (a smile, or a frown when `inverted`).
|
||||
fn smile(painter: &egui::Painter, cx: f32, y: f32, radius: f32, inverted: bool) {
|
||||
let half = radius * 0.45;
|
||||
let depth = radius * 0.5 * if inverted { -1.0 } else { 1.0 };
|
||||
let steps = 7;
|
||||
let mut previous = Pos2::new(cx - half, y);
|
||||
|
||||
for i in 1..=steps {
|
||||
let f = i as f32 / steps as f32;
|
||||
let point = Pos2::new(cx - half + 2.0 * half * f, y + (f * PI).sin() * depth);
|
||||
painter.line_segment([previous, point], Stroke::new(1.8, Color32::WHITE));
|
||||
previous = point;
|
||||
}
|
||||
}
|
||||
@@ -63,6 +63,8 @@ fn is_file(path: &Path) -> bool {
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum VoiceEvent {
|
||||
Transcribed(String),
|
||||
/// Playback of a synthesized answer finished.
|
||||
Spoken,
|
||||
TranscriptionError(String),
|
||||
SpeechError(String),
|
||||
}
|
||||
@@ -173,8 +175,11 @@ where
|
||||
}
|
||||
match tts.as_mut().expect("tts initialised above").synthesize(&text) {
|
||||
Ok((samples, sample_rate)) => {
|
||||
if let Err(error) = audio::play_blocking(&samples, sample_rate) {
|
||||
on_event(VoiceEvent::SpeechError(error.to_string()));
|
||||
match audio::play_blocking(&samples, sample_rate) {
|
||||
Ok(()) => on_event(VoiceEvent::Spoken),
|
||||
Err(error) => {
|
||||
on_event(VoiceEvent::SpeechError(error.to_string()))
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(error) => on_event(VoiceEvent::SpeechError(error.to_string())),
|
||||
|
||||
Reference in new issue
Block a user