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,173 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
|
||||
const generateText = vi.fn()
|
||||
vi.mock('@/lib/ai', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@/lib/ai')>()
|
||||
return { ...actual, getAiService: () => ({ generateText }) }
|
||||
})
|
||||
const buildLedgerTools = vi.fn()
|
||||
const buildAssistantSnapshot = vi.fn()
|
||||
vi.mock('../ledger-tools', () => ({
|
||||
buildLedgerTools: (...a: unknown[]) => buildLedgerTools(...a),
|
||||
}))
|
||||
vi.mock('../snapshot', () => ({
|
||||
buildAssistantSnapshot: (...a: unknown[]) => buildAssistantSnapshot(...a),
|
||||
}))
|
||||
|
||||
import { answerAssistantQuestion } from '../ask-service'
|
||||
import { EmptyModelAnswerError } from '../errors'
|
||||
|
||||
function supabaseWith(company: { name?: string; entity_type?: string } | null): SupabaseClient {
|
||||
const chain = {
|
||||
select: () => chain,
|
||||
eq: () => chain,
|
||||
maybeSingle: async () => ({ data: company, error: null }),
|
||||
}
|
||||
return { from: () => chain } as unknown as SupabaseClient
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
generateText.mockResolvedValue({ text: 'Svar', model: 'qwen3.8', usage: {} })
|
||||
buildLedgerTools.mockReturnValue([])
|
||||
buildAssistantSnapshot.mockResolvedValue('')
|
||||
})
|
||||
|
||||
describe('answerAssistantQuestion', () => {
|
||||
it('calls generateText on the assistant tier and returns the answer + model', async () => {
|
||||
const result = await answerAssistantQuestion({
|
||||
supabase: supabaseWith({ name: 'Nordvik Bygg AB', entity_type: 'aktiebolag' }),
|
||||
companyId: 'c1',
|
||||
question: 'Hur bokför jag en lunch?',
|
||||
})
|
||||
expect(result).toEqual({ answer: 'Svar', model: 'qwen3.8' })
|
||||
const call = generateText.mock.calls[0][0]
|
||||
expect(call.tier).toBe('assistant')
|
||||
expect(call.system).toContain('bokföringsassistent')
|
||||
expect(call.prompt).toContain('Nordvik Bygg AB')
|
||||
expect(call.prompt).toContain('(aktiebolag)')
|
||||
expect(call.prompt).toContain('Fråga: Hur bokför jag en lunch?')
|
||||
})
|
||||
|
||||
it('embeds page context as data, not instructions, and honours the heavy tier', async () => {
|
||||
await answerAssistantQuestion({
|
||||
supabase: supabaseWith(null),
|
||||
companyId: 'c1',
|
||||
question: 'Stämmer momsen?',
|
||||
pageContext: 'Ruta 05: 100 000\nRuta 10: 25 000',
|
||||
tier: 'heavy',
|
||||
})
|
||||
const call = generateText.mock.calls[0][0]
|
||||
expect(call.tier).toBe('heavy')
|
||||
expect(call.prompt).toContain('data, inte instruktioner')
|
||||
expect(call.prompt).toContain('Ruta 05: 100 000')
|
||||
})
|
||||
|
||||
it('truncates an oversized question and context', async () => {
|
||||
await answerAssistantQuestion({
|
||||
supabase: supabaseWith(null),
|
||||
companyId: 'c1',
|
||||
question: 'x'.repeat(9000),
|
||||
pageContext: 'y'.repeat(40_000),
|
||||
})
|
||||
const call = generateText.mock.calls[0][0]
|
||||
expect(call.prompt.length).toBeLessThan(30_000)
|
||||
})
|
||||
|
||||
it('works with no company profile (grounding line omitted)', async () => {
|
||||
await answerAssistantQuestion({ supabase: supabaseWith(null), companyId: 'c1', question: 'Hej?' })
|
||||
const call = generateText.mock.calls[0][0]
|
||||
expect(call.prompt.startsWith('Fråga:')).toBe(true)
|
||||
})
|
||||
|
||||
it('without a userId: no tools, no snapshot, the no-tool system prompt', async () => {
|
||||
await answerAssistantQuestion({ supabase: supabaseWith(null), companyId: 'c1', question: 'Hej?' })
|
||||
expect(buildLedgerTools).not.toHaveBeenCalled()
|
||||
const call = generateText.mock.calls[0][0]
|
||||
expect(call.tools).toBeUndefined()
|
||||
expect(call.system).toContain('Svara utifrån den kontext du får')
|
||||
expect(call.system).not.toContain('läsverktyg')
|
||||
})
|
||||
|
||||
it('with a userId: attaches the read tools + snapshot and the tool-aware prompt', async () => {
|
||||
const tools = [
|
||||
{ name: 'gnubok_get_income_statement', description: 'd', jsonSchema: {}, execute: vi.fn() },
|
||||
]
|
||||
buildLedgerTools.mockReturnValue(tools)
|
||||
buildAssistantSnapshot.mockResolvedValue('Status: momsregistrerad (momsperiod: quarterly).')
|
||||
|
||||
await answerAssistantQuestion({
|
||||
supabase: supabaseWith({ name: 'Arcim Technology AB', entity_type: 'aktiebolag' }),
|
||||
companyId: 'company-1',
|
||||
userId: 'user-1',
|
||||
conversationId: 'conv-1',
|
||||
question: 'Vad är min största utgiftspost den här månaden?',
|
||||
})
|
||||
|
||||
expect(buildLedgerTools).toHaveBeenCalledWith(expect.anything(), 'company-1', 'user-1', 'conv-1')
|
||||
const call = generateText.mock.calls[0][0]
|
||||
expect(call.tools).toBe(tools)
|
||||
expect(call.maxSteps).toBe(5)
|
||||
// tool-aware system prompt
|
||||
expect(call.system).toContain('läsverktyg')
|
||||
expect(call.system).not.toContain('Svara utifrån den kontext du får')
|
||||
// snapshot injected as grounding
|
||||
expect(call.prompt).toContain('Företagets nuläge')
|
||||
expect(call.prompt).toContain('Status: momsregistrerad (momsperiod: quarterly).')
|
||||
})
|
||||
|
||||
it('defaults maxTokens to 5400 (the streaming chat reply ceiling; 1500 caused empty max_tokens answers)', async () => {
|
||||
await answerAssistantQuestion({ supabase: supabaseWith(null), companyId: 'c1', question: 'Hej?' })
|
||||
expect(generateText.mock.calls[0][0].maxTokens).toBe(5400)
|
||||
})
|
||||
|
||||
it('rejects with the typed empty-answer error when the model returns no visible text', async () => {
|
||||
generateText.mockResolvedValue({ text: ' \n', model: 'claude-sonnet-5', usage: {} })
|
||||
const promise = answerAssistantQuestion({
|
||||
supabase: supabaseWith(null),
|
||||
companyId: 'c1',
|
||||
question: 'Hej?',
|
||||
})
|
||||
await expect(promise).rejects.toBeInstanceOf(EmptyModelAnswerError)
|
||||
await expect(promise).rejects.toMatchObject({ code: 'empty_model_answer' })
|
||||
})
|
||||
|
||||
it('forwards the earlier turns as history so a follow-up can refer back', async () => {
|
||||
const history = [
|
||||
{ role: 'user' as const, text: 'Vad är min största utgift?' },
|
||||
{ role: 'assistant' as const, text: '12 345 kr på 5010.' },
|
||||
]
|
||||
await answerAssistantQuestion({
|
||||
supabase: supabaseWith(null),
|
||||
companyId: 'c1',
|
||||
userId: 'u1',
|
||||
conversationId: 'conv-1',
|
||||
question: 'Och förra månaden?',
|
||||
history,
|
||||
})
|
||||
const call = generateText.mock.calls[0][0]
|
||||
expect(call.history).toEqual(history)
|
||||
// The question itself stays the final prompt, not folded into history.
|
||||
expect(call.prompt).toContain('Fråga: Och förra månaden?')
|
||||
})
|
||||
|
||||
it('sends no history key at all for a fresh thread or a one-off ask', async () => {
|
||||
await answerAssistantQuestion({ supabase: supabaseWith(null), companyId: 'c1', question: 'Hej?', history: [] })
|
||||
expect('history' in generateText.mock.calls[0][0]).toBe(false)
|
||||
})
|
||||
|
||||
it('honours a custom maxSteps', async () => {
|
||||
buildLedgerTools.mockReturnValue([
|
||||
{ name: 'gnubok_get_vat_report', description: 'd', jsonSchema: {}, execute: vi.fn() },
|
||||
])
|
||||
await answerAssistantQuestion({
|
||||
supabase: supabaseWith(null),
|
||||
companyId: 'c1',
|
||||
userId: 'u1',
|
||||
question: 'x',
|
||||
maxSteps: 3,
|
||||
})
|
||||
expect(generateText.mock.calls[0][0].maxSteps).toBe(3)
|
||||
})
|
||||
})
|
||||
@@ -1,89 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
import type { AgentTool } from '@/lib/agent/tools/types'
|
||||
|
||||
const getMany = vi.fn()
|
||||
vi.mock('@/lib/agent/tools/registry', () => ({
|
||||
agentToolRegistry: { getMany: (names: string[]) => getMany(names) },
|
||||
}))
|
||||
|
||||
import { buildLedgerTools, LEDGER_READ_TOOLS } from '../ledger-tools'
|
||||
|
||||
function tool(name: string, ann?: AgentTool['annotations']): AgentTool {
|
||||
return {
|
||||
name,
|
||||
description: `desc ${name}`,
|
||||
inputSchema: { type: 'object', properties: {} },
|
||||
...(ann ? { annotations: ann } : {}),
|
||||
execute: vi.fn().mockResolvedValue({ tool: name }),
|
||||
}
|
||||
}
|
||||
|
||||
const supabase = {} as SupabaseClient
|
||||
|
||||
beforeEach(() => vi.clearAllMocks())
|
||||
|
||||
describe('buildLedgerTools', () => {
|
||||
it('requests exactly the read whitelist from the registry', () => {
|
||||
getMany.mockReturnValue([])
|
||||
buildLedgerTools(supabase, 'c1', 'u1')
|
||||
expect(getMany).toHaveBeenCalledWith([...LEDGER_READ_TOOLS])
|
||||
})
|
||||
|
||||
it('keeps read-only + unannotated tools, drops writable/destructive ones', () => {
|
||||
getMany.mockReturnValue([
|
||||
tool('gnubok_get_income_statement', { readOnlyHint: true }),
|
||||
tool('gnubok_list_accounts'), // unannotated: on the curated read whitelist, kept
|
||||
tool('gnubok_categorize_transaction', { readOnlyHint: false }),
|
||||
tool('gnubok_delete_voucher', { destructiveHint: true }),
|
||||
])
|
||||
const defs = buildLedgerTools(supabase, 'c1', 'u1')
|
||||
expect(defs.map((d) => d.name)).toEqual(['gnubok_get_income_statement', 'gnubok_list_accounts'])
|
||||
})
|
||||
|
||||
it('adapts each tool: name/description/jsonSchema and an execute bound to the actor', async () => {
|
||||
const src = tool('gnubok_get_vat_report', { readOnlyHint: true })
|
||||
getMany.mockReturnValue([src])
|
||||
const defs = buildLedgerTools(supabase, 'company-9', 'user-7', 'conv-3')
|
||||
expect(defs).toHaveLength(1)
|
||||
const def = defs[0]
|
||||
expect(def.name).toBe('gnubok_get_vat_report')
|
||||
expect(def.description).toBe('desc gnubok_get_vat_report')
|
||||
expect(def.jsonSchema).toEqual({ type: 'object', properties: {} })
|
||||
|
||||
const out = await def.execute({ period: '2026-07' })
|
||||
expect(out).toEqual({ tool: 'gnubok_get_vat_report' })
|
||||
expect(src.execute).toHaveBeenCalledWith(
|
||||
{ period: '2026-07' },
|
||||
'company-9',
|
||||
'user-7',
|
||||
supabase,
|
||||
{ type: 'agent_chat', id: 'conv-3' },
|
||||
)
|
||||
})
|
||||
|
||||
it('omits the actor id when there is no conversation', async () => {
|
||||
const src = tool('gnubok_get_trial_balance', { readOnlyHint: true })
|
||||
getMany.mockReturnValue([src])
|
||||
const [def] = buildLedgerTools(supabase, 'c1', 'u1')
|
||||
await def.execute({})
|
||||
expect(src.execute).toHaveBeenCalledWith({}, 'c1', 'u1', supabase, { type: 'agent_chat' })
|
||||
})
|
||||
|
||||
it('returns nothing when the registry is empty (core-only build)', () => {
|
||||
getMany.mockReturnValue([])
|
||||
expect(buildLedgerTools(supabase, 'c1', 'u1')).toEqual([])
|
||||
})
|
||||
|
||||
it('never lists a write or memory-write tool on the whitelist', () => {
|
||||
for (const bad of [
|
||||
'gnubok_categorize_transaction',
|
||||
'gnubok_create_invoice',
|
||||
'gnubok_approve_supplier_invoice',
|
||||
'gnubok_remember_fact',
|
||||
'gnubok_forget_fact',
|
||||
]) {
|
||||
expect(LEDGER_READ_TOOLS).not.toContain(bad)
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -1,288 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
import {
|
||||
resolveChatConversation,
|
||||
loadChatHistory,
|
||||
persistUserTurn,
|
||||
persistAssistantTurn,
|
||||
CHAT_INTENT_ID,
|
||||
HISTORY_MAX_CHARS,
|
||||
HISTORY_MAX_MESSAGES,
|
||||
} from '../persist'
|
||||
|
||||
interface Recorded {
|
||||
inserts: { table: string; payload: Record<string, unknown> }[]
|
||||
updates: { table: string; payload: Record<string, unknown>; id?: string }[]
|
||||
}
|
||||
|
||||
/**
|
||||
* Hand-rolled supabase double. agent_messages.insert() is awaited directly
|
||||
* ({ error }); agent_conversations.insert() chains .select('id').single().
|
||||
* agent_conversations.update() chains .eq('id', ...). The mock branches on the
|
||||
* table so both shapes resolve.
|
||||
*/
|
||||
function makeSupabase(opts: {
|
||||
conv?: { id: string; user_id: string; company_id: string; intent_id: string } | null
|
||||
newId?: string
|
||||
msgInsertError?: unknown
|
||||
} = {}) {
|
||||
const rec: Recorded = { inserts: [], updates: [] }
|
||||
const api = {
|
||||
from(table: string) {
|
||||
const chain = {
|
||||
select: () => chain,
|
||||
eq: (_col: string, _val: string) => chain,
|
||||
maybeSingle: async () => ({ data: opts.conv ?? null, error: null }),
|
||||
insert(payload: Record<string, unknown>) {
|
||||
rec.inserts.push({ table, payload })
|
||||
if (table === 'agent_messages') {
|
||||
return Promise.resolve({ error: opts.msgInsertError ?? null })
|
||||
}
|
||||
return {
|
||||
select: () => ({
|
||||
single: async () => ({ data: { id: opts.newId ?? 'new-conv' }, error: null }),
|
||||
}),
|
||||
}
|
||||
},
|
||||
update(payload: Record<string, unknown>) {
|
||||
return {
|
||||
eq: async (_col: string, id: string) => {
|
||||
rec.updates.push({ table, payload, id })
|
||||
return { error: null }
|
||||
},
|
||||
}
|
||||
},
|
||||
}
|
||||
return chain
|
||||
},
|
||||
}
|
||||
return { supabase: api as unknown as SupabaseClient, rec }
|
||||
}
|
||||
|
||||
beforeEach(() => vi.clearAllMocks())
|
||||
|
||||
describe('resolveChatConversation', () => {
|
||||
it('creates a general.help conversation titled from the first question', async () => {
|
||||
const { supabase, rec } = makeSupabase({ newId: 'conv-new' })
|
||||
const res = await resolveChatConversation(
|
||||
supabase,
|
||||
'user-1',
|
||||
'company-1',
|
||||
null,
|
||||
' Hur bokför jag en lunch med en kund? ',
|
||||
'report:vat:2026-07',
|
||||
)
|
||||
expect(res).toEqual({ ok: true, conversationId: 'conv-new', created: true })
|
||||
const insert = rec.inserts.find((i) => i.table === 'agent_conversations')!
|
||||
expect(insert.payload).toMatchObject({
|
||||
company_id: 'company-1',
|
||||
user_id: 'user-1',
|
||||
intent_id: CHAT_INTENT_ID,
|
||||
context_ref: 'report:vat:2026-07',
|
||||
})
|
||||
expect(insert.payload.title).toBe('Hur bokför jag en lunch med en kund?')
|
||||
})
|
||||
|
||||
it('resumes an owned general.help thread', async () => {
|
||||
const { supabase } = makeSupabase({
|
||||
conv: {
|
||||
id: 'conv-9',
|
||||
user_id: 'user-1',
|
||||
company_id: 'company-1',
|
||||
intent_id: CHAT_INTENT_ID,
|
||||
},
|
||||
})
|
||||
const res = await resolveChatConversation(supabase, 'user-1', 'company-1', 'conv-9', 'q')
|
||||
expect(res).toEqual({ ok: true, conversationId: 'conv-9', created: false })
|
||||
})
|
||||
|
||||
it("refuses a colleague's thread (not_found, not 403)", async () => {
|
||||
const { supabase } = makeSupabase({
|
||||
conv: {
|
||||
id: 'conv-9',
|
||||
user_id: 'other-user',
|
||||
company_id: 'company-1',
|
||||
intent_id: CHAT_INTENT_ID,
|
||||
},
|
||||
})
|
||||
const res = await resolveChatConversation(supabase, 'user-1', 'company-1', 'conv-9', 'q')
|
||||
expect(res).toEqual({ ok: false, reason: 'not_found' })
|
||||
})
|
||||
|
||||
it('refuses a thread from another company', async () => {
|
||||
const { supabase } = makeSupabase({
|
||||
conv: { id: 'conv-9', user_id: 'user-1', company_id: 'company-2', intent_id: CHAT_INTENT_ID },
|
||||
})
|
||||
const res = await resolveChatConversation(supabase, 'user-1', 'company-1', 'conv-9', 'q')
|
||||
expect(res).toEqual({ ok: false, reason: 'not_found' })
|
||||
})
|
||||
|
||||
it('refuses a tool-loop thread (wrong intent)', async () => {
|
||||
const { supabase } = makeSupabase({
|
||||
conv: {
|
||||
id: 'conv-9',
|
||||
user_id: 'user-1',
|
||||
company_id: 'company-1',
|
||||
intent_id: 'transaction.categorization',
|
||||
},
|
||||
})
|
||||
const res = await resolveChatConversation(supabase, 'user-1', 'company-1', 'conv-9', 'q')
|
||||
expect(res).toEqual({ ok: false, reason: 'not_found' })
|
||||
})
|
||||
|
||||
it('falls back to a default title when the first question is blank', async () => {
|
||||
const { supabase, rec } = makeSupabase({ newId: 'conv-new' })
|
||||
await resolveChatConversation(supabase, 'user-1', 'company-1', null, ' ')
|
||||
const insert = rec.inserts.find((i) => i.table === 'agent_conversations')!
|
||||
expect(insert.payload.title).toBe('Fråga din assistent')
|
||||
expect(insert.payload.context_ref).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('persistUserTurn', () => {
|
||||
it('appends the question as a text-block user message', async () => {
|
||||
const { supabase, rec } = makeSupabase()
|
||||
await persistUserTurn(supabase, 'conv-9', 'Stämmer momsen?')
|
||||
const insert = rec.inserts.find((i) => i.table === 'agent_messages')!
|
||||
expect(insert.payload).toEqual({
|
||||
conversation_id: 'conv-9',
|
||||
role: 'user',
|
||||
content: [{ type: 'text', text: 'Stämmer momsen?' }],
|
||||
})
|
||||
})
|
||||
|
||||
it('throws if the insert fails (append-only audit must not silently drop turns)', async () => {
|
||||
const { supabase } = makeSupabase({ msgInsertError: new Error('rls') })
|
||||
await expect(persistUserTurn(supabase, 'conv-9', 'q')).rejects.toThrow('rls')
|
||||
})
|
||||
})
|
||||
|
||||
describe('persistAssistantTurn', () => {
|
||||
it('appends the answer and rolls the conversation row forward with a preview', async () => {
|
||||
const { supabase, rec } = makeSupabase()
|
||||
await persistAssistantTurn(supabase, 'conv-9', 'Ja, momsen stämmer.')
|
||||
const insert = rec.inserts.find((i) => i.table === 'agent_messages')!
|
||||
expect(insert.payload).toEqual({
|
||||
conversation_id: 'conv-9',
|
||||
role: 'assistant',
|
||||
content: [{ type: 'text', text: 'Ja, momsen stämmer.' }],
|
||||
})
|
||||
const update = rec.updates.find((u) => u.table === 'agent_conversations')!
|
||||
expect(update.id).toBe('conv-9')
|
||||
expect(update.payload.last_message_preview).toBe('Ja, momsen stämmer.')
|
||||
expect(update.payload.last_message_at).toEqual(expect.any(String))
|
||||
})
|
||||
|
||||
it('truncates a long preview to 200 chars with an ellipsis', async () => {
|
||||
const { supabase, rec } = makeSupabase()
|
||||
await persistAssistantTurn(supabase, 'conv-9', 'x'.repeat(500))
|
||||
const preview = rec.updates.find((u) => u.table === 'agent_conversations')!.payload
|
||||
.last_message_preview as string
|
||||
expect(preview.length).toBe(200)
|
||||
expect(preview.endsWith('…')).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('loadChatHistory', () => {
|
||||
type Row = { role: string; content: unknown; hidden?: boolean | null }
|
||||
// agent_messages read: select → eq → order → order → limit resolves rows.
|
||||
// Rows are handed over newest-first, exactly as the query returns them.
|
||||
function supabaseWithRows(newestFirst: Row[], opts: { error?: unknown; limitSeen?: number[] } = {}) {
|
||||
const chain = {
|
||||
select: () => chain,
|
||||
eq: () => chain,
|
||||
order: () => chain,
|
||||
limit: async (n: number) => {
|
||||
opts.limitSeen?.push(n)
|
||||
return { data: opts.error ? null : newestFirst, error: opts.error ?? null }
|
||||
},
|
||||
}
|
||||
return { from: () => chain } as unknown as SupabaseClient
|
||||
}
|
||||
const text = (t: string) => [{ type: 'text', text: t }]
|
||||
|
||||
it('returns the thread oldest-first as user/assistant text turns', async () => {
|
||||
const supabase = supabaseWithRows([
|
||||
{ role: 'assistant', content: text('12 345 kr på 5010.') },
|
||||
{ role: 'user', content: text('Vad är min största utgift?') },
|
||||
])
|
||||
expect(await loadChatHistory(supabase, 'conv-1')).toEqual([
|
||||
{ role: 'user', text: 'Vad är min största utgift?' },
|
||||
{ role: 'assistant', text: '12 345 kr på 5010.' },
|
||||
])
|
||||
})
|
||||
|
||||
it('drops hidden scaffolding, tool rows and empty tool-only turns from the old streaming runtime', async () => {
|
||||
const supabase = supabaseWithRows([
|
||||
{ role: 'assistant', content: text('Klart.') },
|
||||
{ role: 'tool', content: [{ type: 'tool_result', tool_use_id: 'tu_1', content: '{}' }] },
|
||||
{ role: 'assistant', content: [{ type: 'tool_use', id: 'tu_1', name: 'x', input: {} }] },
|
||||
{ role: 'user', content: text('Kolla momsen.') },
|
||||
{ role: 'user', content: text('[prompt template]'), hidden: true },
|
||||
])
|
||||
expect(await loadChatHistory(supabase, 'conv-1')).toEqual([
|
||||
{ role: 'user', text: 'Kolla momsen.' },
|
||||
{ role: 'assistant', text: 'Klart.' },
|
||||
])
|
||||
})
|
||||
|
||||
it('merges consecutive same-role turns (a question whose answer failed, then its retry)', async () => {
|
||||
const supabase = supabaseWithRows([
|
||||
{ role: 'assistant', content: text('Svar.') },
|
||||
{ role: 'user', content: text('Igen?') },
|
||||
{ role: 'user', content: text('Hur gick juli?') },
|
||||
])
|
||||
expect(await loadChatHistory(supabase, 'conv-1')).toEqual([
|
||||
{ role: 'user', text: 'Hur gick juli?\n\nIgen?' },
|
||||
{ role: 'assistant', text: 'Svar.' },
|
||||
])
|
||||
})
|
||||
|
||||
it('never opens with an assistant turn whose question fell off the window', async () => {
|
||||
const supabase = supabaseWithRows([
|
||||
{ role: 'assistant', content: text('B') },
|
||||
{ role: 'user', content: text('b?') },
|
||||
{ role: 'assistant', content: text('A (its question is outside the window)') },
|
||||
])
|
||||
expect(await loadChatHistory(supabase, 'conv-1')).toEqual([
|
||||
{ role: 'user', text: 'b?' },
|
||||
{ role: 'assistant', text: 'B' },
|
||||
])
|
||||
})
|
||||
|
||||
it('reads only the newest HISTORY_MAX_MESSAGES rows and trims the oldest until the text fits', async () => {
|
||||
const limitSeen: number[] = []
|
||||
const big = 'x'.repeat(2_500)
|
||||
// 6 turns of 2 500 chars = 15 000 > HISTORY_MAX_CHARS: the oldest go.
|
||||
const rows: Row[] = []
|
||||
for (let i = 0; i < 6; i++) rows.push({ role: i % 2 === 0 ? 'assistant' : 'user', content: text(`${i}${big}`) })
|
||||
const supabase = supabaseWithRows(rows, { limitSeen })
|
||||
const turns = await loadChatHistory(supabase, 'conv-1')
|
||||
expect(limitSeen).toEqual([HISTORY_MAX_MESSAGES])
|
||||
const total = turns.reduce((n, t) => n + t.text.length, 0)
|
||||
expect(total).toBeLessThanOrEqual(HISTORY_MAX_CHARS)
|
||||
expect(turns[0].role).toBe('user')
|
||||
// Newest turn (index 0 in the newest-first rows) is the last one kept.
|
||||
expect(turns[turns.length - 1].text.startsWith('0')).toBe(true)
|
||||
})
|
||||
|
||||
it('clamps a single oversized turn instead of letting it eat the whole budget', async () => {
|
||||
const supabase = supabaseWithRows([
|
||||
{ role: 'assistant', content: text('Svar.') },
|
||||
{ role: 'user', content: text('y'.repeat(9_000)) },
|
||||
])
|
||||
const turns = await loadChatHistory(supabase, 'conv-1')
|
||||
expect(turns).toHaveLength(2)
|
||||
expect(turns[0].text.length).toBeLessThan(3_100)
|
||||
expect(turns[0].text.endsWith('…')).toBe(true)
|
||||
})
|
||||
|
||||
it('throws on a read error rather than silently answering without context', async () => {
|
||||
const supabase = supabaseWithRows([], { error: new Error('rls') })
|
||||
await expect(loadChatHistory(supabase, 'conv-1')).rejects.toThrow('rls')
|
||||
})
|
||||
|
||||
it('is empty for a thread with nothing readable', async () => {
|
||||
expect(await loadChatHistory(supabaseWithRows([]), 'conv-1')).toEqual([])
|
||||
})
|
||||
})
|
||||
@@ -1,177 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
|
||||
const getDeadlines = vi.fn()
|
||||
vi.mock('@/lib/deadlines/status-engine', () => ({
|
||||
getDeadlinesNeedingAttention: (...a: unknown[]) => getDeadlines(...a),
|
||||
}))
|
||||
|
||||
import { buildAssistantSnapshot } from '../snapshot'
|
||||
|
||||
/**
|
||||
* company_settings answers maybeSingle(); employees answers the awaited head
|
||||
* count (the builder chain is thenable, like the real PostgREST builder).
|
||||
*/
|
||||
function supabaseWith(
|
||||
settings: Record<string, unknown> | null,
|
||||
activeEmployees: number | null = null,
|
||||
): SupabaseClient {
|
||||
return {
|
||||
from: (table: string) => {
|
||||
const chain = {
|
||||
select: () => chain,
|
||||
eq: () => chain,
|
||||
maybeSingle: async () => ({ data: table === 'company_settings' ? settings : null, error: null }),
|
||||
then: (onFulfilled: (v: unknown) => unknown) =>
|
||||
Promise.resolve({ count: table === 'employees' ? activeEmployees : null, error: null }).then(
|
||||
onFulfilled,
|
||||
),
|
||||
}
|
||||
return chain
|
||||
},
|
||||
} as unknown as SupabaseClient
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
getDeadlines.mockResolvedValue({ overdue: [], actionNeeded: [] })
|
||||
})
|
||||
|
||||
describe('buildAssistantSnapshot', () => {
|
||||
it('summarises the company status line', async () => {
|
||||
const snap = await buildAssistantSnapshot(
|
||||
supabaseWith({
|
||||
vat_registered: true,
|
||||
moms_period: 'quarterly',
|
||||
accounting_method: 'accrual',
|
||||
pays_salaries: true,
|
||||
}),
|
||||
'c1',
|
||||
)
|
||||
expect(snap).toContain('momsregistrerad (momsperiod: quarterly)')
|
||||
expect(snap).toContain('bokföringsmetod: fakturametod')
|
||||
expect(snap).toContain('betalar löner')
|
||||
})
|
||||
|
||||
it('handles a non-VAT, cash-method company', async () => {
|
||||
const snap = await buildAssistantSnapshot(
|
||||
supabaseWith({ vat_registered: false, accounting_method: 'cash', pays_salaries: false }),
|
||||
'c1',
|
||||
)
|
||||
expect(snap).toContain('ej momsregistrerad')
|
||||
expect(snap).toContain('bokföringsmetod: kontantmetod')
|
||||
})
|
||||
|
||||
describe('the salary fact', () => {
|
||||
// pays_salaries is NOT NULL DEFAULT false and only the Skatt settings form
|
||||
// writes it, so false is what every company that never opened that form
|
||||
// reads. Claiming "betalar inte löner" from it told a payroll-running
|
||||
// aktiebolag in every answer that it had no salaries.
|
||||
it('claims nothing when the flag is merely at its column default', async () => {
|
||||
const snap = await buildAssistantSnapshot(
|
||||
supabaseWith({ vat_registered: true, pays_salaries: false, employer_registered: null }, 0),
|
||||
'c1',
|
||||
)
|
||||
expect(snap).not.toContain('betalar inte löner')
|
||||
expect(snap).not.toContain('betalar löner')
|
||||
expect(snap).toContain('Status: momsregistrerad.')
|
||||
})
|
||||
|
||||
it('derives it from active employees when the flag was never set', async () => {
|
||||
const snap = await buildAssistantSnapshot(
|
||||
supabaseWith({ vat_registered: true, pays_salaries: false, employer_registered: null }, 1),
|
||||
'c1',
|
||||
)
|
||||
expect(snap).toContain('betalar löner (1 anställd)')
|
||||
})
|
||||
|
||||
it('pluralises the headcount', async () => {
|
||||
const snap = await buildAssistantSnapshot(
|
||||
supabaseWith({ vat_registered: true, pays_salaries: false }, 3),
|
||||
'c1',
|
||||
)
|
||||
expect(snap).toContain('betalar löner (3 anställda)')
|
||||
})
|
||||
|
||||
it('accepts an attested employer registration as the positive fact', async () => {
|
||||
const snap = await buildAssistantSnapshot(
|
||||
supabaseWith({ vat_registered: true, pays_salaries: false, employer_registered: true }, 0),
|
||||
'c1',
|
||||
)
|
||||
expect(snap).toContain('betalar löner')
|
||||
})
|
||||
|
||||
it('states the negative only from an attested employer_registered = false', async () => {
|
||||
const snap = await buildAssistantSnapshot(
|
||||
supabaseWith({ vat_registered: true, pays_salaries: false, employer_registered: false }, 0),
|
||||
'c1',
|
||||
)
|
||||
expect(snap).toContain('betalar inte löner')
|
||||
})
|
||||
})
|
||||
|
||||
it('tells the model where the profile values are edited', async () => {
|
||||
const snap = await buildAssistantSnapshot(supabaseWith({ vat_registered: true }), 'c1')
|
||||
expect(snap).toContain('Inställningar > Skatt')
|
||||
expect(snap).toContain('Inställningar > Bokföring')
|
||||
})
|
||||
|
||||
it('lists deadlines that need attention (overdue first, capped)', async () => {
|
||||
getDeadlines.mockResolvedValue({
|
||||
overdue: [{ id: '1', title: 'Momsdeklaration', due_date: '2026-08-12', tax_deadline_type: 'vat' }],
|
||||
actionNeeded: [{ id: '2', title: 'Arbetsgivardeklaration', due_date: '2026-08-17', tax_deadline_type: 'employer' }],
|
||||
})
|
||||
const snap = await buildAssistantSnapshot(supabaseWith(null), 'c1')
|
||||
expect(snap).toContain('Deadlines som behöver åtgärd:')
|
||||
expect(snap).toContain('Momsdeklaration (2026-08-12)')
|
||||
expect(snap).toContain('Arbetsgivardeklaration (2026-08-17)')
|
||||
})
|
||||
|
||||
it('is best-effort: a failing settings query still yields the deadlines line', async () => {
|
||||
const throwing = {
|
||||
from: () => ({
|
||||
select: () => ({ eq: () => ({ maybeSingle: async () => { throw new Error('db down') } }) }),
|
||||
}),
|
||||
} as unknown as SupabaseClient
|
||||
getDeadlines.mockResolvedValue({
|
||||
overdue: [],
|
||||
actionNeeded: [{ id: '2', title: 'Moms', due_date: '2026-09-12', tax_deadline_type: 'vat' }],
|
||||
})
|
||||
const snap = await buildAssistantSnapshot(throwing, 'c1')
|
||||
expect(snap).toContain('Moms (2026-09-12)')
|
||||
})
|
||||
|
||||
it('lists the räkenskapsår newest first with their period_id (#2185)', async () => {
|
||||
const periods = [
|
||||
{ id: 'fp-2026', name: '2026', period_start: '2026-01-01', period_end: '2026-12-31', is_closed: false },
|
||||
{ id: 'fp-2025', name: '2025', period_start: '2025-01-01', period_end: '2025-12-31', is_closed: true },
|
||||
]
|
||||
const supabase = {
|
||||
from: (table: string) => {
|
||||
const chain = {
|
||||
select: () => chain,
|
||||
eq: () => chain,
|
||||
order: () => chain,
|
||||
limit: () => chain,
|
||||
maybeSingle: async () => ({ data: null, error: null }),
|
||||
then: (onFulfilled: (v: unknown) => unknown) =>
|
||||
Promise.resolve(
|
||||
table === 'fiscal_periods'
|
||||
? { data: periods, error: null }
|
||||
: { count: null, error: null },
|
||||
).then(onFulfilled),
|
||||
}
|
||||
return chain
|
||||
},
|
||||
} as unknown as SupabaseClient
|
||||
const snap = await buildAssistantSnapshot(supabase, 'c1')
|
||||
expect(snap).toContain(
|
||||
'Räkenskapsår (senaste först): 2026-01-01..2026-12-31 period_id=fp-2026 (senaste); 2025-01-01..2025-12-31 period_id=fp-2025 (avslutat).',
|
||||
)
|
||||
})
|
||||
|
||||
it('returns an empty string when there is nothing to say', async () => {
|
||||
const snap = await buildAssistantSnapshot(supabaseWith(null), 'c1')
|
||||
expect(snap).toBe('')
|
||||
})
|
||||
})
|
||||
File diff suppressed because one or more lines are too long
@@ -1,18 +0,0 @@
|
||||
/**
|
||||
* Typed failure for "the model returned no visible text": stop_reason
|
||||
* max_tokens with the whole budget spent before the first text block, or a
|
||||
* refusal with an empty body. Before this existed, an empty answer flowed
|
||||
* through /api/agent/ask as a 200 and rendered as an invisible bubble
|
||||
* ("Tänker", then silence).
|
||||
*
|
||||
* Lives in its own module so the API route and its tests can match on it
|
||||
* without importing ask-service's full dependency graph.
|
||||
*/
|
||||
export class EmptyModelAnswerError extends Error {
|
||||
readonly code = 'empty_model_answer'
|
||||
|
||||
constructor(model: string) {
|
||||
super(`Model ${model} returned an empty answer`)
|
||||
this.name = 'EmptyModelAnswerError'
|
||||
}
|
||||
}
|
||||
@@ -1,86 +0,0 @@
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
import type { AiToolDef } from '@/lib/ai'
|
||||
import { agentToolRegistry } from '@/lib/agent/tools/registry'
|
||||
import type { AgentActorContext } from '@/lib/agent/tools/types'
|
||||
|
||||
/**
|
||||
* The read-only tools the single-call assistant may call to answer questions
|
||||
* about the ledger (audit Option A: "single-call actions over the existing MCP
|
||||
* tool functions"). This is what makes the console behave like an MCP client:
|
||||
* the model asks for a report, we run the real tool, feed the JSON back.
|
||||
*
|
||||
* The list is the read slice of general.help's old tool whitelist: the
|
||||
* analytical reports and the lookups across the working set. Write/staging
|
||||
* tools (categorize, create_invoice, approve_supplier_invoice, stage_year_end,
|
||||
* …) and the memory-write tools (remember/forget) are deliberately absent: the
|
||||
* console has no ApprovalCard surface, so it reads and guides only; write
|
||||
* actions belong to the page-specific intents where a single entity is in
|
||||
* focus and the user expects a staged card.
|
||||
*
|
||||
* The registry is populated by the mcp-server extension at init
|
||||
* (ensureInitialized). In a core-only build it is empty, so this returns an
|
||||
* empty list and the assistant answers from the prompt + snapshot alone: the
|
||||
* graceful, correct degradation.
|
||||
*/
|
||||
export const LEDGER_READ_TOOLS: readonly string[] = [
|
||||
// Reports (the canonical analytical surface)
|
||||
'gnubok_get_income_statement',
|
||||
'gnubok_get_balance_sheet',
|
||||
'gnubok_get_trial_balance',
|
||||
'gnubok_get_general_ledger',
|
||||
'gnubok_get_kpi_report',
|
||||
'gnubok_get_vat_report',
|
||||
'gnubok_vat_close_check',
|
||||
'gnubok_get_ar_ledger',
|
||||
'gnubok_get_supplier_ledger',
|
||||
'gnubok_get_reconciliation_status',
|
||||
'gnubok_get_salary_journal',
|
||||
'gnubok_year_end_readiness',
|
||||
// Lookups across the working set
|
||||
'gnubok_query_journal',
|
||||
'gnubok_list_uncategorized_transactions',
|
||||
'gnubok_list_transactions_without_documents',
|
||||
'gnubok_list_invoices',
|
||||
'gnubok_list_customers',
|
||||
'gnubok_list_suppliers',
|
||||
'gnubok_list_supplier_invoices',
|
||||
'gnubok_list_accounts',
|
||||
'gnubok_list_fiscal_periods',
|
||||
'gnubok_list_employees',
|
||||
'gnubok_list_inbox_items',
|
||||
'gnubok_list_unmatched_documents',
|
||||
'gnubok_list_voucher_gaps',
|
||||
'gnubok_explain_voucher_gap',
|
||||
'gnubok_get_counterparty_templates',
|
||||
]
|
||||
|
||||
/**
|
||||
* Build the read-only tool defs for one company/user, bound to the same actor
|
||||
* context the streaming runtime uses (`agent_chat` + the conversation id, for
|
||||
* BFL audit). Each def's execute dispatches the real registered tool.
|
||||
*/
|
||||
export function buildLedgerTools(
|
||||
supabase: SupabaseClient,
|
||||
companyId: string,
|
||||
userId: string,
|
||||
conversationId?: string,
|
||||
): AiToolDef[] {
|
||||
const actor: AgentActorContext = {
|
||||
type: 'agent_chat',
|
||||
...(conversationId ? { id: conversationId } : {}),
|
||||
}
|
||||
|
||||
return agentToolRegistry
|
||||
.getMany([...LEDGER_READ_TOOLS])
|
||||
// Belt-and-suspenders on top of the curated whitelist: never expose a tool
|
||||
// the registry itself marks writable or destructive, even if it somehow
|
||||
// ended up on the list.
|
||||
.filter((t) => t.annotations?.readOnlyHint !== false && t.annotations?.destructiveHint !== true)
|
||||
.map((t) => ({
|
||||
name: t.name,
|
||||
description: t.description,
|
||||
jsonSchema: t.inputSchema,
|
||||
execute: (args: Record<string, unknown>) =>
|
||||
t.execute(args, companyId, userId, supabase, actor),
|
||||
}))
|
||||
}
|
||||
@@ -1,227 +0,0 @@
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
import type { AiChatTurn } from '@/lib/ai'
|
||||
|
||||
/**
|
||||
* Thread persistence for the single-call chat console (/chat).
|
||||
*
|
||||
* The console answers in one call via answerAssistantQuestion (no tool loop,
|
||||
* no streaming: runs on a local model). But the founder wants the /chat
|
||||
* sidebar and "resume a thread" to keep working, so each console turn is
|
||||
* written to the SAME durable tables the streaming runtime uses:
|
||||
* agent_conversations + agent_messages. That way old and new threads live in
|
||||
* one list and one schema.
|
||||
*
|
||||
* Content is stored as the canonical Anthropic content array
|
||||
* ([{ type: 'text', text }]) so normalizeStoredMessages() renders these rows
|
||||
* identically to run-turn's, and the BFL append-only audit invariant on
|
||||
* agent_messages holds (no UPDATE/DELETE policy exists on that table).
|
||||
*
|
||||
* Only the general.help intent uses this path. Tool-loop intents
|
||||
* (categorization, invoice draft, supplier review) still go through
|
||||
* run-turn.ts because they stage operations and need the tool loop.
|
||||
*/
|
||||
|
||||
/** The only intent the single-call console persists under. */
|
||||
export const CHAT_INTENT_ID = 'general.help'
|
||||
|
||||
// How much of a thread the model sees on each turn. Bounded because every
|
||||
// resumed turn replays it: a long-lived thread must not grow the prompt
|
||||
// without limit, and a local model may have a small context window. The
|
||||
// newest turns win; the tail that fits is what the model gets.
|
||||
export const HISTORY_MAX_MESSAGES = 16
|
||||
export const HISTORY_MAX_CHARS = 10_000
|
||||
// One turn is clamped too so a single pasted wall of text cannot eat the
|
||||
// whole budget on its own.
|
||||
const HISTORY_MAX_TURN_CHARS = 3_000
|
||||
|
||||
// The sidebar caches a one-line preview per row; the title is the sidebar
|
||||
// label. Both are bounded so a long first question can't bloat the row.
|
||||
const PREVIEW_MAX = 200
|
||||
const TITLE_MAX = 80
|
||||
|
||||
/** Truncate on a whole-grapheme boundary is overkill here; a hard slice with an ellipsis is fine for a preview. */
|
||||
function clamp(text: string, max: number): string {
|
||||
const t = text.trim().replace(/\s+/g, ' ')
|
||||
if (t.length <= max) return t
|
||||
return `${t.slice(0, max - 1).trimEnd()}…`
|
||||
}
|
||||
|
||||
function textBlocks(text: string): { type: 'text'; text: string }[] {
|
||||
return [{ type: 'text', text }]
|
||||
}
|
||||
|
||||
export type ResolveConversationResult =
|
||||
| { ok: true; conversationId: string; created: boolean }
|
||||
// The client passed a conversation id that isn't this user's general.help
|
||||
// thread in this company. Same outcome as "doesn't exist": a 404, never a
|
||||
// 403 that would confirm someone else's id is real.
|
||||
| { ok: false; reason: 'not_found' }
|
||||
|
||||
/**
|
||||
* Resolve the conversation to append this turn to.
|
||||
*
|
||||
* With no id, create a fresh general.help conversation titled from the first
|
||||
* question. With an id, verify ownership the same way /api/agent/invoke does:
|
||||
* RLS on agent_conversations is COMPANY-scoped, so a colleague's thread would
|
||||
* otherwise load; the user_id + company_id + intent_id checks close that.
|
||||
*/
|
||||
export async function resolveChatConversation(
|
||||
supabase: SupabaseClient,
|
||||
userId: string,
|
||||
companyId: string,
|
||||
conversationId: string | null | undefined,
|
||||
firstQuestion: string,
|
||||
contextRef?: string | null,
|
||||
): Promise<ResolveConversationResult> {
|
||||
if (conversationId) {
|
||||
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 !== userId ||
|
||||
conv.company_id !== companyId ||
|
||||
conv.intent_id !== CHAT_INTENT_ID
|
||||
) {
|
||||
return { ok: false, reason: 'not_found' }
|
||||
}
|
||||
return { ok: true, conversationId: conv.id as string, created: false }
|
||||
}
|
||||
|
||||
const { data: created, error } = await supabase
|
||||
.from('agent_conversations')
|
||||
.insert({
|
||||
company_id: companyId,
|
||||
user_id: userId,
|
||||
intent_id: CHAT_INTENT_ID,
|
||||
context_ref: contextRef ?? null,
|
||||
title: clamp(firstQuestion, TITLE_MAX) || 'Fråga din assistent',
|
||||
})
|
||||
.select('id')
|
||||
.single()
|
||||
if (error || !created) throw error ?? new Error('Failed to create conversation')
|
||||
return { ok: true, conversationId: created.id as string, created: true }
|
||||
}
|
||||
|
||||
/** Append the user's question as a persisted turn (append-only). */
|
||||
export async function persistUserTurn(
|
||||
supabase: SupabaseClient,
|
||||
conversationId: string,
|
||||
question: string,
|
||||
): Promise<void> {
|
||||
const { error } = await supabase.from('agent_messages').insert({
|
||||
conversation_id: conversationId,
|
||||
role: 'user',
|
||||
content: textBlocks(question),
|
||||
})
|
||||
if (error) throw error
|
||||
}
|
||||
|
||||
/**
|
||||
* Append the assistant's answer and roll the conversation row forward so the
|
||||
* sidebar shows this thread at the top with a fresh preview. run-turn updates
|
||||
* the same two columns on every assistant turn; we mirror that exactly.
|
||||
*/
|
||||
export async function persistAssistantTurn(
|
||||
supabase: SupabaseClient,
|
||||
conversationId: string,
|
||||
answer: string,
|
||||
): Promise<void> {
|
||||
const { error: msgErr } = await supabase.from('agent_messages').insert({
|
||||
conversation_id: conversationId,
|
||||
role: 'assistant',
|
||||
content: textBlocks(answer),
|
||||
})
|
||||
if (msgErr) throw msgErr
|
||||
|
||||
// Best-effort: a failed roll-forward only mis-sorts the sidebar row, it does
|
||||
// not lose the answer (already persisted above). Do not fail the request on it.
|
||||
await supabase
|
||||
.from('agent_conversations')
|
||||
.update({
|
||||
last_message_at: new Date().toISOString(),
|
||||
last_message_preview: clamp(answer, PREVIEW_MAX),
|
||||
})
|
||||
.eq('id', conversationId)
|
||||
}
|
||||
|
||||
/** Plain text of a stored Anthropic-shaped content array; empty for tool-only rows. */
|
||||
function textOfContent(content: unknown): string {
|
||||
if (typeof content === 'string') return content.trim()
|
||||
if (!Array.isArray(content)) return ''
|
||||
return content
|
||||
.filter(
|
||||
(b): b is { type: 'text'; text: string } =>
|
||||
!!b && typeof b === 'object' && (b as { type?: unknown }).type === 'text' && typeof (b as { text?: unknown }).text === 'string',
|
||||
)
|
||||
.map((b) => b.text)
|
||||
.join('\n')
|
||||
.trim()
|
||||
}
|
||||
|
||||
function clampTurn(text: string): string {
|
||||
if (text.length <= HISTORY_MAX_TURN_CHARS) return text
|
||||
return `${text.slice(0, HISTORY_MAX_TURN_CHARS).trimEnd()}…`
|
||||
}
|
||||
|
||||
/**
|
||||
* The earlier turns of a thread, as the model should see them.
|
||||
*
|
||||
* This is what makes a resumed thread a conversation rather than a series of
|
||||
* unrelated questions: without it every turn was answered blind, so a
|
||||
* follow-up ("och förra månaden?") got "vad syftar du på?". Only the
|
||||
* conversation's own rows are read (the caller has already proven ownership
|
||||
* via resolveChatConversation).
|
||||
*
|
||||
* Shape rules, so both AI adapters can send the result as-is:
|
||||
* - text only: tool_use / tool_result rows from the old streaming runtime
|
||||
* carry no prose, and hidden rows are prompt-template scaffolding, never
|
||||
* something the user said; both are dropped.
|
||||
* - alternating, starting with a user turn: consecutive same-role turns are
|
||||
* merged (a question whose answer failed sits next to its retry), and a
|
||||
* leading assistant turn (its question fell off the window) is dropped.
|
||||
* - bounded: newest HISTORY_MAX_MESSAGES rows, then trimmed from the oldest
|
||||
* end until the text fits HISTORY_MAX_CHARS.
|
||||
*/
|
||||
export async function loadChatHistory(
|
||||
supabase: SupabaseClient,
|
||||
conversationId: string,
|
||||
): Promise<AiChatTurn[]> {
|
||||
const { data, error } = await supabase
|
||||
.from('agent_messages')
|
||||
.select('role, content, hidden, created_at')
|
||||
.eq('conversation_id', conversationId)
|
||||
.order('created_at', { ascending: false })
|
||||
.order('id', { ascending: false })
|
||||
.limit(HISTORY_MAX_MESSAGES)
|
||||
if (error) throw error
|
||||
|
||||
const rows = (data ?? []) as { role: string; content: unknown; hidden?: boolean | null }[]
|
||||
const turns: AiChatTurn[] = []
|
||||
// Oldest first from here on.
|
||||
for (const row of rows.slice().reverse()) {
|
||||
if (row.hidden) continue
|
||||
if (row.role !== 'user' && row.role !== 'assistant') continue
|
||||
const text = textOfContent(row.content)
|
||||
if (!text) continue
|
||||
const clamped = clampTurn(text)
|
||||
const last = turns[turns.length - 1]
|
||||
if (last && last.role === row.role) {
|
||||
last.text = clampTurn(`${last.text}\n\n${clamped}`)
|
||||
} else {
|
||||
turns.push({ role: row.role, text: clamped })
|
||||
}
|
||||
}
|
||||
|
||||
// Trim from the oldest end until the total fits, then make sure what is
|
||||
// left opens with the user.
|
||||
let total = turns.reduce((n, t) => n + t.text.length, 0)
|
||||
while (turns.length > 0 && total > HISTORY_MAX_CHARS) {
|
||||
total -= turns[0].text.length
|
||||
turns.shift()
|
||||
}
|
||||
while (turns.length > 0 && turns[0].role !== 'user') turns.shift()
|
||||
return turns
|
||||
}
|
||||
@@ -1,130 +0,0 @@
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
import { getDeadlinesNeedingAttention } from '@/lib/deadlines/status-engine'
|
||||
import {
|
||||
loadActiveEmployeeCount,
|
||||
resolveEmployeeFacts,
|
||||
type EmployeeVerdict,
|
||||
} from '@/lib/agent/composer/employee-facts'
|
||||
import { loadFiscalYearInventory, renderFiscalYearInventory } from '@/lib/agent/fiscal-years'
|
||||
|
||||
/**
|
||||
* A compact, always-on grounding block for the single-call assistant.
|
||||
*
|
||||
* This is the reliability backstop for the "MCP tools + snapshot" design: it
|
||||
* lets a model that does NOT call tools (a weaker local model, or one whose
|
||||
* function-calling is off) still answer the standing-status questions from
|
||||
* this block alone. It carries the company's standing profile and the
|
||||
* deadlines that need attention: it deliberately does NOT carry figures
|
||||
* (result, expenses, VAT amounts, transactions), which come from the read
|
||||
* tools so they are always live and never stale in a prompt.
|
||||
*
|
||||
* Company-scoped: reads only this company's own rows. Every part is
|
||||
* best-effort: a slow or failing query drops that line, never the answer.
|
||||
*/
|
||||
|
||||
function accountingMethodLabel(method: string | null | undefined): string | null {
|
||||
if (!method) return null
|
||||
const m = method.toLowerCase()
|
||||
if (m.includes('cash') || m.includes('kontant')) return 'kontantmetod'
|
||||
if (m.includes('accrual') || m.includes('faktura')) return 'fakturametod'
|
||||
return method
|
||||
}
|
||||
|
||||
/**
|
||||
* The salary part of the status line, or null when nothing is known.
|
||||
*
|
||||
* company_settings.pays_salaries is NOT NULL DEFAULT false and its only
|
||||
* writer is the Skatt settings form, so `false` is what every company that
|
||||
* never opened that form reads, whatever its ledger says. Stating "betalar
|
||||
* inte löner" from that default told a payroll-running aktiebolag in every
|
||||
* answer that it had no salaries (support case 2026-09-04). The same doctrine
|
||||
* as the composer (lib/agent/composer/employee-facts.ts): positive evidence
|
||||
* (active employees, the flag, an attested employer registration) yields the
|
||||
* fact, only an attested negative yields the negative, and the default
|
||||
* yields nothing.
|
||||
*/
|
||||
function salaryPart(verdict: EmployeeVerdict): string | null {
|
||||
switch (verdict.kind) {
|
||||
case 'count':
|
||||
return `betalar löner (${verdict.count} ${verdict.count === 1 ? 'anställd' : 'anställda'})`
|
||||
case 'employer':
|
||||
return verdict.isEmployer ? 'betalar löner' : 'betalar inte löner'
|
||||
default:
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export async function buildAssistantSnapshot(
|
||||
supabase: SupabaseClient,
|
||||
companyId: string,
|
||||
): Promise<string> {
|
||||
const lines: string[] = []
|
||||
// Kicked off with the first round so it costs no extra latency; never rejects.
|
||||
const fiscalYears = loadFiscalYearInventory(supabase, companyId)
|
||||
|
||||
try {
|
||||
const [{ data }, activeEmployees] = await Promise.all([
|
||||
supabase
|
||||
.from('company_settings')
|
||||
.select('vat_registered, moms_period, accounting_method, pays_salaries, employer_registered')
|
||||
.eq('company_id', companyId)
|
||||
.maybeSingle(),
|
||||
loadActiveEmployeeCount(supabase, companyId),
|
||||
])
|
||||
const row = data as {
|
||||
vat_registered?: boolean | null
|
||||
moms_period?: string | null
|
||||
accounting_method?: string | null
|
||||
pays_salaries?: boolean | null
|
||||
employer_registered?: boolean | null
|
||||
} | null
|
||||
if (row) {
|
||||
const parts: string[] = []
|
||||
parts.push(
|
||||
row.vat_registered
|
||||
? `momsregistrerad${row.moms_period ? ` (momsperiod: ${row.moms_period})` : ''}`
|
||||
: 'ej momsregistrerad',
|
||||
)
|
||||
const method = accountingMethodLabel(row.accounting_method)
|
||||
if (method) parts.push(`bokföringsmetod: ${method}`)
|
||||
const salary = salaryPart(
|
||||
resolveEmployeeFacts({
|
||||
activeEmployees,
|
||||
ticEmployeeRange: null,
|
||||
employerRegistered: row.employer_registered ?? null,
|
||||
paysSalaries: row.pays_salaries ?? null,
|
||||
}),
|
||||
)
|
||||
if (salary) parts.push(salary)
|
||||
lines.push(`Status: ${parts.join(', ')}.`)
|
||||
// So the model can point the user at the right page instead of
|
||||
// "inställningarna" in general when a value here is wrong.
|
||||
lines.push(
|
||||
'Grunduppgifterna ovan ändras under Inställningar > Skatt (moms, löner) och Inställningar > Bokföring (bokföringsmetod).',
|
||||
)
|
||||
}
|
||||
} catch {
|
||||
// best-effort: skip the status line
|
||||
}
|
||||
|
||||
try {
|
||||
const { overdue, actionNeeded } = await getDeadlinesNeedingAttention(supabase, companyId)
|
||||
const soon = [...overdue, ...actionNeeded].slice(0, 6)
|
||||
if (soon.length > 0) {
|
||||
lines.push(
|
||||
`Deadlines som behöver åtgärd: ${soon
|
||||
.map((d) => `${d.title} (${d.due_date})`)
|
||||
.join('; ')}.`,
|
||||
)
|
||||
}
|
||||
} catch {
|
||||
// best-effort: skip the deadlines line
|
||||
}
|
||||
|
||||
// Which years the ledger holds and how to address them: a company with
|
||||
// several imported years otherwise reads as single-year (#2185).
|
||||
const fiscalYearLine = renderFiscalYearInventory(await fiscalYears)
|
||||
if (fiscalYearLine) lines.push(fiscalYearLine)
|
||||
|
||||
return lines.join('\n')
|
||||
}
|
||||
Reference in New Issue
Block a user