feat(studio): the assistant sits beside the book and draws the page it looks at

A chat column in the Studio with its own privacy notice, a live page snapshot
through modern-screenshot that leaves out photos of other people and foreign
map tiles, and flushes before every turn and apply.
This commit is contained in:
Maurice
2026-10-22 21:25:46 +00:00
parent 8b93898b73
commit 09ffc7d946
47 changed files with 1763 additions and 11 deletions
+25 -3
View File
@@ -376,9 +376,18 @@ function IconView({ el }: { el: BookIconElement }) {
}
export function ElementView({
el, big, print = false, dropLabel = '',
}: { el: BookElement; big: boolean; print?: boolean; dropLabel?: string }) {
el, big, print = false, dropLabel = '', hiddenPhotoIds,
}: {
el: BookElement; big: boolean; print?: boolean; dropLabel?: string
/** Photos drawn as empty frames instead of themselves. */
hiddenPhotoIds?: ReadonlySet<number>
}) {
if (el.kind === 'photo') {
// A photo left out is drawn as its empty frame, kept even in print, so the
// page still shows where a picture sits without showing the picture.
if (el.photoId != null && hiddenPhotoIds?.has(el.photoId)) {
return <PhotoView el={{ ...el, photoId: null }} big={big} print={false} dropLabel="" />
}
return <PhotoView el={el} big={big} print={print} dropLabel={dropLabel} />
}
@@ -432,6 +441,7 @@ export function SpreadView({
showGuides = false,
print = false,
dropLabel = '',
hiddenPhotoIds,
}: {
spread: BookSpread
page: BookPageSetup
@@ -447,6 +457,11 @@ export function SpreadView({
/** The print renderer passes this: no guides, no placeholders, no chrome. */
print?: boolean
dropLabel?: string
/**
* Photos to leave out, drawn as empty frames: a page drawn for the
* assistant shows only the asking user's own photos (journey-studio.md 3.4).
*/
hiddenPhotoIds?: ReadonlySet<number>
}) {
const isSingle = spread.role !== 'inner'
const w = isSingle ? page.pageWidth : page.pageWidth * 2
@@ -468,7 +483,14 @@ export function SpreadView({
}}
>
{spread.elements.map(el => (
<ElementView key={el.id} el={el} big={big} print={print} dropLabel={dropLabel} />
<ElementView
key={el.id}
el={el}
big={big}
print={print}
dropLabel={dropLabel}
hiddenPhotoIds={hiddenPhotoIds}
/>
))}
<PageNumbers spread={spread} page={page} folios={folios} />
@@ -0,0 +1,108 @@
/**
* FE-STUDIO-ASTPANEL-001 to FE-STUDIO-ASTPANEL-003
*
* The assistant's column in TREK Studio (journey-studio.md 3.4, 4.5): the
* journey's chat with its own question; the notice that images of a page
* leave only once the user agreed, for the connection on screen, and that
* "Not now" keeps it text for the visit; every key inside the column belongs
* to the chat, so Studio neither closes nor edits the page's selection, and
* Escape stops a running answer first.
*/
import type { AiStatusResponse } from '@trek/shared';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { fireEvent, render, screen, waitFor } from '../../../tests/helpers/render';
import { aiConnectionsRepo } from '../../repo/aiConnectionsRepo';
import { assistantRepo } from '../../repo/assistantRepo';
import { assistantChatKey } from '../../store/assistantChatKey';
import { chatOf, useAssistantStore } from '../../store/assistantStore';
import StudioAssistantPanel from './StudioAssistantPanel';
import type { StudioAssistant } from './useStudioAssistant';
const JOURNEY = 12;
const KEY = assistantChatKey({ kind: 'journey', journeyId: JOURNEY });
const INITIAL = useAssistantStore.getState();
const STATUS: AiStatusResponse = {
available: true,
policy: 'instance',
canConnectOwn: false,
effective: { source: 'instance', kind: 'anthropic', model: 'claude', host: 'api.anthropic.com', paidBy: 'instance' },
own: null,
instance: { kind: 'anthropic', model: 'claude', host: 'api.anthropic.com' },
quota: null,
privacyAcked: true,
studioImagesAcked: false,
retention: { mode: 'days', days: 90 },
openrouterOAuth: false,
};
function assistant(): StudioAssistant {
return { chatKey: KEY, available: true, open: true, toggle: vi.fn(), jobs: [], drawn: vi.fn() };
}
beforeEach(() => {
vi.spyOn(assistantRepo, 'threads').mockResolvedValue([]);
useAssistantStore.setState({ ...INITIAL, status: STATUS, byTrip: {}, studioHosts: {} });
});
afterEach(() => {
vi.restoreAllMocks();
useAssistantStore.setState(INITIAL);
});
describe('StudioAssistantPanel', () => {
it('FE-STUDIO-ASTPANEL-001: shows the journey chat and lets page images leave once the user agreed', async () => {
const ack = vi.spyOn(aiConnectionsRepo, 'ackPrivacy').mockResolvedValueOnce(undefined);
render(<StudioAssistantPanel assistant={assistant()} title="Lisbon" />);
expect(screen.getByRole('complementary', { name: 'Book assistant' })).toBeInTheDocument();
expect(await screen.findByText('What should the book look like?')).toBeInTheDocument();
const notice = screen.getByRole('note');
expect(notice.textContent).toContain('Only that page goes to Anthropic');
fireEvent.click(screen.getByRole('button', { name: 'Show it pages' }));
await waitFor(() => expect(screen.queryByRole('note')).toBeNull());
expect(ack).toHaveBeenCalledWith({ kind: 'anthropic', host: 'api.anthropic.com', scope: 'studio_images' });
expect(useAssistantStore.getState().status?.studioImagesAcked).toBe(true);
});
it('FE-STUDIO-ASTPANEL-002: "Not now" keeps the pages as text, an agreed connection shows no notice', async () => {
const ack = vi.spyOn(aiConnectionsRepo, 'ackPrivacy');
const { unmount } = render(<StudioAssistantPanel assistant={assistant()} title="Lisbon" />);
fireEvent.click(screen.getByRole('button', { name: 'Not now' }));
expect(screen.queryByRole('note')).toBeNull();
expect(ack).not.toHaveBeenCalled();
unmount();
useAssistantStore.setState({ status: { ...STATUS, studioImagesAcked: true } });
render(<StudioAssistantPanel assistant={assistant()} title="Lisbon" />);
expect(await screen.findByText('What should the book look like?')).toBeInTheDocument();
expect(screen.queryByRole('note')).toBeNull();
});
it('FE-STUDIO-ASTPANEL-003: keys in the column stay there, Escape stops a running answer first', () => {
const cancel = vi.fn();
useAssistantStore.setState({
cancel,
byTrip: { [KEY]: { ...chatOf(useAssistantStore.getState(), KEY), isRunning: true } },
});
const studioKeys = vi.fn();
window.addEventListener('keydown', studioKeys);
const panel = assistant();
render(<StudioAssistantPanel assistant={panel} title="Lisbon" />);
const column = screen.getByRole('complementary', { name: 'Book assistant' });
// The editor deletes the selected elements on Backspace; from the chat it must not hear it.
fireEvent.keyDown(column, { key: 'Backspace' });
expect(cancel).not.toHaveBeenCalled();
fireEvent.keyDown(column, { key: 'Escape' });
expect(studioKeys).not.toHaveBeenCalled();
expect(cancel).toHaveBeenCalledTimes(1);
expect(cancel).toHaveBeenCalledWith(KEY);
expect(panel.toggle).not.toHaveBeenCalled();
window.removeEventListener('keydown', studioKeys);
});
});
@@ -0,0 +1,173 @@
import '../../styles/studio-assistant.css';
import { ImageIcon } from 'lucide-react';
import { type HTMLAttributes, type KeyboardEvent, useCallback, useEffect, useRef, useState } from 'react';
import { useNavigate } from 'react-router';
import { useTranslation } from '../../i18n';
import { useAssistantStore } from '../../store/assistantStore';
import AssistantHeader from '../Assistant/AssistantHeader';
import AssistantSurfaceLazy from '../Assistant/AssistantSurfaceLazy';
import type { EntityTarget } from '../Assistant/cards/cardTypes';
import { providerLabel } from '../Assistant/providerCatalog';
import { useAssistantThread } from '../Assistant/useAssistantThread';
import { useToast } from '../shared/Toast';
import { SpreadView } from './SpreadView';
import { sheetSizePx } from './pageSnapshot';
import type { StudioAssistant, StudioRenderJob } from './useStudioAssistant';
/**
* The assistant as a column of TREK Studio (journey-studio.md 4.5): the same
* chat as the planner's window, on the journey's conversations, beside the
* page it talks about. Desktop only, like the Studio itself.
*
* Studio closes on Escape and edits the selection on Delete, copy and paste.
* Inside the column every key belongs to the chat, so it stops here, and
* Escape stops a running answer first.
*/
/** The column is not a window: its head moves nothing. */
const NO_DRAG: HTMLAttributes<HTMLElement> = { style: { cursor: 'default' } };
/**
* Images of a page leave only once the user agreed, per connection. Until
* then the Studio's assistant reads the pages as text. "Not now" hides the
* notice for this visit; the next one asks again.
*/
function StudioImagesNotice() {
const { t } = useTranslation();
const toast = useToast();
const effective = useAssistantStore((s) => s.status?.effective ?? null);
const acked = useAssistantStore((s) => s.status?.studioImagesAcked === true);
const ackStudioImages = useAssistantStore((s) => s.ackStudioImages);
const [later, setLater] = useState(false);
if (!effective || acked || later) return null;
const provider = providerLabel(effective.kind, effective.host);
const allow = async () => {
try {
await ackStudioImages();
} catch {
toast.error(t('assistant.error.generic'));
}
};
return (
<div
role="note"
className="st-assistant-notice rounded-lg border border-edge-faint bg-surface-secondary px-3 py-2.5 text-caption text-content-secondary"
>
<div className="flex items-start gap-2.5">
<ImageIcon size={14} aria-hidden="true" className="mt-0.5 flex-shrink-0 text-content-muted" />
<p className="m-0 min-w-0 flex-1">{t('journey.studio.assistant.notice', { provider })}</p>
</div>
<div className="mt-2 flex items-center justify-end gap-1">
<button
type="button"
onClick={() => setLater(true)}
className="rounded-md px-2 py-1 text-caption text-content-muted hover:bg-surface-hover hover:text-content"
>
{t('journey.studio.assistant.noticeLater')}
</button>
<button
type="button"
onClick={() => void allow()}
className="rounded-md px-2 py-1 text-caption font-medium text-accent-on hover:bg-surface-hover"
>
{t('journey.studio.assistant.noticeAllow')}
</button>
</div>
</div>
);
}
/** One page a turn asked for, drawn as the editor draws it and handed on once it is in the DOM. */
function StageSheet({
job,
onDrawn,
}: {
job: StudioRenderJob;
onDrawn: (job: StudioRenderJob, sheet: HTMLElement) => Promise<void>;
}) {
const sheet = useRef<HTMLDivElement>(null);
// A job goes up once, even when the effect runs again (development's double run, a new callback).
const sent = useRef<StudioRenderJob | null>(null);
const size = sheetSizePx(job.spread, job.page);
useEffect(() => {
if (!sheet.current || sent.current === job) return;
sent.current = job;
void onDrawn(job, sheet.current);
}, [job, onDrawn]);
return (
// A page is laid out in millimetres from its top left whatever the reading direction.
<div ref={sheet} dir="ltr" style={{ position: 'relative', width: size.width, height: size.height }}>
<SpreadView spread={job.spread} page={job.page} folios={job.folios} print hiddenPhotoIds={job.hidden} />
</div>
);
}
/**
* The pages being drawn for a turn, where nobody sees them. Off screen rather
* than hidden, as StudioExport does it: a hidden subtree lays nothing out,
* and the page is measured in millimetres by the CSS that draws it.
*/
export function StudioPageStage({ assistant }: { assistant: StudioAssistant }) {
if (assistant.jobs.length === 0) return null;
return (
<div
aria-hidden="true"
className="st-assistant-stage"
style={{ position: 'fixed', insetInlineStart: '-20000mm', top: 0, pointerEvents: 'none' }}
>
{assistant.jobs.map((job) => (
<StageSheet key={job.request.requestId} job={job} onDrawn={assistant.drawn} />
))}
</div>
);
}
export default function StudioAssistantPanel({ assistant, title }: { assistant: StudioAssistant; title: string }) {
const { t } = useTranslation();
const navigate = useNavigate();
const thread = useAssistantThread(assistant.chatKey);
const { isRunning, stop } = thread;
// A card points at a page of this book (`?page=`) or somewhere else in the app.
const onOpen = useCallback(
(target: EntityTarget) => {
if (target.kind === 'page') void navigate(target.path);
},
[navigate]
);
// Every key pressed in the column is the chat's: the editor's own keys
// (Delete, Backspace, copy, paste, undo, Escape) listen on the window and
// would otherwise act on the page's selection from a focused chat button.
const onKeyDown = (e: KeyboardEvent<HTMLElement>) => {
e.stopPropagation();
if (e.key === 'Escape' && isRunning && !e.defaultPrevented) stop();
};
return (
<aside className="st-panel st-assistant" aria-label={t('journey.studio.assistant.panel')} onKeyDown={onKeyDown}>
<AssistantHeader
tripId={assistant.chatKey}
thread={thread}
tripTitle={title}
dragProps={NO_DRAG}
onClose={assistant.toggle}
/>
<StudioImagesNotice />
<AssistantSurfaceLazy
tripId={assistant.chatKey}
tripTitle={title}
variant="window"
density="compact"
onOpen={onOpen}
/>
</aside>
);
}
+37 -5
View File
@@ -2,7 +2,7 @@ import { useEffect, useRef, useState } from 'react'
import { createPortal } from 'react-dom'
import { useNavigate } from 'react-router'
import {
ArrowLeft, BookOpen, Check, ChevronDown, ClipboardPaste, Download, Maximize2, Minus, Plus,
ArrowLeft, BookOpen, Check, ChevronDown, ClipboardPaste, Download, Maximize2, MessageSquare, Minus, Plus,
Redo2, Sparkles, Undo2,
} from 'lucide-react'
import { useJourneyStudio } from '../../pages/journeyStudio/useJourneyStudio'
@@ -21,6 +21,8 @@ import { PeerBadges } from './PeerBadges'
import { TrimField } from './TrimField'
import { Tooltip } from '../shared/Tooltip'
import { useStudioStore } from '../../store/studioStore'
import StudioAssistantPanel, { StudioPageStage } from './StudioAssistantPanel'
import { useStudioAssistant, type StudioAssistant } from './useStudioAssistant'
import '../../styles/dashboard.css'
import '../../styles/studio.css'
import './bookFontFaces'
@@ -42,6 +44,7 @@ export default function StudioShell() {
const navigate = useNavigate()
const [bookView, setBookView] = useState(true)
const [exporting, setExporting] = useState(false)
const assistant = useStudioAssistant({ journeyId: s.journeyId, flush: s.flushBook })
if (s.isMobile) {
return createPortal(
@@ -83,7 +86,13 @@ export default function StudioShell() {
aria-modal="true"
aria-label={s.t('journey.studio.title')}
>
<StudioBar s={s} bookView={bookView} setBookView={setBookView} onExport={() => setExporting(true)} />
<StudioBar
s={s}
bookView={bookView}
setBookView={setBookView}
onExport={() => setExporting(true)}
assistant={assistant}
/>
{/* The journey gallery's picker, inside Studio's own layer (#2271). */}
{s.providerPick && s.journey && (
<ProviderPicker
@@ -98,7 +107,7 @@ export default function StudioShell() {
/>
)}
<div className="st-body">
<div className={`st-body ${assistant.open ? 'has-assistant' : ''}`}>
<StudioSidebar
page={s.page}
pxPerMm={s.pxPerMm}
@@ -124,7 +133,9 @@ export default function StudioShell() {
t={s.t}
locale={s.locale}
/>
<AssistantColumn s={s} assistant={assistant} />
</div>
<StudioPageStage assistant={assistant} />
{exporting && s.doc && (
<StudioExport
@@ -142,9 +153,18 @@ export default function StudioShell() {
type Studio = ReturnType<typeof useJourneyStudio>
/** The chat column at the end of the body, while it is open. */
function AssistantColumn({ s, assistant }: { s: Studio; assistant: StudioAssistant }) {
if (!assistant.open) return null
return <StudioAssistantPanel assistant={assistant} title={s.journey?.title || s.t('journey.title')} />
}
function StudioBar({
s, bookView, setBookView, onExport,
}: { s: Studio; bookView: boolean; setBookView: (v: boolean) => void; onExport: () => void }) {
s, bookView, setBookView, onExport, assistant,
}: {
s: Studio; bookView: boolean; setBookView: (v: boolean) => void; onExport: () => void
assistant: StudioAssistant
}) {
return (
<div className="st-bar">
<button type="button" onClick={s.close} className="st-back" title={s.t('journey.studio.backToJourney')}>
@@ -217,6 +237,18 @@ function StudioBar({
<div className="st-sep" />
<AutoLayoutButton s={s} />
{/* The book's assistant, as a column beside the page; only where it can run for this user. */}
{assistant.available && (
<button type="button"
className={`st-tool ${assistant.open ? 'is-on' : ''}`}
onClick={assistant.toggle}
aria-pressed={assistant.open}
title={s.t('journey.studio.assistant.toggleHint')}
>
<MessageSquare size={14} />
<span className="st-tool-label">{s.t('journey.studio.assistant.toggle')}</span>
</button>
)}
<button type="button"
className="st-tool is-primary"
onClick={onExport}
@@ -0,0 +1,114 @@
/**
* FE-STUDIO-SNAP-001 to FE-STUDIO-SNAP-005
*
* The page image the Studio sends the assistant (journey-studio.md 3.1, 3.4):
* a sheet's size in CSS pixels, the filter that leaves out pictures from
* other servers and hidden photos before anything is rasterised, the photos
* the upload declares read off what is kept, and the JPEG at most 1280 pixels
* on its long edge. modern-screenshot is faked; a real browser draws the page
* in the Playwright flows.
*/
import { ASSISTANT_PAGE_IMAGE, blankBook, bookPageSetupForPreset } from '@trek/shared';
import { domToBlob, type Options } from 'modern-screenshot';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { drawnPhotoIdsOf, keepNode, sheetSizePx, snapshotSpread } from './pageSnapshot';
vi.mock('modern-screenshot', () => ({ domToBlob: vi.fn() }));
const SVG = 'http://www.w3.org/2000/svg';
function picture(src: string): HTMLImageElement {
const img = document.createElement('img');
img.setAttribute('src', src);
return img;
}
function svgImage(href: string): Element {
const image = document.createElementNS(SVG, 'image');
image.setAttribute('href', href);
return image;
}
/** A sheet holding an own photo twice, a hidden photo, a map tile and a stop's own photo. */
function sheet(): HTMLDivElement {
const root = document.createElement('div');
root.append(
picture('/api/photos/7/thumbnail'),
picture('/api/photos/7/thumbnail'),
picture('/api/photos/31/thumbnail'),
picture('https://tile.openstreetmap.org/5/16/10.png')
);
const svg = document.createElementNS(SVG, 'svg');
svg.append(svgImage('/api/photos/8/thumbnail'), svgImage('/api/photos/32/thumbnail'));
root.append(svg);
return root;
}
const HIDDEN: ReadonlySet<number> = new Set([31, 32]);
/** The calls made to the fake, as the node and options form of domToBlob takes them. */
const blobCalls = () => vi.mocked(domToBlob).mock.calls as unknown as Array<[Node, Options | undefined]>;
afterEach(() => vi.clearAllMocks());
describe('pageSnapshot', () => {
it('FE-STUDIO-SNAP-001: a cover is one page wide and an inner spread two, in CSS pixels', () => {
const page = bookPageSetupForPreset('square-210');
const [cover, , inner] = blankBook({ title: 'Lisbon', page }).spreads;
if (!cover || !inner) throw new Error('blank book without a cover or an inner spread');
const px = 210 * (96 / 25.4);
expect(sheetSizePx(cover, page)).toEqual({ width: px, height: px });
expect(sheetSizePx(inner, page)).toEqual({ width: px * 2, height: px });
});
it('FE-STUDIO-SNAP-002: leaves out pictures from other servers and hidden photos, keeps the rest', () => {
expect(keepNode(picture('/api/photos/7/thumbnail'), HIDDEN)).toBe(true);
expect(keepNode(picture('data:image/png;base64,AAAA'), HIDDEN)).toBe(true);
expect(keepNode(picture('/api/photos/31/original'), HIDDEN)).toBe(false);
expect(keepNode(picture('https://tile.openstreetmap.org/5/16/10.png'), HIDDEN)).toBe(false);
expect(keepNode(svgImage('/api/photos/32/thumbnail'), HIDDEN)).toBe(false);
expect(keepNode(svgImage('https://api.mapbox.com/styles/v1/x/static/0,0,1/400x300'), HIDDEN)).toBe(false);
// Everything that is not a picture is drawn as it is.
expect(keepNode(document.createElement('div'), HIDDEN)).toBe(true);
expect(keepNode(document.createTextNode('Lisbon'), HIDDEN)).toBe(true);
});
it('FE-STUDIO-SNAP-003: declares each kept photo once, and none it left out', () => {
expect(drawnPhotoIdsOf(sheet(), HIDDEN).sort((a, b) => a - b)).toEqual([7, 8]);
expect(drawnPhotoIdsOf(sheet(), new Set()).sort((a, b) => a - b)).toEqual([7, 8, 31, 32]);
});
it('FE-STUDIO-SNAP-004: draws a JPEG with its long edge at 1280 pixels through the same filter', async () => {
const image = new Blob(['jpeg'], { type: 'image/jpeg' });
vi.mocked(domToBlob).mockResolvedValueOnce(image);
const root = sheet();
const shot = await snapshotSpread(root, { width: 1600, height: 800 }, HIDDEN);
expect(shot).toEqual({ image, width: 1280, height: 640, drawnPhotoIds: [7, 8] });
const [node, options] = blobCalls()[0] ?? [];
expect(node).toBe(root);
expect(options).toMatchObject({
width: 1600,
height: 800,
scale: 0.8,
type: 'image/jpeg',
quality: ASSISTANT_PAGE_IMAGE.jpegQuality,
});
const filter = options?.filter;
expect(filter?.(picture('/api/photos/31/thumbnail'))).toBe(false);
expect(filter?.(picture('/api/photos/7/thumbnail'))).toBe(true);
});
it('FE-STUDIO-SNAP-005: an image too large for the server is not sent, a small sheet is not enlarged', async () => {
vi.mocked(domToBlob).mockResolvedValueOnce(new Blob([new Uint8Array(ASSISTANT_PAGE_IMAGE.maxBytes + 1)]));
expect(await snapshotSpread(sheet(), { width: 1600, height: 800 }, HIDDEN)).toBeNull();
vi.mocked(domToBlob).mockResolvedValueOnce(new Blob(['jpeg'], { type: 'image/jpeg' }));
const small = await snapshotSpread(sheet(), { width: 400, height: 300 }, HIDDEN);
expect(small).toMatchObject({ width: 400, height: 300 });
expect(blobCalls()[1]?.[1]).toMatchObject({ scale: 1 });
});
});
@@ -0,0 +1,146 @@
import { ASSISTANT_PAGE_IMAGE, type BookPageSetup, type BookSpread } from '@trek/shared';
/**
* One Studio page as a JPEG, for the assistant to look at (journey-studio.md
* 3.1). The page is the editor's own SpreadView, drawn off screen, and this
* turns that DOM into an image through modern-screenshot, which is loaded
* only when a page is first drawn, so nobody downloads it before the Studio
* chat asks for one.
*
* What is drawn is what is sent, so the filter runs here, on the DOM, before
* anything is rasterised: a picture from another server (map tiles, a static
* map) is left out, because it would taint the canvas and say where the user
* is, and so is any photo the turn named as hidden. The photos left in are
* read off the DOM itself, so the upload declares exactly what the image shows.
*/
/** CSS pixels in a millimetre, the size SpreadView's millimetre boxes are laid out at. */
const PX_PER_MM = 96 / 25.4;
/** How long the pictures of one page may take to load before it is drawn without them. */
const LOAD_TIMEOUT_MS = 8_000;
/** The path of a TREK photo, with its id. */
const PHOTO_PATH = /^\/api\/photos\/(\d+)\//;
interface PageSnapshot {
image: Blob;
width: number;
height: number;
/** The photos the image shows, as the server checks them. */
drawnPhotoIds: number[];
}
/** A sheet's size in CSS pixels: one page for the covers and the first and last pages, two for an inner spread. */
export function sheetSizePx(spread: BookSpread, page: BookPageSetup): { width: number; height: number } {
const pages = spread.role === 'inner' ? 2 : 1;
return { width: page.pageWidth * pages * PX_PER_MM, height: page.pageHeight * PX_PER_MM };
}
/** Where a picture element takes its image from: an img's src, an SVG image's href. */
function sourceOf(node: Element): string | null {
const tag = node.tagName.toLowerCase();
if (tag === 'img') return node.getAttribute('src');
if (tag === 'image') return node.getAttribute('href') ?? node.getAttribute('xlink:href');
return null;
}
/** A picture's URL read against this page, or null when it is not one. */
function urlOf(src: string): URL | null {
try {
return new URL(src, window.location.href);
} catch {
return null;
}
}
/** The TREK photo a picture shows, or null for any other picture. */
function photoIdOf(url: URL): number | null {
const match = PHOTO_PATH.exec(url.pathname);
return match ? Number(match[1]) : null;
}
/** Whether a picture may be drawn: an inline one, or one from this server that is not a hidden photo. */
function drawable(src: string, hidden: ReadonlySet<number>): boolean {
if (src.startsWith('data:')) return true;
const url = urlOf(src);
if (!url || url.origin !== window.location.origin) return false;
const photoId = photoIdOf(url);
return photoId === null || !hidden.has(photoId);
}
/** Whether a node of the page goes into the image. */
export function keepNode(node: Node, hidden: ReadonlySet<number>): boolean {
if (!(node instanceof Element)) return true;
const src = sourceOf(node);
return src === null || drawable(src, hidden);
}
/** The photos the kept pictures of a page show, each once. */
export function drawnPhotoIdsOf(root: Element, hidden: ReadonlySet<number>): number[] {
const ids = new Set<number>();
root.querySelectorAll('img, image').forEach((node) => {
const src = sourceOf(node);
const url = src !== null && drawable(src, hidden) ? urlOf(src) : null;
const photoId = url ? photoIdOf(url) : null;
if (photoId !== null) ids.add(photoId);
});
return [...ids];
}
/** Waits for one picture, loading it now if it was lazy. */
async function decoded(img: HTMLImageElement): Promise<void> {
img.loading = 'eager';
try {
await img.decode();
} catch {
// Drawn as the browser has it: a picture that cannot be decoded leaves its frame, and the page still goes.
}
}
/** Waits for the page's own pictures, at most `LOAD_TIMEOUT_MS`. */
async function picturesLoaded(root: Element, hidden: ReadonlySet<number>): Promise<void> {
const loads = [...root.querySelectorAll('img')].flatMap((img) => {
const src = img.getAttribute('src');
return src !== null && drawable(src, hidden) ? [decoded(img)] : [];
});
let timer: ReturnType<typeof setTimeout> | undefined;
const late = new Promise<void>((resolve) => {
timer = setTimeout(resolve, LOAD_TIMEOUT_MS);
});
await Promise.race([Promise.all(loads), late]);
clearTimeout(timer);
}
/**
* The sheet under `root` as a JPEG, its long edge at most
* `ASSISTANT_PAGE_IMAGE.longEdge` pixels. `size` is the sheet's own size in
* CSS pixels (`sheetSizePx`). Null when the image comes out larger than the
* server takes, so the turn goes on with the page's description.
*/
export async function snapshotSpread(
root: HTMLElement,
size: { width: number; height: number },
hiddenPhotoIds: ReadonlySet<number>
): Promise<PageSnapshot | null> {
await picturesLoaded(root, hiddenPhotoIds);
const scale = Math.min(1, ASSISTANT_PAGE_IMAGE.longEdge / Math.max(size.width, size.height));
const { domToBlob } = await import('modern-screenshot');
const image = await domToBlob(root, {
width: size.width,
height: size.height,
scale,
type: 'image/jpeg',
quality: ASSISTANT_PAGE_IMAGE.jpegQuality,
filter: (node) => keepNode(node, hiddenPhotoIds),
timeout: LOAD_TIMEOUT_MS,
fetch: { requestInit: { credentials: 'same-origin', cache: 'force-cache' } },
});
if (image.size > ASSISTANT_PAGE_IMAGE.maxBytes) return null;
return {
image,
width: Math.round(size.width * scale),
height: Math.round(size.height * scale),
drawnPhotoIds: drawnPhotoIdsOf(root, hiddenPhotoIds),
};
}
@@ -0,0 +1,238 @@
/**
* FE-STUDIO-AST-001 to FE-STUDIO-AST-007
*
* What TREK Studio does for its assistant (journey-studio.md 3.1, 4.5): it
* hosts the journey's chat while the column shows; it draws the page a turn
* asks for off screen, with other members' photos as empty frames, and sends
* it at the version the turn named; a page of a design draft comes from the
* draft; a preview runs on an unsaved copy; each question carries the page on
* screen; `?page=` shows a page. The snapshot
* and the repo are faked: a real browser draws the page in the Playwright flows.
*/
import {
type AiStatusResponse,
type AssistantPageRender,
blankBook,
type BookDocument,
bookPhotoElementSchema,
} from '@trek/shared';
import { useLocation } from 'react-router';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { act, fireEvent, render, screen, waitFor } from '../../../tests/helpers/render';
import { assistantRepo } from '../../repo/assistantRepo';
import { assistantChatKey } from '../../store/assistantChatKey';
import { chatOf, useAssistantStore } from '../../store/assistantStore';
import { useStudioStore } from '../../store/studioStore';
import { StudioPageStage } from './StudioAssistantPanel';
import { snapshotSpread } from './pageSnapshot';
import { renderJobOf, useStudioAssistant } from './useStudioAssistant';
vi.mock('./pageSnapshot', async (importOriginal) => ({
...(await importOriginal<typeof import('./pageSnapshot')>()),
snapshotSpread: vi.fn(),
}));
const JOURNEY = 12;
const KEY = assistantChatKey({ kind: 'journey', journeyId: JOURNEY });
const STATUS: AiStatusResponse = {
available: true,
policy: 'instance',
canConnectOwn: false,
effective: { source: 'instance', kind: 'openai', model: 'gpt', host: 'api.openai.com', paidBy: 'instance' },
own: null,
instance: { kind: 'openai', model: 'gpt', host: 'api.openai.com' },
quota: null,
privacyAcked: true,
studioImagesAcked: true,
retention: { mode: 'days', days: 90 },
openrouterOAuth: false,
};
const REQUEST: AssistantPageRender = {
requestId: '5f0c3a52-8d1e-4b7a-9c2f-0a1b2c3d4e5f',
threadId: 9,
spreadId: 'sp-3',
bookVersion: 4,
hiddenPhotoIds: [31],
};
/** A blank book (sp-1 to sp-5) with an own photo and another member's on the inner spread sp-3. */
function book(): BookDocument {
let seq = 0;
const doc = blankBook({ title: 'Lisbon', newId: (prefix) => `${prefix}-${++seq}` });
const own = bookPhotoElementSchema.parse({
id: 'p-own',
kind: 'photo',
frame: { x: 10, y: 10, w: 80, h: 60 },
photoId: 7,
});
const theirs = bookPhotoElementSchema.parse({
id: 'p-theirs',
kind: 'photo',
frame: { x: 230, y: 10, w: 80, h: 60 },
photoId: 31,
});
return { ...doc, spreads: doc.spreads.map((s) => (s.id === 'sp-3' ? { ...s, elements: [own, theirs] } : s)) };
}
function record(version: number) {
return { id: 1, journeyId: JOURNEY, title: 'Lisbon', version, updatedAt: null, updatedBy: null, document: book() };
}
function Location() {
return <output data-testid="search">{useLocation().search}</output>;
}
function Harness({ flush }: { flush: () => Promise<boolean> }) {
const assistant = useStudioAssistant({ journeyId: JOURNEY, flush });
return (
<>
<button type="button" onClick={assistant.toggle}>
{assistant.open ? 'close' : 'open'}
</button>
<StudioPageStage assistant={assistant} />
<Location />
</>
);
}
const flush = vi.fn(async () => true);
const host = () => useAssistantStore.getState().studioHosts[KEY];
beforeEach(() => {
window.localStorage.setItem('trek.studioAssistant', '1');
useAssistantStore.setState({ status: STATUS, byTrip: {}, studioHosts: {} });
useStudioStore.setState({ doc: null, selection: [], activeSpread: 0 });
});
afterEach(() => {
vi.restoreAllMocks();
vi.mocked(snapshotSpread).mockReset();
window.localStorage.clear();
});
describe('useStudioAssistant', () => {
it('FE-STUDIO-AST-001: hosts the chat while the column shows, remembered, never without an assistant', async () => {
render(<Harness flush={flush} />);
expect(host()).toBeDefined();
await act(async () => {
await host()?.flush();
});
expect(flush).toHaveBeenCalledTimes(1);
fireEvent.click(screen.getByRole('button', { name: 'close' }));
expect(host()).toBeUndefined();
expect(window.localStorage.getItem('trek.studioAssistant')).toBe('0');
fireEvent.click(screen.getByRole('button', { name: 'open' }));
expect(host()).toBeDefined();
act(() => useAssistantStore.setState({ status: { ...STATUS, available: false } }));
expect(host()).toBeUndefined();
});
it('FE-STUDIO-AST-002: draws the page asked for with other members photos left empty, and sends it', async () => {
vi.spyOn(assistantRepo, 'pageBook').mockResolvedValueOnce(record(4));
const upload = vi.spyOn(assistantRepo, 'uploadRender').mockResolvedValueOnce(undefined);
const image = new Blob(['jpeg'], { type: 'image/jpeg' });
let drawnSheet: HTMLElement | null = null;
vi.mocked(snapshotSpread).mockImplementationOnce(async (sheet) => {
drawnSheet = sheet;
return { image, width: 1280, height: 640, drawnPhotoIds: [7] };
});
const { container } = render(<Harness flush={flush} />);
act(() => host()?.render(REQUEST, new AbortController().signal));
await waitFor(() => expect(upload).toHaveBeenCalledTimes(1));
expect(upload.mock.calls[0]?.slice(0, 4)).toEqual([
JOURNEY,
9,
REQUEST.requestId,
{ image, bookVersion: 4, spreadId: 'sp-3', drawnPhotoIds: [7] },
]);
const sheet = drawnSheet as HTMLElement | null;
expect(sheet?.querySelector('img[src="/api/photos/7/thumbnail"]')).not.toBeNull();
expect(sheet?.querySelector('img[src*="/api/photos/31/"]')).toBeNull();
// The stage empties once the page is sent.
await waitFor(() => expect(container.querySelector('.st-assistant-stage')).toBeNull());
});
it('FE-STUDIO-AST-003: a book that moved on past the version asked for is not drawn or sent', async () => {
vi.spyOn(assistantRepo, 'pageBook').mockResolvedValueOnce(record(5));
const upload = vi.spyOn(assistantRepo, 'uploadRender');
render(<Harness flush={flush} />);
await act(async () => {
host()?.render(REQUEST, new AbortController().signal);
await Promise.resolve();
});
expect(assistantRepo.pageBook).toHaveBeenCalledWith(JOURNEY);
expect(snapshotSpread).not.toHaveBeenCalled();
expect(upload).not.toHaveBeenCalled();
});
it('FE-STUDIO-AST-007: a page of a design draft is drawn from the draft, never from the book', async () => {
const draft = book();
const designed = {
...draft,
spreads: draft.spreads.map((s) => (s.id === 'sp-3' ? { ...s, background: '#abcdef' } : s)),
};
const fromDraft = vi.spyOn(assistantRepo, 'pageDraft').mockResolvedValueOnce({ version: 4, document: designed });
const fromBook = vi.spyOn(assistantRepo, 'pageBook');
const upload = vi.spyOn(assistantRepo, 'uploadRender').mockResolvedValueOnce(undefined);
let background = '';
vi.mocked(snapshotSpread).mockImplementationOnce(async (sheet) => {
background = (sheet.firstElementChild as HTMLElement | null)?.style.background ?? '';
return { image: new Blob(['jpeg']), width: 1280, height: 640, drawnPhotoIds: [7] };
});
render(<Harness flush={flush} />);
act(() => host()?.render({ ...REQUEST, designId: 'd-1' }, new AbortController().signal));
await waitFor(() => expect(upload).toHaveBeenCalledTimes(1));
expect(fromDraft).toHaveBeenCalledWith(JOURNEY, 'd-1');
expect(fromBook).not.toHaveBeenCalled();
// The draft's background, however the DOM spells the colour back.
expect(background).toMatch(/#abcdef|171, 205, 239/i);
});
it('FE-STUDIO-AST-004:a preview runs its ops on an unsaved copy, nothing is drawn when they fail', () => {
const doc = book();
const deadline = { signal: new AbortController().signal, release: vi.fn() };
const job = renderJobOf(doc, { ...REQUEST, ops: [{ op: 'background', color: '#123456' }] }, deadline);
expect(job?.spread.background).toBe('#123456');
expect(job?.folios.length).toBeGreaterThan(0);
expect([...(job?.hidden ?? [])]).toEqual([31]);
expect(doc.spreads[2]?.background).toBeNull();
expect(renderJobOf(doc, { ...REQUEST, spreadId: 'sp-99' }, deadline)).toBeNull();
// An element the page does not hold refuses the whole edit.
const missing: AssistantPageRender = { ...REQUEST, ops: [{ op: 'remove', elementIds: ['nope'], park: true }] };
expect(renderJobOf(doc, missing, deadline)).toBeNull();
});
it('FE-STUDIO-AST-005: each question carries the page on screen and the elements selected on it', () => {
act(() => {
useStudioStore.getState().load(book());
useStudioStore.getState().setActiveSpread(2);
useStudioStore.getState().select(['p-own', 'not an id!']);
});
render(<Harness flush={flush} />);
expect(chatOf(useAssistantStore.getState(), KEY).focus).toEqual({ spreadId: 'sp-3', elementIds: ['p-own'] });
act(() => useStudioStore.getState().select([]));
expect(chatOf(useAssistantStore.getState(), KEY).focus).toEqual({ spreadId: 'sp-3' });
});
it('FE-STUDIO-AST-006: ?page= shows that page and leaves the address', async () => {
act(() => useStudioStore.getState().load(book()));
render(<Harness flush={flush} />, { initialEntries: ['/journey/12/studio?page=sp-4'] });
await waitFor(() => expect(useStudioStore.getState().activeSpread).toBe(3));
await waitFor(() => expect(screen.getByTestId('search').textContent).toBe(''));
});
});
@@ -0,0 +1,269 @@
import {
ASSISTANT_PAGE_IMAGE,
applyBookOps,
bookElementIdSchema,
bookSpreadIdSchema,
type AssistantPageRender,
type BookDocument,
type BookPageSetup,
type BookSpread,
} from '@trek/shared';
import { useCallback, useEffect, useState } from 'react';
import { useSearchParams } from 'react-router';
import { assistantRepo } from '../../repo/assistantRepo';
import { assistantChatKey } from '../../store/assistantChatKey';
import { useAssistantStore } from '../../store/assistantStore';
import { useStudioStore } from '../../store/studioStore';
import { foliosOf } from './bookSheets';
import { sheetSizePx, snapshotSpread } from './pageSnapshot';
/**
* The assistant inside TREK Studio (journey-studio.md 4.5): whether its column
* is open, the journey's chat it hosts, and what the Studio does for that chat.
*
* - Before a turn or an apply goes out, the book's local work is written
* (`flush`), so the assistant edits the book the user sees.
* - Each question carries the page on screen and the elements selected on it.
* - A page a turn asks to look at is drawn here, by the editor's own
* SpreadView off screen, and uploaded as an image (3.1): a page of the
* book, or of a design draft the assistant has not applied yet.
* - `?page=<spread id>`, which a page card opens, shows that page.
*/
/** Where the column's open state is kept between visits, like the planner's assistant window. */
const OPEN_STORAGE = 'trek.studioAssistant';
/** Element ids a question's focus carries at most, as the contract takes them. */
const MAX_FOCUS_ELEMENTS = 30;
/** One page a turn asked for, ready for the stage to draw. */
export interface StudioRenderJob {
request: AssistantPageRender;
spread: BookSpread;
page: BookPageSetup;
folios: number[];
hidden: ReadonlySet<number>;
/** Ends with the turn, or once the turn has stopped waiting for the page. */
signal: AbortSignal;
/** Lets go of the turn's signal once the page is sent or given up. */
release: () => void;
}
function readOpen(): boolean {
try {
return window.localStorage.getItem(OPEN_STORAGE) === '1';
} catch {
return false;
}
}
function writeOpen(open: boolean): void {
try {
window.localStorage.setItem(OPEN_STORAGE, open ? '1' : '0');
} catch {
// Storage refused (a private window): the column stays as it is for this visit only.
}
}
/** The turn's signal, also ended once the turn has stopped waiting for the page. */
function withDeadline(signal: AbortSignal): { signal: AbortSignal; release: () => void } {
const controller = new AbortController();
const stop = () => controller.abort();
const timer = setTimeout(stop, ASSISTANT_PAGE_IMAGE.timeoutMs);
signal.addEventListener('abort', stop, { once: true });
if (signal.aborted) stop();
return {
signal: controller.signal,
release: () => {
clearTimeout(timer);
signal.removeEventListener('abort', stop);
},
};
}
/**
* The page a request asks for, from the book at the version it names: with
* the request's ops applied to an unsaved copy (a preview). Null when the
* page is gone or the ops do not apply, so nothing is drawn.
*/
export function renderJobOf(
doc: BookDocument,
request: AssistantPageRender,
deadline: { signal: AbortSignal; release: () => void }
): StudioRenderJob | null {
let next = doc;
if (request.ops) {
const made = applyBookOps(doc, { spreadId: request.spreadId, ops: request.ops });
if (made.ok === false) return null;
next = made.doc;
}
const index = next.spreads.findIndex((s) => s.id === request.spreadId);
const spread = next.spreads[index];
if (!spread) return null;
return {
request,
spread,
page: next.page,
folios: foliosOf(next.spreads, index, next.page.pageNumbers.startAt),
hidden: new Set(request.hiddenPhotoIds),
...deadline,
};
}
/**
* The job for a request, from the book as the server holds it, or from the
* design draft the request names (`designId`, a page of a whole-book design
* not applied yet); null when the page cannot be drawn.
*/
async function jobFor(
journeyId: number,
request: AssistantPageRender,
deadline: { signal: AbortSignal; release: () => void }
): Promise<StudioRenderJob | null> {
try {
const book = request.designId
? await assistantRepo.pageDraft(journeyId, request.designId)
: await assistantRepo.pageBook(journeyId);
// Moved on since the turn asked: an image of another version would be refused, so it goes on as text.
if (!book || book.version !== request.bookVersion || deadline.signal.aborted) return null;
return renderJobOf(book.document, request, deadline);
} catch {
// Offline or refused: the turn waits out its time and goes on with the page's description.
return null;
}
}
/** A drawn sheet as an image, sent to the turn that asked for it. */
async function sendPage(journeyId: number, job: StudioRenderJob, sheet: HTMLElement): Promise<void> {
if (job.signal.aborted) return;
const shot = await snapshotSpread(sheet, sheetSizePx(job.spread, job.page), job.hidden);
if (!shot || job.signal.aborted) return;
const { bookVersion, spreadId, threadId, requestId } = job.request;
const page = { image: shot.image, bookVersion, spreadId, drawnPhotoIds: shot.drawnPhotoIds };
await assistantRepo.uploadRender(journeyId, threadId, requestId, page, job.signal);
}
/** The pages turns ask for: read at their version, queued for the stage, drawn and uploaded. */
function usePageRenders(journeyId: number) {
const [jobs, setJobs] = useState<StudioRenderJob[]>([]);
const prepare = useCallback(
async (request: AssistantPageRender, signal: AbortSignal) => {
const deadline = withDeadline(signal);
const job = await jobFor(journeyId, request, deadline);
if (job) setJobs((current) => [...current, job]);
else deadline.release();
},
[journeyId]
);
const render = useCallback(
(request: AssistantPageRender, signal: AbortSignal) => {
void prepare(request, signal);
},
[prepare]
);
/** The stage drew a job's page: turn it into an image and send it, then take it off the stage. */
const drawn = useCallback(
async (job: StudioRenderJob, sheet: HTMLElement) => {
try {
await sendPage(journeyId, job, sheet);
} catch {
// A page that cannot be drawn or sent is never the user's error: the turn goes on with the description.
} finally {
job.release();
setJobs((current) => current.filter((j) => j !== job));
}
},
[journeyId]
);
return { jobs, render, drawn };
}
/** Each question carries the page on screen and the elements selected on it, as far as the contract takes them. */
function useStudioFocus(key: number, open: boolean) {
const spreadId = useStudioStore((st) => st.doc?.spreads[st.activeSpread]?.id ?? null);
const selection = useStudioStore((st) => st.selection);
const setFocus = useAssistantStore((s) => s.setFocus);
useEffect(() => {
if (!open) return;
if (spreadId === null || !bookSpreadIdSchema.safeParse(spreadId).success) {
setFocus(key, null);
return;
}
const elementIds = selection.filter((id) => bookElementIdSchema.safeParse(id).success).slice(0, MAX_FOCUS_ELEMENTS);
setFocus(key, elementIds.length > 0 ? { spreadId, elementIds } : { spreadId });
}, [open, key, spreadId, selection, setFocus]);
}
/** `?page=<spread id>`, which a page card opens: shows that page once the book is there, then leaves the address. */
function usePageParam() {
const [params, setParams] = useSearchParams();
const wanted = params.get('page');
const loaded = useStudioStore((st) => st.doc !== null);
const setActiveSpread = useStudioStore((st) => st.setActiveSpread);
useEffect(() => {
if (wanted === null || !loaded) return;
const index = useStudioStore.getState().doc?.spreads.findIndex((s) => s.id === wanted) ?? -1;
if (index >= 0) setActiveSpread(index);
setParams(
(current) => {
const next = new URLSearchParams(current);
next.delete('page');
return next;
},
{ replace: true }
);
}, [wanted, loaded, setActiveSpread, setParams]);
}
export function useStudioAssistant({ journeyId, flush }: { journeyId: number; flush: () => Promise<boolean> }) {
const key = assistantChatKey({ kind: 'journey', journeyId });
const available = useAssistantStore((s) => s.status?.available === true);
const hasStatus = useAssistantStore((s) => s.status !== null);
const loadStatus = useAssistantStore((s) => s.loadStatus);
const hostStudio = useAssistantStore((s) => s.hostStudio);
const [open, setOpen] = useState(readOpen);
const renders = usePageRenders(journeyId);
const { render } = renders;
const showing = open && available;
// The planner's window loads it too; the Studio may be the first to ask.
useEffect(() => {
if (!hasStatus) void loadStatus();
}, [hasStatus, loadStatus]);
// The chat is hosted while its column shows: closing it ends the chat's turn anyway.
useEffect(() => {
if (!showing) return undefined;
return hostStudio(key, { render, flush });
}, [showing, key, render, flush, hostStudio]);
useStudioFocus(key, showing);
usePageParam();
const toggle = useCallback(() => {
writeOpen(!open);
setOpen(!open);
}, [open]);
return {
/** The chat's key in the assistant store. */
chatKey: key,
/** Whether the assistant can run for this user at all; the toggle shows only then. */
available,
/** Whether the chat column shows. */
open: showing,
toggle,
/** The pages being drawn for a turn, for the stage. */
jobs: renders.jobs,
drawn: renders.drawn,
};
}
export type StudioAssistant = ReturnType<typeof useStudioAssistant>;