Files
ForgeBase/Max API/src/sessions/sessions.service.spec.ts
T
williamandClaude Sonnet 5 755bc07d18 feat(sessions): wire Agents 2-4 into the pipeline orchestration
confirmObjective() now chains Agent 2 (mapping) then starts Agent 3
(level) synchronously after Agent 1 confirms - by the time the HTTP
response returns, session.status is already "level_assessment" and
the response carries Agent 3's first question in a new "nextPrompt"
field, to be spoken aloud (never displayed as text).

New endpoints: POST /sessions/:id/level/confirm (runs Agent 4, advances
to "planning") and POST /sessions/:id/level/dispute. routeIncomingMessage
dispatches "level_assessment" sessions to LevelAgent.converse(), same
single entry point used for text and voice.

RouteMessageResponseDto gains levelDone/levelProfile fields: every
response field is a structured, typed signal the frontend's main
process can branch on to decide whether to open a result window - never
an instruction embedded in the LLM's reply text.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-11-02 09:48:10 +01:00

394 lines
12 KiB
TypeScript

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 { LevelAgent } from './agents/level.agent';
import { MappingAgent } from './agents/mapping.agent';
import { ObjectiveAgent } from './agents/objective.agent';
import { ResearchAgent } from './agents/research.agent';
import { SessionsService } from './sessions.service';
describe('SessionsService', () => {
let service: SessionsService;
const prisma = {
session: {
create: jest.fn(),
findUnique: jest.fn(),
findFirst: jest.fn(),
update: jest.fn(),
},
sessionConceptMap: { findUniqueOrThrow: jest.fn() },
};
const objectiveAgent = { converse: jest.fn(), confirm: jest.fn() };
const mappingAgent = { runForSession: jest.fn() };
const levelAgent = {
start: jest.fn(),
converse: jest.fn(),
confirm: jest.fn(),
dispute: jest.fn(),
};
const researchAgent = { runForSession: jest.fn() };
const intentRouter = { analyze: jest.fn() };
const llm = { chat: jest.fn() };
beforeEach(async () => {
jest.clearAllMocks();
const module: TestingModule = await Test.createTestingModule({
providers: [
SessionsService,
{ provide: PrismaService, useValue: prisma },
{ provide: ObjectiveAgent, useValue: objectiveAgent },
{ provide: MappingAgent, useValue: mappingAgent },
{ provide: LevelAgent, useValue: levelAgent },
{ provide: ResearchAgent, useValue: researchAgent },
{ provide: IntentRouterAgent, useValue: intentRouter },
{ provide: OpenRouterService, useValue: llm },
],
}).compile();
service = module.get(SessionsService);
});
describe('create()', () => {
it('should create a session in objective_discovery status', async () => {
prisma.session.create.mockResolvedValueOnce({
id: 1,
userId: 7,
status: 'objective_discovery',
createdAt: new Date('2026-01-01'),
updatedAt: new Date('2026-01-01'),
});
const result = await service.create(7);
expect(prisma.session.create).toHaveBeenCalledWith({
data: { userId: 7 },
});
expect(result.status).toBe('objective_discovery');
expect(result.objective).toBeUndefined();
});
});
describe('findOne()', () => {
it('should throw NotFoundException when the session does not belong to the user', async () => {
prisma.session.findUnique.mockResolvedValueOnce({
id: 1,
userId: 2,
objective: null,
});
await expect(service.findOne(1, 99)).rejects.toThrow(NotFoundException);
});
it('should throw NotFoundException when the session does not exist', async () => {
prisma.session.findUnique.mockResolvedValueOnce(null);
await expect(service.findOne(1, 99)).rejects.toThrow(NotFoundException);
});
});
describe('sendObjectiveMessage()', () => {
it('should delegate to the objective agent when the session is still in discovery', async () => {
prisma.session.findUnique.mockResolvedValueOnce({
id: 1,
userId: 7,
status: 'objective_discovery',
objective: null,
});
objectiveAgent.converse.mockResolvedValueOnce({
reply: 'Quel est ton sujet ?',
ready: false,
});
const result = await service.sendObjectiveMessage(
1,
7,
'Je veux apprendre',
);
expect(objectiveAgent.converse).toHaveBeenCalledWith(
1,
7,
'Je veux apprendre',
);
expect(result.ready).toBe(false);
});
it('should reject when the objective is already validated for this session', async () => {
prisma.session.findUnique.mockResolvedValueOnce({
id: 1,
userId: 7,
status: 'objective_validated',
objective: { id: 1 },
});
await expect(
service.sendObjectiveMessage(1, 7, 'Un message'),
).rejects.toThrow(ConflictException);
expect(objectiveAgent.converse).not.toHaveBeenCalled();
});
});
describe('confirmObjective()', () => {
it('should confirm the objective, then chain Agent 2 (mapping) and start Agent 3 (level), ending with status level_assessment', async () => {
prisma.session.findUnique.mockResolvedValueOnce({
id: 1,
userId: 7,
status: 'objective_discovery',
objective: null,
});
objectiveAgent.confirm.mockResolvedValueOnce({
id: 5,
sessionId: 1,
subject: 'Facturation freelance',
professionalGoal: 'Facturer sans erreur',
duration: '2 semaines',
validatedAt: new Date('2026-01-02'),
});
prisma.sessionConceptMap.findUniqueOrThrow.mockResolvedValueOnce({
concepts: [{ name: 'Facturation' }, { name: 'TVA' }],
});
levelAgent.start.mockResolvedValueOnce({
reply:
'Si un client te demande une facture avec TVA, comment fais-tu ?',
done: false,
});
const result = await service.confirmObjective(1, 7);
expect(objectiveAgent.confirm).toHaveBeenCalledWith(1, 7);
expect(mappingAgent.runForSession).toHaveBeenCalledWith(
1,
7,
'Facturation freelance pour Facturer sans erreur, en 2 semaines',
);
expect(levelAgent.start).toHaveBeenCalledWith(
1,
7,
'Facturation freelance pour Facturer sans erreur, en 2 semaines',
'Facturation, TVA',
);
expect(prisma.session.update).toHaveBeenCalledWith({
where: { id: 1 },
data: { status: 'mapping' },
});
expect(prisma.session.update).toHaveBeenCalledWith({
where: { id: 1 },
data: { status: 'level_assessment' },
});
expect(result.id).toBe(5);
expect(result.validatedAt).toEqual(new Date('2026-01-02'));
expect(result.nextPrompt).toBe(
'Si un client te demande une facture avec TVA, comment fais-tu ?',
);
});
});
describe('confirmLevel()', () => {
it('should confirm the level profile, run Agent 4, and advance status to planning', async () => {
prisma.session.findUnique.mockResolvedValueOnce({
id: 1,
userId: 7,
status: 'level_assessment',
objective: null,
});
await service.confirmLevel(1, 7);
expect(levelAgent.confirm).toHaveBeenCalledWith(1);
expect(researchAgent.runForSession).toHaveBeenCalledWith(1, 7);
expect(prisma.session.update).toHaveBeenCalledWith({
where: { id: 1 },
data: { status: 'planning' },
});
});
it('should reject when the session is not at the level_assessment stage', async () => {
prisma.session.findUnique.mockResolvedValueOnce({
id: 1,
userId: 7,
status: 'objective_discovery',
objective: null,
});
await expect(service.confirmLevel(1, 7)).rejects.toThrow(
ConflictException,
);
expect(levelAgent.confirm).not.toHaveBeenCalled();
});
});
describe('disputeLevel()', () => {
it('should forward the dispute to the level agent and map the updated profile', async () => {
prisma.session.findUnique.mockResolvedValueOnce({
id: 1,
userId: 7,
status: 'level_assessment',
objective: null,
});
levelAgent.dispute.mockResolvedValueOnce({
id: 2,
sessionId: 1,
masteredConcepts: ['TVA'],
gapConcepts: [],
unknownConcepts: [],
overallLevel: 'intermediate',
completedAt: new Date('2026-01-03'),
});
const result = await service.disputeLevel(1, 7, {
concept: 'TVA',
answer: "J'applique le taux reduit pour ce type de prestation.",
});
expect(levelAgent.dispute).toHaveBeenCalledWith(
1,
7,
'TVA',
"J'applique le taux reduit pour ce type de prestation.",
);
expect(result.mastered).toEqual(['TVA']);
expect(result.overallLevel).toBe('intermediate');
});
it('should reject when the session is not at the level_assessment stage', async () => {
prisma.session.findUnique.mockResolvedValueOnce({
id: 1,
userId: 7,
status: 'planning',
objective: null,
});
await expect(
service.disputeLevel(1, 7, { concept: 'TVA', answer: 'reponse' }),
).rejects.toThrow(ConflictException);
expect(levelAgent.dispute).not.toHaveBeenCalled();
});
});
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 route to the level agent when an active level_assessment session exists', async () => {
prisma.session.findFirst.mockResolvedValueOnce({
id: 1,
userId: 7,
status: 'level_assessment',
});
levelAgent.converse.mockResolvedValueOnce({
reply: 'Et pour une facture en devise etrangere ?',
done: false,
});
const result = await service.routeIncomingMessage(7, 'Je dirais ...');
expect(levelAgent.converse).toHaveBeenCalledWith(1, 7, 'Je dirais ...');
expect(objectiveAgent.converse).not.toHaveBeenCalled();
expect(result).toEqual({
type: 'learn',
sessionId: 1,
reply: 'Et pour une facture en devise etrangere ?',
levelDone: false,
levelProfile: undefined,
});
});
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: 'planning',
});
await expect(
service.routeIncomingMessage(7, 'un message'),
).rejects.toThrow(ConflictException);
expect(objectiveAgent.converse).not.toHaveBeenCalled();
expect(levelAgent.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,
});
});
});
});