diff --git a/client/src/api/assistant.test.ts b/client/src/api/assistant.test.ts index 8099843ba..ccf0ed029 100644 --- a/client/src/api/assistant.test.ts +++ b/client/src/api/assistant.test.ts @@ -1,10 +1,11 @@ /** - * FE-AI-API-001 to FE-AI-API-007 + * FE-AI-API-001 to FE-AI-API-008 * * The two streaming calls bypass axios, so they carry by hand what the axios * instance would add (the cookie, the socket id) and turn a refusal before the * stream into a typed error the chat can name. The refusal's code comes from - * the body when the server names one, and from the status otherwise. + * the body when the server names one, and from the status otherwise. A + * journey's chat reaches the same calls under the journey. */ import type { AssistantChatRequest } from '@trek/shared'; import { http, HttpResponse } from 'msw'; @@ -130,4 +131,38 @@ describe('assistantApi JSON calls', () => { await expect(assistantApi.stop(4)).resolves.toEqual({ success: true }); expect(body).toEqual({}); }); + + it('FE-AI-API-008: a journey scope reaches the journey routes, a trip scope the trip routes', async () => { + const journey = { kind: 'journey', journeyId: 12 } as const; + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation(async () => streamResponse('data: [DONE]\n\n')); + const signal = new AbortController().signal; + await assistantApi.chat(journey, BODY, signal); + await assistantApi.decide(journey, 7, { locale: 'en', timeZone: 'UTC', decisions: [] }, signal); + await assistantApi.chat({ kind: 'trip', tripId: 4 }, BODY, signal); + expect(fetchSpy.mock.calls.map(([url]) => url)).toEqual([ + '/api/journeys/12/assistant/chat', + '/api/journeys/12/assistant/threads/7/decisions', + '/api/trips/4/assistant/chat', + ]); + + const hits: string[] = []; + server.use( + http.get('/api/journeys/12/assistant/threads', () => { + hits.push('threads'); + return HttpResponse.json({ threads: [] }); + }), + http.post('/api/journeys/12/assistant/tool-calls/:id/undo', () => { + hits.push('undo'); + return HttpResponse.json({ undone: true }); + }), + http.post('/api/journeys/12/assistant/stop', () => { + hits.push('stop'); + return HttpResponse.json({ success: true }); + }) + ); + await assistantApi.threads(journey); + await assistantApi.undo(journey, 'c1'); + await assistantApi.stop(journey); + expect(hits).toEqual(['threads', 'undo', 'stop']); + }); }); diff --git a/client/src/api/assistant.ts b/client/src/api/assistant.ts index 57ad95427..9a61659fe 100644 --- a/client/src/api/assistant.ts +++ b/client/src/api/assistant.ts @@ -18,21 +18,24 @@ import { type AssistantChatRequest, type AssistantDecisionsRequest, type AssistantErrorCode, + type AssistantRenderUploadResponse, + type AssistantScope, type AssistantShareRequest, type AssistantTakeProposalRequest, type AssistantThreadListResponse, type AssistantThreadResponse, type AssistantUndoResponse, + type BookDesignDraftResponse, type CollabMessageResponse, type SuccessResponse, type UiStreamChunk, } from '@trek/shared'; -import apiClient from './client'; +import apiClient, { postMultipart } from './client'; import { parseUiMessageStream } from './uiMessageStream'; import { getSocketId } from './websocket'; /** - * The trip assistant and the AI connections behind it, in their own file + * The assistant and the AI connections behind it, in their own file * rather than in the `client.ts` god module. * * The two streaming calls (a new message, and the decisions on held changes) @@ -97,6 +100,23 @@ async function openStream(path: string, body: unknown, signal: AbortSignal): Pro const tripBase = (tripId: number) => `/trips/${tripId}/assistant`; +/** + * What a conversation call is about: a trip's id (the planner's chat), or a + * scope, which also reaches a journey's chat in TREK Studio. Threads, turns, + * decisions, undo and stop exist under both; files, found places, proposals + * and sharing belong to a trip and take its id. + */ +export type AssistantTarget = number | AssistantScope; + +function scopeBase(target: AssistantTarget): string { + if (typeof target === 'number') return tripBase(target); + return target.kind === 'trip' ? tripBase(target.tripId) : `/journeys/${target.journeyId}/assistant`; +} + +/** Where the Studio uploads a page a running turn of a journey's chat asked for. */ +const renderPath = (journeyId: number, threadId: number, requestId: string) => + `/journeys/${journeyId}/assistant/threads/${threadId}/renders/${encodeURIComponent(requestId)}`; + /** * For the calls that make the server go and ask the provider (listing models, * testing a key, exchanging a sign-in code): the shared 8 s is TREK's own @@ -105,17 +125,17 @@ const tripBase = (tripId: number) => `/trips/${tripId}/assistant`; const viaProvider = { timeout: 30_000 }; export const assistantApi = { - threads: (tripId: number): Promise => - apiClient.get(`${tripBase(tripId)}/threads`).then((r) => r.data), - thread: (tripId: number, threadId: number): Promise => - apiClient.get(`${tripBase(tripId)}/threads/${threadId}`).then((r) => r.data), - deleteThread: (tripId: number, threadId: number): Promise => - apiClient.delete(`${tripBase(tripId)}/threads/${threadId}`).then((r) => r.data), - undo: (tripId: number, toolCallId: string): Promise => - apiClient.post(`${tripBase(tripId)}/tool-calls/${encodeURIComponent(toolCallId)}/undo`, {}).then((r) => r.data), + threads: (target: AssistantTarget): Promise => + apiClient.get(`${scopeBase(target)}/threads`).then((r) => r.data), + thread: (target: AssistantTarget, threadId: number): Promise => + apiClient.get(`${scopeBase(target)}/threads/${threadId}`).then((r) => r.data), + deleteThread: (target: AssistantTarget, threadId: number): Promise => + apiClient.delete(`${scopeBase(target)}/threads/${threadId}`).then((r) => r.data), + undo: (target: AssistantTarget, toolCallId: string): Promise => + apiClient.post(`${scopeBase(target)}/tool-calls/${encodeURIComponent(toolCallId)}/undo`, {}).then((r) => r.data), // Ends this user's running turn, wherever it runs (another tab included). - stop: (tripId: number): Promise => - apiClient.post(`${tripBase(tripId)}/stop`, {}).then((r) => r.data), + stop: (target: AssistantTarget): Promise => + apiClient.post(`${scopeBase(target)}/stop`, {}).then((r) => r.data), // A place a search found, suggested for a day: answers with the message holding the change. addFoundPlace: ( tripId: number, @@ -141,13 +161,25 @@ export const assistantApi = { .post(`${tripBase(tripId)}/threads/${threadId}/messages/${encodeURIComponent(messageId)}/share`, body) .then((r) => r.data), - chat: (tripId: number, body: AssistantChatRequest, signal: AbortSignal) => - openStream(`${tripBase(tripId)}/chat`, body, signal), - decide: (tripId: number, threadId: number, body: AssistantDecisionsRequest, signal: AbortSignal) => - openStream(`${tripBase(tripId)}/threads/${threadId}/decisions`, body, signal), + chat: (target: AssistantTarget, body: AssistantChatRequest, signal: AbortSignal) => + openStream(`${scopeBase(target)}/chat`, body, signal), + decide: (target: AssistantTarget, threadId: number, body: AssistantDecisionsRequest, signal: AbortSignal) => + openStream(`${scopeBase(target)}/threads/${threadId}/decisions`, body, signal), // A booking file: the server reads it and proposes each booking it finds as a change. attach: (tripId: number, form: FormData, signal: AbortSignal) => openStream(`${tripBase(tripId)}/attachments`, form, signal), + // A Studio page a running turn asked for, drawn by this tab: the image and what it shows, as multipart. + uploadRender: ( + journeyId: number, + threadId: number, + requestId: string, + form: FormData, + signal: AbortSignal + ): Promise => + postMultipart(renderPath(journeyId, threadId, requestId), form, { signal }), + // A whole-book design draft, for a page of it a running turn asked the Studio to draw. + bookDesign: (journeyId: number, designId: string): Promise => + apiClient.get(`/journeys/${journeyId}/book-designs/${encodeURIComponent(designId)}`).then((r) => r.data), }; /** A user's own connection, and what the assistant runs on for them. */ diff --git a/client/src/components/Assistant/AssistantComposer.tsx b/client/src/components/Assistant/AssistantComposer.tsx index 9de71068d..1d1464e6f 100644 --- a/client/src/components/Assistant/AssistantComposer.tsx +++ b/client/src/components/Assistant/AssistantComposer.tsx @@ -43,7 +43,7 @@ export default function AssistantComposer({ tripId, tripTitle }: { tripId: numbe const mentions = useAssistantMentions(tripId); const { suggestions } = useAssistantSuggestions(tripId); const empty = useAuiState((s) => s.composer.isEmpty); - const { take, busy, accept } = useAssistantAttach(tripId); + const { take, busy, accept, canAttach } = useAssistantAttach(tripId); const fileInput = useRef(null); const fallback = t('assistant.composer.placeholder', { trip: tripTitle }); const placeholder = useTypewriterPlaceholder( @@ -75,27 +75,31 @@ export default function AssistantComposer({ tripId, tripTitle }: { tripId: numbe )}
- - - - { - take(e.target.files); - e.target.value = ''; - }} - /> + {canAttach && ( + <> + + + + { + take(e.target.files); + e.target.value = ''; + }} + /> + + )} { fireEvent.mouseLeave(card); expect(setPreviewPin).toHaveBeenLastCalledWith(null); }); + + it('FE-AI-PLACES-010: a journey chat lists the places but offers no "+ Day" while the trip is on screen', () => { + // The journey key never matches the planner's trip, so the trip check already hides "+ Day"; + // the scope check in the hook is defence in depth for the day trips and journeys share keys. + seed(); + renderStrip({ toolCallId: 's1', places: [place('s1:0')], more: 0 }, answer(), { + tripId: assistantChatKey({ kind: 'journey', journeyId: TRIP }), + }); + expect(screen.getByText('Trattoria s1:0')).toBeInTheDocument(); + expect(screen.queryByRole('button', { name: /^Add to/ })).toBeNull(); + expect(screen.queryByRole('button', { name: /Pick a day/ })).toBeNull(); + }); }); diff --git a/client/src/components/Assistant/AssistantSurface.test.tsx b/client/src/components/Assistant/AssistantSurface.test.tsx index 22cc93235..637dd015a 100644 --- a/client/src/components/Assistant/AssistantSurface.test.tsx +++ b/client/src/components/Assistant/AssistantSurface.test.tsx @@ -1,15 +1,17 @@ /** - * FE-AI-SURF-001 to FE-AI-SURF-006 + * FE-AI-SURF-001 to FE-AI-SURF-008 * * The chat on the real @assistant-ui runtime, fed from the assistant store: * the empty chat with its suggestions, stored messages as the user sees - * them, sending from the composer, and the composer holding back while a - * change waits for a decision. + * them, sending from the composer, the composer holding back while a change + * waits for a decision, and a journey's chat under its own key, without the + * trip's questions and booking upload. */ import type { AiStatusResponse, AssistantMessage } from '@trek/shared'; import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; import { fireEvent, render, screen, waitFor } from '../../../tests/helpers/render'; +import { assistantChatKey } from '../../store/assistantChatKey'; import { chatOf, useAssistantStore } from '../../store/assistantStore'; import AssistantSurface from './AssistantSurface'; @@ -179,4 +181,56 @@ describe('AssistantSurface', () => { expect(screen.getByRole('list', { name: 'Weather for 1 day' })).toBeInTheDocument(); expect(screen.getByText('14°')).toBeInTheDocument(); }); + + it('FE-AI-SURF-007: a journey chat reads and sends under its own key, not the trip with the same id', async () => { + const key = assistantChatKey({ kind: 'journey', journeyId: TRIP }); + useAssistantStore.setState({ + status: STATUS, + send, + byTrip: { + [TRIP]: { ...chatOf(useAssistantStore.getState(), TRIP), draft: 'trip draft' }, + [key]: { + ...chatOf(useAssistantStore.getState(), key), + messages: [ + { + id: 'q1', + role: 'user', + status: 'complete', + createdAt: AT, + parts: [{ type: 'text', text: 'Tidy page 3' }], + }, + ], + }, + }, + }); + render(); + + expect(await screen.findByText('Tidy page 3')).toBeInTheDocument(); + const input = screen.getByRole('textbox', { name: 'Ask anything about Lisbon' }); + fireEvent.change(input, { target: { value: 'Calmer cover' } }); + fireEvent.keyDown(input, { key: 'Enter' }); + await waitFor(() => expect(send).toHaveBeenCalledWith(key, 'Calmer cover')); + expect(chatOf(useAssistantStore.getState(), TRIP).draft).toBe('trip draft'); + }); + + it('FE-AI-SURF-008: an empty journey chat offers no trip questions, no booking upload and no drop zone', async () => { + const key = assistantChatKey({ kind: 'journey', journeyId: TRIP }); + useAssistantStore.setState({ + status: STATUS, + send, + byTrip: { [key]: { ...chatOf(useAssistantStore.getState(), key), messages: [] } }, + }); + render(); + + const input = await screen.findByRole('textbox', { name: 'Ask anything about Lisbon' }); + // It asks about the book, not the plan. + expect(screen.getByText('What should the book look like?')).toBeInTheDocument(); + expect(screen.queryByText('What are we planning?')).toBeNull(); + expect(screen.queryByRole('button', { name: 'Which days are still empty?' })).toBeNull(); + expect(screen.queryByRole('button', { name: 'Attach a booking' })).toBeNull(); + + // A file dragged over the chat is left to the browser: nothing lights up to take it. + fireEvent.dragEnter(input, { dataTransfer: { types: ['Files'], files: [] } }); + expect(screen.queryByText('Drop it here and I will read the booking')).toBeNull(); + }); }); diff --git a/client/src/components/Assistant/AssistantSurface.tsx b/client/src/components/Assistant/AssistantSurface.tsx index 8cb4cdecb..f77faad14 100644 --- a/client/src/components/Assistant/AssistantSurface.tsx +++ b/client/src/components/Assistant/AssistantSurface.tsx @@ -8,12 +8,15 @@ import { type AssistantView, AssistantViewContext } from './assistantViewContext import { useAssistantRuntime } from './useAssistantRuntime'; export interface AssistantSurfaceProps extends AssistantView { - /** Named in the composer's placeholder. */ + /** Named in the composer's placeholder: the trip's title, or the journey's in TREK Studio. */ tripTitle: string; } /** - * The chat for one trip, the same on the desktop window and the phone screen. + * The chat for one trip, the same on the desktop window and the phone screen, + * and for one journey in TREK Studio: `tripId` is the chat's key, so the + * Studio passes `assistantChatKey({ kind: 'journey', journeyId })` and gets + * the journey's conversations, with the parts that need a trip left empty. * Its own chunk: this is the only module tree that pulls in @assistant-ui, so * nobody downloads the chat runtime before opening the assistant. */ diff --git a/client/src/components/Assistant/assistantViewContext.ts b/client/src/components/Assistant/assistantViewContext.ts index dbe8b5e35..4d487ef27 100644 --- a/client/src/components/Assistant/assistantViewContext.ts +++ b/client/src/components/Assistant/assistantViewContext.ts @@ -1,10 +1,18 @@ +import type { AssistantScope } from '@trek/shared'; import { createContext, useContext } from 'react'; +import { type AssistantChatKey, assistantScopeOf } from '../../store/assistantChatKey'; import type { EntityTarget } from './cards/cardTypes'; /** What the parts deep inside a chat need from whoever shows it. */ export interface AssistantView { - tripId: number; + /** + * The chat's key, which every part hands to the assistant store: the trip's + * id in the planner, a journey's key in TREK Studio (`assistantChatKey`). + * No trip is held under a journey's key, so the parts that read the trip + * (its map, its days, found places) stay empty there. + */ + tripId: AssistantChatKey; /** 'window' on the desktop, 'fullscreen' on the phone. */ variant: 'window' | 'fullscreen'; /** How much room the chat has: a narrow window and the phone are 'compact'. */ @@ -28,3 +36,8 @@ export function useAssistantView(): AssistantView { if (!view) throw new Error('useAssistantView outside AssistantSurface'); return view; } + +/** What the chat on screen is about, for the parts that only make sense on a trip. */ +export function useAssistantScope(): AssistantScope { + return assistantScopeOf(useAssistantView().tripId); +} diff --git a/client/src/components/Assistant/useAssistantAttach.ts b/client/src/components/Assistant/useAssistantAttach.ts index 50f29bec3..b837c49bc 100644 --- a/client/src/components/Assistant/useAssistantAttach.ts +++ b/client/src/components/Assistant/useAssistantAttach.ts @@ -2,6 +2,7 @@ import { LLM_PHOTO_EXTENSIONS } from '@trek/shared'; import { type DragEvent, useState } from 'react'; import { useTranslation } from '../../i18n'; +import { assistantScopeOf } from '../../store/assistantChatKey'; import { chatOf, useAssistantStore } from '../../store/assistantStore'; import { useToast } from '../shared/Toast'; @@ -32,6 +33,8 @@ function hasFiles(e: DragEvent): boolean { * the window. One file at a time, refused here with a toast when it is not * one the import reads or too big, so a wrong file never costs a round trip. * The drop handlers go on the whole chat; `dragging` lights its drop zone. + * A journey's chat imports no bookings: there `canAttach` is false, a file is + * left to the browser and the drop zone never lights. */ export function useAssistantAttach(tripId: number) { const { t } = useTranslation(); @@ -39,10 +42,11 @@ export function useAssistantAttach(tripId: number) { const attach = useAssistantStore((s) => s.attach); const busy = useAssistantStore((s) => chatOf(s, tripId).isRunning); const [dragging, setDragging] = useState(false); + const canAttach = assistantScopeOf(tripId).kind === 'trip'; const take = (files: FileList | File[] | null | undefined): boolean => { const file = files ? Array.from(files)[0] : undefined; - if (!file) return false; + if (!file || !canAttach) return false; if (busy) return true; if (!ATTACH_EXTENSIONS.includes(extensionOf(file.name))) { toast.warning(t('assistant.attach.unsupported')); @@ -58,12 +62,12 @@ export function useAssistantAttach(tripId: number) { const dropZone = { onDragEnter: (e: DragEvent) => { - if (!hasFiles(e)) return; + if (!canAttach || !hasFiles(e)) return; e.preventDefault(); setDragging(true); }, onDragOver: (e: DragEvent) => { - if (!hasFiles(e)) return; + if (!canAttach || !hasFiles(e)) return; e.preventDefault(); e.dataTransfer.dropEffect = 'copy'; }, @@ -73,12 +77,12 @@ export function useAssistantAttach(tripId: number) { setDragging(false); }, onDrop: (e: DragEvent) => { - if (!hasFiles(e)) return; + if (!canAttach || !hasFiles(e)) return; e.preventDefault(); setDragging(false); take(e.dataTransfer.files); }, }; - return { take, busy, dragging, dropZone, accept: ATTACH_EXTENSIONS.join(',') }; + return { take, busy, canAttach, dragging, dropZone, accept: ATTACH_EXTENSIONS.join(',') }; } diff --git a/client/src/components/Assistant/useAssistantPlaceStrip.ts b/client/src/components/Assistant/useAssistantPlaceStrip.ts index f88cf8325..c99434767 100644 --- a/client/src/components/Assistant/useAssistantPlaceStrip.ts +++ b/client/src/components/Assistant/useAssistantPlaceStrip.ts @@ -14,7 +14,7 @@ import { haversineKm } from '../../utils/geo'; import { safeHexColor } from '../../utils/safeColor'; import { formatDistance } from '../../utils/units'; import { hasUndecided } from './assistantParts'; -import { useAssistantView } from './assistantViewContext'; +import { useAssistantScope, useAssistantView } from './assistantViewContext'; import { useCardPoint } from './cards/parts/useCardPoint'; /** A day a found place can be suggested for, named the way the day list names it. */ @@ -66,6 +66,7 @@ function lastSpot(stops: readonly Assignment[] | undefined): { lat: number; lng: export function useAssistantPlaceStrip() { const { t, locale } = useTranslation(); const { tripId } = useAssistantView(); + const scope = useAssistantScope(); const { offline } = useNetworkMode(); const can = useCanDo(); const unit = useSettingsStore((s) => s.settings.distance_unit ?? 'metric'); @@ -108,8 +109,11 @@ export function useAssistantPlaceStrip() { const focusDay = stripDays.find((d) => d.id === focusDayId) ?? null; const from = focusDay && assignments ? lastSpot(assignments[String(focusDay.id)]) : null; - /** Whether "+ Day" shows at all: the planner holds the trip and the user may add to it. */ - const canSuggest = !!trip && can('place_edit', trip) && stripDays.length > 0; + /** + * Whether "+ Day" shows at all: a trip's chat (a journey's has no days), the + * planner holds the trip and the user may add to it. + */ + const canSuggest = scope.kind === 'trip' && !!trip && can('place_edit', trip) && stripDays.length > 0; /** Why "+ Day" is off right now, as a tooltip; null when it is on. */ let blockedKey: string | null = null; if (offline) blockedKey = 'assistant.error.offline'; diff --git a/client/src/components/Assistant/useAssistantRuntime.ts b/client/src/components/Assistant/useAssistantRuntime.ts index c863a781d..d10da90ca 100644 --- a/client/src/components/Assistant/useAssistantRuntime.ts +++ b/client/src/components/Assistant/useAssistantRuntime.ts @@ -3,6 +3,7 @@ import type { AssistantMessage } from '@trek/shared'; import { useMemo } from 'react'; import { useNetworkMode } from '../../hooks/useNetworkMode'; +import type { AssistantChatKey } from '../../store/assistantChatKey'; import { pendingToolCallIds } from '../../store/assistantMessages'; import { chatOf, useAssistantStore } from '../../store/assistantStore'; import { toThreadMessage } from './assistantModel'; @@ -21,11 +22,12 @@ function textOf(message: AppendMessage): string { * * Offline the composer is off; while a change waits for a decision, typing * works but sending waits, because the model is still waiting for that answer. + * A trip's chat and a journey's run the same way, each under its own key. */ -export function useAssistantRuntime(tripId: number) { - const messages = useAssistantStore((s) => chatOf(s, tripId).messages); - const isRunning = useAssistantStore((s) => chatOf(s, tripId).isRunning); - const isLoading = useAssistantStore((s) => chatOf(s, tripId).loading); +export function useAssistantRuntime(key: AssistantChatKey) { + const messages = useAssistantStore((s) => chatOf(s, key).messages); + const isRunning = useAssistantStore((s) => chatOf(s, key).isRunning); + const isLoading = useAssistantStore((s) => chatOf(s, key).loading); const send = useAssistantStore((s) => s.send); const cancel = useAssistantStore((s) => s.cancel); const { offline } = useNetworkMode(); @@ -38,7 +40,7 @@ export function useAssistantRuntime(tripId: number) { isLoading, isDisabled: offline, isSendDisabled: waiting, - onNew: (message) => send(tripId, textOf(message)), - onCancel: async () => cancel(tripId), + onNew: (message) => send(key, textOf(message)), + onCancel: async () => cancel(key), }); } diff --git a/client/src/components/Assistant/useAssistantSuggestions.ts b/client/src/components/Assistant/useAssistantSuggestions.ts index d199a4274..b92766612 100644 --- a/client/src/components/Assistant/useAssistantSuggestions.ts +++ b/client/src/components/Assistant/useAssistantSuggestions.ts @@ -1,6 +1,7 @@ import { useMemo } from 'react'; import { useTranslation } from '../../i18n'; +import { assistantScopeOf } from '../../store/assistantChatKey'; import { useCanDo } from '../../store/permissionsStore'; import { useTripStore } from '../../store/tripStore'; import { localIsoDate } from '../../utils/localDate'; @@ -17,7 +18,8 @@ export interface ReadySuggestion { * The questions the empty chat offers, worded and ready to send, and whether * the user may change this trip at all. For a trip the planner is not showing * (one picked from the dashboard) neither its dates nor its rights are at - * hand, so it gets the general questions and none that would change it. + * hand, so it gets the general questions and none that would change it. A + * journey's chat in TREK Studio gets none: they all ask about a trip. */ export function useAssistantSuggestions(tripId: number): { suggestions: ReadySuggestion[]; canEdit: boolean } { const { t } = useTranslation(); @@ -26,8 +28,10 @@ export function useAssistantSuggestions(tripId: number): { suggestions: ReadySug const hasPlaces = useTripStore((s) => s.places.length > 0); const { label, kind } = useAssistantFocus(tripId); const canEdit = !!trip && can('place_edit', trip); + const tripChat = assistantScopeOf(tripId).kind === 'trip'; - const suggestions = useMemo(() => { + const suggestions = useMemo((): ReadySuggestion[] => { + if (!tripChat) return []; const phase = trip ? tripPhase({ startDate: trip.start_date ?? null, @@ -42,7 +46,7 @@ export function useAssistantSuggestions(tripId: number): { suggestions: ReadySug place: kind === 'place' ? label : null, day: kind === 'day' ? label : null, }).map((s) => ({ id: s.id, prompt: t(s.labelKey, s.params) })); - }, [trip, hasPlaces, canEdit, kind, label, t]); + }, [tripChat, trip, hasPlaces, canEdit, kind, label, t]); return { suggestions, canEdit }; } diff --git a/client/src/repo/assistantRepo.test.ts b/client/src/repo/assistantRepo.test.ts index 43544260c..d034facb5 100644 --- a/client/src/repo/assistantRepo.test.ts +++ b/client/src/repo/assistantRepo.test.ts @@ -1,15 +1,17 @@ /** - * FE-AI-REPO-001 to FE-AI-REPO-005 + * FE-AI-REPO-001 to FE-AI-REPO-007 * * The assistant is online-only on purpose (there is no model on the device * and no cached chats), so the repo makes two promises: nothing is sent while * offline, the manual offline switch included, and answers are parsed against - * the shared contract instead of cast. + * the shared contract instead of cast. A journey's chat goes through the same + * calls with its scope. */ -import type { AssistantThreadResponse } from '@trek/shared'; +import { type AssistantThreadResponse, blankBook } from '@trek/shared'; import { http, HttpResponse } from 'msw'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { server } from '../../tests/helpers/msw/server'; +import { type MultipartBody, readMultipart } from '../../tests/helpers/multipart'; import { assistantApi } from '../api/assistant'; import { _resetNetworkMode, setForcedOffline } from '../sync/networkMode'; import { assistantRepo } from './assistantRepo'; @@ -17,6 +19,10 @@ import { OnlineOnlyError } from './onlineOnly'; const BASE = '/api/trips/4/assistant'; +/** A design draft's book, as GET .../book-designs/:designId answers it. */ +let draftIds = 0; +const DRAFT = blankBook({ title: 'Lisbon', newId: (prefix) => `${prefix}-${++draftIds}` }); + const THREAD: AssistantThreadResponse = { thread: { id: 7, title: 'Kyoto', lastMessageAt: '2026-10-21T08:00:00.000Z' }, messages: [ @@ -105,4 +111,56 @@ describe('assistantRepo', () => { expect(chat).not.toHaveBeenCalled(); expect(threads).not.toHaveBeenCalled(); }); + + it('FE-AI-REPO-006: a journey scope reads the journey threads and hands the scope to the stream', async () => { + const journey = { kind: 'journey', journeyId: 12 } as const; + server.use( + http.get('/api/journeys/12/assistant/threads', () => HttpResponse.json({ threads: [THREAD.thread] })), + http.get('/api/journeys/12/assistant/threads/7', () => HttpResponse.json(THREAD)) + ); + await expect(assistantRepo.threads(journey)).resolves.toEqual([THREAD.thread]); + await expect(assistantRepo.thread(journey, 7)).resolves.toEqual(THREAD); + + const stream = (async function* () {})(); + const chat = vi.spyOn(assistantApi, 'chat').mockResolvedValue(stream); + const body = { locale: 'en', timeZone: 'UTC', threadId: null, text: 'Hi' }; + await expect(assistantRepo.send(journey, body, new AbortController().signal)).resolves.toBe(stream); + expect(chat).toHaveBeenCalledWith(journey, body, expect.any(AbortSignal)); + }); + + it('FE-AI-REPO-007: a Studio page goes up as multipart to the turn that asked, its book is read fresh', async () => { + let sent: MultipartBody | null = null; + let requestId = ''; + server.use( + http.post('/api/journeys/12/assistant/threads/9/renders/:requestId', async ({ request, params }) => { + requestId = String(params.requestId); + sent = await readMultipart(request); + return HttpResponse.json({ accepted: true }); + }), + http.get('/api/journeys/12/book', () => HttpResponse.json({ book: null })), + http.get('/api/journeys/12/book-designs/d-1', () => + HttpResponse.json({ designId: 'd-1', baseVersion: null, document: DRAFT, plan: [], selection: [] }) + ) + ); + const image = new Blob(['jpeg'], { type: 'image/jpeg' }); + const page = { image, bookVersion: 4, spreadId: 'sp-3', drawnPhotoIds: [7, 8] }; + const signal = new AbortController().signal; + + await assistantRepo.uploadRender(12, 9, 'req-1', page, signal); + await expect(assistantRepo.pageBook(12)).resolves.toBeNull(); + // A design draft's page is drawn at the version the draft was made against; a draft of no book is version 0. + await expect(assistantRepo.pageDraft(12, 'd-1')).resolves.toEqual({ version: 0, document: DRAFT }); + + expect(requestId).toBe('req-1'); + expect(sent).toEqual({ + fields: { bookVersion: '4', spreadId: 'sp-3', drawnPhotoIds: '7,8' }, + filenames: ['page.jpg'], + }); + + // Online only, like every other call here. + setForcedOffline(true); + await expect(assistantRepo.uploadRender(12, 9, 'req-1', page, signal)).rejects.toBeInstanceOf(OnlineOnlyError); + await expect(assistantRepo.pageBook(12)).rejects.toBeInstanceOf(OnlineOnlyError); + await expect(assistantRepo.pageDraft(12, 'd-1')).rejects.toBeInstanceOf(OnlineOnlyError); + }); }); diff --git a/client/src/repo/assistantRepo.ts b/client/src/repo/assistantRepo.ts index 26d73a27c..190bf2565 100644 --- a/client/src/repo/assistantRepo.ts +++ b/client/src/repo/assistantRepo.ts @@ -1,5 +1,6 @@ import { assistantAddFoundPlaceResponseSchema, + assistantRenderUploadResponseSchema, assistantThreadListResponseSchema, assistantThreadResponseSchema, collabMessageResponseSchema, @@ -8,12 +9,17 @@ import { type AssistantDecisionsRequest, type AssistantShareRequest, type AssistantTakeProposalRequest, + type BookDocument, + type BookRecord, } from '@trek/shared'; -import { assistantApi } from '../api/assistant'; +import { assistantApi, type AssistantTarget } from '../api/assistant'; +import { journeyApi } from '../api/client'; import { requireOnline } from './onlineOnly'; /** - * The trip assistant's conversations. + * The assistant's conversations: a trip's in the planner, a journey's in TREK + * Studio. The calls both have take an `AssistantTarget` (a trip's id, or a + * scope); files, found places, proposals and sharing take a trip's id. * * **Deliberately online-only, and no Dexie table.** Every answer comes from a * model on the other side of the server, so there is nothing to do offline, @@ -21,35 +27,36 @@ import { requireOnline } from './onlineOnly'; * read lives on the device. Each call refuses with `OnlineOnlyError` before a * request is made; the view says why instead of hanging on a timeout. * - * The planner learns about applied changes the normal way, through the - * WebSocket broadcast the tools send, so nothing here touches trip data. + * The planner and the Studio learn about applied changes the normal way, + * through the WebSocket broadcast the tools send, so nothing here touches + * trip or book data. */ export const assistantRepo = { - async threads(tripId: number) { + async threads(target: AssistantTarget) { requireOnline(); - return assistantThreadListResponseSchema.parse(await assistantApi.threads(tripId)).threads; + return assistantThreadListResponseSchema.parse(await assistantApi.threads(target)).threads; }, - async thread(tripId: number, threadId: number) { + async thread(target: AssistantTarget, threadId: number) { requireOnline(); - return assistantThreadResponseSchema.parse(await assistantApi.thread(tripId, threadId)); + return assistantThreadResponseSchema.parse(await assistantApi.thread(target, threadId)); }, - async deleteThread(tripId: number, threadId: number): Promise { + async deleteThread(target: AssistantTarget, threadId: number): Promise { requireOnline(); - await assistantApi.deleteThread(tripId, threadId); + await assistantApi.deleteThread(target, threadId); }, /** A new message; resolves once the server accepted it, with the stream of the answer. */ - async send(tripId: number, body: AssistantChatRequest, signal: AbortSignal) { + async send(target: AssistantTarget, body: AssistantChatRequest, signal: AbortSignal) { requireOnline(); - return assistantApi.chat(tripId, body, signal); + return assistantApi.chat(target, body, signal); }, /** The decisions on the changes a step holds; the stream carries their results and the rest of the turn. */ - async decide(tripId: number, threadId: number, body: AssistantDecisionsRequest, signal: AbortSignal) { + async decide(target: AssistantTarget, threadId: number, body: AssistantDecisionsRequest, signal: AbortSignal) { requireOnline(); - return assistantApi.decide(tripId, threadId, body, signal); + return assistantApi.decide(target, threadId, body, signal); }, /** A booking file for the chat to read; the stream proposes each booking found in it. */ @@ -68,9 +75,9 @@ export const assistantRepo = { return assistantApi.attach(tripId, form, signal); }, - async undo(tripId: number, toolCallId: string): Promise { + async undo(target: AssistantTarget, toolCallId: string): Promise { requireOnline(); - await assistantApi.undo(tripId, toolCallId); + await assistantApi.undo(target, toolCallId); }, /** A place a search found, held as a change for a day; no model runs for it. */ @@ -95,8 +102,48 @@ export const assistantRepo = { return collabMessageResponseSchema.parse(await assistantApi.share(tripId, threadId, messageId, body)); }, - async stop(tripId: number): Promise { + async stop(target: AssistantTarget): Promise { requireOnline(); - await assistantApi.stop(tripId); + await assistantApi.stop(target); + }, + + /** + * The book as the server holds it, to draw a page a Studio turn asked for + * at the version it names. Read fresh rather than from the Studio's copy, + * which keeps no version beside it. + */ + async pageBook(journeyId: number): Promise { + requireOnline(); + return (await journeyApi.getBook(journeyId)).book; + }, + + /** + * A design draft the assistant made, for a page of it a Studio turn asked + * for (`designId`): its book, at the version of the book it was made + * against, as the server names that version in the request. + */ + async pageDraft(journeyId: number, designId: string): Promise<{ version: number; document: BookDocument }> { + requireOnline(); + const draft = await assistantApi.bookDesign(journeyId, designId); + return { version: draft.baseVersion ?? 0, document: draft.document }; + }, + + /** A page a Studio turn asked for, drawn: the image, its page and version, and the photos it shows. */ + async uploadRender( + journeyId: number, + threadId: number, + requestId: string, + page: { image: Blob; bookVersion: number; spreadId: string; drawnPhotoIds: readonly number[] }, + signal: AbortSignal + ): Promise { + requireOnline(); + const form = new FormData(); + form.append('image', page.image, 'page.jpg'); + form.append('bookVersion', String(page.bookVersion)); + form.append('spreadId', page.spreadId); + if (page.drawnPhotoIds.length > 0) form.append('drawnPhotoIds', page.drawnPhotoIds.join(',')); + assistantRenderUploadResponseSchema.parse( + await assistantApi.uploadRender(journeyId, threadId, requestId, form, signal) + ); }, }; diff --git a/client/src/store/assistantChatKey.ts b/client/src/store/assistantChatKey.ts new file mode 100644 index 000000000..e072d5067 --- /dev/null +++ b/client/src/store/assistantChatKey.ts @@ -0,0 +1,31 @@ +import type { AssistantScope } from '@trek/shared'; + +import type { AssistantTarget } from '../api/assistant'; + +/** + * The key the assistant store keeps a conversation under, and the one every + * part of the chat passes back to it: a trip's id for the planner's chat, and + * the journey's id negated for the chat in TREK Studio. Trip ids are positive + * (a trip is never made offline with a temporary id), so the two never meet, + * and the parts that only make sense on a trip (the map, the day list, found + * places) find no trip under a journey's key and stay empty. + * + * A number rather than `assistantScopeKey`'s `journey:12`, so the trip chat + * keeps the key it always had and every part that reads it stays as it is. + */ +export type AssistantChatKey = number; + +/** The key a scope's chat is kept under. */ +export function assistantChatKey(scope: AssistantScope): AssistantChatKey { + return scope.kind === 'trip' ? scope.tripId : -scope.journeyId; +} + +/** What the chat under a key is about. */ +export function assistantScopeOf(key: AssistantChatKey): AssistantScope { + return key < 0 ? { kind: 'journey', journeyId: -key } : { kind: 'trip', tripId: key }; +} + +/** What the repo is called with for the chat under a key: a trip's id as it always was, a journey's scope. */ +export function assistantTargetOf(key: AssistantChatKey): AssistantTarget { + return key < 0 ? assistantScopeOf(key) : key; +} diff --git a/client/src/store/assistantStore.journey.test.ts b/client/src/store/assistantStore.journey.test.ts new file mode 100644 index 000000000..2f5373b3f --- /dev/null +++ b/client/src/store/assistantStore.journey.test.ts @@ -0,0 +1,187 @@ +/** + * FE-AI-STORE-JRN-001 to FE-AI-STORE-JRN-006 + * + * A journey's chat (the assistant in TREK Studio) in the same store as the + * trips': kept under its own key, beside a trip with the same id; every call + * the two have goes out with the journey's scope; an applied change does not + * make the planner jump; the trip-only actions (files, found places, + * proposals) do nothing for it. The repo is faked, nothing reaches Dexie. + */ +import type { AssistantMessage, AssistantThreadResponse, UiStreamChunk } from '@trek/shared'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import { assistantRepo } from '../repo/assistantRepo'; +import { assistantChatKey, assistantScopeOf, assistantTargetOf } from './assistantChatKey'; +import { chatOf, useAssistantStore } from './assistantStore'; +import { useSettingsStore } from './settingsStore'; + +const JOURNEY = 12; +const KEY = assistantChatKey({ kind: 'journey', journeyId: JOURNEY }); +const SCOPE = { kind: 'journey', journeyId: JOURNEY } as const; +const WRITE_ID = 'c0ffee00-0000-4000-8000-000000000002'; +const AT = '2026-10-22T08:00:00.000Z'; + +const HELD_TURN: UiStreamChunk[] = [ + { type: 'start', messageId: 'msg-1' }, + { type: 'data-trek-thread', data: { threadId: 9, title: 'Lisbon book' } }, + { type: 'text-delta', id: 't', delta: 'A quieter cover.' }, + { type: 'tool-input-available', toolCallId: WRITE_ID, toolName: 'set_book_cover', input: { title: 'Lisbon' } }, + { type: 'tool-approval-request', approvalId: WRITE_ID, toolCallId: WRITE_ID }, + { type: 'finish', finishReason: 'tool-calls' }, +]; + +const APPLIED_TURN: UiStreamChunk[] = [ + { type: 'start', messageId: 'msg-1' }, + { type: 'tool-output-available', toolCallId: WRITE_ID, output: { version: 4 } }, + { + type: 'data-trek-applied', + data: { toolCallId: WRITE_ID, entity: 'book_page', ids: [], dayId: null, undoUntil: '2026-10-22T08:15:00.000Z' }, + }, + { type: 'finish', finishReason: 'stop' }, +]; + +async function* streamOf(chunks: UiStreamChunk[]): AsyncGenerator { + for (const chunk of chunks) yield chunk; +} + +const store = () => useAssistantStore.getState(); +const chat = () => chatOf(store(), KEY); + +async function heldTurn() { + vi.spyOn(assistantRepo, 'send').mockResolvedValueOnce(streamOf(HELD_TURN)); + await store().send(KEY, 'Make the cover quieter'); +} + +beforeEach(() => { + useAssistantStore.setState({ + status: null, + window: { open: false, minimized: false }, + byTrip: {}, + lastApplied: null, + }); + useSettingsStore.setState((s) => ({ settings: { ...s.settings, language: 'en' } })); +}); +afterEach(() => vi.restoreAllMocks()); + +describe('assistantChatKey', () => { + it('FE-AI-STORE-JRN-001: a trip keeps its id as key, a journey gets one no trip has, and both read back', () => { + expect(assistantChatKey({ kind: 'trip', tripId: JOURNEY })).toBe(JOURNEY); + expect(KEY).not.toBe(JOURNEY); + expect(assistantScopeOf(KEY)).toEqual(SCOPE); + expect(assistantScopeOf(JOURNEY)).toEqual({ kind: 'trip', tripId: JOURNEY }); + // The repo is called with a trip's bare id as it always was, and with the scope for a journey. + expect(assistantTargetOf(JOURNEY)).toBe(JOURNEY); + expect(assistantTargetOf(KEY)).toEqual(SCOPE); + }); +}); + +describe('assistantStore: a journey chat', () => { + it('FE-AI-STORE-JRN-002: sends with the journey scope, apart from the trip with the same id', async () => { + store().setFocus(KEY, { spreadId: 'sp-3' }); + const send = vi.spyOn(assistantRepo, 'send').mockResolvedValueOnce(streamOf(HELD_TURN)); + + await store().send(KEY, ' Make the cover quieter '); + + const [target, body] = send.mock.calls[0] ?? []; + expect(target).toEqual(SCOPE); + expect(body).toMatchObject({ + locale: 'en', + threadId: null, + text: 'Make the cover quieter', + focus: { spreadId: 'sp-3' }, + }); + expect(chat()).toMatchObject({ threadId: 9, isRunning: false, error: null }); + expect(chat().messages.map((m) => [m.role, m.status])).toEqual([ + ['user', 'complete'], + ['assistant', 'awaiting_approval'], + ]); + expect(chatOf(store(), JOURNEY)).toMatchObject({ threadId: null, messages: [] }); + }); + + it('FE-AI-STORE-JRN-003: resume, open and delete reach the journey threads', async () => { + const thread: AssistantThreadResponse = { + thread: { id: 9, title: 'Lisbon book', lastMessageAt: AT }, + messages: [{ id: '1', role: 'user', parts: [{ type: 'text', text: 'Hi' }], status: 'complete', createdAt: AT }], + }; + const threads = vi.spyOn(assistantRepo, 'threads').mockResolvedValueOnce([thread.thread]); + const open = vi.spyOn(assistantRepo, 'thread').mockResolvedValueOnce(thread); + + await store().resume(KEY); + + expect(threads).toHaveBeenCalledWith(SCOPE); + expect(open).toHaveBeenCalledWith(SCOPE, 9); + expect(chat()).toMatchObject({ threadId: 9, messages: thread.messages, loading: false }); + + const remove = vi.spyOn(assistantRepo, 'deleteThread').mockResolvedValueOnce(undefined); + await store().deleteThread(KEY, 9); + expect(remove).toHaveBeenCalledWith(SCOPE, 9); + expect(chat()).toMatchObject({ threadId: null, messages: [], threads: [] }); + }); + + it('FE-AI-STORE-JRN-004: a decision goes to the journey thread; an applied change leaves the planner', async () => { + await heldTurn(); + const decide = vi.spyOn(assistantRepo, 'decide').mockResolvedValueOnce(streamOf(APPLIED_TURN)); + + await store().decide(KEY, [{ toolCallId: WRITE_ID, approved: true }]); + + expect(decide).toHaveBeenCalledWith( + SCOPE, + 9, + expect.objectContaining({ decisions: [{ toolCallId: WRITE_ID, approved: true }] }), + expect.any(AbortSignal) + ); + expect(chat().messages[1]?.status).toBe('complete'); + expect(chat().compare).toBeNull(); + expect(store().lastApplied).toBeNull(); + }); + + it('FE-AI-STORE-JRN-005: undo and "continue here" carry the journey scope; a stale undo closes', async () => { + const receipt: AssistantMessage = { + id: 'a', + role: 'assistant', + status: 'complete', + createdAt: AT, + parts: [ + { + type: 'data-trek-applied', + data: { + toolCallId: WRITE_ID, + entity: 'book_page', + ids: [], + dayId: null, + undoUntil: '2026-10-22T08:15:00.000Z', + }, + }, + ], + }; + useAssistantStore.setState({ byTrip: { [KEY]: { ...chat(), threadId: 9, messages: [receipt] } } }); + const undo = vi.spyOn(assistantRepo, 'undo').mockRejectedValueOnce({ response: { status: 409 } }); + + await expect(store().undo(KEY, WRITE_ID)).resolves.toBe('stale'); + expect(undo).toHaveBeenCalledWith(SCOPE, WRITE_ID); + const part = chat().messages[0]?.parts[0]; + expect(part?.type === 'data-trek-applied' ? part.data.undoUntil : 'missing').toBeNull(); + + const stop = vi.spyOn(assistantRepo, 'stop').mockResolvedValueOnce(undefined); + vi.spyOn(assistantRepo, 'send').mockResolvedValueOnce(streamOf([{ type: 'finish' }])); + useAssistantStore.setState({ byTrip: { [KEY]: { ...chat(), unsent: 'Again' } } }); + await store().continueHere(KEY); + expect(stop).toHaveBeenCalledWith(SCOPE); + }); + + it('FE-AI-STORE-JRN-006: files, found places and proposals do nothing in a journey chat', async () => { + useAssistantStore.setState({ byTrip: { [KEY]: { ...chat(), threadId: 9 } } }); + const attach = vi.spyOn(assistantRepo, 'attach'); + const found = vi.spyOn(assistantRepo, 'addFoundPlace'); + const proposal = vi.spyOn(assistantRepo, 'takeProposal'); + + await store().attach(KEY, new File(['x'], 'booking.pdf', { type: 'application/pdf' })); + await store().addFoundPlace(KEY, 's1:0', 31); + await expect(store().takeProposal(KEY, WRITE_ID)).resolves.toBe('skipped'); + + expect(attach).not.toHaveBeenCalled(); + expect(found).not.toHaveBeenCalled(); + expect(proposal).not.toHaveBeenCalled(); + expect(chat()).toMatchObject({ messages: [], isRunning: false, error: null }); + }); +}); diff --git a/client/src/store/assistantStore.ts b/client/src/store/assistantStore.ts index ab9419805..559d44b39 100644 --- a/client/src/store/assistantStore.ts +++ b/client/src/store/assistantStore.ts @@ -10,6 +10,7 @@ import { type AssistantMention, type AssistantMessage, type AssistantMessagePart, + type AssistantPageRender, type AssistantThreadSummary, type UiStreamChunk, } from '@trek/shared'; @@ -21,6 +22,7 @@ import { OnlineOnlyError } from '../repo/onlineOnly'; import type { Assignment } from '../types'; import { randomId } from '../utils/randomId'; import type { RouteProfileFocus } from '../utils/routeGeometry'; +import { assistantScopeOf, assistantTargetOf, type AssistantChatKey } from './assistantChatKey'; import { blockDays, blockKeyOf, @@ -35,8 +37,12 @@ import { useSettingsStore } from './settingsStore'; import { useTripStore } from './tripStore'; /** - * The trip assistant: whether it can run, whether its window is open, and one - * conversation per trip. + * The assistant: whether it can run, whether its window is open, and one + * conversation per trip and one per journey (the chat in TREK Studio), each + * under its `AssistantChatKey`. The actions both kinds of chat have take that + * key; the ones that only make sense on a trip (files, found places, + * proposals, the before and after on the map) take a trip's id and do nothing + * for a journey's key. * * Online-only like the repos it calls; nothing here reaches Dexie. Messages * are kept in the server's stored shape (`AssistantMessage`), and the stream @@ -114,8 +120,9 @@ interface AssistantState { /** What the assistant runs on for this user; null until loaded, and the assistant stays hidden until then. */ status: AiStatusResponse | null; window: { open: boolean; minimized: boolean }; - byTrip: Record; - /** The change applied last, for the planner to jump to it. */ + /** The chats by `AssistantChatKey`: a trip's id, or a journey's key. */ + byTrip: Record; + /** The change applied last in a trip's chat, for the planner to jump to it. */ lastApplied: { tripId: number; applied: AssistantApplied } | null; /** * The change under the pointer, shared by its card row and its pin on the @@ -140,45 +147,51 @@ interface AssistantState { windowRect: WindowRect | null; /** The part of the planner's map on screen, sent with a question so "here" means it. */ mapView: { tripId: number; view: AssistantMapView } | null; + /** The TREK Studio hosting a journey's chat, by the chat's key, while that chat is open there. */ + studioHosts: Record; loadStatus: () => Promise; ackPrivacy: () => Promise; + /** The user let the effective connection receive images of their Studio pages. */ + ackStudioImages: () => Promise; + /** Hosts a journey's chat in the Studio; the returned function ends it, unless another host took the key since. */ + hostStudio: (key: AssistantChatKey, host: AssistantStudioHost) => () => void; open: () => void; close: () => void; toggle: () => void; setMinimized: (minimized: boolean) => void; - /** Opens the window on a trip with a context chip ("Ask" on a place). */ - openWith: (tripId: number, focus: AssistantFocus | null) => void; - setFocus: (tripId: number, focus: AssistantFocus | null) => void; - setDraft: (tripId: number, draft: string) => void; + /** Opens the window on a chat with a context chip ("Ask" on a place). */ + openWith: (key: AssistantChatKey, focus: AssistantFocus | null) => void; + setFocus: (key: AssistantChatKey, focus: AssistantFocus | null) => void; + setDraft: (key: AssistantChatKey, draft: string) => void; /** Loads the thread list and, when nothing is open yet, the latest thread. */ - resume: (tripId: number) => Promise; - loadThreads: (tripId: number) => Promise; - openThread: (tripId: number, threadId: number) => Promise; - newThread: (tripId: number) => void; - deleteThread: (tripId: number, threadId: number) => Promise; + resume: (key: AssistantChatKey) => Promise; + loadThreads: (key: AssistantChatKey) => Promise; + openThread: (key: AssistantChatKey, threadId: number) => Promise; + newThread: (key: AssistantChatKey) => void; + deleteThread: (key: AssistantChatKey, threadId: number) => Promise; - send: (tripId: number, text: string) => Promise; - /** Hands a booking file to the chat, which proposes what it finds in it. */ - attach: (tripId: number, file: File) => Promise; - decide: (tripId: number, decisions: AssistantDecision[]) => Promise; - undo: (tripId: number, toolCallId: string) => Promise; - cancel: (tripId: number) => void; + send: (key: AssistantChatKey, text: string) => Promise; + /** Hands a booking file to a trip's chat, which proposes what it finds in it; does nothing under a journey key. */ + attach: (key: AssistantChatKey, file: File) => Promise; + decide: (key: AssistantChatKey, decisions: AssistantDecision[]) => Promise; + undo: (key: AssistantChatKey, toolCallId: string) => Promise; + cancel: (key: AssistantChatKey) => void; /** Sends the last question again: the refused message, or the one whose answer broke off. */ - retry: (tripId: number) => Promise; + retry: (key: AssistantChatKey) => Promise; /** Stops the turn running in another window, then sends here. */ - continueHere: (tripId: number) => Promise; - dismissError: (tripId: number) => void; + continueHere: (key: AssistantChatKey) => Promise; + dismissError: (key: AssistantChatKey) => void; /** Takes back the applied changes of one block, the last one first. */ - undoBlock: (tripId: number, toolCallIds: readonly string[]) => Promise; - /** Shows the plan before or after the last applied block, on the map. */ - setCompare: (tripId: number, mode: 'before' | 'after') => void; - /** Suggests a place a search found for a day; the server holds it as a change to decide like any other. */ - addFoundPlace: (tripId: number, ref: string, dayId: number) => Promise; - addMention: (tripId: number, mention: AssistantMentionItem) => void; + undoBlock: (key: AssistantChatKey, toolCallIds: readonly string[]) => Promise; + /** Shows the plan before or after the last applied block, on the map; a journey chat has none to show. */ + setCompare: (key: AssistantChatKey, mode: 'before' | 'after') => void; + /** Suggests a found place for a day, held as a change to decide; skipped under a journey key. */ + addFoundPlace: (key: AssistantChatKey, ref: string, dayId: number) => Promise; + addMention: (key: AssistantChatKey, mention: AssistantMentionItem) => void; setMapHover: (tripId: number, hoveredId: string | null, source: AssistantMapSource) => void; requestCamera: (tripId: number, points: LatLng[], mode: 'fit' | 'pan', why: 'user' | 'auto') => void; @@ -190,18 +203,46 @@ interface AssistantState { setRoutePreview: (routePreview: AssistantState['routePreview']) => void; setRoutePeek: (routePeek: AssistantState['routePeek']) => void; /** Picks one of the ways a block of cards offers. */ - pick: (tripId: number, blockKey: string, toolCallId: string) => void; + pick: (key: AssistantChatKey, blockKey: string, toolCallId: string) => void; /** * Takes a proposal an answer showed as a card ("Plan this"); the server holds it as a change to decide. * Says what came of it: held, refused (the chat's error says why), or skipped while a turn ran or the - * thread changed under it. + * thread changed under it, and always skipped under a journey key. */ - takeProposal: (tripId: number, toolCallId: string) => Promise; + takeProposal: (key: AssistantChatKey, toolCallId: string) => Promise; } /** What came of a change the server was asked to hold without a model turn. */ export type HoldOutcome = 'held' | 'refused' | 'skipped'; +/** + * What the TREK Studio holding a journey's chat does for its turns: it writes + * the work still sitting in its autosave before a turn or an apply goes out, + * so the assistant edits the book the user sees, and it draws the pages a + * turn asks to look at (journey-studio.md 3.1). A chat with no host sends text only. + */ +export interface AssistantStudioHost { + /** Draws the page a running turn asked for and uploads it; never throws, a page it cannot send stays text. */ + render: (request: AssistantPageRender, signal: AbortSignal) => void; + /** Writes the local work of the book; false when it could not land (a conflict, a viewer, offline). */ + flush: () => Promise; +} + +/** The Studio hosting the chat under `key`, if one does. */ +const studioHostOf = (ctx: Ctx, key: AssistantChatKey): AssistantStudioHost | undefined => ctx.get().studioHosts[key]; + +/** A turn of a hosted chat writes the book first and says the Studio draws pages; any other turn opens as it is. */ +async function hostedOpen(ctx: Ctx, key: AssistantChatKey, open: (renders: { renders?: true }) => Promise) { + const host = studioHostOf(ctx, key); + if (!host) return open({}); + try { + await host.flush(); + } catch { + // The Studio's save indicator shows its own failure; the turn goes on against the book the server holds. + } + return open({ renders: true }); +} + const NO_LIVE: AssistantTripChat['live'] = { activity: null }; const EMPTY_CHAT: AssistantTripChat = { @@ -225,9 +266,9 @@ const EMPTY_CHAT: AssistantTripChat = { /** What the map shows for the cards of a chat, cleared when the chat closes or changes. */ const NO_ROUTE = { routeFocus: null, routePreview: null, routePeek: null } as const; -/** A trip's chat as the store holds it, or the empty one; stable, so a selector can return it. */ -export function chatOf(state: Pick, tripId: number): AssistantTripChat { - return state.byTrip[tripId] ?? EMPTY_CHAT; +/** A chat as the store holds it, or the empty one; stable, so a selector can return it. */ +export function chatOf(state: Pick, key: AssistantChatKey): AssistantTripChat { + return state.byTrip[key] ?? EMPTY_CHAT; } function httpStatus(err: unknown): number | undefined { @@ -288,8 +329,8 @@ function patch(ctx: Ctx, tripId: number, next: Partial) { ctx.set((s) => ({ byTrip: { ...s.byTrip, [tripId]: { ...chatOf(s, tripId), ...next } } })); } -/** What the store takes from a chunk beside the messages. */ -function onChunk(ctx: Ctx, tripId: number, chunk: UiStreamChunk) { +/** What the store takes from a chunk beside the messages; `signal` ends with the turn. */ +function onChunk(ctx: Ctx, tripId: number, chunk: UiStreamChunk, signal: AbortSignal) { if (chunk.type === 'data-trek-thread') { const { threadId, title } = chunk.data; const threads = chat(ctx, tripId).threads; @@ -299,8 +340,11 @@ function onChunk(ctx: Ctx, tripId: number, chunk: UiStreamChunk) { const status = ctx.get().status; if (status) ctx.set({ status: { ...status, quota: chunk.data } }); } else if (chunk.type === 'data-trek-applied') { - ctx.set({ lastApplied: { tripId, applied: chunk.data } }); - noteAddedPlace(ctx, tripId, chunk.data); + // The planner jumps to a trip's change; the Studio hears a book change through its broadcast. + if (assistantScopeOf(tripId).kind === 'trip') { + ctx.set({ lastApplied: { tripId, applied: chunk.data } }); + noteAddedPlace(ctx, tripId, chunk.data); + } // A kept note lives in the user's settings; read them again so the notes dialog shows it. if (chunk.data.entity === 'memory') void useSettingsStore.getState().loadSettings(); } else if (chunk.type === 'data-trek-activity') { @@ -308,6 +352,9 @@ function onChunk(ctx: Ctx, tripId: number, chunk: UiStreamChunk) { } else if (chunk.type === 'tool-output-available' || chunk.type === 'tool-output-error') { // The step the line spoke of is done; the next one says what it does itself. if (chat(ctx, tripId).live.activity) patch(ctx, tripId, { live: NO_LIVE }); + } else if (chunk.type === 'data-trek-render-request') { + // The Studio holding this chat draws the page; without one the turn waits out its time and goes on as text. + studioHostOf(ctx, tripId)?.render(chunk.data, signal); } } @@ -356,7 +403,7 @@ async function runTurn(ctx: Ctx, tripId: number, turn: Turn): Promise { for await (const chunk of stream) { current = applyChunk(current, chunk); if (chunk.type === 'error') error = chunk.errorText; - if (live()) onChunk(ctx, tripId, chunk); + if (live()) onChunk(ctx, tripId, chunk, abort.signal); commit.schedule(); } } catch (err) { @@ -404,13 +451,17 @@ async function sendMessage(ctx: Ctx, tripId: number, text: string): Promise assistantRepo.send(tripId, body, signal), + open: (signal) => + hostedOpen(ctx, tripId, (renders) => + assistantRepo.send(assistantTargetOf(tripId), { ...body, ...renders }, signal) + ), }); } async function attachFile(ctx: Ctx, tripId: number, file: File): Promise { const c = chat(ctx, tripId); - if (c.isRunning) return; + // Files are read into a trip; a journey's chat has no route for them. + if (c.isRunning || assistantScopeOf(tripId).kind !== 'trip') return; const question: AssistantMessage = { id: `local-${randomId()}`, role: 'user', @@ -486,6 +537,22 @@ function shellActions(ctx: Ctx) { const status = ctx.get().status; if (status) ctx.set({ status: { ...status, privacyAcked: true } }); }, + ackStudioImages: async () => { + const effective = ctx.get().status?.effective; + if (!effective) return; + await aiConnectionsRepo.ackPrivacy({ kind: effective.kind, host: effective.host, scope: 'studio_images' }); + const status = ctx.get().status; + if (status) ctx.set({ status: { ...status, studioImagesAcked: true } }); + }, + hostStudio: (key: AssistantChatKey, host: AssistantStudioHost) => { + ctx.set((s) => ({ studioHosts: { ...s.studioHosts, [key]: host } })); + return () => { + if (ctx.get().studioHosts[key] !== host) return; + ctx.set((s) => ({ + studioHosts: Object.fromEntries(Object.entries(s.studioHosts).filter(([k]) => Number(k) !== key)), + })); + }; + }, open: () => ctx.set({ window: { open: true, minimized: false } }), // Closing leaves the map as the plan is now: "after", nothing hovered, no preview pin. close: () => @@ -511,7 +578,7 @@ function shellActions(ctx: Ctx) { function threadActions(ctx: Ctx) { const loadThreads = async (tripId: number) => { try { - patch(ctx, tripId, { threads: await assistantRepo.threads(tripId) }); + patch(ctx, tripId, { threads: await assistantRepo.threads(assistantTargetOf(tripId)) }); } catch (err) { patch(ctx, tripId, { error: errorCodeOf(err) }); } @@ -522,7 +589,7 @@ function threadActions(ctx: Ctx) { ctx.set(NO_ROUTE); patch(ctx, tripId, { threadId, loading: true, error: null, unsent: null }); try { - const { messages } = await assistantRepo.thread(tripId, threadId); + const { messages } = await assistantRepo.thread(assistantTargetOf(tripId), threadId); // Another thread may have been opened while this one loaded. if (chat(ctx, tripId).threadId === threadId) patch(ctx, tripId, { messages, loading: false }); } catch (err) { @@ -568,7 +635,7 @@ function threadActions(ctx: Ctx) { if (latest && c.threadId === null && c.messages.length === 0 && !c.isRunning) await openThread(tripId, latest.id); }, deleteThread: async (tripId: number, threadId: number) => { - await assistantRepo.deleteThread(tripId, threadId); + await assistantRepo.deleteThread(assistantTargetOf(tripId), threadId); const c = chat(ctx, tripId); patch(ctx, tripId, { threads: c.threads ? c.threads.filter((t) => t.id !== threadId) : null }); if (c.threadId === threadId) newThread(tripId); @@ -579,7 +646,7 @@ function threadActions(ctx: Ctx) { async function undoOne(ctx: Ctx, tripId: number, toolCallId: string): Promise { let outcome: UndoOutcome; try { - await assistantRepo.undo(tripId, toolCallId); + await assistantRepo.undo(assistantTargetOf(tripId), toolCallId); outcome = 'undone'; } catch (err) { const status = httpStatus(err); @@ -677,6 +744,8 @@ async function holdWithoutTurn( hold: (threadId: number) => Promise<{ message: AssistantMessage }> ): Promise { const threadId = chat(ctx, tripId).threadId; + // Found places and proposals are held for a trip's days; a journey's chat has neither. + if (assistantScopeOf(tripId).kind !== 'trip') return 'skipped'; if (chat(ctx, tripId).isRunning || threadId === null) return 'skipped'; try { const { message } = await hold(threadId); @@ -779,7 +848,10 @@ function turnActions(ctx: Ctx) { messages: markDecisions(c.messages, decisions), before: c.messages, unsent: null, - open: (signal) => assistantRepo.decide(tripId, threadId, body, signal), + open: (signal) => + hostedOpen(ctx, tripId, (renders) => + assistantRepo.decide(assistantTargetOf(tripId), threadId, { ...body, ...renders }, signal) + ), }); // Refused before anything ran: there is no "after" to compare with. if (chat(ctx, tripId).error) patch(ctx, tripId, { compare: null }); @@ -789,7 +861,7 @@ function turnActions(ctx: Ctx) { retry, continueHere: async (tripId: number) => { try { - await assistantRepo.stop(tripId); + await assistantRepo.stop(assistantTargetOf(tripId)); } catch (err) { patch(ctx, tripId, { error: errorCodeOf(err) }); return; @@ -812,6 +884,7 @@ export const useAssistantStore = create((set, get) => { preview: null, windowRect: null, mapView: null, + studioHosts: {}, ...NO_ROUTE, ...shellActions(ctx), ...threadActions(ctx), diff --git a/client/src/sync/mutationQueue.ts b/client/src/sync/mutationQueue.ts index b3e65109a..05ba4a3dc 100644 --- a/client/src/sync/mutationQueue.ts +++ b/client/src/sync/mutationQueue.ts @@ -97,6 +97,8 @@ let _lastTempId = 0 /** * Mint a collision-free temporary (negative) id for an offline-created entity. * Monotonic across the session so same-millisecond creates never collide. + * Never use it for trips: the assistant keys a journey's chat by the negated + * journey id (store/assistantChatKey.ts) and relies on trip ids being positive. */ export function nextTempId(): number { const now = Date.now() diff --git a/server/src/db/entities/AssistantThreads.entity.ts b/server/src/db/entities/AssistantThreads.entity.ts index 0171734ac..fb8fd654a 100644 --- a/server/src/db/entities/AssistantThreads.entity.ts +++ b/server/src/db/entities/AssistantThreads.entity.ts @@ -3,6 +3,7 @@ import { AssistantThreadsRepository } from '../repositories/AssistantThreads.rep import { DbTimestampType } from '../types'; import { AssistantMessages } from './AssistantMessages.entity'; import { AssistantToolCalls } from './AssistantToolCalls.entity'; +import { Journeys } from './Journeys.entity'; import { Trips } from './Trips.entity'; import { Users } from './Users.entity'; @@ -11,8 +12,10 @@ export class AssistantThreads { id!: number & Opt; user!: Ref; user_id!: number; - trip!: Ref; - trip_id!: number; + trip?: Ref | null; + trip_id?: number | null; + journey?: Ref | null; + journey_id?: number | null; title!: string; created_at!: string & Opt; last_message_at!: string & Opt; @@ -28,13 +31,19 @@ export const AssistantThreadsSchema = defineEntity({ name: 'idx_assistant_threads_user_trip', properties: ['user_id', 'trip_id', 'last_message_at'], }, + { + name: 'idx_assistant_threads_user_journey', + properties: ['user_id', 'journey_id', 'last_message_at'], + }, ], properties: { id: p.integer().primary(), user: () => p.manyToOne(Users).ref().deleteRule('cascade').hidden(), user_id: p.integer().persist(false), - trip: () => p.manyToOne(Trips).ref().deleteRule('cascade').hidden().index('idx_assistant_threads_trip'), - trip_id: p.integer().persist(false).index('idx_assistant_threads_trip'), + trip: () => p.manyToOne(Trips).ref().deleteRule('cascade').nullable().hidden().index('idx_assistant_threads_trip'), + trip_id: p.integer().nullable().persist(false).index('idx_assistant_threads_trip'), + journey: () => p.manyToOne(Journeys).ref().deleteRule('cascade').nullable().hidden().index('idx_assistant_threads_journey'), + journey_id: p.integer().nullable().persist(false).index('idx_assistant_threads_journey'), title: p.text(), created_at: p.type(DbTimestampType).defaultRaw(`CURRENT_TIMESTAMP`), last_message_at: p.type(DbTimestampType).defaultRaw(`CURRENT_TIMESTAMP`), diff --git a/server/src/db/kysely/AssistantThreads.table.ts b/server/src/db/kysely/AssistantThreads.table.ts index 3ee20fa4c..099abcc01 100644 --- a/server/src/db/kysely/AssistantThreads.table.ts +++ b/server/src/db/kysely/AssistantThreads.table.ts @@ -5,7 +5,8 @@ import type { InsertOptional } from './columns'; export interface AssistantThreadsTable { id: InsertOptional; user_id: number; - trip_id: number; + trip_id: InsertOptional; + journey_id: InsertOptional; title: string; created_at: InsertOptional; last_message_at: InsertOptional; diff --git a/server/src/db/migrations/Migration20200101046250_an_assistant_conversation_can_be_about_a_journey.ts b/server/src/db/migrations/Migration20200101046250_an_assistant_conversation_can_be_about_a_journey.ts new file mode 100644 index 000000000..138938445 --- /dev/null +++ b/server/src/db/migrations/Migration20200101046250_an_assistant_conversation_can_be_about_a_journey.ts @@ -0,0 +1,108 @@ +import { Migration } from '@mikro-orm/migrations'; + +/** + * An assistant conversation can be about a journey instead of a trip: the + * Studio's chat works on a journey's book, and a journey need not belong to a + * trip at all. `assistant_threads.trip_id` may now be NULL, `journey_id` names + * the journey (and goes with it), and a CHECK holds every thread to exactly + * one of the two. Every existing thread is a trip thread and stays one. + * + * SQLite cannot drop a NOT NULL in place, so the table is rebuilt. With + * `foreign_keys = ON` a `DROP TABLE assistant_threads` runs an implicit + * `DELETE FROM assistant_threads` first, and the `ON DELETE CASCADE` on + * `assistant_messages` and `assistant_tool_calls` would empty both. So both + * are rebuilt as well, pointing at the new tables, and the old ones go + * children first: by the time the old threads table goes nothing references + * it. Renaming each new table to its old name rewrites the foreign keys that + * point at it. Every id is copied, so a thread, a message and a proposed + * change keep theirs; the two child tables come back exactly as they were. + * + * The journey index leads with `journey_id` (a journey deleted finds its + * threads by seeking) and the listing index mirrors the trip one. + */ +export class Migration20200101046250_an_assistant_conversation_can_be_about_a_journey extends Migration { + override name = 'Migration20200101046250_an_assistant_conversation_can_be_about_a_journey'; + + override up(): void { + this.addSql(` + CREATE TABLE assistant_threads_new ( + id INTEGER PRIMARY KEY, + user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, + trip_id INTEGER REFERENCES trips(id) ON DELETE CASCADE, + journey_id INTEGER REFERENCES journeys(id) ON DELETE CASCADE, + title TEXT NOT NULL, + created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + last_message_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + CHECK((trip_id IS NULL) <> (journey_id IS NULL)) + ) + `); + this.addSql(` + INSERT INTO assistant_threads_new (id, user_id, trip_id, title, created_at, last_message_at) + SELECT id, user_id, trip_id, title, created_at, last_message_at FROM assistant_threads + `); + + this.addSql(` + CREATE TABLE assistant_messages_new ( + id INTEGER PRIMARY KEY, + thread_id INTEGER NOT NULL REFERENCES assistant_threads_new(id) ON DELETE CASCADE, + role TEXT NOT NULL CHECK(role IN ('user', 'assistant')), + parts TEXT NOT NULL, + provider_state TEXT, + status TEXT NOT NULL DEFAULT 'complete' CHECK(status IN ('complete', 'awaiting_approval', 'aborted', 'error')), + model TEXT, + created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP + ) + `); + this.addSql(` + INSERT INTO assistant_messages_new (id, thread_id, role, parts, provider_state, status, model, created_at) + SELECT id, thread_id, role, parts, provider_state, status, model, created_at FROM assistant_messages + `); + + this.addSql(` + CREATE TABLE assistant_tool_calls_new ( + id TEXT PRIMARY KEY NOT NULL, + thread_id INTEGER NOT NULL REFERENCES assistant_threads_new(id) ON DELETE CASCADE, + message_id INTEGER NOT NULL REFERENCES assistant_messages_new(id) ON DELETE CASCADE, + provider_call_id TEXT NOT NULL, + tool_name TEXT NOT NULL, + args TEXT NOT NULL, + preview TEXT NOT NULL, + state TEXT NOT NULL DEFAULT 'approval_requested' + CHECK(state IN ('approval_requested', 'approved', 'rejected', 'executed', 'failed', 'expired', 'undone')), + result TEXT, + undo_until DATETIME, + created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + decided_at DATETIME, + UNIQUE(thread_id, provider_call_id) + ) + `); + this.addSql(` + INSERT INTO assistant_tool_calls_new ( + id, thread_id, message_id, provider_call_id, tool_name, args, preview, state, result, undo_until, created_at, + decided_at + ) + SELECT + id, thread_id, message_id, provider_call_id, tool_name, args, preview, state, result, undo_until, created_at, + decided_at + FROM assistant_tool_calls + `); + + this.addSql('DROP TABLE assistant_tool_calls'); + this.addSql('DROP TABLE assistant_messages'); + this.addSql('DROP TABLE assistant_threads'); + this.addSql('ALTER TABLE assistant_threads_new RENAME TO assistant_threads'); + this.addSql('ALTER TABLE assistant_messages_new RENAME TO assistant_messages'); + this.addSql('ALTER TABLE assistant_tool_calls_new RENAME TO assistant_tool_calls'); + + this.addSql( + 'CREATE INDEX IF NOT EXISTS idx_assistant_threads_user_journey ON assistant_threads(user_id, journey_id, last_message_at)', + ); + this.addSql('CREATE INDEX IF NOT EXISTS idx_assistant_threads_journey ON assistant_threads(journey_id)'); + this.addSql( + 'CREATE INDEX IF NOT EXISTS idx_assistant_threads_user_trip ON assistant_threads(user_id, trip_id, last_message_at)', + ); + this.addSql('CREATE INDEX IF NOT EXISTS idx_assistant_threads_trip ON assistant_threads(trip_id)'); + this.addSql('CREATE INDEX IF NOT EXISTS idx_assistant_messages_thread ON assistant_messages(thread_id, id)'); + this.addSql('CREATE INDEX IF NOT EXISTS idx_assistant_tool_calls_message ON assistant_tool_calls(message_id)'); + } +} diff --git a/server/src/db/repositories/AssistantThreads.repository.ts b/server/src/db/repositories/AssistantThreads.repository.ts index 82ee3d853..78e940d86 100644 --- a/server/src/db/repositories/AssistantThreads.repository.ts +++ b/server/src/db/repositories/AssistantThreads.repository.ts @@ -3,11 +3,12 @@ import type { DB } from '../kysely/db'; import type { AssertRowKeys } from './_shared/rows'; import { TrekRepository } from './_shared/trek-repository'; -/** One `assistant_threads` row as stored. */ +/** One `assistant_threads` row as stored: about a trip or about a journey, never both. */ export interface AssistantThreadRow { id: number; user_id: number; - trip_id: number; + trip_id: number | null; + journey_id: number | null; title: string; created_at: string; last_message_at: string; @@ -17,19 +18,35 @@ const _assistantThreadRowKeys: AssertRowKeys; -const COLUMNS = ['id', 'user_id', 'trip_id', 'title', 'created_at', 'last_message_at'] as const; +/** What the retention sweep reads to tell who still reaches a thread's trip or journey. */ +type RetentionKyselyDB = Pick< + DB, + | 'assistant_threads' + | 'trips' + | 'trip_members' + | 'journeys' + | 'journey_contributors' + | 'trip_journal_links' + | 'trip_journal_link_members' +>; + +/** The column a thread names what it is about with. */ +type OwnerColumn = 'trip_id' | 'journey_id'; + +const COLUMNS = ['id', 'user_id', 'trip_id', 'journey_id', 'title', 'created_at', 'last_message_at'] as const; /** - * `assistant_threads`: a user's conversations about one trip. Every read and - * delete a request makes names the user and the trip next to the id, so a - * thread is only ever reached by its owner on its own trip. + * `assistant_threads`: a user's conversations about one trip, or (the Studio's) + * about one journey. Every read and delete a request makes names the user and + * the trip or journey next to the id, so a thread is only ever reached by its + * owner on its own trip or journey. */ export class AssistantThreadsRepository extends TrekRepository { private db() { return this.kysely(); } - /** A new thread; answers its id. `at` is both its creation and its last message (`dbNow()`). */ + /** A new thread about a trip; answers its id. `at` is both its creation and its last message (`dbNow()`). */ async createThread(userId: number, tripId: number, title: string, at: string): Promise { const row = await this.db() .insertInto('assistant_threads') @@ -39,28 +56,32 @@ export class AssistantThreadsRepository extends TrekRepository return row.id; } - async findOwned(id: number, userId: number, tripId: number): Promise { + /** A new thread about a journey; answers its id, as `createThread` does. */ + async createJourneyThread(userId: number, journeyId: number, title: string, at: string): Promise { const row = await this.db() - .selectFrom('assistant_threads') - .select(COLUMNS) - .where('id', '=', id) - .where('user_id', '=', userId) - .where('trip_id', '=', tripId) - .executeTakeFirst(); - return row ?? null; + .insertInto('assistant_threads') + .values({ user_id: userId, journey_id: journeyId, title, created_at: at, last_message_at: at }) + .returning('id') + .executeTakeFirstOrThrow(); + return row.id; + } + + async findOwned(id: number, userId: number, tripId: number): Promise { + return this.findOwnedBy(id, userId, 'trip_id', tripId); + } + + async findOwnedOnJourney(id: number, userId: number, journeyId: number): Promise { + return this.findOwnedBy(id, userId, 'journey_id', journeyId); } /** The user's threads on a trip, the most recently used first. */ async listRecent(userId: number, tripId: number, limit: number): Promise { - return this.db() - .selectFrom('assistant_threads') - .select(COLUMNS) - .where('user_id', '=', userId) - .where('trip_id', '=', tripId) - .orderBy('last_message_at', 'desc') - .orderBy('id', 'desc') - .limit(limit) - .execute(); + return this.listRecentBy(userId, 'trip_id', tripId, limit); + } + + /** The user's threads on a journey, the most recently used first. */ + async listRecentOnJourney(userId: number, journeyId: number, limit: number): Promise { + return this.listRecentBy(userId, 'journey_id', journeyId, limit); } async touch(id: number, at: string): Promise { @@ -69,13 +90,12 @@ export class AssistantThreadsRepository extends TrekRepository /** True when the thread was the user's on that trip and is gone now. */ async deleteOwned(id: number, userId: number, tripId: number): Promise { - const result = await this.db() - .deleteFrom('assistant_threads') - .where('id', '=', id) - .where('user_id', '=', userId) - .where('trip_id', '=', tripId) - .executeTakeFirst(); - return Number(result.numDeletedRows) > 0; + return this.deleteOwnedBy(id, userId, 'trip_id', tripId); + } + + /** True when the thread was the user's on that journey and is gone now. */ + async deleteOwnedOnJourney(id: number, userId: number, journeyId: number): Promise { + return this.deleteOwnedBy(id, userId, 'journey_id', journeyId); } /** Retention: drops the threads nobody wrote in since `cutoff`; answers how many went. */ @@ -90,33 +110,114 @@ export class AssistantThreadsRepository extends TrekRepository /** * Drops the threads of users who no longer own or belong to the trip they * are about: removed members keep no conversation about a trip they left. + * A journey thread goes once its user neither owns the journey nor is on its + * contributor list nor is named by one of its trip links. A link member who + * left the linking trip keeps the thread until the link drops them; every + * request checks the access itself, so such a thread is never reached. */ async deleteWithoutAccess(): Promise { - const result = await this.kysely>() + const result = await this.kysely() .deleteFrom('assistant_threads') .where((eb) => - eb.and([ - eb.not( - eb.exists( - eb - .selectFrom('trips') - .select('trips.id') - .whereRef('trips.id', '=', 'assistant_threads.trip_id') - .whereRef('trips.user_id', '=', 'assistant_threads.user_id'), + eb.or([ + eb.and([ + eb('assistant_threads.trip_id', 'is not', null), + eb.not( + eb.exists( + eb + .selectFrom('trips') + .select('trips.id') + .whereRef('trips.id', '=', 'assistant_threads.trip_id') + .whereRef('trips.user_id', '=', 'assistant_threads.user_id'), + ), ), - ), - eb.not( - eb.exists( - eb - .selectFrom('trip_members') - .select('trip_members.id') - .whereRef('trip_members.trip_id', '=', 'assistant_threads.trip_id') - .whereRef('trip_members.user_id', '=', 'assistant_threads.user_id'), + eb.not( + eb.exists( + eb + .selectFrom('trip_members') + .select('trip_members.id') + .whereRef('trip_members.trip_id', '=', 'assistant_threads.trip_id') + .whereRef('trip_members.user_id', '=', 'assistant_threads.user_id'), + ), ), - ), + ]), + eb.and([ + eb('assistant_threads.journey_id', 'is not', null), + eb.not( + eb.exists( + eb + .selectFrom('journeys') + .select('journeys.id') + .whereRef('journeys.id', '=', 'assistant_threads.journey_id') + .whereRef('journeys.user_id', '=', 'assistant_threads.user_id'), + ), + ), + eb.not( + eb.exists( + eb + .selectFrom('journey_contributors') + .select('journey_contributors.journey_id') + .whereRef('journey_contributors.journey_id', '=', 'assistant_threads.journey_id') + .whereRef('journey_contributors.user_id', '=', 'assistant_threads.user_id'), + ), + ), + eb.not( + eb.exists( + eb + .selectFrom('trip_journal_links') + .innerJoin('trip_journal_link_members', 'trip_journal_link_members.link_id', 'trip_journal_links.id') + .select('trip_journal_links.id') + .whereRef('trip_journal_links.journey_id', '=', 'assistant_threads.journey_id') + .whereRef('trip_journal_link_members.user_id', '=', 'assistant_threads.user_id'), + ), + ), + ]), ]), ) .executeTakeFirst(); return Number(result.numDeletedRows); } + + private async findOwnedBy( + id: number, + userId: number, + column: OwnerColumn, + ownerId: number, + ): Promise { + const row = await this.db() + .selectFrom('assistant_threads') + .select(COLUMNS) + .where('id', '=', id) + .where('user_id', '=', userId) + .where(column, '=', ownerId) + .executeTakeFirst(); + return row ?? null; + } + + private async listRecentBy( + userId: number, + column: OwnerColumn, + ownerId: number, + limit: number, + ): Promise { + return this.db() + .selectFrom('assistant_threads') + .select(COLUMNS) + .where('user_id', '=', userId) + .where(column, '=', ownerId) + .orderBy('last_message_at', 'desc') + .orderBy('id', 'desc') + .limit(limit) + .execute(); + } + + private async deleteOwnedBy(id: number, userId: number, column: OwnerColumn, ownerId: number): Promise { + const result = await this.db() + .deleteFrom('assistant_threads') + .where('id', '=', id) + .where('user_id', '=', userId) + .where(column, '=', ownerId) + .executeTakeFirst(); + return Number(result.numDeletedRows) > 0; + } } diff --git a/server/src/db/repositories/AssistantToolCalls.repository.ts b/server/src/db/repositories/AssistantToolCalls.repository.ts index 215840e55..a8ff3d6ea 100644 --- a/server/src/db/repositories/AssistantToolCalls.repository.ts +++ b/server/src/db/repositories/AssistantToolCalls.repository.ts @@ -95,13 +95,27 @@ export class AssistantToolCallsRepository extends TrekRepository { + return this.findOwnedBy(id, userId, 'assistant_threads.trip_id', tripId); + } + + /** A call of one of the user's threads on that journey; null for anyone else's or another journey's. */ + async findOwnedOnJourney(id: string, userId: number, journeyId: number): Promise { + return this.findOwnedBy(id, userId, 'assistant_threads.journey_id', journeyId); + } + + private async findOwnedBy( + id: string, + userId: number, + owner: 'assistant_threads.trip_id' | 'assistant_threads.journey_id', + ownerId: number, + ): Promise { const row = await this.kysely>() .selectFrom('assistant_tool_calls') .innerJoin('assistant_threads', 'assistant_threads.id', 'assistant_tool_calls.thread_id') .selectAll('assistant_tool_calls') .where('assistant_tool_calls.id', '=', id) .where('assistant_threads.user_id', '=', userId) - .where('assistant_threads.trip_id', '=', tripId) + .where(owner, '=', ownerId) .executeTakeFirst(); return row ?? null; } diff --git a/server/src/nest/assistant/assistant-book-context.ts b/server/src/nest/assistant/assistant-book-context.ts new file mode 100644 index 000000000..6f8533d35 --- /dev/null +++ b/server/src/nest/assistant/assistant-book-context.ts @@ -0,0 +1,228 @@ +import { JourneyBookEditService } from '../journey/journey-book-edit.service'; +import { JourneyDomainService } from '../journey/journey-domain.service'; +import { PhotoSignalsService } from '../photos/photo-signals.service'; +import { buildTripCard, todayIn, type TripCard } from './assistant-context'; +import { Injectable } from '@nestjs/common'; +import type { AssistantFocus, BookOverview, BookSpreadSummary } from '@trek/shared'; + +/** + * The journey as the Studio assistant knows it on a turn: the journey, what + * the user may do on it, its book page by page, its gallery in numbers and its + * entries. Built from the journey and book services with the user's own + * rights, it gives the model the page and entry ids it works with. + */ + +/** What the user may do in a journey's book. */ +type BookRole = 'owner' | 'editor' | 'viewer'; + +/** One entry as the card lists it. */ +interface BookCardEntry { + id: number; + date: string; + title: string | null; + place: string | null; + photos: number; +} + +/** The journey's gallery in numbers, videos left out: what a photo pick can go by. */ +interface BookCardGallery { + photos: number; + withTime: number; + withGps: number; +} + +export interface BookCard { + journeyId: number; + title: string; + subtitle: string | null; + role: BookRole; + book: BookOverview; + gallery: BookCardGallery; + entries: BookCardEntry[]; + focus: AssistantFocus | null; +} + +/** Pages the card lists one by one; a longer book is counted past them. */ +const PAGES_LISTED = 150; +/** Entries the card lists one by one; the rest are counted. */ +const ENTRIES_LISTED = 200; +/** Selected elements the focus names; a larger selection is counted. */ +const SELECTED_LISTED = 30; + +const ROLE_WORDING: Readonly> = { + owner: 'owner (you may change the book)', + editor: 'editor (you may change the book)', + viewer: 'viewer (you may read the book but not change it; propose no changes, say so when asked for one)', +}; + +/** User text on one line, so a line break in a title cannot split a row of the card. */ +function oneLine(text: string): string { + return text.replace(/\s+/g, ' ').trim(); +} + +/** A list cut after `max`, with how many more there are. */ +function listed(items: readonly T[], max: number, line: (item: T) => string): string[] { + const lines = items.slice(0, max).map(line); + if (items.length > max) lines.push(`and ${items.length - max} more`); + return lines; +} + +function pageRow(spread: BookSpreadSummary): string { + const texts = spread.texts.map((text) => `"${oneLine(text)}"`).join(', '); + const cells = [spread.index, spread.id, spread.role, spread.entryId ?? '', spread.photoIds.join(', '), texts]; + return cells.join(' | '); +} + +function entryRow(entry: BookCardEntry): string { + const words = [entry.title, entry.place].map((text) => oneLine(text ?? '')); + return [entry.id, entry.date, ...words, entry.photos].join(' | '); +} + +/** What the user looks at in the Studio, first in the card, so "this page" needs no question back. */ +function focusLines(card: BookCard): string[] { + const spreadId = card.focus?.spreadId; + const page = spreadId ? card.book.spreads.find((spread) => spread.id === spreadId) : undefined; + if (!page) return []; + const about = `page ${page.id} (index ${page.index}, ${page.role})`; + const lines = [`The user is looking at ${about}; words like "this page" or "here" mean it.`]; + const selected = card.focus?.elementIds ?? []; + if (selected.length > 0) { + const shown = selected.slice(0, SELECTED_LISTED).join(', '); + const more = selected.length > SELECTED_LISTED ? ` and ${selected.length - SELECTED_LISTED} more` : ''; + lines.push(`Selected on it ("this photo", "these" mean them): ${shown}${more}.`); + } + return [...lines, '']; +} + +/** The book as the model reads it: its setup, then a row per page. */ +function bookLines(book: BookOverview): string[] { + if (!book.exists) return ['Book: none yet (create_book lays down a blank one).']; + const { preset, pageWidth, pageHeight, bleed, safe } = book.page; + const lines = [ + `Book: "${oneLine(book.title)}", version ${book.version ?? '?'}`, + `Page: ${pageWidth} x ${pageHeight} mm (${preset}), bleed ${bleed} mm, safe margin ${safe} mm`, + '', + 'Pages (index | page id | role | entry id | photo ids | first words of its texts):', + ...listed(book.spreads, PAGES_LISTED, pageRow), + ]; + const layouts = book.layouts.map((layout) => `${oneLine(layout.name)} (${layout.id}, ${layout.role})`); + if (layouts.length > 0) lines.push('', `Saved layouts: ${layouts.join(', ')}`); + return lines; +} + +/** The gallery in one line: how many photos a pick chooses from, and how many it can place by time or on the map. */ +function galleryLine({ photos, withTime, withGps }: BookCardGallery): string { + if (photos === 0) return 'Gallery: no photos yet.'; + const known = `${withTime} with the time taken, ${withGps} with a GPS position`; + return `Gallery: ${photos} photos (videos left out), ${known}.`; +} + +/** + * The card as the model reads it: the focus first, then the journey, the + * user's role, the book, the gallery and the entries. + */ +export function renderBookCard(card: BookCard): string { + const lines = [`Journey: ${oneLine(card.title)}`]; + if (card.subtitle) lines.push(`Subtitle: ${oneLine(card.subtitle)}`); + lines.push(`Your role: ${ROLE_WORDING[card.role]}`, '', ...bookLines(card.book), '', galleryLine(card.gallery), ''); + lines.push('Entries (entry id | date | title | place | photos):'); + if (card.entries.length === 0) lines.push('(no entries yet)'); + lines.push(...listed(card.entries, ENTRIES_LISTED, entryRow)); + return [...focusLines(card), ...lines].join('\n'); +} + +/** What the model reads next to its instructions on a Studio turn: the date and the book card. */ +export function bookTurnContext(card: BookCard, timeZone: string, now: Date): string { + const today = `Today is ${todayIn(timeZone, now)} (time zone ${timeZone}).`; + return [today, '', '', renderBookCard(card), ''].join('\n'); +} + +/** + * The trip card a journey turn hands the agent loop: empty, so the trip's + * answer cards (places found, the weather strip) find nothing to show and a + * change card names nothing from a trip. + */ +export function emptyTripCard(userId: number): TripCard { + return buildTripCard(0, userId, null, null, null); +} + +/** The entries the card lists: none waved away, and the suggestions only while nothing is written yet. */ +function listedEntries(entries: readonly T[]): T[] { + const kept = entries.filter((entry) => !entry.dismissed); + const written = kept.filter((entry) => entry.type !== 'skeleton'); + return written.length > 0 ? written : kept; +} + +/** A gallery photo as far as the card counts it. */ +interface GalleryFact { + taken_at: string | null; + lat: number | null; + lng: number | null; +} + +/** A gallery's photos, and how many of them carry the time taken and a position. */ +function galleryOf(photos: readonly GalleryFact[]): BookCardGallery { + return { + photos: photos.length, + withTime: photos.filter((photo) => !!photo.taken_at).length, + withGps: photos.filter((photo) => photo.lat !== null && photo.lng !== null).length, + }; +} + +/** + * Reads the journey a Studio conversation is about, with the user's rights: + * whether they may open it and change its book, and its card for a turn. + */ +@Injectable() +export class AssistantBookContext { + constructor( + private readonly journeys: JourneyDomainService, + private readonly books: JourneyBookEditService, + private readonly photos: PhotoSignalsService, + ) {} + + /** Whether the user may open the journey: its owner and every contributor. */ + async canOpen(userId: number, journeyId: number): Promise { + return (await this.journeys.canAccessJourney(journeyId, userId)) !== null; + } + + /** Whether the user may change the journey's book: its owner and editors. */ + canEdit(userId: number, journeyId: number): Promise { + return this.journeys.canEdit(journeyId, userId); + } + + /** + * The card of one turn. The book is read as get_book reads it, so a journey + * the user can no longer open is refused there (404), as by every tool; the + * entries are read as list_journey_entries reads them and the gallery as + * suggest_book_photos reads it. The journey row, read once, names its owner. + */ + async cardOf(userId: number, journeyId: number, focus: AssistantFocus | null): Promise { + const book = await this.books.overview(journeyId, userId); + const journey = await this.journeys.canAccessJourney(journeyId, userId); + const role = await this.roleOf(userId, journeyId, journey?.user_id === userId); + const entries = (await this.journeys.listEntries(journeyId, userId)) ?? []; + const gallery = journey ? await this.photos.galleryFacts(journeyId) : []; + return { + journeyId, + title: journey?.title ?? '', + subtitle: journey?.subtitle ?? null, + role, + book, + gallery: galleryOf(gallery), + entries: listedEntries(entries).map((entry) => ({ + id: entry.id, + date: entry.entry_date, + title: entry.title ?? null, + place: entry.location_name ?? null, + photos: entry.photos.length, + })), + focus, + }; + } + + private async roleOf(userId: number, journeyId: number, owner: boolean): Promise { + if (owner) return 'owner'; + return (await this.canEdit(userId, journeyId)) ? 'editor' : 'viewer'; + } +} diff --git a/server/src/nest/assistant/assistant-retention.job.ts b/server/src/nest/assistant/assistant-retention.job.ts index 509bcecd0..16ad83740 100644 --- a/server/src/nest/assistant/assistant-retention.job.ts +++ b/server/src/nest/assistant/assistant-retention.job.ts @@ -19,7 +19,7 @@ const DAY_MS = 24 * 60 * 60 * 1000; /** * Nightly sweep of the assistant's conversations: threads nobody wrote in * for longer than the admin's retention (none under "forever"), threads of - * users who no longer belong to their trip, changes that waited a day + * users who no longer belong to their trip or journey, changes that waited a day * without a decision (expired, so no card waits forever), and usage days * older than the usage retention. */ diff --git a/server/src/nest/assistant/assistant-scope.ts b/server/src/nest/assistant/assistant-scope.ts new file mode 100644 index 000000000..3c0774cd6 --- /dev/null +++ b/server/src/nest/assistant/assistant-scope.ts @@ -0,0 +1,133 @@ +import type { AssistantThreadRow, AssistantThreadsRepository } from '../../db/repositories/AssistantThreads.repository'; +import type { + AssistantToolCallRow, + AssistantToolCallsRepository, +} from '../../db/repositories/AssistantToolCalls.repository'; +import { withRequestContext } from '../database/request-context'; +import { SettingsService } from '../settings/settings.service'; +import { AssistantBookContext, bookTurnContext, emptyTripCard } from './assistant-book-context'; +import { AssistantBookGate, openGate, type BookTurnGate } from './assistant-book-gate'; +import { languageName, turnContext, type TripCard } from './assistant-context'; +import { AssistantToolsService, type AssistantToolSession } from './assistant-tools.service'; +import { tripCardFrom } from './assistant-trip-scope'; +import { studioPrompt, systemPrompt } from './assistant.prompt'; +import { MikroORM } from '@mikro-orm/core'; +import { Injectable } from '@nestjs/common'; +import type { AssistantFocus, AssistantMention, AssistantScope } from '@trek/shared'; + +/** + * What a conversation is about, a trip or a journey (`AssistantScope`), and + * what follows from it: where its threads are kept, which tools a turn holds + * (the tools that take a `tripId` or a `journeyId` run on the conversation's + * own), and what the model reads beside the history. The agent loop, the + * cards, the decisions and the undo are the same for both. + */ + +/** The scope of a trip conversation. */ +export function tripScope(tripId: number): AssistantScope { + return { kind: 'trip', tripId }; +} + +/** The user's threads in one scope: every read and delete names the trip or journey next to the user. */ +interface ScopedThreads { + create(userId: number, title: string, at: string): Promise; + find(id: number, userId: number): Promise; + list(userId: number, limit: number): Promise; + remove(id: number, userId: number): Promise; +} + +export function scopedThreads(repo: AssistantThreadsRepository, scope: AssistantScope): ScopedThreads { + if (scope.kind === 'trip') { + const { tripId } = scope; + return { + create: (userId, title, at) => repo.createThread(userId, tripId, title, at), + find: (id, userId) => repo.findOwned(id, userId, tripId), + list: (userId, limit) => repo.listRecent(userId, tripId, limit), + remove: (id, userId) => repo.deleteOwned(id, userId, tripId), + }; + } + const { journeyId } = scope; + return { + create: (userId, title, at) => repo.createJourneyThread(userId, journeyId, title, at), + find: (id, userId) => repo.findOwnedOnJourney(id, userId, journeyId), + list: (userId, limit) => repo.listRecentOnJourney(userId, journeyId, limit), + remove: (id, userId) => repo.deleteOwnedOnJourney(id, userId, journeyId), + }; +} + +/** A proposed change of one of the user's threads in this scope; null for anyone else's or another scope's. */ +export function findScopedCall( + repo: AssistantToolCallsRepository, + scope: AssistantScope, + id: string, + userId: number, +): Promise { + return scope.kind === 'trip' + ? repo.findOwned(id, userId, scope.tripId) + : repo.findOwnedOnJourney(id, userId, scope.journeyId); +} + +/** What a turn knows about the user's request, whatever its scope. */ +interface ScopeTurnInput { + userId: number; + locale: string; + timeZone: string; + focus: AssistantFocus | null; + mentions: readonly AssistantMention[]; + now: Date; +} + +/** + * What a turn hands the model and the agent loop: the trip card the cards + * read, the instructions, the context, and the gate its held calls pass + * (a journey's checks book writes; a trip's lets every call through). + */ +interface ScopeTurn { + card: TripCard; + system: string; + context: string; + gate: BookTurnGate; +} + +/** Opens a scope's tool sessions and writes what its turns read. */ +@Injectable() +export class AssistantScopes { + constructor( + private readonly tools: AssistantToolsService, + private readonly books: AssistantBookContext, + private readonly bookGate: AssistantBookGate, + private readonly settings: SettingsService, + private readonly orm: MikroORM, + ) {} + + /** + * The tool session of a turn (or, with targets, of an undo). A journey's + * offers the book's writes only to someone who may change the book. + */ + async open(userId: number, scope: AssistantScope, undoTargets?: ReadonlySet): Promise { + if (scope.kind === 'trip') return this.tools.open(userId, scope.tripId, undoTargets); + const canWrite = await withRequestContext(this.orm, () => this.books.canEdit(userId, scope.journeyId)); + return this.tools.openJourney(userId, scope.journeyId, canWrite, undoTargets); + } + + /** + * The card, instructions and context of one turn: for a trip the trip card + * read through the turn's session and the user's units and trip notes; for a + * journey the book card, the Studio's instructions and the check of its + * book writes. + */ + async turnOf(session: AssistantToolSession, scope: AssistantScope, turn: ScopeTurnInput): Promise { + const language = languageName(turn.locale); + if (scope.kind === 'trip') { + const card = await tripCardFrom(session, scope.tripId, turn.userId, turn.focus, turn.mentions); + const prefs = await withRequestContext(this.orm, () => this.settings.getUserSettings(turn.userId)); + const context = turnContext(card, turn.timeZone, turn.now, prefs); + return { card, system: systemPrompt(language), context, gate: openGate(session) }; + } + const { journeyId } = scope; + const book = await withRequestContext(this.orm, () => this.books.cardOf(turn.userId, journeyId, turn.focus)); + const context = bookTurnContext(book, turn.timeZone, turn.now); + const gate = this.bookGate.forTurn(turn.userId, journeyId, session); + return { card: emptyTripCard(turn.userId), system: studioPrompt(language), context, gate }; + } +} diff --git a/server/src/nest/assistant/assistant-tool-offer.ts b/server/src/nest/assistant/assistant-tool-offer.ts index 736f43e5d..76c3f645c 100644 --- a/server/src/nest/assistant/assistant-tool-offer.ts +++ b/server/src/nest/assistant/assistant-tool-offer.ts @@ -16,11 +16,10 @@ import { PACKAGE_HELD_READS, PACKAGE_TOOL_CONTROLLERS } from './cards/registry'; */ /** - * The Studio book tools wait for the Studio's own chat: a trip chat has no - * page to show a change on, no way yet to take one back and no forced - * `returnPrevious`, and an applied write would reload an open Studio from its - * cover. External MCP clients keep them; only the assistant leaves them out - * until the journey scope offers them. + * The Studio book tools belong to the Studio's own chat, the journey scope + * (isOfferedInJourney below): a trip chat has no page to show a change on and + * an applied write would reload an open Studio from its cover. External MCP + * clients keep them; a trip conversation of the assistant never sees them. */ const STUDIO_ONLY_TOOLS: Readonly> = Object.fromEntries( [ @@ -34,6 +33,14 @@ const STUDIO_ONLY_TOOLS: Readonly> = Object.fromEntries( 'edit_book_page', 'set_book_cover', 'suggest_book_photos', + 'set_book_setup', + 'duplicate_book_page', + 'save_book_layout', + 'remove_book_layout', + 'design_book', + 'get_book_design', + 'revise_book_design', + 'apply_book_design', ].map((name) => [name, 'a Studio book tool: offered in the Studio chat only, never in a trip chat']), ); @@ -84,6 +91,8 @@ export const ASSISTANT_DENIED_TOOLS: Readonly> = { delete_manual_school_holiday_country: 'changes the holidays of every user', ...STUDIO_ONLY_TOOLS, restore_book_page: 'an undo target only: it puts a book page back as an earlier change left it', + restore_book_layout: 'an undo target only: it puts back a layout an earlier change took away', + restore_book_revision: 'an undo target only: it puts the book back as an applied design found it', }; /** @@ -121,6 +130,73 @@ export function isOfferedTool(name: string): boolean { return !(name in ASSISTANT_DENIED_TOOLS); } +/** The argument a Studio conversation pins on every tool that takes it, as a trip conversation pins `tripId`. */ +export const JOURNEY_PINNED_ARG = 'journeyId'; + +/** The controllers of the book itself: their reads, and their writes for someone who may change the book. */ +const STUDIO_CONTROLLERS: ReadonlySet = new Set([ + 'JourneyBookMcp', + 'JourneyBookPhotosMcp', + 'JourneyBookDesignMcp', +]); + +/** The controllers whose reads a Studio conversation also gets: the journey, its map and its tracks. */ +const JOURNEY_READ_CONTROLLERS: ReadonlySet = new Set(['JourneyMcp', 'JourneyMapMcp', 'JourneyTracksMcp']); + +/** + * Whether a registered tool is one of the book's own. A trip conversation + * leaves these out by their controller as well as by name, so a book tool + * added later never reaches a trip chat through the journey group. + */ +export function isStudioController(className: string | undefined): boolean { + return className !== undefined && STUDIO_CONTROLLERS.has(className); +} + +/** + * What is wrong with the book tools against the registry: one that is not + * listed above as a Studio tool (or as the undo target), so the denylist and + * the Studio's offer no longer tell the same story. + */ +export function checkStudioTools(listing: Iterable>): string[] { + const problems: string[] = []; + for (const entry of listing) { + if (entry.kind === 'tool' && isStudioController(entry.className) && !(entry.name in ASSISTANT_DENIED_TOOLS)) { + problems.push(`book tool "${entry.name}" is not listed as a Studio tool`); + } + } + return problems; +} + +/** + * Whether a Studio conversation attaches a registered tool: one of the book's + * or the journey's, and none the denylist keeps from the assistant, the book + * tools a trip chat goes without excepted (`restore_book_page` stays out: it + * is an undo target only). + */ +export function isOfferedInJourney(name: string, className: string | undefined): boolean { + if (name in ASSISTANT_DENIED_TOOLS && !(name in STUDIO_ONLY_TOOLS)) return false; + return isStudioController(className) || (className !== undefined && JOURNEY_READ_CONTROLLERS.has(className)); +} + +/** + * Whether a Studio conversation keeps an attached tool once its schema and + * annotations are known. Only tools that work on the conversation's journey + * (they take the `journeyId` the server pins) stay, so the conversation never + * reaches another journey; of those every read, and the book's writes only + * for someone who may change the book. The journey's own writes (entries, + * photos, its trips) stay with the journey page. + */ +export function keptInJourney( + className: string | undefined, + kind: 'read' | 'write', + pinned: boolean, + canWrite: boolean, +): boolean { + if (!pinned) return false; + if (kind === 'read') return true; + return canWrite && isStudioController(className); +} + /** What is wrong with the denylist against the registry: a sharing tool that slipped through. */ export function checkDenylist(names: Iterable): string[] { const problems: string[] = []; diff --git a/server/src/nest/assistant/assistant-tools.service.ts b/server/src/nest/assistant/assistant-tools.service.ts index 3362cfadc..b75154144 100644 --- a/server/src/nest/assistant/assistant-tools.service.ts +++ b/server/src/nest/assistant/assistant-tools.service.ts @@ -7,13 +7,24 @@ import { REMEMBER_SPEC } from './assistant-memory'; import { ASSISTANT_TOOL_GROUPS, checkDenylist, + checkStudioTools, groupOf, HELD_READS, + isOfferedInJourney, isOfferedTool, + isStudioController, + JOURNEY_PINNED_ARG, + keptInJourney, USE_TOOLS_SPEC, USE_TOOLS_TOOL, } from './assistant-tool-offer'; -import { ASSISTANT_SCOPES, ASSISTANT_SERVER_TOOLS, PINNED_ARG, REMEMBER_TOOL } from './assistant-tools.constants'; +import { + ASSISTANT_SCOPES, + ASSISTANT_SERVER_TOOLS, + PINNED_ARG, + PREVIEW_BOOK_PAGE_TOOL, + REMEMBER_TOOL, +} from './assistant-tools.constants'; import type { ToolCards } from './cards/card-types'; import { ASSISTANT_ARG_POLICY, @@ -62,8 +73,28 @@ interface ListedTool { hint: ToolHint; } -/** A turn's session offers every tool (the core first, the rest by group); an undo's holds its one target. */ -type SessionMode = 'turn' | 'undo'; +/** + * A trip turn's session offers every tool (the core first, the rest by group); + * a journey turn's offers the Studio's tools at once and nothing else; an + * undo's holds its one target. + */ +type SessionMode = 'turn' | 'journey' | 'undo'; + +/** The argument every pinned tool runs with, and its value: the conversation's trip or journey. */ +interface SessionPin { + arg: string; + id: number; +} + +/** The registered tools by name, as the registry lists them. */ +type ToolCatalog = ReadonlyMap; + +/** Which registered tools a session attaches, and which of those it keeps once they are listed. */ +interface SessionOffer { + catalog: ToolCatalog; + include: (name: string) => boolean; + keep: (tool: ListedTool) => boolean; +} /** * The tools the packages' undo checks read. A package's `reads` names its @@ -83,8 +114,9 @@ function undoReadTools(cards: Readonly>): string[] { * What is wrong with the tool catalog the assistant relies on, given what the * registry holds: a tool with a card of its own, a package's cards for a tool, * an undo target, an undo read or a package's held read that no longer - * exists, a sharing tool the denylist missed, or a tool named like one of the - * server's own steps. Empty when all is well. + * exists, a sharing tool the denylist missed, a book tool not listed as the + * Studio's, or a tool named like one of the server's own steps. Empty when + * all is well. */ export function checkToolCatalog( listing: readonly McpRegistryListing[], @@ -110,11 +142,11 @@ export function checkToolCatalog( for (const name of heldReads) { if (!tools.has(name)) problems.push(`held read "${name}" of a package is not registered`); } - // The server's own steps are told apart from tool calls by name alone. - for (const name of [...ASSISTANT_SERVER_TOOLS, USE_TOOLS_TOOL]) { + // The server's own steps and tools are told apart from the registry's by name alone. + for (const name of [...ASSISTANT_SERVER_TOOLS, USE_TOOLS_TOOL, PREVIEW_BOOK_PAGE_TOOL]) { if (tools.has(name)) problems.push(`"${name}" is the server's own step`); } - return [...problems, ...checkDenylist(tools)]; + return [...problems, ...checkDenylist(tools), ...checkStudioTools(listing)]; } /** @@ -127,14 +159,14 @@ function kindOf(name: string, readOnly: boolean): AssistantToolKind { return readOnly && !HELD_READS.has(name) ? 'read' : 'write'; } -function hiddenArgs(name: string): Set { +function hiddenArgs(name: string, pinArg: string = PINNED_ARG): Set { const policy = ASSISTANT_ARG_POLICY[name]; - return new Set([PINNED_ARG, ...Object.keys(policy?.forced ?? {}), ...(policy?.stripped ?? [])]); + return new Set([pinArg, ...Object.keys(policy?.forced ?? {}), ...(policy?.stripped ?? [])]); } /** The tool's JSON Schema without the arguments the server sets or takes away. */ -function modelSchema(name: string, schema: Record): Record { - const hidden = hiddenArgs(name); +function modelSchema(name: string, schema: Record, pinArg: string): Record { + const hidden = hiddenArgs(name, pinArg); const properties = { ...((schema.properties as Record | undefined) ?? {}) }; for (const key of hidden) delete properties[key]; const required = Array.isArray(schema.required) @@ -171,18 +203,21 @@ function readResult(result: unknown): ToolRun { * broadcast their changes the same way. * * Every tool that takes a trip runs on the conversation's trip: the model - * never sees that argument, and one it sends anyway must name this trip. + * never sees that argument, and one it sends anyway must name this trip. A + * Studio conversation pins its journey the same way, through `journeyId`. */ export class AssistantToolSession { constructor( private readonly client: InstanceType, private readonly server: ReturnType, private readonly tools: ReadonlyMap, - private readonly tripId: number, + /** The conversation's trip, or its journey when `pinArg` is `journeyId`. */ + private readonly pinnedId: number, private readonly audit: (toolName: string) => void, private readonly mode: SessionMode, /** The itineraries the user's transit searches on this trip answered with, kept across turns. */ private readonly itineraries: KeptItineraries = new KeptItineraries(), + private readonly pinArg: string = PINNED_ARG, ) {} /** The groups this turn loaded; the core is always there. */ @@ -190,17 +225,18 @@ export class AssistantToolSession { /** * The tools as the model is offered them: the core and the groups it - * loaded, the trip notes, and the step that loads the other groups. + * loaded, the trip notes, and the step that loads the other groups. A + * journey's session offers all it holds and no more. */ specs(): AiToolSpec[] { const listed = [...this.tools.values()] - .filter((tool) => this.mode === 'undo' || tool.hint.group === null || this.loaded.has(tool.hint.group)) + .filter((tool) => this.mode !== 'turn' || tool.hint.group === null || this.loaded.has(tool.hint.group)) .map((tool) => ({ name: tool.name, description: tool.description, - parameters: modelSchema(tool.name, tool.inputSchema), + parameters: modelSchema(tool.name, tool.inputSchema, this.pinArg), })); - if (this.mode === 'undo') return listed; + if (this.mode !== 'turn') return listed; const more = Object.keys(ASSISTANT_TOOL_GROUPS).some((group) => !this.loaded.has(group)); return [...listed, REMEMBER_SPEC, ...(more ? [USE_TOOLS_SPEC] : [])]; } @@ -222,11 +258,12 @@ export class AssistantToolSession { * conversation's is refused. */ pinArgs(name: string, args: ToolArgs): { args: ToolArgs } | { error: string } { - const given = args[PINNED_ARG]; - if (given !== undefined && Number(given) !== this.tripId) { - return { error: 'This conversation is about one trip; its id is set by the app and cannot be changed.' }; + const given = args[this.pinArg]; + if (given !== undefined && Number(given) !== this.pinnedId) { + const about = this.pinArg === PINNED_ARG ? 'trip' : 'journey'; + return { error: `This conversation is about one ${about}; its id is set by the app and cannot be changed.` }; } - const hidden = hiddenArgs(name); + const hidden = hiddenArgs(name, this.pinArg); return { args: Object.fromEntries(Object.entries(args).filter(([key]) => !hidden.has(key))) }; } @@ -280,7 +317,7 @@ export class AssistantToolSession { const tool = this.tools.get(name); if (!tool) return { ok: false, value: `Unknown tool: ${name}` }; const forced = ASSISTANT_ARG_POLICY[name]?.forced ?? {}; - const final = { ...args, ...(tool.pinned ? { [PINNED_ARG]: this.tripId } : {}), ...forced }; + const final = { ...args, ...(tool.pinned ? { [this.pinArg]: this.pinnedId } : {}), ...forced }; try { return readResult(await this.client.callTool({ name, arguments: final })); } catch (err) { @@ -311,12 +348,52 @@ export class AssistantToolsService implements OnApplicationBootstrap { /** * A session for one user and trip: for a turn every tool the assistant is - * offered, for an undo only the named targets. No plugin tools are ever - * attached: the assistant passes no dynamic tool source. + * offered but the book's own (left out by name and by controller), for an + * undo only the named targets. No plugin tools are ever attached: the + * assistant passes no dynamic tool source. */ async open(userId: number, tripId: number, undoTargets?: ReadonlySet) { - const include = (name: string) => (undoTargets ? undoTargets.has(name) : isOfferedTool(name)); - const classOf = new Map(this.registry.list().map((entry) => [entry.name, entry] as const)); + const catalog = this.catalog(); + const include = (name: string) => + undoTargets ? undoTargets.has(name) : isOfferedTool(name) && !isStudioController(catalog.get(name)?.className); + const mode: SessionMode = undoTargets ? 'undo' : 'turn'; + const kept = this.itineraries.of(userId, tripId); + return this.session(userId, { arg: PINNED_ARG, id: tripId }, mode, { catalog, include, keep: () => true }, kept); + } + + /** + * A session for one user and journey, the Studio's: for a turn the book + * tools and the journey's reads, each on this journey, with the book's + * writes only for someone who may change it (`canWrite`); for an undo only + * the named targets. + */ + async openJourney(userId: number, journeyId: number, canWrite: boolean, undoTargets?: ReadonlySet) { + const catalog = this.catalog(); + const classOf = (name: string) => catalog.get(name)?.className; + const include = (name: string) => (undoTargets ? undoTargets.has(name) : isOfferedInJourney(name, classOf(name))); + const keep = (tool: ListedTool) => + !!undoTargets || keptInJourney(classOf(tool.name), tool.kind, tool.pinned, canWrite); + const mode: SessionMode = undoTargets ? 'undo' : 'journey'; + return this.session(userId, { arg: JOURNEY_PINNED_ARG, id: journeyId }, mode, { catalog, include, keep }); + } + + /** The registered tools by name, read once per session. */ + private catalog(): ToolCatalog { + return new Map( + this.registry + .list() + .filter((entry) => entry.kind === 'tool') + .map((entry) => [entry.name, entry] as const), + ); + } + + private async session( + userId: number, + pin: SessionPin, + mode: SessionMode, + offer: SessionOffer, + kept?: KeptItineraries, + ): Promise { const server = createLocalMcpServer('TREK assistant'); const around = (info: { kind: string; name: string }, call: () => unknown): unknown => traceEntry('mcp', `${info.kind} ${info.name} user=${userId} client=assistant`, () => @@ -326,7 +403,7 @@ export class AssistantToolsService implements OnApplicationBootstrap { this.registry.attach( server, { userId, scopes: [...ASSISTANT_SCOPES], isStaticToken: false }, - { include: (kind, name) => kind === 'tool' && include(name), around }, + { include: (kind, name) => kind === 'tool' && offer.include(name), around }, ), ); const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); @@ -337,27 +414,26 @@ export class AssistantToolsService implements OnApplicationBootstrap { const tools = new Map(); for (const tool of (await client.listTools()).tools) { const annotations = tool.annotations ?? {}; - const kind = undoTargets ? 'write' : kindOf(tool.name, annotations.readOnlyHint === true); + const kind = mode === 'undo' ? 'write' : kindOf(tool.name, annotations.readOnlyHint === true); const inputSchema = tool.inputSchema as Record; const properties = (inputSchema.properties as Record | undefined) ?? {}; - const entry = classOf.get(tool.name); - tools.set(tool.name, { + const entry = offer.catalog.get(tool.name); + const listed: ListedTool = { name: tool.name, description: tool.description ?? '', inputSchema, kind, - pinned: PINNED_ARG in properties, + pinned: pin.arg in properties, hint: { destructive: annotations.destructiveHint === true, creates: annotations.idempotentHint === false, group: entry ? groupOf(entry) : null, }, - }); + }; + if (offer.keep(listed)) tools.set(tool.name, listed); } - const mode: SessionMode = undoTargets ? 'undo' : 'turn'; const audit = (name: string) => this.audit(userId, name); - const kept = this.itineraries.of(userId, tripId); - return new AssistantToolSession(client, server, tools, tripId, audit, mode, kept); + return new AssistantToolSession(client, server, tools, pin.id, audit, mode, kept, pin.arg); } /** The audit row an MCP client's call writes, marked as the assistant's. A failed write never fails the call. */ diff --git a/server/src/nest/assistant/assistant-trip-scope.ts b/server/src/nest/assistant/assistant-trip-scope.ts new file mode 100644 index 000000000..de7fc923d --- /dev/null +++ b/server/src/nest/assistant/assistant-trip-scope.ts @@ -0,0 +1,40 @@ +import { buildTripCard, type TripCard } from './assistant-context'; +import type { AssistantToolSession, AssistantToolsService } from './assistant-tools.service'; +import type { AssistantFocus, AssistantMention } from '@trek/shared'; + +/** + * What only a trip conversation has: the trip card, read through the trip + * tools with the user's rights. A Studio conversation reads its journey + * instead (assistant-book-context.ts). + */ + +/** The reads the trip card is built from. */ +const TRIP_CARD_READS: ReadonlySet = new Set(['get_trip_summary', 'list_places']); + +/** The trip card for a turn, read through the turn's session. */ +export async function tripCardFrom( + session: Pick, + tripId: number, + userId: number, + focus: AssistantFocus | null, + mentions: readonly AssistantMention[] = [], +): Promise { + const summary = await session.read('get_trip_summary'); + const places = await session.read('list_places'); + const [found, listed] = [summary.ok ? summary.value : null, places.ok ? places.value : null]; + return buildTripCard(tripId, userId, found, listed, focus, mentions); +} + +/** + * The trip card outside a turn's session (the labels of what a message + * mentions, the day a booking from a file names), on a session holding only + * its two reads. + */ +export async function readTripCard(tools: AssistantToolsService, userId: number, tripId: number): Promise { + const session = await tools.open(userId, tripId, TRIP_CARD_READS); + try { + return await tripCardFrom(session, tripId, userId, null); + } finally { + await session.close(); + } +} diff --git a/server/src/nest/assistant/assistant.controller.ts b/server/src/nest/assistant/assistant.controller.ts index a4a603846..a9ba54b28 100644 --- a/server/src/nest/assistant/assistant.controller.ts +++ b/server/src/nest/assistant/assistant.controller.ts @@ -11,6 +11,7 @@ import { onClientGone, openSseStream } from '../common/sse-stream'; import { RequirePermission, TripAccessGuard } from '../permissions/trip-access.guard'; import { AssistantFoundPlacesService } from './assistant-found-places.service'; import { AssistantProposalsService } from './assistant-proposals.service'; +import { tripScope } from './assistant-scope'; import { AssistantShareService } from './assistant-share.service'; import { AssistantAddFoundPlaceDto, @@ -35,7 +36,7 @@ import { import type { Response } from 'express'; /** A route id: a positive integer, or the 404 an unknown one gets. */ -function idParam(value: string): number { +export function idParam(value: string): number { const id = Number(value); if (!Number.isInteger(id) || id <= 0) throw aiRefusal('not_found', 'Conversation not found'); return id; @@ -75,20 +76,20 @@ export class AssistantController { @Get('threads') @ResponseContract(assistantThreadListResponseSchema) threads(@CurrentUser() user: User, @Param('tripId') tripId: string) { - return this.assistant.listThreads(user.id, Number(tripId)); + return this.assistant.listThreads(user.id, tripScope(Number(tripId))); } @Get('threads/:threadId') @ResponseContract(assistantThreadResponseSchema) thread(@CurrentUser() user: User, @Param('tripId') tripId: string, @Param('threadId') threadId: string) { - return this.assistant.getThread(user.id, Number(tripId), idParam(threadId)); + return this.assistant.getThread(user.id, tripScope(Number(tripId)), idParam(threadId)); } @Delete('threads/:threadId') @HttpCode(200) @ResponseContract(successResponseSchema) async deleteThread(@CurrentUser() user: User, @Param('tripId') tripId: string, @Param('threadId') threadId: string) { - await this.assistant.deleteThread(user.id, Number(tripId), idParam(threadId)); + await this.assistant.deleteThread(user.id, tripScope(Number(tripId)), idParam(threadId)); return { success: true as const }; } @@ -100,7 +101,7 @@ export class AssistantController { @Body() body: AssistantChatDto, @Res() res: Response, ): Promise { - await this.assistant.chat(user.id, Number(tripId), body, channelOf(res)); + await this.assistant.chat(user.id, tripScope(Number(tripId)), body, channelOf(res)); } // response-contract-exempt: streams the turn through @Res() as server-sent events, there is no JSON body to check. @@ -112,7 +113,7 @@ export class AssistantController { @Body() body: AssistantDecisionsDto, @Res() res: Response, ): Promise { - await this.assistant.decide(user.id, Number(tripId), idParam(threadId), body, channelOf(res)); + await this.assistant.decide(user.id, tripScope(Number(tripId)), idParam(threadId), body, channelOf(res)); } /** "+ Day 3" on a place a search found: a change card for the day, held like any other, no model turn. */ @@ -166,7 +167,7 @@ export class AssistantController { @Param('toolCallId') toolCallId: string, @Body() _body: AssistantUndoDto, ) { - await this.assistant.undo(user.id, Number(tripId), toolCallId); + await this.assistant.undo(user.id, tripScope(Number(tripId)), toolCallId); return { undone: true as const }; } diff --git a/server/src/nest/assistant/assistant.dto.ts b/server/src/nest/assistant/assistant.dto.ts index 07499bcec..4c45f74cf 100644 --- a/server/src/nest/assistant/assistant.dto.ts +++ b/server/src/nest/assistant/assistant.dto.ts @@ -8,6 +8,7 @@ import { assistantAttachmentRequestSchema, assistantChatRequestSchema, assistantDecisionsRequestSchema, + assistantRenderUploadRequestSchema, assistantShareRequestSchema, assistantStopRequestSchema, assistantTakeProposalRequestSchema, @@ -20,6 +21,7 @@ export class AssistantAddFoundPlaceDto extends createZodDto(assistantAddFoundPla export class AssistantAttachmentDto extends createZodDto(assistantAttachmentRequestSchema) {} export class AssistantChatDto extends createZodDto(assistantChatRequestSchema) {} export class AssistantDecisionsDto extends createZodDto(assistantDecisionsRequestSchema) {} +export class AssistantRenderUploadDto extends createZodDto(assistantRenderUploadRequestSchema) {} export class AssistantShareDto extends createZodDto(assistantShareRequestSchema) {} export class AssistantStopDto extends createZodDto(assistantStopRequestSchema) {} export class AssistantTakeProposalDto extends createZodDto(assistantTakeProposalRequestSchema) {} diff --git a/server/src/nest/assistant/assistant.module.ts b/server/src/nest/assistant/assistant.module.ts index c5f5898d0..7c5f50ee0 100644 --- a/server/src/nest/assistant/assistant.module.ts +++ b/server/src/nest/assistant/assistant.module.ts @@ -8,22 +8,32 @@ import { AuditModule } from '../audit/audit.module'; import { BookingImportModule } from '../booking-import/booking-import.module'; import { CollabModule } from '../collab/collab.module'; import { RateLimitModule } from '../common/rate-limit.module'; +import { JourneyBookModule } from '../journey/journey-book.module'; +import { JourneyDomainModule } from '../journey/journey-domain.module'; import { McpSharedModule } from '../mcp-shared/mcp-shared.module'; import { PermissionsModule } from '../permissions/permissions.module'; +import { PhotoSignalsModule } from '../photos/photo-signals.module'; import { SchedulingModule } from '../scheduling/scheduling.module'; import { SettingsModule } from '../settings/settings.module'; import { TripMembershipModule } from '../trip-membership/trip-membership.module'; import { AssistantAttachmentsController } from './assistant-attachments.controller'; +import { AssistantBookContext } from './assistant-book-context'; +import { AssistantBookGate } from './assistant-book-gate'; import { AssistantBookingImportService } from './assistant-booking-import.service'; import { AssistantFoundPlacesService } from './assistant-found-places.service'; import { AssistantProposalsService } from './assistant-proposals.service'; +import { AssistantRenderRegistry, InMemoryAssistantRenderRegistry } from './assistant-render.registry'; +import { AssistantRendersController } from './assistant-renders.controller'; import { AssistantRetentionJob } from './assistant-retention.job'; +import { AssistantScopes } from './assistant-scope'; import { AssistantShareService } from './assistant-share.service'; import { AssistantStreamRegistry, InMemoryAssistantStreamRegistry } from './assistant-stream.registry'; import { AssistantToolsService } from './assistant-tools.service'; +import { AssistantVision } from './assistant-vision'; import { AssistantController } from './assistant.controller'; import { AssistantService } from './assistant.service'; import { AssistantCardContext } from './cards/card-context'; +import { JourneyAssistantController } from './journey-assistant.controller'; import { MikroOrmModule } from '@mikro-orm/nestjs'; import { Module } from '@nestjs/common'; @@ -35,6 +45,17 @@ import { Module } from '@nestjs/common'; * chat is posted through the collab chat. A card names an airport through the * airports' data. Its conversations are kept per user and trip and swept by * the retention job. + * + * The same assistant talks about a journey in TREK Studio + * (JourneyAssistantController): its book's tools come from the registry + * like any others, and the book card is read through the journey domain and + * the book's edit service (JourneyDomainModule, JourneyBookModule), its + * gallery in numbers through the photo signals (PhotoSignalsModule). Its + * book writes are tried on the stored book before the user sees them + * (AssistantBookGate, through the same edit service). A Studio turn may look + * at a page as the Studio draws it (AssistantVision): the Studio tab uploads + * the page to AssistantRendersController, which hands it to the waiting turn + * through AssistantRenderRegistry, only the user's own photos drawn. */ @Module({ imports: [ @@ -44,17 +65,26 @@ import { Module } from '@nestjs/common'; AuditModule, BookingImportModule, CollabModule, + JourneyBookModule, + JourneyDomainModule, McpSharedModule, PermissionsModule, + PhotoSignalsModule, RateLimitModule, SchedulingModule, SettingsModule, TripMembershipModule, MikroOrmModule.forFeature([AssistantThreads, AssistantMessages, AssistantToolCalls]), ], - controllers: [AssistantController, AssistantAttachmentsController], - // The running turns stay in this process's memory; a registry shared - // between processes would be provided here instead. + controllers: [ + AssistantController, + AssistantAttachmentsController, + JourneyAssistantController, + AssistantRendersController, + ], + // The running turns and the page images they wait for stay in this + // process's memory; registries shared between processes would be provided + // here instead. providers: [ AssistantService, AssistantToolsService, @@ -64,7 +94,12 @@ import { Module } from '@nestjs/common'; AssistantShareService, AssistantRetentionJob, AssistantCardContext, + AssistantScopes, + AssistantBookContext, + AssistantBookGate, + AssistantVision, { provide: AssistantStreamRegistry, useClass: InMemoryAssistantStreamRegistry }, + { provide: AssistantRenderRegistry, useClass: InMemoryAssistantRenderRegistry }, ], }) export class AssistantModule {} diff --git a/server/src/nest/assistant/assistant.service.ts b/server/src/nest/assistant/assistant.service.ts index de9f0a917..3161451ba 100644 --- a/server/src/nest/assistant/assistant.service.ts +++ b/server/src/nest/assistant/assistant.service.ts @@ -35,11 +35,12 @@ import { SettingsService } from '../settings/settings.service'; import { runAgentLoop, type AgentStore, type HeldCall, type StepRecord } from './assistant-agent'; import { AssistantBookingImportService } from './assistant-booking-import.service'; import { mentionItems } from './assistant-cards.helpers'; -import { buildTripCard, languageName, todayIn, turnContext, type TripCard } from './assistant-context'; +import { todayIn } from './assistant-context'; import { DISCARDED, NOT_RUN, type Outcome, withCancelled, withOutcomes } from './assistant-decisions.helpers'; import { messageIdOf, outputText, partsOf, toChatHistory, toThreadMessages } from './assistant-history'; import { rememberForTrip } from './assistant-memory'; import { toolOutputForProvider } from './assistant-output'; +import { AssistantScopes, findScopedCall, scopedThreads, tripScope } from './assistant-scope'; import { AssistantStreamRegistry } from './assistant-stream.registry'; import { titleFrom } from './assistant-title'; import { @@ -54,8 +55,9 @@ import { writeToolOf, } from './assistant-tools.constants'; import { AssistantToolsService, type AssistantToolSession, type ToolRun } from './assistant-tools.service'; +import { readTripCard } from './assistant-trip-scope'; import { unchangedSinceApplied, undoSnapshotOf, undoTargetsOf } from './assistant-undo.helpers'; -import { systemPrompt } from './assistant.prompt'; +import { AssistantVision } from './assistant-vision'; import { AssistantCardContext } from './cards/card-context'; import { ASSISTANT_UNDO_MAP } from './cards/registry'; import { appliedChange } from './tool-call-preview.helpers'; @@ -72,6 +74,7 @@ import type { AssistantFocus, AssistantMention, AssistantMessagePart, + AssistantScope, AssistantThreadListResponse, AssistantThreadResponse, AssistantThreadSummary, @@ -114,7 +117,7 @@ export interface TurnChannel { /** What a turn runs with, whichever request started it. */ interface TurnSpec { userId: number; - tripId: number; + scope: AssistantScope; threadId: number; connection: ResolvedAiConnection; locale: string; @@ -124,6 +127,8 @@ interface TurnSpec { quota: { used: number; limit: number } | null; /** The row the first step writes into, when the turn created it already (a chat turn). */ firstRowId: number | null; + /** The client draws Studio pages for this turn (assistant-vision.ts). */ + renders?: boolean; } function summaryOf(thread: AssistantThreadRow): AssistantThreadSummary { @@ -141,9 +146,10 @@ function encodeParts(parts: AssistantMessagePart[]): string { const threadNotFound = () => aiRefusal('not_found', 'Conversation not found'); /** - * The trip assistant: a user's conversations about one trip, the turns that - * answer them, the decisions on the changes a turn proposes and the undo of - * an applied one. + * The assistant: a user's conversations about one trip or (in TREK Studio) + * one journey, the turns that answer them, the decisions on the changes a + * turn proposes and the undo of an applied one. What differs between the two + * scopes (the threads, the tools, the context) is AssistantScopes'. * * A turn checks everything that can refuse it first (the rate limit, the * connection, the daily limit, one turn per user at a time), so a refusal is @@ -169,21 +175,23 @@ export class AssistantService { private readonly uow: UnitOfWork, private readonly orm: MikroORM, private readonly cardContext: AssistantCardContext, + private readonly scopes: AssistantScopes, + private readonly vision: AssistantVision, ) {} - async listThreads(userId: number, tripId: number): Promise { - return { threads: (await this.threads.listRecent(userId, tripId, THREADS_LISTED)).map(summaryOf) }; + async listThreads(userId: number, scope: AssistantScope): Promise { + return { threads: (await scopedThreads(this.threads, scope).list(userId, THREADS_LISTED)).map(summaryOf) }; } - async getThread(userId: number, tripId: number, threadId: number): Promise { - const thread = await this.threads.findOwned(threadId, userId, tripId); + async getThread(userId: number, scope: AssistantScope, threadId: number): Promise { + const thread = await scopedThreads(this.threads, scope).find(threadId, userId); if (!thread) throw threadNotFound(); const rows = await this.messages.listLatest(threadId, THREAD_ROWS); return { thread: summaryOf(thread), messages: toThreadMessages(rows, await this.callsOf(rows), new Date()) }; } - async deleteThread(userId: number, tripId: number, threadId: number): Promise { - if (!(await this.threads.deleteOwned(threadId, userId, tripId))) throw threadNotFound(); + async deleteThread(userId: number, scope: AssistantScope, threadId: number): Promise { + if (!(await scopedThreads(this.threads, scope).remove(threadId, userId))) throw threadNotFound(); } /** Stops the user's running turn, wherever it runs; nothing to stop is not an error. */ @@ -192,22 +200,24 @@ export class AssistantService { } /** - * A new message, in a thread of the user's on this trip or (threadId null) a - * new one, answered as a stream. + * A new message, in a thread of the user's on this trip or journey or + * (threadId null) a new one, answered as a stream. * * @txIndependent a streamed turn writes as it goes: the opening rows in one * transaction, then each step on its own, with the provider's answer between. */ - async chat(userId: number, tripId: number, req: AssistantChatRequest, channel: TurnChannel): Promise { + async chat(userId: number, scope: AssistantScope, req: AssistantChatRequest, channel: TurnChannel): Promise { await this.admit(userId); const connection = await this.connections.resolveForUser(userId); const dailyTurns = await this.withinDailyLimit(userId, connection); await this.claimed(userId, channel.signal, async (signal) => { - const mentions = req.mentions ?? []; + // Days, places and bookings are named with "@" in a trip only. + const tripId = scope.kind === 'trip' ? scope.tripId : null; + const mentions = tripId !== null ? (req.mentions ?? []) : []; // The labels the message keeps come from the trip, never from the request. - const card = mentions.length > 0 ? await this.tripCardOf(userId, tripId) : null; + const card = mentions.length > 0 && tripId !== null ? await readTripCard(this.tools, userId, tripId) : null; const items = card ? mentionItems(card, mentions, req.locale) : []; - const begun = await this.beginTurn(userId, tripId, req.threadId, req.text, connection.model, [ + const begun = await this.beginTurn(userId, scope, req.threadId, req.text, connection.model, [ { type: 'text', text: req.text }, ...(items.length > 0 ? [{ type: 'data-trek-mentions' as const, data: { items } }] : []), ]); @@ -222,7 +232,7 @@ export class AssistantService { : null; const spec: TurnSpec = { userId, - tripId, + scope, threadId: begun.threadId, connection, locale: req.locale, @@ -231,6 +241,7 @@ export class AssistantService { mentions, quota, firstRowId: begun.rowId, + renders: req.renders === true, }; await this.converse(spec, stream, w, signal); }); @@ -259,7 +270,7 @@ export class AssistantService { await this.withinDailyLimit(userId, connection); await this.claimed(userId, channel.signal, async (signal) => { const name = file.originalname.slice(0, MAX_FILE_NAME_CHARS); - const begun = await this.beginTurn(userId, tripId, req.threadId ?? null, name, connection.model, [ + const begun = await this.beginTurn(userId, tripScope(tripId), req.threadId ?? null, name, connection.model, [ { type: 'attachment', name, mime: file.mimetype || 'application/octet-stream', size: file.size }, ]); const stream = channel.open(); @@ -293,16 +304,16 @@ export class AssistantService { */ async decide( userId: number, - tripId: number, + scope: AssistantScope, threadId: number, req: AssistantDecisionsRequest, channel: TurnChannel, ): Promise { - if (!(await this.threads.findOwned(threadId, userId, tripId))) throw threadNotFound(); + if (!(await scopedThreads(this.threads, scope).find(threadId, userId))) throw threadNotFound(); await this.admit(userId); const open = await this.toolCalls.listOpen(threadId); if (open.length > 0 && open.every((call) => ASSISTANT_SERVER_WRITE_TOOLS[call.tool_name]?.quiet === true)) { - await this.decideQuietly(userId, tripId, threadId, req, channel); + await this.decideQuietly(userId, scope, threadId, req, channel); return; } const connection = await this.connections.resolveForUser(userId); @@ -321,7 +332,7 @@ export class AssistantService { : null; const spec: TurnSpec = { userId, - tripId, + scope, threadId, connection, locale: req.locale, @@ -330,10 +341,11 @@ export class AssistantService { mentions: [], quota, firstRowId: null, + renders: req.renders === true, }; await this.converse(spec, stream, w, signal, (session) => this.applyDecisions( - (name, args) => this.runChange(session, userId, tripId, name, args), + (name, args) => this.runChange(session, userId, scope, name, args), threadId, decided, w, @@ -356,7 +368,7 @@ export class AssistantService { */ private async decideQuietly( userId: number, - tripId: number, + scope: AssistantScope, threadId: number, req: AssistantDecisionsRequest, channel: TurnChannel, @@ -368,10 +380,9 @@ export class AssistantService { let opened: AssistantToolSession | null = null; try { w.start(messageIdOf(await this.answerStart(threadId, decided[0].call.message_id))); - const session = await this.tools.open(userId, tripId); + const session = await this.scopes.open(userId, scope); opened = session; - const run = (name: string, args: Record) => - this.runChange(session, userId, tripId, name, args); + const run = (name: string, args: Record) => this.runChange(session, userId, scope, name, args); await this.applyDecisions(run, threadId, decided, w, unrun); w.finish('stop'); } catch (err) { @@ -390,17 +401,23 @@ export class AssistantService { /** * Runs one applied change: a booking from a file through the booking import, * a found place or a taken proposal through the tool it names, anything else through its own tool. + * A booking and a trip note belong to a trip; a journey's session holds neither. */ private runChange( session: AssistantToolSession, userId: number, - tripId: number, + scope: AssistantScope, name: string, args: Record, ): Promise { - if (name === IMPORT_BOOKING_TOOL) return this.inContext(() => this.bookings.apply(userId, tripId, args)); + const tripId = scope.kind === 'trip' ? scope.tripId : null; + if (name === IMPORT_BOOKING_TOOL && tripId !== null) { + return this.inContext(() => this.bookings.apply(userId, tripId, args)); + } if (writeToolOf(name, args) !== name) return session.call(writeToolOf(name, args), foundPlaceArgs(args)); - if (name === REMEMBER_TOOL) return this.inContext(() => rememberForTrip(this.settings, userId, tripId, args)); + if (name === REMEMBER_TOOL && tripId !== null) { + return this.inContext(() => rememberForTrip(this.settings, userId, tripId, args)); + } return session.call(name, args); } @@ -411,9 +428,9 @@ export class AssistantService { * @txIndependent the undo tool commits on its own between the claim and the * claim's release on failure, so the two cannot share a transaction. */ - async undo(userId: number, tripId: number, toolCallId: string): Promise { + async undo(userId: number, scope: AssistantScope, toolCallId: string): Promise { await this.admit(userId); - const call = await this.toolCalls.findOwned(toolCallId, userId, tripId); + const call = await findScopedCall(this.toolCalls, scope, toolCallId, userId); if (!call) throw aiRefusal('not_found', 'Change not found'); const stale = () => conflict('This change cannot be undone any more', { code: 'stale' }); const args = decodeJson(ASSISTANT_TOOL_ARGS, call.args, `tool call ${call.id}`); @@ -423,9 +440,10 @@ export class AssistantService { const preview = decodeJson(ASSISTANT_TOOL_PREVIEW, call.preview, `tool call ${call.id}`); const undoArgs = undo && call.state === 'executed' ? undo.args(args, result, preview) : null; if (!undo || !undoArgs) throw stale(); - const session = await this.tools.open(userId, tripId, undoTargetsOf(undo.tool, tool, args, result)); + const onTrip = scope.kind === 'trip'; + const session = await this.scopes.open(userId, scope, undoTargetsOf(undo.tool, tool, args, result, onTrip)); try { - const snapshot = await undoSnapshotOf(session, tool, args, result); + const snapshot = await undoSnapshotOf(session, tool, args, result, { tripReads: onTrip }); if (!snapshot || !unchangedSinceApplied(tool, result, snapshot)) throw stale(); if (!(await this.toolCalls.claimUndo(call.id, userId, dbNow()))) throw stale(); const run = await session.call(undo.tool, undoArgs); @@ -484,21 +502,22 @@ export class AssistantService { */ private async beginTurn( userId: number, - tripId: number, + scope: AssistantScope, threadId: number | null, titleText: string, model: string, userParts: AssistantMessagePart[], ) { const now = dbNow(); + const threads = scopedThreads(this.threads, scope); return this.uow.transactional(async () => { let id: number; let title: string; if (threadId === null) { title = titleFrom(titleText); - id = await this.threads.createThread(userId, tripId, title, now); + id = await threads.create(userId, title, now); } else { - const thread = await this.threads.findOwned(threadId, userId, tripId); + const thread = await threads.find(threadId, userId); if (!thread) throw threadNotFound(); id = thread.id; title = thread.title; @@ -571,7 +590,7 @@ export class AssistantService { w.finish('error'); return; } - const card = await this.tripCardOf(turn.userId, turn.tripId); + const card = await readTripCard(this.tools, turn.userId, turn.tripId); const ctx = this.cardContext.contextOf(card, new Map(), turn.locale, todayIn(turn.timeZone, new Date())); const proposed = items.map((item) => ({ id: randomUUID(), @@ -601,18 +620,6 @@ export class AssistantService { w.finish('tool-calls'); } - /** The trip card a booking's change card names its day from, read with the user's rights. */ - private async tripCardOf(userId: number, tripId: number): Promise { - const session = await this.tools.open(userId, tripId, new Set(['get_trip_summary', 'list_places'])); - try { - const summary = await session.read('get_trip_summary'); - const places = await session.read('list_places'); - return buildTripCard(tripId, userId, summary.ok ? summary.value : null, places.ok ? places.value : null, null); - } finally { - await session.close(); - } - } - private async cancelOpen(threadId: number, now: string): Promise { const open = await this.toolCalls.listOpen(threadId); const claimed = await Promise.all( @@ -801,9 +808,9 @@ export class AssistantService { } /** - * The turn itself, once the stream is open: the tool session, the trip card, - * the history, then the agent loop. Whatever fails after this point ends the - * stream with an error chunk instead of a JSON answer. + * The turn itself, once the stream is open: the tool session, the trip or + * book card, the history, then the agent loop. Whatever fails after this + * point ends the stream with an error chunk instead of a JSON answer. * * @txIndependent each step is saved when it is complete, with the provider's * answer and the tool calls between two saves. @@ -818,30 +825,37 @@ export class AssistantService { const stopKeepalive = armKeepalive(stream); let opened: AssistantToolSession | null = null; try { - const session = await this.tools.open(spec.userId, spec.tripId); + const session = await this.scopes.open(spec.userId, spec.scope); opened = session; if (prelude) await prelude(session); - const card = await this.cardOf(session, spec); + const { card, system, context, gate } = await this.scopes.turnOf(session, spec.scope, { + ...spec, + now: new Date(), + }); const rows = await this.inContext(() => this.messages.listLatest(spec.threadId, HISTORY_ROWS)); const calls = await this.inContext(() => this.callsOf(rows)); const providerIds = new Map([...calls.values()].map((call) => [call.id, call.provider_call_id])); const history = toChatHistory(rows, providerIds); - const prefs = await this.inContext(() => this.settings.getUserSettings(spec.userId)); const today = todayIn(spec.timeZone, new Date()); + const { userId, threadId, connection } = spec; + const seen = { userId, threadId, connection, renders: spec.renders === true, w, signal }; + const seeing = await this.vision.turnTools(spec.scope, session, seen); const outcome = await runAgentLoop( { client: this.chatClients.create(spec.connection), - tools: session, + tools: seeing.tools, store: this.stepStore(spec), - describe: this.cardContext.forTurn(session, card, spec.locale, today).describe, + describe: this.cardContext.forTurn(gate.reader, card, spec.locale, today).describe, + refusalOf: gate.refusalOf, + vision: seeing.vision, newId: randomUUID, quota: spec.quota, card, today, }, { - system: systemPrompt(languageName(spec.locale)), - context: turnContext(card, spec.timeZone, new Date(), prefs), + system, + context, cacheKey: `trek-thread-${spec.threadId}`, history, usedCallIds: new Set( @@ -876,14 +890,6 @@ export class AssistantService { } } - /** The trip card for this turn, read through the trip tools with the user's rights. */ - private async cardOf(session: AssistantToolSession, spec: TurnSpec): Promise { - const summary = await session.read('get_trip_summary'); - const places = await session.read('list_places'); - const [found, listed] = [summary.ok ? summary.value : null, places.ok ? places.value : null]; - return buildTripCard(spec.tripId, spec.userId, found, listed, spec.focus, spec.mentions); - } - /** * Where the loop keeps its steps: one row each, the chat turn's first one made already. * @txIndependent each step is opened and saved on its own, with a provider's answer between them. diff --git a/server/src/nest/assistant/cards/journey/index.ts b/server/src/nest/assistant/cards/journey/index.ts index 392c4a864..aa833e400 100644 --- a/server/src/nest/assistant/cards/journey/index.ts +++ b/server/src/nest/assistant/cards/journey/index.ts @@ -49,7 +49,10 @@ function journalWrite(tool: string): ToolCards { export const JOURNEY_CARDS: DomainCards = { id: 'journey', tools: { - list_journey_entries: { answer: ({ args, value }) => readAnswer(argId(args, 'journeyId'), value, 'entries') }, + // A Studio conversation pins the journey, so its arguments hold no id: the answer names the journey too. + list_journey_entries: { + answer: ({ args, value }) => readAnswer(argId(args, 'journeyId') ?? idIn(value, 'journey'), value, 'entries'), + }, get_journey_entry: { answer: ({ value }) => readAnswer(idIn(value, 'journey'), value, 'entry') }, get_journey: { answer: ({ value }) => { @@ -76,5 +79,6 @@ export const JOURNEY_CARDS: DomainCards = { }, prompt: [ 'Journal: get_trip_journal finds the journal this trip shows. To show entries, call list_journey_entries with from/to for the days asked: the app draws them as cards, so do not list them again in your answer.', + "Photo book: a journey's photo book is laid out in its Studio, which has an assistant of its own. When asked to design or change the book, tell the user to open Studio from the journey; its tools are not offered here.", ], }; diff --git a/server/src/nest/assistant/journey-assistant.controller.ts b/server/src/nest/assistant/journey-assistant.controller.ts new file mode 100644 index 000000000..f9086d7eb --- /dev/null +++ b/server/src/nest/assistant/journey-assistant.controller.ts @@ -0,0 +1,116 @@ +import { ADDON_IDS } from '../../addons'; +import type { User } from '../../types'; +import { AddonGuard } from '../addons/addon.guard'; +import { RequireAddon } from '../addons/require-addon.decorator'; +import { CurrentUser } from '../auth-core/current-user.decorator'; +import { JwtAuthGuard } from '../auth-core/jwt-auth.guard'; +import { ManagedForbidden } from '../common/managed'; +import { ResponseContract } from '../common/response-contract'; +import { channelOf, idParam } from './assistant.controller'; +import { AssistantChatDto, AssistantDecisionsDto, AssistantStopDto, AssistantUndoDto } from './assistant.dto'; +import { AssistantService } from './assistant.service'; +import { JourneyAssistantGuard } from './journey-assistant.guard'; +import { Body, Controller, Delete, Get, HttpCode, Param, Post, Res, UseGuards } from '@nestjs/common'; +import { + assistantThreadListResponseSchema, + assistantThreadResponseSchema, + assistantUndoResponseSchema, + successResponseSchema, + type AssistantScope, +} from '@trek/shared'; + +import type { Response } from 'express'; + +/** The scope of a request JourneyAssistantGuard let through: the journey is open to the user. */ +function journeyScope(journeyId: string): AssistantScope { + return { kind: 'journey', journeyId: Number(journeyId) }; +} + +/** + * `/api/journeys/:journeyId/assistant`: the user's conversations with the + * assistant in TREK Studio, about one journey and its book. The same + * conversations, turns, change cards, decisions and undo as on a trip, with + * the book's tools; any member may talk about the journey, and what a + * proposed change may do is decided by the tool that runs it, with the + * user's own rights (a viewer's turn is offered no write at all). A journey + * without trips works. No files, found places or sharing to a trip's chat + * here: those belong to a trip. + * + * `chat` and `decisions` answer with a stream of UI message chunks, refused + * before it opens with a JSON `{ error, code }` like the trip's. + */ +@Controller('api/journeys/:journeyId/assistant') +@UseGuards(AddonGuard, JwtAuthGuard, JourneyAssistantGuard) +@RequireAddon(ADDON_IDS.AI_ASSISTANT, 'AI assistant') +@ManagedForbidden('the operator decides which model a managed install talks to, and pays for it') +export class JourneyAssistantController { + constructor(private readonly assistant: AssistantService) {} + + @Get('threads') + @ResponseContract(assistantThreadListResponseSchema) + threads(@CurrentUser() user: User, @Param('journeyId') journeyId: string) { + return this.assistant.listThreads(user.id, journeyScope(journeyId)); + } + + @Get('threads/:threadId') + @ResponseContract(assistantThreadResponseSchema) + thread(@CurrentUser() user: User, @Param('journeyId') journeyId: string, @Param('threadId') threadId: string) { + return this.assistant.getThread(user.id, journeyScope(journeyId), idParam(threadId)); + } + + @Delete('threads/:threadId') + @HttpCode(200) + @ResponseContract(successResponseSchema) + async deleteThread( + @CurrentUser() user: User, + @Param('journeyId') journeyId: string, + @Param('threadId') threadId: string, + ) { + await this.assistant.deleteThread(user.id, journeyScope(journeyId), idParam(threadId)); + return { success: true as const }; + } + + // response-contract-exempt: streams the turn through @Res() as server-sent events, there is no JSON body to check. + @Post('chat') + async chat( + @CurrentUser() user: User, + @Param('journeyId') journeyId: string, + @Body() body: AssistantChatDto, + @Res() res: Response, + ): Promise { + await this.assistant.chat(user.id, journeyScope(journeyId), body, channelOf(res)); + } + + // response-contract-exempt: streams the turn through @Res() as server-sent events, there is no JSON body to check. + @Post('threads/:threadId/decisions') + async decide( + @CurrentUser() user: User, + @Param('journeyId') journeyId: string, + @Param('threadId') threadId: string, + @Body() body: AssistantDecisionsDto, + @Res() res: Response, + ): Promise { + await this.assistant.decide(user.id, journeyScope(journeyId), idParam(threadId), body, channelOf(res)); + } + + @Post('tool-calls/:toolCallId/undo') + @HttpCode(200) + @ResponseContract(assistantUndoResponseSchema) + async undo( + @CurrentUser() user: User, + @Param('journeyId') journeyId: string, + @Param('toolCallId') toolCallId: string, + @Body() _body: AssistantUndoDto, + ) { + await this.assistant.undo(user.id, journeyScope(journeyId), toolCallId); + return { undone: true as const }; + } + + @Post('stop') + @HttpCode(200) + @ResponseContract(successResponseSchema) + async stop(@CurrentUser() user: User, @Body() _body: AssistantStopDto) { + await this.assistant.stop(user.id); + return { success: true as const }; + } +} diff --git a/server/src/nest/assistant/journey-assistant.guard.ts b/server/src/nest/assistant/journey-assistant.guard.ts new file mode 100644 index 000000000..2647c494a --- /dev/null +++ b/server/src/nest/assistant/journey-assistant.guard.ts @@ -0,0 +1,38 @@ +import { ADDON_IDS } from '../../addons'; +import type { User } from '../../types'; +import { AddonsService } from '../addons/addons.service'; +import { AssistantBookContext } from './assistant-book-context'; +import { CanActivate, ExecutionContext, HttpException, Injectable } from '@nestjs/common'; + +import type { Request } from 'express'; + +type JourneyRequest = Request & { user?: User }; + +/** + * Lets a request through to the assistant of `:journeyId` only while the + * journey addon is on and the user can open the journey, before the body is + * read, as TripAccessGuard does for a trip. Both refusals are a 404, worded + * like the journey routes' own, so a stranger learns nothing about which + * journeys exist. The AI assistant addon is checked before this (AddonGuard), + * the session before that (JwtAuthGuard). + */ +@Injectable() +export class JourneyAssistantGuard implements CanActivate { + constructor( + private readonly addons: AddonsService, + private readonly books: AssistantBookContext, + ) {} + + async canActivate(context: ExecutionContext): Promise { + const request = context.switchToHttp().getRequest(); + const user = request.user; + if (!user) throw new HttpException({ error: 'Unauthorized' }, 401); + if (!(await this.addons.isAddonEnabled(ADDON_IDS.JOURNEY))) { + throw new HttpException({ error: 'Journey addon is not enabled' }, 404); + } + const journeyId = Number((request.params as Record).journeyId); + const open = Number.isInteger(journeyId) && journeyId > 0 && (await this.books.canOpen(user.id, journeyId)); + if (!open) throw new HttpException({ error: 'Journey not found' }, 404); + return true; + } +} diff --git a/server/tests/e2e/assistant-journey.e2e.test.ts b/server/tests/e2e/assistant-journey.e2e.test.ts new file mode 100644 index 000000000..09656f193 --- /dev/null +++ b/server/tests/e2e/assistant-journey.e2e.test.ts @@ -0,0 +1,407 @@ +/** + * The assistant in TREK Studio, 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 journey + * addon, the journey itself), a journey without trips holding a conversation + * of its own that a trip's routes never reach, the Studio's instructions and + * book card reaching the model with the book's tools and nothing of a trip, a + * book change held, applied with the user's rights and broadcast to every tab, + * a viewer offered no write at all, and the threads going with their journey. + * Also: the entries read drawing its card although the journey id is hidden, a + * trip tool refused rather than held, a change held for an editor failing once + * they are a viewer, and a new book, which has no undo. + */ +import { buildApp } from '../../src/bootstrap'; +import { AssistantThreads } from '../../src/db/entities/AssistantThreads.entity'; +import { JourneyBooks } from '../../src/db/entities/JourneyBooks.entity'; +import { JourneyContributors } from '../../src/db/entities/JourneyContributors.entity'; +import { Journeys } from '../../src/db/entities/Journeys.entity'; +import { addJourneyContributor, makeJourney, makeJourneyEntry } from '../helpers/factories/journeys'; +import { countRows, deleteRows, findRow, updateRows } from '../helpers/factories/rows'; +import { setAddonEnabled } from '../helpers/factories/settings'; +import { makeTrip } from '../helpers/factories/trips'; +import { makeUser } from '../helpers/factories/users'; +import { spyOnRealtime, type RealtimeSpies } from '../helpers/fake-realtime'; +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 } } }>; +} + +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): 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 { + let text = ''; + for await (const chunk of req) text += String(chunk); + return text; +} + +async function answer(req: IncomingMessage, res: ServerResponse): Promise { + 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; +let broadcasts: RealtimeSpies; + +beforeAll(async () => { + fake = createServer((req, res) => { + answer(req, res).catch(() => res.destroy()); + }); + await new Promise((resolve) => fake.listen(0, '127.0.0.1', resolve)); + nestApp = await buildApp(); + orm = nestApp.get(MikroORM); + broadcasts = spyOnRealtime(nestApp); + await setAddonEnabled(orm, 'ai_assistant', true); + await setAddonEnabled(orm, 'journey', 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 = []; + broadcasts.broadcastToUser.mockClear(); +}); + +afterAll(async () => { + await nestApp.close(); + await new Promise((resolve) => fake.close(() => resolve())); +}); + +// ── Helpers ────────────────────────────────────────────────────────────────── + +const CTX = { locale: 'en', timeZone: 'Europe/Lisbon' }; + +interface Answer { + status: number; + chunks: UiStreamChunk[]; + json: Record | null; +} + +async function post(path: string, userId: number | null, body: object): Promise { + 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) : 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 = (chunks: UiStreamChunk[], type: T) => + chunks.filter((chunk): chunk is Extract => chunk.type === type); + +/** A user with a journey of their own, without any trip, and one entry in it. */ +async function ownerWithJourney() { + const { user } = await makeUser(orm); + const journey = await makeJourney(orm, user.id, { title: 'Portugal by train' }); + await makeJourneyEntry(orm, journey.id, user.id, { title: 'Alfama', location_name: 'Lisbon' }); + return { userId: user.id, journeyId: journey.id, base: `/api/journeys/${journey.id}/assistant` }; +} + +const toolNames = (body: ChatBody) => (body.tools ?? []).map((tool) => tool.function.name); + +// ── Cases ──────────────────────────────────────────────────────────────────── + +describe('Studio assistant e2e', () => { + it('ASTJE2E-001: the AI addon, auth, the journey addon and the journey come before anything else', async () => { + const j = await ownerWithJourney(); + const { user: stranger } = await makeUser(orm); + await setAddonEnabled(orm, 'ai_assistant', false); + expect((await get(`${j.base}/threads`, j.userId)).status).toBe(404); + await setAddonEnabled(orm, 'ai_assistant', true); + expect((await request(nestApp.getHttpServer()).get(`${j.base}/threads`)).status).toBe(401); + await setAddonEnabled(orm, 'journey', false); + try { + const off = await get(`${j.base}/threads`, j.userId); + expect(off.status).toBe(404); + expect(off.body).toEqual({ error: 'Journey addon is not enabled' }); + } finally { + await setAddonEnabled(orm, 'journey', true); + } + const outsider = await get(`${j.base}/threads`, stranger.id); + expect(outsider.status).toBe(404); + expect(outsider.body).toEqual({ error: 'Journey not found' }); + expect((await get('/api/journeys/abc/assistant/threads', j.userId)).status).toBe(404); + // The outsider is turned away before the body is read, like on a trip. + expect((await post(`${j.base}/chat`, stranger.id, { ...CTX, threadId: null, text: '' })).status).toBe(404); + expect((await post(`${j.base}/chat`, j.userId, { ...CTX, threadId: null, text: '' })).status).toBe(400); + expect(provider.requests).toHaveLength(0); + }); + + it('ASTJE2E-002: a journey without trips gets a conversation of its own, with the Studio instructions, the book card and the book tools', async () => { + const j = await ownerWithJourney(); + provider.script = [say('Let us start with the cover.')]; + const turn = await post(`${j.base}/chat`, j.userId, { + ...CTX, + threadId: null, + text: 'Make me a book', + focus: { spreadId: 'sp-nothing', elementIds: ['p-1'] }, + }); + expect(turn.status).toBe(200); + const threadId = ofType(turn.chunks, 'data-trek-thread')[0].data.threadId; + expect(await countRows(orm, AssistantThreads, { id: threadId, journey: j.journeyId, trip: null })).toBe(1); + + const sent = JSON.stringify(provider.requests[0].messages); + expect(sent).toContain('TREK Studio'); + expect(sent).toContain(''); + expect(sent).toContain('Journey: Portugal by train'); + expect(sent).toContain('Alfama'); + expect(sent).toContain('Gallery: no photos yet.'); + expect(sent).not.toContain(''); + const names = toolNames(provider.requests[0]); + expect(names).toEqual(expect.arrayContaining(['get_book', 'describe_book_page', 'create_book', 'edit_book_page'])); + const notHere = ['get_trip_summary', 'create_place', 'remember_for_trip', 'use_addon_tools', 'restore_book_page']; + for (const name of notHere) expect(names, name).not.toContain(name); + for (const tool of provider.requests[0].tools ?? []) { + expect(Object.keys(tool.function.parameters.properties ?? {}), tool.function.name).not.toContain('journeyId'); + } + + const list = await get(`${j.base}/threads`, j.userId); + expect(list.status).toBe(200); + expect(list.body.threads).toEqual([expect.objectContaining({ id: threadId, title: 'Make me a book' })]); + const shown = await get(`${j.base}/threads/${threadId}`, j.userId); + expect(shown.status).toBe(200); + expect(shown.body.messages.map((m: { role: string }) => m.role)).toEqual(['user', 'assistant']); + }); + + it('ASTJE2E-003: a book change is held, applied with the user rights, broadcast to every tab, and the turn goes on', async () => { + const j = await ownerWithJourney(); + provider.script = [callTool('call_book', 'create_book', { title: 'Portugal' })]; + const turn = await post(`${j.base}/chat`, j.userId, { ...CTX, threadId: null, text: 'Start a book' }); + expect(turn.chunks.at(-1)).toEqual({ type: 'finish', finishReason: 'tool-calls' }); + const [held] = ofType(turn.chunks, 'tool-approval-request'); + const threadId = ofType(turn.chunks, 'data-trek-thread')[0].data.threadId; + expect(await findRow(orm, JourneyBooks, { journey: j.journeyId })).toBeNull(); + + provider.script = [say('The book is there.')]; + const decided = await post(`${j.base}/threads/${threadId}/decisions`, j.userId, { + ...CTX, + decisions: [{ toolCallId: held.toolCallId, approved: true }], + }); + expect(decided.status).toBe(200); + expect(ofType(decided.chunks, 'tool-output-available')).toHaveLength(1); + expect(await findRow(orm, JourneyBooks, { journey: j.journeyId })).not.toBeNull(); + expect(broadcasts.broadcastToUser).toHaveBeenCalledWith( + j.userId, + expect.objectContaining({ type: 'journey:book:saved', journeyId: j.journeyId }), + undefined, + ); + expect(provider.requests.at(-1)?.messages.some((message) => message.role === 'tool')).toBe(true); + }); + + it('ASTJE2E-004: a viewer may talk about the journey, and is offered the reads and not one write', async () => { + const j = await ownerWithJourney(); + const { user: viewer } = await makeUser(orm); + await addJourneyContributor(orm, j.journeyId, viewer.id, 'viewer'); + provider.script = [callTool('call_read', 'get_book', {}), say('There is no book yet.')]; + const turn = await post(`${j.base}/chat`, viewer.id, { ...CTX, threadId: null, text: 'What is in the book?' }); + expect(turn.status).toBe(200); + expect(ofType(turn.chunks, 'tool-output-available')).toHaveLength(1); + const names = toolNames(provider.requests[0]); + expect(names).toEqual(expect.arrayContaining(['get_book', 'describe_book_page'])); + for (const name of ['create_book', 'add_book_pages', 'edit_book_page', 'delete_book_pages', 'set_book_cover']) { + expect(names, name).not.toContain(name); + } + expect(JSON.stringify(provider.requests[0].messages)).toContain('Your role: viewer'); + }); + + it('ASTJE2E-005: a journey conversation and a trip conversation never reach each other', async () => { + const j = await ownerWithJourney(); + const trip = await makeTrip(orm, j.userId, { title: 'Kyoto' }); + provider.script = [say('journey'), say('trip')]; + const inJourney = await post(`${j.base}/chat`, j.userId, { ...CTX, threadId: null, text: 'About the book' }); + const inTrip = await post(`/api/trips/${trip.id}/assistant/chat`, j.userId, { + ...CTX, + threadId: null, + text: 'About Kyoto', + }); + const journeyThread = ofType(inJourney.chunks, 'data-trek-thread')[0].data.threadId; + const tripThread = ofType(inTrip.chunks, 'data-trek-thread')[0].data.threadId; + expect(JSON.stringify(provider.requests[1].messages)).toContain(''); + + const tripList = await get(`/api/trips/${trip.id}/assistant/threads`, j.userId); + expect(tripList.body.threads.map((thread: { id: number }) => thread.id)).toEqual([tripThread]); + const journeyList = await get(`${j.base}/threads`, j.userId); + expect(journeyList.body.threads.map((thread: { id: number }) => thread.id)).toEqual([journeyThread]); + expect((await get(`${j.base}/threads/${tripThread}`, j.userId)).status).toBe(404); + expect((await get(`/api/trips/${trip.id}/assistant/threads/${journeyThread}`, j.userId)).status).toBe(404); + const continued = await post(`${j.base}/chat`, j.userId, { ...CTX, threadId: tripThread, text: 'Go on' }); + expect(continued).toMatchObject({ status: 404, json: { code: 'not_found' } }); + }); + + it('ASTJE2E-006: a thread is deleted by its owner only, and all go with the journey', async () => { + const j = await ownerWithJourney(); + const { user: editor } = await makeUser(orm); + await addJourneyContributor(orm, j.journeyId, editor.id, 'editor'); + provider.script = [say('one'), say('two')]; + const first = await post(`${j.base}/chat`, j.userId, { ...CTX, threadId: null, text: 'First' }); + await post(`${j.base}/chat`, j.userId, { ...CTX, threadId: null, text: 'Second' }); + const threadId = ofType(first.chunks, 'data-trek-thread')[0].data.threadId; + const remove = (userId: number) => + request(nestApp.getHttpServer()).delete(`${j.base}/threads/${threadId}`).set('Cookie', sessionCookie(userId)); + expect((await get(`${j.base}/threads/${threadId}`, editor.id)).status).toBe(404); + expect((await remove(editor.id)).status).toBe(404); + expect((await remove(j.userId)).status).toBe(200); + expect((await get(`${j.base}/threads/${threadId}`, j.userId)).status).toBe(404); + expect(await countRows(orm, AssistantThreads, { journey: j.journeyId })).toBe(1); + await deleteRows(orm, Journeys, { id: j.journeyId }); + expect(await countRows(orm, AssistantThreads, { journey: j.journeyId })).toBe(0); + }); + + it('ASTJE2E-007: the entries read draws its card without the hidden journey id, and a trip tool is refused, not held', async () => { + const j = await ownerWithJourney(); + provider.script = [ + callTool('call_entries', 'list_journey_entries', {}), + callTool('call_note', 'remember_for_trip', { note: 'Travels by train' }), + say('Here is the journal.'), + ]; + const turn = await post(`${j.base}/chat`, j.userId, { ...CTX, threadId: null, text: 'What did I write?' }); + expect(turn.status).toBe(200); + const [card] = ofType(turn.chunks, 'data-trek-card'); + expect(card?.data).toMatchObject({ + toolCallId: 'call_entries', + card: { kind: 'journeyEntries', journeyId: j.journeyId }, + }); + expect(ofType(turn.chunks, 'tool-output-error')).toEqual([ + { type: 'tool-output-error', toolCallId: 'call_note', errorText: 'Unknown tool: remember_for_trip' }, + ]); + expect(ofType(turn.chunks, 'tool-approval-request')).toHaveLength(0); + }); + + it('ASTJE2E-008: a book change held for an editor fails once they are a viewer, and writes nothing', async () => { + const j = await ownerWithJourney(); + const { user: editor } = await makeUser(orm); + await addJourneyContributor(orm, j.journeyId, editor.id, 'editor'); + provider.script = [callTool('call_held', 'create_book', { title: 'Portugal' })]; + const turn = await post(`${j.base}/chat`, editor.id, { ...CTX, threadId: null, text: 'Start a book' }); + const [held] = ofType(turn.chunks, 'tool-approval-request'); + const threadId = ofType(turn.chunks, 'data-trek-thread')[0].data.threadId; + await updateRows(orm, JourneyContributors, { journey: j.journeyId, user: editor.id }, { role: 'viewer' }); + + provider.script = [say('That did not go through.')]; + const decided = await post(`${j.base}/threads/${threadId}/decisions`, editor.id, { + ...CTX, + decisions: [{ toolCallId: held.toolCallId, approved: true }], + }); + expect(decided.status).toBe(200); + expect(ofType(decided.chunks, 'tool-output-error')).toEqual([ + { type: 'tool-output-error', toolCallId: held.toolCallId, errorText: expect.stringContaining('Unknown tool') }, + ]); + expect(ofType(decided.chunks, 'tool-output-available')).toHaveLength(0); + expect(await findRow(orm, JourneyBooks, { journey: j.journeyId })).toBeNull(); + }); + + it('ASTJE2E-009: a new book has no undo, and a trip conversation never reaches its change', async () => { + const j = await ownerWithJourney(); + const trip = await makeTrip(orm, j.userId, { title: 'Kyoto' }); + provider.script = [callTool('call_undo', 'create_book', { title: 'Portugal' })]; + const turn = await post(`${j.base}/chat`, j.userId, { ...CTX, threadId: null, text: 'Start a book' }); + const [held] = ofType(turn.chunks, 'tool-approval-request'); + const threadId = ofType(turn.chunks, 'data-trek-thread')[0].data.threadId; + provider.script = [say('The book is there.')]; + await post(`${j.base}/threads/${threadId}/decisions`, j.userId, { + ...CTX, + decisions: [{ toolCallId: held.toolCallId, approved: true }], + }); + const undo = (base: string) => + request(nestApp.getHttpServer()) + .post(`${base}/tool-calls/${held.toolCallId}/undo`) + .set('Cookie', sessionCookie(j.userId)) + .send({}); + const stale = await undo(j.base); + expect(stale.status).toBe(409); + expect(stale.body).toMatchObject({ code: 'stale' }); + expect((await undo(`/api/trips/${trip.id}/assistant`)).status).toBe(404); + expect(await findRow(orm, JourneyBooks, { journey: j.journeyId })).not.toBeNull(); + }); +}); diff --git a/server/tests/unit/db/assistant-journey-threads-migration.test.ts b/server/tests/unit/db/assistant-journey-threads-migration.test.ts new file mode 100644 index 000000000..abffa0c9d --- /dev/null +++ b/server/tests/unit/db/assistant-journey-threads-migration.test.ts @@ -0,0 +1,165 @@ +/** + * `Migration20200101046250_an_assistant_conversation_can_be_about_a_journey`: + * `assistant_threads` is rebuilt so a thread can be about a journey instead of + * a trip, with `assistant_messages` and `assistant_tool_calls` rebuilt beside + * it, without losing a row of any of the three; every thread is about exactly + * one of the two, 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 = 'Migration20200101046250_an_assistant_conversation_can_be_about_a_journey'; + +async function ormBeforeTarget(): Promise { + 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 seedOwner(orm: MikroORM): Promise { + 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)", + ); +} + +async function seedTripConversation(orm: MikroORM): Promise { + 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_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 journey threads migration', () => { + it('JTHRMIG-001: keeps every thread, message and proposed change as it was', async () => { + const orm = await ormBeforeTarget(); + try { + await seedOwner(orm); + await seedTripConversation(orm); + + await migrateTo(orm, TARGET); + + expect(await rawQuery(orm, 'SELECT * FROM assistant_threads')).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', + }, + ]); + expect(await rawQuery(orm, 'SELECT * FROM assistant_messages')).toEqual([ + { + id: 5, + thread_id: 1, + role: 'assistant', + parts: '[]', + provider_state: '{"items":[]}', + status: 'awaiting_approval', + model: 'claude', + created_at: '2026-10-20 10:00:00', + }, + ]); + expect(await rawQuery(orm, 'SELECT * FROM assistant_tool_calls')).toEqual([ + { + id: 'c1', + thread_id: 1, + message_id: 5, + provider_call_id: 'toolu_1', + tool_name: 'create_place', + args: '{"name":"A"}', + preview: '{}', + state: 'executed', + result: '{"place":{"id":3}}', + undo_until: '2026-10-20 10:15:00', + created_at: '2026-10-20 10:00:00', + decided_at: '2026-10-20 10:01:00', + }, + ]); + expect(await rawQuery(orm, 'SELECT * FROM pragma_foreign_key_check')).toEqual([]); + } finally { + await orm.close(true); + } + }, 30000); + + it('JTHRMIG-002: a thread is about a trip or a journey, never both and never neither', async () => { + const orm = await ormBeforeTarget(); + try { + await seedOwner(orm); + await migrateTo(orm, TARGET); + + await rawExec(orm, "INSERT INTO assistant_threads (id, user_id, journey_id, title) VALUES (2, 1, 20, 'Book')"); + expect(await rawQuery(orm, 'SELECT trip_id, journey_id FROM assistant_threads WHERE id = 2')).toEqual([ + { trip_id: null, journey_id: 20 }, + ]); + 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, title) VALUES (1, 'Neither')"), + ).rejects.toThrow(/CHECK/); + await expect( + rawExec(orm, "INSERT INTO assistant_threads (user_id, journey_id, title) VALUES (1, 999, 'Nowhere')"), + ).rejects.toThrow(/FOREIGN KEY/); + } finally { + await orm.close(true); + } + }, 30000); + + it('JTHRMIG-003: each goes with its journey or its trip, children included, and the keys point at the new tables', async () => { + const orm = await ormBeforeTarget(); + try { + await seedOwner(orm); + await seedTripConversation(orm); + await migrateTo(orm, TARGET); + await rawExec(orm, "INSERT INTO assistant_threads (id, user_id, journey_id, title) VALUES (2, 1, 20, 'Book')"); + + 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 journeys WHERE id = 20'); + expect(await rawQuery(orm, 'SELECT id FROM assistant_threads')).toEqual([{ id: 1 }]); + await rawExec(orm, 'DELETE FROM trips WHERE id = 10'); + expect(await rawQuery(orm, 'SELECT COUNT(*) AS n FROM assistant_threads')).toEqual([{ n: 0 }]); + expect(await rawQuery(orm, 'SELECT COUNT(*) AS n FROM assistant_messages')).toEqual([{ n: 0 }]); + expect(await rawQuery(orm, 'SELECT COUNT(*) AS n FROM assistant_tool_calls')).toEqual([{ n: 0 }]); + } finally { + await orm.close(true); + } + }, 30000); +}); diff --git a/server/tests/unit/db/repositories/AssistantConversations.repository.test.ts b/server/tests/unit/db/repositories/AssistantConversations.repository.test.ts index 5e0e19d73..a6a0e8d20 100644 --- a/server/tests/unit/db/repositories/AssistantConversations.repository.test.ts +++ b/server/tests/unit/db/repositories/AssistantConversations.repository.test.ts @@ -1,13 +1,18 @@ /** * The assistant's conversation tables through their repositories: threads - * reached only by their owner on their own trip, messages in the order they - * were written, proposed changes decided and undone exactly once, the usage a - * daily limit counts, and everything going with its user or trip (GDPR). + * reached only by their owner on their own trip or journey, messages in the + * order they were written, proposed changes decided and undone exactly once, + * the usage a daily limit counts, and everything going with its user, trip or + * journey (GDPR). */ import { AssistantMessages } from '../../../../src/db/entities/AssistantMessages.entity'; import { AssistantThreads } from '../../../../src/db/entities/AssistantThreads.entity'; import { AssistantToolCalls } from '../../../../src/db/entities/AssistantToolCalls.entity'; import { AssistantUsage } from '../../../../src/db/entities/AssistantUsage.entity'; +import { JourneyContributors } from '../../../../src/db/entities/JourneyContributors.entity'; +import { Journeys } from '../../../../src/db/entities/Journeys.entity'; +import { TripJournalLinkMembers } from '../../../../src/db/entities/TripJournalLinkMembers.entity'; +import { TripJournalLinks } from '../../../../src/db/entities/TripJournalLinks.entity'; import { Trips } from '../../../../src/db/entities/Trips.entity'; import { Users } from '../../../../src/db/entities/Users.entity'; import type { AssistantMessagesRepository } from '../../../../src/db/repositories/AssistantMessages.repository'; @@ -15,7 +20,8 @@ import type { AssistantThreadsRepository } from '../../../../src/db/repositories import type { AssistantToolCallsRepository } from '../../../../src/db/repositories/AssistantToolCalls.repository'; import type { AssistantUsageRepository } from '../../../../src/db/repositories/AssistantUsage.repository'; import { createSnapshotTestDb } from '../../../helpers/db-mock'; -import { countRows, deleteRows } from '../../../helpers/factories/rows'; +import { addJourneyContributor, makeJourney } from '../../../helpers/factories/journeys'; +import { countRows, createRow, deleteRows, insertRow } from '../../../helpers/factories/rows'; import { addTripMember, makeTrip } from '../../../helpers/factories/trips'; import { makeUser } from '../../../helpers/factories/users'; import { resetTestDb } from '../../../helpers/test-db'; @@ -55,6 +61,12 @@ async function ownerWithTrip() { return { userId: user.id, tripId: trip.id }; } +async function ownerWithJourney() { + const { user } = await makeUser(t); + const journey = await makeJourney(t, user.id); + return { userId: user.id, journeyId: journey.id }; +} + async function threadWithMessage() { const { userId, tripId } = await ownerWithTrip(); const threadId = await threads.createThread(userId, tripId, 'Kyoto day', AT); @@ -119,6 +131,93 @@ describe('threads', () => { }); }); +describe('journey threads', () => { + it('ASTREPO-003: a journey thread is found, listed and deleted only by its owner on its journey, never on a trip', async () => { + const { userId, journeyId } = await ownerWithJourney(); + const { user: other } = await makeUser(t); + const trip = await makeTrip(t, userId); + const older = await threads.createJourneyThread(userId, journeyId, 'Cover', AT); + const newer = await threads.createJourneyThread(userId, journeyId, 'Pages', AT); + const onTrip = await threads.createThread(userId, trip.id, 'Kyoto', AT); + await threads.touch(older, LATER); + + expect((await threads.listRecentOnJourney(userId, journeyId, 20)).map((row) => row.id)).toEqual([older, newer]); + expect((await threads.listRecent(userId, trip.id, 20)).map((row) => row.id)).toEqual([onTrip]); + expect(await threads.findOwnedOnJourney(older, userId, journeyId)).toMatchObject({ + title: 'Cover', + journey_id: journeyId, + trip_id: null, + }); + expect(await threads.findOwnedOnJourney(older, other.id, journeyId)).toBeNull(); + expect(await threads.findOwnedOnJourney(older, userId, journeyId + 1)).toBeNull(); + expect(await threads.findOwnedOnJourney(onTrip, userId, journeyId)).toBeNull(); + expect(await threads.findOwned(older, userId, trip.id)).toBeNull(); + expect(await threads.findOwned(onTrip, userId, trip.id)).toMatchObject({ trip_id: trip.id, journey_id: null }); + + expect(await threads.deleteOwnedOnJourney(older, other.id, journeyId)).toBe(false); + expect(await threads.deleteOwned(older, userId, trip.id)).toBe(false); + expect(await threads.deleteOwnedOnJourney(older, userId, journeyId)).toBe(true); + }); + + it('ASTREPO-004: retention keeps the threads of the journey owner and its contributors, and drops those of people taken off it', async () => { + const { userId, journeyId } = await ownerWithJourney(); + const { user: editor } = await makeUser(t); + const { user: leaver } = await makeUser(t); + await addJourneyContributor(t, journeyId, editor.id, 'editor'); + await addJourneyContributor(t, journeyId, leaver.id, 'viewer'); + const own = await threads.createJourneyThread(userId, journeyId, 'Own', AT); + const edited = await threads.createJourneyThread(editor.id, journeyId, 'Editor', AT); + const left = await threads.createJourneyThread(leaver.id, journeyId, 'Leaver', AT); + await deleteRows(t, JourneyContributors, { journey: journeyId, user: leaver.id }); + + expect(await threads.deleteWithoutAccess()).toBe(1); + expect(await threads.findOwnedOnJourney(own, userId, journeyId)).not.toBeNull(); + expect(await threads.findOwnedOnJourney(edited, editor.id, journeyId)).not.toBeNull(); + expect(await threads.findOwnedOnJourney(left, leaver.id, journeyId)).toBeNull(); + }); + + it('ASTREPO-006: retention keeps the journey threads of someone a trip journal link lets in, until it drops them', async () => { + const { userId, journeyId } = await ownerWithJourney(); + const trip = await makeTrip(t, userId); + const { user: member } = await makeUser(t); + const link = await createRow(t, TripJournalLinks, { trip: trip.id, journey: journeyId, created_at: Date.now() }); + await insertRow(t, TripJournalLinkMembers, { link: link.id, user: member.id, added_at: Date.now() }); + const linked = await threads.createJourneyThread(member.id, journeyId, 'Linked', AT); + + expect(await threads.deleteWithoutAccess()).toBe(0); + expect(await threads.findOwnedOnJourney(linked, member.id, journeyId)).not.toBeNull(); + + await deleteRows(t, TripJournalLinkMembers, { link: link.id, user: member.id }); + expect(await threads.deleteWithoutAccess()).toBe(1); + expect(await threads.findOwnedOnJourney(linked, member.id, journeyId)).toBeNull(); + }); + + it('ASTREPO-005: a change of a journey thread is found only through its own user and journey', async () => { + const { userId, journeyId } = await ownerWithJourney(); + const { user: other } = await makeUser(t); + const threadId = await threads.createJourneyThread(userId, journeyId, 'Book', AT); + const messageId = await messages.append({ + threadId, + role: 'assistant', + parts: '[]', + providerState: null, + status: 'awaiting_approval', + model: 'claude', + createdAt: AT, + }); + await calls.insertProposals([proposal('j1', threadId, messageId)]); + expect(await calls.findOwnedOnJourney('j1', userId, journeyId)).toMatchObject({ id: 'j1', thread_id: threadId }); + expect(await calls.findOwnedOnJourney('j1', other.id, journeyId)).toBeNull(); + expect(await calls.findOwnedOnJourney('j1', userId, journeyId + 1)).toBeNull(); + expect(await calls.findOwned('j1', userId, journeyId)).toBeNull(); + + await deleteRows(t, Journeys, { id: journeyId }); + expect(await countRows(t, AssistantThreads, { id: threadId })).toBe(0); + expect(await countRows(t, AssistantMessages, { id: messageId })).toBe(0); + expect(await countRows(t, AssistantToolCalls, { id: 'j1' })).toBe(0); + }); +}); + 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(); diff --git a/server/tests/unit/nest/assistant/assistant-journey-session.test.ts b/server/tests/unit/nest/assistant/assistant-journey-session.test.ts new file mode 100644 index 000000000..e97075285 --- /dev/null +++ b/server/tests/unit/nest/assistant/assistant-journey-session.test.ts @@ -0,0 +1,130 @@ +/** + * The assistant's tool session for a Studio conversation, over the container's + * real MCP registry: it holds the book's tools and the journey's reads, all on + * the conversation's journey, and nothing of a trip; a viewer's holds no write + * at all; an undo's holds its target; the journey id is hidden and pinned like + * a trip's, and the tools answer with the user's own rights. + */ +import { McpRegistryService } from '../../../../src/nest-mcp'; +import { isOfferedInJourney } from '../../../../src/nest/assistant/assistant-tool-offer'; +import { AssistantToolsService } from '../../../../src/nest/assistant/assistant-tools.service'; +import { addJourneyContributor, makeJourney } from '../../../helpers/factories/journeys'; +import { setAddonEnabled } from '../../../helpers/factories/settings'; +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 { beforeAll, describe, expect, it } from 'vitest'; + +const realtime = new FakeRealtimeService(); +let orm: MikroORM; +let registry: McpRegistryService; +let tools: AssistantToolsService; + +beforeAll(async () => { + const app = await bootTestApp(realtime); + orm = app.get(MikroORM); + registry = app.get(McpRegistryService); + tools = app.get(AssistantToolsService); + await setAddonEnabled(orm, 'journey', true); +}); + +const BOOK_WRITES = ['create_book', 'add_book_pages', 'move_book_page', 'delete_book_pages', 'edit_book_page']; + +async function ownerWithJourneys() { + const { user } = await makeUser(orm); + const journey = await makeJourney(orm, user.id, { title: 'Lisbon' }); + const other = await makeJourney(orm, user.id, { title: 'Porto' }); + return { userId: user.id, journeyId: journey.id, otherId: other.id }; +} + +describe('a Studio tool session', () => { + it('ASTJSES-001: offers the book tools and the journey reads at once, on this journey, and nothing of a trip', async () => { + const { userId, journeyId } = await ownerWithJourneys(); + const session = await tools.openJourney(userId, journeyId, true); + try { + const specs = session.specs(); + const names = specs.map((spec) => spec.name); + expect(names).toEqual( + expect.arrayContaining(['get_book', 'describe_book_page', 'suggest_book_photos', 'list_journey_entries']), + ); + expect(names).toEqual(expect.arrayContaining([...BOOK_WRITES, 'set_book_cover'])); + for (const name of ['restore_book_page', 'get_journey_share_link', 'create_journey_entry', 'list_journeys']) { + expect(names, name).not.toContain(name); + } + for (const name of ['get_trip_summary', 'create_place', 'remember_for_trip', 'use_addon_tools']) { + expect(names, name).not.toContain(name); + } + const classOf = new Map(registry.list().map((entry) => [entry.name, entry.className] as const)); + for (const spec of specs) { + expect(isOfferedInJourney(spec.name, classOf.get(spec.name)), spec.name).toBe(true); + const properties = Object.keys((spec.parameters.properties as Record | undefined) ?? {}); + expect(properties, spec.name).not.toContain('journeyId'); + expect((spec.parameters.required as string[] | undefined) ?? [], spec.name).not.toContain('journeyId'); + } + expect(session.kindOf('get_book')).toBe('read'); + expect(session.kindOf('edit_book_page')).toBe('write'); + expect(session.kindOf('remember_for_trip')).toBeNull(); + expect(session.kindOf('use_addon_tools')).toBeNull(); + } finally { + await session.close(); + } + }); + + it('ASTJSES-002: a viewer is offered the reads and not one write', async () => { + const { journeyId } = await ownerWithJourneys(); + const { user: viewer } = await makeUser(orm); + await addJourneyContributor(orm, journeyId, viewer.id, 'viewer'); + const session = await tools.openJourney(viewer.id, journeyId, false); + try { + const names = session.specs().map((spec) => spec.name); + expect(names).toEqual(expect.arrayContaining(['get_book', 'describe_book_page', 'list_journey_entries'])); + for (const name of [...BOOK_WRITES, 'set_book_cover']) expect(names, name).not.toContain(name); + for (const name of names) expect(session.kindOf(name), name).toBe('read'); + } finally { + await session.close(); + } + }); + + it('ASTJSES-003: a call runs on the conversation journey, and another journey id is refused', async () => { + const { userId, journeyId, otherId } = await ownerWithJourneys(); + const session = await tools.openJourney(userId, journeyId, true); + try { + const run = await session.call('list_journey_entries', {}); + expect(run).toMatchObject({ ok: true, value: { journey: { id: journeyId, title: 'Lisbon' } } }); + expect(await session.call('get_book', {})).toMatchObject({ ok: true, value: { exists: false } }); + expect(session.pinArgs('get_book', { journeyId: otherId })).toEqual({ + error: 'This conversation is about one journey; its id is set by the app and cannot be changed.', + }); + expect(session.pinArgs('describe_book_page', { journeyId, spreadId: 'sp-1' })).toEqual({ + args: { spreadId: 'sp-1' }, + }); + } finally { + await session.close(); + } + }); + + it('ASTJSES-004: a stranger gets the tool refusal, not the journey', async () => { + const { journeyId } = await ownerWithJourneys(); + const { user: stranger } = await makeUser(orm); + const session = await tools.openJourney(stranger.id, journeyId, false); + try { + expect(await session.call('get_book', {})).toEqual({ ok: false, value: 'Journey not found or access denied.' }); + } finally { + await session.close(); + } + }); + + it('ASTJSES-005: an undo session holds its target and nothing else', async () => { + const { userId, journeyId } = await ownerWithJourneys(); + const session = await tools.openJourney(userId, journeyId, true, new Set(['restore_book_page'])); + try { + expect(session.specs().map((spec) => spec.name)).toEqual(['restore_book_page']); + expect(session.kindOf('restore_book_page')).toBe('write'); + expect((await session.read('get_book')).value).toBe('Unknown tool: get_book'); + } finally { + await session.close(); + } + }); +}); diff --git a/server/tests/unit/nest/assistant/assistant-scope.test.ts b/server/tests/unit/nest/assistant/assistant-scope.test.ts new file mode 100644 index 000000000..5d0cad002 --- /dev/null +++ b/server/tests/unit/nest/assistant/assistant-scope.test.ts @@ -0,0 +1,431 @@ +/** + * The assistant's two scopes, a trip and a journey, in their pure parts: which + * repository methods a scope's threads and changes are reached through, which + * tools a Studio conversation attaches and keeps, the book card and the + * Studio's instructions, and the pieces that read through injected services + * (the book context, the scope's session and turn) against fakes. + */ +import type { AssistantThreadsRepository } from '../../../../src/db/repositories/AssistantThreads.repository'; +import type { AssistantToolCallsRepository } from '../../../../src/db/repositories/AssistantToolCalls.repository'; +import { + AssistantBookContext, + bookTurnContext, + emptyTripCard, + renderBookCard, + type BookCard, +} from '../../../../src/nest/assistant/assistant-book-context'; +import type { AssistantBookGate } from '../../../../src/nest/assistant/assistant-book-gate'; +import { + AssistantScopes, + findScopedCall, + scopedThreads, + tripScope, +} from '../../../../src/nest/assistant/assistant-scope'; +import { + isOfferedInJourney, + isOfferedTool, + JOURNEY_PINNED_ARG, + keptInJourney, +} from '../../../../src/nest/assistant/assistant-tool-offer'; +import type { AssistantToolsService } from '../../../../src/nest/assistant/assistant-tools.service'; +import { readTripCard, tripCardFrom } from '../../../../src/nest/assistant/assistant-trip-scope'; +import { studioPrompt, systemPrompt } from '../../../../src/nest/assistant/assistant.prompt'; +import type { JourneyBookEditService } from '../../../../src/nest/journey/journey-book-edit.service'; +import type { JourneyDomainService } from '../../../../src/nest/journey/journey-domain.service'; +import type { PhotoSignalsService } from '../../../../src/nest/photos/photo-signals.service'; +import type { SettingsService } from '../../../../src/nest/settings/settings.service'; +import { createSnapshotTestDb } from '../../../helpers/db-mock'; +import { createTestOrm, type TestOrm } from '../../../helpers/test-orm'; +import type { BookOverview } from '@trek/shared'; + +import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'; + +const testDb = createSnapshotTestDb(); +let t: TestOrm; + +beforeAll(async () => { + t = await createTestOrm(testDb); +}); +afterAll(async () => { + await t.close(); + testDb.close(); +}); + +const NOW = new Date('2026-07-03T09:00:00Z'); + +function threadRepo() { + const row = { id: 1 }; + return { + createThread: vi.fn(async () => 11), + createJourneyThread: vi.fn(async () => 12), + findOwned: vi.fn(async () => row), + findOwnedOnJourney: vi.fn(async () => row), + listRecent: vi.fn(async () => [row]), + listRecentOnJourney: vi.fn(async () => [row]), + deleteOwned: vi.fn(async () => true), + deleteOwnedOnJourney: vi.fn(async () => true), + }; +} + +const BOOK: BookOverview = { + exists: true, + version: 7, + title: 'Lisbon in spring', + page: { preset: 'square-210', pageWidth: 210, pageHeight: 210, bleed: 3, safe: 10 }, + spreads: [ + { + index: 0, + id: 'sp-cover', + role: 'cover', + entryId: null, + background: null, + photoIds: [812], + texts: ['Lisbon'], + elements: 2, + emptyFrames: 0, + parked: 0, + }, + { + index: 1, + id: 'sp-alfama', + role: 'inner', + entryId: 40, + background: '#ffffff', + photoIds: [813, 814], + texts: [], + elements: 2, + emptyFrames: 1, + parked: 0, + }, + ], + layouts: [{ id: 'lay-1', name: 'Three in a row', role: 'inner' }], +}; + +function card(overrides: Partial = {}): BookCard { + return { + journeyId: 12, + title: 'Portugal', + subtitle: 'Two weeks by train', + role: 'editor', + book: BOOK, + gallery: { photos: 120, withTime: 118, withGps: 90 }, + entries: [{ id: 40, date: '2026-04-02', title: 'Alfama', place: 'Lisbon', photos: 3 }], + focus: null, + ...overrides, + }; +} + +describe('a scope reaches its own threads and changes', () => { + it('ASTSCP-001: a trip scope goes through the trip methods with its trip id', async () => { + const repo = threadRepo(); + const threads = scopedThreads(repo as unknown as AssistantThreadsRepository, tripScope(5)); + expect(await threads.create(7, 'Kyoto', 'at')).toBe(11); + await threads.find(3, 7); + await threads.list(7, 20); + expect(await threads.remove(3, 7)).toBe(true); + expect(repo.createThread).toHaveBeenCalledWith(7, 5, 'Kyoto', 'at'); + expect(repo.findOwned).toHaveBeenCalledWith(3, 7, 5); + expect(repo.listRecent).toHaveBeenCalledWith(7, 5, 20); + expect(repo.deleteOwned).toHaveBeenCalledWith(3, 7, 5); + expect(repo.createJourneyThread).not.toHaveBeenCalled(); + }); + + it('ASTSCP-002: a journey scope goes through the journey methods with its journey id', async () => { + const repo = threadRepo(); + const threads = scopedThreads(repo as unknown as AssistantThreadsRepository, { kind: 'journey', journeyId: 12 }); + expect(await threads.create(7, 'Book', 'at')).toBe(12); + await threads.find(3, 7); + await threads.list(7, 20); + await threads.remove(3, 7); + expect(repo.createJourneyThread).toHaveBeenCalledWith(7, 12, 'Book', 'at'); + expect(repo.findOwnedOnJourney).toHaveBeenCalledWith(3, 7, 12); + expect(repo.listRecentOnJourney).toHaveBeenCalledWith(7, 12, 20); + expect(repo.deleteOwnedOnJourney).toHaveBeenCalledWith(3, 7, 12); + expect(repo.createThread).not.toHaveBeenCalled(); + }); + + 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 calls = repo as unknown as AssistantToolCallsRepository; + await findScopedCall(calls, tripScope(5), 'tc-1', 7); + await findScopedCall(calls, { kind: 'journey', journeyId: 12 }, 'tc-2', 7); + expect(repo.findOwned).toHaveBeenCalledWith('tc-1', 7, 5); + expect(repo.findOwnedOnJourney).toHaveBeenCalledWith('tc-2', 7, 12); + }); +}); + +describe('the tools of a Studio conversation', () => { + it('ASTSCP-010: attaches the book tools and the journey tools, the denied ones and every other controller left out', () => { + expect(JOURNEY_PINNED_ARG).toBe('journeyId'); + expect(isOfferedInJourney('edit_book_page', 'JourneyBookMcp')).toBe(true); + expect(isOfferedInJourney('suggest_book_photos', 'JourneyBookPhotosMcp')).toBe(true); + expect(isOfferedInJourney('get_journey', 'JourneyMcp')).toBe(true); + expect(isOfferedInJourney('get_journey_map_layers', 'JourneyMapMcp')).toBe(true); + expect(isOfferedInJourney('restore_book_page', 'JourneyBookMcp')).toBe(false); + expect(isOfferedInJourney('get_journey_share_link', 'JourneyMcp')).toBe(false); + expect(isOfferedInJourney('remove_journey_contributor', 'JourneyMcp')).toBe(false); + expect(isOfferedInJourney('list_places', 'PlacesMcp')).toBe(false); + expect(isOfferedInJourney('get_book', undefined)).toBe(false); + }); + + it('ASTSCP-011: keeps what works on the journey: every read, the book writes only for an editor', () => { + expect(keptInJourney('JourneyMcp', 'read', true, false)).toBe(true); + expect(keptInJourney('JourneyBookMcp', 'write', true, true)).toBe(true); + expect(keptInJourney('JourneyBookMcp', 'write', true, false)).toBe(false); + expect(keptInJourney('JourneyMcp', 'write', true, true)).toBe(false); + expect(keptInJourney('JourneyMcp', 'read', false, true)).toBe(false); + expect(keptInJourney(undefined, 'write', true, true)).toBe(false); + }); + + it('ASTSCP-012: a trip conversation still goes without every book tool', () => { + for (const name of ['get_book', 'edit_book_page', 'suggest_book_photos', 'restore_book_page']) { + expect(isOfferedTool(name), name).toBe(false); + } + }); +}); + +describe('the book card', () => { + it('ASTSCP-020: lists the journey, the role, the book page by page and the entries', () => { + const text = renderBookCard(card()); + expect(text).toContain('Journey: Portugal'); + expect(text).toContain('Subtitle: Two weeks by train'); + expect(text).toContain('Your role: editor (you may change the book)'); + expect(text).toContain('Book: "Lisbon in spring", version 7'); + expect(text).toContain('Page: 210 x 210 mm (square-210), bleed 3 mm, safe margin 10 mm'); + expect(text).toContain('0 | sp-cover | cover | | 812 | "Lisbon"'); + expect(text).toContain('1 | sp-alfama | inner | 40 | 813, 814 | '); + expect(text).toContain('Saved layouts: Three in a row (lay-1, inner)'); + expect(text).toContain('Gallery: 120 photos (videos left out), 118 with the time taken, 90 with a GPS position.'); + expect(text).toContain('40 | 2026-04-02 | Alfama | Lisbon | 3'); + expect(text).not.toContain('The user is looking at'); + expect(text).not.toMatch(/[\u2013\u2014]/); + }); + + it('ASTSCP-026: keeps every row on one line whatever the user typed, and says when the gallery is empty', () => { + const book = { ...BOOK, spreads: BOOK.spreads.map((spread) => ({ ...spread, texts: ['Lisbon\nin\tspring'] })) }; + const entries = [{ id: 40, date: '2026-04-02', title: 'Alfama\nat night', place: ' Lisbon\r\n', photos: 3 }]; + const gallery = { photos: 0, withTime: 0, withGps: 0 }; + const text = renderBookCard(card({ book, entries, title: 'Portugal\n2026', gallery })); + expect(text).toContain('Journey: Portugal 2026'); + expect(text).toContain('0 | sp-cover | cover | | 812 | "Lisbon in spring"'); + expect(text).toContain('40 | 2026-04-02 | Alfama at night | Lisbon | 3'); + expect(text).toContain('Gallery: no photos yet.'); + }); + + it('ASTSCP-021: starts with the page on screen and what is selected on it, and only for a page of the book', () => { + const focused = renderBookCard(card({ focus: { spreadId: 'sp-alfama', elementIds: ['p-1', 'p-2'] } })); + expect(focused.split('\n')[0]).toBe( + 'The user is looking at page sp-alfama (index 1, inner); words like "this page" or "here" mean it.', + ); + expect(focused).toContain('Selected on it ("this photo", "these" mean them): p-1, p-2.'); + expect(renderBookCard(card({ focus: { spreadId: 'sp-gone' } }))).not.toContain('The user is looking at'); + }); + + it('ASTSCP-022: says when there is no book and no entry yet, and what a viewer may not do', () => { + const empty = { ...BOOK, exists: false, version: null, spreads: [], layouts: [] }; + const text = renderBookCard(card({ book: empty, entries: [], role: 'viewer', subtitle: null })); + expect(text).toContain('Book: none yet (create_book lays down a blank one).'); + expect(text).toContain('(no entries yet)'); + expect(text).toContain('propose no changes'); + expect(text).not.toContain('Subtitle:'); + }); + + it('ASTSCP-023: counts what it does not list', () => { + const entries = Array.from({ length: 205 }, (_, i) => ({ + id: i + 1, + date: '2026-04-02', + title: null, + place: null, + photos: 0, + })); + expect(renderBookCard(card({ entries }))).toContain('and 5 more'); + }); + + it('ASTSCP-024: comes with the date in the user zone, inside its own tags', () => { + const context = bookTurnContext(card(), 'Europe/Lisbon', NOW); + expect(context.split('\n')[0]).toBe('Today is 2026-07-03 (time zone Europe/Lisbon).'); + expect(context).toContain('\nJourney: Portugal'); + expect(context.endsWith('')).toBe(true); + }); + + it('ASTSCP-025: hands the agent an empty trip card', () => { + const empty = emptyTripCard(7); + expect(empty).toMatchObject({ viewerId: 7, title: '', days: [] }); + expect(empty.places.size).toBe(0); + }); +}); + +describe('the Studio instructions', () => { + it('ASTSCP-030: answer in the user language and teach the book; the trip prompt only points to the Studio', () => { + const prompt = studioPrompt('German'); + expect(prompt).toContain('in German'); + expect(prompt).not.toContain('{language}'); + expect(prompt).toContain('get_book'); + expect(prompt).toContain('describe_book_page'); + expect(prompt).toContain('suggest_book_photos'); + expect(prompt).toContain('preview_book_page'); + expect(prompt).not.toMatch(/[\u2013\u2014]/); + expect(systemPrompt('German')).toContain('You are the trip assistant inside TREK'); + expect(systemPrompt('German')).not.toContain('TREK Studio'); + expect(systemPrompt('German')).toContain('tell the user to open Studio from the journey'); + }); +}); + +describe('the book context', () => { + interface EntryRow { + id: number; + entry_date: string; + title: string; + type: string; + dismissed: boolean; + photos: object[]; + } + const ALFAMA: EntryRow = { + id: 40, + entry_date: '2026-04-02', + title: 'Alfama', + type: 'entry', + dismissed: false, + photos: [{}, {}], + }; + + function journeysFake(role: 'owner' | 'editor' | 'viewer' | 'none', entries: EntryRow[]) { + const journey = { id: 12, user_id: role === 'owner' ? 7 : 99, title: 'Portugal', subtitle: null }; + return { + canAccessJourney: vi.fn(async () => (role === 'none' ? null : journey)), + isOwner: vi.fn(async () => role === 'owner'), + canEdit: vi.fn(async () => role === 'owner' || role === 'editor'), + listEntries: vi.fn(async () => entries.map((entry) => ({ ...entry, location_name: null }))), + }; + } + + function contextWith(role: 'owner' | 'editor' | 'viewer' | 'none', entries: EntryRow[] = [ALFAMA]) { + const journeys = journeysFake(role, entries); + const books = { overview: vi.fn(async () => BOOK) }; + const photos = { + galleryFacts: vi.fn(async () => [ + { taken_at: '2026-04-02 10:00:00', lat: 38.71, lng: -9.13 }, + { taken_at: '2026-04-02 11:00:00', lat: null, lng: null }, + { taken_at: null, lat: 38.7, lng: null }, + ]), + }; + const context = new AssistantBookContext( + journeys as unknown as JourneyDomainService, + books as unknown as JourneyBookEditService, + photos as unknown as PhotoSignalsService, + ); + return { journeys, books, photos, context }; + } + + it('ASTSCP-040: reads the card with the user rights: the book, the journey, the role, the gallery, the entries', async () => { + const { books, journeys, photos, context } = contextWith('owner'); + const read = await context.cardOf(7, 12, { spreadId: 'sp-cover' }); + expect(books.overview).toHaveBeenCalledWith(12, 7); + expect(photos.galleryFacts).toHaveBeenCalledWith(12); + expect(read).toMatchObject({ journeyId: 12, title: 'Portugal', subtitle: null, role: 'owner', book: BOOK }); + expect(read.gallery).toEqual({ photos: 3, withTime: 2, withGps: 1 }); + expect(read.entries).toEqual([{ id: 40, date: '2026-04-02', title: 'Alfama', place: null, photos: 2 }]); + expect(read.focus).toEqual({ spreadId: 'sp-cover' }); + // The owner is read off the journey row, not asked for again. + expect(journeys.isOwner).not.toHaveBeenCalled(); + expect(journeys.canEdit).not.toHaveBeenCalled(); + expect((await contextWith('editor').context.cardOf(7, 12, null)).role).toBe('editor'); + expect((await contextWith('viewer').context.cardOf(7, 12, null)).role).toBe('viewer'); + }); + + it('ASTSCP-042: lists no entry waved away, and the suggestions only while nothing is written', async () => { + const suggestion = { ...ALFAMA, id: 41, type: 'skeleton' }; + const dismissed = { ...ALFAMA, id: 42, dismissed: true }; + const written = await contextWith('editor', [ALFAMA, suggestion, dismissed]).context.cardOf(7, 12, null); + expect(written.entries.map((entry) => entry.id)).toEqual([40]); + const onlyPlanned = [suggestion, { ...dismissed, type: 'skeleton' }]; + const planned = await contextWith('editor', onlyPlanned).context.cardOf(7, 12, null); + expect(planned.entries.map((entry) => entry.id)).toEqual([41]); + }); + + it('ASTSCP-041: tells who may open the journey and who may change its book', async () => { + expect(await contextWith('viewer').context.canOpen(7, 12)).toBe(true); + expect(await contextWith('none').context.canOpen(7, 12)).toBe(false); + expect(await contextWith('viewer').context.canEdit(7, 12)).toBe(false); + expect(await contextWith('editor').context.canEdit(7, 12)).toBe(true); + }); +}); + +describe('a scope opens its session and writes its turn', () => { + const session = { + read: vi.fn(async (name: string) => + name === 'get_trip_summary' + ? { ok: true, value: { trip: { title: 'Kyoto' }, days: [] } } + : { ok: true, value: { places: [{ id: 3, name: 'Kinkaku-ji' }] } }, + ), + close: vi.fn(async () => undefined), + }; + + function scopesWith(canWrite: boolean) { + const tools = { open: vi.fn(async () => session), openJourney: vi.fn(async () => session) }; + const books = { + canEdit: vi.fn(async () => canWrite), + cardOf: vi.fn(async () => card({ role: canWrite ? 'editor' : 'viewer' })), + }; + const settings = { getUserSettings: vi.fn(async () => ({ temperature_unit: 'celsius' })) }; + const studioGate = { refusalOf: vi.fn(async () => 'faults'), reader: session }; + const gate = { forTurn: vi.fn(() => studioGate) }; + const scopes = new AssistantScopes( + tools as unknown as AssistantToolsService, + books as unknown as AssistantBookContext, + gate as unknown as AssistantBookGate, + settings as unknown as SettingsService, + t.orm, + ); + return { tools, books, settings, scopes, gate, studioGate }; + } + + const turn = { userId: 7, locale: 'en', timeZone: 'UTC', focus: null, mentions: [], now: NOW }; + + it('ASTSCP-050: a trip turn opens the trip session and reads the trip card, the units and the trip prompt', async () => { + const { tools, scopes } = scopesWith(true); + const opened = await scopes.open(7, tripScope(5)); + expect(tools.open).toHaveBeenCalledWith(7, 5, undefined); + const read = await scopes.turnOf(opened, tripScope(5), turn); + expect(read.card).toMatchObject({ tripId: 5, title: 'Kyoto' }); + expect(read.system).toBe(systemPrompt('English')); + expect(read.context).toContain('temperatures in °C'); + expect(read.context).toContain(''); + // A trip's held calls pass as they are, and its cards read the session itself. + expect(read.gate.reader).toBe(opened); + expect(await read.gate.refusalOf('edit_book_page', { spreadId: 'sp-1', ops: [] })).toBeNull(); + }); + + it('ASTSCP-051: a journey turn opens the Studio session with the user right to write, and reads the book card', async () => { + session.read.mockClear(); + const editor = scopesWith(true); + const opened = await editor.scopes.open(7, { kind: 'journey', journeyId: 12 }); + expect(editor.tools.openJourney).toHaveBeenCalledWith(7, 12, true, undefined); + const targets = new Set(['restore_book_page']); + const read = await editor.scopes.turnOf(opened, { kind: 'journey', journeyId: 12 }, turn); + expect(editor.books.cardOf).toHaveBeenCalledWith(7, 12, null); + expect(read.system).toBe(studioPrompt('English')); + expect(read.context).toContain(''); + expect(read.card.tripId).toBe(0); + expect(session.read).not.toHaveBeenCalled(); + // The Studio's book writes pass the book check of this turn. + expect(editor.gate.forTurn).toHaveBeenCalledWith(7, 12, opened); + expect(read.gate).toBe(editor.studioGate); + + const viewer = scopesWith(false); + await viewer.scopes.open(7, { kind: 'journey', journeyId: 12 }, targets); + expect(viewer.tools.openJourney).toHaveBeenCalledWith(7, 12, false, targets); + }); + + 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 }); + expect(fromSession).toMatchObject({ tripId: 5, viewerId: 7, focus: { dayId: 2 } }); + expect(fromSession.places.get(3)?.name).toBe('Kinkaku-ji'); + const tools = { open: vi.fn(async () => session) }; + session.close.mockClear(); + await readTripCard(tools as unknown as AssistantToolsService, 7, 5); + expect(tools.open).toHaveBeenCalledWith(7, 5, new Set(['get_trip_summary', 'list_places'])); + expect(session.close).toHaveBeenCalledTimes(1); + }); +}); diff --git a/server/tests/unit/nest/assistant/assistant-tools.service.test.ts b/server/tests/unit/nest/assistant/assistant-tools.service.test.ts index 57a4d9da7..3766737f9 100644 --- a/server/tests/unit/nest/assistant/assistant-tools.service.test.ts +++ b/server/tests/unit/nest/assistant/assistant-tools.service.test.ts @@ -13,8 +13,10 @@ import { ASSISTANT_DENIED_TOOLS, ASSISTANT_TOOL_GROUPS, checkDenylist, + checkStudioTools, groupOf, isOfferedTool, + isStudioController, } from '../../../../src/nest/assistant/assistant-tool-offer'; import { ASSISTANT_SCOPES, ASSISTANT_SERVER_TOOLS } from '../../../../src/nest/assistant/assistant-tools.constants'; import { AssistantToolsService, checkToolCatalog } from '../../../../src/nest/assistant/assistant-tools.service'; @@ -90,6 +92,7 @@ describe('the assistant tool catalog', () => { const entry = (name: string) => ({ kind: 'tool' as const, name, className: 'X', methodName: 'y' }); 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'); expect(checkDenylist(['create_party_invite'])).toEqual([ '"create_party_invite" shares, invites or publishes; deny it or list it as safe', ]); @@ -214,6 +217,19 @@ describe('the assistant tool catalog', () => { expect(ASSISTANT_DENIED_TOOLS.suggest_book_photos).toMatch(/Studio chat only/); }); + it('ASTTOOL-022: a book tool not listed as one of the Studio is named, whatever its name says', () => { + const entry = (name: string, className: string) => ({ kind: 'tool' as const, name, className, methodName: 'y' }); + expect(checkToolCatalog([entry('arrange_book', 'JourneyBookPhotosMcp')])).toContain( + 'book tool "arrange_book" is not listed as a Studio tool', + ); + const listedOnes = [entry('get_book', 'JourneyBookMcp'), entry('restore_book_page', 'JourneyBookMcp')]; + expect(checkStudioTools([...listedOnes, entry('list_places', 'PlacesMcp')])).toEqual([]); + expect(checkStudioTools([{ kind: 'resource', name: 'book_notes', className: 'JourneyBookMcp' }])).toEqual([]); + expect(isStudioController('JourneyBookPhotosMcp')).toBe(true); + expect(isStudioController('JourneyMcp')).toBe(false); + expect(isStudioController(undefined)).toBe(false); + }); + it('ASTTOOL-017: the hike tools come with the tours, the proposal runs at once and the writes are cards of a tour', () => { const hikeTools = ['propose_hike', 'create_hike', 'update_tour', 'import_tour_gpx']; const entries = hikeTools.map((name) => registry.list().find((e) => e.kind === 'tool' && e.name === name)); @@ -283,6 +299,24 @@ describe('an assistant tool session', () => { } }); + it('ASTTOOL-023: a trip session that loads the journey group gets its tools but none of the book controllers', async () => { + const { userId, tripId } = await ownerWithTrips(); + const session = await tools.open(userId, tripId); + try { + expect((await session.call('use_addon_tools', { groups: ['journey'] })).ok).toBe(true); + const names = session.specs().map((spec) => spec.name); + expect(names).toContain('list_journey_entries'); + const book = registry + .list() + .filter((entry) => entry.kind === 'tool' && isStudioController(entry.className)) + .map((entry) => entry.name); + expect(book.length).toBeGreaterThan(5); + expect(names.filter((name) => book.includes(name))).toEqual([]); + } finally { + await session.close(); + } + }); + it('ASTTOOL-011: a call runs on the conversation trip, and another trip id is refused', async () => { const { userId, tripId, otherId } = await ownerWithTrips(); const session = await tools.open(userId, tripId); diff --git a/server/tests/unit/nest/assistant/assistant.controller.test.ts b/server/tests/unit/nest/assistant/assistant.controller.test.ts index 2693ab929..73c1cf32d 100644 --- a/server/tests/unit/nest/assistant/assistant.controller.test.ts +++ b/server/tests/unit/nest/assistant/assistant.controller.test.ts @@ -1,7 +1,8 @@ /** * The assistant controller: its guards (addon before auth, then the trip), * the managed marker, the routes with their statuses and contracts, and that - * every handler hands the caller's own id and the route's trip to the service. + * every handler hands the caller's own id and the route's trip (as the + * conversation's scope) to the service. */ import 'reflect-metadata'; @@ -26,14 +27,16 @@ import { describe, expect, it, vi } from 'vitest'; const user = { id: 7, role: 'user' } as User; const CHAT = { locale: 'en', timeZone: 'UTC', threadId: null, text: 'Hi' }; +/** The scope of trip 5, as the controller hands it on. */ +const TRIP = { kind: 'trip', tripId: 5 }; 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, _t: number, _b: unknown, _c: TurnChannel) => undefined), - decide: vi.fn(async (_u: number, _t: number, _th: number, _b: unknown, _c: TurnChannel) => 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), }; @@ -124,13 +127,13 @@ describe('AssistantController', () => { it('ASTCTL-003: hands the caller and the trip to the service, and answers the contract bodies', async () => { const { service, controller } = make(); await controller.threads(user, '5'); - expect(service.listThreads).toHaveBeenCalledWith(7, 5); + expect(service.listThreads).toHaveBeenCalledWith(7, TRIP); await controller.thread(user, '5', '9'); - expect(service.getThread).toHaveBeenCalledWith(7, 5, 9); + expect(service.getThread).toHaveBeenCalledWith(7, TRIP, 9); expect(await controller.deleteThread(user, '5', '9')).toEqual({ success: true }); - expect(service.deleteThread).toHaveBeenCalledWith(7, 5, 9); + expect(service.deleteThread).toHaveBeenCalledWith(7, TRIP, 9); expect(await controller.undo(user, '5', 'tc-1', {})).toEqual({ undone: true }); - expect(service.undo).toHaveBeenCalledWith(7, 5, 'tc-1'); + expect(service.undo).toHaveBeenCalledWith(7, TRIP, 'tc-1'); expect(await controller.stop(user, {})).toEqual({ success: true }); expect(service.stop).toHaveBeenCalledWith(7); }); @@ -175,7 +178,7 @@ describe('AssistantController', () => { const res = new FakeResponse(); await controller.chat(user, '5', CHAT, res as unknown as Response); const channel = service.chat.mock.calls[0][3]; - expect(service.chat.mock.calls[0].slice(0, 3)).toEqual([7, 5, CHAT]); + expect(service.chat.mock.calls[0].slice(0, 3)).toEqual([7, TRIP, CHAT]); expect(res.flushHeaders).not.toHaveBeenCalled(); const stream = channel.open(); expect(res.headers['Content-Type']).toBe('text/event-stream; charset=utf-8'); @@ -194,7 +197,7 @@ describe('AssistantController', () => { { locale: 'en', timeZone: 'UTC', decisions: [] }, gone as unknown as Response, ); - expect(service.decide.mock.calls[0].slice(0, 3)).toEqual([7, 5, 9]); + expect(service.decide.mock.calls[0].slice(0, 3)).toEqual([7, TRIP, 9]); const goneSignal = service.decide.mock.calls[0][4].signal; gone.emit('close'); expect(goneSignal.aborted).toBe(true); diff --git a/server/tests/unit/nest/assistant/cards/journey/journey-cards.test.ts b/server/tests/unit/nest/assistant/cards/journey/journey-cards.test.ts index 134d3e536..50c2fcc0d 100644 --- a/server/tests/unit/nest/assistant/cards/journey/journey-cards.test.ts +++ b/server/tests/unit/nest/assistant/cards/journey/journey-cards.test.ts @@ -155,6 +155,14 @@ describe('the answer cards', () => { expect(whole.entries.map((e) => e.entryId)).toEqual([12, 13]); expect(whole.journalTitle).toBe('Berlin 2026'); }); + + it('ASTCARD-JRN-016: a Studio read, whose journey id the server pins and hides, takes the journey from the answer', () => { + const value = { journey: { id: 3, title: 'Berlin 2026' }, entries: [entry()] }; + const card = cardOf(answerCardOf('list_journey_entries', answerInput({}, value))); + expect(card.journeyId).toBe(3); + expect(card.journalTitle).toBe('Berlin 2026'); + expect(card.entries.map((e) => e.entryId)).toEqual([12]); + }); }); describe('an entry as a card shows it', () => { @@ -356,12 +364,14 @@ describe('the applied change', () => { expect(check?.unchanged(created, snapshot(null))).toBe(false); }); - it('ASTCARD-JRN-015: the journal brings its verbs, its undo and one prompt line to the registry', () => { + it('ASTCARD-JRN-015: the journal brings its verbs, its undo and two prompt lines to the registry', () => { expect(ASSISTANT_WRITE_TOOLS.create_journey_entry).toEqual({ verbKey: 'addJournalEntry', entity: 'journey_entry' }); expect(ASSISTANT_WRITE_TOOLS.update_journey_entry?.verbKey).toBe('updateJournalEntry'); expect(ASSISTANT_WRITE_TOOLS.delete_journey_entry?.verbKey).toBe('removeJournalEntry'); expect(ASSISTANT_UNDO_MAP.update_journey_entry).toBeUndefined(); expect(CARD_PROMPT_LINES).toEqual(expect.arrayContaining([...(JOURNEY_CARDS.prompt ?? [])])); - expect(JOURNEY_CARDS.prompt).toHaveLength(1); + expect(JOURNEY_CARDS.prompt).toHaveLength(2); + // A trip chat sends a book request to the Studio instead of trying it. + expect(JOURNEY_CARDS.prompt?.[1]).toContain('open Studio from the journey'); }); }); diff --git a/server/tests/unit/nest/assistant/journey-assistant.controller.test.ts b/server/tests/unit/nest/assistant/journey-assistant.controller.test.ts new file mode 100644 index 000000000..c9d142506 --- /dev/null +++ b/server/tests/unit/nest/assistant/journey-assistant.controller.test.ts @@ -0,0 +1,165 @@ +/** + * The Studio assistant's controller and its guard: the AI addon before auth, + * then the journey addon and the journey (both a 404 worded like the journey + * routes'), the managed marker, the routes with their statuses, and that every + * handler hands the caller's own id and the journey (as the conversation's + * scope) to the same service the trip's controller uses. + */ +import 'reflect-metadata'; + +import { AddonGuard } from '../../../../src/nest/addons/addon.guard'; +import type { AddonsService } from '../../../../src/nest/addons/addons.service'; +import { REQUIRE_ADDON } from '../../../../src/nest/addons/require-addon.decorator'; +import type { AssistantBookContext } from '../../../../src/nest/assistant/assistant-book-context'; +import type { AssistantService, TurnChannel } from '../../../../src/nest/assistant/assistant.service'; +import { JourneyAssistantController } from '../../../../src/nest/assistant/journey-assistant.controller'; +import { JourneyAssistantGuard } from '../../../../src/nest/assistant/journey-assistant.guard'; +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 type { User } from '../../../../src/types'; +import { HttpException, RequestMethod, type ExecutionContext } 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 JOURNEY = { kind: 'journey', journeyId: 12 }; + +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 JourneyAssistantController(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 = (JourneyAssistantController.prototype as unknown as Record)[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, + }; +} + +function guardWith(addonOn: boolean, canOpen: boolean) { + const addons = { isAddonEnabled: vi.fn(async () => addonOn) }; + const books = { canOpen: vi.fn(async () => canOpen) }; + const guard = new JourneyAssistantGuard(addons as unknown as AddonsService, books as unknown as AssistantBookContext); + return { addons, books, guard }; +} + +function contextOf(journeyId: string, who: User | null = user): ExecutionContext { + const request = { user: who ?? undefined, params: { journeyId } }; + return { switchToHttp: () => ({ getRequest: () => request }) } as unknown as ExecutionContext; +} + +async function refusal(run: Promise): Promise<{ status: number; body: unknown }> { + try { + await run; + } catch (err) { + if (err instanceof HttpException) return { status: err.getStatus(), body: err.getResponse() }; + throw err; + } + throw new Error('expected a refusal'); +} + +describe('JourneyAssistantController', () => { + it('ASTJCTL-001: sits behind the AI addon, then auth, then the journey, and is withheld on a managed install', () => { + expect(Reflect.getMetadata(PATH_METADATA, JourneyAssistantController)).toBe('api/journeys/:journeyId/assistant'); + expect(Reflect.getMetadata(GUARDS_METADATA, JourneyAssistantController)).toEqual([ + AddonGuard, + JwtAuthGuard, + JourneyAssistantGuard, + ]); + expect(Reflect.getMetadata(REQUIRE_ADDON, JourneyAssistantController)).toMatchObject({ addonId: 'ai_assistant' }); + expect(Reflect.getMetadata(MANAGED_FORBIDDEN, JourneyAssistantController)?.reason).toBeTruthy(); + }); + + it('ASTJCTL-002: declares the routes of the trip assistant that a journey has, with their statuses', () => { + 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 = JourneyAssistantController.prototype as unknown as Record; + const tripOnly = ['addFoundPlace', 'takeProposal', 'share', 'attach']; + for (const name of tripOnly) expect(handlers[name], name).toBeUndefined(); + }); + + it('ASTJCTL-003: hands the caller and the journey to the service, and answers the contract bodies', async () => { + const { service, controller } = make(); + await controller.threads(user, '12'); + expect(service.listThreads).toHaveBeenCalledWith(7, JOURNEY); + await controller.thread(user, '12', '9'); + expect(service.getThread).toHaveBeenCalledWith(7, JOURNEY, 9); + expect(await controller.deleteThread(user, '12', '9')).toEqual({ success: true }); + expect(service.deleteThread).toHaveBeenCalledWith(7, JOURNEY, 9); + expect(await controller.undo(user, '12', 'tc-1', {})).toEqual({ undone: true }); + expect(service.undo).toHaveBeenCalledWith(7, JOURNEY, 'tc-1'); + expect(await controller.stop(user, {})).toEqual({ success: true }); + expect(service.stop).toHaveBeenCalledWith(7); + expect(() => controller.thread(user, '12', 'abc')).toThrow(DomainError); + }); + + it('ASTJCTL-004: a turn and a decision go to the service with the journey and the stream of the response', async () => { + const { service, controller } = make(); + const chat = { locale: 'en', timeZone: 'UTC', threadId: null, text: 'Hi' }; + await controller.chat(user, '12', chat, new FakeResponse() as unknown as Response); + expect(service.chat.mock.calls[0].slice(0, 3)).toEqual([7, JOURNEY, chat]); + const decisions = { locale: 'en', timeZone: 'UTC', decisions: [] }; + const gone = new FakeResponse(); + await controller.decide(user, '12', '9', decisions, gone as unknown as Response); + expect(service.decide.mock.calls[0].slice(0, 3)).toEqual([7, JOURNEY, 9]); + gone.emit('close'); + expect(service.decide.mock.calls[0][4].signal.aborted).toBe(true); + }); +}); + +describe('JourneyAssistantGuard', () => { + it('ASTJCTL-010: lets a member of the journey through while the journey addon is on', async () => { + const { books, guard } = guardWith(true, true); + expect(await guard.canActivate(contextOf('12'))).toBe(true); + expect(books.canOpen).toHaveBeenCalledWith(7, 12); + }); + + it('ASTJCTL-011: answers 404 with the journey routes wording when the addon is off or the journey is not open', async () => { + const off = guardWith(false, true); + expect(await refusal(off.guard.canActivate(contextOf('12')))).toEqual({ + status: 404, + body: { error: 'Journey addon is not enabled' }, + }); + expect(off.books.canOpen).not.toHaveBeenCalled(); + const closed = guardWith(true, false); + expect(await refusal(closed.guard.canActivate(contextOf('12')))).toEqual({ + status: 404, + body: { error: 'Journey not found' }, + }); + }); + + it('ASTJCTL-012: an id that is not one never reaches the journey, and a request without a user is refused', async () => { + const { books, guard } = guardWith(true, true); + const bad = ['abc', '0', '-2', '1.5']; + const refused = await Promise.all(bad.map((id) => refusal(guard.canActivate(contextOf(id))))); + expect(refused.map((answer) => answer.status)).toEqual([404, 404, 404, 404]); + expect(books.canOpen).not.toHaveBeenCalled(); + expect((await refusal(guard.canActivate(contextOf('12', null)))).status).toBe(401); + }); +}); diff --git a/shared/src/assistant/assistant-scope.schema.spec.ts b/shared/src/assistant/assistant-scope.schema.spec.ts new file mode 100644 index 000000000..2788ec616 --- /dev/null +++ b/shared/src/assistant/assistant-scope.schema.spec.ts @@ -0,0 +1,40 @@ +import { assistantScopeKey, assistantScopeSchema } from './assistant-scope.schema'; +import { assistantFocusSchema } from './assistant.schema'; + +import { describe, expect, it } from 'vitest'; + +describe('assistantScopeSchema', () => { + it('ASTSCOPE-001: is a trip or a journey, each by its own positive id', () => { + expect(assistantScopeSchema.parse({ kind: 'trip', tripId: 5 })).toEqual({ kind: 'trip', tripId: 5 }); + expect(assistantScopeSchema.parse({ kind: 'journey', journeyId: 12 })).toEqual({ kind: 'journey', journeyId: 12 }); + expect(assistantScopeSchema.safeParse({ kind: 'trip', tripId: 0 }).success).toBe(false); + expect(assistantScopeSchema.safeParse({ kind: 'journey', tripId: 5 }).success).toBe(false); + }); + + it('ASTSCOPE-002: is never both and never anything else', () => { + expect(assistantScopeSchema.safeParse({ kind: 'trip', tripId: 5, journeyId: 12 }).success).toBe(false); + expect(assistantScopeSchema.safeParse({ kind: 'collection', collectionId: 3 }).success).toBe(false); + expect(assistantScopeSchema.safeParse({}).success).toBe(false); + }); + + it('ASTSCOPE-003: keys a trip and a journey with the same id apart', () => { + expect(assistantScopeKey({ kind: 'trip', tripId: 7 })).toBe('trip:7'); + expect(assistantScopeKey({ kind: 'journey', journeyId: 7 })).toBe('journey:7'); + }); +}); + +describe('assistantFocusSchema in the Studio', () => { + it('ASTSCOPE-004: carries the page on screen and up to 30 selected elements, by their document ids', () => { + const focus = { spreadId: 'sp-ab12', elementIds: ['p-1', 'p-2'] }; + expect(assistantFocusSchema.parse(focus)).toEqual(focus); + expect(assistantFocusSchema.safeParse({ spreadId: 'sp ab' }).success).toBe(false); + expect(assistantFocusSchema.safeParse({ spreadId: 'x'.repeat(41) }).success).toBe(false); + const many = Array.from({ length: 31 }, (_, i) => `p-${i}`); + expect(assistantFocusSchema.safeParse({ elementIds: many }).success).toBe(false); + }); + + it('ASTSCOPE-005: leaves the planner focus as it was', () => { + expect(assistantFocusSchema.parse({ dayId: 4, placeIds: [1] })).toEqual({ dayId: 4, placeIds: [1] }); + expect(assistantFocusSchema.safeParse({ dayId: 4, page: 2 }).success).toBe(false); + }); +}); diff --git a/shared/src/assistant/assistant-scope.schema.ts b/shared/src/assistant/assistant-scope.schema.ts new file mode 100644 index 000000000..e37bdf218 --- /dev/null +++ b/shared/src/assistant/assistant-scope.schema.ts @@ -0,0 +1,21 @@ +import { idSchema } from '../common/primitives.schema'; + +import { z } from 'zod'; + +/** + * What an assistant conversation is about: a trip (the planner's chat) or a + * journey (the chat in TREK Studio, which works on the journey's book). A + * thread belongs to exactly one of them, and the tools a turn offers, the + * context it reads and the routes it is reached under follow from it: + * `/api/trips/:tripId/assistant` and `/api/journeys/:journeyId/assistant`. + */ +export const assistantScopeSchema = z.discriminatedUnion('kind', [ + z.object({ kind: z.literal('trip'), tripId: idSchema }).strict(), + z.object({ kind: z.literal('journey'), journeyId: idSchema }).strict(), +]); +export type AssistantScope = z.infer; + +/** The key a scope's conversations are kept under on a client: `trip:5`, `journey:12`. */ +export function assistantScopeKey(scope: AssistantScope): string { + return scope.kind === 'trip' ? `trip:${scope.tripId}` : `journey:${scope.journeyId}`; +}