Files
ForgeBase/Max Avatar/tests/unit/openrouter.test.ts
T
william 83043b5819 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 <noreply@anthropic.com>
2026-10-31 19:27:11 +01:00

189 lines
6.7 KiB
TypeScript

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 } }))
interface FakeSkill {
name: string
description: string
parameters: object
execute: (args: Record<string, unknown>) => Promise<string>
}
let currentSkills: FakeSkill[] = []
const loadSkills = vi.fn(() => currentSkills)
vi.mock('../../src/main/skills', () => ({ loadSkills }))
const getMood = vi.fn(() => 0)
vi.mock('../../src/main/memory/store', () => ({ getMood }))
const synthesizeSpeech = vi.fn(async () => Buffer.from([1, 2, 3]))
vi.mock('../../src/main/ai/elevenlabs', () => ({ synthesizeSpeech }))
const sendToRenderer = vi.fn()
vi.mock('../../src/main/windowBridge', () => ({ sendToRenderer }))
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 } }] }
}
function toolCallMessage(name: string, args: Record<string, unknown>, content = ''): unknown {
return {
choices: [
{
message: {
role: 'assistant',
content,
tool_calls: [
{ id: 'call-1', type: 'function', function: { name, arguments: JSON.stringify(args) } }
]
}
}
]
}
}
describe('getAssistantReply()', () => {
beforeEach(() => {
vi.clearAllMocks()
vi.stubGlobal('fetch', vi.fn())
currentSkills = []
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 a direct text reply when the model calls no tool', 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 execute a requested tool and use its result for the follow-up reply', async () => {
const execute = vi.fn(async () => 'Notepad ouvert.')
currentSkills = [
{ name: 'open_notepad', description: 'ouvre notepad', parameters: {}, execute }
]
vi.mocked(fetch)
.mockResolvedValueOnce(okResponse(toolCallMessage('open_notepad', {})))
.mockResolvedValueOnce(okResponse(textMessage("C'est fait, le bloc-notes est ouvert.")))
const reply = await getAssistantReply('ouvre le bloc-notes')
expect(execute).toHaveBeenCalled()
expect(reply).toBe("C'est fait, le bloc-notes est ouvert.")
})
it('should report an unknown/unauthorized tool without crashing', async () => {
currentSkills = []
vi.mocked(fetch)
.mockResolvedValueOnce(okResponse(toolCallMessage('outil_interdit', {})))
.mockResolvedValueOnce(okResponse(textMessage('Compris.')))
const reply = await getAssistantReply('fais un truc interdit')
expect(reply).toBe('Compris.')
})
it('should report a tool execution failure without crashing the turn', async () => {
const execute = vi.fn(async () => {
throw new Error('disque plein')
})
currentSkills = [
{ name: 'create_file', description: 'cree un fichier', parameters: {}, execute }
]
vi.mocked(fetch)
.mockResolvedValueOnce(okResponse(toolCallMessage('create_file', { name: 'test' })))
.mockResolvedValueOnce(okResponse(textMessage('Echec note.')))
const reply = await getAssistantReply('cree un fichier')
expect(reply).toBe('Echec note.')
})
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 recover a fake tool call written as plain text instead of real tool_calls', async () => {
const execute = vi.fn(async () => 'Notepad ouvert.')
currentSkills = [
{ name: 'open_notepad', description: 'ouvre notepad', parameters: {}, execute }
]
vi.mocked(fetch)
.mockResolvedValueOnce(okResponse(textMessage('open_notepad\n{"text": "bonjour"}')))
.mockResolvedValueOnce(okResponse(textMessage('Fait.')))
const reply = await getAssistantReply('ouvre le bloc-notes')
expect(execute).toHaveBeenCalled()
expect(reply).toBe('Fait.')
})
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/)
})
it('should throw once the tool-call round limit is exceeded', async () => {
const execute = vi.fn(async () => 'ok')
currentSkills = [{ name: 'loop_tool', description: 'boucle', parameters: {}, execute }]
vi.mocked(fetch).mockImplementation(async () => okResponse(toolCallMessage('loop_tool', {})))
await expect(getAssistantReply('boucle indefiniment')).rejects.toThrow(/Trop d'appels d'outils/)
}, 20000)
})