feat: add manual feedback AI summaries and secure leaderboard scoring

This commit is contained in:
Lago committed 2026-10-15 19:06:10 +02:00
1 parent 34a3a88376
commit 6bad96ca03
37 files changed
+1640 -77

No files matched your search

+160
View File
@@ -0,0 +1,160 @@
import { test, expect, type Page } from '@playwright/test';
const adminUrl = process.env.CONVIVO_ADMIN_URL || 'http://localhost:3001';
const eventId = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa';
const sessionId = 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb';
const user = { id: '99999999-9999-4999-8999-999999999999', email: '[email protected]', aud: 'authenticated', role: 'authenticated', app_metadata: {}, user_metadata: {} };
async function openAdmin(page: Page, options: { empty?: boolean; configured?: boolean; fail?: boolean; savedSummary?: boolean; feedbackCount?: number } = {}) {
const payload = Buffer.from(JSON.stringify({ sub: user.id, exp: Math.floor(Date.now() / 1000) + 3600 })).toString('base64url');
const session = { user, access_token: `eyJhbGciOiJIUzI1NiJ9.${payload}.test`, refresh_token: 'mock-refresh-token', expires_in: 3600, token_type: 'bearer' };
const event = { id: eventId, name: 'Feedback Conference', is_active: true, start_date: '2026-10-23', end_date: '2026-10-23', num_registrations: 4, num_sessions: 1, num_speakers: 1 };
const requests: Record<string, unknown>[] = [];
const settingsWrites: Record<string, unknown>[] = [];
let settings = { endpoint: options.configured === false ? '' : 'https://llm.example/v1/chat/completions', model: options.configured === false ? '' : 'test-model', has_api_key: true, updated_at: null };
const summaries: Record<string, unknown>[] = options.savedSummary ? [{ scope: 'event', target_id: eventId, event_id: eventId, session_id: null, summary: 'Previous event summary', response_count: 1, model: 'old-model', generated_at: '2026-10-11T10:00:00Z' }] : [];
await page.route('**/auth/v1/**', route => route.fulfill({ json: new URL(route.request().url()).pathname.endsWith('/user') ? user : session }));
await page.route('**/rest/v1/**', async route => {
const url = new URL(route.request().url());
if (url.pathname.endsWith('/contacts')) {
const contact = { email: user.email, full_name: 'Admin', is_admin: true };
return route.fulfill({ json: url.searchParams.has('email') ? contact : [contact] });
}
if (url.pathname.endsWith('/events')) return route.fulfill({ json: url.searchParams.has('is_active') ? event : [event] });
if (url.pathname.endsWith('/sessions')) return route.fulfill({ json: [{ id: sessionId, event_id: eventId, title: 'Session Alpha', slot_id: 1 }] });
if (url.pathname.endsWith('/feedback_summaries')) return route.fulfill({ json: summaries });
if (url.pathname.endsWith('/feedback') || url.pathname.endsWith('/event_feedback')) {
const rows = options.empty ? [] : Array.from({ length: options.feedbackCount || 1 }, (_value, index) => ({
id: `feedback-${index}`, event_id: eventId, session_id: sessionId, contact_email: `attendee-${index}@example.com`,
rating: 5, comment: 'Useful and well organized.', created_at: '2026-10-23T16:00:00Z',
}));
const offset = Number(url.searchParams.get('offset') || 0);
const limit = Number(url.searchParams.get('limit') || rows.length);
return route.fulfill({ json: rows.slice(offset, offset + limit) });
}
return route.fulfill({ json: [] });
});
await page.route('**/sidecar/llm-settings', async route => {
expect(route.request().headers().authorization).toBe(`Bearer ${session.access_token}`);
if (route.request().method() === 'PUT') {
const body = route.request().postDataJSON();
settingsWrites.push(body);
settings = { ...settings, endpoint: body.endpoint, model: body.model, has_api_key: body.api_key === '' ? false : true };
}
return route.fulfill({ json: settings });
});
await page.route('**/sidecar/feedback-summary', async route => {
expect(route.request().headers().authorization).toBe(`Bearer ${session.access_token}`);
const body = route.request().postDataJSON();
requests.push(body);
if (options.fail) return route.fulfill({ status: 502, json: { error: 'LLM request failed (HTTP 503)' } });
const summary = { scope: body.scope, target_id: body.scope === 'event' ? eventId : sessionId, event_id: eventId, session_id: body.session_id || null, summary: `Generated ${body.scope} summary: useful feedback.`, response_count: 1, model: settings.model, source_fingerprint: 'hash', generated_at: '2026-10-11T11:00:00Z' };
const index = summaries.findIndex(item => item.scope === body.scope);
if (index >= 0) summaries.splice(index, 1);
summaries.push(summary);
return route.fulfill({ json: summary });
});
await page.goto(`${adminUrl}/auth/callback#access_token=${session.access_token}&refresh_token=${session.refresh_token}&type=magiclink`);
await expect(page.locator('.nav').getByRole('button', { name: /Dashboard/ })).toBeVisible();
return { requests, settingsWrites };
}
async function openActivity(page: Page, tab: 'Event feedback' | 'Session feedback') {
await page.locator('.nav').getByRole('button', { name: /Activity/ }).click();
await page.getByRole('button', { name: tab, exact: true }).click();
}
test('settings saves model and optional key without exposing the stored key', async ({ page }, testInfo) => {
await page.setViewportSize({ width: 1280, height: 900 });
const { settingsWrites } = await openAdmin(page);
await page.locator('.nav').getByRole('button', { name: 'Settings', exact: true }).click();
await expect(page.getByLabel('API key (optional)')).toHaveValue('');
await expect(page.getByLabel('API key (optional)')).toHaveAttribute('placeholder', 'Key configured');
await page.getByLabel('Model', { exact: true }).fill('new-model');
await page.getByRole('button', { name: 'Save', exact: true }).click();
await expect(page.locator('.llm-settings').getByRole('status')).toHaveText('Settings saved');
expect(settingsWrites[0]).toEqual({ endpoint: 'https://llm.example/v1/chat/completions', model: 'new-model' });
await page.getByLabel('Remove stored API key').check();
await page.getByRole('button', { name: 'Save', exact: true }).click();
await expect.poll(() => settingsWrites.length).toBe(2);
expect(settingsWrites[1].api_key).toBe('');
await expect(page.locator('.llm-settings').getByRole('status')).toHaveText('Settings saved');
await page.screenshot({ path: testInfo.outputPath('ai-settings-desktop.png'), fullPage: true });
});
for (const scope of ['event', 'session'] as const) {
test(`manually generates ${scope} summary and restores it when reopening Activity`, async ({ page }, testInfo) => {
await page.setViewportSize({ width: 1280, height: 900 });
const { requests } = await openAdmin(page);
await openActivity(page, scope === 'event' ? 'Event feedback' : 'Session feedback');
const button = page.getByRole('button', { name: 'Generate AI Summary', exact: true });
await expect(button).toBeEnabled();
expect(requests).toHaveLength(0);
await button.click();
await expect(page.getByText(`Generated ${scope} summary: useful feedback.`, { exact: true })).toBeVisible();
expect(requests).toEqual([{ event_id: eventId, scope, ...(scope === 'session' ? { session_id: sessionId } : {}) }]);
await page.screenshot({ path: testInfo.outputPath(`ai-${scope}-desktop.png`), fullPage: true });
await page.locator('.nav').getByRole('button', { name: /Dashboard/ }).click();
await openActivity(page, scope === 'event' ? 'Event feedback' : 'Session feedback');
await expect(page.getByText(`Generated ${scope} summary: useful feedback.`, { exact: true })).toBeVisible();
expect(requests).toHaveLength(1);
});
}
test('empty feedback disables generation', async ({ page }) => {
const { requests } = await openAdmin(page, { empty: true });
await openActivity(page, 'Event feedback');
await expect(page.getByRole('button', { name: 'Generate AI Summary', exact: true })).toBeDisabled();
await expect(page.getByText('No event-level feedback yet.')).toBeVisible();
expect(requests).toHaveLength(0);
});
test('counts feedback beyond the first query page without automatic generation', async ({ page }) => {
const { requests } = await openAdmin(page, { feedbackCount: 501 });
await openActivity(page, 'Session feedback');
await expect(page.getByRole('region', { name: /AI summary: Session Alpha/ }).getByText('501 responses', { exact: true })).toBeVisible();
await page.getByRole('button', { name: 'Event feedback', exact: true }).click();
await expect(page.getByRole('region', { name: 'AI summary: Feedback Conference' }).getByText('501 responses', { exact: true })).toBeVisible();
expect(requests).toHaveLength(0);
});
test('unconfigured endpoint disables generation', async ({ page }) => {
const { requests } = await openAdmin(page, { configured: false });
await openActivity(page, 'Session feedback');
await expect(page.getByRole('button', { name: 'Generate AI Summary', exact: true })).toBeDisabled();
await expect(page.getByText('LLM endpoint not configured', { exact: true })).toBeVisible();
expect(requests).toHaveLength(0);
});
test('provider failure preserves the previous summary and allows retry', async ({ page }) => {
const { requests } = await openAdmin(page, { fail: true, savedSummary: true });
await openActivity(page, 'Event feedback');
await page.getByRole('button', { name: 'Generate AI Summary', exact: true }).click();
await expect(page.getByRole('alert')).toHaveText('LLM request failed (HTTP 503)');
await expect(page.getByText('Previous event summary', { exact: true })).toBeVisible();
await expect(page.getByRole('button', { name: 'Generate AI Summary', exact: true })).toBeEnabled();
expect(requests).toHaveLength(1);
});
test('summary and settings controls fit a mobile viewport', async ({ page }, testInfo) => {
await page.setViewportSize({ width: 390, height: 844 });
await openAdmin(page, { savedSummary: true });
await openActivity(page, 'Event feedback');
const panel = page.getByRole('region', { name: 'AI summary: Feedback Conference' });
expect(await page.locator('.activity-tabs').evaluate(element => getComputedStyle(element).display)).toBe('grid');
const firstTab = await page.getByRole('button', { name: 'Check-ins', exact: true }).boundingBox();
const lastTab = await page.getByRole('button', { name: 'Event feedback', exact: true }).boundingBox();
expect(lastTab!.y).toBeGreaterThan(firstTab!.y);
await expect(panel).toBeVisible();
await expect(panel.getByRole('button', { name: 'Generate AI Summary' })).toBeEnabled();
expect(await panel.evaluate(element => element.scrollWidth <= element.clientWidth)).toBe(true);
const bounds = await panel.boundingBox();
expect(bounds).not.toBeNull();
expect(bounds!.x).toBeGreaterThanOrEqual(0);
expect(bounds!.x + bounds!.width).toBeLessThanOrEqual(390);
await page.screenshot({ path: testInfo.outputPath('ai-feedback-mobile.png'), fullPage: true });
await page.locator('.nav').getByRole('button', { name: 'Settings', exact: true }).click();
await expect(page.getByLabel('LLM endpoint (OpenAI-compatible)')).toBeVisible();
expect(await page.locator('.llm-settings').evaluate(element => element.scrollWidth <= element.clientWidth)).toBe(true);
await page.screenshot({ path: testInfo.outputPath('ai-settings-mobile.png'), fullPage: true });
});
+83
View File
@@ -0,0 +1,83 @@
import { test, expect } from '@playwright/test';
import { randomUUID } from 'node:crypto';
import { APP_URL, SUPABASE_URL, ANON_KEY, SERVICE_ROLE_KEY } from '../src/helpers/config';
import { psql, sqlQuote } from '../src/helpers/db';
import { login } from '../src/helpers/auth';
test('real leaderboard updates scores and ranks without rewarding staff or admins', async ({ page }) => {
test.skip(new URL(APP_URL).hostname !== 'localhost' && new URL(APP_URL).hostname !== '127.0.0.1', 'Disposable fixtures are local-only');
const suffix = randomUUID();
const emails = ['player', 'peer', 'third', 'fourth', 'staff', 'admin'].map(role => `board-${role}-${suffix}@example.test`);
const password = randomUUID();
const userIds: string[] = [];
const eventId = psql('select id from public.events where is_active limit 1;');
expect(eventId).toMatch(/^[0-9a-f-]{36}$/);
const initialPoints = Number(psql('select coalesce(max(points),0) from public.leaderboard;')) + 100;
let subscribed = false;
let updates = 0;
const transportMessages: string[] = [];
page.on('websocket', socket => {
if (!socket.url().includes('/realtime/')) return;
socket.on('framereceived', frame => {
try {
const decoded = JSON.parse(String(frame.payload));
const message = Array.isArray(decoded) ? { event: decoded[3], payload: decoded[4] } : decoded;
transportMessages.push(JSON.stringify({ event: message.event, status: message.payload?.status,
response: message.payload?.response, extension: message.payload?.extension, message: message.payload?.message }));
if (message.event === 'phx_reply' && message.payload?.status === 'ok'
&& message.payload?.response?.postgres_changes?.length) subscribed = true;
if (message.event === 'postgres_changes') updates++;
} catch { /* Ignore non-JSON transport frames. */ }
});
});
try {
const created = await fetch(`${SUPABASE_URL}/auth/v1/admin/users`, {
method: 'POST', headers: { apikey: SERVICE_ROLE_KEY, Authorization: `Bearer ${SERVICE_ROLE_KEY}`, 'Content-Type': 'application/json' },
body: JSON.stringify({ email: emails[0], password, email_confirm: true }),
});
expect(created.ok, 'Create disposable local Auth user').toBe(true);
const user = await created.json();
userIds.push(user.id);
psql(`begin;
insert into public.contacts(email,full_name,is_admin) values ${emails.map((email, index) =>
`(${sqlQuote(email)},${sqlQuote(['Board Player','Board Peer','Board Third','Board Fourth','Board Staff','Board Admin'][index])},${index === 5})`).join(',')};
insert into public.registrations(event_id,contact_email,type,checked_in,points,qr_token) values ${emails.map((email, index) =>
`(${sqlQuote(eventId)},${sqlQuote(email)},${sqlQuote(index >= 4 ? 'staff' : 'attendee')},true,${initialPoints + (4 - index) * 10},${sqlQuote(index === 0 ? password : randomUUID())})`).join(',')};
commit;`);
await login(page, APP_URL, { email: emails[0], qrToken: password, type: 'attendee', label: 'Disposable leaderboard player' });
await page.getByText('Leaderboard', { exact: true }).click();
await expect(page.locator('.podium .pname')).toHaveText(['Board', 'Board', 'Board']);
await expect(page.getByText('Board Fourth', { exact: true })).toBeVisible();
await expect(page.getByText(/You.re ranked/)).toContainText('#1');
await expect.poll(() => subscribed, { timeout: 20_000, message: 'Realtime subscription acknowledged' }).toBe(true)
.catch(error => { throw new Error(`${error.message}\n${transportMessages.join('\n')}`); });
psql(`begin;
select set_config('request.jwt.claims', ${sqlQuote(JSON.stringify({ email: emails[5], role: 'authenticated' }))}, true);
set local role authenticated;
select public.adjust_points(${sqlQuote(emails[1])},100,'Leaderboard regression');
select public.adjust_points(${sqlQuote(emails[4])},9999,'Excluded staff regression');
select public.adjust_points(${sqlQuote(emails[5])},9999,'Excluded admin regression');
commit;`);
await expect(page.locator('.podium .bar.b1')).toHaveText(String(initialPoints + 130));
await expect(page.getByText(/You.re ranked/)).toContainText('#2');
expect(updates).toBeGreaterThan(0);
expect(psql(`select bool_and(points=0) from public.registrations where contact_email in (${emails.slice(4).map(sqlQuote).join(',')});`)).toBe('t');
expect(psql(`select count(*) from public.leaderboard where contact_email in (${emails.slice(4).map(sqlQuote).join(',')});`)).toBe('0');
expect(psql(`select count(*) from public.points_log where contact_email in (${emails.slice(4).map(sqlQuote).join(',')});`)).toBe('0');
const forbidden = await fetch(`${SUPABASE_URL}/rest/v1/rpc/_award_points`, {
method: 'POST', headers: { apikey: ANON_KEY, 'Content-Type': 'application/json' },
body: JSON.stringify({ p_event_id: eventId, p_contact_email: emails[0], p_delta: 9999, p_category: 'admin' }),
});
expect(forbidden.ok, 'Anonymous API must not forge points').toBe(false);
} finally {
await page.close();
psql(`delete from public.contacts where email in (${emails.map(sqlQuote).join(',')});`);
for (const userId of userIds) {
const deleted = await fetch(`${SUPABASE_URL}/auth/v1/admin/users/${userId}`, {
method: 'DELETE', headers: { apikey: SERVICE_ROLE_KEY, Authorization: `Bearer ${SERVICE_ROLE_KEY}` },
});
expect(deleted.ok, 'Delete disposable Auth user').toBe(true);
}
expect(psql(`select count(*) from public.contacts where email in (${emails.map(sqlQuote).join(',')});`)).toBe('0');
}
});