feat(sessions): route chat messages through the intent-aware backend entry point

Replace the chat window's unconditional create-session-then-send flow
with a single call to the new POST /sessions/messages endpoint: a
plain "salut ça va ?" no longer starts a fake training session, since
the backend's intent router decides that now.

Add sessions.routeMessage to the IPC/preload surface and the sessions
HTTP client. useSessionStore.sendMessage only sets sessionId/status
(fetched fresh via sessions:get) when the backend actually reports
type: "learn". The stepper-window-open + status-broadcast trigger in
main/index.ts moves from sessions:create's handler to
sessions:route-message's, since session creation now happens inside
the backend's routing logic rather than via an explicit prior call.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
william
2026-11-01 09:02:39 +01:00
co-authored by Claude Sonnet 5
parent ce25d3f290
commit 7179743d4e
9 changed files with 160 additions and 44 deletions
+11
View File
@@ -1,6 +1,7 @@
import { getAccessToken } from '../auth/session' import { getAccessToken } from '../auth/session'
import type { import type {
ObjectiveMessageResponse, ObjectiveMessageResponse,
RouteMessageResponse,
SessionObjectiveResponse, SessionObjectiveResponse,
SessionResponse SessionResponse
} from '../../shared/session' } from '../../shared/session'
@@ -68,3 +69,13 @@ export function sendObjectiveMessage(
export function confirmObjective(id: number): Promise<SessionObjectiveResponse> { export function confirmObjective(id: number): Promise<SessionObjectiveResponse> {
return call(`/sessions/${id}/objective/confirm`, { method: 'POST' }) 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<RouteMessageResponse> {
return call('/sessions/messages', {
method: 'POST',
body: JSON.stringify({ message } satisfies { message: string })
})
}
+24
View File
@@ -15,12 +15,14 @@ import {
confirmObjective, confirmObjective,
createSession, createSession,
getSession, getSession,
routeMessage,
sendObjectiveMessage sendObjectiveMessage
} from './api/sessionsClient' } from './api/sessionsClient'
import type { VoiceTurnResult } from '../shared/voice' import type { VoiceTurnResult } from '../shared/voice'
import type { AuthStatus, LoginResult } from '../shared/auth' import type { AuthStatus, LoginResult } from '../shared/auth'
import type { import type {
ObjectiveMessageResponse, ObjectiveMessageResponse,
RouteMessageResponse,
SessionObjectiveResponse, SessionObjectiveResponse,
SessionResponse, SessionResponse,
SessionStatus SessionStatus
@@ -265,6 +267,28 @@ 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)
// "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( ipcMain.handle(
'sessions:confirm-objective', 'sessions:confirm-objective',
async (_event, id: unknown): Promise<SessionObjectiveResponse> => { async (_event, id: unknown): Promise<SessionObjectiveResponse> => {
+2
View File
@@ -3,6 +3,7 @@ import type { VoiceTurnResult } from '../shared/voice'
import type { AuthStatus, LoginResult } from '../shared/auth' import type { AuthStatus, LoginResult } from '../shared/auth'
import type { import type {
ObjectiveMessageResponse, ObjectiveMessageResponse,
RouteMessageResponse,
SessionObjectiveResponse, SessionObjectiveResponse,
SessionResponse, SessionResponse,
SessionStatus SessionStatus
@@ -13,6 +14,7 @@ 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 {
+4 -1
View File
@@ -4,6 +4,7 @@ import type { VoiceTurnResult } from '../shared/voice'
import type { AuthStatus, LoginResult } from '../shared/auth' import type { AuthStatus, LoginResult } from '../shared/auth'
import type { import type {
ObjectiveMessageResponse, ObjectiveMessageResponse,
RouteMessageResponse,
SessionObjectiveResponse, SessionObjectiveResponse,
SessionResponse, SessionResponse,
SessionStatus SessionStatus
@@ -76,7 +77,9 @@ 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)
} }
} }
@@ -54,17 +54,19 @@ export const useSessionStore = create<SessionState>((set, get) => ({
})) }))
try { try {
let { sessionId } = get() // Point d'entree unique (docs/Max_System_Prompt.md, routeur d'intention) : ne cree une
if (sessionId === null) { // session que si le backend detecte reellement une intention d'apprendre. Un message de
const session = await window.api.sessions.create() // simple conversation ("salut ça va ?") ne demarre jamais de formation.
sessionId = session.id const result = await window.api.sessions.routeMessage(text)
set({ sessionId, status: session.status })
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) => ({ set((state) => ({
messages: pushMessage(state.messages, 'max', result.reply), messages: pushMessage(state.messages, 'max', result.reply),
objectiveReady: result.ready, objectiveReady: result.ready ?? false,
objectiveDraft: result.draft ?? state.objectiveDraft, objectiveDraft: result.draft ?? state.objectiveDraft,
loading: false loading: false
})) }))
+11
View File
@@ -37,3 +37,14 @@ export interface ObjectiveMessageResponse {
ready: boolean ready: boolean
draft?: ObjectiveDraft 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
}
@@ -3,16 +3,15 @@ import { render, screen, fireEvent, waitFor } 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 create = vi.fn()
const get = vi.fn() const get = vi.fn()
const sendObjectiveMessage = vi.fn() const routeMessage = 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: { create, get, sendObjectiveMessage, confirmObjective }, sessions: { get, routeMessage, confirmObjective },
notifySessionEnded notifySessionEnded
} }
useSessionStore.getState().restart() useSessionStore.getState().restart()
@@ -26,8 +25,13 @@ describe('<ChatPanel />', () => {
}) })
it('should send the first message, creating a session, and render the conversation', async () => { it('should send the first message, creating a session, and render the conversation', async () => {
create.mockResolvedValueOnce({ id: 1, status: 'objective_discovery' }) routeMessage.mockResolvedValueOnce({
sendObjectiveMessage.mockResolvedValueOnce({ reply: 'Quel est ton sujet ?', ready: false }) type: 'learn',
sessionId: 1,
reply: 'Quel est ton sujet ?',
ready: false
})
get.mockResolvedValueOnce({ id: 1, status: 'objective_discovery' })
render(<ChatPanel />) render(<ChatPanel />)
fireEvent.change(screen.getByLabelText('Message'), { target: { value: 'Je veux apprendre' } }) fireEvent.change(screen.getByLabelText('Message'), { target: { value: 'Je veux apprendre' } })
@@ -38,12 +42,14 @@ describe('<ChatPanel />', () => {
}) })
it('should show the ObjectiveValidationCard instead of the input bar once the agent is ready', async () => { it('should show the ObjectiveValidationCard instead of the input bar once the agent is ready', async () => {
create.mockResolvedValueOnce({ id: 1, status: 'objective_discovery' }) routeMessage.mockResolvedValueOnce({
sendObjectiveMessage.mockResolvedValueOnce({ type: 'learn',
sessionId: 1,
reply: 'Voici le recap', reply: 'Voici le recap',
ready: true, ready: true,
draft: { subject: 's', professionalGoal: 'g', duration: '1 semaine' } draft: { subject: 's', professionalGoal: 'g', duration: '1 semaine' }
}) })
get.mockResolvedValueOnce({ id: 1, status: 'objective_discovery' })
render(<ChatPanel />) render(<ChatPanel />)
fireEvent.change(screen.getByLabelText('Message'), { target: { value: 'message' } }) fireEvent.change(screen.getByLabelText('Message'), { target: { value: 'message' } })
@@ -54,7 +60,7 @@ describe('<ChatPanel />', () => {
}) })
it('should show the store error message when a call fails', async () => { 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(<ChatPanel />) render(<ChatPanel />)
fireEvent.change(screen.getByLabelText('Message'), { target: { value: 'message' } }) fireEvent.change(screen.getByLabelText('Message'), { target: { value: 'message' } })
@@ -1,56 +1,89 @@
import { describe, it, expect, vi, beforeEach } from 'vitest' 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 create = vi.fn()
const get = vi.fn() const get = vi.fn()
const sendObjectiveMessage = vi.fn() const routeMessage = 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: { create, get, sendObjectiveMessage, confirmObjective }, sessions: { get, routeMessage, confirmObjective },
notifySessionEnded notifySessionEnded
} }
useSessionStore.getState().restart() useSessionStore.getState().restart()
}) })
describe('useSessionStore', () => { describe('useSessionStore', () => {
it('should create a session on the first message and send it there', async () => { it('should not create a session when the backend classifies the message as chat', async () => {
create.mockResolvedValueOnce({ id: 1, status: 'objective_discovery' }) routeMessage.mockResolvedValueOnce({ type: 'chat', reply: 'Salut, comment puis-je aider ?' })
sendObjectiveMessage.mockResolvedValueOnce({ reply: 'Quel est ton sujet ?', ready: false })
await useSessionStore.getState().sendMessage('Je veux apprendre la facturation') await useSessionStore.getState().sendMessage('Salut ça va ?')
expect(create).toHaveBeenCalledOnce() expect(routeMessage).toHaveBeenCalledWith('Salut ça va ?')
expect(sendObjectiveMessage).toHaveBeenCalledWith(1, 'Je veux apprendre la facturation') expect(get).not.toHaveBeenCalled()
const state = useSessionStore.getState() const state = useSessionStore.getState()
expect(state.sessionId).toBe(1) expect(state.sessionId).toBeNull()
expect(state.status).toBe('objective_discovery')
expect(state.messages.map((m) => m.role)).toEqual(['user', 'max']) expect(state.messages.map((m) => m.role)).toEqual(['user', 'max'])
expect(state.loading).toBe(false) expect(state.loading).toBe(false)
}) })
it('should reuse the existing session id on subsequent messages', async () => { it('should set the session id and fetch the fresh status when the backend starts a training session', async () => {
create.mockResolvedValueOnce({ id: 1, status: 'objective_discovery' }) routeMessage.mockResolvedValueOnce({
sendObjectiveMessage.mockResolvedValue({ reply: 'ok', ready: false }) 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') 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') await useSessionStore.getState().sendMessage('second message')
expect(create).toHaveBeenCalledOnce() expect(routeMessage).toHaveBeenCalledTimes(2)
expect(sendObjectiveMessage).toHaveBeenCalledTimes(2) expect(useSessionStore.getState().sessionId).toBe(1)
}) })
it('should store the draft and ready flag once the agent is ready to confirm', async () => { 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 = { const draft = {
subject: 'Facturation freelance', subject: 'Facturation freelance',
professionalGoal: 'Facturer sans erreur', professionalGoal: 'Facturer sans erreur',
duration: '2 semaines' 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') 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 () => { 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') await useSessionStore.getState().sendMessage('message')
@@ -70,19 +103,18 @@ describe('useSessionStore', () => {
}) })
it('should confirm the objective and refresh the session status', async () => { it('should confirm the objective and refresh the session status', async () => {
create.mockResolvedValueOnce({ id: 1, status: 'objective_discovery' }) routeMessage.mockResolvedValueOnce({
sendObjectiveMessage.mockResolvedValueOnce({ type: 'learn',
sessionId: 1,
reply: 'Recap', reply: 'Recap',
ready: true, ready: true,
draft: { subject: 's', professionalGoal: 'g', duration: '1 semaine' } draft: { subject: 's', professionalGoal: 'g', duration: '1 semaine' }
}) })
get.mockResolvedValueOnce({ id: 1, status: 'objective_discovery' })
await useSessionStore.getState().sendMessage('message') await useSessionStore.getState().sendMessage('message')
confirmObjective.mockResolvedValueOnce({}) confirmObjective.mockResolvedValueOnce({})
get.mockResolvedValueOnce({ id: 1, status: 'objective_validated' }) get.mockResolvedValueOnce({ id: 1, status: 'objective_validated' })
;(window as unknown as { api: Record<string, unknown> }).api = {
sessions: { create, get, sendObjectiveMessage, confirmObjective }
}
await useSessionStore await useSessionStore
.getState() .getState()
@@ -104,8 +136,13 @@ describe('useSessionStore', () => {
}) })
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', async () => {
create.mockResolvedValueOnce({ id: 1, status: 'objective_discovery' }) routeMessage.mockResolvedValueOnce({
sendObjectiveMessage.mockResolvedValueOnce({ reply: 'ok', ready: false }) type: 'learn',
sessionId: 1,
reply: 'ok',
ready: false
})
get.mockResolvedValueOnce({ id: 1, status: 'objective_discovery' })
await useSessionStore.getState().sendMessage('message') await useSessionStore.getState().sendMessage('message')
notifySessionEnded.mockClear() notifySessionEnded.mockClear()
+22 -2
View File
@@ -3,8 +3,14 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
const getAccessToken = vi.fn<() => string | null>(() => 'jwt-token') const getAccessToken = vi.fn<() => string | null>(() => 'jwt-token')
vi.mock('../../src/main/auth/session', () => ({ getAccessToken })) vi.mock('../../src/main/auth/session', () => ({ getAccessToken }))
const { createSession, getSession, sendObjectiveMessage, confirmObjective, MaxApiError } = const {
await import('../../src/main/api/sessionsClient') createSession,
getSession,
sendObjectiveMessage,
confirmObjective,
routeMessage,
MaxApiError
} = await import('../../src/main/api/sessionsClient')
function jsonResponse(body: unknown, ok = true, status = ok ? 200 : 400): Response { function jsonResponse(body: unknown, ok = true, status = ok ? 200 : 400): Response {
return { ok, status, json: () => Promise.resolve(body) } as Response return { ok, status, json: () => Promise.resolve(body) } as Response
@@ -84,6 +90,20 @@ describe('sessionsClient', () => {
expect(result.sessionId).toBe(1) 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 () => { it('should throw MaxApiError with the server message on a non-ok response', async () => {
global.fetch = vi.fn().mockResolvedValueOnce(jsonResponse({ message: 'Conflit' }, false, 409)) global.fetch = vi.fn().mockResolvedValueOnce(jsonResponse({ message: 'Conflit' }, false, 409))