From ce25d3f29035c82dccd08bab9062ba11a0510ba8 Mon Sep 17 00:00:00 2001 From: william Date: Sun, 1 Nov 2026 08:57:29 +0100 Subject: [PATCH] feat(sessions): add unified /sessions/messages entry point Add SessionsService#routeIncomingMessage: if the user has an active non-completed session, route to its agent by status (only objective_discovery is implemented so far - any other status rejects with a clear 409 rather than failing silently); otherwise run the intent router first and only create a session + start Agent 1 when it detects a learning intent, replying as plain conversational Max (PERSONALITY_PROMPT only, no session) otherwise. Exposed as POST /sessions/messages (JWT-protected), the new single entry point the chat window should call instead of unconditionally creating a session on every message. Co-Authored-By: Claude Sonnet 5 --- .../dto/route-message-response.dto.ts | 26 +++++ .../src/sessions/sessions.controller.spec.ts | 13 +++ Max API/src/sessions/sessions.controller.ts | 21 ++++ Max API/src/sessions/sessions.module.ts | 3 +- Max API/src/sessions/sessions.service.spec.ts | 109 +++++++++++++++++- Max API/src/sessions/sessions.service.ts | 67 +++++++++++ 6 files changed, 237 insertions(+), 2 deletions(-) create mode 100644 Max API/src/sessions/dto/route-message-response.dto.ts diff --git a/Max API/src/sessions/dto/route-message-response.dto.ts b/Max API/src/sessions/dto/route-message-response.dto.ts new file mode 100644 index 0000000..c350702 --- /dev/null +++ b/Max API/src/sessions/dto/route-message-response.dto.ts @@ -0,0 +1,26 @@ +import { ApiProperty } from '@nestjs/swagger'; +import { ObjectiveDraftDto } from './objective-message-response.dto'; + +export class RouteMessageResponseDto { + @ApiProperty({ + enum: ['chat', 'learn'], + description: + '"chat" : reponse conversationnelle, aucune session creee. "learn" : une session de formation est active (nouvelle ou existante).', + }) + type!: 'chat' | 'learn'; + + @ApiProperty({ description: 'Reponse de Max a afficher dans le chat.' }) + reply!: string; + + @ApiProperty({ + required: false, + description: 'Present uniquement si type="learn".', + }) + sessionId?: number; + + @ApiProperty({ required: false }) + ready?: boolean; + + @ApiProperty({ type: ObjectiveDraftDto, required: false }) + draft?: ObjectiveDraftDto; +} diff --git a/Max API/src/sessions/sessions.controller.spec.ts b/Max API/src/sessions/sessions.controller.spec.ts index 8eeb88a..0ca08b9 100644 --- a/Max API/src/sessions/sessions.controller.spec.ts +++ b/Max API/src/sessions/sessions.controller.spec.ts @@ -11,6 +11,7 @@ describe('SessionsController', () => { findOne: jest.fn(), sendObjectiveMessage: jest.fn(), confirmObjective: jest.fn(), + routeIncomingMessage: jest.fn(), }; const request = { user: { sub: 7, email: 'w@example.com' }, @@ -66,4 +67,16 @@ describe('SessionsController', () => { await controller.confirmObjective(1, request); expect(sessionsService.confirmObjective).toHaveBeenCalledWith(1, 7); }); + + it('should route an incoming message for the authenticated user', async () => { + sessionsService.routeIncomingMessage.mockResolvedValueOnce({ + type: 'chat', + reply: 'ok', + }); + await controller.routeMessage({ message: 'Salut' }, request); + expect(sessionsService.routeIncomingMessage).toHaveBeenCalledWith( + 7, + 'Salut', + ); + }); }); diff --git a/Max API/src/sessions/sessions.controller.ts b/Max API/src/sessions/sessions.controller.ts index 9c3a2a8..4474535 100644 --- a/Max API/src/sessions/sessions.controller.ts +++ b/Max API/src/sessions/sessions.controller.ts @@ -19,6 +19,7 @@ import { import type { AuthenticatedRequest } from '../auth/jwt-auth.guard'; import { JwtAuthGuard } from '../auth/jwt-auth.guard'; import { ObjectiveMessageResponseDto } from './dto/objective-message-response.dto'; +import { RouteMessageResponseDto } from './dto/route-message-response.dto'; import { SendObjectiveMessageDto } from './dto/send-objective-message.dto'; import { SessionObjectiveResponseDto } from './dto/session-objective-response.dto'; import { SessionResponseDto } from './dto/session-response.dto'; @@ -38,6 +39,26 @@ export class SessionsController { return this.sessionsService.create(request.user.sub); } + @Post('messages') + @ApiOperation({ + summary: + "Point d'entree unique du chat : route vers la session active ou demarre une formation selon l'intention detectee", + }) + @ApiResponse({ status: HttpStatus.CREATED, type: RouteMessageResponseDto }) + @ApiResponse({ + status: HttpStatus.CONFLICT, + description: 'Etape du pipeline pas encore implementee', + }) + routeMessage( + @Body() dto: SendObjectiveMessageDto, + @Req() request: AuthenticatedRequest, + ): Promise { + return this.sessionsService.routeIncomingMessage( + request.user.sub, + dto.message, + ); + } + @Get(':id') @ApiOperation({ summary: "Recuperer l'etat d'une session" }) @ApiResponse({ status: HttpStatus.OK, type: SessionResponseDto }) diff --git a/Max API/src/sessions/sessions.module.ts b/Max API/src/sessions/sessions.module.ts index 39bc069..127f808 100644 --- a/Max API/src/sessions/sessions.module.ts +++ b/Max API/src/sessions/sessions.module.ts @@ -2,6 +2,7 @@ import { Module } from '@nestjs/common'; import { AuthModule } from '../auth/auth.module'; import { LlmModule } from '../llm/llm.module'; import { PrismaModule } from '../prisma/prisma.module'; +import { IntentRouterAgent } from './agents/intent-router.agent'; import { ObjectiveAgent } from './agents/objective.agent'; import { SessionsController } from './sessions.controller'; import { SessionsService } from './sessions.service'; @@ -9,7 +10,7 @@ import { SessionsService } from './sessions.service'; @Module({ imports: [PrismaModule, LlmModule, AuthModule], controllers: [SessionsController], - providers: [SessionsService, ObjectiveAgent], + providers: [SessionsService, ObjectiveAgent, IntentRouterAgent], exports: [SessionsService], }) export class SessionsModule {} diff --git a/Max API/src/sessions/sessions.service.spec.ts b/Max API/src/sessions/sessions.service.spec.ts index ada6262..4110866 100644 --- a/Max API/src/sessions/sessions.service.spec.ts +++ b/Max API/src/sessions/sessions.service.spec.ts @@ -1,15 +1,19 @@ import { ConflictException, NotFoundException } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; +import { OpenRouterService } from '../llm/openrouter.service'; import { PrismaService } from '../prisma/prisma.service'; +import { IntentRouterAgent } from './agents/intent-router.agent'; import { ObjectiveAgent } from './agents/objective.agent'; import { SessionsService } from './sessions.service'; describe('SessionsService', () => { let service: SessionsService; const prisma = { - session: { create: jest.fn(), findUnique: jest.fn() }, + session: { create: jest.fn(), findUnique: jest.fn(), findFirst: jest.fn() }, }; const objectiveAgent = { converse: jest.fn(), confirm: jest.fn() }; + const intentRouter = { analyze: jest.fn() }; + const llm = { chat: jest.fn() }; beforeEach(async () => { jest.clearAllMocks(); @@ -18,6 +22,8 @@ describe('SessionsService', () => { SessionsService, { provide: PrismaService, useValue: prisma }, { provide: ObjectiveAgent, useValue: objectiveAgent }, + { provide: IntentRouterAgent, useValue: intentRouter }, + { provide: OpenRouterService, useValue: llm }, ], }).compile(); @@ -125,4 +131,105 @@ describe('SessionsService', () => { expect(result.validatedAt).toEqual(new Date('2026-01-02')); }); }); + + describe('routeIncomingMessage()', () => { + it('should route to the objective agent when an active objective_discovery session exists', async () => { + const activeSession = { + id: 1, + userId: 7, + status: 'objective_discovery', + objective: null, + }; + prisma.session.findFirst.mockResolvedValueOnce(activeSession); + prisma.session.findUnique.mockResolvedValueOnce(activeSession); + objectiveAgent.converse.mockResolvedValueOnce({ + reply: 'Quel est ton sujet ?', + ready: false, + }); + + const result = await service.routeIncomingMessage(7, 'Je veux apprendre'); + + expect(objectiveAgent.converse).toHaveBeenCalledWith( + 1, + 7, + 'Je veux apprendre', + ); + expect(result).toEqual({ + type: 'learn', + sessionId: 1, + reply: 'Quel est ton sujet ?', + ready: false, + draft: undefined, + }); + expect(intentRouter.analyze).not.toHaveBeenCalled(); + }); + + it('should reject when the active session is in a status with no agent built yet', async () => { + prisma.session.findFirst.mockResolvedValueOnce({ + id: 1, + userId: 7, + status: 'mapping', + }); + + await expect( + service.routeIncomingMessage(7, 'un message'), + ).rejects.toThrow(ConflictException); + expect(objectiveAgent.converse).not.toHaveBeenCalled(); + }); + + it('should reply conversationally without creating a session when intent is chat', async () => { + prisma.session.findFirst.mockResolvedValueOnce(null); + intentRouter.analyze.mockResolvedValueOnce({ + intent: 'chat', + subject: null, + }); + llm.chat.mockResolvedValueOnce('Salut, comment puis-je aider ?'); + + const result = await service.routeIncomingMessage(7, 'Salut ça va ?'); + + expect(result).toEqual({ + type: 'chat', + reply: 'Salut, comment puis-je aider ?', + }); + expect(prisma.session.create).not.toHaveBeenCalled(); + }); + + it('should create a session and start Agent 1 when intent is learn', async () => { + prisma.session.findFirst.mockResolvedValueOnce(null); + intentRouter.analyze.mockResolvedValueOnce({ + intent: 'learn', + subject: 'React', + }); + prisma.session.create.mockResolvedValueOnce({ + id: 9, + userId: 7, + status: 'objective_discovery', + }); + objectiveAgent.converse.mockResolvedValueOnce({ + reply: 'Quel est ton objectif avec React ?', + ready: false, + }); + + const result = await service.routeIncomingMessage( + 7, + 'Apprends-moi React', + ); + + expect(prisma.session.create).toHaveBeenCalledWith({ + data: { userId: 7 }, + }); + expect(objectiveAgent.converse).toHaveBeenCalledWith( + 9, + 7, + 'Apprends-moi React', + ); + expect(result).toEqual({ + type: 'learn', + sessionId: 9, + reply: 'Quel est ton objectif avec React ?', + ready: false, + draft: undefined, + }); + }); + }); }); diff --git a/Max API/src/sessions/sessions.service.ts b/Max API/src/sessions/sessions.service.ts index 4705dd8..f497227 100644 --- a/Max API/src/sessions/sessions.service.ts +++ b/Max API/src/sessions/sessions.service.ts @@ -4,18 +4,26 @@ import { NotFoundException, } from '@nestjs/common'; import { Session, SessionObjective } from '@prisma/client'; +import { OpenRouterService } from '../llm/openrouter.service'; import { PrismaService } from '../prisma/prisma.service'; +import { IntentRouterAgent } from './agents/intent-router.agent'; import { ObjectiveAgent, ObjectiveTurnResult } from './agents/objective.agent'; +import { RouteMessageResponseDto } from './dto/route-message-response.dto'; +import { buildAgentPrompt, PERSONALITY_PROMPT } from './prompts/base.prompt'; import { SessionObjectiveResponseDto } from './dto/session-objective-response.dto'; import { SessionResponseDto } from './dto/session-response.dto'; type SessionWithObjective = Session & { objective: SessionObjective | null }; +const IMPLEMENTED_STATUSES = new Set(['objective_discovery']); + @Injectable() export class SessionsService { constructor( private readonly prisma: PrismaService, private readonly objectiveAgent: ObjectiveAgent, + private readonly intentRouter: IntentRouterAgent, + private readonly llm: OpenRouterService, ) {} async create(userId: number): Promise { @@ -55,6 +63,65 @@ export class SessionsService { }; } + /** + * Porte d'entree unique du chat (docs/Max_System_Prompt.md) : route vers l'agent de la session + * active si elle existe, sinon classifie le message (routeur d'intention) pour decider de + * demarrer une formation ou de repondre simplement en conversation. Le statut de session n'est + * jamais choisi par le LLM : seul le code decide ici de creer une session ou non. + */ + async routeIncomingMessage( + userId: number, + message: string, + ): Promise { + const activeSession = await this.prisma.session.findFirst({ + where: { userId, status: { not: 'completed' } }, + orderBy: { createdAt: 'desc' }, + }); + + if (activeSession) { + if (!IMPLEMENTED_STATUSES.has(activeSession.status)) { + throw new ConflictException( + "Cette etape du pipeline n'est pas encore implementee.", + ); + } + const result = await this.sendObjectiveMessage( + activeSession.id, + userId, + message, + ); + return { + type: 'learn', + sessionId: activeSession.id, + reply: result.reply, + ready: result.ready, + draft: result.draft, + }; + } + + const intent = await this.intentRouter.analyze(userId, message); + if (intent.intent === 'chat') { + const reply = await this.llm.chat(userId, [ + { role: 'system', content: buildAgentPrompt(PERSONALITY_PROMPT) }, + { role: 'user', content: message }, + ]); + return { type: 'chat', reply }; + } + + const session = await this.prisma.session.create({ data: { userId } }); + const result = await this.objectiveAgent.converse( + session.id, + userId, + message, + ); + return { + type: 'learn', + sessionId: session.id, + reply: result.reply, + ready: result.ready, + draft: result.draft, + }; + } + private async findOwnedSession( id: number, userId: number,