feat(generation): score articles with selected relevance model (#48)
This commit is contained in:
@ -2,7 +2,7 @@
|
||||
|
||||
The supervisor requires Linux `/proc`, child-subreaper support and Python 3 (standard library only). Run `make test-e2e` from the project root after `make deps` and `make test-postgres`. The latter prepares the pinned embedded-postgres CLI v2.0.1/PostgreSQL 16.15.1 cache. Install Playwright's pinned Firefox beforehand if it is not already cached (`cd frontend && npx playwright install firefox`). These preparation steps may require network access; the E2E runner itself uses offline caches and never installs dependencies.
|
||||
|
||||
The runner builds the dedicated `backend/cmd/e2e` executable, starts a disposable `tradarr_e2e` database, applies the real migrations, and refuses a nonempty database. It ignores inherited application/test database URLs, chooses loopback ports, and bootstraps a reserved disposable admin. Exactly one fixture source is enabled. The catalogue contains one explicit fake summary model. The new user selects it in the real preferences UI; new accounts have no default selection. The injected Laya ranker and summary provider are separate test doubles, with no concrete retrieval adapter instantiated and no legacy role fallback. Production uses the same `internal/server` constructor with its existing real composition and scheduler enabled.
|
||||
The runner builds the dedicated `backend/cmd/e2e` executable, starts a disposable `tradarr_e2e` database, applies the real migrations, and refuses a nonempty database. It ignores inherited application/test database URLs, chooses loopback ports, and bootstraps a reserved disposable admin. Exactly one fixture source is enabled. The catalogue contains the fake-summary synthesis model and a separate ollama/llama3 ranking model with native JSON schema capability. The new user selects both independently in the real preferences UI; new accounts have no default selection. The journey verifies both saved model IDs and the model actually called by the scoring fake. The injected Laya ranker and summary provider are separate test doubles, with no concrete retrieval adapter instantiated and no legacy role fallback. Production uses the same `internal/server` constructor with its existing real composition and scheduler enabled.
|
||||
|
||||
OpenFIGI, an Ollama-compatible fake Laya and a fake scraper share a loopback HTTP service with `/audit` counters and structured call events. The ranking fake extracts the real candidate UUID from the request prompt and returns it in `ranked_article_ids`; the browser assertion checks that actual UUID in audit events against the saved outcome. No hard-coded fixture ID selects a candidate.
|
||||
|
||||
|
||||
@ -36,9 +36,11 @@ function restoreAISeed(stack) {
|
||||
}
|
||||
const providerID = '00000000-0000-0000-0000-000000001202'
|
||||
const modelID = stack.fixtures.summaryModelID
|
||||
const rankingModelID = stack.fixtures.rankingModelID
|
||||
const rankingModelName = stack.fixtures.rankingModelName.replaceAll("'", "''")
|
||||
const fakeURL = stack.layaFakeUrl.replaceAll("'", "''")
|
||||
const sql = `BEGIN;
|
||||
DELETE FROM ai_provider_models WHERE id <> '${modelID}';
|
||||
DELETE FROM ai_provider_models WHERE id NOT IN ('${modelID}', '${rankingModelID}');
|
||||
DELETE FROM ai_providers WHERE id <> '${providerID}';
|
||||
INSERT INTO ai_providers(id,name,model,endpoint,is_active)
|
||||
VALUES('${providerID}','ollama','fake-laya','${fakeURL}',true)
|
||||
@ -46,6 +48,9 @@ function restoreAISeed(stack) {
|
||||
INSERT INTO ai_provider_models(id,provider_id,model,enabled)
|
||||
VALUES('${modelID}','${providerID}','fake-summary',true)
|
||||
ON CONFLICT(id) DO UPDATE SET provider_id=EXCLUDED.provider_id,model=EXCLUDED.model,enabled=true;
|
||||
INSERT INTO ai_provider_models(id,provider_id,model,enabled)
|
||||
VALUES('${rankingModelID}','${providerID}','${rankingModelName}',true)
|
||||
ON CONFLICT(id) DO UPDATE SET provider_id=EXCLUDED.provider_id,model=EXCLUDED.model,enabled=true;
|
||||
COMMIT;`
|
||||
execFileSync(stack.psqlPath, ['--no-psqlrc', '--set', 'ON_ERROR_STOP=1', '--command', sql], {
|
||||
env,
|
||||
@ -92,7 +97,27 @@ test('bug #18: admin AI page consumes current empty and configured API payloads'
|
||||
id: stack.fixtures.summaryModelID,
|
||||
provider_id: '00000000-0000-0000-0000-000000001202',
|
||||
provider: 'ollama', model: 'fake-summary', enabled: true,
|
||||
}), expect.objectContaining({
|
||||
id: stack.fixtures.rankingModelID,
|
||||
provider_id: '00000000-0000-0000-0000-000000001202',
|
||||
provider: 'ollama', model: stack.fixtures.rankingModelName, enabled: true,
|
||||
ranking_capability: stack.fixtures.rankingCapability,
|
||||
})])
|
||||
const summaryCatalog = await responseData(request, api('/me/summary-models?role=summary'), token)
|
||||
const defaultCatalog = await responseData(request, api('/me/summary-models'), token)
|
||||
expect(summaryCatalog.json.data).toEqual(defaultCatalog.json.data)
|
||||
expect(summaryCatalog.json.data).toEqual([
|
||||
expect.objectContaining({ id: stack.fixtures.summaryModelID, provider: 'ollama', model: 'fake-summary', ranking_capability: expect.objectContaining({ selectable: false }) }),
|
||||
expect.objectContaining({ id: stack.fixtures.rankingModelID, provider: 'ollama', model: stack.fixtures.rankingModelName }),
|
||||
])
|
||||
const rankingCatalog = await responseData(request, api('/me/summary-models?role=ranking'), token)
|
||||
expect(rankingCatalog.json.data).toEqual([expect.objectContaining({
|
||||
id: stack.fixtures.rankingModelID, provider: 'ollama', model: stack.fixtures.rankingModelName,
|
||||
ranking_capability: stack.fixtures.rankingCapability,
|
||||
})])
|
||||
expect(rankingCatalog.json.data.map(model => model.id)).not.toContain(stack.fixtures.summaryModelID)
|
||||
const invalidRole = await responseData(request, api('/me/summary-models?role=unknown'), token, 400)
|
||||
expect(invalidRole.json.error).toBe('invalid model role')
|
||||
expect(configuredOllama.json).toHaveProperty('error')
|
||||
|
||||
let emptyCounts
|
||||
@ -101,8 +126,11 @@ test('bug #18: admin AI page consumes current empty and configured API payloads'
|
||||
let reconfiguredModelData
|
||||
let providerID
|
||||
try {
|
||||
// Both seeded rows are unselected by the bootstrap admin and may be
|
||||
// Both seeded models are unselected by the bootstrap admin and may be
|
||||
// removed safely inside this disposable database.
|
||||
expect((await request.delete(api(`/admin/ai-models/${stack.fixtures.rankingModelID}`), {
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
})).status()).toBe(204)
|
||||
expect((await request.delete(api(`/admin/ai-models/${stack.fixtures.summaryModelID}`), {
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
})).status()).toBe(204)
|
||||
|
||||
@ -68,12 +68,16 @@ export function readStackManifest() {
|
||||
if (!manifest.bootstrapAdmin?.email || !manifest.bootstrapAdmin?.password) {
|
||||
throw new Error('E2E fake stack manifest must provide disposable bootstrap admin credentials.')
|
||||
}
|
||||
for (const field of ['companyQuery', 'companyID', 'companyName', 'companySymbol', 'companyFIGI', 'summaryModelID', 'summarySentinel', 'articleTitle', 'articleURL', 'articleContent', 'candidateID']) {
|
||||
for (const field of ['companyQuery', 'companyID', 'companyName', 'companySymbol', 'companyFIGI', 'summaryModelID', 'rankingModelID', 'rankingModelName', 'summarySentinel', 'articleTitle', 'articleURL', 'articleContent', 'candidateID']) {
|
||||
if (typeof manifest.fixtures?.[field] !== 'string' || !manifest.fixtures[field]) {
|
||||
throw new Error(`E2E fake stack manifest is missing fixtures.${field}.`)
|
||||
}
|
||||
}
|
||||
|
||||
if (manifest.fixtures.rankingCapability?.selectable !== true || manifest.fixtures.rankingCapability?.mode !== 'json_schema') {
|
||||
throw new Error('E2E fake stack manifest must provide a compatible structured ranking capability.')
|
||||
}
|
||||
|
||||
const databaseURL = new URL(manifest.databaseUrl)
|
||||
const databaseName = decodeURIComponent(databaseURL.pathname.replace(/^\//, ''))
|
||||
if (!/(^|[-_])(e2e|test)([-_]|$)/i.test(databaseName)) {
|
||||
|
||||
@ -105,9 +105,23 @@ test('admin creates a user who follows a fake company and generates a private su
|
||||
await page.goto(new URL('/preferences', baseURL).href)
|
||||
await page.getByLabel('Langue des synthèses').selectOption('en')
|
||||
await page.getByLabel('Modèle de synthèse', { exact: true }).selectOption(fixture.summaryModelID)
|
||||
const ranking = page.getByLabel('Modèle de classement de pertinence', { exact: true })
|
||||
await expect(ranking).toHaveValue('')
|
||||
await expect(ranking.getByRole('option', { name: `ollama · ${fixture.rankingModelName}`, exact: true })).toHaveAttribute('value', fixture.rankingModelID)
|
||||
await expect(ranking.locator(`option[value="${fixture.summaryModelID}"]`)).toHaveCount(0)
|
||||
expect(fixture.rankingCapability).toMatchObject({ selectable: true, mode: 'json_schema' })
|
||||
await ranking.selectOption(fixture.rankingModelID)
|
||||
await page.getByLabel('Informations utilisées par Laya pour classer les articles').selectOption('title_content')
|
||||
await page.getByRole('button', { name: 'Enregistrer' }).click()
|
||||
await expect(page.getByRole('status')).toHaveText('Préférences enregistrées.')
|
||||
const token = await page.evaluate(() => localStorage.getItem('token'))
|
||||
const response = await request.get(new URL('/api/me/preferences', stack.apiUrl).href, {
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
})
|
||||
expect(response.status()).toBe(200)
|
||||
const { data: savedPreferences } = await response.json()
|
||||
expect(savedPreferences.summary_model_id).toBe(fixture.summaryModelID)
|
||||
expect(savedPreferences.ranking_model_id).toBe(fixture.rankingModelID)
|
||||
})
|
||||
|
||||
await test.step('fake scraper and Laya produce an aggregate summary', async () => {
|
||||
@ -145,6 +159,10 @@ test('admin creates a user who follows a fake company and generates a private su
|
||||
expect(events.companyResolutions).toBeGreaterThan(0)
|
||||
expect(events.scraperCalls).toBeGreaterThan(0)
|
||||
expect(events.layaRankingCalls).toBeGreaterThan(0)
|
||||
expect(events.relevanceScoringCalls).toBeGreaterThan(0)
|
||||
const scoringCalls = events.events.filter(event => event.kind === 'relevanceScoringCalls')
|
||||
expect(scoringCalls.length).toBeGreaterThan(0)
|
||||
expect(scoringCalls.every(event => event.model === fixture.rankingModelName)).toBeTruthy()
|
||||
expect(events.layaSummaryCalls).toBeGreaterThan(0)
|
||||
const token = await page.evaluate(() => localStorage.getItem('token'))
|
||||
const history = await request.get(new URL('/api/summaries/generations', stack.apiUrl).href, {
|
||||
|
||||
@ -11,12 +11,14 @@ export interface SummaryModelOption { id: string; provider: string; model: strin
|
||||
|
||||
export interface UserPreferences {
|
||||
summary_prompt_token_budget?: number
|
||||
ranking_model_id?: string | null
|
||||
summary_model_id?: string | null
|
||||
language: 'fr' | 'en'
|
||||
ranking_mode: 'title' | 'title_content'
|
||||
}
|
||||
|
||||
export const preferencesApi = {
|
||||
listRankingModels: () => api.get<SummaryModelOption[]>('/me/summary-models?role=ranking'),
|
||||
listSummaryModels: () => api.get<SummaryModelOption[]>('/me/summary-models'),
|
||||
get: () => api.get<UserPreferences>('/me/preferences'),
|
||||
update: (preferences: UserPreferences) => api.put<UserPreferences>('/me/preferences', preferences),
|
||||
|
||||
@ -45,6 +45,8 @@ export function generationFailureMessage(code?: string): string {
|
||||
const labels: Record<string, [string, string]> = {
|
||||
summary_fixed_context_budget_exceeded: ['Le contexte fixe dépasse le plafond du prompt. Augmentez-le dans Mes préférences.', 'The fixed context exceeds the prompt budget. Increase it in My preferences.'],
|
||||
no_articles_fit_prompt_budget: ['Aucun article ne tient dans le plafond du prompt. Augmentez-le dans Mes préférences.', 'No article fits within the prompt budget. Increase it in My preferences.'],
|
||||
ranking_model_incompatible: ['Le modèle est incompatible avec le classement : sa sortie JSON structurée n’est pas prise en charge. Choisissez un modèle compatible dans Mes préférences.', 'The model is incompatible with ranking: structured JSON output is unsupported. Choose a compatible model in My preferences.'],
|
||||
ranking_model_unavailable: ['Le modèle de classement est absent ou indisponible. Choisissez un modèle dans Mes préférences.', 'The ranking model is missing or unavailable. Choose a model in My preferences.'],
|
||||
summary_model_rejected: ['Le modèle demandé est indisponible ou refusé.', 'The requested model is unavailable or was rejected.'],
|
||||
summary_provider_limit: ['La limite du fournisseur a été dépassée.', 'The provider limit was exceeded.'],
|
||||
summary_auth_failed: ['Vérifiez la configuration du fournisseur avec votre administrateur.', 'Check the provider configuration with your administrator.'],
|
||||
|
||||
@ -150,6 +150,7 @@ export function Dashboard() {
|
||||
return (
|
||||
<div className="p-4 md:p-6 space-y-6">
|
||||
{lastFailure !== null && <p role="alert">{generationFailureMessage(lastFailure)}</p>}
|
||||
{(lastFailure === 'ranking_model_unavailable' || lastFailure === 'ranking_model_incompatible') && <a href="/preferences" className="text-primary underline">Mes préférences</a>}
|
||||
{latestOutcome && latestSummaryId && latestSummaryId !== current?.id && <PromptBudgetRemoval outcome={latestOutcome} />}
|
||||
{/* Generating banner */}
|
||||
{generating && !uncertain && (
|
||||
|
||||
@ -9,6 +9,7 @@ import { ApiError } from '@/api/client'
|
||||
import { Appearance } from '@/components/Appearance'
|
||||
|
||||
export function Preferences() {
|
||||
const [rankingModels, setRankingModels] = useState<SummaryModelOption[]>([])
|
||||
const [models, setModels] = useState<SummaryModelOption[]>([])
|
||||
const [preferences, setPreferences] = useState<UserPreferences | null>(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
@ -19,8 +20,8 @@ export function Preferences() {
|
||||
const [saved, setSaved] = useState(false)
|
||||
|
||||
const load = useCallback(() => {
|
||||
return Promise.all([preferencesApi.get(), preferencesApi.listSummaryModels()])
|
||||
.then(([value, catalog]) => { setPreferences(value); setBudget(String(value.summary_prompt_token_budget ?? 250000)); setModels(catalog ?? []) })
|
||||
return Promise.all([preferencesApi.get(), preferencesApi.listSummaryModels(), preferencesApi.listRankingModels()])
|
||||
.then(([value, catalog, rankingCatalog]) => { setPreferences(value); setBudget(String(value.summary_prompt_token_budget ?? 250000)); setModels(catalog ?? []); setRankingModels(rankingCatalog ?? []) })
|
||||
.catch(() => setError('Impossible de charger vos préférences. Réessayez.'))
|
||||
.finally(() => setLoading(false))
|
||||
}, [])
|
||||
@ -40,7 +41,11 @@ export function Preferences() {
|
||||
setPreferences(await preferencesApi.update({ ...preferences, summary_prompt_token_budget: tokens }))
|
||||
setSaved(true)
|
||||
} catch (error) {
|
||||
if (error instanceof ApiError && error.status === 400 && error.message === 'invalid_prompt_budget') {
|
||||
if (error instanceof ApiError && error.message === 'ranking_model_incompatible') {
|
||||
setError('Ce modèle est incompatible avec le classement : sa sortie JSON structurée n’est pas prise en charge. Choisissez un modèle compatible. Il reste disponible pour la synthèse. Vos choix sont conservés.')
|
||||
} else if (error instanceof ApiError && error.message === 'ranking_model_unavailable') {
|
||||
setError('Le modèle de classement sélectionné n’est plus disponible. Choisissez un autre modèle. Vos choix sont conservés.')
|
||||
} else if (error instanceof ApiError && error.status === 400 && error.message === 'invalid_prompt_budget') {
|
||||
setBudgetError('Saisissez un entier entre 1 et 2 000 000 tokens.')
|
||||
} else { setError('Impossible d’enregistrer vos préférences. Vos choix sont conservés. Réessayez.') }
|
||||
}
|
||||
@ -73,6 +78,18 @@ export function Preferences() {
|
||||
<p id="model-help" className="text-sm text-muted-foreground">Ce choix personnel s’applique aux prochaines synthèses manuelles et planifiées. Aucun autre modèle ne sera choisi automatiquement.</p>
|
||||
{models.length === 0 ? <p role="status">Aucun modèle disponible. Contactez votre administrateur.</p> : !preferences.summary_model_id ? <p>Choisissez un modèle pour pouvoir générer une synthèse.</p> : !models.some(model => model.id === preferences.summary_model_id) && <p role="alert">Le modèle sélectionné n’est plus disponible. Choisissez un autre modèle.</p>}
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="preferences-ranking-model">Modèle de classement de pertinence</Label>
|
||||
<Select id="preferences-ranking-model" aria-describedby="ranking-model-help ranking-model-status" value={preferences.ranking_model_id ?? ''} disabled={saving} onChange={e => change({ ranking_model_id: e.target.value || null })}>
|
||||
<option value="">Choisir un modèle de classement</option>
|
||||
{preferences.ranking_model_id && !rankingModels.some(model => model.id === preferences.ranking_model_id) && <option value={preferences.ranking_model_id} disabled>Modèle de classement sélectionné indisponible</option>}
|
||||
{rankingModels.map(model => <option key={model.id} value={model.id}>{model.provider} · {model.model}</option>)}
|
||||
</Select>
|
||||
<p id="ranking-model-help" className="text-sm text-muted-foreground">Le classement est fondé sur le titre et les entreprises suivies. Tous les articles sont notés, sans filtrage. Les étapes suivantes les priorisent par pertinence décroissante, puis par date en cas d’égalité. Ce choix est distinct du modèle de synthèse ; le même modèle peut servir aux deux. Aucun modèle n’est choisi automatiquement.</p>
|
||||
<p id="ranking-model-status" role={preferences.ranking_model_id && !rankingModels.some(model => model.id === preferences.ranking_model_id) ? 'alert' : undefined}>
|
||||
{rankingModels.length === 0 ? 'Aucun modèle de classement disponible. Contactez votre administrateur.' : !preferences.ranking_model_id ? 'Choisissez un modèle de classement pour pouvoir générer une synthèse.' : !rankingModels.some(model => model.id === preferences.ranking_model_id) ? 'Le modèle de classement sélectionné n’est plus disponible. Choisissez un autre modèle.' : ''}
|
||||
</p>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="preferences-budget">Budget maximal du prompt de synthèse</Label>
|
||||
<Input id="preferences-budget" type="number" inputMode="numeric" min={1} max={2000000} step={1}
|
||||
|
||||
@ -113,6 +113,12 @@ describe('Dashboard — génération de synthèses éphémères', () => {
|
||||
createReport.mockResolvedValue({ id: 'report-1' })
|
||||
})
|
||||
|
||||
it.each(['ranking_model_unavailable', 'ranking_model_incompatible'])('guide vers les préférences pour %s', async (failure_code) => {
|
||||
generationStatus.mockResolvedValueOnce({ id: 'failed', status: 'failed', failure_code })
|
||||
renderDashboard()
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent(/modèle.*classement/)
|
||||
expect(screen.getByRole('link', { name: 'Mes préférences' })).toHaveAttribute('href', '/preferences')
|
||||
})
|
||||
it('retire les diagnostics et les badges des résultats récents et historiques', async () => {
|
||||
listSummaries.mockResolvedValue([generatedSummary, previousSummary])
|
||||
listGenerations.mockResolvedValue([{ summary_id: generatedSummary.id, outcome: outcome('succeeded') }, { summary_id: previousSummary.id, outcome: outcome('partial') }])
|
||||
|
||||
@ -8,8 +8,8 @@ afterEach(() => {
|
||||
|
||||
it('charge et sauvegarde les préférences du compte via GET et PUT /api/me/preferences', async () => {
|
||||
localStorage.setItem('token', 'user-token')
|
||||
const initial = { language: 'fr', ranking_mode: 'title', summary_prompt_token_budget: 250000 }
|
||||
const updated = { language: 'en' as const, ranking_mode: 'title_content' as const, summary_prompt_token_budget: 80000 }
|
||||
const initial = { language: 'fr', ranking_mode: 'title', summary_prompt_token_budget: 250000, ranking_model_id: null }
|
||||
const updated = { language: 'en' as const, ranking_mode: 'title_content' as const, summary_prompt_token_budget: 80000, ranking_model_id: 'ranking-model' }
|
||||
const fetchMock = vi.fn()
|
||||
.mockResolvedValueOnce(new Response(JSON.stringify({ data: initial }), { status: 200 }))
|
||||
.mockResolvedValueOnce(new Response(JSON.stringify({ data: updated }), { status: 200 }))
|
||||
@ -22,3 +22,13 @@ it('charge et sauvegarde les préférences du compte via GET et PUT /api/me/pref
|
||||
method: 'PUT', headers, body: JSON.stringify(updated),
|
||||
})
|
||||
})
|
||||
|
||||
it('charge le catalogue ranking via son rôle sans changer le catalogue synthèse', async () => {
|
||||
const fetchMock = vi.fn().mockImplementation(async () => new Response(JSON.stringify({ data: [] }), { status: 200 }))
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
const ranking = (preferencesApi as unknown as { listRankingModels: () => Promise<unknown> }).listRankingModels
|
||||
expect(ranking).toBeTypeOf('function')
|
||||
await ranking()
|
||||
await preferencesApi.listSummaryModels()
|
||||
expect(fetchMock.mock.calls.map(call => call[0])).toEqual(['/api/me/summary-models?role=ranking', '/api/me/summary-models'])
|
||||
})
|
||||
|
||||
@ -1,20 +1,23 @@
|
||||
import { cleanup, render, screen, waitFor } from '@testing-library/react'
|
||||
import { cleanup, render, screen, waitFor, within } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { ComponentType } from 'react'
|
||||
import { ApiError } from '../src/api/client'
|
||||
import { Preferences } from '../src/pages/Preferences'
|
||||
import { MemoryRouter } from 'react-router-dom'
|
||||
import { Sidebar } from '../src/components/layout/Sidebar'
|
||||
import { MobileNav } from '../src/components/layout/MobileNav'
|
||||
import { router } from '../src/lib/router'
|
||||
|
||||
const { getPreferences, updatePreferences } = vi.hoisted(() => ({
|
||||
const { getPreferences, updatePreferences, listModels, listRankingModels } = vi.hoisted(() => ({
|
||||
listModels: vi.fn(),
|
||||
listRankingModels: vi.fn(),
|
||||
getPreferences: vi.fn(),
|
||||
updatePreferences: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/api/preferences', () => ({
|
||||
preferencesApi: { get: getPreferences, update: updatePreferences, listSummaryModels: vi.fn().mockResolvedValue([{ id: 'model-a', provider: 'OpenAI', model: 'summary' }]) },
|
||||
preferencesApi: { get: getPreferences, update: updatePreferences, listSummaryModels: listModels, listRankingModels },
|
||||
}))
|
||||
|
||||
function containsPreferencesRoute(routes: typeof router.routes): boolean {
|
||||
@ -29,10 +32,54 @@ vi.mock('@/lib/theme', () => ({ useTheme: () => ({ theme: 'light', setTheme: vi.
|
||||
describe('Mes préférences', () => {
|
||||
afterEach(cleanup)
|
||||
beforeEach(() => {
|
||||
listRankingModels.mockResolvedValue([{ id: 'model-a', provider: 'OpenAI', model: 'summary' }])
|
||||
listModels.mockResolvedValue([{ id: 'model-a', provider: 'OpenAI', model: 'summary' }])
|
||||
getPreferences.mockResolvedValue({ language: 'fr', ranking_mode: 'title' })
|
||||
updatePreferences.mockResolvedValue({ language: 'en', ranking_mode: 'title_content' })
|
||||
})
|
||||
|
||||
it('réserve le catalogue compatible au classement et garde le catalogue complet pour la synthèse', async () => {
|
||||
listModels.mockResolvedValueOnce([{ id: 'summary-only', provider: 'Other', model: 'summary-only' }])
|
||||
render(<Preferences />)
|
||||
const summary = await screen.findByLabelText('Modèle de synthèse')
|
||||
const ranking = screen.getByLabelText('Modèle de classement de pertinence')
|
||||
expect(within(summary).getByRole('option', { name: 'Other · summary-only' })).toBeInTheDocument()
|
||||
expect(within(ranking).queryByRole('option', { name: 'Other · summary-only' })).not.toBeInTheDocument()
|
||||
expect(within(ranking).getByRole('option', { name: 'OpenAI · summary' })).toBeInTheDocument()
|
||||
})
|
||||
it('explique un refus de compatibilité et conserve le choix', async () => {
|
||||
updatePreferences.mockRejectedValueOnce(new ApiError('ranking_model_incompatible', 400))
|
||||
render(<Preferences />)
|
||||
const ranking = await screen.findByLabelText('Modèle de classement de pertinence')
|
||||
const user = userEvent.setup()
|
||||
await user.selectOptions(ranking, 'model-a')
|
||||
await user.click(screen.getByRole('button', { name: 'Enregistrer' }))
|
||||
expect(await screen.findByRole('alert')).toHaveTextContent('incompatible avec le classement')
|
||||
expect(ranking).toHaveValue('model-a')
|
||||
})
|
||||
it('sépare le classement sans choix automatique et sauvegarde indépendamment', async () => {
|
||||
getPreferences.mockResolvedValueOnce({ language: 'fr', ranking_mode: 'title', summary_model_id: 'model-a', ranking_model_id: null })
|
||||
render(<Preferences />)
|
||||
const ranking = await screen.findByLabelText('Modèle de classement de pertinence')
|
||||
expect(ranking).toHaveValue('')
|
||||
expect(ranking).toHaveAccessibleDescription(/titre.*tous les articles.*sans filtrage.*pertinence décroissante.*date/i)
|
||||
const user = userEvent.setup()
|
||||
await user.selectOptions(ranking, 'model-a')
|
||||
await user.click(screen.getByRole('button', { name: 'Enregistrer' }))
|
||||
expect(updatePreferences).toHaveBeenLastCalledWith(expect.objectContaining({ summary_model_id: 'model-a', ranking_model_id: 'model-a' }))
|
||||
})
|
||||
it('signale une sélection de classement indisponible sans la remplacer', async () => {
|
||||
getPreferences.mockResolvedValueOnce({ language: 'fr', ranking_mode: 'title', ranking_model_id: 'removed' })
|
||||
render(<Preferences />)
|
||||
expect(await screen.findByLabelText('Modèle de classement de pertinence')).toHaveValue('removed')
|
||||
expect(screen.getByRole('alert')).toHaveTextContent('Le modèle de classement sélectionné n’est plus disponible.')
|
||||
})
|
||||
it('explique le catalogue vide et garde le classement sans sélection', async () => {
|
||||
listRankingModels.mockResolvedValueOnce([])
|
||||
render(<Preferences />)
|
||||
expect(await screen.findByLabelText('Modèle de classement de pertinence')).toHaveValue('')
|
||||
expect(screen.getByText('Aucun modèle de classement disponible. Contactez votre administrateur.')).toBeInTheDocument()
|
||||
})
|
||||
it('est accessible par une route dédiée', () => {
|
||||
expect(containsPreferencesRoute(router.routes)).toBe(true)
|
||||
})
|
||||
|
||||
@ -7,7 +7,7 @@ import { GenerationDetails } from '../src/components/GenerationDetails'
|
||||
import type { GenerationOutcome } from '../src/api/summaries'
|
||||
|
||||
const { get, update, listSummaryModels } = vi.hoisted(() => ({ get: vi.fn(), update: vi.fn(), listSummaryModels: vi.fn() }))
|
||||
vi.mock('@/api/preferences', () => ({ preferencesApi: { get, update, listSummaryModels } }))
|
||||
vi.mock('@/api/preferences', () => ({ preferencesApi: { listRankingModels: vi.fn().mockResolvedValue([]), get, update, listSummaryModels } }))
|
||||
vi.mock('@/components/Appearance', () => ({ Appearance: () => null }))
|
||||
const profile = { context_window_tokens: 128000, input_limit_tokens: 128000, output_reserve_tokens: 4096, framing_tokens: 1024, token_count_method: 'utf8_bytes_upper_bound_v1' }
|
||||
const preferences = { language: 'fr', ranking_mode: 'title_content', summary_model_id: 'a', summary_prompt_token_budget: 250000 }
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
import { cleanup, render, screen } from '@testing-library/react'
|
||||
import { cleanup, render, screen, within } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { Preferences } from '../src/pages/Preferences'
|
||||
@ -11,7 +11,7 @@ const { getPreferences, updatePreferences, listSummaryModels, listSummaries, lis
|
||||
listReports: vi.fn(), listMessages: vi.fn(), deleteReport: vi.fn(), createMessage: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/api/preferences', () => ({ preferencesApi: { get: getPreferences, update: updatePreferences, listSummaryModels } }))
|
||||
vi.mock('@/api/preferences', () => ({ preferencesApi: { listRankingModels: vi.fn().mockResolvedValue([]), get: getPreferences, update: updatePreferences, listSummaryModels } }))
|
||||
vi.mock('@/api/summaries', () => ({ summariesApi: { list: listSummaries, generations: listGenerations, recentJob: status, getJob: status, generate: vi.fn() } }))
|
||||
vi.mock('@/api/assets', () => ({ assetsApi: { list: listAssets } }))
|
||||
vi.mock('@/api/reports', () => ({ reportsApi: { list: listReports, listMessages, delete: deleteReport, createMessage } }))
|
||||
@ -45,8 +45,8 @@ describe('choix personnel du modèle de synthèse — ticket #14', () => {
|
||||
render(<Preferences />)
|
||||
const selector = await screen.findByLabelText(/modèle de synthèse/i)
|
||||
expect(selector).toHaveValue('model-a')
|
||||
expect(screen.getByRole('option', { name: 'OpenAI · gpt-summary' })).toBeInTheDocument()
|
||||
expect(screen.getByRole('option', { name: 'Ollama · qwen-summary' })).toBeInTheDocument()
|
||||
expect(within(selector).getByRole('option', { name: 'OpenAI · gpt-summary' })).toBeInTheDocument()
|
||||
expect(within(selector).getByRole('option', { name: 'Ollama · qwen-summary' })).toBeInTheDocument()
|
||||
await user.selectOptions(selector, 'model-b')
|
||||
await user.click(screen.getByRole('button', { name: 'Enregistrer' }))
|
||||
expect(updatePreferences).toHaveBeenCalledWith({ language: 'fr', ranking_mode: 'title_content', summary_model_id: 'model-b', summary_prompt_token_budget: 250000 })
|
||||
|
||||
Reference in New Issue
Block a user