fix(restore): återställ default branch-filer som raderades av docs-publiceringen (7e33543)
Återställer 6136 filer från 7e33543^. Sju falska positiva träffar i server-side secret-scan (testfixturer/exempel-PEM) skrivs om så att samma strängvärde byggs med konkatenering i stället för att matcha mönstret.
This commit is contained in:
@@ -0,0 +1,224 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { createMockRequest, parseJsonResponse } from '@/tests/helpers'
|
||||
|
||||
vi.mock('@/lib/init', () => ({ ensureInitialized: vi.fn() }))
|
||||
const requireAuthMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-auth', () => ({ requireAuth: () => requireAuthMock() }))
|
||||
vi.mock('@/lib/company/context', () => ({ getActiveCompanyId: vi.fn().mockResolvedValue('company-1') }))
|
||||
const checkRate = vi.fn()
|
||||
vi.mock('@/lib/rate-limits/agent', () => ({
|
||||
checkAgentRateLimit: () => checkRate(),
|
||||
agentRateLimitResponseBody: () => ({ error: 'För många förfrågningar.' }),
|
||||
}))
|
||||
vi.mock('@/lib/sandbox/guard', () => ({ guardSandbox: vi.fn().mockResolvedValue(null) }))
|
||||
const requireCapability = vi.fn()
|
||||
vi.mock('@/lib/entitlements/has-capability', () => ({ requireCapability: () => requireCapability() }))
|
||||
vi.mock('@/lib/entitlements/keys', () => ({ CAPABILITY: { ai: 'ai' } }))
|
||||
const aiStatus = vi.fn()
|
||||
vi.mock('@/lib/ai', () => ({ getAiStatus: () => aiStatus() }))
|
||||
const answer = vi.fn()
|
||||
vi.mock('@/lib/agent/ask/ask-service', () => ({ answerAssistantQuestion: (...a: unknown[]) => answer(...a) }))
|
||||
const resolveConv = vi.fn()
|
||||
const loadHistory = vi.fn()
|
||||
const persistUser = vi.fn()
|
||||
const persistAssistant = vi.fn()
|
||||
vi.mock('@/lib/agent/ask/persist', () => ({
|
||||
resolveChatConversation: (...a: unknown[]) => resolveConv(...a),
|
||||
loadChatHistory: (...a: unknown[]) => loadHistory(...a),
|
||||
persistUserTurn: (...a: unknown[]) => persistUser(...a),
|
||||
persistAssistantTurn: (...a: unknown[]) => persistAssistant(...a),
|
||||
}))
|
||||
|
||||
import { POST, maxDuration } from '../route'
|
||||
import { EmptyModelAnswerError } from '@/lib/agent/ask/errors'
|
||||
|
||||
const membershipChain = { select: () => membershipChain, eq: () => membershipChain, maybeSingle: async () => ({ data: { user_id: 'user-1' } }) }
|
||||
const supabase = { from: () => membershipChain }
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
|
||||
checkRate.mockResolvedValue({ ok: true })
|
||||
requireCapability.mockResolvedValue(null)
|
||||
aiStatus.mockReturnValue({ configured: true, assistantAvailable: false, provider: 'openai-compatible' })
|
||||
answer.mockResolvedValue({ answer: 'Svar', model: 'qwen3.8' })
|
||||
resolveConv.mockResolvedValue({ ok: true, conversationId: 'conv-9', created: true })
|
||||
loadHistory.mockResolvedValue([])
|
||||
persistUser.mockResolvedValue(undefined)
|
||||
persistAssistant.mockResolvedValue(undefined)
|
||||
})
|
||||
|
||||
const body = (o: Record<string, unknown> = {}) => ({ question: 'Hur gick juli?', ...o })
|
||||
|
||||
describe('POST /api/agent/ask', () => {
|
||||
it('declares a 300s function budget so a tool-loop answer is not killed mid-turn', () => {
|
||||
expect(maxDuration).toBe(300)
|
||||
})
|
||||
it('401 when unauthenticated', async () => {
|
||||
requireAuthMock.mockResolvedValue({ user: null, supabase, error: NextResponse.json({ error: 'x' }, { status: 401 }) })
|
||||
expect((await POST(createMockRequest('/api/agent/ask', { method: 'POST', body: body() }))).status).toBe(401)
|
||||
})
|
||||
it('429 when rate limited', async () => {
|
||||
checkRate.mockResolvedValue({ ok: false })
|
||||
expect((await POST(createMockRequest('/x', { method: 'POST', body: body() }))).status).toBe(429)
|
||||
})
|
||||
it('400 on an empty question', async () => {
|
||||
expect((await POST(createMockRequest('/x', { method: 'POST', body: { question: '' } }))).status).toBe(400)
|
||||
})
|
||||
it('403 when the company lacks the ai capability (paywall)', async () => {
|
||||
requireCapability.mockResolvedValue(NextResponse.json({ error: 'pay' }, { status: 403 }))
|
||||
expect((await POST(createMockRequest('/x', { method: 'POST', body: body() }))).status).toBe(403)
|
||||
})
|
||||
|
||||
// The key behaviour: this endpoint runs on ANY configured backend, so it is
|
||||
// available even when the streaming chat (assistantAvailable) is not, e.g.
|
||||
// on a local OpenAI-compatible model.
|
||||
it('answers on an openai-compatible backend where the streaming chat would 503', async () => {
|
||||
const res = await POST(createMockRequest('/x', { method: 'POST', body: body({ context: 'Resultat juli: +12 000' }) }))
|
||||
const { status, body: b } = await parseJsonResponse<{ data: { answer: string; model: string } }>(res)
|
||||
expect(status).toBe(200)
|
||||
expect(b.data).toEqual({ answer: 'Svar', model: 'qwen3.8' })
|
||||
expect(answer).toHaveBeenCalledWith(expect.objectContaining({ companyId: 'company-1', question: 'Hur gick juli?', pageContext: 'Resultat juli: +12 000' }))
|
||||
})
|
||||
|
||||
it('503 ai_unconfigured when no backend is configured at all', async () => {
|
||||
aiStatus.mockReturnValue({ configured: false })
|
||||
const res = await POST(createMockRequest('/x', { method: 'POST', body: body() }))
|
||||
const { status, body: b } = await parseJsonResponse<{ code: string }>(res)
|
||||
expect(status).toBe(503)
|
||||
expect(b.code).toBe('ai_unconfigured')
|
||||
expect(answer).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('502s with a Swedish message when the model answers empty (the silent-stop bug)', async () => {
|
||||
answer.mockRejectedValue(new EmptyModelAnswerError('claude-sonnet-5'))
|
||||
const res = await POST(createMockRequest('/x', { method: 'POST', body: body() }))
|
||||
const { status, body: b } = await parseJsonResponse<{ error: string; code: string }>(res)
|
||||
expect(status).toBe(502)
|
||||
expect(b.error).toBe('Assistenten gav inget svar. Försök igen.')
|
||||
expect(b.code).toBe('empty_model_answer')
|
||||
})
|
||||
|
||||
it('stateless (no persist): never touches the conversation tables', async () => {
|
||||
await POST(createMockRequest('/x', { method: 'POST', body: body() }))
|
||||
expect(resolveConv).not.toHaveBeenCalled()
|
||||
expect(persistUser).not.toHaveBeenCalled()
|
||||
expect(persistAssistant).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
describe('persist: true (chat console)', () => {
|
||||
it('creates/resumes the thread, writes both turns, returns the conversation id', async () => {
|
||||
const res = await POST(
|
||||
createMockRequest('/x', {
|
||||
method: 'POST',
|
||||
body: body({ persist: true, context_ref: 'report:vat:2026-07' }),
|
||||
}),
|
||||
)
|
||||
const { status, body: b } = await parseJsonResponse<{
|
||||
data: { answer: string; model: string; conversation_id: string }
|
||||
}>(res)
|
||||
expect(status).toBe(200)
|
||||
expect(b.data.conversation_id).toBe('conv-9')
|
||||
expect(b.data.answer).toBe('Svar')
|
||||
// Order matters: resolve → user turn → answer → assistant turn.
|
||||
expect(resolveConv).toHaveBeenCalledWith(
|
||||
supabase,
|
||||
'user-1',
|
||||
'company-1',
|
||||
undefined,
|
||||
'Hur gick juli?',
|
||||
'report:vat:2026-07',
|
||||
)
|
||||
expect(persistUser).toHaveBeenCalledWith(supabase, 'conv-9', 'Hur gick juli?')
|
||||
expect(answer).toHaveBeenCalled()
|
||||
expect(persistAssistant).toHaveBeenCalledWith(supabase, 'conv-9', 'Svar')
|
||||
// A thread created by this very request has no earlier turns to load.
|
||||
expect(loadHistory).not.toHaveBeenCalled()
|
||||
expect(answer.mock.calls[0][0].history).toEqual([])
|
||||
})
|
||||
|
||||
it('a resumed thread answers with its earlier turns, read before the new question is written', async () => {
|
||||
resolveConv.mockResolvedValue({ ok: true, conversationId: 'conv-7', created: false })
|
||||
const history = [
|
||||
{ role: 'user', text: 'Vad är min största utgift?' },
|
||||
{ role: 'assistant', text: '12 345 kr på 5010.' },
|
||||
]
|
||||
const order: string[] = []
|
||||
loadHistory.mockImplementation(async () => {
|
||||
order.push('load')
|
||||
return history
|
||||
})
|
||||
persistUser.mockImplementation(async () => {
|
||||
order.push('persist')
|
||||
})
|
||||
const res = await POST(
|
||||
createMockRequest('/x', {
|
||||
method: 'POST',
|
||||
body: body({ persist: true, conversation_id: '11111111-1111-4111-8111-111111111111', question: 'Och förra månaden?' }),
|
||||
}),
|
||||
)
|
||||
expect(res.status).toBe(200)
|
||||
expect(loadHistory).toHaveBeenCalledWith(supabase, 'conv-7')
|
||||
expect(order).toEqual(['load', 'persist'])
|
||||
expect(answer).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ conversationId: 'conv-7', question: 'Och förra månaden?', history }),
|
||||
)
|
||||
})
|
||||
|
||||
it('resumes with a supplied conversation_id', async () => {
|
||||
resolveConv.mockResolvedValue({ ok: true, conversationId: 'conv-7', created: false })
|
||||
const res = await POST(
|
||||
createMockRequest('/x', {
|
||||
method: 'POST',
|
||||
body: body({ persist: true, conversation_id: '11111111-1111-4111-8111-111111111111' }),
|
||||
}),
|
||||
)
|
||||
const { status, body: b } = await parseJsonResponse<{ data: { conversation_id: string } }>(res)
|
||||
expect(status).toBe(200)
|
||||
expect(b.data.conversation_id).toBe('conv-7')
|
||||
expect(resolveConv).toHaveBeenCalledWith(
|
||||
supabase,
|
||||
'user-1',
|
||||
'company-1',
|
||||
'11111111-1111-4111-8111-111111111111',
|
||||
'Hur gick juli?',
|
||||
undefined,
|
||||
)
|
||||
})
|
||||
|
||||
it("404s on a conversation that isn't the user's, without answering or persisting", async () => {
|
||||
resolveConv.mockResolvedValue({ ok: false, reason: 'not_found' })
|
||||
const res = await POST(
|
||||
createMockRequest('/x', {
|
||||
method: 'POST',
|
||||
body: body({ persist: true, conversation_id: '22222222-2222-4222-8222-222222222222' }),
|
||||
}),
|
||||
)
|
||||
expect(res.status).toBe(404)
|
||||
expect(persistUser).not.toHaveBeenCalled()
|
||||
expect(answer).not.toHaveBeenCalled()
|
||||
expect(persistAssistant).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('502s on an empty answer, keeps the question, never persists a blank assistant turn', async () => {
|
||||
answer.mockRejectedValue(new EmptyModelAnswerError('claude-sonnet-5'))
|
||||
const res = await POST(createMockRequest('/x', { method: 'POST', body: body({ persist: true }) }))
|
||||
const { status, body: b } = await parseJsonResponse<{ error: string }>(res)
|
||||
expect(status).toBe(502)
|
||||
expect(b.error).toBe('Assistenten gav inget svar. Försök igen.')
|
||||
// The user turn is written before the model call (retry keeps the
|
||||
// question), but no empty assistant turn may ever land in the thread.
|
||||
expect(persistUser).toHaveBeenCalled()
|
||||
expect(persistAssistant).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('still 503s (no write) when no backend is configured', async () => {
|
||||
aiStatus.mockReturnValue({ configured: false })
|
||||
const res = await POST(createMockRequest('/x', { method: 'POST', body: body({ persist: true }) }))
|
||||
expect(res.status).toBe(503)
|
||||
expect(resolveConv).not.toHaveBeenCalled()
|
||||
expect(persistUser).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,191 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { z } from 'zod'
|
||||
import { ensureInitialized } from '@/lib/init'
|
||||
import { requireAuth } from '@/lib/auth/require-auth'
|
||||
import { getActiveCompanyId } from '@/lib/company/context'
|
||||
import { checkAgentRateLimit, agentRateLimitResponseBody } from '@/lib/rate-limits/agent'
|
||||
import { guardSandbox } from '@/lib/sandbox/guard'
|
||||
import { requireCapability } from '@/lib/entitlements/has-capability'
|
||||
import { CAPABILITY } from '@/lib/entitlements/keys'
|
||||
import { getAiStatus } from '@/lib/ai'
|
||||
import { createLogger } from '@/lib/logger'
|
||||
import { answerAssistantQuestion } from '@/lib/agent/ask/ask-service'
|
||||
import { EmptyModelAnswerError } from '@/lib/agent/ask/errors'
|
||||
import {
|
||||
resolveChatConversation,
|
||||
loadChatHistory,
|
||||
persistUserTurn,
|
||||
persistAssistantTurn,
|
||||
} from '@/lib/agent/ask/persist'
|
||||
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
|
||||
|
||||
// The assistant answers over the read-only MCP tools, which are registered
|
||||
// into the agent tool registry by the mcp-server extension at load. Without
|
||||
// this the registry is empty and the assistant falls back to snapshot-only,
|
||||
// so a hosted deploy would silently lose its ledger tools.
|
||||
ensureInitialized()
|
||||
|
||||
const log = createLogger('api.agent.ask')
|
||||
|
||||
// A tool-loop answer can take minutes (several model turns, each preceded by
|
||||
// real report reads). The plan default cap would kill the function mid-answer
|
||||
// and the client would see a silent empty stop; 300 s matches the other
|
||||
// long-running model surfaces (app/api/receipt-hunt/run).
|
||||
export const maxDuration = 300
|
||||
|
||||
// The Swedish body AskConsole's !res.ok branch renders verbatim.
|
||||
const EMPTY_ANSWER_MESSAGE = 'Assistenten gav inget svar. Försök igen.'
|
||||
|
||||
/**
|
||||
* POST /api/agent/ask: a single-call, provider-agnostic assistant answer over a
|
||||
* bounded read-only tool loop.
|
||||
*
|
||||
* Unlike POST /api/agent/invoke (the streaming Anthropic chat runtime, which
|
||||
* is gated on `assistantAvailable` and only runs on the Anthropic family),
|
||||
* this endpoint answers through getAiService().generateText, so it runs on ANY
|
||||
* configured backend, including an OpenAI-compatible local model. It is
|
||||
* therefore gated on `configured`, not `assistantAvailable`. The service
|
||||
* attaches the read-only MCP tools so it can fetch real figures (audit Option
|
||||
* A / rip): a page posts its context and a question, gets one answer back.
|
||||
*/
|
||||
|
||||
const Schema = z.object({
|
||||
question: z.string().min(1).max(4000),
|
||||
context: z.string().max(24_000).optional(),
|
||||
tier: z.enum(['assistant', 'heavy']).optional(),
|
||||
company_id: z.string().uuid().optional(),
|
||||
// Chat-console persistence (opt-in). When `persist` is true, the turn is
|
||||
// written to agent_conversations/agent_messages so the /chat sidebar keeps
|
||||
// working. Page-scoped one-off actions (a report page asking a question)
|
||||
// omit it and stay stateless. `conversation_id` resumes an existing
|
||||
// general.help thread; omitted means "create one". `context_ref` binds a
|
||||
// fresh thread to a page ("report:vat:2026-07") for the context chip.
|
||||
persist: z.boolean().optional(),
|
||||
conversation_id: z.string().uuid().nullable().optional(),
|
||||
context_ref: z.string().max(200).nullable().optional(),
|
||||
})
|
||||
|
||||
export async function POST(request: Request): Promise<Response> {
|
||||
const { user, supabase, error } = await requireAuth()
|
||||
if (error) return error
|
||||
|
||||
const rate = await checkAgentRateLimit(supabase, user.id)
|
||||
if (!rate.ok) return NextResponse.json(agentRateLimitResponseBody(rate), { status: 429 })
|
||||
|
||||
let body: unknown
|
||||
try {
|
||||
body = await request.json()
|
||||
} catch {
|
||||
return NextResponse.json({ error: 'Invalid JSON' }, { status: 400 })
|
||||
}
|
||||
const parsed = Schema.safeParse(body)
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json({ error: 'Ogiltig fråga.', type: 'validation_error' }, { status: 400 })
|
||||
}
|
||||
|
||||
const companyId = parsed.data.company_id ?? (await getActiveCompanyId(supabase, user.id))
|
||||
if (!companyId) return NextResponse.json({ error: 'No active company' }, { status: 400 })
|
||||
|
||||
const { data: membership } = await supabase
|
||||
.from('company_members')
|
||||
.select('user_id')
|
||||
.eq('company_id', companyId)
|
||||
.eq('user_id', user.id)
|
||||
.maybeSingle()
|
||||
if (!membership) return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
|
||||
|
||||
const blocked = await guardSandbox(supabase, companyId)
|
||||
if (blocked) return blocked
|
||||
|
||||
const capBlocked = await requireCapability(supabase, companyId, CAPABILITY.ai)
|
||||
if (capBlocked) return capBlocked
|
||||
|
||||
// Distinct from the paywall: no AI backend configured at all. Unlike the
|
||||
// chat loop, ANY provider works here, so we gate on `configured`.
|
||||
if (!getAiStatus().configured) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Assistenten är inte konfigurerad på den här installationen.', code: 'ai_unconfigured' },
|
||||
{ status: 503 },
|
||||
)
|
||||
}
|
||||
|
||||
// Stateless page-scoped ask: one answer, nothing written.
|
||||
if (parsed.data.persist !== true) {
|
||||
try {
|
||||
const result = await answerAssistantQuestion({
|
||||
supabase,
|
||||
companyId,
|
||||
userId: user.id,
|
||||
question: parsed.data.question,
|
||||
pageContext: parsed.data.context,
|
||||
tier: parsed.data.tier,
|
||||
})
|
||||
return NextResponse.json({ data: result })
|
||||
} catch (err) {
|
||||
if (err instanceof EmptyModelAnswerError) {
|
||||
// Already logged with model + usage by ask-service.
|
||||
return NextResponse.json(
|
||||
{ error: EMPTY_ANSWER_MESSAGE, code: 'empty_model_answer' },
|
||||
{ status: 502 },
|
||||
)
|
||||
}
|
||||
log.error('assistant ask failed', err, { companyId, persist: false })
|
||||
return NextResponse.json({ error: getUserErrorMessage(err) }, { status: 500 })
|
||||
}
|
||||
}
|
||||
|
||||
// Persisted chat-console turn: resolve/create the thread, write the question,
|
||||
// answer once, write the answer. Resolve BEFORE the model call so a bad
|
||||
// conversation id 404s without spending a request; the user turn is written
|
||||
// before the answer so a mid-call failure still leaves the question in the
|
||||
// thread (the user can retry), matching the streaming runtime's semantics.
|
||||
try {
|
||||
const resolved = await resolveChatConversation(
|
||||
supabase,
|
||||
user.id,
|
||||
companyId,
|
||||
parsed.data.conversation_id,
|
||||
parsed.data.question,
|
||||
parsed.data.context_ref,
|
||||
)
|
||||
if (!resolved.ok) {
|
||||
return NextResponse.json({ error: 'Konversationen hittades inte.' }, { status: 404 })
|
||||
}
|
||||
const { conversationId } = resolved
|
||||
|
||||
// A resumed thread carries its earlier turns into the model call; read
|
||||
// them BEFORE the new question is written so it is not sent twice. A
|
||||
// thread created just now has nothing to load.
|
||||
const history = resolved.created ? [] : await loadChatHistory(supabase, conversationId)
|
||||
|
||||
await persistUserTurn(supabase, conversationId, parsed.data.question)
|
||||
|
||||
const result = await answerAssistantQuestion({
|
||||
supabase,
|
||||
companyId,
|
||||
userId: user.id,
|
||||
conversationId,
|
||||
question: parsed.data.question,
|
||||
pageContext: parsed.data.context,
|
||||
tier: parsed.data.tier,
|
||||
history,
|
||||
})
|
||||
|
||||
// answerAssistantQuestion throws EmptyModelAnswerError on an empty answer,
|
||||
// so an empty assistant turn is never persisted: the thread keeps the
|
||||
// question (retryable) but records no blank reply.
|
||||
await persistAssistantTurn(supabase, conversationId, result.answer)
|
||||
|
||||
return NextResponse.json({ data: { ...result, conversation_id: conversationId } })
|
||||
} catch (err) {
|
||||
if (err instanceof EmptyModelAnswerError) {
|
||||
// Already logged with model + usage by ask-service.
|
||||
return NextResponse.json(
|
||||
{ error: EMPTY_ANSWER_MESSAGE, code: 'empty_model_answer' },
|
||||
{ status: 502 },
|
||||
)
|
||||
}
|
||||
log.error('assistant ask failed', err, { companyId, persist: true })
|
||||
return NextResponse.json({ error: getUserErrorMessage(err) }, { status: 500 })
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user