Develop #2

Open
w-vandal wants to merge 48 commits from develop into main
2 changed files with 229 additions and 0 deletions
Showing only changes of commit 050aad9469 - Show all commits
@@ -0,0 +1,114 @@
import { create } from 'zustand'
import type { ObjectiveDraft, SessionStatus } from '../../../shared/session'
export interface ChatMessage {
id: string
role: 'max' | 'user'
content: string
timestamp: Date
}
interface SessionState {
sessionId: number | null
status: SessionStatus | null
messages: ChatMessage[]
objectiveDraft: ObjectiveDraft | null
objectiveReady: boolean
objectiveConfirmed: boolean
loading: boolean
error: string | null
sendMessage: (text: string) => Promise<void>
confirmObjective: (objective: ObjectiveDraft) => Promise<void>
restart: () => void
}
function pushMessage(
messages: ChatMessage[],
role: ChatMessage['role'],
content: string
): ChatMessage[] {
return [...messages, { id: crypto.randomUUID(), role, content, timestamp: new Date() }]
}
/**
* Seule source de verite pour l'etat du pipeline cote renderer. Le statut de session n'est JAMAIS
* calcule ici : il vient toujours de ce que l'API a reellement renvoye (voir
* docs/Max_Composants_Frontend.md, regle de PipelineStepper).
*/
export const useSessionStore = create<SessionState>((set, get) => ({
sessionId: null,
status: null,
messages: [],
objectiveDraft: null,
objectiveReady: false,
objectiveConfirmed: false,
loading: false,
error: null,
sendMessage: async (text: string): Promise<void> => {
set((state) => ({
messages: pushMessage(state.messages, 'user', text),
loading: true,
error: null
}))
try {
let { sessionId } = get()
if (sessionId === null) {
const session = await window.api.sessions.create()
sessionId = session.id
set({ 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,
objectiveDraft: result.draft ?? state.objectiveDraft,
loading: false
}))
} catch (error) {
set({
loading: false,
error: error instanceof Error ? error.message : 'Erreur inattendue'
})
}
},
confirmObjective: async (objective: ObjectiveDraft): Promise<void> => {
const { sessionId } = get()
if (sessionId === null) {
set({ error: 'Aucune session en cours' })
return
}
set({ loading: true, error: null, objectiveDraft: objective })
try {
await window.api.sessions.confirmObjective(sessionId)
const session = await window.api.sessions.get(sessionId)
set({
status: session.status,
objectiveConfirmed: true,
loading: false
})
} catch (error) {
set({
loading: false,
error: error instanceof Error ? error.message : 'Erreur inattendue'
})
}
},
restart: (): void => {
set({
sessionId: null,
status: null,
messages: [],
objectiveDraft: null,
objectiveReady: false,
objectiveConfirmed: false,
loading: false,
error: null
})
}
}))
@@ -0,0 +1,115 @@
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 confirmObjective = vi.fn()
beforeEach(() => {
vi.clearAllMocks()
;(window as unknown as { api: Record<string, unknown> }).api = {
sessions: { create, get, sendObjectiveMessage, confirmObjective }
}
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 })
await useSessionStore.getState().sendMessage('Je veux apprendre la facturation')
expect(create).toHaveBeenCalledOnce()
expect(sendObjectiveMessage).toHaveBeenCalledWith(1, 'Je veux apprendre la facturation')
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'])
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 })
await useSessionStore.getState().sendMessage('premier message')
await useSessionStore.getState().sendMessage('second message')
expect(create).toHaveBeenCalledOnce()
expect(sendObjectiveMessage).toHaveBeenCalledTimes(2)
})
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 })
await useSessionStore.getState().sendMessage('message')
const state = useSessionStore.getState()
expect(state.objectiveReady).toBe(true)
expect(state.objectiveDraft).toEqual(draft)
})
it('should set an error and stop loading when sending a message fails', async () => {
create.mockRejectedValueOnce(new Error('Max API injoignable'))
await useSessionStore.getState().sendMessage('message')
const state = useSessionStore.getState()
expect(state.error).toBe('Max API injoignable')
expect(state.loading).toBe(false)
})
it('should confirm the objective and refresh the session status', async () => {
create.mockResolvedValueOnce({ id: 1, status: 'objective_discovery' })
sendObjectiveMessage.mockResolvedValueOnce({
reply: 'Recap',
ready: true,
draft: { subject: 's', professionalGoal: 'g', duration: '1 semaine' }
})
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()
.confirmObjective({ subject: 's', professionalGoal: 'g', duration: '1 semaine' })
expect(confirmObjective).toHaveBeenCalledWith(1)
const state = useSessionStore.getState()
expect(state.objectiveConfirmed).toBe(true)
expect(state.status).toBe('objective_validated')
})
it('should error out when confirming without an active session', async () => {
await useSessionStore
.getState()
.confirmObjective({ subject: 's', professionalGoal: 'g', duration: '1 semaine' })
expect(confirmObjective).not.toHaveBeenCalled()
expect(useSessionStore.getState().error).toBe('Aucune session en cours')
})
it('should reset all state on restart', async () => {
create.mockResolvedValueOnce({ id: 1, status: 'objective_discovery' })
sendObjectiveMessage.mockResolvedValueOnce({ reply: 'ok', ready: false })
await useSessionStore.getState().sendMessage('message')
useSessionStore.getState().restart()
const state = useSessionStore.getState()
expect(state.sessionId).toBeNull()
expect(state.messages).toEqual([])
})
})