feat(studio): a sticker library of 148 hand-drawn illustrations, placed, recoloured and searched by people and the assistant

A new element kind, sticker, draws layered vector illustrations from a library in twelve themes, behind its own entry point @trek/shared/stickers. Studio gets a Stickers rail section (themes, localized search, recently used, click or drag to place) and an inspector for colour slots, mirroring, turning and opacity. The assistant gets list_book_assets, add and style of stickers in edit_book_page, stickers in describe_book_page and an overlap warning for a sticker over words. BOOK_SCHEMA_REV goes to 2.
This commit is contained in:
Maurice
2026-10-23 19:50:55 +02:00
parent 23c446b7e9
commit 8c6f5deab2
110 changed files with 13616 additions and 19 deletions
@@ -26,6 +26,7 @@ const STUDIO_ONLY_TOOLS: Readonly<Record<string, string>> = Object.fromEntries(
'get_book',
'describe_book_page',
'list_book_layouts',
'list_book_assets',
'create_book',
'add_book_pages',
'move_book_page',
@@ -60,7 +60,9 @@ import {
type SaveBookLayoutRequest,
type SetBookCoverRequest,
type SetBookSetupRequest,
type ListBookAssetsRequest,
} from '@trek/shared';
import { bookStickerLookup, listBookAssets } from '@trek/shared/stickers';
import { createHash } from 'node:crypto';
@@ -165,6 +167,16 @@ export class JourneyBookEditService {
return listBookLayouts(doc, doc?.page ?? bookPageSetupSchema.parse({}), role);
}
/**
* `list_book_assets`: the Studio's sticker library, searched. Not of the
* journey, but asked on one, a member's read like the other book reads, so
* the Studio chat keeps it (its tools are pinned to the journey).
*/
async assets(journeyId: number, userId: number, search: Omit<ListBookAssetsRequest, 'kind'>) {
await this.readable(journeyId, userId);
return { kind: 'sticker' as const, ...listBookAssets(search) };
}
/**
* The stored book and what the engine checks a change against (the
* gallery, the entries), for a change that is only tried: the assistant runs
@@ -397,6 +409,8 @@ export class JourneyBookEditService {
location: e.location_name ?? null,
})),
},
// The Studio's sticker library, which a new sticker is placed from.
stickers: bookStickerLookup,
};
}
+16 -1
View File
@@ -22,6 +22,7 @@ import {
duplicateBookPageArgs,
editBookPageArgs,
idSchema,
listBookAssetsArgs,
listBookLayouts,
listBookLayoutsArgs,
moveBookPageArgs,
@@ -36,6 +37,7 @@ import {
type DeleteBookPagesRequest,
type DuplicateBookPageRequest,
type EditBookPageRequest,
type ListBookAssetsRequest,
type MoveBookPageRequest,
type RemoveBookLayoutRequest,
type RestoreBookLayoutRequest,
@@ -125,6 +127,19 @@ export class JourneyBookMcp {
return ok(await this.books.layouts(journeyId, ctx.userId, role));
}
@Tool({
name: 'list_book_assets',
description:
"The Studio's library of things to put on a page of a journey's book, searchable, the same one the Studio's panels show. kind sticker lists the illustrations: flat, multi-coloured drawings of landmarks, travel things, tropical and Mediterranean motifs, the sea, mountains, the north, Asia, food, paper and tape, hand-drawn doodles and ornaments. Each row has its id, theme, one sentence of what it shows, its tags, its aspect (width over height) and its colour slots with their defaults. query searches ids, tags and descriptions in English; tags and theme narrow it; at most limit rows, 40 by default, with the total found. Place one with edit_book_page add { kind: 'sticker', stickerId }, recolour it with colors (one per slot, in order) and mirror it with flipX. Stickers are decoration: put them beside or over a photo, never over words.",
inputSchema: { journeyId: idSchema, ...listBookAssetsArgs },
annotations: TOOL_ANNOTATIONS_READONLY,
when: journeyAddonOn,
access: { group: 'journey', mode: 'read' },
})
async listAssets({ journeyId, query, tags, theme, limit }: OnJourney & ListBookAssetsRequest, ctx: McpContext) {
return ok(await this.books.assets(journeyId, ctx.userId, { query, tags, theme, limit }));
}
// ── Write ───────────────────────────────────────────────────────────────
@Tool({
@@ -177,7 +192,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 (a colour, or a paint: a colour with alpha, a linear or radial gradient, or one of twelve patterns; 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, a shape's paint, 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}`,
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 (a colour, or a paint: a colour with alpha, a linear or radial gradient, or one of twelve patterns; null is the paper), add (a new photo frame, text, shape, icon, sticker from list_book_assets, 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, a shape's paint, 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,
@@ -377,7 +377,8 @@ describe('the whole-book design through the Studio chat', () => {
expect([undone.status, undone.body]).toEqual([200, { undone: true }]);
const restored = await bookOf(j.journeyId, j.ownerId);
expect(restored.version).toBe(3);
expect(restored.document).toEqual(before.document);
// Put back as it was, written by this build: stamped with its format revision (book-schema-rev.ts).
expect({ ...restored.document, schemaRev: undefined }).toEqual({ ...before.document, schemaRev: undefined });
expect(restored.document.spreads.map((spread) => spread.id)).toEqual(j.created.spread_ids);
expect(savedTo(j.ownerId)).toBe(1);
const again = await undo(j.base, j.ownerId, turn.heldId);
@@ -37,6 +37,7 @@ const BOOK_TOOLS = [
'get_book',
'describe_book_page',
'list_book_layouts',
'list_book_assets',
'create_book',
'add_book_pages',
'move_book_page',
@@ -192,6 +192,7 @@ describe('the assistant tool catalog', () => {
'get_book',
'describe_book_page',
'list_book_layouts',
'list_book_assets',
'create_book',
'add_book_pages',
'move_book_page',
@@ -0,0 +1,134 @@
/**
* list_book_assets and the sticker kind (JBASSET-*): the Studio's sticker
* library searched through JourneyBookMcp, and a sticker placed with
* edit_book_page from the library the edit context hands the engine. Taken
* from JourneyBookModule over a snapshot test db.
*
* What it pins: the tool waits for the Journey addon, only reads and sits in
* the journey group; any member may search, an outsider is told the journey
* is not there; the answer is the catalogue's rows with their slots; a
* sticker the library holds lands on the page in its proportions, one it does
* not hold is refused with the engine's code and nothing is written.
*/
import type { McpContext } from '../../../src/nest-mcp';
import { getEntry, type ClassRef } from '../../../src/nest-mcp/metadata';
import { AddonsService } from '../../../src/nest/addons/addons.service';
import { JourneyBookMcp } from '../../../src/nest/journey/journey-book.mcp';
import { JourneyBookModule } from '../../../src/nest/journey/journey-book.module';
import { createSnapshotTestDb } from '../../helpers/db-mock';
import { addJourneyContributor, makeJourney } from '../../helpers/factories/journeys';
import { makeUser } from '../../helpers/factories/users';
import { resetTestDb } from '../../helpers/test-db';
import { createTestModule, type TestModule } from '../../helpers/test-module';
import { createTestOrm, type TestOrm } from '../../helpers/test-orm';
import { bookOverviewSchema, bookWriteResultSchema } from '@trek/shared';
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
const db = createSnapshotTestDb();
let t: TestModule;
let orm: TestOrm;
let mcp: JourneyBookMcp;
beforeAll(async () => {
t = await createTestModule({ db, imports: [JourneyBookModule] });
mcp = t.get(JourneyBookMcp);
orm = await createTestOrm(db);
});
beforeEach(() => {
resetTestDb(db);
orm.clear();
vi.restoreAllMocks();
});
afterAll(async () => {
await orm.close();
await t.close();
db.close();
});
const ctx = (userId: number) => ({ userId }) as McpContext;
const json = (result: { content: Array<{ type: string; text: string }> }) => JSON.parse(result.content[0]?.text ?? '');
/** A journey with a blank book, and the id of its one double spread. */
async function bookFor(ownerId: number) {
const journey = await makeJourney(orm, ownerId);
await mcp.createBook({ journeyId: journey.id }, ctx(ownerId));
const overview = bookOverviewSchema.parse(json(await mcp.getBook({ journeyId: journey.id }, ctx(ownerId))));
const inner = overview.spreads.find((s) => s.role === 'inner')?.id ?? '';
return { journey, inner };
}
describe('list_book_assets', () => {
it('JBASSET-001: waits for the Journey addon, reads only, in the journey group', async () => {
const { user } = await makeUser(orm);
const entry = getEntry(JourneyBookMcp as unknown as ClassRef, 'listAssets');
if (entry?.kind !== 'tool') throw new Error('listAssets is no tool');
expect(entry.options.name).toBe('list_book_assets');
expect(entry.options.access).toEqual({ group: 'journey', mode: 'read' });
expect(entry.options.annotations?.readOnlyHint).toBe(true);
const enabled = vi.spyOn(t.get(AddonsService), 'isAddonEnabled');
enabled.mockResolvedValue(false);
expect(await entry.options.when?.(ctx(user.id), mcp)).toBe(false);
enabled.mockResolvedValue(true);
expect(await entry.options.when?.(ctx(user.id), mcp)).toBe(true);
});
it('JBASSET-002: any member searches the library, an outsider is told the journey is not there', async () => {
const { user: owner } = await makeUser(orm);
const { user: viewer } = await makeUser(orm);
const { user: stranger } = await makeUser(orm);
const journey = await makeJourney(orm, owner.id);
await addJourneyContributor(orm, journey.id, viewer.id, 'viewer');
const answer = json(
await mcp.listAssets({ journeyId: journey.id, kind: 'sticker', query: 'lemon', limit: 3 }, ctx(viewer.id)),
);
expect(answer.kind).toBe('sticker');
expect(answer.rows).toHaveLength(3);
expect(answer.rows[0]).toMatchObject({ id: 'lemon', theme: 'mediterranean', aspect: 1.25 });
expect(answer.rows[0].slots).toEqual([
{ name: 'lemon', default: '#ffd23f' },
{ name: 'leaves', default: '#3f8f4f' },
]);
expect(answer.total).toBeGreaterThanOrEqual(3);
const paper = json(await mcp.listAssets({ journeyId: journey.id, kind: 'sticker', theme: 'paper' }, ctx(owner.id)));
expect(paper.rows.every((row: { theme: string }) => row.theme === 'paper')).toBe(true);
await expect(mcp.listAssets({ journeyId: journey.id, kind: 'sticker' }, ctx(stranger.id))).rejects.toThrow(
'Journey not found',
);
});
});
describe('a sticker on a page', () => {
it('JBASSET-003: edit_book_page places a sticker the library holds, in its proportions and the colours asked for', async () => {
const { user: owner } = await makeUser(orm);
const { journey, inner } = await bookFor(owner.id);
const element = { kind: 'sticker' as const, stickerId: 'eiffelTower', colors: ['#1d3557'] };
const written = bookWriteResultSchema.parse(
json(
await mcp.editBookPage(
{ journeyId: journey.id, spreadId: inner, ops: [{ op: 'add', element }] },
ctx(owner.id),
),
),
);
expect(written.spread_ids).toEqual([inner]);
const page = json(await mcp.describeBookPage({ journeyId: journey.id, spreadId: inner }, ctx(owner.id)));
const sticker = page.elements.find((e: { kind: string }) => e.kind === 'sticker');
// The tower is drawn 70 by 100: on the 21 cm page it stands 63 mm tall and 44.1 mm wide.
expect(sticker?.frame).toMatchObject({ w: 44.1, h: 63 });
expect(page.text).toMatch(/sticker eiffelTower, colours #1d3557/);
});
it('JBASSET-004: a sticker the library does not hold is refused with the engine code, and nothing is written', async () => {
const { user: owner } = await makeUser(orm);
const { journey, inner } = await bookFor(owner.id);
const before = json(await mcp.getBook({ journeyId: journey.id }, ctx(owner.id))).version;
const element = { kind: 'sticker' as const, stickerId: 'unicornCastle' };
await expect(
mcp.editBookPage({ journeyId: journey.id, spreadId: inner, ops: [{ op: 'add', element }] }, ctx(owner.id)),
).rejects.toThrow(/no sticker unicornCastle/);
expect(json(await mcp.getBook({ journeyId: journey.id }, ctx(owner.id))).version).toBe(before);
});
});