From 83043b58195bc11e64ed8c4de4b707f54448b32c Mon Sep 17 00:00:00 2001 From: william Date: Sat, 31 Oct 2026 19:27:11 +0100 Subject: [PATCH] chore(cleanup): remove assistant-exclusive skills Removes the meeting transcription/recording feature end-to-end (get_last_meeting_summary, meetingRecorder/meetingStore/summarize, the useMeetingRecorder renderer hook, and the related IPC/preload wiring) and the remember_info/forget_info long-term memory skills: all three were only ever reachable from the now-removed Assistant mode. adjust_mood and its mood store are unrelated (transversal) and are kept as-is. Co-Authored-By: Claude Sonnet 5 --- Max Avatar/src/main/ai/openrouter.ts | 16 +-- Max Avatar/src/main/index.ts | 9 -- .../src/main/meeting/meetingRecorder.ts | 67 --------- Max Avatar/src/main/meeting/meetingStore.ts | 33 ----- Max Avatar/src/main/meeting/summarize.ts | 58 -------- Max Avatar/src/main/memory/store.ts | 41 ------ Max Avatar/src/main/skills/index.ts | 3 +- .../skills/meeting/getLastMeetingSummary.ts | 15 -- Max Avatar/src/main/skills/meeting/index.ts | 4 - .../src/main/skills/memory/forgetInfo.ts | 33 ----- Max Avatar/src/main/skills/memory/index.ts | 6 +- .../src/main/skills/memory/rememberInfo.ts | 25 ---- Max Avatar/src/preload/index.d.ts | 3 - Max Avatar/src/preload/index.ts | 12 -- Max Avatar/src/renderer/src/App.tsx | 13 +- .../renderer/src/voice/useMeetingRecorder.ts | 128 ------------------ Max Avatar/tests/unit/components/App.test.tsx | 6 +- .../components/useMeetingRecorder.test.ts | 96 ------------- Max Avatar/tests/unit/meetingRecorder.test.ts | 84 ------------ Max Avatar/tests/unit/openrouter.test.ts | 3 +- Max Avatar/tests/unit/skills.memory.test.ts | 41 +----- ...ts.test.ts => skills.webDocuments.test.ts} | 18 +-- Max Avatar/tests/unit/summarize.test.ts | 48 ------- 23 files changed, 13 insertions(+), 749 deletions(-) delete mode 100644 Max Avatar/src/main/meeting/meetingRecorder.ts delete mode 100644 Max Avatar/src/main/meeting/meetingStore.ts delete mode 100644 Max Avatar/src/main/meeting/summarize.ts delete mode 100644 Max Avatar/src/main/skills/meeting/getLastMeetingSummary.ts delete mode 100644 Max Avatar/src/main/skills/meeting/index.ts delete mode 100644 Max Avatar/src/main/skills/memory/forgetInfo.ts delete mode 100644 Max Avatar/src/main/skills/memory/rememberInfo.ts delete mode 100644 Max Avatar/src/renderer/src/voice/useMeetingRecorder.ts delete mode 100644 Max Avatar/tests/unit/components/useMeetingRecorder.test.ts delete mode 100644 Max Avatar/tests/unit/meetingRecorder.test.ts rename Max Avatar/tests/unit/{skills.visionWebMeetingDocuments.test.ts => skills.webDocuments.test.ts} (84%) delete mode 100644 Max Avatar/tests/unit/summarize.test.ts diff --git a/Max Avatar/src/main/ai/openrouter.ts b/Max Avatar/src/main/ai/openrouter.ts index 3fe702e..b1fad6b 100644 --- a/Max Avatar/src/main/ai/openrouter.ts +++ b/Max Avatar/src/main/ai/openrouter.ts @@ -1,5 +1,5 @@ import { loadSkills } from '../skills' -import { getMemoriesText, getMood } from '../memory/store' +import { getMood } from '../memory/store' import { synthesizeSpeech } from './elevenlabs' import { sendToRenderer } from '../windowBridge' import { logger } from '../utils/logger' @@ -70,12 +70,8 @@ jamais qu'une action a reussi si l'outil a signale un probleme, et ne minimise p aucun outil ne peut t'aider et que tu n'es pas sur de ta reponse, dis-le honnetement plutot que d'inventer une information. -Tu as une memoire a long terme sur l'utilisateur : quand il partage une preference, une habitude ou un -fait personnel important, appelle remember_info pour t'en souvenir pour les conversations futures. -Si on te demande d'oublier quelque chose, appelle forget_info. Utilise naturellement ce que tu -sais deja sur lui sans le reciter mecaniquement. Tu as aussi une humeur qui evolue selon le ton de la -conversation : appelle adjust_mood quand l'echange est notablement agreable ou tendu (voir description -de l'outil).` +Tu as aussi une humeur qui evolue selon le ton de la conversation : appelle adjust_mood quand +l'echange est notablement agreable ou tendu (voir description de l'outil).` function describeMood(mood: number): string { if (mood >= 2) return "Tu es actuellement de tres bonne humeur, enjoue et plein d'energie." @@ -87,11 +83,7 @@ function describeMood(mood: number): string { function buildSystemPrompt(): string { const moodBlock = describeMood(getMood()) - const memories = getMemoriesText() - const memoryBlock = memories - ? `\n\nCe que tu sais deja sur l'utilisateur (memoire long terme) :\n${memories}` - : '' - return `${BASE_SYSTEM_PROMPT}\n\n${moodBlock}${memoryBlock}` + return `${BASE_SYSTEM_PROMPT}\n\n${moodBlock}` } function buildTools(): object[] { diff --git a/Max Avatar/src/main/index.ts b/Max Avatar/src/main/index.ts index 75cc856..8cc0d8b 100644 --- a/Max Avatar/src/main/index.ts +++ b/Max Avatar/src/main/index.ts @@ -7,7 +7,6 @@ import { getAssistantReply } from './ai/openrouter' import { setMainWindow, sendToRenderer } from './windowBridge' import { extractText } from './skills/documents/extractText' import { stripWakeWord } from './wakeWord' -import { enqueueMeetingAudioChunk, finishMeetingSession } from './meeting/meetingRecorder' import { loginAndLoadKeys } from './auth/authClient' import { openLoginWindow, closeLoginWindow } from './auth/loginWindow' import { clearSession, getCurrentUserEmail, isLoggedIn } from './auth/session' @@ -168,14 +167,6 @@ app if (window) menu.popup({ window }) }) - ipcMain.on('meeting-audio-chunk', (_event, audio: ArrayBuffer, mimeType: string) => { - enqueueMeetingAudioChunk(Buffer.from(audio), mimeType) - }) - - ipcMain.on('meeting-recording-stopped', () => { - void finishMeetingSession() - }) - ipcMain.on('dropped-files', (_event, paths: string[]) => { void (async () => { const path = paths[0] diff --git a/Max Avatar/src/main/meeting/meetingRecorder.ts b/Max Avatar/src/main/meeting/meetingRecorder.ts deleted file mode 100644 index 175ccac..0000000 --- a/Max Avatar/src/main/meeting/meetingRecorder.ts +++ /dev/null @@ -1,67 +0,0 @@ -import { Notification } from 'electron' -import { transcribeAudio, synthesizeSpeech } from '../ai/elevenlabs' -import { sendToRenderer } from '../windowBridge' -import { summarizeMeeting } from './summarize' -import { saveMeeting } from './meetingStore' - -let segments: string[] = [] -let active = false -// Chaine les transcriptions de segments pour les traiter dans l'ordre d'arrivee, meme si un -// segment met plus longtemps a transcrire que le suivant. -let queue: Promise = Promise.resolve() - -export function startMeetingSession(): void { - segments = [] - active = true - queue = Promise.resolve() -} - -async function processChunk(audio: Buffer, mimeType: string): Promise { - try { - const text = await transcribeAudio(audio, mimeType) - if (text) segments.push(text) - } catch (error) { - console.error('[meeting] echec transcription segment', error) - } -} - -export function enqueueMeetingAudioChunk(audio: Buffer, mimeType: string): void { - if (!active) return - queue = queue.then(() => processChunk(audio, mimeType)) -} - -export async function finishMeetingSession(): Promise { - if (!active) return - active = false - await queue - - const transcript = segments.join('\n') - segments = [] - - if (!transcript.trim()) { - new Notification({ - title: 'Transcription', - body: 'Aucune parole detectee, rien a resumer.' - }).show() - return - } - - try { - const summary = await summarizeMeeting(transcript) - saveMeeting(transcript, summary) - new Notification({ title: 'Transcription terminee', body: 'Le resume est pret.' }).show() - - const speech = await synthesizeSpeech(`Transcription terminee. ${summary}`) - const buffer = speech.buffer.slice( - speech.byteOffset, - speech.byteOffset + speech.byteLength - ) as ArrayBuffer - sendToRenderer('proactive-speech', buffer) - } catch (error) { - console.error('[meeting] echec resume', error) - new Notification({ - title: 'Transcription', - body: 'Echec du resume de la session (voir les logs).' - }).show() - } -} diff --git a/Max Avatar/src/main/meeting/meetingStore.ts b/Max Avatar/src/main/meeting/meetingStore.ts deleted file mode 100644 index 4359a94..0000000 --- a/Max Avatar/src/main/meeting/meetingStore.ts +++ /dev/null @@ -1,33 +0,0 @@ -import { app } from 'electron' -import { DatabaseSync } from 'node:sqlite' -import { join } from 'path' - -let db: DatabaseSync | null = null - -function getDb(): DatabaseSync { - if (db) return db - - const dbPath = join(app.getPath('userData'), 'meetings.sqlite') - db = new DatabaseSync(dbPath) - db.exec(` - CREATE TABLE IF NOT EXISTS meetings ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - transcript TEXT NOT NULL, - summary TEXT NOT NULL, - created_at TEXT NOT NULL - ); - `) - return db -} - -export function saveMeeting(transcript: string, summary: string): void { - getDb() - .prepare('INSERT INTO meetings (transcript, summary, created_at) VALUES (?, ?, ?)') - .run(transcript, summary, new Date().toISOString()) -} - -export function getLastMeetingSummary(): string | null { - const row = getDb().prepare('SELECT summary FROM meetings ORDER BY id DESC LIMIT 1').get() as - { summary: string } | undefined - return row?.summary ?? null -} diff --git a/Max Avatar/src/main/meeting/summarize.ts b/Max Avatar/src/main/meeting/summarize.ts deleted file mode 100644 index 6dc98ec..0000000 --- a/Max Avatar/src/main/meeting/summarize.ts +++ /dev/null @@ -1,58 +0,0 @@ -const OPENROUTER_URL = 'https://openrouter.ai/api/v1/chat/completions' -const MAX_CHUNK_CHARS = 12000 - -async function callModel(prompt: string): Promise { - const apiKey = process.env.OPENROUTER_API_KEY - if (!apiKey) throw new Error('OPENROUTER_API_KEY manquante dans .env') - const model = process.env.OPENROUTER_MODEL || 'deepseek/deepseek-chat' - - const response = await fetch(OPENROUTER_URL, { - method: 'POST', - headers: { - Authorization: `Bearer ${apiKey}`, - 'Content-Type': 'application/json' - }, - body: JSON.stringify({ model, messages: [{ role: 'user', content: prompt }] }) - }) - - if (!response.ok) { - throw new Error(`Resume echoue (${response.status}): ${await response.text()}`) - } - - const data = (await response.json()) as { - choices?: { message: { content?: string } }[] - } - return (data.choices?.[0]?.message.content ?? '').trim() -} - -function splitIntoChunks(text: string, maxChars: number): string[] { - const chunks: string[] = [] - for (let i = 0; i < text.length; i += maxChars) chunks.push(text.slice(i, i + maxChars)) - return chunks -} - -function buildPrompt(transcript: string): string { - return `Voici la transcription d'une reunion ou d'un cours. Redige un resume structure en -francais : points cles abordes, decisions prises et actions a suivre s'il y en a. Reste concis et -factuel, base-toi uniquement sur ce texte.\n\nTranscription :\n${transcript}` -} - -/** - * Resume un transcript de reunion/cours. Un transcript long (cours d'1h+) est decoupe et resume - * en deux passes (resumes partiels puis fusion) plutot que tronque brutalement. - */ -export async function summarizeMeeting(transcript: string): Promise { - if (transcript.length <= MAX_CHUNK_CHARS) { - return callModel(buildPrompt(transcript)) - } - - const chunks = splitIntoChunks(transcript, MAX_CHUNK_CHARS) - const partialSummaries = await Promise.all(chunks.map((chunk) => callModel(buildPrompt(chunk)))) - - const mergePrompt = `Voici plusieurs resumes partiels successifs d'une meme reunion ou d'un -meme cours. Fusionne-les en un seul resume structure et coherent en francais (points cles, -decisions, actions), sans repetitions :\n\n${partialSummaries - .map((summary, index) => `Partie ${index + 1} :\n${summary}`) - .join('\n\n')}` - return callModel(mergePrompt) -} diff --git a/Max Avatar/src/main/memory/store.ts b/Max Avatar/src/main/memory/store.ts index 22fcbba..de6282d 100644 --- a/Max Avatar/src/main/memory/store.ts +++ b/Max Avatar/src/main/memory/store.ts @@ -2,8 +2,6 @@ import { app } from 'electron' import { DatabaseSync } from 'node:sqlite' import { join } from 'path' -const MAX_MEMORIES = 150 - let db: DatabaseSync | null = null function getDb(): DatabaseSync { @@ -12,11 +10,6 @@ function getDb(): DatabaseSync { const dbPath = join(app.getPath('userData'), 'memory.sqlite') db = new DatabaseSync(dbPath) db.exec(` - CREATE TABLE IF NOT EXISTS memories ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - text TEXT NOT NULL, - created_at TEXT NOT NULL - ); CREATE TABLE IF NOT EXISTS mood ( id INTEGER PRIMARY KEY CHECK (id = 1), value INTEGER NOT NULL @@ -26,40 +19,6 @@ function getDb(): DatabaseSync { return db } -export function addMemory(text: string): void { - const database = getDb() - database - .prepare('INSERT INTO memories (text, created_at) VALUES (?, ?)') - .run(text, new Date().toISOString()) - - // Ne garde que les MAX_MEMORIES souvenirs les plus recents. - database - .prepare( - `DELETE FROM memories WHERE id NOT IN ( - SELECT id FROM memories ORDER BY id DESC LIMIT ? - )` - ) - .run(MAX_MEMORIES) -} - -/** Supprime les souvenirs dont le texte contient la recherche. Renvoie true si au moins un a ete retire. */ -export function forgetMemory(query: string): boolean { - const result = getDb().prepare('DELETE FROM memories WHERE text LIKE ?').run(`%${query}%`) - return result.changes > 0 -} - -export function clearAllMemories(): void { - getDb().exec('DELETE FROM memories') -} - -export function getMemoriesText(): string { - const rows = getDb().prepare('SELECT text FROM memories ORDER BY id ASC').all() as { - text: string - }[] - if (rows.length === 0) return '' - return rows.map((row) => `- ${row.text}`).join('\n') -} - export function getMood(): number { const row = getDb().prepare('SELECT value FROM mood WHERE id = 1').get() as { value: number } | undefined diff --git a/Max Avatar/src/main/skills/index.ts b/Max Avatar/src/main/skills/index.ts index 8720710..807f5bf 100644 --- a/Max Avatar/src/main/skills/index.ts +++ b/Max Avatar/src/main/skills/index.ts @@ -4,13 +4,12 @@ import { macSkills } from './mac' import { memorySkills } from './memory' import { webSkills } from './web' import { browserSkills } from './browser' -import { meetingSkills } from './meeting' export type { SkillDefinition } from './types' export function loadSkills(): SkillDefinition[] { const platformSkills = process.platform === 'darwin' ? macSkills : windowsSkills - return [...platformSkills, ...memorySkills, ...webSkills, ...browserSkills, ...meetingSkills] + return [...platformSkills, ...memorySkills, ...webSkills, ...browserSkills] } export function findSkill(name: string): SkillDefinition | undefined { diff --git a/Max Avatar/src/main/skills/meeting/getLastMeetingSummary.ts b/Max Avatar/src/main/skills/meeting/getLastMeetingSummary.ts deleted file mode 100644 index b17bc23..0000000 --- a/Max Avatar/src/main/skills/meeting/getLastMeetingSummary.ts +++ /dev/null @@ -1,15 +0,0 @@ -import { getLastMeetingSummary } from '../../meeting/meetingStore' -import type { SkillDefinition } from '../types' - -export const getLastMeetingSummarySkill: SkillDefinition = { - name: 'get_last_meeting_summary', - description: - "Renvoie le resume de la derniere session de transcription (reunion ou cours) enregistree via le menu contextuel de l'avatar (clic droit).", - parameters: { type: 'object', properties: {}, required: [] }, - execute: async () => { - const summary = getLastMeetingSummary() - return summary - ? `Resume de la derniere session enregistree :\n${summary}` - : "Aucune session de transcription n'a encore ete enregistree." - } -} diff --git a/Max Avatar/src/main/skills/meeting/index.ts b/Max Avatar/src/main/skills/meeting/index.ts deleted file mode 100644 index d290365..0000000 --- a/Max Avatar/src/main/skills/meeting/index.ts +++ /dev/null @@ -1,4 +0,0 @@ -import type { SkillDefinition } from '../types' -import { getLastMeetingSummarySkill } from './getLastMeetingSummary' - -export const meetingSkills: SkillDefinition[] = [getLastMeetingSummarySkill] diff --git a/Max Avatar/src/main/skills/memory/forgetInfo.ts b/Max Avatar/src/main/skills/memory/forgetInfo.ts deleted file mode 100644 index dfe7f12..0000000 --- a/Max Avatar/src/main/skills/memory/forgetInfo.ts +++ /dev/null @@ -1,33 +0,0 @@ -import { clearAllMemories, forgetMemory } from '../../memory/store' -import type { SkillDefinition } from '../types' -import { asString } from '../argUtils' - -export const forgetInfo: SkillDefinition = { - name: 'forget_info', - description: - 'Supprime une information precedemment memorisee sur l\'utilisateur, ou efface toute la memoire si demande explicitement ("tout").', - parameters: { - type: 'object', - properties: { - query: { - type: 'string', - description: 'Mots-cles de l\'information a oublier, ou "tout" pour tout effacer' - } - }, - required: ['query'] - }, - execute: async (args) => { - const query = asString(args.query).trim() - if (!query) throw new Error('recherche manquante') - - if (query.toLowerCase() === 'tout') { - clearAllMemories() - return 'Toute la memoire a ete effacee.' - } - - const removed = forgetMemory(query) - return removed - ? `Information oubliee : ${query}` - : `Aucune information correspondant a "${query}" trouvee.` - } -} diff --git a/Max Avatar/src/main/skills/memory/index.ts b/Max Avatar/src/main/skills/memory/index.ts index 2d48848..188bd46 100644 --- a/Max Avatar/src/main/skills/memory/index.ts +++ b/Max Avatar/src/main/skills/memory/index.ts @@ -1,7 +1,5 @@ import type { SkillDefinition } from '../types' -import { rememberInfo } from './rememberInfo' -import { forgetInfo } from './forgetInfo' import { adjustMoodSkill } from './adjustMood' -// Memoire et humeur sont independantes de l'OS, communes a toutes les plateformes. -export const memorySkills: SkillDefinition[] = [rememberInfo, forgetInfo, adjustMoodSkill] +// Humeur, independante de l'OS, commune a toutes les plateformes. +export const memorySkills: SkillDefinition[] = [adjustMoodSkill] diff --git a/Max Avatar/src/main/skills/memory/rememberInfo.ts b/Max Avatar/src/main/skills/memory/rememberInfo.ts deleted file mode 100644 index 988116d..0000000 --- a/Max Avatar/src/main/skills/memory/rememberInfo.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { addMemory } from '../../memory/store' -import type { SkillDefinition } from '../types' -import { asString } from '../argUtils' - -export const rememberInfo: SkillDefinition = { - name: 'remember_info', - description: - "Memorise durablement une information sur l'utilisateur (preference, habitude, fait personnel important) pour s'en souvenir dans les conversations futures, meme apres redemarrage.", - parameters: { - type: 'object', - properties: { - info: { - type: 'string', - description: 'Information a retenir, formulee clairement (ex: "aime le cafe sans sucre")' - } - }, - required: ['info'] - }, - execute: async (args) => { - const info = asString(args.info).trim() - if (!info) throw new Error('information manquante') - addMemory(info) - return `Retenu : ${info}` - } -} diff --git a/Max Avatar/src/preload/index.d.ts b/Max Avatar/src/preload/index.d.ts index d22424a..ba21225 100644 --- a/Max Avatar/src/preload/index.d.ts +++ b/Max Avatar/src/preload/index.d.ts @@ -9,9 +9,6 @@ export interface ForgeAvatarApi { sendVoiceTurn: (audio: ArrayBuffer, mimeType: string) => Promise showContextMenu: (listening: boolean) => void onToggleListening: (callback: (listening: boolean) => void) => () => void - onToggleMeetingTranscription: (callback: (transcribing: boolean) => void) => () => void - sendMeetingAudioChunk: (audio: ArrayBuffer, mimeType: string) => void - sendMeetingRecordingStopped: () => void onProactiveSpeech: (callback: (audio: ArrayBuffer) => void) => () => void getPathForFile: (file: File) => string sendDroppedFiles: (paths: string[]) => void diff --git a/Max Avatar/src/preload/index.ts b/Max Avatar/src/preload/index.ts index c3ea647..b2ece63 100644 --- a/Max Avatar/src/preload/index.ts +++ b/Max Avatar/src/preload/index.ts @@ -23,18 +23,6 @@ const api = { ipcRenderer.on('toggle-listening', handler) return () => ipcRenderer.removeListener('toggle-listening', handler) }, - onToggleMeetingTranscription: (callback: (transcribing: boolean) => void): (() => void) => { - const handler = (_event: Electron.IpcRendererEvent, transcribing: boolean): void => - callback(transcribing) - ipcRenderer.on('toggle-meeting-transcription', handler) - return () => ipcRenderer.removeListener('toggle-meeting-transcription', handler) - }, - sendMeetingAudioChunk: (audio: ArrayBuffer, mimeType: string): void => { - ipcRenderer.send('meeting-audio-chunk', audio, mimeType) - }, - sendMeetingRecordingStopped: (): void => { - ipcRenderer.send('meeting-recording-stopped') - }, onProactiveSpeech: (callback: (audio: ArrayBuffer) => void): (() => void) => { const handler = (_event: Electron.IpcRendererEvent, audio: ArrayBuffer): void => callback(audio) ipcRenderer.on('proactive-speech', handler) diff --git a/Max Avatar/src/renderer/src/App.tsx b/Max Avatar/src/renderer/src/App.tsx index 838e3a0..bbdda01 100644 --- a/Max Avatar/src/renderer/src/App.tsx +++ b/Max Avatar/src/renderer/src/App.tsx @@ -5,16 +5,13 @@ import VoiceErrorBanner from './components/VoiceErrorBanner' import UpdateBanner from './components/UpdateBanner' import { useVoiceAssistant, type VoiceState } from './voice/useVoiceAssistant' import { useProactiveSpeech } from './voice/useProactiveSpeech' -import { useMeetingRecorder } from './voice/useMeetingRecorder' function App(): React.JSX.Element { const avatar = useRef(null) - // Faux par defaut : l'ecoute (comme les modes) n'est activee que si un compte est connecte, voir - // l'effet ci-dessous qui verifie l'etat de connexion au demarrage. + // Faux par defaut : l'ecoute n'est activee que si un compte est connecte, voir l'effet + // ci-dessous qui verifie l'etat de connexion au demarrage. const [listening, setListening] = useState(false) const listeningRef = useRef(listening) - const [transcribing, setTranscribing] = useState(false) - const transcribingRef = useRef(transcribing) const [voiceState, setVoiceState] = useState('idle') const [voiceError, setVoiceError] = useState(null) const [updateStatus, setUpdateStatus] = useState<'available' | 'ready' | null>(null) @@ -32,16 +29,11 @@ function App(): React.JSX.Element { }, []) useVoiceAssistant(avatar, listening, handleVoiceStateChange, handleVoiceError) useProactiveSpeech(avatar) - useMeetingRecorder() useEffect(() => { listeningRef.current = listening }, [listening]) - useEffect(() => { - transcribingRef.current = transcribing - }, [transcribing]) - useEffect(() => window.api.onToggleListening(setListening), []) // Restaure l'ecoute par defaut si l'app demarre deja connectee (ex: redemarrage apres une // connexion precedente dans la meme session OS, bien qu'aucune session ne soit persistee entre @@ -52,7 +44,6 @@ function App(): React.JSX.Element { .then((status) => setListening(status.loggedIn)) .catch(() => setListening(false)) }, []) - useEffect(() => window.api.onToggleMeetingTranscription(setTranscribing), []) useEffect(() => window.api.onProactiveSpeech(() => setVoiceState('speaking')), []) const onDragOver = useCallback((event: React.DragEvent) => { diff --git a/Max Avatar/src/renderer/src/voice/useMeetingRecorder.ts b/Max Avatar/src/renderer/src/voice/useMeetingRecorder.ts deleted file mode 100644 index 32a0484..0000000 --- a/Max Avatar/src/renderer/src/voice/useMeetingRecorder.ts +++ /dev/null @@ -1,128 +0,0 @@ -import { useEffect, useRef } from 'react' - -const SEGMENT_MS = 90_000 -const STEREO_MIX_PATTERN = /stereo mix|what u hear|wave ?out mix|loopback/i - -interface RecordingState { - micStream: MediaStream - systemStream: MediaStream | null - audioContext: AudioContext | null - recorder: MediaRecorder | null - segmentTimeout: ReturnType | null - stopping: boolean -} - -async function findStereoMixDeviceId(): Promise { - try { - const devices = await navigator.mediaDevices.enumerateDevices() - const match = devices.find( - (device) => device.kind === 'audioinput' && STEREO_MIX_PATTERN.test(device.label) - ) - return match?.deviceId ?? null - } catch { - return null - } -} - -// Enregistre micro + "Stereo Mix" (audio systeme) si ce peripherique existe sur la machine, -// sinon se rabat silencieusement sur le micro seul. Active/desactive via le menu contextuel de -// l'avatar, independamment de l'assistant vocal (useVoiceAssistant) qui garde sa propre capture. -export function useMeetingRecorder(): void { - const stateRef = useRef(null) - - useEffect(() => { - function startNewSegment(combinedStream: MediaStream): void { - const state = stateRef.current - if (!state) return - - const recorder = new MediaRecorder(combinedStream, { mimeType: 'audio/webm' }) - const chunks: Blob[] = [] - recorder.ondataavailable = (event) => { - if (event.data.size > 0) chunks.push(event.data) - } - recorder.onstop = () => { - const blob = new Blob(chunks, { type: 'audio/webm' }) - void blob.arrayBuffer().then((buffer) => { - window.api.sendMeetingAudioChunk(buffer, blob.type) - if (state.stopping) { - window.api.sendMeetingRecordingStopped() - } else { - startNewSegment(combinedStream) - } - }) - } - - recorder.start() - state.recorder = recorder - state.segmentTimeout = setTimeout(() => { - if (recorder.state !== 'inactive') recorder.stop() - }, SEGMENT_MS) - } - - async function start(): Promise { - let micStream: MediaStream - try { - micStream = await navigator.mediaDevices.getUserMedia({ audio: true }) - } catch (error) { - console.error('[meeting] micro indisponible', error) - return - } - - const state: RecordingState = { - micStream, - systemStream: null, - audioContext: null, - recorder: null, - segmentTimeout: null, - stopping: false - } - stateRef.current = state - - const stereoMixId = await findStereoMixDeviceId() - if (stereoMixId) { - try { - state.systemStream = await navigator.mediaDevices.getUserMedia({ - audio: { deviceId: { exact: stereoMixId } } - }) - } catch (error) { - console.error('[meeting] Stereo Mix detecte mais indisponible', error) - } - } - - let combinedStream: MediaStream = state.micStream - if (state.systemStream) { - const audioContext = new AudioContext() - state.audioContext = audioContext - const destination = audioContext.createMediaStreamDestination() - audioContext.createMediaStreamSource(state.micStream).connect(destination) - audioContext.createMediaStreamSource(state.systemStream).connect(destination) - combinedStream = destination.stream - } - - startNewSegment(combinedStream) - } - - function stop(): void { - const state = stateRef.current - if (!state) return - state.stopping = true - if (state.segmentTimeout) clearTimeout(state.segmentTimeout) - if (state.recorder && state.recorder.state !== 'inactive') { - state.recorder.stop() - } else { - // Aucun enregistrement actif a arreter (ex: micro indisponible au demarrage) : previens - // quand meme le process principal pour qu'il finalise une session potentiellement vide. - window.api.sendMeetingRecordingStopped() - } - state.micStream.getTracks().forEach((track) => track.stop()) - state.systemStream?.getTracks().forEach((track) => track.stop()) - void state.audioContext?.close() - stateRef.current = null - } - - return window.api.onToggleMeetingTranscription((transcribing) => { - if (transcribing) void start() - else stop() - }) - }, []) -} diff --git a/Max Avatar/tests/unit/components/App.test.tsx b/Max Avatar/tests/unit/components/App.test.tsx index 43270b0..e3cecca 100644 --- a/Max Avatar/tests/unit/components/App.test.tsx +++ b/Max Avatar/tests/unit/components/App.test.tsx @@ -26,9 +26,6 @@ vi.mock('../../../src/renderer/src/voice/useVoiceAssistant', () => ({ useVoiceAs vi.mock('../../../src/renderer/src/voice/useProactiveSpeech', () => ({ useProactiveSpeech: vi.fn() })) -vi.mock('../../../src/renderer/src/voice/useMeetingRecorder', () => ({ - useMeetingRecorder: vi.fn() -})) let onUpdateAvailableCb: (() => void) | undefined let onUpdateReadyCb: (() => void) | undefined @@ -53,7 +50,6 @@ function setupWindowApi(): void { return () => {} }), onToggleListening: vi.fn(() => () => {}), - onToggleMeetingTranscription: vi.fn(() => () => {}), onProactiveSpeech: vi.fn(() => () => {}), getPathForFile, sendDroppedFiles, @@ -126,7 +122,7 @@ describe('', () => { expect(sendDroppedFiles).not.toHaveBeenCalled() }) - it('should request the context menu with the current listening/transcribing state', () => { + it('should request the context menu with the current listening state', () => { // Faux par defaut (ecoute non activee tant qu'aucun compte n'est connecte, voir // getAuthStatus ci-dessus qui renvoie loggedIn: false). render() diff --git a/Max Avatar/tests/unit/components/useMeetingRecorder.test.ts b/Max Avatar/tests/unit/components/useMeetingRecorder.test.ts deleted file mode 100644 index 480649c..0000000 --- a/Max Avatar/tests/unit/components/useMeetingRecorder.test.ts +++ /dev/null @@ -1,96 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from 'vitest' -import { renderHook } from '@testing-library/react' - -let onToggleCallback: ((transcribing: boolean) => void) | undefined -const sendMeetingAudioChunk = vi.fn() -const sendMeetingRecordingStopped = vi.fn() -const onToggleMeetingTranscription = vi.fn((cb: (transcribing: boolean) => void) => { - onToggleCallback = cb - return () => {} -}) - -function fakeStream(): MediaStream { - const stop = vi.fn() - return { getTracks: () => [{ stop }] } as unknown as MediaStream -} - -const getUserMedia = vi.fn(async () => fakeStream()) -const enumerateDevices = vi.fn(async () => []) - -class FakeMediaRecorder { - static instances: FakeMediaRecorder[] = [] - state: 'recording' | 'inactive' = 'recording' - ondataavailable: ((event: { data: Blob }) => void) | null = null - onstop: (() => void) | null = null - constructor( - public stream: MediaStream, - public options: { mimeType: string } - ) { - FakeMediaRecorder.instances.push(this) - } - start(): void { - this.state = 'recording' - } - stop(): void { - this.state = 'inactive' - this.ondataavailable?.({ data: new Blob(['chunk'], { type: 'audio/webm' }) }) - this.onstop?.() - } -} - -const { useMeetingRecorder } = await import('../../../src/renderer/src/voice/useMeetingRecorder') - -describe('useMeetingRecorder()', () => { - beforeEach(() => { - vi.clearAllMocks() - FakeMediaRecorder.instances = [] - ;(window as unknown as { api: Record }).api = { - onToggleMeetingTranscription, - sendMeetingAudioChunk, - sendMeetingRecordingStopped - } - Object.defineProperty(navigator, 'mediaDevices', { - value: { getUserMedia, enumerateDevices }, - configurable: true - }) - vi.stubGlobal('MediaRecorder', FakeMediaRecorder) - }) - - it('should start recording the microphone when transcription is toggled on', async () => { - renderHook(() => useMeetingRecorder()) - onToggleCallback?.(true) - await vi.waitFor(() => expect(FakeMediaRecorder.instances.length).toBe(1)) - expect(getUserMedia).toHaveBeenCalledWith({ audio: true }) - }) - - it('should give up quietly when the microphone is unavailable, without ever starting a recorder', async () => { - getUserMedia.mockRejectedValueOnce(new Error('no mic')) - renderHook(() => useMeetingRecorder()) - onToggleCallback?.(true) - await vi.waitFor(() => expect(getUserMedia).toHaveBeenCalled()) - // Rien n'a jamais demarre : stopper ensuite ne doit ni planter ni envoyer de notification pour - // une session qui n'a jamais existe. - expect(() => onToggleCallback?.(false)).not.toThrow() - expect(FakeMediaRecorder.instances.length).toBe(0) - }) - - it('should send the recorded chunk and notify the main process when stopped', async () => { - renderHook(() => useMeetingRecorder()) - onToggleCallback?.(true) - await vi.waitFor(() => expect(FakeMediaRecorder.instances.length).toBe(1)) - - onToggleCallback?.(false) - await vi.waitFor(() => expect(sendMeetingAudioChunk).toHaveBeenCalled()) - expect(sendMeetingRecordingStopped).toHaveBeenCalled() - }) - - it('should start a new segment automatically instead of stopping when not asked to stop', async () => { - renderHook(() => useMeetingRecorder()) - onToggleCallback?.(true) - await vi.waitFor(() => expect(FakeMediaRecorder.instances.length).toBe(1)) - - FakeMediaRecorder.instances[0]?.stop() - await vi.waitFor(() => expect(FakeMediaRecorder.instances.length).toBe(2)) - expect(sendMeetingRecordingStopped).not.toHaveBeenCalled() - }) -}) diff --git a/Max Avatar/tests/unit/meetingRecorder.test.ts b/Max Avatar/tests/unit/meetingRecorder.test.ts deleted file mode 100644 index e044e78..0000000 --- a/Max Avatar/tests/unit/meetingRecorder.test.ts +++ /dev/null @@ -1,84 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from 'vitest' - -const NotificationShow = vi.fn() -class NotificationMock { - constructor(public options: { title: string; body: string }) {} - show = NotificationShow -} -vi.mock('electron', () => ({ Notification: NotificationMock })) - -const transcribeAudio = vi.fn(async () => 'Un segment transcrit.') -const synthesizeSpeech = vi.fn(async () => Buffer.from([1, 2, 3])) -vi.mock('../../src/main/ai/elevenlabs', () => ({ transcribeAudio, synthesizeSpeech })) - -const sendToRenderer = vi.fn() -vi.mock('../../src/main/windowBridge', () => ({ sendToRenderer })) - -const summarizeMeeting = vi.fn(async () => 'Resume de la reunion.') -vi.mock('../../src/main/meeting/summarize', () => ({ summarizeMeeting })) - -const saveMeeting = vi.fn() -vi.mock('../../src/main/meeting/meetingStore', () => ({ saveMeeting })) - -const { startMeetingSession, enqueueMeetingAudioChunk, finishMeetingSession } = - await import('../../src/main/meeting/meetingRecorder') - -describe('meetingRecorder', () => { - beforeEach(() => { - vi.clearAllMocks() - }) - - it('should do nothing when a chunk arrives without an active session', async () => { - enqueueMeetingAudioChunk(Buffer.from('audio'), 'audio/webm') - await finishMeetingSession() - expect(transcribeAudio).not.toHaveBeenCalled() - }) - - it('should notify when stopping a session with no speech detected', async () => { - startMeetingSession() - await finishMeetingSession() - expect(NotificationShow).toHaveBeenCalled() - expect(summarizeMeeting).not.toHaveBeenCalled() - }) - - it('should transcribe queued chunks in order and summarize the full session', async () => { - startMeetingSession() - enqueueMeetingAudioChunk(Buffer.from('audio1'), 'audio/webm') - enqueueMeetingAudioChunk(Buffer.from('audio2'), 'audio/webm') - await finishMeetingSession() - - expect(transcribeAudio).toHaveBeenCalledTimes(2) - expect(summarizeMeeting).toHaveBeenCalledWith('Un segment transcrit.\nUn segment transcrit.') - expect(saveMeeting).toHaveBeenCalledWith( - 'Un segment transcrit.\nUn segment transcrit.', - 'Resume de la reunion.' - ) - expect(sendToRenderer).toHaveBeenCalledWith('proactive-speech', expect.anything()) - }) - - it('should skip a segment whose transcription fails, without aborting the session', async () => { - transcribeAudio.mockRejectedValueOnce(new Error('echec reseau')) - startMeetingSession() - enqueueMeetingAudioChunk(Buffer.from('audio1'), 'audio/webm') - enqueueMeetingAudioChunk(Buffer.from('audio2'), 'audio/webm') - await finishMeetingSession() - expect(summarizeMeeting).toHaveBeenCalledWith('Un segment transcrit.') - }) - - it('should notify a failure when summarizing throws', async () => { - summarizeMeeting.mockRejectedValueOnce(new Error('echec resume')) - startMeetingSession() - enqueueMeetingAudioChunk(Buffer.from('audio1'), 'audio/webm') - await finishMeetingSession() - expect(NotificationShow).toHaveBeenCalled() - expect(saveMeeting).not.toHaveBeenCalled() - }) - - it('should do nothing when finishing a session that was already finished', async () => { - startMeetingSession() - await finishMeetingSession() - NotificationShow.mockClear() - await finishMeetingSession() - expect(NotificationShow).not.toHaveBeenCalled() - }) -}) diff --git a/Max Avatar/tests/unit/openrouter.test.ts b/Max Avatar/tests/unit/openrouter.test.ts index 42e9a46..272690d 100644 --- a/Max Avatar/tests/unit/openrouter.test.ts +++ b/Max Avatar/tests/unit/openrouter.test.ts @@ -14,9 +14,8 @@ let currentSkills: FakeSkill[] = [] const loadSkills = vi.fn(() => currentSkills) vi.mock('../../src/main/skills', () => ({ loadSkills })) -const getMemoriesText = vi.fn(() => '') const getMood = vi.fn(() => 0) -vi.mock('../../src/main/memory/store', () => ({ getMemoriesText, getMood })) +vi.mock('../../src/main/memory/store', () => ({ getMood })) const synthesizeSpeech = vi.fn(async () => Buffer.from([1, 2, 3])) vi.mock('../../src/main/ai/elevenlabs', () => ({ synthesizeSpeech })) diff --git a/Max Avatar/tests/unit/skills.memory.test.ts b/Max Avatar/tests/unit/skills.memory.test.ts index d0a98c3..fb3e0c3 100644 --- a/Max Avatar/tests/unit/skills.memory.test.ts +++ b/Max Avatar/tests/unit/skills.memory.test.ts @@ -9,48 +9,9 @@ vi.mock('electron', () => ({ app: { getPath: () => tempDir } })) -const { getMemoriesText, getMood } = await import('../../src/main/memory/store') -const { rememberInfo } = await import('../../src/main/skills/memory/rememberInfo') -const { forgetInfo } = await import('../../src/main/skills/memory/forgetInfo') +const { getMood } = await import('../../src/main/memory/store') const { adjustMoodSkill } = await import('../../src/main/skills/memory/adjustMood') -describe('remember_info', () => { - it('should refuse an empty piece of information', async () => { - await expect(rememberInfo.execute({ info: ' ' })).rejects.toThrow(/manquante/) - }) - - it('should persist the information so it is retrievable later', async () => { - const result = await rememberInfo.execute({ info: 'aime le cafe sans sucre' }) - expect(result).toMatch(/Retenu/) - expect(getMemoriesText()).toMatch(/aime le cafe sans sucre/) - }) -}) - -describe('forget_info', () => { - it('should refuse an empty query', async () => { - await expect(forgetInfo.execute({ query: '' })).rejects.toThrow(/manquante/) - }) - - it('should report when nothing matches the query', async () => { - const result = await forgetInfo.execute({ query: 'inexistant-xyz' }) - expect(result).toMatch(/Aucune information/) - }) - - it('should remove a previously remembered piece of information matching the query', async () => { - await rememberInfo.execute({ info: 'deteste le lundi matin' }) - const result = await forgetInfo.execute({ query: 'lundi' }) - expect(result).toMatch(/oubliee/) - expect(getMemoriesText()).not.toMatch(/lundi/) - }) - - it('should clear every memory when the query is "tout"', async () => { - await rememberInfo.execute({ info: 'un souvenir quelconque' }) - const result = await forgetInfo.execute({ query: 'tout' }) - expect(result).toMatch(/effacee/) - expect(getMemoriesText()).toBe('') - }) -}) - describe('adjust_mood', () => { it('should increase the mood score on a positive change', async () => { const before = getMood() diff --git a/Max Avatar/tests/unit/skills.visionWebMeetingDocuments.test.ts b/Max Avatar/tests/unit/skills.webDocuments.test.ts similarity index 84% rename from Max Avatar/tests/unit/skills.visionWebMeetingDocuments.test.ts rename to Max Avatar/tests/unit/skills.webDocuments.test.ts index c05be3d..b081a14 100644 --- a/Max Avatar/tests/unit/skills.visionWebMeetingDocuments.test.ts +++ b/Max Avatar/tests/unit/skills.webDocuments.test.ts @@ -3,7 +3,7 @@ import { mkdtempSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' -const tempDir = mkdtempSync(join(tmpdir(), 'forge-avatar-vision-meeting-test-')) +const tempDir = mkdtempSync(join(tmpdir(), 'forge-avatar-web-documents-test-')) vi.mock('electron', () => ({ app: { getPath: () => tempDir } @@ -20,9 +20,6 @@ vi.mock('mammoth', () => ({ })) const { searchWeb } = await import('../../src/main/skills/web/searchWeb') -const { getLastMeetingSummarySkill } = - await import('../../src/main/skills/meeting/getLastMeetingSummary') -const { saveMeeting } = await import('../../src/main/meeting/meetingStore') const { extractText } = await import('../../src/main/skills/documents/extractText') beforeEach(() => { @@ -68,19 +65,6 @@ describe('search_web', () => { }) }) -describe('get_last_meeting_summary', () => { - it('should report no session recorded yet', async () => { - const result = await getLastMeetingSummarySkill.execute({}) - expect(result).toMatch(/Aucune session/) - }) - - it('should return the last saved meeting summary', async () => { - saveMeeting('transcript complet', 'resume de la reunion') - const result = await getLastMeetingSummarySkill.execute({}) - expect(result).toMatch(/resume de la reunion/) - }) -}) - describe('extractText()', () => { it('should read a plain text file as-is', async () => { const filePath = join(tempDir, 'note.txt') diff --git a/Max Avatar/tests/unit/summarize.test.ts b/Max Avatar/tests/unit/summarize.test.ts deleted file mode 100644 index 133e4ff..0000000 --- a/Max Avatar/tests/unit/summarize.test.ts +++ /dev/null @@ -1,48 +0,0 @@ -import { describe, it, expect, vi, beforeEach } from 'vitest' -import { summarizeMeeting } from '../../src/main/meeting/summarize' - -describe('summarizeMeeting()', () => { - beforeEach(() => { - vi.stubGlobal('fetch', vi.fn()) - process.env.OPENROUTER_API_KEY = 'test-key' - }) - - it('should throw when the API key is missing', async () => { - delete process.env.OPENROUTER_API_KEY - await expect(summarizeMeeting('court transcript')).rejects.toThrow(/OPENROUTER_API_KEY/) - }) - - it('should summarize a short transcript in a single call', async () => { - vi.mocked(fetch).mockResolvedValue({ - ok: true, - json: () => Promise.resolve({ choices: [{ message: { content: 'Resume concis.' } }] }) - } as Response) - - const summary = await summarizeMeeting('Un court transcript de reunion.') - expect(summary).toBe('Resume concis.') - expect(fetch).toHaveBeenCalledTimes(1) - }) - - it('should throw a descriptive error when the API call fails', async () => { - vi.mocked(fetch).mockResolvedValue({ - ok: false, - status: 500, - text: () => Promise.resolve('panne') - } as Response) - await expect(summarizeMeeting('transcript')).rejects.toThrow(/Resume echoue/) - }) - - it('should split a long transcript into chunks, summarize each, then merge', async () => { - const longTranscript = 'a'.repeat(25000) - vi.mocked(fetch).mockResolvedValue({ - ok: true, - json: () => - Promise.resolve({ choices: [{ message: { content: 'Resume partiel ou final.' } }] }) - } as Response) - - const summary = await summarizeMeeting(longTranscript) - expect(summary).toBe('Resume partiel ou final.') - // 25000 chars / 12000 max => 3 chunks + 1 fusion = 4 appels. - expect(fetch).toHaveBeenCalledTimes(4) - }) -})