Skip to content

armgit / TREK

Public Imported from GitHub
0

The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.

fix(llm-parse): harden photo reading and finish the receipt scan

Maurice237f42a4938a
diff --git a/client/src/components/Admin/AddonManager.test.tsx b/client/src/components/Admin/AddonManager.test.tsx
index 88094b9d4..739bb1b71 100644
--- a/client/src/components/Admin/AddonManager.test.tsx
+++ b/client/src/components/Admin/AddonManager.test.tsx
@@ -1,4 +1,4 @@
-// FE-ADMIN-ADDON-001 to FE-ADMIN-ADDON-037
+// FE-ADMIN-ADDON-001 to FE-ADMIN-ADDON-039
import { render, screen, waitFor } from '../../../tests/helpers/render';
import userEvent from '@testing-library/user-event';
import { delay, http, HttpResponse } from 'msw';
@@ -769,7 +769,7 @@ describe('AddonManager', () => {
});
});
- it('FE-ADMIN-ADDON-035: whether the model reads images is auto, on or off, kept as stored and saved as chosen', async () => {
+ it('FE-ADMIN-ADDON-038: whether the model reads images is auto, on or off, kept as stored and saved as chosen', async () => {
const user = userEvent.setup();
const bodies: unknown[] = [];
server.use(
@@ -792,7 +792,7 @@ describe('AddonManager', () => {
expect(bodies[0]).not.toHaveProperty('config.multimodal');
});
- it('FE-ADMIN-ADDON-036: with the local provider the hint says Automatic asks the server', async () => {
+ it('FE-ADMIN-ADDON-039: with the local provider the hint says Automatic asks the server', async () => {
server.use(addonsRoute([llmAddon({ provider: 'local', model: 'qwen3.5:4b' })]), modelsRoute([]));
render(<AddonManager />);
expect(await screen.findByText('Automatic asks the Ollama server whether this model reads images.')).toBeInTheDocument();
diff --git a/client/src/components/BackgroundTasks/BackgroundTasksWidget.extra.test.tsx b/client/src/components/BackgroundTasks/BackgroundTasksWidget.extra.test.tsx
index 4ba36c96b..d77fbabcc 100644
--- a/client/src/components/BackgroundTasks/BackgroundTasksWidget.extra.test.tsx
+++ b/client/src/components/BackgroundTasks/BackgroundTasksWidget.extra.test.tsx
@@ -1,4 +1,4 @@
-// FE-W4BGT-001 to FE-W4BGT-024
+// FE-W4BGT-001 to FE-W4BGT-029
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { screen, act, waitFor } from '@testing-library/react'
import { render, fireEvent } from '../../../tests/helpers/render'
@@ -344,4 +344,12 @@ describe('BackgroundTasksWidget — a receipt scanned from Costs', () => {
render(<BackgroundTasksWidget />)
expect(await screen.findByRole('button', { name: 'Review expense' })).toBeInTheDocument()
})
+
+ it('FE-W4BGT-029: a receipt restored from a reload says it is reading the receipt until its status is back', () => {
+ // The status request stays pending (beforeEach), so the card shows the restored state.
+ useBackgroundTasksStore.setState({ tasks: [task({ kind: 'costs', label: 'bill.jpg', items: undefined })] })
+ render(<BackgroundTasksWidget />)
+ expect(screen.getByText('Reading the receipt…')).toBeInTheDocument()
+ expect(screen.queryByText('Parsing files…')).not.toBeInTheDocument()
+ })
})
diff --git a/client/src/components/BackgroundTasks/BackgroundTasksWidget.tsx b/client/src/components/BackgroundTasks/BackgroundTasksWidget.tsx
index 6240e5e55..087464442 100644
--- a/client/src/components/BackgroundTasks/BackgroundTasksWidget.tsx
+++ b/client/src/components/BackgroundTasks/BackgroundTasksWidget.tsx
@@ -19,6 +19,11 @@ function settleJob(id: string, tripId: string, result: unknown): void {
useBackgroundTasksStore.getState().setDone(id, tripId, (r?.items ?? []) as never, r?.warnings ?? [], r?.receipt)
}
+/** What a job that is still reading says: a receipt scan reads, a booking import parses. */
+function readingKey(task: BackgroundImportTask): string {
+ return task.kind === 'costs' ? 'costs.scan.reading' : 'reservations.import.parsing'
+}
+
/**
* Global, route-independent widget (bottom-right) that tracks background booking
* imports. Mounted once at the app root so it survives navigation. It listens to the
@@ -164,7 +169,7 @@ export default function BackgroundTasksWidget() {
{task.status === 'running' && (
<div style={{ fontSize: 'calc(11px * var(--fs-scale-caption, 1))', color: 'var(--text-faint)', marginTop: 1 }}>
- {t(task.kind === 'costs' ? 'costs.scan.reading' : 'reservations.import.parsing')}
+ {t(readingKey(task))}
{task.total > 1 ? ` · ${task.done}/${task.total}` : ''}
</div>
)}
@@ -172,7 +177,7 @@ export default function BackgroundTasksWidget() {
{task.status === 'done' && (
task.items === undefined ? (
// Restored from a reload; items are being re-fetched (see the poll backstop).
- <div style={{ fontSize: 'calc(11px * var(--fs-scale-caption, 1))', color: 'var(--text-faint)', marginTop: 1 }}>{t('reservations.import.parsing')}</div>
+ <div style={{ fontSize: 'calc(11px * var(--fs-scale-caption, 1))', color: 'var(--text-faint)', marginTop: 1 }}>{t(readingKey(task))}</div>
) : taskFoundSomething(task) ? (
<div>
<button type="button"
diff --git a/client/src/components/Budget/CostsPanel.test.tsx b/client/src/components/Budget/CostsPanel.test.tsx
index 8003fe279..3f7ac195a 100644
--- a/client/src/components/Budget/CostsPanel.test.tsx
+++ b/client/src/components/Budget/CostsPanel.test.tsx
@@ -1,5 +1,5 @@
// FE-COMP-COSTS: settlements surfaced inline in the Costs ledger (issue #1241)
-// FE-W5COSTS-001 to FE-W5COSTS-035: the rest of the Costs panel
+// FE-W5COSTS-001 to FE-W5COSTS-096: the rest of the Costs panel
import { render, screen, waitFor, fireEvent, within } from '../../../tests/helpers/render'
import userEvent from '@testing-library/user-event'
import { http, HttpResponse } from 'msw'
@@ -1625,7 +1625,7 @@ describe('CostsPanel — expense modal', () => {
expect(onSaved).toHaveBeenCalled()
})
- it('FE-W5COSTS-081: offers Scan receipt beside Add expense only when the AI model reads images', async () => {
+ it('FE-W5COSTS-096: offers Scan receipt beside Add expense only when the AI model reads images', async () => {
server.use(http.get('/api/llm/capabilities', () => HttpResponse.json({ images: true })))
const { unmount } = render(<CostsPanel tripId={1} tripMembers={tripMembers} />)
fireEvent.click((await screen.findAllByRole('button', { name: 'Scan receipt' }))[0])
@@ -1638,7 +1638,7 @@ describe('CostsPanel — expense modal', () => {
expect(screen.queryByRole('button', { name: 'Scan receipt' })).not.toBeInTheDocument()
})
- it('FE-W5COSTS-080: a scanned receipt opens in its own currency and day, with its photo waiting to be attached', () => {
+ it('FE-W5COSTS-095: a scanned receipt opens in its own currency and day, with its photo waiting to be attached', () => {
const photo = new File(['x'], 'bill.jpg', { type: 'image/jpeg' })
render(
<ExpenseModal tripId={1} base="EUR" people={tripMembers} me={1} editing={null}
diff --git a/client/src/components/Budget/CostsPanel.tsx b/client/src/components/Budget/CostsPanel.tsx
index 3ec72ca97..c8745f178 100644
--- a/client/src/components/Budget/CostsPanel.tsx
+++ b/client/src/components/Budget/CostsPanel.tsx
@@ -1411,11 +1411,11 @@ export function ExpenseModal({ tripId, base, people, me, editing, prefill, onClo
}, [totalNum])
const enableMultiPayer = () => {
- const seed = payerIds.size > 0 ? new Set(payerIds) : new Set<number>([payerId > 0 ? payerId : me])
+ const startPayers = payerIds.size > 0 ? new Set(payerIds) : new Set<number>([payerId > 0 ? payerId : me])
const pinned = new Set<number>()
- setPayerIds(seed)
+ setPayerIds(startPayers)
setPinnedPayers(pinned)
- setPayerAmounts(prev => rebalancePayers(prev, pinned, seed, totalNum))
+ setPayerAmounts(prev => rebalancePayers(prev, pinned, startPayers, totalNum))
setMultiPayer(true)
}
diff --git a/client/src/components/Budget/ReceiptScanModal.test.tsx b/client/src/components/Budget/ReceiptScanModal.test.tsx
index bb863762a..536730e41 100644
--- a/client/src/components/Budget/ReceiptScanModal.test.tsx
+++ b/client/src/components/Budget/ReceiptScanModal.test.tsx
@@ -1,4 +1,4 @@
-// FE-BUDGET-SCAN-001 to FE-BUDGET-SCAN-011
+// FE-BUDGET-SCAN-001 to FE-BUDGET-SCAN-010
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { http, HttpResponse } from 'msw'
import { render, screen, fireEvent, waitFor } from '../../../tests/helpers/render'
diff --git a/client/src/components/Planner/BookingImportModal.test.tsx b/client/src/components/Planner/BookingImportModal.test.tsx
index b32042be3..6874371f3 100644
--- a/client/src/components/Planner/BookingImportModal.test.tsx
+++ b/client/src/components/Planner/BookingImportModal.test.tsx
@@ -1,4 +1,4 @@
-// FE-PLANNER-BOOKIMP-001 to FE-PLANNER-BOOKIMP-014
+// FE-PLANNER-BOOKIMP-001 to FE-PLANNER-BOOKIMP-021
import { render, screen, fireEvent, waitFor } from '../../../tests/helpers/render';
import userEvent from '@testing-library/user-event';
import { http, HttpResponse } from 'msw';
diff --git a/client/src/mobile/screens/trip/sheets/MCostSheet.tsx b/client/src/mobile/screens/trip/sheets/MCostSheet.tsx
index 0c3e7acd4..b3e22bbd6 100644
--- a/client/src/mobile/screens/trip/sheets/MCostSheet.tsx
+++ b/client/src/mobile/screens/trip/sheets/MCostSheet.tsx
@@ -192,11 +192,11 @@ export default function MCostSheet({ tripId, base, people, me, editing, prefill,
}, [totalNum])
const enableMultiPayer = () => {
- const seed = payerIds.size > 0 ? new Set(payerIds) : new Set<number>([payerId > 0 ? payerId : me])
+ const startPayers = payerIds.size > 0 ? new Set(payerIds) : new Set<number>([payerId > 0 ? payerId : me])
const pinned = new Set<number>()
- setPayerIds(seed)
+ setPayerIds(startPayers)
setPinnedPayers(pinned)
- setPayerAmounts(prev => rebalancePayers(prev, pinned, seed, totalNum))
+ setPayerAmounts(prev => rebalancePayers(prev, pinned, startPayers, totalNum))
setMultiPayer(true)
}
diff --git a/client/src/mobile/screens/trip/tabs/MCostsTab.tsx b/client/src/mobile/screens/trip/tabs/MCostsTab.tsx
index 0fb55490d..64463d773 100644
--- a/client/src/mobile/screens/trip/tabs/MCostsTab.tsx
+++ b/client/src/mobile/screens/trip/tabs/MCostsTab.tsx
@@ -72,15 +72,17 @@ export default function MCostsTab({ planner, shell }: MTabScreenProps) {
}, [tripId, base, tripCurrency, displayPerTrip])
// Mirrors CostsPanel.tsx: items reload on trip change, settlement reloads on
- // trip/base change; further refreshes are explicit after each mutation below
- // (add/edit/delete expense, add payment) rather than watching budgetItems, so
- // an unrelated re-render doesn't refetch the settlement.
+ // trip/base change and when the number of expenses changes; further refreshes
+ // are explicit after each mutation below (add/edit/delete expense, add
+ // payment), so an unrelated re-render doesn't refetch the settlement. The count
+ // is for an expense saved outside this tab: a scanned receipt is reviewed in
+ // the trip sheets, which reload the items but cannot reach this settlement.
useEffect(() => {
planner.tripActions.loadBudgetItems(tripId)
}, [tripId, planner.tripActions])
useEffect(() => {
loadSettlement()
- }, [loadSettlement])
+ }, [budgetItems.length, loadSettlement])
useFreezeMissingRates({ tripId, tripCurrency, canEdit, unconverted: settlement?.unconverted, onHealed: loadSettlement })
const [search, setSearch] = useState('')
diff --git a/client/src/pages/tripPlanner/useTripPlanner.test.tsx b/client/src/pages/tripPlanner/useTripPlanner.test.tsx
index 0d9ddce9a..7915fa17f 100644
--- a/client/src/pages/tripPlanner/useTripPlanner.test.tsx
+++ b/client/src/pages/tripPlanner/useTripPlanner.test.tsx
@@ -1,4 +1,4 @@
-// FE-TP-HOOK-001 to FE-TP-HOOK-142
+// FE-TP-HOOK-001 to FE-TP-HOOK-163
import React from 'react'
import { renderHook, act, waitFor } from '@testing-library/react'
import { TranslationProvider } from '../../i18n/TranslationContext'
@@ -2162,6 +2162,26 @@ describe('useTripPlanner — a receipt scanned from Costs', () => {
await waitFor(() => expect(useBackgroundTasksStore.getState().tasks).toHaveLength(0))
expect(result.current.receiptExpense).toBeNull()
})
+
+ it('FE-TP-HOOK-163: a member who may add expenses but not upload files gets the reading without the photo', async () => {
+ // The photo goes up through the file upload on save, and a refused upload
+ // used to take the whole expense down with it.
+ seedStore(useAuthStore, { user: buildUser({ id: 2, role: 'user' }) })
+ usePermissionsStore.setState({ permissions: { file_upload: 'trip_owner' } })
+ seedTrip()
+ const photo = new File(['x'], 'bill.jpg', { type: 'image/jpeg' })
+ useBackgroundTasksStore.setState({
+ tasks: [{
+ id: 'job-u', tripId: '42', label: 'bill.jpg', status: 'done', done: 1, total: 1, kind: 'costs',
+ reviewRequested: true, items: [], receipt: RECEIPT, sourceFiles: [photo],
+ }] as never,
+ })
+
+ const { result } = await renderPlanner()
+
+ await waitFor(() => expect(result.current.receiptExpense).not.toBeNull())
+ expect(result.current.receiptExpense).toMatchObject({ name: 'Café', amount: 12.5, receiptFiles: [] })
+ })
})
describe('useTripPlanner — misc state', () => {
diff --git a/client/src/pages/tripPlanner/useTripPlanner.ts b/client/src/pages/tripPlanner/useTripPlanner.ts
index 397cdf0ce..934d0cfb5 100644
--- a/client/src/pages/tripPlanner/useTripPlanner.ts
+++ b/client/src/pages/tripPlanner/useTripPlanner.ts
@@ -2727,13 +2727,19 @@ export function useTripPlanner() {
// Lives in the hook so the page stays a pure wiring container.
const bgTasks = useBackgroundTasksStore((s) => s.tasks)
const dismissBgTask = useBackgroundTasksStore((s) => s.dismiss)
+ const loadedTripId = trip?.id
useEffect(() => {
const task = bgTasks.find(
(tk) => tk.tripId === String(tripId) && tk.status === 'done' && tk.reviewRequested && !tk.consumed,
)
if (task && task.kind === 'costs') {
// A scanned receipt is reviewed in the expense editor, pre-filled with what
- // was read and with the photo waiting to be attached when it is saved.
+ // was read and with the photo waiting to be attached when it is saved. The
+ // photo goes up through the trip's file upload, so it is only put there for
+ // someone who may upload files: for anyone else it made the whole save fail,
+ // expense included, over an attachment they never picked. Whether they may
+ // is only known once this trip is loaded, so the review waits for it.
+ if (loadedTripId !== tripId) return
const receipt = task.receipt
const jobId = task.id
const inMemory = task.sourceFiles
@@ -2742,7 +2748,7 @@ export function useTripPlanner() {
void (async () => {
const files = inMemory && inMemory.length ? inMemory : await getImportFiles(jobId)
deleteImportFiles(jobId)
- setReceiptExpense(receiptToPrefill(receipt, files))
+ setReceiptExpense(receiptToPrefill(receipt, canUploadFiles ? files : []))
})()
} else if (task && task.items && task.items.length > 0) {
// Hand the items (and the source files, to attach to each booking) to the review flow
@@ -2759,7 +2765,7 @@ export function useTripPlanner() {
startImportReview(items, files, kind)
})()
}
- }, [bgTasks, tripId, startImportReview, dismissBgTask])
+ }, [bgTasks, tripId, startImportReview, dismissBgTask, canUploadFiles, loadedTripId])
// Called when a reviewed item's modal closes (saved or skipped): open the next,
// or finish the review session and refresh accommodations.
diff --git a/client/tests/unit/mobile/admin/MAdminAddonManager.test.tsx b/client/tests/unit/mobile/admin/MAdminAddonManager.test.tsx
index 466fe9875..3840c0193 100644
--- a/client/tests/unit/mobile/admin/MAdminAddonManager.test.tsx
+++ b/client/tests/unit/mobile/admin/MAdminAddonManager.test.tsx
@@ -1,4 +1,4 @@
-// FE-MOB-AADD-001 to FE-MOB-AADD-032
+// FE-MOB-AADD-001 to FE-MOB-AADD-033
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import userEvent from '@testing-library/user-event';
import { delay, http, HttpResponse } from 'msw';
@@ -657,7 +657,7 @@ describe('MAdminAddonManager', () => {
await screen.findByText('Failed to save');
});
- it('FE-MOB-AADD-030: whether the model reads images is a three-way choice, saved as picked', async () => {
+ it('FE-MOB-AADD-033: whether the model reads images is a three-way choice, saved as picked', async () => {
const user = userEvent.setup();
const bodies: unknown[] = [];
server.use(
diff --git a/client/tests/unit/mobile/trip/MCostsTab.test.tsx b/client/tests/unit/mobile/trip/MCostsTab.test.tsx
index 504ce0549..a17c49c25 100644
--- a/client/tests/unit/mobile/trip/MCostsTab.test.tsx
+++ b/client/tests/unit/mobile/trip/MCostsTab.test.tsx
@@ -15,7 +15,7 @@ import { resetAllStores, seedStore } from '../../../helpers/store'
import { server } from '../../../helpers/msw/server'
import { fireEvent, render, screen, waitFor, within } from '../../../helpers/render'
-// FE-MOB-COSTT-001 to FE-MOB-COSTT-049
+// FE-MOB-COSTT-001 to FE-MOB-COSTT-050
// The add/edit expense sheet is the shared desktop-sized form; the panel only
// owns when it opens and what happens on save, so it is stubbed here.
@@ -874,4 +874,15 @@ describe('MCostsTab', () => {
fireEvent.click(submit)
expect(create).not.toHaveBeenCalled()
})
+
+ it('FE-MOB-COSTT-050: reads the settlement again when an expense is saved outside the tab', async () => {
+ // A scanned receipt is reviewed in the trip sheets, which reload the items only.
+ const p = planner()
+ const { rerender, shell } = await renderTab(p)
+ expect(settlementBases).toHaveLength(1)
+
+ const bread = { ...RAMEN, id: 15, name: 'Bread', total_price: 18.1 } as BudgetItem
+ rerender(<MCostsTab planner={{ ...p, budgetItems: [...ITEMS, bread] }} shell={shell} />)
+ await waitFor(() => expect(settlementBases).toHaveLength(2))
+ })
})
diff --git a/server/src/nest/llm-parse/image-input.ts b/server/src/nest/llm-parse/image-input.ts
index 75f7dc148..ddb8072a3 100644
--- a/server/src/nest/llm-parse/image-input.ts
+++ b/server/src/nest/llm-parse/image-input.ts
@@ -27,20 +27,145 @@ export const IMAGE_MAX_EDGE = 1600;
const IMAGE_JPEG_QUALITY = 82;
/**
- * The image, no larger than the model needs. Returns the bytes unchanged when
- * they are already small enough, or when they cannot be decoded (Jimp has no
- * WebP): a photo that might be read beats one refused over a failed resize.
+ * The most pixels a photo may have before it is decoded. Decoding is pure JS on
+ * the main thread, and a PNG says in its first bytes how large it inflates: a
+ * 2 MB file of one flat colour can claim 20000 x 20000, which is 1.6 GB of
+ * bitmap before a single pixel is resized. Forty megapixels is more than any
+ * phone takes by default and stays in the hundreds of megabytes.
+ */
+export const IMAGE_MAX_PIXELS = 40_000_000;
+
+/**
+ * The most bytes a photo is sent with. Anthropic refuses an image over 5 MB and
+ * base64 adds a third, so a small image that is heavy (a noisy PNG) is
+ * re-encoded as a JPEG, and one TREK cannot re-encode is refused over it.
+ */
+export const IMAGE_MAX_BYTES = Math.floor(3.5 * 1024 * 1024);
+
+/** A photo TREK will not decode or send: the message says why, for the import's warning. */
+export class ImageTooLargeError extends Error {}
+
+export interface ImageHeader {
+ mimeType: 'image/png' | 'image/jpeg' | 'image/webp';
+ width: number;
+ height: number;
+}
+
+/** JPEG start-of-frame markers: every SOFn except DHT (C4), JPG (C8) and DAC (CC). */
+function isStartOfFrame(marker: number): boolean {
+ return marker >= 0xc0 && marker <= 0xcf && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc;
+}
+
+function jpegSize(data: Buffer): { width: number; height: number } | null {
+ let i = 2;
+ while (i + 4 <= data.length) {
+ // Stray bytes between segments, which some cameras write, are stepped over.
+ if (data[i] !== 0xff) {
+ i += 1;
+ continue;
+ }
+ const marker = data[i + 1];
+ // Fill bytes, and the markers that carry no length.
+ if (marker === 0xff) {
+ i += 1;
+ continue;
+ }
+ if (marker === 0x01 || marker === 0xd8 || (marker >= 0xd0 && marker <= 0xd7)) {
+ i += 2;
+ continue;
+ }
+ // The scan or the end came before any frame header.
+ if (marker === 0xd9 || marker === 0xda) return null;
+ const length = data.readUInt16BE(i + 2);
+ if (length < 2) return null;
+ if (isStartOfFrame(marker)) {
+ if (i + 9 > data.length) return null;
+ return { height: data.readUInt16BE(i + 5), width: data.readUInt16BE(i + 7) };
+ }
+ i += 2 + length;
+ }
+ return null;
+}
+
+function webpSize(data: Buffer): { width: number; height: number } | null {
+ const chunk = data.toString('latin1', 12, 16);
+ if (chunk === 'VP8 ' && data.length >= 30) {
+ return { width: data.readUInt16LE(26) & 0x3fff, height: data.readUInt16LE(28) & 0x3fff };
+ }
+ if (chunk === 'VP8L' && data.length >= 25) {
+ const bits = data.readUInt32LE(21);
+ return { width: (bits & 0x3fff) + 1, height: ((bits >>> 14) & 0x3fff) + 1 };
+ }
+ if (chunk === 'VP8X' && data.length >= 30) {
+ return { width: data.readUIntLE(24, 3) + 1, height: data.readUIntLE(27, 3) + 1 };
+ }
+ return null;
+}
+
+/**
+ * What a photo is and how large, read from its first bytes without decoding it:
+ * PNG from IHDR, JPEG from its frame header, WebP from its VP8, VP8L or VP8X
+ * chunk. Null when the bytes are none of the three, or do not say.
+ */
+export function readImageHeader(data: Buffer): ImageHeader | null {
+ let found: ImageHeader | null = null;
+ if (data.length >= 24 && data.readUInt32BE(0) === 0x89504e47 && data.toString('latin1', 12, 16) === 'IHDR') {
+ found = { mimeType: 'image/png', width: data.readUInt32BE(16), height: data.readUInt32BE(20) };
+ } else if (data.length >= 4 && data[0] === 0xff && data[1] === 0xd8 && data[2] === 0xff) {
+ const size = jpegSize(data);
+ found = size && { mimeType: 'image/jpeg', ...size };
+ } else if (data.length >= 16 && data.toString('latin1', 0, 4) === 'RIFF' && data.toString('latin1', 8, 12) === 'WEBP') {
+ const size = webpSize(data);
+ found = size && { mimeType: 'image/webp', ...size };
+ }
+ // A zero edge is a header that defers its size (a JPEG's DNL), which says nothing.
+ return found && found.width > 0 && found.height > 0 ? found : null;
+}
+
+/** Bytes sent as they came, as long as a provider takes them at that size. */
+function asTheyCame(data: Buffer, mimeType: string): { data: Buffer; mimeType: string } {
+ if (data.length > IMAGE_MAX_BYTES) {
+ const mb = (bytes: number) => (bytes / 1024 / 1024).toFixed(1);
+ throw new ImageTooLargeError(
+ `the photo is ${mb(data.length)} MB and cannot be made smaller, a model takes at most ${mb(IMAGE_MAX_BYTES)} MB`,
+ );
+ }
+ return { data, mimeType };
+}
+
+/**
+ * The image, no larger than the model needs, typed by its bytes rather than its
+ * name: a PNG renamed to .jpg goes as the PNG it is, which Anthropic insists on.
+ *
+ * A PNG or JPEG is decoded only when its header says it is within the pixel cap,
+ * and shrunk to the long edge, or re-encoded when it is small but heavy. Bytes
+ * TREK cannot decode (WebP, or a header that says nothing) go as they came,
+ * since a photo that might be read beats one refused over a failed resize, as
+ * long as they are within the byte cap. Throws `ImageTooLargeError` for a photo
+ * over either cap; the callers turn it into a warning like any unreadable file.
*/
export async function capImage(data: Buffer, mimeType: string): Promise<{ data: Buffer; mimeType: string }> {
+ const header = readImageHeader(data);
+ if (header && header.width * header.height > IMAGE_MAX_PIXELS) {
+ throw new ImageTooLargeError(
+ `the photo is ${header.width} x ${header.height} pixels, more than the ${IMAGE_MAX_PIXELS / 1_000_000} megapixels TREK reads`,
+ );
+ }
+ if (!header || header.mimeType === 'image/webp') return asTheyCame(data, header?.mimeType ?? mimeType);
+ if (Math.max(header.width, header.height) <= IMAGE_MAX_EDGE && data.length <= IMAGE_MAX_BYTES) {
+ return { data, mimeType: header.mimeType };
+ }
try {
- const image = await Jimp.read(data);
- if (Math.max(image.width, image.height) <= IMAGE_MAX_EDGE) return { data, mimeType };
- if (image.width >= image.height) image.resize({ w: IMAGE_MAX_EDGE });
- else image.resize({ h: IMAGE_MAX_EDGE });
- const resized = await image.getBuffer('image/jpeg', { quality: IMAGE_JPEG_QUALITY });
- return { data: Buffer.from(resized), mimeType: 'image/jpeg' };
+ // jpeg-js checks the size again while it decodes, in case the file has more than one frame header.
+ const image = await Jimp.read(data, { 'image/jpeg': { maxResolutionInMP: IMAGE_MAX_PIXELS / 1_000_000 } });
+ if (Math.max(image.width, image.height) > IMAGE_MAX_EDGE) {
+ if (image.width >= image.height) image.resize({ w: IMAGE_MAX_EDGE });
+ else image.resize({ h: IMAGE_MAX_EDGE });
+ }
+ const encoded = await image.getBuffer('image/jpeg', { quality: IMAGE_JPEG_QUALITY });
+ return { data: Buffer.from(encoded), mimeType: 'image/jpeg' };
} catch {
- return { data, mimeType };
+ return asTheyCame(data, header.mimeType);
}
}
@@ -51,14 +176,31 @@ export async function capImage(data: Buffer, mimeType: string): Promise<{ data:
*/
export const PDF_PAGES_AS_IMAGES = 2;
-/** The first pages of a PDF drawn as images, capped like a photo; empty when none could be drawn. */
+/**
+ * The first pages of a PDF drawn as images, capped like a photo; empty when none could be drawn.
+ *
+ * Each page is drawn with its LONG edge at the cap, so no canvas is ever larger
+ * than a capped photo: scaled by width alone, a page of 10 x 2000 points became
+ * a canvas of 1600 x 320000 pixels. pdf.js leaves out an embedded image above the
+ * pixel cap instead of decoding it, since it decodes images only while drawing.
+ */
export async function renderPdfPages(data: Buffer): Promise<{ data: Buffer; mimeType: string }[]> {
- const parser = new PDFParse({ data: new Uint8Array(data) });
+ const parser = new PDFParse({ data: new Uint8Array(data), maxImageSize: IMAGE_MAX_PIXELS });
try {
- const shot = await parser.getScreenshot({ first: PDF_PAGES_AS_IMAGES, desiredWidth: IMAGE_MAX_EDGE, imageBuffer: true, imageDataUrl: false });
+ const info = await parser.getInfo({ first: PDF_PAGES_AS_IMAGES, parsePageInfo: true });
const pages: { data: Buffer; mimeType: string }[] = [];
- for (const page of shot.pages) {
- if (page.data?.length) pages.push(await capImage(Buffer.from(page.data), 'image/png'));
+ for (const { pageNumber, width, height } of info.pages) {
+ const longEdge = Math.max(width, height);
+ if (!Number.isFinite(longEdge) || Math.min(width, height) <= 0) continue;
+ const shot = await parser.getScreenshot({
+ partial: [pageNumber],
+ scale: IMAGE_MAX_EDGE / longEdge,
+ imageBuffer: true,
+ imageDataUrl: false,
+ });
+ for (const page of shot.pages) {
+ if (page.data?.length) pages.push(await capImage(Buffer.from(page.data), 'image/png'));
+ }
}
return pages;
} finally {
diff --git a/server/src/nest/llm-parse/llm-local.service.ts b/server/src/nest/llm-parse/llm-local.service.ts
index 77e6f3a5a..188c30ace 100644
--- a/server/src/nest/llm-parse/llm-local.service.ts
+++ b/server/src/nest/llm-parse/llm-local.service.ts
@@ -1,3 +1,4 @@
+import { createHash } from 'node:crypto';
import { Injectable, HttpException } from '@nestjs/common';
import { z } from 'zod';
import { safeFetchLlm } from '../../utils/ssrfGuard';
@@ -86,10 +87,17 @@ export class LlmLocalService {
* does not have, an answer that is not what Ollama sends. Never throws, since
* every caller treats "unknown" as "no", and remembers the answer per server
* and model so a page load does not become a request to the model server.
+ *
+ * The configured key goes along as the same Bearer header the extraction
+ * sends: an Ollama behind an auth proxy answered 401 without it, and a model
+ * the extraction could reach was never offered a photo. The answer is
+ * remembered per key too, by its hash, so a corrected key is asked afresh
+ * instead of inheriting the miss of the wrong one.
*/
- async modelCapabilities(baseUrl: string | undefined, model: string): Promise<string[] | null> {
+ async modelCapabilities(baseUrl: string | undefined, model: string, apiKey?: string): Promise<string[] | null> {
const now = Date.now();
- const key = `${baseUrl ?? ''}\n${model}`;
+ const keyHash = apiKey ? createHash('sha256').update(apiKey).digest('hex') : '';
+ const key = `${baseUrl ?? ''}\n${model}\n${keyHash}`;
const cached = this.capabilityCache.get(key);
if (cached && cached.expires > now) return cached.capabilities;
@@ -98,7 +106,10 @@ export class LlmLocalService {
const root = this.ollamaRoot(baseUrl);
const res = await safeFetchLlm(`${root}/api/show`, {
method: 'POST',
- headers: { 'content-type': 'application/json' },
+ headers: {
+ 'content-type': 'application/json',
+ ...(apiKey ? { authorization: `Bearer ${apiKey}` } : {}),
+ },
body: JSON.stringify({ model }),
signal: AbortSignal.timeout(SHOW_TIMEOUT_MS),
});
diff --git a/server/src/nest/llm-parse/llm-parse.service.ts b/server/src/nest/llm-parse/llm-parse.service.ts
index d06ebf592..a8e446b6a 100644
--- a/server/src/nest/llm-parse/llm-parse.service.ts
+++ b/server/src/nest/llm-parse/llm-parse.service.ts
@@ -14,7 +14,7 @@ import {
toReceiptRead,
} from './receipt-read';
import { buildSystemPrompt, KI_RESERVATION_JSON_SCHEMA } from './llm-prompt';
-import type { LlmExtractionInput } from './llm-provider.interface';
+import type { LlmExtractionFile, LlmExtractionInput } from './llm-provider.interface';
import { isPdf, extractText } from './text-extract';
import { routeExtraction, routeImageExtraction, detectFlightNumbers, extractTotalPrice } from './router/extraction-router';
import { toIsoCurrency } from './currency-code';
@@ -72,11 +72,18 @@ export class LlmParseService {
return { receipt: null, warnings: [`${file.originalName}: the configured model does not read images`] };
}
- const image = await capImage(file.buffer, imageType);
- const prompt = buildReceiptPrompt();
+ let image: LlmExtractionFile;
+ try {
+ image = await capImage(file.buffer, imageType);
+ } catch (err) {
+ // A photo too large to decode or to send, refused like one that cannot be read.
+ return { receipt: null, warnings: [`${file.originalName}: ${err instanceof Error ? err.message : String(err)}`] };
+ }
+ const local = config.provider === 'local';
+ const prompt = buildReceiptPrompt(new Date(), !local);
let raw: unknown;
try {
- if (config.provider === 'local') {
+ if (local) {
// Ollama's own chat API, as the booking router uses: `think: false` and
// `num_ctx` exist there and not on /v1, and a hybrid model that is left
// to reason spends the whole token budget on it and answers nothing.
@@ -119,7 +126,7 @@ export class LlmParseService {
// Only a local Ollama can be asked. A cloud model is not assumed to read
// images: an admin who knows it does says so.
if (config.provider !== 'local') return false;
- const capabilities = await this.local.modelCapabilities(config.baseUrl, config.model);
+ const capabilities = await this.local.modelCapabilities(config.baseUrl, config.model, config.apiKey);
return capabilities?.includes('vision') ?? false;
}
diff --git a/server/src/nest/llm-parse/receipt-read.ts b/server/src/nest/llm-parse/receipt-read.ts
index fefd49901..0deaab995 100644
--- a/server/src/nest/llm-parse/receipt-read.ts
+++ b/server/src/nest/llm-parse/receipt-read.ts
@@ -1,4 +1,11 @@
-import { receiptReadSchema, type ReceiptLine, type ReceiptRead } from '@trek/shared';
+import {
+ RECEIPT_AMOUNT_MAX,
+ RECEIPT_LINES_MAX,
+ RECEIPT_TEXT_MAX,
+ receiptReadSchema,
+ type ReceiptLine,
+ type ReceiptRead,
+} from '@trek/shared';
import { toIsoCurrency } from './currency-code';
import { parseAmount } from './clients/nuextract';
@@ -48,10 +55,23 @@ export const RECEIPT_LIST_JSON_SCHEMA = {
required: [RECEIPT_ROOT_KEY],
} as const;
-export function buildReceiptPrompt(today: Date = new Date()): string {
+/** One receipt as the prompt spells it out, empty the way an unread field is answered. */
+const RECEIPT_SHAPE = '{ "merchant": "", "date": "", "total": 0, "currency": "", "items": [ { "name": "", "price": 0 } ] }';
+
+/**
+ * The instructions for one receipt. `listed` is the cloud form, whose answer is
+ * wrapped as `{ "receipts": [...] }`. The prompt states that shape itself: a
+ * server that turns the schema down falls back to `json_object` or to no format
+ * at all, and then the prompt is all the model goes by, and `json_object` mode
+ * wants the word JSON in it. Without the wrapper a flat answer came back, which
+ * the cloud clients read as no receipt.
+ */
+export function buildReceiptPrompt(today: Date = new Date(), listed = false): string {
const todayIso = today.toISOString().slice(0, 10);
+ const shape = listed ? `{ "${RECEIPT_ROOT_KEY}": [ ${RECEIPT_SHAPE} ] }, with the one receipt in the list` : RECEIPT_SHAPE;
return [
'You read a photographed receipt, bill or invoice: often a paper till roll, possibly crumpled, skewed or in a foreign language.',
+ `Return ONLY a JSON object of the form ${shape}. No prose, no markdown.`,
'Fill "total" with the grand total actually paid, after tax and tip: the final TOTAL or AMOUNT DUE line, not a subtotal.',
'Fill "currency" with its ISO 4217 code, from the symbol and the country when the code is not printed.',
'Fill "merchant" with the business name printed at the top, and "date" as YYYY-MM-DD.',
@@ -68,6 +88,12 @@ function toText(value: unknown): string | null {
return typeof value === 'string' && value.trim() ? value.trim() : null;
}
+/** Text as a name the editor takes: trimmed, and cut at the length the contract allows. */
+function toName(value: unknown): string | null {
+ const text = toText(value);
+ return text ? text.slice(0, RECEIPT_TEXT_MAX).trim() : null;
+}
+
/** A real calendar date as YYYY-MM-DD, or null. */
function toDate(value: unknown): string | null {
const s = toText(value);
@@ -76,29 +102,66 @@ function toDate(value: unknown): string | null {
return !Number.isNaN(d.getTime()) && d.toISOString().slice(0, 10) === s ? s : null;
}
+function isDigit(code: number): boolean {
+ return code >= 48 && code <= 57;
+}
+
+/** The hyphen a till prints, and the typographic minus sign a model may write instead. */
+const MINUS_SIGNS = ['-', String.fromCodePoint(0x2212)];
+
+/**
+ * An amount as parseAmount reads it, with the sign parseAmount strips from text:
+ * a till prints a discount as "-2,00" or "2,00-", and read without its sign it
+ * would become a charge of 2. A Swiss till writes a whole amount as "45.-" or
+ * "45,-", where the dash stands for the cents and is no sign.
+ */
+function toAmount(value: unknown): number | null {
+ const amount = parseAmount(value);
+ if (amount === null || typeof value !== 'string') return amount;
+ const first = value.search(/\d/);
+ let last = value.length - 1;
+ while (last > first && !isDigit(value.charCodeAt(last))) last--;
+ const tail = value.slice(last + 1);
+ const wholeMark = /^[.,]\s*[-−]/.exec(tail);
+ const outside = value.slice(0, first) + (wholeMark ? tail.slice(wholeMark[0].length) : tail);
+ return MINUS_SIGNS.some((sign) => outside.includes(sign)) ? -amount : amount;
+}
+
+/** An amount a receipt can carry: above zero and within the contract's ceiling. */
+function inRange(amount: number | null): amount is number {
+ return amount !== null && amount > 0 && amount <= RECEIPT_AMOUNT_MAX;
+}
+
/**
* The model's answer as a `ReceiptRead`, or null when it holds nothing a person
* could use: no total, no merchant and no line. Each field is kept only when it
* reads as what it claims to be, so a garbled one is left for the person to fill
* rather than saved wrong.
+ *
+ * A line is kept only with a price above zero. A discount, a deposit returned
+ * or a free item would leave the Ticket split unable to save, since it takes
+ * priced lines only; the total already counts it. Names are cut to the length
+ * the contract allows and the list to its first lines, rather than losing the
+ * whole reading over one of them.
*/
export function toReceiptRead(raw: unknown): ReceiptRead | null {
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
const node = raw as Record<string, unknown>;
- const total = parseAmount(node.total);
+ const total = toAmount(node.total);
const items: ReceiptLine[] = [];
if (Array.isArray(node.items)) {
for (const line of node.items) {
+ if (items.length === RECEIPT_LINES_MAX) break;
if (!line || typeof line !== 'object') continue;
- const name = toText((line as Record<string, unknown>).name);
- const price = parseAmount((line as Record<string, unknown>).price);
- if (name && price !== null) items.push({ name, price });
+ const name = toName((line as Record<string, unknown>).name);
+ const price = toAmount((line as Record<string, unknown>).price);
+ if (name && inRange(price)) items.push({ name, price });
}
}
const read = {
- merchant: toText(node.merchant),
+ merchant: toName(node.merchant),
date: toDate(node.date),
- total: total !== null && total > 0 ? total : null,
+ total: inRange(total) ? total : null,
currency: toIsoCurrency(node.currency) ?? null,
items,
};
diff --git a/server/src/nest/reservation-import/reservation-import.controller.ts b/server/src/nest/reservation-import/reservation-import.controller.ts
index 3874d4df0..3ec73f94f 100644
--- a/server/src/nest/reservation-import/reservation-import.controller.ts
+++ b/server/src/nest/reservation-import/reservation-import.controller.ts
@@ -30,6 +30,11 @@ import { BookingImportConfirmDto, BookingImportPreviewDto } from './reservation-
import { IMAGE_EXTENSIONS, imageMimeType } from '../llm-parse/image-input';
const ACCEPTED_EXTS = new Set(['.eml', '.pdf', '.pkpass', '.html', '.htm', '.txt', ...IMAGE_EXTENSIONS]);
+/**
+ * The formats as the 400 names them. The photo formats come from the list the
+ * check itself reads, so a format added there is named here too.
+ */
+const ACCEPTED_LABEL = `EML, PDF, PKPass, HTML, TXT, ${IMAGE_EXTENSIONS.map((ext) => ext.slice(1).toUpperCase()).join(', ')} (photos when the AI model reads images)`;
const MAX_FILE_BYTES = 10 * 1024 * 1024;
const MAX_FILES = 5;
@@ -116,7 +121,7 @@ export class ReservationImportController {
for (const f of files) {
const ext = f.originalname.toLowerCase().slice(f.originalname.lastIndexOf('.'));
if (!ACCEPTED_EXTS.has(ext)) {
- throw new HttpException({ error: `Unsupported file type: ${f.originalname}. Accepted: EML, PDF, PKPass, HTML, TXT` }, 400);
+ throw new HttpException({ error: `Unsupported file type: ${f.originalname}. Accepted: ${ACCEPTED_LABEL}` }, 400);
}
}
// A photo has no text layer and no structure: only a model that reads images
diff --git a/server/tests/unit/nest/booking-import/reservation-import.controller.test.ts b/server/tests/unit/nest/booking-import/reservation-import.controller.test.ts
index 87ea2202b..b06b65408 100644
--- a/server/tests/unit/nest/booking-import/reservation-import.controller.test.ts
+++ b/server/tests/unit/nest/booking-import/reservation-import.controller.test.ts
@@ -78,6 +78,14 @@ describe('ReservationImportController.preview', () => {
expect(await status(() => c.preview(user, 't1', [file('IMG_1.heic')], { mode: 'fallback-on-empty' }))).toBe(400);
});
+ it('names the photo formats in that refusal too', async () => {
+ const { c } = make();
+ const err = await c.preview(user, 't1', [file('IMG_1.heic')], { mode: 'fallback-on-empty' }).catch((e: unknown) => e);
+ expect((err as HttpException).getResponse()).toEqual({
+ error: 'Unsupported file type: IMG_1.heic. Accepted: EML, PDF, PKPass, HTML, TXT, JPG, JPEG, PNG, WEBP (photos when the AI model reads images)',
+ });
+ });
+
it('defaults the mode to no-ai when omitted', async () => {
const { c, svc } = make();
await c.preview(user, 't1', [file()], {});
diff --git a/server/tests/unit/nest/llm-parse/clients.test.ts b/server/tests/unit/nest/llm-parse/clients.test.ts
index aed940545..53656f4c7 100644
--- a/server/tests/unit/nest/llm-parse/clients.test.ts
+++ b/server/tests/unit/nest/llm-parse/clients.test.ts
@@ -10,6 +10,13 @@ vi.mock('../../../../src/utils/ssrfGuard', () => ({ safeFetchLlm: safeFetchLlmMo
import { OpenAiCompatibleClient } from '../../../../src/nest/llm-parse/clients/openai-compatible.client';
import { AnthropicClient } from '../../../../src/nest/llm-parse/clients/anthropic.client';
import type { LlmExtractionInput } from '../../../../src/nest/llm-parse/llm-provider.interface';
+import {
+ buildReceiptPrompt,
+ RECEIPT_LIST_JSON_SCHEMA,
+ RECEIPT_ROOT_KEY,
+ RECEIPT_USER_TEXT,
+ toReceiptRead,
+} from '../../../../src/nest/llm-parse/receipt-read';
import { readEnv } from '../../../../src/app-config';
const baseInput: LlmExtractionInput = {
@@ -141,6 +148,31 @@ describe('OpenAiCompatibleClient', () => {
expect(second.model).toBe(first.model);
});
+ it('reads a receipt from a server that only takes json_object, going by the prompt alone', async () => {
+ // The server refuses json_schema, so the schema never reaches the model: the
+ // prompt has to name JSON (json_object mode wants the word) and the wrapper
+ // the answer is read under, or a flat receipt comes back as none.
+ safeFetchLlmMock
+ .mockResolvedValueOnce(jsonResponse({ error: { message: 'response_format json_schema is not supported' } }, false, 400))
+ .mockResolvedValueOnce(jsonResponse({
+ choices: [{ message: { content: '{"receipts":[{"merchant":"Café","date":"2026-09-20","total":12.5,"currency":"EUR","items":[]}]}' } }],
+ }));
+ const out = await new OpenAiCompatibleClient().extract({
+ prompt: buildReceiptPrompt(new Date('2026-09-24T10:00:00Z'), true),
+ jsonSchema: RECEIPT_LIST_JSON_SCHEMA,
+ rootKey: RECEIPT_ROOT_KEY,
+ userText: RECEIPT_USER_TEXT,
+ model: 'deepseek-chat',
+ file: { mimeType: 'image/jpeg', data: Buffer.from('jpeg') },
+ });
+
+ const second = JSON.parse((safeFetchLlmMock.mock.calls[1][1] as RequestInit).body as string);
+ expect(second.response_format).toEqual({ type: 'json_object' });
+ expect(second.messages[0].content).toContain('JSON');
+ expect(second.messages[0].content).toContain('{ "receipts": [');
+ expect(toReceiptRead(out[0])).toEqual({ merchant: 'Café', date: '2026-09-20', total: 12.5, currency: 'EUR', items: [] });
+ });
+
it('retries with max_completion_tokens when the model rejects max_tokens (400, #1760)', async () => {
safeFetchLlmMock
.mockResolvedValueOnce(
diff --git a/server/tests/unit/nest/llm-parse/image-input.test.ts b/server/tests/unit/nest/llm-parse/image-input.test.ts
index 493aba20a..06bdb2904 100644
--- a/server/tests/unit/nest/llm-parse/image-input.test.ts
+++ b/server/tests/unit/nest/llm-parse/image-input.test.ts
@@ -1,12 +1,82 @@
import { describe, it, expect } from 'vitest';
import { Jimp } from 'jimp';
-import { capImage, imageMimeType, IMAGE_MAX_EDGE, renderPdfPages } from '../../../../src/nest/llm-parse/image-input';
+import {
+ capImage,
+ IMAGE_MAX_BYTES,
+ IMAGE_MAX_EDGE,
+ imageMimeType,
+ ImageTooLargeError,
+ readImageHeader,
+ renderPdfPages,
+} from '../../../../src/nest/llm-parse/image-input';
async function png(w: number, h: number): Promise<Buffer> {
const image = new Jimp({ width: w, height: h, color: 0xffffffff });
return Buffer.from(await image.getBuffer('image/png'));
}
+/** A PNG that does not compress: every pixel from a fixed pseudo-random sequence. */
+async function noisePng(w: number, h: number): Promise<Buffer> {
+ const image = new Jimp({ width: w, height: h, color: 0xffffffff });
+ let seed = 1;
+ for (let i = 0; i < image.bitmap.data.length; i++) {
+ seed = (seed * 1103515245 + 12345) % 2147483648;
+ image.bitmap.data[i] = i % 4 === 3 ? 255 : (seed >>> 16) & 0xff;
+ }
+ return Buffer.from(await image.getBuffer('image/png'));
+}
+
+/** The signature and IHDR of a PNG, and nothing after them. */
+function pngHeader(w: number, h: number): Buffer {
+ const out = Buffer.alloc(33);
+ Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]).copy(out, 0);
+ out.writeUInt32BE(13, 8);
+ out.write('IHDR', 12, 'latin1');
+ out.writeUInt32BE(w, 16);
+ out.writeUInt32BE(h, 20);
+ out.writeUInt8(8, 24);
+ out.writeUInt8(6, 25);
+ return out;
+}
+
+/** SOI, an APP0 segment to step over, and a baseline frame header. */
+function jpegHeader(w: number, h: number): Buffer {
+ const app0 = Buffer.alloc(18);
+ app0.writeUInt16BE(0xffe0, 0);
+ app0.writeUInt16BE(16, 2);
+ app0.write('JFIF', 4, 'latin1');
+ const sof = Buffer.alloc(19);
+ sof.writeUInt16BE(0xffc0, 0);
+ sof.writeUInt16BE(17, 2);
+ sof.writeUInt8(8, 4);
+ sof.writeUInt16BE(h, 5);
+ sof.writeUInt16BE(w, 7);
+ sof.writeUInt8(3, 9);
+ return Buffer.concat([Buffer.from([0xff, 0xd8]), app0, sof]);
+}
+
+/** A RIFF/WEBP container with the size field of one of the three chunk kinds. */
+function webpHeader(chunk: 'VP8 ' | 'VP8L' | 'VP8X', w: number, h: number): Buffer {
+ const out = Buffer.alloc(30);
+ out.write('RIFF', 0, 'latin1');
+ out.writeUInt32LE(22, 4);
+ out.write('WEBP', 8, 'latin1');
+ out.write(chunk, 12, 'latin1');
+ out.writeUInt32LE(10, 16);
+ if (chunk === 'VP8 ') {
+ Buffer.from([0x9d, 0x01, 0x2a]).copy(out, 23);
+ out.writeUInt16LE(w, 26);
+ out.writeUInt16LE(h, 28);
+ } else if (chunk === 'VP8L') {
+ out.writeUInt8(0x2f, 20);
+ out.writeUInt32LE(((w - 1) | ((h - 1) << 14)) >>> 0, 21);
+ } else {
+ out.writeUIntLE(w - 1, 24, 3);
+ out.writeUIntLE(h - 1, 27, 3);
+ }
+ return out;
+}
+
describe('imageMimeType', () => {
it('knows the photo formats a provider reads, whatever the case', () => {
expect(imageMimeType('a.jpg')).toBe('image/jpeg');
@@ -44,10 +114,68 @@ describe('capImage', () => {
const data = Buffer.from('RIFF....WEBP');
expect(await capImage(data, 'image/webp')).toEqual({ data, mimeType: 'image/webp' });
});
+
+ it('refuses a PNG whose header claims more than the pixel cap, before decoding a byte of it', async () => {
+ // 33 bytes that would inflate to 1.6 GB: the header alone says so.
+ await expect(capImage(pngHeader(20000, 20000), 'image/png')).rejects.toThrow(ImageTooLargeError);
+ await expect(capImage(pngHeader(20000, 20000), 'image/png')).rejects.toThrow('20000 x 20000 pixels, more than the 40 megapixels');
+ });
+
+ it('refuses a JPEG and a WebP over the pixel cap the same way', async () => {
+ await expect(capImage(jpegHeader(10000, 10000), 'image/jpeg')).rejects.toThrow(ImageTooLargeError);
+ await expect(capImage(webpHeader('VP8X', 8000, 6000), 'image/webp')).rejects.toThrow(ImageTooLargeError);
+ });
+
+ it('types a photo by its bytes, not its name', async () => {
+ const data = await png(400, 300);
+ expect(await capImage(data, 'image/jpeg')).toEqual({ data, mimeType: 'image/png' });
+ });
+
+ it('re-encodes a photo that fits the edge but is too heavy to send', async () => {
+ const heavy = await noisePng(1300, 1300);
+ expect(heavy.length).toBeGreaterThan(IMAGE_MAX_BYTES);
+ const out = await capImage(heavy, 'image/png');
+ expect(out.mimeType).toBe('image/jpeg');
+ expect(out.data.length).toBeLessThan(heavy.length);
+ const back = await Jimp.read(out.data);
+ expect([back.width, back.height]).toEqual([1300, 1300]);
+ }, 30_000);
+
+ it('sends a WebP as it came, since nothing here decodes one, and refuses it over the byte cap', async () => {
+ const small = webpHeader('VP8 ', 640, 480);
+ expect(await capImage(small, 'image/webp')).toEqual({ data: small, mimeType: 'image/webp' });
+ const heavy = Buffer.concat([small, Buffer.alloc(IMAGE_MAX_BYTES)]);
+ await expect(capImage(heavy, 'image/webp')).rejects.toThrow(/cannot be made smaller/);
+ });
+});
+
+describe('readImageHeader', () => {
+ it('reads the size of a PNG and a JPEG from their first bytes', async () => {
+ expect(readImageHeader(await png(400, 300))).toEqual({ mimeType: 'image/png', width: 400, height: 300 });
+ const jpg = Buffer.from(await new Jimp({ width: 320, height: 200, color: 0xffffffff }).getBuffer('image/jpeg'));
+ expect(readImageHeader(jpg)).toEqual({ mimeType: 'image/jpeg', width: 320, height: 200 });
+ expect(readImageHeader(jpegHeader(640, 480))).toEqual({ mimeType: 'image/jpeg', width: 640, height: 480 });
+ });
+
+ it('reads all three WebP flavours', () => {
+ expect(readImageHeader(webpHeader('VP8 ', 640, 480))).toEqual({ mimeType: 'image/webp', width: 640, height: 480 });
+ expect(readImageHeader(webpHeader('VP8L', 1024, 768))).toEqual({ mimeType: 'image/webp', width: 1024, height: 768 });
+ expect(readImageHeader(webpHeader('VP8X', 4000, 3000))).toEqual({ mimeType: 'image/webp', width: 4000, height: 3000 });
+ });
+
+ it('is null for bytes that are none of the three, or say no size', () => {
+ const noFrame = Buffer.from([0xff, 0xd8, 0xff, 0xd9]);
+ for (const data of [Buffer.from('not an image'), Buffer.from('RIFF....WEBP'), noFrame, pngHeader(0, 10)]) {
+ expect(readImageHeader(data)).toBeNull();
+ }
+ });
});
-/** A PDF with no text layer: each page is one JPEG, as a scanner writes it. */
-async function scannedPdf(pages: number): Promise<Buffer> {
+/**
+ * A PDF with no text layer: each page is one JPEG, as a scanner writes it. The
+ * page box, and the size the image claims to have, can differ from the JPEG's.
+ */
+async function scannedPdf(pages: number, box = { w: 300, h: 400 }, claimed = { w: 300, h: 400 }): Promise<Buffer> {
const jpg = Buffer.from(await new Jimp({ width: 300, height: 400, color: 0xddddddff }).getBuffer('image/jpeg'));
const objects: Buffer[] = [];
const kids = Array.from({ length: pages }, (_, i) => `${3 + i * 3} 0 R`).join(' ');
@@ -55,11 +183,11 @@ async function scannedPdf(pages: number): Promise<Buffer> {
objects.push(Buffer.from(`<< /Type /Pages /Kids [${kids}] /Count ${pages} >>`));
for (let i = 0; i < pages; i++) {
const page = 3 + i * 3;
- const content = 'q 300 0 0 400 0 0 cm /Im0 Do Q';
- objects.push(Buffer.from(`<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 400] /Resources << /XObject << /Im0 ${page + 2} 0 R >> >> /Contents ${page + 1} 0 R >>`));
+ const content = `q ${box.w} 0 0 ${box.h} 0 0 cm /Im0 Do Q`;
+ objects.push(Buffer.from(`<< /Type /Page /Parent 2 0 R /MediaBox [0 0 ${box.w} ${box.h}] /Resources << /XObject << /Im0 ${page + 2} 0 R >> >> /Contents ${page + 1} 0 R >>`));
objects.push(Buffer.from(`<< /Length ${content.length} >>\nstream\n${content}\nendstream`));
objects.push(Buffer.concat([
- Buffer.from(`<< /Type /XObject /Subtype /Image /Width 300 /Height 400 /ColorSpace /DeviceRGB /BitsPerComponent 8 /Filter /DCTDecode /Length ${jpg.length} >>\nstream\n`),
+ Buffer.from(`<< /Type /XObject /Subtype /Image /Width ${claimed.w} /Height ${claimed.h} /ColorSpace /DeviceRGB /BitsPerComponent 8 /Filter /DCTDecode /Length ${jpg.length} >>\nstream\n`),
jpg,
Buffer.from('\nendstream'),
]));
@@ -88,6 +216,19 @@ describe('renderPdfPages', () => {
}
}, 30_000);
+ it('draws a page by its long edge, so a tall strip never becomes a huge canvas', async () => {
+ // Scaled by its width alone, this page was a canvas of 1600 x 320000 pixels.
+ const [page] = await renderPdfPages(await scannedPdf(1, { w: 10, h: 2000 }));
+ const image = await Jimp.read(page.data);
+ expect(image.height).toBeLessThanOrEqual(IMAGE_MAX_EDGE);
+ expect(image.width).toBeLessThanOrEqual(10);
+ }, 30_000);
+
+ it('still draws a page whose embedded image claims more than the pixel cap, leaving that image out', async () => {
+ const pages = await renderPdfPages(await scannedPdf(1, { w: 300, h: 400 }, { w: 20000, h: 20000 }));
+ expect(pages).toHaveLength(1);
+ }, 30_000);
+
it('throws for bytes that are not a PDF, which the caller reports as unreadable', async () => {
await expect(renderPdfPages(Buffer.from('not a pdf'))).rejects.toThrow();
});
diff --git a/server/tests/unit/nest/llm-parse/llm-local.service.test.ts b/server/tests/unit/nest/llm-parse/llm-local.service.test.ts
index a26dd5786..5cbdaba42 100644
--- a/server/tests/unit/nest/llm-parse/llm-local.service.test.ts
+++ b/server/tests/unit/nest/llm-parse/llm-local.service.test.ts
@@ -81,6 +81,23 @@ describe('LlmLocalService.modelCapabilities', () => {
await expect(svc().modelCapabilities('http://ollama:11434/v1', 'qwen3.5:4b')).resolves.toEqual(['completion', 'vision']);
expect(fetchFn.mock.calls[0][0]).toBe('http://ollama:11434/api/show');
expect(JSON.parse(fetchFn.mock.calls[0][1].body)).toEqual({ model: 'qwen3.5:4b' });
+ expect(fetchFn.mock.calls[0][1].headers).not.toHaveProperty('authorization');
+ });
+
+ it('sends the configured key as the Bearer header the extraction sends', async () => {
+ const fetchFn = mockFetch(async () => showOk({ capabilities: ['vision'] }));
+ await expect(svc().modelCapabilities('http://ollama:11434/v1', 'qwen3.5:4b', 'proxy-key')).resolves.toEqual(['vision']);
+ expect(fetchFn.mock.calls[0][1].headers).toMatchObject({ authorization: 'Bearer proxy-key' });
+ });
+
+ it('remembers an answer per key, so a corrected key is asked afresh', async () => {
+ const fetchFn = mockFetch(async (_url: string, init: { headers: Record<string, string> }) =>
+ init?.headers?.authorization === 'Bearer right' ? showOk({ capabilities: ['vision'] }) : { ok: false, status: 401, body: null });
+ const s = svc();
+ await expect(s.modelCapabilities('http://ollama:11434', 'm', 'wrong')).resolves.toBeNull();
+ await expect(s.modelCapabilities('http://ollama:11434', 'm', 'right')).resolves.toEqual(['vision']);
+ await expect(s.modelCapabilities('http://ollama:11434', 'm', 'right')).resolves.toEqual(['vision']);
+ expect(fetchFn).toHaveBeenCalledTimes(2);
});
it('asks the server once per server and model, not once per call', async () => {
diff --git a/server/tests/unit/nest/llm-parse/llm-parse.service.test.ts b/server/tests/unit/nest/llm-parse/llm-parse.service.test.ts
index cf237c0b7..5ff76889c 100644
--- a/server/tests/unit/nest/llm-parse/llm-parse.service.test.ts
+++ b/server/tests/unit/nest/llm-parse/llm-parse.service.test.ts
@@ -55,6 +55,17 @@ const svc = () => new LlmParseService(
);
const file = (name: string, body = 'Flight AB123') => ({ buffer: Buffer.from(body), originalName: name });
+/** The first bytes of a PNG that claims the given size: enough for the pixel cap to refuse it. */
+function pngClaiming(w: number, h: number): Buffer {
+ const out = Buffer.alloc(33);
+ Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]).copy(out, 0);
+ out.writeUInt32BE(13, 8);
+ out.write('IHDR', 12, 'latin1');
+ out.writeUInt32BE(w, 16);
+ out.writeUInt32BE(h, 20);
+ return out;
+}
+
beforeEach(() => {
vi.clearAllMocks();
resolveLlmConfig.mockReturnValue(cfg());
@@ -319,10 +330,11 @@ describe('LlmParseService: a photo', () => {
});
it('readsImages on auto asks a local server, and answers no for a cloud provider', async () => {
- resolveLlmConfig.mockReturnValue(cfg({ provider: 'local', vision: 'auto', baseUrl: 'http://ollama:11434/v1', model: 'qwen3.5:4b' }));
+ resolveLlmConfig.mockReturnValue(cfg({ provider: 'local', vision: 'auto', baseUrl: 'http://ollama:11434/v1', model: 'qwen3.5:4b', apiKey: 'proxy-key' }));
modelCapabilities.mockResolvedValue(['completion', 'vision']);
await expect(svc().readsImages(1)).resolves.toBe(true);
- expect(modelCapabilities).toHaveBeenCalledWith('http://ollama:11434/v1', 'qwen3.5:4b');
+ // With the key the extraction sends, so an Ollama behind an auth proxy answers.
+ expect(modelCapabilities).toHaveBeenCalledWith('http://ollama:11434/v1', 'qwen3.5:4b', 'proxy-key');
modelCapabilities.mockResolvedValue(['completion']);
await expect(svc().readsImages(1)).resolves.toBe(false);
modelCapabilities.mockResolvedValue(null);
@@ -371,6 +383,14 @@ describe('LlmParseService: a photo', () => {
expect(extract).not.toHaveBeenCalled();
});
+ it('turns a photo too large to decode into a warning, not a throw', async () => {
+ resolveLlmConfig.mockReturnValue(cfg({ vision: 'on' }));
+ const res = await svc().parse({ buffer: pngClaiming(20000, 20000), originalName: 'ticket.png' }, 1);
+ expect(res.kiItems).toEqual([]);
+ expect(res.warnings[0]).toMatch(/^ticket\.png: could not read file .*20000 x 20000 pixels/);
+ expect(extract).not.toHaveBeenCalled();
+ });
+
it('leaves a PDF on its text path when the model reads images', async () => {
resolveLlmConfig.mockReturnValue(cfg({ vision: 'on' }));
await svc().parse(file('a.pdf', '%PDF'), 1);
@@ -400,6 +420,8 @@ describe('LlmParseService.readReceipt', () => {
const call = extractEnforced.mock.calls[0][0];
expect(call).toMatchObject({ baseUrl: 'http://ollama:11434/v1', model: 'qwen3.5:4b', images: [Buffer.from('jpeg').toString('base64')] });
expect(call.schema.required).toContain('total');
+ // The grammar holds Ollama to one flat receipt, and the prompt says the same.
+ expect(call.system).toContain('Return ONLY a JSON object of the form { "merchant"');
expect(extract).not.toHaveBeenCalled();
});
@@ -411,6 +433,14 @@ describe('LlmParseService.readReceipt', () => {
expect(input.rootKey).toBe('receipts');
expect(input.file).toEqual({ mimeType: 'image/png', data: Buffer.from('png') });
expect(input.text).toBeUndefined();
+ expect(input.prompt).toContain('Return ONLY a JSON object of the form { "receipts": [');
+ });
+
+ it('refuses a photo too large to decode with a warning, before asking the model', async () => {
+ resolveLlmConfig.mockReturnValue(cfg({ vision: 'on' }));
+ const res = await svc().readReceipt({ buffer: pngClaiming(20000, 20000), originalName: 'r.png' }, 1);
+ expect(res).toEqual({ receipt: null, warnings: ['r.png: the photo is 20000 x 20000 pixels, more than the 40 megapixels TREK reads'] });
+ expect(extract).not.toHaveBeenCalled();
});
it('answers a warning, not a throw, when the model fails or reads nothing', async () => {
diff --git a/server/tests/unit/nest/llm-parse/receipt-read.test.ts b/server/tests/unit/nest/llm-parse/receipt-read.test.ts
index 6485dded1..b0cf4681d 100644
--- a/server/tests/unit/nest/llm-parse/receipt-read.test.ts
+++ b/server/tests/unit/nest/llm-parse/receipt-read.test.ts
@@ -1,4 +1,5 @@
import { describe, it, expect } from 'vitest';
+import { RECEIPT_AMOUNT_MAX, RECEIPT_LINES_MAX, RECEIPT_TEXT_MAX } from '@trek/shared';
import { buildReceiptPrompt, RECEIPT_LIST_JSON_SCHEMA, RECEIPT_ROOT_KEY, toReceiptRead } from '../../../../src/nest/llm-parse/receipt-read';
describe('toReceiptRead', () => {
@@ -38,6 +39,54 @@ describe('toReceiptRead', () => {
it('is null when nothing usable came back', () => {
for (const raw of [null, undefined, 'text', [], {}, { total: 'n/a', merchant: ' ' }]) expect(toReceiptRead(raw)).toBeNull();
});
+
+ it('leaves out a discount or a free line, written as a number or as text, so the Ticket split can save', () => {
+ const read = toReceiptRead({
+ total: 10,
+ items: [
+ { name: 'Tea', price: 3 },
+ { name: 'Discount', price: -2 },
+ { name: 'Coupon', price: '-2,00' },
+ { name: 'Bag refund', price: '0,50-' },
+ { name: 'Voucher', price: '€ −1.00' },
+ { name: 'Water', price: 0 },
+ ],
+ });
+ expect(read?.items).toEqual([{ name: 'Tea', price: 3 }]);
+ });
+
+ it('keeps the sign of a total written as text, and drops a negative one', () => {
+ expect(toReceiptRead({ merchant: 'Shop', total: '-12,50' })?.total).toBeNull();
+ expect(toReceiptRead({ total: '12,50 €' })?.total).toBe(12.5);
+ });
+
+ it('reads a Swiss whole amount such as "45.-" as positive, while "2,00-" stays a discount', () => {
+ const read = toReceiptRead({
+ total: 'CHF 45.-',
+ items: [
+ { name: 'Fondue', price: '38,-' },
+ { name: 'Coupon', price: '2,00-' },
+ ],
+ });
+ expect(read?.total).toBe(45);
+ expect(read?.items).toEqual([{ name: 'Fondue', price: 38 }]);
+ });
+
+ it('cuts names, lines and amounts to what the contract takes instead of losing the whole reading', () => {
+ const read = toReceiptRead({
+ merchant: 'M'.repeat(RECEIPT_TEXT_MAX + 50),
+ total: RECEIPT_AMOUNT_MAX * 10,
+ items: [
+ { name: 'Gold', price: RECEIPT_AMOUNT_MAX + 1 },
+ ...Array.from({ length: RECEIPT_LINES_MAX + 20 }, (_, i) => ({ name: `Line ${i} ${'x'.repeat(RECEIPT_TEXT_MAX)}`, price: 1 })),
+ ],
+ });
+ expect(read?.merchant).toHaveLength(RECEIPT_TEXT_MAX);
+ expect(read?.total).toBeNull();
+ expect(read?.items).toHaveLength(RECEIPT_LINES_MAX);
+ expect(read?.items[0].name).toMatch(/^Line 0 /);
+ expect(read?.items.every((line) => line.name.length <= RECEIPT_TEXT_MAX)).toBe(true);
+ });
});
describe('the receipt prompt and schema', () => {
@@ -45,6 +94,15 @@ describe('the receipt prompt and schema', () => {
expect(buildReceiptPrompt(new Date('2026-09-24T10:00:00Z'))).toContain('Today is 2026-09-24.');
});
+ it('spells out the JSON it wants, wrapped in the receipts list for the cloud clients', () => {
+ const local = buildReceiptPrompt(new Date('2026-09-24T10:00:00Z'));
+ expect(local).toContain('Return ONLY a JSON object of the form { "merchant": ""');
+ expect(local).not.toContain(`"${RECEIPT_ROOT_KEY}"`);
+ // A server that turns json_schema down reads this prompt alone, in json_object mode.
+ const cloud = buildReceiptPrompt(new Date('2026-09-24T10:00:00Z'), true);
+ expect(cloud).toContain(`Return ONLY a JSON object of the form { "${RECEIPT_ROOT_KEY}": [ { "merchant": ""`);
+ });
+
it('wraps one receipt under the key the cloud clients read', () => {
expect(RECEIPT_LIST_JSON_SCHEMA.required).toEqual([RECEIPT_ROOT_KEY]);
expect(RECEIPT_LIST_JSON_SCHEMA.properties[RECEIPT_ROOT_KEY].items.required).toEqual(['merchant', 'date', 'total', 'currency', 'items']);
diff --git a/shared/src/budget/receipt-scan.schema.spec.ts b/shared/src/budget/receipt-scan.schema.spec.ts
new file mode 100644
index 000000000..81d5a0e42
--- /dev/null
+++ b/shared/src/budget/receipt-scan.schema.spec.ts
@@ -0,0 +1,60 @@
+import {
+ RECEIPT_AMOUNT_MAX,
+ RECEIPT_LINES_MAX,
+ RECEIPT_TEXT_MAX,
+ receiptReadSchema,
+ receiptScanResultSchema,
+} from './receipt-scan.schema';
+
+import { describe, it, expect } from 'vitest';
+
+const read = {
+ merchant: 'Café de Flore',
+ date: '2026-09-20',
+ total: 23.4,
+ currency: 'EUR',
+ items: [{ name: 'Croque', price: 15.4 }],
+};
+
+describe('receiptReadSchema', () => {
+ it('takes a reading, and one where nothing but the total was read', () => {
+ expect(receiptReadSchema.safeParse(read).success).toBe(true);
+ expect(
+ receiptReadSchema.safeParse({ merchant: null, date: null, total: 5, currency: null, items: [] }).success,
+ ).toBe(true);
+ });
+
+ it('refuses a line that is not a charge: a discount or a free item stops the Ticket split', () => {
+ for (const price of [0, -2]) {
+ expect(receiptReadSchema.safeParse({ ...read, items: [{ name: 'Discount', price }] }).success).toBe(false);
+ }
+ });
+
+ it('holds names, lines and amounts to their bounds', () => {
+ const long = 'x'.repeat(RECEIPT_TEXT_MAX + 1);
+ expect(receiptReadSchema.safeParse({ ...read, merchant: long }).success).toBe(false);
+ expect(receiptReadSchema.safeParse({ ...read, items: [{ name: long, price: 1 }] }).success).toBe(false);
+ const lines = Array.from({ length: RECEIPT_LINES_MAX + 1 }, () => ({ name: 'Tea', price: 1 }));
+ expect(receiptReadSchema.safeParse({ ...read, items: lines }).success).toBe(false);
+ expect(receiptReadSchema.safeParse({ ...read, items: lines.slice(1) }).success).toBe(true);
+ expect(receiptReadSchema.safeParse({ ...read, total: RECEIPT_AMOUNT_MAX + 1 }).success).toBe(false);
+ expect(receiptReadSchema.safeParse({ ...read, total: Number.POSITIVE_INFINITY }).success).toBe(false);
+ expect(
+ receiptReadSchema.safeParse({ ...read, items: [{ name: 'Gold', price: RECEIPT_AMOUNT_MAX + 1 }] }).success,
+ ).toBe(false);
+ });
+
+ it('refuses a date or a currency in any other form', () => {
+ expect(receiptReadSchema.safeParse({ ...read, date: '20/09/2026' }).success).toBe(false);
+ expect(receiptReadSchema.safeParse({ ...read, currency: 'eur' }).success).toBe(false);
+ });
+});
+
+describe('receiptScanResultSchema', () => {
+ it('carries a reading, or none with the reason', () => {
+ expect(receiptScanResultSchema.safeParse({ receipt: read, warnings: [] }).success).toBe(true);
+ expect(
+ receiptScanResultSchema.safeParse({ receipt: null, warnings: ['bill.jpg: no receipt could be read'] }).success,
+ ).toBe(true);
+ });
+});
diff --git a/shared/src/budget/receipt-scan.schema.ts b/shared/src/budget/receipt-scan.schema.ts
index 00ab391c7..faccaebc3 100644
--- a/shared/src/budget/receipt-scan.schema.ts
+++ b/shared/src/budget/receipt-scan.schema.ts
@@ -1,5 +1,20 @@
import { z } from 'zod';
+/**
+ * The bounds a model's reading of a receipt is held to. The answer comes from a
+ * photo anyone on the trip can take, of paper anyone can print, so it is never
+ * trusted to be short or sane: a name longer than a till prints, more lines
+ * than one expense is split into, or an amount no receipt carries is cut or
+ * dropped before it reaches the expense editor.
+ */
+export const RECEIPT_TEXT_MAX = 200;
+export const RECEIPT_LINES_MAX = 100;
+/**
+ * Above any receipt in any currency, the weakest included, and far enough
+ * under 2^53 for the integer cent maths of a split.
+ */
+export const RECEIPT_AMOUNT_MAX = 10_000_000_000;
+
/**
* A photographed receipt, as the AI model read it for the Costs tab.
*
@@ -8,29 +23,34 @@ import { z } from 'zod';
* There is no category: which kind of spending it was is the person's call.
*/
export const receiptLineSchema = z.object({
- name: z.string().min(1),
- /** What the line cost in total, quantity included, in the receipt's currency. */
- price: z.number(),
+ name: z.string().min(1).max(RECEIPT_TEXT_MAX),
+ /**
+ * What the line cost in total, quantity included, in the receipt's currency.
+ * Positive: a discount or a free line would leave the Ticket split unable to
+ * save, which takes only priced lines, so it is not a line here. The total
+ * already counts it.
+ */
+ price: z.number().positive().max(RECEIPT_AMOUNT_MAX),
});
export type ReceiptLine = z.infer<typeof receiptLineSchema>;
export const receiptReadSchema = z.object({
/** The business, which becomes the expense name. */
- merchant: z.string().min(1).nullable(),
+ merchant: z.string().min(1).max(RECEIPT_TEXT_MAX).nullable(),
/** YYYY-MM-DD. */
date: z
.string()
.regex(/^\d{4}-\d{2}-\d{2}$/)
.nullable(),
/** The grand total paid. */
- total: z.number().positive().nullable(),
+ total: z.number().positive().max(RECEIPT_AMOUNT_MAX).nullable(),
/** ISO 4217. */
currency: z
.string()
.regex(/^[A-Z]{3}$/)
.nullable(),
/** The itemized lines, which seed the Ticket split. */
- items: z.array(receiptLineSchema),
+ items: z.array(receiptLineSchema).max(RECEIPT_LINES_MAX),
});
export type ReceiptRead = z.infer<typeof receiptReadSchema>;
diff --git a/wiki/AI-Booking-Import.md b/wiki/AI-Booking-Import.md
index 9f5e8f859..529bc9daf 100644
--- a/wiki/AI-Booking-Import.md
+++ b/wiki/AI-Booking-Import.md
@@ -98,6 +98,7 @@ When the configured model reads images (see **Model reads images** above), the i
- A photo always goes to the model: KDE Itinerary is not asked, since it reads documents, not pictures.
- A scanned PDF (no text layer) is read the same way: its first two pages are drawn as images and sent to the model.
- It is shrunk to 1600 px on its longest side before it is sent. A model pays for every pixel and does not read a till roll better at twelve megapixels; on a local `qwen3.5:4b` running on CPU the same ticket took several times longer at full size.
+- A photo over 40 megapixels is refused, with a warning naming the file, before it is even decoded. So is a WEBP over 3.5 MB: TREK shrinks JPG and PNG but cannot shrink a WEBP, and a provider takes no more than that.
- HEIC is not accepted. A phone's photo picker hands over a JPEG.
- When the model does not read images, the dialog does not offer photos, and the server refuses one sent anyway with *The configured AI model does not read photos*.
diff --git a/wiki/Admin-Addons.md b/wiki/Admin-Addons.md
index d21037c4f..2478a0813 100644
--- a/wiki/Admin-Addons.md
+++ b/wiki/Admin-Addons.md
@@ -54,7 +54,7 @@ Integration addons connect TREK to external services. Most of them need addition
- The **Naver List Import** addon imports the places of a shared Naver Maps list into a trip. **Enabled by default.** It needs no key.
- The **AirTrail** addon syncs flights from a self-hosted AirTrail instance. **Disabled by default.** The toggle here is the instance-wide switch only; each user connects their own instance (URL + API key) in **Settings → Integrations**.
- The **Dawarich** addon reads the stays and recorded routes of a self-hosted Dawarich instance and offers them as suggestions. **Disabled by default.** The toggle here is the instance-wide switch only; each user connects their own instance (address + API key) in **Settings → Integrations**. A Dawarich on your local network also needs `ALLOW_INTERNAL_NETWORK=true`. See [Dawarich](Dawarich).
-- The **AI Parsing** addon is the LLM fallback for booking imports KItinerary cannot read. **Disabled by default.** When enabled, its provider, base URL, API key, and model fields appear inline underneath the addon row. Filling them in sets the instance-wide config for all users; leaving them blank lets each user configure their own provider in **Settings → Integrations**. See [AI-Booking-Import](AI-Booking-Import).
+- The **AI Parsing** addon is the LLM fallback for booking imports KItinerary cannot read. **Disabled by default.** When enabled, its provider, base URL, API key, and model fields appear inline underneath the addon row, with **Model reads images** (**Automatic**, **Yes** or **No**). Automatic asks a local Ollama server whether the model reads images and means no for a cloud provider. When it resolves to yes, the booking import takes photos (JPG, PNG, WEBP) and scanned PDFs are read page by page, and Costs offers **Scan receipt**. Filling the fields in sets the instance-wide config for all users; leaving them blank lets each user configure their own provider in **Settings → Integrations**. See [AI-Booking-Import](AI-Booking-Import) and [Budget-Tracking](Budget-Tracking#scanning-a-receipt).
## Enabling or disabling an addon
diff --git a/wiki/Budget-Tracking.md b/wiki/Budget-Tracking.md
index 29c397369..3769a88a2 100644
--- a/wiki/Budget-Tracking.md
+++ b/wiki/Budget-Tracking.md
@@ -82,9 +82,9 @@ A row with receipts shows a **Receipts** chip beside the name, with the count wh
With the [AI Parsing](AI-Booking-Import) addon on and a model that reads images (see *Model reads images* there), a **Scan receipt** button sits beside **Add expense**, and on a phone the Costs header carries a scan icon. It is offered to whoever may add expenses.
-1. Click **Scan receipt**. A dialog like the booking import's takes one photo of the receipt (JPG, PNG or WEBP, up to 10 MB): drop it on the box, or click the box to pick one or, on a phone, take one. Then click **Scan**.
+1. Click **Scan receipt**. A dialog like the booking import's takes one photo of the receipt (JPG, PNG or WEBP, up to 10 MB; a photo over 40 megapixels or a WEBP over 3.5 MB is refused): drop it on the box, or click the box to pick one or, on a phone, take one. Then click **Scan**.
2. The dialog closes and the model reads the photo in the background: the **background tasks** widget shows *Reading the receipt…*, and you can keep using TREK meanwhile. On a local model running on CPU this takes from a few seconds to a couple of minutes.
-3. When it is done, **Review expense** opens the expense editor pre-filled with what was read: the merchant as the name, the total, the currency and the day. The split stays **Equally**; switch it to **Ticket** and the receipt's lines are already listed, each shared by everyone. The photo is already in **Receipts & Invoices**, uploaded when you save like any receipt you attach yourself, which needs `file_upload` too.
+3. When it is done, **Review expense** opens the expense editor pre-filled with what was read: the merchant as the name, the total, the currency and the day. The split stays **Equally**; switch it to **Ticket** and the receipt's lines are already listed, each shared by everyone. Discount and free lines are left out, since a Ticket line needs a price. If you may upload files (`file_upload`), the photo is already in **Receipts & Invoices**, uploaded when you save like any receipt you attach yourself. Without that permission the editor opens pre-filled all the same, just without the photo.
4. Check everything, pick the category, who paid and the split, and save. Nothing is stored before that.
The scan reads one photo per expense and does not guess the category. A photo nothing could be read from ends on *No receipt could be read from this photo.*, with the reason under it. Scan jobs are kept for about 10 minutes after they finish, like [booking imports](AI-Booking-Import#good-to-know).
diff --git a/wiki/Reservations-and-Bookings.md b/wiki/Reservations-and-Bookings.md
index 00004ce57..ba1115f94 100644
--- a/wiki/Reservations-and-Bookings.md
+++ b/wiki/Reservations-and-Bookings.md
@@ -105,8 +105,9 @@ TREK can parse booking confirmation emails, PDFs, and pass files and create rese
| Apple Wallet pass | `.pkpass` |
| HTML confirmation page | `.html`, `.htm` |
| Plain-text email | `.txt` |
+| Photo of a ticket or confirmation | `.jpg`, `.jpeg`, `.png`, `.webp` (only with the AI Parsing addon and a model that reads images) |
-Up to 5 files, 10 MB each, per import.
+Up to 5 files, 10 MB each, per import. A photo always goes to the AI model, never to KDE Itinerary, and the upload dialog only offers photos when the model reads images. See [AI-Booking-Import](AI-Booking-Import#photos).
### How to import
diff --git a/wiki/User-Settings.md b/wiki/User-Settings.md
index a5a9d79cf..3325f251c 100644
--- a/wiki/User-Settings.md
+++ b/wiki/User-Settings.md
@@ -97,7 +97,7 @@ The Integrations tab is only visible when a **photo provider** (Immich or Synolo
- **Photo Providers** (only when a photo provider is enabled) — Configure Immich, Synology Photos, and other photo integrations. One card appears per enabled provider.
- **AirTrail** (only when the AirTrail addon is enabled) — Instance URL and API key for your self-hosted AirTrail, plus a self-signed-certificate switch and a **Write changes back to AirTrail** toggle (off by default: AirTrail is the source of truth and TREK only reads from it). **Test connection** reports how many flights it can see. The key is stored encrypted and never prefilled — leaving the field blank keeps the stored one.
- **Dawarich** (only when the Dawarich addon is enabled): the **Instance address** and **API key** of your own Dawarich, a self-signed-certificate switch, **Test connection** and **Disconnect**. The key is stored encrypted and never handed back. See [Dawarich](Dawarich).
-- **AI parsing** (only when the AI Parsing addon is enabled) — The provider (OpenAI or Anthropic), model and API key used to extract bookings from your uploaded files, plus **Send documents as images** for vision-capable models. This is the per-user fallback: it only takes effect when your administrator has not configured a model for the whole instance. A local Ollama endpoint is not offered here — that is set up once, instance-wide, in the admin settings (#1772). See [AI-Booking-Import](AI-Booking-Import).
+- **AI parsing** (only when the AI Parsing addon is enabled): the provider (OpenAI or Anthropic), model and API key used to extract bookings from your uploaded files, plus **Model reads images**. Turn that on for a model that reads images: a photo of a ticket can then be imported as a booking, and a receipt scanned in Costs. This is the per-user fallback: it only takes effect when your administrator has not configured a model for the whole instance. A local Ollama endpoint is not offered here; that is set up once, instance-wide, in the admin settings (#1772). See [AI-Booking-Import](AI-Booking-Import#photos) and [Budget-Tracking](Budget-Tracking#scanning-a-receipt).
- **API Keys** (whenever the tab is shown): read-only keys for the public API, so other software can read your trips. **Create key** names the key and lets you narrow **what this key may read** to single areas; the key is shown once. See [Public-API](Public-API).
- **MCP section** (only when MCP addon is enabled):
- Shows the MCP server endpoint URL.