The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.
TypeScript budget-trackercollaborativedockeritinerarymcp-serveroffline-firstopen-sourceopenstreetmappacking-listpwareal-timeself-hostedselfhostedtraveltravel-apptravel-journaltravel-plannertripitwanderlog
fix(assistant): book changes undo per page, and the Studio prompt fits the user's rights
Maurice72c61f242e3e
diff --git a/client/src/components/Assistant/cards/tour/tourTakeModel.test.ts b/client/src/components/Assistant/cards/tour/tourTakeModel.test.tsindex 3b441f368..719cfb6ee 100644--- a/client/src/components/Assistant/cards/tour/tourTakeModel.test.ts+++ b/client/src/components/Assistant/cards/tour/tourTakeModel.test.ts@@ -1,10 +1,11 @@/**- * FE-AI-TOUR-047+ * FE-AI-TOUR-047, FE-AI-TOUR-048** Whether a proposal was already taken, read from the thread: a later answer- * holding "Plan this" for the same way, waiting or applied, takes it; one- * discarded, cancelled or expired, another way, or a thread that no longer- * holds the proposal does not.+ * holding "Plan this" for it, waiting or applied, takes it; one discarded,+ * cancelled or expired, another way, or a thread that no longer holds the+ * proposal does not. A take names the proposal it came from, which decides+ * before the way; one held before it named any is matched by its way.*/import type { AssistantMessage, AssistantMessagePart, AssistantToolApproval, TourRouteCard } from '@trek/shared';import { describe, expect, it } from 'vitest';@@ -22,8 +23,13 @@ const message = (id: string, parts: AssistantMessagePart[]): AssistantMessage =>const proposal = message('m1', [{ type: 'data-trek-card', data: { toolCallId: 'call_1', card: HIKE } }]);-/** The answer holding "Plan this" for `card`, decided as `approval` says. */-function take(card: TourRouteCard, approval: Omit<AssistantToolApproval, 'id'> = {}, toolName = 'take_proposal') {+/** The answer holding "Plan this" for `card`, decided as `approval` says, naming `takenFrom` when given. */+function take(+ card: TourRouteCard,+ approval: Omit<AssistantToolApproval, 'id'> = {},+ toolName = 'take_proposal',+ takenFrom?: string+) {return message('m2', [{ type: 'tool-call', toolCallId: 't1', toolName, args: {}, approval: { id: 't1', ...approval } },{@@ -37,6 +43,7 @@ function take(card: TourRouteCard, approval: Omit<AssistantToolApproval, 'id'> =placeIds: [],undoable: true,card: { ...card, source: 'pending' },+ ...(takenFrom ? { takenFrom } : {}),},},]);@@ -56,4 +63,13 @@ describe('takeInThread', () => {expect(takeInThread([take(HIKE), proposal], 'call_1', HIKE)).toBeNull();expect(takeInThread([take(HIKE)], 'call_1', HIKE)).toBeNull();});++ it('FE-AI-TOUR-048: a take that names its proposal is matched by it, not by its way', () => {+ const other = { ...GENTLE, line: [[47.9, 12.8, 600], ...GENTLE.line.slice(1)] } satisfies TourRouteCard;+ expect(takeInThread([proposal, take(other, {}, 'take_proposal', 'call_1')], 'call_1', HIKE)).toBe('waiting');+ // The same way taken from another proposal leaves this one free.+ expect(+ takeInThread([proposal, take(HIKE, { approved: true }, 'take_proposal', 'call_2')], 'call_1', HIKE)+ ).toBeNull();+ });});diff --git a/client/src/components/Assistant/cards/tour/tourTakeModel.ts b/client/src/components/Assistant/cards/tour/tourTakeModel.tsindex b4dedc6b8..eea0ad93d 100644--- a/client/src/components/Assistant/cards/tour/tourTakeModel.ts+++ b/client/src/components/Assistant/cards/tour/tourTakeModel.ts@@ -1,11 +1,11 @@-import type { AssistantMessage, TourRouteCard } from '@trek/shared';+import type { AssistantChangePreview, AssistantMessage, TourRouteCard } from '@trek/shared';/*** Whether a proposal was already taken ("Plan this"), read from the thread* rather than from the card, so a card drawn again (the chat reopened, the* thread loaded anew, a long answer scrolled away and back) does not offer- * the same tour twice. The change the server holds names the way it creates,- * not the card it came from, so it is matched by its way.+ * the same tour twice. The change the server holds names the proposal it was+ * taken from (`takenFrom`); one held before it did is matched by its way.*//** The tool a change held by "Plan this" runs under, as the server names it. */@@ -21,6 +21,12 @@ function sameWay(a: TourRouteCard, b: TourRouteCard): boolean {return aStart === bStart && aEnd === bEnd;}+/** Whether a held take came from the proposal: by the proposal it names, or, held before it named one, by its way. */+function takenFromProposal(change: AssistantChangePreview, toolCallId: string, card: TourRouteCard): boolean {+ if (change.takenFrom !== undefined) return change.takenFrom === toolCallId;+ return change.card?.kind === 'tourRoute' && sameWay(change.card, card);+}+/** The index of the answer that drew the proposal's card; -1 when the thread no longer holds it. */function proposalIndex(messages: readonly AssistantMessage[], toolCallId: string): number {return messages.findIndex((message) =>@@ -32,7 +38,7 @@ function proposalIndex(messages: readonly AssistantMessage[], toolCallId: stringtype ThreadTake = 'waiting' | 'applied' | null;/**- * The take a later answer holds for the same way, still waiting or applied.+ * The take a later answer holds for the proposal, still waiting or applied.* One discarded, cancelled or expired leaves the proposal free to be taken* again.*/@@ -50,9 +56,9 @@ export function takeInThread(if (part.approval?.approved !== false) open.set(part.toolCallId, part.approval?.approved ? 'applied' : 'waiting');}for (const part of message.parts) {- if (part.type !== 'data-trek-change' || part.data.card?.kind !== 'tourRoute') continue;+ if (part.type !== 'data-trek-change') continue;const take = open.get(part.data.toolCallId);- if (take && sameWay(part.data.card, card)) return take;+ if (take && takenFromProposal(part.data, toolCallId, card)) return take;}}return null;diff --git a/server/src/nest/assistant/assistant-book-context.ts b/server/src/nest/assistant/assistant-book-context.tsindex 7a74f3b39..ac142888f 100644--- a/server/src/nest/assistant/assistant-book-context.ts+++ b/server/src/nest/assistant/assistant-book-context.ts@@ -1,3 +1,4 @@+import { JourneyAiPhotosService } from '../journey/journey-ai-photos.service';import { JourneyBookEditService } from '../journey/journey-book-edit.service';import { JourneyDomainService } from '../journey/journey-domain.service';import { PhotoSignalsService } from '../photos/photo-signals.service';@@ -7,8 +8,9 @@ import type { AssistantFocus, BookOverview, BookSpreadSummary } from '@trek/shar/*** 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+ * the user may do on it, its book page by page, its gallery in numbers with+ * how many of its photos a page image may show (journey-studio.md 4.1), 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.*/@@ -29,6 +31,8 @@ interface BookCardGallery {photos: number;withTime: number;withGps: number;+ /** The photos the user contributed: the only ones a page image draws, every other one an empty frame there. */+ own: number;}export interface BookCard {@@ -115,11 +119,26 @@ function bookLines(book: BookOverview, role: BookRole): string[] {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 {+/**+ * Which of the photos a page image may show: only the user's own, so a photo+ * of another contributor is an empty frame there. Said as the rule, since a+ * turn of a model that reads no images gets none.+ */+function shownLine(photos: number, own: number): string {+ if (own >= photos) return 'All of them are yours, so a page image may show every one.';+ if (own === 0) return 'None of them are yours, so a page image shows each of them as an empty frame.';+ const others = 'photos of other contributors are empty frames there on purpose';+ return `${own} of them are yours; a page image shows only those, and ${others}.`;+}++/**+ * The gallery in one line: how many photos a pick chooses from, how many it+ * can place by time or on the map, and how many a page image may show.+ */+function galleryLine({ photos, withTime, withGps, own }: 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}.`;+ return `Gallery: ${photos} photos (videos left out), ${known}. ${shownLine(photos, own)}`;}/**@@ -161,17 +180,23 @@ function listedEntries<T extends { dismissed: boolean; type?: string | null }>(e/** A gallery photo as far as the card counts it. */interface GalleryFact {+ photo_id: number;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 {+/**+ * A gallery's photos, how many of them carry the time taken and a position,+ * and how many are the user's own (`own`): counted among these photos, so a+ * video of theirs is not.+ */+function galleryOf(photos: readonly GalleryFact[], own: ReadonlySet<number>): BookCardGallery {return {photos: photos.length,withTime: photos.filter((photo) => !!photo.taken_at).length,withGps: photos.filter((photo) => photo.lat !== null && photo.lng !== null).length,+ own: photos.filter((photo) => own.has(photo.photo_id)).length,};}@@ -185,6 +210,8 @@ export class AssistantBookContext {private readonly journeys: JourneyDomainService,private readonly books: JourneyBookEditService,private readonly photos: PhotoSignalsService,+ // Which gallery photos are the user's own, the ones a page image may draw.+ private readonly aiPhotos: JourneyAiPhotosService,) {}/** Whether the user may open the journey: its owner and every contributor. */@@ -201,7 +228,8 @@ export class AssistantBookContext {* 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.+ * suggest_book_photos reads it, its photos of the user's own as a page image+ * draws them. The journey row, read once, names its owner.*/async cardOf(userId: number, journeyId: number, focus: AssistantFocus | null): Promise<BookCard> {const book = await this.books.overview(journeyId, userId);@@ -209,13 +237,14 @@ export class AssistantBookContext {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) : [];+ const own = journey ? await this.aiPhotos.ownPhotoIds(journeyId, userId) : new Set<number>();return {journeyId,title: journey?.title ?? '',subtitle: journey?.subtitle ?? null,role,book,- gallery: galleryOf(gallery),+ gallery: galleryOf(gallery, own),entries: listedEntries(entries).map((entry) => ({id: entry.id,date: entry.entry_date,diff --git a/server/src/nest/assistant/assistant-book-preview.ts b/server/src/nest/assistant/assistant-book-preview.tsindex 3ab13c375..8c62b0c70 100644--- a/server/src/nest/assistant/assistant-book-preview.ts+++ b/server/src/nest/assistant/assistant-book-preview.ts@@ -21,16 +21,26 @@ import { ASSISTANT_PAGE_IMAGE, previewBookPageRequestSchema } from '@trek/sharedconst EDIT_TOOL = 'edit_book_page';-const DESCRIPTION =- 'Look at one page of the book before you change it or after: its elements, its findings (overlaps, words past ' +- 'their frame, empty frames, low resolution, content in the fold) and, when your model reads images, the page as ' +- 'the Studio draws it, with photos of other contributors left as empty frames. With ops (the same ops ' +- 'edit_book_page takes) you see the page as that edit would leave it, without saving anything. Preview a page ' +- 'once before you propose an edit of it, fix what the findings or the image show, then propose the edit. ' +- 'With designId (from design_book) you see the page of that design draft instead of the book. ' ++/** What a look answers, whoever looks. */+const SEES =+ 'its elements, its findings (overlaps, words past their frame, empty frames, low resolution, content in the ' ++ 'fold) and, when your model reads images, the page as the Studio draws it, with photos of other contributors ' ++ 'left as empty frames.';++const CAPS =`At most ${ASSISTANT_PAGE_IMAGE.previewsPerStep} previews per step and ${ASSISTANT_PAGE_IMAGE.previewsPerTurn} ` +'per turn.';+/** For a session that may change the book: a proposed edit and a design draft can be looked at too. */+const EDITOR_DESCRIPTION =+ `Look at one page of the book before you change it or after: ${SEES} With ops (the same ops edit_book_page ` ++ 'takes) you see the page as that edit would leave it, without saving anything. Preview a page once before you ' ++ 'propose an edit of it, fix what the findings or the image show, then propose the edit. With designId (from ' ++ `design_book) you see the page of that design draft instead of the book. ${CAPS}`;++/** For a session without edit_book_page (a viewer's): the page as it stands, nothing it could not ask for. */+const READER_DESCRIPTION = `Look at one page of the book as it stands: ${SEES} ${CAPS}`;+/** The draft a preview may look at instead of the book, by design_book's design_id. */const DESIGN_ID = { type: 'string', pattern: '^[\\w-]{1,40}$', description: 'A design draft, by its design_id.' };@@ -48,7 +58,7 @@ function previewSpec(specs: readonly AiToolSpec[]): AiToolSpec {for (const key of ['$defs', 'definitions']) if (edit?.parameters[key]) shared[key] = edit.parameters[key];return {name: PREVIEW_BOOK_PAGE_TOOL,- description: DESCRIPTION,+ description: ops ? EDITOR_DESCRIPTION : READER_DESCRIPTION,parameters: {type: 'object',properties: {diff --git a/server/src/nest/assistant/assistant-proposals.service.ts b/server/src/nest/assistant/assistant-proposals.service.tsindex 1261aeda5..8d98e2a94 100644--- a/server/src/nest/assistant/assistant-proposals.service.ts+++ b/server/src/nest/assistant/assistant-proposals.service.ts@@ -230,9 +230,11 @@ export class AssistantProposalsService {const args = proposal ? takeArgsOf(proposal) : null;if (!proposal || !args) throw aiRefusal('generic', 'Nothing can be created from this proposal: ask for it again');const ctx = this.cardContext.contextOf(card, categories, req.locale, today);+ // The proposal it came from, so the thread tells which card was taken, whatever way it creates.const preview = {...describeToolCall(TAKE_PROPOSAL_TOOL, id, args, ctx),card: pendingCardOf(proposal.card, args),+ takenFrom: req.toolCallId,};const parts: AssistantMessagePart[] = [{ type: 'tool-call', toolCallId: id, toolName: TAKE_PROPOSAL_TOOL, args, approval: { id } },diff --git a/server/src/nest/assistant/assistant-scope.ts b/server/src/nest/assistant/assistant-scope.tsindex 3c0774cd6..5cf6c5eb1 100644--- a/server/src/nest/assistant/assistant-scope.ts+++ b/server/src/nest/assistant/assistant-scope.ts@@ -128,6 +128,7 @@ export class AssistantScopes {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 };+ const system = studioPrompt(language, book.role !== 'viewer');+ return { card: emptyTripCard(turn.userId), system, context, gate };}}diff --git a/server/src/nest/assistant/assistant-undo.helpers.ts b/server/src/nest/assistant/assistant-undo.helpers.tsindex 9d5680440..266d3b8f6 100644--- a/server/src/nest/assistant/assistant-undo.helpers.ts+++ b/server/src/nest/assistant/assistant-undo.helpers.ts@@ -1,5 +1,5 @@import type { AssistantToolSession } from './assistant-tools.service';-import type { ToolArgs, UndoSnapshot } from './cards/card-types';+import type { ToolArgs, UndoCall, UndoSnapshot } from './cards/card-types';import { readKey, recordOf, type Row } from './cards/card-values';import { TOOL_CARDS, undoReadsOf } from './cards/registry';import {@@ -55,24 +55,36 @@ const CORE_CHECKS: Readonly<Record<string, (result: Row, snapshot: UndoSnapshot)},};+/** One check: the change's answer, the snapshot, and the call it answered (its arguments, its stored preview). */+type Check = (result: Row, snapshot: UndoSnapshot, call: UndoCall) => boolean;+/*** The core checks and each package's `undo.unchanged`, which the registry* guards (one that throws reads as changed) and keeps off the core's tools.*/-const CHECKS: Readonly<Record<string, (result: Row, snapshot: UndoSnapshot) => boolean>> = {+const CHECKS: Readonly<Partial<Record<string, Check>>> = {...CORE_CHECKS,...Object.fromEntries(- Object.entries(TOOL_CARDS).flatMap(([tool, cards]) => {+ Object.entries(TOOL_CARDS).flatMap(([tool, cards]): Array<[string, Check]> => {const undo = cards.undo;- return undo ? [[tool, (result: Row, snapshot: UndoSnapshot) => undo.unchanged(result, snapshot)]] : [];+ return undo ? [[tool, (result, snapshot, call) => undo.unchanged(result, snapshot, call)]] : [];}),),};-/** True when the change `toolName` made (its stored `result`) is still as it left it. */-export function unchangedSinceApplied(toolName: string, result: unknown, snapshot: TripSnapshot): boolean {+/**+ * True when the change `toolName` made (its stored `result`) is still as it+ * left it. `call` is what the answer may not name (the day a vacation toggle+ * was for, the person); a check that needs none ignores it.+ */+export function unchangedSinceApplied(+ toolName: string,+ result: unknown,+ snapshot: TripSnapshot,+ call: UndoCall = { args: {}, preview: null },+): boolean {const check = CHECKS[toolName];- return !!check && check(recordOf(result), { ...snapshot, reads: snapshot.reads ?? new Map() });+ return !!check && check(recordOf(result), { ...snapshot, reads: snapshot.reads ?? new Map() }, call);}/**diff --git a/server/src/nest/assistant/assistant.controller.ts b/server/src/nest/assistant/assistant.controller.tsindex fed46d352..abeedb792 100644--- a/server/src/nest/assistant/assistant.controller.ts+++ b/server/src/nest/assistant/assistant.controller.ts@@ -116,9 +116,13 @@ export class AssistantController {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. */+ /**+ * "+ Day 3" on a place a search found: a change card for the day, held like any other, no model turn.+ * It holds a new place or a place planned on a day, so it asks for the right the place routes ask for.+ */@Post('threads/:threadId/found-places')@HttpCode(200)+ @RequirePermission('place_edit')@ResponseContract(assistantAddFoundPlaceResponseSchema)addFoundPlace(@CurrentUser() user: User,diff --git a/server/src/nest/assistant/assistant.prompt.ts b/server/src/nest/assistant/assistant.prompt.tsindex d09ef4e3a..b29747c61 100644--- a/server/src/nest/assistant/assistant.prompt.ts+++ b/server/src/nest/assistant/assistant.prompt.ts@@ -54,7 +54,7 @@ How you work:- Answer briefly and plainly, in {language}. Use short paragraphs or lists, no headings.- The book card in the context lists the book's pages with their ids and the journey's entries. A book is a list of pages (spreads): the cover, the first page, inner double spreads, the last page and the back. Positions and sizes are millimetres from the top left of the page; a double spread is twice the page width, with the fold at one page width.- Every tool works on the open journey. You never pass a journey id.-- Read get_book and describe_book_page before you change a page. Page and element ids come from them and from the book card; never invent one. Photo ids come only from the book, the entries or suggest_book_photos.+- Read get_book and describe_book_page before you change a page. Page and element ids come from them and from the book card; never invent one. Photo ids come only from {photoSources}.- To change the book, call the tool for the change: the app shows each call to the user as a change card, and nothing happens until they apply it. Do not describe a change in text and ask whether to make it. Make one edit_book_page call per page in a step, with all of that page's operations.- Act, don't announce. Make the reads and changes you need in this reply; never end a reply with "I will now ..." and no calls. Never say a change was made unless its result says it was applied.- Keep every text inside its frame and nothing important in the fold or past the trim. When a result lists severe findings (overlapping photos, words past their frame, empty frames, content in the fold), fix them with the next change.@@ -68,7 +68,19 @@ How you work:- The book card may start with the page the user is looking at and what they selected on it. "This page", "this photo" or "here" mean that; never ask which one they mean then.- If the request is unclear, ask one short question instead of guessing.`;-/** The Studio's standing instructions with the designer's rules, telling the model which language to answer in. */-export function studioPrompt(language: string): string {- return `${STUDIO_INSTRUCTIONS.replace('{language}', language)}\n\n${BOOK_DESIGN_PROMPT}`;+/** Where photo ids come from: a design draft only for someone offered the design's tools. */+const WRITER_PHOTO_SOURCES =+ 'the book, a design draft (design_book, get_book_design, revise_book_design) or suggest_book_photos';+const READER_PHOTO_SOURCES = 'the book or suggest_book_photos';++/**+ * The Studio's standing instructions, telling the model which language to+ * answer in. The designer's rules and the design draft come only with the+ * right to change the book, as the design's tools do; each of the two+ * variants is the same text every turn, so the provider's cache holds.+ */+export function studioPrompt(language: string, canWrite: boolean): string {+ const sources = canWrite ? WRITER_PHOTO_SOURCES : READER_PHOTO_SOURCES;+ const base = STUDIO_INSTRUCTIONS.replace('{language}', language).replace('{photoSources}', sources);+ return canWrite ? `${base}\n\n${BOOK_DESIGN_PROMPT}` : base;}diff --git a/server/src/nest/assistant/assistant.service.ts b/server/src/nest/assistant/assistant.service.tsindex 3161451ba..a56250d2d 100644--- a/server/src/nest/assistant/assistant.service.ts+++ b/server/src/nest/assistant/assistant.service.ts@@ -102,6 +102,8 @@ interface AppliedSink {unrun: Set<string>;outcomes: Map<string, Outcome>;receipts: AssistantMessagePart[];+ /** The trip the conversation is on, for the receipts; null in a Studio conversation. */+ tripId: number | null;}/**@@ -344,13 +346,11 @@ export class AssistantService {renders: req.renders === true,};await this.converse(spec, stream, w, signal, (session) =>- this.applyDecisions(- (name, args) => this.runChange(session, userId, scope, name, args),- threadId,- decided,+ this.applyDecisions((name, args) => this.runChange(session, userId, scope, name, args), threadId, decided, {w,unrun,- ),+ scope,+ }),);} finally {if (unrun.size > 0) await this.failUnrun(threadId, decided, unrun);@@ -383,7 +383,7 @@ export class AssistantService {const session = await this.scopes.open(userId, scope);opened = session;const run = (name: string, args: Record<string, unknown>) => this.runChange(session, userId, scope, name, args);- await this.applyDecisions(run, threadId, decided, w, unrun);+ await this.applyDecisions(run, threadId, decided, { w, unrun, scope });w.finish('stop');} catch (err) {const reason = err instanceof Error ? err.message : String(err);@@ -444,7 +444,7 @@ export class AssistantService {const session = await this.scopes.open(userId, scope, undoTargetsOf(undo.tool, tool, args, result, onTrip));try {const snapshot = await undoSnapshotOf(session, tool, args, result, { tripReads: onTrip });- if (!snapshot || !unchangedSinceApplied(tool, result, snapshot)) throw stale();+ if (!snapshot || !unchangedSinceApplied(tool, result, snapshot, { args, preview })) throw stale();if (!(await this.toolCalls.claimUndo(call.id, userId, dbNow()))) throw stale();const run = await session.call(undo.tool, undoArgs);if (!run.ok) {@@ -658,8 +658,12 @@ export class AssistantService {}const now = new Date();const notBefore = dbNow(new Date(now.getTime() - APPROVAL_TTL_MS));+ // In the order the decisions name them, the order the chat shows the changes in: the changes of one step+ // share their time, and their ids sort at random, so only this order lets "undo all" walk them back.+ const position = new Map(decisions.map((decision, i) => [decision.toolCallId, i]));+ const ordered = [...open].sort((a, b) => (position.get(a.id) ?? 0) - (position.get(b.id) ?? 0));const decided = await this.uow.transactional(async () => {- const claims = open.map((call) => ({ call, approved: wanted.get(call.id) === true }));+ const claims = ordered.map((call) => ({ call, approved: wanted.get(call.id) === true }));const taken = await Promise.all(claims.map(({ call, approved }) =>this.toolCalls.claimDecision(call.id, threadId, approved, notBefore, dbNow(now)),@@ -687,15 +691,15 @@ export class AssistantService {run: (name: string, args: Record<string, unknown>) => Promise<ToolRun>,threadId: number,decided: Array<{ call: AssistantToolCallRow; approved: boolean }>,- w: UiStreamWriter,- unrun: Set<string>,+ { w, unrun, scope }: { w: UiStreamWriter; unrun: Set<string>; scope: AssistantScope },): Promise<void> {const outcomes = new Map<string, Outcome>();const receipts: AssistantMessagePart[] = [];+ const tripId = scope.kind === 'trip' ? scope.tripId : null;// One after another: a change may build on the one before it.await decided.reduce<Promise<void>>(async (previous, { call, approved }) => {await previous;- await this.applyOne(run, call, approved, { w, unrun, outcomes, receipts });+ await this.applyOne(run, call, approved, { w, unrun, outcomes, receipts, tripId });}, Promise.resolve());await this.recordDecided(threadId, decided[0].call.message_id, outcomes, receipts);}@@ -705,7 +709,7 @@ export class AssistantService {run: (name: string, args: Record<string, unknown>) => Promise<ToolRun>,call: AssistantToolCallRow,approved: boolean,- { w, unrun, outcomes, receipts }: AppliedSink,+ { w, unrun, outcomes, receipts, tripId }: AppliedSink,): Promise<void> {if (!approved) {w.toolDenied(call.id);@@ -740,6 +744,7 @@ export class AssistantService {ran.value,preview?.dayId ?? null,utcSuffix(undoUntil),+ { preview, tripId },);if (applied) {w.applied(applied);diff --git a/server/src/nest/assistant/cards/book-design/book-design-undo.ts b/server/src/nest/assistant/cards/book-design/book-design-undo.tsindex 96f251f4b..6724f0059 100644--- a/server/src/nest/assistant/cards/book-design/book-design-undo.ts+++ b/server/src/nest/assistant/cards/book-design/book-design-undo.ts@@ -1,5 +1,6 @@-import type { ToolArgs, ToolCards, UndoSnapshot } from '../card-types';-import { readKey, recordOf } from '../card-values';+import { BOOK_READ, bookUnmoved, versionOf, type BookUndo } from '../book/book-undo';+import type { ToolArgs } from '../card-types';+import { recordOf } from '../card-values';/*** The way back from the book-level changes (journey-studio-wp13.md 6.1). An@@ -8,27 +9,10 @@ import { readKey, recordOf } from '../card-values';* layout with `remove_book_layout`, a removed one with `restore_book_layout`.* Each call names the version the change left, so a save landing in between* is refused (409, "changed since") rather than overwritten; the ones that- * can only tell from the book also read `get_book` first, like the page- * undos of the photo book (book-undo.ts), whose version is the whole book's.+ * can only tell from the book also read `get_book` first, with the same+ * version check as the photo book's new and moved pages (book-undo.ts).*/-type BookUndo = NonNullable<ToolCards['undo']>;--/** The version a write's answer left the book at; null for an answer that names none. */-function versionOf(result: unknown): number | null {- const version = recordOf(result).version;- return typeof version === 'number' && Number.isInteger(version) && version > 0 ? version : null;-}--/** The book as the undo reads it before it checks. */-const BOOK_READ = { tool: 'get_book', args: {} } as const;--/** Nothing was saved to the book since the change: `get_book` still reads the version it left. */-function bookUnmoved(result: unknown, snapshot: UndoSnapshot): boolean {- const left = versionOf(result);- return left !== null && versionOf(snapshot.reads.get(readKey(BOOK_READ.tool, BOOK_READ.args))) === left;-}-/** The revision an applied design kept; null when the journey had no book before it. */function revisionOf(result: unknown): number | null {const id = recordOf(result).revision_id;diff --git a/server/src/nest/assistant/cards/book/book-undo.ts b/server/src/nest/assistant/cards/book/book-undo.tsindex 4b84bc9dd..d3067111f 100644--- a/server/src/nest/assistant/cards/book/book-undo.ts+++ b/server/src/nest/assistant/cards/book/book-undo.ts@@ -2,25 +2,28 @@ import type { ToolArgs, ToolCards, UndoSnapshot } from '../card-types';import { readKey, recordOf } from '../card-values';/**- * The way back from an applied book change. Edits, the cover and deleted- * pages go back with `restore_book_page`, which puts the pages the change- * answered under `previous_spreads` back as they were and only while the book- * is still at the version the change left: anything saved since makes it- * refuse, and the undo answers "changed since". New pages are deleted again- * and a moved page moved back, both only while `get_book` still reads the- * version the change left, and the call itself names that version, so a save- * landing between the check and the call is refused rather than overwritten.+ * The way back from an applied book change. Edits and the cover go back with+ * `restore_book_page`, which puts the pages the change answered under+ * `previous_spreads` back as they were, and only while each of those pages is+ * still as the change left it (`page_digests`): a later save to one of them+ * makes it refuse, and the undo answers "changed since", while a save to+ * another page does not hold it back. "Undo all" over several page changes,+ * newest first, therefore takes each back in turn.*- * The version is the whole book's: an undo after any later save to the book- * answers "changed since", a page the save never touched included. "Undo- * all" over several book changes therefore takes back the newest one only,- * the older ones then being behind the version it left.+ * Deleted pages go back at the place they had, which only means the same+ * while the book is still at the version the delete left; new pages are+ * deleted again and a moved page moved back on that same condition, read+ * with `get_book` first, and the call itself names that version, so a save+ * landing between the check and the call is refused rather than overwritten.+ * A block that mixes them with page edits can still end partly "changed+ * since": the newer undo of an edit is a save the older delete or move then+ * stands behind.*/-type BookUndo = NonNullable<ToolCards['undo']>;+export type BookUndo = NonNullable<ToolCards['undo']>;/** The version a write's answer left the book at; null for an answer that names none. */-function versionOf(result: unknown): number | null {+export function versionOf(result: unknown): number | null {const version = recordOf(result).version;return typeof version === 'number' && Number.isInteger(version) && version > 0 ? version : null;}@@ -31,26 +34,49 @@ function previousOf(result: unknown): unknown[] {return Array.isArray(pages) ? pages : [];}+/**+ * The pages the restore checks, as the write answered them under+ * `page_digests`: only when every page it puts back is still in the book, so+ * each is replaced where it is; otherwise none, and the whole book's version+ * stands guard.+ */+function digestsOf(result: unknown, pages: readonly unknown[]): Array<{ spreadId: string; digest: string }> {+ const answered = recordOf(result).page_digests;+ const digests = (Array.isArray(answered) ? answered : []).flatMap((row) => {+ const { spreadId, digest } = recordOf(row);+ return typeof spreadId === 'string' && typeof digest === 'string' ? [{ spreadId, digest }] : [];+ });+ const named = new Set(digests.map((row) => row.spreadId));+ const covered = pages.every((page) => {+ const id = recordOf(recordOf(page).spread).id;+ return typeof id === 'string' && named.has(id);+ });+ return covered ? digests : [];+}+/** The book as the undo reads it before it checks: its summary, whatever the change was. */-const BOOK_READ = { tool: 'get_book', args: {} } as const;+export const BOOK_READ = { tool: 'get_book', args: {} } as const;/** Nothing was saved to the book since the change: `get_book` still reads the version it left. */-function bookUnmoved(result: unknown, snapshot: UndoSnapshot): boolean {+export function bookUnmoved(result: unknown, snapshot: UndoSnapshot): boolean {const left = versionOf(result);return left !== null && versionOf(snapshot.reads.get(readKey(BOOK_READ.tool, BOOK_READ.args))) === left;}/*** Pages put back as the change found them. The restore itself refuses unless- * the book is still at the version the change left, so the check only asks- * that the answer holds what the restore needs.+ * the pages it names are still as the change left them (or, for pages the+ * change deleted, the book still at the version it left), so the check only+ * asks that the answer holds what the restore needs.*/export const RESTORE_PREVIOUS: BookUndo = {tool: 'restore_book_page',args: (_args, result) => {const pages = previousOf(result);const expectedVersion = versionOf(result);- return pages.length > 0 && expectedVersion !== null ? { pages, expectedVersion } : null;+ if (pages.length === 0 || expectedVersion === null) return null;+ const expectedPages = digestsOf(result, pages);+ return expectedPages.length > 0 ? { pages, expectedVersion, expectedPages } : { pages, expectedVersion };},unchanged: (result) => previousOf(result).length > 0 && versionOf(result) !== null,};diff --git a/server/src/nest/assistant/cards/book/index.ts b/server/src/nest/assistant/cards/book/index.tsindex 4605dec03..20fa6b779 100644--- a/server/src/nest/assistant/cards/book/index.ts+++ b/server/src/nest/assistant/cards/book/index.ts@@ -10,18 +10,19 @@ import type { AssistantChangeVerbKey } from '@trek/shared';* card carries, with what it brings and what the server's check of the result* found; once applied, the pages as it left them. Edits, the cover and* deleted pages are taken back with `restore_book_page`, new pages deleted- * again, a moved page moved back, each only while nothing was saved since.+ * again, a moved page moved back: an edit while its page is as the change+ * left it, the others while nothing was saved to the book since.** The check itself is the turn's gate (assistant-book-gate.ts): it tries the* call on the stored book, refuses what the engine refuses and sends a change* with new faults back to the model once, and the card reads that same trial.*/-/** A write's answer as the model and the chat see it: without the pages it kept for its undo. */+/** A write's answer as the model and the chat see it: without the pages and their digests it kept for its undo. */function withoutPrevious(value: unknown): unknown {const answer = recordOf(value);- if (!('previous_spreads' in answer)) return value;- const { previous_spreads: _kept, ...rest } = answer;+ if (!('previous_spreads' in answer) && !('page_digests' in answer)) return value;+ const { previous_spreads: _kept, page_digests: _digests, ...rest } = answer;return rest;}diff --git a/server/src/nest/assistant/cards/card-types.ts b/server/src/nest/assistant/cards/card-types.tsindex 23f3d116f..66f92f4f3 100644--- a/server/src/nest/assistant/cards/card-types.ts+++ b/server/src/nest/assistant/cards/card-types.ts@@ -66,6 +66,12 @@ export interface Described {verbKey?: AssistantChangeVerbKey;tool?: string;domain?: string;+ /**+ * False when the package already sees that this held call has no way back,+ * though its tool has one (a toggle that would clear a day); the card is+ * then not offered as undoable. Left out, the tool's undo decides.+ */+ undoable?: boolean;}/** What an answer card is built from: a read that ran, with its raw value (never the redacted one). */@@ -88,6 +94,19 @@ export interface UndoSnapshot {reads: ReadonlyMap<string, unknown>;}+/** What a receipt is read with beyond the call: the stored preview, and the trip the conversation is on. */+export interface AppliedFrom {+ preview: AssistantChangePreview | null;+ /** Null in a Studio conversation, which is about a journey. */+ tripId: number | null;+}++/** What an undo is checked with beyond the answer and the reads: the call's arguments and its stored preview. */+export interface UndoCall {+ args: ToolArgs;+ preview: AssistantChangePreview | null;+}+/** The way back from an applied change: the removing tool and its arguments, null when there is none. */export interface ToolUndo {tool: string;@@ -121,7 +140,7 @@ export interface ToolCards<L = unknown> {/** The card of the applied change, from the stored preview card and the tool's raw answer. */applied?(input: { args: ToolArgs; result: unknown; preview: AssistantChangePreview | null }): TrekCard | null;/** The ids the receipt names, when the answer does not name them under the usual keys. */- appliedIds?(args: ToolArgs, result: unknown): number[];+ appliedIds?(args: ToolArgs, result: unknown, from: AppliedFrom): number[];/** The way back, with what it reads first and how it tells that nothing changed since. */undo?: ToolUndo & {/**@@ -130,7 +149,12 @@ export interface ToolCards<L = unknown> {* tools it names may not depend on them (their arguments may).*/reads?(args: ToolArgs, result: unknown): ReadonlyArray<{ tool: string; args: ToolArgs }>;- unchanged(result: unknown, snapshot: UndoSnapshot): boolean;+ /**+ * Whether what the change did is still as it left it. `call` names what+ * the answer may not (a date, a person); the undo always hands it in, and+ * a check that needs it reads its absence as changed since.+ */+ unchanged(result: unknown, snapshot: UndoSnapshot, call?: UndoCall): boolean;};/** The name of an id argument the trip card cannot name, for the generic card. */nameArg?(key: string, value: number, card: TripCard): string | null;diff --git a/server/src/nest/assistant/cards/collection/collection-applied.ts b/server/src/nest/assistant/cards/collection/collection-applied.tsindex 3867902b1..09a011ac5 100644--- a/server/src/nest/assistant/cards/collection/collection-applied.ts+++ b/server/src/nest/assistant/cards/collection/collection-applied.ts@@ -1,4 +1,4 @@-import type { ToolArgs, ToolCards, UndoSnapshot } from '../card-types';+import type { AppliedFrom, ToolArgs, ToolCards, UndoSnapshot } from '../card-types';import { argId, clipped, readKey, recordOf, type Row } from '../card-values';import { rowsOf, same } from '../undo-snapshot';import { listsCard } from './collection-answers';@@ -136,24 +136,35 @@ export const COLLECTION_APPLIED: Readonly<Partial<Record<string, (input: Appliedupdate_collection_label: labelApplied,};+type AppliedIds = (args: ToolArgs, result: unknown, from: AppliedFrom) => number[];++/** The list the held card showed the change in; none for a change across lists or without a card. */+const shownList: AppliedIds = (_args, _result, { preview }) =>+ idsOf(positiveId(previewCard(preview, 'collectionPlaces')?.list?.id));+/** The ids a receipt names where the answer does not name them under the usual keys. */-export const COLLECTION_APPLIED_IDS: Readonly<Partial<Record<string, (args: ToolArgs, result: unknown) => number[]>>> =- {- create_collection: (_args, result) => idsOf(positiveId(recordOf(recordOf(result).collection).id)),- update_collection: (args) => idsOf(argId(args, 'collectionId')),- delete_collection: (args) => idsOf(argId(args, 'collectionId')),- save_trip_places_to_collection: (args) => idsOf(argId(args, 'collectionId')),- accept_collection_invite: (args) => idsOf(argId(args, 'collectionId')),- decline_collection_invite: (args) => idsOf(argId(args, 'collectionId')),- cancel_collection_invite: (args) => idsOf(argId(args, 'collectionId')),- create_collection_label: (args) => idsOf(argId(args, 'collection_id')),- update_collection_label: (_args, result) => idsOf(positiveId(recordOf(recordOf(result).label).collection_id)),- // The new trip places, so "Show on map" opens the first of them.- copy_collection_places_to_trip: (_args, result) =>- rowsOf(recordOf(result).created)- .map((row) => positiveId(row.id))- .filter((id): id is number => id !== null),- };+export const COLLECTION_APPLIED_IDS: Readonly<Partial<Record<string, AppliedIds>>> = {+ create_collection: (_args, result) => idsOf(positiveId(recordOf(recordOf(result).collection).id)),+ update_collection: (args) => idsOf(argId(args, 'collectionId')),+ delete_collection: (args) => idsOf(argId(args, 'collectionId')),+ save_trip_places_to_collection: (args) => idsOf(argId(args, 'collectionId')),+ accept_collection_invite: (args) => idsOf(argId(args, 'collectionId')),+ decline_collection_invite: (args) => idsOf(argId(args, 'collectionId')),+ cancel_collection_invite: (args) => idsOf(argId(args, 'collectionId')),+ create_collection_label: (args) => idsOf(argId(args, 'collection_id')),+ update_collection_label: (_args, result) => idsOf(positiveId(recordOf(recordOf(result).label).collection_id)),+ set_collection_place_status_from_trip: shownList,+ assign_collection_labels: shownList,+ delete_collection_label: shownList,+ // The new places of a copy into the chat's own trip, so "Show on map" opens the first of them; a copy+ // into another trip names none, since the map shows the chat's trip, where those places are not.+ copy_collection_places_to_trip: (args, result, { tripId }) =>+ tripId !== null && argId(args, 'trip_id') === tripId+ ? rowsOf(recordOf(result).created)+ .map((row) => positiveId(row.id))+ .filter((id): id is number => id !== null)+ : [],+};function idsOf(id: number | null): number[] {return id === null ? [] : [id];diff --git a/server/src/nest/assistant/cards/registry.ts b/server/src/nest/assistant/cards/registry.tsindex ec05bab55..ab202ccde 100644--- a/server/src/nest/assistant/cards/registry.ts+++ b/server/src/nest/assistant/cards/registry.ts@@ -14,12 +14,14 @@ import { BOOKING_CARDS } from './booking';import { BUDGET_CARDS } from './budget';import type {AnswerInput,+ AppliedFrom,Described,DomainCards,PreviewContext,ToolArgs,ToolCards,ToolUndo,+ UndoCall,UndoSnapshot,} from './card-types';import { COLLAB_CARDS } from './collab';@@ -129,8 +131,8 @@ function guardUndo(tool: string, undo: Undo): Undo {safely<UndoReads>(tool, 'undo reads', [], () => undo.reads?.(args, result) ?? []),}: {}),- unchanged: (result: unknown, snapshot: UndoSnapshot) =>- safely(tool, 'undo check', false, () => undo.unchanged(result, snapshot)),+ unchanged: (result: unknown, snapshot: UndoSnapshot, call?: UndoCall) =>+ safely(tool, 'undo check', false, () => undo.unchanged(result, snapshot, call)),};}@@ -156,9 +158,9 @@ function guardTool(tool: string, cards: ToolCards): ToolCards {: {}),...(cards.appliedIds? {- appliedIds: (args: ToolArgs, result: unknown) =>+ appliedIds: (args: ToolArgs, result: unknown, from: AppliedFrom) =>safely<number[]>(tool, 'applied ids', [], () =>- (cards.appliedIds?.(args, result) ?? []).filter((value) => idSchema.safeParse(value).success),+ (cards.appliedIds?.(args, result, from) ?? []).filter((value) => idSchema.safeParse(value).success),),}: {}),diff --git a/server/src/nest/assistant/cards/vacay/index.ts b/server/src/nest/assistant/cards/vacay/index.tsindex 761327d10..cb4e8b561 100644--- a/server/src/nest/assistant/cards/vacay/index.ts+++ b/server/src/nest/assistant/cards/vacay/index.ts@@ -3,6 +3,7 @@ import { VACAY_ANSWER_CARDS } from './vacay-answer';import { appliedCompany, appliedToggle } from './vacay-applied';import { VACAY_CHANGE_CARDS, VACAY_DESCRIBERS } from './vacay-change';import { loadDay, loadStats, type VacayLoaded, type VacayStatsLoaded } from './vacay-load';+import { TOGGLE_BACK } from './vacay-undo';/*** The vacation planner in the assistant chat. Its reads show the days off,@@ -13,10 +14,12 @@ import { loadDay, loadStats, type VacayLoaded, type VacayStatsLoaded } from './v* can come hours after the hold, so the applied card follows what the tool* says it did, not what the held card foresaw (`applied`).*- * A toggle cannot be undone from the chat yet: whether the day is still as- * the change left it needs the change's own date, which an undo check is not- * handed (`undo.unchanged` gets the result only, and the result names no- * date). The other vacation writes stay cards built from their arguments.+ * A day the assistant added or converted is taken back with the toggle once+ * more, while the day is still as the change left it (vacay-undo.ts); a day+ * it cleared is not, since the toggle cannot give back a note the day may+ * have carried. The held card says so up front (`undoable` only for a day it+ * would add or convert, never before the lookup ran). The company holiday and+ * the allowance have no way back.*/const toggle: ToolCards<VacayLoaded> = {@@ -25,6 +28,7 @@ const toggle: ToolCards<VacayLoaded> = {describe: VACAY_DESCRIBERS.toggle_vacay_entry,change: VACAY_CHANGE_CARDS.toggle_vacay_entry,applied: appliedToggle,+ undo: TOGGLE_BACK,};const companyHoliday: ToolCards<VacayLoaded> = {diff --git a/server/src/nest/assistant/cards/vacay/vacay-change.ts b/server/src/nest/assistant/cards/vacay/vacay-change.tsindex dbc612f2c..aae1de417 100644--- a/server/src/nest/assistant/cards/vacay/vacay-change.ts+++ b/server/src/nest/assistant/cards/vacay/vacay-change.ts@@ -15,6 +15,7 @@ import {} from './vacay-frame';import { dateArg, yearArg, type VacayLoaded, type VacayStatsLoaded } from './vacay-load';import type { Fraction, VacayEntryRow } from './vacay-reads';+import { takesBack } from './vacay-undo';import {VACAY_CARD_MAX_HOLIDAYS,type AssistantChangeVerbKey,@@ -201,11 +202,13 @@ function dayDescribed(ctx: PreviewContext, args: ToolArgs): Described {}export const VACAY_DESCRIBERS = {+ /** Undoable only when the lookup ran and the toggle would add or convert the day (vacay-undo.ts). */toggle_vacay_entry: (ctx: PreviewContext, args: ToolArgs, loaded: VacayLoaded | null): Described => {const described = dayDescribed(ctx, args);const date = dateArg(args);- if (!loaded || !date) return described;- return { ...described, verbKey: TOGGLE_VERBS[toggleProposal(ctx.card.viewerId, args, loaded, date).outcome] };+ if (!loaded || !date) return { ...described, undoable: false };+ const proposal = toggleProposal(ctx.card.viewerId, args, loaded, date);+ return { ...described, verbKey: TOGGLE_VERBS[proposal.outcome], undoable: takesBack(proposal) };},toggle_company_holiday: (ctx: PreviewContext, args: ToolArgs): Described => {const described = dayDescribed(ctx, args);diff --git a/server/src/nest/assistant/cards/vacay/vacay-undo.ts b/server/src/nest/assistant/cards/vacay/vacay-undo.tsnew file mode 100644index 000000000..9d7857c24--- /dev/null+++ b/server/src/nest/assistant/cards/vacay/vacay-undo.ts@@ -0,0 +1,143 @@+import type { ToolArgs, ToolCards, UndoCall, UndoSnapshot } from '../card-types';+import { readKey, recordOf } from '../card-values';+import { dateArg } from './vacay-load';+import { entriesOf, type Fraction } from './vacay-reads';+import type { AssistantChangePreview, VacayCardProposal } from '@trek/shared';++/**+ * The way back from a day off the assistant toggled: the same toggle once+ * more, for the same person, with what puts the day back exactly as it was.+ * A day the change added is cleared with the size and kind it was added+ * with; a day it converted goes back to the size and kind its card showed+ * before. The person comes from the held card, since a toggle for the caller+ * names nobody and its answer names no day.+ *+ * Only while the person's day is still as the change left it, read with+ * `get_vacay_entries` for the day's year and the year before (the signed-in+ * user's calendar grid can show the day in either), and only where the+ * planner's toggle does exactly that: half a company holiday on the day makes+ * every toggle half a day, so a whole day cannot come back then and the undo+ * answers "changed since"; a whole one set since took the day off already.+ *+ * Not taken back at all: a day the change cleared, since the planner's toggle+ * adds a day without the note the cleared one may have carried and nothing+ * the chat holds says whether it carried one; and a toggle that did not do+ * what its card foresaw (the day changed between the hold and the decision),+ * since what it found then is not known.+ */++type VacayUndo = NonNullable<ToolCards['undo']>;+type DayKind = VacayCardProposal['kind'];++/** One size and kind of a day off. */+interface DayOff {+ fraction: Fraction;+ kind: DayKind;+}++/** What one toggle did: whose day, which date, how it left the day, and the toggle that puts it back. */+interface Toggled {+ date: string;+ personId: number;+ left: DayOff;+ back: DayOff;+}++const ENTRIES_READ = 'get_vacay_entries';++function dayOff(fraction: unknown, kind: unknown): DayOff | null {+ if ((fraction === 0.5 || fraction === 1) && (kind === 'vacation' || kind === 'comp')) return { fraction, kind };+ return null;+}++/**+ * Whether a toggle held with this proposal can be taken back once it ran as+ * foreseen: a day it adds, or one it converts from a size and kind the card+ * saw. A day it clears, or one it is refused, has no way back.+ */+export function takesBack(proposal: VacayCardProposal): boolean {+ return proposal.outcome === 'add' || (proposal.outcome === 'convert' && proposal.before !== null);+}++/** The held card's day, when the card is the planner's and names whose day it is. */+function heldDay(preview: AssistantChangePreview | null): (VacayCardProposal & { personId: number }) | null {+ const card = preview?.card;+ const proposal = card?.kind === 'vacay' ? card.proposal : null;+ const personId = proposal?.personId ?? null;+ return proposal && personId !== null ? { ...proposal, personId } : null;+}++/**+ * The size and kind the toggle back sets, when that puts the day back+ * exactly: what an added day was added with, or what the card saw before a+ * conversion that did just what the card foresaw.+ */+function backOf(action: unknown, proposal: VacayCardProposal, left: DayOff): DayOff | null {+ if (action === 'added') return proposal.outcome === 'add' ? left : null;+ if (action !== 'updated' || proposal.outcome !== 'convert' || proposal.before === null) return null;+ const foreseen = left.fraction === proposal.fraction && left.kind === proposal.kind;+ return foreseen ? dayOff(proposal.before.fraction, proposal.before.kind) : null;+}++/**+ * What the toggle did, from its arguments, its answer and the card it was+ * held with; null for a toggle that cannot be taken back exactly.+ */+function toggledOf(args: ToolArgs, result: unknown, preview: AssistantChangePreview | null): Toggled | null {+ const proposal = heldDay(preview);+ const date = dateArg(args);+ if (!proposal || date === null || proposal.date !== date) return null;+ const answer = recordOf(result);+ const left = dayOff(answer.fraction, answer.kind);+ const back = left ? backOf(answer.action, proposal, left) : null;+ return left && back ? { date, personId: proposal.personId, left, back } : null;+}++/** The logged days and company holidays the undo read, of both years; null when either read failed. */+function readDays(snapshot: UndoSnapshot, date: string) {+ const year = Number(date.slice(0, 4));+ const read = (of: number) => entriesOf(snapshot.reads.get(readKey(ENTRIES_READ, { year: of })));+ const now = read(year);+ const earlier = read(year - 1);+ if (!now || !earlier) return null;+ return { entries: [...now.entries, ...earlier.entries], company: [...now.company, ...earlier.company] };+}++/**+ * The person's day is as the change left it, and the toggle back would do+ * exactly what it says: no half company holiday on the day unless half a day+ * is what goes back.+ */+function unchangedToggle(result: unknown, snapshot: UndoSnapshot, call?: UndoCall): boolean {+ const toggled = call ? toggledOf(call.args, result, call.preview) : null;+ if (!toggled) return false;+ const days = readDays(snapshot, toggled.date);+ if (!days) return false;+ const { date, personId, left, back } = toggled;+ const own = days.entries.filter((entry) => entry.date === date && entry.personId === personId);+ const halfCompany = days.company.some((row) => row.date === date && row.fraction < 1);+ return (+ own.length > 0 &&+ own.every((entry) => entry.fraction === left.fraction && entry.kind === left.kind) &&+ (back.fraction === 0.5 || !halfCompany)+ );+}++/** The undo of `toggle_vacay_entry`. */+export const TOGGLE_BACK: VacayUndo = {+ tool: 'toggle_vacay_entry',+ args: (args, result, preview) => {+ const toggled = toggledOf(args, result, preview);+ if (!toggled) return null;+ const { date, personId, back } = toggled;+ return { date, fraction: back.fraction, kind: back.kind, targetUserId: personId };+ },+ reads: (args) => {+ const year = Number(dateArg(args)?.slice(0, 4) ?? 0);+ return [+ { tool: ENTRIES_READ, args: { year } },+ { tool: ENTRIES_READ, args: { year: year - 1 } },+ ];+ },+ unchanged: unchangedToggle,+};diff --git a/server/src/nest/assistant/tool-call-preview.helpers.ts b/server/src/nest/assistant/tool-call-preview.helpers.tsindex 15eace226..f37c01648 100644--- a/server/src/nest/assistant/tool-call-preview.helpers.ts+++ b/server/src/nest/assistant/tool-call-preview.helpers.ts@@ -1,7 +1,7 @@import type { CardPlace } from './assistant-context';import { noteOf } from './assistant-memory';import { ASSISTANT_SERVER_WRITE_TOOLS, REMEMBER_TOOL, writeToolOf } from './assistant-tools.constants';-import type { Described, PreviewContext } from './cards/card-types';+import type { AppliedFrom, Described, PreviewContext } from './cards/card-types';import {categoryName,clip,@@ -337,7 +337,7 @@ export function describeToolCall(rows: described.rows.rows.slice(0, MAX_ROWS),dayId: described.dayId,placeIds: described.placeIds,- undoable: runs in ASSISTANT_UNDO_MAP,+ undoable: runs in ASSISTANT_UNDO_MAP && described.undoable !== false,effect: planned ?? null,...(described.tool ? { tool: described.tool } : {}),...(described.domain ? { domain: described.domain } : {}),@@ -383,7 +383,8 @@ function bookedDay(result: unknown): number | null {* The receipt of an applied change: what it touched (the created row from its* answer, the changed one from its arguments), the day "Show on map" goes to* (the card's, else the one a created booking landed on), and until when it- * can be undone.+ * can be undone. A package that names the ids itself reads `from` too: the+ * stored preview, and the trip the conversation is on.*/export function appliedChange(toolName: string,@@ -392,11 +393,12 @@ export function appliedChange(result: unknown,dayId: number | null,undoUntil: string | null,+ from: AppliedFrom = { preview: null, tripId: null },): AssistantApplied | null {// A tool without a card of its own touched something the client has no view for.const runs = writeToolOf(toolName, args);const tool = writeTool(runs) ?? { entity: 'other' as const };- const own = TOOL_CARDS[runs]?.appliedIds?.(args, result) ?? [];+ const own = TOOL_CARDS[runs]?.appliedIds?.(args, result, from) ?? [];const created = own.length > 0 ? own : createdIds(result);const named = ARG_KEYS.map((key) => id(args, key)).filter((value): value is number => value !== null);return {diff --git a/server/src/nest/journey/book-design-apply.ts b/server/src/nest/journey/book-design-apply.tsindex 780222acc..b6d8215bd 100644--- a/server/src/nest/journey/book-design-apply.ts+++ b/server/src/nest/journey/book-design-apply.ts@@ -1,4 +1,5 @@import {+ compareCodeUnits,MAX_SPREADS,type BookDesignPlanRow,type BookDesignSkipped,@@ -32,13 +33,18 @@ interface AppliedDesign {skipped: BookDesignSkipped[];}-/** JSON with the keys of every object sorted, so two equal pages read alike whatever order their keys came in. */-function canonical(value: unknown): string {- if (Array.isArray(value)) return `[${value.map(canonical).join(',')}]`;+/**+ * JSON with the keys of every object sorted, so two equal pages read alike+ * whatever order their keys came in. The one compare of pages: the apply+ * here, and the digest a page restore checks (journey-book-edit.service.ts).+ * Keys sort by code unit, so the text is the same on every machine.+ */+export function canonical(value: unknown): string {+ if (Array.isArray(value)) return `[${value.map((item) => canonical(item)).join(',')}]`;if (value !== null && typeof value === 'object') {const entries = Object.entries(value as Record<string, unknown>).filter(([, v]) => v !== undefined)- .sort(([a], [b]) => a.localeCompare(b, 'en'));+ .sort(([a], [b]) => compareCodeUnits(a, b));return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canonical(v)}`).join(',')}}`;}return JSON.stringify(value);@@ -147,13 +153,14 @@ export function applyDesignDraft(const skipped: BookDesignSkipped[] = [];const skip = (spreadId: string, reason: BookDesignSkipped['reason']) => skipped.push({ spreadId, reason });const frame = current ? bookFrame(current, draft) : null;- if (!current || !frame) {+ // A missing base already leaves no frame; naming it here lets the reads below take the base as it is.+ if (!current || !draft.base || !frame) {for (const row of draft.plan) if (row.action !== 'keep') skip(row.spreadId, 'changed_since');return { doc: current ?? draft.doc, applied, skipped };}const chosen = new Set(draft.selection);const designed = new Map(draft.doc.spreads.map((s) => [s.id, s]));- const base = new Map((draft.base?.spreads ?? []).map((s) => [s.id, s]));+ const base = new Map(draft.base.spreads.map((s) => [s.id, s]));const spreads = [...current.spreads];draft.plan.forEach((row, i) => {if (row.action === 'keep') return;diff --git a/server/src/nest/journey/journey-book-edit.service.ts b/server/src/nest/journey/journey-book-edit.service.tsindex 3bb01a4e2..53cd126a2 100644--- a/server/src/nest/journey/journey-book-edit.service.ts+++ b/server/src/nest/journey/journey-book-edit.service.ts@@ -5,6 +5,7 @@ import type { JourneyPhotosRepository } from '../../db/repositories/JourneyPhotoimport { DomainError } from '../common/domain-error';import { PhotoSignalsService } from '../photos/photo-signals.service';import { SettingsService } from '../settings/settings.service';+import { canonical } from './book-design-apply';import { BookDesignDraftStore, designExpired } from './book-design-draft.store';import { bookEntriesOf } from './book-journey-input';import { bookLanguage, loadBookWords, type BookWords } from './book-travel-labels';@@ -41,8 +42,10 @@ import {type BookOpsContext,type BookOverview,type BookPageDescription,+ type BookPageDigest,type BookPhotoInfo,type BookPreviousSpread,+ type BookSpread,type BookSpreadSummary,type BookTravelContext,type BookWriteResult,@@ -59,6 +62,8 @@ import {type SetBookSetupRequest,} from '@trek/shared';+import { createHash } from 'node:crypto';+/** A book write's answer, in the shared result's shape. */export type BookWriteAnswer = BookWriteResult;@@ -280,14 +285,31 @@ export class JourneyBookEditService {* Pages put back as they were, for the assistant's undo: all the pages one* change answered under `previous_spreads` in one call, and only while the* book is still at `expectedVersion`, so an undo never overwrites what anyone- * saved after the change it takes back (409 instead). The engine holds a- * restore to an edit's rules: photos from the gallery or the book, locked- * elements as they are.+ * saved after the change it takes back (409 instead). `expectedPages` (the+ * change's `page_digests`) are checked in the write's transaction: every+ * page they name must still be as the change left them. They stand in for+ * the version only when they name every page put back with a digest, so+ * "undo all" over several page edits takes each back while a later save to+ * another page stands; a page put back that they do not name, or name as+ * gone (a deleted page goes back at its old index, which means the same+ * only at the version), keeps the whole book's check, and so does an MCP+ * client that names only the version. The engine holds a restore to an+ * edit's rules: photos from the gallery or the book, locked elements as+ * they are.*/async restorePage(journeyId: number, userId: number, args: RestoreBookPageRequest): Promise<BookWriteAnswer> {- return this.write(journeyId, userId, (doc, ctx) => restoreBookPage(stored(doc), args, ctx), {- expectedVersion: args.expectedVersion,- });+ const pinned = args.expectedPages;+ const covered = pinned !== undefined && args.pages.every((page) => digestNamed(pinned, page.spread.id));+ return this.write(+ journeyId,+ userId,+ (doc, ctx) => {+ const book = stored(doc);+ if (pinned && !pagesAsLeft(book, pinned)) throw pageMoved();+ return restoreBookPage(book, args, ctx);+ },+ { expectedVersion: covered ? undefined : args.expectedVersion },+ );}/**@@ -417,12 +439,43 @@ export class JourneyBookEditService {pages: answer.pages,findings: answer.findings,dropped: result.made.dropped,- ...(options.returnPrevious ? { previous_spreads: previousOf(result.before, result.made.spreadIds) } : {}),+ ...(options.returnPrevious+ ? {+ previous_spreads: previousOf(result.before, result.made.spreadIds),+ page_digests: digestsOf(record.document, result.made.spreadIds),+ }+ : {}),...options.extra?.(result.before, result.made),};}}+/** A page as the book stores it, as a restore checks it: a digest of its canonical JSON. */+function pageDigest(spread: BookSpread): string {+ return createHash('sha256').update(canonical(spread)).digest('hex').slice(0, 16);+}++/** The pages a write touched as it left them; null for one it took out of the book. */+function digestsOf(doc: BookDocument, spreadIds: readonly string[]): BookPageDigest[] {+ return spreadIds.map((spreadId) => {+ const spread = doc.spreads.find((s) => s.id === spreadId);+ return { spreadId, digest: spread ? pageDigest(spread) : null };+ });+}++/** The digests name this page as the write left it in the book, not as one it took out. */+function digestNamed(expected: readonly BookPageDigest[], spreadId: string): boolean {+ return expected.some((row) => row.spreadId === spreadId && row.digest !== null);+}++/** Every page named is as its digest says: there and unchanged, or still gone for a null digest. */+function pagesAsLeft(doc: BookDocument, expected: readonly BookPageDigest[]): boolean {+ return expected.every(({ spreadId, digest }) => {+ const spread = doc.spreads.find((s) => s.id === spreadId);+ return spread ? digest !== null && pageDigest(spread) === digest : digest === null;+ });+}+/** The pages a write touched as they are stored now, with their findings, severe first and capped. */function pagesOf(doc: BookDocument, made: BookMade, ctx: BookOpsContext) {const pages: BookSpreadSummary[] = [];@@ -475,6 +528,14 @@ function noBook(): DomainError {});}+/** A page a restore names was saved since the change it takes back: the 409 a moved book gets. */+function pageMoved(): DomainError {+ return new DomainError(409, 'Book was changed by someone else', {+ code: 'book_conflict',+ mcpMessage: 'A page was changed since that change. Read the book again with get_book before changing it.',+ });+}+function pageNotFound(spreadId: string): DomainError {return new DomainError(404, `No page ${spreadId} in this book`, {code: 'book_page_missing',diff --git a/server/src/nest/journey/journey-book.mcp.ts b/server/src/nest/journey/journey-book.mcp.tsindex 7839c89f6..61a370766 100644--- a/server/src/nest/journey/journey-book.mcp.ts+++ b/server/src/nest/journey/journey-book.mcp.ts@@ -165,7 +165,7 @@ export class JourneyBookMcp {@Tool({name: 'delete_book_pages',- description: `Delete 1 to ${BOOK_OP_LIMITS.pagesPerCall} inner double spreads with everything on them. The cover, first, last and back pages cannot be deleted. Only when the person asked for it. With returnPrevious the answer also holds the deleted pages as they were, under previous_spreads. ${WRITE_ANSWER}`,+ description: `Delete 1 to ${BOOK_OP_LIMITS.pagesPerCall} inner double spreads with everything on them. The cover, first, last and back pages cannot be deleted. Only when the person asked for it. With returnPrevious the answer also holds the deleted pages as they were, under previous_spreads, and a null digest for each under page_digests (for restore_book_page expectedPages). ${WRITE_ANSWER}`,inputSchema: { journeyId: idSchema, ...deleteBookPagesArgs },annotations: TOOL_ANNOTATIONS_DELETE,when: journeyAddonOn,@@ -177,7 +177,7 @@ export class JourneyBookMcp {@Tool({name: 'edit_book_page',- description: `Change one page with 1 to ${BOOK_OP_LIMITS.opsPerCall} operations, run in order, all or nothing: layout (a template, grid, saved layout, or auto to lay the page out again from its entry), place_photo (a photo of the journey's gallery into a frame by elementId, by its slot among the page's frames, or into a new frame), photo_look (the crop as fit and focal point, mask, frame style, filter, radius), swap_photos, text (by elementId, or by role heading, body or meta, which creates the text when the page has none), caption (under a photo, bound to its caption in the journal unless words are given), frame (move, resize, turn), remove (parked with the page by default, park false deletes), background (null is the paper), add (a new photo frame, text, shape, icon, map, figures, country outlines, mark or list; the journey's own values such as the route, figures and countries come from the journey, never from you), style (the look of one element of its kind: opacity, colours, fonts, strokes and the like), arrange (to front, forward, backward, to back), align and distribute (several elements by their edges or centres, against each other, the page or the safe area), lock, duplicate, fill (a photo to the bleed of its page or the spread, behind everything), copy_from (elements of another page), refresh_travel (travel elements to the journey's current figures) and add_grid (a photo grid as empty frames in a box). A locked element refuses any operation that would change it but lock. The road a map draws between stops is a straight or bowed line; roads are not routed. ${LAYOUT_NOTES.templates} ${LAYOUT_NOTES.grids} ${UNITS} With returnPrevious the answer also holds the page as it was, under previous_spreads. ${WRITE_ANSWER}`,+ description: `Change one page with 1 to ${BOOK_OP_LIMITS.opsPerCall} operations, run in order, all or nothing: layout (a template, grid, saved layout, or auto to lay the page out again from its entry), place_photo (a photo of the journey's gallery into a frame by elementId, by its slot among the page's frames, or into a new frame), photo_look (the crop as fit and focal point, mask, frame style, filter, radius), swap_photos, text (by elementId, or by role heading, body or meta, which creates the text when the page has none), caption (under a photo, bound to its caption in the journal unless words are given), frame (move, resize, turn), remove (parked with the page by default, park false deletes), background (null is the paper), add (a new photo frame, text, shape, icon, map, figures, country outlines, mark or list; the journey's own values such as the route, figures and countries come from the journey, never from you), style (the look of one element of its kind: opacity, colours, fonts, strokes and the like), arrange (to front, forward, backward, to back), align and distribute (several elements by their edges or centres, against each other, the page or the safe area), lock, duplicate, fill (a photo to the bleed of its page or the spread, behind everything), copy_from (elements of another page), refresh_travel (travel elements to the journey's current figures) and add_grid (a photo grid as empty frames in a box). A locked element refuses any operation that would change it but lock. The road a map draws between stops is a straight or bowed line; roads are not routed. ${LAYOUT_NOTES.templates} ${LAYOUT_NOTES.grids} ${UNITS} With returnPrevious the answer also holds the page as it was, under previous_spreads, and a digest of each page as the write left it under page_digests (for restore_book_page expectedPages). ${WRITE_ANSWER}`,inputSchema: { journeyId: idSchema, ...editBookPageArgs },annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,when: journeyAddonOn,@@ -189,7 +189,7 @@ export class JourneyBookMcp {@Tool({name: 'set_book_cover',- description: `The cover of a journey's book: its layout (a single page template), its photo (from the journey's gallery, into a free frame, else a full bleed one behind everything), its title and its subtitle. A title or subtitle bound to the journey's own stays bound unless other words are given. With returnPrevious the answer also holds the cover as it was, under previous_spreads. ${WRITE_ANSWER}`,+ description: `The cover of a journey's book: its layout (a single page template), its photo (from the journey's gallery, into a free frame, else a full bleed one behind everything), its title and its subtitle. A title or subtitle bound to the journey's own stays bound unless other words are given. With returnPrevious the answer also holds the cover as it was, under previous_spreads, and a digest of the cover as the write left it under page_digests (for restore_book_page expectedPages). ${WRITE_ANSWER}`,inputSchema: { journeyId: idSchema, ...setBookCoverArgs },annotations: TOOL_ANNOTATIONS_WRITE,when: journeyAddonOn,@@ -261,7 +261,7 @@ export class JourneyBookMcp {@Tool({name: 'restore_book_page',- description: `Put pages of a journey's book back exactly as pages gives them, all in one call: each in its place when the book still has a page with its id, else at its index, lowest index first. Refused unless the book is still at expectedVersion, so nothing saved since is overwritten. A photo must be in the journey's gallery or already in the book, and a locked element stays as it is. This takes back an earlier change (pages is that change's previous_spreads, whole); it is not a way to edit a page. ${WRITE_ANSWER}`,+ description: `Put pages of a journey's book back exactly as pages gives them, all in one call: each in its place when the book still has a page with its id, else at its index, lowest index first. Refused unless the book is still at expectedVersion, so nothing saved since is overwritten. With expectedPages (that change's page_digests) every page they name must still be as the change left them, and when they name every page put back with a digest the version is not checked; a page put back that they leave out or name as deleted keeps the version check. A photo must be in the journey's gallery or already in the book, and a locked element stays as it is. This takes back an earlier change (pages is that change's previous_spreads, whole); it is not a way to edit a page. ${WRITE_ANSWER}`,inputSchema: { journeyId: idSchema, ...restoreBookPageArgs },annotations: TOOL_ANNOTATIONS_WRITE,when: journeyAddonOn,diff --git a/server/tests/e2e/assistant-book-cards.e2e.test.ts b/server/tests/e2e/assistant-book-cards.e2e.test.tsindex dd9474ac0..711665a3b 100644--- a/server/tests/e2e/assistant-book-cards.e2e.test.ts+++ b/server/tests/e2e/assistant-book-cards.e2e.test.ts@@ -9,11 +9,13 @@* operations, the findings), applied with a receipt card, and taken back in* one undo while nothing was saved since; an operation the engine refuses* never reaches the user; new pages are not taken back once the book moved on,- * and neither is an edited page (the restore's version check refuses it). The- * version is the whole book's, so of two book changes applied together only- * the newer one can be taken back: a known limit, pinned here. A page is- * previewed with the ops of an edit before it is proposed, nothing saved; on- * this text-only model the preview is the page's description alone.+ * and neither is an edited page once that page was saved since (the restore+ * checks the page as the change left it). A save to another page does not+ * hold an edit's undo back, so of two changes to one page applied together+ * "undo all" takes back the newer, then the older; changes apply in the order+ * the decisions name them. A page is previewed with the ops of an edit before+ * it is proposed, nothing saved; on this text-only model the preview is the+ * page's description alone.*/import { buildApp } from '../../src/bootstrap';import { withRequestContext } from '../../src/nest/database/request-context';@@ -248,6 +250,7 @@ describe('Studio book cards e2e', () => {});// The pages the answer kept for the undo never reach the model or the chat.expect(JSON.stringify(ofType(decided, 'tool-output-available'))).not.toContain('previous_spreads');+ expect(JSON.stringify(ofType(decided, 'tool-output-available'))).not.toContain('page_digests');expect((await bookOf(j)).spreads[2]?.emptyFrames).toBe(2);const undone = await undo(j.base, j.userId, held?.toolCallId ?? '');@@ -308,7 +311,7 @@ describe('Studio book cards e2e', () => {expect([after.version, after.spreads[2]?.elements]).toEqual([3, 1]);});- it('ASTBKE2E-005: of two book changes applied together, the newer is taken back and the older then answers stale', async () => {+ it('ASTBKE2E-005: of two changes to one page applied together, "undo all" takes back the newer, then the older', async () => {const j = await ownerWithBook();provider.script = [callTools(paper('call_a', j.inner, '#f4efe6'), paper('call_b', j.inner, '#e6eef4'))];const first = await stream(`${j.base}/chat`, j.userId, { ...CTX, threadId: null, text: 'Try two papers' });@@ -316,14 +319,16 @@ describe('Studio book cards e2e', () => {expect(held).toHaveLength(2);const threadId = ofType(first, 'data-trek-thread')[0]?.data.threadId ?? 0;await approve(j.base, j.userId, threadId, ...held);- expect((await bookOf(j)).version).toBe(3);+ // Applied in the order the decisions name them, which is the order they were proposed in: the second paper stays.+ const applied = await bookOf(j);+ expect([applied.version, applied.spreads[2]?.background]).toEqual([3, '#e6eef4']);- // Newest first, as "undo all" runs: the newer change goes back, the older is behind the version that left.+ // Newest first, as "undo all" runs: each restore checks only its own page, as its change left it.expect((await undo(j.base, j.userId, held[1] ?? '')).status).toBe(200);- const older = await undo(j.base, j.userId, held[0] ?? '');- expect(older.status).toBe(409);- expect(older.body).toMatchObject({ code: 'stale' });- expect((await bookOf(j)).version).toBe(4);+ expect((await bookOf(j)).spreads[2]?.background).toBe('#f4efe6');+ expect((await undo(j.base, j.userId, held[0] ?? '')).status).toBe(200);+ const after = await bookOf(j);+ expect([after.version, after.spreads[2]?.background]).toEqual([5, null]);});it('ASTBKE2E-006: a preview shows a proposed page in words, saves nothing, asks a text model no image', async () => {@@ -345,4 +350,27 @@ describe('Studio book cards e2e', () => {expect(answer?.content).toContain('Findings');expect((await bookOf(j)).version).toBe(1);});++ it('ASTBKE2E-007: an edited page is put back though another page was saved since, and that save stays', async () => {+ const j = await ownerWithBook();+ provider.script = [callTools(paper('call_bg', j.inner, '#f4efe6'))];+ const first = await stream(`${j.base}/chat`, j.userId, { ...CTX, threadId: null, text: 'Warmer paper' });+ const [held] = ofType(first, 'tool-approval-request');+ const threadId = ofType(first, 'data-trek-thread')[0]?.data.threadId ?? 0;+ await approve(j.base, j.userId, threadId, held?.toolCallId ?? '');++ // The Studio saves the first page after the change: the book's version moves on, the edited page does not.+ const firstPage = (await bookOf(j)).spreads.find((spread) => spread.role === 'first')?.id ?? 'no first page';+ const dark: BookPageOp[] = [{ op: 'background', color: '#101010' }];+ await inContext(() => books.editPage(j.journeyId, j.userId, { spreadId: firstPage, ops: dark }));+ expect((await undo(j.base, j.userId, held?.toolCallId ?? '')).status).toBe(200);+ const after = await bookOf(j);+ expect(after.version).toBe(4);+ expect(after.spreads.map((spread) => [spread.id, spread.background])).toEqual(+ expect.arrayContaining([+ [j.inner, null],+ [firstPage, '#101010'],+ ]),+ );+ });});diff --git a/server/tests/e2e/assistant-book-design.e2e.test.ts b/server/tests/e2e/assistant-book-design.e2e.test.tsindex fc2dc08c2..647d9b578 100644--- a/server/tests/e2e/assistant-book-design.e2e.test.ts+++ b/server/tests/e2e/assistant-book-design.e2e.test.ts@@ -460,8 +460,12 @@ describe('the whole-book design through the Studio chat', () => {const names = toolNames(provider.requests[0]);expect(names).toContain('get_book');for (const name of BOOK_WRITES) expect(names, name).not.toContain(name);+ // The design's reads go only to someone who may change the book, like its writes.+ for (const name of ['design_book', 'get_book_design', 'revise_book_design'])+ expect(names, name).not.toContain(name);const refused = ofType(turn.chunks, 'tool-output-error');expect(refused.map((part) => part.toolCallId)).toEqual(['call_design', 'call_apply']);+ expect(refused[0]?.errorText).toBe('Unknown tool: design_book');expect(refused[1]?.errorText).toBe('Unknown tool: apply_book_design');expect(ofType(turn.chunks, 'tool-approval-request')).toEqual([]);expect(ofType(turn.chunks, 'data-trek-change')).toEqual([]);diff --git a/server/tests/e2e/assistant-renders.e2e.test.ts b/server/tests/e2e/assistant-renders.e2e.test.tsindex ec794d114..210a97a92 100644--- a/server/tests/e2e/assistant-renders.e2e.test.ts+++ b/server/tests/e2e/assistant-renders.e2e.test.ts@@ -182,6 +182,9 @@ describe('Studio page images e2e', () => {// The friend may open the journey, but the turn is not theirs.expect((await upload({ ...base, userId: s.friendId })).status).toBe(404);expect((await upload({ ...base, userId: s.userId, threadId: 5 })).status).toBe(404);+ // A thread id that is none asks for no page, before the file is looked at.+ const noThread = await upload({ ...base, userId: s.userId, threadId: 0 });+ expect([noThread.status, noThread.body]).toEqual([404, { error: 'No page was asked for' }]);expect((await upload({ ...base, userId: s.userId, requestId: randomUUID() })).status).toBe(404);const stale = await upload({ ...base, userId: s.userId, fields: { bookVersion: '2', spreadId: 'sp-2' } });expect(stale.status).toBe(409);diff --git a/server/tests/e2e/assistant.e2e.test.ts b/server/tests/e2e/assistant.e2e.test.tsindex 97152240d..cfba0042f 100644--- a/server/tests/e2e/assistant.e2e.test.ts+++ b/server/tests/e2e/assistant.e2e.test.ts@@ -13,8 +13,9 @@* booking file attached in the chat (the extractor, an external binary, is* stubbed on the booking import), the cards a search and a weather lookup* make (the place search and the forecast are stubbed on their services), a- * found place suggested for a day without the model, mentions, an answer- * shared in the trip chat, and a vacation day held with its calendar card.+ * found place suggested for a day without the model (only with the right to+ * edit places), mentions, an answer shared in the trip chat, and a vacation+ * day held with its calendar card, applied and taken back.*/import { buildApp } from '../../src/bootstrap';import { AssistantMessages } from '../../src/db/entities/AssistantMessages.entity';@@ -39,7 +40,7 @@ import { makeCollabMessage } from '../helpers/factories/collab';import { makePlace } from '../helpers/factories/places';import { countRows, deleteRows, findRow, updateRows } from '../helpers/factories/rows';import { setAddonEnabled, setCollabFeature } from '../helpers/factories/settings';-import { makeTrip, readTripDays } from '../helpers/factories/trips';+import { addTripMember, makeTrip, readTripDays } from '../helpers/factories/trips';import { makeUser } from '../helpers/factories/users';import { spyOnRealtime, type RealtimeSpies } from '../helpers/fake-realtime';import { resetRateLimits } from '../helpers/test-db';@@ -895,6 +896,33 @@ describe('Trip assistant e2e', () => {expect(provider.requests).toHaveLength(2);});+ it('ASTE2E-024: "+ Day" asks for the right to edit places: 403 and nothing held without it, 404 outside the trip', async () => {+ const t = await travelerWithTrip();+ const { user: member } = await makeUser(orm);+ await addTripMember(orm, t.tripId, member.id);+ const [day] = await readTripDays(orm, t.tripId);+ const { threadId } = await searchTurn({ userId: member.id, base: t.base });+ const path = `${t.base}/threads/${threadId}/found-places`;++ const permissions = vi.spyOn(nestApp.get(PermissionsService), 'checkPermission');+ permissions.mockImplementation((action: string) => Promise.resolve(action !== 'place_edit'));+ try {+ const refused = await addFound(path, member.id, { ref: 'call_find:0', dayId: day.id });+ expect([refused.status, refused.body]).toEqual([403, { error: 'No permission' }]);+ expect(permissions).toHaveBeenCalledWith('place_edit', expect.any(String), t.userId, member.id, true);+ } finally {+ permissions.mockRestore();+ }+ expect(await countRows(orm, AssistantToolCalls, { thread: threadId })).toBe(0);++ const { user: stranger } = await makeUser(orm);+ const outside = await addFound(path, stranger.id, { ref: 'call_find:0', dayId: day.id });+ expect([outside.status, outside.body]).toEqual([404, { error: 'Trip not found' }]);++ // With the right, the same member holds the same place for the day.+ expect((await addFound(path, member.id, { ref: 'call_find:0', dayId: day.id })).status).toBe(200);+ });+it('ASTE2E-020: mentions reach the model as the trip names them, and the message keeps the checked ones', async () => {const t = await travelerWithTrip();const [day] = await readTripDays(orm, t.tripId);@@ -1042,7 +1070,7 @@ describe('Trip assistant e2e', () => {});});- it('ASTE2E-023: a vacation day is held on its month with the days left, applied, and told to the own tabs', async () => {+ it('ASTE2E-023: a vacation day is held on its month with the days left, applied, told to the own tabs and taken back', async () => {await setAddonEnabled(orm, 'vacay', true);const t = await travelerWithTrip();provider.script = [callTools({ id: 'call_day', name: 'toggle_vacay_entry', args: { date: '2026-06-12' } })];@@ -1069,7 +1097,7 @@ describe('Trip assistant e2e', () => {toolCallId: held.toolCallId,entity: 'vacay',ids: [],- undoUntil: null,+ undoUntil: expect.any(String),});// The applied card follows the tool's answer, which took the day as the held card foresaw.const [receipt] = ofType(decided.chunks, 'data-trek-card');@@ -1080,6 +1108,28 @@ describe('Trip assistant e2e', () => {expect(broadcasts.broadcastToUser).toHaveBeenCalledWith(t.userId, { type: 'vacay:update' }, undefined);const shown = await get(`${t.base}/threads/${threadId}`, t.userId);expect(shown.status).toBe(200);++ // The day made half a day in the planner since: the undo would not put back what was there.+ const toggle = (body: object) =>+ request(nestApp.getHttpServer())+ .post('/api/addons/vacay/entries/toggle')+ .set('Cookie', sessionCookie(t.userId))+ .send({ date: '2026-06-12', ...body });+ const undo = () =>+ request(nestApp.getHttpServer())+ .post(`${t.base}/tool-calls/${held.toolCallId}/undo`)+ .set('Cookie', sessionCookie(t.userId))+ .send({});+ expect((await toggle({ fraction: 0.5 })).body).toMatchObject({ action: 'updated', fraction: 0.5 });+ const stale = await undo();+ expect([stale.status, stale.body.code]).toEqual([409, 'stale']);+ // A whole day again, as the change left it: the undo clears it, once.+ expect((await toggle({ fraction: 1 })).body).toMatchObject({ action: 'updated', fraction: 1 });+ expect((await undo()).status).toBe(200);+ const left = await get('/api/addons/vacay/entries/2026', t.userId);+ const days = (left.body.entries as Array<{ date: string; user_id: number }>).filter((e) => e.date === '2026-06-12');+ expect(days).toEqual([]);+ expect((await undo()).body).toMatchObject({ code: 'stale' });});it('ASTE2E-ATLAS-001: a country mark is held with its flag and counter, applied with the exact count, and told to the own tabs', async () => {diff --git a/server/tests/unit/nest/assistant/assistant-book-gate.test.ts b/server/tests/unit/nest/assistant/assistant-book-gate.test.tsindex fb2f55609..4a8e2bae4 100644--- a/server/tests/unit/nest/assistant/assistant-book-gate.test.ts+++ b/server/tests/unit/nest/assistant/assistant-book-gate.test.ts@@ -1,5 +1,5 @@/**- * ASTBGATE-001 to ASTBGATE-007+ * ASTBGATE-001 to ASTBGATE-008** The book check of a Studio turn: a held book write is tried on the stored* book before the user sees it; what the engine refuses goes back to the@@ -7,8 +7,8 @@* goes back once a turn per tool and page with its findings, after which the* same call is held. Filling some of a page's empty frames and new pages laid* out on a template are not new faults. The book is read once per turn and every call tried once,- * whether the gate or its change card asks first. A book that cannot be read- * holds every call as it is.+ * whether the gate or its change card asks first. A book that cannot be read,+ * or a fault in the engine, holds every call as it is.*/import { AssistantBookGate, bounceText, openGate } from '../../../../src/nest/assistant/assistant-book-gate';import { BOOK_TRIAL_READ } from '../../../../src/nest/assistant/cards/book/book-trial';@@ -137,6 +137,29 @@ describe('the book check of a Studio turn', () => {expect(logMock.logWarn).toHaveBeenCalledWith(expect.stringContaining('Journey not found'));});+ it('ASTBGATE-008: a fault in the engine holds the call as it is, and says so in the log', async () => {+ const found = base();+ // The gallery fails as the engine reads it: a plain fault, not a refusal of the change.+ const broken = {+ ...found,+ ctx: {+ journey: found.ctx.journey,+ get photos(): never {+ throw new Error('the gallery is gone');+ },+ },+ };+ const { turn } = gateOver(broken);+ const gate = turn();+ expect(await gate.refusalOf('edit_book_page', EMPTY_FRAMES)).toBeNull();+ expect(await gate.reader.read(BOOK_TRIAL_READ, { tool: 'edit_book_page', args: EMPTY_FRAMES })).toMatchObject({+ ok: false,+ });+ expect(logMock.logWarn).toHaveBeenCalledWith(+ expect.stringContaining('the trial of edit_book_page failed: the gallery is gone'),+ );+ });+it("ASTBGATE-005: a trip conversation's gate sends nothing back and its cards read the session itself", async () => {const { session } = gateOver();const gate = openGate(session);diff --git a/server/tests/unit/nest/assistant/assistant-book-preview.test.ts b/server/tests/unit/nest/assistant/assistant-book-preview.test.tsindex 56031b615..0158b8a19 100644--- a/server/tests/unit/nest/assistant/assistant-book-preview.test.ts+++ b/server/tests/unit/nest/assistant/assistant-book-preview.test.ts@@ -52,6 +52,19 @@ describe('withPagePreview', () => {expect(viewer?.parameters).not.toHaveProperty('$defs');});+ it('ASTPVW-006: a session without edit_book_page is told of no ops, design drafts or edit tools', () => {+ const viewer = setup([]).tools.specs()[0];+ expect(viewer?.description).toContain('as it stands');+ expect(viewer?.description).not.toMatch(/edit_book_page|design_book|designId|ops/);+ const editor = setup().tools.specs()[1];+ expect(editor?.description).toContain('edit_book_page');+ expect(editor?.description).toContain('designId');+ for (const spec of [viewer, editor]) {+ expect(spec?.description).toContain(`At most ${ASSISTANT_PAGE_IMAGE.previewsPerStep} previews per step`);+ expect(spec?.description).not.toMatch(/[\u2013\u2014]/);+ }+ });+it('ASTPVW-002: the preview is a read through the vision; every other tool stays the session one', async () => {const { tools, session, vision, looked } = setup();expect(tools.kindOf('preview_book_page')).toBe('read');diff --git a/server/tests/unit/nest/assistant/assistant-proposals.service.test.ts b/server/tests/unit/nest/assistant/assistant-proposals.service.test.tsindex 553991718..d62be2adc 100644--- a/server/tests/unit/nest/assistant/assistant-proposals.service.test.ts+++ b/server/tests/unit/nest/assistant/assistant-proposals.service.test.ts@@ -167,7 +167,14 @@ describe('AssistantProposalsService', () => {start_time: '08:00',});const preview = JSON.parse(call?.preview ?? '{}') as Record<string, unknown>;- expect(preview).toMatchObject({ verbKey: 'addTour', subject: 'Herzogstand', dayId: 32, undoable: true });+ // It names the proposal it was taken from, so the chat tells which card was taken.+ expect(preview).toMatchObject({+ verbKey: 'addTour',+ subject: 'Herzogstand',+ dayId: 32,+ undoable: true,+ takenFrom: 'h1',+ });// The card the answer showed, waiting, under the name the change saves.expect(preview.card).toEqual({ ...tourRouteCard(), source: 'pending', name: 'Herzogstand' });expect(message.parts).toContainEqual(@@ -188,7 +195,7 @@ describe('AssistantProposalsService', () => {stations: WALK_RESULT.stations_for_create,});const preview = JSON.parse(call?.preview ?? '{}') as Record<string, unknown>;- expect(preview).toMatchObject({ verbKey: 'addTour', subject: 'Marienplatz → Hofgarten' });+ expect(preview).toMatchObject({ verbKey: 'addTour', subject: 'Marienplatz → Hofgarten', takenFrom: 'w1' });});it('ASTPROP-003: a call the thread does not hold, or one that proposed nothing, is not found', async () => {diff --git a/server/tests/unit/nest/assistant/assistant-scope.test.ts b/server/tests/unit/nest/assistant/assistant-scope.test.tsindex bb3315666..ad115563e 100644--- a/server/tests/unit/nest/assistant/assistant-scope.test.ts+++ b/server/tests/unit/nest/assistant/assistant-scope.test.ts@@ -30,6 +30,7 @@ import {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 { JourneyAiPhotosService } from '../../../../src/nest/journey/journey-ai-photos.service';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';@@ -108,7 +109,7 @@ function card(overrides: Partial<BookCard> = {}): BookCard {subtitle: 'Two weeks by train',role: 'editor',book: BOOK,- gallery: { photos: 120, withTime: 118, withGps: 90 },+ gallery: { photos: 120, withTime: 118, withGps: 90, own: 100 },entries: [{ id: 40, date: '2026-04-02', title: 'Alfama', place: 'Lisbon', photos: 3 }],focus: null,...overrides,@@ -168,8 +169,11 @@ describe('the tools of a Studio conversation', () => {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', () => {+ it('ASTSCP-011: keeps what works on the journey: every read, design reads and book writes only for an editor', () => {expect(keptInJourney('JourneyMcp', 'read', true, false)).toBe(true);+ expect(keptInJourney(undefined, 'read', true, false)).toBe(true);+ expect(keptInJourney('JourneyBookDesignMcp', 'read', true, false)).toBe(false);+ expect(keptInJourney('JourneyBookDesignMcp', 'read', true, true)).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);@@ -196,6 +200,11 @@ describe('the book card', () => {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.');+ // Which photos a page image may show, said as the rule: a text turn learns it too.+ expect(text).toContain('100 of them are yours; a page image shows only those');+ const gallery = { photos: 120, withTime: 118, withGps: 90 };+ expect(renderBookCard(card({ gallery: { ...gallery, own: 120 } }))).toContain('All of them are yours');+ expect(renderBookCard(card({ gallery: { ...gallery, own: 0 } }))).toContain('None of them are yours');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]/);@@ -204,7 +213,7 @@ describe('the book card', () => {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 gallery = { photos: 0, withTime: 0, withGps: 0, own: 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"');@@ -261,14 +270,27 @@ describe('the book card', () => {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');+ const prompt = studioPrompt('German', true);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');+ // A design draft names photo ids too: the plan's rows and the photos it left out.+ expect(prompt).toContain(+ 'a design draft (design_book, get_book_design, revise_book_design) or suggest_book_photos',+ );expect(prompt).not.toMatch(/[\u2013\u2014]/);+ expect(prompt).not.toContain('{photoSources}');+ // A viewer is offered none of the design's tools, so its prompt names none of them.+ const viewer = studioPrompt('German', false);+ expect(viewer).toContain('in German');+ expect(viewer).toContain('Photo ids come only from the book or suggest_book_photos.');+ for (const tool of ['design_book', 'get_book_design', 'revise_book_design', 'apply_book_design']) {+ expect(viewer, tool).not.toContain(tool);+ }+ expect(prompt.startsWith(viewer)).toBe(false);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');@@ -308,26 +330,30 @@ describe('the book context', () => {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 },+ { photo_id: 1, taken_at: '2026-04-02 10:00:00', lat: 38.71, lng: -9.13 },+ { photo_id: 2, taken_at: '2026-04-02 11:00:00', lat: null, lng: null },+ { photo_id: 3, taken_at: null, lat: 38.7, lng: null },]),};+ // The user's own: photo 1 of the gallery, and 99, a video of theirs the facts leave out.+ const aiPhotos = { ownPhotoIds: vi.fn(async () => new Set([1, 99])) };const context = new AssistantBookContext(journeys as unknown as JourneyDomainService,books as unknown as JourneyBookEditService,photos as unknown as PhotoSignalsService,+ aiPhotos as unknown as JourneyAiPhotosService,);- return { journeys, books, photos, context };+ return { journeys, books, photos, aiPhotos, 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 { books, journeys, photos, aiPhotos, 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(aiPhotos.ownPhotoIds).toHaveBeenCalledWith(12, 7);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.gallery).toEqual({ photos: 3, withTime: 2, withGps: 1, own: 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.@@ -408,7 +434,7 @@ describe('a scope opens its session and writes its turn', () => {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.system).toBe(studioPrompt('English', true));expect(read.context).toContain('<book_card>');expect(read.card.tripId).toBe(0);expect(session.read).not.toHaveBeenCalled();@@ -417,8 +443,11 @@ describe('a scope opens its session and writes its turn', () => {expect(read.gate).toBe(editor.studioGate);const viewer = scopesWith(false);- await viewer.scopes.open(7, { kind: 'journey', journeyId: 12 }, targets);+ const viewing = await viewer.scopes.open(7, { kind: 'journey', journeyId: 12 }, targets);expect(viewer.tools.openJourney).toHaveBeenCalledWith(7, 12, false, targets);+ // A viewer's turn reads the instructions without the designer's rules.+ const viewed = await viewer.scopes.turnOf(viewing, { kind: 'journey', journeyId: 12 }, turn);+ expect(viewed.system).toBe(studioPrompt('English', false));});it('ASTSCP-052: the trip card is read through the session, or on a session of its own two reads', async () => {diff --git a/server/tests/unit/nest/assistant/assistant.controller.test.ts b/server/tests/unit/nest/assistant/assistant.controller.test.tsindex e714d628a..79bef8e56 100644--- a/server/tests/unit/nest/assistant/assistant.controller.test.ts+++ b/server/tests/unit/nest/assistant/assistant.controller.test.ts@@ -150,11 +150,12 @@ describe('AssistantController', () => {expect(() => controller.addFoundPlace(user, '5', 'x', body)).toThrow(DomainError);});- it('ASTCTL-008: sharing asks for the trip chat right, "Plan this" for editing places; nothing else asks', () => {+ it('ASTCTL-008: sharing asks for the trip chat right, "Plan this" and "+ Day" for editing places; nothing else asks', () => {const handlers = AssistantController.prototype as unknown as Record<string, object>;expect(Reflect.getMetadata(TRIP_PERMISSION_KEY, handlers.share)).toBe('collab_edit');expect(Reflect.getMetadata(TRIP_PERMISSION_KEY, handlers.takeProposal)).toBe('place_edit');- for (const name of ['chat', 'decide', 'undo', 'addFoundPlace']) {+ expect(Reflect.getMetadata(TRIP_PERMISSION_KEY, handlers.addFoundPlace)).toBe('place_edit');+ for (const name of ['chat', 'decide', 'undo']) {expect(Reflect.getMetadata(TRIP_PERMISSION_KEY, handlers[name]), name).toBeUndefined();}});diff --git a/server/tests/unit/nest/assistant/cards/book-design/book-design-cards.test.ts b/server/tests/unit/nest/assistant/cards/book-design/book-design-cards.test.tsindex 916719206..654a74331 100644--- a/server/tests/unit/nest/assistant/cards/book-design/book-design-cards.test.ts+++ b/server/tests/unit/nest/assistant/cards/book-design/book-design-cards.test.ts@@ -222,13 +222,13 @@ describe('the book-level changes', () => {describe('the designer in the Studio', () => {it('ASTBD-008: the Studio instructions end with the design rules, cache-stable and without dashes', () => {- const prompt = studioPrompt('German');+ const prompt = studioPrompt('German', true);expect(prompt.endsWith(BOOK_DESIGN_PROMPT)).toBe(true);expect(BOOK_DESIGN_PROMPT.split('\n').length).toBeLessThanOrEqual(14);for (const tool of ['design_book', 'revise_book_design', 'apply_book_design', 'preview_book_page']) {expect(BOOK_DESIGN_PROMPT).toContain(tool);}expect(BOOK_DESIGN_PROMPT).not.toMatch(/[\u2013\u2014]/);- expect(studioPrompt('German')).toBe(prompt);+ expect(studioPrompt('German', true)).toBe(prompt);});});diff --git a/server/tests/unit/nest/assistant/cards/book/book-cards.test.ts b/server/tests/unit/nest/assistant/cards/book/book-cards.test.tsindex 7110d4ee1..dba71c1ee 100644--- a/server/tests/unit/nest/assistant/cards/book/book-cards.test.ts+++ b/server/tests/unit/nest/assistant/cards/book/book-cards.test.ts@@ -369,7 +369,7 @@ describe('the receipt and the way back', () => {expect(receipt(full, 3)).toMatchObject({ moreFindings: 34 });});- it('ASTCARD-BKPG-009: edits, the cover and deletes go back by restore at their version; new pages and moves while unmoved', () => {+ it('ASTCARD-BKPG-009: edits and the cover go back by restore checking their pages, deletes at their version; new pages and moves while unmoved', () => {const previous = [{ index: 2, spread: book().spreads[2] }];const result = { version: 4, spread_ids: ['sp-3'], previous_spreads: previous };for (const tool of ['edit_book_page', 'set_book_cover', 'delete_book_pages']) {@@ -382,6 +382,27 @@ describe('the receipt and the way back', () => {// The pages kept for the undo never reach the model or the chat.expect(toolOutputForProvider(tool, result)).toEqual({ version: 4, spread_ids: ['sp-3'] });}+ // With the digest of every page it puts back, the restore checks those pages only, not the book's version.+ const digests = [{ spreadId: 'sp-3', digest: '0123456789abcdef' }];+ const digested = { ...result, page_digests: digests };+ for (const tool of ['edit_book_page', 'set_book_cover']) {+ expect(ASSISTANT_UNDO_MAP[tool]?.args({}, digested, null), tool).toEqual({+ pages: previous,+ expectedVersion: 4,+ expectedPages: digests,+ });+ // The digests stay with the undo too: neither the model nor the chat sees them.+ expect(toolOutputForProvider(tool, digested)).toEqual({ version: 4, spread_ids: ['sp-3'] });+ }+ // A deleted page has no digest, and digests that miss a page leave the version to guard the restore.+ const deleted = { ...result, page_digests: [{ spreadId: 'sp-3', digest: null }] };+ expect(ASSISTANT_UNDO_MAP.delete_book_pages?.args({}, deleted, null)).toEqual({+ pages: previous,+ expectedVersion: 4,+ });+ const partial = { ...result, page_digests: [{ spreadId: 'sp-9', digest: '0123456789abcdef' }, 'odd'] };+ expect(ASSISTANT_UNDO_MAP.edit_book_page?.args({}, partial, null)).toEqual({ pages: previous, expectedVersion: 4 });+ expect(toolOutputForProvider('edit_book_page', { version: 4, page_digests: digests })).toEqual({ version: 4 });// The undo of new pages and of a move names the version the change left, so a save since refuses it.expect(ASSISTANT_UNDO_MAP.add_book_pages?.args({}, { version: 4, spread_ids: ['sp-x', 'sp-y'] }, null)).toEqual({spreadIds: ['sp-x', 'sp-y'],diff --git a/server/tests/unit/nest/assistant/cards/collection/collection-applied.test.ts b/server/tests/unit/nest/assistant/cards/collection/collection-applied.test.tsindex b3025b3f2..64f085893 100644--- a/server/tests/unit/nest/assistant/cards/collection/collection-applied.test.ts+++ b/server/tests/unit/nest/assistant/cards/collection/collection-applied.test.ts@@ -1,14 +1,15 @@/**- * ASTCOL-040 to ASTCOL-048: what an applied change of the collections shows- * in place of its preview, what its receipt names, and the way back from a- * created list or a saved place.+ * ASTCOL-040 to ASTCOL-049: what an applied change of the collections shows+ * in place of its preview, what its receipt names (the new places of a copy+ * only on the chat's own trip, the list a held card showed), and the way back+ * from a created list or a saved place.*/import { unchangedSinceApplied } from '../../../../../../src/nest/assistant/assistant-undo.helpers';import { readKey } from '../../../../../../src/nest/assistant/cards/card-values';import type { CollectionLookup } from '../../../../../../src/nest/assistant/cards/collection/collection-load';import { appliedCardOf, ASSISTANT_UNDO_MAP, undoReadsOf } from '../../../../../../src/nest/assistant/cards/registry';import { appliedChange, describeToolCall } from '../../../../../../src/nest/assistant/tool-call-preview.helpers';-import { collectionValue, ctx, itemsValue, savedPlace } from './collection-fixtures';+import { collectionValue, ctx, itemsValue, savedPlace, TRIP_ID } from './collection-fixtures';import type { CollectionListsCard, CollectionPlacesCard } from '@trek/shared';import { describe, expect, it, vi } from 'vitest';@@ -121,7 +122,7 @@ describe('applied collection cards', () => {it('ASTCOL-045: a receipt names a list, a saved place, or the new trip places of a copy', () => {const receipt = (tool: string, args: Record<string, unknown>, result: unknown) =>- appliedChange(tool, 'c', args, result, null, null);+ appliedChange(tool, 'c', args, result, null, null, { preview: null, tripId: TRIP_ID });const made = receipt('create_collection', { name: 'Rome' }, { collection: { id: 44 } });expect(made).toMatchObject({ entity: 'collection', ids: [44] });expect(receipt('save_place_to_collection', SAVE, { place: { id: 77 } })).toMatchObject({@@ -142,6 +143,35 @@ describe('applied collection cards', () => {expect(kept).toMatchObject({ entity: 'collection', ids: [12] });});+ it('ASTCOL-049: a copy into another trip names no places, and a change shown in one list names that list', () => {+ const created = [{ id: 950, source_id: 34 }];+ const copy = (tripId: number | null, into: number) => {+ const args = { trip_id: into, place_ids: [34] };+ const chat = { preview: null, tripId };+ return appliedChange('copy_collection_places_to_trip', 'c', args, { created }, null, null, chat)?.ids;+ };+ expect(copy(TRIP_ID, TRIP_ID)).toEqual([950]);+ // The map shows the chat's trip, where the places of another trip are not; a Studio chat has no trip.+ expect(copy(TRIP_ID, 8)).toEqual([]);+ expect(copy(null, TRIP_ID)).toEqual([]);++ // The held card showed the labels on Septime in list 12: the receipt opens that list.+ const labelled = { label_ids: [53], place_ids: [34] };+ const preview = previewOf('assign_collection_labels', labelled, { items: itemsValue([savedPlace()]) });+ const from = { preview, tripId: TRIP_ID };+ const receipt = appliedChange('assign_collection_labels', 'c', labelled, { success: true }, null, null, from);+ expect(receipt).toMatchObject({ entity: 'collection', ids: [12] });+ // Without the held card, or set across every list, the receipt names no list.+ expect(appliedChange('assign_collection_labels', 'c', labelled, {}, null, null)?.ids).toEqual([]);+ const marked = { trip_id: TRIP_ID, place_ids: [5], status: 'visited' };+ const across = previewOf('set_collection_place_status_from_trip', marked, {});+ const set = appliedChange('set_collection_place_status_from_trip', 'c', marked, {}, null, null, {+ preview: across,+ tripId: TRIP_ID,+ });+ expect(set?.ids).toEqual([]);+ });+it('ASTCOL-046: a created list is taken back while it is empty, unshared and unchanged', () => {const result = { collection: { id: 44, name: 'Rome', color: '#6366f1', updated_at: '2026-06-01 10:00:00' } };expect(ASSISTANT_UNDO_MAP.create_collection?.tool).toBe('delete_collection');diff --git a/server/tests/unit/nest/assistant/cards/registry-guards.test.ts b/server/tests/unit/nest/assistant/cards/registry-guards.test.tsindex a9da905f2..9112a87ca 100644--- a/server/tests/unit/nest/assistant/cards/registry-guards.test.ts+++ b/server/tests/unit/nest/assistant/cards/registry-guards.test.ts@@ -40,6 +40,20 @@ vi.mock('../../../../../src/nest/assistant/cards/vacay', () => {undo: { tool: 'delete_probe', args: boom, reads: boom, unchanged: boom },},list_probe: { appliedIds: () => [3, 0, -1, 2.5, 'x'] },+ // Names an id only from what the receipt is read with: the stored preview and the chat's trip.+ from_probe: {+ appliedIds: (_args: unknown, _result: unknown, from: { preview: unknown; tripId: number | null }) =>+ from.preview && from.tripId === 5 ? [11] : [],+ },+ // Tells the undo the call's own arguments are still what it reads.+ call_probe: {+ undo: {+ tool: 'delete_probe',+ args: () => ({}),+ unchanged: (_result: unknown, _snapshot: unknown, call: { args: Record<string, unknown> }) =>+ call.args.date === '2026-06-12',+ },+ },},},};@@ -80,6 +94,18 @@ describe('the guarded package hooks', () => {]);});+ it("ASTREG-034: the preview and the trip reach a package's receipt ids, and the call its undo check", () => {+ const preview = describeToolCall('create_place', 'c3', { name: 'Lake' }, ctx);+ expect(appliedChange('from_probe', 'c3', {}, {}, null, null, { preview, tripId: 5 })?.ids).toEqual([11]);+ expect(appliedChange('from_probe', 'c3', {}, {}, null, null)?.ids).toEqual([]);+ const snapshot = { summary: {}, places: {} };+ const call = { args: { date: '2026-06-12' }, preview: null };+ expect(unchangedSinceApplied('call_probe', {}, snapshot, call)).toBe(true);+ // Without the call the check reads empty arguments, as the core's own checks do.+ expect(unchangedSinceApplied('call_probe', {}, snapshot)).toBe(false);+ expect(logged()).toEqual([]);+ });+it('ASTREG-033: a projection that throws hands the provider the answer as it came', () => {expect(toolOutputForProvider('plan_probe', { days: 3 })).toEqual({ days: 3 });expect(logged()[0]).toContain('the projection of plan_probe failed: boom');diff --git a/server/tests/unit/nest/assistant/cards/vacay/vacay-cards.test.ts b/server/tests/unit/nest/assistant/cards/vacay/vacay-cards.test.tsindex 4ce30dd4c..c7fab6194 100644--- a/server/tests/unit/nest/assistant/cards/vacay/vacay-cards.test.ts+++ b/server/tests/unit/nest/assistant/cards/vacay/vacay-cards.test.ts@@ -2,25 +2,29 @@* The vacation planner's cards: what a held day off looks up first, what it* would do to the day (taken, given back, changed, refused) and to the days* left, the company holiday and the new allowance, the applied card against- * what the tool says it did, and the answer cards of the planner's reads,- * each checked against the card union.+ * what the tool says it did, the way back from a toggled day while it is as+ * the change left it, and the answer cards of the planner's reads, each+ * checked against the card union.*/import { buildTripCard } from '../../../../../../src/nest/assistant/assistant-context';-import type { CardReader, PreviewContext } from '../../../../../../src/nest/assistant/cards/card-types';+import { unchangedSinceApplied } from '../../../../../../src/nest/assistant/assistant-undo.helpers';+import type { CardReader, PreviewContext, UndoSnapshot } from '../../../../../../src/nest/assistant/cards/card-types';import { readKey } from '../../../../../../src/nest/assistant/cards/card-values';import {answerCardOf,appliedCardOf,+ ASSISTANT_UNDO_MAP,ASSISTANT_WRITE_TOOLS,CARD_PROMPT_LINES,changeCardOf,TOOL_CARDS,+ undoReadsOf,} from '../../../../../../src/nest/assistant/cards/registry';import { VACAY_CARDS } from '../../../../../../src/nest/assistant/cards/vacay';import { loadDay, loadStats, type VacayLoaded } from '../../../../../../src/nest/assistant/cards/vacay/vacay-load';import { entriesOf, holidaysOf, planOf, statsOf } from '../../../../../../src/nest/assistant/cards/vacay/vacay-reads';import { appliedChange, describeToolCall } from '../../../../../../src/nest/assistant/tool-call-preview.helpers';-import { trekCardSchema, VACAY_CARD_MAX_DAYS, type VacayCard } from '@trek/shared';+import { trekCardSchema, VACAY_CARD_MAX_DAYS, type AssistantChangePreview, type VacayCard } from '@trek/shared';import { describe, expect, it } from 'vitest';@@ -375,6 +379,11 @@ describe('a held day off', () => {expect(remove.card?.kind).toBe('vacay');const convert = describeToolCall('toggle_vacay_entry', 'v2', { date: '2026-10-27' }, ctx, found);expect(convert.verbKey).toBe('changeVacationDay');+ // A day added or converted has a way back (ASTVAC-015), a day cleared none, nor a call whose lookup failed.+ const add = describeToolCall('toggle_vacay_entry', 'v4', { date: '2026-10-28' }, ctx, found);+ expect(add).toMatchObject({ verbKey: 'addVacationDay', undoable: true });+ expect(convert.undoable).toBe(true);+ expect(remove.undoable).toBe(false);const bare = describeToolCall('toggle_vacay_entry', 'v3', { date: '2026-10-26' }, ctx, null);expect(bare).toMatchObject({ verbKey: 'addVacationDay', subject: 'Mon, Oct 26', undoable: false });expect(bare.card).toBeUndefined();@@ -430,6 +439,90 @@ describe('a held day off', () => {});});+describe('the way back from a day off', () => {+ const ADDED = { action: 'added', fraction: 1, kind: 'vacation' };+ /** What a toggle answers when it converted a day to a whole vacation day. */+ const CONVERTED = { action: 'updated', fraction: 1, kind: 'vacation' };+ const undoArgs = (args: Record<string, unknown>, result: unknown, preview: AssistantChangePreview | null) =>+ ASSISTANT_UNDO_MAP.toggle_vacay_entry?.args(args, result, preview);++ it('ASTVAC-015: an added day is cleared and a converted one set back, for the person held; a cleared day stays', async () => {+ const found = await loaded();+ const held = (args: Record<string, unknown>) => describeToolCall('toggle_vacay_entry', 'v1', args, ctx, found);+ const day = { date: '2026-10-28' };+ expect(undoArgs(day, ADDED, held(day))).toEqual({+ date: '2026-10-28',+ fraction: 1,+ kind: 'vacation',+ targetUserId: ANA,+ });+ const ben = { date: '2026-10-28', targetUserId: BEN, kind: 'comp' };+ expect(undoArgs(ben, { action: 'added', fraction: 1, kind: 'comp' }, held(ben))).toEqual({+ date: '2026-10-28',+ fraction: 1,+ kind: 'comp',+ targetUserId: BEN,+ });+ // Ana's half day made whole goes back to half a day.+ const half = { date: '2026-10-27' };+ expect(undoArgs(half, CONVERTED, held(half))).toEqual({+ date: '2026-10-27',+ fraction: 0.5,+ kind: 'vacation',+ targetUserId: ANA,+ });+ // Cleared, done otherwise than the card foresaw, without the card or on another day: no way back.+ const full = { date: '2026-10-26' };+ expect(undoArgs(full, { action: 'removed' }, held(full))).toBeNull();+ expect(undoArgs(day, CONVERTED, held(day))).toBeNull();+ expect(undoArgs(half, { action: 'updated', fraction: 1, kind: 'comp' }, held(half))).toBeNull();+ expect(undoArgs(half, ADDED, held(half))).toBeNull();+ expect(undoArgs(day, ADDED, null)).toBeNull();+ expect(undoArgs({ date: '2026-10-29' }, ADDED, held(day))).toBeNull();+ expect(undoArgs(day, { action: 'added', fraction: 2, kind: 'vacation' }, held(day))).toBeNull();+ expect(undoReadsOf('toggle_vacay_entry', day, ADDED)).toEqual([+ { tool: 'get_vacay_entries', args: { year: 2026 } },+ { tool: 'get_vacay_entries', args: { year: 2025 } },+ ]);+ });++ it('ASTVAC-016: the undo runs only while the day is as the change left it and the toggle back does just that', async () => {+ const found = await loaded();+ const day = { date: '2026-10-28' };+ const call = { args: day, preview: describeToolCall('toggle_vacay_entry', 'v1', day, ctx, found) };+ const none = { entries: { entries: [], companyHolidays: [] } };+ const snapshot = (rows: unknown[], company: unknown[] = [], earlier: unknown = none): UndoSnapshot => ({+ summary: null,+ places: null,+ reads: new Map([+ [readKey('get_vacay_entries', { year: 2026 }), { entries: { entries: rows, companyHolidays: company } }],+ [readKey('get_vacay_entries', { year: 2025 }), earlier],+ ]),+ });+ const check = (result: unknown, snap: UndoSnapshot, made = call) =>+ unchangedSinceApplied('toggle_vacay_entry', result, snap, made);+ expect(check(ADDED, snapshot([entry(ANA, '2026-10-28')]))).toBe(true);+ // The grid of the year before can show the day too: it is read there as well.+ const before = { entries: { entries: [entry(ANA, '2026-10-28')], companyHolidays: [] } };+ expect(check(ADDED, snapshot([], [], before))).toBe(true);+ // Changed by hand, cleared, or only someone else's day: changed since.+ expect(check(ADDED, snapshot([entry(ANA, '2026-10-28', 0.5)]))).toBe(false);+ expect(check(ADDED, snapshot([entry(BEN, '2026-10-28')]))).toBe(false);+ expect(check(ADDED, snapshot([]))).toBe(false);+ // Half a company holiday since makes every toggle half a day: a whole day is not cleared that way.+ const halfCompany = (date: string) => [{ date, fraction: 0.5 }];+ expect(check(ADDED, snapshot([entry(ANA, '2026-10-28')], halfCompany('2026-10-28')))).toBe(false);+ // A read that failed, or no call to tell the day by, reads as changed since.+ expect(check(ADDED, snapshot([entry(ANA, '2026-10-28')], [], null))).toBe(false);+ expect(unchangedSinceApplied('toggle_vacay_entry', ADDED, snapshot([entry(ANA, '2026-10-28')]))).toBe(false);+ expect(TOOL_CARDS.toggle_vacay_entry?.undo?.unchanged(ADDED, snapshot([entry(ANA, '2026-10-28')]))).toBe(false);+ // Half a day set back on half a company holiday is just what the toggle does there.+ const half = { date: '2026-10-27' };+ const converted = { args: half, preview: describeToolCall('toggle_vacay_entry', 'v2', half, ctx, found) };+ expect(check(CONVERTED, snapshot([entry(ANA, '2026-10-27')], halfCompany('2026-10-27')), converted)).toBe(true);+ });+});+describe('a held company holiday and allowance', () => {it('ASTVAC-020: a whole company holiday gives back what was logged that day, a half one half of a whole day', async () => {const found = await loaded();@@ -474,14 +567,16 @@ describe('a held company holiday and allowance', () => {});});- it('ASTVAC-022: the package registers its writes, reads and one prompt line, and no undo', () => {+ it('ASTVAC-022: the package registers its writes, reads, one prompt line and the way back of a toggle only', () => {expect(ASSISTANT_WRITE_TOOLS.toggle_vacay_entry).toEqual({ verbKey: 'addVacationDay', entity: 'vacay' });expect(ASSISTANT_WRITE_TOOLS.toggle_company_holiday?.verbKey).toBe('setCompanyHoliday');expect(ASSISTANT_WRITE_TOOLS.update_vacay_stats?.verbKey).toBe('setVacationAllowance');for (const tool of ['get_vacay_entries', 'get_vacay_stats', 'list_holidays']) {expect(TOOL_CARDS[tool]?.answer, tool).toBeTypeOf('function');}- expect(TOOL_CARDS.toggle_vacay_entry?.undo).toBeUndefined();+ expect(TOOL_CARDS.toggle_vacay_entry?.undo?.tool).toBe('toggle_vacay_entry');+ expect(TOOL_CARDS.toggle_company_holiday?.undo).toBeUndefined();+ expect(TOOL_CARDS.update_vacay_stats?.undo).toBeUndefined();expect(TOOL_CARDS.toggle_vacay_entry?.applied).toBeTypeOf('function');expect(TOOL_CARDS.toggle_company_holiday?.applied).toBeTypeOf('function');expect(CARD_PROMPT_LINES).toContain(VACAY_CARDS.prompt?.[0]);diff --git a/server/tests/unit/nest/assistant/tool-call-preview.helpers.test.ts b/server/tests/unit/nest/assistant/tool-call-preview.helpers.test.tsindex 1e1a81db3..eb1b60df7 100644--- a/server/tests/unit/nest/assistant/tool-call-preview.helpers.test.ts+++ b/server/tests/unit/nest/assistant/tool-call-preview.helpers.test.ts@@ -594,6 +594,21 @@ describe('the cards of tours', () => {);expect(applied).toMatchObject({ entity: 'place', ids: [77] });expect(appliedChange('create_place', 'tc', {}, { place: { id: 5 } }, null, null)).toMatchObject({ ids: [5] });+ // The hook reads what the receipt is made with: the stored preview and the trip of the chat, or none of them.+ const preview = describe_('create_place', { name: 'Kinkaku-ji' });+ const seen: unknown[] = [];+ const hook = (_args: unknown, _result: unknown, from: unknown): number[] => {+ seen.push(from);+ return [];+ };+ withCards('create_place', { appliedIds: hook }, null, () => {+ appliedChange('create_place', 'tc', {}, {}, null, null, { preview, tripId: 1 });+ return appliedChange('create_place', 'tc', {}, {}, null, null);+ });+ expect(seen).toEqual([+ { preview, tripId: 1 },+ { preview: null, tripId: null },+ ]);});it('ASTPRV-031: a package names its ids first; a place id of a tool outside the trip is no trip place', () => {diff --git a/server/tests/unit/nest/journey-book-edit.service.test.ts b/server/tests/unit/nest/journey-book-edit.service.test.tsindex 8898d83e4..0ab65c5f6 100644--- a/server/tests/unit/nest/journey-book-edit.service.test.ts+++ b/server/tests/unit/nest/journey-book-edit.service.test.ts@@ -12,9 +12,11 @@* gallery; `previous_spreads` comes back only when asked for; a move answers* where the page stood and a move to where it is writes nothing; a restore* lands only at the version it names, all the pages of one delete at once,- * held to the gallery like an edit; and a move or a delete that names a- * version (the assistant's undo) lands only there too. A held change is tried on the stored book- * with the journey's gallery and entries, read with a member's rights.+ * held to the gallery like an edit, or, naming the pages' digests the change+ * answered, only while those pages are as it left them; and a move or a+ * delete that names a version (the assistant's undo) lands only there too. A+ * held change is tried on the stored book with the journey's gallery and+ * entries, read with a member's rights.*/import { JourneyPhotos } from '../../../src/db/entities/JourneyPhotos.entity';import { TrekPhotos } from '../../../src/db/entities/TrekPhotos.entity';@@ -456,4 +458,73 @@ describe('adding, moving, deleting and restoring pages', () => {const gone = await edit.deletePages(journey.id, owner.id, { spreadIds: [fresh], expectedVersion: moved.version });expect(gone.version).toBe(moved.version + 1);});++ it('JBEDIT-015: a restore naming expectedPages checks those pages only: another page saved since lets it land, the page itself not', async () => {+ const { journey, owner, inner, first } = await crew();+ const edited = await edit.editPage(journey.id, owner.id, {+ spreadId: inner,+ ops: [{ op: 'background', color: '#f4efe6' }],+ returnPrevious: true,+ });+ const pages = edited.previous_spreads ?? [];+ const expectedPages = edited.page_digests ?? [];+ expect(expectedPages).toEqual([{ spreadId: inner, digest: expect.stringMatching(/^[0-9a-f]{16}$/) }]);+ const dark = await edit.editPage(journey.id, owner.id, {+ spreadId: first,+ ops: [{ op: 'background', color: '#101010' }],+ returnPrevious: true,+ });+ expect(dark.page_digests).toEqual([{ spreadId: first, digest: expect.stringMatching(/^[0-9a-f]{16}$/) }]);++ // The book moved on with the first page, the edited page did not: the version refuses, the page lets it land.+ const byVersion = () => edit.restorePage(journey.id, owner.id, { pages, expectedVersion: edited.version });+ expect(await refusal(byVersion)).toMatchObject({ status: 409, code: 'book_conflict' });+ // Digests that leave out a page put back do not stand in for the version, even while they hold.+ const others = () =>+ edit.restorePage(journey.id, owner.id, {+ pages,+ expectedVersion: edited.version,+ expectedPages: dark.page_digests ?? [],+ });+ expect(await refusal(others)).toMatchObject({ status: 409, code: 'book_conflict' });+ const byPage = () =>+ edit.restorePage(journey.id, owner.id, { pages, expectedVersion: edited.version, expectedPages });+ expect(firstPage(await byPage())).toMatchObject({ id: inner, background: null });+ const kept = await edit.overview(journey.id, owner.id);+ expect(kept.spreads.find((s) => s.id === first)?.background).toBe('#101010');++ // Once the page itself was saved since, the same restore is refused: nothing written, nothing sent.+ const again = await edit.editPage(journey.id, owner.id, {+ spreadId: inner,+ ops: [{ op: 'background', color: '#222222' }],+ });+ expect(again).not.toHaveProperty('page_digests');+ const version = (await edit.overview(journey.id, owner.id)).version;+ t.realtime.reset();+ expect(await refusal(byPage)).toMatchObject({ status: 409, code: 'book_conflict' });+ expect((await edit.overview(journey.id, owner.id)).version).toBe(version);+ expect(sent()).toEqual([]);++ // A page the change took out has no digest; one named with a digest refuses, whatever the version says.+ const gone = await edit.deletePages(journey.id, owner.id, { spreadIds: [inner], returnPrevious: true });+ expect(gone.page_digests).toEqual([{ spreadId: inner, digest: null }]);+ const restore = (expected: Array<{ spreadId: string; digest: string | null }>, expectedVersion: number) =>+ edit.restorePage(journey.id, owner.id, {+ pages: gone.previous_spreads ?? [],+ expectedVersion,+ expectedPages: expected,+ });+ const named = [{ spreadId: inner, digest: '0123456789abcdef' }];+ expect(await refusal(() => restore(named, 0))).toMatchObject({ status: 409, code: 'book_conflict' });+ // A page named as gone goes back at its old index, which means the same only at the version: a stale one refuses.+ const asGone = [{ spreadId: inner, digest: null }];+ expect(await refusal(() => restore(asGone, 0))).toMatchObject({ status: 409, code: 'book_conflict' });+ // A page named as gone that is still in the book refuses even at the version.+ const stillThere = [...asGone, { spreadId: first, digest: null }];+ expect(await refusal(() => restore(stillThere, gone.version))).toMatchObject({+ status: 409,+ code: 'book_conflict',+ });+ expect(firstPage(await restore(asGone, gone.version))).toMatchObject({ id: inner, index: 2 });+ });});diff --git a/shared/src/assistant/assistant.schema.spec.ts b/shared/src/assistant/assistant.schema.spec.tsindex 3f67e5fa1..9c56aac3a 100644--- a/shared/src/assistant/assistant.schema.spec.ts+++ b/shared/src/assistant/assistant.schema.spec.ts@@ -132,6 +132,13 @@ describe('assistantChangePreviewSchema', () => {expect(assistantChangePreviewWriteSchema.safeParse({ ...preview, card: { kind: 'nope' } }).success).toBe(false);});+ it('names the proposal a taken change came from by its call id, bounded like the take request', () => {+ expect(assistantChangePreviewWriteSchema.parse({ ...preview, takenFrom: 'call_hike' }).takenFrom).toBe('call_hike');+ expect(assistantChangePreviewSchema.parse(preview).takenFrom).toBeUndefined();+ expect(assistantChangePreviewWriteSchema.safeParse({ ...preview, takenFrom: '' }).success).toBe(false);+ expect(assistantChangePreviewWriteSchema.safeParse({ ...preview, takenFrom: 'c'.repeat(65) }).success).toBe(false);+ });+it('holds at most twelve rows', () => {const rows = ASSISTANT_CHANGE_LABEL_KEYS.slice(0, 13).map((labelKey) => ({op: 'add',diff --git a/shared/src/assistant/assistant.schema.ts b/shared/src/assistant/assistant.schema.tsindex 7424f9b68..65443a4f5 100644--- a/shared/src/assistant/assistant.schema.ts+++ b/shared/src/assistant/assistant.schema.ts@@ -356,6 +356,8 @@ export const assistantChangePreviewWriteSchema = z.object({domain: z.string().max(40).optional(),// What the change will do, drawn as a card; absent on older rows and on cards without one.card: trekCardSchema.nullable().optional(),+ // The proposal a change held by "Plan this" was taken from (its call id); absent on every other change.+ takenFrom: assistantTakeProposalRequestSchema.shape.toolCallId.optional(),});/**diff --git a/shared/src/book/book-element-ops.schema.ts b/shared/src/book/book-element-ops.schema.tsindex 61db44f97..1657ad665 100644--- a/shared/src/book/book-element-ops.schema.ts+++ b/shared/src/book/book-element-ops.schema.ts@@ -72,8 +72,8 @@ const PHOTO_PROPS = {filter: photo.filter.unwrap().optional(),radius: z.number().finite().min(0).max(500).optional(),};-const TEXT_PROPS = {- ...COMMON,+/** How a text is set, each field left as it is when not named: the style op's and the page edit's text op's. */+export const TEXT_STYLE_FIELDS = {font: text.font.unwrap().optional(),size: text.size.unwrap().optional(),weight: text.weight.unwrap().optional(),@@ -83,6 +83,7 @@ const TEXT_PROPS = {tracking: text.tracking.unwrap().optional(),color: text.color.unwrap().optional(),};+const TEXT_PROPS = { ...COMMON, ...TEXT_STYLE_FIELDS };const SHAPE_PROPS = {...COMMON,fill: shape.fill.unwrap().optional(),diff --git a/shared/src/book/book-ops.schema.ts b/shared/src/book/book-ops.schema.tsindex 16d3de28f..235e77aa6 100644--- a/shared/src/book/book-ops.schema.ts+++ b/shared/src/book/book-ops.schema.ts@@ -1,5 +1,5 @@import { idSchema } from '../common/primitives.schema';-import { BOOK_ELEMENT_OP_SCHEMAS, bindingNamesItsSource } from './book-element-ops.schema';+import { BOOK_ELEMENT_OP_SCHEMAS, TEXT_STYLE_FIELDS, bindingNamesItsSource } from './book-element-ops.schema';import { BOOK_COVER_TEMPLATES, BOOK_TEMPLATES } from './book-layouts';import { bookElementIdSchema, bookGridIdSchema, bookSpreadIdSchema } from './book-op-ids';import {@@ -141,14 +141,7 @@ export const bookPageOpSchema = z.discriminatedUnion('op', [role: z.enum(['heading', 'body', 'meta']).optional(),text: z.string().max(BOOK_OP_LIMITS.text).optional(),binding: text.binding.unwrap().optional(),- font: text.font.unwrap().optional(),- size: text.size.unwrap().optional(),- weight: text.weight.unwrap().optional(),- italic: text.italic.unwrap().optional(),- align: text.align.unwrap().optional(),- leading: text.leading.unwrap().optional(),- tracking: text.tracking.unwrap().optional(),- color: text.color.unwrap().optional(),+ ...TEXT_STYLE_FIELDS,}).refine((v) => v.elementId !== undefined || v.role !== undefined, { message: 'name an elementId or a role' }).refine((v) => bindingNamesItsSource(v.binding), {@@ -250,13 +243,34 @@ export const bookPreviousSpreadSchema = z.object({});export type BookPreviousSpread = z.infer<typeof bookPreviousSpreadSchema>;+/**+ * A page as a write left it, for the assistant's undo: its id and a digest of+ * the page as the book stores it, which the write answered under+ * `page_digests` (with `returnPrevious`). A null digest names a page the+ * write took out of the book.+ */+export const bookPageDigestSchema = z.strictObject({+ spreadId: bookSpreadIdSchema,+ digest: z+ .string()+ .regex(/^[0-9a-f]{16}$/)+ .nullable(),+});+export type BookPageDigest = z.infer<typeof bookPageDigestSchema>;+/*** The pages a write answered under `previous_spreads`, put back in one call- * (several deleted pages are one undo), lowest index first.+ * (several deleted pages are one undo), lowest index first. The book must+ * still be at `expectedVersion`. Every page `expectedPages` names must still+ * be as its digest says, and only when they name every page put back with a+ * digest do they replace the version, so a later save to another page does+ * not hold the undo back; a page put back that they leave out or name as+ * gone keeps the version's check.*/export const restoreBookPageArgs = {pages: z.array(bookPreviousSpreadSchema).min(1).max(BOOK_OP_LIMITS.pagesPerCall),expectedVersion: z.number().int().nonnegative(),+ expectedPages: z.array(bookPageDigestSchema).min(1).max(BOOK_OP_LIMITS.pagesPerCall).optional(),};/** A design draft's id, as `design_book` answers it. */export const bookDesignIdSchema = z.string().regex(/^[\w-]{1,40}$/);@@ -428,9 +442,9 @@ export type BookPageDescription = z.infer<typeof bookPageDescriptionSchema>;/*** What a book write answers. `dropped` names the elements whose content left- * the page (a layout, a hard remove). `previous_spreads` only when the call- * asked with `returnPrevious`; `from_index` only from a move, where the page- * stood before it, so a move can be taken back.+ * the page (a layout, a hard remove). `previous_spreads` and `page_digests`+ * only when the call asked with `returnPrevious`; `from_index` only from a+ * move, where the page stood before it, so a move can be taken back.*/export const bookWriteResultSchema = z.object({version: z.number().int().nonnegative(),@@ -439,6 +453,8 @@ export const bookWriteResultSchema = z.object({findings: z.array(bookFindingSchema).max(BOOK_OP_LIMITS.findings),dropped: z.array(z.string()).max(MAX_SPREAD_ELEMENTS * 2),previous_spreads: z.array(bookPreviousSpreadSchema).optional(),+ /** The pages the write touched as it left them, for an undo that checks only those (`expectedPages`). */+ page_digests: z.array(bookPageDigestSchema).max(MAX_SPREADS).optional(),from_index: z.number().int().nonnegative().optional(),/** From `set_book_setup`: the setup as it was, to set it back. */previous_setup: bookPageSetupSchema.optional(),