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:
@@ -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' });
|
||||
|
||||
Reference in New Issue
Block a user