diff --git a/Max Avatar/src/main/api/sessionsClient.ts b/Max Avatar/src/main/api/sessionsClient.ts index ad91a30..9a011ca 100644 --- a/Max Avatar/src/main/api/sessionsClient.ts +++ b/Max Avatar/src/main/api/sessionsClient.ts @@ -1,6 +1,7 @@ import { getAccessToken } from '../auth/session' import type { ObjectiveMessageResponse, + RouteMessageResponse, SessionObjectiveResponse, SessionResponse } from '../../shared/session' @@ -68,3 +69,13 @@ export function sendObjectiveMessage( export function confirmObjective(id: number): Promise { return call(`/sessions/${id}/objective/confirm`, { method: 'POST' }) } + +/** Point d'entree unique du chat (docs/Max_System_Prompt.md) : route vers la session active de + * l'utilisateur, ou classifie le message (routeur d'intention) pour decider de demarrer une + * formation ou de simplement repondre en conversation. */ +export function routeMessage(message: string): Promise { + return call('/sessions/messages', { + method: 'POST', + body: JSON.stringify({ message } satisfies { message: string }) + }) +} diff --git a/Max Avatar/src/main/index.ts b/Max Avatar/src/main/index.ts index 92bb7e0..1ab01c5 100644 --- a/Max Avatar/src/main/index.ts +++ b/Max Avatar/src/main/index.ts @@ -15,12 +15,14 @@ import { confirmObjective, createSession, getSession, + routeMessage, sendObjectiveMessage } from './api/sessionsClient' import type { VoiceTurnResult } from '../shared/voice' import type { AuthStatus, LoginResult } from '../shared/auth' import type { ObjectiveMessageResponse, + RouteMessageResponse, SessionObjectiveResponse, SessionResponse, SessionStatus @@ -265,6 +267,28 @@ 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) + // "learn" est le seul cas ou une session existe reellement (nouvelle ou poursuivie) : + // c'est le seul moment ou le stepper doit apparaitre (routeur d'intention, voir + // docs/Max_System_Prompt.md). openStepperWindow() est idempotent (singleton). + if (result.type === 'learn' && result.sessionId !== undefined) { + openStepperWindow() + const session = await getSession(result.sessionId) + broadcastSessionStatus(session.status) + } + return result + } + ) + ipcMain.handle( 'sessions:confirm-objective', async (_event, id: unknown): Promise => { diff --git a/Max Avatar/src/preload/index.d.ts b/Max Avatar/src/preload/index.d.ts index 133b06b..c9aa41a 100644 --- a/Max Avatar/src/preload/index.d.ts +++ b/Max Avatar/src/preload/index.d.ts @@ -3,6 +3,7 @@ import type { VoiceTurnResult } from '../shared/voice' import type { AuthStatus, LoginResult } from '../shared/auth' import type { ObjectiveMessageResponse, + RouteMessageResponse, SessionObjectiveResponse, SessionResponse, SessionStatus @@ -13,6 +14,7 @@ export interface SessionsApi { get: (id: number) => Promise sendObjectiveMessage: (id: number, message: string) => Promise confirmObjective: (id: number) => Promise + routeMessage: (message: string) => Promise } export interface ForgeAvatarApi { diff --git a/Max Avatar/src/preload/index.ts b/Max Avatar/src/preload/index.ts index e0169c0..0a82c7e 100644 --- a/Max Avatar/src/preload/index.ts +++ b/Max Avatar/src/preload/index.ts @@ -4,6 +4,7 @@ import type { VoiceTurnResult } from '../shared/voice' import type { AuthStatus, LoginResult } from '../shared/auth' import type { ObjectiveMessageResponse, + RouteMessageResponse, SessionObjectiveResponse, SessionResponse, SessionStatus @@ -76,7 +77,9 @@ 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) + ipcRenderer.invoke('sessions:confirm-objective', id), + routeMessage: (message: string): Promise => + ipcRenderer.invoke('sessions:route-message', message) } } diff --git a/Max Avatar/src/renderer/src/stores/useSessionStore.ts b/Max Avatar/src/renderer/src/stores/useSessionStore.ts index 27413a3..6c1b278 100644 --- a/Max Avatar/src/renderer/src/stores/useSessionStore.ts +++ b/Max Avatar/src/renderer/src/stores/useSessionStore.ts @@ -54,17 +54,19 @@ export const useSessionStore = create((set, get) => ({ })) try { - let { sessionId } = get() - if (sessionId === null) { - const session = await window.api.sessions.create() - sessionId = session.id - set({ sessionId, status: session.status }) + // 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.sessions.sendObjectiveMessage(sessionId, text) set((state) => ({ messages: pushMessage(state.messages, 'max', result.reply), - objectiveReady: result.ready, + objectiveReady: result.ready ?? false, objectiveDraft: result.draft ?? state.objectiveDraft, loading: false })) diff --git a/Max Avatar/src/shared/session.ts b/Max Avatar/src/shared/session.ts index d458caa..f5b3f5e 100644 --- a/Max Avatar/src/shared/session.ts +++ b/Max Avatar/src/shared/session.ts @@ -37,3 +37,14 @@ export interface ObjectiveMessageResponse { ready: boolean draft?: ObjectiveDraft } + +// Reponse de POST /sessions/messages : point d'entree unique du chat (docs/Max_System_Prompt.md, +// routeur d'intention). "chat" ne cree jamais de session ; "learn" en cree une (ou reutilise la +// session active) et demarre/poursuit l'Agent 1. +export interface RouteMessageResponse { + type: 'chat' | 'learn' + reply: string + sessionId?: number + ready?: boolean + draft?: ObjectiveDraft +} diff --git a/Max Avatar/tests/unit/components/ChatPanel.test.tsx b/Max Avatar/tests/unit/components/ChatPanel.test.tsx index 7cc4e56..94e326a 100644 --- a/Max Avatar/tests/unit/components/ChatPanel.test.tsx +++ b/Max Avatar/tests/unit/components/ChatPanel.test.tsx @@ -3,16 +3,15 @@ import { render, screen, fireEvent, waitFor } from '@testing-library/react' import ChatPanel from '../../../src/renderer/src/components/ChatPanel' import { useSessionStore } from '../../../src/renderer/src/stores/useSessionStore' -const create = vi.fn() const get = vi.fn() -const sendObjectiveMessage = vi.fn() +const routeMessage = vi.fn() const confirmObjective = vi.fn() const notifySessionEnded = vi.fn() beforeEach(() => { vi.clearAllMocks() ;(window as unknown as { api: Record }).api = { - sessions: { create, get, sendObjectiveMessage, confirmObjective }, + sessions: { get, routeMessage, confirmObjective }, notifySessionEnded } useSessionStore.getState().restart() @@ -26,8 +25,13 @@ describe('', () => { }) it('should send the first message, creating a session, and render the conversation', async () => { - create.mockResolvedValueOnce({ id: 1, status: 'objective_discovery' }) - sendObjectiveMessage.mockResolvedValueOnce({ reply: 'Quel est ton sujet ?', ready: false }) + 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' } }) @@ -38,12 +42,14 @@ describe('', () => { }) it('should show the ObjectiveValidationCard instead of the input bar once the agent is ready', async () => { - create.mockResolvedValueOnce({ id: 1, status: 'objective_discovery' }) - sendObjectiveMessage.mockResolvedValueOnce({ + 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' } }) @@ -54,7 +60,7 @@ describe('', () => { }) it('should show the store error message when a call fails', async () => { - create.mockRejectedValueOnce(new Error('Max API injoignable')) + routeMessage.mockRejectedValueOnce(new Error('Max API injoignable')) render() fireEvent.change(screen.getByLabelText('Message'), { target: { value: 'message' } }) diff --git a/Max Avatar/tests/unit/components/stores/useSessionStore.test.ts b/Max Avatar/tests/unit/components/stores/useSessionStore.test.ts index dd1156d..9502032 100644 --- a/Max Avatar/tests/unit/components/stores/useSessionStore.test.ts +++ b/Max Avatar/tests/unit/components/stores/useSessionStore.test.ts @@ -1,56 +1,89 @@ import { describe, it, expect, vi, beforeEach } from 'vitest' import { useSessionStore } from '../../../../src/renderer/src/stores/useSessionStore' -const create = vi.fn() const get = vi.fn() -const sendObjectiveMessage = vi.fn() +const routeMessage = vi.fn() const confirmObjective = vi.fn() const notifySessionEnded = vi.fn() beforeEach(() => { vi.clearAllMocks() ;(window as unknown as { api: Record }).api = { - sessions: { create, get, sendObjectiveMessage, confirmObjective }, + sessions: { get, routeMessage, confirmObjective }, notifySessionEnded } useSessionStore.getState().restart() }) describe('useSessionStore', () => { - it('should create a session on the first message and send it there', async () => { - create.mockResolvedValueOnce({ id: 1, status: 'objective_discovery' }) - sendObjectiveMessage.mockResolvedValueOnce({ reply: 'Quel est ton sujet ?', ready: false }) + 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 ?' }) - await useSessionStore.getState().sendMessage('Je veux apprendre la facturation') + await useSessionStore.getState().sendMessage('Salut ça va ?') - expect(create).toHaveBeenCalledOnce() - expect(sendObjectiveMessage).toHaveBeenCalledWith(1, 'Je veux apprendre la facturation') + expect(routeMessage).toHaveBeenCalledWith('Salut ça va ?') + expect(get).not.toHaveBeenCalled() const state = useSessionStore.getState() - expect(state.sessionId).toBe(1) - expect(state.status).toBe('objective_discovery') + expect(state.sessionId).toBeNull() expect(state.messages.map((m) => m.role)).toEqual(['user', 'max']) expect(state.loading).toBe(false) }) - it('should reuse the existing session id on subsequent messages', async () => { - create.mockResolvedValueOnce({ id: 1, status: 'objective_discovery' }) - sendObjectiveMessage.mockResolvedValue({ reply: 'ok', ready: false }) + 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' }) + 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(create).toHaveBeenCalledOnce() - expect(sendObjectiveMessage).toHaveBeenCalledTimes(2) + 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 () => { - create.mockResolvedValueOnce({ id: 1, status: 'objective_discovery' }) const draft = { subject: 'Facturation freelance', professionalGoal: 'Facturer sans erreur', duration: '2 semaines' } - sendObjectiveMessage.mockResolvedValueOnce({ reply: 'Voici le recap', ready: true, draft }) + 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') @@ -60,7 +93,7 @@ describe('useSessionStore', () => { }) it('should set an error and stop loading when sending a message fails', async () => { - create.mockRejectedValueOnce(new Error('Max API injoignable')) + routeMessage.mockRejectedValueOnce(new Error('Max API injoignable')) await useSessionStore.getState().sendMessage('message') @@ -70,19 +103,18 @@ describe('useSessionStore', () => { }) it('should confirm the objective and refresh the session status', async () => { - create.mockResolvedValueOnce({ id: 1, status: 'objective_discovery' }) - sendObjectiveMessage.mockResolvedValueOnce({ + 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') confirmObjective.mockResolvedValueOnce({}) get.mockResolvedValueOnce({ id: 1, status: 'objective_validated' }) - ;(window as unknown as { api: Record }).api = { - sessions: { create, get, sendObjectiveMessage, confirmObjective } - } await useSessionStore .getState() @@ -104,8 +136,13 @@ describe('useSessionStore', () => { }) it('should reset all state on restart and notify the main process', async () => { - create.mockResolvedValueOnce({ id: 1, status: 'objective_discovery' }) - sendObjectiveMessage.mockResolvedValueOnce({ reply: 'ok', ready: false }) + routeMessage.mockResolvedValueOnce({ + type: 'learn', + sessionId: 1, + reply: 'ok', + ready: false + }) + get.mockResolvedValueOnce({ id: 1, status: 'objective_discovery' }) await useSessionStore.getState().sendMessage('message') notifySessionEnded.mockClear() diff --git a/Max Avatar/tests/unit/sessionsClient.test.ts b/Max Avatar/tests/unit/sessionsClient.test.ts index a7b3fbe..340f3eb 100644 --- a/Max Avatar/tests/unit/sessionsClient.test.ts +++ b/Max Avatar/tests/unit/sessionsClient.test.ts @@ -3,8 +3,14 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest' const getAccessToken = vi.fn<() => string | null>(() => 'jwt-token') vi.mock('../../src/main/auth/session', () => ({ getAccessToken })) -const { createSession, getSession, sendObjectiveMessage, confirmObjective, MaxApiError } = - await import('../../src/main/api/sessionsClient') +const { + createSession, + getSession, + sendObjectiveMessage, + confirmObjective, + routeMessage, + MaxApiError +} = await import('../../src/main/api/sessionsClient') function jsonResponse(body: unknown, ok = true, status = ok ? 200 : 400): Response { return { ok, status, json: () => Promise.resolve(body) } as Response @@ -84,6 +90,20 @@ describe('sessionsClient', () => { expect(result.sessionId).toBe(1) }) + it('should route a message to the unified entry point', async () => { + global.fetch = vi.fn().mockResolvedValueOnce(jsonResponse({ type: 'chat', reply: 'Salut !' })) + + const result = await routeMessage('Salut ça va ?') + + expect(result).toEqual({ type: 'chat', reply: 'Salut !' }) + const calls = (global.fetch as unknown as { mock: { calls: [string, RequestInit][] } }).mock + .calls + const call = calls.at(0) + expect(call?.[0]).toContain('/sessions/messages') + const body = call?.[1]?.body as string + expect(JSON.parse(body)).toEqual({ message: 'Salut ça va ?' }) + }) + it('should throw MaxApiError with the server message on a non-ok response', async () => { global.fetch = vi.fn().mockResolvedValueOnce(jsonResponse({ message: 'Conflit' }, false, 409))