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
+44
-3
@@ -116,6 +116,40 @@ Le bouton « Stopper » annule un `CancellationToken` (tokio-util) : la tâche d
|
||||
s'arrête immédiatement et la connexion HTTP est coupée, ce qui permet au backend
|
||||
d'interrompre la requête auprès d'Ollama (économie GPU/CPU).
|
||||
|
||||
### Projets et contexte
|
||||
|
||||
La barre latérale de gauche pilote les **projets** du backend : une conversation =
|
||||
une mémoire persistante.
|
||||
|
||||
- **Sans projet** : chaque message part avec l'historique de la fenêtre (endpoint
|
||||
`POST /api/chat`), rien n'est enregistré côté serveur.
|
||||
- **Un projet sélectionné** : l'historique est rechargé depuis
|
||||
`GET /api/projects/:id/messages`, et l'envoi passe par
|
||||
`POST /api/projects/:id/chat/stream`. Le backend y rejoue le contexte stocké vers
|
||||
Ollama, puis enregistre la question **et** la réponse — les événements SSE sont
|
||||
alors nommés :
|
||||
|
||||
| Événement reçu | Traitement |
|
||||
| ------------------- | --------------------------------------------------- |
|
||||
| `event: delta` | fragment ajouté à la bulle assistant |
|
||||
| `event: done` | fin de génération + compteurs de la barre rafraîchis |
|
||||
| `event: error` | erreur affichée dans la GUI |
|
||||
|
||||
- Depuis la barre latérale : création (`POST /api/projects`), renommage
|
||||
(`PATCH /api/projects/:id`), suppression (`DELETE /api/projects/:id`, avec
|
||||
confirmation), ajout d'une **note système** au contexte (`POST
|
||||
/api/projects/:id/messages`) et vidage de l'historique (`DELETE
|
||||
/api/projects/:id/messages`).
|
||||
- **⟳ Recharger** relit le contexte depuis le backend ; **🧠 Vérifier** demande à Jarvis de
|
||||
**réciter** ce qu'il a reçu (`POST /api/projects/:id/context/recall`). Cette sonde
|
||||
n'enregistre rien : l'événement `done` renvoie `contextMessages`, le nombre exact de
|
||||
messages réellement renvoyés au modèle, affiché dans la bulle de légende.
|
||||
- Le projet ouvert est mémorisé et rouvert au lancement suivant.
|
||||
|
||||
La conversation est dessinée dans une **colonne centrée** de largeur bornée : le texte
|
||||
est mis en page *avant* l'allocation de la bulle, ce qui garantit qu'une longue réponse
|
||||
se replie au lieu de déborder de la fenêtre.
|
||||
|
||||
### Gestion des erreurs
|
||||
|
||||
- Backend injoignable → message réseau affiché dans la GUI.
|
||||
@@ -162,7 +196,8 @@ src/
|
||||
config.rs # configuration (variables d'environnement)
|
||||
model.rs # structs serde partagées avec le backend
|
||||
api.rs # client HTTP : login, /me, flux SSE (eventsource-stream + CancellationToken)
|
||||
app.rs # état de l'app, écran de connexion, chat egui, persistance, push-to-talk
|
||||
app.rs # état de l'app, connexion, barre projets, chat egui, persistance
|
||||
tamagotchi.rs # compagnon animé dont l'humeur suit l'état de l'app
|
||||
voice/
|
||||
mod.rs # module voix
|
||||
audio.rs # micro (cpal) + lecture haut-parleur + rééchantillonnage
|
||||
@@ -170,7 +205,9 @@ src/
|
||||
tts.rs # text-to-speech embarqué (piper-rs)
|
||||
engine.rs # thread dédié (chargement paresseux des modèles, commandes/évènements)
|
||||
tests/
|
||||
stream_sse.rs # tests d'intégration du client SSE contre un serveur HTTP local
|
||||
stream_sse.rs # tests d'intégration du client SSE contre un serveur HTTP local
|
||||
projects_api.rs # endpoints projets/contexte + SSE nommé du chat par projet
|
||||
chat_layout.rs # mise en page headless : les bulles restent dans la colonne
|
||||
```
|
||||
|
||||
## Tests
|
||||
@@ -184,7 +221,11 @@ cargo test
|
||||
- **Intégration** : un petit serveur HTTP rejoue le contrat du backend et vérifie, à travers le
|
||||
vrai code `reqwest` + `eventsource-stream` : le body envoyé (`model` + `messages`), l'en-tête
|
||||
`Authorization`, l'assemblage des fragments, `[DONE]`, l'erreur inline `data: {"error":...}`
|
||||
et le cas d'un statut HTTP non-200.
|
||||
et le cas d'un statut HTTP non-200. Le même principe couvre les routes projets
|
||||
(création, renommage, suppression, contexte, note système) et les événements nommés
|
||||
`delta` / `done` / `error` du chat par projet.
|
||||
- **Mise en page** : un passage `egui` sans fenêtre mesure les rectangles peints, et vérifie
|
||||
qu'une longue réponse se replie **dans** la colonne centrée (y compris sur fenêtre étroite).
|
||||
|
||||
## Dépannage
|
||||
|
||||
|
||||
+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())),
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
//! Headless layout tests of the conversation area.
|
||||
//!
|
||||
//! `egui` runs fine without a window: a pass is fed a `RawInput` with a fixed
|
||||
//! screen size and the painted shapes come back in the `FullOutput`. Bubbles
|
||||
//! are painted as filled rectangles with their own colours, so they can be
|
||||
//! measured to prove that long answers wrap *inside* the centred column instead
|
||||
//! of running past the edge of the window.
|
||||
|
||||
use eframe::egui;
|
||||
use jarvise_frontend::app::{COLUMN_MAX_WIDTH, COLUMN_MIN_MARGIN, chat_area};
|
||||
use jarvise_frontend::model::ChatMessage;
|
||||
|
||||
/// Colour of the user's bubbles.
|
||||
const USER_FILL: egui::Color32 = egui::Color32::from_rgb(0x2f, 0x6f, 0xb5);
|
||||
/// Colour of Jarvis' bubbles.
|
||||
const JARVIS_FILL: egui::Color32 = egui::Color32::from_gray(58);
|
||||
|
||||
/// A paragraph long enough to need several lines in a bubble.
|
||||
fn long_text() -> String {
|
||||
"Jarvise garde le contexte de chaque projet et le renvoie au modèle à chaque tour de parole. "
|
||||
.repeat(8)
|
||||
}
|
||||
|
||||
/// Column `chat_area` builds inside a window of `screen_width`.
|
||||
fn column(screen_width: f32) -> (f32, f32) {
|
||||
let width = (screen_width - 2.0 * COLUMN_MIN_MARGIN).min(COLUMN_MAX_WIDTH);
|
||||
let side = ((screen_width - width) / 2.0).max(0.0);
|
||||
(side, side + width)
|
||||
}
|
||||
|
||||
/// Runs one egui pass on a window of the given width and returns what was painted.
|
||||
fn painted(screen_width: f32, messages: &[ChatMessage]) -> Vec<egui::epaint::ClippedShape> {
|
||||
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(screen_width, 900.0),
|
||||
)),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let mut output = ctx.run_ui(input, |ui| chat_area(ui, messages));
|
||||
let shapes = std::mem::take(&mut output.shapes);
|
||||
// Nothing rasterises the fonts here, so the texture deltas can be dropped.
|
||||
output.drop_without_applying_deltas();
|
||||
shapes
|
||||
}
|
||||
|
||||
/// Filled rectangles painted with a bubble colour, i.e. the bubbles themselves.
|
||||
fn bubbles(shapes: &[egui::epaint::ClippedShape]) -> Vec<egui::Rect> {
|
||||
shapes
|
||||
.iter()
|
||||
.filter_map(|clipped| match &clipped.shape {
|
||||
egui::Shape::Rect(rect) if rect.fill == USER_FILL || rect.fill == JARVIS_FILL => {
|
||||
Some(rect.rect)
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn long_answers_wrap_inside_the_centred_column() {
|
||||
let messages = vec![
|
||||
ChatMessage::assistant(long_text()),
|
||||
ChatMessage::user(long_text()),
|
||||
];
|
||||
|
||||
let shapes = painted(1400.0, &messages);
|
||||
let rects = bubbles(&shapes);
|
||||
assert_eq!(rects.len(), 2, "one bubble per message, got {rects:?}");
|
||||
|
||||
let (left, right) = column(1400.0);
|
||||
for rect in &rects {
|
||||
assert!(
|
||||
rect.min.x >= left - 1.0 && rect.max.x <= right + 1.0,
|
||||
"bubble {rect:?} escapes the column [{left}, {right}]"
|
||||
);
|
||||
assert!(
|
||||
rect.width() <= (right - left) * 0.83,
|
||||
"bubble {rect:?} is wider than the column"
|
||||
);
|
||||
// A single line would be ~20 pt high: several lines prove the text wrapped.
|
||||
assert!(
|
||||
rect.height() > 40.0,
|
||||
"long text was not wrapped, bubble {rect:?} is one line high"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bubbles_stay_on_screen_in_a_narrow_window() {
|
||||
let messages = vec![
|
||||
ChatMessage::user(long_text()),
|
||||
ChatMessage::assistant(long_text()),
|
||||
];
|
||||
|
||||
let shapes = painted(420.0, &messages);
|
||||
let (left, right) = column(420.0);
|
||||
for rect in bubbles(&shapes) {
|
||||
assert!(
|
||||
rect.min.x >= left - 1.0 && rect.max.x <= right + 1.0,
|
||||
"bubble {rect:?} escapes the column [{left}, {right}] of a 420 pt window"
|
||||
);
|
||||
assert!(rect.max.x <= 420.0, "bubble {rect:?} runs off the window");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn user_bubbles_hug_the_right_and_jarvis_the_left() {
|
||||
let messages = vec![
|
||||
ChatMessage::assistant("Salut"),
|
||||
ChatMessage::user("Salut"),
|
||||
];
|
||||
|
||||
let shapes = painted(1400.0, &messages);
|
||||
let rects = bubbles(&shapes);
|
||||
assert_eq!(rects.len(), 2);
|
||||
|
||||
let jarvis = rects.iter().find(|rect| rect.width() > 0.0 && rect.min.x < 300.0);
|
||||
assert!(jarvis.is_some(), "Jarvis' bubble must start at the left: {rects:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_conversation_paints_no_bubble() {
|
||||
let shapes = painted(1400.0, &[]);
|
||||
|
||||
assert!(
|
||||
bubbles(&shapes).is_empty(),
|
||||
"the placeholder must not look like a message"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,526 @@
|
||||
//! Integration tests for the projects and their message context.
|
||||
//!
|
||||
//! A fake HTTP server stands in for the backend, so the real reqwest code path
|
||||
//! is exercised end to end: request method and path, JSON bodies, camelCase
|
||||
//! decoding, the `204 No Content` of a deletion and the named SSE events of
|
||||
//! `POST /api/projects/:id/chat/stream`.
|
||||
|
||||
use std::io::{Read, Write};
|
||||
use std::net::{TcpListener, TcpStream};
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::thread;
|
||||
|
||||
use jarvise_frontend::api::{ApiClient, ApiError, RecallEvent, StreamEvent};
|
||||
use jarvise_frontend::model::{Project, StoredMessage};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
/// What the fake server received.
|
||||
#[derive(Clone, Debug)]
|
||||
struct CapturedRequest {
|
||||
method: String,
|
||||
target: String,
|
||||
body: String,
|
||||
}
|
||||
|
||||
/// Answer of the fake server.
|
||||
struct FakeReply {
|
||||
status_line: &'static str,
|
||||
content_type: &'static str,
|
||||
body: String,
|
||||
}
|
||||
|
||||
impl FakeReply {
|
||||
fn json(body: impl Into<String>) -> Self {
|
||||
Self {
|
||||
status_line: "HTTP/1.1 200 OK",
|
||||
content_type: "application/json",
|
||||
body: body.into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn created(body: impl Into<String>) -> Self {
|
||||
Self {
|
||||
status_line: "HTTP/1.1 201 Created",
|
||||
content_type: "application/json",
|
||||
body: body.into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn empty() -> Self {
|
||||
Self {
|
||||
status_line: "HTTP/1.1 204 No Content",
|
||||
content_type: "application/json",
|
||||
body: String::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn sse(body: impl Into<String>) -> Self {
|
||||
Self {
|
||||
status_line: "HTTP/1.1 200 OK",
|
||||
content_type: "text/event-stream",
|
||||
body: body.into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn status(status_line: &'static str, body: impl Into<String>) -> Self {
|
||||
Self {
|
||||
status_line,
|
||||
content_type: "application/json",
|
||||
body: body.into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct FakeServer {
|
||||
base_url: String,
|
||||
requests: Arc<Mutex<Vec<CapturedRequest>>>,
|
||||
stop: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
impl FakeServer {
|
||||
fn client(&self) -> ApiClient {
|
||||
let mut client = ApiClient::new(self.base_url.clone());
|
||||
client.set_token(Some("test-token".to_string()));
|
||||
client
|
||||
}
|
||||
|
||||
/// Requests received so far, in order.
|
||||
fn requests(&self) -> Vec<CapturedRequest> {
|
||||
self.requests.lock().expect("lock").clone()
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for FakeServer {
|
||||
fn drop(&mut self) {
|
||||
self.stop.store(true, Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
|
||||
/// Starts a server answering every request through `handler` until dropped.
|
||||
fn start_server<H>(handler: H) -> FakeServer
|
||||
where
|
||||
H: Fn(&CapturedRequest) -> FakeReply + Send + Sync + 'static,
|
||||
{
|
||||
let listener = TcpListener::bind("127.0.0.1:0").expect("bind");
|
||||
listener.set_nonblocking(true).expect("nonblocking");
|
||||
let base_url = format!("http://{}", listener.local_addr().expect("addr"));
|
||||
let requests = Arc::new(Mutex::new(Vec::new()));
|
||||
let stop = Arc::new(AtomicBool::new(false));
|
||||
|
||||
let sink = requests.clone();
|
||||
let flag = stop.clone();
|
||||
thread::spawn(move || {
|
||||
while !flag.load(Ordering::SeqCst) {
|
||||
match listener.accept() {
|
||||
Ok((mut socket, _)) => {
|
||||
socket.set_nonblocking(false).expect("blocking socket");
|
||||
let request = read_request(&mut socket);
|
||||
let reply = handler(&request);
|
||||
sink.lock().expect("lock").push(request);
|
||||
|
||||
let response = format!(
|
||||
"{}\r\nContent-Type: {}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
|
||||
reply.status_line,
|
||||
reply.content_type,
|
||||
reply.body.len(),
|
||||
reply.body
|
||||
);
|
||||
let _ = socket.write_all(response.as_bytes());
|
||||
let _ = socket.flush();
|
||||
}
|
||||
Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
|
||||
thread::sleep(std::time::Duration::from_millis(2));
|
||||
}
|
||||
Err(_) => break,
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
FakeServer {
|
||||
base_url,
|
||||
requests,
|
||||
stop,
|
||||
}
|
||||
}
|
||||
|
||||
fn read_request(socket: &mut TcpStream) -> CapturedRequest {
|
||||
let mut data = Vec::new();
|
||||
let mut buffer = [0u8; 1024];
|
||||
|
||||
loop {
|
||||
match socket.read(&mut buffer) {
|
||||
Ok(0) | Err(_) => break,
|
||||
Ok(n) => {
|
||||
data.extend_from_slice(&buffer[..n]);
|
||||
if let Some(header_end) = find(&data, b"\r\n\r\n") {
|
||||
let head = String::from_utf8_lossy(&data[..header_end]).to_string();
|
||||
let length = content_length(&head);
|
||||
let body_start = header_end + 4;
|
||||
while data.len() < body_start + length {
|
||||
match socket.read(&mut buffer) {
|
||||
Ok(0) | Err(_) => break,
|
||||
Ok(n) => data.extend_from_slice(&buffer[..n]),
|
||||
}
|
||||
}
|
||||
let body = String::from_utf8_lossy(&data[body_start..]).to_string();
|
||||
|
||||
let mut lines = head.lines();
|
||||
let mut start = lines.next().unwrap_or_default().split_whitespace();
|
||||
let method = start.next().unwrap_or_default().to_string();
|
||||
let target = start.next().unwrap_or_default().to_string();
|
||||
|
||||
return CapturedRequest {
|
||||
method,
|
||||
target,
|
||||
body,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
CapturedRequest {
|
||||
method: String::new(),
|
||||
target: String::new(),
|
||||
body: String::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn find(haystack: &[u8], needle: &[u8]) -> Option<usize> {
|
||||
haystack
|
||||
.windows(needle.len())
|
||||
.position(|window| window == needle)
|
||||
}
|
||||
|
||||
fn content_length(head: &str) -> usize {
|
||||
head.lines()
|
||||
.find_map(|line| {
|
||||
let (name, value) = line.split_once(':')?;
|
||||
name.eq_ignore_ascii_case("content-length")
|
||||
.then(|| value.trim().parse().ok())
|
||||
.flatten()
|
||||
})
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
fn body_json(request: &CapturedRequest) -> serde_json::Value {
|
||||
serde_json::from_str(&request.body).expect("the request body must be JSON")
|
||||
}
|
||||
|
||||
fn sample_project() -> &'static str {
|
||||
r#"{
|
||||
"id": 3,
|
||||
"userId": 1,
|
||||
"name": "Jarvise",
|
||||
"description": "The assistant itself",
|
||||
"messageCount": 7,
|
||||
"createdAt": "2026-10-05 10:00:00",
|
||||
"updatedAt": "2026-10-05 12:34:00"
|
||||
}"#
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn lists_projects_and_decodes_camel_case() {
|
||||
let server = start_server(|_| {
|
||||
FakeReply::json(format!("{{\"projects\":[{}]}}", sample_project()))
|
||||
});
|
||||
|
||||
let projects = server.client().list_projects().await.expect("list projects");
|
||||
|
||||
assert_eq!(
|
||||
projects,
|
||||
vec![Project {
|
||||
id: 3,
|
||||
name: "Jarvise".to_string(),
|
||||
description: Some("The assistant itself".to_string()),
|
||||
message_count: 7,
|
||||
updated_at: Some("2026-10-05 12:34:00".to_string()),
|
||||
}]
|
||||
);
|
||||
|
||||
let requests = server.requests();
|
||||
assert_eq!(requests[0].method, "GET");
|
||||
assert_eq!(requests[0].target, "/api/projects");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn creates_a_project_with_its_description() {
|
||||
let server = start_server(|_| FakeReply::created(format!("{{\"project\":{}}}", sample_project())));
|
||||
|
||||
let project = server
|
||||
.client()
|
||||
.create_project("Jarvise", Some("The assistant itself"))
|
||||
.await
|
||||
.expect("create project");
|
||||
|
||||
assert_eq!(project.id, 3);
|
||||
assert_eq!(project.message_count, 7);
|
||||
|
||||
let requests = server.requests();
|
||||
assert_eq!(requests[0].method, "POST");
|
||||
assert_eq!(requests[0].target, "/api/projects");
|
||||
|
||||
let body = body_json(&requests[0]);
|
||||
assert_eq!(body["name"], "Jarvise");
|
||||
assert_eq!(body["description"], "The assistant itself");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn renames_then_deletes_a_project() {
|
||||
let server = start_server(|request| {
|
||||
if request.method == "DELETE" {
|
||||
FakeReply::empty()
|
||||
} else {
|
||||
FakeReply::json(format!("{{\"project\":{}}}", sample_project()))
|
||||
}
|
||||
});
|
||||
|
||||
let client = server.client();
|
||||
let renamed = client
|
||||
.update_project(3, Some("Jarvise 2"), None)
|
||||
.await
|
||||
.expect("rename project");
|
||||
assert_eq!(renamed.name, "Jarvise");
|
||||
client.delete_project(3).await.expect("delete project");
|
||||
|
||||
let requests = server.requests();
|
||||
assert_eq!(requests[0].method, "PATCH");
|
||||
assert_eq!(requests[0].target, "/api/projects/3");
|
||||
// `description` is left out so the backend keeps the stored value.
|
||||
assert_eq!(body_json(&requests[0]), serde_json::json!({"name": "Jarvise 2"}));
|
||||
|
||||
assert_eq!(requests[1].method, "DELETE");
|
||||
assert_eq!(requests[1].target, "/api/projects/3");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn loads_the_message_context_of_a_project() {
|
||||
let server = start_server(|_| {
|
||||
FakeReply::json(
|
||||
r#"{
|
||||
"projectId": 3,
|
||||
"messages": [
|
||||
{"id": 10, "projectId": 3, "role": "user", "content": "Bonjour", "createdAt": "2026-10-05 12:00:00"},
|
||||
{"id": 11, "projectId": 3, "role": "assistant", "content": "Bonjour !", "createdAt": "2026-10-05 12:00:09"}
|
||||
],
|
||||
"hasMore": false,
|
||||
"oldestId": 10
|
||||
}"#,
|
||||
)
|
||||
});
|
||||
|
||||
let page = server
|
||||
.client()
|
||||
.project_messages(3, 200)
|
||||
.await
|
||||
.expect("load messages");
|
||||
|
||||
assert!(!page.has_more);
|
||||
assert_eq!(page.messages.len(), 2);
|
||||
assert_eq!(page.messages[0].role, "user");
|
||||
assert_eq!(page.messages[0].to_chat().content, "Bonjour");
|
||||
assert_eq!(page.messages[1].time_label(), Some("12:00"));
|
||||
|
||||
let requests = server.requests();
|
||||
assert_eq!(requests[0].method, "GET");
|
||||
assert_eq!(requests[0].target, "/api/projects/3/messages?limit=200");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn adds_a_note_to_the_context_and_clears_it() {
|
||||
let server = start_server(|request| {
|
||||
if request.method == "DELETE" {
|
||||
FakeReply::json(r#"{"deleted": 4}"#)
|
||||
} else {
|
||||
FakeReply::created(
|
||||
r#"{"message":{"id": 12, "projectId": 3, "role": "system", "content": "Réponds en français.", "createdAt": "2026-10-05 12:40:00"}}"#,
|
||||
)
|
||||
}
|
||||
});
|
||||
|
||||
let client = server.client();
|
||||
let note = client
|
||||
.add_project_message(3, "system", "Réponds en français.")
|
||||
.await
|
||||
.expect("add message");
|
||||
assert_eq!(note.role, "system");
|
||||
assert_eq!(note.to_chat().content, "Réponds en français.");
|
||||
|
||||
let deleted = client
|
||||
.clear_project_messages(3)
|
||||
.await
|
||||
.expect("clear messages");
|
||||
assert_eq!(deleted, 4);
|
||||
|
||||
let requests = server.requests();
|
||||
assert_eq!(requests[0].method, "POST");
|
||||
assert_eq!(requests[0].target, "/api/projects/3/messages");
|
||||
assert_eq!(
|
||||
body_json(&requests[0]),
|
||||
serde_json::json!({"role": "system", "content": "Réponds en français."})
|
||||
);
|
||||
|
||||
assert_eq!(requests[1].method, "DELETE");
|
||||
assert_eq!(requests[1].target, "/api/projects/3/messages");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn streams_a_project_chat_with_named_events() {
|
||||
let server = start_server(|_| {
|
||||
FakeReply::sse(concat!(
|
||||
": stream open\n\n",
|
||||
"event: delta\ndata: {\"content\":\"Bonjour\"}\n\n",
|
||||
"event: delta\ndata: {\"content\":\" Tony\"}\n\n",
|
||||
"event: done\ndata: {\"reply\":\"Bonjour Tony\",\"model\":\"qwen2.5:3b\",\"projectId\":3,\"messages\":[]}\n\n",
|
||||
))
|
||||
});
|
||||
|
||||
let events = Arc::new(Mutex::new(Vec::new()));
|
||||
let sink = events.clone();
|
||||
|
||||
let result = server
|
||||
.client()
|
||||
.stream_project_chat(
|
||||
3,
|
||||
"Salut",
|
||||
"qwen2.5:3b",
|
||||
CancellationToken::new(),
|
||||
move |event| sink.lock().expect("lock").push(event),
|
||||
)
|
||||
.await;
|
||||
|
||||
result.expect("the project stream should succeed");
|
||||
assert_eq!(
|
||||
*events.lock().expect("lock"),
|
||||
vec![
|
||||
StreamEvent::Delta("Bonjour".to_string()),
|
||||
StreamEvent::Delta(" Tony".to_string()),
|
||||
StreamEvent::Done,
|
||||
]
|
||||
);
|
||||
|
||||
let requests = server.requests();
|
||||
assert_eq!(requests[0].method, "POST");
|
||||
assert_eq!(requests[0].target, "/api/projects/3/chat/stream");
|
||||
// The context lives in the backend: only the new prompt travels.
|
||||
assert_eq!(
|
||||
body_json(&requests[0]),
|
||||
serde_json::json!({"message": "Salut", "model": "qwen2.5:3b"})
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn reports_an_inline_error_event_of_a_project_chat() {
|
||||
let server = start_server(|_| {
|
||||
FakeReply::sse("event: error\ndata: {\"error\":\"Ollama injoignable\",\"partial\":\"\"}\n\n")
|
||||
});
|
||||
|
||||
let events = Arc::new(Mutex::new(Vec::new()));
|
||||
let sink = events.clone();
|
||||
|
||||
server
|
||||
.client()
|
||||
.stream_project_chat(
|
||||
3,
|
||||
"Salut",
|
||||
"qwen2.5:3b",
|
||||
CancellationToken::new(),
|
||||
move |event| sink.lock().expect("lock").push(event),
|
||||
)
|
||||
.await
|
||||
.expect("an inline error is not a transport failure");
|
||||
|
||||
assert_eq!(
|
||||
*events.lock().expect("lock"),
|
||||
vec![StreamEvent::Error("Ollama injoignable".to_string())]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn recites_the_context_and_reports_the_message_count() {
|
||||
let server = start_server(|_| {
|
||||
FakeReply::sse(concat!(
|
||||
": stream open\n\n",
|
||||
"event: delta\ndata: {\"content\":\"Le frontend est en Rust\"}\n\n",
|
||||
"event: done\ndata: {\"reply\":\"Le frontend est en Rust\",\"model\":\"qwen2.5:3b\",\"contextMessages\":2}\n\n",
|
||||
))
|
||||
});
|
||||
|
||||
let events = Arc::new(Mutex::new(Vec::new()));
|
||||
let sink = events.clone();
|
||||
|
||||
server
|
||||
.client()
|
||||
.stream_project_recall(3, "qwen2.5:3b", CancellationToken::new(), move |event| {
|
||||
sink.lock().expect("lock").push(event)
|
||||
})
|
||||
.await
|
||||
.expect("the recall stream should succeed");
|
||||
|
||||
assert_eq!(
|
||||
*events.lock().expect("lock"),
|
||||
vec![
|
||||
RecallEvent::Delta("Le frontend est en Rust".to_string()),
|
||||
// How many stored messages the backend actually replayed.
|
||||
RecallEvent::Done(2),
|
||||
]
|
||||
);
|
||||
|
||||
let requests = server.requests();
|
||||
assert_eq!(requests[0].method, "POST");
|
||||
assert_eq!(requests[0].target, "/api/projects/3/context/recall");
|
||||
assert_eq!(
|
||||
body_json(&requests[0]),
|
||||
serde_json::json!({"model": "qwen2.5:3b"})
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn surfaces_a_missing_project() {
|
||||
let server = start_server(|_| {
|
||||
FakeReply::status("HTTP/1.1 404 Not Found", r#"{"error":"Project not found."}"#)
|
||||
});
|
||||
|
||||
let error = server
|
||||
.client()
|
||||
.project_messages(42, 50)
|
||||
.await
|
||||
.expect_err("a 404 must be an error");
|
||||
|
||||
match error {
|
||||
ApiError::Status { status, message } => {
|
||||
assert_eq!(status.as_u16(), 404);
|
||||
assert_eq!(message, "Project not found.");
|
||||
}
|
||||
other => panic!("expected a status error, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn fails_when_no_token_is_set() {
|
||||
let server = start_server(|_| FakeReply::json("{\"projects\":[]}"));
|
||||
let client = ApiClient::new(server.base_url.clone());
|
||||
|
||||
// The client is not authenticated: nothing should reach the network.
|
||||
client.list_projects().await.expect_err("expected an error");
|
||||
|
||||
assert!(server.requests().is_empty());
|
||||
}
|
||||
|
||||
/// Guards the `StoredMessage` -> `ChatMessage` conversion used by the sidebar.
|
||||
#[test]
|
||||
fn converts_a_stored_message_into_a_chat_message() {
|
||||
let stored = StoredMessage {
|
||||
id: 1,
|
||||
role: "assistant".to_string(),
|
||||
content: "Bonjour !".to_string(),
|
||||
created_at: Some("2026-10-05 12:34:56".to_string()),
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
stored.to_chat(),
|
||||
jarvise_frontend::model::ChatMessage::assistant("Bonjour !")
|
||||
);
|
||||
assert_eq!(stored.time_label(), Some("12:34"));
|
||||
}
|
||||
Reference in new issue
Block a user