Lorebook Entry Images — Design Document

Status:

User-facing docs for the live (Side A) feature live at /features/picture-entries. This document is the design source of truth and tracks Side B + carousel + open seams.

Overview

Lorebook entries describe world-building concepts — characters, locations, items, factions, etc. Adding an image to an entry gives visual context to that world-building data.

Two independent features, two independent toggles

When entries trigger during a conversation, their images have two unrelated payoffs, and we treat them as two separate features that ship in two separate phases with two separate user toggles:

Side A — UI display Side B — Vision injection
What it does Shows the triggered entry's image to the user in the chat UI Sends the image into the LLM prompt as multimodal content
Who it's for Every user — visual context for the human reader Users on vision-capable models who want the AI to "see" the image
Cost Bandwidth only Significant token cost per turn
Default On Off
Toggle key Features.EnableLorebookImages Features.SendLorebookImagesToLlm
HowDrawer row "Picture entries" (existing placeholder, repurposed) New coming-soon row added in Side A's phase, wired in Side B's phase
Shipping order First Second (independent — Side B can ship months later)

The two toggles are independent. A user can enable UI display without vision injection (default), enable vision without UI, or enable / disable both. Side B may add a soft hint in the UI ("you have vision injection on but not display — you can't see what the AI sees"), but neither toggle is hard-dependency-locked on the other. Both, however, are dependency-locked on Features.EnableLorebook — turning off lorebooks turns off both image features.

The shared backend work — gallery FK, upsert, search/expand returning picture_image_id, creator-side picker — happens once in Phase 1 and serves both sides. Everything after that splits.

Core Goals


What's Already in Place

The unified gallery system that this feature plugs into is already shipped and in use elsewhere:

Piece Location
gallery_images table database/v1/31_* (table family)
gallery_image_entity_links join table database/v1/31d_entity_avatar_image_links.sql
*_image_id FK pattern on entities characters, lorebooks (picture_image_id), users, personas
GalleryImageStorageService server/EchoOfDreams.Core/Services/GalleryImageStorageService.cs
Presigned upload/download flow server/EchoOfDreams.ServerAPI/Api/Endpoints/GalleryEndpoints.cs
Thumbnail generation, content rating, moderation gallery pipeline
HowDrawer coming-soon placeholder "Picture entries" clientConsole/src/pages/chat-v2/components/HowDrawer.tsx (line ~1034) — needs wiring to a real toggle + copy rewrite
FeatureRow + ConversationFeatureState toggle pattern clientConsole/src/pages/chat-v2/components/how/FeatureRow.tsx, server/EchoOfDreams.WebChat/Services/IWebChatFeatureStateService.cs
Shared ImagePickerModal (gallery / upload / URL tabs) shared/src/components/common/ImagePickerModal.tsx
ImagePickerField (thumbnail + open-picker affordance) shared/src/components/common/ImagePickerField.tsx
useImagePicker hook (data fetching + state) clientConsole/src/hooks/useImagePicker.ts
ContentImage + ContentImageContext (rating-aware blur) shared/src/components/common/ContentImage.tsx, ContentImageContext.tsx
ImageLightbox (full-size view) shared/src/components/common/ImageLightbox.tsx
ReportModal + reportsApi clientConsole/src/components/common/ReportModal.tsx, clientConsole/src/api/reports.ts
Legacy URL → gallery migration precedent database/v1/38_migrate_legacy_image_urls.sql (characters, lorebooks, personas)
EntityType.Lorebook = 2, sub-entity Entry Core/Entities/EntityRegistry.cs

What is not in place yet for entries:


Database Changes

New column on lorebook_entries

Match the existing convention (characters.avatar_image_id, lorebooks.picture_image_id):

ALTER TABLE lorebook_entries
    ADD COLUMN IF NOT EXISTS picture_image_id INTEGER
        REFERENCES gallery_images(id) ON DELETE SET NULL;

CREATE INDEX IF NOT EXISTS idx_lorebook_entries_picture_image
    ON lorebook_entries(picture_image_id)
    WHERE picture_image_id IS NOT NULL;

COMMENT ON COLUMN lorebook_entries.picture_image_id IS
    'FK to gallery_images. The image and its alt text are read from gallery_images.';

Alt text, content type, content rating, dimensions, and moderation status all live on gallery_images — no duplication.

Entries plug into gallery_image_entity_links like every other entity that uses gallery images — that's how fn_gallery_image_usage ("where is this image used?") and fn_get_entity_linked_images work, and every existing Set*ImageAsync (characters, lorebooks, personas) populates this table. Entries get the same treatment for consistency.

gallery_image_entity_links keys by (entity_type, entity_id), and EntityType.Lorebook = 2 is already taken by top-level lorebooks. So:

Updated functions


API Endpoints

Reuse the existing gallery upload flow rather than building a new one:

# Existing — already shipped
POST   /api/gallery/upload-url            # presigned PUT
POST   /api/gallery/confirm               # finalize gallery_images row

# New — entry-level link/unlink (mirrors Lorebook.SetPictureImageAsync)
PUT    /api/creator/lorebooks/{lorebookId}/entries/{entryId}/picture
       body: { imageUuid: "…" | null }
DELETE /api/creator/lorebooks/{lorebookId}/entries/{entryId}/picture

The entry upsert endpoint also accepts an optional pictureImageUuid so creating an entry with an image is a single round-trip.

External-URL pasting is no longer entry-specific: a creator pastes a URL into the gallery uploader, gallery creates a row with external_url, the entry FKs to it. This keeps content moderation consistent.


Subscription Limits

No new entry-specific limits. Image size, allowed types, and per-user storage caps all live on the gallery system and apply uniformly. Image count is bounded by the entry count (one per entry).


Conversation Integration

This section is split into the two independent sides described in the Overview. Side A (UI display) is Phase 2 and ships first. Side B (vision injection) is Phase 3 and is independently shippable later. Each side has its own toggle in HowDrawer; they do not depend on each other.

Side A — Chat UI display (ships first, Phase 2)

When the lorebook pipeline matches entries during a conversation turn, matched entries that have a picture_image_id are included in the response metadata. The chat UI renders the triggered images using the existing ContentImage wrapper, which already implements the user's blur preferences (blurSuggestive, blurNSFW, blurIntensity from ContentImageContext). Pass the image's contentRating and moderationStatus through from gallery_images — under-review images get a non-revealable blur for free.

The thumbnail carries a small report affordance wired to the existing ReportModal (clientConsole/src/components/common/ReportModal.tsx). ReportEntityType doesn't currently include image-level reporting — add a 'GalleryImage' (or 'LorebookEntry') variant so users can flag a triggered image as miscategorized or inappropriate without leaving the chat. The button is intentionally tiny (<Button iconOnly size="xs" icon="flag">), positioned in the corner of the thumbnail container so it doesn't compete with the conversation.

v1: only the top matched entry's image is shown

Even when several matched entries have images, v1 renders exactly one — the highest-ranked match (same ranking the lorebook pipeline already computes for entry priority). Rationale:

The pipeline still emits the full list of matched-with-image entries in metadata (so v2 can light up without a server change) — the UI just slices [0].

v2 — multi-image carousel. Once a shared rotating-image component lands (modeled on the existing HeroBanner carousel — shared/src/components/common/HeroBanner.tsx — with bottom dots and < / > arrows), the panel switches to that component and shows all matched-with-image entries. Don't reimplement the rotation; extract the navigation/dots from HeroBanner into a reusable primitive (e.g. <ImageCarousel>) and use it in both places. Until that primitive exists, v1 stays single-image.

Streaming the image list before the assistant text

Lorebook matching runs in ContextBuildingStageBase — a pre-LLM stage, before the first content token. The matched entries (and therefore their picture_image_ids and resolved URLs) are fully known by the time ChatPipeline.ExecuteStreamAsync enters the LLM call. We exploit that:

Why this matters:

The full list is emitted, even though v1 only renders [0]. v2's carousel lights up by changing the renderer, not the protocol.

Failure handling: if the image list is empty (no matches with images), no LorebookImages token is sent — the panel never renders. If the token never arrives (older client / pipeline error), the chat falls back to the metadata that's also attached to the assistant message on Done, so the panel still appears post-stream.

Layout (per breakpoint)

The triggered-images panel changes location based on viewport and chat layout state:

Mobile — inline, expand/collapse:

┌──────────────────────────────┐
│  AI message text here...     │
│  ...                         │
├──────────────────────────────┤
│ ▸ Elara's Tower              │  ← collapsed by default
└──────────────────────────────┘
        ↓ tap to expand ↓
┌──────────────────────────────┐
│  AI message text here...     │
├──────────────────────────────┤
│ ▾ Elara's Tower         ⚐    │
│  ┌────────────────────┐      │
│  │      🏰            │      │
│  │   (thumbnail)      │      │
│  └────────────────────┘      │
└──────────────────────────────┘

Desktop, focus mode or one drawer collapsed — side panel:

┌────────────────────┬────────────┐
│                    │ Elara's    │
│                    │ Tower  ⚐   │
│                    │ ┌────────┐ │
│   chat messages    │ │ 🏰     │ │
│                    │ │ tower  │ │
│                    │ └────────┘ │
│                    │            │
└────────────────────┴────────────┘

Desktop, both drawers open — falls back to inline (mobile-style) inside the message column. The condition is "is there spare side gutter ≥ 240px" rather than a hard breakpoint.

Display is independent of vision injection — flipping Features.SendLorebookImagesToLlm (Side B) on or off changes nothing on Side A's path.

Side A toggle: Features.EnableLorebookImages

Plug into the existing feature-toggle infrastructure rather than inventing a new bespoke setting. The Features.Enable{Summaries,Memories,Lorebook} family already exists:

Setting key:    Features.EnableLorebookImages
Default:        true
Scope:          per-conversation (overridable per-channel on Discord), with user default
Dependency:     Features.EnableLorebook (lorebook itself must be on)
Independence:   NOT linked to Features.SendLorebookImagesToLlm — the two toggles are orthogonal

Server work — extend ConversationFeatureState with LorebookImagesEnabled (raw user toggle) and ModeSupportsLorebookImages (mirrors ModeSupportsLorebook for the dependency-lock badge). The pipeline checks the resolved-effective value before emitting the LorebookImages token; when disabled, no token is sent and no panel renders.

Client work — wire the existing "Picture entries" row in HowDrawer to Features.EnableLorebookImages. It renders dependency-locked with requires="Lorebook" when lorebook itself is off, mirroring the existing Memories-requires-Summaries behavior.

"Coming soon" row already exists

A coming-soon placeholder row labeled "Picture entries" is already rendered in HowDrawer.tsx (in the inline "Coming soon" group alongside Trackers / Journal / Living Lorebook). It has no setting key, no ConversationFeatureState wiring — it's pure UI copy at this point.

Two notes on the existing row:

  1. Current copy is vision-focused. The placeholder description today reads "Image-bearing lorebook entries. When the entry triggers, its image goes into the prompt for vision-capable models — a way to describe a character or setting visually instead of writing every detail in text." That frames the feature as Phase 3 (LLM multimodal), not Phase 2 (chat-UI display). Rewrite the copy to lead with the visible-in-chat behavior — it ships first and is the more universally useful half — with a one-liner about the optional vision-injection follow-up.

  2. No backfill schema work needed for the toggle to become real. Going from placeholder to functional is: add Features.EnableLorebookImages to SettingsKeys, surface LorebookImagesEnabled + ModeSupportsLorebookImages on ConversationFeatureState, replace the row's hard-coded state={{ kind: 'coming-soon' }} with the resolved state from feature-state. No setting rename, no migration.

Practical sequencing — Phase 2 splits cleanly:

Side B — LLM vision injection (ships independently, Phase 3)

A second, separate feature with its own toggle. Side B can ship months after Side A — or never — without changing anything on Side A's path. Likewise, Side A users don't need vision-capable models, while Side B is gated on them.

Side B toggle: Features.SendLorebookImagesToLlm

Setting key:    Features.SendLorebookImagesToLlm
Default:        false  (vision tokens are expensive)
Scope:          per-conversation (overridable per-channel on Discord), with user default
Dependency:     Features.EnableLorebook (lorebook itself must be on)
Independence:   NOT linked to Features.EnableLorebookImages — a user can send to LLM without
                seeing in chat, or vice versa, in any combination
Hard requirement: active model must support vision; toggle is disabled with a tooltip otherwise

A new HowDrawer row (separate from "Picture entries") is added in Phase 3. It ships in coming-soon state during Phase 2 if convenient, with copy that explicitly distinguishes it from Side A: "Send the matched entry's image into the prompt for vision-capable models. Increases token cost. Independent of whether you display the image in chat."

When enabled

  1. LorebookContentProvider collects picture_image_ids from matched entries
  2. Resolves them to URLs via the gallery service (presigned for uploads, direct for external_url)
  3. The pipeline emits multimodal content blocks (text + image) instead of text-only
  4. The LLM receives the image alongside the entry text

Cost transparency in the UI

Pipeline changes (Side B only)

The LorebookContentProvider currently returns a plain string. To support multimodal:

public record PromptContent(string Text, IReadOnlyList<ContentImage>? Images = null);
public record ContentImage(string Url, string? AltText = null);

Image caching

To avoid re-fetching/re-encoding on every turn:


Creator UI

Entry editor

A new "Image" section in the entry form. No new UI components — drop in the existing shared ImagePickerField (which wraps ImagePickerModal via useImagePicker), the same picker already used everywhere else images are attached. It ships gallery / upload / external-URL tabs out of the box, plus thumbnail preview, clear, and showcase coverage.

Entry list

Entries with images show a small image indicator. Hover reveals the thumbnail.

Export / Import


Implementation Phases

Phase 1: Images on entries (creator feature) — shipped

What landed:

  1. database/v1/40_lorebook_entry_picture_image.sql — adds lorebook_entries.picture_image_id INTEGER REFERENCES gallery_images(id) ON DELETE SET NULL + partial index. Wired into v1_run_all.sql.
  2. LorebookEntryRow gains picture_image_id + 8 joined gallery fields; EntrySelectColumns left-joins gallery_images.
  3. ILorebookRepository.SetEntryPictureImageAsync(entryId, lorebookId, actorUserId, imageUuid?) — scoped to the entry's parent lorebook (the entry endpoints authorize can_edit on it, so a project editor's picture lands; until 2026-10-09 the setter was owner-only and dropped an editor's picture behind a 200), the image must be the actor's own or the entry's current picture, and it returns false when nothing landed so the endpoint refuses with image_not_in_gallery; populates gallery_image_entity_links with entity_type = 13 (literal id reserved for lorebook entries; distinct from 2 = top-level lorebook).
  4. Create/UpdateLorebookEntryRequest gain Guid? PictureImageUuid (three-state: null / Guid.Empty / value). LorebookEntryItem gains PictureImageUuid + content rating + moderation status + resolved URL + content type. MapToLorebookEntryItem helper centralizes mapping.
  5. Creator UI: <ImagePickerField> + <ImagePickerModal> integrated into LorebookEntriesPanel's entry editor with a pictureDirty flag so untouched entries omit the field on save.

Notably not implemented (skipped vs original plan): no separate PUT/DELETE /entries/{entryId}/picture endpoints — picture changes flow through the entry create/update endpoints' pictureImageUuid field, mirroring the lorebook precedent. No change to fn_upsert_lorebook_entry SQL — the picture is set via a follow-up SetEntryPictureImageAsync call instead.

Phase 2a — Side A: Wire the existing "Picture entries" row — shipped

What landed:

  1. Features.EnableLorebookImages added to SettingsKeys + seeded as true by default in SettingsDefaults with label "Picture entries" + display order 4 (right after Lorebook).
  2. ConversationFeatureState extended with LorebookImagesEnabled + ModeSupportsLorebookImages. WebChatFeatureStateService resolves the user toggle and mirrors ModeSupportsLorebook for the mode capability check.
  3. ModeSupportsDto and FeatureTogglesDto both gain LorebookImages. ConversationsEndpoints plumbs them through.
  4. Frontend: Features.EnableLorebookImages constant in clientConsole/src/constants/settingKeys.ts; ModeSupports.lorebookImages + FeatureToggles.lorebookImages added to chat types; effectiveConversation overlay in HowDrawer extended with the new toggle so optimistic updates work.

Phase 2a was effectively bundled with 2b in the final shipping, so the "ship as coming-soon first" interim step was skipped — by the time the toggle plumbing was complete, the renderer was right behind it. The HowDrawer row went straight from coming-soon placeholder to fully interactive in Phase 2b.

Phase 2b — Side A: Chat UI display (single image) — shipped

What landed:

  1. fn_search_lorebook and fn_expand_lorebook_entries extended to return 9 picture columns (picture_image_id, picture_image_uuid, picture_content_rating, picture_moderation_status, resolved_picture_url, three bucket keys, picture_content_type) plus parent lorebook identity (lorebook_id, lorebook_uuid, lorebook_name). The gallery_images join + lorebooks join sit after LIMIT in the final SELECT so they only fire for result rows. Three always-include inline queries in LorebookSearchRepository got the same shape.
  2. LorebookSearchResult gains 11 new fields (9 picture + lorebook id/uuid/name). MatchedEntryImage record carries the per-turn payload to the streaming layer.
  3. IPipelineContext.MatchedEntryImages: IReadOnlyList<MatchedEntryImage>? — defaults null; LorebookContentProvider populates it as a by-product of building lorebook content. Defensively drops under-review images at the source (defense in depth — ContentImage also enforces).
  4. ChatPipeline.ExecuteStreamAsync emits PipelineToken.LorebookImagesToken(images) immediately after Start and before the LLM call. Triple-gated: list non-empty + Features.EnableLorebookImages on + Features.EnableLorebook on.
  5. SSE writer in ConversationsEndpoints.MapPipelineTokenToEvent forwards as { type: "lorebook-images", images: [...] } over the existing single SSE channel.
  6. SSEStreamCallbacks.onLorebookImages? callback in processSSEStream. NewChatPage uses a pendingImagesRef to bridge the gap between the pre-LLM event and the eventual done/stopped event when the assistant message gets its id. Both send + regenerate flows wired.
  7. Message.triggeredEntryImages?: TriggeredEntryImage[] field added.
  8. New TriggeredEntryImagesPanel component — renders only the top match (v1), inline placement under the assistant bubble, collapsed by default on touch / expanded by default on desktop, uses <ContentImage> for blur, tap → <ImageLightbox> (single-image, no nav), report button opens <ReportModal> against the image itself (GalleryImage, shipped 2026-09-05 — see below).
  9. HowDrawer "Picture entries" row flipped from coming-soon to interactive: lorebookImagesState() + lorebookImagesBody() with mode-locked → dependency-locked('Lorebook') → active/inactive cascade.

Notable scope decisions vs original plan:

Phase 3 — Side B: LLM vision injection — not started

  1. Add Features.SendLorebookImagesToLlm to SettingsKeys
  2. Extend ConversationFeatureState with SendLorebookImagesToLlmEnabled; gate on vision-capable model in the resolved state
  3. Add a second HowDrawer row (separate from "Picture entries") wired to the new toggle, with copy that explicitly distinguishes it from Side A
  4. Introduce PromptContent and migrate IPromptContentProvider
  5. LorebookContentProvider opts into multimodal output
  6. System prompt builder + provider clients gain multimodal block emission (Anthropic / OpenAI / Google formats differ)
  7. Image cache layer

Result: Opt-in vision-aware lorebook recall. Does not depend on Phase 2 having shipped — Side A and Side B can ship in either order, though Phase 1 (the picture FK) is a prerequisite for both.

  1. Extract HeroBanner's rotation/dots/arrows into a reusable <ImageCarousel> primitive (or equivalent) in shared/src/components/common/
  2. TriggeredEntryImagesPanel switches from "render [0]" to rendering the full list through the carousel
  3. No backend change — metadata already carries the full list

Result: All matched-with-image entries are reachable from a single panel via dots / arrows.


Files

Files to create

File Purpose
database/v1/<next>_lorebook_entry_picture_image.sql Migration: add picture_image_id FK + index

Files to modify

File Change
database/v1/v1_run_all.sql Register new migration
database/v1/functions/09_lorebook_migration_functions.sql fn_upsert_lorebook_entry accepts p_picture_image_id
database/v1/views/04_lorebook_view.sql Surface picture_image_id + joined image fields
database/v1/functions/15_search_lorebook.sql Return picture_image_id
database/v1/functions/25_expand_lorebook_entry.sql Return picture_image_id
server/EchoOfDreams.Database/Interfaces/ILorebookRepository.cs Entry image set/clear method
server/EchoOfDreams.Database/Repositories/LorebookRepository.cs Implementation (mirror SetPictureImageAsync)
server/EchoOfDreams.Core/Storage/Interfaces/ILorebookSearchRepository.cs Add PictureImageId / resolved URL
server/EchoOfDreams.Database/Repositories/LorebookSearchRepository.cs Map new fields
server/EchoOfDreams.ServerAPI/Api/Endpoints/CreatorLorebookEndpoints.cs Entry picture endpoints + upsert field
server/EchoOfDreams.ServerAPI/Api/Models/CreatorModels.cs pictureImageUuid on entry DTOs
server/EchoOfDreams.Core/Pipeline/ChatPipeline.cs New PipelineTokenType.LorebookImages + PipelineToken.LorebookImages(...) factory
server/EchoOfDreams.Core/Pipeline/Stages/ContextBuildingStageBase.cs Stash matched-with-image list in IPipelineContext so the streaming loop can flush it pre-LLM
server/EchoOfDreams.WebChat/... (SSE writer) Forward the new token as event: lorebook-images
server/EchoOfDreams.DiscordChat/... Decide whether Discord renders inline images per-turn (likely v2+) or only respects the toggle
clientConsole/src/... (chat SSE consumer) Handle the new event, populate the panel before Done
server/EchoOfDreams.Core/Pipeline/Providers/LorebookContentProvider.cs Multimodal support (Phase 3)
server/EchoOfDreams.Core/Settings/SettingsKeys.cs Features.EnableLorebookImages (Side A, Phase 2a), Features.SendLorebookImagesToLlm (Side B, Phase 3)
server/EchoOfDreams.WebChat/Services/IWebChatFeatureStateService.cs + impl Side A: LorebookImagesEnabled + ModeSupportsLorebookImages. Side B: SendLorebookImagesToLlmEnabled + vision-capable check on ConversationFeatureState
server/EchoOfDreams.ServerAPI/Api/Models/WebChatModels.cs Add LorebookImages (Side A) and SendLorebookImagesToLlm (Side B) to FeatureTogglesDto
clientConsole/src/pages/chat-v2/components/HowDrawer.tsx Side A: wire existing "Picture entries" row (2a coming-soon → 2b interactive). Side B: add a separate row for vision injection (Phase 3)
clientConsole/src/api/reports.ts 'GalleryImage' in ReportEntityType + the reportEntityLabel copy map — shipped
clientConsole/src/pages/chat/... New TriggeredEntryImagesPanel (inline + side-rail layouts)
database/v1/functions/51c_content_report_functions.sql fn_resolve_reportable_entity arm 17 (gallery image) — shipped; reports.entity_type needed no schema change

Notably no longer required: LorebookImageStorageService (use GalleryImageStorageService), bespoke image_url / image_source / image_bucket_key / image_alt_text columns, entry-specific upload endpoints.


Future Considerations