mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-02 17:26:24 +00:00
feat(assistant): the assistant opens outside a trip, as a home chat about all trips
A third scope, home, next to trip and journey: threads that name neither a trip nor a journey (the CHECK now only forbids both), reached under /api/assistant by their owner only. A home turn reads the user's trips through list_trips into a short card (under way, next, later, behind, undated), offers every read (a trip's on the id the model names, checked by the tool with the user's rights) and only the writes that take no trip or journey (atlas, vacation planner, collections, tour library, settings), all held as change cards. open_trip_chat answers with a card that goes on in that trip's own chat with the question waiting in its composer. On the desktop the window opens on the home chat outside a trip; its head lists the trips to switch into and a switched trip chat has the way back. On the phone the home chat opens full screen from the dashboard head and the dock's More list, and the card opens the trip with its chat. Both run on useAssistantHome.
This commit is contained in:
@@ -0,0 +1,345 @@
|
||||
/**
|
||||
* The assistant outside any one trip, end to end: the whole app (buildApp,
|
||||
* every global guard, the Zod pipe, the response contracts, the real MCP
|
||||
* registry) with an instance connection of kind `custom` pointing at a fake
|
||||
* OpenAI-compatible server on loopback, scripted per case.
|
||||
*
|
||||
* Covered: the gates before anything runs (the AI addon, auth, the body), a
|
||||
* home conversation of its own that the trip routes never reach and that
|
||||
* reaches no trip's, the home instructions and the card of the user's own
|
||||
* trips reaching the model with the reads and no trip write, a trip read by
|
||||
* its id with the user's rights, the way into a trip's chat shown as a card
|
||||
* for the user's own trip only, and a change that belongs to no trip (the
|
||||
* atlas) held and applied like any other, its undo reached only by its user.
|
||||
*/
|
||||
import { buildApp } from '../../src/bootstrap';
|
||||
import { AssistantThreads } from '../../src/db/entities/AssistantThreads.entity';
|
||||
import { VisitedCountries } from '../../src/db/entities/VisitedCountries.entity';
|
||||
import { countRows } from '../helpers/factories/rows';
|
||||
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 { 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 } from 'vitest';
|
||||
|
||||
// ── The fake provider ─────────────────────────────────────────────────────────
|
||||
|
||||
interface ChatBody {
|
||||
model: string;
|
||||
messages: Array<{ role: string; content: string | null; tool_call_id?: string }>;
|
||||
tools?: Array<{ function: { name: string; parameters: { properties?: Record<string, unknown> } } }>;
|
||||
}
|
||||
|
||||
type Step = (body: ChatBody) => { 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;
|
||||
}
|
||||
const body = JSON.parse(await readBody(req)) as ChatBody;
|
||||
provider.requests.push(body);
|
||||
const reply = (provider.script.shift() ?? say('Nothing more.'))(body);
|
||||
if (res.destroyed) return;
|
||||
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, 'atlas', true);
|
||||
const adminId = (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(adminId))
|
||||
.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 = [];
|
||||
});
|
||||
|
||||
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 | null, body: object): Promise<Answer> {
|
||||
const base = request(nestApp.getHttpServer()).post(path);
|
||||
const req = (userId === null ? base : base.set('Cookie', sessionCookie(userId))).send(body);
|
||||
const res = await req.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));
|
||||
return {
|
||||
status: res.status,
|
||||
chunks: events.filter((event) => event !== '[DONE]').map((event) => JSON.parse(event) as UiStreamChunk),
|
||||
json: null,
|
||||
};
|
||||
}
|
||||
|
||||
function get(path: string, userId: number) {
|
||||
return request(nestApp.getHttpServer()).get(path).set('Cookie', sessionCookie(userId));
|
||||
}
|
||||
|
||||
const ofType = <T extends UiStreamChunk['type']>(chunks: UiStreamChunk[], type: T) =>
|
||||
chunks.filter((chunk): chunk is Extract<UiStreamChunk, { type: T }> => chunk.type === type);
|
||||
|
||||
const BASE = '/api/assistant';
|
||||
|
||||
/** A user with two trips of their own, one dated and one not. */
|
||||
async function ownerWithTrips() {
|
||||
const { user } = await makeUser(orm);
|
||||
const next = await makeTrip(orm, user.id, { title: 'Kyoto', start_date: '2099-04-01', end_date: '2099-04-08' });
|
||||
const later = await makeTrip(orm, user.id, { title: 'Someday Patagonia' });
|
||||
return { userId: user.id, nextId: next.id, laterId: later.id };
|
||||
}
|
||||
|
||||
const toolNames = (body: ChatBody) => (body.tools ?? []).map((tool) => tool.function.name);
|
||||
|
||||
const threadOf = (answer: Answer) => ofType(answer.chunks, 'data-trek-thread')[0].data.threadId;
|
||||
|
||||
// ── Cases ────────────────────────────────────────────────────────────────────
|
||||
|
||||
describe('Home assistant e2e', () => {
|
||||
it('ASTHE2E-001: the AI addon, auth and the body come before anything else', async () => {
|
||||
const h = await ownerWithTrips();
|
||||
await setAddonEnabled(orm, 'ai_assistant', false);
|
||||
try {
|
||||
expect((await get(`${BASE}/threads`, h.userId)).status).toBe(404);
|
||||
} finally {
|
||||
await setAddonEnabled(orm, 'ai_assistant', true);
|
||||
}
|
||||
expect((await request(nestApp.getHttpServer()).get(`${BASE}/threads`)).status).toBe(401);
|
||||
expect((await post(`${BASE}/chat`, null, { ...CTX, threadId: null, text: 'Hi' })).status).toBe(401);
|
||||
expect((await post(`${BASE}/chat`, h.userId, { ...CTX, threadId: null, text: '' })).status).toBe(400);
|
||||
expect((await get(`${BASE}/threads/abc`, h.userId)).status).toBe(404);
|
||||
expect(provider.requests).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('ASTHE2E-002: a home conversation reads the user trips and offers the reads, the home steps and no trip write', async () => {
|
||||
const h = await ownerWithTrips();
|
||||
const { user: other } = await makeUser(orm);
|
||||
await makeTrip(orm, other.id, { title: 'Not yours' });
|
||||
provider.script = [say('Kyoto comes next.')];
|
||||
const turn = await post(`${BASE}/chat`, h.userId, { ...CTX, threadId: null, text: 'What is next?' });
|
||||
expect(turn.status).toBe(200);
|
||||
const threadId = threadOf(turn);
|
||||
expect(await countRows(orm, AssistantThreads, { id: threadId, trip: null, journey: null })).toBe(1);
|
||||
|
||||
const sent = JSON.stringify(provider.requests[0].messages);
|
||||
expect(sent).toContain('not about one trip');
|
||||
expect(sent).toContain('<home_card>');
|
||||
expect(sent).toContain(`${h.nextId} | Kyoto | next, 2099-04-01 to 2099-04-08`);
|
||||
expect(sent).toContain(`${h.laterId} | Someday Patagonia | no dates`);
|
||||
expect(sent).not.toContain('Not yours');
|
||||
expect(sent).not.toContain('<trip_card>');
|
||||
const names = toolNames(provider.requests[0]);
|
||||
expect(names).toEqual(expect.arrayContaining(['list_trips', 'get_trip_summary', 'open_trip_chat']));
|
||||
expect(names).toEqual(expect.arrayContaining(['use_addon_tools', 'suggest_follow_ups']));
|
||||
for (const name of ['create_place', 'update_trip', 'remember_for_trip', 'get_book', 'delete_trip']) {
|
||||
expect(names, name).not.toContain(name);
|
||||
}
|
||||
const summary = provider.requests[0].tools?.find((tool) => tool.function.name === 'get_trip_summary');
|
||||
expect(Object.keys(summary?.function.parameters.properties ?? {})).toContain('tripId');
|
||||
|
||||
const list = await get(`${BASE}/threads`, h.userId);
|
||||
expect(list.body.threads).toEqual([expect.objectContaining({ id: threadId, title: 'What is next?' })]);
|
||||
expect((await get(`${BASE}/threads`, other.id)).body.threads).toEqual([]);
|
||||
expect((await get(`${BASE}/threads/${threadId}`, other.id)).status).toBe(404);
|
||||
});
|
||||
|
||||
it('ASTHE2E-003: a trip is read by its id with the user rights, and another user trip is refused', async () => {
|
||||
const h = await ownerWithTrips();
|
||||
const { user: other } = await makeUser(orm);
|
||||
const foreign = await makeTrip(orm, other.id, { title: 'Theirs' });
|
||||
provider.script = [
|
||||
callTool('call_own', 'get_trip_summary', { tripId: h.nextId }),
|
||||
callTool('call_foreign', 'get_trip_summary', { tripId: foreign.id }),
|
||||
say('Done.'),
|
||||
];
|
||||
const turn = await post(`${BASE}/chat`, h.userId, { ...CTX, threadId: null, text: 'Tell me about both' });
|
||||
expect(turn.status).toBe(200);
|
||||
const outputs = ofType(turn.chunks, 'tool-output-available');
|
||||
expect(outputs.map((chunk) => chunk.toolCallId)).toEqual(['call_own']);
|
||||
expect(JSON.stringify(outputs[0].output)).toContain('Kyoto');
|
||||
expect(ofType(turn.chunks, 'tool-output-error').map((chunk) => chunk.toolCallId)).toEqual(['call_foreign']);
|
||||
expect(ofType(turn.chunks, 'tool-approval-request')).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("ASTHE2E-004: the way into a trip's chat shows a card for the user's own trip only", async () => {
|
||||
const h = await ownerWithTrips();
|
||||
const { user: other } = await makeUser(orm);
|
||||
const foreign = await makeTrip(orm, other.id, { title: 'Theirs' });
|
||||
provider.script = [
|
||||
callTool('call_open', 'open_trip_chat', { tripId: h.nextId, question: 'What is still missing?' }),
|
||||
callTool('call_theirs', 'open_trip_chat', { tripId: foreign.id }),
|
||||
say('Go on in the trip.'),
|
||||
];
|
||||
const turn = await post(`${BASE}/chat`, h.userId, { ...CTX, threadId: null, text: 'Plan Kyoto with me' });
|
||||
expect(turn.status).toBe(200);
|
||||
expect(ofType(turn.chunks, 'data-trek-card')).toEqual([
|
||||
{
|
||||
type: 'data-trek-card',
|
||||
data: {
|
||||
toolCallId: 'call_open',
|
||||
card: {
|
||||
kind: 'tripChat',
|
||||
trip: {
|
||||
id: h.nextId,
|
||||
title: 'Kyoto',
|
||||
startDate: '2099-04-01',
|
||||
endDate: '2099-04-08',
|
||||
phase: 'next',
|
||||
placeCount: 0,
|
||||
},
|
||||
question: 'What is still missing?',
|
||||
},
|
||||
},
|
||||
},
|
||||
]);
|
||||
expect(ofType(turn.chunks, 'tool-output-error').map((chunk) => chunk.toolCallId)).toEqual(['call_theirs']);
|
||||
const shown = await get(`${BASE}/threads/${threadOf(turn)}`, h.userId);
|
||||
expect(JSON.stringify(shown.body.messages)).toContain('"kind":"tripChat"');
|
||||
});
|
||||
|
||||
it('ASTHE2E-005: a change that belongs to no trip is held, applied with the user rights, its undo only theirs', async () => {
|
||||
const h = await ownerWithTrips();
|
||||
provider.script = [
|
||||
callTool('call_load', 'use_addon_tools', { groups: ['atlas'] }),
|
||||
callTool('call_mark', 'mark_country_visited', { country_code: 'JP' }),
|
||||
];
|
||||
const turn = await post(`${BASE}/chat`, h.userId, { ...CTX, threadId: null, text: 'I was in Japan' });
|
||||
expect(turn.chunks.at(-1)).toEqual({ type: 'finish', finishReason: 'tool-calls' });
|
||||
const [held] = ofType(turn.chunks, 'tool-approval-request');
|
||||
expect(held).toBeDefined();
|
||||
expect(await countRows(orm, VisitedCountries, { user: h.userId, country_code: 'JP' })).toBe(0);
|
||||
|
||||
provider.script = [say('Japan is in your atlas.')];
|
||||
const decided = await post(`${BASE}/threads/${threadOf(turn)}/decisions`, h.userId, {
|
||||
...CTX,
|
||||
decisions: [{ toolCallId: held.toolCallId, approved: true }],
|
||||
});
|
||||
expect(decided.status).toBe(200);
|
||||
expect(ofType(decided.chunks, 'tool-output-available')).toHaveLength(1);
|
||||
expect(await countRows(orm, VisitedCountries, { user: h.userId, country_code: 'JP' })).toBe(1);
|
||||
|
||||
const { user: other } = await makeUser(orm);
|
||||
const foreignUndo = await request(nestApp.getHttpServer())
|
||||
.post(`${BASE}/tool-calls/${held.toolCallId}/undo`)
|
||||
.set('Cookie', sessionCookie(other.id))
|
||||
.send({});
|
||||
expect(foreignUndo.status).toBe(404);
|
||||
});
|
||||
|
||||
it('ASTHE2E-006: a home conversation and a trip conversation never reach each other', async () => {
|
||||
const h = await ownerWithTrips();
|
||||
const tripBase = `/api/trips/${h.nextId}/assistant`;
|
||||
provider.script = [say('home'), say('trip')];
|
||||
const atHome = await post(`${BASE}/chat`, h.userId, { ...CTX, threadId: null, text: 'Across my trips' });
|
||||
const inTrip = await post(`${tripBase}/chat`, h.userId, { ...CTX, threadId: null, text: 'About Kyoto' });
|
||||
const homeThread = threadOf(atHome);
|
||||
const tripThread = threadOf(inTrip);
|
||||
|
||||
const ids = (res: { body: { threads: Array<{ id: number }> } }) => res.body.threads.map((t) => t.id);
|
||||
expect(ids(await get(`${BASE}/threads`, h.userId))).toEqual([homeThread]);
|
||||
expect(ids(await get(`${tripBase}/threads`, h.userId))).toEqual([tripThread]);
|
||||
expect((await get(`${BASE}/threads/${tripThread}`, h.userId)).status).toBe(404);
|
||||
expect((await get(`${tripBase}/threads/${homeThread}`, h.userId)).status).toBe(404);
|
||||
const continued = await post(`${BASE}/chat`, h.userId, { ...CTX, threadId: tripThread, text: 'Go on' });
|
||||
expect(continued).toMatchObject({ status: 404, json: { code: 'not_found' } });
|
||||
|
||||
const removed = await request(nestApp.getHttpServer())
|
||||
.delete(`${BASE}/threads/${homeThread}`)
|
||||
.set('Cookie', sessionCookie(h.userId));
|
||||
expect(removed.status).toBe(200);
|
||||
expect(await countRows(orm, AssistantThreads, { id: homeThread })).toBe(0);
|
||||
expect(await countRows(orm, AssistantThreads, { id: tripThread })).toBe(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,148 @@
|
||||
/**
|
||||
* `Migration20200101046280_an_assistant_conversation_can_be_about_no_one_trip`:
|
||||
* `assistant_threads` is rebuilt so a thread of the home chat can name neither
|
||||
* a trip nor a journey, with `assistant_messages` and `assistant_tool_calls`
|
||||
* rebuilt beside it, without losing a row of any of the three; a thread still
|
||||
* never names both, and each goes with what it is about.
|
||||
*/
|
||||
import { createMigrationOrm, migrateTo, pendingNames, rawExec, rawQuery } from '../../helpers/migration-step';
|
||||
import type { MikroORM } from '@mikro-orm/sqlite';
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
const TARGET = 'Migration20200101046280_an_assistant_conversation_can_be_about_no_one_trip';
|
||||
|
||||
async function ormBeforeTarget(): Promise<MikroORM> {
|
||||
const orm = await createMigrationOrm();
|
||||
const names = await pendingNames(orm);
|
||||
const index = names.indexOf(TARGET);
|
||||
expect(index).toBeGreaterThan(0);
|
||||
await migrateTo(orm, names[index - 1]);
|
||||
return orm;
|
||||
}
|
||||
|
||||
async function seed(orm: MikroORM): Promise<void> {
|
||||
await rawExec(orm, "INSERT INTO users (id, username, email, password_hash) VALUES (1, 'owner', 'owner@test', 'x')");
|
||||
await rawExec(orm, "INSERT INTO trips (id, user_id, title) VALUES (10, 1, 'Kyoto')");
|
||||
await rawExec(
|
||||
orm,
|
||||
"INSERT INTO journeys (id, user_id, title, created_at, updated_at) VALUES (20, 1, 'Portugal', 0, 0)",
|
||||
);
|
||||
await rawExec(
|
||||
orm,
|
||||
`INSERT INTO assistant_threads (id, user_id, trip_id, title, created_at, last_message_at)
|
||||
VALUES (1, 1, 10, 'Kyoto day', '2026-10-20 10:00:00', '2026-10-20 11:00:00')`,
|
||||
);
|
||||
await rawExec(
|
||||
orm,
|
||||
`INSERT INTO assistant_threads (id, user_id, journey_id, title, created_at, last_message_at)
|
||||
VALUES (2, 1, 20, 'Cover', '2026-10-21 10:00:00', '2026-10-21 11:00:00')`,
|
||||
);
|
||||
await rawExec(
|
||||
orm,
|
||||
`INSERT INTO assistant_messages (id, thread_id, role, parts, provider_state, status, model, created_at)
|
||||
VALUES (5, 1, 'assistant', '[]', '{"items":[]}', 'awaiting_approval', 'claude', '2026-10-20 10:00:00')`,
|
||||
);
|
||||
await rawExec(
|
||||
orm,
|
||||
`INSERT INTO assistant_tool_calls (id, thread_id, message_id, provider_call_id, tool_name, args, preview, state,
|
||||
result, undo_until, created_at, decided_at)
|
||||
VALUES ('c1', 1, 5, 'toolu_1', 'create_place', '{"name":"A"}', '{}', 'executed', '{"place":{"id":3}}',
|
||||
'2026-10-20 10:15:00', '2026-10-20 10:00:00', '2026-10-20 10:01:00')`,
|
||||
);
|
||||
}
|
||||
|
||||
describe('Assistant home threads migration', () => {
|
||||
it('HTHRMIG-001: keeps every trip and journey thread, message and proposed change as it was', async () => {
|
||||
const orm = await ormBeforeTarget();
|
||||
try {
|
||||
await seed(orm);
|
||||
await migrateTo(orm, TARGET);
|
||||
|
||||
expect(await rawQuery(orm, 'SELECT * FROM assistant_threads ORDER BY id')).toEqual([
|
||||
{
|
||||
id: 1,
|
||||
user_id: 1,
|
||||
trip_id: 10,
|
||||
journey_id: null,
|
||||
title: 'Kyoto day',
|
||||
created_at: '2026-10-20 10:00:00',
|
||||
last_message_at: '2026-10-20 11:00:00',
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
user_id: 1,
|
||||
trip_id: null,
|
||||
journey_id: 20,
|
||||
title: 'Cover',
|
||||
created_at: '2026-10-21 10:00:00',
|
||||
last_message_at: '2026-10-21 11:00:00',
|
||||
},
|
||||
]);
|
||||
expect(await rawQuery(orm, 'SELECT id, thread_id, status, provider_state FROM assistant_messages')).toEqual([
|
||||
{ id: 5, thread_id: 1, status: 'awaiting_approval', provider_state: '{"items":[]}' },
|
||||
]);
|
||||
expect(
|
||||
await rawQuery(orm, 'SELECT id, thread_id, message_id, state, undo_until FROM assistant_tool_calls'),
|
||||
).toEqual([{ id: 'c1', thread_id: 1, message_id: 5, state: 'executed', undo_until: '2026-10-20 10:15:00' }]);
|
||||
expect(await rawQuery(orm, 'SELECT * FROM pragma_foreign_key_check')).toEqual([]);
|
||||
} finally {
|
||||
await orm.close(true);
|
||||
}
|
||||
}, 30000);
|
||||
|
||||
it('HTHRMIG-002: a thread may name neither a trip nor a journey, still never both', async () => {
|
||||
const orm = await ormBeforeTarget();
|
||||
try {
|
||||
await seed(orm);
|
||||
await migrateTo(orm, TARGET);
|
||||
|
||||
await rawExec(orm, "INSERT INTO assistant_threads (id, user_id, title) VALUES (3, 1, 'Home')");
|
||||
expect(await rawQuery(orm, 'SELECT trip_id, journey_id FROM assistant_threads WHERE id = 3')).toEqual([
|
||||
{ trip_id: null, journey_id: null },
|
||||
]);
|
||||
await expect(
|
||||
rawExec(orm, "INSERT INTO assistant_threads (user_id, trip_id, journey_id, title) VALUES (1, 10, 20, 'Both')"),
|
||||
).rejects.toThrow(/CHECK/);
|
||||
await expect(
|
||||
rawExec(orm, "INSERT INTO assistant_threads (user_id, trip_id, title) VALUES (1, 999, 'Nowhere')"),
|
||||
).rejects.toThrow(/FOREIGN KEY/);
|
||||
} finally {
|
||||
await orm.close(true);
|
||||
}
|
||||
}, 30000);
|
||||
|
||||
it('HTHRMIG-003: the keys point at the new tables, the indexes come back, and each thread goes with what it is about', async () => {
|
||||
const orm = await ormBeforeTarget();
|
||||
try {
|
||||
await seed(orm);
|
||||
await migrateTo(orm, TARGET);
|
||||
await rawExec(orm, "INSERT INTO assistant_threads (id, user_id, title) VALUES (3, 1, 'Home')");
|
||||
|
||||
const parents = await rawQuery<{ table: string }>(
|
||||
orm,
|
||||
`SELECT "table" FROM pragma_foreign_key_list('assistant_tool_calls') ORDER BY "table"`,
|
||||
);
|
||||
expect(parents.map((row) => row.table)).toEqual(['assistant_messages', 'assistant_threads']);
|
||||
const indexes = await rawQuery<{ name: string }>(
|
||||
orm,
|
||||
"SELECT name FROM sqlite_master WHERE type = 'index' AND tbl_name = 'assistant_threads' AND sql IS NOT NULL ORDER BY name",
|
||||
);
|
||||
expect(indexes.map((row) => row.name)).toEqual([
|
||||
'idx_assistant_threads_journey',
|
||||
'idx_assistant_threads_trip',
|
||||
'idx_assistant_threads_user_journey',
|
||||
'idx_assistant_threads_user_trip',
|
||||
]);
|
||||
|
||||
await rawExec(orm, 'DELETE FROM trips WHERE id = 10');
|
||||
await rawExec(orm, 'DELETE FROM journeys WHERE id = 20');
|
||||
expect(await rawQuery(orm, 'SELECT id FROM assistant_threads')).toEqual([{ id: 3 }]);
|
||||
expect(await rawQuery(orm, 'SELECT COUNT(*) AS n FROM assistant_messages')).toEqual([{ n: 0 }]);
|
||||
await rawExec(orm, 'DELETE FROM users WHERE id = 1');
|
||||
expect(await rawQuery(orm, 'SELECT COUNT(*) AS n FROM assistant_threads')).toEqual([{ n: 0 }]);
|
||||
} finally {
|
||||
await orm.close(true);
|
||||
}
|
||||
}, 30000);
|
||||
});
|
||||
@@ -95,6 +95,7 @@ const UNNUMBERED = [
|
||||
'Migration20200101046250_an_assistant_conversation_can_be_about_a_journey',
|
||||
'Migration20200101046260_a_book_keeps_its_last_revisions',
|
||||
'Migration20200101046270_a_photo_knows_its_colours_and_calm_areas',
|
||||
'Migration20200101046280_an_assistant_conversation_can_be_about_no_one_trip',
|
||||
];
|
||||
// The last step the positional runner ever had; planLegacyBaseline refuses a
|
||||
// schema_version past it.
|
||||
|
||||
@@ -218,6 +218,78 @@ describe('journey threads', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('home threads', () => {
|
||||
it('ASTREPO-007: a home thread is found, listed and deleted only by its owner at home, never on a trip or a journey', async () => {
|
||||
const { userId, tripId } = await ownerWithTrip();
|
||||
const journey = await makeJourney(t, userId);
|
||||
const { user: other } = await makeUser(t);
|
||||
const older = await threads.createHomeThread(userId, 'Next trip', AT);
|
||||
const newer = await threads.createHomeThread(userId, 'Atlas', AT);
|
||||
const onTrip = await threads.createThread(userId, tripId, 'Kyoto', AT);
|
||||
const onJourney = await threads.createJourneyThread(userId, journey.id, 'Book', AT);
|
||||
await threads.createHomeThread(other.id, 'Theirs', AT);
|
||||
await threads.touch(older, LATER);
|
||||
|
||||
expect((await threads.listRecentAtHome(userId, 20)).map((row) => row.id)).toEqual([older, newer]);
|
||||
expect(await threads.listRecentAtHome(userId, 1)).toHaveLength(1);
|
||||
expect((await threads.listRecent(userId, tripId, 20)).map((row) => row.id)).toEqual([onTrip]);
|
||||
expect(await threads.findOwnedAtHome(older, userId)).toMatchObject({
|
||||
title: 'Next trip',
|
||||
trip_id: null,
|
||||
journey_id: null,
|
||||
last_message_at: LATER,
|
||||
});
|
||||
expect(await threads.findOwnedAtHome(older, other.id)).toBeNull();
|
||||
expect(await threads.findOwnedAtHome(onTrip, userId)).toBeNull();
|
||||
expect(await threads.findOwnedAtHome(onJourney, userId)).toBeNull();
|
||||
expect(await threads.findOwned(older, userId, tripId)).toBeNull();
|
||||
expect(await threads.findOwnedOnJourney(older, userId, journey.id)).toBeNull();
|
||||
|
||||
expect(await threads.deleteOwnedAtHome(older, other.id)).toBe(false);
|
||||
expect(await threads.deleteOwnedAtHome(onTrip, userId)).toBe(false);
|
||||
expect(await threads.deleteOwned(older, userId, tripId)).toBe(false);
|
||||
expect(await threads.deleteOwnedAtHome(older, userId)).toBe(true);
|
||||
expect(await threads.findOwnedAtHome(older, userId)).toBeNull();
|
||||
});
|
||||
|
||||
it('ASTREPO-008: retention keeps a home thread while it is in use and its user stays', async () => {
|
||||
const { user } = await makeUser(t);
|
||||
const kept = await threads.createHomeThread(user.id, 'Kept', AT);
|
||||
const idle = await threads.createHomeThread(user.id, 'Idle', '2026-01-01 00:00:00');
|
||||
|
||||
expect(await threads.deleteWithoutAccess()).toBe(0);
|
||||
expect(await threads.deleteIdleBefore('2026-06-01 00:00:00')).toBe(1);
|
||||
expect(await threads.findOwnedAtHome(kept, user.id)).not.toBeNull();
|
||||
expect(await threads.findOwnedAtHome(idle, user.id)).toBeNull();
|
||||
|
||||
await deleteRows(t, Users, { id: user.id });
|
||||
expect(await countRows(t, AssistantThreads, { id: kept })).toBe(0);
|
||||
});
|
||||
|
||||
it('ASTREPO-009: a change of a home thread is found only through its own user, never on a trip or a journey', async () => {
|
||||
const { userId, tripId } = await ownerWithTrip();
|
||||
const { user: other } = await makeUser(t);
|
||||
const threadId = await threads.createHomeThread(userId, 'Atlas', AT);
|
||||
const messageId = await messages.append({
|
||||
threadId,
|
||||
role: 'assistant',
|
||||
parts: '[]',
|
||||
providerState: null,
|
||||
status: 'awaiting_approval',
|
||||
model: 'claude',
|
||||
createdAt: AT,
|
||||
});
|
||||
await calls.insertProposals([proposal('h1', threadId, messageId)]);
|
||||
expect(await calls.findOwnedAtHome('h1', userId)).toMatchObject({ id: 'h1', thread_id: threadId });
|
||||
expect(await calls.findOwnedAtHome('h1', other.id)).toBeNull();
|
||||
expect(await calls.findOwned('h1', userId, tripId)).toBeNull();
|
||||
|
||||
const { threadId: tripThread, messageId: tripMessage, userId: tripUser } = await threadWithMessage();
|
||||
await calls.insertProposals([proposal('t1', tripThread, tripMessage)]);
|
||||
expect(await calls.findOwnedAtHome('t1', tripUser)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('messages', () => {
|
||||
it('ASTREPO-010: the latest messages come oldest first, and a message changes its parts and status', async () => {
|
||||
const { threadId, messageId } = await threadWithMessage();
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
/**
|
||||
* The assistant's tool session for the home chat, over the container's real
|
||||
* MCP registry: it reads any trip the user may read, on the id the model
|
||||
* passes, and holds no write that takes a trip or a journey; the writes that
|
||||
* belong to no trip (the atlas, collections) come with their groups; the way
|
||||
* into a trip's chat answers from the user's own trips only; an undo's
|
||||
* session holds its target.
|
||||
*/
|
||||
import { OPEN_TRIP_CHAT_TOOL } from '../../../../src/nest/assistant/assistant-home';
|
||||
import { USE_TOOLS_TOOL } from '../../../../src/nest/assistant/assistant-tool-offer';
|
||||
import { AssistantToolsService } from '../../../../src/nest/assistant/assistant-tools.service';
|
||||
import { setAddonEnabled } from '../../../helpers/factories/settings';
|
||||
import { makeTrip } from '../../../helpers/factories/trips';
|
||||
import { makeUser } from '../../../helpers/factories/users';
|
||||
import { FakeRealtimeService } from '../../../helpers/fake-realtime';
|
||||
import { bootTestApp } from '../../../helpers/test-app';
|
||||
import { MikroORM } from '@mikro-orm/core';
|
||||
import { ASSISTANT_FOLLOW_UPS_TOOL } from '@trek/shared';
|
||||
|
||||
import { beforeAll, describe, expect, it } from 'vitest';
|
||||
|
||||
const realtime = new FakeRealtimeService();
|
||||
let orm: MikroORM;
|
||||
let tools: AssistantToolsService;
|
||||
|
||||
beforeAll(async () => {
|
||||
const app = await bootTestApp(realtime);
|
||||
orm = app.get(MikroORM);
|
||||
tools = app.get(AssistantToolsService);
|
||||
await setAddonEnabled(orm, 'atlas', true);
|
||||
await setAddonEnabled(orm, 'collections', true);
|
||||
});
|
||||
|
||||
async function ownerWithTrip() {
|
||||
const { user } = await makeUser(orm);
|
||||
const trip = await makeTrip(orm, user.id, { title: 'Kyoto' });
|
||||
return { userId: user.id, tripId: trip.id };
|
||||
}
|
||||
|
||||
describe('a home tool session', () => {
|
||||
it('ASTHSES-001: offers the trip reads with their trip id, no trip write, and the server steps of the home chat', async () => {
|
||||
const { userId } = await ownerWithTrip();
|
||||
const session = await tools.openHome(userId);
|
||||
try {
|
||||
const specs = session.specs();
|
||||
const names = specs.map((spec) => spec.name);
|
||||
expect(names).toEqual(expect.arrayContaining(['list_trips', 'get_trip_summary', 'list_places']));
|
||||
expect(names).toEqual(expect.arrayContaining([OPEN_TRIP_CHAT_TOOL, USE_TOOLS_TOOL, ASSISTANT_FOLLOW_UPS_TOOL]));
|
||||
for (const name of ['create_place', 'update_trip', 'create_budget_item', 'remember_for_trip', 'get_book']) {
|
||||
expect(names, name).not.toContain(name);
|
||||
}
|
||||
// Nothing is pinned: the model names the trip it reads.
|
||||
const summary = specs.find((spec) => spec.name === 'get_trip_summary');
|
||||
expect(Object.keys((summary?.parameters.properties as Record<string, unknown>) ?? {})).toContain('tripId');
|
||||
expect(session.kindOf('get_trip_summary')).toBe('read');
|
||||
expect(session.kindOf(OPEN_TRIP_CHAT_TOOL)).toBe('read');
|
||||
expect(session.kindOf(USE_TOOLS_TOOL)).toBe('read');
|
||||
expect(session.kindOf('remember_for_trip')).toBeNull();
|
||||
expect(session.kindOf('create_place')).toBeNull();
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
it('ASTHSES-002: a loaded group brings its writes that belong to no trip, held as changes', async () => {
|
||||
const { userId } = await ownerWithTrip();
|
||||
const session = await tools.openHome(userId);
|
||||
try {
|
||||
expect(session.specs().map((spec) => spec.name)).not.toContain('mark_country_visited');
|
||||
const loaded = await session.call(USE_TOOLS_TOOL, { groups: ['atlas', 'collections'] });
|
||||
expect(loaded).toMatchObject({ ok: true, value: { loaded: ['atlas', 'collections'] } });
|
||||
const names = session.specs().map((spec) => spec.name);
|
||||
expect(names).toEqual(expect.arrayContaining(['mark_country_visited', 'create_collection']));
|
||||
expect(names).not.toContain('copy_collection_places_to_trip');
|
||||
expect(session.kindOf('mark_country_visited')).toBe('write');
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
it('ASTHSES-003: reads a trip of the user by its id, and only with the user rights', async () => {
|
||||
const { userId, tripId } = await ownerWithTrip();
|
||||
const { user: stranger } = await makeUser(orm);
|
||||
const own = await tools.openHome(userId);
|
||||
const theirs = await tools.openHome(stranger.id);
|
||||
try {
|
||||
expect(own.pinArgs('get_trip_summary', { tripId })).toEqual({ args: { tripId } });
|
||||
expect(await own.call('get_trip_summary', { tripId })).toMatchObject({
|
||||
ok: true,
|
||||
value: { trip: { id: tripId, title: 'Kyoto' } },
|
||||
});
|
||||
expect((await theirs.call('get_trip_summary', { tripId })).ok).toBe(false);
|
||||
} finally {
|
||||
await own.close();
|
||||
await theirs.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("ASTHSES-004: offers a trip's chat only for a trip of the user's", async () => {
|
||||
const { userId, tripId } = await ownerWithTrip();
|
||||
const { user: stranger } = await makeUser(orm);
|
||||
const own = await tools.openHome(userId);
|
||||
const theirs = await tools.openHome(stranger.id);
|
||||
try {
|
||||
expect(await own.call(OPEN_TRIP_CHAT_TOOL, { tripId, question: ' What is missing? ' })).toMatchObject({
|
||||
ok: true,
|
||||
value: { trip: { id: tripId, title: 'Kyoto', phase: 'undated' }, question: 'What is missing?' },
|
||||
});
|
||||
expect(await theirs.call(OPEN_TRIP_CHAT_TOOL, { tripId })).toMatchObject({ ok: false });
|
||||
} finally {
|
||||
await own.close();
|
||||
await theirs.close();
|
||||
}
|
||||
});
|
||||
|
||||
it('ASTHSES-005: an undo session holds its target and nothing of the home steps', async () => {
|
||||
const { userId } = await ownerWithTrip();
|
||||
const session = await tools.openHome(userId, new Set(['delete_collection']));
|
||||
try {
|
||||
expect(session.specs().map((spec) => spec.name)).toEqual(['delete_collection']);
|
||||
expect(session.kindOf(OPEN_TRIP_CHAT_TOOL)).toBeNull();
|
||||
expect(session.kindOf(USE_TOOLS_TOOL)).toBeNull();
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,196 @@
|
||||
/**
|
||||
* The home chat in its pure parts: the user's trips as the home card reads
|
||||
* them (where each stands, which comes next, how many are left out), the
|
||||
* context and instructions of a home turn, the step that offers a trip's own
|
||||
* chat and the card it shows, and which tools the home chat keeps.
|
||||
*/
|
||||
import { emptyTripCard } from '../../../../src/nest/assistant/assistant-book-context';
|
||||
import {
|
||||
homeCardFrom,
|
||||
homeCardOf,
|
||||
homePrompt,
|
||||
homeTurnContext,
|
||||
OPEN_TRIP_CHAT_SPEC,
|
||||
OPEN_TRIP_CHAT_TOOL,
|
||||
openTripChat,
|
||||
phaseOf,
|
||||
renderHomeCard,
|
||||
tripsOf,
|
||||
} from '../../../../src/nest/assistant/assistant-home';
|
||||
import { HOME_USE_TOOLS_SPEC, keptAtHome, USE_TOOLS_SPEC } from '../../../../src/nest/assistant/assistant-tool-offer';
|
||||
import { tripChatAnswer } from '../../../../src/nest/assistant/cards/home';
|
||||
import { answerCardOf } from '../../../../src/nest/assistant/cards/registry';
|
||||
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const TODAY = '2026-10-23';
|
||||
|
||||
function row(id: number, title: string, start: string | null, end: string | null, extra: Record<string, unknown> = {}) {
|
||||
return { id, title, start_date: start, end_date: end, place_count: 4, shared_count: 0, is_owner: 1, ...extra };
|
||||
}
|
||||
|
||||
const LISTED = {
|
||||
trips: [
|
||||
row(1, 'Lisbon', '2026-10-20', '2026-10-27'),
|
||||
row(2, 'Kyoto', '2026-12-01', '2026-12-10', { shared_count: 2 }),
|
||||
row(3, 'Oslo', '2026-11-05', '2026-11-08'),
|
||||
row(4, 'Rome', '2026-05-01', '2026-05-07', { is_archived: 1 }),
|
||||
row(5, 'Someday', null, null, { place_count: null }),
|
||||
row(6, 'Porto', '2025-09-01', '2025-09-04', { is_owner: 0 }),
|
||||
],
|
||||
};
|
||||
|
||||
describe('the trips of the home card', () => {
|
||||
it('ASTHOME-001: tells where a trip stands on a day, with one date standing for both', () => {
|
||||
expect(phaseOf('2026-10-20', '2026-10-27', TODAY)).toBe('now');
|
||||
expect(phaseOf('2026-10-23', null, TODAY)).toBe('now');
|
||||
expect(phaseOf('2026-11-01', '2026-11-03', TODAY)).toBe('upcoming');
|
||||
expect(phaseOf(null, '2026-01-03', TODAY)).toBe('past');
|
||||
expect(phaseOf(null, null, TODAY)).toBe('undated');
|
||||
});
|
||||
|
||||
it('ASTHOME-002: reads the rows of list_trips once each, and nothing without an id or a title', () => {
|
||||
const trips = tripsOf(
|
||||
{ trips: [...LISTED.trips, row(1, 'Again', null, null), { id: 0, title: 'x' }, { id: 9, title: ' ' }, null] },
|
||||
TODAY,
|
||||
);
|
||||
expect(trips.map((trip) => trip.id)).toEqual([1, 2, 3, 4, 5, 6]);
|
||||
expect(trips.find((trip) => trip.id === 2)).toMatchObject({ shared: true, placeCount: 4 });
|
||||
expect(trips.find((trip) => trip.id === 4)).toMatchObject({ archived: true, phase: 'past' });
|
||||
expect(trips.find((trip) => trip.id === 5)).toMatchObject({ placeCount: null, phase: 'undated' });
|
||||
expect(trips.find((trip) => trip.id === 6)).toMatchObject({ shared: true });
|
||||
expect(tripsOf(null, TODAY)).toEqual([]);
|
||||
expect(tripsOf({ trips: 'none' }, TODAY)).toEqual([]);
|
||||
});
|
||||
|
||||
it('ASTHOME-003: lists the trip under way, the next ones soonest first, the latest behind and the undated', () => {
|
||||
const card = homeCardOf(tripsOf(LISTED, TODAY));
|
||||
expect(card.trips.map((trip) => [trip.id, trip.phase])).toEqual([
|
||||
[1, 'now'],
|
||||
[3, 'next'],
|
||||
[2, 'upcoming'],
|
||||
[4, 'past'],
|
||||
[6, 'past'],
|
||||
[5, 'undated'],
|
||||
]);
|
||||
expect(card.total).toBe(6);
|
||||
});
|
||||
|
||||
it('ASTHOME-004: keeps a long history short and says how many it leaves out', () => {
|
||||
const many = Array.from({ length: 12 }, (_, i) =>
|
||||
row(100 + i, `Past ${i}`, `2025-0${(i % 9) + 1}-01`, `2025-0${(i % 9) + 1}-02`),
|
||||
);
|
||||
const card = homeCardOf(tripsOf({ trips: many }, TODAY));
|
||||
expect(card.trips).toHaveLength(4);
|
||||
expect(renderHomeCard(card)).toContain('and 8 more; list_trips lists them all.');
|
||||
});
|
||||
|
||||
it('ASTHOME-005: renders one trip a line, with its id, and says when there is none', () => {
|
||||
const text = renderHomeCard(homeCardOf(tripsOf(LISTED, TODAY)));
|
||||
expect(text.split('\n')[0]).toBe("The user's trips (trip id | title | where it stands):");
|
||||
expect(text).toContain('1 | Lisbon | under way, 2026-10-20 to 2026-10-27, 4 places');
|
||||
expect(text).toContain('3 | Oslo | next, 2026-11-05 to 2026-11-08, 4 places');
|
||||
expect(text).toContain('2 | Kyoto | later, 2026-12-01 to 2026-12-10, 4 places, shared');
|
||||
expect(text).toContain('4 | Rome | behind, 2026-05-01 to 2026-05-07, 4 places, archived');
|
||||
expect(text).toMatch(/^5 \| Someday \| no dates$/m);
|
||||
expect(text).not.toContain('more;');
|
||||
expect(renderHomeCard({ trips: [], total: 0 })).toBe('The user has no trips yet.');
|
||||
});
|
||||
|
||||
it('ASTHOME-006: is read through the session, and empty when the trips cannot be read', async () => {
|
||||
const read = vi.fn(async () => ({ ok: true, value: LISTED }));
|
||||
expect((await homeCardFrom({ read }, TODAY)).total).toBe(6);
|
||||
expect(read).toHaveBeenCalledWith('list_trips', {});
|
||||
expect(await homeCardFrom({ read: async () => ({ ok: false, value: 'no' }) }, TODAY)).toEqual({
|
||||
trips: [],
|
||||
total: 0,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('a home turn', () => {
|
||||
it('ASTHOME-010: brings the date, the units and the home card in its own tags', () => {
|
||||
const card = homeCardOf(tripsOf(LISTED, TODAY));
|
||||
const now = new Date('2026-10-23T09:00:00Z');
|
||||
const context = homeTurnContext(card, 'Europe/Berlin', now, { distance_unit: 'metric' });
|
||||
const lines = context.split('\n');
|
||||
expect(lines[0]).toBe('Today is 2026-10-23 (time zone Europe/Berlin).');
|
||||
expect(lines[1]).toBe('The user prefers distances in km.');
|
||||
expect(context).toContain('<home_card>');
|
||||
expect(context).toContain('</home_card>');
|
||||
expect(homeTurnContext(card, 'UTC', now, {}).split('\n')[1]).toBe('');
|
||||
});
|
||||
|
||||
it('ASTHOME-011: tells the model what it can do here and that a trip is changed in its own chat', () => {
|
||||
const prompt = homePrompt('German');
|
||||
expect(prompt).toContain('in German');
|
||||
expect(prompt).not.toContain('{language}');
|
||||
expect(prompt).toContain('open_trip_chat');
|
||||
expect(prompt).toContain('You cannot change a trip from here.');
|
||||
expect(prompt).toContain('use_addon_tools');
|
||||
expect(OPEN_TRIP_CHAT_SPEC.name).toBe(OPEN_TRIP_CHAT_TOOL);
|
||||
expect(OPEN_TRIP_CHAT_SPEC.parameters.required).toEqual(['tripId']);
|
||||
});
|
||||
|
||||
it('ASTHOME-012: the step that loads groups says what needs nothing loaded in each chat', () => {
|
||||
expect(HOME_USE_TOOLS_SPEC.name).toBe(USE_TOOLS_SPEC.name);
|
||||
expect(HOME_USE_TOOLS_SPEC.parameters).toEqual(USE_TOOLS_SPEC.parameters);
|
||||
expect(HOME_USE_TOOLS_SPEC.description).toContain('list_trips');
|
||||
expect(USE_TOOLS_SPEC.description).toContain('The trip itself');
|
||||
});
|
||||
});
|
||||
|
||||
describe("the way into a trip's chat", () => {
|
||||
const listed = { ok: true, value: LISTED };
|
||||
|
||||
it("ASTHOME-020: answers with one of the user's trips and the question, cleaned up", () => {
|
||||
const run = openTripChat({ tripId: 3, question: ' What is left to book? ' }, listed, TODAY);
|
||||
expect(run).toMatchObject({
|
||||
ok: true,
|
||||
value: {
|
||||
trip: { id: 3, title: 'Oslo', startDate: '2026-11-05', endDate: '2026-11-08', phase: 'next', placeCount: 4 },
|
||||
question: 'What is left to book?',
|
||||
},
|
||||
});
|
||||
expect(openTripChat({ tripId: 2 }, listed, TODAY)).toMatchObject({ value: { question: null } });
|
||||
});
|
||||
|
||||
it('ASTHOME-021: a trip past the card is still found, and one the user cannot open is refused', () => {
|
||||
const many = { ok: true, value: { trips: Array.from({ length: 9 }, (_, i) => row(i + 1, `T${i}`, null, null)) } };
|
||||
expect(openTripChat({ tripId: 9 }, many, TODAY)).toMatchObject({ ok: true, value: { trip: { id: 9 } } });
|
||||
expect(openTripChat({ tripId: 77 }, listed, TODAY)).toMatchObject({ ok: false });
|
||||
expect(openTripChat({ tripId: 3 }, { ok: false, value: 'no' }, TODAY)).toMatchObject({ ok: false });
|
||||
expect(openTripChat({}, listed, TODAY)).toMatchObject({ ok: false });
|
||||
});
|
||||
|
||||
it('ASTHOME-022: shows a card, reading where the trip stands in the user zone', () => {
|
||||
const run = openTripChat({ tripId: 3, question: 'Pack list?' }, listed, TODAY);
|
||||
const input = { toolCallId: 'c1', args: {}, value: run.value, card: emptyTripCard(1), today: TODAY };
|
||||
expect(tripChatAnswer(input)).toEqual({
|
||||
kind: 'tripChat',
|
||||
trip: { id: 3, title: 'Oslo', startDate: '2026-11-05', endDate: '2026-11-08', phase: 'next', placeCount: 4 },
|
||||
question: 'Pack list?',
|
||||
});
|
||||
// The day it starts on, it is under way, whatever the step read.
|
||||
expect(tripChatAnswer({ ...input, today: '2026-11-05' })).toMatchObject({ trip: { phase: 'now' } });
|
||||
expect(answerCardOf(OPEN_TRIP_CHAT_TOOL, input)).toMatchObject({ kind: 'tripChat' });
|
||||
});
|
||||
|
||||
it('ASTHOME-023: shows no card for an answer without a trip or with a broken one', () => {
|
||||
const base = { toolCallId: 'c1', args: {}, card: emptyTripCard(1), today: TODAY };
|
||||
expect(tripChatAnswer({ ...base, value: 'No trip' })).toBeNull();
|
||||
expect(tripChatAnswer({ ...base, value: { trip: { id: 0, title: '' } } })).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('the tools the home chat keeps', () => {
|
||||
it('ASTHOME-030: every read, and only the writes that name no trip and no journey', () => {
|
||||
expect(keptAtHome('read', ['tripId'])).toBe(true);
|
||||
expect(keptAtHome('read', ['journeyId'])).toBe(true);
|
||||
expect(keptAtHome('write', ['country_code'])).toBe(true);
|
||||
expect(keptAtHome('write', [])).toBe(true);
|
||||
for (const arg of ['tripId', 'journeyId', 'trip_id', 'trip_ids', 'journey_id']) {
|
||||
expect(keptAtHome('write', ['name', arg]), arg).toBe(false);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
type BookCard,
|
||||
} from '../../../../src/nest/assistant/assistant-book-context';
|
||||
import type { AssistantBookGate } from '../../../../src/nest/assistant/assistant-book-gate';
|
||||
import { homePrompt } from '../../../../src/nest/assistant/assistant-home';
|
||||
import {
|
||||
AssistantScopes,
|
||||
findScopedCall,
|
||||
@@ -65,6 +66,10 @@ function threadRepo() {
|
||||
listRecentOnJourney: vi.fn(async () => [row]),
|
||||
deleteOwned: vi.fn(async () => true),
|
||||
deleteOwnedOnJourney: vi.fn(async () => true),
|
||||
createHomeThread: vi.fn(async () => 13),
|
||||
findOwnedAtHome: vi.fn(async () => row),
|
||||
listRecentAtHome: vi.fn(async () => [row]),
|
||||
deleteOwnedAtHome: vi.fn(async () => true),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -146,12 +151,33 @@ describe('a scope reaches its own threads and changes', () => {
|
||||
});
|
||||
|
||||
it('ASTSCP-003: a change is looked up in the scope it was proposed in', async () => {
|
||||
const repo = { findOwned: vi.fn(async () => null), findOwnedOnJourney: vi.fn(async () => null) };
|
||||
const repo = {
|
||||
findOwned: vi.fn(async () => null),
|
||||
findOwnedOnJourney: vi.fn(async () => null),
|
||||
findOwnedAtHome: vi.fn(async () => null),
|
||||
};
|
||||
const calls = repo as unknown as AssistantToolCallsRepository;
|
||||
await findScopedCall(calls, tripScope(5), 'tc-1', 7);
|
||||
await findScopedCall(calls, { kind: 'journey', journeyId: 12 }, 'tc-2', 7);
|
||||
await findScopedCall(calls, { kind: 'home' }, 'tc-3', 7);
|
||||
expect(repo.findOwned).toHaveBeenCalledWith('tc-1', 7, 5);
|
||||
expect(repo.findOwnedOnJourney).toHaveBeenCalledWith('tc-2', 7, 12);
|
||||
expect(repo.findOwnedAtHome).toHaveBeenCalledWith('tc-3', 7);
|
||||
});
|
||||
|
||||
it('ASTSCP-004: the home scope goes through the home methods, with no trip and no journey', async () => {
|
||||
const repo = threadRepo();
|
||||
const threads = scopedThreads(repo as unknown as AssistantThreadsRepository, { kind: 'home' });
|
||||
expect(await threads.create(7, 'Next trip', 'at')).toBe(13);
|
||||
await threads.find(3, 7);
|
||||
await threads.list(7, 20);
|
||||
await threads.remove(3, 7);
|
||||
expect(repo.createHomeThread).toHaveBeenCalledWith(7, 'Next trip', 'at');
|
||||
expect(repo.findOwnedAtHome).toHaveBeenCalledWith(3, 7);
|
||||
expect(repo.listRecentAtHome).toHaveBeenCalledWith(7, 20);
|
||||
expect(repo.deleteOwnedAtHome).toHaveBeenCalledWith(3, 7);
|
||||
expect(repo.createThread).not.toHaveBeenCalled();
|
||||
expect(repo.createJourneyThread).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -392,7 +418,11 @@ describe('a scope opens its session and writes its turn', () => {
|
||||
};
|
||||
|
||||
function scopesWith(canWrite: boolean) {
|
||||
const tools = { open: vi.fn(async () => session), openJourney: vi.fn(async () => session) };
|
||||
const tools = {
|
||||
open: vi.fn(async () => session),
|
||||
openJourney: vi.fn(async () => session),
|
||||
openHome: vi.fn(async () => session),
|
||||
};
|
||||
const books = {
|
||||
canEdit: vi.fn(async () => canWrite),
|
||||
cardOf: vi.fn(async () => card({ role: canWrite ? 'editor' : 'viewer' })),
|
||||
@@ -450,6 +480,30 @@ describe('a scope opens its session and writes its turn', () => {
|
||||
expect(viewed.system).toBe(studioPrompt('English', false));
|
||||
});
|
||||
|
||||
it('ASTSCP-053: a home turn opens the home session, reads the user trips through it and the home prompt', async () => {
|
||||
const { tools, scopes, books } = scopesWith(true);
|
||||
const targets = new Set(['delete_collection']);
|
||||
await scopes.open(7, { kind: 'home' }, targets);
|
||||
expect(tools.openHome).toHaveBeenCalledWith(7, targets);
|
||||
const homeSession = {
|
||||
...session,
|
||||
read: vi.fn(async () => ({
|
||||
ok: true,
|
||||
value: { trips: [{ id: 5, title: 'Kyoto', start_date: '2026-08-01', end_date: '2026-08-09' }] },
|
||||
})),
|
||||
};
|
||||
const read = await scopes.turnOf(homeSession as never, { kind: 'home' }, turn);
|
||||
expect(homeSession.read).toHaveBeenCalledWith('list_trips', {});
|
||||
expect(read.system).toBe(homePrompt('English'));
|
||||
expect(read.context).toContain('<home_card>');
|
||||
expect(read.context).toContain('5 | Kyoto | next, 2026-08-01 to 2026-08-09');
|
||||
expect(read.context).toContain('temperatures in °C');
|
||||
expect(read.card.tripId).toBe(0);
|
||||
expect(books.cardOf).not.toHaveBeenCalled();
|
||||
// The home chat's held calls pass as a trip's do.
|
||||
expect(await read.gate.refusalOf('mark_country_visited', { country_code: 'JP' })).toBeNull();
|
||||
});
|
||||
|
||||
it('ASTSCP-052: the trip card is read through the session, or on a session of its own two reads', async () => {
|
||||
session.read.mockClear();
|
||||
const fromSession = await tripCardFrom(session, 5, 7, { dayId: 2 });
|
||||
|
||||
@@ -94,6 +94,9 @@ describe('the assistant tool catalog', () => {
|
||||
expect(checkToolCatalog([entry('import_booking')])).toContain('"import_booking" is the server\'s own step');
|
||||
expect(checkToolCatalog([entry('use_addon_tools')])).toContain('"use_addon_tools" is the server\'s own step');
|
||||
expect(checkToolCatalog([entry('preview_book_page')])).toContain('"preview_book_page" is the server\'s own step');
|
||||
// The home chat's way into a trip's chat is the server's own, with cards of its own but no registry tool.
|
||||
expect(checkToolCatalog([entry('open_trip_chat')])).toContain('"open_trip_chat" is the server\'s own step');
|
||||
expect(checkToolCatalog([]).join()).not.toContain('"open_trip_chat" with cards');
|
||||
expect(checkDenylist(['create_party_invite'])).toEqual([
|
||||
'"create_party_invite" shares, invites or publishes; deny it or list it as safe',
|
||||
]);
|
||||
|
||||
@@ -57,7 +57,7 @@ const described = () => ({ subject: 'x', rows: new Rows(), dayId: null, placeIds
|
||||
describe('mergeDomains', () => {
|
||||
it('ASTREG-001: the live registry holds every package once, the core tables and the tours they brought', () => {
|
||||
expect(new Set(DOMAINS.map((d) => d.id)).size).toBe(DOMAINS.length);
|
||||
expect(DOMAINS).toHaveLength(12);
|
||||
expect(DOMAINS).toHaveLength(13);
|
||||
for (const name of Object.keys(CORE_WRITE_TOOLS)) expect(ASSISTANT_WRITE_TOOLS[name]).toBe(CORE_WRITE_TOOLS[name]);
|
||||
expect(ASSISTANT_WRITE_TOOLS.create_hike).toEqual({ verbKey: 'addTour', entity: 'tour' });
|
||||
expect(ASSISTANT_UNDO_MAP.create_city_walk?.tool).toBe('delete_place');
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
/**
|
||||
* The home assistant's controller: the AI addon before auth and nothing else
|
||||
* to open, the managed marker, the routes with their statuses, and that every
|
||||
* handler hands the caller's own id and the home scope to the same service
|
||||
* the trip's and the journey's controllers use.
|
||||
*/
|
||||
import 'reflect-metadata';
|
||||
|
||||
import { AddonGuard } from '../../../../src/nest/addons/addon.guard';
|
||||
import { REQUIRE_ADDON } from '../../../../src/nest/addons/require-addon.decorator';
|
||||
import type { AssistantService, TurnChannel } from '../../../../src/nest/assistant/assistant.service';
|
||||
import { HomeAssistantController } from '../../../../src/nest/assistant/home-assistant.controller';
|
||||
import { JwtAuthGuard } from '../../../../src/nest/auth-core/jwt-auth.guard';
|
||||
import { DomainError } from '../../../../src/nest/common/domain-error';
|
||||
import { MANAGED_FORBIDDEN } from '../../../../src/nest/common/managed';
|
||||
import { MANAGED_ROUTE_ALLOW_LIST } from '../../../../src/nest/common/validate-managed-routes';
|
||||
import type { User } from '../../../../src/types';
|
||||
import { RequestMethod } from '@nestjs/common';
|
||||
import { GUARDS_METADATA, HTTP_CODE_METADATA, METHOD_METADATA, PATH_METADATA } from '@nestjs/common/constants';
|
||||
|
||||
import type { Response } from 'express';
|
||||
import { EventEmitter } from 'node:events';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const user = { id: 7, role: 'user' } as User;
|
||||
const HOME = { kind: 'home' };
|
||||
|
||||
function make() {
|
||||
const service = {
|
||||
listThreads: vi.fn(async () => ({ threads: [] })),
|
||||
getThread: vi.fn(async () => ({ thread: { id: 1, title: 't', lastMessageAt: 'x' }, messages: [] })),
|
||||
deleteThread: vi.fn(async () => undefined),
|
||||
chat: vi.fn(async (_u: number, _s: unknown, _b: unknown, _c: TurnChannel) => undefined),
|
||||
decide: vi.fn(async (_u: number, _s: unknown, _th: number, _b: unknown, _c: TurnChannel) => undefined),
|
||||
undo: vi.fn(async () => undefined),
|
||||
stop: vi.fn(async () => undefined),
|
||||
};
|
||||
const controller = new HomeAssistantController(service as unknown as AssistantService);
|
||||
return { service, controller };
|
||||
}
|
||||
|
||||
/** Enough of an Express response for a turn to hand to the service. */
|
||||
class FakeResponse extends EventEmitter {
|
||||
writableEnded = false;
|
||||
destroyed = false;
|
||||
}
|
||||
|
||||
function route(name: string) {
|
||||
const handler = (HomeAssistantController.prototype as unknown as Record<string, object>)[name];
|
||||
return {
|
||||
method: Reflect.getMetadata(METHOD_METADATA, handler) as RequestMethod,
|
||||
path: Reflect.getMetadata(PATH_METADATA, handler) as string,
|
||||
httpCode: Reflect.getMetadata(HTTP_CODE_METADATA, handler) as number | undefined,
|
||||
};
|
||||
}
|
||||
|
||||
describe('HomeAssistantController', () => {
|
||||
it('ASTHCTL-001: sits behind the AI addon and auth, and is withheld on a managed install', () => {
|
||||
expect(Reflect.getMetadata(PATH_METADATA, HomeAssistantController)).toBe('api/assistant');
|
||||
expect(Reflect.getMetadata(GUARDS_METADATA, HomeAssistantController)).toEqual([AddonGuard, JwtAuthGuard]);
|
||||
expect(Reflect.getMetadata(REQUIRE_ADDON, HomeAssistantController)).toMatchObject({ addonId: 'ai_assistant' });
|
||||
expect(Reflect.getMetadata(MANAGED_FORBIDDEN, HomeAssistantController)?.reason).toBeTruthy();
|
||||
for (const name of ['chat', 'decide', 'deleteThread', 'stop', 'thread', 'threads', 'undo']) {
|
||||
expect(MANAGED_ROUTE_ALLOW_LIST, name).toContain(`HomeAssistantController.${name}`);
|
||||
}
|
||||
});
|
||||
|
||||
it('ASTHCTL-002: declares the conversation routes, with their statuses, and none that belongs to a trip', () => {
|
||||
expect(route('threads')).toMatchObject({ method: RequestMethod.GET, path: 'threads' });
|
||||
expect(route('thread')).toMatchObject({ method: RequestMethod.GET, path: 'threads/:threadId' });
|
||||
expect(route('deleteThread')).toEqual({ method: RequestMethod.DELETE, path: 'threads/:threadId', httpCode: 200 });
|
||||
expect(route('chat')).toMatchObject({ method: RequestMethod.POST, path: 'chat' });
|
||||
expect(route('decide')).toMatchObject({ method: RequestMethod.POST, path: 'threads/:threadId/decisions' });
|
||||
expect(route('undo')).toEqual({ method: RequestMethod.POST, path: 'tool-calls/:toolCallId/undo', httpCode: 200 });
|
||||
expect(route('stop')).toEqual({ method: RequestMethod.POST, path: 'stop', httpCode: 200 });
|
||||
const handlers = HomeAssistantController.prototype as unknown as Record<string, unknown>;
|
||||
for (const name of ['addFoundPlace', 'takeProposal', 'share', 'attach', 'upload']) {
|
||||
expect(handlers[name], name).toBeUndefined();
|
||||
}
|
||||
});
|
||||
|
||||
it('ASTHCTL-003: hands the caller and the home scope to the service, and answers the contract bodies', async () => {
|
||||
const { service, controller } = make();
|
||||
await controller.threads(user);
|
||||
expect(service.listThreads).toHaveBeenCalledWith(7, HOME);
|
||||
await controller.thread(user, '9');
|
||||
expect(service.getThread).toHaveBeenCalledWith(7, HOME, 9);
|
||||
expect(await controller.deleteThread(user, '9')).toEqual({ success: true });
|
||||
expect(service.deleteThread).toHaveBeenCalledWith(7, HOME, 9);
|
||||
expect(await controller.undo(user, 'tc-1', {})).toEqual({ undone: true });
|
||||
expect(service.undo).toHaveBeenCalledWith(7, HOME, 'tc-1');
|
||||
expect(await controller.stop(user, {})).toEqual({ success: true });
|
||||
expect(service.stop).toHaveBeenCalledWith(7);
|
||||
expect(() => controller.thread(user, 'abc')).toThrow(DomainError);
|
||||
await expect(controller.deleteThread(user, '0')).rejects.toThrow(DomainError);
|
||||
});
|
||||
|
||||
it('ASTHCTL-004: a turn and a decision go to the service at home, with the stream of the response', async () => {
|
||||
const { service, controller } = make();
|
||||
const chat = { locale: 'en', timeZone: 'UTC', threadId: null, text: 'Which trip is next?' };
|
||||
await controller.chat(user, chat, new FakeResponse() as unknown as Response);
|
||||
expect(service.chat.mock.calls[0].slice(0, 3)).toEqual([7, HOME, chat]);
|
||||
const decisions = { locale: 'en', timeZone: 'UTC', decisions: [] };
|
||||
const gone = new FakeResponse();
|
||||
await controller.decide(user, '9', decisions, gone as unknown as Response);
|
||||
expect(service.decide.mock.calls[0].slice(0, 3)).toEqual([7, HOME, 9]);
|
||||
gone.emit('close');
|
||||
expect(service.decide.mock.calls[0][4].signal.aborted).toBe(true);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user