refactor: move app code into Max Avatar/ subfolder (monorepo prep for backend)

Step 1 of adding a backend proxy server (API keys held server-side instead
of shipped in the installer). Moves everything app-specific into
"Max Avatar/" via git mv (preserves history): src/, tests/, scripts/,
assets/, build/, resources/, package.json/-lock.json, electron-builder.yml,
electron.vite.config.ts, eslint.config.mjs, playwright.config.ts,
vitest.config.mts, sonar-project.properties, tsconfig*.json, Dockerfile,
.editorconfig/.env*/.gitignore/.prettier*.

CLAUDE.md, README.md, docs/, .claude/, .gitea/, .husky/, .vscode/, and the
docker-compose files stay at the repo root, since they'll apply to both the
app and the future backend.

No application code needed changes (all its internal paths are relative to
its own tree). Adjusted what referenced the old root from outside:
- .husky/pre-commit: cd into "Max Avatar" before lint-staged
- .gitea/workflows/*.yml: working-directory + cache-dependency-path +
  artifact paths + SonarQube projectBaseDir
- docker-compose.yml: build context -> ./Max Avatar
- Max Avatar/Dockerfile: node:20-alpine -> node:24-alpine (same node:sqlite
  issue already fixed elsewhere, never applied here before)
- .vscode/launch.json, README.md: updated paths/instructions

Verified from Max Avatar/ after the move: npm ci, typecheck, lint,
test:coverage (473/473, same coverage numbers), build, and dev all work
unchanged.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
william
2026-10-31 12:15:30 +01:00
co-authored by Claude Sonnet 5
parent 60e2fb26af
commit 1c2f002eb3
224 changed files with 135 additions and 18 deletions
+260
View File
@@ -0,0 +1,260 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
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 getSkillsForMode = vi.fn(() => currentSkills)
vi.mock('../../src/main/skills', () => ({ getSkillsForMode }))
let currentMode: 'basic' | 'coach' | 'assistant' = 'basic'
const getMode = vi.fn(() => currentMode)
vi.mock('../../src/main/mode/modeState', () => ({ getMode }))
const getMemoriesText = vi.fn(() => '')
const getMood = vi.fn(() => 0)
vi.mock('../../src/main/memory/store', () => ({ getMemoriesText, 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 getSubjectLevel = vi.fn((): string | null => null)
vi.mock('../../src/main/coach/coachStore', () => ({ getSubjectLevel }))
const recordCourseBuildTool = vi.fn()
const clearCourseBuild = vi.fn()
vi.mock('../../src/main/coach/courseBuildStepper', () => ({
recordCourseBuildTool,
clearCourseBuild
}))
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 = []
currentMode = 'basic'
getSubjectLevel.mockReturnValue(null)
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(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)
})
describe('getAssistantReply() — garde-fous du pipeline Coach', () => {
beforeEach(() => {
vi.clearAllMocks()
vi.stubGlobal('fetch', vi.fn())
currentMode = 'coach'
getSubjectLevel.mockReturnValue(null)
process.env.OPENROUTER_API_KEY = 'test-key'
currentSkills = [
{
name: 'research_topic',
description: '',
parameters: {},
execute: vi.fn(async () => 'Recherche enregistree.')
}
]
})
it('should force a retry toward generate_course_plan when research_topic was called but not the plan', async () => {
const executeGeneratePlan = vi.fn(async () => 'Plan enregistre.')
currentSkills.push({
name: 'generate_course_plan',
description: '',
parameters: {},
execute: executeGeneratePlan
})
// Des que le nudge a ete pousse une fois (verifie par l'appel ci-dessous), on simule que le
// niveau vient d'etre enregistre pour ne pas enchainer sur tous les nudges suivants du pipeline
// (plan -> contenu -> evaluation) : seul le declenchement de CE nudge precis est teste ici.
getSubjectLevel.mockImplementation(() =>
executeGeneratePlan.mock.calls.length > 0 ? 'debutant' : null
)
vi.mocked(fetch)
.mockResolvedValueOnce(okResponse(toolCallMessage('research_topic', { subject: 'algebre' })))
.mockResolvedValueOnce(okResponse(textMessage("J'ai fini pour l'instant.")))
.mockResolvedValueOnce(
okResponse(toolCallMessage('generate_course_plan', { subject: 'algebre' }))
)
.mockResolvedValueOnce(okResponse(textMessage('Plan en cours.')))
const reply = await getAssistantReply('apprends-moi algebre')
expect(executeGeneratePlan).toHaveBeenCalled()
expect(reply).toBe('Plan en cours.')
})
it('should force a retry when the model announces an action at round 0 without calling any tool', async () => {
// "subject" est volontairement omis : on isole ici le garde-fou "annonce au round 0", pas celui
// du pipeline (recherche -> plan), qui se redeclencherait sinon des que trackedSubject est fixe.
vi.mocked(fetch)
.mockResolvedValueOnce(
okResponse(
textMessage("Je vais t'apprendre la trigonometrie ! Commencons par une recherche.")
)
)
.mockResolvedValueOnce(okResponse(toolCallMessage('research_topic', {})))
.mockResolvedValueOnce(okResponse(textMessage('Recherche terminee, module prepare.')))
const reply = await getAssistantReply('apprends-moi la trigonometrie')
expect(reply).toBe('Recherche terminee, module prepare.')
})
})