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:
co-authored by
Claude Sonnet 5
parent
ce25d3f290
commit
7179743d4e
@@ -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<SessionObjectiveResponse> {
|
||||
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 })
|
||||
})
|
||||
}
|
||||
|
||||
@@ -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<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(
|
||||
'sessions:confirm-objective',
|
||||
async (_event, id: unknown): Promise<SessionObjectiveResponse> => {
|
||||
|
||||
Vendored
+2
@@ -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<SessionResponse>
|
||||
sendObjectiveMessage: (id: number, message: string) => Promise<ObjectiveMessageResponse>
|
||||
confirmObjective: (id: number) => Promise<SessionObjectiveResponse>
|
||||
routeMessage: (message: string) => Promise<RouteMessageResponse>
|
||||
}
|
||||
|
||||
export interface ForgeAvatarApi {
|
||||
|
||||
@@ -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<ObjectiveMessageResponse> =>
|
||||
ipcRenderer.invoke('sessions:send-objective-message', id, message),
|
||||
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 {
|
||||
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
|
||||
}))
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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<string, unknown> }).api = {
|
||||
sessions: { create, get, sendObjectiveMessage, confirmObjective },
|
||||
sessions: { get, routeMessage, confirmObjective },
|
||||
notifySessionEnded
|
||||
}
|
||||
useSessionStore.getState().restart()
|
||||
@@ -26,8 +25,13 @@ describe('<ChatPanel />', () => {
|
||||
})
|
||||
|
||||
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(<ChatPanel />)
|
||||
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 () => {
|
||||
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(<ChatPanel />)
|
||||
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 () => {
|
||||
create.mockRejectedValueOnce(new Error('Max API injoignable'))
|
||||
routeMessage.mockRejectedValueOnce(new Error('Max API injoignable'))
|
||||
|
||||
render(<ChatPanel />)
|
||||
fireEvent.change(screen.getByLabelText('Message'), { target: { value: 'message' } })
|
||||
|
||||
@@ -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<string, unknown> }).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<string, unknown> }).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()
|
||||
|
||||
@@ -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))
|
||||
|
||||
|
||||
Reference in New Issue
Block a user