docs(production): standardiserad produktionsberedskap och gap-analys
Lägger docs/production-readiness.md och siax/production-gaps.json enligt SIAX Master Definition of Done. Underlag: git-, kod- och live-evidens 2026-11-11. Nivån är evidensbaserad, inte ett leveransgodkännande.
This commit is contained in:
@@ -1,102 +0,0 @@
|
||||
/**
|
||||
* Tests for POST /api/agent/composer.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { createQueuedMockSupabase, createMockRequest, parseJsonResponse } from '@/tests/helpers'
|
||||
|
||||
const { supabase, enqueue, reset } = createQueuedMockSupabase()
|
||||
|
||||
const requireAuthMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-auth', () => ({
|
||||
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/company/context', () => ({
|
||||
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
}))
|
||||
|
||||
const checkRateMock = vi.fn()
|
||||
vi.mock('@/lib/rate-limits/agent', () => ({
|
||||
checkAgentRateLimit: (...args: unknown[]) => checkRateMock(...args),
|
||||
agentRateLimitResponseBody: () => ({ error: 'För många förfrågningar.' }),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/sandbox/guard', () => ({
|
||||
guardSandbox: vi.fn().mockResolvedValue(null),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/entitlements/has-capability', () => ({
|
||||
requireCapability: vi.fn().mockResolvedValue(null),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/entitlements/keys', () => ({
|
||||
CAPABILITY: { ai: 'ai' },
|
||||
}))
|
||||
|
||||
const composeMock = vi.fn()
|
||||
vi.mock('@/lib/agent/composer', () => ({
|
||||
composeAgentProfile: (...args: unknown[]) => composeMock(...args),
|
||||
}))
|
||||
|
||||
import { POST } from '../composer/route'
|
||||
|
||||
const routeParams = { params: Promise.resolve({}) }
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
reset()
|
||||
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
|
||||
checkRateMock.mockResolvedValue({ ok: true })
|
||||
})
|
||||
|
||||
describe('POST /api/agent/composer', () => {
|
||||
it('returns 401 when not authenticated', async () => {
|
||||
requireAuthMock.mockResolvedValue({
|
||||
user: null,
|
||||
supabase,
|
||||
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
|
||||
})
|
||||
const req = createMockRequest('/api/agent/composer', { method: 'POST', body: {} })
|
||||
const res = await POST(req, routeParams)
|
||||
expect(res.status).toBe(401)
|
||||
})
|
||||
|
||||
it('returns 429 when rate limited', async () => {
|
||||
checkRateMock.mockResolvedValue({ ok: false, retryAfterSec: 30 })
|
||||
|
||||
const req = createMockRequest('/api/agent/composer', { method: 'POST', body: {} })
|
||||
const res = await POST(req, routeParams)
|
||||
expect(res.status).toBe(429)
|
||||
expect(res.headers.get('Retry-After')).toBe('30')
|
||||
})
|
||||
|
||||
it('refuses a viewer with 403 (composer rewrites the profile)', async () => {
|
||||
enqueue({ data: { role: 'viewer' } })
|
||||
|
||||
const req = createMockRequest('/api/agent/composer', { method: 'POST', body: {} })
|
||||
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(
|
||||
await POST(req, routeParams)
|
||||
)
|
||||
expect(status).toBe(403)
|
||||
expect(body.error.code).toBe('WRITE_PERMISSION_REQUIRED')
|
||||
expect(composeMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('runs the composer for a non-viewer member', async () => {
|
||||
enqueue({ data: { role: 'owner' } })
|
||||
composeMock.mockResolvedValue({ company_id: 'company-1', profile_summary: 'Byggd' })
|
||||
|
||||
const req = createMockRequest('/api/agent/composer', {
|
||||
method: 'POST',
|
||||
body: { dry_run: true },
|
||||
})
|
||||
const { status, body } = await parseJsonResponse<{ data: { profile_summary: string } }>(
|
||||
await POST(req, routeParams)
|
||||
)
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.profile_summary).toBe('Byggd')
|
||||
expect(composeMock).toHaveBeenCalledWith(expect.anything(), 'company-1', { dryRun: true })
|
||||
})
|
||||
})
|
||||
@@ -1,176 +0,0 @@
|
||||
/**
|
||||
* Tests for GET /api/agent/conversations and GET/PATCH /api/agent/conversations/[id].
|
||||
*
|
||||
* Uses a filter-capturing Supabase mock so the user-scoping regression is
|
||||
* locked in: RLS on agent_conversations is company-scoped, so the explicit
|
||||
* .eq('user_id', …) filter in the list route is the only thing preventing
|
||||
* team members from seeing each other's conversation titles/previews.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { createMockRequest, parseJsonResponse } from '@/tests/helpers'
|
||||
|
||||
const requireAuthMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-auth', () => ({
|
||||
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/company/context', () => ({
|
||||
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
}))
|
||||
|
||||
import { GET as listGET } from '../conversations/route'
|
||||
import { GET as detailGET, PATCH as detailPATCH } from '../conversations/[id]/route'
|
||||
|
||||
interface CapturedCall {
|
||||
method: string
|
||||
args: unknown[]
|
||||
}
|
||||
|
||||
/** Chainable builder that records every call and resolves queued results per from(). */
|
||||
function createCapturingSupabase(results: { data?: unknown; error?: unknown }[]) {
|
||||
const calls: CapturedCall[] = []
|
||||
let idx = 0
|
||||
const makeBuilder = () => {
|
||||
const result = results[idx++] ?? { data: null, error: null }
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const b: any = {}
|
||||
for (const m of ['select', 'eq', 'is', 'or', 'order', 'limit', 'insert', 'update', 'maybeSingle', 'single']) {
|
||||
b[m] = (...args: unknown[]) => {
|
||||
calls.push({ method: m, args })
|
||||
return b
|
||||
}
|
||||
}
|
||||
b.then = (resolve: (v: unknown) => void) =>
|
||||
resolve({ data: result.data ?? null, error: result.error ?? null, count: null })
|
||||
return b
|
||||
}
|
||||
const supabase = {
|
||||
from: (table: string) => {
|
||||
calls.push({ method: 'from', args: [table] })
|
||||
return makeBuilder()
|
||||
},
|
||||
}
|
||||
return { supabase, calls }
|
||||
}
|
||||
|
||||
const routeParams = { params: Promise.resolve({}) }
|
||||
const idParams = { params: Promise.resolve({ id: 'conv-1' }) }
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
describe('GET /api/agent/conversations', () => {
|
||||
it('returns 401 when not authenticated', async () => {
|
||||
requireAuthMock.mockResolvedValue({
|
||||
user: null,
|
||||
supabase: {},
|
||||
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
|
||||
})
|
||||
|
||||
const res = await listGET(createMockRequest('/api/agent/conversations'), routeParams)
|
||||
expect(res.status).toBe(401)
|
||||
})
|
||||
|
||||
it('returns 400 for a non-numeric limit', async () => {
|
||||
const { supabase } = createCapturingSupabase([])
|
||||
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
|
||||
|
||||
const req = createMockRequest('/api/agent/conversations', { searchParams: { limit: 'abc' } })
|
||||
const { status } = await parseJsonResponse(await listGET(req, routeParams))
|
||||
expect(status).toBe(400)
|
||||
})
|
||||
|
||||
it('filters the list by BOTH company_id and the calling user_id', async () => {
|
||||
const { supabase, calls } = createCapturingSupabase([
|
||||
{ data: [{ id: 'conv-1', title: 'Min konversation' }] },
|
||||
])
|
||||
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
|
||||
|
||||
const req = createMockRequest('/api/agent/conversations')
|
||||
const { status, body } = await parseJsonResponse<{ data: unknown[] }>(
|
||||
await listGET(req, routeParams)
|
||||
)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data).toHaveLength(1)
|
||||
const eqCalls = calls.filter((c) => c.method === 'eq').map((c) => c.args)
|
||||
expect(eqCalls).toContainEqual(['company_id', 'company-1'])
|
||||
// Privacy regression guard: without this filter, company-scoped RLS lets
|
||||
// every member read colleagues' titles and last_message_preview.
|
||||
expect(eqCalls).toContainEqual(['user_id', 'user-1'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('GET /api/agent/conversations/[id]', () => {
|
||||
it('returns 404 when the conversation is not owned by the caller', async () => {
|
||||
// Ownership is part of the fetch (.eq user_id) — a non-owned id resolves null.
|
||||
const { supabase, calls } = createCapturingSupabase([{ data: null }])
|
||||
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
|
||||
|
||||
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(
|
||||
await detailGET(createMockRequest('/api/agent/conversations/conv-1'), idParams)
|
||||
)
|
||||
|
||||
expect(status).toBe(404)
|
||||
expect(body.error.code).toBe('CONVERSATION_NOT_FOUND')
|
||||
const eqCalls = calls.filter((c) => c.method === 'eq').map((c) => c.args)
|
||||
expect(eqCalls).toContainEqual(['user_id', 'user-1'])
|
||||
})
|
||||
|
||||
it('returns the conversation with its messages for the owner', async () => {
|
||||
const { supabase } = createCapturingSupabase([
|
||||
{ data: { id: 'conv-1', company_id: 'company-1', user_id: 'user-1', title: 'T' } },
|
||||
{ data: { role: 'member' } },
|
||||
{ data: [{ id: 'm1', role: 'user', content: 'Hej' }] },
|
||||
])
|
||||
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
|
||||
|
||||
const { status, body } = await parseJsonResponse<{
|
||||
data: { conversation: { id: string }; messages: unknown[] }
|
||||
}>(await detailGET(createMockRequest('/api/agent/conversations/conv-1'), idParams))
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.conversation.id).toBe('conv-1')
|
||||
expect(body.data.messages).toHaveLength(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('PATCH /api/agent/conversations/[id]', () => {
|
||||
it('returns 400 when the body has nothing to update', async () => {
|
||||
const { supabase } = createCapturingSupabase([])
|
||||
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
|
||||
|
||||
const req = createMockRequest('/api/agent/conversations/conv-1', {
|
||||
method: 'PATCH',
|
||||
body: {},
|
||||
})
|
||||
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(
|
||||
await detailPATCH(req, idParams)
|
||||
)
|
||||
|
||||
expect(status).toBe(400)
|
||||
expect(body.error.code).toBe('NOTHING_TO_UPDATE')
|
||||
})
|
||||
|
||||
it('updates pin state for an owned conversation', async () => {
|
||||
const { supabase } = createCapturingSupabase([
|
||||
{ data: { user_id: 'user-1', company_id: 'company-1' } },
|
||||
{ data: { id: 'conv-1', pinned: true } },
|
||||
])
|
||||
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
|
||||
|
||||
const req = createMockRequest('/api/agent/conversations/conv-1', {
|
||||
method: 'PATCH',
|
||||
body: { pinned: true },
|
||||
})
|
||||
const { status, body } = await parseJsonResponse<{ data: { pinned: boolean } }>(
|
||||
await detailPATCH(req, idParams)
|
||||
)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.pinned).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -1,184 +0,0 @@
|
||||
/**
|
||||
* Tests for POST /api/agent/feedback.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { createQueuedMockSupabase, createMockRequest, parseJsonResponse } from '@/tests/helpers'
|
||||
|
||||
const { supabase, enqueue, reset } = createQueuedMockSupabase()
|
||||
|
||||
const requireAuthMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-auth', () => ({
|
||||
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/company/context', () => ({
|
||||
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
}))
|
||||
|
||||
const requireWriteMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-write', () => ({
|
||||
requireWritePermission: (...args: unknown[]) => requireWriteMock(...args),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/init', () => ({ ensureInitialized: vi.fn() }))
|
||||
|
||||
const emitMock = vi.fn()
|
||||
vi.mock('@/lib/events/bus', () => ({
|
||||
eventBus: { emit: (...args: unknown[]) => emitMock(...args) },
|
||||
}))
|
||||
|
||||
import { POST } from '../feedback/route'
|
||||
|
||||
const routeParams = { params: Promise.resolve({}) }
|
||||
const CONVERSATION_ID = '11111111-2222-4333-8444-555555555555'
|
||||
|
||||
const body = (over: Record<string, unknown> = {}) => ({
|
||||
conversation_id: CONVERSATION_ID,
|
||||
sentiment: 'negative',
|
||||
...over,
|
||||
})
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
reset()
|
||||
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
|
||||
requireWriteMock.mockResolvedValue({ ok: true })
|
||||
})
|
||||
|
||||
describe('POST /api/agent/feedback', () => {
|
||||
it('returns 401 when not authenticated', async () => {
|
||||
requireAuthMock.mockResolvedValue({
|
||||
user: null,
|
||||
supabase,
|
||||
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
|
||||
})
|
||||
|
||||
const req = createMockRequest('/api/agent/feedback', { method: 'POST', body: body() })
|
||||
expect((await POST(req, routeParams)).status).toBe(401)
|
||||
expect(emitMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns 400 for a sentiment outside the two votes the UI can send', async () => {
|
||||
const req = createMockRequest('/api/agent/feedback', {
|
||||
method: 'POST',
|
||||
body: body({ sentiment: 'furious' }),
|
||||
})
|
||||
const { status } = await parseJsonResponse(await POST(req, routeParams))
|
||||
expect(status).toBe(400)
|
||||
expect(emitMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns 400 when the conversation id is not a uuid', async () => {
|
||||
const req = createMockRequest('/api/agent/feedback', {
|
||||
method: 'POST',
|
||||
body: body({ conversation_id: 'not-a-uuid' }),
|
||||
})
|
||||
const { status } = await parseJsonResponse(await POST(req, routeParams))
|
||||
expect(status).toBe(400)
|
||||
})
|
||||
|
||||
it('404s on a conversation belonging to another user', async () => {
|
||||
// Same hole that /api/agent/invoke had: the id is caller-supplied, so
|
||||
// without the ownership check a member could file feedback against a
|
||||
// colleague's thread and the triage backlog would carry a conversation the
|
||||
// reporter never saw.
|
||||
enqueue({
|
||||
data: {
|
||||
id: CONVERSATION_ID,
|
||||
user_id: 'someone-else',
|
||||
company_id: 'company-1',
|
||||
intent_id: 'general.help',
|
||||
},
|
||||
})
|
||||
|
||||
const req = createMockRequest('/api/agent/feedback', { method: 'POST', body: body() })
|
||||
const { status } = await parseJsonResponse(await POST(req, routeParams))
|
||||
expect(status).toBe(404)
|
||||
expect(emitMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('404s on a conversation in another company', async () => {
|
||||
enqueue({
|
||||
data: {
|
||||
id: CONVERSATION_ID,
|
||||
user_id: 'user-1',
|
||||
company_id: 'company-2',
|
||||
intent_id: 'general.help',
|
||||
},
|
||||
})
|
||||
|
||||
const req = createMockRequest('/api/agent/feedback', { method: 'POST', body: body() })
|
||||
expect((await parseJsonResponse(await POST(req, routeParams))).status).toBe(404)
|
||||
expect(emitMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('404s when the conversation does not exist', async () => {
|
||||
enqueue({ data: null })
|
||||
const req = createMockRequest('/api/agent/feedback', { method: 'POST', body: body() })
|
||||
expect((await parseJsonResponse(await POST(req, routeParams))).status).toBe(404)
|
||||
})
|
||||
|
||||
it('emits agent.feedback with actorType user on the happy path', async () => {
|
||||
enqueue({
|
||||
data: {
|
||||
id: CONVERSATION_ID,
|
||||
user_id: 'user-1',
|
||||
company_id: 'company-1',
|
||||
intent_id: 'vat.review',
|
||||
},
|
||||
})
|
||||
|
||||
const req = createMockRequest('/api/agent/feedback', {
|
||||
method: 'POST',
|
||||
body: body({ sentiment: 'positive', message_index: 4 }),
|
||||
})
|
||||
const { status } = await parseJsonResponse(await POST(req, routeParams))
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(emitMock).toHaveBeenCalledOnce()
|
||||
const event = emitMock.mock.calls[0]![0] as {
|
||||
type: string
|
||||
payload: Record<string, unknown>
|
||||
}
|
||||
// Same event type the MCP tool emits, so chat votes land in the backlog
|
||||
// the product team already reads instead of a second place.
|
||||
expect(event.type).toBe('agent.feedback')
|
||||
expect(event.payload.sentiment).toBe('positive')
|
||||
expect(event.payload.actorType).toBe('user')
|
||||
expect(event.payload.actorId).toBe('user-1')
|
||||
expect(event.payload.companyId).toBe('company-1')
|
||||
expect(event.payload.sessionId).toBe(CONVERSATION_ID)
|
||||
// Traceable to an answer: a thumbs-down that cannot be tied to a turn is a
|
||||
// number, not a report.
|
||||
expect(event.payload.context).toContain('vat.review')
|
||||
expect(event.payload.context).toContain('#4')
|
||||
})
|
||||
|
||||
it('never carries user free text into the telemetry log', async () => {
|
||||
// A comment box here would put whatever the user typed, in an accounting
|
||||
// product, verbatim into event_log under telemetry retention: client
|
||||
// names, personnummer, case details. The field is not accepted, and a
|
||||
// caller that sends one anyway must not have it stored.
|
||||
enqueue({
|
||||
data: {
|
||||
id: CONVERSATION_ID,
|
||||
user_id: 'user-1',
|
||||
company_id: 'company-1',
|
||||
intent_id: 'general.help',
|
||||
},
|
||||
})
|
||||
|
||||
const req = createMockRequest('/api/agent/feedback', {
|
||||
method: 'POST',
|
||||
body: body({ comment: 'Anna Andersson 19850101-1234 fick fel konto' }),
|
||||
})
|
||||
await POST(req, routeParams)
|
||||
|
||||
const event = emitMock.mock.calls[0]![0] as { payload: { context: string } }
|
||||
expect(event.payload.context).not.toContain('Anna Andersson')
|
||||
expect(event.payload.context).not.toContain('19850101')
|
||||
expect(JSON.stringify(event.payload)).not.toContain('19850101')
|
||||
})
|
||||
})
|
||||
@@ -1,282 +0,0 @@
|
||||
/**
|
||||
* Tests for POST /api/agent/invoke, focused on conversation ownership.
|
||||
*
|
||||
* RLS on agent_conversations/agent_messages is company-scoped, not user-scoped
|
||||
* (migration 20260517204000), so the route itself has to prove that a resumed
|
||||
* conversation_id belongs to the caller. Without that check, a member could
|
||||
* post a colleague's conversation id and have their history loaded into the
|
||||
* prompt (and their own turns appended to it).
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { createQueuedMockSupabase, createMockRequest, parseJsonResponse } from '@/tests/helpers'
|
||||
|
||||
const { supabase, enqueue, reset } = createQueuedMockSupabase()
|
||||
|
||||
const requireAuthMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-auth', () => ({
|
||||
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/company/context', () => ({
|
||||
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
}))
|
||||
|
||||
const checkRateMock = vi.fn()
|
||||
vi.mock('@/lib/rate-limits/agent', () => ({
|
||||
checkAgentRateLimit: (...args: unknown[]) => checkRateMock(...args),
|
||||
agentRateLimitResponseBody: () => ({ error: 'För många förfrågningar.' }),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/sandbox/guard', () => ({
|
||||
guardSandbox: vi.fn().mockResolvedValue(null),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/entitlements/has-capability', () => ({
|
||||
requireCapability: vi.fn().mockResolvedValue(null),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/entitlements/keys', () => ({
|
||||
CAPABILITY: { ai: 'ai' },
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/init', () => ({
|
||||
ensureInitialized: vi.fn(),
|
||||
}))
|
||||
|
||||
const getIntentMock = vi.fn()
|
||||
vi.mock('@/lib/agent/intents/registry', () => ({
|
||||
getIntent: (...args: unknown[]) => getIntentMock(...args),
|
||||
}))
|
||||
|
||||
// Deployment-level AI availability (distinct from the per-company paywall).
|
||||
// Default: available, so the ownership tests below exercise the real flow.
|
||||
const aiStatusMock = vi.fn()
|
||||
vi.mock('@/lib/ai', () => ({
|
||||
getAiStatus: () => aiStatusMock(),
|
||||
}))
|
||||
|
||||
const runChatTurnMock = vi.fn()
|
||||
vi.mock('@/lib/agent/chat/run-turn', () => ({
|
||||
runChatTurn: (...args: unknown[]) => runChatTurnMock(...args),
|
||||
friendlyModelError: () => 'Något gick fel hos assistenten.',
|
||||
}))
|
||||
|
||||
import { POST } from '../invoke/route'
|
||||
|
||||
const CONVERSATION_ID = '11111111-1111-4111-8111-111111111111'
|
||||
|
||||
function body(overrides: Record<string, unknown> = {}) {
|
||||
return {
|
||||
intent_id: 'general.help',
|
||||
user_message: 'Hur gick juli?',
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Queue the reads the route performs before it resolves the conversation.
|
||||
*
|
||||
* Ownership is validated ahead of every side effect and of the company/profile
|
||||
* reads, so a rejected request costs exactly one membership read plus the
|
||||
* conversation lookup.
|
||||
*/
|
||||
function enqueuePreamble() {
|
||||
enqueue({ data: { role: 'owner' } }) // company_members
|
||||
}
|
||||
|
||||
/** The company + profile reads that only happen once a request is accepted. */
|
||||
function enqueueAcceptedTail() {
|
||||
enqueue({ data: { name: 'Nordvik Bygg AB' } }) // companies
|
||||
enqueue({ data: { full_name: 'Johan Nordvik' } }) // profiles
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
reset()
|
||||
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
|
||||
checkRateMock.mockResolvedValue({ ok: true })
|
||||
getIntentMock.mockReturnValue({ id: 'general.help', sheetTitle: 'Assistenten' })
|
||||
runChatTurnMock.mockResolvedValue(undefined)
|
||||
aiStatusMock.mockReturnValue({ configured: true, assistantAvailable: true, provider: 'bedrock' })
|
||||
})
|
||||
|
||||
describe('POST /api/agent/invoke', () => {
|
||||
it('returns 401 when not authenticated', async () => {
|
||||
requireAuthMock.mockResolvedValue({
|
||||
user: null,
|
||||
supabase,
|
||||
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
|
||||
})
|
||||
const res = await POST(createMockRequest('/api/agent/invoke', { method: 'POST', body: body() }))
|
||||
const { status } = await parseJsonResponse(res)
|
||||
expect(status).toBe(401)
|
||||
})
|
||||
|
||||
it('returns 400 on an invalid body', async () => {
|
||||
const res = await POST(createMockRequest('/api/agent/invoke', { method: 'POST', body: { intent_id: '' } }))
|
||||
const { status } = await parseJsonResponse(res)
|
||||
expect(status).toBe(400)
|
||||
})
|
||||
|
||||
it('returns 400 for an unknown intent', async () => {
|
||||
getIntentMock.mockReturnValue(undefined)
|
||||
const res = await POST(createMockRequest('/api/agent/invoke', { method: 'POST', body: body() }))
|
||||
const { status } = await parseJsonResponse<{ error: string }>(res)
|
||||
expect(status).toBe(400)
|
||||
})
|
||||
|
||||
// A self-host without an AI key, or on an OpenAI-compatible endpoint the
|
||||
// chat loop does not speak yet: say so up front with a distinct code, never
|
||||
// open a stream that dies on the first model call, never confuse it with
|
||||
// the paywall.
|
||||
it('returns 503 ai_unconfigured when the deployment has no assistant backend', async () => {
|
||||
aiStatusMock.mockReturnValue({ configured: false, assistantAvailable: false, provider: 'bedrock' })
|
||||
enqueuePreamble()
|
||||
const res = await POST(createMockRequest('/api/agent/invoke', { method: 'POST', body: body() }))
|
||||
const { status, body: json } = await parseJsonResponse<{ error: string; code: string }>(res)
|
||||
expect(status).toBe(503)
|
||||
expect(json.code).toBe('ai_unconfigured')
|
||||
expect(runChatTurnMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns 403 when the user is not a member of the company', async () => {
|
||||
enqueue({ data: null }) // company_members: no row
|
||||
const res = await POST(createMockRequest('/api/agent/invoke', { method: 'POST', body: body() }))
|
||||
const { status } = await parseJsonResponse(res)
|
||||
expect(status).toBe(403)
|
||||
})
|
||||
|
||||
it('returns 404 when resuming a conversation owned by another user', async () => {
|
||||
enqueuePreamble()
|
||||
enqueue({
|
||||
data: {
|
||||
id: CONVERSATION_ID,
|
||||
user_id: 'user-2', // someone else in the same company
|
||||
company_id: 'company-1',
|
||||
intent_id: 'general.help',
|
||||
},
|
||||
})
|
||||
|
||||
const res = await POST(
|
||||
createMockRequest('/api/agent/invoke', { method: 'POST', body: body({ conversation_id: CONVERSATION_ID }) }),
|
||||
)
|
||||
|
||||
const { status, body: json } = await parseJsonResponse<{ error: string }>(res)
|
||||
expect(status).toBe(404)
|
||||
expect(json.error).toBe('Konversationen hittades inte.')
|
||||
expect(runChatTurnMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns 404 when resuming a conversation from another company', async () => {
|
||||
enqueuePreamble()
|
||||
enqueue({
|
||||
data: {
|
||||
id: CONVERSATION_ID,
|
||||
user_id: 'user-1', // same user...
|
||||
company_id: 'company-2', // ...but a company other than the active one
|
||||
intent_id: 'general.help',
|
||||
},
|
||||
})
|
||||
|
||||
const res = await POST(
|
||||
createMockRequest('/api/agent/invoke', { method: 'POST', body: body({ conversation_id: CONVERSATION_ID }) }),
|
||||
)
|
||||
|
||||
const { status } = await parseJsonResponse(res)
|
||||
expect(status).toBe(404)
|
||||
expect(runChatTurnMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns 404 when the conversation does not exist', async () => {
|
||||
enqueuePreamble()
|
||||
enqueue({ data: null })
|
||||
|
||||
const res = await POST(
|
||||
createMockRequest('/api/agent/invoke', { method: 'POST', body: body({ conversation_id: CONVERSATION_ID }) }),
|
||||
)
|
||||
|
||||
const { status } = await parseJsonResponse(res)
|
||||
expect(status).toBe(404)
|
||||
expect(runChatTurnMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns 400 when the conversation belongs to a different intent', async () => {
|
||||
enqueuePreamble()
|
||||
enqueue({
|
||||
data: {
|
||||
id: CONVERSATION_ID,
|
||||
user_id: 'user-1',
|
||||
company_id: 'company-1',
|
||||
intent_id: 'vat.review', // tool loadout differs from general.help
|
||||
},
|
||||
})
|
||||
|
||||
const res = await POST(
|
||||
createMockRequest('/api/agent/invoke', { method: 'POST', body: body({ conversation_id: CONVERSATION_ID }) }),
|
||||
)
|
||||
|
||||
const { status } = await parseJsonResponse(res)
|
||||
expect(status).toBe(400)
|
||||
expect(runChatTurnMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('runs the turn when the caller owns the conversation', async () => {
|
||||
enqueuePreamble()
|
||||
enqueue({
|
||||
data: {
|
||||
id: CONVERSATION_ID,
|
||||
user_id: 'user-1',
|
||||
company_id: 'company-1',
|
||||
intent_id: 'general.help',
|
||||
},
|
||||
})
|
||||
enqueueAcceptedTail()
|
||||
|
||||
const res = await POST(
|
||||
createMockRequest('/api/agent/invoke', { method: 'POST', body: body({ conversation_id: CONVERSATION_ID }) }),
|
||||
)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
// The route streams NDJSON; draining it is enough to know the turn ran.
|
||||
await res.text()
|
||||
expect(runChatTurnMock).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('hands the first-turn profile summary to the turn instead of re-reading it', async () => {
|
||||
// On a first turn the route reads agent_profiles to build the intent's
|
||||
// prompt template. run-turn needs the same value for the system prompt, so
|
||||
// it is passed through rather than read a second time.
|
||||
getIntentMock.mockReturnValue({
|
||||
id: 'general.help',
|
||||
sheetTitle: 'Assistenten',
|
||||
capture: vi.fn().mockResolvedValue({ some: 'context' }),
|
||||
promptTemplate: vi.fn().mockReturnValue('templated first turn'),
|
||||
})
|
||||
|
||||
enqueuePreamble()
|
||||
enqueue({ data: { id: CONVERSATION_ID } }) // conversation insert
|
||||
enqueueAcceptedTail()
|
||||
enqueue({ data: { profile_summary: 'Byggkonsult, K2' } }) // agent_profiles
|
||||
enqueue({ data: [] }) // agent_memory
|
||||
|
||||
const res = await POST(
|
||||
createMockRequest('/api/agent/invoke', {
|
||||
method: 'POST',
|
||||
body: { intent_id: 'general.help' }, // no user_message => first turn
|
||||
}),
|
||||
)
|
||||
await res.text()
|
||||
|
||||
expect(runChatTurnMock).toHaveBeenCalledTimes(1)
|
||||
const args = runChatTurnMock.mock.calls[0]![0] as {
|
||||
preloadedProfileSummary?: string | null
|
||||
userMessage: string
|
||||
userMessageHidden?: boolean
|
||||
}
|
||||
expect(args.preloadedProfileSummary).toBe('Byggkonsult, K2')
|
||||
expect(args.userMessage).toBe('templated first turn')
|
||||
expect(args.userMessageHidden).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -1,150 +0,0 @@
|
||||
/**
|
||||
* Tests for GET/POST /api/agent/memory and PATCH /api/agent/memory/[id].
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { createQueuedMockSupabase, createMockRequest, parseJsonResponse } from '@/tests/helpers'
|
||||
|
||||
const { supabase, enqueue, reset } = createQueuedMockSupabase()
|
||||
|
||||
const requireAuthMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-auth', () => ({
|
||||
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/company/context', () => ({
|
||||
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
}))
|
||||
|
||||
const requireWriteMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-write', () => ({
|
||||
requireWritePermission: (...args: unknown[]) => requireWriteMock(...args),
|
||||
}))
|
||||
|
||||
import { GET, POST } from '../memory/route'
|
||||
import { PATCH } from '../memory/[id]/route'
|
||||
|
||||
const routeParams = { params: Promise.resolve({}) }
|
||||
const idParams = { params: Promise.resolve({ id: 'mem-1' }) }
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
reset()
|
||||
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
|
||||
requireWriteMock.mockResolvedValue({ ok: true })
|
||||
})
|
||||
|
||||
describe('GET /api/agent/memory', () => {
|
||||
it('returns 401 when not authenticated', async () => {
|
||||
requireAuthMock.mockResolvedValue({
|
||||
user: null,
|
||||
supabase,
|
||||
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
|
||||
})
|
||||
|
||||
const res = await GET(createMockRequest('/api/agent/memory'), routeParams)
|
||||
expect(res.status).toBe(401)
|
||||
})
|
||||
|
||||
it('returns 400 for an unknown kind filter', async () => {
|
||||
const req = createMockRequest('/api/agent/memory', { searchParams: { kind: 'gossip' } })
|
||||
const { status } = await parseJsonResponse(await GET(req, routeParams))
|
||||
expect(status).toBe(400)
|
||||
})
|
||||
|
||||
it('lists memory entries', async () => {
|
||||
enqueue({ data: [{ id: 'mem-1', kind: 'fact', content: 'Fakturerar i SEK' }] })
|
||||
|
||||
const { status, body } = await parseJsonResponse<{ data: unknown[] }>(
|
||||
await GET(createMockRequest('/api/agent/memory'), routeParams)
|
||||
)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data).toHaveLength(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('POST /api/agent/memory', () => {
|
||||
it('rejects a viewer in the target company with 403', async () => {
|
||||
// requireWrite passed for the ACTIVE company, but the body targets a
|
||||
// company where the caller is only a viewer — the re-check must refuse.
|
||||
enqueue({ data: { role: 'viewer' } })
|
||||
|
||||
const req = createMockRequest('/api/agent/memory', {
|
||||
method: 'POST',
|
||||
body: { company_id: '7f3e0b1a-9c4d-4a2b-8f6e-1d2c3b4a5e6f', content: 'Ett minne' },
|
||||
})
|
||||
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(
|
||||
await POST(req, routeParams)
|
||||
)
|
||||
|
||||
expect(status).toBe(403)
|
||||
expect(body.error.code).toBe('WRITE_PERMISSION_REQUIRED')
|
||||
})
|
||||
|
||||
it('rejects an invalid body with 400', async () => {
|
||||
const req = createMockRequest('/api/agent/memory', {
|
||||
method: 'POST',
|
||||
body: { content: 'x' }, // below min length 2
|
||||
})
|
||||
const { status } = await parseJsonResponse(await POST(req, routeParams))
|
||||
expect(status).toBe(400)
|
||||
})
|
||||
|
||||
it('inserts a memory entry for the active company', async () => {
|
||||
enqueue({ data: { role: 'admin' } }) // membership re-check
|
||||
enqueue({ data: { id: 'mem-2', kind: 'fact', content: 'Ett minne' } })
|
||||
|
||||
const req = createMockRequest('/api/agent/memory', {
|
||||
method: 'POST',
|
||||
body: { content: 'Ett minne' },
|
||||
})
|
||||
const { status, body } = await parseJsonResponse<{ data: { id: string } }>(
|
||||
await POST(req, routeParams)
|
||||
)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.id).toBe('mem-2')
|
||||
})
|
||||
})
|
||||
|
||||
describe('PATCH /api/agent/memory/[id]', () => {
|
||||
it('returns 400 when the body has nothing to update', async () => {
|
||||
const req = createMockRequest('/api/agent/memory/mem-1', { method: 'PATCH', body: {} })
|
||||
const { status } = await parseJsonResponse(await PATCH(req, idParams))
|
||||
expect(status).toBe(400)
|
||||
})
|
||||
|
||||
it('returns 404 when the memory row does not exist', async () => {
|
||||
enqueue({ data: null })
|
||||
|
||||
const req = createMockRequest('/api/agent/memory/mem-1', {
|
||||
method: 'PATCH',
|
||||
body: { is_pinned: true },
|
||||
})
|
||||
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(
|
||||
await PATCH(req, idParams)
|
||||
)
|
||||
|
||||
expect(status).toBe(404)
|
||||
expect(body.error.code).toBe('MEMORY_NOT_FOUND')
|
||||
})
|
||||
|
||||
it('updates a memory entry', async () => {
|
||||
enqueue({ data: { company_id: 'company-1' } }) // row lookup
|
||||
enqueue({ data: { role: 'member' } }) // membership re-check
|
||||
enqueue({ data: { id: 'mem-1', is_pinned: true } }) // update
|
||||
|
||||
const req = createMockRequest('/api/agent/memory/mem-1', {
|
||||
method: 'PATCH',
|
||||
body: { is_pinned: true },
|
||||
})
|
||||
const { status, body } = await parseJsonResponse<{ data: { is_pinned: boolean } }>(
|
||||
await PATCH(req, idParams)
|
||||
)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.is_pinned).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -1,92 +0,0 @@
|
||||
/**
|
||||
* Tests for POST /api/agent/onboarding/stream — auth surface only.
|
||||
*
|
||||
* The composer pipeline itself is exercised via lib tests; here we lock in
|
||||
* the guard order: 401, membership 403, and the viewer refusal (the pipeline
|
||||
* upserts agent_profiles, so viewers must not be able to trigger it).
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { createMockRequest, parseJsonResponse } from '@/tests/helpers'
|
||||
|
||||
vi.mock('@/lib/company/context', () => ({
|
||||
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/rate-limits/agent', () => ({
|
||||
checkAgentRateLimit: vi.fn().mockResolvedValue({ ok: true }),
|
||||
agentRateLimitResponseBody: () => ({ error: 'För många förfrågningar.' }),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/sandbox/guard', () => ({ guardSandbox: vi.fn().mockResolvedValue(null) }))
|
||||
vi.mock('@/lib/entitlements/has-capability', () => ({
|
||||
requireCapability: vi.fn().mockResolvedValue(null),
|
||||
}))
|
||||
vi.mock('@/lib/entitlements/keys', () => ({ CAPABILITY: { ai: 'ai' } }))
|
||||
|
||||
// Pipeline internals — never reached in these tests, stubbed so the module loads.
|
||||
vi.mock('@/lib/agent/composer/inputs', () => ({
|
||||
gatherComposerInputs: vi.fn(),
|
||||
inputsToSourceSignals: vi.fn(),
|
||||
}))
|
||||
vi.mock('@/lib/agent/composer/atom-selection', () => ({
|
||||
selectAtoms: vi.fn(),
|
||||
filterRedundantQuestions: vi.fn(),
|
||||
}))
|
||||
vi.mock('@/lib/agent/composer/narrative', () => ({ writeNarrative: vi.fn() }))
|
||||
vi.mock('@/lib/agent/composer/fallback', () => ({
|
||||
fallbackAtomSelection: vi.fn(),
|
||||
fallbackNarrative: vi.fn(),
|
||||
}))
|
||||
vi.mock('@/lib/agent/composer/prewarm', () => ({ preWarmAtomCache: vi.fn() }))
|
||||
vi.mock('@/lib/agent/composer/client', () => ({ OPUS_MODEL: 'opus-test' }))
|
||||
vi.mock('@/lib/agent/composer/tic-fetch', () => ({ ensureTicSnapshot: vi.fn() }))
|
||||
|
||||
vi.mock('@/lib/supabase/server', () => ({ createClient: vi.fn() }))
|
||||
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { POST } from '../onboarding/stream/route'
|
||||
|
||||
const mockCreateClient = vi.mocked(createClient)
|
||||
|
||||
function mockAuth(userId: string | null, membership: { role: string } | null) {
|
||||
mockCreateClient.mockResolvedValue({
|
||||
auth: {
|
||||
getUser: vi.fn().mockResolvedValue({ data: { user: userId ? { id: userId } : null } }),
|
||||
},
|
||||
from: vi.fn().mockReturnValue({
|
||||
select: vi.fn().mockReturnThis(),
|
||||
eq: vi.fn().mockReturnThis(),
|
||||
maybeSingle: vi.fn().mockResolvedValue({ data: membership, error: null }),
|
||||
}),
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} as any)
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
describe('POST /api/agent/onboarding/stream', () => {
|
||||
it('returns 401 when not authenticated', async () => {
|
||||
mockAuth(null, null)
|
||||
const req = createMockRequest('/api/agent/onboarding/stream', { method: 'POST', body: {} })
|
||||
const res = await POST(req)
|
||||
expect(res.status).toBe(401)
|
||||
})
|
||||
|
||||
it('returns 403 for a non-member', async () => {
|
||||
mockAuth('user-1', null)
|
||||
const req = createMockRequest('/api/agent/onboarding/stream', { method: 'POST', body: {} })
|
||||
const { status } = await parseJsonResponse(await POST(req))
|
||||
expect(status).toBe(403)
|
||||
})
|
||||
|
||||
it('refuses a viewer with 403 (pipeline upserts agent_profiles)', async () => {
|
||||
mockAuth('user-1', { role: 'viewer' })
|
||||
const req = createMockRequest('/api/agent/onboarding/stream', { method: 'POST', body: {} })
|
||||
const { status, body } = await parseJsonResponse<{ error: string }>(await POST(req))
|
||||
expect(status).toBe(403)
|
||||
expect(body.error).toContain('läsbehörighet')
|
||||
})
|
||||
})
|
||||
@@ -1,149 +0,0 @@
|
||||
/**
|
||||
* Tests for GET/PATCH /api/agent/profile and POST /api/agent/profile/verify.
|
||||
*
|
||||
* Covers the role model: reads allow any member, mutations (PATCH, verify)
|
||||
* refuse viewers — the same rule verify always had, now enforced on PATCH too.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { createQueuedMockSupabase, createMockRequest, parseJsonResponse } from '@/tests/helpers'
|
||||
|
||||
const { supabase, enqueue, reset } = createQueuedMockSupabase()
|
||||
|
||||
const requireAuthMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-auth', () => ({
|
||||
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/company/context', () => ({
|
||||
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
}))
|
||||
|
||||
import { GET, PATCH } from '../profile/route'
|
||||
import { POST as VERIFY } from '../profile/verify/route'
|
||||
|
||||
const routeParams = { params: Promise.resolve({}) }
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
reset()
|
||||
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
|
||||
})
|
||||
|
||||
describe('GET /api/agent/profile', () => {
|
||||
it('returns 401 when not authenticated', async () => {
|
||||
requireAuthMock.mockResolvedValue({
|
||||
user: null,
|
||||
supabase,
|
||||
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
|
||||
})
|
||||
const res = await GET(createMockRequest('/api/agent/profile'), routeParams)
|
||||
expect(res.status).toBe(401)
|
||||
})
|
||||
|
||||
it('returns 403 when the caller is not a member of the target company', async () => {
|
||||
enqueue({ data: null }) // membership lookup
|
||||
|
||||
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(
|
||||
await GET(createMockRequest('/api/agent/profile'), routeParams)
|
||||
)
|
||||
expect(status).toBe(403)
|
||||
expect(body.error.code).toBe('NOT_COMPANY_MEMBER')
|
||||
})
|
||||
|
||||
it('returns the profile for a member (viewers may read)', async () => {
|
||||
enqueue({ data: { role: 'viewer' } })
|
||||
enqueue({ data: { company_id: 'company-1', profile_summary: 'Konsultbolag' } })
|
||||
|
||||
const { status, body } = await parseJsonResponse<{ data: { profile_summary: string } }>(
|
||||
await GET(createMockRequest('/api/agent/profile'), routeParams)
|
||||
)
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.profile_summary).toBe('Konsultbolag')
|
||||
})
|
||||
})
|
||||
|
||||
describe('PATCH /api/agent/profile', () => {
|
||||
it('refuses a viewer with 403 (profile mutation)', async () => {
|
||||
enqueue({ data: { role: 'viewer' } })
|
||||
|
||||
const req = createMockRequest('/api/agent/profile', {
|
||||
method: 'PATCH',
|
||||
body: { profile_summary: 'Nytt sammandrag' },
|
||||
})
|
||||
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(
|
||||
await PATCH(req, routeParams)
|
||||
)
|
||||
expect(status).toBe(403)
|
||||
expect(body.error.code).toBe('WRITE_PERMISSION_REQUIRED')
|
||||
})
|
||||
|
||||
it('returns 404 when the company has no agent_profile row', async () => {
|
||||
enqueue({ data: { role: 'admin' } })
|
||||
enqueue({ data: null }) // current profile lookup
|
||||
|
||||
const req = createMockRequest('/api/agent/profile', {
|
||||
method: 'PATCH',
|
||||
body: { profile_summary: 'Nytt sammandrag' },
|
||||
})
|
||||
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(
|
||||
await PATCH(req, routeParams)
|
||||
)
|
||||
expect(status).toBe(404)
|
||||
expect(body.error.code).toBe('AGENT_PROFILE_NOT_FOUND')
|
||||
})
|
||||
|
||||
it('returns 400 when the body contains nothing to update', async () => {
|
||||
enqueue({ data: { role: 'admin' } })
|
||||
enqueue({ data: { field_overrides: null } })
|
||||
|
||||
const req = createMockRequest('/api/agent/profile', { method: 'PATCH', body: {} })
|
||||
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(
|
||||
await PATCH(req, routeParams)
|
||||
)
|
||||
expect(status).toBe(400)
|
||||
expect(body.error.code).toBe('NOTHING_TO_UPDATE')
|
||||
})
|
||||
|
||||
it('merges field_overrides and updates the profile', async () => {
|
||||
enqueue({ data: { role: 'admin' } })
|
||||
enqueue({ data: { field_overrides: { old: { value: 1, overridden_at: 'x' } } } })
|
||||
enqueue({ data: { company_id: 'company-1', profile_summary: 'Uppdaterad' } })
|
||||
|
||||
const req = createMockRequest('/api/agent/profile', {
|
||||
method: 'PATCH',
|
||||
body: { profile_summary: 'Uppdaterad', field_overrides: { vat_period: 'quarterly' } },
|
||||
})
|
||||
const { status, body } = await parseJsonResponse<{ data: { profile_summary: string } }>(
|
||||
await PATCH(req, routeParams)
|
||||
)
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.profile_summary).toBe('Uppdaterad')
|
||||
})
|
||||
})
|
||||
|
||||
describe('POST /api/agent/profile/verify', () => {
|
||||
it('refuses a viewer with 403', async () => {
|
||||
enqueue({ data: { role: 'viewer' } })
|
||||
|
||||
const req = createMockRequest('/api/agent/profile/verify', { method: 'POST', body: {} })
|
||||
const { status, body } = await parseJsonResponse<{ error: { code: string } }>(
|
||||
await VERIFY(req, routeParams)
|
||||
)
|
||||
expect(status).toBe(403)
|
||||
expect(body.error.code).toBe('WRITE_PERMISSION_REQUIRED')
|
||||
})
|
||||
|
||||
it('stamps verified_at for a non-viewer member', async () => {
|
||||
enqueue({ data: { role: 'owner' } })
|
||||
enqueue({ data: { company_id: 'company-1', verified_at: '2026-07-03T00:00:00Z', verified_by_user_id: 'user-1' } })
|
||||
|
||||
const req = createMockRequest('/api/agent/profile/verify', { method: 'POST', body: {} })
|
||||
const { status, body } = await parseJsonResponse<{ data: { verified_by_user_id: string } }>(
|
||||
await VERIFY(req, routeParams)
|
||||
)
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.verified_by_user_id).toBe('user-1')
|
||||
})
|
||||
})
|
||||
@@ -1,224 +0,0 @@
|
||||
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()
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -1,191 +0,0 @@
|
||||
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 })
|
||||
}
|
||||
}
|
||||
@@ -1,140 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { createMockRequest, createMockRouteParams, parseJsonResponse } from '@/tests/helpers'
|
||||
|
||||
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: 'rate' }),
|
||||
}))
|
||||
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 gatherCandidates = vi.fn()
|
||||
vi.mock('@/lib/agent/categorize/candidates', () => ({ gatherCandidates: (...a: unknown[]) => gatherCandidates(...a) }))
|
||||
const gatherUnderlag = vi.fn()
|
||||
vi.mock('@/lib/agent/categorize/underlag', () => ({ gatherUnderlag: (...a: unknown[]) => gatherUnderlag(...a) }))
|
||||
const selectAccount = vi.fn()
|
||||
vi.mock('@/lib/agent/categorize/select-account', () => ({ selectAccount: (...a: unknown[]) => selectAccount(...a) }))
|
||||
|
||||
import { POST } from '../route'
|
||||
|
||||
// supabase router: membership + transactions + companies + company_settings.
|
||||
function makeSupabase(opts: { tx?: unknown; member?: boolean } = {}) {
|
||||
return {
|
||||
auth: { getUser: vi.fn() },
|
||||
from(table: string) {
|
||||
const rows: Record<string, unknown> = {
|
||||
company_members: opts.member === false ? null : { user_id: 'user-1' },
|
||||
transactions: opts.tx === undefined ? { id: 'tx-1' } : opts.tx,
|
||||
companies: { entity_type: 'aktiebolag' },
|
||||
company_settings: { vat_registered: true },
|
||||
}
|
||||
const chain = {
|
||||
select: () => chain,
|
||||
eq: () => chain,
|
||||
maybeSingle: async () => ({ data: rows[table] ?? null }),
|
||||
}
|
||||
return chain
|
||||
},
|
||||
}
|
||||
}
|
||||
const supabase = makeSupabase()
|
||||
|
||||
const VALID_TX = '11111111-1111-4111-8111-111111111111'
|
||||
const body = (o: Record<string, unknown> = {}) => ({ transaction_id: VALID_TX, ...o })
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
|
||||
checkRate.mockResolvedValue({ ok: true })
|
||||
requireCapability.mockResolvedValue(null)
|
||||
aiStatus.mockReturnValue({ configured: true })
|
||||
gatherCandidates.mockResolvedValue([{ account: '5410', label: 'Material', vatTreatment: 'standard_25', source: 'counterparty_template', confidence: 0.9 }])
|
||||
gatherUnderlag.mockResolvedValue('Kvitto: Biltema, totalt 499 SEK.')
|
||||
selectAccount.mockResolvedValue({
|
||||
account: '5410', category: null, vatTreatment: 'standard_25', reverseCharge: false,
|
||||
confidence: 0.86, modelConfidence: 'high', agreement: 1, reasoning: 'r',
|
||||
choice: { kind: 'candidate', account: '5410' }, model: 'qwen3.8', fromCandidate: true,
|
||||
})
|
||||
})
|
||||
|
||||
describe('POST /api/agent/categorize', () => {
|
||||
it('401 when unauthenticated', async () => {
|
||||
requireAuthMock.mockResolvedValue({ user: null, supabase, error: NextResponse.json({ error: 'x' }, { status: 401 }) })
|
||||
expect((await POST(createMockRequest('/x', { method: 'POST', body: body() }), createMockRouteParams({}))).status).toBe(401)
|
||||
expect(selectAccount).not.toHaveBeenCalled()
|
||||
})
|
||||
it('resolves the session through requireAuth (withRouteContext), never a hand-rolled getUser()', async () => {
|
||||
await POST(createMockRequest('/x', { method: 'POST', body: body() }), createMockRouteParams({}))
|
||||
expect(requireAuthMock).toHaveBeenCalledTimes(1)
|
||||
expect(supabase.auth.getUser).not.toHaveBeenCalled()
|
||||
})
|
||||
it('403 when the body names a company the caller is not a member of', async () => {
|
||||
const other = '22222222-2222-4222-8222-222222222222'
|
||||
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase: makeSupabase({ member: false }), error: null })
|
||||
const res = await POST(createMockRequest('/x', { method: 'POST', body: body({ company_id: other }) }), createMockRouteParams({}))
|
||||
expect(res.status).toBe(403)
|
||||
expect(selectAccount).not.toHaveBeenCalled()
|
||||
})
|
||||
it('uses the active company without a membership round trip when no override is given', async () => {
|
||||
const res = await POST(createMockRequest('/x', { method: 'POST', body: body() }), createMockRouteParams({}))
|
||||
expect(res.status).toBe(200)
|
||||
expect(gatherCandidates).toHaveBeenCalledWith(expect.anything(), 'company-1', expect.anything())
|
||||
})
|
||||
it('429 when rate limited', async () => {
|
||||
checkRate.mockResolvedValue({ ok: false })
|
||||
expect((await POST(createMockRequest('/x', { method: 'POST', body: body() }), createMockRouteParams({}))).status).toBe(429)
|
||||
})
|
||||
it('400 on a missing/invalid transaction_id', async () => {
|
||||
expect((await POST(createMockRequest('/x', { method: 'POST', body: {} }), createMockRouteParams({}))).status).toBe(400)
|
||||
expect((await POST(createMockRequest('/x', { method: 'POST', body: { transaction_id: 'nope' } }), createMockRouteParams({}))).status).toBe(400)
|
||||
})
|
||||
it('403 without the ai capability', async () => {
|
||||
requireCapability.mockResolvedValue(NextResponse.json({ error: 'pay' }, { status: 403 }))
|
||||
expect((await POST(createMockRequest('/x', { method: 'POST', body: body() }), createMockRouteParams({}))).status).toBe(403)
|
||||
})
|
||||
it('503 when no backend is configured', async () => {
|
||||
aiStatus.mockReturnValue({ configured: false })
|
||||
const res = await POST(createMockRequest('/x', { method: 'POST', body: body() }), createMockRouteParams({}))
|
||||
const { status, body: b } = await parseJsonResponse<{ code: string }>(res)
|
||||
expect(status).toBe(503)
|
||||
expect(b.code).toBe('ai_unconfigured')
|
||||
expect(selectAccount).not.toHaveBeenCalled()
|
||||
})
|
||||
it('404 when the transaction is not found / not this company', async () => {
|
||||
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase: makeSupabase({ tx: null }), error: null })
|
||||
const res = await POST(createMockRequest('/x', { method: 'POST', body: body() }), createMockRouteParams({}))
|
||||
expect(res.status).toBe(404)
|
||||
expect(selectAccount).not.toHaveBeenCalled()
|
||||
})
|
||||
it('returns the selection + candidate slate on the happy path', async () => {
|
||||
const res = await POST(createMockRequest('/x', { method: 'POST', body: body({ samples: 3, underlag: 'Biltema AB 499 kr' }) }), createMockRouteParams({}))
|
||||
const { status, body: b } = await parseJsonResponse<{
|
||||
data: { account: string; confidence: number; candidates: { account: string }[] }
|
||||
}>(res)
|
||||
expect(status).toBe(200)
|
||||
expect(b.data.account).toBe('5410')
|
||||
expect(b.data.confidence).toBe(0.86)
|
||||
expect(b.data.candidates[0].account).toBe('5410')
|
||||
// A caller-supplied underlag is used verbatim (no server gather).
|
||||
expect(gatherUnderlag).not.toHaveBeenCalled()
|
||||
expect(selectAccount).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ entityType: 'aktiebolag', vatRegistered: true, underlag: 'Biltema AB 499 kr', samples: 3 }),
|
||||
)
|
||||
})
|
||||
|
||||
it('gathers underlag server-side when the caller did not supply it', async () => {
|
||||
await POST(createMockRequest('/x', { method: 'POST', body: body() }), createMockRouteParams({}))
|
||||
expect(gatherUnderlag).toHaveBeenCalled()
|
||||
expect(selectAccount).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ underlag: 'Kvitto: Biltema, totalt 499 SEK.' }),
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -1,107 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { createMockRequest } from '@/tests/helpers'
|
||||
|
||||
const requireAuthMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-auth', () => ({ requireAuth: () => requireAuthMock() }))
|
||||
vi.mock('@/lib/company/context', () => ({ getActiveCompanyId: vi.fn().mockResolvedValue('company-1') }))
|
||||
const guardSandbox = vi.fn()
|
||||
vi.mock('@/lib/sandbox/guard', () => ({ guardSandbox: () => guardSandbox() }))
|
||||
|
||||
import { POST } from '../route'
|
||||
|
||||
const inserts: Record<string, unknown>[] = []
|
||||
// company_settings.maybeSingle() feeds the consent gate; company_members
|
||||
// feeds the membership check. Default: a member of an opted-in company.
|
||||
function makeSupabase(membership: unknown = { user_id: 'user-1' }, optedIn = true) {
|
||||
return {
|
||||
from(table: string) {
|
||||
const chain = {
|
||||
select: () => chain,
|
||||
eq: () => chain,
|
||||
maybeSingle: async () =>
|
||||
table === 'company_settings'
|
||||
? { data: { data_analysis_opt_in: optedIn }, error: null }
|
||||
: { data: membership, error: null },
|
||||
insert: async (payload: Record<string, unknown>) => {
|
||||
if (table === 'categorize_calibration_samples') inserts.push(payload)
|
||||
return { error: null }
|
||||
},
|
||||
}
|
||||
return chain
|
||||
},
|
||||
}
|
||||
}
|
||||
const supabase = makeSupabase()
|
||||
|
||||
const body = (o: Record<string, unknown> = {}) => ({ confidence: 0.9, booked_account: '5410', ...o })
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
inserts.length = 0
|
||||
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
|
||||
guardSandbox.mockResolvedValue(null)
|
||||
})
|
||||
|
||||
describe('POST /api/agent/categorize/outcome', () => {
|
||||
it('401 when unauthenticated', async () => {
|
||||
requireAuthMock.mockResolvedValue({ user: null, supabase, error: NextResponse.json({ error: 'x' }, { status: 401 }) })
|
||||
expect((await POST(createMockRequest('/x', { method: 'POST', body: body() }))).status).toBe(401)
|
||||
})
|
||||
|
||||
it('400 on an invalid body', async () => {
|
||||
expect((await POST(createMockRequest('/x', { method: 'POST', body: { confidence: 2 } }))).status).toBe(400)
|
||||
expect((await POST(createMockRequest('/x', { method: 'POST', body: { booked_account: '5410' } }))).status).toBe(400)
|
||||
})
|
||||
|
||||
it('403 without company membership', async () => {
|
||||
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase: makeSupabase(null), error: null })
|
||||
expect((await POST(createMockRequest('/x', { method: 'POST', body: body() }))).status).toBe(403)
|
||||
})
|
||||
|
||||
it('skips sandbox bookings (204, no sample)', async () => {
|
||||
guardSandbox.mockResolvedValue(NextResponse.json({ error: 'sandbox' }, { status: 403 }))
|
||||
const res = await POST(createMockRequest('/x', { method: 'POST', body: body() }))
|
||||
expect(res.status).toBe(204)
|
||||
expect(inserts).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('skips companies that have not opted in to data analysis (204, no sample)', async () => {
|
||||
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase: makeSupabase({ user_id: 'user-1' }, false), error: null })
|
||||
const res = await POST(
|
||||
createMockRequest('/x', { method: 'POST', body: body({ proposed_account: '5410', booked_account: '5410' }) }),
|
||||
)
|
||||
expect(res.status).toBe(204)
|
||||
expect(inserts).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('logs was_correct=true when the proposed account was booked (opted-in company)', async () => {
|
||||
const res = await POST(
|
||||
createMockRequest('/x', {
|
||||
method: 'POST',
|
||||
body: body({ proposed_account: '5410', booked_account: '5410', confidence: 0.86, source: 'counterparty_template', amount: 499 }),
|
||||
}),
|
||||
)
|
||||
expect(res.status).toBe(204)
|
||||
expect(inserts).toHaveLength(1)
|
||||
expect(inserts[0]).toMatchObject({
|
||||
company_id: 'company-1',
|
||||
confidence: 0.86,
|
||||
proposed_account: '5410',
|
||||
booked_account: '5410',
|
||||
was_correct: true,
|
||||
source: 'counterparty_template',
|
||||
amount: 499,
|
||||
})
|
||||
})
|
||||
|
||||
it('logs was_correct=false when the user booked a different account', async () => {
|
||||
await POST(createMockRequest('/x', { method: 'POST', body: body({ proposed_account: '5410', booked_account: '6110' }) }))
|
||||
expect(inserts[0].was_correct).toBe(false)
|
||||
})
|
||||
|
||||
it('logs was_correct=false when there was no proposed account', async () => {
|
||||
await POST(createMockRequest('/x', { method: 'POST', body: body({ proposed_account: null, booked_account: '5410' }) }))
|
||||
expect(inserts[0].was_correct).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -1,89 +0,0 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { z } from 'zod'
|
||||
import { requireAuth } from '@/lib/auth/require-auth'
|
||||
import { getActiveCompanyId } from '@/lib/company/context'
|
||||
import { isDataAnalysisOptedIn } from '@/lib/company/data-analysis'
|
||||
import { guardSandbox } from '@/lib/sandbox/guard'
|
||||
|
||||
/**
|
||||
* POST /api/agent/categorize/outcome: log one calibration sample.
|
||||
*
|
||||
* Called (fire-and-forget) after a user books an AI proposal: it records the
|
||||
* confidence the model reported and whether the proposed account was the one
|
||||
* actually booked. That corpus is what lib/agent/categorize/calibration.ts
|
||||
* later fits an isotonic calibrator on, so "säker" can be made to mean ~right.
|
||||
*
|
||||
* Telemetry only: it never posts anything and is gated on auth + membership.
|
||||
* Sandbox bookings run on seed data, so they are silently skipped (a 204) to
|
||||
* keep the corpus clean. The corpus is read across companies, so it only
|
||||
* collects from companies that opted in to data analysis
|
||||
* (company_settings.data_analysis_opt_in, #1346): everyone else gets the same
|
||||
* silent 204 and no row.
|
||||
*/
|
||||
|
||||
const Schema = z.object({
|
||||
company_id: z.string().uuid().optional(),
|
||||
confidence: z.number().min(0).max(1),
|
||||
proposed_account: z.string().max(20).nullable().optional(),
|
||||
booked_account: z.string().min(1).max(20),
|
||||
agreement: z.number().min(0).max(1).nullable().optional(),
|
||||
model_confidence: z.enum(['high', 'medium', 'low']).nullable().optional(),
|
||||
source: z.string().max(40).nullable().optional(),
|
||||
amount: z.number().nullable().optional(),
|
||||
})
|
||||
|
||||
const noContent = () => new Response(null, { status: 204 })
|
||||
|
||||
export async function POST(request: Request): Promise<Response> {
|
||||
const { user, supabase, error } = await requireAuth()
|
||||
if (error) return error
|
||||
|
||||
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: 'Invalid body' }, { status: 400 })
|
||||
|
||||
const companyId = parsed.data.company_id ?? (await getActiveCompanyId(supabase, user.id))
|
||||
if (!companyId) return noContent()
|
||||
|
||||
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 })
|
||||
|
||||
// Sandbox bookings are seed data: don't pollute the calibration corpus.
|
||||
const blocked = await guardSandbox(supabase, companyId)
|
||||
if (blocked) return noContent()
|
||||
|
||||
// Consent gate: the corpus is analysed across companies, so a company that
|
||||
// has not opted in contributes nothing (default false, no grandfathering).
|
||||
if (!(await isDataAnalysisOptedIn(supabase, companyId))) return noContent()
|
||||
|
||||
const proposed = parsed.data.proposed_account ?? null
|
||||
|
||||
// Best-effort: a failed telemetry insert must never surface to the user.
|
||||
try {
|
||||
await supabase.from('categorize_calibration_samples').insert({
|
||||
company_id: companyId,
|
||||
confidence: parsed.data.confidence,
|
||||
agreement: parsed.data.agreement ?? null,
|
||||
model_confidence: parsed.data.model_confidence ?? null,
|
||||
source: parsed.data.source ?? null,
|
||||
proposed_account: proposed,
|
||||
booked_account: parsed.data.booked_account,
|
||||
was_correct: proposed !== null && proposed === parsed.data.booked_account,
|
||||
amount: parsed.data.amount ?? null,
|
||||
})
|
||||
} catch {
|
||||
// swallow
|
||||
}
|
||||
|
||||
return noContent()
|
||||
}
|
||||
@@ -1,132 +0,0 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { parseEntityType } from '@/lib/company/entity-type'
|
||||
import { z } from 'zod'
|
||||
import { withRouteContext } from '@/lib/api/with-route-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 { gatherCandidates } from '@/lib/agent/categorize/candidates'
|
||||
import { gatherUnderlag } from '@/lib/agent/categorize/underlag'
|
||||
import { selectAccount } from '@/lib/agent/categorize/select-account'
|
||||
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
|
||||
import type { EntityType, Transaction } from '@/types'
|
||||
|
||||
/**
|
||||
* POST /api/agent/categorize: a provider-agnostic booking proposal for one
|
||||
* transaction — the auto-booking cascade end to end (Tier 1 retrieval → Tier 2
|
||||
* selector), minus the write.
|
||||
*
|
||||
* It gathers the deterministic candidate accounts (counterparty templates,
|
||||
* rules, history) with NO model call, then has the model SELECT among them
|
||||
* (self-consistency sampled), and returns the proposed account + VAT +
|
||||
* confidence + reasoning + the candidate slate. It never posts anything: the
|
||||
* caller (the transaction row) renders the proposal as an approval card.
|
||||
*
|
||||
* Runs on any configured backend (Bedrock or a local model), so it is gated on
|
||||
* `configured`, not `assistantAvailable` — same as /api/agent/ask.
|
||||
*/
|
||||
|
||||
const Schema = z.object({
|
||||
transaction_id: z.string().uuid(),
|
||||
company_id: z.string().uuid().optional(),
|
||||
/** Extracted receipt/invoice text, if the caller already has it. */
|
||||
underlag: z.string().max(24_000).optional(),
|
||||
/** Self-consistency samples (default 3). */
|
||||
samples: z.number().int().min(1).max(5).optional(),
|
||||
})
|
||||
|
||||
// withRouteContext enforces auth (MFA on hosted) and resolves the active
|
||||
// company; the body may still name another company the caller belongs to.
|
||||
export const POST = withRouteContext(
|
||||
'agent.categorize',
|
||||
async (request, { user, supabase, companyId: activeCompanyId }) => {
|
||||
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 förfrågan.', type: 'validation_error' }, { status: 400 })
|
||||
}
|
||||
|
||||
const companyId = parsed.data.company_id ?? activeCompanyId
|
||||
|
||||
// The wrapper already guarantees membership of the active company; an
|
||||
// explicit company_id override must be verified the same way.
|
||||
if (companyId !== activeCompanyId) {
|
||||
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
|
||||
|
||||
if (!getAiStatus().configured) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Assistenten är inte konfigurerad på den här installationen.', code: 'ai_unconfigured' },
|
||||
{ status: 503 },
|
||||
)
|
||||
}
|
||||
|
||||
const { data: tx } = await supabase
|
||||
.from('transactions')
|
||||
.select('id, merchant_name, description, original_description, amount, date, currency, category, is_business, document_id')
|
||||
.eq('id', parsed.data.transaction_id)
|
||||
.eq('company_id', companyId)
|
||||
.maybeSingle()
|
||||
if (!tx) return NextResponse.json({ error: 'Transaktionen hittades inte.' }, { status: 404 })
|
||||
|
||||
const [{ data: company }, { data: settings }] = await Promise.all([
|
||||
supabase.from('companies').select('entity_type').eq('id', companyId).maybeSingle(),
|
||||
supabase.from('company_settings').select('vat_registered').eq('company_id', companyId).maybeSingle(),
|
||||
])
|
||||
|
||||
try {
|
||||
// Gather the matched receipt/invoice text when the caller didn't supply it:
|
||||
// this is what lifts the cold-start case — the model reads the actual
|
||||
// supplier + line items, not just the bank line. Best-effort; '' if none.
|
||||
const underlag =
|
||||
parsed.data.underlag ??
|
||||
(await gatherUnderlag(
|
||||
supabase,
|
||||
companyId,
|
||||
(tx as Transaction).id,
|
||||
(tx as { document_id?: string | null }).document_id,
|
||||
))
|
||||
|
||||
const candidates = await gatherCandidates(supabase, companyId, tx as Transaction)
|
||||
const selection = await selectAccount({
|
||||
transaction: {
|
||||
merchantName: (tx as Transaction).merchant_name,
|
||||
description: (tx as Transaction).description,
|
||||
amount: (tx as Transaction).amount,
|
||||
date: (tx as Transaction).date,
|
||||
currency: (tx as Transaction).currency,
|
||||
},
|
||||
underlag,
|
||||
candidates,
|
||||
entityType: parseEntityType(company?.entity_type),
|
||||
vatRegistered: settings?.vat_registered ?? false,
|
||||
samples: parsed.data.samples,
|
||||
})
|
||||
return NextResponse.json({ data: { ...selection, candidates } })
|
||||
} catch (err) {
|
||||
return NextResponse.json({ error: getUserErrorMessage(err) }, { status: 500 })
|
||||
}
|
||||
},
|
||||
)
|
||||
@@ -1,103 +0,0 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { z } from 'zod'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { checkAgentRateLimit, agentRateLimitResponseBody } from '@/lib/rate-limits/agent'
|
||||
import { composeAgentProfile } from '@/lib/agent/composer'
|
||||
import { guardSandbox } from '@/lib/sandbox/guard'
|
||||
import { requireCapability } from '@/lib/entitlements/has-capability'
|
||||
import { CAPABILITY } from '@/lib/entitlements/keys'
|
||||
|
||||
const BodySchema = z.object({
|
||||
// Optional override; if absent we use the user's active_company_id.
|
||||
company_id: z.string().uuid().optional(),
|
||||
// dry_run=true returns the composed profile without writing to agent_profiles.
|
||||
dry_run: z.boolean().optional(),
|
||||
})
|
||||
|
||||
// POST /api/agent/composer
|
||||
//
|
||||
// Runs the specialized accountant composer pipeline for a company:
|
||||
// 1. Gathers TIC snapshot, optional SIE summary, optional banking summary.
|
||||
// 2. Calls Opus 4.7 to select horizontal/vertical/modifier atoms.
|
||||
// 3. Calls Sonnet 4.6 to write the Swedish profile_summary.
|
||||
// 4. Persists to agent_profiles (skipped on dry_run).
|
||||
// 5. Fires fire-and-forget cache pre-warm.
|
||||
//
|
||||
// Auth: must be a non-viewer member of the target company (it rewrites the
|
||||
// company's agent_profile unless dry_run).
|
||||
//
|
||||
// Plan ref: dev_docs/specialized-agent-plan.md §6.
|
||||
export const POST = withRouteContext('agent.composer.run', async (request, ctx) => {
|
||||
const { supabase, companyId: activeCompanyId, user } = ctx
|
||||
|
||||
const rate = await checkAgentRateLimit(supabase, user.id)
|
||||
if (!rate.ok) {
|
||||
return NextResponse.json(agentRateLimitResponseBody(rate), {
|
||||
status: 429,
|
||||
headers: rate.retryAfterSec ? { 'Retry-After': String(rate.retryAfterSec) } : undefined,
|
||||
})
|
||||
}
|
||||
|
||||
// Tolerant parse: ops callers POST with an empty body, which is valid here.
|
||||
const raw = await request.json().catch(() => ({}))
|
||||
const parsed = BodySchema.safeParse(raw)
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: 'Validation failed',
|
||||
type: 'validation_error',
|
||||
errors: parsed.error.issues.map((issue) => ({
|
||||
field: issue.path.join('.'),
|
||||
message: issue.message,
|
||||
code: issue.code,
|
||||
})),
|
||||
},
|
||||
{ status: 400 },
|
||||
)
|
||||
}
|
||||
const body = parsed.data
|
||||
|
||||
const companyId = body.company_id ?? activeCompanyId
|
||||
|
||||
// Defense in depth alongside RLS: confirm membership before composing, and
|
||||
// require a non-viewer role: the composer rewrites agent_profiles.
|
||||
const { data: membership } = await supabase
|
||||
.from('company_members')
|
||||
.select('role')
|
||||
.eq('company_id', companyId)
|
||||
.eq('user_id', user.id)
|
||||
.maybeSingle()
|
||||
if (!membership) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: {
|
||||
code: 'NOT_COMPANY_MEMBER',
|
||||
message: 'Du är inte medlem i detta företag.',
|
||||
message_en: 'Not a member of this company.',
|
||||
},
|
||||
},
|
||||
{ status: 403 },
|
||||
)
|
||||
}
|
||||
if (membership.role === 'viewer') {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: {
|
||||
code: 'WRITE_PERMISSION_REQUIRED',
|
||||
message: 'Du har endast läsbehörighet i detta företag.',
|
||||
message_en: 'You only have read access in this company.',
|
||||
},
|
||||
},
|
||||
{ status: 403 },
|
||||
)
|
||||
}
|
||||
|
||||
const blocked = await guardSandbox(supabase, companyId)
|
||||
if (blocked) return blocked
|
||||
|
||||
const capBlocked = await requireCapability(supabase, companyId, CAPABILITY.ai)
|
||||
if (capBlocked) return capBlocked
|
||||
|
||||
const composed = await composeAgentProfile(supabase, companyId, { dryRun: body.dry_run })
|
||||
return NextResponse.json({ data: composed })
|
||||
})
|
||||
@@ -1,61 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { createMockRequest, createMockRouteParams, parseJsonResponse, createQueuedMockSupabase } from '@/tests/helpers'
|
||||
|
||||
const { supabase: mockSupabase, enqueue, reset } = createQueuedMockSupabase()
|
||||
|
||||
const requireAuthMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-auth', () => ({ requireAuth: (...a: unknown[]) => requireAuthMock(...a) }))
|
||||
vi.mock('@/lib/company/context', () => ({
|
||||
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
}))
|
||||
vi.mock('@/lib/auth/require-write', () => ({ requireWritePermission: vi.fn().mockResolvedValue({ ok: true }) }))
|
||||
const rejectPending = vi.fn()
|
||||
vi.mock('@/lib/agent/pending/reject-conversation-pending', () => ({
|
||||
rejectPendingForConversation: (...a: unknown[]) => rejectPending(...a),
|
||||
}))
|
||||
|
||||
import { POST } from '../reject-pending/route'
|
||||
|
||||
const params = () => createMockRouteParams({ id: 'conv-1' })
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
reset()
|
||||
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase: mockSupabase, error: null })
|
||||
rejectPending.mockResolvedValue(3)
|
||||
})
|
||||
|
||||
describe('POST /api/agent/conversations/[id]/reject-pending', () => {
|
||||
it('401 when unauthenticated', async () => {
|
||||
requireAuthMock.mockResolvedValue({ user: null, supabase: mockSupabase, error: NextResponse.json({ error: 'x' }, { status: 401 }) })
|
||||
const res = await POST(createMockRequest('/x', { method: 'POST' }), params())
|
||||
expect((await parseJsonResponse(res)).status).toBe(401)
|
||||
})
|
||||
|
||||
it('404 when the conversation is not the caller’s', async () => {
|
||||
enqueue({ data: null }) // conversation ownership lookup misses
|
||||
const res = await POST(createMockRequest('/x', { method: 'POST' }), params())
|
||||
expect(res.status).toBe(404)
|
||||
expect(rejectPending).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('404 when the caller is no longer a member of the company', async () => {
|
||||
enqueue({ data: { id: 'conv-1', company_id: 'company-1', user_id: 'user-1' } }) // owns it
|
||||
enqueue({ data: null }) // membership lookup misses
|
||||
const res = await POST(createMockRequest('/x', { method: 'POST' }), params())
|
||||
expect(res.status).toBe(404)
|
||||
expect(rejectPending).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('clears the conversation’s pending proposals and returns the count', async () => {
|
||||
enqueue({ data: { id: 'conv-1', company_id: 'company-1', user_id: 'user-1' } })
|
||||
enqueue({ data: { role: 'owner' } })
|
||||
const res = await POST(createMockRequest('/x', { method: 'POST' }), params())
|
||||
const { status, body } = await parseJsonResponse<{ data: { cleared: number } }>(res)
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.cleared).toBe(3)
|
||||
expect(rejectPending).toHaveBeenCalledWith(mockSupabase, 'company-1', 'conv-1')
|
||||
})
|
||||
})
|
||||
@@ -1,50 +0,0 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { rejectPendingForConversation } from '@/lib/agent/pending/reject-conversation-pending'
|
||||
|
||||
// POST /api/agent/conversations/[id]/reject-pending
|
||||
//
|
||||
// Rejects every still-pending proposal the assistant staged in this
|
||||
// conversation — the chat's "clear the proposals I didn't approve" action, so
|
||||
// users don't have to reject leftovers one by one in Granskning.
|
||||
|
||||
const notFound = () =>
|
||||
NextResponse.json(
|
||||
{
|
||||
error: {
|
||||
code: 'CONVERSATION_NOT_FOUND',
|
||||
message: 'Konversationen hittades inte.',
|
||||
message_en: 'Conversation not found.',
|
||||
},
|
||||
},
|
||||
{ status: 404 },
|
||||
)
|
||||
|
||||
export const POST = withRouteContext(
|
||||
'agent.conversations.reject_pending',
|
||||
async (_request, ctx, { params }: { params: Promise<{ id: string }> }) => {
|
||||
const { id } = await params
|
||||
const { supabase, user } = ctx
|
||||
|
||||
// Conversations are user-scoped: prove ownership before touching its rows.
|
||||
const { data: conv } = await supabase
|
||||
.from('agent_conversations')
|
||||
.select('id, company_id, user_id')
|
||||
.eq('id', id)
|
||||
.eq('user_id', user.id)
|
||||
.maybeSingle()
|
||||
if (!conv) return notFound()
|
||||
|
||||
// Defense in depth alongside RLS: still a member of the conversation's company.
|
||||
const { data: membership } = await supabase
|
||||
.from('company_members')
|
||||
.select('role')
|
||||
.eq('company_id', conv.company_id)
|
||||
.eq('user_id', user.id)
|
||||
.maybeSingle()
|
||||
if (!membership) return notFound()
|
||||
|
||||
const cleared = await rejectPendingForConversation(supabase, conv.company_id as string, id)
|
||||
return NextResponse.json({ data: { cleared } })
|
||||
},
|
||||
)
|
||||
@@ -1,165 +0,0 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { z } from 'zod'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { validateBody } from '@/lib/api/validate'
|
||||
import { rejectPendingForConversation } from '@/lib/agent/pending/reject-conversation-pending'
|
||||
|
||||
// GET /api/agent/conversations/[id]
|
||||
//
|
||||
// Returns one conversation + its messages in chronological order. The chat
|
||||
// page hydrates with this on mount; the agent loop then continues via
|
||||
// /api/agent/invoke with the conversation_id.
|
||||
//
|
||||
// PATCH /api/agent/conversations/[id]
|
||||
//
|
||||
// Updates pin/archive state or title. The chat list relies on these.
|
||||
|
||||
const PatchSchema = z.object({
|
||||
pinned: z.boolean().nullable().optional(),
|
||||
archived: z.boolean().nullable().optional(),
|
||||
title: z.string().min(1).max(200).nullable().optional(),
|
||||
})
|
||||
|
||||
const notFound = () =>
|
||||
NextResponse.json(
|
||||
{
|
||||
error: {
|
||||
code: 'CONVERSATION_NOT_FOUND',
|
||||
message: 'Konversationen hittades inte.',
|
||||
message_en: 'Conversation not found.',
|
||||
},
|
||||
},
|
||||
{ status: 404 },
|
||||
)
|
||||
|
||||
export const GET = withRouteContext(
|
||||
'agent.conversations.get',
|
||||
async (_request, ctx, { params }: { params: Promise<{ id: string }> }) => {
|
||||
const { id } = await params
|
||||
const { supabase, user } = ctx
|
||||
|
||||
// Conversations are user-scoped: fetched by ownership rather than the
|
||||
// active company, so a user can open their own conversations in any
|
||||
// company they belong to.
|
||||
const { data: conv, error: convErr } = await supabase
|
||||
.from('agent_conversations')
|
||||
.select(
|
||||
'id, company_id, user_id, intent_id, context_ref, title, pinned, archived, last_message_at, created_at',
|
||||
)
|
||||
.eq('id', id)
|
||||
.eq('user_id', user.id)
|
||||
.maybeSingle()
|
||||
if (convErr) throw convErr
|
||||
if (!conv) return notFound()
|
||||
|
||||
// Defense in depth alongside RLS: the caller must still be a member of
|
||||
// the conversation's company (they may have been removed since).
|
||||
const { data: membership } = await supabase
|
||||
.from('company_members')
|
||||
.select('role')
|
||||
.eq('company_id', conv.company_id)
|
||||
.eq('user_id', user.id)
|
||||
.maybeSingle()
|
||||
if (!membership) return notFound()
|
||||
|
||||
const { data: messages, error: msgErr } = await supabase
|
||||
.from('agent_messages')
|
||||
.select('id, role, content, tool_use_id, hidden, created_at')
|
||||
.eq('conversation_id', id)
|
||||
.order('created_at', { ascending: true })
|
||||
if (msgErr) throw msgErr
|
||||
|
||||
// Proposals this conversation staged that nobody has answered yet.
|
||||
//
|
||||
// Approval cards ride on the streamed `staged_operation` events, which are
|
||||
// not persisted, so a resumed thread rendered the tool trace and the answer
|
||||
// but silently dropped the card: the proposal then sat in Granskning for
|
||||
// its full 30 days with nothing in the conversation pointing at it.
|
||||
// run-turn stamps agent_metadata.conversation_id on every staged row, so
|
||||
// the still-open ones can be re-attached here.
|
||||
const { data: staged, error: stagedErr } = await supabase
|
||||
.from('pending_operations')
|
||||
.select('id, operation_type, title, risk_level, preview_data, created_at')
|
||||
.eq('company_id', conv.company_id)
|
||||
.eq('status', 'pending')
|
||||
.eq('agent_metadata->>conversation_id', id)
|
||||
.order('created_at', { ascending: true })
|
||||
// Do not swallow this: silently returning an empty list would drop the very
|
||||
// proposals this query exists to restore, and the thread would look like it
|
||||
// never staged anything. Same handling as the message query above.
|
||||
if (stagedErr) throw stagedErr
|
||||
|
||||
return NextResponse.json({
|
||||
data: {
|
||||
conversation: conv,
|
||||
messages: messages ?? [],
|
||||
staged_operations: staged ?? [],
|
||||
},
|
||||
})
|
||||
},
|
||||
)
|
||||
|
||||
export const PATCH = withRouteContext(
|
||||
'agent.conversations.update',
|
||||
async (request, ctx, { params }: { params: Promise<{ id: string }> }) => {
|
||||
const { id } = await params
|
||||
const { supabase, user, log } = ctx
|
||||
|
||||
const validation = await validateBody(request, PatchSchema, {
|
||||
log,
|
||||
operation: 'agent.conversations.update',
|
||||
})
|
||||
if (!validation.success) return validation.response
|
||||
const body = validation.data
|
||||
|
||||
const update: Record<string, unknown> = {}
|
||||
if (body.pinned != null) update.pinned = body.pinned
|
||||
if (body.archived != null) update.archived = body.archived
|
||||
if (body.title != null) update.title = body.title
|
||||
if (Object.keys(update).length === 0) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: {
|
||||
code: 'NOTHING_TO_UPDATE',
|
||||
message: 'Inget att uppdatera.',
|
||||
message_en: 'Nothing to update.',
|
||||
},
|
||||
},
|
||||
{ status: 400 },
|
||||
)
|
||||
}
|
||||
|
||||
// Defense in depth: verify ownership before update so a 404 is returned
|
||||
// (instead of relying solely on RLS, which would silently 0-row).
|
||||
const { data: existing } = await supabase
|
||||
.from('agent_conversations')
|
||||
.select('user_id, company_id')
|
||||
.eq('id', id)
|
||||
.eq('user_id', user.id)
|
||||
.maybeSingle()
|
||||
if (!existing) return notFound()
|
||||
|
||||
const { data, error } = await supabase
|
||||
.from('agent_conversations')
|
||||
.update(update)
|
||||
.eq('id', id)
|
||||
.eq('user_id', user.id)
|
||||
.eq('company_id', existing.company_id)
|
||||
.select('id, intent_id, context_ref, title, pinned, archived, last_message_at, created_at')
|
||||
.single()
|
||||
if (error) throw error
|
||||
|
||||
// Archiving a thread means "I'm done with it": clear any proposals the
|
||||
// assistant staged here that the user never acted on, so they don't linger
|
||||
// in Granskning. Best-effort — a failure here must not fail the archive.
|
||||
if (body.archived === true) {
|
||||
try {
|
||||
await rejectPendingForConversation(supabase, existing.company_id as string, id)
|
||||
} catch {
|
||||
// ignored
|
||||
}
|
||||
}
|
||||
|
||||
return NextResponse.json({ data })
|
||||
},
|
||||
)
|
||||
@@ -1,121 +0,0 @@
|
||||
/**
|
||||
* GET /api/agent/conversations/[id] returns the conversation's still-open
|
||||
* proposals alongside its messages.
|
||||
*
|
||||
* Approval cards live in streamed events that are never persisted, so without
|
||||
* these rows a resumed thread renders the tool trace and the answer but drops
|
||||
* the card, and the proposal waits out its 30-day expiry in Granskning with
|
||||
* nothing in the conversation pointing at it.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { NextResponse } from 'next/server'
|
||||
import {
|
||||
createMockRequest,
|
||||
createMockRouteParams,
|
||||
parseJsonResponse,
|
||||
createQueuedMockSupabase,
|
||||
} from '@/tests/helpers'
|
||||
|
||||
const { supabase: mockSupabase, enqueue, enqueueMany, reset } = createQueuedMockSupabase()
|
||||
|
||||
const requireAuthMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-auth', () => ({
|
||||
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/company/context', () => ({
|
||||
getActiveCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
requireCompanyId: vi.fn().mockResolvedValue('company-1'),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/auth/require-write', () => ({
|
||||
requireWritePermission: vi.fn().mockResolvedValue({ ok: true }),
|
||||
}))
|
||||
|
||||
import { GET } from '../[id]/route'
|
||||
|
||||
const CONV = { id: 'conv-1', company_id: 'company-1', user_id: 'user-1', intent_id: 'general.help' }
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
reset()
|
||||
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase: mockSupabase, error: null })
|
||||
})
|
||||
|
||||
describe('GET /api/agent/conversations/[id]', () => {
|
||||
it('returns 401 when not authenticated', async () => {
|
||||
requireAuthMock.mockResolvedValue({
|
||||
user: null,
|
||||
supabase: mockSupabase,
|
||||
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
|
||||
})
|
||||
|
||||
const res = await GET(
|
||||
createMockRequest('/api/agent/conversations/conv-1'),
|
||||
createMockRouteParams({ id: 'conv-1' }),
|
||||
)
|
||||
expect((await parseJsonResponse(res)).status).toBe(401)
|
||||
})
|
||||
|
||||
it('returns 404 for a conversation the caller does not own', async () => {
|
||||
enqueue({ data: null }) // conversation lookup filters on user_id
|
||||
|
||||
const res = await GET(
|
||||
createMockRequest('/api/agent/conversations/conv-1'),
|
||||
createMockRouteParams({ id: 'conv-1' }),
|
||||
)
|
||||
expect((await parseJsonResponse(res)).status).toBe(404)
|
||||
})
|
||||
|
||||
it('returns unanswered proposals alongside the messages', async () => {
|
||||
enqueueMany([
|
||||
{ data: CONV }, // conversation
|
||||
{ data: { role: 'owner' } }, // company_members
|
||||
{ data: [{ role: 'assistant', content: [] }] }, // agent_messages
|
||||
{
|
||||
data: [
|
||||
{
|
||||
id: 'op-1',
|
||||
operation_type: 'gnubok_categorize_transaction',
|
||||
title: 'Kontering: Circle K',
|
||||
risk_level: 'low',
|
||||
preview_data: {},
|
||||
},
|
||||
],
|
||||
}, // pending_operations
|
||||
])
|
||||
|
||||
const res = await GET(
|
||||
createMockRequest('/api/agent/conversations/conv-1'),
|
||||
createMockRouteParams({ id: 'conv-1' }),
|
||||
)
|
||||
const { status, body } = await parseJsonResponse<{
|
||||
data: { staged_operations: { id: string }[]; messages: unknown[] }
|
||||
}>(res)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.messages).toHaveLength(1)
|
||||
expect(body.data.staged_operations).toHaveLength(1)
|
||||
expect(body.data.staged_operations[0]!.id).toBe('op-1')
|
||||
})
|
||||
|
||||
it('returns an empty list rather than failing when nothing is staged', async () => {
|
||||
enqueueMany([
|
||||
{ data: CONV },
|
||||
{ data: { role: 'owner' } },
|
||||
{ data: [] },
|
||||
{ data: null }, // no rows at all
|
||||
])
|
||||
|
||||
const res = await GET(
|
||||
createMockRequest('/api/agent/conversations/conv-1'),
|
||||
createMockRouteParams({ id: 'conv-1' }),
|
||||
)
|
||||
const { status, body } = await parseJsonResponse<{
|
||||
data: { staged_operations: unknown[] }
|
||||
}>(res)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.staged_operations).toEqual([])
|
||||
})
|
||||
})
|
||||
@@ -1,71 +0,0 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { z } from 'zod'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { validateQuery } from '@/lib/api/validate'
|
||||
|
||||
// GET /api/agent/conversations
|
||||
//
|
||||
// Query params:
|
||||
// archived: 'true' | 'false' (default 'false')
|
||||
// pinned: 'true' filters to pinned only
|
||||
// intent: 'general.help' (or any intent id), filter
|
||||
// q: case-insensitive substring match on title/context_ref
|
||||
// limit: 1..200, default 50
|
||||
//
|
||||
// Returns: { data: [{ id, intent_id, context_ref, title, pinned, archived,
|
||||
// last_message_at, created_at }] }
|
||||
//
|
||||
// Ordered: pinned first (within archived bucket), then last_message_at desc.
|
||||
// Used by the /chat sidebar and "resume conversation" UI in the sheet.
|
||||
|
||||
const ListQuerySchema = z.object({
|
||||
archived: z.enum(['true', 'false']).default('false'),
|
||||
pinned: z.enum(['true', 'false']).optional(),
|
||||
intent: z.string().min(1).optional(),
|
||||
q: z.string().optional(),
|
||||
limit: z.coerce.number().int().min(1).max(200).default(50),
|
||||
})
|
||||
|
||||
export const GET = withRouteContext('agent.conversations.list', async (request, ctx) => {
|
||||
const { supabase, companyId, user, log } = ctx
|
||||
|
||||
const validated = validateQuery(request, ListQuerySchema, {
|
||||
log,
|
||||
operation: 'agent.conversations.list',
|
||||
})
|
||||
if (!validated.success) return validated.response
|
||||
const { archived, pinned, intent, limit } = validated.data
|
||||
const q = validated.data.q?.trim() ?? ''
|
||||
|
||||
let query = supabase
|
||||
.from('agent_conversations')
|
||||
.select(
|
||||
'id, intent_id, context_ref, title, pinned, archived, last_message_at, last_message_preview, created_at',
|
||||
)
|
||||
.eq('company_id', companyId)
|
||||
// Conversations are user-scoped within a company — one member must not
|
||||
// see another's (see [id]/route.ts). The RLS policy is company-scoped,
|
||||
// so this filter is what actually prevents cross-member leakage of
|
||||
// titles and last_message_preview snippets.
|
||||
.eq('user_id', user.id)
|
||||
.eq('archived', archived === 'true')
|
||||
|
||||
if (pinned === 'true') query = query.eq('pinned', true)
|
||||
if (intent) query = query.eq('intent_id', intent)
|
||||
if (q.length > 0) {
|
||||
// Pattern is sanitized via Postgres' percent-handling; ilike accepts the
|
||||
// % wildcard and we only inject the user's substring between them.
|
||||
const safe = q.replace(/[%_]/g, (m) => `\\${m}`)
|
||||
query = query.or(`title.ilike.%${safe}%,context_ref.ilike.%${safe}%`)
|
||||
}
|
||||
|
||||
// Sort: pinned first, then most recent message.
|
||||
query = query
|
||||
.order('pinned', { ascending: false })
|
||||
.order('last_message_at', { ascending: false, nullsFirst: false })
|
||||
.limit(limit)
|
||||
|
||||
const { data, error } = await query
|
||||
if (error) throw error
|
||||
return NextResponse.json({ data: data ?? [] })
|
||||
})
|
||||
@@ -1,108 +0,0 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { z } from 'zod'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { validateBody } from '@/lib/api/validate'
|
||||
import { ensureInitialized } from '@/lib/init'
|
||||
import { eventBus } from '@/lib/events/bus'
|
||||
|
||||
// The event bus is a module-level singleton and extension handlers are wired
|
||||
// by this call. Without it at module level the emit below goes nowhere and the
|
||||
// vote is silently dropped, which is exactly the failure this route exists to
|
||||
// fix.
|
||||
ensureInitialized()
|
||||
|
||||
// POST /api/agent/feedback
|
||||
//
|
||||
// A thumbs-up or thumbs-down on one assistant answer.
|
||||
//
|
||||
// The buttons have existed since the message-actions pass but were wired to
|
||||
// nothing: they animated, and the vote died in component state. An affordance
|
||||
// that looks like it reports something and does not is worse than no
|
||||
// affordance, because it spends the user's goodwill once and silently.
|
||||
//
|
||||
// This emits the SAME `agent.feedback` event the gnubok_feedback MCP tool
|
||||
// emits, with actorType 'user'. The product team already queries event_log for
|
||||
// that type, so votes from the chat land in the existing triage flow rather
|
||||
// than in a second place someone has to remember to look at. That is also why
|
||||
// there is no migration here: event_log takes the payload as jsonb and already
|
||||
// treats agent.* as telemetry with the longer retention.
|
||||
|
||||
const BodySchema = z.object({
|
||||
conversation_id: z.string().uuid(),
|
||||
sentiment: z.enum(['positive', 'negative']),
|
||||
// Which answer, so a vote can be traced to the turn it was about.
|
||||
message_index: z.number().int().min(0).optional(),
|
||||
})
|
||||
|
||||
export const POST = withRouteContext(
|
||||
'agent.feedback.create',
|
||||
async (request, ctx) => {
|
||||
const { supabase, companyId, user, log } = ctx
|
||||
|
||||
const validation = await validateBody(request, BodySchema, {
|
||||
log,
|
||||
operation: 'agent.feedback.create',
|
||||
})
|
||||
if (!validation.success) return validation.response
|
||||
const body = validation.data
|
||||
|
||||
// The conversation id comes from the client, so it is checked the same way
|
||||
// /api/agent/invoke checks it: without this, any member could attach
|
||||
// feedback to another member's thread, and the triage backlog would carry
|
||||
// rows whose conversation the reporter never saw.
|
||||
const { data: conversation } = await supabase
|
||||
.from('agent_conversations')
|
||||
.select('id, user_id, company_id, intent_id')
|
||||
.eq('id', body.conversation_id)
|
||||
.maybeSingle()
|
||||
|
||||
if (
|
||||
!conversation ||
|
||||
conversation.user_id !== user.id ||
|
||||
conversation.company_id !== companyId
|
||||
) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: {
|
||||
code: 'CONVERSATION_NOT_FOUND',
|
||||
message: 'Konversationen hittades inte.',
|
||||
message_en: 'Conversation not found.',
|
||||
},
|
||||
},
|
||||
{ status: 404 },
|
||||
)
|
||||
}
|
||||
|
||||
await eventBus.emit({
|
||||
type: 'agent.feedback',
|
||||
payload: {
|
||||
// Deliberately NOT free text. A comment box here would put whatever
|
||||
// the user typed, in an accounting product, verbatim into event_log
|
||||
// under telemetry retention: names, personnummer, client details. The
|
||||
// vote carries only what it needs to be actionable, which is the intent
|
||||
// and which answer it was about. If a comment field is ever wanted, it
|
||||
// needs its own data-classification and redaction decision first, made
|
||||
// with the UI in front of it rather than as an unused parameter.
|
||||
context: [
|
||||
`Chattbetyg på svar i ${conversation.intent_id}.`,
|
||||
body.message_index === undefined ? null : `(svar #${body.message_index})`,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(' '),
|
||||
sentiment: body.sentiment,
|
||||
suggestion: null,
|
||||
toolName: null,
|
||||
skillSlug: null,
|
||||
sessionId: conversation.id,
|
||||
actorType: 'user',
|
||||
actorId: user.id,
|
||||
actorLabel: null,
|
||||
userId: user.id,
|
||||
companyId,
|
||||
},
|
||||
})
|
||||
|
||||
return NextResponse.json({ data: { recorded: true } })
|
||||
},
|
||||
{ requireWrite: true },
|
||||
)
|
||||
@@ -1,370 +0,0 @@
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
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 { getIntent } from '@/lib/agent/intents/registry'
|
||||
import { checkAgentRateLimit, agentRateLimitResponseBody } from '@/lib/rate-limits/agent'
|
||||
import { runChatTurn, friendlyModelError } from '@/lib/agent/chat/run-turn'
|
||||
import { getAiStatus } from '@/lib/ai'
|
||||
import { guardSandbox } from '@/lib/sandbox/guard'
|
||||
import { requireCapability } from '@/lib/entitlements/has-capability'
|
||||
import { CAPABILITY } from '@/lib/entitlements/keys'
|
||||
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
|
||||
|
||||
// Make sure extensions are loaded: the chat loop dispatches against the
|
||||
// agent tool registry which is populated by the mcp-server extension at load.
|
||||
ensureInitialized()
|
||||
|
||||
// Deep turns (thinking at high/xhigh effort, up to 12 tool iterations, a
|
||||
// 15-27k-token prompt prefix) can outlive the plan default duration cap; a
|
||||
// function killed mid-stream closes the NDJSON stream cleanly, which the chat
|
||||
// used to render as silent success. 300 s matches the other long-running model
|
||||
// surfaces (app/api/receipt-hunt/run, app/api/agent/ask).
|
||||
export const maxDuration = 300
|
||||
|
||||
// Hard cap on the per-turn user input. Generous for a chat composer (about
|
||||
// 5k words / 20 pages) but bounds Bedrock token cost if the rate limiter is
|
||||
// ever fail-open and a client floods large payloads.
|
||||
const MAX_USER_MESSAGE_LEN = 20_000
|
||||
|
||||
const BodySchema = z.object({
|
||||
intent_id: z.string().min(1).max(200),
|
||||
// Existing conversation to resume; if omitted, the route creates one. The
|
||||
// chat sheet's React state holds the conversation id as `string | null`
|
||||
// and serializes `null` on the first turn, so accept null alongside
|
||||
// undefined and treat both as "no existing conversation".
|
||||
conversation_id: z.string().uuid().nullable().optional(),
|
||||
// Optional company override; defaults to active_company_id.
|
||||
company_id: z.string().uuid().nullable().optional(),
|
||||
// The user's message (or, on the first turn, this is empty and we send the
|
||||
// intent's prompt template instead). Capped to bound LLM cost.
|
||||
user_message: z.string().max(MAX_USER_MESSAGE_LEN).nullable().optional(),
|
||||
// Intent-specific capture args (e.g. { transaction_id: '...' } for
|
||||
// transaction.categorization). Used only on the first turn to build the
|
||||
// prompt template. Each value is bounded so capture inputs can't be a
|
||||
// megabyte each; the dispatcher rejects oversize values upfront.
|
||||
intent_args: z
|
||||
.record(z.string().max(120), z.unknown())
|
||||
.nullable()
|
||||
.optional()
|
||||
.refine(
|
||||
(v) => {
|
||||
if (!v) return true
|
||||
try {
|
||||
return JSON.stringify(v).length <= MAX_USER_MESSAGE_LEN
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
},
|
||||
{ message: 'intent_args too large' },
|
||||
),
|
||||
// Optional context_ref for the conversation row, e.g. 'transaction:<id>'.
|
||||
context_ref: z.string().max(200).nullable().optional(),
|
||||
// When true (and user_message is provided), persist the turn but flag it
|
||||
// hidden so it doesn't render as a user bubble on resume. Used by the chat's
|
||||
// rejection-correction flow (ApprovalCard → AgentChat) to feed the agent a
|
||||
// synthetic correction without showing it as something the user typed.
|
||||
user_message_hidden: z.boolean().nullable().optional(),
|
||||
})
|
||||
|
||||
// POST /api/agent/invoke
|
||||
//
|
||||
// Streams NDJSON events from the chat loop. Each line is a JSON object whose
|
||||
// `kind` identifies the event type: see lib/agent/chat/run-turn.ts StreamEvent.
|
||||
//
|
||||
// Auth: the user must be a member of the resolved company.
|
||||
//
|
||||
// Plan ref: dev_docs/specialized-agent-plan.md §9 (chat loop).
|
||||
export async function POST(request: Request) {
|
||||
const { user, supabase, error } = await requireAuth()
|
||||
if (error) return error
|
||||
|
||||
// Generous per-user rate limit: bounds runaway Bedrock spend (loop-firing
|
||||
// sessions). Fails open on infra error.
|
||||
const rate = await checkAgentRateLimit(supabase, user.id)
|
||||
if (!rate.ok) {
|
||||
return NextResponse.json(agentRateLimitResponseBody(rate), {
|
||||
status: 429,
|
||||
headers: rate.retryAfterSec ? { 'Retry-After': String(rate.retryAfterSec) } : undefined,
|
||||
})
|
||||
}
|
||||
|
||||
let body: z.infer<typeof BodySchema>
|
||||
try {
|
||||
body = BodySchema.parse(await request.json())
|
||||
} catch (err) {
|
||||
return NextResponse.json(
|
||||
{ error: err instanceof Error ? getUserErrorMessage(err) : 'Invalid body' },
|
||||
{ status: 400 },
|
||||
)
|
||||
}
|
||||
|
||||
const intent = getIntent(body.intent_id)
|
||||
if (!intent) {
|
||||
return NextResponse.json({ error: `Unknown intent: ${body.intent_id}` }, { status: 400 })
|
||||
}
|
||||
|
||||
const companyId = body.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('role')
|
||||
.eq('company_id', companyId)
|
||||
.eq('user_id', user.id)
|
||||
.maybeSingle()
|
||||
if (!membership) return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
|
||||
|
||||
// No Anthropic Bedrock calls in the sandbox: the demo runs entirely on
|
||||
// seed data and the assistant is gated to a "look, don't touch" preview.
|
||||
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: the deployment has no AI backend the chat
|
||||
// loop can run on (no credentials, or an OpenAI-compatible endpoint, which
|
||||
// the loop does not speak yet). Answer up front instead of opening a
|
||||
// stream that dies on the first model call.
|
||||
if (!getAiStatus().assistantAvailable) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: 'Assistenten är inte konfigurerad på den här installationen.',
|
||||
code: 'ai_unconfigured',
|
||||
},
|
||||
{ status: 503 },
|
||||
)
|
||||
}
|
||||
|
||||
// Resolve the conversation BEFORE any side effect below (the onboarding
|
||||
// intake stamp): a request that is about to be rejected must not write.
|
||||
let conversationId = body.conversation_id ?? null
|
||||
if (conversationId) {
|
||||
// A resumed conversation id comes straight from the client, so ownership
|
||||
// has to be proven here. RLS on agent_conversations/agent_messages is
|
||||
// COMPANY-scoped (migration 20260517204000), not user-scoped, so RLS alone
|
||||
// would happily load a colleague's thread into the prompt and append this
|
||||
// user's turns to it. The conversations list route filters on user_id for
|
||||
// exactly this reason; the same rule applies to the turn itself.
|
||||
//
|
||||
// The company check matters too: a user who belongs to several companies
|
||||
// must not resume a thread from company B while the turn runs with company
|
||||
// A's ledger, tools and staged operations.
|
||||
const { data: conv } = await supabase
|
||||
.from('agent_conversations')
|
||||
.select('id, user_id, company_id, intent_id')
|
||||
.eq('id', conversationId)
|
||||
.maybeSingle()
|
||||
|
||||
if (!conv || conv.user_id !== user.id || conv.company_id !== companyId) {
|
||||
// Same response for "doesn't exist" and "isn't yours": a 403 here would
|
||||
// confirm that someone else's conversation id is real.
|
||||
return NextResponse.json({ error: 'Konversationen hittades inte.' }, { status: 404 })
|
||||
}
|
||||
|
||||
// The intent decides the tool loadout and the system prompt. Letting a
|
||||
// resumed thread switch intent mid-conversation would swap the tool
|
||||
// whitelist under history the model has already been shown.
|
||||
if (conv.intent_id !== body.intent_id) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Konversationen hör till ett annat sammanhang.' },
|
||||
{ status: 400 },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// onboarding.intake completion signal: once the user has actually
|
||||
// engaged (typed a real reply, not the auto-fired greeting prompt that
|
||||
// mounts the chat), stamp intake_completed_at on the profile so re-entry
|
||||
// logic and opportunistic follow-up logic in other intents can tell the
|
||||
// intake happened. Idempotent: the IS NULL guard ensures we never
|
||||
// overwrite the first engagement timestamp. Best-effort: failure here
|
||||
// doesn't break the chat; the next user turn retries.
|
||||
if (
|
||||
body.intent_id === 'onboarding.intake' &&
|
||||
typeof body.user_message === 'string' &&
|
||||
body.user_message.trim().length > 0 &&
|
||||
body.user_message_hidden !== true
|
||||
) {
|
||||
try {
|
||||
await supabase
|
||||
.from('agent_profiles')
|
||||
.update({ intake_completed_at: new Date().toISOString() })
|
||||
.eq('company_id', companyId)
|
||||
.is('intake_completed_at', null)
|
||||
} catch {
|
||||
// ignored: see comment above
|
||||
}
|
||||
}
|
||||
|
||||
// Load lightweight company + user signals for the system prompt.
|
||||
const [{ data: company }, { data: profile }] = await Promise.all([
|
||||
supabase.from('companies').select('name').eq('id', companyId).single(),
|
||||
supabase.from('profiles').select('full_name').eq('id', user.id).single(),
|
||||
])
|
||||
const companyName = company?.name ?? ''
|
||||
const firstName = profile?.full_name?.split(' ')[0] ?? null
|
||||
|
||||
// Create the conversation row when this is a fresh thread.
|
||||
if (!conversationId) {
|
||||
const { data: newConv, error: convErr } = await supabase
|
||||
.from('agent_conversations')
|
||||
.insert({
|
||||
company_id: companyId,
|
||||
user_id: user.id,
|
||||
intent_id: body.intent_id,
|
||||
context_ref: body.context_ref ?? null,
|
||||
title: intent.sheetTitle,
|
||||
})
|
||||
.select('id')
|
||||
.single()
|
||||
if (convErr || !newConv) {
|
||||
return NextResponse.json(
|
||||
{ error: getUserErrorMessage(convErr) ?? 'Failed to create conversation' },
|
||||
{ status: 500 },
|
||||
)
|
||||
}
|
||||
conversationId = newConv.id as string
|
||||
}
|
||||
|
||||
// Compute the user message to send to Anthropic. On the first turn (no
|
||||
// user_message provided), we run the intent's capture + promptTemplate
|
||||
// pipeline so the prompt is anchored on the page context the user
|
||||
// clicked from.
|
||||
let effectiveUserMessage = body.user_message ?? ''
|
||||
// When the caller didn't supply a user_message, we synthesize one from the
|
||||
// intent's promptTemplate. Mark that synthetic turn hidden so the UI
|
||||
// doesn't render the template scaffolding as a user bubble on resume. The
|
||||
// client can also explicitly request a hidden turn (rejection correction)
|
||||
// even when it DID supply a user_message.
|
||||
let userMessageHidden = body.user_message_hidden === true
|
||||
// Set on a first turn, where the prompt template needs it anyway; handed to
|
||||
// runChatTurn so the system prompt reuses it instead of re-reading.
|
||||
let preloadedProfileSummary: string | null | undefined
|
||||
if (!effectiveUserMessage) {
|
||||
try {
|
||||
const captured = await intent.capture(body.intent_args ?? {}, {
|
||||
supabase,
|
||||
userId: user.id,
|
||||
companyId,
|
||||
})
|
||||
const [profileSummary, memory] = await Promise.all([
|
||||
loadProfileSummary(supabase, companyId),
|
||||
loadRankedMemory(supabase, companyId, 30),
|
||||
])
|
||||
effectiveUserMessage = intent.promptTemplate({
|
||||
captured,
|
||||
profileSummary,
|
||||
activeMemory: memory,
|
||||
})
|
||||
// Hand it to the turn so it doesn't re-read it for the system prompt.
|
||||
preloadedProfileSummary = profileSummary
|
||||
userMessageHidden = true
|
||||
} catch (err) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error:
|
||||
err instanceof Error
|
||||
? `Capture failed: ${getUserErrorMessage(err)}`
|
||||
: 'Capture failed',
|
||||
},
|
||||
{ status: 500 },
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// Stream: NDJSON events from the chat loop.
|
||||
const encoder = new TextEncoder()
|
||||
// Conversation id is set above; capture into a non-null local for the
|
||||
// streaming closure's first emission.
|
||||
const convId: string = conversationId
|
||||
|
||||
const stream = new ReadableStream<Uint8Array>({
|
||||
async start(controller) {
|
||||
const emit = (event: unknown): boolean => {
|
||||
try {
|
||||
controller.enqueue(encoder.encode(JSON.stringify(event) + '\n'))
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// Surface the conversation id so the client can resume with it.
|
||||
emit({ kind: 'conversation', conversation_id: convId })
|
||||
|
||||
try {
|
||||
await runChatTurn({
|
||||
supabase,
|
||||
userId: user.id,
|
||||
companyId,
|
||||
companyName,
|
||||
firstName,
|
||||
intent,
|
||||
conversationId: convId,
|
||||
userMessage: effectiveUserMessage,
|
||||
userMessageHidden,
|
||||
persist: true,
|
||||
preloadedProfileSummary,
|
||||
emit: (event) => emit(event),
|
||||
})
|
||||
} catch (err) {
|
||||
// run-turn already emitted a friendly error before re-throwing; emit a
|
||||
// normalized one here too so this outer catch never overwrites it with a
|
||||
// raw AWS SDK string.
|
||||
emit({
|
||||
kind: 'error',
|
||||
message: friendlyModelError(err),
|
||||
})
|
||||
} finally {
|
||||
try {
|
||||
controller.close()
|
||||
} catch {
|
||||
// Already closed
|
||||
}
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
return new Response(stream, {
|
||||
headers: {
|
||||
'Content-Type': 'application/x-ndjson; charset=utf-8',
|
||||
'Cache-Control': 'no-store',
|
||||
'X-Accel-Buffering': 'no',
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
async function loadProfileSummary(
|
||||
supabase: Awaited<ReturnType<typeof createClient>>,
|
||||
companyId: string,
|
||||
): Promise<string | null> {
|
||||
const { data } = await supabase
|
||||
.from('agent_profiles')
|
||||
.select('profile_summary')
|
||||
.eq('company_id', companyId)
|
||||
.maybeSingle()
|
||||
return (data?.profile_summary as string | null) ?? null
|
||||
}
|
||||
|
||||
async function loadRankedMemory(
|
||||
supabase: Awaited<ReturnType<typeof createClient>>,
|
||||
companyId: string,
|
||||
cap: number,
|
||||
): Promise<{ content: string; kind: string }[]> {
|
||||
const { data } = await supabase
|
||||
.from('agent_memory')
|
||||
.select('content, kind, relevance_score, last_accessed_at')
|
||||
.eq('company_id', companyId)
|
||||
.eq('is_active', true)
|
||||
.order('relevance_score', { ascending: false })
|
||||
.order('last_accessed_at', { ascending: false, nullsFirst: false })
|
||||
.limit(cap)
|
||||
return (data ?? []).map((r: { content: string; kind: string }) => ({
|
||||
content: r.content,
|
||||
kind: r.kind,
|
||||
}))
|
||||
}
|
||||
@@ -1,88 +0,0 @@
|
||||
/**
|
||||
* Tests for GET /api/agent/knowledge (the "Vad din agent vet" data source for
|
||||
* the Kunskap tab in the assistant settings hub). Exercises the route through
|
||||
* the real withRouteContext wrapper, mocking auth/company and the three
|
||||
* ledger-context builders. Covers auth 401, no-company 400, and the happy path
|
||||
* aggregation shape.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { createQueuedMockSupabase, createMockRequest, parseJsonResponse } from '@/tests/helpers'
|
||||
|
||||
const { supabase } = createQueuedMockSupabase()
|
||||
|
||||
const requireAuthMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-auth', () => ({
|
||||
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
|
||||
}))
|
||||
|
||||
const getActiveCompanyIdMock = vi.fn()
|
||||
const getCompanyDisplayNameMock = vi.fn()
|
||||
vi.mock('@/lib/company/context', () => ({
|
||||
getActiveCompanyId: (...args: unknown[]) => getActiveCompanyIdMock(...args),
|
||||
getCompanyDisplayName: (...args: unknown[]) => getCompanyDisplayNameMock(...args),
|
||||
}))
|
||||
|
||||
const buildLedgerContextMock = vi.fn()
|
||||
vi.mock('@/lib/agent-context/ledger-context', () => ({
|
||||
buildLedgerContext: (...args: unknown[]) => buildLedgerContextMock(...args),
|
||||
}))
|
||||
|
||||
const buildDeepEntitiesMock = vi.fn()
|
||||
vi.mock('@/lib/agent-context/ledger-deep', () => ({
|
||||
buildDeepEntities: (...args: unknown[]) => buildDeepEntitiesMock(...args),
|
||||
}))
|
||||
|
||||
const buildAgentCompetenceMock = vi.fn()
|
||||
vi.mock('@/lib/agent-context/agent-competence', () => ({
|
||||
buildAgentCompetence: (...args: unknown[]) => buildAgentCompetenceMock(...args),
|
||||
}))
|
||||
|
||||
import { GET } from '../route'
|
||||
|
||||
describe('GET /api/agent/knowledge', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
|
||||
getActiveCompanyIdMock.mockResolvedValue('company-1')
|
||||
getCompanyDisplayNameMock.mockResolvedValue('Acme AB')
|
||||
buildLedgerContextMock.mockResolvedValue({ meta: { coverage: {} }, explicit_rules: [], vat_profile: {}, conventions: {} })
|
||||
buildDeepEntitiesMock.mockResolvedValue({ counterparty_entities: [], supplier_entities: [] })
|
||||
buildAgentCompetenceMock.mockResolvedValue({ atoms: [], facts: [] })
|
||||
})
|
||||
|
||||
it('returns 401 when not authenticated', async () => {
|
||||
requireAuthMock.mockResolvedValue({
|
||||
user: null,
|
||||
supabase,
|
||||
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
|
||||
})
|
||||
const res = await GET(createMockRequest('/api/agent/knowledge'), { params: Promise.resolve({}) })
|
||||
const { status } = await parseJsonResponse(res)
|
||||
expect(status).toBe(401)
|
||||
})
|
||||
|
||||
it('returns 400 when there is no active company', async () => {
|
||||
getActiveCompanyIdMock.mockResolvedValue(null)
|
||||
const res = await GET(createMockRequest('/api/agent/knowledge'), { params: Promise.resolve({}) })
|
||||
const { status } = await parseJsonResponse(res)
|
||||
expect(status).toBe(400)
|
||||
})
|
||||
|
||||
it('aggregates the ledger context, deep entities, competence and company name', async () => {
|
||||
const res = await GET(createMockRequest('/api/agent/knowledge'), { params: Promise.resolve({}) })
|
||||
const { status, body } = await parseJsonResponse<{
|
||||
data: { context: unknown; deep: unknown; competence: unknown; companyName: string }
|
||||
}>(res)
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.companyName).toBe('Acme AB')
|
||||
expect(body.data.context).toEqual({ meta: { coverage: {} }, explicit_rules: [], vat_profile: {}, conventions: {} })
|
||||
expect(body.data.deep).toEqual({ counterparty_entities: [], supplier_entities: [] })
|
||||
expect(body.data.competence).toEqual({ atoms: [], facts: [] })
|
||||
// each builder was called with the resolved supabase + companyId
|
||||
expect(buildLedgerContextMock).toHaveBeenCalledWith(supabase, 'company-1')
|
||||
expect(buildDeepEntitiesMock).toHaveBeenCalledWith(supabase, 'company-1')
|
||||
expect(buildAgentCompetenceMock).toHaveBeenCalledWith(supabase, 'company-1')
|
||||
})
|
||||
})
|
||||
@@ -1,30 +0,0 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { getCompanyDisplayName } from '@/lib/company/context'
|
||||
import { buildLedgerContext } from '@/lib/agent-context/ledger-context'
|
||||
import { buildDeepEntities } from '@/lib/agent-context/ledger-deep'
|
||||
import { buildAgentCompetence } from '@/lib/agent-context/agent-competence'
|
||||
|
||||
// GET /api/agent/knowledge
|
||||
//
|
||||
// Read-only transparency surface for "Vad din agent vet": the exact ledger
|
||||
// context the AI agent reads before booking, plus the deep entity-resolved
|
||||
// profile and the agent's competence. Powers the Kunskap tab in the assistant
|
||||
// settings hub (client-fetched so it renders identically in the full-page
|
||||
// settings rail and the routed settings modal, which both mount the same
|
||||
// propless content component). Derived per request from live bookings; never
|
||||
// cached, so a fixed profile can't go stale.
|
||||
export const GET = withRouteContext('agent.knowledge.get', async (_request, ctx) => {
|
||||
const { supabase, companyId } = ctx
|
||||
|
||||
const [context, deep, competence, companyName] = await Promise.all([
|
||||
buildLedgerContext(supabase, companyId),
|
||||
buildDeepEntities(supabase, companyId),
|
||||
buildAgentCompetence(supabase, companyId),
|
||||
getCompanyDisplayName(supabase, companyId),
|
||||
])
|
||||
|
||||
return NextResponse.json({
|
||||
data: { context, deep, competence, companyName: companyName ?? '' },
|
||||
})
|
||||
})
|
||||
@@ -1,94 +0,0 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { z } from 'zod'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { validateBody } from '@/lib/api/validate'
|
||||
|
||||
// PATCH /api/agent/memory/[id]
|
||||
//
|
||||
// Mutate a single memory entry. Powers the list/edit/pin/dismiss affordances
|
||||
// on /settings/agent-memory (plan §11).
|
||||
//
|
||||
// content: edit the durable text (kind never changes; that would
|
||||
// muddle the audit lineage). Append-only is preserved by
|
||||
// superseded_by chains when an upstream caller wants it; the
|
||||
// transparency UI is allowed to overwrite in place because
|
||||
// the row's `updated_at` already documents the edit.
|
||||
// is_pinned: boost into the top-N prompt block regardless of score.
|
||||
// is_active: false = dismiss (removes from ranking pool); true = restore.
|
||||
//
|
||||
// RLS scopes to user_company_ids(); we ALSO re-verify membership for the
|
||||
// row's company_id as defense in depth before mutating.
|
||||
|
||||
const PatchSchema = z
|
||||
.object({
|
||||
content: z.string().min(2).max(2000).optional(),
|
||||
is_pinned: z.boolean().optional(),
|
||||
is_active: z.boolean().optional(),
|
||||
})
|
||||
.refine(
|
||||
(v) => v.content !== undefined || v.is_pinned !== undefined || v.is_active !== undefined,
|
||||
{ message: 'Nothing to update' },
|
||||
)
|
||||
|
||||
const notFound = () =>
|
||||
NextResponse.json(
|
||||
{
|
||||
error: {
|
||||
code: 'MEMORY_NOT_FOUND',
|
||||
message: 'Minnet hittades inte.',
|
||||
message_en: 'Memory not found.',
|
||||
},
|
||||
},
|
||||
{ status: 404 },
|
||||
)
|
||||
|
||||
export const PATCH = withRouteContext(
|
||||
'agent.memory.update',
|
||||
async (request, ctx, { params }: { params: Promise<{ id: string }> }) => {
|
||||
const { id } = await params
|
||||
const { supabase, user, log } = ctx
|
||||
|
||||
const validation = await validateBody(request, PatchSchema, {
|
||||
log,
|
||||
operation: 'agent.memory.update',
|
||||
})
|
||||
if (!validation.success) return validation.response
|
||||
const body = validation.data
|
||||
|
||||
const update: Record<string, unknown> = {}
|
||||
if (body.content !== undefined) update.content = body.content
|
||||
if (body.is_pinned !== undefined) update.is_pinned = body.is_pinned
|
||||
if (body.is_active !== undefined) update.is_active = body.is_active
|
||||
|
||||
// Look up the row's company_id and re-check membership before mutating.
|
||||
const { data: existing } = await supabase
|
||||
.from('agent_memory')
|
||||
.select('company_id')
|
||||
.eq('id', id)
|
||||
.maybeSingle()
|
||||
if (!existing) return notFound()
|
||||
|
||||
const { data: membership } = await supabase
|
||||
.from('company_members')
|
||||
.select('role')
|
||||
.eq('company_id', existing.company_id)
|
||||
.eq('user_id', user.id)
|
||||
.maybeSingle()
|
||||
if (!membership) return notFound()
|
||||
|
||||
const { data, error } = await supabase
|
||||
.from('agent_memory')
|
||||
.update(update)
|
||||
.eq('id', id)
|
||||
.eq('company_id', existing.company_id)
|
||||
.select(
|
||||
'id, kind, content, source, source_ref, relevance_score, is_pinned, is_active, last_accessed_at, created_at, updated_at',
|
||||
)
|
||||
.maybeSingle()
|
||||
if (error) throw error
|
||||
if (!data) return notFound()
|
||||
|
||||
return NextResponse.json({ data })
|
||||
},
|
||||
{ requireWrite: true },
|
||||
)
|
||||
@@ -1,300 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import {
|
||||
createMockRequest,
|
||||
createMockRouteParams,
|
||||
parseJsonResponse,
|
||||
createQueuedMockSupabase,
|
||||
} from '@/tests/helpers'
|
||||
|
||||
const { supabase: mockSupabase, enqueue, reset } = createQueuedMockSupabase()
|
||||
vi.mock('@/lib/supabase/server', () => ({
|
||||
createClient: () => Promise.resolve(mockSupabase),
|
||||
}))
|
||||
|
||||
const getActiveCompanyIdMock = vi.fn()
|
||||
vi.mock('@/lib/company/context', () => ({
|
||||
getActiveCompanyId: (...args: unknown[]) => getActiveCompanyIdMock(...args),
|
||||
}))
|
||||
|
||||
const requireWritePermissionMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-write', () => ({
|
||||
requireWritePermission: (...args: unknown[]) => requireWritePermissionMock(...args),
|
||||
}))
|
||||
|
||||
import { GET, POST } from '../route'
|
||||
import { PATCH } from '../[id]/route'
|
||||
|
||||
const mockUser = { id: 'user-1', email: '[email protected]' }
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
reset()
|
||||
mockSupabase.auth.getUser.mockResolvedValue({ data: { user: mockUser } })
|
||||
getActiveCompanyIdMock.mockResolvedValue('company-1')
|
||||
requireWritePermissionMock.mockResolvedValue({ ok: true })
|
||||
})
|
||||
|
||||
describe('GET /api/agent/memory', () => {
|
||||
it('returns 401 when not authenticated', async () => {
|
||||
mockSupabase.auth.getUser.mockResolvedValue({ data: { user: null } })
|
||||
const response = await GET(createMockRequest('/api/agent/memory'), createMockRouteParams({}))
|
||||
const { status, body } = await parseJsonResponse<{ error: string }>(response)
|
||||
expect(status).toBe(401)
|
||||
expect(body.error).toBe('Unauthorized')
|
||||
})
|
||||
|
||||
it('returns 400 when no active company', async () => {
|
||||
getActiveCompanyIdMock.mockResolvedValue(null)
|
||||
const response = await GET(createMockRequest('/api/agent/memory'), createMockRouteParams({}))
|
||||
const { status } = await parseJsonResponse(response)
|
||||
expect(status).toBe(400)
|
||||
})
|
||||
|
||||
it('returns rows for the active company', async () => {
|
||||
const rows = [
|
||||
{
|
||||
id: 'mem-1',
|
||||
kind: 'fact',
|
||||
content: 'Räkenskapsår jan-dec',
|
||||
source: 'composer',
|
||||
source_ref: null,
|
||||
relevance_score: 0.5,
|
||||
is_pinned: false,
|
||||
is_active: true,
|
||||
last_accessed_at: null,
|
||||
created_at: '2026-05-10T09:00:00Z',
|
||||
updated_at: '2026-05-10T09:00:00Z',
|
||||
},
|
||||
]
|
||||
enqueue({ data: rows })
|
||||
const response = await GET(createMockRequest('/api/agent/memory'), createMockRouteParams({}))
|
||||
const { status, body } = await parseJsonResponse<{ data: typeof rows }>(response)
|
||||
expect(status).toBe(200)
|
||||
expect(body.data).toHaveLength(1)
|
||||
expect(body.data[0].id).toBe('mem-1')
|
||||
})
|
||||
|
||||
it('does not require write permission for read', async () => {
|
||||
enqueue({ data: [] })
|
||||
await GET(createMockRequest('/api/agent/memory'), createMockRouteParams({}))
|
||||
expect(requireWritePermissionMock).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('POST /api/agent/memory', () => {
|
||||
it('returns 401 when not authenticated', async () => {
|
||||
mockSupabase.auth.getUser.mockResolvedValue({ data: { user: null } })
|
||||
const response = await POST(
|
||||
createMockRequest('/api/agent/memory', {
|
||||
method: 'POST',
|
||||
body: { content: 'hello world' },
|
||||
}),
|
||||
createMockRouteParams({}),
|
||||
)
|
||||
expect(response.status).toBe(401)
|
||||
})
|
||||
|
||||
it('blocks viewers via requireWritePermission', async () => {
|
||||
const { NextResponse } = await import('next/server')
|
||||
requireWritePermissionMock.mockResolvedValue({
|
||||
ok: false,
|
||||
response: NextResponse.json({ error: 'forbidden' }, { status: 403 }),
|
||||
})
|
||||
const response = await POST(
|
||||
createMockRequest('/api/agent/memory', {
|
||||
method: 'POST',
|
||||
body: { content: 'hello world' },
|
||||
}),
|
||||
createMockRouteParams({}),
|
||||
)
|
||||
expect(response.status).toBe(403)
|
||||
})
|
||||
|
||||
it('rejects too-short content', async () => {
|
||||
const response = await POST(
|
||||
createMockRequest('/api/agent/memory', {
|
||||
method: 'POST',
|
||||
body: { content: 'x' },
|
||||
}),
|
||||
createMockRouteParams({}),
|
||||
)
|
||||
expect(response.status).toBe(400)
|
||||
})
|
||||
|
||||
it('inserts and returns the row on happy path', async () => {
|
||||
const inserted = {
|
||||
id: 'mem-2',
|
||||
kind: 'fact',
|
||||
content: 'En sak att komma ihåg',
|
||||
source: 'user_taught',
|
||||
source_ref: null,
|
||||
relevance_score: 1,
|
||||
is_pinned: false,
|
||||
is_active: true,
|
||||
last_accessed_at: null,
|
||||
created_at: '2026-05-18T10:00:00Z',
|
||||
updated_at: '2026-05-18T10:00:00Z',
|
||||
}
|
||||
// Defense-in-depth: body company_id membership re-check happens after
|
||||
// requireWritePermission. POST flow now is: (1) company_members lookup,
|
||||
// (2) insert.
|
||||
enqueue({ data: { role: 'member' } })
|
||||
enqueue({ data: inserted })
|
||||
const response = await POST(
|
||||
createMockRequest('/api/agent/memory', {
|
||||
method: 'POST',
|
||||
body: { content: 'En sak att komma ihåg' },
|
||||
}),
|
||||
createMockRouteParams({}),
|
||||
)
|
||||
const { status, body } = await parseJsonResponse<{ data: typeof inserted }>(response)
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.id).toBe('mem-2')
|
||||
})
|
||||
|
||||
it('rejects when user is a viewer in the target company', async () => {
|
||||
enqueue({ data: { role: 'viewer' } })
|
||||
const response = await POST(
|
||||
createMockRequest('/api/agent/memory', {
|
||||
method: 'POST',
|
||||
body: { content: 'En sak att komma ihåg' },
|
||||
}),
|
||||
createMockRouteParams({}),
|
||||
)
|
||||
expect(response.status).toBe(403)
|
||||
})
|
||||
})
|
||||
|
||||
describe('PATCH /api/agent/memory/[id]', () => {
|
||||
it('returns 401 when not authenticated', async () => {
|
||||
mockSupabase.auth.getUser.mockResolvedValue({ data: { user: null } })
|
||||
const response = await PATCH(
|
||||
createMockRequest('/api/agent/memory/mem-1', {
|
||||
method: 'PATCH',
|
||||
body: { is_pinned: true },
|
||||
}),
|
||||
createMockRouteParams({ id: 'mem-1' }),
|
||||
)
|
||||
expect(response.status).toBe(401)
|
||||
})
|
||||
|
||||
it('blocks viewers via requireWritePermission', async () => {
|
||||
const { NextResponse } = await import('next/server')
|
||||
requireWritePermissionMock.mockResolvedValue({
|
||||
ok: false,
|
||||
response: NextResponse.json({ error: 'forbidden' }, { status: 403 }),
|
||||
})
|
||||
const response = await PATCH(
|
||||
createMockRequest('/api/agent/memory/mem-1', {
|
||||
method: 'PATCH',
|
||||
body: { is_pinned: true },
|
||||
}),
|
||||
createMockRouteParams({ id: 'mem-1' }),
|
||||
)
|
||||
expect(response.status).toBe(403)
|
||||
})
|
||||
|
||||
it('rejects empty patch body', async () => {
|
||||
const response = await PATCH(
|
||||
createMockRequest('/api/agent/memory/mem-1', { method: 'PATCH', body: {} }),
|
||||
createMockRouteParams({ id: 'mem-1' }),
|
||||
)
|
||||
expect(response.status).toBe(400)
|
||||
})
|
||||
|
||||
it('returns 404 when row not found / not visible via RLS', async () => {
|
||||
// Row lookup returns null → defense-in-depth 404 before update.
|
||||
enqueue({ data: null })
|
||||
const response = await PATCH(
|
||||
createMockRequest('/api/agent/memory/mem-x', {
|
||||
method: 'PATCH',
|
||||
body: { is_pinned: true },
|
||||
}),
|
||||
createMockRouteParams({ id: 'mem-x' }),
|
||||
)
|
||||
expect(response.status).toBe(404)
|
||||
})
|
||||
|
||||
it('returns 404 when user has no membership in row company', async () => {
|
||||
enqueue({ data: { company_id: 'company-2' } })
|
||||
enqueue({ data: null }) // company_members lookup
|
||||
const response = await PATCH(
|
||||
createMockRequest('/api/agent/memory/mem-1', {
|
||||
method: 'PATCH',
|
||||
body: { is_pinned: true },
|
||||
}),
|
||||
createMockRouteParams({ id: 'mem-1' }),
|
||||
)
|
||||
expect(response.status).toBe(404)
|
||||
})
|
||||
|
||||
it('pins a row', async () => {
|
||||
const updated = {
|
||||
id: 'mem-1',
|
||||
kind: 'fact',
|
||||
content: 'X',
|
||||
source: 'composer',
|
||||
source_ref: null,
|
||||
relevance_score: 0.5,
|
||||
is_pinned: true,
|
||||
is_active: true,
|
||||
last_accessed_at: null,
|
||||
created_at: '2026-05-10T09:00:00Z',
|
||||
updated_at: '2026-05-18T10:00:00Z',
|
||||
}
|
||||
// PATCH flow: (1) row lookup, (2) membership lookup, (3) update.
|
||||
enqueue({ data: { company_id: 'company-1' } })
|
||||
enqueue({ data: { role: 'member' } })
|
||||
enqueue({ data: updated })
|
||||
const response = await PATCH(
|
||||
createMockRequest('/api/agent/memory/mem-1', {
|
||||
method: 'PATCH',
|
||||
body: { is_pinned: true },
|
||||
}),
|
||||
createMockRouteParams({ id: 'mem-1' }),
|
||||
)
|
||||
const { status, body } = await parseJsonResponse<{ data: typeof updated }>(response)
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.is_pinned).toBe(true)
|
||||
})
|
||||
|
||||
it('dismisses a row by setting is_active=false', async () => {
|
||||
const updated = {
|
||||
id: 'mem-1',
|
||||
kind: 'fact',
|
||||
content: 'X',
|
||||
source: 'composer',
|
||||
source_ref: null,
|
||||
relevance_score: 0.5,
|
||||
is_pinned: false,
|
||||
is_active: false,
|
||||
last_accessed_at: null,
|
||||
created_at: '2026-05-10T09:00:00Z',
|
||||
updated_at: '2026-05-18T10:00:00Z',
|
||||
}
|
||||
enqueue({ data: { company_id: 'company-1' } })
|
||||
enqueue({ data: { role: 'member' } })
|
||||
enqueue({ data: updated })
|
||||
const response = await PATCH(
|
||||
createMockRequest('/api/agent/memory/mem-1', {
|
||||
method: 'PATCH',
|
||||
body: { is_active: false },
|
||||
}),
|
||||
createMockRouteParams({ id: 'mem-1' }),
|
||||
)
|
||||
const { status, body } = await parseJsonResponse<{ data: typeof updated }>(response)
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.is_active).toBe(false)
|
||||
})
|
||||
|
||||
it('rejects content shorter than 2 chars', async () => {
|
||||
const response = await PATCH(
|
||||
createMockRequest('/api/agent/memory/mem-1', {
|
||||
method: 'PATCH',
|
||||
body: { content: 'x' },
|
||||
}),
|
||||
createMockRouteParams({ id: 'mem-1' }),
|
||||
)
|
||||
expect(response.status).toBe(400)
|
||||
})
|
||||
})
|
||||
@@ -1,135 +0,0 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { z } from 'zod'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { validateBody, validateQuery } from '@/lib/api/validate'
|
||||
|
||||
// GET /api/agent/memory
|
||||
//
|
||||
// Lists memory entries for the active company, ordered by pin > relevance >
|
||||
// recency. Powers /settings/agent-memory (transparency UI per plan §11).
|
||||
//
|
||||
// Query params:
|
||||
// include_dismissed: 'true' includes is_active=false rows (audit view).
|
||||
// kind: filter by kind.
|
||||
// limit: 1..200, default 200 (matches the storage cap).
|
||||
//
|
||||
// POST /api/agent/memory
|
||||
//
|
||||
// Inserts a memory entry for the company. Used by Phase B's free-text seed
|
||||
// memory field ("Lägg till om ditt företag (valfritt)") to capture
|
||||
// foundational facts as `kind=fact`, `source=user_taught` with an elevated
|
||||
// relevance score so they land in the top-30 prompt block.
|
||||
//
|
||||
// Also usable from /settings/agent-memory ("Lägg till minne" affordance) and
|
||||
// post-Phase 4 explicit "Kom ihåg det här" surfaces.
|
||||
|
||||
const KIND = ['fact', 'preference', 'pattern', 'correction'] as const
|
||||
const SOURCE = ['composer', 'user_taught', 'agent_learned', 'derived'] as const
|
||||
|
||||
const MEMORY_COLUMNS =
|
||||
'id, kind, content, source, source_ref, relevance_score, is_pinned, is_active, last_accessed_at, created_at, updated_at'
|
||||
|
||||
const ListQuerySchema = z.object({
|
||||
include_dismissed: z.enum(['true', 'false']).optional(),
|
||||
kind: z.enum(KIND).optional(),
|
||||
limit: z.coerce.number().int().min(1).max(200).default(200),
|
||||
})
|
||||
|
||||
const BodySchema = z.object({
|
||||
company_id: z.string().uuid().optional(),
|
||||
content: z.string().min(2).max(2000),
|
||||
kind: z.enum(KIND).default('fact'),
|
||||
source: z.enum(SOURCE).default('user_taught'),
|
||||
source_ref: z.string().max(200).optional(),
|
||||
// Default 1.0 keeps user-taught entries above composer-derived (0.5) by
|
||||
// default; conversation-time captures can land anywhere in [0, 1].
|
||||
relevance_score: z.number().min(0).max(1).default(1.0),
|
||||
})
|
||||
|
||||
export const GET = withRouteContext('agent.memory.list', async (request, ctx) => {
|
||||
const { supabase, companyId, log } = ctx
|
||||
|
||||
const validated = validateQuery(request, ListQuerySchema, {
|
||||
log,
|
||||
operation: 'agent.memory.list',
|
||||
})
|
||||
if (!validated.success) return validated.response
|
||||
const { include_dismissed, kind, limit } = validated.data
|
||||
|
||||
let query = supabase
|
||||
.from('agent_memory')
|
||||
.select(MEMORY_COLUMNS)
|
||||
.eq('company_id', companyId)
|
||||
|
||||
if (include_dismissed !== 'true') query = query.eq('is_active', true)
|
||||
if (kind) query = query.eq('kind', kind)
|
||||
|
||||
query = query
|
||||
.order('is_active', { ascending: false })
|
||||
.order('is_pinned', { ascending: false })
|
||||
.order('relevance_score', { ascending: false })
|
||||
.order('last_accessed_at', { ascending: false, nullsFirst: false })
|
||||
.order('created_at', { ascending: false })
|
||||
.limit(limit)
|
||||
|
||||
const { data, error } = await query
|
||||
if (error) throw error
|
||||
return NextResponse.json({ data: data ?? [] })
|
||||
})
|
||||
|
||||
export const POST = withRouteContext(
|
||||
'agent.memory.create',
|
||||
async (request, ctx) => {
|
||||
const { supabase, companyId: activeCompanyId, user, log } = ctx
|
||||
|
||||
const validation = await validateBody(request, BodySchema, {
|
||||
log,
|
||||
operation: 'agent.memory.create',
|
||||
})
|
||||
if (!validation.success) return validation.response
|
||||
const body = validation.data
|
||||
|
||||
const companyId = body.company_id ?? activeCompanyId
|
||||
|
||||
// requireWrite (wrapper option) checks the *active* company's role; if
|
||||
// the caller passes a different company_id in the body, re-check
|
||||
// membership + non-viewer role for THAT company specifically.
|
||||
const { data: bodyMembership } = await supabase
|
||||
.from('company_members')
|
||||
.select('role')
|
||||
.eq('company_id', companyId)
|
||||
.eq('user_id', user.id)
|
||||
.maybeSingle()
|
||||
if (!bodyMembership || bodyMembership.role === 'viewer') {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: {
|
||||
code: 'WRITE_PERMISSION_REQUIRED',
|
||||
message: 'Du har endast läsbehörighet i detta företag.',
|
||||
message_en: 'You only have read access in this company.',
|
||||
},
|
||||
},
|
||||
{ status: 403 },
|
||||
)
|
||||
}
|
||||
|
||||
const { data, error } = await supabase
|
||||
.from('agent_memory')
|
||||
.insert({
|
||||
company_id: companyId,
|
||||
kind: body.kind,
|
||||
content: body.content,
|
||||
source: body.source,
|
||||
source_ref: body.source_ref ?? null,
|
||||
relevance_score: body.relevance_score,
|
||||
is_active: true,
|
||||
created_by_user_id: user.id,
|
||||
})
|
||||
.select(MEMORY_COLUMNS)
|
||||
.single()
|
||||
if (error) throw error
|
||||
|
||||
return NextResponse.json({ data })
|
||||
},
|
||||
{ requireWrite: true },
|
||||
)
|
||||
@@ -1,297 +0,0 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { z } from 'zod'
|
||||
import { requireAuth } from '@/lib/auth/require-auth'
|
||||
import { getActiveCompanyId } from '@/lib/company/context'
|
||||
import { guardSandbox } from '@/lib/sandbox/guard'
|
||||
import { requireCapability } from '@/lib/entitlements/has-capability'
|
||||
import { CAPABILITY } from '@/lib/entitlements/keys'
|
||||
import { checkAgentRateLimit, agentRateLimitResponseBody } from '@/lib/rate-limits/agent'
|
||||
import { gatherComposerInputs, inputsToSourceSignals } from '@/lib/agent/composer/inputs'
|
||||
import { selectAtoms } from '@/lib/agent/composer/atom-selection'
|
||||
import { writeNarrative } from '@/lib/agent/composer/narrative'
|
||||
import { fallbackAtomSelection, fallbackNarrative } from '@/lib/agent/composer/fallback'
|
||||
import { filterRedundantQuestions } from '@/lib/agent/composer/atom-selection'
|
||||
import { preWarmAtomCache } from '@/lib/agent/composer/prewarm'
|
||||
import { OPUS_MODEL } from '@/lib/agent/composer/client'
|
||||
import { ensureTicSnapshot } from '@/lib/agent/composer/tic-fetch'
|
||||
import type { AtomSelection } from '@/lib/agent/composer/schemas'
|
||||
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
|
||||
import { withTimeout } from '@/lib/utils'
|
||||
|
||||
const BodySchema = z.object({
|
||||
company_id: z.string().uuid().optional(),
|
||||
})
|
||||
|
||||
// 10s: the user is on a wait-screen with visible progress, so we can afford
|
||||
// the longer budget. The prior 5s clipped legitimate fetches (TIC fans out to
|
||||
// ~13 Lens calls upstream) into the fallback bucket while still burning the
|
||||
// in-flight upstream calls against quota. See actions.ts:182-189 for the
|
||||
// May 2026 incident context.
|
||||
const TIC_BUDGET_MS = 10_000
|
||||
// Bedrock cold-starts can take 2-3s before the first token, plus the actual
|
||||
// Opus selection call typically lands at 10-14s. 15s was too tight and put
|
||||
// real Opus calls into the fallback bucket on the first turn of the day.
|
||||
const SELECT_BUDGET_MS = 25_000
|
||||
const NARRATIVE_BUDGET_MS = 8_000
|
||||
|
||||
// Per-step event shape streamed as NDJSON. Each line is one JSON object.
|
||||
type Step = 'tic' | 'select' | 'narrative' | 'finalize' | 'prewarm'
|
||||
type Status = 'in_progress' | 'success' | 'fallback' | 'skipped' | 'error'
|
||||
type StreamEvent =
|
||||
| { step: Step; status: Status }
|
||||
| { step: 'select'; status: 'success' | 'fallback'; selection: AtomSelection }
|
||||
| { step: 'narrative'; status: 'success' | 'fallback'; narrative: string }
|
||||
| { step: 'finalize'; status: 'success'; profile: ProfilePayload }
|
||||
| { step: 'error'; status: 'error'; message: string }
|
||||
|
||||
interface ProfilePayload {
|
||||
company_id: string
|
||||
horizontal_atoms: string[]
|
||||
vertical_atoms: string[]
|
||||
modifier_atoms: string[]
|
||||
is_multi_vertical: boolean
|
||||
profile_summary: string
|
||||
verification_questions: string[]
|
||||
uncertainty_notes: string[]
|
||||
composer_model: string
|
||||
composed_at: string
|
||||
}
|
||||
|
||||
// POST /api/agent/onboarding/stream
|
||||
//
|
||||
// Streams real-timed progress for the agent build sequence (plan §7 Phase A).
|
||||
// Each step runs on its actual latency: no artificial delays. On timeout or
|
||||
// failure, the step emits `fallback` and the pipeline continues with a
|
||||
// deterministic default so the user always reaches Phase B.
|
||||
//
|
||||
// Response: application/x-ndjson, one JSON event per line.
|
||||
export async function POST(request: Request) {
|
||||
const { user, supabase, error } = await requireAuth()
|
||||
if (error) return error
|
||||
|
||||
// Generous per-user rate limit: bounds reload-spam of the onboarding build
|
||||
// (each run fires 2 LLM calls). Fails open on infra error.
|
||||
const rate = await checkAgentRateLimit(supabase, user.id)
|
||||
if (!rate.ok) {
|
||||
return NextResponse.json(agentRateLimitResponseBody(rate), {
|
||||
status: 429,
|
||||
headers: rate.retryAfterSec ? { 'Retry-After': String(rate.retryAfterSec) } : undefined,
|
||||
})
|
||||
}
|
||||
|
||||
let body: z.infer<typeof BodySchema>
|
||||
try {
|
||||
body = BodySchema.parse(await request.json().catch(() => ({})))
|
||||
} catch (err) {
|
||||
return NextResponse.json(
|
||||
{ error: err instanceof Error ? getUserErrorMessage(err) : 'Invalid body' },
|
||||
{ status: 400 },
|
||||
)
|
||||
}
|
||||
|
||||
const companyId = body.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('role')
|
||||
.eq('company_id', companyId)
|
||||
.eq('user_id', user.id)
|
||||
.maybeSingle()
|
||||
if (!membership) {
|
||||
return NextResponse.json({ error: 'Not a member of this company' }, { status: 403 })
|
||||
}
|
||||
// The pipeline upserts agent_profiles — a mutation, so viewers are refused
|
||||
// (same rule as /api/agent/profile and /verify).
|
||||
if (membership.role === 'viewer') {
|
||||
return NextResponse.json(
|
||||
{ error: 'Du har endast läsbehörighet i detta företag.' },
|
||||
{ status: 403 },
|
||||
)
|
||||
}
|
||||
|
||||
// No live composer run for sandbox companies: they ship with a pre-built
|
||||
// verified agent_profile so the chrome is visible without burning Bedrock.
|
||||
const blocked = await guardSandbox(supabase, companyId)
|
||||
if (blocked) return blocked
|
||||
|
||||
const capBlocked = await requireCapability(supabase, companyId, CAPABILITY.ai)
|
||||
if (capBlocked) return capBlocked
|
||||
|
||||
const stream = new ReadableStream<Uint8Array>({
|
||||
async start(controller) {
|
||||
const encoder = new TextEncoder()
|
||||
const send = (event: StreamEvent) => {
|
||||
try {
|
||||
controller.enqueue(encoder.encode(JSON.stringify(event) + '\n'))
|
||||
} catch {
|
||||
// Stream was cancelled (user navigated away). Subsequent enqueues
|
||||
// would throw: we just stop emitting.
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
// Step 1: TIC: read companies.tic_snapshot; if missing or stale,
|
||||
// live-fetch from the TIC extension (cookies forwarded from the
|
||||
// incoming request) and persist. Falls through gracefully when TIC is
|
||||
// disabled, the company has no org_number, or the request times out.
|
||||
send({ step: 'tic', status: 'in_progress' })
|
||||
const cookieHeader = request.headers.get('cookie') ?? ''
|
||||
// SSRF guard: derive origin from NEXT_PUBLIC_APP_URL (a required env
|
||||
// var per CLAUDE.md) instead of request.headers.host. On self-hosted
|
||||
// Docker the Host header can be attacker-controlled and would
|
||||
// otherwise let an attacker redirect the cookie-bearing TIC fetch to
|
||||
// a host they control.
|
||||
const appUrl = process.env.NEXT_PUBLIC_APP_URL?.replace(/\/+$/, '') ?? ''
|
||||
const fallbackHost = request.headers.get('host') ?? 'localhost:3000'
|
||||
const fallbackProto =
|
||||
request.headers.get('x-forwarded-proto') ??
|
||||
(fallbackHost.startsWith('localhost') ? 'http' : 'https')
|
||||
const origin = appUrl || `${fallbackProto}://${fallbackHost}`
|
||||
const ticResult = await withTimeout(
|
||||
// upgradeV1: agent build is the consumer of the v2-only sections;
|
||||
// bounded to companies actively creating an agent, so the TIC
|
||||
// budget stays safe even when upgrading pre-v2 snapshots.
|
||||
// timeoutMs: lift the internal fetch signal to match the outer
|
||||
// budget: otherwise the 5s default fires first and we get the
|
||||
// pre-fix behavior even with the longer outer budget.
|
||||
ensureTicSnapshot({
|
||||
supabase,
|
||||
companyId,
|
||||
cookieHeader,
|
||||
origin,
|
||||
upgradeV1: true,
|
||||
timeoutMs: TIC_BUDGET_MS,
|
||||
}),
|
||||
TIC_BUDGET_MS,
|
||||
).catch(() => ({ snapshot: null, source: 'fallback' as const }))
|
||||
send({
|
||||
step: 'tic',
|
||||
status: ticResult.snapshot ? 'success' : 'fallback',
|
||||
})
|
||||
|
||||
// Gather inputs once: used by select + narrative + persistence.
|
||||
const inputs = await gatherComposerInputs(supabase, companyId)
|
||||
|
||||
// Step 2: Opus atom selection with timeout + deterministic fallback.
|
||||
send({ step: 'select', status: 'in_progress' })
|
||||
let selection: AtomSelection
|
||||
try {
|
||||
selection = await withTimeout(selectAtoms(inputs), SELECT_BUDGET_MS)
|
||||
send({ step: 'select', status: 'success', selection })
|
||||
} catch {
|
||||
selection = fallbackAtomSelection(inputs)
|
||||
send({ step: 'select', status: 'fallback', selection })
|
||||
}
|
||||
|
||||
// Filter verification questions deterministically regardless of which
|
||||
// path produced the selection. fallbackAtomSelection generates a
|
||||
// generic template that doesn't know about KÄNDA FAKTA; the Opus
|
||||
// path is also re-filtered in case the model strayed. Cheap belt-
|
||||
// and-braces: same function used for both.
|
||||
selection.verification_questions = filterRedundantQuestions(
|
||||
selection.verification_questions,
|
||||
inputs,
|
||||
selection.modifier_atoms,
|
||||
)
|
||||
|
||||
// Step 3: Sonnet narrative with timeout + plain fallback.
|
||||
send({ step: 'narrative', status: 'in_progress' })
|
||||
let narrative: string
|
||||
try {
|
||||
narrative = await withTimeout(writeNarrative(inputs, selection), NARRATIVE_BUDGET_MS)
|
||||
send({ step: 'narrative', status: 'success', narrative })
|
||||
} catch {
|
||||
narrative = fallbackNarrative(inputs)
|
||||
send({ step: 'narrative', status: 'fallback', narrative })
|
||||
}
|
||||
|
||||
// Step 4: Persist the profile so Phase B has a row to edit.
|
||||
const composedAt = new Date().toISOString()
|
||||
const sourceSignals = inputsToSourceSignals(inputs)
|
||||
const { error: upsertErr } = await supabase
|
||||
.from('agent_profiles')
|
||||
.upsert(
|
||||
{
|
||||
company_id: companyId,
|
||||
horizontal_atoms: selection.horizontal_atoms,
|
||||
vertical_atoms: selection.vertical_atoms,
|
||||
modifier_atoms: selection.modifier_atoms,
|
||||
profile_summary: narrative,
|
||||
source_signals: sourceSignals,
|
||||
// Persist so the Phase C intake agent can read them server-
|
||||
// side when the chat opens. Plan §7 Phase C.
|
||||
verification_questions: selection.verification_questions,
|
||||
composed_at: composedAt,
|
||||
composer_model: OPUS_MODEL,
|
||||
composer_version: 1,
|
||||
},
|
||||
{ onConflict: 'company_id' },
|
||||
)
|
||||
if (upsertErr) {
|
||||
send({ step: 'error', status: 'error', message: getUserErrorMessage(upsertErr) })
|
||||
return
|
||||
}
|
||||
|
||||
send({
|
||||
step: 'finalize',
|
||||
status: 'success',
|
||||
profile: {
|
||||
company_id: companyId,
|
||||
horizontal_atoms: selection.horizontal_atoms,
|
||||
vertical_atoms: selection.vertical_atoms,
|
||||
modifier_atoms: selection.modifier_atoms,
|
||||
is_multi_vertical: selection.is_multi_vertical,
|
||||
profile_summary: narrative,
|
||||
verification_questions: selection.verification_questions,
|
||||
uncertainty_notes: selection.uncertainty_notes,
|
||||
composer_model: OPUS_MODEL,
|
||||
composed_at: composedAt,
|
||||
},
|
||||
})
|
||||
|
||||
// Step 5: fire-and-forget cache pre-warm. The client renders the
|
||||
// review card already; pre-warm just buys a faster first chat turn.
|
||||
send({ step: 'prewarm', status: 'in_progress' })
|
||||
const allIds = [
|
||||
...selection.horizontal_atoms,
|
||||
...selection.vertical_atoms,
|
||||
...selection.modifier_atoms,
|
||||
]
|
||||
if (allIds.length > 0) {
|
||||
const { data: rows } = await supabase
|
||||
.from('agent_atom_registry')
|
||||
.select('id, body')
|
||||
.in('id', allIds)
|
||||
const bodies = (rows ?? [])
|
||||
.map((r: { body: string | null }) => r.body ?? '')
|
||||
.filter((b: string) => b.length > 0)
|
||||
void preWarmAtomCache({ atomBodies: bodies })
|
||||
}
|
||||
send({ step: 'prewarm', status: 'success' })
|
||||
} catch (err) {
|
||||
send({
|
||||
step: 'error',
|
||||
status: 'error',
|
||||
message: err instanceof Error ? getUserErrorMessage(err) : 'Composer pipeline failed',
|
||||
})
|
||||
} finally {
|
||||
try {
|
||||
controller.close()
|
||||
} catch {
|
||||
// Already closed.
|
||||
}
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
return new Response(stream, {
|
||||
headers: {
|
||||
'Content-Type': 'application/x-ndjson; charset=utf-8',
|
||||
'Cache-Control': 'no-store',
|
||||
'X-Accel-Buffering': 'no',
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -1,176 +0,0 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { z } from 'zod'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { validateBody, validateQuery } from '@/lib/api/validate'
|
||||
|
||||
// GET /api/agent/profile?company_id=...
|
||||
// PATCH same path
|
||||
//
|
||||
// GET returns the composed profile + the source verification_questions stored
|
||||
// alongside it (read from agent_profiles row).
|
||||
//
|
||||
// PATCH updates field_overrides (timestamped, merged with existing) and
|
||||
// optionally rewrites the atom arrays from the review UI. Does not touch
|
||||
// verified_at: that flows through /verify. Requires a non-viewer role in
|
||||
// the target company (same rule as /verify: it mutates the profile).
|
||||
|
||||
const AtomArrays = z.object({
|
||||
horizontal_atoms: z.array(z.string()).optional(),
|
||||
vertical_atoms: z.array(z.string()).optional(),
|
||||
modifier_atoms: z.array(z.string()).optional(),
|
||||
})
|
||||
|
||||
const PatchBody = z.object({
|
||||
company_id: z.string().uuid().optional(),
|
||||
field_overrides: z.record(z.string(), z.unknown()).optional(),
|
||||
atoms: AtomArrays.optional(),
|
||||
profile_summary: z.string().min(1).max(2000).optional(),
|
||||
// Agent personalization: name shown on the FAB and chat headers, and
|
||||
// avatar key into the static AVATAR_OPTIONS registry. Both nullable so
|
||||
// the user can clear them back to defaults.
|
||||
display_name: z.string().min(1).max(60).nullable().optional(),
|
||||
avatar_id: z.string().max(60).nullable().optional(),
|
||||
})
|
||||
|
||||
const GetQuerySchema = z.object({
|
||||
company_id: z.string().uuid().optional(),
|
||||
})
|
||||
|
||||
const forbidden = (code: 'NOT_COMPANY_MEMBER' | 'WRITE_PERMISSION_REQUIRED') =>
|
||||
NextResponse.json(
|
||||
{
|
||||
error:
|
||||
code === 'NOT_COMPANY_MEMBER'
|
||||
? {
|
||||
code,
|
||||
message: 'Du är inte medlem i detta företag.',
|
||||
message_en: 'Not a member of this company.',
|
||||
}
|
||||
: {
|
||||
code,
|
||||
message: 'Du har endast läsbehörighet i detta företag.',
|
||||
message_en: 'You only have read access in this company.',
|
||||
},
|
||||
},
|
||||
{ status: 403 },
|
||||
)
|
||||
|
||||
export const GET = withRouteContext('agent.profile.get', async (request, ctx) => {
|
||||
const { supabase, companyId: activeCompanyId, user, log } = ctx
|
||||
|
||||
const validated = validateQuery(request, GetQuerySchema, {
|
||||
log,
|
||||
operation: 'agent.profile.get',
|
||||
})
|
||||
if (!validated.success) return validated.response
|
||||
const companyId = validated.data.company_id ?? activeCompanyId
|
||||
|
||||
// Defense in depth alongside RLS: confirm membership before reading.
|
||||
const { data: membership } = await supabase
|
||||
.from('company_members')
|
||||
.select('role')
|
||||
.eq('company_id', companyId)
|
||||
.eq('user_id', user.id)
|
||||
.maybeSingle()
|
||||
if (!membership) return forbidden('NOT_COMPANY_MEMBER')
|
||||
|
||||
const { data, error } = await supabase
|
||||
.from('agent_profiles')
|
||||
.select(
|
||||
'company_id, horizontal_atoms, vertical_atoms, modifier_atoms, profile_summary, source_signals, field_overrides, composed_at, composer_model, composer_version, verified_at, verified_by_user_id, display_name, avatar_id',
|
||||
)
|
||||
.eq('company_id', companyId)
|
||||
.maybeSingle()
|
||||
if (error) throw error
|
||||
if (!data) return NextResponse.json({ data: null })
|
||||
|
||||
return NextResponse.json({ data })
|
||||
})
|
||||
|
||||
export const PATCH = withRouteContext('agent.profile.update', async (request, ctx) => {
|
||||
const { supabase, companyId: activeCompanyId, user, log } = ctx
|
||||
|
||||
const validation = await validateBody(request, PatchBody, {
|
||||
log,
|
||||
operation: 'agent.profile.update',
|
||||
})
|
||||
if (!validation.success) return validation.response
|
||||
const body = validation.data
|
||||
|
||||
const companyId = body.company_id ?? activeCompanyId
|
||||
|
||||
// RLS guards reads/updates by company_id; defense in depth: confirm
|
||||
// membership AND a non-viewer role (this mutates the company's profile;
|
||||
// same rule /verify already enforces).
|
||||
const { data: membership } = await supabase
|
||||
.from('company_members')
|
||||
.select('role')
|
||||
.eq('company_id', companyId)
|
||||
.eq('user_id', user.id)
|
||||
.maybeSingle()
|
||||
if (!membership) return forbidden('NOT_COMPANY_MEMBER')
|
||||
if (membership.role === 'viewer') return forbidden('WRITE_PERMISSION_REQUIRED')
|
||||
|
||||
// Load current overrides to merge timestamp-stamped entries. Avoids round-trip
|
||||
// when caller sends only an atom-array change.
|
||||
const { data: current } = await supabase
|
||||
.from('agent_profiles')
|
||||
.select('field_overrides')
|
||||
.eq('company_id', companyId)
|
||||
.single()
|
||||
if (!current) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: {
|
||||
code: 'AGENT_PROFILE_NOT_FOUND',
|
||||
message: 'Det finns ingen agentprofil för detta företag.',
|
||||
message_en: 'agent_profile not found for this company.',
|
||||
},
|
||||
},
|
||||
{ status: 404 },
|
||||
)
|
||||
}
|
||||
|
||||
const update: Record<string, unknown> = {}
|
||||
if (body.field_overrides && Object.keys(body.field_overrides).length > 0) {
|
||||
const merged: Record<string, { value: unknown; overridden_at: string }> = {
|
||||
...((current.field_overrides as Record<string, { value: unknown; overridden_at: string }>) ?? {}),
|
||||
}
|
||||
const now = new Date().toISOString()
|
||||
for (const [k, v] of Object.entries(body.field_overrides)) {
|
||||
merged[k] = { value: v, overridden_at: now }
|
||||
}
|
||||
update.field_overrides = merged
|
||||
}
|
||||
if (body.atoms?.horizontal_atoms) update.horizontal_atoms = body.atoms.horizontal_atoms
|
||||
if (body.atoms?.vertical_atoms) update.vertical_atoms = body.atoms.vertical_atoms
|
||||
if (body.atoms?.modifier_atoms) update.modifier_atoms = body.atoms.modifier_atoms
|
||||
if (body.profile_summary) update.profile_summary = body.profile_summary
|
||||
if (body.display_name !== undefined) update.display_name = body.display_name
|
||||
if (body.avatar_id !== undefined) update.avatar_id = body.avatar_id
|
||||
|
||||
if (Object.keys(update).length === 0) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: {
|
||||
code: 'NOTHING_TO_UPDATE',
|
||||
message: 'Inget att uppdatera.',
|
||||
message_en: 'Nothing to update.',
|
||||
},
|
||||
},
|
||||
{ status: 400 },
|
||||
)
|
||||
}
|
||||
|
||||
const { data, error } = await supabase
|
||||
.from('agent_profiles')
|
||||
.update(update)
|
||||
.eq('company_id', companyId)
|
||||
.select(
|
||||
'company_id, horizontal_atoms, vertical_atoms, modifier_atoms, profile_summary, field_overrides',
|
||||
)
|
||||
.single()
|
||||
if (error) throw error
|
||||
|
||||
return NextResponse.json({ data })
|
||||
})
|
||||
@@ -1,72 +0,0 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { z } from 'zod'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
|
||||
// POST /api/agent/profile/verify
|
||||
//
|
||||
// Stamps verified_at + verified_by_user_id on agent_profiles when the user
|
||||
// clicks "Det här ser rätt ut, kör" in Phase B. Idempotent: re-verifying
|
||||
// updates the timestamp; this is desirable for "Bygg om" rebuild flows.
|
||||
|
||||
const BodySchema = z.object({
|
||||
company_id: z.string().uuid().optional(),
|
||||
})
|
||||
|
||||
export const POST = withRouteContext('agent.profile.verify', async (request, ctx) => {
|
||||
const { supabase, companyId: activeCompanyId, user } = ctx
|
||||
|
||||
// Tolerant parse: the review card POSTs with an empty body when verifying
|
||||
// the active company.
|
||||
const raw = await request.json().catch(() => ({}))
|
||||
const parsed = BodySchema.safeParse(raw)
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: 'Validation failed',
|
||||
type: 'validation_error',
|
||||
errors: parsed.error.issues.map((issue) => ({
|
||||
field: issue.path.join('.'),
|
||||
message: issue.message,
|
||||
code: issue.code,
|
||||
})),
|
||||
},
|
||||
{ status: 400 },
|
||||
)
|
||||
}
|
||||
|
||||
const companyId = parsed.data.company_id ?? activeCompanyId
|
||||
|
||||
// Defense in depth alongside RLS: confirm membership for the target
|
||||
// company; a non-viewer role is required to stamp verified_at.
|
||||
const { data: membership } = await supabase
|
||||
.from('company_members')
|
||||
.select('role')
|
||||
.eq('company_id', companyId)
|
||||
.eq('user_id', user.id)
|
||||
.maybeSingle()
|
||||
if (!membership || membership.role === 'viewer') {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: {
|
||||
code: 'WRITE_PERMISSION_REQUIRED',
|
||||
message: 'Du har endast läsbehörighet i detta företag.',
|
||||
message_en: 'You only have read access in this company.',
|
||||
},
|
||||
},
|
||||
{ status: 403 },
|
||||
)
|
||||
}
|
||||
|
||||
const { data, error } = await supabase
|
||||
.from('agent_profiles')
|
||||
.update({
|
||||
verified_at: new Date().toISOString(),
|
||||
verified_by_user_id: user.id,
|
||||
})
|
||||
.eq('company_id', companyId)
|
||||
.select('company_id, verified_at, verified_by_user_id')
|
||||
.single()
|
||||
if (error) throw error
|
||||
|
||||
return NextResponse.json({ data })
|
||||
})
|
||||
@@ -1,107 +0,0 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { z } from 'zod'
|
||||
import { withRouteContext } from '@/lib/api/with-route-context'
|
||||
import { validateQuery } from '@/lib/api/validate'
|
||||
|
||||
// GET /api/agent/skills
|
||||
//
|
||||
// Read-only transparency surface for the in-app bookkeeping assistant's domain
|
||||
// knowledge ("atoms"). Powers /settings/agent-skills: the companion to
|
||||
// /settings/agent-memory. Memory is what the assistant *learned* about this
|
||||
// company (user-editable); skills are the Swedish-accounting expertise it
|
||||
// *ships* with: authored in .claude/skills/**/SKILL.md, seeded into
|
||||
// agent_atom_registry, read-only for users, curated via mcp_exposed.
|
||||
//
|
||||
// Two shapes off one route:
|
||||
// (no params) → metadata for every active + exposed atom, each flagged
|
||||
// active-for-this-company. Bodies omitted so the list payload
|
||||
// stays small.
|
||||
// ?slug=<id> → the full SKILL.md body for one atom, loaded on expand.
|
||||
//
|
||||
// "Active for this company": horizontal atoms are regulatory and shared by
|
||||
// every Swedish company, so always active. Vertical/modifier atoms are active
|
||||
// only when the composer selected them into this company's agent_profile:
|
||||
// others are shown dormant so the user sees both the full library and what's
|
||||
// tuned for them. The profile arrays store full ids ("vertical/konsult-it"),
|
||||
// matched directly against agent_atom_registry.id (see lib/agent/chat/system-prompt.ts).
|
||||
|
||||
interface AtomMeta {
|
||||
id: string
|
||||
tier: 'horizontal' | 'vertical' | 'modifier'
|
||||
title: string
|
||||
description: string
|
||||
active: boolean
|
||||
}
|
||||
|
||||
const QuerySchema = z.object({
|
||||
slug: z.string().min(1).optional(),
|
||||
})
|
||||
|
||||
export const GET = withRouteContext('agent.skills.list', async (request, ctx) => {
|
||||
const { supabase, companyId, log } = ctx
|
||||
|
||||
const validated = validateQuery(request, QuerySchema, {
|
||||
log,
|
||||
operation: 'agent.skills.list',
|
||||
})
|
||||
if (!validated.success) return validated.response
|
||||
const { slug } = validated.data
|
||||
|
||||
// Detail: one atom's body, fetched lazily when the user expands a card.
|
||||
// The atom registry is global product content (not tenant data), so no
|
||||
// company filter applies here.
|
||||
if (slug) {
|
||||
const { data, error } = await supabase
|
||||
.from('agent_atom_registry')
|
||||
.select('id, title, body, is_active, mcp_exposed')
|
||||
.eq('id', slug)
|
||||
.maybeSingle()
|
||||
if (error) throw error
|
||||
if (!data || !data.is_active || !data.mcp_exposed) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: {
|
||||
code: 'SKILL_NOT_FOUND',
|
||||
message: 'Kunskapen hittades inte.',
|
||||
message_en: 'Skill not found.',
|
||||
},
|
||||
},
|
||||
{ status: 404 },
|
||||
)
|
||||
}
|
||||
return NextResponse.json({ data: { id: data.id, title: data.title, body: data.body ?? '' } })
|
||||
}
|
||||
|
||||
// List: metadata for every visible atom + which are active for this company.
|
||||
const { data: atoms, error } = await supabase
|
||||
.from('agent_atom_registry')
|
||||
.select('id, tier, title, description')
|
||||
.eq('is_active', true)
|
||||
.eq('mcp_exposed', true)
|
||||
.is('parent_atom_id', null) // show top-level skills only; reference children are internal
|
||||
.order('tier', { ascending: true })
|
||||
.order('title', { ascending: true })
|
||||
if (error) throw error
|
||||
|
||||
const { data: profile } = await supabase
|
||||
.from('agent_profiles')
|
||||
.select('vertical_atoms, modifier_atoms')
|
||||
.eq('company_id', companyId)
|
||||
.maybeSingle()
|
||||
|
||||
const verticalActive = new Set((profile?.vertical_atoms as string[] | null) ?? [])
|
||||
const modifierActive = new Set((profile?.modifier_atoms as string[] | null) ?? [])
|
||||
|
||||
const result: AtomMeta[] = (atoms ?? []).map((a) => {
|
||||
const tier = a.tier as AtomMeta['tier']
|
||||
const active =
|
||||
tier === 'horizontal'
|
||||
? true
|
||||
: tier === 'vertical'
|
||||
? verticalActive.has(a.id)
|
||||
: modifierActive.has(a.id)
|
||||
return { id: a.id, tier, title: a.title, description: a.description, active }
|
||||
})
|
||||
|
||||
return NextResponse.json({ data: result })
|
||||
})
|
||||
Reference in New Issue
Block a user