Files
accounted/extensions/general/document-extraction/__tests__/handler.test.ts
T
c7a75d069d feat(ai): job-shaped AI service with OpenAI-compatible backend, extraction-first; stop extracting every inbox document twice (#1740)
* feat(ai): job-shaped AI service with OpenAI-compatible backend, extraction-first; stop extracting every inbox document twice

Sovereign plan WS1 PR1 (#1406 Tier 2, extraction-first, aligned with the
AI surface audit).

lib/ai grows a job-shaped service (generateText / generateStructured /
extractFromDocument; no streaming members yet, see plan rule R3):
- services/anthropic-family delegates to the existing createAiClient()
  and sends the exact request literals the inbox extractor sent before
  (request-shape tests deep-equal them), so hosted Bedrock stays
  byte-identical.
- services/openai-compatible talks to any chat-completions endpoint
  (BYO Swedish provider) via Vercel AI SDK 6.x, exact-pinned and
  guarded: images as parts, PDFs rasterized with poppler (AI_PDF_MODE)
  or sent natively, AI_VISION / AI_STRICT_JSON declared, honest skips
  (ai_no_vision, pdf_rasterizer_missing) instead of fake failures.
- config.ts: AI_PROVIDER/AI_BASE_URL/AI_API_KEY/AI_MODEL and per-tier
  AI_*_MODEL with the legacy BEDROCK_* names kept as the same overrides;
  getAiStatus() is the single source of truth for "is AI wired up".
- provider.ts: openai-compatible in the auto-detect chain (after Bedrock
  and the direct API); createAiClient() refuses it loudly.

Document extraction moves onto the service and gets the audit's fixes:
- Inbox documents were extracted TWICE (pipeline A ran inside
  uploadDocument() before the inbox row existed, so its dedupe branch
  never fired; 3 707 + 1 666 calls / 30 d). The inbox now declares
  extractionOwner on the upload, the extension yields, and the inbox
  mirrors its single outcome onto document_attachments from every
  writer (sync, deferred, attach, retry, MCP).
- Every "no extraction will ever happen" outcome is stamped
  (skipped:no_ai_entitlement / ai_unconfigured / system_generated /
  ...); the status route maps the quiet ones to 'disabled' on the first
  poll instead of a 30 s client timeout. Prod showed 309 of the 327
  never-extracted uploads were the paywall working silently.
- Self-generated documents (our own invoice PDFs, payout files) are no
  longer OCR'd.
- Agent invoke answers 503 ai_unconfigured when the deployment has no
  assistant backend, distinct from the paywall.

Guard: new direct-ai-client antipattern check (shrink-only allowlist of
the pre-abstraction SDK callers) plus exact pins for @anthropic-ai/sdk,
ai and @ai-sdk/openai-compatible.

Verified: 15 958 unit tests green, guards, lint ratchet, typecheck, and a
live smoke against hosted Bedrock through the new service (ping, streamed
tool turn, thinking+cache, PDF extraction).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat(ai): make AI_API_KEY optional for OpenAI-compatible endpoints (keyless local model servers)

A local model server (llama.cpp's server, Ollama /v1, LM Studio, vLLM)
usually has no auth. Before, the OpenAI-compatible backend required both
AI_BASE_URL and AI_API_KEY to count as configured, so running Accounted on a
local model meant setting a meaningless placeholder key.

- resolveAiProvider / hasAiCredentials: a base URL alone is now enough.
- services/openai-compatible: only send Authorization: Bearer when AI_API_KEY
  is set, so a keyless server is never handed an empty bearer; a hosted
  provider that needs a key still sets it.
- Docs (SELF-HOSTING Option 3: local-model example, key marked optional),
  DECISIONS.

Verified: with no AI_API_KEY, just AI_BASE_URL + AI_MODEL, getAiStatus()
reports configured=true / provider=openai-compatible (live). lib/ai suite
71 green; tsc, guards, lint clean. Bedrock/Anthropic logic unchanged.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Jakob Wennberg <311770904+jakobwennberg-oss@users.noreply.github.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-20 19:39:08 +02:00

159 lines
6.5 KiB
TypeScript

import { describe, it, expect, vi, beforeEach } from 'vitest'
import { createQueuedMockSupabase } from '@/tests/helpers'
const { supabase, enqueue, reset, findCalls } = createQueuedMockSupabase()
vi.mock('@/lib/supabase/server', () => ({
createServiceClient: () => supabase,
}))
const extractMock = vi.fn()
vi.mock('@/extensions/general/invoice-inbox/lib/extract-invoice-fields', () => ({
extractInvoiceFields: (...args: unknown[]) => extractMock(...args),
}))
const hasCapabilityMock = vi.fn()
vi.mock('@/lib/entitlements/has-capability', () => ({
hasCapability: (...args: unknown[]) => hasCapabilityMock(...args),
}))
const aiStatusMock = vi.fn()
vi.mock('@/lib/ai', () => ({
getAiStatus: () => aiStatusMock(),
}))
import { documentExtractionExtension } from '../index'
const handler = documentExtractionExtension.eventHandlers![0].handler
function doc(overrides: Record<string, unknown> = {}) {
return {
id: 'doc-1',
company_id: 'company-1',
file_name: 'kvitto.pdf',
mime_type: 'application/pdf',
storage_path: 'company-1/user-1/kvitto.pdf',
upload_source: 'file_upload',
...overrides,
}
}
function payload(overrides: Record<string, unknown> = {}, document = doc()) {
return { document, userId: 'user-1', companyId: 'company-1', ...overrides }
}
/** extraction_model of the LAST document_attachments update, or undefined. */
function lastStamp(): string | undefined {
const updates = findCalls('document_attachments', 'update')
const last = updates[updates.length - 1]?.[0] as { extraction_model?: string } | undefined
return last?.extraction_model
}
beforeEach(() => {
vi.clearAllMocks()
reset()
aiStatusMock.mockReturnValue({ configured: true, assistantAvailable: true })
hasCapabilityMock.mockResolvedValue(true)
extractMock.mockResolvedValue({
data: { supplier: { name: 'Elgiganten' } },
rawText: '{"supplier":{"name":"Elgiganten"}}',
model: 'eu.anthropic.claude-sonnet-5',
})
})
describe('document-extraction handler', () => {
// THE dedupe: inbox-owned documents are extracted (and mirrored) by the
// inbox itself. The handler used to race it and pay a second model call.
it('yields entirely when the inbox owns extraction', async () => {
await handler(payload({ extractionOwner: 'invoice-inbox' }))
expect(supabase.from).not.toHaveBeenCalled()
expect(extractMock).not.toHaveBeenCalled()
})
it('stamps unsupported types from the payload without reading the row', async () => {
enqueue({ data: null }) // the stamp update
await handler(payload({}, doc({ mime_type: 'application/json' })))
expect(findCalls('document_attachments', 'select')).toHaveLength(0)
expect(lastStamp()).toBe('skipped:unsupported_mime')
expect(extractMock).not.toHaveBeenCalled()
})
// Our own invoice PDFs, payout files, filings: nothing to read, paid calls
// to waste (on hosted and on a BYO-key self-host).
it('stamps system-generated documents instead of extracting them', async () => {
enqueue({ data: null })
await handler(payload({}, doc({ upload_source: 'system' })))
expect(lastStamp()).toBe('skipped:system_generated')
expect(extractMock).not.toHaveBeenCalled()
})
it('does nothing for a row that was already attempted', async () => {
enqueue({ data: { id: 'doc-1', mime_type: 'application/pdf', storage_path: 'p', extracted_at: '2026-08-20T00:00:00Z' } })
await handler(payload())
expect(findCalls('document_attachments', 'update')).toHaveLength(0)
expect(extractMock).not.toHaveBeenCalled()
})
// Self-host without an AI key: stamp so the status route answers
// 'disabled' on the first poll instead of after a 30 s timeout.
it('stamps ai_unconfigured when the deployment has no AI', async () => {
aiStatusMock.mockReturnValue({ configured: false, assistantAvailable: false })
enqueue({ data: { id: 'doc-1', mime_type: 'application/pdf', storage_path: 'p', extracted_at: null } })
enqueue({ data: null })
await handler(payload())
expect(lastStamp()).toBe('skipped:ai_unconfigured')
expect(hasCapabilityMock).not.toHaveBeenCalled()
expect(extractMock).not.toHaveBeenCalled()
})
// The paywall, made visible: 309 of the 327 never-extracted uploads in a
// 30-day prod window belonged to companies without the ai capability.
it('stamps no_ai_entitlement for companies without the ai capability', async () => {
hasCapabilityMock.mockResolvedValue(false)
enqueue({ data: { id: 'doc-1', mime_type: 'application/pdf', storage_path: 'p', extracted_at: null } })
enqueue({ data: null })
await handler(payload())
expect(lastStamp()).toBe('skipped:no_ai_entitlement')
expect(extractMock).not.toHaveBeenCalled()
})
it('stamps a storage download failure', async () => {
enqueue({ data: { id: 'doc-1', mime_type: 'application/pdf', storage_path: 'p', extracted_at: null } })
enqueue({ data: null })
supabase.storage.from.mockReturnValueOnce({
download: vi.fn().mockResolvedValue({ data: null, error: { message: 'boom' } }),
})
await handler(payload())
expect(lastStamp()).toBe('failed:storage_download')
expect(extractMock).not.toHaveBeenCalled()
})
it('persists the result with the model that answered', async () => {
enqueue({ data: { id: 'doc-1', mime_type: 'application/pdf', storage_path: 'p', extracted_at: null } })
enqueue({ data: null })
await handler(payload())
expect(extractMock).toHaveBeenCalledWith(expect.objectContaining({ mimeType: 'application/pdf', fileName: 'kvitto.pdf' }))
const updates = findCalls('document_attachments', 'update')
expect(updates[updates.length - 1][0]).toMatchObject({
extracted_data: { supplier: { name: 'Elgiganten' } },
extraction_model: 'eu.anthropic.claude-sonnet-5',
})
})
it('stamps the skip reason the extractor reports (no vision, rasterizer missing, ...)', async () => {
extractMock.mockResolvedValue({ data: {}, rawText: null, skipped: 'pdf_rasterizer_missing' })
enqueue({ data: { id: 'doc-1', mime_type: 'application/pdf', storage_path: 'p', extracted_at: null } })
enqueue({ data: null })
await handler(payload())
expect(lastStamp()).toBe('skipped:pdf_rasterizer_missing')
})
it('stamps failed:no_raw_text when the model call produced nothing parseable', async () => {
extractMock.mockResolvedValue({ data: {}, rawText: null })
enqueue({ data: { id: 'doc-1', mime_type: 'application/pdf', storage_path: 'p', extracted_at: null } })
enqueue({ data: null })
await handler(payload())
expect(lastStamp()).toBe('failed:no_raw_text')
})
})