feat(tours): round hikes, other ways of a leg and wanderer trails through the assistant

The assistant can now search a round hike of about a wished length from one
point and the router's other ways for one leg of a hike, with the planner's
own search, and propose each one as a hike card to compare and take. It can
also search the user's wanderer trails, preview one as a card, import it and
check a wanderer tour against its source.

The round search, its loop geometry, the test whether two lines are one way,
the other ways among a router's offers and the pins that hold a chosen way
move to @trek/shared; the planner and the road trip use them from there.
This commit is contained in:
Maurice
2026-10-23 21:15:37 +02:00
parent 338548bf7f
commit 14196358fb
74 changed files with 3031 additions and 438 deletions
@@ -28,7 +28,7 @@ import { makePackingBag, makePackingItem } from '../../helpers/factories/packing
import { makeCategory, makePlace, makeTag } from '../../helpers/factories/places';
import { makeReservation } from '../../helpers/factories/reservations';
import { createRow, findRow, insertRow, updateRows } from '../../helpers/factories/rows';
import { setAddonEnabled, setCollabFeature } from '../../helpers/factories/settings';
import { setAddonEnabled, setAppSetting, setCollabFeature } from '../../helpers/factories/settings';
import { makeTodoItem } from '../../helpers/factories/todos';
import { makeTour } from '../../helpers/factories/tours';
import { addTripMember, makeTrip, readTripDays } from '../../helpers/factories/trips';
@@ -221,6 +221,8 @@ export async function openHarness(): Promise<ParityHarness> {
const orm = app.get(MikroORM);
await oneByOne(Object.values(ADDON_IDS), (addon) => setAddonEnabled(orm, addon, true));
await oneByOne(['chat', 'notes', 'polls', 'whatsnext'] as const, (feature) => setCollabFeature(orm, feature, true));
// The wanderer tools show only while wanderer is allowed under Tours.
await setAppSetting(orm, 'tours_wanderer_enabled', 'true');
// The photo search tools show only while a provider is on.
await updateRows(orm, PhotoProviders, { id: { $in: ['immich', 'synologyphotos'] } }, { enabled: 1 });
@@ -5,6 +5,8 @@ import { TourWaypoints } from '../../../src/db/entities/TourWaypoints.entity';
import { Tours } from '../../../src/db/entities/Tours.entity';
import { RoadtripRouterService } from '../../../src/nest/roadtrip/roadtrip-router.service';
import { proposalIdOf } from '../../../src/nest/tours/tour-change-proposal';
import { ToursWandererService } from '../../../src/nest/tours/tours-wanderer.service';
import { WandererService } from '../../../src/nest/wanderer/wanderer.service';
import { makeDayAssignment } from '../../helpers/factories/itinerary';
import { makePlace } from '../../helpers/factories/places';
import { createRow, deleteRows, updateRows } from '../../helpers/factories/rows';
@@ -192,6 +194,53 @@ const gpxOf = (s: Scene) =>
`<gpx><trk><name>Ridge ${s.n}</name><trkseg><trkpt lat="47.6" lon="11.3"><ele>800</ele></trkpt>` +
'<trkpt lat="47.61" lon="11.3"><ele>1000</ele></trkpt></trkseg></trk></gpx>';
/** The fingerprint of the wanderer trail a case's setup previewed, by the scene's number. */
const trailHashFor = new Map<number, string>();
function trailHash(s: Scene): string {
const hash = trailHashFor.get(s.n);
if (hash === undefined) throw new Error(`scene ${s.n}: the case's setup previewed no trail`);
return hash;
}
/** No wanderer instance in a test: the owner's own trail, found and downloaded as the connection would. */
function wandererTrail(app: INestApplication): () => void {
const wanderer = app.get(WandererService);
const summary = {
id: 'trail-1',
name: 'Kesselberg',
description: null,
location: 'Kochel',
distanceM: 2200,
durationS: 3600,
elevationGainM: 200,
elevationLossM: 0,
difficulty: 'moderate' as const,
public: false,
author: 'owner',
line: [],
externalUrl: 'https://wanderer.example/trail/view/trail-1',
};
const found = vi.spyOn(wanderer, 'findTrail').mockResolvedValue(summary);
const download = vi.spyOn(wanderer, 'download').mockResolvedValue({
instance: 'https://wanderer.example',
trail: { id: 'trail-1', name: 'Kesselberg', description: null, author: 'owner', updated: null } as never,
gpx:
'<gpx><trk><name>Kesselberg</name><trkseg><trkpt lat="47.6" lon="11.3"><ele>800</ele></trkpt>' +
'<trkpt lat="47.62" lon="11.3"><ele>1000</ele></trkpt></trkseg></trk></gpx>',
});
return () => {
found.mockRestore();
download.mockRestore();
};
}
/** The trail previewed first, as the traveller sees it before the import: its fingerprint is what the import takes. */
async function previewTrail(s: Scene, app: INestApplication): Promise<void> {
const preview = await app.get(ToursWandererService).preview(String(s.trip.id), s.owner.id, 'trail-1');
trailHashFor.set(s.n, preview.contentHash);
}
const roadtripDay = (s: Scene) => `/api/trips/${s.trip.id}/roadtrip/days/${s.days[0].id}`;
const tourPath = (s: Scene) => `/api/trips/${s.trip.id}/tours/${s.tourPlace.id}`;
@@ -365,6 +414,18 @@ export const toursRoadtrip: CaseGroup = {
twin: 'POST /api/trips/:tripId/tours/import/gpx with the file',
expect: ['tours:changed', 'place:created'],
},
{
tool: 'import_wanderer_trail',
setup: previewTrail,
args: (s) => ({ tripId: s.trip.id, trailId: 'trail-1', contentHash: trailHash(s) }),
rest: {
method: 'post',
path: (s) => `/api/trips/${s.trip.id}/tours/wanderer/import`,
body: (s) => ({ trailId: 'trail-1', contentHash: trailHash(s) }),
},
stub: wandererTrail,
expect: ['tours:changed', 'place:created'],
},
{
tool: 'save_tour_change',
needs: ['tour'],
@@ -0,0 +1,80 @@
/**
* ASSISTANT-WAYS-TAKE-001 to ASSISTANT-WAYS-TAKE-004: "Plan this" on a round
* hike, another way of a leg and a wanderer trail: the change each holds,
* taken from the stored proposal, never from the request.
*/
import { isWayProposal, wayTakeArgsOf } from '../../../../src/nest/assistant/assistant-proposal-ways';
import { takeArgsOf } from '../../../../src/nest/assistant/assistant-proposals.service';
import { writeToolOf } from '../../../../src/nest/assistant/assistant-tools.constants';
import type { TourRouteCard } from '@trek/shared';
import { describe, expect, it } from 'vitest';
const CARD = { kind: 'tourRoute', source: 'proposal', routed: true, placeId: null } as TourRouteCard;
const START = { lat: 47.6, lng: 11.3, name: 'Car park', at_m: 0 };
const ROUND = {
create_with: {
waypoints: [START, { lat: 47.61, lng: 11.31 }, { lat: 47.62, lng: 11.3, poi_category: 'peak' }],
round_trip: true,
},
};
describe('taking a round or a leg’s way', () => {
it('ASSISTANT-WAYS-TAKE-001: a round is created through the points it answered, under the rules it was asked with', () => {
const args = { name: 'Round', start: START, distance_km: 10, max_hiking_difficulty: 3, day_id: 31, round: 'b' };
expect(wayTakeArgsOf('propose_round_hike', args, ROUND, CARD)).toEqual({
via: 'create_hike',
name: 'Round',
max_hiking_difficulty: 3,
day_id: 31,
round_trip: true,
waypoints: [
{ lat: 47.6, lng: 11.3, name: 'Car park' },
{ lat: 47.61, lng: 11.31 },
{ lat: 47.62, lng: 11.3, poi_category: 'peak' },
],
});
expect(takeArgsOf({ toolName: 'propose_round_hike', args, result: ROUND, card: CARD })).toMatchObject({
via: 'create_hike',
});
// A stop a day ends at stays one on a hike over several days.
const trek = {
create_with: { waypoints: [START, { lat: 47.7, lng: 11.4, stage_end: true }, START], round_trip: false },
};
expect(wayTakeArgsOf('propose_hike_leg_way', { name: 'Trek' }, trek, CARD)?.waypoints).toEqual([
{ lat: 47.6, lng: 11.3, name: 'Car park' },
{ lat: 47.7, lng: 11.4, stage_end: true },
{ lat: 47.6, lng: 11.3, name: 'Car park' },
]);
expect(isWayProposal('propose_hike_leg_way')).toBe(true);
expect(isWayProposal('toString')).toBe(false);
});
it('ASSISTANT-WAYS-TAKE-002: nothing is taken from a way not planned, a saved hike’s leg or broken points', () => {
expect(wayTakeArgsOf('propose_round_hike', {}, ROUND, { ...CARD, routed: false })).toBeNull();
expect(wayTakeArgsOf('propose_hike_leg_way', {}, ROUND, { ...CARD, placeId: 61 })).toBeNull();
const broken = { create_with: { waypoints: [START, { lat: 'x' }], round_trip: false } };
expect(wayTakeArgsOf('propose_hike_leg_way', {}, broken, CARD)).toBeNull();
expect(wayTakeArgsOf('propose_hike_leg_way', {}, {}, CARD)).toBeNull();
});
});
describe('taking a wanderer trail', () => {
it('ASSISTANT-WAYS-TAKE-003: a trail is imported with the fingerprint its preview answered', () => {
const result = { contentHash: 'h'.repeat(32), state: 'new' };
expect(wayTakeArgsOf('preview_wanderer_trail', { trailId: 'trail-1' }, result, CARD)).toEqual({
via: 'import_wanderer_trail',
trailId: 'trail-1',
contentHash: 'h'.repeat(32),
});
// The take runs the import itself.
expect(writeToolOf('take_proposal', { via: 'import_wanderer_trail' })).toBe('import_wanderer_trail');
});
it('ASSISTANT-WAYS-TAKE-004: a trail already in the trip as it is, or a preview without its fingerprint, is not taken', () => {
const args = { trailId: 'trail-1' };
expect(wayTakeArgsOf('preview_wanderer_trail', args, { contentHash: 'h', state: 'unchanged' }, CARD)).toBeNull();
expect(wayTakeArgsOf('preview_wanderer_trail', args, { state: 'new' }, CARD)).toBeNull();
expect(wayTakeArgsOf('preview_wanderer_trail', {}, { contentHash: 'h', state: 'new' }, CARD)).toBeNull();
});
});
@@ -0,0 +1,196 @@
/**
* ASTCARD-TOUR-WAYS-001 to ASTCARD-TOUR-WAYS-008
*
* The cards of the planner's other searches through the assistant: a round
* hike and another way for one leg, drawn as propose_hike's proposals are,
* the leg's way beside the hike as it runs now; a wanderer trail previewed
* as a way to take in, and its import with a change card and a way back.
*/
import { buildTripCard } from '../../../../../../src/nest/assistant/assistant-context';
import type { CardReader, PreviewContext } from '../../../../../../src/nest/assistant/cards/card-types';
import {
answerCardOf,
ASSISTANT_ARG_POLICY,
ASSISTANT_UNDO_MAP,
ASSISTANT_WRITE_TOOLS,
CARD_PROMPT_LINES,
} from '../../../../../../src/nest/assistant/cards/registry';
import {
IMPORT_WANDERER_TRAIL,
legWayCard,
roundHikeCard,
wandererPreviewCard,
wandererTrailCard,
} from '../../../../../../src/nest/assistant/cards/tour/tour-ways.cards';
import { trekCardSchema } from '@trek/shared';
import { describe, expect, it, vi } from 'vitest';
const card = buildTripCard(1, 7, { trip: { title: 'Bavaria' }, days: [] }, { places: [] }, null);
const ctx: PreviewContext = { card, categories: new Map(), locale: 'en-GB', today: '2026-06-01', airport: () => null };
const LINE: Array<[number, number, number]> = [
[47.6, 11.3, 800],
[47.61, 11.31, 950],
[47.62, 11.3, 1100],
[47.6, 11.3, 800],
];
/** A proposal as propose_hike answers it, its way planned, with what the search adds. */
function proposal(extra: Record<string, unknown> = {}) {
return {
found: true,
name: 'Round over the Kesselberg',
variant_label: null,
route: { planned: true },
distance_m: 10_400,
ascent_m: 300,
descent_m: 300,
duration_minutes: 190,
duration_basis: 'din33466',
max_hiking_difficulty: 2,
line_geometry: LINE,
waypoints: [
{ lat: 47.6, lng: 11.3, name: 'Car park', at_m: 0, minutes: 0 },
{ lat: 47.61, lng: 11.31, name: null, at_m: 3000, minutes: 60 },
{ lat: 47.6, lng: 11.3, name: 'Car park', at_m: 10_400, minutes: 190 },
],
...extra,
};
}
const answer = (value: unknown, args: Record<string, unknown> = {}) => ({
toolCallId: 't1',
args,
value,
card,
today: '2026-06-01',
});
describe('a round and another way of a leg', () => {
it('ASTCARD-TOUR-WAYS-001: a round found is a hike proposal’s card; one not found draws nothing', () => {
const drawn = roundHikeCard(answer(proposal({ round: { key: 'a' } })));
expect(drawn).toMatchObject({ kind: 'tourRoute', source: 'proposal', activity: 'hike', distanceM: 10_400 });
expect(trekCardSchema.safeParse(drawn).success).toBe(true);
expect(roundHikeCard(answer({ found: false, way: 'b', ways_found: 1, why: 'none_found' }))).toBeNull();
});
it('ASTCARD-TOUR-WAYS-002: a leg’s way draws the hike as it runs now beneath it, and names a saved hike', () => {
const value = proposal({
leg_way: { key: 'b', leg: 1, ways_found: 2, tour_id: 61 },
current: { distance_m: 9_800, ascent_m: 280, duration_minutes: 175 },
current_geometry: LINE.slice(0, 3),
});
const drawn = legWayCard(answer(value));
expect(drawn?.previous).toMatchObject({ distanceM: 9_800, ascentM: 280, minutes: 175 });
expect(drawn?.previous?.line).toHaveLength(3);
expect(drawn?.placeId).toBe(61);
expect(trekCardSchema.safeParse(drawn).success).toBe(true);
const unsaved = legWayCard(answer(proposal({ leg_way: { tour_id: null }, current: {} })));
expect(unsaved).toMatchObject({ placeId: null, previous: null });
expect(legWayCard(answer({ found: false }))).toBeNull();
});
it('ASTCARD-TOUR-WAYS-003: the planning tools are always asked for their line, and the prompt names them', () => {
for (const tool of ['propose_round_hike', 'propose_hike_leg_way', 'preview_wanderer_trail']) {
expect(ASSISTANT_ARG_POLICY[tool]?.forced, tool).toEqual({ include_geometry: true });
}
expect(answerCardOf('propose_round_hike', answer(proposal()))?.kind).toBe('tourRoute');
const prompt = CARD_PROMPT_LINES.join(' ');
expect(prompt).toContain('propose_round_hike');
expect(prompt).toContain('import_wanderer_trail');
});
});
const PREVIEW = {
trail: {
id: 'trail-1',
name: 'Herzogstand',
location: 'Kochel',
difficulty: 'moderate',
externalUrl: 'https://w.example/t/1',
},
distanceKm: 9.1,
elevationGainM: 812,
elevationLossM: 790,
hasElevation: true,
points: 900,
line_geometry: [
[47.6, 11.3],
[47.62, 11.33],
[47.65, 11.36],
],
contentHash: 'h'.repeat(32),
state: 'new',
snapshot: null,
changes: [],
};
describe('a wanderer trail', () => {
it('ASTCARD-TOUR-WAYS-004: a trail previewed is a hike to take in: its line, length, climb and grade', () => {
const drawn = wandererPreviewCard(answer(PREVIEW));
expect(drawn).toMatchObject({
source: 'proposal',
activity: 'hike',
placeId: null,
name: 'Herzogstand',
distanceM: 9100,
ascentM: 812,
descentM: 790,
limit: 2,
routed: true,
});
expect(drawn?.stops.map((stop) => stop.role)).toEqual(['start', 'end']);
expect(drawn?.stops[0]?.name).toBe('Kochel');
expect(trekCardSchema.safeParse(drawn).success).toBe(true);
});
it('ASTCARD-TOUR-WAYS-005: one already in the trip as it is reads as that saved tour; a loop has one stop', () => {
const kept = wandererPreviewCard(answer({ ...PREVIEW, state: 'unchanged', snapshot: { placeId: 61 } }));
expect(kept).toMatchObject({ source: 'saved', placeId: 61 });
const loop = wandererTrailCard(
{
...PREVIEW,
trail: { name: 'Loop', difficulty: 'unknown' },
line_geometry: [
[47.6, 11.3],
[47.62, 11.33],
[47.6, 11.3],
],
},
'pending',
);
expect(loop).toMatchObject({ source: 'pending', placeId: null, limit: null });
expect(loop?.stops).toHaveLength(1);
expect(wandererPreviewCard(answer({ ...PREVIEW, line_geometry: [] }))).toBeNull();
});
it('ASTCARD-TOUR-WAYS-006: a held import reads the trail again and shows it waiting, named and graded', async () => {
const read = vi.fn(async () => PREVIEW) as unknown as CardReader;
const loaded = await IMPORT_WANDERER_TRAIL.load?.({ trailId: 'trail-1', contentHash: 'x' }, read);
expect(read).toHaveBeenCalledWith('preview_wanderer_trail', { trailId: 'trail-1', include_geometry: true });
const described = IMPORT_WANDERER_TRAIL.describe?.(ctx, { trailId: 'trail-1' }, loaded ?? null);
expect(described?.subject).toBe('Herzogstand');
expect(described?.rows.rows.map((row) => [row.labelKey, row.after])).toEqual([
['location', 'Kochel'],
['difficulty', 'T2'],
['link', 'https://w.example/t/1'],
]);
expect(IMPORT_WANDERER_TRAIL.change?.(ctx, {}, loaded ?? null)).toMatchObject({ source: 'pending' });
expect(IMPORT_WANDERER_TRAIL.change?.(ctx, {}, null)).toBeNull();
});
it('ASTCARD-TOUR-WAYS-007: an import without a trail looks nothing up and is named by the trail asked for', async () => {
const read = vi.fn() as unknown as CardReader;
expect(await IMPORT_WANDERER_TRAIL.load?.({}, read)).toBeNull();
expect(read).not.toHaveBeenCalled();
expect(IMPORT_WANDERER_TRAIL.describe?.(ctx, { trailId: 'trail-9' }, null).subject).toBe('trail-9');
});
it('ASTCARD-TOUR-WAYS-008: an import is a tour added, taken back by deleting the tour it made', () => {
expect(ASSISTANT_WRITE_TOOLS.import_wanderer_trail).toEqual({ verbKey: 'importTour', entity: 'tour' });
expect(ASSISTANT_UNDO_MAP.import_wanderer_trail?.args({}, { tour: { place_id: 72 } }, null)).toEqual({
placeId: 72,
});
});
});
@@ -0,0 +1,90 @@
/**
* The pure halves of the round hikes and the ways of a leg the assistant
* proposes: which way a call asks for, the points a found way runs through,
* and the keys a search is kept under.
*/
import {
legEndsOf,
legWaysKey,
percentOf,
pinnedPointsOf,
roadOf,
roundPointsOf,
roundSearchKey,
rulesOf,
wayIndexOf,
wayKeyAt,
wayMissing,
} from '../../../src/nest/tours/hike-ways.helpers';
import { HIKE_MAX_WAYPOINTS, TOURS_MAX_HIKING_DIFFICULTY } from '@trek/shared';
import { describe, expect, it } from 'vitest';
// HIKE-WAYS-HELP-001 to HIKE-WAYS-HELP-006
const A = { lat: 47.5, lng: 11.1, name: 'Car park' };
const B = { lat: 47.52, lng: 11.14 };
const C = { lat: 47.55, lng: 11.2, name: 'Hut' };
describe('the ways a call asks for', () => {
it('HIKE-WAYS-HELP-001: a, b and c are the first, second and third way; a when left out', () => {
expect([wayIndexOf(undefined), wayIndexOf('a'), wayIndexOf('b'), wayIndexOf('c')]).toEqual([0, 0, 1, 2]);
expect([wayKeyAt(0), wayKeyAt(2), wayKeyAt(7)]).toEqual(['a', 'c', 'a']);
expect(wayMissing('b', 1, null)).toEqual({ found: false, way: 'b', ways_found: 1, why: 'none_found' });
expect(wayMissing(undefined, 0, 'no_valhalla')).toEqual({
found: false,
way: 'a',
ways_found: 0,
why: 'no_valhalla',
});
});
it('HIKE-WAYS-HELP-002: the rules default to the hike’s limit and no preferences; shares read as whole percent', () => {
expect(rulesOf({})).toEqual({ limit: TOURS_MAX_HIKING_DIFFICULTY, preferences: null });
expect(rulesOf({ max_hiking_difficulty: 4 }).limit).toBe(4);
expect([percentOf(0.084), percentOf(-0.05)]).toEqual([8, -5]);
});
});
describe('the keys a search is kept under', () => {
it('HIKE-WAYS-HELP-003: one search per user, trip, start to about a metre, length and rules', () => {
const round = { name: 'Round', start: A, distance_km: 10 };
expect(roundSearchKey(1, 2, round)).toBe(roundSearchKey(1, 2, { ...round, name: 'Other', round: 'c' }));
expect(roundSearchKey(1, 2, round)).toBe(roundSearchKey(1, 2, { ...round, start: { ...A, lat: 47.500001 } }));
expect(roundSearchKey(1, 2, round)).not.toBe(roundSearchKey(3, 2, round));
expect(roundSearchKey(1, 2, round)).not.toBe(roundSearchKey(1, 2, { ...round, distance_km: 12 }));
expect(roundSearchKey(1, 2, round)).not.toBe(roundSearchKey(1, 2, { ...round, max_hiking_difficulty: 4 }));
const leg = { name: 'Hike', waypoints: [A, B, C], leg: 1 };
expect(legWaysKey(1, 2, leg)).toBe(legWaysKey(1, 2, { ...leg, way: 'b' }));
expect(legWaysKey(1, 2, leg)).not.toBe(legWaysKey(1, 2, { ...leg, leg: 2 }));
expect(legWaysKey(1, 2, leg)).not.toBe(legWaysKey(1, 2, { ...leg, round_trip: true }));
});
});
describe('the points of a way', () => {
it('HIKE-WAYS-HELP-004: a round runs from its start through the spots its loop was steered through, and back', () => {
expect(roundPointsOf(A, [B, { lat: 47.6, lng: 11.3 }])).toEqual({
waypoints: [A, { lat: B.lat, lng: B.lng }, { lat: 47.6, lng: 11.3 }],
round_trip: true,
});
});
it('HIKE-WAYS-HELP-005: a leg runs between its two points, the way back of a round trip to its start', () => {
expect(legEndsOf([A, B, C], false, 1)).toEqual({
from: { lat: A.lat, lng: A.lng },
to: { lat: B.lat, lng: B.lng },
});
expect(legEndsOf([A, B, C], true, 3)).toEqual({ from: { lat: C.lat, lng: C.lng }, to: { lat: A.lat, lng: A.lng } });
expect(legEndsOf([A, B, C], false, 3)).toBeNull();
});
it('HIKE-WAYS-HELP-006: the pins of a leg go right after its first point, those of the way back last', () => {
const pin = { lat: 47.51, lng: 11.12 };
expect(pinnedPointsOf([A, B, C], 1, [pin])).toEqual([A, pin, B, C]);
expect(pinnedPointsOf([A, B, C], 2, [pin])).toEqual([A, B, pin, C]);
expect(pinnedPointsOf([A, B, C], 3, [pin])).toEqual([A, B, C, pin]);
const full = Array.from({ length: HIKE_MAX_WAYPOINTS }, (_, index) => ({ lat: 47 + index / 100, lng: 11 }));
expect(pinnedPointsOf(full, 1, [pin])).toBeNull();
expect(roadOf([[47, 11]])).toEqual({ coordinates: [[47, 11]], distance: 0, duration: 0 });
});
});
@@ -0,0 +1,233 @@
/**
* HikeWaysMcp and HikeWaysService: the planner's round hikes of a wished
* length and its other ways for one leg, over MCP. The search is the shared
* one, asked of a stubbed RoadtripRouterService that walks straight between
* the points it is given; each way found is proposed through a stub of
* HikePlanService.propose (its own suite plans the hike). The trip and a
* saved hike are seeded through the ORM factories over a snapshot test db.
*/
import type { McpContext } from '../../../src/nest-mcp';
import { RoadtripRouterService, RouteRefusal } from '../../../src/nest/roadtrip/roadtrip-router.service';
import { HikePlanService } from '../../../src/nest/tours/hike-plan.service';
import { HikeWaysMcp } from '../../../src/nest/tours/hike-ways.mcp';
import { ToursModule } from '../../../src/nest/tours/tours.module';
import { createSnapshotTestDb } from '../../helpers/db-mock';
import { makePlace } from '../../helpers/factories/places';
import { makeTour } from '../../helpers/factories/tours';
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 type { HikeProposeRequest } from '@trek/shared';
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
// HIKE-WAYS-MCP-001 to HIKE-WAYS-MCP-008
type Spot = { lat: number; lng: number };
const db = createSnapshotTestDb();
const route = vi.fn<RoadtripRouterService['route']>();
const alternatesOnFoot = vi.fn<RoadtripRouterService['alternatesOnFoot']>();
const propose = vi.fn<HikePlanService['propose']>();
let t: TestModule;
let mcp: HikeWaysMcp;
const orm = () => t.get(MikroORM);
/** The router's answer for points walked straight between, each met where it was asked. */
function straight(points: Spot[]) {
return {
leg: {
line: points.map(({ lat, lng }): [number, number] => [lat, lng]),
seg: { distance: 0, duration: 0 },
},
parts: points.slice(1).map(() => ({ distance: 0, duration: 0 })),
snapped: points.map(({ lat, lng }) => ({ asked: [lat, lng], at: [lat, lng], meters: 0 })),
avoidMissed: [],
} as unknown as Awaited<ReturnType<RoadtripRouterService['route']>>;
}
/** The stub's proposal: the request's points given back, a length and a line. */
async function proposal(_userId: number, _tripId: number, request: HikeProposeRequest) {
return {
name: request.name,
variant_label: request.variant_label ?? null,
route: { planned: true },
distance_m: 10_400,
ascent_m: 420,
duration_minutes: 190,
waypoints: request.waypoints,
round_trip: request.round_trip ?? false,
line_geometry: request.waypoints.map(({ lat, lng }): [number, number] => [lat, lng]),
} as unknown as Awaited<ReturnType<HikePlanService['propose']>>;
}
beforeAll(async () => {
t = await createTestModule({
db,
imports: [ToursModule],
overrides: [
{ provide: RoadtripRouterService, useValue: { route, alternatesOnFoot } },
{ provide: HikePlanService, useValue: { propose } },
],
});
mcp = t.get(HikeWaysMcp);
});
beforeEach(() => {
resetTestDb(db);
route.mockReset().mockImplementation(async (_u, _t, _d, points) => straight(points));
alternatesOnFoot.mockReset();
propose.mockReset().mockImplementation(proposal);
});
afterAll(async () => {
await t.close();
db.close();
});
const ctx = (userId: number) => ({ userId }) as McpContext;
/** The JSON a tool answered, or the error text it refused with. */
function read(result: { content: Array<{ type: string; text: string }>; isError?: boolean }) {
const text = result.content[0]?.text ?? '';
return result.isError ? { error: text } : JSON.parse(text);
}
async function tripOf() {
const { user } = await makeUser(orm());
const trip = await makeTrip(orm(), user.id);
return { userId: user.id, tripId: trip.id };
}
const START = { lat: 47.5, lng: 11.1, name: 'Car park' };
describe('propose_round_hike', () => {
it('HIKE-WAYS-MCP-001: proposes the round asked for as a hike back to its start, with the points to create it', async () => {
const { userId, tripId } = await tripOf();
const answer = read(
await mcp.proposeRoundHike({ tripId, name: 'Round', start: START, distance_km: 10, round: 'b' }, ctx(userId)),
);
expect(answer.found).toBe(true);
expect(answer.round).toMatchObject({ key: 'b', target_m: 10_000, deviation_pct: 4, rounds_found: 3 });
expect(answer.create_with.round_trip).toBe(true);
expect(answer.create_with.waypoints).toHaveLength(4);
expect(answer.create_with.waypoints[0]).toEqual(START);
const [, , asked] = propose.mock.calls[0] ?? [];
expect(asked).toMatchObject({ name: 'Round', round_trip: true, along: false });
// Every loop was asked on foot under the hike's own costing, out of the start and back.
for (const [, , , points, profile, , options] of route.mock.calls) {
expect(points[0]).toEqual({ lat: START.lat, lng: START.lng });
expect(points.at(-1)).toEqual({ lat: START.lat, lng: START.lng });
expect(profile).toBe('walking');
expect(options?.costingOptions).toMatchObject({ max_hiking_difficulty: 2 });
}
});
it('HIKE-WAYS-MCP-002: the rounds of one search are asked for one after another without asking the router again', async () => {
const { userId, tripId } = await tripOf();
const request = { tripId, name: 'Round', start: START, distance_km: 10 };
await mcp.proposeRoundHike({ ...request, round: 'a' }, ctx(userId));
const asked = route.mock.calls.length;
const c = read(await mcp.proposeRoundHike({ ...request, round: 'c' }, ctx(userId)));
expect(c.round.key).toBe('c');
expect(route.mock.calls.length).toBe(asked);
});
it('HIKE-WAYS-MCP-003: a router that never answers, or no Valhalla, finds no round and says why', async () => {
const { userId, tripId } = await tripOf();
route.mockRejectedValue(new Error('down'));
const down = read(await mcp.proposeRoundHike({ tripId, name: 'R', start: START, distance_km: 8 }, ctx(userId)));
expect(down).toEqual({ found: false, way: 'a', ways_found: 0, why: 'router_unavailable' });
route.mockReset().mockRejectedValue(new RouteRefusal('no_valhalla', 'none'));
const none = read(await mcp.proposeRoundHike({ tripId, name: 'R', start: START, distance_km: 9 }, ctx(userId)));
expect(none.why).toBe('no_valhalla');
// Without a Valhalla the search stops at its first question.
expect(route).toHaveBeenCalledTimes(1);
expect(propose).not.toHaveBeenCalled();
});
it('HIKE-WAYS-MCP-004: a trip the caller cannot see is not found', async () => {
const { tripId } = await tripOf();
const { user: stranger } = await makeUser(orm());
const answer = read(
await mcp.proposeRoundHike({ tripId, name: 'R', start: START, distance_km: 8 }, ctx(stranger.id)),
);
expect(answer.error).toBeDefined();
expect(route).not.toHaveBeenCalled();
});
});
const A = { lat: 47.5, lng: 11.1, name: 'Car park' };
const B = { lat: 47.52, lng: 11.1, name: 'Hut' };
const OWN: Array<[number, number]> = [
[47.5, 11.1],
[47.52, 11.1],
];
const OTHER: Array<[number, number]> = [
[47.5, 11.1],
[47.51, 11.12],
[47.52, 11.1],
];
describe('propose_hike_leg_way', () => {
it('HIKE-WAYS-MCP-005: the other way of a leg is the whole hike with the way held by a pin, beside the hike as it runs', async () => {
const { userId, tripId } = await tripOf();
alternatesOnFoot.mockResolvedValue([OWN, OTHER]);
const answer = read(
await mcp.proposeHikeLegWay(
{ tripId, name: 'Hike', waypoints: [A, B], leg: 1, include_geometry: true },
ctx(userId),
),
);
expect(answer.found).toBe(true);
expect(answer.leg_way).toEqual({ key: 'a', leg: 1, ways_found: 1, tour_id: null });
expect(answer.create_with).toEqual({ waypoints: [A, { lat: 47.51, lng: 11.12 }, B], round_trip: false });
expect(answer.current).toEqual({ distance_m: 10_400, ascent_m: 420, duration_minutes: 190 });
expect(answer.current_geometry).toHaveLength(2);
const [, from, to, costing, count] = alternatesOnFoot.mock.calls[0] ?? [];
expect([from, to, count]).toEqual([{ lat: A.lat, lng: A.lng }, { lat: B.lat, lng: B.lng }, 3]);
expect(costing).toMatchObject({ max_hiking_difficulty: 2 });
});
it('HIKE-WAYS-MCP-006: a router that knows only its own way, or a way it does not keep to, offers none', async () => {
const { userId, tripId } = await tripOf();
alternatesOnFoot.mockResolvedValue([OWN, OWN]);
const same = read(await mcp.proposeHikeLegWay({ tripId, name: 'H', waypoints: [A, B], leg: 1 }, ctx(userId)));
expect(same).toEqual({ found: false, way: 'a', ways_found: 0, why: 'none_found' });
alternatesOnFoot.mockResolvedValue([OWN, OTHER]);
route.mockRejectedValue(new Error('down'));
const held = read(
await mcp.proposeHikeLegWay(
{ tripId, name: 'H', waypoints: [A, B], leg: 1, max_hiking_difficulty: 3 },
ctx(userId),
),
);
expect(held.found).toBe(false);
alternatesOnFoot.mockRejectedValue(new RouteRefusal('no_way', 'none'));
const none = read(
await mcp.proposeHikeLegWay(
{ tripId, name: 'H', waypoints: [A, B], leg: 1, max_hiking_difficulty: 4 },
ctx(userId),
),
);
expect(none.why).toBe('no_way');
});
it('HIKE-WAYS-MCP-007: a leg the hike does not have is refused', async () => {
const { userId, tripId } = await tripOf();
const answer = read(await mcp.proposeHikeLegWay({ tripId, name: 'H', waypoints: [A, B], leg: 2 }, ctx(userId)));
expect(answer.error).toContain('no such leg');
expect(alternatesOnFoot).not.toHaveBeenCalled();
});
it('HIKE-WAYS-MCP-008: the way of a saved hike names that hike', async () => {
const { userId, tripId } = await tripOf();
const place = await makePlace(orm(), tripId, { name: 'Saved hike', lat: A.lat, lng: A.lng });
await makeTour(orm(), place.id);
alternatesOnFoot.mockResolvedValue([OWN, OTHER]);
const answer = read(
await mcp.proposeHikeLegWay({ tripId, name: 'H', waypoints: [A, B], leg: 1, tour_id: place.id }, ctx(userId)),
);
expect(answer.leg_way.tour_id).toBe(place.id);
});
});
@@ -588,3 +588,89 @@ describe('server Roadtrip router, a hike: its costing, heights and ways', () =>
await expect(setup().router.wayIds(1, line(3))).rejects.toThrow();
});
});
describe('server Roadtrip router: other ways on foot (RTE-02)', () => {
const trip = (points: Array<[number, number]>) => ({
legs: [{ shape: valhallaPolyline(points), summary: { length: 1.2, time: 900 } }],
});
it('ROUTER-WAYS-001: asks Valhalla once on foot under the hike’s costing, its own way first', async () => {
vi.mocked(safeFetchAdminConfigured).mockResolvedValueOnce(
new Response(
JSON.stringify({
trip: trip([
[47, 11],
[47.01, 11.01],
]),
alternates: [
{
trip: trip([
[47, 11],
[47.02, 11],
[47.01, 11.01],
]),
},
],
}),
),
);
const { router } = setup({ valhalla_base_url: 'https://valhalla.internal/' });
const ways = await router.alternatesOnFoot(
1,
{ lat: 47, lng: 11 },
{ lat: 47.01, lng: 11.01 },
{ max_hiking_difficulty: 3 },
3,
);
expect(ways).toEqual([
[
[47, 11],
[47.01, 11.01],
],
[
[47, 11],
[47.02, 11],
[47.01, 11.01],
],
]);
const [url, init] = vi.mocked(safeFetchAdminConfigured).mock.calls[0] ?? [];
expect(url).toBe('https://valhalla.internal/route');
expect(JSON.parse(String((init as RequestInit).body))).toMatchObject({
costing: 'pedestrian',
costing_options: { pedestrian: { max_hiking_difficulty: 3 } },
alternates: 3,
locations: [
{ lat: 47, lon: 11 },
{ lat: 47.01, lon: 11.01 },
],
});
});
it('ROUTER-WAYS-002: an answer without alternates is the one way; no Valhalla refuses before asking', async () => {
vi.mocked(safeFetchAdminConfigured).mockResolvedValueOnce(
new Response(
JSON.stringify({
trip: trip([
[47, 11],
[47.01, 11.01],
]),
}),
),
);
const ways = await setup().router.alternatesOnFoot(1, { lat: 47, lng: 11 }, { lat: 47.01, lng: 11.01 }, {}, 0);
expect(ways).toHaveLength(1);
const body = JSON.parse(String((vi.mocked(safeFetchAdminConfigured).mock.calls[0]?.[1] as RequestInit).body));
expect(body.alternates).toBeUndefined();
vi.mocked(safeFetchAdminConfigured).mockClear();
await expect(
setup({ routing_base_url: 'http://router.internal' }).router.alternatesOnFoot(
1,
{ lat: 47, lng: 11 },
{ lat: 47.01, lng: 11.01 },
{},
3,
),
).rejects.toMatchObject({ why: 'no_valhalla' });
expect(safeFetchAdminConfigured).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,196 @@
/**
* ToursWandererMcp: the trip-side wanderer routes over MCP. Each tool checks
* trip access and 'place_edit' as the REST guards do, then hands the same
* values to ToursWandererService, a stub in this suite (its own suite reads
* a stubbed instance); the trip and its members are seeded through the ORM
* factories over a snapshot test db.
*/
import { TripMembers } from '../../../src/db/entities/TripMembers.entity';
import type { McpContext } from '../../../src/nest-mcp';
import { getEntry, type ClassRef } from '../../../src/nest-mcp/metadata';
import { AddonsService } from '../../../src/nest/addons/addons.service';
import { McpToolGuardsService } from '../../../src/nest/mcp-shared/mcp-tool-guards.service';
import { ToursWandererMcp } from '../../../src/nest/tours/tours-wanderer.mcp';
import { ToursWandererService } from '../../../src/nest/tours/tours-wanderer.service';
import { ToursModule } from '../../../src/nest/tours/tours.module';
import { createSnapshotTestDb } from '../../helpers/db-mock';
import { insertRow } 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 { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
// WANDERER-MCP-001 to WANDERER-MCP-006
const db = createSnapshotTestDb();
const search = vi.fn<ToursWandererService['search']>();
const preview = vi.fn<ToursWandererService['preview']>();
const importTrail = vi.fn<ToursWandererService['import']>();
const checkSource = vi.fn<ToursWandererService['checkSource']>();
const hasTripPermission = vi.fn<McpToolGuardsService['hasTripPermission']>();
const isWandererAvailable = vi.fn<AddonsService['isWandererAvailable']>();
let t: TestModule;
let mcp: ToursWandererMcp;
const orm = () => t.get(MikroORM);
const TRAIL = {
id: 'trail-1',
name: 'Herzogstand',
description: null,
location: 'Kochel',
distanceM: 9000,
durationS: 14_400,
elevationGainM: 800,
elevationLossM: 800,
difficulty: 'moderate' as const,
public: true,
author: null,
line: [
[47.6, 11.3],
[47.62, 11.33],
] as Array<[number, number]>,
externalUrl: 'https://wanderer.example/trails/trail-1',
importedAs: [],
};
beforeAll(async () => {
t = await createTestModule({
db,
imports: [ToursModule],
overrides: [
{ provide: ToursWandererService, useValue: { search, preview, import: importTrail, checkSource } },
{ provide: McpToolGuardsService, useValue: { hasTripPermission } },
],
});
mcp = t.get(ToursWandererMcp);
vi.spyOn(t.get(AddonsService), 'isWandererAvailable').mockImplementation(isWandererAvailable);
});
beforeEach(() => {
resetTestDb(db);
hasTripPermission.mockReset().mockResolvedValue(true);
isWandererAvailable.mockReset().mockResolvedValue(true);
search.mockReset().mockResolvedValue({ trails: [TRAIL], total: 1, page: 1, pageSize: 20 });
preview.mockReset().mockResolvedValue({
trail: TRAIL,
distanceKm: 9.1,
elevationGainM: 812,
elevationLossM: 812,
hasElevation: true,
points: 900,
line: TRAIL.line,
contentHash: 'h'.repeat(32),
state: 'new',
snapshot: null,
changes: [],
});
importTrail.mockReset();
checkSource.mockReset();
});
afterAll(async () => {
await t.close();
db.close();
});
const ctx = (userId: number) => ({ userId }) as McpContext;
function read(result: { content: Array<{ type: string; text: string }>; isError?: boolean }) {
const text = result.content[0]?.text ?? '';
return result.isError ? { error: text } : JSON.parse(text);
}
async function tripOf() {
const { user } = await makeUser(orm());
const trip = await makeTrip(orm(), user.id);
return { userId: user.id, tripId: trip.id };
}
describe('wanderer over MCP', () => {
it('WANDERER-MCP-001: a search hands its words on and answers the trails without their lines', async () => {
const { userId, tripId } = await tripOf();
const answer = read(await mcp.searchTrails({ tripId, q: 'Herzogstand' }, ctx(userId)));
expect(search).toHaveBeenCalledWith(String(tripId), userId, { q: 'Herzogstand', page: 1, bbox: undefined });
expect(answer.trails[0]).toMatchObject({ id: 'trail-1', name: 'Herzogstand' });
expect(answer.trails[0].line).toBeUndefined();
expect(hasTripPermission).toHaveBeenCalledWith('place_edit', tripId, userId);
});
it('WANDERER-MCP-002: a preview answers its line for drawing only when asked, as line_geometry', async () => {
const { userId, tripId } = await tripOf();
const plain = read(await mcp.previewTrail({ tripId, trailId: 'trail-1' }, ctx(userId)));
expect(plain.line).toBeUndefined();
expect(plain.line_geometry).toBeUndefined();
expect(plain.trail.line).toBeUndefined();
expect(plain.contentHash).toBe('h'.repeat(32));
const drawn = read(await mcp.previewTrail({ tripId, trailId: 'trail-1', include_geometry: true }, ctx(userId)));
expect(drawn.line_geometry).toEqual(TRAIL.line);
});
it('WANDERER-MCP-003: the import and the source check run through the service with the caller’s rights', async () => {
const { userId, tripId } = await tripOf();
importTrail.mockResolvedValue({ tour: { place_id: 9 } } as never);
const imported = read(
await mcp.importTrail({ tripId, trailId: 'trail-1', contentHash: 'h'.repeat(32) }, ctx(userId)),
);
expect(imported.tour.place_id).toBe(9);
expect(importTrail).toHaveBeenCalledWith(String(tripId), userId, {
trailId: 'trail-1',
contentHash: 'h'.repeat(32),
});
checkSource.mockResolvedValue({
state: 'unchanged',
changes: [],
externalUpdated: null,
importedUpdated: null,
editedLocally: false,
reimport: null,
});
const checked = read(await mcp.checkSource({ tripId, placeId: 9 }, ctx(userId)));
expect(checked.state).toBe('unchanged');
expect(checkSource).toHaveBeenCalledWith(String(tripId), userId, '9');
});
it('WANDERER-MCP-004: without place editing permission nothing is read or written', async () => {
const { userId, tripId } = await tripOf();
hasTripPermission.mockResolvedValue(false);
expect(read(await mcp.searchTrails({ tripId }, ctx(userId))).error).toBeDefined();
expect(
read(await mcp.importTrail({ tripId, trailId: 'x', contentHash: 'h'.repeat(32) }, ctx(userId))).error,
).toBeDefined();
expect(search).not.toHaveBeenCalled();
expect(importTrail).not.toHaveBeenCalled();
});
it('WANDERER-MCP-005: a trip the caller cannot see is not found', async () => {
const { tripId } = await tripOf();
const { user: stranger } = await makeUser(orm());
expect(read(await mcp.previewTrail({ tripId, trailId: 'trail-1' }, ctx(stranger.id))).error).toBeDefined();
expect(preview).not.toHaveBeenCalled();
// A member who may not edit places is refused as well.
await insertRow(orm(), TripMembers, { trip: tripId, user: stranger.id });
hasTripPermission.mockResolvedValue(false);
expect(read(await mcp.previewTrail({ tripId, trailId: 'trail-1' }, ctx(stranger.id))).error).toBeDefined();
expect(preview).not.toHaveBeenCalled();
});
it('WANDERER-MCP-006: the tools are offered only while wanderer is allowed under Tours', async () => {
const methods = ['searchTrails', 'previewTrail', 'importTrail', 'checkSource'];
const options = methods.map((method) => {
const entry = getEntry(ToursWandererMcp as unknown as ClassRef, method);
if (!entry || entry.kind !== 'tool') throw new Error(`${method} is no MCP tool`);
return entry.options;
});
expect(options.map((tool) => [tool.name, tool.annotations?.readOnlyHint, tool.access])).toEqual([
['search_wanderer_trails', true, { group: 'trips', mode: 'read' }],
['preview_wanderer_trail', true, { group: 'trips', mode: 'read' }],
['import_wanderer_trail', false, { group: 'trips', mode: 'write' }],
['check_tour_source', true, { group: 'trips', mode: 'read' }],
]);
const gate = options[0]?.when;
expect(await gate?.(ctx(1), mcp)).toBe(true);
isWandererAvailable.mockResolvedValue(false);
expect(await gate?.(ctx(1), mcp)).toBe(false);
});
});