Files
Convivo/apps/admin/src/views/Settings.tsx
T
d3083b7940 fix(points): welcome check-in awards +10; add Sessions view, AI connection test, silent reload
The front-desk check-in set checked_in and printed badges but awarded nothing,
so the +10 depended on which check-in a person happened to get. Every award
path was reviewed:

- welcome_checkin awards +10 (category checkin) on a genuine first check-in and
  returns points + points_awarded; checkin_attendee and preview_welcome_checkin
  return points_awarded too.
- set_registration_checked_in(false) deleted all checkin points while keeping
  the checkins rows, and switching back on awarded nothing -- one mistaken
  toggle destroyed those points permanently. ON now recomputes from the rows
  that still exist and awards only the shortfall: reversible, still unfarmable.
- The staff/Admin/@appe.at exclusion stays (product decision) but is no longer
  silent: three-way points sheets in the scanner, "no points" with a tooltip in
  Registrations, and the Contacts points modal refuses to apply rather than
  letting adjust_points (void) no-op quietly.

Also in this change:
- admin silent refresh (5s poll + 500ms after writes) across all data views;
  Registrations patches in place so rows never slide under the cursor
- Settings "Validate AI connection" via a new sidecar POST /llm-test verdict
  endpoint (never leaks the key, distinguishes "no usage block" from "off")
- new Sessions view between Schedule and Activity: speakers, attendance,
  ratings, attendee filter, and one button that summarises every session with
  feedback (one request each, concurrency 3, UI blocked until all settle)
- provider requests disable thinking through one shared body builder sending
  both reasoning_effort:"none" and chat_template_kwargs.enable_thinking

SQL: 113 / 57 / 24 assertions (set_registration_checked_in section 3 was
rewritten, it asserted the bug). Sidecar 34 unit tests. Full e2e 202 passed,
0 failed. Migration applied locally only -- not deployed.

Co-authored-by: Stephan Charles <[email protected]>
Co-authored-by: Amelia Hernandez <[email protected]>
Co-authored-by: Markus Franz <[email protected]>
Co-authored-by: Sabrina Hota <[email protected]>
Co-authored-by: Nilüfer Doğan <[email protected]>
2026-10-19 20:14:03 +02:00

150 lines
8.2 KiB
TypeScript

import { useEffect, useState, type FormEvent } from 'react';
import { PlugZap, Save } from 'lucide-react';
import { getActiveEvent, getLlmSettings, saveLlmSettings, testLlmConnection } from '../lib/api';
import type { Event, LlmTestResult } from '../lib/types';
import { Spinner } from '../components/ui';
import { BadgeCopiesSetting } from '../components/BadgeCopiesSetting';
export function Settings() {
const [endpoint, setEndpoint] = useState('');
const [model, setModel] = useState('');
const [apiKey, setApiKey] = useState('');
const [hasKey, setHasKey] = useState(false);
const [clearKey, setClearKey] = useState(false);
const [loaded, setLoaded] = useState(false);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const [saved, setSaved] = useState(false);
const [testing, setTesting] = useState(false);
const [testResult, setTestResult] = useState<LlmTestResult | null>(null);
// What is actually stored in the DB. The sidecar tests the stored settings
// (the API key never reaches the browser), so unsaved edits cannot be tested —
// this is what lets the UI say "save first" instead of testing stale values.
const [baseline, setBaseline] = useState({ endpoint: '', model: '', has_api_key: false });
// Badge printing is per event, so it follows the active event.
const [activeEvent, setActiveEvent] = useState<Event | null>(null);
useEffect(() => {
let active = true;
getLlmSettings().then(settings => {
if (!active) return;
setEndpoint(settings.endpoint);
setModel(settings.model);
setHasKey(settings.has_api_key);
setBaseline({ endpoint: settings.endpoint, model: settings.model, has_api_key: settings.has_api_key });
setLoaded(true);
}).catch(cause => { if (active) setError(cause instanceof Error ? cause.message : 'Failed to load settings'); });
// Best-effort: a failure here just hides the badge section, it must not
// break the Feedback AI settings below.
getActiveEvent()
.then(event => { if (active) setActiveEvent(event); })
.catch(() => { if (active) setActiveEvent(null); });
return () => { active = false; };
}, []);
// Unsaved edits mean a test would measure something other than what's on
// screen, so the button stays disabled with an explanation instead.
const pendingChanges =
endpoint.trim() !== baseline.endpoint || model.trim() !== baseline.model || clearKey || apiKey.length > 0;
async function save(event: FormEvent) {
event.preventDefault();
setBusy(true);
setSaved(false);
setError(null);
try {
const settings = await saveLlmSettings({ endpoint: endpoint.trim(), model: model.trim(), ...(clearKey ? { api_key: '' } : apiKey ? { api_key: apiKey } : {}) });
setEndpoint(settings.endpoint);
setHasKey(settings.has_api_key);
setBaseline({ endpoint: settings.endpoint, model: settings.model, has_api_key: settings.has_api_key });
setApiKey('');
setClearKey(false);
setSaved(true);
// Saving changes what a test would measure, so any old verdict is void.
setTestResult(null);
} catch (cause) { setError(cause instanceof Error ? cause.message : 'Failed to save settings'); }
finally { setBusy(false); }
}
async function testConnection() {
if (testing) return;
setTesting(true);
setTestResult(null);
setError(null);
try {
setTestResult(await testLlmConnection());
} catch (cause) {
setError(cause instanceof Error ? cause.message : 'Could not reach the sync sidecar (is it running?)');
} finally { setTesting(false); }
}
return (
<div>
<div className="page-head"><h1>Settings</h1></div>
{error && <p className="feedback-error" role="alert">{error}</p>}
{!loaded && !error && <Spinner />}
{activeEvent && (
<section className="settings-section" aria-labelledby="badge-printing-h" data-testid="settings-badge-printing">
<h2 className="h2" id="badge-printing-h">Badge printing</h2>
<BadgeCopiesSetting eventId={activeEvent.id} initialCopies={activeEvent.badge_copies ?? 1} eventName={activeEvent.name} />
</section>
)}
{loaded && <form className="llm-settings" onSubmit={save} onChange={() => setSaved(false)}>
<h2 className="h2">Feedback AI</h2>
<div className="field">
<label htmlFor="llm-endpoint">LLM endpoint (OpenAI-compatible)</label>
<input id="llm-endpoint" className="input" type="url" placeholder="https://api.example.com/v1/chat/completions" required value={endpoint} disabled={busy} onChange={event => setEndpoint(event.target.value)} />
</div>
<div className="field">
<label htmlFor="llm-model">Model</label>
<input id="llm-model" className="input" required maxLength={200} value={model} disabled={busy} onChange={event => setModel(event.target.value)} />
</div>
<div className="field">
<label htmlFor="llm-key">API key (optional)</label>
<input id="llm-key" className="input" type="password" autoComplete="new-password" maxLength={4096} value={apiKey} disabled={busy || clearKey} placeholder={hasKey ? 'Key configured' : ''} onChange={event => setApiKey(event.target.value)} />
</div>
{hasKey && <label className="row"><input type="checkbox" checked={clearKey} disabled={busy} onChange={event => setClearKey(event.target.checked)} />Remove stored API key</label>}
<div className="row">
<button className="btn primary" type="submit" disabled={busy}><Save size={16} aria-hidden="true" />{busy ? 'Saving...' : 'Save'}</button>
{saved && <span role="status">Settings saved</span>}
</div>
<div className="llm-test">
<div className="row">
{/* type=button: inside the form, a submit would save instead of test. */}
<button className="btn" type="button" onClick={testConnection} data-testid="llm-test-button"
disabled={busy || testing || pendingChanges}
title={pendingChanges ? 'Save these settings first — the test uses what is stored on the server' : 'Sends one request to the endpoint and reports what came back'}>
<PlugZap size={16} aria-hidden="true" />{testing ? 'Testing...' : 'Validate AI connection'}
</button>
{pendingChanges && <span className="muted small" data-testid="llm-test-dirty">Save first — the test uses the stored settings.</span>}
</div>
{testing && <p className="muted small" role="status" data-testid="llm-test-progress">Sending one request to {model.trim() || 'the configured model'}…</p>}
{/* The verdict stays on the page rather than in a toast: the latency and
the reasoning-token line are the parts people need to read twice. */}
{testResult && (
<div className={`llm-test-result ${testResult.ok ? (testResult.reasoning_disabled ? 'good' : 'warn') : 'bad'}`}
role="status" data-testid="llm-test-result" data-ok={String(testResult.ok)}
data-reasoning-disabled={String(testResult.reasoning_disabled)}>
<strong data-testid="llm-test-headline">
{testResult.ok
? testResult.reasoning_disabled
? `Connection works — replied in ${testResult.latency_ms} ms`
: 'Connection works, but the model is still thinking'
: 'Connection failed'}
</strong>
{testResult.model && <p className="muted small">{testResult.model} at {testResult.endpoint}</p>}
{testResult.error && <p className="feedback-error" data-testid="llm-test-error">{testResult.error}</p>}
{testResult.warning && <p data-testid="llm-test-warning">{testResult.warning}</p>}
{testResult.ok && (
<p className="muted small" data-testid="llm-test-reasoning">
Reasoning tokens: {testResult.reasoning_tokens === null ? 'not reported by this endpoint' : testResult.reasoning_tokens}
{testResult.content ? ` · reply: “${testResult.content.slice(0, 60)}”` : ''}
</p>
)}
</div>
)}
</div>
</form>}
</div>
);
}