feat(llm-parse): read a photo, as a booking or as a receipt in Costs

Whether the AI Parsing model reads images is an admin setting now, and it
lands with the two features that send a photo, so it has something to
control.

The setting is `vision: 'auto' | 'on' | 'off'` on the addon config. On
Automatic a local Ollama is asked what the model can do (`/api/show`), and a
cloud provider means no; Yes and No are applied as set. The old `multimodal`
flag is not read: the admin screens wrote it false on every save, so a
stored false meant nothing. The per-user toggle keeps its on/off meaning and
is read by the extraction now. The lookup is server-side only: capped read,
validated body, never throws, cached per server and model.
GET /api/llm/capabilities answers it for the signed-in caller, and both
photo pickers below ask it.

The booking import takes JPG, PNG and WEBP when the model reads images.
The photo goes as an image to every provider (image_url, an Anthropic image
block, Ollama's native chat with `images`), capped at 1600px, and skips KDE
Itinerary. A scanned PDF, which used to reach the model as empty text, has
its first two pages drawn by pdf-parse and sent the same way. The rest is
the import as it was: background job, review, the file attached to the
booking, the linked cost. On a real qwen3.5:4b a train ticket came back as
bare clock times until the router gave the model every type's field
meanings, and its price as an object inside a string, which read as 4900;
both are handled.

Costs gets Scan receipt: a dialog laid out like the booking import's takes
one photo, read on the import job queue, then reviewed in the existing
expense editor pre-filled with merchant, total, currency, day and lines,
the photo waiting in Receipts & Invoices to be uploaded on save. No table,
no migration, no category guess, no document-type detection.
This commit is contained in:
RemEx
2026-09-24 17:12:54 +00:00
committed by Maurice
parent 706c6c3959
commit b1c05bca83
183 changed files with 3098 additions and 218 deletions
@@ -197,3 +197,38 @@ describe('BookingImportModal', () => {
expect(onClose).toHaveBeenCalledTimes(1);
});
});
describe('BookingImportModal with a model that reads images', () => {
const jpg = () => new File(['jpeg'], 'ticket.jpg', { type: 'image/jpeg' });
it('FE-PLANNER-BOOKIMP-020: offers photos, and imports one with AI, when the model reads images', async () => {
let mode: string | null = null;
server.use(
http.get('/api/health/features', () => HttpResponse.json({ bookingImport: true, aiParsing: true })),
http.get('/api/llm/capabilities', () => HttpResponse.json({ images: true })),
http.post('/api/trips/4/reservations/import/booking/async', async ({ request }) => {
mode = (await readMultipart(request)).fields.mode ?? null;
return HttpResponse.json({ jobId: 'job-2' });
}),
);
render(<BookingImportModal {...defaultProps} kind="transports" />);
expect(await screen.findByText(/Photos \(JPG, PNG, WEBP\) are read by the AI model\./)).toBeInTheDocument();
expect(fileInput().accept).toContain('.jpg');
fireEvent.change(fileInput(), { target: { files: [jpg()] } });
expect(screen.getByText('ticket.jpg')).toBeInTheDocument();
await userEvent.click(screen.getByRole('button', { name: 'Import' }));
await waitFor(() => expect(useBackgroundTasksStore.getState().tasks.find(t => t.id === 'job-2')).toMatchObject({ kind: 'transports' }));
expect(mode).toBe('fallback-on-empty');
});
it('FE-PLANNER-BOOKIMP-021: refuses a photo while the model reads no images', async () => {
server.use(http.get('/api/llm/capabilities', () => HttpResponse.json({ images: false })));
render(<BookingImportModal {...defaultProps} />);
await waitFor(() => expect(fileInput().accept).not.toContain('.jpg'));
fireEvent.change(fileInput(), { target: { files: [jpg()] } });
expect(screen.getByText('Unsupported file format. Use EML, PDF, PKPass, HTML, or TXT.')).toBeInTheDocument();
expect(screen.queryByText(/Photos \(JPG/)).not.toBeInTheDocument();
});
});
@@ -3,6 +3,8 @@ import { useState, useRef, useEffect } from 'react'
import { Upload, X } from 'lucide-react'
import { useTranslation } from '../../i18n'
import { reservationsApi, healthApi } from '../../api/client'
import { llmRepo } from '../../repo/llmRepo'
import { LLM_PHOTO_EXTENSIONS } from '@trek/shared'
import { useBackgroundTasksStore } from '../../store/backgroundTasksStore'
import { saveImportFiles } from '../../db/offlineDb'
@@ -36,6 +38,9 @@ export default function BookingImportModal({ isOpen, onClose, tripId, kind }: Bo
const [loading, setLoading] = useState(false)
const [error, setError] = useState('')
const [aiParsing, setAiParsing] = useState(false)
const [readsPhotos, setReadsPhotos] = useState(false)
// Only a model that reads images can do anything with a photo, so photos are offered only then.
const acceptedExts: readonly string[] = readsPhotos ? [...ACCEPTED_EXTS, ...LLM_PHOTO_EXTENSIONS] : ACCEPTED_EXTS
const reset = () => {
setFiles([])
@@ -53,13 +58,14 @@ export default function BookingImportModal({ isOpen, onClose, tripId, kind }: Bo
useEffect(() => {
if (!isOpen) return
healthApi.features().then((f) => setAiParsing(!!f.aiParsing)).catch(() => setAiParsing(false))
llmRepo.readsPhotos().then(setReadsPhotos).catch(() => setReadsPhotos(false))
}, [isOpen])
const handleClose = () => { reset(); onClose() }
const validateFile = (f: File): string | null => {
const ext = ('.' + f.name.toLowerCase().split('.').pop()) as string
if (!ACCEPTED_EXTS.includes(ext)) return t('reservations.import.unsupportedFormat')
if (!acceptedExts.includes(ext)) return t('reservations.import.unsupportedFormat')
if (f.size > MAX_FILE_BYTES) return t('reservations.import.fileTooLarge', { name: f.name })
return null
}
@@ -143,12 +149,13 @@ export default function BookingImportModal({ isOpen, onClose, tripId, kind }: Bo
<div style={{ flex: 1, overflowY: 'auto', minHeight: 0 }}>
<div style={{ fontSize: 'calc(12px * var(--fs-scale-body, 1))', color: 'var(--text-faint)', marginBottom: 14, lineHeight: 1.45 }}>
{t('reservations.import.acceptedFormats')}
{readsPhotos && <> {t('reservations.import.acceptedPhotos')}</>}
</div>
<input
ref={fileInputRef}
type="file"
accept={ACCEPTED_EXTS.join(',')}
accept={acceptedExts.join(',')}
multiple
style={{ display: 'none' }}
onChange={handleInputChange}