fix(studio): the assistant column draws the page the server applied, and reads the user's role

A page preview draws the spread the server applied with the journey's photos,
texts and figures instead of applying the operations again without them. The
Studio's welcome, privacy banner and header fit a journey chat: a viewer is
told they can only look, the banner speaks of the book, and the trip notes
button stays in the trip chat. Escape closes the header menu before it stops a
reply, a single page renders at the full long edge, the status says a model
reads pages only while its provider has not refused an image, and pointing at
a page in a design card outlines it in the Studio.
This commit is contained in:
Maurice
2026-10-23 01:45:16 +00:00
parent 72c61f242e
commit 9e40092507
85 changed files with 857 additions and 144 deletions
@@ -23,7 +23,7 @@ import { maskHint, openSecrets, sealSecrets } from './ai-secrets';
import { AiSettingsService } from './ai-settings.service';
import { AiUsageService } from './ai-usage.service';
import { ChatgptAuthService } from './chatgpt-auth.service';
import { ModelCatalogService, pickDefaultModel, type CatalogTarget } from './model-catalog.service';
import { ModelCatalogService, modelReadsImages, pickDefaultModel, type CatalogTarget } from './model-catalog.service';
import { AiProviderError } from './providers/provider-errors';
import { InjectRepository } from '@mikro-orm/nestjs';
import { Injectable } from '@nestjs/common';
@@ -89,6 +89,9 @@ export class AiConnectionsService implements SharedAiConnectionPort {
private readonly audit: AuditService,
) {}
/** `kind:model` of the models a provider refused an image for, while this process runs. */
private readonly textOnly = new Set<string>();
/** Whether the assistant exists here at all: the addon is on and the install is not centrally administered. */
async enabled(): Promise<boolean> {
return !readEnv().managed.enabled && (await this.addons.isAddonEnabled(ADDON_IDS.AI_ASSISTANT));
@@ -129,6 +132,7 @@ export class AiConnectionsService implements SharedAiConnectionPort {
? { used: await this.usage.instanceTurnsToday(userId), limit: settings.dailyTurns }
: null,
privacyAcked: acked,
studioImages: !!effective && this.readsImages({ kind: kindOf(effective), model: effective.model }),
studioImagesAcked: !!effective && (await this.studioImagesAckedFor(userId, `${kindOf(effective)}@${host}`)),
retention: settings.retention,
openrouterOAuth: openrouterOAuthAvailable(),
@@ -247,6 +251,21 @@ export class AiConnectionsService implements SharedAiConnectionPort {
return (await this.settings.getDecryptedUserSetting(userId, AI_STUDIO_IMAGES_ACK_SETTING)) === target;
}
/**
* Whether a model is shown the Studio's pages as images: its name says it
* reads them, and no provider refused an image for it while this process
* runs. Status asks this too, so the Studio offers images only where a turn
* would send them.
*/
readsImages({ kind, model }: Pick<ResolvedAiConnection, 'kind' | 'model'>): boolean {
return modelReadsImages(kind, model) && !this.textOnly.has(`${kind}:${model}`);
}
/** A provider refused an image for this model: it reads pages in words until the process restarts. */
refuseImages({ kind, model }: Pick<ResolvedAiConnection, 'kind' | 'model'>): void {
this.textOnly.add(`${kind}:${model}`);
}
// ── The instance's connection (admin) ──────────────────────────────────────
async readSettings(): Promise<AiAdminSettings> {
+11 -14
View File
@@ -1,7 +1,6 @@
import type { AiChatMessage, AiImage } from '../ai-connections/ai-chat-client.interface';
import { AiConnectionsService } from '../ai-connections/ai-connections.service';
import type { ResolvedAiConnection } from '../ai-connections/ai-connections.types';
import { modelReadsImages } from '../ai-connections/model-catalog.service';
import { logDebug } from '../audit/audit-log.logger';
import { DomainError } from '../common/domain-error';
import { withRequestContext } from '../database/request-context';
@@ -23,6 +22,7 @@ import {
type BookDocument,
type BookElement,
type BookPageOp,
type BookSpread,
} from '@trek/shared';
import { randomUUID } from 'node:crypto';
@@ -142,7 +142,7 @@ function reason(err: unknown): string {
return err instanceof Error ? err.message : String(err);
}
/** Builds each Studio turn's vision, and remembers the models a provider refused an image for. */
/** Builds each Studio turn's vision; the connections remember the models a provider refused an image for. */
@Injectable()
export class AssistantVision {
constructor(
@@ -153,9 +153,6 @@ export class AssistantVision {
private readonly orm: MikroORM,
) {}
/** `kind:model` of the models a provider refused an image for, while this process runs. */
private readonly textOnly = new Set<string>();
/** A turn's tools and its vision: a Studio turn's with the page preview beside them, a trip turn's as they are. */
async turnTools(
scope: AssistantScope,
@@ -168,18 +165,16 @@ export class AssistantVision {
}
async forTurn(input: VisionTurnInput): Promise<TurnVision> {
const model = `${input.connection.kind}:${input.connection.model}`;
let images =
input.renders &&
modelReadsImages(input.connection.kind, input.connection.model) &&
!this.textOnly.has(model) &&
this.connections.readsImages(input.connection) &&
(await withRequestContext(this.orm, () => this.connections.studioImagesAcked(input.userId, input.connection)));
const vision: TurnVision = {
sendsImages: () => images,
look: (spreadId, ops, designId) => this.look(input, images, spreadId, { ops, designId }),
refused: () => {
images = false;
this.textOnly.add(model);
this.connections.refuseImages(input.connection);
},
afterApply: (history) => (images ? this.afterApply(vision, history) : Promise.resolve([...history])),
};
@@ -246,8 +241,10 @@ export class AssistantVision {
const photos = (base.ctx.photos ?? []).map((p) => (hidden.includes(p.photoId) ? { ...p, hidden: true } : p));
const described = describeSpread(doc, spreadId, photos);
if (!described) return { ok: false, value: `This book has no page ${spreadId}: get_book lists its pages.` };
// A proposal goes as the page applied here, with the journey's photos, words and figures the Studio lacks.
const spread = ops ? doc.spreads.find((s) => s.id === spreadId) : undefined;
const image = draws
? await this.render(input, { spreadId, bookVersion: base.version, ops, designId, hidden })
? await this.render(input, { spreadId, bookVersion: base.version, spread, designId, hidden })
: null;
const value = {
spreadId,
@@ -265,18 +262,18 @@ export class AssistantVision {
/** Asks the Studio tab for the page and waits for it; null when none came in time or the turn stopped. */
private async render(
input: VisionTurnInput,
page: { spreadId: string; bookVersion: number; ops?: BookPageOp[]; designId?: string; hidden: number[] },
page: { spreadId: string; bookVersion: number; spread?: BookSpread; designId?: string; hidden: number[] },
): Promise<PageImage | null> {
const requestId = randomUUID();
const { userId, journeyId, threadId, signal } = input;
const { spreadId, bookVersion, ops, designId, hidden } = page;
const { spreadId, bookVersion, spread, designId, hidden } = page;
// Waiting before asking: an upload that comes back at once finds its turn.
const waiting = this.registry.wait(
{ userId, journeyId, threadId, requestId, spreadId, bookVersion },
signal,
ASSISTANT_PAGE_IMAGE.timeoutMs,
);
// A draft's page: the Studio draws it from the draft (GET .../book-designs/:designId).
// A draft's page: the Studio draws it from the draft (GET .../book-designs/:designId); a proposal's as sent.
const asked = {
requestId,
threadId,
@@ -285,7 +282,7 @@ export class AssistantVision {
hiddenPhotoIds: hidden,
...(designId ? { designId } : {}),
};
input.w.renderRequest(ops ? { ...asked, ops } : asked);
input.w.renderRequest(spread ? { ...asked, spread } : asked);
const image = await waiting;
// Size and dimensions only: the page shows the user's photos.
if (image) logDebug(`[assistant] page image ${image.width}x${image.height}, ${image.data.length} bytes`);