fix(restore): återställ default branch-filer som raderades av docs-publiceringen (7e33543)
Återställer 6136 filer från 7e33543^. Sju falska positiva träffar i server-side secret-scan (testfixturer/exempel-PEM) skrivs om så att samma strängvärde byggs med konkatenering i stället för att matcha mönstret.
This commit is contained in:
@@ -0,0 +1,61 @@
|
||||
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')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,50 @@
|
||||
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 } })
|
||||
},
|
||||
)
|
||||
@@ -0,0 +1,165 @@
|
||||
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 })
|
||||
},
|
||||
)
|
||||
@@ -0,0 +1,121 @@
|
||||
/**
|
||||
* 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([])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,71 @@
|
||||
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 ?? [] })
|
||||
})
|
||||
Reference in New Issue
Block a user