Files
CatoandClaude Opus 5.5 ce98b0cc24 fix(ai): context extraction only on the user's own key; vendors by id (main green again) (#205)
* fix(ai): pick chain vendors by id, and make main green again

main has been red since #203 bumped @bitbaum/ai-kit to 1.10, which put
Gemini second in freeChain('BOTSMANN'). vendorChain() indexed [1] for
OpenRouter, so a BYOK OpenRouter user's key would have been sent down the
Gemini link. Look vendors up by id instead (code and both tests).

Also clears the rest of the red verify from the same bump: prettier 3.x
reformat of six files and the new next lint rule on relative
window.location.href assignments (sign-out keeps its full reload).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Signed-off-by: Cato <41178744+catomean@users.noreply.github.com>

* fix(ai): context extraction runs only on the user's own key

Every professional-chat turn fired a second, unasked model call
(extractAndSaveContext, fire-and-forget after the answer) on the shared
free-tier Groq key. Standing rule (2026-09-25): free-tier keys are spent
only when a person deliberately asks. Extraction now requires the user's
own key and uses their provider; without one it returns before any call.

Adds tests/__tests__/no-free-background-ai.test.ts: walks the import graph
from the timer route (/api/rebuild, appcron-botsmann-rebuild), /api/warmup
and /api/health and fails if any reaches a model client. Proven by
mutation: importing lib/nlp into /api/rebuild fails it, and dropping the
own-key guard fails the three new extractor cases.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Signed-off-by: Cato <41178744+catomean@users.noreply.github.com>

---------

Signed-off-by: Cato <41178744+catomean@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-25 00:44:17 -07:00

223 lines
6.9 KiB
TypeScript

import { extractAndSaveContext } from '@/lib/context/extractor';
// Mock dependencies
vi.mock('@/lib/llm-client', () => ({
generateLLMResponse: vi.fn(),
}));
vi.mock('@/lib/context/store', () => ({
saveUserContext: vi.fn(),
}));
vi.mock('@/lib/context/domain-detector', () => ({
detectDomains: vi.fn(),
}));
import { generateLLMResponse } from '@/lib/llm-client';
import { saveUserContext } from '@/lib/context/store';
import { detectDomains } from '@/lib/context/domain-detector';
import type { Mock } from 'vitest';
/** The user's own key. Without one, extraction must not call a model at all. */
const OWN = { provider: 'groq' as const, apiKey: 'gsk_users_own' };
beforeEach(() => {
vi.clearAllMocks();
(detectDomains as Mock).mockReturnValue(['general']);
});
describe('extractAndSaveContext', () => {
it.each([null, undefined, ''])(
"never calls a model without the user's own key (apiKey=%s) — the shared free tier is not for background work",
async (apiKey) => {
(generateLLMResponse as Mock).mockResolvedValue({
content: '[{"fact":"x","confidence":0.9}]',
});
const result = await extractAndSaveContext(
'user-1',
'conv-1',
'I live in Zürich',
'Nice',
undefined,
{
provider: 'groq',
apiKey,
},
);
expect(result).toBe(0);
expect(generateLLMResponse).not.toHaveBeenCalled();
},
);
it('extracts facts from conversation and saves them', async () => {
(generateLLMResponse as Mock).mockResolvedValue({
content: JSON.stringify([
{ fact: 'User lives in Zürich', confidence: 0.9 },
{ fact: 'User has two children', confidence: 0.85 },
]),
});
(saveUserContext as Mock).mockResolvedValue(2);
const result = await extractAndSaveContext(
'user-1',
'conv-1',
'I live in Zürich with my two kids',
'That sounds lovely!',
undefined,
OWN,
);
expect(result).toBe(2);
expect(generateLLMResponse).toHaveBeenCalledWith(
expect.arrayContaining([
expect.objectContaining({ role: 'system' }),
expect.objectContaining({
role: 'user',
content: expect.stringContaining('I live in Zürich with my two kids'),
}),
]),
expect.objectContaining({ provider: 'groq', apiKey: 'gsk_users_own', temperature: 0.1 }),
);
expect(saveUserContext).toHaveBeenCalledWith('user-1', [
expect.objectContaining({
content: 'User lives in Zürich',
sourceType: 'conversation',
sourceId: 'conv-1',
confidence: 0.9,
}),
expect.objectContaining({
content: 'User has two children',
confidence: 0.85,
}),
]);
});
it('uses professional domain when provided', async () => {
(generateLLMResponse as Mock).mockResolvedValue({
content: JSON.stringify([{ fact: 'User has back pain', confidence: 0.9 }]),
});
(saveUserContext as Mock).mockResolvedValue(1);
await extractAndSaveContext(
'user-1',
'conv-1',
'My back hurts',
'Sorry to hear',
'health',
OWN,
);
expect(saveUserContext).toHaveBeenCalledWith('user-1', [
expect.objectContaining({
domains: ['health', 'general'],
}),
]);
// detectDomains should NOT be called when professional domain is provided
expect(detectDomains).not.toHaveBeenCalled();
});
it('uses detectDomains when no professional domain', async () => {
(generateLLMResponse as Mock).mockResolvedValue({
content: JSON.stringify([{ fact: 'User needs a lawyer', confidence: 0.8 }]),
});
(detectDomains as Mock).mockReturnValue(['legal', 'general']);
(saveUserContext as Mock).mockResolvedValue(1);
await extractAndSaveContext('user-1', 'conv-1', 'I need legal help', 'Sure', undefined, OWN);
expect(detectDomains).toHaveBeenCalledWith('User needs a lawyer');
expect(saveUserContext).toHaveBeenCalledWith('user-1', [
expect.objectContaining({
domains: ['legal', 'general'],
}),
]);
});
it('returns 0 when no facts extracted', async () => {
(generateLLMResponse as Mock).mockResolvedValue({
content: JSON.stringify([]),
});
const result = await extractAndSaveContext('user-1', 'conv-1', 'Hello', 'Hi!', undefined, OWN);
expect(result).toBe(0);
expect(saveUserContext).not.toHaveBeenCalled();
});
it('returns 0 when LLM returns invalid JSON', async () => {
(generateLLMResponse as Mock).mockResolvedValue({
content: 'not json',
});
const result = await extractAndSaveContext('user-1', 'conv-1', 'Hi', 'Hello', undefined, OWN);
expect(result).toBe(0);
});
it('returns 0 when LLM returns non-array JSON', async () => {
(generateLLMResponse as Mock).mockResolvedValue({
content: JSON.stringify({ fact: 'not an array' }),
});
const result = await extractAndSaveContext('user-1', 'conv-1', 'Hi', 'Hello', undefined, OWN);
expect(result).toBe(0);
});
it('returns 0 when LLM call throws', async () => {
(generateLLMResponse as Mock).mockRejectedValue(new Error('API error'));
const result = await extractAndSaveContext('user-1', 'conv-1', 'Hi', 'Hello', undefined, OWN);
expect(result).toBe(0);
});
it('filters out facts exceeding 200 characters', async () => {
const longFact = 'A'.repeat(201);
(generateLLMResponse as Mock).mockResolvedValue({
content: JSON.stringify([
{ fact: longFact, confidence: 0.9 },
{ fact: 'Short valid fact', confidence: 0.8 },
]),
});
(saveUserContext as Mock).mockResolvedValue(1);
await extractAndSaveContext('user-1', 'conv-1', 'msg', 'resp', undefined, OWN);
expect(saveUserContext).toHaveBeenCalledWith('user-1', [
expect.objectContaining({ content: 'Short valid fact' }),
]);
});
it('clamps confidence to 0.5-1.0 range', async () => {
(generateLLMResponse as Mock).mockResolvedValue({
content: JSON.stringify([
{ fact: 'Low confidence', confidence: 0.1 },
{ fact: 'High confidence', confidence: 1.5 },
{ fact: 'No confidence' },
]),
});
(saveUserContext as Mock).mockResolvedValue(3);
await extractAndSaveContext('user-1', 'conv-1', 'msg', 'resp', undefined, OWN);
const savedFacts = (saveUserContext as Mock).mock.calls[0][1];
expect(savedFacts[0].confidence).toBe(0.5);
expect(savedFacts[1].confidence).toBe(1.0);
expect(savedFacts[2].confidence).toBe(0.8); // default
});
it('filters out facts with empty string', async () => {
(generateLLMResponse as Mock).mockResolvedValue({
content: JSON.stringify([
{ fact: '', confidence: 0.9 },
{ fact: 'Valid fact', confidence: 0.8 },
]),
});
(saveUserContext as Mock).mockResolvedValue(1);
await extractAndSaveContext('user-1', 'conv-1', 'msg', 'resp', undefined, OWN);
expect(saveUserContext).toHaveBeenCalledWith('user-1', [
expect.objectContaining({ content: 'Valid fact' }),
]);
});
});