Develop #2
@@ -6,9 +6,11 @@ import { SECURE_WEB_PREFERENCES, blockExternalNavigation } from './utils/windowS
|
|||||||
let win: BrowserWindow | null = null
|
let win: BrowserWindow | null = null
|
||||||
let onClosedCallback: (() => void) | null = null
|
let onClosedCallback: (() => void) | null = null
|
||||||
|
|
||||||
// Fenetre separee et deplacable (retour utilisateur direct : le chat et le stepper doivent etre
|
// Fenetre separee et deplacable (retour utilisateur direct : la barre de saisie texte et le
|
||||||
// des vraies fenetres Electron, pas des panneaux ancres dans la fenetre avatar), meme pattern
|
// stepper doivent etre des vraies fenetres Electron, pas des panneaux ancres dans la fenetre
|
||||||
// singleton que src/main/auth/loginWindow.ts et stepperWindow.ts.
|
// 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 {
|
export function isChatWindowOpen(): boolean {
|
||||||
return win !== null && !win.isDestroyed()
|
return win !== null && !win.isDestroyed()
|
||||||
}
|
}
|
||||||
@@ -22,8 +24,8 @@ export function openChatWindow(): void {
|
|||||||
|
|
||||||
win = new BrowserWindow({
|
win = new BrowserWindow({
|
||||||
width: 380,
|
width: 380,
|
||||||
height: 560,
|
height: 100,
|
||||||
title: 'Max — conversation',
|
title: 'Max — écrire un message',
|
||||||
frame: false,
|
frame: false,
|
||||||
transparent: true,
|
transparent: true,
|
||||||
backgroundColor: '#00000000',
|
backgroundColor: '#00000000',
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import { loginAndLoadKeys } from './auth/authClient'
|
|||||||
import { openLoginWindow, closeLoginWindow } from './auth/loginWindow'
|
import { openLoginWindow, closeLoginWindow } from './auth/loginWindow'
|
||||||
import { clearSession, getCurrentUserEmail, isLoggedIn, requireLoggedIn } from './auth/session'
|
import { clearSession, getCurrentUserEmail, isLoggedIn, requireLoggedIn } from './auth/session'
|
||||||
import { closeChatWindow, isChatWindowOpen, onChatWindowClosed, openChatWindow } from './chatWindow'
|
import { closeChatWindow, isChatWindowOpen, onChatWindowClosed, openChatWindow } from './chatWindow'
|
||||||
|
import { closeObjectiveWindow, openObjectiveWindow } from './objectiveWindow'
|
||||||
import { closeStepperWindow, openStepperWindow } from './stepperWindow'
|
import { closeStepperWindow, openStepperWindow } from './stepperWindow'
|
||||||
import {
|
import {
|
||||||
confirmObjective,
|
confirmObjective,
|
||||||
@@ -18,9 +19,10 @@ import {
|
|||||||
routeMessage,
|
routeMessage,
|
||||||
sendObjectiveMessage
|
sendObjectiveMessage
|
||||||
} from './api/sessionsClient'
|
} 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 { AuthStatus, LoginResult } from '../shared/auth'
|
||||||
import type {
|
import type {
|
||||||
|
ObjectiveDraft,
|
||||||
ObjectiveMessageResponse,
|
ObjectiveMessageResponse,
|
||||||
RouteMessageResponse,
|
RouteMessageResponse,
|
||||||
SessionObjectiveResponse,
|
SessionObjectiveResponse,
|
||||||
@@ -153,6 +155,7 @@ app
|
|||||||
clearSession()
|
clearSession()
|
||||||
closeChatWindow()
|
closeChatWindow()
|
||||||
closeStepperWindow()
|
closeStepperWindow()
|
||||||
|
closeObjectiveWindow()
|
||||||
event.sender.send('toggle-listening', false)
|
event.sender.send('toggle-listening', false)
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -167,7 +170,10 @@ app
|
|||||||
// fenetre de chat est fermee autrement que par ce menu (ex: Alt+F4).
|
// fenetre de chat est fermee autrement que par ce menu (ex: Alt+F4).
|
||||||
onChatWindowClosed(() => mainWindow?.webContents.send('chat-window-closed'))
|
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
|
// 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
|
// (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
|
// Relais inter-fenetres vers la fenetre dediee a la validation de l'objectif (voir
|
||||||
// fenetre de chat texte a son propre store Zustand (messages, brouillon d'objectif) qui ne
|
// src/main/objectiveWindow.ts) : separee du chat texte sur demande directe de l'utilisateur
|
||||||
// recoit jamais les tours de conversation inities depuis la voix, puisque ceux-ci sont geres
|
// (la confirmation ne doit jamais dependre d'ouvrir la conversation, y compris quand tout
|
||||||
// entierement dans le main process sans passer par l'IPC "sessions:route-message" de cette
|
// l'echange se fait au vocal). Ouverte et alimentee ici, dans le code partage par le texte et
|
||||||
// fenetre. Sans ce relais, ObjectiveValidationCard ne peut jamais apparaitre pour un
|
// la voix (handleRouteMessageResult), pour garantir que les deux canaux se comportent pareil.
|
||||||
// utilisateur qui fait tout au vocal (constate en test reel).
|
function broadcastObjectiveReady(sessionId: number, draft: ObjectiveDraft): void {
|
||||||
function broadcastVoiceTurn(result: RouteMessageResponse): void {
|
openObjectiveWindow()
|
||||||
for (const window of BrowserWindow.getAllWindows()) {
|
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
|
// Partage entre la barre de saisie texte (text-turn) et la voix (voice-turn) : "learn" est le
|
||||||
// le seul cas ou une session existe reellement (nouvelle ou poursuivie), cote serveur, quel
|
// seul cas ou une session existe reellement (nouvelle ou poursuivie), cote serveur, quel que
|
||||||
// que soit le canal d'entree (routeur d'intention, voir docs/Max_System_Prompt.md).
|
// soit le canal d'entree (routeur d'intention, voir docs/Max_System_Prompt.md).
|
||||||
// openStepperWindow() est idempotent (singleton).
|
// openStepperWindow()/openObjectiveWindow() sont idempotentes (singleton).
|
||||||
async function handleRouteMessageResult(result: RouteMessageResponse): Promise<void> {
|
async function handleRouteMessageResult(result: RouteMessageResponse): Promise<void> {
|
||||||
if (result.type === 'learn' && result.sessionId !== undefined) {
|
if (result.type === 'learn' && result.sessionId !== undefined) {
|
||||||
openStepperWindow()
|
openStepperWindow()
|
||||||
const session = await getSession(result.sessionId)
|
const session = await getSession(result.sessionId)
|
||||||
broadcastSessionStatus(session.status)
|
broadcastSessionStatus(session.status)
|
||||||
|
|
||||||
|
if (result.ready && result.draft) {
|
||||||
|
broadcastObjectiveReady(result.sessionId, result.draft)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -219,21 +229,13 @@ app
|
|||||||
return { ok: 'ignored', transcript }
|
return { ok: 'ignored', transcript }
|
||||||
}
|
}
|
||||||
|
|
||||||
// Meme point d'entree que le chat texte (POST /sessions/messages, routeur d'intention
|
// Meme point d'entree que la barre de saisie texte (POST /sessions/messages, routeur
|
||||||
// inclus) : une seule personnalite, un seul pipeline, quel que soit le canal d'entree.
|
// d'intention inclus) : une seule personnalite, un seul pipeline, quel que soit le canal
|
||||||
|
// d'entree.
|
||||||
const routed = await routeMessage(command)
|
const routed = await routeMessage(command)
|
||||||
const afterChat = performance.now()
|
const afterChat = performance.now()
|
||||||
const reply = sanitizeForSpeech(routed.reply)
|
const reply = sanitizeForSpeech(routed.reply)
|
||||||
await handleRouteMessageResult(routed)
|
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 speech = await synthesizeSpeech(reply)
|
||||||
const afterTts = performance.now()
|
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<TextTurnResult> => {
|
||||||
|
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(
|
ipcMain.handle(
|
||||||
'auth-login',
|
'auth-login',
|
||||||
async (_event, email: string, password: string): Promise<LoginResult> => {
|
async (_event, email: string, password: string): Promise<LoginResult> => {
|
||||||
@@ -305,21 +336,6 @@ app
|
|||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
ipcMain.handle(
|
|
||||||
'sessions:route-message',
|
|
||||||
async (_event, message: unknown): Promise<RouteMessageResponse> => {
|
|
||||||
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(
|
ipcMain.handle(
|
||||||
'sessions:confirm-objective',
|
'sessions:confirm-objective',
|
||||||
async (_event, id: unknown): Promise<SessionObjectiveResponse> => {
|
async (_event, id: unknown): Promise<SessionObjectiveResponse> => {
|
||||||
|
|||||||
@@ -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()
|
||||||
|
}
|
||||||
Vendored
+4
-4
@@ -1,9 +1,9 @@
|
|||||||
import { ElectronAPI } from '@electron-toolkit/preload'
|
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 { AuthStatus, LoginResult } from '../shared/auth'
|
||||||
import type {
|
import type {
|
||||||
|
ObjectiveDraft,
|
||||||
ObjectiveMessageResponse,
|
ObjectiveMessageResponse,
|
||||||
RouteMessageResponse,
|
|
||||||
SessionObjectiveResponse,
|
SessionObjectiveResponse,
|
||||||
SessionResponse,
|
SessionResponse,
|
||||||
SessionStatus
|
SessionStatus
|
||||||
@@ -14,7 +14,6 @@ export interface SessionsApi {
|
|||||||
get: (id: number) => Promise<SessionResponse>
|
get: (id: number) => Promise<SessionResponse>
|
||||||
sendObjectiveMessage: (id: number, message: string) => Promise<ObjectiveMessageResponse>
|
sendObjectiveMessage: (id: number, message: string) => Promise<ObjectiveMessageResponse>
|
||||||
confirmObjective: (id: number) => Promise<SessionObjectiveResponse>
|
confirmObjective: (id: number) => Promise<SessionObjectiveResponse>
|
||||||
routeMessage: (message: string) => Promise<RouteMessageResponse>
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ForgeAvatarApi {
|
export interface ForgeAvatarApi {
|
||||||
@@ -22,6 +21,7 @@ export interface ForgeAvatarApi {
|
|||||||
getWindowBounds: () => Promise<{ x: number; y: number; width: number; height: number }>
|
getWindowBounds: () => Promise<{ x: number; y: number; width: number; height: number }>
|
||||||
setWindowPosition: (x: number, y: number, width: number, height: number) => void
|
setWindowPosition: (x: number, y: number, width: number, height: number) => void
|
||||||
sendVoiceTurn: (audio: ArrayBuffer, mimeType: string) => Promise<VoiceTurnResult>
|
sendVoiceTurn: (audio: ArrayBuffer, mimeType: string) => Promise<VoiceTurnResult>
|
||||||
|
sendTextTurn: (message: string) => Promise<TextTurnResult>
|
||||||
openLoginWindow: () => void
|
openLoginWindow: () => void
|
||||||
logout: () => void
|
logout: () => void
|
||||||
quitApp: () => void
|
quitApp: () => void
|
||||||
@@ -31,7 +31,7 @@ export interface ForgeAvatarApi {
|
|||||||
onProactiveSpeech: (callback: (audio: ArrayBuffer) => void) => () => void
|
onProactiveSpeech: (callback: (audio: ArrayBuffer) => void) => () => void
|
||||||
onChatWindowClosed: (callback: () => void) => () => void
|
onChatWindowClosed: (callback: () => void) => () => void
|
||||||
onSessionStatusChanged: (callback: (status: SessionStatus) => 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
|
onUpdateAvailable: (callback: () => void) => () => void
|
||||||
onUpdateReady: (callback: () => void) => () => void
|
onUpdateReady: (callback: () => void) => () => void
|
||||||
login: (email: string, password: string) => Promise<LoginResult>
|
login: (email: string, password: string) => Promise<LoginResult>
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
import { contextBridge, ipcRenderer } from 'electron'
|
import { contextBridge, ipcRenderer } from 'electron'
|
||||||
import { electronAPI } from '@electron-toolkit/preload'
|
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 { AuthStatus, LoginResult } from '../shared/auth'
|
||||||
import type {
|
import type {
|
||||||
|
ObjectiveDraft,
|
||||||
ObjectiveMessageResponse,
|
ObjectiveMessageResponse,
|
||||||
RouteMessageResponse,
|
|
||||||
SessionObjectiveResponse,
|
SessionObjectiveResponse,
|
||||||
SessionResponse,
|
SessionResponse,
|
||||||
SessionStatus
|
SessionStatus
|
||||||
@@ -21,6 +21,8 @@ const api = {
|
|||||||
},
|
},
|
||||||
sendVoiceTurn: (audio: ArrayBuffer, mimeType: string): Promise<VoiceTurnResult> =>
|
sendVoiceTurn: (audio: ArrayBuffer, mimeType: string): Promise<VoiceTurnResult> =>
|
||||||
ipcRenderer.invoke('voice-turn', audio, mimeType),
|
ipcRenderer.invoke('voice-turn', audio, mimeType),
|
||||||
|
sendTextTurn: (message: string): Promise<TextTurnResult> =>
|
||||||
|
ipcRenderer.invoke('text-turn', message),
|
||||||
openLoginWindow: (): void => {
|
openLoginWindow: (): void => {
|
||||||
ipcRenderer.send('open-login-window')
|
ipcRenderer.send('open-login-window')
|
||||||
},
|
},
|
||||||
@@ -58,11 +60,16 @@ const api = {
|
|||||||
ipcRenderer.on('session-status-changed', handler)
|
ipcRenderer.on('session-status-changed', handler)
|
||||||
return () => ipcRenderer.removeListener('session-status-changed', handler)
|
return () => ipcRenderer.removeListener('session-status-changed', handler)
|
||||||
},
|
},
|
||||||
onVoiceTurnSynced: (callback: (result: RouteMessageResponse) => void): (() => void) => {
|
onObjectiveReady: (
|
||||||
const handler = (_event: Electron.IpcRendererEvent, result: RouteMessageResponse): void =>
|
callback: (sessionId: number, draft: ObjectiveDraft) => void
|
||||||
callback(result)
|
): (() => void) => {
|
||||||
ipcRenderer.on('voice-turn-synced', handler)
|
const handler = (
|
||||||
return () => ipcRenderer.removeListener('voice-turn-synced', 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) => {
|
onUpdateAvailable: (callback: () => void): (() => void) => {
|
||||||
const handler = (): void => callback()
|
const handler = (): void => callback()
|
||||||
@@ -83,9 +90,7 @@ const api = {
|
|||||||
sendObjectiveMessage: (id: number, message: string): Promise<ObjectiveMessageResponse> =>
|
sendObjectiveMessage: (id: number, message: string): Promise<ObjectiveMessageResponse> =>
|
||||||
ipcRenderer.invoke('sessions:send-objective-message', id, message),
|
ipcRenderer.invoke('sessions:send-objective-message', id, message),
|
||||||
confirmObjective: (id: number): Promise<SessionObjectiveResponse> =>
|
confirmObjective: (id: number): Promise<SessionObjectiveResponse> =>
|
||||||
ipcRenderer.invoke('sessions:confirm-objective', id),
|
ipcRenderer.invoke('sessions:confirm-objective', id)
|
||||||
routeMessage: (message: string): Promise<RouteMessageResponse> =>
|
|
||||||
ipcRenderer.invoke('sessions:route-message', message)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -22,7 +22,6 @@ function App(): React.JSX.Element {
|
|||||||
const [voiceState, setVoiceState] = useState<VoiceState>('idle')
|
const [voiceState, setVoiceState] = useState<VoiceState>('idle')
|
||||||
const [voiceError, setVoiceError] = useState<string | null>(null)
|
const [voiceError, setVoiceError] = useState<string | null>(null)
|
||||||
const [updateStatus, setUpdateStatus] = useState<'available' | 'ready' | null>(null)
|
const [updateStatus, setUpdateStatus] = useState<'available' | 'ready' | null>(null)
|
||||||
const sessionId = useSessionStore((state) => state.sessionId)
|
|
||||||
const restartSession = useSessionStore((state) => state.restart)
|
const restartSession = useSessionStore((state) => state.restart)
|
||||||
useEffect(() => window.api.onUpdateAvailable(() => setUpdateStatus('available')), [])
|
useEffect(() => window.api.onUpdateAvailable(() => setUpdateStatus('available')), [])
|
||||||
useEffect(() => window.api.onUpdateReady(() => setUpdateStatus('ready')), [])
|
useEffect(() => window.api.onUpdateReady(() => setUpdateStatus('ready')), [])
|
||||||
@@ -37,7 +36,7 @@ function App(): React.JSX.Element {
|
|||||||
if (state === 'recording' || state === 'processing') setVoiceError(null)
|
if (state === 'recording' || state === 'processing') setVoiceError(null)
|
||||||
}, [])
|
}, [])
|
||||||
useVoiceAssistant(avatar, listening, handleVoiceStateChange, handleVoiceError)
|
useVoiceAssistant(avatar, listening, handleVoiceStateChange, handleVoiceError)
|
||||||
useProactiveSpeech(avatar)
|
useProactiveSpeech(avatar, setVoiceState)
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
listeningRef.current = listening
|
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
|
// 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).
|
// (l'utilisateur peut couper l'ecoute manuellement sans se deconnecter).
|
||||||
useEffect(() => window.api.onToggleListening(refreshAuthStatus), [refreshAuthStatus])
|
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
|
// 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
|
// 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
|
// propre fenetre, ouverte directement par le main process des que le routeur d'intention detecte
|
||||||
// src/main/index.ts) - rien a faire ici.
|
// "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
|
// Resynchronise la coche du menu si la fenetre de saisie texte est fermee autrement que par ce
|
||||||
// d'envoyer le premier message qui cree la session, donc la fenetre de chat est deja ouverte a ce
|
// menu (ex: Alt+F4).
|
||||||
// moment-la. Ce filet de securite l'ouvre quand meme si une session demarre sans qu'elle le soit.
|
|
||||||
const previousSessionId = useRef<number | null>(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.
|
|
||||||
useEffect(() => window.api.onChatWindowClosed(() => setChatOpen(false)), [])
|
useEffect(() => window.api.onChatWindowClosed(() => setChatOpen(false)), [])
|
||||||
|
|
||||||
const onContextMenu = useCallback((event: React.MouseEvent) => {
|
const onContextMenu = useCallback((event: React.MouseEvent) => {
|
||||||
|
|||||||
@@ -1,74 +1,25 @@
|
|||||||
import { useEffect, useRef } from 'react'
|
|
||||||
import { useSessionStore } from '../stores/useSessionStore'
|
import { useSessionStore } from '../stores/useSessionStore'
|
||||||
import ChatBubble from './ChatBubble'
|
|
||||||
import InputBar from './InputBar'
|
import InputBar from './InputBar'
|
||||||
import ObjectiveValidationCard from './ObjectiveValidationCard'
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Panneau de conversation (docs/Max_Composants_Frontend.md section 4) : historique de messages +
|
* Ce n'est PAS un chat (retour utilisateur direct) : juste une barre de saisie alternative au
|
||||||
* carte de validation de l'objectif + barre de saisie. Rendu dans sa propre fenetre Electron
|
* micro, rendue dans sa propre fenetre Electron separee et deplacable (voir src/main/chatWindow.ts
|
||||||
* separee et deplacable (voir src/main/chatWindow.ts et la route #chat dans main.tsx), distincte
|
* et la route #chat dans main.tsx). Le texte tape suit exactement le meme pipeline qu'une phrase
|
||||||
* de la fenetre de l'avatar et de celle du PipelineStepper - voir le retour utilisateur qui
|
* prononcee a voix haute (meme routeur d'intention, meme Agent 1, voir "text-turn" dans
|
||||||
* demandait que chat et stepper soient des fenetres separees, deplacables independamment.
|
* src/main/index.ts) et Max repond TOUJOURS a voix haute via la file d'attente audio partagee -
|
||||||
* N'affiche jamais un statut calcule localement.
|
* jamais de reponse affichee a l'ecrit, donc aucun historique de conversation ici.
|
||||||
*/
|
*/
|
||||||
export default function ChatPanel(): React.JSX.Element {
|
export default function ChatPanel(): React.JSX.Element {
|
||||||
const {
|
const { loading, error, sendTextTurn } = useSessionStore()
|
||||||
messages,
|
|
||||||
objectiveDraft,
|
|
||||||
objectiveReady,
|
|
||||||
objectiveConfirmed,
|
|
||||||
loading,
|
|
||||||
error,
|
|
||||||
sendMessage,
|
|
||||||
confirmObjective,
|
|
||||||
restart,
|
|
||||||
syncVoiceTurn
|
|
||||||
} = useSessionStore()
|
|
||||||
const chatRef = useRef<HTMLDivElement | null>(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
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="chat-panel">
|
<div className="chat-panel">
|
||||||
<div className="chat-panel__messages" ref={chatRef}>
|
|
||||||
{messages.map((message) => (
|
|
||||||
<ChatBubble
|
|
||||||
key={message.id}
|
|
||||||
role={message.role}
|
|
||||||
content={message.content}
|
|
||||||
timestamp={message.timestamp}
|
|
||||||
/>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{error && <p className="chat-panel__error">{error}</p>}
|
{error && <p className="chat-panel__error">{error}</p>}
|
||||||
|
<InputBar
|
||||||
{showObjectiveCard && objectiveDraft ? (
|
placeholder="Ecris ce que tu veux dire a Max..."
|
||||||
<ObjectiveValidationCard
|
disabled={loading}
|
||||||
objective={objectiveDraft}
|
onSend={(text) => void sendTextTurn(text)}
|
||||||
onConfirm={confirmObjective}
|
/>
|
||||||
onRestart={restart}
|
|
||||||
/>
|
|
||||||
) : (
|
|
||||||
<InputBar
|
|
||||||
placeholder="Explique a Max ce que tu veux apprendre..."
|
|
||||||
disabled={loading}
|
|
||||||
onSend={(text) => void sendMessage(text)}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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 (
|
||||||
|
<ObjectiveValidationCard
|
||||||
|
objective={objectiveDraft}
|
||||||
|
onConfirm={confirmObjective}
|
||||||
|
onRestart={restart}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -12,15 +12,18 @@ import { createRoot } from 'react-dom/client'
|
|||||||
import App from './App'
|
import App from './App'
|
||||||
import ChatPanel from './components/ChatPanel'
|
import ChatPanel from './components/ChatPanel'
|
||||||
import LoginView from './components/LoginView'
|
import LoginView from './components/LoginView'
|
||||||
|
import ObjectiveWindowRoot from './components/ObjectiveWindowRoot'
|
||||||
import StepperView from './components/StepperView'
|
import StepperView from './components/StepperView'
|
||||||
|
|
||||||
// Fenetres secondaires (login, chat, stepper - chacune ouverte/fermee par le main process) :
|
// Fenetres secondaires (login, chat, stepper, objectif - chacune ouverte/fermee par le main
|
||||||
// chargent ce meme bundle avec un hash different pour afficher une autre vue que l'avatar. La
|
// process) : chargent ce meme bundle avec un hash different pour afficher une autre vue que
|
||||||
// fenetre avatar, chargee sans hash, continue de monter <App /> comme avant, sans aucun changement.
|
// l'avatar. La fenetre avatar, chargee sans hash, continue de monter <App /> comme avant, sans
|
||||||
|
// aucun changement.
|
||||||
function renderForHash(): React.JSX.Element {
|
function renderForHash(): React.JSX.Element {
|
||||||
if (location.hash === '#login') return <LoginView />
|
if (location.hash === '#login') return <LoginView />
|
||||||
if (location.hash === '#chat') return <ChatPanel />
|
if (location.hash === '#chat') return <ChatPanel />
|
||||||
if (location.hash === '#stepper') return <StepperView />
|
if (location.hash === '#stepper') return <StepperView />
|
||||||
|
if (location.hash === '#objective') return <ObjectiveWindowRoot />
|
||||||
return <App />
|
return <App />
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,76 +1,46 @@
|
|||||||
import { create } from 'zustand'
|
import { create } from 'zustand'
|
||||||
import type { ObjectiveDraft, RouteMessageResponse, SessionStatus } from '../../../shared/session'
|
import type { ObjectiveDraft, SessionStatus } from '../../../shared/session'
|
||||||
|
|
||||||
export interface ChatMessage {
|
|
||||||
id: string
|
|
||||||
role: 'max' | 'user'
|
|
||||||
content: string
|
|
||||||
timestamp: Date
|
|
||||||
}
|
|
||||||
|
|
||||||
interface SessionState {
|
interface SessionState {
|
||||||
sessionId: number | null
|
sessionId: number | null
|
||||||
status: SessionStatus | null
|
status: SessionStatus | null
|
||||||
messages: ChatMessage[]
|
|
||||||
objectiveDraft: ObjectiveDraft | null
|
objectiveDraft: ObjectiveDraft | null
|
||||||
objectiveReady: boolean
|
objectiveReady: boolean
|
||||||
objectiveConfirmed: boolean
|
|
||||||
loading: boolean
|
loading: boolean
|
||||||
error: string | null
|
error: string | null
|
||||||
sendMessage: (text: string) => Promise<void>
|
sendTextTurn: (text: string) => Promise<void>
|
||||||
confirmObjective: (objective: ObjectiveDraft) => Promise<void>
|
confirmObjective: (objective: ObjectiveDraft) => Promise<void>
|
||||||
restart: () => void
|
restart: () => void
|
||||||
setStatus: (status: SessionStatus) => void
|
setStatus: (status: SessionStatus) => void
|
||||||
syncVoiceTurn: (result: RouteMessageResponse) => void
|
applyObjectiveReady: (sessionId: number, draft: ObjectiveDraft) => void
|
||||||
}
|
|
||||||
|
|
||||||
function pushMessage(
|
|
||||||
messages: ChatMessage[],
|
|
||||||
role: ChatMessage['role'],
|
|
||||||
content: string
|
|
||||||
): ChatMessage[] {
|
|
||||||
return [...messages, { id: crypto.randomUUID(), role, content, timestamp: new Date() }]
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Seule source de verite pour l'etat du pipeline cote renderer. Le statut de session n'est JAMAIS
|
* 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
|
* 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<SessionState>((set, get) => ({
|
export const useSessionStore = create<SessionState>((set, get) => ({
|
||||||
sessionId: null,
|
sessionId: null,
|
||||||
status: null,
|
status: null,
|
||||||
messages: [],
|
|
||||||
objectiveDraft: null,
|
objectiveDraft: null,
|
||||||
objectiveReady: false,
|
objectiveReady: false,
|
||||||
objectiveConfirmed: false,
|
|
||||||
loading: false,
|
loading: false,
|
||||||
error: null,
|
error: null,
|
||||||
|
|
||||||
sendMessage: async (text: string): Promise<void> => {
|
sendTextTurn: async (text: string): Promise<void> => {
|
||||||
set((state) => ({
|
set({ loading: true, error: null })
|
||||||
messages: pushMessage(state.messages, 'user', text),
|
|
||||||
loading: true,
|
|
||||||
error: null
|
|
||||||
}))
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Point d'entree unique (docs/Max_System_Prompt.md, routeur d'intention) : ne cree une
|
const result = await window.api.sendTextTurn(text)
|
||||||
// session que si le backend detecte reellement une intention d'apprendre. Un message de
|
if (!result.ok) {
|
||||||
// simple conversation ("salut ça va ?") ne demarre jamais de formation.
|
set({ loading: false, error: result.error })
|
||||||
const result = await window.api.sessions.routeMessage(text)
|
return
|
||||||
|
|
||||||
if (result.type === 'learn' && result.sessionId !== undefined) {
|
|
||||||
const session = await window.api.sessions.get(result.sessionId)
|
|
||||||
set({ sessionId: result.sessionId, status: session.status })
|
|
||||||
}
|
}
|
||||||
|
set({ loading: false })
|
||||||
set((state) => ({
|
|
||||||
messages: pushMessage(state.messages, 'max', result.reply),
|
|
||||||
objectiveReady: result.ready ?? false,
|
|
||||||
objectiveDraft: result.draft ?? state.objectiveDraft,
|
|
||||||
loading: false
|
|
||||||
}))
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
set({
|
set({
|
||||||
loading: false,
|
loading: false,
|
||||||
@@ -92,7 +62,6 @@ export const useSessionStore = create<SessionState>((set, get) => ({
|
|||||||
const session = await window.api.sessions.get(sessionId)
|
const session = await window.api.sessions.get(sessionId)
|
||||||
set({
|
set({
|
||||||
status: session.status,
|
status: session.status,
|
||||||
objectiveConfirmed: true,
|
|
||||||
loading: false
|
loading: false
|
||||||
})
|
})
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -108,37 +77,28 @@ export const useSessionStore = create<SessionState>((set, get) => ({
|
|||||||
set({
|
set({
|
||||||
sessionId: null,
|
sessionId: null,
|
||||||
status: null,
|
status: null,
|
||||||
messages: [],
|
|
||||||
objectiveDraft: null,
|
objectiveDraft: null,
|
||||||
objectiveReady: false,
|
objectiveReady: false,
|
||||||
objectiveConfirmed: false,
|
|
||||||
loading: false,
|
loading: false,
|
||||||
error: null
|
error: null
|
||||||
})
|
})
|
||||||
},
|
},
|
||||||
|
|
||||||
// Utilise uniquement par la fenetre du stepper (src/renderer/src/components/StepperView.tsx),
|
// Utilise par la fenetre du stepper (StepperView.tsx) : elle vit dans un process renderer isole
|
||||||
// qui vit dans un process renderer isole et n'a donc pas sa propre copie a jour de l'etat :
|
// et n'a donc pas sa propre copie a jour de l'etat. Le main process relaie le statut des qu'il
|
||||||
// le main process relaie le statut recu par la fenetre de chat via l'IPC
|
// change reellement cote serveur, quel que soit le canal d'entree (voir
|
||||||
// "session-status-changed" (voir src/main/index.ts). La fenetre de chat, elle, continue de
|
// "session-status-changed" dans src/main/index.ts).
|
||||||
// deriver son statut directement des reponses de ses propres appels API.
|
|
||||||
setStatus: (status: SessionStatus): void => {
|
setStatus: (status: SessionStatus): void => {
|
||||||
set({ status })
|
set({ status })
|
||||||
},
|
},
|
||||||
|
|
||||||
// Utilise uniquement par la fenetre de chat (src/renderer/src/components/ChatPanel.tsx), qui
|
// Utilise uniquement par la fenetre dediee a la validation de l'objectif
|
||||||
// sinon ne voit jamais les tours de conversation inities au vocal : son store Zustand, isole
|
// (ObjectiveWindowRoot.tsx), separee de la barre de saisie texte sur demande directe de
|
||||||
// dans son propre process renderer, ne recoit rien des appels faits par le process main pour le
|
// l'utilisateur : la confirmation ne doit jamais dependre d'ouvrir cette barre, y compris quand
|
||||||
// handler "voice-turn" (voir src/main/index.ts, broadcastVoiceTurn). Sans ca,
|
// tout l'echange se fait au vocal. Alimentee par le main process des que l'Agent 1 produit un
|
||||||
// ObjectiveValidationCard ne peut jamais apparaitre pour un utilisateur qui fait tout au vocal
|
// objectif pret a confirmer, quel que soit le canal d'entree (texte ou vocal, voir
|
||||||
// (constate en test reel). Ne pousse PAS le message utilisateur original (le main process ne le
|
// "objective-ready" dans src/main/index.ts, declenche depuis le meme handleRouteMessageResult).
|
||||||
// relaie pas ici), seulement la reponse de Max et l'etat pret/brouillon qui en resulte.
|
applyObjectiveReady: (sessionId: number, draft: ObjectiveDraft): void => {
|
||||||
syncVoiceTurn: (result: RouteMessageResponse): void => {
|
set({ sessionId, objectiveDraft: draft, objectiveReady: true })
|
||||||
set((state) => ({
|
|
||||||
sessionId: result.sessionId ?? state.sessionId,
|
|
||||||
messages: pushMessage(state.messages, 'max', result.reply),
|
|
||||||
objectiveReady: result.ready ?? state.objectiveReady,
|
|
||||||
objectiveDraft: result.draft ?? state.objectiveDraft
|
|
||||||
}))
|
|
||||||
}
|
}
|
||||||
}))
|
}))
|
||||||
|
|||||||
@@ -356,12 +356,12 @@
|
|||||||
pointer-events: none;
|
pointer-events: none;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* ── Fenetre de chat (fenetre Electron separee et deplacable, voir src/main/chatWindow.ts) ──
|
/* ── Barre de saisie texte (fenetre Electron separee et deplacable, voir src/main/chatWindow.ts) ──
|
||||||
Remplit entierement sa propre fenetre transparente : le cadre arrondi/l'ombre donnent
|
Ce n'est PAS un chat (retour utilisateur direct) : juste une entree alternative au micro, sans
|
||||||
l'apparence d'une carte flottante malgre la fenetre rectangulaire sous-jacente. La fenetre
|
historique de conversation affiche. Remplit entierement sa propre fenetre transparente : le
|
||||||
entiere est une zone de glisser-deplacer (-webkit-app-region: drag), sauf les zones
|
cadre arrondi/l'ombre donnent l'apparence d'une carte flottante malgre la fenetre rectangulaire
|
||||||
interactives (messages, saisie, carte de validation) qui doivent rester cliquables/
|
sous-jacente. La fenetre entiere est une zone de glisser-deplacer (-webkit-app-region: drag),
|
||||||
selectionnables. */
|
sauf la zone de saisie qui doit rester cliquable/selectionnable. */
|
||||||
|
|
||||||
.chat-panel {
|
.chat-panel {
|
||||||
width: 100%;
|
width: 100%;
|
||||||
@@ -378,18 +378,6 @@
|
|||||||
-webkit-app-region: drag;
|
-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 {
|
.chat-panel__error {
|
||||||
margin: 0;
|
margin: 0;
|
||||||
font-size: var(--text-sm);
|
font-size: var(--text-sm);
|
||||||
|
|||||||
@@ -2,16 +2,20 @@ import { useEffect, type RefObject } from 'react'
|
|||||||
import type { AvatarHandle } from '../components/AvatarViewer'
|
import type { AvatarHandle } from '../components/AvatarViewer'
|
||||||
import { bindSpeechAvatar, enqueueSpeech } from './speechQueue'
|
import { bindSpeechAvatar, enqueueSpeech } from './speechQueue'
|
||||||
|
|
||||||
// Joue une reponse de l'IA declenchee sans question de l'utilisateur (ex: rappel programme,
|
// Joue une reponse de l'IA declenchee sans micro actif (ex: reponse a un message tape dans la
|
||||||
// commentaire immediat pendant qu'un outil s'execute), independamment de l'etat d'activation de
|
// barre de saisie texte - voir "text-turn" dans src/main/index.ts - ou un rappel programme),
|
||||||
// l'ecoute vocale. Passe par la file d'attente partagee (speechQueue.ts) pour ne jamais chevaucher
|
// independamment de l'etat d'activation de l'ecoute vocale. Passe par la file d'attente partagee
|
||||||
// la reponse finale d'un tour de voix (constate en test reel : deux chemins audio independants se
|
// (speechQueue.ts) pour ne jamais chevaucher la reponse finale d'un tour de voix (constate en test
|
||||||
// chevauchaient avant cette unification).
|
// reel : deux chemins audio independants se chevauchaient avant cette unification).
|
||||||
export function useProactiveSpeech(avatarRef: RefObject<AvatarHandle | null>): void {
|
export function useProactiveSpeech(
|
||||||
|
avatarRef: RefObject<AvatarHandle | null>,
|
||||||
|
onStateChange?: (state: 'speaking' | 'idle') => void
|
||||||
|
): void {
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
bindSpeechAvatar(avatarRef)
|
bindSpeechAvatar(avatarRef)
|
||||||
return window.api.onProactiveSpeech((audio) => {
|
return window.api.onProactiveSpeech((audio) => {
|
||||||
void enqueueSpeech(audio)
|
onStateChange?.('speaking')
|
||||||
|
void enqueueSpeech(audio).then(() => onStateChange?.('idle'))
|
||||||
})
|
})
|
||||||
}, [avatarRef])
|
}, [avatarRef, onStateChange])
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,3 +2,9 @@ export type VoiceTurnResult =
|
|||||||
| { ok: true; transcript: string; reply: string; audio: ArrayBuffer }
|
| { ok: true; transcript: string; reply: string; audio: ArrayBuffer }
|
||||||
| { ok: 'ignored'; transcript: string }
|
| { ok: 'ignored'; transcript: string }
|
||||||
| { ok: false; error: 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 }
|
||||||
|
|||||||
@@ -234,13 +234,13 @@ describe('<App />', () => {
|
|||||||
expect(screen.queryByLabelText('Message')).not.toBeInTheDocument()
|
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' })
|
getAuthStatus.mockResolvedValue({ loggedIn: true, email: 'william@example.com' })
|
||||||
render(<App />)
|
render(<App />)
|
||||||
await waitFor(() => expect(getAuthStatus).toHaveBeenCalled())
|
await waitFor(() => expect(getAuthStatus).toHaveBeenCalled())
|
||||||
|
|
||||||
act(() => useSessionStore.setState({ sessionId: 1, status: 'objective_discovery' }))
|
act(() => useSessionStore.setState({ sessionId: 1, status: 'objective_discovery' }))
|
||||||
|
|
||||||
expect(toggleChatWindow).toHaveBeenCalledOnce()
|
expect(toggleChatWindow).not.toHaveBeenCalled()
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -1,90 +1,47 @@
|
|||||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
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 ChatPanel from '../../../src/renderer/src/components/ChatPanel'
|
||||||
import { useSessionStore } from '../../../src/renderer/src/stores/useSessionStore'
|
import { useSessionStore } from '../../../src/renderer/src/stores/useSessionStore'
|
||||||
|
|
||||||
const get = vi.fn()
|
const sendTextTurn = vi.fn()
|
||||||
const routeMessage = vi.fn()
|
|
||||||
const confirmObjective = vi.fn()
|
|
||||||
const notifySessionEnded = vi.fn()
|
const notifySessionEnded = vi.fn()
|
||||||
const onVoiceTurnSynced = vi.fn(() => () => {})
|
|
||||||
|
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
vi.clearAllMocks()
|
vi.clearAllMocks()
|
||||||
;(window as unknown as { api: Record<string, unknown> }).api = {
|
;(window as unknown as { api: Record<string, unknown> }).api = {
|
||||||
sessions: { get, routeMessage, confirmObjective },
|
sendTextTurn,
|
||||||
notifySessionEnded,
|
notifySessionEnded
|
||||||
onVoiceTurnSynced
|
|
||||||
}
|
}
|
||||||
useSessionStore.getState().restart()
|
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('<ChatPanel />', () => {
|
describe('<ChatPanel />', () => {
|
||||||
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(<ChatPanel />)
|
render(<ChatPanel />)
|
||||||
expect(screen.getByLabelText('Message')).toBeInTheDocument()
|
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(<ChatPanel />)
|
|
||||||
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(<ChatPanel />)
|
|
||||||
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(<ChatPanel />)
|
|
||||||
expect(screen.queryByText('Ton objectif de formation')).not.toBeInTheDocument()
|
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 () => {
|
it('should submit the typed text via text-turn and clear the field', async () => {
|
||||||
routeMessage.mockRejectedValueOnce(new Error('Max API injoignable'))
|
sendTextTurn.mockResolvedValueOnce({ ok: true })
|
||||||
|
|
||||||
|
render(<ChatPanel />)
|
||||||
|
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(<ChatPanel />)
|
render(<ChatPanel />)
|
||||||
fireEvent.change(screen.getByLabelText('Message'), { target: { value: 'message' } })
|
fireEvent.change(screen.getByLabelText('Message'), { target: { value: 'message' } })
|
||||||
|
|||||||
@@ -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<string, unknown> }).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('<ObjectiveWindowRoot />', () => {
|
||||||
|
it('should render nothing before the main process relays a ready objective', () => {
|
||||||
|
const { container } = render(<ObjectiveWindowRoot />)
|
||||||
|
expect(container).toBeEmptyDOMElement()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('should show the card once the main process relays a ready objective (text or voice, same path)', () => {
|
||||||
|
render(<ObjectiveWindowRoot />)
|
||||||
|
|
||||||
|
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<string, unknown> } }).api.sessions.get = vi
|
||||||
|
.fn()
|
||||||
|
.mockResolvedValueOnce({ id: 1, status: 'objective_validated' })
|
||||||
|
|
||||||
|
render(<ObjectiveWindowRoot />)
|
||||||
|
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()
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -2,116 +2,76 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'
|
|||||||
import { useSessionStore } from '../../../../src/renderer/src/stores/useSessionStore'
|
import { useSessionStore } from '../../../../src/renderer/src/stores/useSessionStore'
|
||||||
|
|
||||||
const get = vi.fn()
|
const get = vi.fn()
|
||||||
const routeMessage = vi.fn()
|
const sendTextTurn = vi.fn()
|
||||||
const confirmObjective = vi.fn()
|
const confirmObjective = vi.fn()
|
||||||
const notifySessionEnded = vi.fn()
|
const notifySessionEnded = vi.fn()
|
||||||
|
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
vi.clearAllMocks()
|
vi.clearAllMocks()
|
||||||
;(window as unknown as { api: Record<string, unknown> }).api = {
|
;(window as unknown as { api: Record<string, unknown> }).api = {
|
||||||
sessions: { get, routeMessage, confirmObjective },
|
sessions: { get, confirmObjective },
|
||||||
|
sendTextTurn,
|
||||||
notifySessionEnded
|
notifySessionEnded
|
||||||
}
|
}
|
||||||
useSessionStore.getState().restart()
|
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', () => {
|
describe('useSessionStore', () => {
|
||||||
it('should not create a session when the backend classifies the message as chat', async () => {
|
it('should send a typed message via text-turn and clear the loading state on success', async () => {
|
||||||
routeMessage.mockResolvedValueOnce({ type: 'chat', reply: 'Salut, comment puis-je aider ?' })
|
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(sendTextTurn).toHaveBeenCalledWith('Je veux apprendre la facturation')
|
||||||
expect(get).not.toHaveBeenCalled()
|
|
||||||
const state = useSessionStore.getState()
|
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.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 () => {
|
it('should set an error when the backend reports a failure', async () => {
|
||||||
routeMessage.mockResolvedValueOnce({
|
sendTextTurn.mockResolvedValueOnce({ ok: false, error: 'Max API injoignable' })
|
||||||
type: 'learn',
|
|
||||||
sessionId: 1,
|
|
||||||
reply: 'Quel est ton sujet ?',
|
|
||||||
ready: false
|
|
||||||
})
|
|
||||||
get.mockResolvedValueOnce({ id: 1, status: 'objective_discovery' })
|
|
||||||
|
|
||||||
await useSessionStore.getState().sendMessage('Je veux apprendre la facturation')
|
await useSessionStore.getState().sendTextTurn('message')
|
||||||
|
|
||||||
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')
|
|
||||||
|
|
||||||
const state = useSessionStore.getState()
|
const state = useSessionStore.getState()
|
||||||
expect(state.error).toBe('Max API injoignable')
|
expect(state.error).toBe('Max API injoignable')
|
||||||
expect(state.loading).toBe(false)
|
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 () => {
|
it('should confirm the objective and refresh the session status', async () => {
|
||||||
routeMessage.mockResolvedValueOnce({
|
useSessionStore
|
||||||
type: 'learn',
|
.getState()
|
||||||
sessionId: 1,
|
.applyObjectiveReady(1, { subject: 's', professionalGoal: 'g', duration: '1 semaine' })
|
||||||
reply: 'Recap',
|
|
||||||
ready: true,
|
|
||||||
draft: { subject: 's', professionalGoal: 'g', duration: '1 semaine' }
|
|
||||||
})
|
|
||||||
get.mockResolvedValueOnce({ id: 1, status: 'objective_discovery' })
|
|
||||||
await useSessionStore.getState().sendMessage('message')
|
|
||||||
|
|
||||||
confirmObjective.mockResolvedValueOnce({})
|
confirmObjective.mockResolvedValueOnce({})
|
||||||
get.mockResolvedValueOnce({ id: 1, status: 'objective_validated' })
|
get.mockResolvedValueOnce({ id: 1, status: 'objective_validated' })
|
||||||
@@ -122,7 +82,6 @@ describe('useSessionStore', () => {
|
|||||||
|
|
||||||
expect(confirmObjective).toHaveBeenCalledWith(1)
|
expect(confirmObjective).toHaveBeenCalledWith(1)
|
||||||
const state = useSessionStore.getState()
|
const state = useSessionStore.getState()
|
||||||
expect(state.objectiveConfirmed).toBe(true)
|
|
||||||
expect(state.status).toBe('objective_validated')
|
expect(state.status).toBe('objective_validated')
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -135,15 +94,10 @@ describe('useSessionStore', () => {
|
|||||||
expect(useSessionStore.getState().error).toBe('Aucune session en cours')
|
expect(useSessionStore.getState().error).toBe('Aucune session en cours')
|
||||||
})
|
})
|
||||||
|
|
||||||
it('should reset all state on restart and notify the main process', async () => {
|
it('should reset all state on restart and notify the main process', () => {
|
||||||
routeMessage.mockResolvedValueOnce({
|
useSessionStore
|
||||||
type: 'learn',
|
.getState()
|
||||||
sessionId: 1,
|
.applyObjectiveReady(1, { subject: 's', professionalGoal: 'g', duration: '1 semaine' })
|
||||||
reply: 'ok',
|
|
||||||
ready: false
|
|
||||||
})
|
|
||||||
get.mockResolvedValueOnce({ id: 1, status: 'objective_discovery' })
|
|
||||||
await useSessionStore.getState().sendMessage('message')
|
|
||||||
|
|
||||||
notifySessionEnded.mockClear()
|
notifySessionEnded.mockClear()
|
||||||
useSessionStore.getState().restart()
|
useSessionStore.getState().restart()
|
||||||
@@ -151,7 +105,8 @@ describe('useSessionStore', () => {
|
|||||||
expect(notifySessionEnded).toHaveBeenCalledOnce()
|
expect(notifySessionEnded).toHaveBeenCalledOnce()
|
||||||
const state = useSessionStore.getState()
|
const state = useSessionStore.getState()
|
||||||
expect(state.sessionId).toBeNull()
|
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)', () => {
|
it('should set the status directly (used by the stepper window to sync with the main process)', () => {
|
||||||
|
|||||||
@@ -31,4 +31,16 @@ describe('useProactiveSpeech()', () => {
|
|||||||
onProactiveSpeechCallback?.(audio)
|
onProactiveSpeechCallback?.(audio)
|
||||||
expect(enqueueSpeech).toHaveBeenCalledWith(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')
|
||||||
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -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)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
})
|
||||||
Reference in New Issue
Block a user