feat(assistant): hike, walk and route cards with their lines on the map, and "Plan this"

This commit is contained in:
Maurice
2026-10-22 15:50:47 +02:00
parent 8547006742
commit 59313dfaff
135 changed files with 12185 additions and 234 deletions
@@ -0,0 +1,322 @@
/**
* Trip assistant e2e for the tours: the whole app (buildApp, every global
* guard, the Zod pipe, the response contracts, the real MCP registry with
* its addon gates) with an instance connection to a fake OpenAI-compatible
* server on loopback, scripted per case. The hike planner itself is stubbed
* on the container's HikePlanService (its routing has suites of its own,
* tours-hike.e2e): the proposal it answers, and the hike it creates on a
* real place of the trip.
*
* Covered: a proposed hike streams and stores its route card, its line for
* drawing asked for by the server and kept from the model; "Plan this" holds
* the hike as a change card from the stored proposal, refused for an unknown
* proposal and while it waits; applying it runs create_hike without a model
* turn and names the tour in the receipt and on its card.
*/
import { buildApp } from '../../src/bootstrap';
import { HikePlanService } from '../../src/nest/tours/hike-plan.service';
import { makePlace } from '../helpers/factories/places';
import { setAddonEnabled } from '../helpers/factories/settings';
import { makeTrip } from '../helpers/factories/trips';
import { makeUser } from '../helpers/factories/users';
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, HikeProposal, HikeProposeRequest, UiStreamChunk } from '@trek/shared';
import { createServer, type IncomingMessage, type Server as HttpServer, type ServerResponse } from 'node:http';
import type { AddressInfo } from 'node:net';
import request from 'supertest';
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
// ── The fake provider ─────────────────────────────────────────────────────────
interface ChatBody {
messages: Array<{ role: string; content: string | null }>;
tools?: Array<{ function: { name: string; parameters: { properties?: Record<string, unknown> } } }>;
}
type Step = () => { chunks: object[] };
const provider = { requests: [] as ChatBody[], script: [] as Step[] };
const say =
(text: string): Step =>
() => ({
chunks: [
{ choices: [{ index: 0, delta: { content: text } }] },
{ choices: [{ index: 0, delta: {}, finish_reason: 'stop' }] },
{ choices: [], usage: { prompt_tokens: 12, completion_tokens: 4 } },
],
});
const callTool =
(id: string, name: string, args: Record<string, unknown>): Step =>
() => ({
chunks: [
{
choices: [
{
index: 0,
delta: {
tool_calls: [{ index: 0, id, type: 'function', function: { name, arguments: JSON.stringify(args) } }],
},
},
],
},
{ choices: [{ index: 0, delta: {}, finish_reason: 'tool_calls' }] },
],
});
async function readBody(req: IncomingMessage): Promise<string> {
let text = '';
for await (const chunk of req) text += String(chunk);
return text;
}
async function answer(req: IncomingMessage, res: ServerResponse): Promise<void> {
if (req.method === 'GET' && req.url?.startsWith('/api/tags')) {
res.writeHead(200, { 'content-type': 'application/json' });
res.end(JSON.stringify({ models: [{ name: 'fake-model', size: 1 }] }));
return;
}
if (req.method !== 'POST' || req.url !== '/v1/chat/completions') {
res.writeHead(404).end();
return;
}
provider.requests.push(JSON.parse(await readBody(req)) as ChatBody);
const reply = (provider.script.shift() ?? say('Nothing more.'))();
res.writeHead(200, { 'content-type': 'text/event-stream' });
for (const chunk of reply.chunks) res.write(`data: ${JSON.stringify(chunk)}\n\n`);
res.end('data: [DONE]\n\n');
}
// ── The app ──────────────────────────────────────────────────────────────────
let nestApp: INestApplication;
let orm: MikroORM;
let fake: HttpServer;
beforeAll(async () => {
fake = createServer((req, res) => {
answer(req, res).catch(() => res.destroy());
});
await new Promise<void>((resolve) => fake.listen(0, '127.0.0.1', resolve));
nestApp = await buildApp();
orm = nestApp.get(MikroORM);
await setAddonEnabled(orm, 'ai_assistant', true);
await setAddonEnabled(orm, 'tours', true);
const admin = (await makeUser(orm, { role: 'admin' })).user.id;
const { port } = fake.address() as AddressInfo;
const res = await request(nestApp.getHttpServer())
.put('/api/admin/ai/connection')
.set('Cookie', sessionCookie(admin))
.send({ kind: 'custom', baseUrl: `http://127.0.0.1:${port}/v1`, model: 'fake-model' });
expect(res.status).toBe(200);
});
beforeEach(async () => {
await resetRateLimits(nestApp);
provider.requests = [];
provider.script = [];
vi.restoreAllMocks();
});
afterAll(async () => {
await nestApp.close();
await new Promise<void>((resolve) => fake.close(() => resolve()));
});
// ── Helpers ──────────────────────────────────────────────────────────────────
const CTX = { locale: 'en', timeZone: 'Europe/Berlin' };
interface Answer {
status: number;
chunks: UiStreamChunk[];
json: Record<string, unknown> | null;
}
async function post(path: string, userId: number, body: object): Promise<Answer> {
const res = await request(nestApp.getHttpServer())
.post(path)
.set('Cookie', sessionCookie(userId))
.send(body)
.buffer(true)
.parse((stream, done) => {
let text = '';
stream.setEncoding('utf8');
stream.on('data', (chunk: string) => (text += chunk));
stream.on('end', () => done(null, text));
});
const text = res.body as string;
if (!String(res.headers['content-type']).includes('text/event-stream')) {
return { status: res.status, chunks: [], json: text ? (JSON.parse(text) as Record<string, unknown>) : null };
}
const events = text
.split('\n\n')
.filter((event) => event.startsWith('data: '))
.map((event) => event.slice('data: '.length));
expect(events.at(-1)).toBe('[DONE]');
const chunks = events.slice(0, -1).map((event) => JSON.parse(event) as UiStreamChunk);
return { status: res.status, chunks, json: null };
}
const ofType = <T extends UiStreamChunk['type']>(chunks: UiStreamChunk[], type: T) =>
chunks.filter((chunk): chunk is Extract<UiStreamChunk, { type: T }> => chunk.type === type);
const WAYPOINTS = [
{ lat: 47.6, lng: 11.3, name: 'Car park' },
{ lat: 47.61, lng: 11.3, name: 'Summit', poi_category: 'peak' as const },
];
const LINE: HikeProposal['line_geometry'] = [
[47.6, 11.3, 800],
[47.61, 11.3, 880],
];
const PROFILE: HikeProposal['profile_geometry'] = [
[0, 800],
[1112, 880],
];
/** What the planner answers for the hike: a routed way of 1.1 km, its line only when asked for. */
function proposalFor(asked: HikeProposeRequest): HikeProposal {
return {
name: asked.name,
variant_label: null,
route: { planned: true },
unreachable: null,
distance_m: 1112,
ascent_m: 80,
descent_m: 0,
duration_minutes: 22,
duration_basis: 'din33466',
heights_known: true,
min_ele_m: 800,
max_ele_m: 880,
...(asked.include_geometry ? { line_geometry: LINE, profile_geometry: PROFILE } : {}),
sac: { segments: [{ from_m: 0, to_m: 1112, sac: 2 }], highest: 2, unknown_share: 0 },
high_point: { lat: 47.61, lng: 11.3, ele_m: 880, at_m: 1112 },
waypoints: [
{ ...WAYPOINTS[0], poi_category: null, at_m: 0, snapped_m: 2, minutes: 0, arrival: null },
{ ...WAYPOINTS[1], at_m: 1112, snapped_m: 3, minutes: 22, arrival: null },
],
along: null,
max_hiking_difficulty: 2,
hiking_preferences: null,
round_trip: false,
day_id: null,
date: null,
start_time: null,
schedule: null,
warnings: [],
};
}
/** A traveller with a trip, the tour place create_hike will answer with, and the planner stubbed. */
async function travellerWithPlanner() {
const { user } = await makeUser(orm);
const trip = await makeTrip(orm, user.id, { title: 'Bavaria' });
const place = await makePlace(orm, trip.id, { name: 'Herzogstand', category: null });
const hikes = nestApp.get(HikePlanService);
const propose = vi.spyOn(hikes, 'propose').mockImplementation(async (_u, _t, req) => proposalFor(req));
const create = vi.spyOn(hikes, 'create').mockResolvedValue({
tour: { place_id: place.id, name: 'Herzogstand' },
waypoints: [],
route: { planned: true },
assignment: null,
} as unknown as Awaited<ReturnType<HikePlanService['create']>>);
const base = `/api/trips/${trip.id}/assistant`;
return { userId: user.id, tripId: trip.id, placeId: place.id, base, propose, create };
}
/** A turn that loads the tours and proposes the hike. */
async function proposeTurn(t: { userId: number; base: string }) {
provider.script = [
callTool('call_tours', 'use_addon_tools', { groups: ['tours'] }),
callTool('call_hike', 'propose_hike', { name: 'Herzogstand', waypoints: WAYPOINTS }),
say('A short hike up the Herzogstand.'),
];
const turn = await post(`${t.base}/chat`, t.userId, { ...CTX, threadId: null, text: 'A hike up the Herzogstand?' });
return { turn, threadId: ofType(turn.chunks, 'data-trek-thread')[0].data.threadId };
}
// ── Cases ────────────────────────────────────────────────────────────────────
describe('a proposed hike in the chat', () => {
it('ASTE2E-TOUR-001: streams and stores its route card; the line is asked for by the server and kept from the model', async () => {
const t = await travellerWithPlanner();
const { turn, threadId } = await proposeTurn(t);
expect(t.propose).toHaveBeenCalledWith(
t.userId,
t.tripId,
expect.objectContaining({ name: 'Herzogstand', include_geometry: true }),
);
const [card] = ofType(turn.chunks, 'data-trek-card');
expect(card?.data).toMatchObject({
toolCallId: 'call_hike',
card: { kind: 'tourRoute', source: 'proposal', name: 'Herzogstand', routed: true, distanceM: 1112 },
});
// The model never sees the flag nor the line: neither in the tool it is offered nor in the answer it reads.
const last = provider.requests.at(-1);
const offered = last?.tools?.find((tool) => tool.function.name === 'propose_hike');
expect(offered).toBeDefined();
expect(Object.keys(offered?.function.parameters.properties ?? {})).not.toContain('include_geometry');
expect(JSON.stringify(last?.messages)).not.toContain('line_geometry');
const shown = await request(nestApp.getHttpServer())
.get(`${t.base}/threads/${threadId}`)
.set('Cookie', sessionCookie(t.userId));
expect(shown.status).toBe(200);
const parts = (shown.body.messages as Array<{ parts: AssistantMessagePart[] }>).flatMap((m) => m.parts);
expect(parts).toContainEqual(
expect.objectContaining({
type: 'data-trek-card',
data: expect.objectContaining({ toolCallId: 'call_hike' }),
}),
);
});
it('ASTE2E-TOUR-002: "Plan this" holds the hike from the stored proposal; applying it creates the tour without a model turn', async () => {
const t = await travellerWithPlanner();
const { threadId } = await proposeTurn(t);
const path = `${t.base}/threads/${threadId}/proposals`;
const unknown = await post(path, t.userId, { ...CTX, toolCallId: 'call_nope' });
expect(unknown).toMatchObject({ status: 404, json: { code: 'not_found' } });
const taken = await post(path, t.userId, { ...CTX, toolCallId: 'call_hike' });
expect(taken.status).toBe(200);
const parts = (taken.json?.message as { parts: AssistantMessagePart[] }).parts;
const change = parts.find((part) => part.type === 'data-trek-change');
expect(change?.type === 'data-trek-change' && change.data).toMatchObject({
verbKey: 'addTour',
subject: 'Herzogstand',
card: { kind: 'tourRoute', source: 'pending', routed: true },
});
expect(parts).toContainEqual(expect.objectContaining({ type: 'tool-call', toolName: 'take_proposal' }));
const twice = await post(path, t.userId, { ...CTX, toolCallId: 'call_hike' });
expect(twice).toMatchObject({ status: 409, json: { code: 'decide_first' } });
const toolCallId = change?.type === 'data-trek-change' ? change.data.toolCallId : '';
const asked = provider.requests.length;
const decided = await post(`${t.base}/threads/${threadId}/decisions`, t.userId, {
...CTX,
decisions: [{ toolCallId, approved: true }],
});
expect(decided.status).toBe(200);
expect(provider.requests).toHaveLength(asked);
expect(t.create).toHaveBeenCalledWith(
t.userId,
t.tripId,
expect.objectContaining({ name: 'Herzogstand', waypoints: WAYPOINTS }),
);
expect(t.create.mock.calls[0]?.[2]).not.toHaveProperty('via');
const [applied] = ofType(decided.chunks, 'data-trek-applied');
expect(applied?.data).toMatchObject({ toolCallId, entity: 'tour', ids: [t.placeId] });
// The card the change showed stays beside the receipt, now naming the tour it created.
const [receipt] = ofType(decided.chunks, 'data-trek-card');
expect(receipt?.data).toMatchObject({ toolCallId, card: { kind: 'tourRoute', placeId: t.placeId } });
});
});
@@ -0,0 +1,95 @@
import type { TourListCard, TourRouteCard } from '@trek/shared';
/**
* Tour cards as the tours package builds them, valid against the card union,
* for suites that hand a card through the stream, a stored part or a change
* preview and need one the strict write accepts.
*/
/** A short routed hike with every field the kind declares. */
export function tourRouteCard(extra: Partial<TourRouteCard> = {}): TourRouteCard {
return {
kind: 'tourRoute',
source: 'proposal',
activity: 'hike',
placeId: null,
name: 'Ridge walk',
label: null,
distanceM: 1112,
ascentM: 80,
descentM: 0,
minEleM: 800,
maxEleM: 880,
minutes: 22,
minutesBasis: 'din33466',
limit: 2,
grades: null,
routed: true,
problem: null,
line: [
[47.6, 11.3, 800],
[47.605, 11.3, 840],
[47.61, 11.3, 880],
],
stretches: [],
stops: [
{
role: 'start',
kind: null,
name: 'Car park',
lat: 47.6,
lng: 11.3,
atM: 0,
offM: null,
minutes: 0,
clock: null,
stayMinutes: null,
stageEnd: false,
flag: null,
},
{
role: 'end',
kind: 'peak',
name: 'Summit',
lat: 47.61,
lng: 11.3,
atM: 1112,
offM: null,
minutes: 22,
clock: null,
stayMinutes: null,
stageEnd: false,
flag: null,
},
],
stages: null,
skiScheme: null,
schedule: null,
warnings: [],
previous: null,
...extra,
};
}
/** One saved tour of a trip as a list. */
export function tourListCard(extra: Partial<TourListCard> = {}): TourListCard {
return {
kind: 'tourList',
dayId: null,
more: 0,
rows: [
{
placeId: 77,
name: 'Ridge walk',
activity: 'hike',
limit: 2,
distanceM: 1112,
ascentM: 80,
minutes: 22,
stages: null,
days: [2],
},
],
...extra,
};
}
@@ -125,6 +125,32 @@ describe('foundPlacesOf', () => {
expect(JSON.stringify(poi)).not.toMatch(/ramen\.example|opening/);
});
it('ASTCRD-008: the places along a saved tour show as cards; an unnamed tap is left out', () => {
const along = {
pois: [
{ id: 'node:7', name: 'Herzogstandhaus', lat: 47.6, lng: 11.3, category: 'shelter', kind: 'alpine_hut' },
{ id: 'node:8', name: '', lat: 47.61, lng: 11.3, category: 'drinking_water', kind: 'amenity=drinking_water' },
],
truncated: false,
partial: false,
capped: false,
unavailable: [],
};
const found = foundPlacesOf('search_tour_pois', 't', along, card, '2026-06-12');
expect(found?.places.map((place) => place.name)).toEqual(['Herzogstandhaus']);
expect(found?.places[0]).toMatchObject({ ref: 't:0', lat: 47.6, lng: 11.3, googlePlaceId: null });
// The POI's own id is its OpenStreetMap element: a place already in the trip is named, not added twice.
expect(found?.places[0]).toMatchObject({ osmId: 'node:7', inTripPlaceId: null });
const known = { pois: [{ id: 'way:77', name: 'Nishiki', lat: 35.005, lng: 135.764, category: 'shop' }] };
expect(foundPlacesOf('search_tour_pois', 'k', known, card, 'x')?.places[0]).toMatchObject({
osmId: 'way:77',
inTripPlaceId: 14,
});
// An id of another index is no OpenStreetMap id.
const indexed = { pois: [{ id: 'trek:55', name: 'Hut', lat: 47.6, lng: 11.3, category: 'shelter' }] };
expect(foundPlacesOf('search_tour_pois', 'i', indexed, card, 'x')?.places[0]?.osmId).toBeNull();
});
it('ASTCRD-004: at most twenty cards, the rest counted; places without a position or name are left out', () => {
const many = Array.from({ length: 23 }, (_, i) => ({ name: `Place ${i}`, lat: 35 + i / 100, lng: 135 }));
const found = foundPlacesOf('search_place', 'm', { places: [{ name: 'No position' }, ...many] }, card, 'x');
@@ -360,6 +386,15 @@ describe('found place arguments', () => {
expect(writeToolOf('add_found_place', { via: 'create_and_assign_place' })).toBe('create_and_assign_place');
expect(writeToolOf('add_found_place', { via: 'delete_trip' })).toBe('add_found_place');
expect(writeToolOf('create_place', { via: 'assign_place_to_day' })).toBe('create_place');
// A proposal taken from an answer runs as the create its `via` names, and as nothing else.
expect(writeToolOf('take_proposal', { via: 'create_hike' })).toBe('create_hike');
expect(writeToolOf('take_proposal', { via: 'create_city_walk' })).toBe('create_city_walk');
expect(writeToolOf('take_proposal', { via: 'create_and_assign_place' })).toBe('take_proposal');
expect(writeToolOf('add_found_place', { via: 'create_hike' })).toBe('add_found_place');
expect(foundPlaceArgs({ via: 'create_hike', name: 'Herzogstand', waypoints: [] })).toEqual({
name: 'Herzogstand',
waypoints: [],
});
expect(foundPlaceArgs({ via: 'assign_place_to_day', dayId: 3, placeId: 4, name: 'X' })).toEqual({
dayId: 3,
placeId: 4,
@@ -250,6 +250,31 @@ describe('toChatHistory', () => {
},
]);
});
it('ASTHIS-013: a proposal the user took to add is told as a note, a hike or a city walk, whatever became of it', () => {
const taken = (approval: AssistantToolApproval, via = 'create_hike', isError = false) =>
serverStepsNote([
{
type: 'tool-call',
toolCallId: 'p',
toolName: 'take_proposal',
args: { via, name: 'Herzogstand' },
approval,
...(isError ? { isError: true } : {}),
},
]);
expect(taken({ id: 'p' })).toBe(
'The user took the proposed hike "Herzogstand" to add it; it waits for them to add or discard it.',
);
expect(taken({ id: 'p', approved: true })).toBe('The hike "Herzogstand" was added to the trip.');
expect(taken({ id: 'p', approved: true }, 'create_hike', true)).toBe('The hike "Herzogstand" could not be added.');
expect(taken({ id: 'p', approved: false }, 'create_city_walk')).toBe(
'The user discarded the city walk "Herzogstand".',
);
expect(taken({ id: 'p', resolution: 'expired' })).toBe(
'The hike "Herzogstand" was not added; the user moved on without deciding.',
);
});
});
describe('toThreadMessages', () => {
@@ -0,0 +1,305 @@
/**
* "Plan this" on a proposed hike or city walk, over the real thread, message
* and tool call repositories on a migrated test db: the proposal comes from
* the call and card stored in the thread, never from the request, and the
* change that creates it is held as a card in one transaction, refused while
* a turn runs, while another change waits, for a proposal the thread does not
* hold and for one nothing can be created from. A walk is asked again, since
* the stored answer is the model's shortened copy.
*
* 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 {
AssistantProposalsService,
pendingCardOf,
storedProposal,
takeArgsOf,
} from '../../../../src/nest/assistant/assistant-proposals.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 { tourRouteCard } from '../../../helpers/assistant-tour-cards';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { createRow, findRows } from '../../../helpers/factories/rows';
import { makeTrip } from '../../../helpers/factories/trips';
import { makeUser } from '../../../helpers/factories/users';
import { resetTestDb } from '../../../helpers/test-db';
import { createTestModule, type TestModule } from '../../../helpers/test-module';
import { MikroORM } from '@mikro-orm/core';
import { MikroOrmModule } from '@mikro-orm/nestjs';
import type { TourRouteCard } from '@trek/shared';
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
const db = createSnapshotTestDb();
let t: TestModule;
const WALK_RESULT = {
date: '2026-06-12',
frame: { start_time: '10:00', end_time: '14:00' },
can_create: true,
stations: [
{ lat: 48.137, lng: 11.575, name: 'Marienplatz', arrival: '10:00', stay_minutes: 0 },
{ lat: 48.14, lng: 11.58, name: 'Museum', arrival: '10:10', walk_from_previous: { metres: 600, minutes: 10 } },
{ lat: 48.143, lng: 11.58, name: 'Hofgarten', arrival: '11:15', walk_from_previous: { metres: 350, minutes: 5 } },
],
totals: { walk_m: 950, total_minutes: 75, ends_at: '11:15' },
stations_for_create: [
{ lat: 48.137, lng: 11.575, name: 'Marienplatz', stay_minutes: 0 },
{ lat: 48.14, lng: 11.58, name: 'Museum', stay_minutes: 60 },
{ lat: 48.143, lng: 11.58, name: 'Hofgarten', stay_minutes: null },
],
};
/** The walk as the thread stores it: the model's copy, masked and with its lists cut to fit. */
const WALK_STORED = {
...WALK_RESULT,
stations_for_create: [{ lat: 48.137, lng: 11.575, name: '[hidden]', stay_minutes: 0 }],
truncated: true,
};
const WALK_ARGS = { date: '2026-06-12', day_id: 32, start_time: '10:00' };
/** What the trip tools answer: one day, no places, one category; and the walk asked again. */
const reads: Record<string, unknown> = {
get_trip_summary: { trip: { title: 'Bavaria' }, days: [{ id: 32, day_number: 2, date: '2026-06-12' }] },
list_places: { places: [] },
list_categories: { categories: [{ id: 4, name: 'Sights', icon: 'Landmark' }] },
propose_city_walk: WALK_RESULT,
};
const answers = async (name: string, _args?: Record<string, unknown>) => ({ ok: true, value: reads[name] });
const session = {
read: vi.fn(answers),
close: vi.fn(async () => undefined),
};
const tools = { open: vi.fn(async () => session) };
const rateLimit = { check: vi.fn(async () => true) };
const streams = { claim: vi.fn(async () => true), release: vi.fn(async () => undefined) };
beforeAll(async () => {
t = await createTestModule({
db,
imports: [MikroOrmModule.forFeature([AssistantThreads, AssistantMessages, AssistantToolCalls])],
providers: [
AssistantProposalsService,
AssistantCardContext,
{ provide: AirportsService, useValue: { findByIata: () => null } },
{ provide: AssistantToolsService, useValue: tools },
{ provide: RateLimitService, useValue: rateLimit },
{ provide: AssistantStreamRegistry, useValue: streams },
],
});
});
beforeEach(() => {
resetTestDb(db);
vi.clearAllMocks();
});
afterAll(async () => {
await t.close();
db.close();
});
const HIKE_ARGS = {
name: 'Herzogstand',
waypoints: [
{ lat: 47.6, lng: 11.3, name: 'Car park' },
{ lat: 47.61, lng: 11.3, name: 'Summit', poi_category: 'peak' },
],
max_hiking_difficulty: 3,
variant_label: 'the short one',
along: false,
day_id: 32,
start_time: '08:00',
};
/** A thread whose answer proposed a hike (`h1`) and a city walk (`w1`), each with its card, and searched (`s1`). */
async function conversation(hikeCard: TourRouteCard = tourRouteCard()) {
const orm = t.get(MikroORM);
const { user } = await makeUser(orm);
const trip = await makeTrip(orm, user.id);
const thread = await createRow(orm, AssistantThreads, { user: user.id, trip: trip.id, title: 'Hikes' });
const walkCard = tourRouteCard({ activity: 'walk', name: null, minutesBasis: 'stations' });
const parts = JSON.stringify([
{ type: 'tool-call', toolCallId: 'h1', toolName: 'propose_hike', args: HIKE_ARGS, result: { name: 'Herzogstand' } },
{ type: 'data-trek-card', data: { toolCallId: 'h1', card: hikeCard } },
{ type: 'tool-call', toolCallId: 'w1', toolName: 'propose_city_walk', args: WALK_ARGS, result: WALK_STORED },
{ type: 'data-trek-card', data: { toolCallId: 'w1', card: walkCard } },
{ type: 'tool-call', toolCallId: 's1', toolName: 'search_place', args: { query: 'huts' }, result: {} },
]);
await createRow(orm, AssistantMessages, { thread: thread.id, role: 'assistant', parts, status: 'complete' });
return { userId: user.id, tripId: trip.id, threadId: thread.id };
}
function take(c: { userId: number; tripId: number; threadId: number }, toolCallId: string, threadId = c.threadId) {
return t
.get(AssistantProposalsService)
.take(c.userId, c.tripId, threadId, { toolCallId, locale: 'en', timeZone: 'UTC' });
}
function calls(threadId: number) {
return findRows(t.get(MikroORM), AssistantToolCalls, { thread_id: threadId });
}
describe('AssistantProposalsService', () => {
it('ASTPROP-001: a proposed hike is held as create_hike with its own arguments and the card the answer showed', async () => {
const c = await conversation();
const transactional = vi.spyOn(t.get(UnitOfWork), 'transactional');
const { message } = await take(c, 'h1');
expect(transactional).toHaveBeenCalledOnce();
const [call] = await calls(c.threadId);
expect(call).toMatchObject({ tool_name: 'take_proposal', state: 'approval_requested' });
expect(JSON.parse(call?.args ?? '{}')).toEqual({
via: 'create_hike',
name: 'Herzogstand',
waypoints: HIKE_ARGS.waypoints,
max_hiking_difficulty: 3,
day_id: 32,
start_time: '08:00',
});
const preview = JSON.parse(call?.preview ?? '{}') as Record<string, unknown>;
expect(preview).toMatchObject({ verbKey: 'addTour', subject: 'Herzogstand', dayId: 32, undoable: true });
// The card the answer showed, waiting, under the name the change saves.
expect(preview.card).toEqual({ ...tourRouteCard(), source: 'pending', name: 'Herzogstand' });
expect(message.parts).toContainEqual(
expect.objectContaining({ type: 'tool-call', toolCallId: call?.id, toolName: 'take_proposal' }),
);
expect(streams.release).toHaveBeenCalledOnce();
expect(session.close).toHaveBeenCalledOnce();
});
it('ASTPROP-002: a proposed city walk is held as create_city_walk with the stations it answered, named by its ends', async () => {
const c = await conversation();
await take(c, 'w1');
expect(session.read).toHaveBeenCalledWith('propose_city_walk', WALK_ARGS);
const [call] = await calls(c.threadId);
expect(JSON.parse(call?.args ?? '{}')).toEqual({
via: 'create_city_walk',
name: 'Marienplatz → Hofgarten',
stations: WALK_RESULT.stations_for_create,
});
const preview = JSON.parse(call?.preview ?? '{}') as Record<string, unknown>;
expect(preview).toMatchObject({ verbKey: 'addTour', subject: 'Marienplatz → Hofgarten' });
});
it('ASTPROP-003: a call the thread does not hold, or one that proposed nothing, is not found', async () => {
const c = await conversation();
const notFound = { status: 404, code: 'not_found' };
await expect(take(c, 'nope')).rejects.toMatchObject(notFound);
await expect(take(c, 's1')).rejects.toMatchObject(notFound);
await expect(take(c, 'h1', c.threadId + 1000)).rejects.toMatchObject(notFound);
expect(await calls(c.threadId)).toHaveLength(0);
});
it('ASTPROP-004: a hike whose way was not planned cannot be taken; nothing is held', async () => {
const problem = { why: 'no_way' as const, position: null, snappedM: null };
const c = await conversation(tourRouteCard({ routed: false, problem }));
await expect(take(c, 'h1')).rejects.toMatchObject({ status: 400, code: 'generic' });
expect(await calls(c.threadId)).toHaveLength(0);
expect(streams.release).toHaveBeenCalledOnce();
});
it('ASTPROP-005: refused while another change waits, while a turn runs, and past the per-minute limit', async () => {
const c = await conversation();
await take(c, 'h1');
await expect(take(c, 'w1')).rejects.toMatchObject({ status: 409, code: 'decide_first' });
streams.claim.mockResolvedValueOnce(false);
await expect(take(c, 'w1')).rejects.toMatchObject({ status: 409, code: 'busy' });
rateLimit.check.mockResolvedValueOnce(false);
await expect(take(c, 'w1')).rejects.toMatchObject({ status: 429, code: 'too_many_requests' });
expect(await calls(c.threadId)).toHaveLength(1);
});
});
it('ASTPROP-008: a walk stored cut down and masked is created from the tool asked again, named and on no day', async () => {
const c = await conversation();
await take(c, 'w1');
const [call] = await calls(c.threadId);
const args = JSON.parse(call?.args ?? '{}') as Record<string, unknown>;
// Never the stored copy: all three stations, none of them masked.
expect(args.stations).toEqual(WALK_RESULT.stations_for_create);
expect(JSON.stringify(args)).not.toContain('[hidden]');
const card = (JSON.parse(call?.preview ?? '{}') as { card: TourRouteCard }).card;
expect(card).toMatchObject({ source: 'pending', activity: 'walk', name: 'Marienplatz → Hofgarten' });
expect(card.stops.map((stop) => stop.name)).toEqual(['Marienplatz', 'Museum', 'Hofgarten']);
// create_city_walk puts the walk on no day, so the card names none.
expect(card.schedule).toMatchObject({ date: '2026-06-12', dayId: null, dayNumber: null });
});
it('ASTPROP-009: a walk the tool cannot answer now cannot be taken; nothing is held', async () => {
const c = await conversation();
session.read.mockImplementation(async (name: string) =>
name === 'propose_city_walk' ? { ok: false, value: 'Tours are off' } : { ok: true, value: reads[name] },
);
try {
await expect(take(c, 'w1')).rejects.toMatchObject({ status: 400, code: 'generic' });
} finally {
session.read.mockImplementation(answers);
}
expect(await calls(c.threadId)).toHaveLength(0);
expect(session.close).toHaveBeenCalledOnce();
});
});
describe('what a proposal can be taken as', () => {
const card = tourRouteCard();
it('ASTPROP-006: a walk without stations to create, or one its answer says cannot be, gives nothing', () => {
const walk = { toolName: 'propose_city_walk', args: {}, card };
expect(takeArgsOf({ ...walk, result: { ...WALK_RESULT, can_create: false } })).toBeNull();
expect(takeArgsOf({ ...walk, result: { stations_for_create: [WALK_RESULT.stations_for_create[0]] } })).toBeNull();
// Stations without names are named by the day and the start.
const nameless = WALK_RESULT.stations_for_create.map(({ name: _name, ...station }) => station);
expect(takeArgsOf({ ...walk, result: { ...WALK_RESULT, stations_for_create: nameless } })).toMatchObject({
name: '2026-06-12 10:00',
});
});
it('ASTPROP-010: a hike asked by date alone is created on no day, and its waiting card names none', () => {
const schedule = {
date: '2026-06-12',
dayId: 32,
dayNumber: 2,
start: '08:00',
arrive: '08:22',
nextDay: false,
sunrise: null,
sunset: null,
latestStart: null,
weather: null,
hours: [],
};
const { day_id: _day, ...undated } = HIKE_ARGS;
const args = takeArgsOf({ toolName: 'propose_hike', args: { ...undated, date: '2026-06-12' }, result: {}, card });
expect(args).not.toHaveProperty('day_id');
expect(args).not.toHaveProperty('date');
const waiting = pendingCardOf(tourRouteCard({ label: 'the short one', schedule }), args ?? {});
expect(waiting).toMatchObject({ source: 'pending', name: 'Herzogstand', label: null });
expect(waiting.schedule).toEqual({ ...schedule, dayId: null, dayNumber: null });
// On the day the change puts it on, the day stays.
expect(pendingCardOf(tourRouteCard({ schedule }), { day_id: 32 }).schedule).toEqual(schedule);
});
it('ASTPROP-007: the newest row holding the call wins; a card of another kind is no proposal', () => {
const row = (id: number, card: unknown) => ({
id,
parts: JSON.stringify([
{ type: 'tool-call', toolCallId: 'h1', toolName: 'propose_hike', args: { name: `Hike ${id}` } },
{ type: 'data-trek-card', data: { toolCallId: 'h1', card } },
]),
});
const rows = [row(1, card), row(2, { ...card, name: 'Newer' })] as unknown as Parameters<typeof storedProposal>[0];
expect(storedProposal(rows, 'h1')).toMatchObject({ toolName: 'propose_hike', args: { name: 'Hike 2' } });
const list = [row(3, { kind: 'tourList', dayId: null, more: 0, rows: [] })] as unknown as typeof rows;
expect(storedProposal(list, 'h1')).toBeNull();
});
});
@@ -8,6 +8,7 @@ import 'reflect-metadata';
import { AddonGuard } from '../../../../src/nest/addons/addon.guard';
import { REQUIRE_ADDON } from '../../../../src/nest/addons/require-addon.decorator';
import type { AssistantFoundPlacesService } from '../../../../src/nest/assistant/assistant-found-places.service';
import type { AssistantProposalsService } from '../../../../src/nest/assistant/assistant-proposals.service';
import type { AssistantShareService } from '../../../../src/nest/assistant/assistant-share.service';
import { AssistantController } from '../../../../src/nest/assistant/assistant.controller';
import type { AssistantService, TurnChannel } from '../../../../src/nest/assistant/assistant.service';
@@ -38,12 +39,14 @@ function make() {
};
const foundPlaces = { add: vi.fn(async () => ({ message: { id: 'msg-3' } })) };
const shares = { share: vi.fn(async () => ({ message: { id: 12, origin: 'assistant' } })) };
const proposals = { take: vi.fn(async () => ({ message: { id: 'msg-4' } })) };
const controller = new AssistantController(
service as unknown as AssistantService,
foundPlaces as unknown as AssistantFoundPlacesService,
shares as unknown as AssistantShareService,
proposals as unknown as AssistantProposalsService,
);
return { service, foundPlaces, shares, controller };
return { service, foundPlaces, shares, proposals, controller };
}
/** Enough of an Express response for the stream: headers, writes and the close event. */
@@ -106,6 +109,11 @@ describe('AssistantController', () => {
path: 'threads/:threadId/found-places',
httpCode: 200,
});
expect(route('takeProposal')).toEqual({
method: RequestMethod.POST,
path: 'threads/:threadId/proposals',
httpCode: 200,
});
expect(route('share')).toEqual({
method: RequestMethod.POST,
path: 'threads/:threadId/messages/:messageId/share',
@@ -142,11 +150,19 @@ describe('AssistantController', () => {
it('ASTCTL-008: sharing needs the right to write in the trip chat; nothing else here asks for a right', () => {
const handlers = AssistantController.prototype as unknown as Record<string, object>;
expect(Reflect.getMetadata(TRIP_PERMISSION_KEY, handlers.share)).toBe('collab_edit');
for (const name of ['chat', 'decide', 'undo', 'addFoundPlace']) {
for (const name of ['chat', 'decide', 'undo', 'addFoundPlace', 'takeProposal']) {
expect(Reflect.getMetadata(TRIP_PERMISSION_KEY, handlers[name]), name).toBeUndefined();
}
});
it('ASTCTL-009: "Plan this" goes to the proposals with the caller, the trip and the thread', async () => {
const { proposals, controller } = make();
const body = { locale: 'en', timeZone: 'UTC', toolCallId: 'call_7' };
expect(await controller.takeProposal(user, '5', '9', body)).toEqual({ message: { id: 'msg-4' } });
expect(proposals.take).toHaveBeenCalledWith(7, 5, 9, body);
expect(() => controller.takeProposal(user, '5', '0', body)).toThrow(DomainError);
});
it('ASTCTL-004: a thread id that is not one answers 404', () => {
const { controller } = make();
for (const bad of ['0', '-3', 'abc', '1.5']) {
@@ -0,0 +1,367 @@
/**
* ASTCARD-TOUR-030 to ASTCARD-TOUR-043
*
* The tours inside the change cards: what a held create_hike, create_city_walk
* and update_tour look up (through a fake reader, as the turn's memo hands
* it) and the card each shows, the day a hike lands on, the words of the
* writes, the way back from a tour taken over or imported, and what the
* package sets for the model: the planning tools always asked for their line,
* a saved tour's line in brief kept from the provider, its prompt lines.
*/
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 { systemPrompt } from '../../../../../../src/nest/assistant/assistant.prompt';
import { loadFor } from '../../../../../../src/nest/assistant/cards/card-context';
import type { PreviewContext } from '../../../../../../src/nest/assistant/cards/card-types';
import {
appliedCardOf,
ASSISTANT_ARG_POLICY,
ASSISTANT_UNDO_MAP,
ASSISTANT_WRITE_TOOLS,
CARD_PROMPT_LINES,
PROJECTIONS,
} from '../../../../../../src/nest/assistant/cards/registry';
import { planArgsOf, replans } from '../../../../../../src/nest/assistant/cards/tour/tour-change.cards';
import { describeToolCall } from '../../../../../../src/nest/assistant/tool-call-preview.helpers';
import { assistantChangePreviewSchema, trekCardSchema, type TourRouteCard } 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());
const card = buildTripCard(
1,
7,
{
trip: { title: 'Bavaria' },
days: [
{ id: 31, day_number: 1, date: '2026-06-11', assignments: [] },
{ id: 32, day_number: 2, date: '2026-06-12', title: 'Mountains', assignments: [] },
],
},
{ places: [{ id: 61, name: 'Hut walk', lat: 47.6, lng: 11.3 }] },
null,
);
const ctx: PreviewContext = { card, categories: new Map(), locale: 'en-GB', today: '2026-06-01', airport: () => null };
const POINTS = [
{ lat: 47.6, lng: 11.3, name: 'Car park' },
{ lat: 47.61, lng: 11.3, name: 'Summit', poi_category: 'peak' },
];
const CREATE = {
name: 'Herzogstand',
description: 'Up from the car park',
waypoints: POINTS,
max_hiking_difficulty: 3,
planned_duration_minutes: 300,
day_id: 32,
start_time: '08:00',
};
/** What propose_hike answers for the two points: a routed way of 1.1 km. */
const PROPOSAL = {
name: 'Herzogstand',
variant_label: 'the short one',
route: { planned: true },
distance_m: 1112,
ascent_m: 80,
descent_m: 0,
duration_minutes: 22,
duration_basis: 'din33466',
min_ele_m: 800,
max_ele_m: 880,
line_geometry: [
[47.6, 11.3, 800],
[47.61, 11.3, 880],
],
sac: { segments: [], highest: 2, unknown_share: 0 },
high_point: null,
waypoints: [
{ ...POINTS[0], poi_category: null, at_m: 0, minutes: 0, arrival: '08:00' },
{ ...POINTS[1], at_m: 1112, minutes: 22, arrival: '08:22' },
],
along: null,
max_hiking_difficulty: 3,
schedule: null,
warnings: [],
};
/** What get_tour_plan answers for the saved hike 61: limit T3, steps avoided, a line in brief. */
const SAVED = {
tour: {
place_id: 61,
name: 'Hut walk',
tour_type: 'hike',
distance: 2.5,
elevation_gain: 300,
duration: 75,
max_hiking_difficulty: 3,
hiking_preferences: { avoid_steps: true },
},
waypoints: [
{ lat: 47.6, lng: 11.3, role: 'start' },
{ lat: 47.62, lng: 11.31, role: 'end' },
],
line: {
point_count: 400,
has_heights: true,
preview: [
[47.6, 11.3, 800],
[47.61, 11.305, 950],
[47.62, 11.31, 1100],
],
},
};
/** A reader that answers each tool from `answers` and records what it was asked. */
function reader(answers: Record<string, unknown>) {
return vi.fn(async (tool: string, _args?: Record<string, unknown>) => answers[tool] ?? null);
}
function route(preview: { card?: unknown }): TourRouteCard {
const shown = preview.card as TourRouteCard | undefined;
if (shown?.kind !== 'tourRoute') throw new Error('no route card');
expect(trekCardSchema.safeParse(shown).success).toBe(true);
return shown;
}
describe('a held new hike', () => {
it('ASTCARD-TOUR-030: reads the proposal of the same points and shows its way, named as the change names it', async () => {
const read = reader({ propose_hike: PROPOSAL });
const loaded = await loadFor('create_hike', CREATE, read);
expect(read).toHaveBeenCalledWith('propose_hike', {
along: false,
name: 'Herzogstand',
waypoints: POINTS,
max_hiking_difficulty: 3,
day_id: 32,
start_time: '08:00',
});
const preview = describeToolCall('create_hike', 'tc-1', CREATE, ctx, loaded);
expect(assistantChangePreviewSchema.safeParse(preview).success).toBe(true);
expect(preview).toMatchObject({ verbKey: 'addTour', subject: 'Herzogstand', dayId: 32, undoable: true });
const day = 'Fri 12 Jun, Mountains, 08:00';
expect(preview.rows).toContainEqual({ op: 'add', labelKey: 'day', before: null, after: day });
expect(preview.effect).toEqual({
kind: 'add',
dayId: 32,
fromDayId: null,
placeId: null,
assignmentId: null,
place: { name: 'Herzogstand', lat: 47.6, lng: 11.3, categoryId: null },
});
expect(route(preview)).toMatchObject({
source: 'pending',
name: 'Herzogstand',
label: null,
routed: true,
distanceM: 1112,
});
});
it('ASTCARD-TOUR-031: without a plan the points are drawn straight, planned once the hike is added', async () => {
const failed = await loadFor('create_hike', { ...CREATE, round_trip: true }, reader({}));
const straight = route(describeToolCall('create_hike', 'tc-2', { ...CREATE, round_trip: true }, ctx, failed));
expect(straight).toMatchObject({ routed: false, problem: { why: 'not_planned' }, limit: 3 });
// A round trip is drawn back to its start.
expect(straight.stops.map((stop) => stop.role)).toEqual(['start', 'via', 'end']);
// The planner's own refusal is shown as it is; a router that did not answer saves the points, planned later.
const refused = { plan: { route: { planned: false, why: 'no_way', position: null } }, saved: null };
expect(route(describeToolCall('create_hike', 'tc-3', CREATE, ctx, refused)).problem?.why).toBe('no_way');
const down = { plan: { route: { planned: false, why: 'router_unavailable', position: null } }, saved: null };
expect(route(describeToolCall('create_hike', 'tc-4', CREATE, ctx, down)).problem?.why).toBe('not_planned');
// Too few points draw nothing; the words still stand.
expect(describeToolCall('create_hike', 'tc-5', { name: 'Odd' }, ctx, null)).not.toHaveProperty('card');
});
it('ASTCARD-TOUR-032: the plan it reads leaves out what the change card does not show', () => {
expect(planArgsOf({ ...CREATE, round_trip: true, hiking_preferences: null })).toEqual({
along: false,
name: 'Herzogstand',
waypoints: POINTS,
max_hiking_difficulty: 3,
hiking_preferences: null,
round_trip: true,
day_id: 32,
start_time: '08:00',
});
});
it('ASTCARD-TOUR-033: lands on its day at its first point; without a day of this trip it touches no day', () => {
const { day_id: _day, ...free } = CREATE;
expect(describeToolCall('create_hike', 'tc-6', free, ctx, null).effect).toBeNull();
expect(describeToolCall('create_hike', 'tc-7', { ...CREATE, day_id: 99 }, ctx, null)).toMatchObject({
effect: null,
dayId: null,
});
const nameless = describeToolCall('create_hike', 'tc-8', { ...CREATE, name: ' ' }, ctx, null);
expect(nameless.effect).toMatchObject({ kind: 'add', dayId: 32, place: null });
});
});
describe('an applied new tour', () => {
it('ASTCARD-TOUR-042: keeps the card the change showed, now naming the tour it created', async () => {
const loaded = await loadFor('create_hike', CREATE, reader({ propose_hike: PROPOSAL }));
const preview = describeToolCall('create_hike', 'tc-14', CREATE, ctx, loaded);
const created = { tour: { place_id: 64, name: 'Herzogstand' }, assignment: { id: 305, day_id: 32 } };
const applied = appliedCardOf('create_hike', { args: CREATE, result: created, preview });
expect(applied).toEqual({ ...route(preview), placeId: 64 });
expect(appliedCardOf('create_city_walk', { args: {}, result: created, preview: null })).toBeNull();
expect(appliedCardOf('create_hike', { args: CREATE, result: 'Tour not found.', preview })).toBeNull();
});
it('ASTCARD-TOUR-043: an applied change of a saved hike keeps its new way beside the receipt', async () => {
const moved = { placeId: 61, expected_revision: 2, waypoints: POINTS };
const loaded = await loadFor('update_tour', moved, reader({ get_tour_plan: SAVED, propose_hike: PROPOSAL }));
const preview = describeToolCall('update_tour', 'tc-15', moved, ctx, loaded);
const saved = { ...SAVED, tour: { ...SAVED.tour, revision: 3 }, replanned: true, route: { planned: true } };
const applied = appliedCardOf('update_tour', { args: moved, result: saved, preview });
expect(applied).toEqual({ ...route(preview), placeId: 61 });
expect(applied).toMatchObject({ routed: true, previous: { distanceM: 2500 } });
expect(appliedCardOf('update_tour', { args: moved, result: 'Tour not found.', preview })).toBeNull();
});
});
describe('a held new city walk', () => {
it('ASTCARD-TOUR-034: shows its stations straight with their stays; the way on foot is planned on save', async () => {
const args = {
name: 'Old town',
stations: [
{ lat: 48.137, lng: 11.575, name: 'Marienplatz', stay_minutes: 0 },
{ lat: 48.14, lng: 11.58, name: 'Museum', stay_minutes: 60 },
],
};
expect(await loadFor('create_city_walk', args, reader({}))).toBeNull();
const shown = route(describeToolCall('create_city_walk', 'tc-9', args, ctx, null));
expect(shown).toMatchObject({ activity: 'walk', name: 'Old town', routed: false, problem: { why: 'not_planned' } });
expect(shown.stops.map((stop) => [stop.kind, stop.name, stop.stayMinutes])).toEqual([
['station', 'Marienplatz', 0],
['station', 'Museum', 60],
]);
});
});
describe('a held change of a saved hike', () => {
const MOVED = { placeId: 61, expected_revision: 2, waypoints: POINTS };
it('ASTCARD-TOUR-035: plans the new way under the saved limit and preferences and shows the old way beside it', async () => {
const read = reader({ get_tour_plan: SAVED, propose_hike: PROPOSAL });
const loaded = await loadFor('update_tour', MOVED, read);
expect(read).toHaveBeenNthCalledWith(1, 'get_tour_plan', { placeId: 61 });
expect(read).toHaveBeenNthCalledWith(2, 'propose_hike', {
name: 'Hut walk',
waypoints: POINTS,
max_hiking_difficulty: 3,
hiking_preferences: { avoid_steps: true },
along: false,
});
const shown = route(describeToolCall('update_tour', 'tc-10', MOVED, ctx, loaded));
expect(shown).toMatchObject({ source: 'pending', placeId: 61, name: 'Hut walk', routed: true, distanceM: 1112 });
expect(shown.previous).toEqual({
line: [
[47.6, 11.3],
[47.61, 11.305],
[47.62, 11.31],
],
distanceM: 2500,
ascentM: 300,
minutes: 75,
});
});
it('ASTCARD-TOUR-036: a new limit alone replans through the saved points; a new name alone draws nothing', async () => {
const read = reader({ get_tour_plan: SAVED, propose_hike: PROPOSAL });
await loadFor('update_tour', { placeId: 61, expected_revision: 2, max_hiking_difficulty: 4 }, read);
expect(read).toHaveBeenLastCalledWith('propose_hike', {
name: 'Hut walk',
waypoints: [
{ lat: 47.6, lng: 11.3 },
{ lat: 47.62, lng: 11.31 },
],
max_hiking_difficulty: 4,
hiking_preferences: { avoid_steps: true },
along: false,
});
const renamed = { placeId: 61, expected_revision: 2, name: 'Ridge' };
const named = reader({ get_tour_plan: SAVED });
const loaded = await loadFor('update_tour', renamed, named);
expect(named).toHaveBeenCalledTimes(1);
expect(describeToolCall('update_tour', 'tc-11', renamed, ctx, loaded)).not.toHaveProperty('card');
expect(await loadFor('update_tour', { name: 'No id' }, named)).toBeNull();
});
it('ASTCARD-TOUR-037: replans as update_tour decides, and draws a way it could not plan straight', () => {
expect(replans({ max_hiking_difficulty: 3 }, SAVED)).toBe(false);
expect(replans({ hiking_preferences: { avoid_steps: true, avoid_climbs: false } }, SAVED)).toBe(false);
expect(replans({ hiking_preferences: null }, SAVED)).toBe(true);
expect(replans({}, { ...SAVED, line: null })).toBe(true);
expect(replans({ waypoints: POINTS }, SAVED)).toBe(true);
const unplanned = { plan: null, saved: SAVED };
const moved = { placeId: 61, waypoints: POINTS };
const shown = route(describeToolCall('update_tour', 'tc-12', moved, ctx, unplanned));
expect(shown).toMatchObject({ routed: false, problem: { why: 'not_planned' }, placeId: 61 });
expect(shown.previous?.distanceM).toBe(2500);
});
});
describe('the words and the way back of the other tour writes', () => {
it('ASTCARD-TOUR-038: a tour taken over is a new tour, named as the copy is named, and taken back with its place', () => {
const copy = { source_trip_id: 4, source_place_id: 9, name: 'Copy' };
const preview = describeToolCall('take_over_tour', 'tc-13', copy, ctx);
expect(preview).toMatchObject({ verbKey: 'addTour', subject: 'Copy', undoable: true });
expect(ASSISTANT_WRITE_TOOLS.take_over_tour).toEqual({ verbKey: 'addTour', entity: 'tour' });
expect(ASSISTANT_UNDO_MAP.take_over_tour.args({}, { tour: { place_id: 70 } }, null)).toEqual({ placeId: 70 });
});
it('ASTCARD-TOUR-039: tours from a file are taken back only when the file brought in one', () => {
const one = { tours: [{ place_id: 71, name: 'Ridge', description: null }], caution: false, skipped: 0 };
const two = { tours: [{ place_id: 71 }, { place_id: 72 }], caution: false, skipped: 0 };
expect(ASSISTANT_UNDO_MAP.import_tour_gpx.args({}, one, null)).toEqual({ placeId: 71 });
expect(ASSISTANT_UNDO_MAP.import_tour_gpx.args({}, two, null)).toBeNull();
const made = '2026-10-21 10:00:00';
const place = { id: 71, name: 'Ridge', description: null, created_at: made, updated_at: made };
const snapshot = { places: { places: [place] }, summary: { days: [] } };
expect(unchangedSinceApplied('import_tour_gpx', one, snapshot)).toBe(true);
expect(unchangedSinceApplied('import_tour_gpx', two, snapshot)).toBe(false);
const renamed = { places: { places: [{ ...place, name: 'Other' }] }, summary: { days: [] } };
expect(unchangedSinceApplied('import_tour_gpx', one, renamed)).toBe(false);
});
it('ASTCARD-TOUR-040: a hike created on a day is taken back with its own visit, not once planned elsewhere', () => {
const made = '2026-10-21 10:00:00';
const hike = { id: 64, name: 'Herzogstand', description: null, created_at: made, updated_at: made };
const created = { tour: { place_id: 64, name: 'Herzogstand' }, assignment: { id: 305, day_id: 32 } };
const onItsDay = {
places: { places: [hike] },
summary: { days: [{ id: 32, assignments: [{ id: 305, place_id: 64 }] }] },
};
expect(unchangedSinceApplied('create_hike', created, onItsDay)).toBe(true);
const twice = {
places: { places: [hike] },
summary: { days: [{ id: 31, assignments: [{ id: 306, place_id: 64 }, { id: 305, place_id: 64 }] }] },
};
expect(unchangedSinceApplied('create_hike', created, twice)).toBe(false);
// A new way saved since (any route write stamps updated_at) keeps the tour, name and day unchanged or not.
const rerouted = { ...onItsDay, places: { places: [{ ...hike, updated_at: '2026-10-21 10:05:00' }] } };
expect(unchangedSinceApplied('create_hike', created, rerouted)).toBe(false);
});
});
describe('what the tours set for the model', () => {
it('ASTCARD-TOUR-041: the planning tools draw their line, a saved line stays with the card, the prompt says so', () => {
for (const tool of ['propose_hike', 'propose_city_walk', 'plan_paddle_route', 'plan_ski_route']) {
expect(ASSISTANT_ARG_POLICY[tool]?.forced, tool).toEqual({ include_geometry: true });
}
const brief = PROJECTIONS.get_tour_plan?.(SAVED) as { line: Record<string, unknown> };
expect(brief.line).toEqual({ point_count: 400, has_heights: true });
expect(PROJECTIONS.get_tour_plan?.({ tour: {}, line: null })).toEqual({ tour: {}, line: null });
expect(JSON.stringify(toolOutputForProvider('get_tour_plan', SAVED))).not.toContain('preview');
const hikes = CARD_PROMPT_LINES.filter((line) => line.includes('propose_hike'));
expect(hikes.some((line) => line.includes('variant_label'))).toBe(true);
for (const line of CARD_PROMPT_LINES) expect(systemPrompt('English')).toContain(line);
});
});
@@ -0,0 +1,456 @@
/**
* ASTCARD-TOUR-001 to ASTCARD-TOUR-013
*
* The cards of a proposed hike and of a saved tour, built from the tool's raw
* answer through the registry's guarded call, so every card asserted here
* also fits the shared card union and the size cap: the way with its figures,
* the SAC stretches merged, the points, the places along it and the highest
* point in the order walked, the day with its weather, a way that was not
* planned drawn straight, and a saved tour's points placed along its line.
*/
import { buildTripCard } from '../../../../../../src/nest/assistant/assistant-context';
import type { AnswerInput } from '../../../../../../src/nest/assistant/cards/card-types';
import { answerCardOf } from '../../../../../../src/nest/assistant/cards/registry';
import { fitted, hardestStretches } from '../../../../../../src/nest/assistant/cards/tour/tour-card-values';
import { sacStretches } from '../../../../../../src/nest/assistant/cards/tour/tour-route.cards';
import {
MAX_CARD_CHARS,
trekCardSchema,
type TourRouteCard,
type TourRouteStretch,
type 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());
const card = buildTripCard(
1,
7,
{
trip: { title: 'Bavaria' },
days: [
{ id: 31, day_number: 1, date: '2026-06-11', assignments: [] },
{ id: 32, day_number: 2, date: '2026-06-12', assignments: [] },
],
},
{ places: [] },
null,
);
/** A point `k` steps of 0.005° north of 47.6° N, about 556 m a step, 40 m higher each. */
const at = (k: number, height: number | null = 800 + 40 * k) => [47.6 + k * 0.005, 11.3, height];
/** What propose_hike answers for a short hike up to a summit on day 2 at eight. */
function proposal(extra: Record<string, unknown> = {}) {
return {
name: 'Herzogstand',
variant_label: 'short and steep',
route: { planned: true },
unreachable: null,
distance_m: 1112,
ascent_m: 80,
descent_m: 0,
duration_minutes: 22,
duration_basis: 'din33466',
heights_known: true,
min_ele_m: 800,
max_ele_m: 880,
line_geometry: [at(0, 800.4), at(1), at(2)],
profile_geometry: [
[0, 800],
[1112, 880],
],
sac: {
segments: [
{ from_m: 0, to_m: 300, sac: 2 },
{ from_m: 300, to_m: 600, sac: 2 },
{ from_m: 600, to_m: 1112, sac: 3 },
],
highest: 3,
unknown_share: 0.25,
},
high_point: { lat: 47.61, lng: 11.3, ele_m: 880, at_m: 1112 },
waypoints: [
{
lat: 47.6,
lng: 11.3,
name: 'Car park',
poi_category: null,
at_m: 0,
snapped_m: 3,
minutes: 0,
arrival: '08:00',
},
{
lat: 47.61,
lng: 11.3,
name: 'Summit of desk@peak.test',
poi_category: 'peak',
at_m: 1112,
snapped_m: 2,
minutes: 22,
arrival: '08:22',
},
],
along: [
{ name: 'Spring', category: 'drinking_water', lat: 47.603, lng: 11.301, at_m: 400, off_m: 80 },
{ name: 'View', category: 'viewpoint', lat: 47.607, lng: 11.299, at_m: 800, off_m: 3000 },
],
max_hiking_difficulty: 3,
hiking_preferences: null,
round_trip: false,
day_id: 32,
date: '2026-06-12',
start_time: '08:00',
schedule: {
date: '2026-06-12',
day_id: 32,
start: '08:00',
arrive: '08:22',
next_day: false,
sunrise: '05:10',
sunset: '21:15',
latest_start: null,
weather: 'forecast',
hours: [
{ hour: 7, main: 'Clear', temp_c: 12, rain_pct: null, wind_kmh: 8 },
{ hour: 8, main: 'Thunderstorm', temp_c: 14, rain_pct: 70, wind_kmh: 20 },
{ hour: 9, main: '', temp_c: 14, rain_pct: 10, wind_kmh: 5 },
],
},
warnings: [
{ kind: 'thunder', at: '08:00' },
{ kind: 'locusts', at: null },
],
...extra,
};
}
const ARGS = {
name: 'Herzogstand',
waypoints: [
{ lat: 47.6, lng: 11.3, name: 'Car park' },
{ lat: 47.61, lng: 11.3, name: 'Summit', poi_category: 'peak' },
],
};
function input(tool: string, value: unknown, args: Record<string, unknown> = ARGS): [string, AnswerInput] {
return [tool, { toolCallId: 'call_1', args, value, card, today: '2026-06-01' }];
}
function route(built: TrekCard | null): TourRouteCard {
if (built?.kind !== 'tourRoute') throw new Error(`no route card: ${JSON.stringify(built)}`);
expect(trekCardSchema.safeParse(built).success).toBe(true);
return built;
}
describe('the card of a proposed hike', () => {
it('ASTCARD-TOUR-001: shows the way with its figures, grades, merged stretches and the day', () => {
const shown = route(answerCardOf(...input('propose_hike', proposal())));
expect(shown).toMatchObject({
source: 'proposal',
activity: 'hike',
name: 'Herzogstand',
label: 'short and steep',
distanceM: 1112,
ascentM: 80,
descentM: 0,
minEleM: 800,
maxEleM: 880,
minutes: 22,
minutesBasis: 'din33466',
limit: 3,
grades: { highest: 3, unknownShare: 0.25 },
routed: true,
problem: null,
});
expect(shown.line).toEqual([
[47.6, 11.3, 800],
[47.605, 11.3, 840],
[47.61, 11.3, 880],
]);
expect(shown.stretches).toEqual([
{ facet: 'sac', fromM: 0, toM: 600, step: 2 },
{ facet: 'sac', fromM: 600, toM: 1112, step: 3 },
]);
expect(shown.schedule).toMatchObject({ date: '2026-06-12', dayId: 32, dayNumber: 2, start: '08:00' });
expect(shown.schedule?.hours).toEqual([
{ hour: 7, main: 'Clear', tempC: 12, rainPct: null, windKmh: 8 },
{ hour: 8, main: 'Thunderstorm', tempC: 14, rainPct: 70, windKmh: 20 },
]);
expect(shown.warnings).toEqual([{ kind: 'thunder', at: '08:00', count: null }]);
});
it('ASTCARD-TOUR-002: lists the points and the places along the way in the order walked, timed between', () => {
const shown = route(answerCardOf(...input('propose_hike', proposal())));
expect(shown.stops.map((stop) => [stop.role, stop.kind, stop.atM, stop.minutes, stop.clock])).toEqual([
['start', null, 0, 0, '08:00'],
['along', 'drinking_water', 400, 8, '08:08'],
['along', 'viewpoint', 800, 16, '08:16'],
['end', 'peak', 1112, 22, '08:22'],
]);
// A place far off the way is capped at what a card shows; a name from the answer is masked.
expect(shown.stops[2]?.offM).toBe(2000);
expect(shown.stops[3]?.name).toBe('Summit of [hidden]');
expect(JSON.stringify(shown)).not.toContain('desk@peak.test');
});
it('ASTCARD-TOUR-003: adds the highest point as a stop of its own when no summit stands there', () => {
const plain = proposal({
waypoints: [
{ lat: 47.6, lng: 11.3, name: 'Car park', poi_category: null, at_m: 0, minutes: 0, arrival: null },
{ lat: 47.6, lng: 11.31, name: 'Lake', poi_category: null, at_m: 2000, minutes: 40, arrival: null },
],
along: null,
start_time: null,
});
const shown = route(answerCardOf(...input('propose_hike', plain)));
expect(shown.stops.map((stop) => [stop.role, stop.kind, stop.atM, stop.minutes, stop.clock])).toEqual([
['start', null, 0, 0, null],
['along', 'highest', 1112, 22, null],
['end', null, 2000, 40, null],
]);
});
it('ASTCARD-TOUR-004: a line with one height missing keeps none, so no profile is drawn from it', () => {
const gap = proposal({ line_geometry: [at(0), at(1, null), at(2)] });
const shown = route(answerCardOf(...input('propose_hike', gap)));
expect(shown.line.every(([, , height]) => height === null)).toBe(true);
});
it('ASTCARD-TOUR-005: a proposal without its line for drawing, or a broken answer, has no card', () => {
const { line_geometry: _line, ...flagOff } = proposal();
expect(answerCardOf(...input('propose_hike', flagOff))).toBeNull();
expect(answerCardOf(...input('propose_hike', 'not a proposal', {}))).toBeNull();
});
it('ASTCARD-TOUR-006: a way that was not planned is drawn straight through its points, with why', () => {
const unrouted = {
name: 'Herzogstand',
variant_label: null,
route: { planned: false, why: 'point_off_the_way', position: 2 },
unreachable: { position: 2, snapped_m: 340 },
waypoints: [
{ lat: 47.6, lng: 11.3, name: 'Car park', poi_category: null, at_m: null },
{ lat: 47.61, lng: 11.3, name: 'Summit', poi_category: 'peak', at_m: null },
],
max_hiking_difficulty: 2,
warnings: [],
};
const shown = route(answerCardOf(...input('propose_hike', unrouted)));
expect(shown).toMatchObject({
routed: false,
problem: { why: 'point_off_the_way', position: 2, snappedM: 340 },
distanceM: null,
minutes: null,
limit: 2,
line: [
[47.6, 11.3, null],
[47.61, 11.3, null],
],
});
expect(shown.stops.map((stop) => [stop.role, stop.atM])).toEqual([
['start', 0],
['end', 1112],
]);
// An answer naming no points falls back to the call's own; a reason this build does not know reads as unplanned.
const bare = route(answerCardOf(...input('propose_hike', { route: { planned: false, why: 'gremlins' } })));
expect(bare.problem?.why).toBe('not_planned');
expect(bare.stops).toHaveLength(2);
});
it('ASTCARD-TOUR-007: stretches past the card share keep the hardest, in the order they lie', () => {
const segments = Array.from({ length: 120 }, (_, i) => ({
from_m: i * 10,
to_m: i * 10 + 5,
sac: i % 3 === 0 ? 4 : 1,
}));
const kept = sacStretches(segments);
expect(kept).toHaveLength(80);
expect(kept.filter((stretch) => stretch.facet === 'sac' && stretch.step === 4)).toHaveLength(40);
const starts = kept.map((stretch) => stretch.fromM);
expect(starts).toEqual([...starts].sort((a, b) => a - b));
expect(sacStretches([{ from_m: 50, to_m: 10, sac: 2 }, { sac: 9 }, 'odd'])).toEqual([]);
});
it('ASTCARD-TOUR-008: the heaviest proposal still goes out, lightened until it fits the cap', () => {
const long = 'Hut '.repeat(30);
const heavy = proposal({
line_geometry: Array.from({ length: 300 }, (_, k) => [47.123456 + k / 10000, 11.123456, 1234]),
waypoints: Array.from({ length: 26 }, (_, i) => ({
lat: 47.1 + i / 100,
lng: 11.1,
name: `${long}${i}`,
poi_category: 'shelter',
at_m: i * 1000,
minutes: i * 20,
arrival: '09:00',
})),
along: Array.from({ length: 12 }, (_, i) => ({
name: `${long}${i}`,
category: 'viewpoint',
lat: 47.2,
lng: 11.2,
at_m: i * 900 + 50,
off_m: 100,
})),
sac: {
segments: Array.from({ length: 80 }, (_, i) => ({ from_m: i * 100, to_m: i * 100 + 50, sac: (i % 6) + 1 })),
highest: 6,
unknown_share: 0.1,
},
});
const shown = route(answerCardOf(...input('propose_hike', heavy)));
expect(JSON.stringify(shown).length).toBeLessThanOrEqual(MAX_CARD_CHARS);
expect(shown.stops.filter((stop) => stop.role !== 'along')).toHaveLength(26);
// With a full line and the way it replaces beside it, the card is too heavy: both lines are thinned first.
const fine = (k: number): [number, number] => [47.1234567891 + k / 1e7, 11.1234567891];
const previous = {
line: Array.from({ length: 200 }, (_, k) => fine(k)),
distanceM: 9000,
ascentM: null,
minutes: null,
};
const line = Array.from({ length: 300 }, (_, k): [number, number, number] => [...fine(k), 1234]);
const inflated: TourRouteCard = { ...shown, line, previous };
expect(JSON.stringify(inflated).length).toBeGreaterThan(MAX_CARD_CHARS);
const light = fitted(inflated);
expect(JSON.stringify(light).length).toBeLessThanOrEqual(MAX_CARD_CHARS);
expect(light.line.length).toBeLessThanOrEqual(200);
expect(light.previous?.line).toHaveLength(100);
// A card light enough goes out as it is.
const small = route(answerCardOf(...input('propose_hike', proposal())));
expect(fitted(small)).toBe(small);
});
it('ASTCARD-TOUR-013: lightened to its last step, a route keeps its hardest grades, the end of the way too', () => {
const sac = (fromM: number, step: number): TourRouteStretch => ({ facet: 'sac', fromM, toM: fromM + 5, step });
const easy = Array.from({ length: 60 }, (_, i) => sac(i * 10, 1));
const hard = Array.from({ length: 20 }, (_, i) => sac(600 + i * 10, 5));
const kept = hardestStretches([...easy, ...hard], 40);
expect(kept).toHaveLength(40);
expect(kept.filter((stretch) => stretch.facet === 'sac' && stretch.step === 5)).toHaveLength(20);
// The easy ones kept are the first, and all of them lie in their order along the way.
expect(kept.slice(0, 20)).toEqual(easy.slice(0, 20));
const starts = kept.map((stretch) => stretch.fromM);
expect(starts).toEqual([...starts].sort((a, b) => a - b));
expect(hardestStretches(easy.slice(0, 3), 40)).toEqual(easy.slice(0, 3));
});
});
/** What get_tour_plan answers for a saved hike up to a hut that ends a stage. */
function savedPlan(extra: Record<string, unknown> = {}) {
return {
tour: {
place_id: 61,
name: 'Hut walk',
tour_type: 'hike',
distance: 1.112,
elevation_gain: 80,
elevation_loss: 0,
duration: 25,
planned_duration_minutes: null,
max_hiking_difficulty: 2,
stage_count: 2,
website: 'https://example.com/hut',
},
waypoints: [
{ lat: 47.6, lng: 11.3, role: 'start', sequence: 0, name: 'Car park' },
{ lat: 47.605, lng: 11.3, role: 'via', sequence: 1, shaping: true },
{
lat: 47.61,
lng: 11.3,
role: 'end',
sequence: 2,
linked_place_id: 12,
linked_place_name: 'Hut',
stage_end: true,
},
],
line: { point_count: 900, has_heights: true, preview: [at(0), at(1), at(2)] },
...extra,
};
}
describe('the card of a saved tour', () => {
it('ASTCARD-TOUR-009: draws the saved line in brief with its points placed and timed along it', () => {
const shown = route(answerCardOf(...input('get_tour_plan', savedPlan(), { placeId: 61 })));
expect(shown).toMatchObject({
source: 'saved',
activity: 'hike',
placeId: 61,
name: 'Hut walk',
distanceM: 1112,
ascentM: 80,
minEleM: 800,
maxEleM: 880,
minutes: 25,
minutesBasis: 'planned',
limit: 2,
routed: true,
stages: 2,
schedule: null,
grades: null,
});
expect(shown.stops.map((stop) => [stop.role, stop.name, stop.atM, stop.minutes, stop.stageEnd])).toEqual([
['start', 'Car park', 0, 0, false],
['end', 'Hut', 1112, 25, true],
]);
expect(JSON.stringify(shown)).not.toContain('http');
});
it('ASTCARD-TOUR-010: a loop ends at the end of its line, not at its first pass', () => {
const loop = savedPlan({
waypoints: [
{ lat: 47.6, lng: 11.3, role: 'start', name: 'Car park' },
{ lat: 47.61, lng: 11.3, role: 'via', name: 'Top' },
{ lat: 47.6, lng: 11.3, role: 'end', name: 'Car park' },
],
line: { preview: [at(0), at(1), at(2), at(1), at(0)] },
});
const shown = route(answerCardOf(...input('get_tour_plan', loop, { placeId: 61 })));
expect(shown.stops.map((stop) => [stop.role, stop.atM])).toEqual([
['start', 0],
['via', 1112],
['end', 2224],
]);
});
it('ASTCARD-TOUR-011: a city walk still waiting for its way shows its stations straight, placed and masked', () => {
const walk = savedPlan({
tour: { place_id: 62, name: 'Old town', tour_type: 'walk', distance: null, duration: null },
waypoints: [
{ lat: 48.137, lng: 11.575, role: 'start', key: 'a', name: 'Marienplatz', stay_minutes: 0 },
{ lat: 48.14, lng: 11.58, role: 'end', key: 'b', name: 'Hofgarten, ask desk@hof.test', stay_minutes: 30 },
],
line: null,
});
const shown = route(answerCardOf(...input('get_tour_plan', walk, { placeId: 62 })));
expect(shown).toMatchObject({
activity: 'walk',
routed: false,
problem: { why: 'not_planned' },
minutes: null,
minutesBasis: null,
});
// Placed along the straight line between them (about 499 m), not all at its start.
expect(shown.stops.map((stop) => [stop.kind, stop.stayMinutes, stop.minutes, stop.atM])).toEqual([
['station', 0, null, 0],
['station', 30, null, 499],
]);
expect(shown.stops[1]?.name).toBe('Hofgarten, ask [hidden]');
expect(JSON.stringify(shown)).not.toContain('desk@hof.test');
});
it('ASTCARD-TOUR-012: a tour of a type this build does not know, or without its place, has no card', () => {
const canoe = savedPlan({ tour: { place_id: 61, tour_type: 'canoe' } });
expect(answerCardOf(...input('get_tour_plan', canoe))).toBeNull();
expect(answerCardOf(...input('get_tour_plan', savedPlan({ tour: { tour_type: 'hike' } })))).toBeNull();
expect(answerCardOf(...input('get_tour_plan', savedPlan({ line: null, waypoints: [] })))).toBeNull();
});
});
@@ -0,0 +1,391 @@
/**
* ASTCARD-TOUR-020 to ASTCARD-TOUR-029
*
* The cards of a proposed city walk, a paddle plan and a ski plan, and of a
* trip's tours as a list, built from the tool's raw answer through the
* registry's guarded call (so each also fits the card union and the cap):
* the walk's stations with their times and stays, the legs of a plan joined
* into one route with their stretches placed along the whole, the failed
* legs counted and a failed leg between planned ones marked as a gap of its
* straight length, and the list's rows with their days.
*/
import { buildTripCard } from '../../../../../../src/nest/assistant/assistant-context';
import type { AnswerInput } from '../../../../../../src/nest/assistant/cards/card-types';
import { answerCardOf } from '../../../../../../src/nest/assistant/cards/registry';
import { trekCardSchema, type TourListCard, type TourRouteCard, type 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());
const card = buildTripCard(
1,
7,
{ trip: { title: 'Munich' }, days: [{ id: 31, day_number: 3, date: '2026-06-13', assignments: [] }] },
{ places: [] },
null,
);
function built(tool: string, value: unknown, args: Record<string, unknown> = {}): TrekCard | null {
return answerCardOf(tool, { toolCallId: 'call_1', args, value, card, today: '2026-06-01' } satisfies AnswerInput);
}
function route(shown: TrekCard | null): TourRouteCard {
if (shown?.kind !== 'tourRoute') throw new Error(`no route card: ${JSON.stringify(shown)}`);
expect(trekCardSchema.safeParse(shown).success).toBe(true);
return shown;
}
/** What propose_city_walk answers for three stations from ten, the museum closed when it is reached. */
function walk(extra: Record<string, unknown> = {}) {
return {
date: '2026-06-13',
frame: { start_time: '10:00', end_time: '14:00' },
stations: [
{ position: 1, name: 'Marienplatz', lat: 48.137, lng: 11.575, walk_from_previous: null, arrival: '10:00' },
{
position: 2,
name: 'Museum',
lat: 48.14,
lng: 11.58,
walk_from_previous: { metres: 600, minutes: 8 },
arrival: '10:08',
stay_minutes: 60,
conflicts: ['closed_at_arrival', 'late'],
},
{
position: 3,
name: 'Hofgarten',
lat: 48.143,
lng: 11.58,
walk_from_previous: { metres: 400, minutes: 6 },
arrival: '11:14',
stay_minutes: null,
conflicts: ['after_frame'],
},
],
totals: { walk_m: 1000, walk_minutes: 14, total_minutes: 74, ends_at: '11:14' },
estimate: { kind: 'routed', profile: 'walking' },
line_geometry: [
[48.137, 11.575],
[48.14, 11.58],
[48.143, 11.58],
],
stations_for_create: [],
...extra,
};
}
describe('the card of a proposed city walk', () => {
it('ASTCARD-TOUR-020: shows the stations in order with walking minutes, arrivals, stays and flags', () => {
const shown = route(built('propose_city_walk', walk(), { day_id: 31 }));
expect(shown).toMatchObject({
source: 'proposal',
activity: 'walk',
name: null,
distanceM: 1000,
minutes: 74,
minutesBasis: 'stations',
routed: true,
problem: null,
schedule: { date: '2026-06-13', dayId: 31, dayNumber: 3, start: '10:00', arrive: '11:14', hours: [] },
});
expect(shown.line[0]).toEqual([48.137, 11.575, null]);
expect(shown.stops.map((stop) => [stop.role, stop.kind, stop.atM, stop.minutes, stop.clock, stop.flag])).toEqual([
['start', 'station', 0, 0, '10:00', null],
['via', 'station', 600, 8, '10:08', 'closed'],
['end', 'station', 1000, 14, '11:14', 'after_frame'],
]);
expect(shown.stops[1]?.stayMinutes).toBe(60);
});
it('ASTCARD-TOUR-021: without a routed way the stations are joined straight, with why', () => {
const { line_geometry: _line, ...estimated } = walk({
estimate: { kind: 'straight_line', why: 'station_off_the_way', position: 3 },
date: null,
});
const shown = route(built('propose_city_walk', estimated));
expect(shown).toMatchObject({
routed: false,
problem: { why: 'point_off_the_way', position: 3, snappedM: null },
schedule: null,
});
expect(shown.line).toHaveLength(3);
const ferry = route(built('propose_city_walk', { ...estimated, estimate: { why: 'ferry_only', position: 2 } }));
expect(ferry.problem?.why).toBe('ferry_only');
const down = route(built('propose_city_walk', { ...estimated, estimate: { why: 'router_unavailable' } }));
expect(down.problem?.why).toBe('router_unavailable');
expect(built('propose_city_walk', walk({ stations: [walk().stations[0]] }))).toBeNull();
});
});
/** A planned leg along the line given, with its stretches. */
function leg(line: number[][], distance: number, segments: object[], extra: Record<string, unknown> = {}) {
return { status: 'ok', distance_m: distance, line_geometry: line, segments, ...extra };
}
describe('the card of a paddle plan', () => {
const args = {
legs: [
{ from: { lat: 47.6, lng: 11.3 }, to: { lat: 47.61, lng: 11.3 } },
{ from: { lat: 47.61, lng: 11.3 }, to: { lat: 47.62, lng: 11.3 } },
{ from: { lat: 47.62, lng: 11.3 }, to: { lat: 47.63, lng: 11.3 } },
],
};
it('ASTCARD-TOUR-022: joins the legs into one route, marks portages and rapids, counts the failed leg', () => {
const value = {
legs: [
leg(
[
[47.6, 11.3],
[47.61, 11.3],
],
1100,
[
{ kind: 'water', from_m: 0, to_m: 800 },
{ kind: 'portage', from_m: 800, to_m: 1100 },
],
),
leg(
[
[47.61, 11.3],
[47.62, 11.3],
],
1200,
[
{ kind: 'rapids', from_m: 100, to_m: 400 },
{ kind: 'lock', from_m: 500, to_m: 600 },
],
),
{ status: 'failed', reason: 'no_water_path' },
],
graph_rev: 'r1',
};
const shown = route(built('plan_paddle_route', value, args));
expect(shown).toMatchObject({ source: 'plan', activity: 'kayak', distanceM: 2300, routed: true, minutes: null });
expect(shown.line).toHaveLength(4);
expect(shown.line.every(([, , height]) => height === null)).toBe(true);
expect(shown.stretches).toEqual([
{ facet: 'mark', fromM: 800, toM: 1100, kind: 'portage' },
{ facet: 'mark', fromM: 1200, toM: 1500, kind: 'rapids' },
]);
expect(shown.stops.map((stop) => [stop.role, stop.atM])).toEqual([
['start', 0],
['via', 1100],
['via', 2300],
['end', 2300],
]);
expect(shown.warnings).toEqual([{ kind: 'legs_failed', at: null, count: 1 }]);
});
it('ASTCARD-TOUR-028: a failed leg between planned ones is a gap as long as the straight jump, and what follows moves on', () => {
const value = {
legs: [
leg(
[
[47.6, 11.3],
[47.605, 11.3],
],
556,
[{ kind: 'portage', from_m: 0, to_m: 100 }],
),
{ status: 'failed', reason: 'no_water_path' },
leg(
[
[47.615, 11.3],
[47.62, 11.3],
],
556,
[{ kind: 'rapids', from_m: 100, to_m: 300 }],
),
],
};
const gapped = {
legs: [
{ from: { lat: 47.6, lng: 11.3 }, to: { lat: 47.605, lng: 11.3 } },
{ from: { lat: 47.605, lng: 11.3 }, to: { lat: 47.615, lng: 11.3 } },
{ from: { lat: 47.615, lng: 11.3 }, to: { lat: 47.62, lng: 11.3 } },
],
};
const shown = route(built('plan_paddle_route', value, gapped));
// 0.01 degrees north is 1112 m straight: the line runs on by that much.
expect(shown.distanceM).toBe(2224);
expect(shown.stretches).toEqual([
{ facet: 'mark', fromM: 0, toM: 100, kind: 'portage' },
{ facet: 'mark', fromM: 556, toM: 1668, kind: 'gap' },
{ facet: 'mark', fromM: 1768, toM: 1968, kind: 'rapids' },
]);
expect(shown.stops.map((stop) => [stop.role, stop.atM])).toEqual([
['start', 0],
['via', 556],
['via', 1668],
['end', 2224],
]);
expect(shown.warnings).toEqual([{ kind: 'legs_failed', at: null, count: 1 }]);
});
it('ASTCARD-TOUR-023: a plan without a planned leg or without lines for drawing has no card', () => {
expect(built('plan_paddle_route', { legs: [{ status: 'failed' }] }, args)).toBeNull();
expect(built('plan_paddle_route', { legs: [{ status: 'ok', distance_m: 900, segments: [] }] }, args)).toBeNull();
});
});
describe('the card of a ski plan', () => {
it('ASTCARD-TOUR-024: sums the legs, keeps the heights, colours runs by difficulty and dots the lifts', () => {
const value = {
legs: [
leg(
[
[47.4, 11.0, 1800],
[47.41, 11.0, 1500],
],
1500,
[
{ kind: 'run', difficulty: 'intermediate', from_m: 0, to_m: 700 },
{ kind: 'run', difficulty: 'intermediate', from_m: 700, to_m: 1000 },
{ kind: 'lift', difficulty: null, from_m: 1000, to_m: 1500 },
{ kind: 'teleport', from_m: 0, to_m: 1 },
],
{ climb_m: 300, descent_m: 300, seconds: { ski: 300, lift: 240, wait: 60, walk: 0 } },
),
],
colour_scheme: 'north_america',
};
const args = { legs: [{ from: { lat: 47.4, lng: 11.0 }, to: { lat: 47.41, lng: 11.0 } }] };
const shown = route(built('plan_ski_route', value, args));
expect(shown).toMatchObject({
source: 'plan',
activity: 'ski',
distanceM: 1500,
ascentM: 300,
descentM: 300,
minEleM: 1500,
maxEleM: 1800,
minutes: 10,
minutesBasis: 'piste',
skiScheme: 'north_america',
warnings: [],
});
expect(shown.stretches).toEqual([
{ facet: 'ski', fromM: 0, toM: 1000, kind: 'run', difficulty: 'intermediate' },
{ facet: 'mark', fromM: 1000, toM: 1500, kind: 'lift' },
]);
expect(built('plan_ski_route', { legs: [] }, args)).toBeNull();
});
});
describe('the card of a ski plan with a leg that failed', () => {
it('ASTCARD-TOUR-029: the runs after a failed leg sit past the gap it leaves, the heights kept', () => {
const value = {
legs: [
leg(
[
[47.4, 11.0, 1800],
[47.405, 11.0, 1600],
],
600,
[{ kind: 'run', difficulty: 'intermediate', from_m: 0, to_m: 600 }],
),
{ status: 'failed', reason: 'no_way' },
leg(
[
[47.415, 11.0, 1700],
[47.42, 11.0, 1500],
],
600,
[{ kind: 'run', difficulty: 'freeride', from_m: 0, to_m: 600 }],
),
],
};
const args = {
legs: [
{ from: { lat: 47.4, lng: 11.0 }, to: { lat: 47.405, lng: 11.0 } },
{ from: { lat: 47.405, lng: 11.0 }, to: { lat: 47.415, lng: 11.0 } },
{ from: { lat: 47.415, lng: 11.0 }, to: { lat: 47.42, lng: 11.0 } },
],
};
const shown = route(built('plan_ski_route', value, args));
expect(shown).toMatchObject({ distanceM: 2312, minEleM: 1500, maxEleM: 1800 });
expect(shown.stretches).toEqual([
{ facet: 'ski', fromM: 0, toM: 600, kind: 'run', difficulty: 'intermediate' },
{ facet: 'mark', fromM: 600, toM: 1712, kind: 'gap' },
{ facet: 'ski', fromM: 1712, toM: 2312, kind: 'run', difficulty: 'freeride' },
]);
expect(shown.stops.map((stop) => stop.atM)).toEqual([0, 600, 1712, 2312]);
expect(shown.warnings).toEqual([{ kind: 'legs_failed', at: null, count: 1 }]);
});
});
describe('the card of a list of tours', () => {
const tour = (id: number, extra: Record<string, unknown> = {}) => ({
place_id: id,
name: `Tour ${id}`,
tour_type: 'hike',
distance: 9.8,
elevation_gain: 520,
duration: 225,
max_hiking_difficulty: 2,
days: [{ day_id: 32, day_number: 2 }],
...extra,
});
function list(shown: TrekCard | null): TourListCard {
if (shown?.kind !== 'tourList') throw new Error(`no list card: ${JSON.stringify(shown)}`);
expect(trekCardSchema.safeParse(shown).success).toBe(true);
return shown;
}
it('ASTCARD-TOUR-025: lists each tour with its figures, stages and days, the planned time first', () => {
const value = {
tours: [
tour(61, { planned_duration_minutes: 300, stage_count: 2, days: [{ day_number: 3 }, { day_number: 2 }] }),
tour(62, { tour_type: 'walk', duration: null, time_estimate: { minutes: 95 }, distance: null }),
],
};
const shown = list(built('list_tours', value));
expect(shown).toMatchObject({ dayId: null, more: 0 });
expect(shown.rows).toEqual([
{
placeId: 61,
name: 'Tour 61',
activity: 'hike',
limit: 2,
distanceM: 9800,
ascentM: 520,
minutes: 300,
stages: 2,
days: [2, 3],
},
{
placeId: 62,
name: 'Tour 62',
activity: 'walk',
limit: 2,
distanceM: null,
ascentM: 520,
minutes: 95,
stages: null,
days: [2],
},
]);
});
it('ASTCARD-TOUR-026: shows twelve rows and counts the rest; the day asked for is kept', () => {
const tours = Array.from({ length: 15 }, (_, i) => tour(70 + i));
const shown = list(built('find_tours_for_day', { tours }, { dayId: 32 }));
expect(shown.rows).toHaveLength(12);
expect(shown).toMatchObject({ dayId: 32, more: 3 });
});
it('ASTCARD-TOUR-027: a tour without a name or of an unknown type is left out; an empty list has no card', () => {
const tours = [tour(1, { name: '' }), tour(2, { tour_type: 'canoe' }), tour(3)];
const shown = list(built('list_tours', { tours }));
expect(shown.rows.map((row) => row.placeId)).toEqual([3]);
expect(built('list_tours', { tours: [] })).toBeNull();
expect(built('find_tours_for_day', null, { dayId: 32 })).toBeNull();
});
});