fix(voice): route voice turns through the same backend pipeline as chat
Voice interactions still called OpenRouter directly from the main
process with a leftover pre-redesign system prompt ("coach de
formation vocal"), bypassing Max API's intent router and the new
PERSONALITY_PROMPT entirely - causing Max to misrepresent himself in
spoken conversation. voice-turn now calls routeMessage() (the same
POST /sessions/messages entry point the chat window uses), so voice
and text share one personality and one pipeline.
The leaked-boilerplate/degenerate-text safety checks that used to live
alongside the old direct OpenRouter call move to a focused
speechSafety.ts module, still applied to the reply before it's spoken.
getAssistantReply() and its model-fallback plumbing are deleted - that
logic now lives server-side in Max API's OpenRouterService.
A learn-intent voice command (e.g. saying "apprends-moi React out
loud") now opens the pipeline stepper and syncs session status exactly
like typing it in chat, via a handleRouteMessageResult() helper shared
between voice-turn and sessions:route-message.
Known limitations (unchanged from the text-chat intent router, now
just consistent across both channels): casual chat-intent turns have
no cross-turn memory (no pre-session history storage server-side yet),
and a voice-started session's messages don't appear in the chat
window's own transcript if opened afterwards (per-window state only).
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Sonnet 5
parent
78d6547037
commit
73bc2587b8
@@ -1,131 +0,0 @@
|
||||
import { logger } from '../utils/logger'
|
||||
import { getConfigValue, requireLoggedIn } from '../auth/session'
|
||||
|
||||
const OPENROUTER_URL = 'https://openrouter.ai/api/v1/chat/completions'
|
||||
|
||||
// Si le modele principal est temporairement indisponible cote fournisseur (constate en test reel :
|
||||
// 429 "rate-limited upstream" puis 504 "operation was aborted" sur deepseek/deepseek-chat), on
|
||||
// bascule automatiquement sur un modele de secours de meme categorie, plutot que de faire echouer
|
||||
// la reponse et d'afficher une erreur a l'utilisateur.
|
||||
const FALLBACK_MODEL = process.env.OPENROUTER_FALLBACK_MODEL || 'qwen/qwen-2.5-72b-instruct'
|
||||
|
||||
interface ChatMessage {
|
||||
role: 'system' | 'user' | 'assistant'
|
||||
content: string
|
||||
}
|
||||
|
||||
const BASE_SYSTEM_PROMPT = `Tu es Max, le coach de formation vocal d'un freelance. Tu discutes avec
|
||||
lui de maniere naturelle et amicale, comme un collegue. Tes reponses sont lues a voix haute, donc
|
||||
reste concis (2 a 4 phrases), parle en francais naturel, sans listes a puces ni mise en forme.
|
||||
|
||||
Regle absolue : ne decris jamais un processus ou un resultat que tu n'as pas reellement obtenu.
|
||||
Si tu n'es pas sur de ta reponse, dis-le honnetement plutot que d'inventer une information.`
|
||||
|
||||
// Marqueurs pour detecter une fuite de "boilerplate" interne du modele (constate en test reel :
|
||||
// "Use the results below to formulate an answer..." prononce a voix haute au lieu d'une vraie
|
||||
// reponse de Max) : present si ca ressemble a de l'anglais generique sans aucun mot-outil francais.
|
||||
const ENGLISH_LEAK_MARKERS =
|
||||
/\b(the|unless|below|formulate|additional|information|needed|answer the|user question)\b/i
|
||||
const FRENCH_MARKERS =
|
||||
/\b(le|la|les|de|des|et|un|une|est|tu|je|pour|dans|avec|qui|que|ce|ton|ta)\b/i
|
||||
|
||||
function containsLeakedBoilerplate(text: string): boolean {
|
||||
return ENGLISH_LEAK_MARKERS.test(text) && !FRENCH_MARKERS.test(text)
|
||||
}
|
||||
|
||||
/**
|
||||
* Le modele peut "decrocher" et renvoyer un texte corrompu (constate en test reel : " foia" +
|
||||
* caracteres chinois/bengalis a la place d'une vraie phrase). Detecte via la part de caracteres
|
||||
* non-latins/non-imprimables dans le texte.
|
||||
*/
|
||||
function isDegenerateText(text: string): boolean {
|
||||
const trimmed = text.trim()
|
||||
if (!trimmed) return false
|
||||
let latinCount = 0
|
||||
for (const char of trimmed) {
|
||||
const code = char.codePointAt(0) ?? 0
|
||||
if ((code >= 0x20 && code <= 0x7e) || (code >= 0xa0 && code <= 0x24f)) latinCount++
|
||||
}
|
||||
return latinCount / trimmed.length < 0.7 || (trimmed.length > 15 && latinCount < 8)
|
||||
}
|
||||
|
||||
const FALLBACK_REPLY =
|
||||
"Voila, j'ai bien avance avec toi sur ce sujet. Dis-moi si tu veux qu'on continue."
|
||||
|
||||
// Historique borne en memoire pour garder le contexte entre deux echanges vocaux.
|
||||
const history: ChatMessage[] = []
|
||||
const MAX_HISTORY_MESSAGES = 16
|
||||
|
||||
export async function getAssistantReply(userText: string): Promise<string> {
|
||||
requireLoggedIn()
|
||||
const apiKey = getConfigValue('OPENROUTER_API_KEY')
|
||||
if (!apiKey) throw new Error('OPENROUTER_API_KEY manquante dans .env')
|
||||
|
||||
const primaryModel = getConfigValue('OPENROUTER_MODEL') || 'deepseek/deepseek-chat'
|
||||
history.push({ role: 'user', content: userText })
|
||||
|
||||
const messages: ChatMessage[] = [{ role: 'system', content: BASE_SYSTEM_PROMPT }, ...history]
|
||||
|
||||
const callModel = (model: string): Promise<Response> =>
|
||||
fetch(OPENROUTER_URL, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: `Bearer ${apiKey}`,
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({ model, messages })
|
||||
})
|
||||
|
||||
// La bascule de modele (panne HTTP ou reponse invalide) doit rester TRANSPARENTE pour
|
||||
// l'utilisateur : meme `messages` (donc meme contexte de conversation) est reutilise quel que
|
||||
// soit le modele qui repond, et on essaie l'AUTRE modele avant d'abandonner, plutot que de
|
||||
// remonter une erreur visible des le premier echec (constate en test reel : une reponse 200 OK
|
||||
// sans "choices" apres bascule faisait planter tout le tour au lieu d'etre rattrapee).
|
||||
const modelsToTry = [primaryModel, FALLBACK_MODEL]
|
||||
let data: ChatMessage | null = null
|
||||
let lastError: string | null = null
|
||||
|
||||
for (const model of modelsToTry) {
|
||||
let response: Response
|
||||
try {
|
||||
response = await callModel(model)
|
||||
} catch (error) {
|
||||
lastError = error instanceof Error ? error.message : String(error)
|
||||
console.warn(`[chat] ${model} injoignable (${lastError}), tentative suivante si possible`)
|
||||
continue
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
lastError = `${response.status}: ${await response.text()}`
|
||||
console.warn(
|
||||
`[chat] ${model} a renvoye une erreur (${lastError}), tentative suivante si possible`
|
||||
)
|
||||
continue
|
||||
}
|
||||
|
||||
const parsed = (await response.json()) as { choices?: { message: ChatMessage }[] }
|
||||
const choice = parsed.choices?.[0]
|
||||
if (!choice) {
|
||||
lastError = `reponse inattendue (${(parsed as { error?: { message?: string } })?.error?.message ?? 'forme inconnue'})`
|
||||
console.warn(`[chat] ${model} : ${lastError}, tentative suivante si possible`)
|
||||
continue
|
||||
}
|
||||
|
||||
data = choice.message
|
||||
break
|
||||
}
|
||||
|
||||
if (!data) {
|
||||
throw new Error(`Aucun modele disponible n'a pu repondre (${lastError ?? 'raison inconnue'})`)
|
||||
}
|
||||
|
||||
let reply = data.content ?? ''
|
||||
if (containsLeakedBoilerplate(reply) || isDegenerateText(reply)) {
|
||||
console.warn(`[chat] reponse finale rejetee (fuite/degeneree), fallback utilise: ${reply}`)
|
||||
reply = FALLBACK_REPLY
|
||||
}
|
||||
logger.debug(`[chat] reponse finale: ${reply}`)
|
||||
history.push({ role: 'assistant', content: reply })
|
||||
history.splice(0, Math.max(0, history.length - MAX_HISTORY_MESSAGES))
|
||||
return reply
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
// Marqueurs pour detecter une fuite de "boilerplate" interne du modele (constate en test reel :
|
||||
// "Use the results below to formulate an answer..." prononce a voix haute au lieu d'une vraie
|
||||
// reponse de Max) : present si ca ressemble a de l'anglais generique sans aucun mot-outil francais.
|
||||
const ENGLISH_LEAK_MARKERS =
|
||||
/\b(the|unless|below|formulate|additional|information|needed|answer the|user question)\b/i
|
||||
const FRENCH_MARKERS =
|
||||
/\b(le|la|les|de|des|et|un|une|est|tu|je|pour|dans|avec|qui|que|ce|ton|ta)\b/i
|
||||
|
||||
export function containsLeakedBoilerplate(text: string): boolean {
|
||||
return ENGLISH_LEAK_MARKERS.test(text) && !FRENCH_MARKERS.test(text)
|
||||
}
|
||||
|
||||
/**
|
||||
* Le modele peut "decrocher" et renvoyer un texte corrompu (constate en test reel : " foia" +
|
||||
* caracteres chinois/bengalis a la place d'une vraie phrase). Detecte via la part de caracteres
|
||||
* non-latins/non-imprimables dans le texte.
|
||||
*/
|
||||
export function isDegenerateText(text: string): boolean {
|
||||
const trimmed = text.trim()
|
||||
if (!trimmed) return false
|
||||
let latinCount = 0
|
||||
for (const char of trimmed) {
|
||||
const code = char.codePointAt(0) ?? 0
|
||||
if ((code >= 0x20 && code <= 0x7e) || (code >= 0xa0 && code <= 0x24f)) latinCount++
|
||||
}
|
||||
return latinCount / trimmed.length < 0.7 || (trimmed.length > 15 && latinCount < 8)
|
||||
}
|
||||
|
||||
export const SPEECH_FALLBACK_REPLY =
|
||||
"Voila, j'ai bien avance avec toi sur ce sujet. Dis-moi si tu veux qu'on continue."
|
||||
|
||||
/**
|
||||
* A appliquer sur tout texte destine a etre prononce a voix haute (voir voice-turn dans
|
||||
* src/main/index.ts) avant de l'envoyer a la synthese vocale : remplace une reponse
|
||||
* fuyante/corrompue par une phrase de secours plutot que de la lire telle quelle a l'utilisateur.
|
||||
*/
|
||||
export function sanitizeForSpeech(text: string): string {
|
||||
if (containsLeakedBoilerplate(text) || isDegenerateText(text)) {
|
||||
return SPEECH_FALLBACK_REPLY
|
||||
}
|
||||
return text
|
||||
}
|
||||
@@ -3,7 +3,7 @@ import { app, session, shell, BrowserWindow, ipcMain } from 'electron'
|
||||
import { join } from 'path'
|
||||
import { electronApp, optimizer, is } from '@electron-toolkit/utils'
|
||||
import { transcribeAudio, synthesizeSpeech } from './ai/elevenlabs'
|
||||
import { getAssistantReply } from './ai/openrouter'
|
||||
import { sanitizeForSpeech } from './ai/speechSafety'
|
||||
import { setMainWindow } from './windowBridge'
|
||||
import { stripWakeWord } from './wakeWord'
|
||||
import { loginAndLoadKeys } from './auth/authClient'
|
||||
@@ -179,10 +179,23 @@ app
|
||||
}
|
||||
}
|
||||
|
||||
// Partage entre le chat texte (sessions:route-message) et la voix (voice-turn) : "learn" est
|
||||
// le seul cas ou une session existe reellement (nouvelle ou poursuivie), cote serveur, quel
|
||||
// que soit le canal d'entree (routeur d'intention, voir docs/Max_System_Prompt.md).
|
||||
// openStepperWindow() est idempotent (singleton).
|
||||
async function handleRouteMessageResult(result: RouteMessageResponse): Promise<void> {
|
||||
if (result.type === 'learn' && result.sessionId !== undefined) {
|
||||
openStepperWindow()
|
||||
const session = await getSession(result.sessionId)
|
||||
broadcastSessionStatus(session.status)
|
||||
}
|
||||
}
|
||||
|
||||
ipcMain.handle(
|
||||
'voice-turn',
|
||||
async (_event, inputAudio: ArrayBuffer, mimeType: string): Promise<VoiceTurnResult> => {
|
||||
try {
|
||||
requireLoggedIn()
|
||||
const start = performance.now()
|
||||
const transcript = await transcribeAudio(Buffer.from(inputAudio), mimeType)
|
||||
const afterStt = performance.now()
|
||||
@@ -194,8 +207,12 @@ app
|
||||
return { ok: 'ignored', transcript }
|
||||
}
|
||||
|
||||
const reply = await getAssistantReply(command)
|
||||
// Meme point d'entree que le chat texte (POST /sessions/messages, routeur d'intention
|
||||
// inclus) : une seule personnalite, un seul pipeline, quel que soit le canal d'entree.
|
||||
const routed = await routeMessage(command)
|
||||
const afterChat = performance.now()
|
||||
const reply = sanitizeForSpeech(routed.reply)
|
||||
await handleRouteMessageResult(routed)
|
||||
const speech = await synthesizeSpeech(reply)
|
||||
const afterTts = performance.now()
|
||||
|
||||
@@ -277,14 +294,7 @@ app
|
||||
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)
|
||||
}
|
||||
await handleRouteMessageResult(result)
|
||||
return result
|
||||
}
|
||||
)
|
||||
|
||||
@@ -1,90 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { setCurrentUserEmail, clearSession } from '../../src/main/auth/session'
|
||||
|
||||
vi.mock('@electron-toolkit/utils', () => ({ is: { dev: false } }))
|
||||
|
||||
const { getAssistantReply } = await import('../../src/main/ai/openrouter')
|
||||
|
||||
function okResponse(body: unknown): Response {
|
||||
return { ok: true, json: () => Promise.resolve(body) } as Response
|
||||
}
|
||||
|
||||
function textMessage(content: string): unknown {
|
||||
return { choices: [{ message: { role: 'assistant', content } }] }
|
||||
}
|
||||
|
||||
describe('getAssistantReply()', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
vi.stubGlobal('fetch', vi.fn())
|
||||
process.env.OPENROUTER_API_KEY = 'test-key'
|
||||
setCurrentUserEmail('test@example.com')
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
clearSession()
|
||||
})
|
||||
|
||||
it('should throw when the API key is missing', async () => {
|
||||
delete process.env.OPENROUTER_API_KEY
|
||||
await expect(getAssistantReply('Bonjour')).rejects.toThrow(/OPENROUTER_API_KEY/)
|
||||
})
|
||||
|
||||
it('should return the assistant text reply when the API responds successfully', async () => {
|
||||
vi.mocked(fetch).mockResolvedValue(okResponse(textMessage('Bonjour, comment puis-je aider ?')))
|
||||
const reply = await getAssistantReply('Salut Max')
|
||||
expect(reply).toBe('Bonjour, comment puis-je aider ?')
|
||||
})
|
||||
|
||||
it('should transparently fall back to the secondary model when the primary one errors out', async () => {
|
||||
vi.mocked(fetch)
|
||||
.mockResolvedValueOnce({
|
||||
ok: false,
|
||||
status: 503,
|
||||
text: () => Promise.resolve('unavailable')
|
||||
} as Response)
|
||||
.mockResolvedValueOnce(okResponse(textMessage('Reponse du modele de secours.')))
|
||||
|
||||
const reply = await getAssistantReply('question')
|
||||
expect(reply).toBe('Reponse du modele de secours.')
|
||||
})
|
||||
|
||||
it('should treat a 200 response with no choices as a failure and try the other model', async () => {
|
||||
vi.mocked(fetch)
|
||||
.mockResolvedValueOnce(okResponse({}))
|
||||
.mockResolvedValueOnce(okResponse(textMessage('Ca marche quand meme.')))
|
||||
|
||||
const reply = await getAssistantReply('question')
|
||||
expect(reply).toBe('Ca marche quand meme.')
|
||||
})
|
||||
|
||||
it('should throw a clear error when both models fail', async () => {
|
||||
vi.mocked(fetch).mockResolvedValue({
|
||||
ok: false,
|
||||
status: 500,
|
||||
text: () => Promise.resolve('panne totale')
|
||||
} as Response)
|
||||
|
||||
await expect(getAssistantReply('question')).rejects.toThrow(/Aucun modele disponible/)
|
||||
})
|
||||
|
||||
it('should replace a leaked English boilerplate reply with the safe fallback message', async () => {
|
||||
vi.mocked(fetch).mockResolvedValue(
|
||||
okResponse(
|
||||
textMessage(
|
||||
'Use the results below to formulate an answer to the user question with additional information needed'
|
||||
)
|
||||
)
|
||||
)
|
||||
const reply = await getAssistantReply('question')
|
||||
expect(reply).toMatch(/bien avance avec toi/)
|
||||
})
|
||||
|
||||
it('should replace a degenerate (non-Latin) reply with the safe fallback message', async () => {
|
||||
vi.mocked(fetch).mockResolvedValue(
|
||||
okResponse(textMessage('的问题是什么呢我不知道该怎么办才好呢'))
|
||||
)
|
||||
const reply = await getAssistantReply('question')
|
||||
expect(reply).toMatch(/bien avance avec toi/)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,55 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import {
|
||||
containsLeakedBoilerplate,
|
||||
isDegenerateText,
|
||||
sanitizeForSpeech,
|
||||
SPEECH_FALLBACK_REPLY
|
||||
} from '../../src/main/ai/speechSafety'
|
||||
|
||||
describe('containsLeakedBoilerplate()', () => {
|
||||
it('should detect leaked English model boilerplate with no French words', () => {
|
||||
expect(
|
||||
containsLeakedBoilerplate(
|
||||
'Use the results below to formulate an answer to the user question with additional information needed'
|
||||
)
|
||||
).toBe(true)
|
||||
})
|
||||
|
||||
it('should not flag a normal French reply', () => {
|
||||
expect(containsLeakedBoilerplate('Bonjour, comment puis-je aider ?')).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('isDegenerateText()', () => {
|
||||
it('should detect a non-Latin corrupted reply', () => {
|
||||
expect(isDegenerateText('的问题是什么呢我不知道该怎么办才好呢')).toBe(true)
|
||||
})
|
||||
|
||||
it('should not flag a normal French reply', () => {
|
||||
expect(isDegenerateText('Bonjour, comment puis-je aider ?')).toBe(false)
|
||||
})
|
||||
|
||||
it('should not flag an empty string', () => {
|
||||
expect(isDegenerateText('')).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('sanitizeForSpeech()', () => {
|
||||
it('should replace a leaked English boilerplate reply with the safe fallback message', () => {
|
||||
expect(
|
||||
sanitizeForSpeech(
|
||||
'Use the results below to formulate an answer to the user question with additional information needed'
|
||||
)
|
||||
).toBe(SPEECH_FALLBACK_REPLY)
|
||||
})
|
||||
|
||||
it('should replace a degenerate (non-Latin) reply with the safe fallback message', () => {
|
||||
expect(sanitizeForSpeech('的问题是什么呢我不知道该怎么办才好呢')).toBe(SPEECH_FALLBACK_REPLY)
|
||||
})
|
||||
|
||||
it('should return the original text when it is a normal French reply', () => {
|
||||
expect(sanitizeForSpeech('Bonjour, comment puis-je aider ?')).toBe(
|
||||
'Bonjour, comment puis-je aider ?'
|
||||
)
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user