Measured against the gateway this deployment actually uses (ai.lago.dev), a
"Reply with OK" request comes back with usage.completion_tokens_details: {} --
the provider does not report a reasoning counter at all. Thinking is
verifiably off there (2 completion tokens, 424 ms, versus ~235 tokens and
~3.5x latency when on), but reasoning_tokens is undefined, not 0.
The verdict had two states, so a healthy production connection rendered amber
with "the model is still thinking" -- the button would have reported a working
configuration as broken. The reasoning verdict is now three-state:
- reported 0 -> reasoning_disabled: true, green
- not reported -> reasoning_tokens: null, no warning, neutral card that
says it cannot be confirmed from the usage block
- reported and > 0 -> amber + the existing warning
Only a reported 0 asserts reasoning_disabled, so the UI still never claims
thinking is off without evidence.
Sidecar 34 -> 35 tests (all three unreported shapes assert no warning); new
e2e/tests/llm-connection-test.spec.ts, 6 tests, covering the three verdict
tones, the failure case, the dirty-form lock and the in-flight state.
223 lines
13 KiB
JavaScript
223 lines
13 KiB
JavaScript
const { test } = require('node:test');
|
|
const assert = require('node:assert/strict');
|
|
const { createFeedbackApi } = require('../src/feedback-api');
|
|
const { isPublicAddress, resolveEndpoint } = require('../src/llm-fetch');
|
|
const eventId = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa';
|
|
const sessionId = 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb';
|
|
const config = { endpoint: 'https://llm.example/v1/chat/completions', model: 'model', api_key: 'secret' };
|
|
const request = (method = 'POST') => ({ method, headers: { authorization: 'Bearer user-token' } });
|
|
|
|
function fixture(options = {}) {
|
|
const writes = [];
|
|
const reads = [];
|
|
const api = createFeedbackApi({
|
|
supabaseUrl: 'https://supabase.example', serviceRoleKey: 'server-only',
|
|
fetchImpl: async (_url, init) => {
|
|
assert.equal(init.headers.Authorization, 'Bearer user-token');
|
|
return new Response(JSON.stringify({ id: 'user-id', email: '[email protected]' }), { status: options.unauthorized ? 401 : 200 });
|
|
},
|
|
validateEndpoint: options.validateEndpoint || (async () => {}),
|
|
providerFetch: options.providerFetch || (async () => new Response(JSON.stringify({ choices: [{ message: { content: 'Helpful feedback summary' } }] }))),
|
|
supabaseFetch: async (path, init) => {
|
|
if (init) { writes.push({ path, ...init }); return null; }
|
|
reads.push(path);
|
|
if (path.includes('/contacts?')) return [{ is_admin: !options.notAdmin }];
|
|
if (path.includes('/llm_settings?')) return options.noSettings ? [] : (options.settingsRows || [config]);
|
|
if (path.includes('/events?')) return [{ id: eventId, name: 'Event' }];
|
|
if (path.includes('/sessions?')) return options.wrongSession ? [] : [{ id: sessionId, title: 'Session' }];
|
|
if (path.includes('/feedback?') || path.includes('/event_feedback?')) {
|
|
const rows = options.empty ? [] : Array.from({ length: options.feedbackCount || 1 }, () => ({ rating: 5, comment: 'Helpful' }));
|
|
const offset = Number(new URL(path, 'https://supabase.example').searchParams.get('offset') || 0);
|
|
return rows.slice(offset, offset + 500);
|
|
}
|
|
throw new Error(`Unexpected path: ${path}`);
|
|
},
|
|
});
|
|
return { api, writes, reads };
|
|
}
|
|
|
|
test('rejects missing, invalid and non-admin credentials before reading feedback', async () => {
|
|
for (const options of [{ unauthorized: true }, { notAdmin: true }]) {
|
|
const { api, reads } = fixture(options);
|
|
await assert.rejects(api.handle(request(), '/feedback-summary', {}), error => [401, 403].includes(error.status));
|
|
assert.ok(!reads.some(path => path.includes('/feedback?')));
|
|
}
|
|
await assert.rejects(fixture().api.handle({ method: 'GET', headers: {} }, '/llm-settings'), error => error.status === 401);
|
|
});
|
|
|
|
test('never returns the stored key; retains it on unchanged-endpoint edits', async () => {
|
|
const { api, writes } = fixture();
|
|
const read = await api.handle(request('GET'), '/llm-settings');
|
|
assert.equal(read.has_api_key, true);
|
|
assert.ok(!('api_key' in read));
|
|
const saved = await api.handle(request('PUT'), '/llm-settings', { endpoint: config.endpoint, model: 'new-model' });
|
|
assert.equal(writes[0].body.api_key, 'secret');
|
|
assert.ok(!('api_key' in saved));
|
|
await assert.rejects(api.handle(request('PUT'), '/llm-settings', { endpoint: 'https://different.example/completions', model: 'model' }), /Enter or clear/);
|
|
await api.handle(request('PUT'), '/llm-settings', { ...config, api_key: '' });
|
|
assert.equal(writes[1].body.api_key, '');
|
|
});
|
|
|
|
for (const scope of ['event', 'session']) {
|
|
test(`generates and persists isolated ${scope} feedback with provenance`, async () => {
|
|
const { api, writes, reads } = fixture();
|
|
const summary = await api.handle(request(), '/feedback-summary', { scope, event_id: eventId, session_id: sessionId });
|
|
assert.equal(summary.summary, 'Helpful feedback summary');
|
|
assert.equal(summary.response_count, 1);
|
|
assert.equal(summary.source_fingerprint.length, 64);
|
|
assert.equal(summary.target_id, scope === 'session' ? sessionId : eventId);
|
|
assert.equal(writes.length, 1);
|
|
assert.equal(writes[0].prefer, 'resolution=merge-duplicates');
|
|
assert.ok(reads.some(path => path.includes(`/rest/v1/${scope === 'session' ? 'feedback' : 'event_feedback'}?event_id=eq.${eventId}`)));
|
|
if (scope === 'session') assert.ok(reads.some(path => path.includes(`&session_id=eq.${sessionId}`)));
|
|
assert.ok(!JSON.stringify(summary).includes('secret'));
|
|
});
|
|
}
|
|
|
|
test('no writes for empty feedback, absent config, wrong event or provider failure', async () => {
|
|
for (const options of [{ empty: true }, { noSettings: true }, { wrongSession: true }, { providerFetch: async () => new Response('{}', { status: 500 }) }]) {
|
|
const { api, writes } = fixture(options);
|
|
await assert.rejects(api.handle(request(), '/feedback-summary', { scope: 'session', event_id: eventId, session_id: sessionId }));
|
|
assert.equal(writes.length, 0);
|
|
}
|
|
});
|
|
|
|
test('includes feedback from every query page in the provider snapshot', async () => {
|
|
const { api, reads } = fixture({ feedbackCount: 501, providerFetch: async (_url, options) => {
|
|
const messages = JSON.parse(options.body).messages;
|
|
assert.equal(JSON.parse(messages[1].content).response_count, 501);
|
|
return new Response(JSON.stringify({ choices: [{ message: { content: 'All responses summarized' } }] }));
|
|
} });
|
|
const summary = await api.handle(request(), '/feedback-summary', { scope: 'event', event_id: eventId });
|
|
assert.equal(summary.response_count, 501);
|
|
assert.equal(reads.filter(path => path.includes('/event_feedback?')).length, 2);
|
|
});
|
|
|
|
test('rejects overlapping generation and releases lock after a failure', async () => {
|
|
let release;
|
|
const pending = new Promise(resolve => { release = resolve; });
|
|
let started;
|
|
const began = new Promise(resolve => { started = resolve; });
|
|
const { api } = fixture({ providerFetch: async () => { started(); await pending; throw new Error('fail'); } });
|
|
const body = { scope: 'event', event_id: eventId };
|
|
const first = api.handle(request(), '/feedback-summary', body);
|
|
await began;
|
|
await assert.rejects(api.handle(request(), '/feedback-summary', body), error => error.status === 409);
|
|
release();
|
|
await assert.rejects(first, error => error.status === 502);
|
|
await assert.rejects(api.handle(request(), '/feedback-summary', body), error => error.status === 502);
|
|
});
|
|
|
|
test('blocks private, loopback, metadata, mapped and reserved IP destinations', async () => {
|
|
for (const address of ['127.0.0.1', '10.0.0.1', '172.16.0.1', '192.168.1.1', '169.254.169.254', '0.0.0.0', '::1', '::ffff:127.0.0.1', 'fc00::1', 'fe80::1']) {
|
|
assert.equal(isPublicAddress(address), false, address);
|
|
}
|
|
assert.equal(isPublicAddress('8.8.8.8'), true);
|
|
await assert.rejects(resolveEndpoint(config.endpoint, async () => [{ address: '127.0.0.1', family: 4 }]), /public IP/);
|
|
const record = await resolveEndpoint(config.endpoint, async () => [{ address: '8.8.8.8', family: 4 }]);
|
|
assert.equal(record.address, '8.8.8.8');
|
|
});
|
|
|
|
const okReply = { choices: [{ message: { content: 'OK' } }], usage: { completion_tokens: 1, completion_tokens_details: { reasoning_tokens: 0 } } };
|
|
|
|
test('llm-test verifies the connection and sends thinking-disabled request', async () => {
|
|
const calls = [];
|
|
const { api, writes } = fixture({ providerFetch: async (url, options) => {
|
|
calls.push({ url, options, body: JSON.parse(options.body) });
|
|
return new Response(JSON.stringify(okReply));
|
|
} });
|
|
const verdict = await api.handle(request(), '/llm-test');
|
|
assert.equal(verdict.ok, true);
|
|
assert.equal(verdict.model, 'model');
|
|
assert.equal(verdict.endpoint, config.endpoint);
|
|
assert.equal(verdict.reasoning_disabled, true);
|
|
assert.equal(verdict.content, 'OK');
|
|
assert.equal(verdict.error, null);
|
|
assert.equal(typeof verdict.latency_ms, 'number');
|
|
assert.equal(writes.length, 0);
|
|
assert.equal(calls.length, 1);
|
|
assert.equal(calls[0].url, config.endpoint);
|
|
assert.equal(calls[0].options.headers.Authorization, 'Bearer secret');
|
|
// Same body shape as generateSummary, so the test really proves summaries work.
|
|
assert.equal(calls[0].body.model, 'model');
|
|
assert.equal(calls[0].body.stream, false);
|
|
assert.equal(calls[0].body.reasoning_effort, 'none');
|
|
assert.deepEqual(calls[0].body.chat_template_kwargs, { enable_thinking: false });
|
|
assert.equal(calls[0].body.thinking, undefined);
|
|
assert.ok(!JSON.stringify(verdict).includes('secret'));
|
|
});
|
|
|
|
test('llm-test reports thinking still on without calling it a clean pass', async () => {
|
|
const { api } = fixture({ providerFetch: async () => new Response(JSON.stringify({
|
|
choices: [{ message: { content: 'OK' } }],
|
|
usage: { completion_tokens: 236, completion_tokens_details: { reasoning_tokens: 235 } },
|
|
})) });
|
|
const verdict = await api.handle(request(), '/llm-test');
|
|
assert.equal(verdict.ok, true);
|
|
assert.equal(verdict.reasoning_disabled, false);
|
|
assert.equal(verdict.reasoning_tokens, 235);
|
|
assert.match(verdict.warning, /thinking is still enabled/);
|
|
});
|
|
|
|
test('llm-test treats an unreported reasoning count as unknown, not as a warning', async () => {
|
|
// What ai.lago.dev actually answers: a usage block whose
|
|
// completion_tokens_details is EMPTY. Reading that as "still thinking" told
|
|
// admins their working gateway was misconfigured, so the verdict has to be ok
|
|
// with no warning and reasoning_tokens: null — null means "not reported",
|
|
// deliberately different from 0, which means "reported and off".
|
|
const shapes = [
|
|
{ label: 'empty details', usage: { completion_tokens: 2, completion_tokens_details: {} } },
|
|
{ label: 'no usage block', usage: undefined },
|
|
{ label: 'details absent', usage: { completion_tokens: 2 } },
|
|
];
|
|
for (const shape of shapes) {
|
|
const { api } = fixture({ providerFetch: async () => new Response(JSON.stringify({
|
|
choices: [{ message: { content: 'OK' } }], usage: shape.usage,
|
|
})) });
|
|
const verdict = await api.handle(request(), '/llm-test');
|
|
assert.equal(verdict.ok, true, shape.label);
|
|
assert.equal(verdict.reasoning_tokens, null, shape.label);
|
|
assert.equal(verdict.reasoning_disabled, false, shape.label);
|
|
assert.equal(verdict.warning, null, shape.label);
|
|
}
|
|
});
|
|
|
|
test('llm-test answers ok:false for unconfigured settings, provider errors and blocked endpoints', async () => {
|
|
const cases = [
|
|
{ label: 'no settings stored', options: { noSettings: true }, match: /No LLM endpoint and model are configured/ },
|
|
{ label: 'endpoint stored without a model', options: { settingsRows: [{ ...config, model: '' }] }, match: /No LLM endpoint and model are configured/ },
|
|
{ label: 'provider 503', options: { providerFetch: async () => new Response(JSON.stringify({ error: { message: 'upstream unavailable' } }), { status: 503 }) }, match: /HTTP 503.*upstream unavailable/ },
|
|
{ label: 'provider network failure', options: { providerFetch: async () => { throw new Error('ECONNREFUSED'); } }, match: /failed or timed out/ },
|
|
{ label: 'endpoint fails SSRF validation', options: { validateEndpoint: async () => { throw new Error('LLM endpoint must resolve to a public IP address'); } }, match: /must resolve to a public IP/ },
|
|
];
|
|
for (const { label, options, match } of cases) {
|
|
const { api, writes } = fixture(options);
|
|
const verdict = await api.handle(request(), '/llm-test');
|
|
assert.equal(verdict.ok, false, label);
|
|
assert.match(verdict.error, match, label);
|
|
assert.equal(verdict.model, /no settings|endpoint stored/.test(label) ? '' : 'model', label);
|
|
assert.equal(writes.length, 0, label);
|
|
assert.ok(!JSON.stringify(verdict).includes('secret'), label);
|
|
}
|
|
// A blocked endpoint must never reach the provider.
|
|
let providerCalled = false;
|
|
const blocked = fixture({ validateEndpoint: async () => { throw new Error('private'); }, providerFetch: async () => { providerCalled = true; return new Response('{}'); } });
|
|
assert.equal((await blocked.api.handle(request(), '/llm-test')).ok, false);
|
|
assert.equal(providerCalled, false);
|
|
});
|
|
|
|
test('llm-test never leaks the stored key and rejects non-POST', async () => {
|
|
const { api } = fixture({ providerFetch: async () => new Response(JSON.stringify({ error: { message: `bad key: ${'secret'}` } }), { status: 401 }) });
|
|
const verdict = await api.handle(request(), '/llm-test');
|
|
assert.equal(verdict.ok, false);
|
|
assert.match(verdict.error, /HTTP 401/);
|
|
assert.ok(!verdict.error.includes('secret'));
|
|
assert.match(verdict.error, /\[redacted\]/);
|
|
await assert.rejects(api.handle(request('GET'), '/llm-test'), error => error.status === 405);
|
|
});
|
|
|
|
test('llm-test requires an authenticated admin', async () => {
|
|
const { api } = fixture({ unauthorized: true });
|
|
await assert.rejects(api.handle(request(), '/llm-test'), error => error.status === 401);
|
|
});
|