mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-03 01:28:55 +00:00
fix(assistant): improve trip proposals and approvals
This commit is contained in:
@@ -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();
|
||||
|
||||
Reference in New Issue
Block a user