From 85da9fcad0d8845ca10fff554265a0663b4f85b7 Mon Sep 17 00:00:00 2001 From: william Date: Sun, 1 Nov 2026 10:52:09 +0100 Subject: [PATCH] refactor(pipeline): the text bar is not a chat, Max always replies by voice Two pieces of direct user feedback, addressed together since they touch the same files: 1. ObjectiveValidationCard now lives in its own dedicated, movable window (objectiveWindow.ts / ObjectiveWindowRoot.tsx), independent of the text input window. Confirming an objective must never depend on opening that window, including when the whole exchange happens by voice. Both sendTextTurn and voice-turn open/feed this window through the same shared handleRouteMessageResult code path, so text and voice behave identically - no more special-casing one channel. 2. The "chat window" was never meant to be a chat: it's an alternate text entry point for the exact same voice pipeline. Removed the message history/ChatBubble display and the old sessions:route-message + voice-turn-synced plumbing that existed to sync a conversation transcript across windows. Replaced with a new text-turn IPC handler mirroring voice-turn (routeMessage -> handleRouteMessageResult -> synthesizeSpeech) minus the STT step; the reply is relayed to the avatar window via the existing proactive-speech channel and spoken aloud, never displayed. The input window shrinks accordingly (560px -> 100px tall) and no longer auto-opens when a session starts, since there is nothing to show there anymore - it only opens on explicit user request. useProactiveSpeech now accepts an onStateChange callback so the avatar status indicator correctly flips back to idle once a text-turn reply finishes playing (it previously only ever got set to 'speaking', never reset - a latent gap this reuse surfaced). Co-Authored-By: Claude Sonnet 5 --- Max Avatar/src/main/chatWindow.ts | 12 +- Max Avatar/src/main/index.ts | 96 +++++++----- Max Avatar/src/main/objectiveWindow.ts | 54 +++++++ Max Avatar/src/preload/index.d.ts | 8 +- Max Avatar/src/preload/index.ts | 25 +-- Max Avatar/src/renderer/src/App.tsx | 26 +--- .../src/renderer/src/components/ChatPanel.tsx | 73 ++------- .../src/components/ObjectiveWindowRoot.tsx | 29 ++++ Max Avatar/src/renderer/src/main.tsx | 9 +- .../renderer/src/stores/useSessionStore.ts | 94 ++++-------- Max Avatar/src/renderer/src/styles/app.css | 24 +-- .../renderer/src/voice/useProactiveSpeech.ts | 20 ++- Max Avatar/src/shared/voice.ts | 6 + Max Avatar/tests/unit/components/App.test.tsx | 4 +- .../tests/unit/components/ChatPanel.test.tsx | 93 +++-------- .../components/ObjectiveWindowRoot.test.tsx | 73 +++++++++ .../components/stores/useSessionStore.test.ts | 145 ++++++------------ .../components/useProactiveSpeech.test.ts | 12 ++ Max Avatar/tests/unit/objectiveWindow.test.ts | 78 ++++++++++ 19 files changed, 482 insertions(+), 399 deletions(-) create mode 100644 Max Avatar/src/main/objectiveWindow.ts create mode 100644 Max Avatar/src/renderer/src/components/ObjectiveWindowRoot.tsx create mode 100644 Max Avatar/tests/unit/components/ObjectiveWindowRoot.test.tsx create mode 100644 Max Avatar/tests/unit/objectiveWindow.test.ts diff --git a/Max Avatar/src/main/chatWindow.ts b/Max Avatar/src/main/chatWindow.ts index e54aaa6..72001f9 100644 --- a/Max Avatar/src/main/chatWindow.ts +++ b/Max Avatar/src/main/chatWindow.ts @@ -6,9 +6,11 @@ import { SECURE_WEB_PREFERENCES, blockExternalNavigation } from './utils/windowS let win: BrowserWindow | null = null let onClosedCallback: (() => void) | null = null -// Fenetre separee et deplacable (retour utilisateur direct : le chat et le stepper doivent etre -// des vraies fenetres Electron, pas des panneaux ancres dans la fenetre avatar), meme pattern -// singleton que src/main/auth/loginWindow.ts et stepperWindow.ts. +// Fenetre separee et deplacable (retour utilisateur direct : la barre de saisie texte et le +// stepper doivent etre des vraies fenetres Electron, pas des panneaux ancres dans la fenetre +// avatar), meme pattern singleton que src/main/auth/loginWindow.ts et stepperWindow.ts. Ce n'est +// PAS une fenetre de chat (retour utilisateur direct) : juste une barre de saisie alternative au +// micro, sans historique de conversation affiche - d'ou sa petite taille. export function isChatWindowOpen(): boolean { return win !== null && !win.isDestroyed() } @@ -22,8 +24,8 @@ export function openChatWindow(): void { win = new BrowserWindow({ width: 380, - height: 560, - title: 'Max — conversation', + height: 100, + title: 'Max — écrire un message', frame: false, transparent: true, backgroundColor: '#00000000', diff --git a/Max Avatar/src/main/index.ts b/Max Avatar/src/main/index.ts index 2a49970..f8bcf8d 100644 --- a/Max Avatar/src/main/index.ts +++ b/Max Avatar/src/main/index.ts @@ -10,6 +10,7 @@ import { loginAndLoadKeys } from './auth/authClient' import { openLoginWindow, closeLoginWindow } from './auth/loginWindow' import { clearSession, getCurrentUserEmail, isLoggedIn, requireLoggedIn } from './auth/session' import { closeChatWindow, isChatWindowOpen, onChatWindowClosed, openChatWindow } from './chatWindow' +import { closeObjectiveWindow, openObjectiveWindow } from './objectiveWindow' import { closeStepperWindow, openStepperWindow } from './stepperWindow' import { confirmObjective, @@ -18,9 +19,10 @@ import { routeMessage, sendObjectiveMessage } from './api/sessionsClient' -import type { VoiceTurnResult } from '../shared/voice' +import type { TextTurnResult, VoiceTurnResult } from '../shared/voice' import type { AuthStatus, LoginResult } from '../shared/auth' import type { + ObjectiveDraft, ObjectiveMessageResponse, RouteMessageResponse, SessionObjectiveResponse, @@ -153,6 +155,7 @@ app clearSession() closeChatWindow() closeStepperWindow() + closeObjectiveWindow() event.sender.send('toggle-listening', false) }) @@ -167,7 +170,10 @@ app // fenetre de chat est fermee autrement que par ce menu (ex: Alt+F4). onChatWindowClosed(() => mainWindow?.webContents.send('chat-window-closed')) - ipcMain.on('session-ended', () => closeStepperWindow()) + ipcMain.on('session-ended', () => { + closeStepperWindow() + closeObjectiveWindow() + }) // Relais inter-fenetres : la fenetre du stepper vit dans son propre process renderer isole // (voir src/main/stepperWindow.ts) et n'a donc pas acces a l'etat de la fenetre de chat qui @@ -179,27 +185,31 @@ app } } - // Relais inter-fenetres specifique au vocal (voir handler "voice-turn" ci-dessous) : la - // fenetre de chat texte a son propre store Zustand (messages, brouillon d'objectif) qui ne - // recoit jamais les tours de conversation inities depuis la voix, puisque ceux-ci sont geres - // entierement dans le main process sans passer par l'IPC "sessions:route-message" de cette - // fenetre. Sans ce relais, ObjectiveValidationCard ne peut jamais apparaitre pour un - // utilisateur qui fait tout au vocal (constate en test reel). - function broadcastVoiceTurn(result: RouteMessageResponse): void { + // Relais inter-fenetres vers la fenetre dediee a la validation de l'objectif (voir + // src/main/objectiveWindow.ts) : separee du chat texte sur demande directe de l'utilisateur + // (la confirmation ne doit jamais dependre d'ouvrir la conversation, y compris quand tout + // l'echange se fait au vocal). Ouverte et alimentee ici, dans le code partage par le texte et + // la voix (handleRouteMessageResult), pour garantir que les deux canaux se comportent pareil. + function broadcastObjectiveReady(sessionId: number, draft: ObjectiveDraft): void { + openObjectiveWindow() for (const window of BrowserWindow.getAllWindows()) { - window.webContents.send('voice-turn-synced', result) + window.webContents.send('objective-ready', sessionId, draft) } } - // Partage entre le chat texte (sessions:route-message) et la voix (voice-turn) : "learn" est - // le seul cas ou une session existe reellement (nouvelle ou poursuivie), cote serveur, quel - // que soit le canal d'entree (routeur d'intention, voir docs/Max_System_Prompt.md). - // openStepperWindow() est idempotent (singleton). + // Partage entre la barre de saisie texte (text-turn) et la voix (voice-turn) : "learn" est le + // seul cas ou une session existe reellement (nouvelle ou poursuivie), cote serveur, quel que + // soit le canal d'entree (routeur d'intention, voir docs/Max_System_Prompt.md). + // openStepperWindow()/openObjectiveWindow() sont idempotentes (singleton). async function handleRouteMessageResult(result: RouteMessageResponse): Promise { if (result.type === 'learn' && result.sessionId !== undefined) { openStepperWindow() const session = await getSession(result.sessionId) broadcastSessionStatus(session.status) + + if (result.ready && result.draft) { + broadcastObjectiveReady(result.sessionId, result.draft) + } } } @@ -219,21 +229,13 @@ app return { ok: 'ignored', transcript } } - // Meme point d'entree que le chat texte (POST /sessions/messages, routeur d'intention - // inclus) : une seule personnalite, un seul pipeline, quel que soit le canal d'entree. + // Meme point d'entree que la barre de saisie texte (POST /sessions/messages, routeur + // d'intention inclus) : une seule personnalite, un seul pipeline, quel que soit le canal + // d'entree. const routed = await routeMessage(command) const afterChat = performance.now() const reply = sanitizeForSpeech(routed.reply) await handleRouteMessageResult(routed) - // La fenetre de chat texte est la seule a savoir afficher ObjectiveValidationCard (la - // confirmation finale exige un clic, pas realisable en vocal seul) : si la voix a fait - // avancer une formation, on ouvre cette fenetre et on lui transmet le tour (message + - // etat pret/brouillon) puisque son store Zustand, isole dans son propre process - // renderer, ne recoit sinon jamais rien de ce qui se passe cote vocal. - if (routed.type === 'learn') { - openChatWindow() - broadcastVoiceTurn(routed) - } const speech = await synthesizeSpeech(reply) const afterTts = performance.now() @@ -253,6 +255,35 @@ app } ) + // Entree alternative au micro, PAS un chat (retour utilisateur direct) : le texte tape suit + // exactement le meme pipeline qu'une phrase prononcee (meme routeMessage, + // handleRouteMessageResult, personnalite, routeur d'intention) et Max repond TOUJOURS a voix + // haute via la file d'attente partagee (proactive-speech, jouee dans la fenetre avatar) - + // jamais de reponse affichee a l'ecrit, aucun historique de conversation. + ipcMain.handle('text-turn', async (_event, message: unknown): Promise => { + try { + requireLoggedIn() + if (typeof message !== 'string' || message.trim().length === 0) { + throw new Error('message vide') + } + if (message.length > 2000) throw new Error('message trop long') + + const routed = await routeMessage(message) + const reply = sanitizeForSpeech(routed.reply) + await handleRouteMessageResult(routed) + const speech = await synthesizeSpeech(reply) + const audio = speech.buffer.slice( + speech.byteOffset, + speech.byteOffset + speech.byteLength + ) as ArrayBuffer + mainWindow?.webContents.send('proactive-speech', audio) + return { ok: true } + } catch (error) { + console.error('[text-turn]', error) + return { ok: false, error: error instanceof Error ? error.message : String(error) } + } + }) + ipcMain.handle( 'auth-login', async (_event, email: string, password: string): Promise => { @@ -305,21 +336,6 @@ app } ) - ipcMain.handle( - 'sessions:route-message', - async (_event, message: unknown): Promise => { - requireLoggedIn() - if (typeof message !== 'string' || message.trim().length === 0) { - throw new Error('message vide') - } - if (message.length > 2000) throw new Error('message trop long') - - const result = await routeMessage(message) - await handleRouteMessageResult(result) - return result - } - ) - ipcMain.handle( 'sessions:confirm-objective', async (_event, id: unknown): Promise => { diff --git a/Max Avatar/src/main/objectiveWindow.ts b/Max Avatar/src/main/objectiveWindow.ts new file mode 100644 index 0000000..c999b94 --- /dev/null +++ b/Max Avatar/src/main/objectiveWindow.ts @@ -0,0 +1,54 @@ +import { BrowserWindow } from 'electron' +import { join } from 'path' +import { is } from '@electron-toolkit/utils' +import { SECURE_WEB_PREFERENCES, blockExternalNavigation } from './utils/windowSecurity' + +let win: BrowserWindow | null = null + +// Fenetre separee et dediee, independante du chat texte (retour utilisateur direct : la +// confirmation de l'objectif ne doit jamais dependre d'ouvrir la fenetre de conversation, y +// compris quand tout l'echange se fait au vocal) : affiche uniquement ObjectiveValidationCard. +// Meme pattern singleton que chatWindow.ts/stepperWindow.ts. +export function isObjectiveWindowOpen(): boolean { + return win !== null && !win.isDestroyed() +} + +export function openObjectiveWindow(): void { + if (isObjectiveWindowOpen()) { + win?.show() + win?.focus() + return + } + + win = new BrowserWindow({ + width: 360, + height: 320, + title: 'Max — ton objectif', + frame: false, + transparent: true, + backgroundColor: '#00000000', + hasShadow: false, + alwaysOnTop: true, + resizable: false, + skipTaskbar: true, + webPreferences: { + preload: join(__dirname, '../preload/index.js'), + ...SECURE_WEB_PREFERENCES + } + }) + blockExternalNavigation(win) + win.setAlwaysOnTop(true, 'floating') + win.on('closed', () => { + win = null + }) + + if (is.dev && process.env['ELECTRON_RENDERER_URL']) { + void win.loadURL(`${process.env['ELECTRON_RENDERER_URL']}#objective`) + } else { + void win.loadFile(join(__dirname, '../renderer/index.html'), { hash: 'objective' }) + } +} + +export function closeObjectiveWindow(): void { + if (isObjectiveWindowOpen()) win?.close() +} diff --git a/Max Avatar/src/preload/index.d.ts b/Max Avatar/src/preload/index.d.ts index 34faf86..8cce7ea 100644 --- a/Max Avatar/src/preload/index.d.ts +++ b/Max Avatar/src/preload/index.d.ts @@ -1,9 +1,9 @@ import { ElectronAPI } from '@electron-toolkit/preload' -import type { VoiceTurnResult } from '../shared/voice' +import type { TextTurnResult, VoiceTurnResult } from '../shared/voice' import type { AuthStatus, LoginResult } from '../shared/auth' import type { + ObjectiveDraft, ObjectiveMessageResponse, - RouteMessageResponse, SessionObjectiveResponse, SessionResponse, SessionStatus @@ -14,7 +14,6 @@ export interface SessionsApi { get: (id: number) => Promise sendObjectiveMessage: (id: number, message: string) => Promise confirmObjective: (id: number) => Promise - routeMessage: (message: string) => Promise } export interface ForgeAvatarApi { @@ -22,6 +21,7 @@ export interface ForgeAvatarApi { getWindowBounds: () => Promise<{ x: number; y: number; width: number; height: number }> setWindowPosition: (x: number, y: number, width: number, height: number) => void sendVoiceTurn: (audio: ArrayBuffer, mimeType: string) => Promise + sendTextTurn: (message: string) => Promise openLoginWindow: () => void logout: () => void quitApp: () => void @@ -31,7 +31,7 @@ export interface ForgeAvatarApi { onProactiveSpeech: (callback: (audio: ArrayBuffer) => void) => () => void onChatWindowClosed: (callback: () => void) => () => void onSessionStatusChanged: (callback: (status: SessionStatus) => void) => () => void - onVoiceTurnSynced: (callback: (result: RouteMessageResponse) => void) => () => void + onObjectiveReady: (callback: (sessionId: number, draft: ObjectiveDraft) => void) => () => void onUpdateAvailable: (callback: () => void) => () => void onUpdateReady: (callback: () => void) => () => void login: (email: string, password: string) => Promise diff --git a/Max Avatar/src/preload/index.ts b/Max Avatar/src/preload/index.ts index eb85874..6aec9c7 100644 --- a/Max Avatar/src/preload/index.ts +++ b/Max Avatar/src/preload/index.ts @@ -1,10 +1,10 @@ import { contextBridge, ipcRenderer } from 'electron' import { electronAPI } from '@electron-toolkit/preload' -import type { VoiceTurnResult } from '../shared/voice' +import type { TextTurnResult, VoiceTurnResult } from '../shared/voice' import type { AuthStatus, LoginResult } from '../shared/auth' import type { + ObjectiveDraft, ObjectiveMessageResponse, - RouteMessageResponse, SessionObjectiveResponse, SessionResponse, SessionStatus @@ -21,6 +21,8 @@ const api = { }, sendVoiceTurn: (audio: ArrayBuffer, mimeType: string): Promise => ipcRenderer.invoke('voice-turn', audio, mimeType), + sendTextTurn: (message: string): Promise => + ipcRenderer.invoke('text-turn', message), openLoginWindow: (): void => { ipcRenderer.send('open-login-window') }, @@ -58,11 +60,16 @@ const api = { ipcRenderer.on('session-status-changed', handler) return () => ipcRenderer.removeListener('session-status-changed', handler) }, - onVoiceTurnSynced: (callback: (result: RouteMessageResponse) => void): (() => void) => { - const handler = (_event: Electron.IpcRendererEvent, result: RouteMessageResponse): void => - callback(result) - ipcRenderer.on('voice-turn-synced', handler) - return () => ipcRenderer.removeListener('voice-turn-synced', handler) + onObjectiveReady: ( + callback: (sessionId: number, draft: ObjectiveDraft) => void + ): (() => void) => { + const handler = ( + _event: Electron.IpcRendererEvent, + sessionId: number, + draft: ObjectiveDraft + ): void => callback(sessionId, draft) + ipcRenderer.on('objective-ready', handler) + return () => ipcRenderer.removeListener('objective-ready', handler) }, onUpdateAvailable: (callback: () => void): (() => void) => { const handler = (): void => callback() @@ -83,9 +90,7 @@ const api = { sendObjectiveMessage: (id: number, message: string): Promise => ipcRenderer.invoke('sessions:send-objective-message', id, message), confirmObjective: (id: number): Promise => - ipcRenderer.invoke('sessions:confirm-objective', id), - routeMessage: (message: string): Promise => - ipcRenderer.invoke('sessions:route-message', message) + ipcRenderer.invoke('sessions:confirm-objective', id) } } diff --git a/Max Avatar/src/renderer/src/App.tsx b/Max Avatar/src/renderer/src/App.tsx index 0b3c95f..c59f6c4 100644 --- a/Max Avatar/src/renderer/src/App.tsx +++ b/Max Avatar/src/renderer/src/App.tsx @@ -22,7 +22,6 @@ function App(): React.JSX.Element { const [voiceState, setVoiceState] = useState('idle') const [voiceError, setVoiceError] = useState(null) const [updateStatus, setUpdateStatus] = useState<'available' | 'ready' | null>(null) - const sessionId = useSessionStore((state) => state.sessionId) const restartSession = useSessionStore((state) => state.restart) useEffect(() => window.api.onUpdateAvailable(() => setUpdateStatus('available')), []) useEffect(() => window.api.onUpdateReady(() => setUpdateStatus('ready')), []) @@ -37,7 +36,7 @@ function App(): React.JSX.Element { if (state === 'recording' || state === 'processing') setVoiceError(null) }, []) useVoiceAssistant(avatar, listening, handleVoiceStateChange, handleVoiceError) - useProactiveSpeech(avatar) + useProactiveSpeech(avatar, setVoiceState) useEffect(() => { listeningRef.current = listening @@ -66,26 +65,17 @@ function App(): React.JSX.Element { // pour revalider loggedIn aupres du main process plutot que de le deduire de l'etat d'ecoute // (l'utilisateur peut couper l'ecoute manuellement sans se deconnecter). useEffect(() => window.api.onToggleListening(refreshAuthStatus), [refreshAuthStatus]) - useEffect(() => window.api.onProactiveSpeech(() => setVoiceState('speaking')), []) // Le stepper n'apparait que lorsqu'une session existe reellement (l'utilisateur a mentionne // vouloir apprendre quelque chose, pas juste parce qu'il est connecte) : il vit desormais dans sa - // propre fenetre, ouverte directement par le main process des que sessions:create reussit (voir - // src/main/index.ts) - rien a faire ici. + // propre fenetre, ouverte directement par le main process des que le routeur d'intention detecte + // "learn" (voir src/main/index.ts) - rien a faire ici. Meme chose pour la fenetre de validation + // de l'objectif. La barre de saisie texte, elle, n'est qu'une entree alternative au micro (pas un + // chat, voir ChatPanel.tsx) : elle ne s'ouvre jamais automatiquement, uniquement sur demande + // explicite de l'utilisateur via le menu contextuel. - // Garde-fou : en usage normal, c'est l'ouverture du chat via le menu contextuel qui permet - // d'envoyer le premier message qui cree la session, donc la fenetre de chat est deja ouverte a ce - // moment-la. Ce filet de securite l'ouvre quand meme si une session demarre sans qu'elle le soit. - const previousSessionId = useRef(null) - useEffect(() => { - if (previousSessionId.current === null && sessionId !== null && !chatOpen) { - window.api.toggleChatWindow() - setChatOpen(true) - } - previousSessionId.current = sessionId - }, [sessionId, chatOpen]) - - // Resynchronise la coche du menu si la fenetre de chat est fermee autrement que par ce menu. + // Resynchronise la coche du menu si la fenetre de saisie texte est fermee autrement que par ce + // menu (ex: Alt+F4). useEffect(() => window.api.onChatWindowClosed(() => setChatOpen(false)), []) const onContextMenu = useCallback((event: React.MouseEvent) => { diff --git a/Max Avatar/src/renderer/src/components/ChatPanel.tsx b/Max Avatar/src/renderer/src/components/ChatPanel.tsx index 155b758..41df0a0 100644 --- a/Max Avatar/src/renderer/src/components/ChatPanel.tsx +++ b/Max Avatar/src/renderer/src/components/ChatPanel.tsx @@ -1,74 +1,25 @@ -import { useEffect, useRef } from 'react' import { useSessionStore } from '../stores/useSessionStore' -import ChatBubble from './ChatBubble' import InputBar from './InputBar' -import ObjectiveValidationCard from './ObjectiveValidationCard' /** - * Panneau de conversation (docs/Max_Composants_Frontend.md section 4) : historique de messages + - * carte de validation de l'objectif + barre de saisie. Rendu dans sa propre fenetre Electron - * separee et deplacable (voir src/main/chatWindow.ts et la route #chat dans main.tsx), distincte - * de la fenetre de l'avatar et de celle du PipelineStepper - voir le retour utilisateur qui - * demandait que chat et stepper soient des fenetres separees, deplacables independamment. - * N'affiche jamais un statut calcule localement. + * Ce n'est PAS un chat (retour utilisateur direct) : juste une barre de saisie alternative au + * micro, rendue dans sa propre fenetre Electron separee et deplacable (voir src/main/chatWindow.ts + * et la route #chat dans main.tsx). Le texte tape suit exactement le meme pipeline qu'une phrase + * prononcee a voix haute (meme routeur d'intention, meme Agent 1, voir "text-turn" dans + * src/main/index.ts) et Max repond TOUJOURS a voix haute via la file d'attente audio partagee - + * jamais de reponse affichee a l'ecrit, donc aucun historique de conversation ici. */ export default function ChatPanel(): React.JSX.Element { - const { - messages, - objectiveDraft, - objectiveReady, - objectiveConfirmed, - loading, - error, - sendMessage, - confirmObjective, - restart, - syncVoiceTurn - } = useSessionStore() - const chatRef = useRef(null) - - useEffect(() => { - const chat = chatRef.current - if (chat && typeof chat.scrollTo === 'function') { - chat.scrollTo({ top: chat.scrollHeight }) - } - }, [messages]) - - // Une formation demarree ou poursuivie au vocal n'arrive jamais ici via sendMessage() (c'est le - // main process qui appelle Max API directement pour la voix) : sans cet abonnement, la carte de - // validation ne peut jamais apparaitre pour un utilisateur qui fait tout au vocal. - useEffect(() => window.api.onVoiceTurnSynced(syncVoiceTurn), [syncVoiceTurn]) - - const showObjectiveCard = objectiveReady && objectiveDraft !== null && !objectiveConfirmed + const { loading, error, sendTextTurn } = useSessionStore() return (
-
- {messages.map((message) => ( - - ))} -
- {error &&

{error}

} - - {showObjectiveCard && objectiveDraft ? ( - - ) : ( - void sendMessage(text)} - /> - )} + void sendTextTurn(text)} + />
) } diff --git a/Max Avatar/src/renderer/src/components/ObjectiveWindowRoot.tsx b/Max Avatar/src/renderer/src/components/ObjectiveWindowRoot.tsx new file mode 100644 index 0000000..6259742 --- /dev/null +++ b/Max Avatar/src/renderer/src/components/ObjectiveWindowRoot.tsx @@ -0,0 +1,29 @@ +import { useEffect } from 'react' +import { useSessionStore } from '../stores/useSessionStore' +import ObjectiveValidationCard from './ObjectiveValidationCard' + +/** + * Point d'entree de la fenetre dediee a la validation de l'objectif (voir + * src/main/objectiveWindow.ts et la route #objective dans main.tsx). Separee de la fenetre de + * chat : la confirmation de l'objectif ne doit jamais dependre d'ouvrir la conversation texte, + * y compris quand tout l'echange se fait au vocal (retour utilisateur direct). Cette fenetre vit + * dans son propre process renderer isole : son etat (sessionId, brouillon) lui est relaye par le + * main process des que l'Agent 1 produit un objectif pret a confirmer, quel que soit le canal + * d'entree (texte ou vocal, voir "objective-ready" dans src/main/index.ts). + */ +export default function ObjectiveWindowRoot(): React.JSX.Element | null { + const { objectiveDraft, objectiveReady, confirmObjective, restart } = useSessionStore() + const applyObjectiveReady = useSessionStore((state) => state.applyObjectiveReady) + + useEffect(() => window.api.onObjectiveReady(applyObjectiveReady), [applyObjectiveReady]) + + if (!objectiveReady || objectiveDraft === null) return null + + return ( + + ) +} diff --git a/Max Avatar/src/renderer/src/main.tsx b/Max Avatar/src/renderer/src/main.tsx index bbbfe77..12c6fde 100644 --- a/Max Avatar/src/renderer/src/main.tsx +++ b/Max Avatar/src/renderer/src/main.tsx @@ -12,15 +12,18 @@ import { createRoot } from 'react-dom/client' import App from './App' import ChatPanel from './components/ChatPanel' import LoginView from './components/LoginView' +import ObjectiveWindowRoot from './components/ObjectiveWindowRoot' import StepperView from './components/StepperView' -// Fenetres secondaires (login, chat, stepper - chacune ouverte/fermee par le main process) : -// chargent ce meme bundle avec un hash different pour afficher une autre vue que l'avatar. La -// fenetre avatar, chargee sans hash, continue de monter comme avant, sans aucun changement. +// Fenetres secondaires (login, chat, stepper, objectif - chacune ouverte/fermee par le main +// process) : chargent ce meme bundle avec un hash different pour afficher une autre vue que +// l'avatar. La fenetre avatar, chargee sans hash, continue de monter comme avant, sans +// aucun changement. function renderForHash(): React.JSX.Element { if (location.hash === '#login') return if (location.hash === '#chat') return if (location.hash === '#stepper') return + if (location.hash === '#objective') return return } diff --git a/Max Avatar/src/renderer/src/stores/useSessionStore.ts b/Max Avatar/src/renderer/src/stores/useSessionStore.ts index 16345d5..f5dee18 100644 --- a/Max Avatar/src/renderer/src/stores/useSessionStore.ts +++ b/Max Avatar/src/renderer/src/stores/useSessionStore.ts @@ -1,76 +1,46 @@ import { create } from 'zustand' -import type { ObjectiveDraft, RouteMessageResponse, SessionStatus } from '../../../shared/session' - -export interface ChatMessage { - id: string - role: 'max' | 'user' - content: string - timestamp: Date -} +import type { ObjectiveDraft, SessionStatus } from '../../../shared/session' interface SessionState { sessionId: number | null status: SessionStatus | null - messages: ChatMessage[] objectiveDraft: ObjectiveDraft | null objectiveReady: boolean - objectiveConfirmed: boolean loading: boolean error: string | null - sendMessage: (text: string) => Promise + sendTextTurn: (text: string) => Promise confirmObjective: (objective: ObjectiveDraft) => Promise restart: () => void setStatus: (status: SessionStatus) => void - syncVoiceTurn: (result: RouteMessageResponse) => void -} - -function pushMessage( - messages: ChatMessage[], - role: ChatMessage['role'], - content: string -): ChatMessage[] { - return [...messages, { id: crypto.randomUUID(), role, content, timestamp: new Date() }] + applyObjectiveReady: (sessionId: number, draft: ObjectiveDraft) => void } /** * Seule source de verite pour l'etat du pipeline cote renderer. Le statut de session n'est JAMAIS * calcule ici : il vient toujours de ce que l'API a reellement renvoye (voir - * docs/Max_Composants_Frontend.md, regle de PipelineStepper). + * docs/Max_Composants_Frontend.md, regle de PipelineStepper). La barre de saisie texte n'est PAS + * un chat (retour utilisateur direct) : elle ne garde aucun historique de conversation, Max + * repond toujours a voix haute (voir ChatPanel.tsx et "text-turn" dans src/main/index.ts). La + * carte de validation de l'objectif vit dans sa propre fenetre dediee, alimentee par + * applyObjectiveReady quel que soit le canal d'entree (texte ou vocal). */ export const useSessionStore = create((set, get) => ({ sessionId: null, status: null, - messages: [], objectiveDraft: null, objectiveReady: false, - objectiveConfirmed: false, loading: false, error: null, - sendMessage: async (text: string): Promise => { - set((state) => ({ - messages: pushMessage(state.messages, 'user', text), - loading: true, - error: null - })) - + sendTextTurn: async (text: string): Promise => { + set({ loading: true, error: null }) try { - // Point d'entree unique (docs/Max_System_Prompt.md, routeur d'intention) : ne cree une - // session que si le backend detecte reellement une intention d'apprendre. Un message de - // simple conversation ("salut ça va ?") ne demarre jamais de formation. - const result = await window.api.sessions.routeMessage(text) - - if (result.type === 'learn' && result.sessionId !== undefined) { - const session = await window.api.sessions.get(result.sessionId) - set({ sessionId: result.sessionId, status: session.status }) + const result = await window.api.sendTextTurn(text) + if (!result.ok) { + set({ loading: false, error: result.error }) + return } - - set((state) => ({ - messages: pushMessage(state.messages, 'max', result.reply), - objectiveReady: result.ready ?? false, - objectiveDraft: result.draft ?? state.objectiveDraft, - loading: false - })) + set({ loading: false }) } catch (error) { set({ loading: false, @@ -92,7 +62,6 @@ export const useSessionStore = create((set, get) => ({ const session = await window.api.sessions.get(sessionId) set({ status: session.status, - objectiveConfirmed: true, loading: false }) } catch (error) { @@ -108,37 +77,28 @@ export const useSessionStore = create((set, get) => ({ set({ sessionId: null, status: null, - messages: [], objectiveDraft: null, objectiveReady: false, - objectiveConfirmed: false, loading: false, error: null }) }, - // Utilise uniquement par la fenetre du stepper (src/renderer/src/components/StepperView.tsx), - // qui vit dans un process renderer isole et n'a donc pas sa propre copie a jour de l'etat : - // le main process relaie le statut recu par la fenetre de chat via l'IPC - // "session-status-changed" (voir src/main/index.ts). La fenetre de chat, elle, continue de - // deriver son statut directement des reponses de ses propres appels API. + // Utilise par la fenetre du stepper (StepperView.tsx) : elle vit dans un process renderer isole + // et n'a donc pas sa propre copie a jour de l'etat. Le main process relaie le statut des qu'il + // change reellement cote serveur, quel que soit le canal d'entree (voir + // "session-status-changed" dans src/main/index.ts). setStatus: (status: SessionStatus): void => { set({ status }) }, - // Utilise uniquement par la fenetre de chat (src/renderer/src/components/ChatPanel.tsx), qui - // sinon ne voit jamais les tours de conversation inities au vocal : son store Zustand, isole - // dans son propre process renderer, ne recoit rien des appels faits par le process main pour le - // handler "voice-turn" (voir src/main/index.ts, broadcastVoiceTurn). Sans ca, - // ObjectiveValidationCard ne peut jamais apparaitre pour un utilisateur qui fait tout au vocal - // (constate en test reel). Ne pousse PAS le message utilisateur original (le main process ne le - // relaie pas ici), seulement la reponse de Max et l'etat pret/brouillon qui en resulte. - syncVoiceTurn: (result: RouteMessageResponse): void => { - set((state) => ({ - sessionId: result.sessionId ?? state.sessionId, - messages: pushMessage(state.messages, 'max', result.reply), - objectiveReady: result.ready ?? state.objectiveReady, - objectiveDraft: result.draft ?? state.objectiveDraft - })) + // Utilise uniquement par la fenetre dediee a la validation de l'objectif + // (ObjectiveWindowRoot.tsx), separee de la barre de saisie texte sur demande directe de + // l'utilisateur : la confirmation ne doit jamais dependre d'ouvrir cette barre, y compris quand + // tout l'echange se fait au vocal. Alimentee par le main process des que l'Agent 1 produit un + // objectif pret a confirmer, quel que soit le canal d'entree (texte ou vocal, voir + // "objective-ready" dans src/main/index.ts, declenche depuis le meme handleRouteMessageResult). + applyObjectiveReady: (sessionId: number, draft: ObjectiveDraft): void => { + set({ sessionId, objectiveDraft: draft, objectiveReady: true }) } })) diff --git a/Max Avatar/src/renderer/src/styles/app.css b/Max Avatar/src/renderer/src/styles/app.css index 6b5cfae..28c7e10 100644 --- a/Max Avatar/src/renderer/src/styles/app.css +++ b/Max Avatar/src/renderer/src/styles/app.css @@ -356,12 +356,12 @@ pointer-events: none; } -/* ── Fenetre de chat (fenetre Electron separee et deplacable, voir src/main/chatWindow.ts) ── - Remplit entierement sa propre fenetre transparente : le cadre arrondi/l'ombre donnent - l'apparence d'une carte flottante malgre la fenetre rectangulaire sous-jacente. La fenetre - entiere est une zone de glisser-deplacer (-webkit-app-region: drag), sauf les zones - interactives (messages, saisie, carte de validation) qui doivent rester cliquables/ - selectionnables. */ +/* ── Barre de saisie texte (fenetre Electron separee et deplacable, voir src/main/chatWindow.ts) ── + Ce n'est PAS un chat (retour utilisateur direct) : juste une entree alternative au micro, sans + historique de conversation affiche. Remplit entierement sa propre fenetre transparente : le + cadre arrondi/l'ombre donnent l'apparence d'une carte flottante malgre la fenetre rectangulaire + sous-jacente. La fenetre entiere est une zone de glisser-deplacer (-webkit-app-region: drag), + sauf la zone de saisie qui doit rester cliquable/selectionnable. */ .chat-panel { width: 100%; @@ -378,18 +378,6 @@ -webkit-app-region: drag; } -.chat-panel__messages { - flex: 1; - min-height: 60px; - overflow-y: auto; - display: flex; - flex-direction: column; - gap: var(--space-2); - scrollbar-width: thin; - scrollbar-color: var(--surface-2) transparent; - -webkit-app-region: no-drag; -} - .chat-panel__error { margin: 0; font-size: var(--text-sm); diff --git a/Max Avatar/src/renderer/src/voice/useProactiveSpeech.ts b/Max Avatar/src/renderer/src/voice/useProactiveSpeech.ts index 4b28ed0..d6792bf 100644 --- a/Max Avatar/src/renderer/src/voice/useProactiveSpeech.ts +++ b/Max Avatar/src/renderer/src/voice/useProactiveSpeech.ts @@ -2,16 +2,20 @@ import { useEffect, type RefObject } from 'react' import type { AvatarHandle } from '../components/AvatarViewer' import { bindSpeechAvatar, enqueueSpeech } from './speechQueue' -// Joue une reponse de l'IA declenchee sans question de l'utilisateur (ex: rappel programme, -// commentaire immediat pendant qu'un outil s'execute), independamment de l'etat d'activation de -// l'ecoute vocale. Passe par la file d'attente partagee (speechQueue.ts) pour ne jamais chevaucher -// la reponse finale d'un tour de voix (constate en test reel : deux chemins audio independants se -// chevauchaient avant cette unification). -export function useProactiveSpeech(avatarRef: RefObject): void { +// Joue une reponse de l'IA declenchee sans micro actif (ex: reponse a un message tape dans la +// barre de saisie texte - voir "text-turn" dans src/main/index.ts - ou un rappel programme), +// independamment de l'etat d'activation de l'ecoute vocale. Passe par la file d'attente partagee +// (speechQueue.ts) pour ne jamais chevaucher la reponse finale d'un tour de voix (constate en test +// reel : deux chemins audio independants se chevauchaient avant cette unification). +export function useProactiveSpeech( + avatarRef: RefObject, + onStateChange?: (state: 'speaking' | 'idle') => void +): void { useEffect(() => { bindSpeechAvatar(avatarRef) return window.api.onProactiveSpeech((audio) => { - void enqueueSpeech(audio) + onStateChange?.('speaking') + void enqueueSpeech(audio).then(() => onStateChange?.('idle')) }) - }, [avatarRef]) + }, [avatarRef, onStateChange]) } diff --git a/Max Avatar/src/shared/voice.ts b/Max Avatar/src/shared/voice.ts index fdbb2a9..5cf7659 100644 --- a/Max Avatar/src/shared/voice.ts +++ b/Max Avatar/src/shared/voice.ts @@ -2,3 +2,9 @@ export type VoiceTurnResult = | { ok: true; transcript: string; reply: string; audio: ArrayBuffer } | { ok: 'ignored'; transcript: string } | { ok: false; error: string } + +// Reponse d'un message tape dans la barre de saisie texte (voir "text-turn" dans +// src/main/index.ts) : ce n'est pas un chat (retour utilisateur direct) - Max repond TOUJOURS a +// voix haute via la file d'attente audio partagee (proactive-speech), jamais par du texte affiche. +// Le resultat ne contient donc ni reponse ni audio, seulement si l'envoi a reussi. +export type TextTurnResult = { ok: true } | { ok: false; error: string } diff --git a/Max Avatar/tests/unit/components/App.test.tsx b/Max Avatar/tests/unit/components/App.test.tsx index 6b73b63..0e54fda 100644 --- a/Max Avatar/tests/unit/components/App.test.tsx +++ b/Max Avatar/tests/unit/components/App.test.tsx @@ -234,13 +234,13 @@ describe('', () => { expect(screen.queryByLabelText('Message')).not.toBeInTheDocument() }) - it('should open the chat window automatically if a session starts without it (safety net)', async () => { + it('should NOT open the text input window automatically when a session starts (not a chat - only explicit user request opens it)', async () => { getAuthStatus.mockResolvedValue({ loggedIn: true, email: 'william@example.com' }) render() await waitFor(() => expect(getAuthStatus).toHaveBeenCalled()) act(() => useSessionStore.setState({ sessionId: 1, status: 'objective_discovery' })) - expect(toggleChatWindow).toHaveBeenCalledOnce() + expect(toggleChatWindow).not.toHaveBeenCalled() }) }) diff --git a/Max Avatar/tests/unit/components/ChatPanel.test.tsx b/Max Avatar/tests/unit/components/ChatPanel.test.tsx index eb6d133..35dbb85 100644 --- a/Max Avatar/tests/unit/components/ChatPanel.test.tsx +++ b/Max Avatar/tests/unit/components/ChatPanel.test.tsx @@ -1,90 +1,47 @@ import { describe, it, expect, vi, beforeEach } from 'vitest' -import { render, screen, fireEvent, waitFor } from '@testing-library/react' +import { render, screen, fireEvent } from '@testing-library/react' import ChatPanel from '../../../src/renderer/src/components/ChatPanel' import { useSessionStore } from '../../../src/renderer/src/stores/useSessionStore' -const get = vi.fn() -const routeMessage = vi.fn() -const confirmObjective = vi.fn() +const sendTextTurn = vi.fn() const notifySessionEnded = vi.fn() -const onVoiceTurnSynced = vi.fn(() => () => {}) beforeEach(() => { vi.clearAllMocks() ;(window as unknown as { api: Record }).api = { - sessions: { get, routeMessage, confirmObjective }, - notifySessionEnded, - onVoiceTurnSynced + sendTextTurn, + notifySessionEnded } useSessionStore.getState().restart() }) +/** + * Ce n'est PAS un chat (retour utilisateur direct) : juste une barre de saisie alternative au + * micro. Le texte tape suit le meme pipeline qu'une phrase prononcee et Max repond toujours a + * voix haute - aucune bulle, aucun historique de conversation affiche ici. + */ describe('', () => { - it('should show an input bar and no pipeline steps before any session exists', () => { + it('should show only the message input, no conversation history', () => { render() expect(screen.getByLabelText('Message')).toBeInTheDocument() - expect(screen.queryByText('Objectif')).not.toBeInTheDocument() - }) - - it('should send the first message, creating a session, and render the conversation', async () => { - routeMessage.mockResolvedValueOnce({ - type: 'learn', - sessionId: 1, - reply: 'Quel est ton sujet ?', - ready: false - }) - get.mockResolvedValueOnce({ id: 1, status: 'objective_discovery' }) - - render() - fireEvent.change(screen.getByLabelText('Message'), { target: { value: 'Je veux apprendre' } }) - fireEvent.click(screen.getByRole('button', { name: 'Envoyer le message' })) - - expect(await screen.findByText('Je veux apprendre')).toBeInTheDocument() - expect(await screen.findByText('Quel est ton sujet ?')).toBeInTheDocument() - }) - - it('should show the ObjectiveValidationCard instead of the input bar once the agent is ready', async () => { - routeMessage.mockResolvedValueOnce({ - type: 'learn', - sessionId: 1, - reply: 'Voici le recap', - ready: true, - draft: { subject: 's', professionalGoal: 'g', duration: '1 semaine' } - }) - get.mockResolvedValueOnce({ id: 1, status: 'objective_discovery' }) - - render() - fireEvent.change(screen.getByLabelText('Message'), { target: { value: 'message' } }) - fireEvent.click(screen.getByRole('button', { name: 'Envoyer le message' })) - - await waitFor(() => expect(screen.getByText('Ton objectif de formation')).toBeInTheDocument()) - expect(screen.queryByLabelText('Message')).not.toBeInTheDocument() - }) - - it('should show the ObjectiveValidationCard from a voice-originated turn, not just a typed message', async () => { - let voiceTurnCallback: ((result: unknown) => void) | undefined - onVoiceTurnSynced.mockImplementationOnce((callback: (result: unknown) => void) => { - voiceTurnCallback = callback - return () => {} - }) - - render() expect(screen.queryByText('Ton objectif de formation')).not.toBeInTheDocument() - - voiceTurnCallback?.({ - type: 'learn', - sessionId: 1, - reply: 'Voici le recap (dit a voix haute)', - ready: true, - draft: { subject: 's', professionalGoal: 'g', duration: '1 semaine' } - }) - - await waitFor(() => expect(screen.getByText('Ton objectif de formation')).toBeInTheDocument()) - expect(screen.getByText('Voici le recap (dit a voix haute)')).toBeInTheDocument() }) - it('should show the store error message when a call fails', async () => { - routeMessage.mockRejectedValueOnce(new Error('Max API injoignable')) + it('should submit the typed text via text-turn and clear the field', async () => { + sendTextTurn.mockResolvedValueOnce({ ok: true }) + + render() + fireEvent.change(screen.getByLabelText('Message'), { + target: { value: 'Je veux apprendre la facturation' } + }) + fireEvent.click(screen.getByRole('button', { name: 'Envoyer le message' })) + + expect(sendTextTurn).toHaveBeenCalledWith('Je veux apprendre la facturation') + expect(await screen.findByDisplayValue('')).toBeInTheDocument() + }) + + it('should show the store error message when the backend reports a failure', async () => { + sendTextTurn.mockResolvedValueOnce({ ok: false, error: 'Max API injoignable' }) render() fireEvent.change(screen.getByLabelText('Message'), { target: { value: 'message' } }) diff --git a/Max Avatar/tests/unit/components/ObjectiveWindowRoot.test.tsx b/Max Avatar/tests/unit/components/ObjectiveWindowRoot.test.tsx new file mode 100644 index 0000000..fb9cc56 --- /dev/null +++ b/Max Avatar/tests/unit/components/ObjectiveWindowRoot.test.tsx @@ -0,0 +1,73 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest' +import { render, screen, fireEvent, waitFor, act } from '@testing-library/react' +import ObjectiveWindowRoot from '../../../src/renderer/src/components/ObjectiveWindowRoot' +import { useSessionStore } from '../../../src/renderer/src/stores/useSessionStore' + +const confirmObjective = vi.fn() +const notifySessionEnded = vi.fn() +let objectiveReadyCallback: ((sessionId: number, draft: unknown) => void) | undefined +const onObjectiveReady = vi.fn((callback: (sessionId: number, draft: unknown) => void) => { + objectiveReadyCallback = callback + return () => {} +}) + +beforeEach(() => { + vi.clearAllMocks() + objectiveReadyCallback = undefined + ;(window as unknown as { api: Record }).api = { + sessions: { confirmObjective, get: vi.fn() }, + notifySessionEnded, + onObjectiveReady + } + useSessionStore.getState().restart() +}) + +/** + * Fenetre independante du chat texte (retour utilisateur direct : la confirmation de l'objectif + * ne doit jamais dependre d'ouvrir la conversation, y compris quand tout l'echange se fait au + * vocal). Son etat vient exclusivement du relais "objective-ready" du main process. + */ +describe('', () => { + it('should render nothing before the main process relays a ready objective', () => { + const { container } = render() + expect(container).toBeEmptyDOMElement() + }) + + it('should show the card once the main process relays a ready objective (text or voice, same path)', () => { + render() + + act(() => + objectiveReadyCallback?.(1, { + subject: 'Facturation freelance', + professionalGoal: 'Facturer sans erreur', + duration: '2 semaines' + }) + ) + + expect(screen.getByText('Ton objectif de formation')).toBeInTheDocument() + expect(screen.getByText('Facturation freelance')).toBeInTheDocument() + }) + + it('should confirm the objective via the store, independently of any chat window', async () => { + confirmObjective.mockResolvedValueOnce({}) + ;(window as unknown as { api: { sessions: Record } }).api.sessions.get = vi + .fn() + .mockResolvedValueOnce({ id: 1, status: 'objective_validated' }) + + render() + act(() => + objectiveReadyCallback?.(1, { + subject: 'Facturation freelance', + professionalGoal: 'Facturer sans erreur', + duration: '2 semaines' + }) + ) + + fireEvent.click( + screen.getByRole('button', { name: "C'est exactement ca, confirmer l'objectif" }) + ) + + await waitFor(() => expect(confirmObjective).toHaveBeenCalledWith(1)) + expect(await screen.findByText(/Objectif enregistre/)).toBeInTheDocument() + }) +}) diff --git a/Max Avatar/tests/unit/components/stores/useSessionStore.test.ts b/Max Avatar/tests/unit/components/stores/useSessionStore.test.ts index 9502032..579db8b 100644 --- a/Max Avatar/tests/unit/components/stores/useSessionStore.test.ts +++ b/Max Avatar/tests/unit/components/stores/useSessionStore.test.ts @@ -2,116 +2,76 @@ import { describe, it, expect, vi, beforeEach } from 'vitest' import { useSessionStore } from '../../../../src/renderer/src/stores/useSessionStore' const get = vi.fn() -const routeMessage = vi.fn() +const sendTextTurn = vi.fn() const confirmObjective = vi.fn() const notifySessionEnded = vi.fn() beforeEach(() => { vi.clearAllMocks() ;(window as unknown as { api: Record }).api = { - sessions: { get, routeMessage, confirmObjective }, + sessions: { get, confirmObjective }, + sendTextTurn, notifySessionEnded } useSessionStore.getState().restart() }) +/** + * La barre de saisie texte n'est PAS un chat (retour utilisateur direct) : elle ne garde aucun + * historique de conversation, et Max repond toujours a voix haute (voir text-turn dans + * src/main/index.ts). Le store ne fait donc que suivre le succes/l'echec de l'envoi, rien de plus. + */ describe('useSessionStore', () => { - it('should not create a session when the backend classifies the message as chat', async () => { - routeMessage.mockResolvedValueOnce({ type: 'chat', reply: 'Salut, comment puis-je aider ?' }) + it('should send a typed message via text-turn and clear the loading state on success', async () => { + sendTextTurn.mockResolvedValueOnce({ ok: true }) - await useSessionStore.getState().sendMessage('Salut ça va ?') + await useSessionStore.getState().sendTextTurn('Je veux apprendre la facturation') - expect(routeMessage).toHaveBeenCalledWith('Salut ça va ?') - expect(get).not.toHaveBeenCalled() + expect(sendTextTurn).toHaveBeenCalledWith('Je veux apprendre la facturation') const state = useSessionStore.getState() - expect(state.sessionId).toBeNull() - expect(state.messages.map((m) => m.role)).toEqual(['user', 'max']) expect(state.loading).toBe(false) + expect(state.error).toBeNull() }) - it('should set the session id and fetch the fresh status when the backend starts a training session', async () => { - routeMessage.mockResolvedValueOnce({ - type: 'learn', - sessionId: 1, - reply: 'Quel est ton sujet ?', - ready: false - }) - get.mockResolvedValueOnce({ id: 1, status: 'objective_discovery' }) + it('should set an error when the backend reports a failure', async () => { + sendTextTurn.mockResolvedValueOnce({ ok: false, error: 'Max API injoignable' }) - await useSessionStore.getState().sendMessage('Je veux apprendre la facturation') - - expect(get).toHaveBeenCalledWith(1) - const state = useSessionStore.getState() - expect(state.sessionId).toBe(1) - expect(state.status).toBe('objective_discovery') - expect(state.messages.map((m) => m.role)).toEqual(['user', 'max']) - }) - - it('should reuse the same session id on subsequent messages of an ongoing training', async () => { - routeMessage.mockResolvedValueOnce({ - type: 'learn', - sessionId: 1, - reply: 'Quel est ton sujet ?', - ready: false - }) - get.mockResolvedValueOnce({ id: 1, status: 'objective_discovery' }) - await useSessionStore.getState().sendMessage('premier message') - - routeMessage.mockResolvedValueOnce({ - type: 'learn', - sessionId: 1, - reply: 'Et ton but professionnel ?', - ready: false - }) - get.mockResolvedValueOnce({ id: 1, status: 'objective_discovery' }) - await useSessionStore.getState().sendMessage('second message') - - expect(routeMessage).toHaveBeenCalledTimes(2) - expect(useSessionStore.getState().sessionId).toBe(1) - }) - - it('should store the draft and ready flag once the agent is ready to confirm', async () => { - const draft = { - subject: 'Facturation freelance', - professionalGoal: 'Facturer sans erreur', - duration: '2 semaines' - } - routeMessage.mockResolvedValueOnce({ - type: 'learn', - sessionId: 1, - reply: 'Voici le recap', - ready: true, - draft - }) - get.mockResolvedValueOnce({ id: 1, status: 'objective_discovery' }) - - await useSessionStore.getState().sendMessage('message') - - const state = useSessionStore.getState() - expect(state.objectiveReady).toBe(true) - expect(state.objectiveDraft).toEqual(draft) - }) - - it('should set an error and stop loading when sending a message fails', async () => { - routeMessage.mockRejectedValueOnce(new Error('Max API injoignable')) - - await useSessionStore.getState().sendMessage('message') + await useSessionStore.getState().sendTextTurn('message') const state = useSessionStore.getState() expect(state.error).toBe('Max API injoignable') expect(state.loading).toBe(false) }) + it('should set an error and stop loading when sending a message throws', async () => { + sendTextTurn.mockRejectedValueOnce(new Error('Max API injoignable')) + + await useSessionStore.getState().sendTextTurn('message') + + const state = useSessionStore.getState() + expect(state.error).toBe('Max API injoignable') + expect(state.loading).toBe(false) + }) + + it('should apply an objective-ready broadcast from the main process (used by the dedicated objective window)', () => { + const draft = { + subject: 'Facturation freelance', + professionalGoal: 'Facturer sans erreur', + duration: '2 semaines' + } + + useSessionStore.getState().applyObjectiveReady(1, draft) + + const state = useSessionStore.getState() + expect(state.sessionId).toBe(1) + expect(state.objectiveReady).toBe(true) + expect(state.objectiveDraft).toEqual(draft) + }) + it('should confirm the objective and refresh the session status', async () => { - routeMessage.mockResolvedValueOnce({ - type: 'learn', - sessionId: 1, - reply: 'Recap', - ready: true, - draft: { subject: 's', professionalGoal: 'g', duration: '1 semaine' } - }) - get.mockResolvedValueOnce({ id: 1, status: 'objective_discovery' }) - await useSessionStore.getState().sendMessage('message') + useSessionStore + .getState() + .applyObjectiveReady(1, { subject: 's', professionalGoal: 'g', duration: '1 semaine' }) confirmObjective.mockResolvedValueOnce({}) get.mockResolvedValueOnce({ id: 1, status: 'objective_validated' }) @@ -122,7 +82,6 @@ describe('useSessionStore', () => { expect(confirmObjective).toHaveBeenCalledWith(1) const state = useSessionStore.getState() - expect(state.objectiveConfirmed).toBe(true) expect(state.status).toBe('objective_validated') }) @@ -135,15 +94,10 @@ describe('useSessionStore', () => { expect(useSessionStore.getState().error).toBe('Aucune session en cours') }) - it('should reset all state on restart and notify the main process', async () => { - routeMessage.mockResolvedValueOnce({ - type: 'learn', - sessionId: 1, - reply: 'ok', - ready: false - }) - get.mockResolvedValueOnce({ id: 1, status: 'objective_discovery' }) - await useSessionStore.getState().sendMessage('message') + it('should reset all state on restart and notify the main process', () => { + useSessionStore + .getState() + .applyObjectiveReady(1, { subject: 's', professionalGoal: 'g', duration: '1 semaine' }) notifySessionEnded.mockClear() useSessionStore.getState().restart() @@ -151,7 +105,8 @@ describe('useSessionStore', () => { expect(notifySessionEnded).toHaveBeenCalledOnce() const state = useSessionStore.getState() expect(state.sessionId).toBeNull() - expect(state.messages).toEqual([]) + expect(state.objectiveReady).toBe(false) + expect(state.objectiveDraft).toBeNull() }) it('should set the status directly (used by the stepper window to sync with the main process)', () => { diff --git a/Max Avatar/tests/unit/components/useProactiveSpeech.test.ts b/Max Avatar/tests/unit/components/useProactiveSpeech.test.ts index 377aa91..f46911b 100644 --- a/Max Avatar/tests/unit/components/useProactiveSpeech.test.ts +++ b/Max Avatar/tests/unit/components/useProactiveSpeech.test.ts @@ -31,4 +31,16 @@ describe('useProactiveSpeech()', () => { onProactiveSpeechCallback?.(audio) expect(enqueueSpeech).toHaveBeenCalledWith(audio) }) + + it('should report speaking then idle around playback (used by the avatar status indicator for text-turn replies)', async () => { + const onStateChange = vi.fn() + renderHook(() => useProactiveSpeech({ current: null }, onStateChange)) + + onProactiveSpeechCallback?.(new ArrayBuffer(4)) + expect(onStateChange).toHaveBeenCalledWith('speaking') + + await Promise.resolve() + await Promise.resolve() + expect(onStateChange).toHaveBeenCalledWith('idle') + }) }) diff --git a/Max Avatar/tests/unit/objectiveWindow.test.ts b/Max Avatar/tests/unit/objectiveWindow.test.ts new file mode 100644 index 0000000..b4a5842 --- /dev/null +++ b/Max Avatar/tests/unit/objectiveWindow.test.ts @@ -0,0 +1,78 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest' +import { EventEmitter } from 'node:events' + +vi.mock('@electron-toolkit/utils', () => ({ is: { dev: false } })) + +class FakeWebContents extends EventEmitter {} + +class FakeBrowserWindow extends EventEmitter { + webContents = new FakeWebContents() + show = vi.fn() + focus = vi.fn() + setAlwaysOnTop = vi.fn() + loadURL = vi.fn() + loadFile = vi.fn() + close = vi.fn() + destroyed = false + isDestroyed(): boolean { + return this.destroyed + } +} + +let lastWindow: FakeBrowserWindow | null = null +function createBrowserWindow(): FakeBrowserWindow { + const window = new FakeBrowserWindow() + lastWindow = window + return window +} + +vi.mock('electron', () => ({ + BrowserWindow: vi.fn(createBrowserWindow) +})) + +const { openObjectiveWindow, closeObjectiveWindow, isObjectiveWindowOpen } = + await import('../../src/main/objectiveWindow') + +describe('objectiveWindow', () => { + beforeEach(() => { + lastWindow?.emit('closed') + vi.clearAllMocks() + lastWindow = null + }) + + describe('openObjectiveWindow()', () => { + it('should create and load a window on the #objective hash', () => { + openObjectiveWindow() + + expect(lastWindow?.loadFile).toHaveBeenCalledWith( + expect.stringContaining('index.html'), + expect.objectContaining({ hash: 'objective' }) + ) + expect(isObjectiveWindowOpen()).toBe(true) + }) + + it('should reuse the existing window and bring it to front on a second call', () => { + openObjectiveWindow() + const firstWindow = lastWindow + openObjectiveWindow() + + expect(lastWindow).toBe(firstWindow) + expect(firstWindow?.show).toHaveBeenCalled() + expect(firstWindow?.focus).toHaveBeenCalled() + }) + }) + + describe('closeObjectiveWindow()', () => { + it('should close the window when one is open', () => { + openObjectiveWindow() + closeObjectiveWindow() + + expect(lastWindow?.close).toHaveBeenCalled() + }) + + it('should do nothing when no window is open', () => { + expect(() => closeObjectiveWindow()).not.toThrow() + expect(isObjectiveWindowOpen()).toBe(false) + }) + }) +})