fix(mail-import): retry a busy AI provider and never drop a booking mail in silence

A forwarded booking mail whose AI read failed in passing (a 503 "high
demand", a rate limit, a timeout) was settled at once with an inbox entry
nobody read again, and a manual import printed "no reservations found"
under the AI error as if the file held none.

Both LLM clients now send a failed request again up to twice, honouring
Retry-After within the request timeout. The mail pipeline puts such a mail
back in the queue and keeps the inbox entry only after its last try, and
these attempts no longer count toward the daily AI limit.

The mail prompt now names the answer's shape, { "bookings": [...] }, for
providers that get no tool. An answer in another shape used to read as
"not a booking" and the mail was discarded without a trace; it now ends
as a failed read the person sees in the inbox.

The import warnings lose their dashes, and the image sets LANG=C.UTF-8 so
KItinerary stops warning about the C locale on every run.
This commit is contained in:
Maurice
2026-11-24 12:51:56 +01:00
parent 7fe4fbb683
commit eeff0398a7
24 changed files with 566 additions and 78 deletions
@@ -135,12 +135,57 @@ describe('BookingImportService.preview', () => {
const { svc } = make({
kit: true,
ai: true,
parse: async () => ({ kiItems: [], warnings: ['a.pdf: AI parsing failed — 429'], outcome: 'quota_exhausted' }),
parse: async () => ({ kiItems: [], warnings: ['a.pdf: AI parsing failed: 429'], outcome: 'quota_exhausted' }),
});
const res = await svc.preview([file()], 'fallback-on-empty', 1);
expect(res.files).toEqual([{ fileName: 'a.pdf', aiAvailable: true, aiUsed: true, outcome: 'quota_exhausted' }]);
});
it('says no reservations were found only where the AI did not fail', async () => {
const failed = make({
kit: true,
ai: true,
extract: async () => [],
parse: async () => ({
kiItems: [],
warnings: ['a.pdf: AI parsing failed: LLM request failed (503): high demand'],
outcome: 'provider_error',
}),
});
expect((await failed.svc.preview([file()], 'fallback-on-empty', 1)).warnings).toEqual([
'a.pdf: AI parsing failed: LLM request failed (503): high demand',
]);
const quiet = await Promise.all(
(['empty', undefined] as const).map((outcome) =>
make({
kit: true,
ai: true,
extract: async () => [],
parse: async () => ({ kiItems: [], warnings: [], ...(outcome && { outcome }) }),
}).svc.preview([file()], 'fallback-on-empty', 1),
),
);
for (const res of quiet) expect(res.warnings).toEqual(['a.pdf: no reservations found']);
// The local router's warnings do not name the file, so the line that does stays.
const local = make({
kit: true,
ai: true,
extract: async () => [],
parse: async () => ({ kiItems: [], warnings: ['AI parsing failed: model not found'], outcome: 'provider_error' }),
});
expect((await local.svc.preview([file()], 'fallback-on-empty', 1)).warnings).toEqual([
'AI parsing failed: model not found',
'a.pdf: no reservations found',
]);
const noAi = make({ kit: true, ai: false, extract: async () => [] });
expect((await noAi.svc.preview([file()], 'fallback-on-empty', 1)).warnings).toEqual([
'a.pdf: no reservations found',
]);
});
it('fallback-on-empty: skips the LLM when kitinerary already found items', async () => {
const { svc, llmParse } = make({ kit: true, ai: true, extract: async () => [HOTEL_KI] });
const res = await svc.preview([file()], 'fallback-on-empty', 1);
@@ -484,7 +484,7 @@ describe('kitinerary mapper: a rail ticket with changes (#2895)', () => {
);
expect(items).toEqual([]);
expect(warnings).toEqual(['Unknown type "constructor" in odd.json[0] — skipped']);
expect(warnings).toEqual(['Unknown type "constructor" in odd.json[0], skipped']);
});
});
@@ -547,7 +547,7 @@ describe('kitinerary mapper — a recognised type that cannot be mapped (#2375)'
);
expect(items).toHaveLength(0);
expect(warnings).toEqual(['Incomplete LodgingReservation in airbnb.pdf[0] (no name in reservationFor) — skipped']);
expect(warnings).toEqual(['Incomplete LodgingReservation in airbnb.pdf[0] (no name in reservationFor), skipped']);
});
it('warns for a flight that carries no reservationFor at all', () => {
@@ -557,7 +557,7 @@ describe('kitinerary mapper — a recognised type that cannot be mapped (#2375)'
);
expect(items).toHaveLength(0);
expect(warnings).toEqual(['Incomplete FlightReservation in ticket.eml[0] (no reservationFor) — skipped']);
expect(warnings).toEqual(['Incomplete FlightReservation in ticket.eml[0] (no reservationFor), skipped']);
});
it('names the type it could not map, TouristAttractionVisit included', () => {
@@ -566,9 +566,7 @@ describe('kitinerary mapper — a recognised type that cannot be mapped (#2375)'
'museum.pdf',
);
expect(warnings[0]).toBe(
'Incomplete TouristAttractionVisit in museum.pdf[0] (no name in reservationFor) — skipped',
);
expect(warnings[0]).toBe('Incomplete TouristAttractionVisit in museum.pdf[0] (no name in reservationFor), skipped');
});
it('keeps the bookings it could map and warns only about the weak one', () => {
@@ -592,7 +590,7 @@ describe('kitinerary mapper — a recognised type that cannot be mapped (#2375)'
);
expect(items).toHaveLength(0);
expect(warnings).toEqual(['Unknown type "RocketLaunchReservation" in mars.eml[0] — skipped']);
expect(warnings).toEqual(['Unknown type "RocketLaunchReservation" in mars.eml[0], skipped']);
});
});
@@ -1,6 +1,7 @@
import { readEnv } from '../../../../src/app-config';
import { AnthropicClient } from '../../../../src/nest/llm-parse/clients/anthropic.client';
import { LlmContextOverflowError } from '../../../../src/nest/llm-parse/clients/context-overflow';
import { LlmRequestError } from '../../../../src/nest/llm-parse/clients/llm-request-error';
import { OpenAiCompatibleClient } from '../../../../src/nest/llm-parse/clients/openai-compatible.client';
import type { LlmExtractionInput } from '../../../../src/nest/llm-parse/llm-provider.interface';
import {
@@ -11,7 +12,7 @@ import {
toReceiptRead,
} from '../../../../src/nest/llm-parse/receipt-read';
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { afterEach, describe, it, expect, vi, beforeEach } from 'vitest';
// The clients go through safeFetchLlm (SSRF guard: blocks the cloud-metadata
// range, allows a local/LAN Ollama). Mock it here so the tests never do a real
@@ -32,8 +33,14 @@ function mockFetch(impl: (url: string, init: RequestInit) => Promise<Response> |
return safeFetchLlmMock;
}
function jsonResponse(body: unknown, ok = true, status = 200): Response {
return { ok, status, json: async () => body, text: async () => JSON.stringify(body) } as unknown as Response;
function jsonResponse(body: unknown, ok = true, status = 200, headers: Record<string, string> = {}): Response {
return {
ok,
status,
headers: new Headers(headers),
json: async () => body,
text: async () => JSON.stringify(body),
} as unknown as Response;
}
beforeEach(() => safeFetchLlmMock.mockReset());
@@ -148,7 +155,7 @@ describe('OpenAiCompatibleClient', () => {
jsonResponse({ choices: [{ message: { content: '{"reservations":[{"@type":"Flig' }, finish_reason: 'length' }] }),
);
await expect(new OpenAiCompatibleClient().extract(baseInput)).rejects.toThrow(
/cut off at the 4096-token limit — raise LLM_MAX_OUTPUT_TOKENS/,
/cut off at the 4096-token limit. Raise LLM_MAX_OUTPUT_TOKENS/,
);
});
@@ -768,8 +775,9 @@ describe('AnthropicClient', () => {
});
it('throws on non-2xx', async () => {
mockFetch(() => jsonResponse({ error: 'bad' }, false, 500));
await expect(new AnthropicClient().extract(baseInput)).rejects.toThrow(/500/);
mockFetch(() => jsonResponse({ error: 'bad' }, false, 401));
await expect(new AnthropicClient().extract(baseInput)).rejects.toThrow(/401/);
expect(safeFetchLlmMock).toHaveBeenCalledTimes(1);
});
it('sends a native pdf as a base64 document block', async () => {
@@ -786,6 +794,128 @@ describe('AnthropicClient', () => {
});
});
/**
* A provider that is busy for a moment (a 503 "high demand", a rate limit, a
* timeout) used to fail the reading at once, and a forwarded mail ended in the
* inbox with nothing read. Each client now asks again, at most twice, within
* the one LLM_TIMEOUT_MS.
*/
describe('a passing failure is asked again', () => {
const okOpenAi = () => jsonResponse({ choices: [{ message: { content: '{"reservations":[{"@type":"X"}]}' } }] });
const okAnthropic = () =>
jsonResponse({
content: [{ type: 'tool_use', name: 'emit_reservations', input: { reservations: [{ '@type': 'X' }] } }],
});
const busy = (headers: Record<string, string> = {}) =>
jsonResponse({ error: { message: 'model is currently experiencing high demand' } }, false, 503, headers);
beforeEach(() => vi.useFakeTimers());
afterEach(() => vi.useRealTimers());
/** Runs the extraction with every wait it sets up passed at once; answers what it settled to. */
async function settle<T>(run: Promise<T>): Promise<{ value?: T; error?: unknown }> {
const outcome = run.then(
(value) => ({ value }),
(error: unknown) => ({ error }),
);
await vi.runAllTimersAsync();
return outcome;
}
it('reads the answer after a 503 on both clients', async () => {
const openai = vi.fn().mockResolvedValueOnce(busy()).mockResolvedValueOnce(okOpenAi());
mockFetch(openai);
expect((await settle(new OpenAiCompatibleClient().extract(baseInput))).value).toEqual([{ '@type': 'X' }]);
expect(openai).toHaveBeenCalledTimes(2);
const anthropic = vi.fn().mockResolvedValueOnce(busy()).mockResolvedValueOnce(okAnthropic());
mockFetch(anthropic);
expect((await settle(new AnthropicClient().extract(baseInput))).value).toEqual([{ '@type': 'X' }]);
expect(anthropic).toHaveBeenCalledTimes(2);
});
it('gives up after two retries with the last refusal', async () => {
mockFetch(() => busy());
const { error } = await settle(new AnthropicClient().extract(baseInput));
expect(error).toBeInstanceOf(LlmRequestError);
expect(error).toMatchObject({ status: 503 });
expect(safeFetchLlmMock).toHaveBeenCalledTimes(3);
});
it('retries a rate limit, a timeout and a dropped connection, never a spent allowance', async () => {
const rateLimited = jsonResponse({ error: { code: 'rate_limit_error' } }, false, 429);
const flaky = vi
.fn()
.mockResolvedValueOnce(rateLimited)
.mockRejectedValueOnce(new DOMException('aborted', 'AbortError'))
.mockRejectedValueOnce(new TypeError('fetch failed'))
.mockResolvedValueOnce(okOpenAi());
mockFetch(flaky);
const { error } = await settle(new OpenAiCompatibleClient().extract(baseInput));
expect(error).toBeInstanceOf(TypeError);
expect(flaky).toHaveBeenCalledTimes(3);
mockFetch(() => jsonResponse({ error: 'spent', code: 'QUOTA_SPENT' }, false, 429));
const spent = await settle(new OpenAiCompatibleClient().extract(baseInput));
expect(spent.error).toMatchObject({ status: 429, code: 'QUOTA_SPENT' });
expect(safeFetchLlmMock).toHaveBeenCalledTimes(4);
});
it('keeps the 400 ladder as it was: a refused shape is not a passing failure', async () => {
const fetchFn = mockFetch(() => jsonResponse({ error: 'response_format json_schema unsupported' }, false, 400));
await settle(new OpenAiCompatibleClient().extract(baseInput));
expect(fetchFn).toHaveBeenCalledTimes(3);
});
it('waits as long as Retry-After asks, in seconds or as a date, but no longer than five seconds', async () => {
const waits: number[] = [];
const realSetTimeout = globalThis.setTimeout;
const spy = vi.spyOn(globalThis, 'setTimeout').mockImplementation(((fn: () => void, ms?: number) => {
if (ms !== undefined && ms <= 5000) waits.push(ms);
return realSetTimeout(fn, ms);
}) as typeof setTimeout);
try {
const later = new Date(Date.now() + 4000).toUTCString();
mockFetch(
vi
.fn()
.mockResolvedValueOnce(busy({ 'retry-after': '2' }))
.mockResolvedValueOnce(busy({ 'retry-after': later }))
.mockResolvedValueOnce(okOpenAi()),
);
await settle(new OpenAiCompatibleClient().extract(baseInput));
expect(waits[0]).toBe(2000);
expect(waits[1]).toBeGreaterThan(1000);
expect(waits[1]).toBeLessThanOrEqual(2000);
waits.length = 0;
mockFetch(
vi
.fn()
.mockResolvedValueOnce(busy({ 'retry-after': '120' }))
.mockResolvedValueOnce(okOpenAi()),
);
await settle(new OpenAiCompatibleClient().extract(baseInput));
expect(waits).toEqual([5000]);
} finally {
spy.mockRestore();
}
});
it('does not retry past the one timeout every try shares', async () => {
vi.stubEnv('LLM_TIMEOUT_MS', '1500');
try {
mockFetch(() => busy());
const { error } = await settle(new OpenAiCompatibleClient().extract(baseInput));
expect(error).toMatchObject({ status: 503 });
// The first wait (1 s) fits the 1.5 s, the second (2 s) does not.
expect(safeFetchLlmMock).toHaveBeenCalledTimes(2);
} finally {
vi.unstubAllEnvs();
}
});
});
/**
* The three per-client constants are gone; what replaced them is a config read.
* Nothing else in the suite would notice if one of them came back as a literal,
@@ -4,7 +4,7 @@ import { LlmRequestError } from '../../../../src/nest/llm-parse/clients/llm-requ
import { ImageTooLargeError } from '../../../../src/nest/llm-parse/image-input';
import type { LlmConfigResolver } from '../../../../src/nest/llm-parse/llm-config.resolver';
import type { LlmLocalService } from '../../../../src/nest/llm-parse/llm-local.service';
import { failureOutcome } from '../../../../src/nest/llm-parse/llm-outcome';
import { failureOutcome, isTransientLlmFailure } from '../../../../src/nest/llm-parse/llm-outcome';
import { LlmParseService } from '../../../../src/nest/llm-parse/llm-parse.service';
import { describe, it, expect, vi, beforeEach } from 'vitest';
@@ -441,7 +441,7 @@ describe('LlmParseService: a photo', () => {
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(res.warnings[0]).toMatch(/^ticket\.png: could not read file: .*20000 x 20000 pixels/);
expect(extract).not.toHaveBeenCalled();
});
@@ -517,7 +517,7 @@ describe('LlmParseService.readReceipt', () => {
extract.mockRejectedValue(new Error('429'));
const failed = await svc().readReceipt(file('r.jpg'), 1);
expect(failed.receipt).toBeNull();
expect(failed.warnings[0]).toMatch(/AI parsing failed — 429/);
expect(failed.warnings[0]).toMatch(/AI parsing failed: 429/);
extract.mockResolvedValue([]);
expect(await svc().readReceipt(file('r.jpg'), 1)).toEqual({
receipt: null,
@@ -754,4 +754,24 @@ describe('LlmParseService.parse outcome', () => {
expect(failureOutcome(new ImageTooLargeError('too many pixels'))).toBe('too_large');
expect(failureOutcome('boom')).toBe('provider_error');
});
it('LLM-OUTCOME-006: a busy provider, a timeout and a dropped connection may pass; a spent allowance does not', () => {
for (const status of [408, 500, 502, 503, 504]) {
expect(isTransientLlmFailure(new LlmRequestError('x', status, undefined))).toBe(true);
}
expect(isTransientLlmFailure(new LlmRequestError('x', 429, undefined))).toBe(true);
expect(isTransientLlmFailure(new LlmRequestError('x', 429, 'rate_limit_error'))).toBe(true);
expect(isTransientLlmFailure(new LlmRequestError('x', 429, 'QUOTA_SPENT'))).toBe(false);
expect(isTransientLlmFailure(new LlmRequestError('x', 429, 'HARD_CAP'))).toBe(false);
for (const status of [400, 401, 403, 404, 413, 501]) {
expect(isTransientLlmFailure(new LlmRequestError('x', status, undefined))).toBe(false);
}
expect(isTransientLlmFailure(new DOMException('aborted', 'AbortError'))).toBe(true);
expect(isTransientLlmFailure(new DOMException('timed out', 'TimeoutError'))).toBe(true);
expect(isTransientLlmFailure(new TypeError('fetch failed'))).toBe(true);
expect(isTransientLlmFailure(new TypeError('x is not a function'))).toBe(false);
expect(isTransientLlmFailure(new LlmContextOverflowError('prompt is too long'))).toBe(false);
expect(isTransientLlmFailure(new Error('LLM request failed (503)'))).toBe(false);
expect(isTransientLlmFailure('boom')).toBe(false);
});
});
@@ -131,6 +131,40 @@ describe('MailReadService.read', () => {
expect(lines.join(' | ')).not.toContain('ABC123');
});
it('flags a failure that may pass, and no other, as worth trying again', async () => {
vi.spyOn(console, 'error').mockImplementation(() => undefined);
extract.mockRejectedValue(new LlmRequestError('LLM request failed (503): high demand', 503, undefined));
expect(await service.read(input(), 1, '2026-11-13')).toMatchObject({
outcome: 'provider_error',
bookings: [],
transient: true,
});
extract.mockRejectedValue(new LlmRequestError('gate', 429, 'QUOTA_SPENT'));
expect(await service.read(input(), 1, '2026-11-13')).toMatchObject({
outcome: 'quota_exhausted',
transient: false,
});
extract.mockRejectedValue(new LlmRequestError('LLM request failed (401): bad key', 401, undefined));
expect(await service.read(input(), 1, '2026-11-13')).toMatchObject({ outcome: 'provider_error', transient: false });
extract.mockResolvedValue([{ kind: 'new_booking', reservations: [flight], trip_ref: 't1' }]);
expect(await service.read(input(), 1, '2026-11-13')).toMatchObject({ outcome: 'ok', transient: false });
});
it('reports an answer in another shape as a provider failure, not as a mail without a booking', async () => {
vi.spyOn(console, 'error').mockImplementation(() => undefined);
extract.mockResolvedValue([flight]);
expect(await service.read(input(), 1, '2026-11-13')).toMatchObject({
outcome: 'provider_error',
bookings: [],
transient: false,
});
extract.mockResolvedValue([]);
expect((await service.read(input(), 1, '2026-11-13')).outcome).toBe('empty');
});
it('reads through the local router without a trip choice', async () => {
resolve.mockResolvedValue({ provider: 'local', model: 'qwen', vision: 'off' });
routeExtraction.mockResolvedValue({ kiItems: [flight], warnings: [], outcome: 'ok' });
@@ -3,10 +3,12 @@
* the listed trips can be chosen, a field name the contract does not know is
* dropped, and a mail cannot close its own data tag.
*/
import { UnreadableLlmResponse } from '../../../../src/nest/llm-parse/clients/openai-compatible.client';
import {
buildMailPrompt,
MAIL_READ_JSON_SCHEMA,
MAIL_READ_MAX_BOOKINGS,
MAIL_READ_USER_TEXT,
mailReadText,
readMailAnswer,
} from '../../../../src/nest/llm-parse/mail-read';
@@ -41,6 +43,23 @@ describe('buildMailPrompt', () => {
expect(buildMailPrompt([], '2026-11-13')).toContain('(none: the person has no trip a booking could go to)');
});
/*
* Only the Anthropic client hands the model a tool. On the OpenAI-compatible
* json_object and no-format rungs the prompt alone says the shape, and it
* named a tool and never the "bookings" key: an answer under another key read
* as no booking and the mail was discarded.
*/
it("names the answer's exact shape but not how to send it, so every provider reads it alike", () => {
const prompt = buildMailPrompt(TRIPS, '2026-11-13');
expect(prompt).toContain('{ "bookings": [ ... ] }');
expect(prompt).toContain('An email that holds no booking gets { "bookings": [] }.');
expect(prompt).not.toContain('emit_bookings');
// The Anthropic client adds "answer only by calling the tool"; nothing here may say otherwise.
expect(prompt).not.toMatch(/no prose|in text|only one JSON object|exactly one JSON object/i);
expect(MAIL_READ_USER_TEXT).toContain('{ "bookings": [ ... ] }');
expect(MAIL_READ_USER_TEXT).not.toContain('emit_bookings');
});
it('asks for a trip reference next to every booking', () => {
expect(MAIL_READ_JSON_SCHEMA.properties.bookings.items.required).toEqual(['kind', 'reservations', 'trip_ref']);
});
@@ -91,6 +110,18 @@ describe('readMailAnswer', () => {
expect(readMailAnswer(many, TRIPS, identity)).toHaveLength(MAIL_READ_MAX_BOOKINGS);
});
it('throws on an answer whose entries are none of them bookings, and still reads an empty one as no booking', () => {
expect(() => readMailAnswer([flight, { '@type': 'LodgingReservation' }], TRIPS, identity)).toThrow(
UnreadableLlmResponse,
);
expect(() => readMailAnswer([{ reservations: 'none' }], TRIPS, identity)).toThrow(/shape other than the bookings/);
expect(readMailAnswer([], TRIPS, identity)).toEqual([]);
// One entry that reads as a booking is enough for the others to be skipped quietly.
expect(
readMailAnswer([flight, { kind: 'new_booking', reservations: [flight], trip_ref: null }], TRIPS, identity),
).toHaveLength(1);
});
it('puts each reservation through the given normaliser', () => {
const [booking] = readMailAnswer(
[
@@ -682,6 +682,104 @@ describe('a mail that keeps failing', () => {
});
});
/*
* A plain hotel mail met a provider "experiencing high demand": the reading
* failed in passing, the mail was settled at once with an empty inbox entry,
* and the attempt counted against the person's daily AI limit.
*/
describe('a mail the AI could not read for a moment', () => {
const HOUR_MS = 60 * 60 * 1000;
const busy = (): AiReading => ({
outcome: 'provider_error',
bookings: [],
documentText: BODY,
imageOnly: false,
transient: true,
});
const flightReading = (): AiReading => ({
outcome: 'ok',
documentText: BODY,
imageOnly: false,
transient: false,
bookings: [
{
kind: 'new_booking',
reservations: [{ '@type': 'FlightReservation' }] as never,
tripRef: 't1',
tripConfidence: 0.9,
uncertainFields: [],
suggestedNewTrip: null,
},
],
});
const pendingNotice = expect.objectContaining({ event: 'mail_booking_pending' });
async function upload(userId: number, id: string): Promise<number> {
const taken = await intake().upload(eml(id), userId);
if (taken.status !== 'accepted') throw new Error('not taken in');
return taken.messageId;
}
it('is read again later, and waits in the inbox only after its last try, without counting against the limit', async () => {
const user = await person();
reader.isAvailable.mockResolvedValue(true);
machine.mockResolvedValue([]);
aiRead.mockResolvedValue(busy());
const messageId = await upload(user.id, 'busy');
expect(await job().tick(NOW)).toBe(1);
expect(await findRow(orm(), MailIngestMessages, { id: messageId })).toMatchObject({ status: 'queued', ai_used: 0 });
expect(await entriesOf(messageId)).toHaveLength(0);
expect(notifications.send).not.toHaveBeenCalledWith(pendingNotice);
expect(await job().tick(new Date(NOW.getTime() + HOUR_MS))).toBe(1);
expect(await findRow(orm(), MailIngestMessages, { id: messageId })).toMatchObject({ status: 'queued' });
expect(await job().tick(new Date(NOW.getTime() + 2 * HOUR_MS))).toBe(1);
expect(aiRead).toHaveBeenCalledTimes(3);
expect(await findRow(orm(), MailIngestMessages, { id: messageId })).toMatchObject({
status: 'processed',
reason: 'ai_provider_error',
ai_used: 0,
});
expect(await entriesOf(messageId)).toMatchObject([{ resolution: 'pending', reason: 'ai_provider_error' }]);
expect(notifications.send).toHaveBeenCalledWith(pendingNotice);
});
it('adds its booking once the AI answers on a later try', async () => {
const user = await person();
const trip = await makeTrip(orm(), user.id, { start_date: '2030-03-01', end_date: '2030-03-10' });
reader.isAvailable.mockResolvedValue(true);
machine.mockResolvedValue([]);
aiRead.mockResolvedValueOnce(busy()).mockResolvedValueOnce(flightReading());
const messageId = await upload(user.id, 'later');
expect(await job().tick(NOW)).toBe(1);
expect(await job().tick(new Date(NOW.getTime() + HOUR_MS))).toBe(1);
expect(await findRow(orm(), MailIngestMessages, { id: messageId })).toMatchObject({
status: 'processed',
ai_used: 1,
});
expect(await entriesOf(messageId)).toMatchObject([{ resolution: 'auto_applied' }]);
expect(await countRows(orm(), Reservations, { trip: trip.id })).toBe(1);
});
it('is settled at once when its machine-readable data names the booking', async () => {
const user = await person();
await makeTrip(orm(), user.id, { start_date: '2030-03-01', end_date: '2030-03-10' });
reader.isAvailable.mockResolvedValue(true);
aiRead.mockResolvedValue(busy());
const messageId = await upload(user.id, 'machine');
expect(await job().tick(NOW)).toBe(1);
expect(await findRow(orm(), MailIngestMessages, { id: messageId })).toMatchObject({
status: 'processed',
ai_used: 0,
});
expect(await entriesOf(messageId)).toMatchObject([{ source: 'kitinerary', resolution: 'auto_applied' }]);
});
});
describe('what the person sees', () => {
const inbox = () => t.get(MailIngestInboxService);