mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-30 00:20:07 +00:00
feat(assistant): a card framework every addon package plugs into
This commit is contained in:
@@ -17,6 +17,7 @@
|
||||
* shared in the trip chat.
|
||||
*/
|
||||
import { buildApp } from '../../src/bootstrap';
|
||||
import { AssistantMessages } from '../../src/db/entities/AssistantMessages.entity';
|
||||
import { AssistantThreads } from '../../src/db/entities/AssistantThreads.entity';
|
||||
import { AssistantToolCalls } from '../../src/db/entities/AssistantToolCalls.entity';
|
||||
import { CollabMessages } from '../../src/db/entities/CollabMessages.entity';
|
||||
@@ -26,6 +27,7 @@ import { Reservations } from '../../src/db/entities/Reservations.entity';
|
||||
import { Trips } from '../../src/db/entities/Trips.entity';
|
||||
import { TURNS_PER_MINUTE } from '../../src/nest/assistant/assistant-tools.constants';
|
||||
import { AssistantToolsService } from '../../src/nest/assistant/assistant-tools.service';
|
||||
import { AssistantCardContext } from '../../src/nest/assistant/cards/card-context';
|
||||
import { BookingImportService } from '../../src/nest/booking-import/booking-import.service';
|
||||
import { MapsService } from '../../src/nest/maps/maps.service';
|
||||
import { PermissionsService } from '../../src/nest/permissions/permissions.service';
|
||||
@@ -40,7 +42,7 @@ import { resetRateLimits } from '../helpers/test-db';
|
||||
import { sessionCookie } from './harness';
|
||||
import { MikroORM } from '@mikro-orm/core';
|
||||
import type { INestApplication } from '@nestjs/common';
|
||||
import type { AssistantMessagePart, UiStreamChunk } from '@trek/shared';
|
||||
import { storedTrekCardSchema, type AssistantMessagePart, type TrekCard, type UiStreamChunk } from '@trek/shared';
|
||||
|
||||
import { createServer, type IncomingMessage, type Server as HttpServer, type ServerResponse } from 'node:http';
|
||||
import type { AddressInfo } from 'node:net';
|
||||
@@ -949,11 +951,12 @@ describe('Trip assistant e2e', () => {
|
||||
origin: 'assistant',
|
||||
user_id: t.userId,
|
||||
});
|
||||
// The asking tab is not left out: it never put the message into its own chat.
|
||||
expect(broadcasts.broadcast).toHaveBeenCalledWith(
|
||||
String(t.tripId),
|
||||
'collab:message:created',
|
||||
{ message: expect.objectContaining({ origin: 'assistant' }) },
|
||||
'sock-1',
|
||||
undefined,
|
||||
);
|
||||
const listed = await get(`/api/trips/${t.tripId}/collab/messages`, t.userId);
|
||||
expect(listed.body.messages).toEqual([
|
||||
@@ -977,4 +980,61 @@ describe('Trip assistant e2e', () => {
|
||||
}
|
||||
expect(await countRows(orm, CollabMessages, { trip: t.tripId })).toBe(1);
|
||||
});
|
||||
|
||||
it('ASTE2E-022: an applied change keeps its card on the proposing message; a card or part this build does not know reads as nothing', async () => {
|
||||
const t = await travelerWithTrip();
|
||||
const { turn, toolCallId, threadId } = await proposePlace(t, 'Sanjusangen-do');
|
||||
const proposing = Number(ofType(turn.chunks, 'start')[0].messageId.slice('msg-'.length));
|
||||
const built = { kind: 'tourRoute' } as TrekCard;
|
||||
const applied = vi.spyOn(nestApp.get(AssistantCardContext), 'appliedCard').mockReturnValue(built);
|
||||
provider.script = [say('Added it.')];
|
||||
try {
|
||||
const decided = await post(`${t.base}/threads/${threadId}/decisions`, t.userId, {
|
||||
...CTX,
|
||||
decisions: [{ toolCallId, approved: true }],
|
||||
});
|
||||
expect(applied).toHaveBeenCalledWith(
|
||||
'create_place',
|
||||
expect.objectContaining({ args: { name: 'Sanjusangen-do' } }),
|
||||
);
|
||||
const types = decided.chunks.map((chunk) => chunk.type);
|
||||
expect(types.indexOf('data-trek-card')).toBeGreaterThan(types.indexOf('data-trek-applied'));
|
||||
expect(ofType(decided.chunks, 'data-trek-card')[0].data.toolCallId).toBe(toolCallId);
|
||||
} finally {
|
||||
applied.mockRestore();
|
||||
}
|
||||
|
||||
const stored = await findRow(orm, AssistantMessages, { id: proposing });
|
||||
const parts = JSON.parse(stored?.parts ?? '[]') as Array<{ type: string; data?: { toolCallId?: string } }>;
|
||||
expect(parts.filter((part) => part.type === 'data-trek-card').map((part) => part.data?.toolCallId)).toEqual([
|
||||
toolCallId,
|
||||
]);
|
||||
const cardOf = (messages: Array<{ parts: AssistantMessagePart[] }>, id: string) =>
|
||||
messages
|
||||
.flatMap((message) => message.parts)
|
||||
.find((part) => part.type === 'data-trek-card' && part.data.toolCallId === id);
|
||||
const shown = await get(`${t.base}/threads/${threadId}`, t.userId);
|
||||
expect(shown.status).toBe(200);
|
||||
expect(cardOf(shown.body.messages, toolCallId)).toEqual({
|
||||
type: 'data-trek-card',
|
||||
data: { toolCallId, card: storedTrekCardSchema.parse(built) },
|
||||
});
|
||||
|
||||
// A later build's part and kind, as a rolled back server finds them in the row.
|
||||
const later = [
|
||||
...parts,
|
||||
{ type: 'data-trek-book-page', data: { page: 3 } },
|
||||
{ type: 'data-trek-card', data: { toolCallId: 'call_later', card: { kind: 'bookPage', page: 3 } } },
|
||||
];
|
||||
await updateRows(orm, AssistantMessages, { id: proposing }, { parts: JSON.stringify(later) });
|
||||
const tolerant = await get(`${t.base}/threads/${threadId}`, t.userId);
|
||||
expect(tolerant.status).toBe(200);
|
||||
const kept = (tolerant.body.messages as Array<{ parts: AssistantMessagePart[] }>).flatMap((m) => m.parts);
|
||||
expect(kept.map((part) => part.type)).not.toContain('data-trek-book-page');
|
||||
expect(kept.map((part) => part.type)).toContain('data-trek-change');
|
||||
expect(cardOf(tolerant.body.messages, 'call_later')).toEqual({
|
||||
type: 'data-trek-card',
|
||||
data: { toolCallId: 'call_later', card: null },
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -19,14 +19,16 @@ import {
|
||||
} from '../../../../src/nest/assistant/assistant-agent';
|
||||
import { buildTripCard } from '../../../../src/nest/assistant/assistant-context';
|
||||
import {
|
||||
MAX_CARDS_PER_STEP,
|
||||
MAX_READS_PER_STEP,
|
||||
MAX_STEPS,
|
||||
MAX_WRITES_PER_STEP,
|
||||
} from '../../../../src/nest/assistant/assistant-tools.constants';
|
||||
import type { AssistantToolKind } from '../../../../src/nest/assistant/assistant-tools.service';
|
||||
import type { AnswerInput } from '../../../../src/nest/assistant/cards/card-types';
|
||||
import { UiStreamWriter } from '../../../../src/nest/assistant/ui-stream.writer';
|
||||
import type { SseStream } from '../../../../src/nest/common/sse-stream';
|
||||
import type { AssistantChangePreview, UiStreamChunk } from '@trek/shared';
|
||||
import type { AssistantChangePreview, TrekCard, UiStreamChunk } from '@trek/shared';
|
||||
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
@@ -136,7 +138,7 @@ function setup(steps: Step[], overrides: Partial<AgentDeps> = {}) {
|
||||
describe: vi.fn(async (_name: string, id: string) => preview(id)),
|
||||
newId: () => `id-${++ids}`,
|
||||
quota: null,
|
||||
card: buildTripCard(1, { days: [{ id: 41, day_number: 1, date: '2026-06-11' }] }, null, null),
|
||||
card: buildTripCard(1, 7, { days: [{ id: 41, day_number: 1, date: '2026-06-11' }] }, null, null),
|
||||
today: '2026-01-05',
|
||||
...overrides,
|
||||
};
|
||||
@@ -487,7 +489,7 @@ describe('runAgentLoop', () => {
|
||||
|
||||
it('ASTAGT-015: a details lookup runs only for a google id from the card or a search of this turn', async () => {
|
||||
const places = { places: [{ id: 9, name: 'Nishiki', google_place_id: 'ChIJn' }] };
|
||||
const card = buildTripCard(1, { days: [] }, places, null);
|
||||
const card = buildTripCard(1, 7, { days: [] }, places, null);
|
||||
const details = (id: string, placeId: string) => ({
|
||||
type: 'tool-call' as const,
|
||||
call: { id, name: 'get_place_details', args: { placeId } },
|
||||
@@ -556,4 +558,69 @@ describe('runAgentLoop', () => {
|
||||
{ role: 'user', text: expect.stringContaining('cut off') },
|
||||
]);
|
||||
});
|
||||
|
||||
describe('answer cards', () => {
|
||||
/** A card as a package would build it; its fields do not matter to the loop. */
|
||||
const CARD = { kind: 'tourList' } as TrekCard;
|
||||
const read = (id: string) => ({ type: 'tool-call' as const, call: { id, name: 'list_places', args: {} } });
|
||||
|
||||
it('ASTAGT-019: a read card follows its answer in the stream and its call in the step, built from the raw value', async () => {
|
||||
const raw = { places: [{ id: 5, name: 'Kinkaku-ji', email: 'desk@kinkaku.test' }] };
|
||||
const answerCard = vi.fn((_tool: string, _input: AnswerInput) => CARD);
|
||||
const t = setup([[read('c1')], [{ type: 'text-delta', delta: 'Done.' }]], { answerCard });
|
||||
t.tools.call.mockImplementation(async () => ({ ok: true, value: raw }));
|
||||
await runAgentLoop(t.deps, t.input, t.writer, new AbortController().signal);
|
||||
expect(answerCard).toHaveBeenCalledWith('list_places', {
|
||||
toolCallId: 'c1',
|
||||
args: {},
|
||||
value: raw,
|
||||
card: t.deps.card,
|
||||
today: '2026-01-05',
|
||||
});
|
||||
expect(types(t.chunks).slice(0, 6)).toEqual([
|
||||
'start-step',
|
||||
'tool-input-start',
|
||||
'tool-input-available',
|
||||
'tool-output-available',
|
||||
'data-trek-card',
|
||||
'finish-step',
|
||||
]);
|
||||
expect(t.chunks[4]).toEqual({ type: 'data-trek-card', data: { toolCallId: 'c1', card: CARD } });
|
||||
const [call, card] = t.memory.saved[0].step.parts;
|
||||
expect(card).toEqual({ type: 'data-trek-card', data: { toolCallId: 'c1', card: CARD } });
|
||||
expect(JSON.stringify(call)).not.toContain('desk@kinkaku.test');
|
||||
expect(JSON.stringify(t.requests[1].messages)).not.toContain('desk@kinkaku.test');
|
||||
});
|
||||
|
||||
it('ASTAGT-020: a failed read makes no card, and a step shows at most twelve', async () => {
|
||||
const answerCard = vi.fn(() => CARD);
|
||||
const calls = Array.from({ length: MAX_CARDS_PER_STEP + 2 }, (_, i) => read(`c${i}`));
|
||||
const failing = { type: 'tool-call' as const, call: { id: 'bad', name: 'search_place', args: { query: 'x' } } };
|
||||
const t = setup([[...calls, failing]], { answerCard });
|
||||
t.tools.call.mockImplementation(async (name: string) =>
|
||||
name === 'search_place' ? { ok: false, value: 'Place search failed.' } : { ok: true, value: ANSWERS[name] },
|
||||
);
|
||||
await runAgentLoop(t.deps, t.input, t.writer, new AbortController().signal);
|
||||
expect(answerCard).toHaveBeenCalledTimes(MAX_CARDS_PER_STEP + 2);
|
||||
expect(types(t.chunks).filter((type) => type === 'data-trek-card')).toHaveLength(MAX_CARDS_PER_STEP);
|
||||
const parts = t.memory.saved[0].step.parts;
|
||||
expect(parts.filter((part) => part.type === 'data-trek-card')).toHaveLength(MAX_CARDS_PER_STEP);
|
||||
expect(parts.filter((part) => part.type === 'tool-call')).toHaveLength(MAX_CARDS_PER_STEP + 3);
|
||||
});
|
||||
|
||||
it('ASTAGT-021: no card for a builder that gives none or a call id past 64 characters', async () => {
|
||||
const long = `toolu_${'x'.repeat(64)}`;
|
||||
const answerCard = vi.fn((_tool: string, input: AnswerInput) => (input.toolCallId === 'none' ? null : CARD));
|
||||
const t = setup([[read(long), read('none')]], { answerCard });
|
||||
await runAgentLoop(t.deps, t.input, t.writer, new AbortController().signal);
|
||||
expect(answerCard).toHaveBeenCalledTimes(1);
|
||||
expect(types(t.chunks)).not.toContain('data-trek-card');
|
||||
});
|
||||
|
||||
it('ASTAGT-022: without a builder of its own the loop asks the registry, where no core tool has an answer card', async () => {
|
||||
const t = setup([[read('c1')], [{ type: 'text-delta', delta: 'Done.' }]]);
|
||||
await runAgentLoop(t.deps, t.input, t.writer, new AbortController().signal);
|
||||
expect(t.memory.saved[0].step.parts.map((part) => part.type)).toEqual(['tool-call']);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -19,6 +19,7 @@ import { describe, expect, it } from 'vitest';
|
||||
|
||||
const card = buildTripCard(
|
||||
1,
|
||||
7,
|
||||
{
|
||||
trip: { title: 'Kyoto', start_date: '2026-06-11', end_date: '2026-06-13' },
|
||||
days: [
|
||||
@@ -86,7 +87,7 @@ describe('foundPlacesOf', () => {
|
||||
const value = { places: [{ name: 'Cafe', lat: 35, lng: 135, open_now: false, types: ['cafe'] }] };
|
||||
expect(foundPlacesOf('search_place', 'c', value, card, '2026-06-11')?.places[0].openNow).toBe(false);
|
||||
expect(foundPlacesOf('search_place', 'c', value, card, '2026-10-21')?.places[0].openNow).toBeNull();
|
||||
const undated = buildTripCard(1, { trip: { title: 'T' } }, null, null);
|
||||
const undated = buildTripCard(1, 7, { trip: { title: 'T' } }, null, null);
|
||||
expect(foundPlacesOf('search_place', 'c', value, undated, '2026-06-11')?.places[0].openNow).toBeNull();
|
||||
});
|
||||
|
||||
|
||||
@@ -45,6 +45,7 @@ describe('buildTripCard', () => {
|
||||
it('ASTCTX-030: knows the source ids of places and the bookings with their day', () => {
|
||||
const card = buildTripCard(
|
||||
1,
|
||||
7,
|
||||
{
|
||||
...SUMMARY,
|
||||
reservations: [{ id: 71, title: 'Gion Corner', day_id: 31 }, { id: 72, day_id: null }, { title: 'no id' }],
|
||||
@@ -69,7 +70,7 @@ describe('buildTripCard', () => {
|
||||
{ id: 73, title: 'Bus' },
|
||||
],
|
||||
};
|
||||
const card = buildTripCard(1, summary, PLACES, { dayId: 32, placeIds: [12] }, [
|
||||
const card = buildTripCard(1, 7, summary, PLACES, { dayId: 32, placeIds: [12] }, [
|
||||
{ kind: 'place', id: 14 },
|
||||
{ kind: 'place', id: 12 },
|
||||
{ kind: 'place', id: 999 },
|
||||
@@ -93,7 +94,7 @@ describe('buildTripCard', () => {
|
||||
].join('\n'),
|
||||
);
|
||||
expect(text).not.toMatch(/place 999|day 99\b|booking 98/);
|
||||
const unknownOnly = buildTripCard(1, SUMMARY, PLACES, null, [{ kind: 'place', id: 999 }]);
|
||||
const unknownOnly = buildTripCard(1, 7, SUMMARY, PLACES, null, [{ kind: 'place', id: 999 }]);
|
||||
expect(renderTripCard(unknownOnly)).not.toContain('The user names');
|
||||
});
|
||||
|
||||
@@ -115,7 +116,7 @@ describe('buildTripCard', () => {
|
||||
});
|
||||
|
||||
it('ASTCTX-001: reads days, places, assignments, notes, packing and members', () => {
|
||||
const card = buildTripCard(1, SUMMARY, PLACES, null);
|
||||
const card = buildTripCard(1, 7, SUMMARY, PLACES, null);
|
||||
expect(card).toMatchObject({ tripId: 1, title: 'Kyoto in June', currency: 'JPY', startDate: '2026-06-11' });
|
||||
expect(card.days).toEqual([
|
||||
{ id: 31, number: 1, date: '2026-06-11', title: 'Arrival', placeIds: [12] },
|
||||
@@ -133,24 +134,44 @@ describe('buildTripCard', () => {
|
||||
});
|
||||
expect(card.packing.get(51)).toMatchObject({ name: 'Umbrella', weight: 300 });
|
||||
expect([...card.members.entries()]).toEqual([
|
||||
[7, 'mia'],
|
||||
[8, 'jon'],
|
||||
[7, { name: 'mia', avatarKey: null }],
|
||||
[8, { name: 'jon', avatarKey: null }],
|
||||
]);
|
||||
});
|
||||
|
||||
it('ASTCTX-003: knows who asks, the members by their stored pictures, and the answers it was built from', () => {
|
||||
const summary = {
|
||||
...SUMMARY,
|
||||
members: {
|
||||
owner: { id: 7, username: 'mia', avatar_url: '/uploads/avatars/mia-1.png' },
|
||||
collaborators: [
|
||||
{ id: 8, username: 'jon', avatar_url: 'https://lh3.example.test/jon.png' },
|
||||
{ id: 9, username: 'ana', avatar_url: '/uploads/avatars/../../secret' },
|
||||
],
|
||||
},
|
||||
};
|
||||
const card = buildTripCard(1, 8, summary, PLACES, null);
|
||||
expect(card.viewerId).toBe(8);
|
||||
expect(card.members.get(7)).toEqual({ name: 'mia', avatarKey: 'mia-1.png' });
|
||||
expect(card.members.get(8)).toEqual({ name: 'jon', avatarKey: null });
|
||||
expect(card.members.get(9)).toEqual({ name: 'ana', avatarKey: null });
|
||||
expect(card.sources).toEqual({ summary, places: PLACES });
|
||||
});
|
||||
|
||||
it('ASTCTX-002: a tool that answered with an error leaves an emptier card, not a broken one', () => {
|
||||
const card = buildTripCard(5, 'Trip not found or access denied.', null, null);
|
||||
const card = buildTripCard(5, 7, 'Trip not found or access denied.', null, null);
|
||||
expect(card).toMatchObject({ tripId: 5, title: '', days: [] });
|
||||
expect(card.places.size).toBe(0);
|
||||
expect(
|
||||
buildTripCard(5, { days: [{ id: 'x' }, null, { id: 3, assignments: [{ id: 1 }] }] }, { places: 'no' }, null).days,
|
||||
buildTripCard(5, 7, { days: [{ id: 'x' }, null, { id: 3, assignments: [{ id: 1 }] }] }, { places: 'no' }, null)
|
||||
.days,
|
||||
).toEqual([{ id: 3, number: 1, date: null, title: null, placeIds: [] }]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('renderTripCard', () => {
|
||||
it('ASTCTX-010: lists the days with their places and ids, the unscheduled places and the focus', () => {
|
||||
const text = renderTripCard(buildTripCard(1, SUMMARY, PLACES, { dayId: 32, placeIds: [14, 999] }));
|
||||
const text = renderTripCard(buildTripCard(1, 7, SUMMARY, PLACES, { dayId: 32, placeIds: [14, 999] }));
|
||||
expect(text).toContain('Trip: Kyoto in June');
|
||||
expect(text).toContain('Dates: 2026-06-11 to 2026-06-12');
|
||||
expect(text).toContain('31 | 2026-06-11 | Arrival | Nishiki Market (12)');
|
||||
@@ -164,7 +185,7 @@ describe('renderTripCard', () => {
|
||||
|
||||
it('ASTCTX-011: a trip without days says so, and long lists are counted, not listed', () => {
|
||||
const many = { places: Array.from({ length: 205 }, (_, i) => ({ id: i + 1, name: `P${i + 1}` })) };
|
||||
const text = renderTripCard(buildTripCard(1, { trip: { title: 'T' } }, many, null));
|
||||
const text = renderTripCard(buildTripCard(1, 7, { trip: { title: 'T' } }, many, null));
|
||||
expect(text).toContain('(no days yet)');
|
||||
expect(text).toContain('and 5 more');
|
||||
});
|
||||
@@ -177,22 +198,22 @@ describe('renderTripCard', () => {
|
||||
{ id: 15, name: 'Kansai Airport', lat: 34.434, lng: 135.244 },
|
||||
],
|
||||
};
|
||||
const text = renderTripCard(buildTripCard(1, SUMMARY, places, { placeIds: [12] }));
|
||||
const text = renderTripCard(buildTripCard(1, 7, SUMMARY, places, { placeIds: [12] }));
|
||||
expect(text).toContain('Around: 34.9670, 135.7640');
|
||||
expect(text).toContain('Nishiki Market (12, google ChIJn)');
|
||||
expect(text).toContain('- place 12: Nishiki Market (at 35.0050, 135.7640; google place id ChIJn)');
|
||||
expect(renderTripCard(buildTripCard(1, SUMMARY, PLACES, null))).not.toContain('Around:');
|
||||
expect(renderTripCard(buildTripCard(1, 7, SUMMARY, PLACES, null))).not.toContain('Around:');
|
||||
});
|
||||
|
||||
it('ASTCTX-013: the part of the map on screen tells "here", a view of a whole country does not', () => {
|
||||
const view = { south: 35.6, west: 139.7, north: 35.72, east: 139.82 };
|
||||
const text = renderTripCard(buildTripCard(1, SUMMARY, PLACES, { view }));
|
||||
const text = renderTripCard(buildTripCard(1, 7, SUMMARY, PLACES, { view }));
|
||||
expect(text).toContain(
|
||||
"The map on the user's screen shows south 35.6000, west 139.7000, north 35.7200, east 139.8200.",
|
||||
);
|
||||
expect(text).toContain('"here", "nearby" or "around" means this area');
|
||||
const country = { south: 30, west: 129, north: 45, east: 146 };
|
||||
expect(renderTripCard(buildTripCard(1, SUMMARY, PLACES, { view: country }))).not.toContain('on the user');
|
||||
expect(renderTripCard(buildTripCard(1, 7, SUMMARY, PLACES, { view: country }))).not.toContain('on the user');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -211,7 +232,7 @@ describe('the turn context', () => {
|
||||
});
|
||||
|
||||
it('ASTCTX-022: carries the date, the units the user prefers and the card', () => {
|
||||
const card = buildTripCard(1, SUMMARY, PLACES, null);
|
||||
const card = buildTripCard(1, 7, SUMMARY, PLACES, null);
|
||||
const context = turnContext(card, 'Asia/Tokyo', new Date('2026-06-11T23:30:00Z'), {
|
||||
temperature_unit: 'fahrenheit',
|
||||
distance_unit: 'metric',
|
||||
@@ -224,7 +245,7 @@ describe('the turn context', () => {
|
||||
});
|
||||
|
||||
it("ASTCTX-023: the trip notes of this trip come along as preferences, never another trip's", () => {
|
||||
const card = buildTripCard(1, SUMMARY, PLACES, null);
|
||||
const card = buildTripCard(1, 7, SUMMARY, PLACES, null);
|
||||
const prefs = { assistant_memory: { '1': ' Vegetarian, no museums. ', '2': 'Other trip' } };
|
||||
const context = turnContext(card, 'UTC', new Date(), prefs);
|
||||
expect(context).toContain('<trip_notes>\nVegetarian, no museums.\n</trip_notes>');
|
||||
@@ -234,7 +255,7 @@ describe('the turn context', () => {
|
||||
});
|
||||
|
||||
it('ASTCTX-024: cost estimates are asked for unless the user turned them off', () => {
|
||||
const card = buildTripCard(1, SUMMARY, PLACES, null);
|
||||
const card = buildTripCard(1, 7, SUMMARY, PLACES, null);
|
||||
expect(turnContext(card, 'UTC', new Date(), {})).toContain('create_budget_item');
|
||||
expect(turnContext(card, 'UTC', new Date(), { assistant_cost_estimates: false })).not.toContain(
|
||||
'create_budget_item',
|
||||
|
||||
@@ -5,15 +5,17 @@
|
||||
* suggestion is held as a change card in one transaction, refused while a turn
|
||||
* runs, while another change waits, or past the per-minute limit.
|
||||
*
|
||||
* Replaced: the trip tools (what the trip reads as), the rate limit and the
|
||||
* stream registry.
|
||||
* Replaced: the trip tools (what the trip reads as), the rate limit, the
|
||||
* stream registry and the airports.
|
||||
*/
|
||||
import { AssistantMessages } from '../../../../src/db/entities/AssistantMessages.entity';
|
||||
import { AssistantThreads } from '../../../../src/db/entities/AssistantThreads.entity';
|
||||
import { AssistantToolCalls } from '../../../../src/db/entities/AssistantToolCalls.entity';
|
||||
import { AirportsService } from '../../../../src/nest/airports/airports.service';
|
||||
import { AssistantFoundPlacesService } from '../../../../src/nest/assistant/assistant-found-places.service';
|
||||
import { AssistantStreamRegistry } from '../../../../src/nest/assistant/assistant-stream.registry';
|
||||
import { AssistantToolsService } from '../../../../src/nest/assistant/assistant-tools.service';
|
||||
import { AssistantCardContext } from '../../../../src/nest/assistant/cards/card-context';
|
||||
import { RateLimitService } from '../../../../src/nest/common/rate-limit.service';
|
||||
import { UnitOfWork } from '../../../../src/nest/database/unit-of-work';
|
||||
import { createSnapshotTestDb } from '../../../helpers/db-mock';
|
||||
@@ -53,6 +55,8 @@ beforeAll(async () => {
|
||||
imports: [MikroOrmModule.forFeature([AssistantThreads, AssistantMessages, AssistantToolCalls])],
|
||||
providers: [
|
||||
AssistantFoundPlacesService,
|
||||
AssistantCardContext,
|
||||
{ provide: AirportsService, useValue: { findByIata: () => null } },
|
||||
{ provide: AssistantToolsService, useValue: tools },
|
||||
{ provide: RateLimitService, useValue: rateLimit },
|
||||
{ provide: AssistantStreamRegistry, useValue: streams },
|
||||
|
||||
@@ -4,7 +4,8 @@
|
||||
* plan, and anything too large cut down along its structure, never through
|
||||
* the middle of the JSON.
|
||||
*/
|
||||
import { fitToSize, redactForProvider, toolOutputForProvider } from '../../../../src/nest/assistant/assistant-redact';
|
||||
import { fitToSize, toolOutputForProvider } from '../../../../src/nest/assistant/assistant-output';
|
||||
import { redactForProvider } from '../../../../src/nest/assistant/assistant-redact';
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
@@ -27,6 +28,15 @@ describe('redactForProvider', () => {
|
||||
reservations: [{ confirmation_number: '[hidden]', title: 'Dinner' }, { confirmation_number: null }],
|
||||
});
|
||||
});
|
||||
|
||||
it("ASTRED-002: drops a booked place's picture and the trip's cover, wherever they sit", () => {
|
||||
expect(
|
||||
redactForProvider({
|
||||
reservations: [{ title: 'Ryokan', place_image: '/uploads/places/ryokan.jpg' }],
|
||||
trip: { title: 'Kyoto', trip_cover: '/uploads/covers/kyoto.jpg' },
|
||||
}),
|
||||
).toEqual({ reservations: [{ title: 'Ryokan' }], trip: { title: 'Kyoto' } });
|
||||
});
|
||||
});
|
||||
|
||||
describe('fitToSize', () => {
|
||||
|
||||
@@ -16,13 +16,9 @@ import {
|
||||
groupOf,
|
||||
isOfferedTool,
|
||||
} from '../../../../src/nest/assistant/assistant-tool-offer';
|
||||
import {
|
||||
ASSISTANT_ARG_POLICY,
|
||||
ASSISTANT_SCOPES,
|
||||
ASSISTANT_SERVER_TOOLS,
|
||||
ASSISTANT_WRITE_TOOLS,
|
||||
} from '../../../../src/nest/assistant/assistant-tools.constants';
|
||||
import { ASSISTANT_SCOPES, ASSISTANT_SERVER_TOOLS } from '../../../../src/nest/assistant/assistant-tools.constants';
|
||||
import { AssistantToolsService, checkToolCatalog } from '../../../../src/nest/assistant/assistant-tools.service';
|
||||
import { ASSISTANT_ARG_POLICY, ASSISTANT_WRITE_TOOLS } from '../../../../src/nest/assistant/cards/registry';
|
||||
import { withRequestContext } from '../../../../src/nest/database/request-context';
|
||||
import { makePlace } from '../../../helpers/factories/places';
|
||||
import { findRows } from '../../../helpers/factories/rows';
|
||||
@@ -98,6 +94,37 @@ describe('the assistant tool catalog', () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it('ASTTOOL-018: names a package entry for a tool that does not exist, and an undo read that is not registered', () => {
|
||||
const entry = (name: string) => ({ kind: 'tool' as const, name, className: 'X', methodName: 'y' });
|
||||
expect(checkToolCatalog([])).toContain(
|
||||
'tool "create_hike" with cards of a package is neither registered nor the server\'s own',
|
||||
);
|
||||
const cards = {
|
||||
list_vacay: { answer: () => null },
|
||||
take_vacay: {
|
||||
undo: {
|
||||
tool: 'delete_place',
|
||||
args: () => null,
|
||||
reads: () => [{ tool: 'get_vacay_plan', args: {} }],
|
||||
unchanged: () => true,
|
||||
},
|
||||
},
|
||||
add_found_place: { appliedIds: () => [] },
|
||||
};
|
||||
const problems = checkToolCatalog([entry('take_vacay')], cards);
|
||||
expect(problems).toContain('tool "list_vacay" with cards of a package is neither registered nor the server\'s own');
|
||||
expect(problems).toContain('undo read "get_vacay_plan" is not registered');
|
||||
expect(problems.join()).not.toContain('"add_found_place" with cards');
|
||||
expect(problems.join()).not.toContain('"take_vacay" with cards');
|
||||
});
|
||||
|
||||
it('ASTTOOL-019: names a held read of a package that is not registered', () => {
|
||||
const entry = (name: string) => ({ kind: 'tool' as const, name, className: 'X', methodName: 'y' });
|
||||
const problems = checkToolCatalog([entry('fetch_corridor')], {}, ['fetch_corridor', 'fetch_tolls']);
|
||||
expect(problems).toContain('held read "fetch_tolls" of a package is not registered');
|
||||
expect(problems.join()).not.toContain('"fetch_corridor"');
|
||||
});
|
||||
|
||||
it("ASTTOOL-006: the server's own steps are no MCP tools", () => {
|
||||
for (const name of ASSISTANT_SERVER_TOOLS) expect(listed.has(name), name).toBe(false);
|
||||
});
|
||||
|
||||
@@ -2,10 +2,16 @@
|
||||
* The undo guard: an applied change is taken back only while what it created
|
||||
* is as it left it, and, for a place, still only where the change put it.
|
||||
*/
|
||||
import { ASSISTANT_UNDO_MAP } from '../../../../src/nest/assistant/assistant-tools.constants';
|
||||
import { unchangedSinceApplied, type TripSnapshot } from '../../../../src/nest/assistant/assistant-undo.helpers';
|
||||
import {
|
||||
unchangedSinceApplied,
|
||||
undoSnapshotOf,
|
||||
undoTargetsOf,
|
||||
type TripSnapshot,
|
||||
} from '../../../../src/nest/assistant/assistant-undo.helpers';
|
||||
import { readKey } from '../../../../src/nest/assistant/cards/card-values';
|
||||
import { ASSISTANT_UNDO_MAP } from '../../../../src/nest/assistant/cards/registry';
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const PLACE = { id: 9, name: 'Kinkaku-ji', updated_at: '2026-10-21 10:00:00', lat: 35, lng: 135 };
|
||||
|
||||
@@ -103,22 +109,22 @@ describe('unchangedSinceApplied', () => {
|
||||
|
||||
describe('ASSISTANT_UNDO_MAP', () => {
|
||||
it('ASTUND-010: builds the counter-call from the change and its answer, or none', () => {
|
||||
expect(ASSISTANT_UNDO_MAP.create_place.args({}, { place: { id: 9 } })).toEqual({ placeId: 9 });
|
||||
expect(ASSISTANT_UNDO_MAP.create_and_assign_place.args({}, { place: { id: 9 } })).toEqual({ placeId: 9 });
|
||||
expect(ASSISTANT_UNDO_MAP.assign_place_to_day.args({ dayId: 31 }, { assignment: { id: 301 } })).toEqual({
|
||||
expect(ASSISTANT_UNDO_MAP.create_place.args({}, { place: { id: 9 } }, null)).toEqual({ placeId: 9 });
|
||||
expect(ASSISTANT_UNDO_MAP.create_and_assign_place.args({}, { place: { id: 9 } }, null)).toEqual({ placeId: 9 });
|
||||
expect(ASSISTANT_UNDO_MAP.assign_place_to_day.args({ dayId: 31 }, { assignment: { id: 301 } }, null)).toEqual({
|
||||
dayId: 31,
|
||||
assignmentId: 301,
|
||||
});
|
||||
expect(ASSISTANT_UNDO_MAP.create_day_note.args({ dayId: 31 }, { note: { id: 41 } })).toEqual({
|
||||
expect(ASSISTANT_UNDO_MAP.create_day_note.args({ dayId: 31 }, { note: { id: 41 } }, null)).toEqual({
|
||||
dayId: 31,
|
||||
noteId: 41,
|
||||
});
|
||||
expect(ASSISTANT_UNDO_MAP.create_packing_item.args({}, { item: { id: 51 } })).toEqual({ itemId: 51 });
|
||||
expect(ASSISTANT_UNDO_MAP.create_todo.args({}, { item: { id: 61 } })).toEqual({ itemId: 61 });
|
||||
expect(ASSISTANT_UNDO_MAP.create_budget_item.args({}, { item: { id: 71 } })).toEqual({ itemId: 71 });
|
||||
expect(ASSISTANT_UNDO_MAP.create_place.args({}, 'Place not found.')).toBeNull();
|
||||
expect(ASSISTANT_UNDO_MAP.assign_place_to_day.args({}, { assignment: { id: 301 } })).toBeNull();
|
||||
expect(ASSISTANT_UNDO_MAP.create_day_note.args({ dayId: 31 }, { note: { id: 0 } })).toBeNull();
|
||||
expect(ASSISTANT_UNDO_MAP.create_packing_item.args({}, { item: { id: 51 } }, null)).toEqual({ itemId: 51 });
|
||||
expect(ASSISTANT_UNDO_MAP.create_todo.args({}, { item: { id: 61 } }, null)).toEqual({ itemId: 61 });
|
||||
expect(ASSISTANT_UNDO_MAP.create_budget_item.args({}, { item: { id: 71 } }, null)).toEqual({ itemId: 71 });
|
||||
expect(ASSISTANT_UNDO_MAP.create_place.args({}, 'Place not found.', null)).toBeNull();
|
||||
expect(ASSISTANT_UNDO_MAP.assign_place_to_day.args({}, { assignment: { id: 301 } }, null)).toBeNull();
|
||||
expect(ASSISTANT_UNDO_MAP.create_day_note.args({ dayId: 31 }, { note: { id: 0 } }, null)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -177,10 +183,47 @@ describe('a created tour', () => {
|
||||
it('ASTUND-011: is taken back by deleting its place, named in the answer', () => {
|
||||
for (const tool of ['create_hike', 'create_city_walk']) {
|
||||
expect(ASSISTANT_UNDO_MAP[tool].tool).toBe('delete_place');
|
||||
expect(ASSISTANT_UNDO_MAP[tool].args({}, created)).toEqual({ placeId: 64 });
|
||||
expect(ASSISTANT_UNDO_MAP[tool].args({}, { tour: { place_id: 0 } })).toBeNull();
|
||||
expect(ASSISTANT_UNDO_MAP[tool].args({}, { tour: 'odd' })).toBeNull();
|
||||
expect(ASSISTANT_UNDO_MAP[tool].args({}, 'Tour not found.')).toBeNull();
|
||||
expect(ASSISTANT_UNDO_MAP[tool].args({}, created, null)).toEqual({ placeId: 64 });
|
||||
expect(ASSISTANT_UNDO_MAP[tool].args({}, { tour: { place_id: 0 } }, null)).toBeNull();
|
||||
expect(ASSISTANT_UNDO_MAP[tool].args({}, { tour: 'odd' }, null)).toBeNull();
|
||||
expect(ASSISTANT_UNDO_MAP[tool].args({}, 'Tour not found.', null)).toBeNull();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('the undo session', () => {
|
||||
const session = (failing: string[] = []) => ({
|
||||
read: vi.fn(async (name: string, args: Record<string, unknown> = {}) =>
|
||||
failing.includes(name) ? { ok: false, value: 'Not allowed.' } : { ok: true, value: { name, args } },
|
||||
),
|
||||
});
|
||||
|
||||
it('ASTUND-020: holds the removing tool and the trip reads, and reads the trip before the check', async () => {
|
||||
expect([...undoTargetsOf('delete_place', 'create_hike', {}, {})]).toEqual([
|
||||
'delete_place',
|
||||
'get_trip_summary',
|
||||
'list_places',
|
||||
]);
|
||||
const snap = await undoSnapshotOf(session(), 'create_place', {}, {});
|
||||
expect(snap).toEqual({
|
||||
summary: { name: 'get_trip_summary', args: {} },
|
||||
places: { name: 'list_places', args: {} },
|
||||
reads: new Map(),
|
||||
});
|
||||
expect(await undoSnapshotOf(session(['list_places']), 'create_place', {}, {})).toBeNull();
|
||||
});
|
||||
|
||||
it('ASTUND-021: keeps what a package reads by tool and arguments, a failed read as null', async () => {
|
||||
const reads = [
|
||||
{ tool: 'get_vacay_plan', args: { year: 2026 } },
|
||||
{ tool: 'list_vacay_entries', args: {} },
|
||||
];
|
||||
const snap = await undoSnapshotOf(session(['list_vacay_entries']), 'toggle_vacay', {}, {}, reads);
|
||||
expect(snap?.reads.get(readKey('get_vacay_plan', { year: 2026 }))).toEqual({
|
||||
name: 'get_vacay_plan',
|
||||
args: { year: 2026 },
|
||||
});
|
||||
expect(snap?.reads.get(readKey('list_vacay_entries'))).toBeNull();
|
||||
expect(snap?.reads.size).toBe(2);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,189 @@
|
||||
/**
|
||||
* What the change cards are made with beyond the tool's own answer: the
|
||||
* turn's reads, each made once and cut off after four per change, the
|
||||
* categories read once a turn, the airports by their codes, the lookups of
|
||||
* a change the server proposes itself, and the card of an applied change
|
||||
* through the guarded registry.
|
||||
*/
|
||||
import { AirportsService } from '../../../../../src/nest/airports/airports.service';
|
||||
import { buildTripCard } from '../../../../../src/nest/assistant/assistant-context';
|
||||
import type { AssistantToolsService, ToolRun } from '../../../../../src/nest/assistant/assistant-tools.service';
|
||||
import {
|
||||
AssistantCardContext,
|
||||
loadFor,
|
||||
MAX_CARD_READS,
|
||||
memoisedReader,
|
||||
} from '../../../../../src/nest/assistant/cards/card-context';
|
||||
import type { ToolCards } from '../../../../../src/nest/assistant/cards/card-types';
|
||||
import type { AssistantMessagePart, TrekCard } from '@trek/shared';
|
||||
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const logMock = vi.hoisted(() => ({ logInfo: vi.fn(), logError: vi.fn(), logWarn: vi.fn(), logDebug: vi.fn() }));
|
||||
vi.mock('../../../../../src/nest/audit/audit-log.logger', () => logMock);
|
||||
|
||||
beforeEach(() => vi.clearAllMocks());
|
||||
|
||||
/** A session that answers every read with its tool and arguments, or fails the ones named. */
|
||||
function session(failing: readonly string[] = []) {
|
||||
return {
|
||||
read: vi.fn(async (name: string, args: Record<string, unknown> = {}): Promise<ToolRun> =>
|
||||
failing.includes(name) ? { ok: false, value: 'Not allowed.' } : { ok: true, value: { name, args } },
|
||||
),
|
||||
hintOf: vi.fn(() => ({ destructive: false, creates: true, group: 'vacay' })),
|
||||
};
|
||||
}
|
||||
|
||||
const airports = {
|
||||
findByIata: vi.fn((code: string) =>
|
||||
code === 'MUC'
|
||||
? { iata: 'MUC', name: 'Munich', city: 'München', lat: 48.35, lng: 11.79, tz: 'Europe/Berlin' }
|
||||
: null,
|
||||
),
|
||||
};
|
||||
const opened = { ...session(), close: vi.fn(async () => undefined) };
|
||||
const tools = { open: vi.fn(async () => opened) };
|
||||
const context = new AssistantCardContext(
|
||||
airports as unknown as AirportsService,
|
||||
tools as unknown as AssistantToolsService,
|
||||
);
|
||||
const card = buildTripCard(1, 7, { trip: { title: 'Bavaria' }, days: [{ id: 31, day_number: 1 }] }, null, null);
|
||||
|
||||
describe('memoisedReader', () => {
|
||||
it('ASTCCX-001: reads a tool and its arguments once, whatever their key order', async () => {
|
||||
const s = session();
|
||||
const read = memoisedReader(s);
|
||||
const first = await read('get_vacay_plan', { year: 2026, userId: 7 });
|
||||
const again = await read('get_vacay_plan', { userId: 7, year: 2026 });
|
||||
await read('get_vacay_plan', { year: 2027, userId: 7 });
|
||||
expect(again).toBe(first);
|
||||
expect(first).toEqual({ name: 'get_vacay_plan', args: { year: 2026, userId: 7 } });
|
||||
expect(s.read).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('ASTCCX-002: a read that failed or threw reads as null', async () => {
|
||||
const s = session(['list_budget_items']);
|
||||
const read = memoisedReader(s);
|
||||
expect(await read('list_budget_items')).toBeNull();
|
||||
s.read.mockRejectedValueOnce(new Error('closed'));
|
||||
expect(await read('get_trip_summary')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('loadFor', () => {
|
||||
it('ASTCCX-010: a lookup gets at most four reads; the ones past it read as null and are logged', async () => {
|
||||
const seen: unknown[] = [];
|
||||
const cards: Record<string, ToolCards> = {
|
||||
plan_days: {
|
||||
load: async (_args, read) => {
|
||||
for (const year of [2021, 2022, 2023, 2024, 2025]) seen.push(await read('get_vacay_plan', { year }));
|
||||
return seen.length;
|
||||
},
|
||||
},
|
||||
};
|
||||
const s = session();
|
||||
expect(await loadFor('plan_days', {}, memoisedReader(s), cards)).toBe(5);
|
||||
expect(s.read).toHaveBeenCalledTimes(MAX_CARD_READS);
|
||||
expect(seen.at(-1)).toBeNull();
|
||||
expect(String(logMock.logWarn.mock.calls[0]?.[0])).toContain('more than 4 reads');
|
||||
});
|
||||
|
||||
it('ASTCCX-011: a lookup that throws gives null; a tool without one reads nothing', async () => {
|
||||
const cards: Record<string, ToolCards> = {
|
||||
broken: {
|
||||
load: () => {
|
||||
throw new Error('bad shape');
|
||||
},
|
||||
},
|
||||
};
|
||||
const s = session();
|
||||
expect(await loadFor('broken', {}, memoisedReader(s), cards)).toBeNull();
|
||||
expect(String(logMock.logWarn.mock.calls[0]?.[0])).toContain('the lookup of broken failed: bad shape');
|
||||
expect(await loadFor('create_place', {}, memoisedReader(s))).toBeNull();
|
||||
expect(s.read).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('AssistantCardContext', () => {
|
||||
it('ASTCCX-020: a turn reads the categories once, when the first change needs them', async () => {
|
||||
const s = session();
|
||||
s.read.mockImplementation(async (name: string) =>
|
||||
name === 'list_categories'
|
||||
? { ok: true, value: { categories: [{ id: 2, name: 'Food', icon: null }] } }
|
||||
: { ok: false, value: 'no' },
|
||||
);
|
||||
const turn = context.forTurn(s, card, 'en', '2026-06-01');
|
||||
expect(s.read).not.toHaveBeenCalled();
|
||||
const first = await turn.describe('create_place', 'w1', { name: 'Hofbräuhaus', category_id: 2 });
|
||||
const second = await turn.describe('create_place', 'w2', { name: 'Viktualienmarkt', category_id: 2 });
|
||||
expect(first.rows).toContainEqual({ op: 'add', labelKey: 'category', before: null, after: 'Food' });
|
||||
expect(second.toolCallId).toBe('w2');
|
||||
expect(s.read).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('ASTCCX-021: a tool without a card of its own is described from its arguments and its hint', async () => {
|
||||
const s = session();
|
||||
const preview = await context.forTurn(s, card, 'en', '2026-06-01').describe('set_vacay_days', 'w1', { days: 3 });
|
||||
expect(preview).toMatchObject({ verbKey: 'genericCreate', tool: 'set_vacay_days', domain: 'vacay' });
|
||||
expect(s.hintOf).toHaveBeenCalledWith('set_vacay_days');
|
||||
});
|
||||
|
||||
it('ASTCCX-022: names an airport by its code, any case, and nothing for what is no code', () => {
|
||||
const ctx = context.contextOf(card, new Map(), 'en', '2026-06-01');
|
||||
expect(ctx.airport('muc')).toEqual({ city: 'München', lat: 48.35, lng: 11.79, tz: 'Europe/Berlin' });
|
||||
expect(ctx.airport('XXX')).toBeNull();
|
||||
expect(ctx.airport('Munich')).toBeNull();
|
||||
expect(airports.findByIata).toHaveBeenCalledTimes(2);
|
||||
expect(ctx).not.toHaveProperty('hintOf');
|
||||
});
|
||||
|
||||
it('ASTCCX-024: a proposed change without a lookup is described without opening a session', async () => {
|
||||
const ctx = context.contextOf(card, new Map(), 'en', '2026-06-01');
|
||||
const [change] = await context.describeProposed(7, 1, ctx, [{ id: 'p1', toolName: 'create_place', args: {} }]);
|
||||
expect(change).toMatchObject({ id: 'p1', toolName: 'create_place', preview: { toolCallId: 'p1' } });
|
||||
expect(tools.open).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('ASTCCX-025: proposed changes with a lookup share one session and its memo, closed after', async () => {
|
||||
const ctx = context.contextOf(card, new Map(), 'en', '2026-06-01');
|
||||
const looked: unknown[] = [];
|
||||
const cards: Record<string, ToolCards> = {
|
||||
import_booking: {
|
||||
load: async (_args, read) => {
|
||||
looked.push(await read('list_reservations'));
|
||||
return null;
|
||||
},
|
||||
},
|
||||
};
|
||||
const calls = [
|
||||
{ id: 'p1', toolName: 'import_booking', args: {} },
|
||||
{ id: 'p2', toolName: 'import_booking', args: {} },
|
||||
];
|
||||
const changes = await context.describeProposed(7, 1, ctx, calls, cards);
|
||||
expect(changes.map((change) => change.preview.toolCallId)).toEqual(['p1', 'p2']);
|
||||
expect(tools.open).toHaveBeenCalledTimes(1);
|
||||
expect(tools.open).toHaveBeenCalledWith(7, 1);
|
||||
expect(opened.read).toHaveBeenCalledTimes(1);
|
||||
expect(looked).toEqual([
|
||||
{ name: 'list_reservations', args: {} },
|
||||
{ name: 'list_reservations', args: {} },
|
||||
]);
|
||||
expect(opened.close).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('ASTCCX-023: the receipt of an applied change carries the card its builder gave', () => {
|
||||
const built = { kind: 'tourRoute' } as TrekCard;
|
||||
const applied = vi.spyOn(context, 'appliedCard').mockReturnValue(built);
|
||||
const w = { card: vi.fn() };
|
||||
const receipts: AssistantMessagePart[] = [];
|
||||
context.receipt(w, receipts, { id: 'w1', tool_name: 'create_hike' }, { name: 'Lake' }, { tour: {} }, null);
|
||||
expect(applied).toHaveBeenCalledWith('create_hike', {
|
||||
args: { name: 'Lake' },
|
||||
result: { tour: {} },
|
||||
preview: null,
|
||||
});
|
||||
expect(receipts).toEqual([{ type: 'data-trek-card', data: { toolCallId: 'w1', card: built } }]);
|
||||
applied.mockRestore();
|
||||
expect(context.appliedCard('create_place', { args: {}, result: {}, preview: null })).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,102 @@
|
||||
/**
|
||||
* The readers every card is built with: text masked when it comes from an
|
||||
* answer, cut to its bound, line breaks kept where a note needs them; ids,
|
||||
* clocks, moments, colours and stored file names read without trusting the
|
||||
* shape; people named from the trip card; reads named the same whatever the
|
||||
* key order of their arguments.
|
||||
*/
|
||||
import { buildTripCard } from '../../../../../src/nest/assistant/assistant-context';
|
||||
import {
|
||||
argId,
|
||||
blockText,
|
||||
canonicalJson,
|
||||
clipped,
|
||||
clockOf,
|
||||
fileKeyOf,
|
||||
hexOrNull,
|
||||
idIn,
|
||||
instantOf,
|
||||
personOf,
|
||||
readKey,
|
||||
} from '../../../../../src/nest/assistant/cards/card-values';
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
describe('card values', () => {
|
||||
it('ASTCVL-001: one line of text is masked, trimmed and cut', () => {
|
||||
expect(clipped(' Write to anna@example.test\nsoon ', 80)).toBe('Write to [hidden] soon');
|
||||
expect(clipped('abcdef', 4)).toBe('abc…');
|
||||
expect(clipped(' ', 4)).toBeNull();
|
||||
expect(clipped(7, 4)).toBeNull();
|
||||
});
|
||||
|
||||
it('ASTCVL-002: a longer text keeps its paragraphs, masked only when it comes from an answer', () => {
|
||||
const note = 'Bring cash.\r\n\r\n\r\n\r\nAsk bob@example.test\t at the desk. ';
|
||||
expect(blockText(note, 200, { mask: true })).toBe('Bring cash.\n\nAsk [hidden] at the desk.');
|
||||
expect(blockText(note, 200, { mask: false })).toBe('Bring cash.\n\nAsk bob@example.test at the desk.');
|
||||
expect(blockText('one\ntwo three', 8, { mask: false })).toBe('one\ntwo…');
|
||||
expect(blockText('\n \n', 8, { mask: false })).toBeNull();
|
||||
expect(blockText(null, 8, { mask: true })).toBeNull();
|
||||
});
|
||||
|
||||
it('ASTCVL-003: ids are positive integers, read from an answer or the arguments', () => {
|
||||
expect(idIn({ place: { id: 4 } }, 'place')).toBe(4);
|
||||
expect(idIn({ place: { id: '4' } }, 'place')).toBeNull();
|
||||
expect(idIn(null, 'place')).toBeNull();
|
||||
expect(argId({ dayId: 3, noteId: 0, itemId: 1.5 }, 'dayId')).toBe(3);
|
||||
expect(argId({ noteId: 0 }, 'noteId')).toBeNull();
|
||||
expect(argId({ itemId: 1.5 }, 'itemId')).toBeNull();
|
||||
});
|
||||
|
||||
it('ASTCVL-004: a clock is HH:MM, from a time or the time of a date and time as written', () => {
|
||||
expect(clockOf('9:30')).toBe('09:30');
|
||||
expect(clockOf('09:30:00')).toBe('09:30');
|
||||
expect(clockOf('2026-06-11T18:05:00+02:00')).toBe('18:05');
|
||||
expect(clockOf('2026-06-11 07:45')).toBe('07:45');
|
||||
expect(clockOf('24:00')).toBeNull();
|
||||
expect(clockOf('noon')).toBeNull();
|
||||
});
|
||||
|
||||
it('ASTCVL-005: a moment needs its zone and is written in UTC to the second', () => {
|
||||
expect(instantOf('2026-06-11T18:05:30.250+02:00')).toBe('2026-06-11T16:05:30Z');
|
||||
expect(instantOf('2026-06-11T18:05Z')).toBe('2026-06-11T18:05:00Z');
|
||||
expect(instantOf('2026-06-11T18:05:00')).toBeNull();
|
||||
expect(instantOf('2026-06-11')).toBeNull();
|
||||
expect(instantOf(1_700_000_000)).toBeNull();
|
||||
});
|
||||
|
||||
it('ASTCVL-006: a colour is #rrggbb, a stored file name comes only from one of TREK own upload paths', () => {
|
||||
expect(hexOrNull('#1a2B3c')).toBe('#1a2B3c');
|
||||
expect(hexOrNull('red')).toBeNull();
|
||||
expect(hexOrNull('#123')).toBeNull();
|
||||
expect(fileKeyOf('/uploads/avatars/a1b2-c3.png')).toBe('a1b2-c3.png');
|
||||
expect(fileKeyOf('/uploads/places/x.jpg?v=2')).toBeNull();
|
||||
expect(fileKeyOf('https://lh3.example.test/a.png')).toBeNull();
|
||||
expect(fileKeyOf('/uploads/avatars/../secret')).toBeNull();
|
||||
expect(fileKeyOf('/uploads/avatars/..hidden')).toBeNull();
|
||||
expect(fileKeyOf('a.png')).toBeNull();
|
||||
});
|
||||
|
||||
it('ASTCVL-007: a person is a trip member by id, named as the trip names them', () => {
|
||||
const summary = {
|
||||
members: {
|
||||
owner: { id: 7, username: 'mia@example.test', avatar_url: '/uploads/avatars/mia.png' },
|
||||
collaborators: [{ id: 8, username: 'jon' }],
|
||||
},
|
||||
};
|
||||
const card = buildTripCard(1, 8, summary, null, null);
|
||||
expect(personOf(card, 7)).toEqual({ id: 7, name: '[hidden]', avatarKey: 'mia.png' });
|
||||
expect(personOf(card, 8)).toEqual({ id: 8, name: 'jon', avatarKey: null });
|
||||
expect(personOf(card, 9)).toBeNull();
|
||||
});
|
||||
|
||||
it('ASTCVL-008: a read is named by its tool and its arguments, in any key order', () => {
|
||||
expect(canonicalJson({ b: [2, { d: 1, c: null }], a: 'x', skip: undefined })).toBe(
|
||||
'{"a":"x","b":[2,{"c":null,"d":1}]}',
|
||||
);
|
||||
expect(readKey('get_vacay_plan', { year: 2026, userId: 7 })).toBe(
|
||||
readKey('get_vacay_plan', { userId: 7, year: 2026 }),
|
||||
);
|
||||
expect(readKey('list_places')).toBe('list_places {}');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,87 @@
|
||||
/**
|
||||
* A package hook that throws never breaks a turn, a decision or an undo: the
|
||||
* registry wraps each one at load, and the place that calls it falls back to
|
||||
* what a tool without the hook gets. One package is replaced by a probe whose
|
||||
* every hook throws, so these cases run through the live call sites.
|
||||
*/
|
||||
import { buildTripCard } from '../../../../../src/nest/assistant/assistant-context';
|
||||
import { toolOutputForProvider } from '../../../../../src/nest/assistant/assistant-output';
|
||||
import { unchangedSinceApplied } from '../../../../../src/nest/assistant/assistant-undo.helpers';
|
||||
import type { PreviewContext } from '../../../../../src/nest/assistant/cards/card-types';
|
||||
import {
|
||||
ASSISTANT_UNDO_MAP,
|
||||
describedOf,
|
||||
nameArgOf,
|
||||
TOOL_CARDS,
|
||||
undoReadsOf,
|
||||
} from '../../../../../src/nest/assistant/cards/registry';
|
||||
import { appliedChange, describeToolCall } from '../../../../../src/nest/assistant/tool-call-preview.helpers';
|
||||
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const logMock = vi.hoisted(() => ({ logInfo: vi.fn(), logError: vi.fn(), logWarn: vi.fn(), logDebug: vi.fn() }));
|
||||
vi.mock('../../../../../src/nest/audit/audit-log.logger', () => logMock);
|
||||
|
||||
vi.mock('../../../../../src/nest/assistant/cards/vacay', () => {
|
||||
const boom = (): never => {
|
||||
throw new Error('boom');
|
||||
};
|
||||
return {
|
||||
VACAY_CARDS: {
|
||||
id: 'vacay',
|
||||
tools: {
|
||||
plan_probe: {
|
||||
write: { verbKey: 'genericCreate', entity: 'other' },
|
||||
describe: boom,
|
||||
effect: boom,
|
||||
project: boom,
|
||||
appliedIds: boom,
|
||||
nameArg: boom,
|
||||
undo: { tool: 'delete_probe', args: boom, reads: boom, unchanged: boom },
|
||||
},
|
||||
list_probe: { appliedIds: () => [3, 0, -1, 2.5, 'x'] },
|
||||
},
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
beforeEach(() => vi.clearAllMocks());
|
||||
|
||||
const card = buildTripCard(1, 7, { trip: { title: 'Alps' } }, null, null);
|
||||
const ctx: PreviewContext = { card, categories: new Map(), locale: 'en', today: '2026-06-01', airport: () => null };
|
||||
const logged = () => logMock.logWarn.mock.calls.map(([line]) => String(line));
|
||||
|
||||
describe('the guarded package hooks', () => {
|
||||
it('ASTREG-030: a describer that throws gives way to the card built from the arguments', () => {
|
||||
const preview = describeToolCall('plan_probe', 'c1', { name: 'Lake' }, ctx);
|
||||
expect(preview).toMatchObject({ toolCallId: 'c1', tool: 'plan_probe' });
|
||||
expect(logged()[0]).toContain('the describer of plan_probe failed: boom');
|
||||
expect(describedOf('create_place', ctx, {}, null)).toBeNull();
|
||||
expect(TOOL_CARDS.plan_probe?.effect?.(ctx, {}, null)).toBeNull();
|
||||
});
|
||||
|
||||
it('ASTREG-031: ids that throw fall back to the answer, and ids that are no row ids are left out', () => {
|
||||
const applied = appliedChange('plan_probe', 'c1', {}, { place: { id: 9 } }, null, null);
|
||||
expect(applied).toMatchObject({ entity: 'other', ids: [9] });
|
||||
expect(appliedChange('list_probe', 'c2', {}, {}, null, null)?.ids).toEqual([3]);
|
||||
expect(logged()[0]).toContain('the applied ids of plan_probe failed: boom');
|
||||
});
|
||||
|
||||
it('ASTREG-032: an undo whose hooks throw has no way back and reads as changed since', () => {
|
||||
expect(ASSISTANT_UNDO_MAP.plan_probe?.args({}, {}, null)).toBeNull();
|
||||
expect(undoReadsOf('plan_probe', {}, {})).toEqual([]);
|
||||
expect(unchangedSinceApplied('plan_probe', {}, { summary: {}, places: {} })).toBe(false);
|
||||
expect(nameArgOf('plan_probe', 'probeId', 1, card)).toBeNull();
|
||||
expect(logged()).toEqual([
|
||||
expect.stringContaining('the undo arguments of plan_probe failed'),
|
||||
expect.stringContaining('the undo reads of plan_probe failed'),
|
||||
expect.stringContaining('the undo check of plan_probe failed'),
|
||||
expect.stringContaining('the name of probeId of plan_probe failed'),
|
||||
]);
|
||||
});
|
||||
|
||||
it('ASTREG-033: a projection that throws hands the provider the answer as it came', () => {
|
||||
expect(toolOutputForProvider('plan_probe', { days: 3 })).toEqual({ days: 3 });
|
||||
expect(logged()[0]).toContain('the projection of plan_probe failed: boom');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,225 @@
|
||||
/**
|
||||
* The cards registry: the packages' entries merged by tool name, every overlap
|
||||
* refused at load, and the guarded card calls that give no card, never a
|
||||
* broken turn, for a builder that throws, misbuilds or builds too much. The
|
||||
* receipt card of an applied change rides on the same guard.
|
||||
*/
|
||||
import { buildTripCard } from '../../../../../src/nest/assistant/assistant-context';
|
||||
import { withPackageControllers } from '../../../../../src/nest/assistant/assistant-tool-offer';
|
||||
import { CORE_WRITE_TOOLS } from '../../../../../src/nest/assistant/assistant-tools.constants';
|
||||
import { receiptCard } from '../../../../../src/nest/assistant/cards/applied-cards';
|
||||
import type { DomainCards, PreviewContext, ToolCards } from '../../../../../src/nest/assistant/cards/card-types';
|
||||
import { Rows } from '../../../../../src/nest/assistant/cards/preview-format';
|
||||
import {
|
||||
answerCardOf,
|
||||
ASSISTANT_UNDO_MAP,
|
||||
ASSISTANT_WRITE_TOOLS,
|
||||
CARD_PROMPT_LINES,
|
||||
DOMAINS,
|
||||
guardedCards,
|
||||
mergeDomains,
|
||||
nameArgOf,
|
||||
refuseCoreOverlap,
|
||||
TOOL_CARDS,
|
||||
undoReadsOf,
|
||||
type CardCheck,
|
||||
} from '../../../../../src/nest/assistant/cards/registry';
|
||||
import type { AssistantMessagePart, TrekCard } from '@trek/shared';
|
||||
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { z, type ZodType } from 'zod';
|
||||
|
||||
const logMock = vi.hoisted(() => ({ logInfo: vi.fn(), logError: vi.fn(), logWarn: vi.fn(), logDebug: vi.fn() }));
|
||||
vi.mock('../../../../../src/nest/audit/audit-log.logger', () => logMock);
|
||||
|
||||
beforeEach(() => vi.clearAllMocks());
|
||||
|
||||
const card = buildTripCard(1, 7, { trip: { title: 'Alps' } }, null, null);
|
||||
const ctx: PreviewContext = { card, categories: new Map(), locale: 'en', today: '2026-06-01', airport: () => null };
|
||||
|
||||
/**
|
||||
* A stand-in for the card union with one kind of its own, so these cases hold
|
||||
* whatever fields the packages give their kinds.
|
||||
*/
|
||||
const PROBE: CardCheck = {
|
||||
schema: z.object({ kind: z.literal('probe'), title: z.string().max(12) }) as unknown as ZodType<TrekCard>,
|
||||
maxChars: 60,
|
||||
};
|
||||
const probe = (title: string) => ({ kind: 'probe', title }) as unknown as TrekCard;
|
||||
|
||||
const domain = (id: DomainCards['id'], tools: Record<string, ToolCards>, extra: Partial<DomainCards> = {}) => ({
|
||||
id,
|
||||
tools,
|
||||
...extra,
|
||||
});
|
||||
const described = () => ({ subject: 'x', rows: new Rows(), dayId: null, placeIds: [] });
|
||||
|
||||
describe('mergeDomains', () => {
|
||||
it('ASTREG-001: the live registry holds every package once, the core tables and the tours they brought', () => {
|
||||
expect(new Set(DOMAINS.map((d) => d.id)).size).toBe(10);
|
||||
for (const name of Object.keys(CORE_WRITE_TOOLS)) expect(ASSISTANT_WRITE_TOOLS[name]).toBe(CORE_WRITE_TOOLS[name]);
|
||||
expect(ASSISTANT_WRITE_TOOLS.create_hike).toEqual({ verbKey: 'addTour', entity: 'tour' });
|
||||
expect(ASSISTANT_UNDO_MAP.create_city_walk?.tool).toBe('delete_place');
|
||||
expect(ASSISTANT_UNDO_MAP.create_city_walk?.args({}, { tour: { place_id: 9 } }, null)).toEqual({ placeId: 9 });
|
||||
expect(TOOL_CARDS.update_tour?.undo).toBeUndefined();
|
||||
expect(CARD_PROMPT_LINES).toEqual([]);
|
||||
});
|
||||
|
||||
it('ASTREG-002: two packages may fill different fields of one tool, never the same one', () => {
|
||||
const answer = () => null;
|
||||
const merged = mergeDomains([
|
||||
domain('tour', { list_tours: { answer } }),
|
||||
domain('packing', { list_tours: { appliedIds: () => [1] } }),
|
||||
]);
|
||||
expect(Object.keys(merged.tools.list_tours ?? {})).toEqual(['answer', 'appliedIds']);
|
||||
expect(() =>
|
||||
mergeDomains([domain('tour', { list_tours: { answer } }), domain('packing', { list_tours: { answer } })]),
|
||||
).toThrow('"answer" of "list_tours" is claimed by tour and packing');
|
||||
});
|
||||
|
||||
it("ASTREG-003: a package never takes the core's entry of a tool, nor half a curated card", () => {
|
||||
const write = { verbKey: 'genericCreate', entity: 'other' } as const;
|
||||
expect(() => mergeDomains([domain('budget', { create_place: { write, describe: described } })])).toThrow(
|
||||
'"write" of "create_place" is the core\'s own',
|
||||
);
|
||||
expect(() => mergeDomains([domain('budget', { import_booking: { write, describe: described } })])).toThrow(
|
||||
'"write" of "import_booking"',
|
||||
);
|
||||
const undo = { tool: 'delete_todo', args: () => null, unchanged: () => true };
|
||||
expect(() => mergeDomains([domain('packing', { create_todo: { undo } })])).toThrow('"undo" of "create_todo"');
|
||||
expect(() => mergeDomains([domain('tour', { update_place: { argPolicy: { stripped: ['x'] } } })])).toThrow(
|
||||
'"argPolicy" of "update_place"',
|
||||
);
|
||||
expect(() => mergeDomains([domain('vacay', { set_vacay: { describe: described } })])).toThrow(
|
||||
'needs both a write entry and a describer',
|
||||
);
|
||||
expect(() => mergeDomains([domain('vacay', { set_vacay: { write } })])).toThrow('needs both');
|
||||
});
|
||||
|
||||
it('ASTREG-004: a package comes once, with at most two prompt lines; its lines, groups and projections are gathered', () => {
|
||||
expect(() => mergeDomains([domain('atlas', {}), domain('atlas', {})])).toThrow('registered twice');
|
||||
expect(() => mergeDomains([domain('atlas', {}, { prompt: ['a', 'b', 'c'] })])).toThrow('more than 2 prompt lines');
|
||||
const merged = mergeDomains([
|
||||
domain(
|
||||
'collection',
|
||||
{ list_collection: { project: (value) => ({ kept: value }) } },
|
||||
{
|
||||
prompt: ['Collections are drawn as cards.'],
|
||||
foreignIdGroups: ['collections'],
|
||||
},
|
||||
),
|
||||
domain('atlas', {}, { prompt: ['The atlas too.'], foreignIdGroups: ['atlas'] }),
|
||||
]);
|
||||
expect(merged.promptLines).toEqual(['Collections are drawn as cards.', 'The atlas too.']);
|
||||
expect([...merged.foreignIdGroups]).toEqual(['collections', 'atlas']);
|
||||
expect(merged.projections.list_collection?.(3)).toEqual({ kept: 3 });
|
||||
});
|
||||
|
||||
it("ASTREG-005: the core's describers, effects and projections refuse a package's entry for their tool", () => {
|
||||
const tools: Record<string, ToolCards> = { create_place: { effect: () => null } };
|
||||
expect(() => refuseCoreOverlap('effect', ['create_place'], tools)).toThrow('"effect" of "create_place"');
|
||||
expect(() => refuseCoreOverlap('describe', ['create_place'], tools)).not.toThrow();
|
||||
});
|
||||
|
||||
it('ASTREG-006: the controllers and held reads of the packages are gathered, a controller only once', () => {
|
||||
const merged = mergeDomains([
|
||||
domain('roadtrip', {}, { toolControllers: { roadtrip: ['CorridorMcp'] }, heldReads: ['fetch_corridor'] }),
|
||||
domain('budget', {}, { toolControllers: { roadtrip: ['TollMcp'], files: ['ReceiptMcp'] } }),
|
||||
]);
|
||||
expect(merged.toolControllers).toEqual({ roadtrip: ['CorridorMcp', 'TollMcp'], files: ['ReceiptMcp'] });
|
||||
expect([...merged.heldReads]).toEqual(['fetch_corridor']);
|
||||
expect(() =>
|
||||
mergeDomains([
|
||||
domain('roadtrip', {}, { toolControllers: { roadtrip: ['CorridorMcp'] } }),
|
||||
domain('budget', {}, { toolControllers: { files: ['CorridorMcp'] } }),
|
||||
]),
|
||||
).toThrow('controller "CorridorMcp" is listed twice');
|
||||
});
|
||||
|
||||
it('ASTREG-007: a package adds controllers to a known tool group, never to a new one or twice', () => {
|
||||
const core = { roadtrip: { about: 'Road trips.', controllers: ['RoadtripMcp'] } };
|
||||
expect(withPackageControllers(core, { roadtrip: ['CorridorMcp'] }).roadtrip?.controllers).toEqual([
|
||||
'RoadtripMcp',
|
||||
'CorridorMcp',
|
||||
]);
|
||||
expect(core.roadtrip.controllers).toEqual(['RoadtripMcp']);
|
||||
expect(() => withPackageControllers(core, { trains: ['RailMcp'] })).toThrow('no group "trains"');
|
||||
expect(() => withPackageControllers(core, { roadtrip: ['RoadtripMcp'] })).toThrow(
|
||||
'"RoadtripMcp" is listed already',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('the guarded card calls', () => {
|
||||
const answerInput = { toolCallId: 'c1', args: {}, value: {}, card, today: '2026-06-01' };
|
||||
|
||||
it('ASTREG-010: a card that fits its kind comes through as the union reads it', () => {
|
||||
const calls = guardedCards(
|
||||
{ find: { answer: () => ({ ...probe('Lake'), extra: 1 }) as unknown as TrekCard } },
|
||||
PROBE,
|
||||
);
|
||||
expect(calls.answerCardOf('find', answerInput)).toEqual({ kind: 'probe', title: 'Lake' });
|
||||
expect(calls.answerCardOf('other', answerInput)).toBeNull();
|
||||
expect(logMock.logWarn).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('ASTREG-011: a builder that throws, misbuilds or builds past the size cap gives null and a log line', () => {
|
||||
const calls = guardedCards(
|
||||
{
|
||||
thrown: {
|
||||
answer: () => {
|
||||
throw new Error('boom');
|
||||
},
|
||||
},
|
||||
misbuilt: { change: () => probe('A title far too long') },
|
||||
heavy: { applied: () => probe('x'.repeat(12)) },
|
||||
},
|
||||
{ ...PROBE, maxChars: 30 },
|
||||
);
|
||||
expect(calls.answerCardOf('thrown', answerInput)).toBeNull();
|
||||
expect(calls.changeCardOf('misbuilt', ctx, {}, null)).toBeNull();
|
||||
expect(calls.appliedCardOf('heavy', { args: {}, result: {}, preview: null })).toBeNull();
|
||||
const lines = logMock.logWarn.mock.calls.map(([line]) => String(line));
|
||||
expect(lines[0]).toContain('the answer card of thrown failed: boom');
|
||||
expect(lines[1]).toContain('the change card of misbuilt does not fit its kind: title');
|
||||
expect(lines[2]).toContain('the applied card of heavy is too large');
|
||||
});
|
||||
|
||||
it('ASTREG-012: the live calls check against the card union itself', () => {
|
||||
expect(answerCardOf('list_places', answerInput)).toBeNull();
|
||||
const unknown = guardedCards({ list_places: { answer: () => ({ kind: 'bookPage' }) as unknown as TrekCard } });
|
||||
expect(unknown.answerCardOf('list_places', answerInput)).toBeNull();
|
||||
expect(String(logMock.logWarn.mock.calls[0]?.[0])).toContain('does not fit its kind');
|
||||
});
|
||||
|
||||
it('ASTREG-013: a package names no id and reads nothing for an undo unless it says so', () => {
|
||||
expect(nameArgOf('create_hike', 'placeId', 3, card)).toBeNull();
|
||||
expect(undoReadsOf('create_hike', {}, {})).toEqual([]);
|
||||
expect(undoReadsOf('no_such_tool', {}, {})).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('receiptCard', () => {
|
||||
it('ASTREG-020: streams and keeps the applied card under the write id, for the tool a found place runs as', () => {
|
||||
const w = { card: vi.fn() };
|
||||
const receipts: AssistantMessagePart[] = [];
|
||||
const build = vi.fn(() => probe('Lake'));
|
||||
const args = { via: 'create_and_assign_place', dayId: 3, name: 'Lake' };
|
||||
receiptCard(w, receipts, { id: 'w1', tool_name: 'add_found_place' }, args, { place: { id: 4 } }, null, build);
|
||||
expect(build).toHaveBeenCalledWith('create_and_assign_place', {
|
||||
args,
|
||||
result: { place: { id: 4 } },
|
||||
preview: null,
|
||||
});
|
||||
expect(w.card).toHaveBeenCalledWith({ toolCallId: 'w1', card: probe('Lake') });
|
||||
expect(receipts).toEqual([{ type: 'data-trek-card', data: { toolCallId: 'w1', card: probe('Lake') } }]);
|
||||
});
|
||||
|
||||
it('ASTREG-021: adds nothing when the tool has no applied card', () => {
|
||||
const w = { card: vi.fn() };
|
||||
const receipts: AssistantMessagePart[] = [];
|
||||
receiptCard(w, receipts, { id: 'w1', tool_name: 'create_place' }, {}, {}, null);
|
||||
expect(w.card).not.toHaveBeenCalled();
|
||||
expect(receipts).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -3,19 +3,18 @@
|
||||
* locale, the value before a change, and the receipt of an applied change.
|
||||
*/
|
||||
import { buildTripCard } from '../../../../src/nest/assistant/assistant-context';
|
||||
import { ASSISTANT_WRITE_TOOLS } from '../../../../src/nest/assistant/assistant-tools.constants';
|
||||
import {
|
||||
appliedChange,
|
||||
dayLabel,
|
||||
describeToolCall,
|
||||
type PreviewContext,
|
||||
} from '../../../../src/nest/assistant/tool-call-preview.helpers';
|
||||
import { assistantChangePreviewSchema } from '@trek/shared';
|
||||
import type { AssistantWriteTool } from '../../../../src/nest/assistant/assistant-tools.constants';
|
||||
import type { PreviewContext, ToolCards } from '../../../../src/nest/assistant/cards/card-types';
|
||||
import { dayLabel, Rows } from '../../../../src/nest/assistant/cards/preview-format';
|
||||
import { ASSISTANT_WRITE_TOOLS, FOREIGN_ID_GROUPS, TOOL_CARDS } from '../../../../src/nest/assistant/cards/registry';
|
||||
import { appliedChange, describeToolCall } from '../../../../src/nest/assistant/tool-call-preview.helpers';
|
||||
import { assistantChangePreviewSchema, trekCardSchema, type TrekCard } from '@trek/shared';
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
const card = buildTripCard(
|
||||
1,
|
||||
7,
|
||||
{
|
||||
trip: { title: 'Kyoto', currency: 'EUR' },
|
||||
members: { owner: { id: 7, username: 'mia' }, collaborators: [{ id: 8, username: 'jon' }] },
|
||||
@@ -56,6 +55,8 @@ const ctx: PreviewContext = {
|
||||
[3, 'Sights'],
|
||||
]),
|
||||
locale: 'en-GB',
|
||||
today: '2026-06-01',
|
||||
airport: () => null,
|
||||
};
|
||||
|
||||
const describe_ = (name: string, args: Record<string, unknown>) => describeToolCall(name, 'tc-1', args, ctx);
|
||||
@@ -515,4 +516,105 @@ describe('the cards of tours', () => {
|
||||
ids: [],
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* Lends a tool package cards for one case, the way a package's index adds
|
||||
* them, and takes them back after it.
|
||||
*/
|
||||
function withCards<T>(tool: string, cards: ToolCards, write: AssistantWriteTool | null, run: () => T): T {
|
||||
const tools = TOOL_CARDS as Record<string, ToolCards>;
|
||||
const writes = ASSISTANT_WRITE_TOOLS as Record<string, AssistantWriteTool>;
|
||||
const [before, writeBefore] = [tools[tool], writes[tool]];
|
||||
tools[tool] = { ...before, ...cards };
|
||||
if (write) writes[tool] = write;
|
||||
try {
|
||||
return run();
|
||||
} finally {
|
||||
if (before) tools[tool] = before;
|
||||
else Reflect.deleteProperty(tools, tool);
|
||||
if (writeBefore) writes[tool] = writeBefore;
|
||||
else Reflect.deleteProperty(writes, tool);
|
||||
}
|
||||
}
|
||||
|
||||
it("ASTPRV-028: a package's describer speaks for its tool with its lookup, its overrides and its effect", () => {
|
||||
const cards: ToolCards<string> = {
|
||||
describe: (_ctx, args, loaded) => ({
|
||||
subject: `${String(args.name)} (${loaded ?? 'none'})`,
|
||||
rows: new Rows().add('day', 'Fri'),
|
||||
dayId: 32,
|
||||
placeIds: [],
|
||||
verbKey: 'genericUpdate',
|
||||
tool: 'plan_vacay_days',
|
||||
domain: 'vacay',
|
||||
}),
|
||||
effect: (_ctx, _args, loaded) =>
|
||||
loaded ? { kind: 'add', dayId: 32, fromDayId: null, placeId: 12, assignmentId: null, place: null } : null,
|
||||
};
|
||||
const preview = withCards('plan_vacay_days', cards, { verbKey: 'genericCreate', entity: 'other' }, () =>
|
||||
describeToolCall('plan_vacay_days', 'tc-30', { name: 'Summer' }, ctx, 'plan'),
|
||||
);
|
||||
expect(preview).toMatchObject({
|
||||
verbKey: 'genericUpdate',
|
||||
subject: 'Summer (plan)',
|
||||
tool: 'plan_vacay_days',
|
||||
domain: 'vacay',
|
||||
dayId: 32,
|
||||
undoable: false,
|
||||
effect: { kind: 'add', dayId: 32, placeId: 12 },
|
||||
});
|
||||
expect(assistantChangePreviewSchema.safeParse(preview).success).toBe(true);
|
||||
});
|
||||
|
||||
it('ASTPRV-029: a change card rides on a curated and on a generic card; one its kind refuses stays out', () => {
|
||||
const built = { kind: 'tourRoute' } as TrekCard;
|
||||
const drawn = trekCardSchema.safeParse(built).success ? { card: built } : {};
|
||||
const curated = withCards('create_place', { change: () => built }, null, () =>
|
||||
describe_('create_place', { name: 'Kinkaku-ji' }),
|
||||
);
|
||||
expect(curated).toMatchObject({ verbKey: 'addPlace', subject: 'Kinkaku-ji', ...drawn });
|
||||
const generic = withCards('set_vacay_days', { change: () => built }, null, () =>
|
||||
describe_('set_vacay_days', { days: 3 }),
|
||||
);
|
||||
expect(generic).toMatchObject({ tool: 'set_vacay_days', ...drawn });
|
||||
const refused = withCards(
|
||||
'set_vacay_days',
|
||||
{ change: () => ({ kind: 'bookPage' }) as unknown as TrekCard },
|
||||
null,
|
||||
() => describe_('set_vacay_days', { days: 3 }),
|
||||
);
|
||||
expect(refused).not.toHaveProperty('card');
|
||||
expect(describe_('create_place', { name: 'Kinkaku-ji' })).not.toHaveProperty('card');
|
||||
});
|
||||
|
||||
it("ASTPRV-030: a package's applied ids name the receipt before the answer's usual keys", () => {
|
||||
const applied = withCards('create_place', { appliedIds: (_args, result) => [Number(result)] }, null, () =>
|
||||
appliedChange('create_place', 'tc', {}, 77, null, null),
|
||||
);
|
||||
expect(applied).toMatchObject({ entity: 'place', ids: [77] });
|
||||
expect(appliedChange('create_place', 'tc', {}, { place: { id: 5 } }, null, null)).toMatchObject({ ids: [5] });
|
||||
});
|
||||
|
||||
it('ASTPRV-031: a package names its ids first; a place id of a tool outside the trip is no trip place', () => {
|
||||
const groups = FOREIGN_ID_GROUPS as Set<string>;
|
||||
const saved = { ...ctx, hintOf: () => ({ destructive: false, creates: true, group: 'collections' }) };
|
||||
const add = () => describeToolCall('add_collection_place', 'tc-31', { placeId: 12 }, saved);
|
||||
// Place 12 is the trip's Nishiki Market until the collections say their ids are their own.
|
||||
expect(add()).toMatchObject({ subject: 'Nishiki Market', placeIds: [12], domain: 'collections' });
|
||||
groups.add('collections');
|
||||
try {
|
||||
const outside = add();
|
||||
expect(outside).toMatchObject({ subject: 'add collection place', placeIds: [] });
|
||||
expect(outside.rows).toEqual([{ op: 'add', labelKey: 'field', field: 'placeId', before: null, after: '12' }]);
|
||||
const named = withCards(
|
||||
'add_collection_place',
|
||||
{ nameArg: (key, value) => (key === 'placeId' ? `Saved place ${value}` : null) },
|
||||
null,
|
||||
add,
|
||||
);
|
||||
expect(named).toMatchObject({ subject: 'Saved place 12', rows: [], placeIds: [] });
|
||||
} finally {
|
||||
groups.delete('collections');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
*/
|
||||
import { UiStreamWriter } from '../../../../src/nest/assistant/ui-stream.writer';
|
||||
import type { SseStream } from '../../../../src/nest/common/sse-stream';
|
||||
import { uiStreamChunkSchema, UI_STREAM_DONE } from '@trek/shared';
|
||||
import { uiStreamChunkSchema, UI_STREAM_DONE, type TrekCard } from '@trek/shared';
|
||||
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { resolve } from 'node:path';
|
||||
@@ -16,6 +16,13 @@ const FIXTURE = readFileSync(
|
||||
resolve(__dirname, '../../../../../shared/src/assistant/__fixtures__/ui-stream.v1.txt'),
|
||||
'utf8',
|
||||
);
|
||||
const CARDS_FIXTURE = readFileSync(
|
||||
resolve(__dirname, '../../../../../shared/src/assistant/__fixtures__/ui-stream.cards.v1.txt'),
|
||||
'utf8',
|
||||
);
|
||||
|
||||
/** A card as a package builds it; the writer passes it on as it is, whatever its fields. */
|
||||
const cardOf = (kind: string) => ({ kind }) as TrekCard;
|
||||
|
||||
function memoryStream(): SseStream & { text: () => string; ended: boolean } {
|
||||
let out = '';
|
||||
@@ -156,6 +163,7 @@ describe('UiStreamWriter', () => {
|
||||
{ dayId: 4, date: '2026-06-11', main: 'Drizzle', tempMax: 19, tempMin: null, rainPct: 80, kind: 'forecast' },
|
||||
],
|
||||
});
|
||||
w.card({ toolCallId: 'call_2', card: cardOf('tourList') });
|
||||
const chunks = stream
|
||||
.text()
|
||||
.split('\n\n')
|
||||
@@ -168,7 +176,45 @@ describe('UiStreamWriter', () => {
|
||||
'data-trek-activity',
|
||||
'data-trek-places',
|
||||
'data-trek-weather',
|
||||
'data-trek-card',
|
||||
]);
|
||||
expect(chunks[3]).toMatchObject({ transient: true, data: { label: 'Trastevere' } });
|
||||
expect(chunks[6]).toMatchObject({ data: { toolCallId: 'call_2' } });
|
||||
expect(chunks[6]).not.toHaveProperty('transient');
|
||||
});
|
||||
|
||||
it('ASTWRT-006: writes the shared cards fixture byte for byte: a receipt card, a read card, a held change card', () => {
|
||||
const applied = '7c1e2d3a-0b4f-4e8a-9d6c-1f2e3a4b5c6d';
|
||||
const held = '9a8b7c6d-5e4f-4a3b-8c2d-1e0f9a8b7c6d';
|
||||
const stream = memoryStream();
|
||||
const w = new UiStreamWriter(stream);
|
||||
w.start('msg-12');
|
||||
w.toolOutput(applied, { tour: { place_id: 77, name: 'Ridge walk' } });
|
||||
w.applied({ toolCallId: applied, entity: 'tour', ids: [77], dayId: 32, undoUntil: '2026-06-11T09:15:00Z' });
|
||||
w.card({ toolCallId: applied, card: cardOf('tourRoute') });
|
||||
w.startStep();
|
||||
w.toolInput('toolu_02', 'list_tours', {});
|
||||
w.toolOutput('toolu_02', { tours: [{ place_id: 77, name: 'Ridge walk' }] });
|
||||
w.card({ toolCallId: 'toolu_02', card: cardOf('tourList') });
|
||||
w.finishStep();
|
||||
w.startStep();
|
||||
w.text('The ridge walk is on Friday now. ');
|
||||
w.text('A lake loop would fit on Saturday.');
|
||||
w.toolInput(held, 'create_hike', { name: 'Lake loop', round_trip: true });
|
||||
w.approvalRequest(held);
|
||||
w.change({
|
||||
toolCallId: held,
|
||||
verbKey: 'addTour',
|
||||
subject: 'Lake loop',
|
||||
rows: [{ op: 'add', labelKey: 'route', before: null, after: 'Car park → Lake → Car park' }],
|
||||
dayId: null,
|
||||
placeIds: [],
|
||||
undoable: true,
|
||||
card: cardOf('tourRoute'),
|
||||
});
|
||||
w.quota(4, 50);
|
||||
w.finish('tool-calls');
|
||||
w.close();
|
||||
expect(stream.text()).toBe(CARDS_FIXTURE);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -17,7 +17,7 @@ import { trekMcpErrorMapper } from '../../../src/mcp/nest-mcp-policy';
|
||||
import { errorResult, type McpContext, type McpTextResult, type ToolOptions } from '../../../src/nest-mcp';
|
||||
import { getEntry, type ClassRef } from '../../../src/nest-mcp/metadata';
|
||||
import { AddonsService } from '../../../src/nest/addons/addons.service';
|
||||
import { toolOutputForProvider } from '../../../src/nest/assistant/assistant-redact';
|
||||
import { toolOutputForProvider } from '../../../src/nest/assistant/assistant-output';
|
||||
import { DomainError } from '../../../src/nest/common/domain-error';
|
||||
import { DawarichAtlasMcp } from '../../../src/nest/integrations/dawarich-atlas.mcp';
|
||||
import { DawarichSuggestionsService } from '../../../src/nest/integrations/dawarich-suggestions.service';
|
||||
|
||||
@@ -12,7 +12,7 @@ import type { McpContext } from '../../../src/nest-mcp';
|
||||
import { getEntry, type ClassRef } from '../../../src/nest-mcp/metadata';
|
||||
import { AddonsModule } from '../../../src/nest/addons/addons.module';
|
||||
import { AddonsService } from '../../../src/nest/addons/addons.service';
|
||||
import { toolOutputForProvider } from '../../../src/nest/assistant/assistant-redact';
|
||||
import { toolOutputForProvider } from '../../../src/nest/assistant/assistant-output';
|
||||
import { JourneyDomainModule } from '../../../src/nest/journey/journey-domain.module';
|
||||
import { JourneyDomainService } from '../../../src/nest/journey/journey-domain.service';
|
||||
import { JourneyTracksMcp } from '../../../src/nest/journey/journey-tracks.mcp';
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
import {
|
||||
ASSISTANT_MESSAGE_PARTS,
|
||||
ASSISTANT_MESSAGE_PARTS_WRITE,
|
||||
ASSISTANT_TOOL_PREVIEW,
|
||||
ASSISTANT_TOOL_PREVIEW_WRITE,
|
||||
COLLAB_POLL_OPTIONS,
|
||||
JOURNEY_ENTRY_PROS_CONS,
|
||||
JOURNEY_ENTRY_TAGS,
|
||||
@@ -156,4 +160,48 @@ describe('the declared columns', () => {
|
||||
expect(decodeJson(TOUR_CHANGE_STEP_BEFORE, '{"waypoints":"none"}')).toBeNull();
|
||||
expect(decodeJson(TOUR_CHANGE_STEP_BEFORE, '{bad')).toBeNull();
|
||||
});
|
||||
|
||||
it('JSONCOL-035: an assistant message drops a data part or card a later build wrote, never the message', () => {
|
||||
const text = { type: 'text', text: 'Here is the walk.' };
|
||||
const stored = JSON.stringify([
|
||||
text,
|
||||
{ type: 'data-trek-book-page', data: { page: 3 } },
|
||||
{ type: 'data-trek-card', data: { toolCallId: 'c1', card: { kind: 'bookPage' } } },
|
||||
]);
|
||||
expect(decodeJson(ASSISTANT_MESSAGE_PARTS, stored)).toEqual([
|
||||
text,
|
||||
{ type: 'data-trek-card', data: { toolCallId: 'c1', card: null } },
|
||||
]);
|
||||
expect(logMock.logWarn).not.toHaveBeenCalled();
|
||||
expect(decodeJson(ASSISTANT_MESSAGE_PARTS, '[{"type":"text","text":5}]', 'message 9')).toEqual([]);
|
||||
expect(logMock.logWarn).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('JSONCOL-036: an assistant message is written strictly: a part this build cannot describe is refused', () => {
|
||||
const parts = [{ type: 'data-trek-card' as const, data: { toolCallId: 'c1', card: null } }];
|
||||
expect(JSON.parse(encodeJson(ASSISTANT_MESSAGE_PARTS_WRITE, parts))).toEqual(parts);
|
||||
const unknown = [{ type: 'data-trek-book-page', data: {} }] as unknown as typeof parts;
|
||||
expect(() => encodeJson(ASSISTANT_MESSAGE_PARTS_WRITE, unknown)).toThrow();
|
||||
const misbuilt = [{ type: 'data-trek-card', data: { toolCallId: 'c1', card: { kind: 'bookPage' } } }];
|
||||
expect(() => encodeJson(ASSISTANT_MESSAGE_PARTS_WRITE, misbuilt as unknown as typeof parts)).toThrow();
|
||||
expect(ASSISTANT_MESSAGE_PARTS_WRITE.column).toBe(ASSISTANT_MESSAGE_PARTS.column);
|
||||
});
|
||||
|
||||
it('JSONCOL-037: a stored change card reads a later verb as a plain update, and is written strictly', () => {
|
||||
const preview = {
|
||||
toolCallId: 'c1',
|
||||
verbKey: 'addPlace' as const,
|
||||
subject: 'Lake',
|
||||
rows: [],
|
||||
dayId: null,
|
||||
placeIds: [],
|
||||
undoable: false,
|
||||
};
|
||||
const later = JSON.stringify({ ...preview, verbKey: 'laterVerb' });
|
||||
expect(decodeJson(ASSISTANT_TOOL_PREVIEW, later)).toEqual({ ...preview, verbKey: 'genericUpdate' });
|
||||
expect(JSON.parse(encodeJson(ASSISTANT_TOOL_PREVIEW_WRITE, preview))).toEqual(preview);
|
||||
const misbuilt = { ...preview, verbKey: 'laterVerb' } as unknown as typeof preview;
|
||||
expect(() => encodeJson(ASSISTANT_TOOL_PREVIEW_WRITE, misbuilt)).toThrow();
|
||||
expect(ASSISTANT_TOOL_PREVIEW_WRITE.column).toBe(ASSISTANT_TOOL_PREVIEW.column);
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user