fix(admin-ai): handle malformed model catalogs
Validate model catalog responses before rendering and offer a recoverable reload while preserving the last valid catalog. Cover malformed and legacy payloads with component and Playwright API tests. Refs #18 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
183
frontend/e2e/bug18-admin-ai-api.spec.mjs
Normal file
183
frontend/e2e/bug18-admin-ai-api.spec.mjs
Normal file
@ -0,0 +1,183 @@
|
||||
import { execFileSync } from 'node:child_process'
|
||||
import { test, expect } from '@playwright/test'
|
||||
import { readStackManifest } from './stack-manifest.mjs'
|
||||
|
||||
async function loginAsBootstrapAdmin(page, stack) {
|
||||
await page.goto(new URL('/login', stack.frontendUrl).href)
|
||||
await page.getByLabel('Adresse email').fill(stack.bootstrapAdmin.email)
|
||||
await page.getByLabel('Mot de passe').fill(stack.bootstrapAdmin.password)
|
||||
await page.getByRole('button', { name: 'Se connecter' }).click()
|
||||
await expect(page).toHaveURL(new URL('/', stack.frontendUrl).href)
|
||||
}
|
||||
|
||||
async function responseData(request, url, token, expectedStatus = 200) {
|
||||
const response = await request.get(url, { headers: { Authorization: `Bearer ${token}` } })
|
||||
expect(response.status()).toBe(expectedStatus)
|
||||
return { response, json: await response.json() }
|
||||
}
|
||||
|
||||
function expectPageLoadedAdminAIEndpoints(responses) {
|
||||
expect(responses).toEqual(expect.arrayContaining([
|
||||
expect.objectContaining({ path: '/api/admin/ai-providers', status: 200 }),
|
||||
expect.objectContaining({ path: '/api/admin/ai-models', status: 200 }),
|
||||
expect.objectContaining({ path: '/api/admin/ollama/models', status: 500 }),
|
||||
]))
|
||||
}
|
||||
|
||||
function restoreAISeed(stack) {
|
||||
const env = {
|
||||
...process.env,
|
||||
PGHOST: stack.databaseURL.hostname,
|
||||
PGPORT: stack.databaseURL.port || '5432',
|
||||
PGUSER: decodeURIComponent(stack.databaseURL.username),
|
||||
PGPASSWORD: decodeURIComponent(stack.databaseURL.password),
|
||||
PGDATABASE: decodeURIComponent(stack.databaseURL.pathname.slice(1)),
|
||||
PGSSLMODE: stack.databaseURL.searchParams.get('sslmode') || 'disable',
|
||||
}
|
||||
const providerID = '00000000-0000-0000-0000-000000001202'
|
||||
const modelID = stack.fixtures.summaryModelID
|
||||
const fakeURL = stack.layaFakeUrl.replaceAll("'", "''")
|
||||
const sql = `BEGIN;
|
||||
DELETE FROM ai_provider_models WHERE id <> '${modelID}';
|
||||
DELETE FROM ai_providers WHERE id <> '${providerID}';
|
||||
INSERT INTO ai_providers(id,name,model,endpoint,is_active)
|
||||
VALUES('${providerID}','ollama','fake-laya','${fakeURL}',true)
|
||||
ON CONFLICT(id) DO UPDATE SET name=EXCLUDED.name,model=EXCLUDED.model,endpoint=EXCLUDED.endpoint,is_active=true;
|
||||
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;
|
||||
COMMIT;`
|
||||
execFileSync(stack.psqlPath, ['--no-psqlrc', '--set', 'ON_ERROR_STOP=1', '--command', sql], {
|
||||
env,
|
||||
encoding: 'utf8',
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
timeout: 10_000,
|
||||
})
|
||||
}
|
||||
|
||||
test('bug #18: admin AI page consumes current empty and configured API payloads', async ({ page, request }) => {
|
||||
const stack = readStackManifest()
|
||||
await page.context().route('**/*', async route => {
|
||||
const host = new URL(route.request().url()).hostname
|
||||
if (host !== '127.0.0.1' && host !== '[::1]') return route.abort('blockedbyclient')
|
||||
return route.continue()
|
||||
})
|
||||
|
||||
await loginAsBootstrapAdmin(page, stack)
|
||||
const token = await page.evaluate(() => localStorage.getItem('token'))
|
||||
expect(token).toBeTruthy()
|
||||
const api = path => new URL(`/api${path}`, stack.apiUrl).href
|
||||
|
||||
const pageAPIResponses = []
|
||||
page.on('response', response => {
|
||||
const url = new URL(response.url())
|
||||
if (url.pathname.startsWith('/api/admin/') && ['/ai-providers', '/ai-models', '/ollama/models'].some(path => url.pathname.endsWith(path))) {
|
||||
pageAPIResponses.push({ path: url.pathname, status: response.status() })
|
||||
}
|
||||
})
|
||||
|
||||
await page.goto(new URL('/admin/ai', stack.frontendUrl).href)
|
||||
await expect(page.getByRole('heading', { name: 'Fournisseurs IA' })).toBeVisible()
|
||||
await expect(page.getByText('ollama · fake-summary')).toBeVisible()
|
||||
await expect(page.getByRole('alert')).toHaveCount(0)
|
||||
expectPageLoadedAdminAIEndpoints(pageAPIResponses)
|
||||
|
||||
const configuredProviders = await responseData(request, api('/admin/ai-providers'), token)
|
||||
const configuredModels = await responseData(request, api('/admin/ai-models'), token)
|
||||
const configuredOllama = await responseData(request, api('/admin/ollama/models'), token, 500)
|
||||
expect(configuredProviders.json.data).toEqual([expect.objectContaining({
|
||||
id: '00000000-0000-0000-0000-000000001202', name: 'ollama', model: 'fake-laya', has_key: false,
|
||||
})])
|
||||
expect(configuredModels.json.data).toEqual([expect.objectContaining({
|
||||
id: stack.fixtures.summaryModelID,
|
||||
provider_id: '00000000-0000-0000-0000-000000001202',
|
||||
provider: 'ollama', model: 'fake-summary', enabled: true,
|
||||
})])
|
||||
expect(configuredOllama.json).toHaveProperty('error')
|
||||
|
||||
let emptyCounts
|
||||
let currentCounts
|
||||
let reconfiguredProviderData
|
||||
let reconfiguredModelData
|
||||
let providerID
|
||||
try {
|
||||
// Both seeded rows 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.summaryModelID}`), {
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
})).status()).toBe(204)
|
||||
expect((await request.delete(api('/admin/ai-providers/00000000-0000-0000-0000-000000001202'), {
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
})).status()).toBe(204)
|
||||
|
||||
await page.reload()
|
||||
await expect(page.getByText('Aucun fournisseur configuré')).toBeVisible()
|
||||
await expect(page.getByText('Aucun modèle configuré.')).toBeVisible()
|
||||
await expect(page.getByRole('alert')).toHaveCount(0)
|
||||
expectPageLoadedAdminAIEndpoints(pageAPIResponses)
|
||||
const emptyProviders = await responseData(request, api('/admin/ai-providers'), token)
|
||||
const emptyModels = await responseData(request, api('/admin/ai-models'), token)
|
||||
const emptyOllama = await responseData(request, api('/admin/ollama/models'), token, 500)
|
||||
expect(emptyProviders.json.data).toEqual([])
|
||||
expect(emptyModels.json.data).toEqual([])
|
||||
expect(emptyOllama.json).toHaveProperty('error')
|
||||
emptyCounts = {
|
||||
providers: emptyProviders.json.data.length,
|
||||
models: emptyModels.json.data.length,
|
||||
ollamaStatus: emptyOllama.response.status(),
|
||||
ollamaBody: emptyOllama.json,
|
||||
}
|
||||
|
||||
// Reconfigure with a loopback-only provider and summary model, then verify
|
||||
// the same real page and APIs consume the post-migration catalogue shape.
|
||||
const createdProvider = await request.post(api('/admin/ai-providers'), {
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
data: { name: 'ollama', model: 'fake-laya', endpoint: stack.layaFakeUrl },
|
||||
})
|
||||
expect(createdProvider.status()).toBe(201)
|
||||
const providerEnvelope = await createdProvider.json()
|
||||
providerID = providerEnvelope.data.id
|
||||
const createdModel = await request.post(api('/admin/ai-models'), {
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
data: { provider_id: providerID, model: 'bug18-summary' },
|
||||
})
|
||||
expect(createdModel.status()).toBe(201)
|
||||
const modelEnvelope = await createdModel.json()
|
||||
|
||||
await page.reload()
|
||||
await expect(page.getByText('ollama · bug18-summary')).toBeVisible()
|
||||
await expect(page.locator('span.font-semibold.capitalize').filter({ hasText: 'ollama' })).toBeVisible()
|
||||
await expect(page.getByRole('alert')).toHaveCount(0)
|
||||
expectPageLoadedAdminAIEndpoints(pageAPIResponses)
|
||||
const currentProviders = await responseData(request, api('/admin/ai-providers'), token)
|
||||
const currentModels = await responseData(request, api('/admin/ai-models'), token)
|
||||
expect(currentProviders.json.data).toEqual([expect.objectContaining({ id: providerID, name: 'ollama', has_key: false })])
|
||||
expect(currentModels.json.data).toEqual([expect.objectContaining({
|
||||
id: modelEnvelope.data.id, provider_id: providerID, provider: 'ollama', model: 'bug18-summary', enabled: true,
|
||||
})])
|
||||
currentCounts = { providers: currentProviders.json.data.length, models: currentModels.json.data.length }
|
||||
reconfiguredProviderData = currentProviders.json.data.map(({ endpoint, ...provider }) => ({ ...provider, endpoint: endpoint ? '<loopback fake>' : '' }))
|
||||
reconfiguredModelData = currentModels.json.data
|
||||
} finally {
|
||||
// Restore the original fixed fixture IDs so subsequent E2E specs see the
|
||||
// clean post-migration composition they expect, even after an assertion fails.
|
||||
restoreAISeed(stack)
|
||||
}
|
||||
|
||||
// Do not log the serialized provider (it includes a per-run loopback port).
|
||||
console.log(JSON.stringify({
|
||||
configured: {
|
||||
providers: configuredProviders.json.data.map(({ endpoint, ...provider }) => ({ ...provider, endpoint: endpoint ? '<loopback fake>' : '' })),
|
||||
models: configuredModels.json.data,
|
||||
ollamaStatus: configuredOllama.response.status(),
|
||||
ollamaBody: configuredOllama.json,
|
||||
},
|
||||
empty: emptyCounts,
|
||||
reconfigured: {
|
||||
counts: currentCounts,
|
||||
providers: reconfiguredProviderData,
|
||||
models: reconfiguredModelData,
|
||||
},
|
||||
frontendRequests: pageAPIResponses,
|
||||
}))
|
||||
})
|
||||
Reference in New Issue
Block a user