fix(assistant): improve trip proposals and approvals

This commit is contained in:
Maurice
2026-12-02 22:03:28 +01:00
parent 01ad13623c
commit 62a3e63f3f
144 changed files with 4093 additions and 1336 deletions
+177 -15
View File
@@ -39,7 +39,9 @@ import { WeatherService } from '../../src/nest/weather/weather.service';
import { tourRouteCard } from '../helpers/assistant-tour-cards';
import { makeBudgetItem } from '../helpers/factories/budget';
import { makeCollabMessage } from '../helpers/factories/collab';
import { makeDayAssignment } from '../helpers/factories/itinerary';
import { makePlace } from '../helpers/factories/places';
import { makeReservation } from '../helpers/factories/reservations';
import { countRows, deleteRows, findRow, updateRows } from '../helpers/factories/rows';
import { setAddonEnabled, setCollabFeature } from '../helpers/factories/settings';
import { addTripMember, makeTrip, readTripDays } from '../helpers/factories/trips';
@@ -401,6 +403,21 @@ describe('Trip assistant e2e', () => {
expect(toolAnswer?.content).toContain('Kinkaku-ji');
});
it('offers hiking tools and waypoint guidance in the first request for a hike', async () => {
const t = await travelerWithTrip();
await setAddonEnabled(orm, 'tours', true);
provider.script = [say('I will use the documented trail.')];
const turn = await post(`${t.base}/chat`, t.userId, {
...CTX,
threadId: null,
text: 'Leg mir mal ne Tour am Fuji an Hiking Anspruchsvoll',
});
expect(turn.status).toBe(200);
expect(provider.requests).toHaveLength(1);
expect(provider.requests[0].tools?.map((tool) => tool.function.name)).toContain('propose_hike');
expect(provider.requests[0].messages[0].content).toContain('Never guess coordinates for numbered stations');
});
it('ASTE2E-005: a change is held, applied with its stored arguments, broadcast, and the turn goes on', async () => {
const t = await travelerWithTrip();
const { turn, toolCallId, threadId } = await proposePlace(t, 'Ryoan-ji');
@@ -445,19 +462,164 @@ describe('Trip assistant e2e', () => {
expect(await countRows(orm, Places, { trip: t.tripId, name: 'Ryoan-ji' })).toBe(1);
});
it('ASTE2E-006: a discarded change does not run, and the model is told', async () => {
it('offers booking tools immediately and holds only the confirmed booking when the model also tries place writes', async () => {
const t = await travelerWithTrip();
provider.script = [
callTools({ id: 'trip-summary', name: 'get_trip_summary', args: {} }),
callTools({ id: 'model-probe', name: 'create_place', args: { name: '__probe5__' } }),
callTools({ id: 'wrong-place', name: 'create_place', args: { name: 'Nishiki restaurant' } }),
callTools({
id: 'confirmed-booking',
name: 'create_reservation',
args: {
title: 'Confirmed dinner',
type: 'restaurant',
confirmation_number: 'ABC-12345',
notes: 'Window table. Booking code: ABC-12345.',
reservation_time: '13:00',
},
}),
];
const turn = await post(`${t.base}/chat`, t.userId, {
...CTX,
locale: 'de',
threadId: null,
text: 'Kannst du mir für das Restaurant eine Buchung zu 13 Uhr anlegen, ist schon vom Restaurant bestätigt. Buchungsnummer ABC-12345.',
});
const [held] = ofType(turn.chunks, 'tool-approval-request');
const [thread] = ofType(turn.chunks, 'data-trek-thread');
expect(provider.requests[0]?.tools?.map((tool) => tool.function.name)).toContain('create_reservation');
expect(ofType(turn.chunks, 'tool-approval-request')).toHaveLength(1);
expect(ofType(turn.chunks, 'tool-output-error')).toEqual([
expect.objectContaining({ errorText: expect.stringContaining('diagnostic placeholder') }),
expect.objectContaining({ errorText: expect.stringContaining('record a booking') }),
]);
expect(ofType(turn.chunks, 'data-trek-change')[0]?.data.rows).toContainEqual(
expect.objectContaining({ labelKey: 'confirmation', after: 'ABC-12345' }),
);
expect(ofType(turn.chunks, 'data-trek-change')[0]?.data.card).toMatchObject({
kind: 'booking',
items: [{ status: 'confirmed' }],
});
const stored = await findRow(orm, AssistantToolCalls, { id: held.toolCallId });
if (!stored) throw new Error('Booking draft was not saved');
const storedMessage = await findRow(orm, AssistantMessages, { id: stored.message_id });
if (!storedMessage) throw new Error('Booking draft message was not saved');
const args = JSON.parse(stored.args) as Record<string, unknown>;
expect(args.status).toBe('confirmed');
// Simulate a draft that was held before the server filled the omitted status.
delete args.status;
await updateRows(orm, AssistantToolCalls, { id: held.toolCallId }, { args: JSON.stringify(args) });
const parts = (JSON.parse(storedMessage.parts) as AssistantMessagePart[]).map((part) => {
if (part.type === 'tool-call') return { ...part, args };
if (part.type !== 'data-trek-change' || part.data.card?.kind !== 'booking') return part;
const { card } = part.data;
return {
...part,
data: { ...part.data, card: { ...card, items: card.items.map((item) => ({ ...item, status: 'pending' })) } },
};
});
await updateRows(orm, AssistantMessages, { id: stored.message_id }, { parts: JSON.stringify(parts) });
const reopened = await get(`${t.base}/threads/${thread.data.threadId}`, t.userId);
const reopenedParts = reopened.body.messages[1].parts as AssistantMessagePart[];
expect(reopenedParts.find((part) => part.type === 'data-trek-change')).toMatchObject({
data: { card: { kind: 'booking', items: [{ status: 'confirmed' }] } },
});
const requestCount = provider.requests.length;
provider.script = [() => ({ status: 429 })];
const decided = await post(`${t.base}/threads/${thread.data.threadId}/decisions`, t.userId, {
...CTX,
decisions: [{ toolCallId: held.toolCallId, approved: true }],
});
expect(provider.requests).toHaveLength(requestCount);
expect(ofType(decided.chunks, 'error')).toHaveLength(0);
expect(ofType(decided.chunks, 'tool-output-error')).toHaveLength(0);
expect(await findRow(orm, Reservations, { trip: t.tripId, title: 'Confirmed dinner' })).toMatchObject({
status: 'confirmed',
confirmation_number: 'ABC-12345',
notes: 'Window table.',
});
expect(await findRow(orm, Places, { trip: t.tripId, name: 'Nishiki restaurant' })).toBeNull();
});
it('saves a booking link and ends on the receipt without asking the model again', async () => {
const t = await travelerWithTrip();
const [day] = await readTripDays(orm, t.tripId);
const venue = await makePlace(orm, t.tripId, { name: 'Dinner venue' });
const visit = await makeDayAssignment(orm, day.id, venue.id);
const booking = await makeReservation(orm, t.tripId, {
title: 'Confirmed dinner',
type: 'restaurant',
status: 'confirmed',
day: day.id,
});
provider.script = [
callTools({
id: 'link-booking',
name: 'update_reservation',
args: { reservationId: booking.id, assignment_id: visit.id },
}),
];
const turn = await post(`${t.base}/chat`, t.userId, {
...CTX,
locale: 'de',
threadId: null,
text: 'Verknüpfe die Buchung mit dem Restaurant im Tagesplan.',
});
const [held] = ofType(turn.chunks, 'tool-approval-request');
const [thread] = ofType(turn.chunks, 'data-trek-thread');
const requestCount = provider.requests.length;
provider.script = [() => ({ status: 429 })];
const decided = await post(`${t.base}/threads/${thread.data.threadId}/decisions`, t.userId, {
...CTX,
decisions: [{ toolCallId: held.toolCallId, approved: true }],
});
expect(provider.requests).toHaveLength(requestCount);
expect(ofType(decided.chunks, 'error')).toHaveLength(0);
expect(ofType(decided.chunks, 'data-trek-applied')).toHaveLength(1);
expect(await findRow(orm, Reservations, { id: booking.id })).toMatchObject({
status: 'confirmed',
assignment_id: visit.id,
});
});
it('ends a failed approval at the error without asking the model for another change', async () => {
const t = await travelerWithTrip();
const { toolCallId, threadId } = await proposePlace(t, 'Ryoan-ji');
await updateRows(
orm,
AssistantToolCalls,
{ id: toolCallId },
{
args: JSON.stringify({ name: '__probe__' }),
},
);
const requestCount = provider.requests.length;
provider.script = [callTools({ id: 'test-write', name: 'create_place', args: { name: '__probe__' } })];
const decided = await post(`${t.base}/threads/${threadId}/decisions`, t.userId, {
...CTX,
decisions: [{ toolCallId, approved: true }],
});
expect(ofType(decided.chunks, 'tool-output-error')).toHaveLength(1);
expect(ofType(decided.chunks, 'tool-approval-request')).toHaveLength(0);
expect(provider.requests).toHaveLength(requestCount);
expect(await findRow(orm, AssistantToolCalls, { id: toolCallId })).toMatchObject({ state: 'failed' });
expect(await findRow(orm, Places, { trip: t.tripId, name: '__probe__' })).toBeNull();
});
it('ASTE2E-006: discarding ends the round without a new model call', async () => {
const t = await travelerWithTrip();
const { toolCallId, threadId } = await proposePlace(t, 'Nijo Castle');
provider.script = [say('Fine, left it out.')];
const requestCount = provider.requests.length;
provider.script = [callTools({ id: 'test-write', name: 'create_place', args: { name: '__probe__' } })];
const decided = await post(`${t.base}/threads/${threadId}/decisions`, t.userId, {
...CTX,
decisions: [{ toolCallId, approved: false }],
});
expect(ofType(decided.chunks, 'tool-output-denied')).toEqual([{ type: 'tool-output-denied', toolCallId }]);
expect(await findRow(orm, Places, { trip: t.tripId, name: 'Nijo Castle' })).toBeNull();
expect(provider.requests.at(-1)?.messages.find((message) => message.role === 'tool')?.content).toContain(
'discarded',
);
expect(ofType(decided.chunks, 'tool-approval-request')).toHaveLength(0);
expect(provider.requests).toHaveLength(requestCount);
});
it('ASTE2E-007: decisions name every waiting change, in a thread of the user', async () => {
@@ -705,7 +867,7 @@ describe('Trip assistant e2e', () => {
expect(await countRows(orm, AssistantThreads, { trip: t.tripId })).toBe(0);
});
it('ASTE2E-016: the bookings of an attached file are held as cards, applied, and the model is told', async () => {
it('ASTE2E-016: one approval saves the imported booking and attaches its source file', async () => {
const t = await travelerWithTrip();
const bookingImport = nestApp.get(BookingImportService);
const extractor = vi.spyOn(bookingImport, 'isAvailable').mockReturnValue(true);
@@ -741,22 +903,21 @@ describe('Trip assistant e2e', () => {
'tool-input-available',
'tool-approval-request',
'data-trek-change',
'data-trek-follow-ups',
'finish-step',
'finish',
]);
expect(ofType(turn.chunks, 'text-delta')[0].delta).toBe(
'I found 1 booking in ticket.pdf. Add it below if it looks right.',
);
expect(ofType(turn.chunks, 'data-trek-follow-ups')[0].data.questions).toEqual([
'Keep the file with this booking',
]);
expect(ofType(turn.chunks, 'tool-input-start')[0].toolName).toBe('read_booking_file');
expect(ofType(turn.chunks, 'data-trek-change')[0].data).toMatchObject({
verbKey: 'importBooking',
subject: 'Gion Corner show',
undoable: false,
});
expect(ofType(turn.chunks, 'data-trek-change')[0].data.rows).toContainEqual(
expect.objectContaining({ labelKey: 'attachedTo', after: 'ticket.pdf' }),
);
const file = expect.objectContaining({ originalname: 'ticket.pdf' });
expect(preview).toHaveBeenCalledWith([file], 'no-ai', t.userId);
threadId = ofType(turn.chunks, 'data-trek-thread')[0].data.threadId;
@@ -773,7 +934,6 @@ describe('Trip assistant e2e', () => {
]);
expect(shown.body.messages[1].status).toBe('awaiting_approval');
provider.script = [say('The show is on your trip.')];
const decided = await post(`${t.base}/threads/${threadId}/decisions`, t.userId, {
...CTX,
decisions: [{ toolCallId, approved: true }],
@@ -783,10 +943,12 @@ describe('Trip assistant e2e', () => {
const booked = await findRow(orm, Reservations, { trip: t.tripId, title: 'Gion Corner show' });
expect(booked).not.toBeNull();
expect(applied.data.ids).toEqual([booked?.id]);
const sent = provider.requests[0].messages.map((message) => String(message.content ?? '')).join('\n');
expect(sent).toContain('The user attached the file "ticket.pdf"');
expect(sent).toContain('"Gion Corner show" was added to the trip');
expect(provider.requests[0].tools?.map((tool) => tool.function.name)).not.toContain('import_booking');
const files = await get(`/api/trips/${t.tripId}/files`, t.userId);
expect(files.status).toBe(200);
expect(files.body.files).toEqual([
expect.objectContaining({ original_name: 'ticket.pdf', reservation_id: booked?.id }),
]);
expect(provider.requests).toHaveLength(0);
});
it('ASTE2E-017: a search and a weather lookup stream where they look and come back as cards, kept with the answer', async () => {
const t = await travelerWithTrip();
@@ -20,6 +20,7 @@ import {
type StepRecord,
} from '../../../../src/nest/assistant/assistant-agent';
import { buildTripCard } from '../../../../src/nest/assistant/assistant-context';
import { appliedPlanPreview, withPlanEdits } from '../../../../src/nest/assistant/assistant-decisions.helpers';
import { FOLLOW_UPS_ANSWER, followUpsOf } from '../../../../src/nest/assistant/assistant-follow-ups';
import {
MAX_CARDS_PER_STEP,
@@ -33,6 +34,7 @@ import { UiStreamWriter } from '../../../../src/nest/assistant/ui-stream.writer'
import type { SseStream } from '../../../../src/nest/common/sse-stream';
import {
ASSISTANT_FOLLOW_UPS_TOOL,
assistantPlanEditsSchema,
type AssistantChangePreview,
type TrekCard,
type UiStreamChunk,
@@ -1034,12 +1036,14 @@ describe('runAgentLoop', () => {
});
it('ASTAGT-039: a provider web search is a step of its own, the cited pages a part after the text, neither sent back as a call', async () => {
const exa = 'https://exa.ai/library/places?example=test';
const t = setup(
[
[
{ type: 'web-search', query: 'Rostock harbour restaurants' },
{ type: 'text-delta', delta: 'Eat at the Alter Strom.' },
{ type: 'source', source: { url: 'https://a.example', title: 'A guide' } },
{ type: 'source', source: { url: exa, title: '{"places":[{"id":"truncated' } },
{ type: 'finish', reason: 'stop' },
],
],
@@ -1057,7 +1061,15 @@ describe('runAgentLoop', () => {
result: 'searched',
},
{ type: 'text', text: 'Eat at the Alter Strom.' },
{ type: 'data-trek-sources', data: { sources: [{ url: 'https://a.example', title: 'A guide' }] } },
{
type: 'data-trek-sources',
data: {
sources: [
{ url: 'https://a.example', title: 'A guide' },
{ url: exa, title: '' },
],
},
},
]);
expect(types(t.chunks)).toEqual(
expect.arrayContaining(['tool-input-available', 'tool-output-available', 'data-trek-sources']),
@@ -1073,6 +1085,54 @@ describe('runAgentLoop', () => {
expect(unable.requests[0]?.webSearch).toBe(false);
});
it('applies edited place details without changing the held visit target and reflects them in the receipt', () => {
const stored = { dayId: 7, name: 'Old name', address: 'Old address', lat: 35, lng: 139 };
const edits = assistantPlanEditsSchema.parse({
place: { name: 'New name', address: null, lat: 36, lng: 140 },
categoryId: 13,
notes: 'Use the side entrance',
startTime: '10:00',
});
expect(assistantPlanEditsSchema.safeParse({ place: { dayId: 42, price: 99 } }).success).toBe(false);
expect(withPlanEdits('create_and_assign_place', stored, edits)).toEqual({
dayId: 7,
name: 'New name',
lat: 36,
lng: 140,
category_id: 13,
assignment_notes: 'Use the side entrance',
place_time: '10:00',
});
expect(withPlanEdits('assign_place_to_day', { dayId: 7, placeId: 8 }, edits)).toEqual({
dayId: 7,
placeId: 8,
notes: 'Use the side entrance',
place_time: '10:00',
});
const preview: AssistantChangePreview = {
toolCallId: 'w1',
verbKey: 'addPlaceToDay',
subject: 'Old name',
rows: [],
dayId: 7,
placeIds: [],
undoable: true,
effect: {
kind: 'add',
dayId: 7,
fromDayId: null,
assignmentId: null,
placeId: null,
place: { name: 'Old name', lat: 35, lng: 139, categoryId: null },
},
};
expect(appliedPlanPreview(preview, edits, { place: { category: { name: 'Garden' } } })).toMatchObject({
subject: 'New name',
effect: { place: { name: 'New name', lat: 36, lng: 140, categoryId: 13 } },
rows: expect.arrayContaining([expect.objectContaining({ labelKey: 'category', after: 'Garden' })]),
});
});
it('ASTAGT-041: a step that searched the web and called a read answers only the read, never the search', async () => {
const t = setup(
[
@@ -115,8 +115,9 @@ describe('attachedPort', () => {
it('ASTATL-005: the standing instructions say how an attached file is read and booked', () => {
const prompt = systemPrompt('English');
expect(prompt).toContain('read it with read_attached_file');
expect(prompt).toContain('proposed with create_reservation');
expect(prompt).toContain('Read its content with read_attached_file');
expect(prompt).toContain('If TREK already offered or saved a booking from the file, reuse that proposal or booking.');
expect(prompt).toContain('Only propose create_reservation for a booking that has neither been offered nor saved.');
});
it('ASTATL-006: a keep is always held, checked, and names the file; an attachment of no one here is refused alike', () => {
@@ -8,6 +8,7 @@ import {
AssistantBookingImportService,
emptyReason,
} from '../../../../src/nest/assistant/assistant-booking-import.service';
import { AssistantKeepFileService } from '../../../../src/nest/assistant/assistant-keep-file.service';
import { MAX_WRITES_PER_STEP } from '../../../../src/nest/assistant/assistant-tools.constants';
import { BookingImportService } from '../../../../src/nest/booking-import/booking-import.service';
import { DemoService } from '../../../../src/nest/common/demo.service';
@@ -56,6 +57,7 @@ async function make(opts: Opts = {}) {
const trips = { findAccessible: vi.fn(async () => (opts.trip === false ? undefined : { id: 5, user_id: 7 })) };
const guards = { hasTripPermission: vi.fn(async () => opts.right !== false) };
const demo = { isDemoUserId: vi.fn(async () => opts.demo === true) };
const files = { keep: vi.fn(async () => ({ ok: true, value: { file: { id: 82 } } })) };
const moduleRef = await Test.createTestingModule({
providers: [
AssistantBookingImportService,
@@ -63,9 +65,10 @@ async function make(opts: Opts = {}) {
{ provide: TripAccessService, useValue: trips },
{ provide: McpToolGuardsService, useValue: guards },
{ provide: DemoService, useValue: demo },
{ provide: AssistantKeepFileService, useValue: files },
],
}).compile();
return { service: moduleRef.get(AssistantBookingImportService), bookingImport, trips, guards };
return { service: moduleRef.get(AssistantBookingImportService), bookingImport, trips, guards, files };
}
async function codeOf(promise: Promise<unknown>): Promise<string | null> {
@@ -135,11 +138,25 @@ describe('AssistantBookingImportService', () => {
const run = await t.service.apply(7, 5, { ...ITEM });
const reservation = { id: 81, title: 'ICE 123', type: 'train', day_id: 31 };
expect(run).toEqual({ ok: true, value: { reservation } });
expect(t.bookingImport.confirm).toHaveBeenCalledWith('5', 7, [ITEM], undefined);
expect(t.bookingImport.confirm).toHaveBeenCalledWith('5', 7, [ITEM], undefined, { unassignedHotel: true });
expect(t.trips.findAccessible).toHaveBeenCalledWith(5, 7);
expect(t.guards.hasTripPermission).toHaveBeenCalledWith('reservation_edit', 5, 7);
});
it('keeps the original receipt with the booking on the same approval', async () => {
const t = await make();
const out = await t.service.apply(7, 5, { ...ITEM, attachmentId: 'receipt', receiptKey: 'file-digest' }, 12);
expect(t.bookingImport.confirm).toHaveBeenCalledWith('5', 7, [ITEM], undefined, {
unassignedHotel: true,
fallbackId: 'file-digest',
});
expect(t.files.keep).toHaveBeenCalledWith(
{ userId: 7, tripId: 5, threadId: 12 },
{ attachmentId: 'receipt', reservation_id: 81 },
);
expect(out).toMatchObject({ ok: true, value: { reservation: { id: 81 }, receipt: { file: { id: 82 } } } });
});
it('ASTBKI-004: refused for a demo account, off the trip, without the right, or when broken', async () => {
const refused = async (opts: Parameters<typeof make>[0]) => {
const t = await make(opts);
@@ -0,0 +1,69 @@
import {
bookingConfirmationFrom,
bookingEntryIntent,
isStandaloneBookingRequest,
withBookingConfirmation,
} from '../../../../src/nest/assistant/assistant-booking-intent';
import { describe, expect, it } from 'vitest';
describe('bookingEntryIntent', () => {
it.each([
['Kannst du mir zur Udon-Kette Marugame eine Buchung zu 13 Uhr bitte anlegen?', 'booking'],
['Für diesen Ort bitte eine bestätigte Reservierung eintragen.', 'booking'],
['Record a booking at this place for 13:00.', 'booking'],
['Bitte eine Buchung eintragen und einen Ort hinzufügen.', 'combined'],
['Add this restaurant to the day and record my reservation.', 'combined'],
['Welche Buchung hat den Code ABC-12345?', null],
['Keine Buchung anlegen, sondern einen Ort.', null],
['Please do not create a reservation.', null],
['Zeig mir Orte für Tag 2.', null],
] as const)('routes %s', (text, intent) => {
expect(bookingEntryIntent(text)).toBe(intent);
});
});
describe('isStandaloneBookingRequest', () => {
it.each([
['Bitte eine Buchung zu 13 Uhr anlegen. Ist schon vom Restaurant bestätigt.', true],
['Verknüpfe die Buchung mit dem Restaurant im Tagesplan.', true],
['Link the reservation to the existing visit on day 1.', true],
['Bitte die Buchung anlegen und einen Ort hinzufügen.', false],
['Record the reservation and add an expense.', false],
['Bitte die Buchung anlegen. Verknüpfe sie mit dem Termin.', false],
['Welche Buchung hat den Code ABC-12345?', false],
] as const)('uses a receipt as the final answer for %s', (text, standalone) => {
expect(isStandaloneBookingRequest(text)).toBe(standalone);
});
});
describe('bookingConfirmationFrom', () => {
it.each([
[
'Bitte eine Buchung anlegen, ist schon vom Restaurant bestätigt. Buchungsnummer ABC-12345.',
{ reference: 'ABC-12345' },
],
['Bitte eine bestätigte Reservierung eintragen.', { reference: null }],
['Record the reservation. It has already been confirmed. Booking code 4YRT2P.', { reference: '4YRT2P' }],
['Bitte eine Buchung eintragen. Das Restaurant hat noch nicht bestätigt.', null],
['Bitte eine Buchung anlegen. Wird sie schon bestätigt?', null],
['Bitte eine Buchung anlegen, wenn sie bestätigt ist.', null],
['Please log the reservation. It will be confirmed tomorrow.', null],
['Bitte eine Buchung eintragen. Buchungsnummer ABC-12345.', null],
['Bitte zwei Buchungen eintragen. Die erste ist schon bestätigt.', null],
] as const)('reads explicit confirmation from %s', (text, confirmation) => {
expect(bookingConfirmationFrom(text)).toEqual(confirmation);
});
it('updates only the targeted booking and keeps unrelated metadata', () => {
const confirmation = { reference: 'ABC-12345' };
const args = { title: 'Dinner', notes: 'Window table', confirmation_number: 'ABC-12345' };
expect(withBookingConfirmation('create_reservation', args, confirmation, false)).toEqual({
...args,
status: 'confirmed',
});
expect(withBookingConfirmation('create_place', args, confirmation, true)).toBe(args);
const other = { ...args, confirmation_number: 'OTHER-12345' };
expect(withBookingConfirmation('create_reservation', other, confirmation, true)).toBe(other);
});
});
@@ -0,0 +1,33 @@
import {
isHikePlanningRequest,
wantsChallengingHike,
withChallengingHikeLimit,
} from '../../../../src/nest/assistant/assistant-hike-intent';
import { describe, expect, it } from 'vitest';
describe('hike planning from a chat request', () => {
it('uses the challenging route profile for a request without a stated ceiling', () => {
expect(wantsChallengingHike('Leg mir mal ne Tour am Fuji an Hiking Anspruchsvoll')).toBe(true);
expect(withChallengingHikeLimit('propose_hike', { max_hiking_difficulty: 3 }, true)).toEqual({
max_hiking_difficulty: 4,
});
});
it.each([
'Plane eine anspruchsvolle Wanderung bis T3',
'Plane eine Wanderung. Sie soll nicht anspruchsvoll sein',
'Plan a challenging hike but avoid exposed terrain',
'Plan a demanding hike, at most grade 3',
])('does not replace a constrained preference in %s', (request) => {
expect(wantsChallengingHike(request)).toBe(false);
});
it('keeps difficulty limits on deliberate alternatives and saves the chosen profile as given', () => {
const easyWay = { max_hiking_difficulty: 3, variant_label: 'Easier' };
const chosen = { max_hiking_difficulty: 3 };
expect(withChallengingHikeLimit('propose_hike', easyWay, true)).toBe(easyWay);
expect(withChallengingHikeLimit('create_hike', chosen, true)).toBe(chosen);
expect(isHikePlanningRequest('Where is my train ticket?')).toBe(false);
});
});
@@ -61,6 +61,31 @@ function call(id: string, state: string, extra: Partial<AssistantToolCallRow> =
const NOW = new Date('2026-10-21T10:05:00Z');
describe('toChatHistory', () => {
it('leaves diagnostic place writes out of model history while keeping real calls in the same step', () => {
const rows = [
row('user', [{ type: 'text', text: 'Record a booking' }]),
row(
'assistant',
[
{
type: 'tool-call',
toolCallId: 'probe',
toolName: 'create_place',
args: { name: '__probe5__' },
result: 'Discarded',
},
{ type: 'tool-call', toolCallId: 'read', toolName: 'list_places', args: {}, result: [] },
],
{ provider_state: '{"adapter":"openai-responses","items":[{"type":"function_call","call_id":"probe"}]}' },
),
];
expect(toChatHistory(rows, new Map())).toEqual([
{ role: 'user', text: 'Record a booking' },
{ role: 'assistant', text: '', toolCalls: [{ id: 'read', name: 'list_places', args: {} }], providerState: null },
{ role: 'tool', toolCallId: 'read', name: 'list_places', output: '[]' },
]);
});
it('ASTHIS-001: starts at the first user message and answers every call', () => {
const rows = [
row('assistant', [{ type: 'text', text: 'orphan' }]),
@@ -581,7 +581,7 @@ describe('a scope opens its session and writes its turn', () => {
expect(await read.gate.refusalOf('mark_country_visited', { country_code: 'JP' })).toBeNull();
});
it('ASTSCP-052: the trip card is read through the session, or on a session of its own two reads', async () => {
it('ASTSCP-052: the trip card reads the summary, places and categories in its session', async () => {
session.read.mockClear();
const fromSession = await tripCardFrom(session, 5, 7, { dayId: 2 });
expect(fromSession).toMatchObject({ tripId: 5, viewerId: 7, focus: { dayId: 2 } });
@@ -589,7 +589,7 @@ describe('a scope opens its session and writes its turn', () => {
const tools = { open: vi.fn(async () => session) };
session.close.mockClear();
await readTripCard(tools as unknown as AssistantToolsService, 7, 5);
expect(tools.open).toHaveBeenCalledWith(7, 5, new Set(['get_trip_summary', 'list_places']));
expect(tools.open).toHaveBeenCalledWith(7, 5, new Set(['get_trip_summary', 'list_places', 'list_categories']));
expect(session.close).toHaveBeenCalledTimes(1);
});
});
@@ -146,6 +146,7 @@ describe('describeToolCall', () => {
});
expect(describe_('create_day_note', { dayId: 33, text: 'Laundry', icon: '🧺' }).rows).toEqual([
{ op: 'add', labelKey: 'day', before: null, after: 'Spare day' },
{ op: 'add', labelKey: 'title', before: null, after: 'Laundry' },
{ op: 'add', labelKey: 'icon', before: null, after: '🧺' },
]);
});
@@ -345,7 +346,7 @@ describe('describeToolCall', () => {
endpoints: [{ role: 'from', sequence: 0, name: 'Gion' }],
source: { fileName: 'stay.eml', index: 0 },
});
expect(stay.dayId).toBe(32);
expect(stay.dayId).toBeNull();
const after = Object.fromEntries(stay.rows.map((row) => [row.labelKey, row.after]));
expect(after).toMatchObject({ checkIn: 'Fri 12 Jun', checkOut: 'Sun 14 Jun', confirmation: 'H-9' });
expect(after).toMatchObject({ location: 'Hotel Gion', address: 'Gion 1' });