Gallery & Image Storage — Design Document

Implementation Status

Area Status Notes
Database tables Done galleries, gallery_images, gallery_image_entity_links
Database functions Done 12 functions: CRUD, quota enforcement, slug suggestion, reference resolution, gallery slug suggestion, slug-based resolution
Database views Done vw_galleries (with creator username), vw_gallery_images
Subscription tier limits Done Free 100 MB / 5 MB, Pro 5 GB / 20 MB
Backend endpoints Done 13 authenticated + 3 public (gallery resolve, public gallery detail, g:// image redirect)
Request/response models Done All DTOs including public gallery models, rating breakdown
Repository layer Done Full IGalleryRepository + GalleryRepository with filtered paging, rating breakdown
Storage service Done GalleryImageStorageService extending BucketStorageBase — card + avatar thumbnail generation, guarded decode via GuardedImageDecoder. Serving goes through signed streaming URLs (see below).
Content blur settings Done Single Content.BlurMode setting (all / suggestive / none) + Content.BlurIntensity slider
Content blur components Done ContentImage, ContentImageContext, ContentFilterToggle in shared library
Upload panel Done Content rating radio group, gallery selector, avatar crop, storage usage
Image picker modal Done ImagePickerModal with Upload / Galleries tabs, search, pagination
User dropdown toggle Done ContentFilterToggle in user menu for quick blur mode switching
Backend tests Done 137 test methods in GalleryEndpointTests.cs alone, plus dedicated image-serving (ImageEndpointTests.cs) and g:// resolution suites
Showcase Done ContentImageSection at /dev/components
Gallery page Done Three-panel layout on the media site, media.echoofdreams.eu/images — gallery list, image grid with filters, detail editor. The writing app's old /creator/gallery address forwards there
Gallery grid component Done Responsive CSS grid with ContentImage cards, rating badges, drag-to-upload zone, pagination
List view + quick edit Done Grid/list toggle on the gallery page (persisted preference). List rows expand accordion-style into a lightweight quick-edit form — slug, caption, rating, recall keyword, g:// copy — for post-bulk-upload metadata cleanup. Future mount point for image trigger keywords (Gallery Links & Image Keywords, slice 5).
Thumbnail hover peek Done Shared ImageHoverPeek (showcase: Display) — hovering a row/cell thumb floats a larger preview beside it; clicking opens ImageLightbox. Mounted in the gallery list view and the admin Gallery Images table; under-review containment carries onto the peek via blurPreview.
Signed image URLs Done Superseded the public-ACL thumbnail model: every variant (original, card, avatar) is served via stable HMAC-signed streaming URLs — GET /api/img/{uuid}/{variant}?s=... (ImageEndpoints.cs, ImageUrlSigner). Access checked at mint time, responses cached immutable. The old thumb_card_url/thumb_avatar_url columns are dead.
Moderation containment Done UnderReview enforced server-side — serve-time 404 in /api/img, excluded from the public resolvers, public list, and OG responses
Upload hardening Done Quota checks serialized via per-user advisory lock (gallery_quota); decompression-bomb guard (GuardedImageDecoder identify pre-check — 12k px per axis, 40 MP total); covering index idx_gallery_images_user (user_id, file_size_bytes) makes the quota SUM index-only
Bulk operations Done Set-based bulk delete + bulk rating — creator (/images/bulk-delete, /images/bulk-rating) and admin (/bulk/delete, /bulk/update-rating, /bulk/moderation-status)
Gallery cover image Done Settable via PATCH /api/galleries/{uuid} (CoverImageUuid, three-state omit/clear/set). Picker UI shipped: the gallery detail panel's Cover image field (GalleryCoverPickerModal, staged into Save/Cancel) plus the image panel's immediate Set as cover action.
Picker search Done Server-side ?search= on the image list endpoints — no client-side filtering
Detail drawer conventions Done Drawer panels follow the Save/Cancel + surgical-update pattern; "" clears fields end-to-end (NULLIF in the update functions)
Entity image linking Done FK columns avatar_image_id/picture_image_id on characters, lorebooks, users. ON DELETE SET NULL. Pre-resolved via DB view JOINs — zero-cost reads.
Image picker in forms Done ImagePickerField + ImagePickerModal replaces raw URL inputs in CharacterEditForm, LorebookEditForm
Image usage tracking Done fn_get_gallery_image_usage(), usage_count in views, usage detail endpoint, "Used by" in image detail panel
Entity image linking Done gallery_image_entity_links wired up: link/unlink endpoints, EntityImagesSection in workbench, LinkedImages in entity detail responses, usage tracking includes link table
Recall keyword resolution Not started Pipeline integration for {{image:keyword}} tokens. The keyword field is editable today (ImageDetailPanel, list quick edit) and its copy says the lookup isn't live yet — flip that copy (and Gallery's Recall keyword row) when this ships.
Image tags UI Not started tags_0/1/2 columns, the PATCH fields and the ?includeTags= / ?excludeTags= list filters exist; no tag picker in the image editor and no tag filter on the gallery page (Tags (Bitmask System)). The public Gallery doc no longer lists Tags until this ships.
Entity filter chips + picker pre-filter Not started Links are managed from the workbench EntityImagesSection; the gallery page only has a Linked / Not linked filter. No per-entity chips (linkedEntities in the detail response) and ImagePickerModal's entityContext only changes the title — nothing passes it, nothing filters on it (Per-Image Entity Links).
gallery:// resolution Superseded Replaced by FK-based entity image linking with pre-resolved URLs
g:// markdown references Done g://gallery-slug/image-slug and g://username/gallery-slug/image-slug syntax in markdown. Gallery slug column, fn_resolve_gallery_image_by_slugs, redirect endpoint GET /api/g/{username}/{gallerySlug}/{imageSlug}, MarkdownContent/ChatMarkdown/PageMarkdown components resolve via GalleryOwnerContext
Public gallery on profiles Not started Creator profile gallery section with rating breakdowns
GIF stop frame UI Done GifStopFramePicker in shared library, wired into ImageDetailPanel, frame extraction with compositing and LRU cache
AI description field Done Manual textarea in ImageDetailPanel. Generate button present but disabled (Coming Soon) — vision model integration planned.
Orphan cleanup job Done Deleting an image removes its stored files right after its row. Whatever is left behind — a delete that failed, or a linked image's thumbnails when its whole gallery is deleted (taken at once from Images on R2 milestone I2c) — goes in the daily orphan sweep (CleanupOrphanedStorageTask), which deletes stored files nothing in the database accounts for. The old row-only fn_cleanup_orphan_gallery_images() was never called and is dropped (it deleted rows without their files).
Lightbox / full-size view Done ImageLightbox shared component — click-to-expand in the gallery pages and public gallery view (signed URLs need no refresh)
ai_description on entities Not started avatar_ai_description on characters, lorebooks, personas
Gallery folders (nesting) Done Shipped 2026-08-18 (7146bc42): one level of subfolders, placement via Location → Change location / New subfolder and drawer drag (all six slices shipped; pointer-drag paths not yet exercised in a browser). Reverses the flat-list v1 decision below — see Gallery Folders
Metadata stripping Planned Location, device and editing metadata removed from every stored original and thumbnail, orientation applied first — see Image Metadata

Overview

Galleries are a first-class entity type for organizing user-uploaded images. They serve as the central media library for pictures, sprites, backgrounds, and other visual assets used across the platform — in characters, lorebooks, chat effects, triggers, and profile customization.

Users can upload their own images or reference external URLs. Uploaded images are stored in Railway Buckets (Tigris, S3-compatible) — the same infrastructure used for ticket attachments.

Core Goals


Architecture: Data-Driven UI & Server/Client Responsibilities

The gallery system follows the platform's data-driven architecture: one API call per page, server assembles the data, UI is a lightweight display layer.

Server Responsibilities (What the API Does)

The server owns all business logic, permission checks, and data assembly:

Responsibility Details
Gallery-as-folder semantics A gallery is a folder of images. The API returns the folder contents pre-assembled — images with stable signed URLs (thumbnails and originals alike), metadata, tags, content ratings — in a single response. The UI never fetches images individually.
Entity attachment resolution When a gallery is attached to an entity (character, lorebook, etc.), the server resolves this at query time. The character detail endpoint returns the character's attached galleries inline — the UI does not make a second call.
Per-image slug generation & validation Each image has an optional user-settable slug (URL-friendly identifier). The server validates uniqueness per gallery, enforces the pattern, and auto-generates a slug suggestion from the file name on upload.
Content rating enforcement The server stores and returns the content_rating (SFW/Suggestive/NSFW) for every image. Filtering by rating happens server-side — the API accepts a ?maxRating=0 (SFW only), ?maxRating=1 (SFW + Suggestive), or no filter (all). The response includes a ratingBreakdown with counts per level so the UI can show what's hidden.
Tag bitmask filtering Tags use the same bitmask system as characters/lorebooks (3 BIGINT columns, predefined tag indices). The server filters using tags_match_any / tags_match_none — no text normalization needed.
URL resolution The gallery detail endpoint returns all visible images with stable HMAC-signed streaming URLs (/api/img/{uuid}/{variant}) for every variant. No TTL, no refresh — signed URLs are content-immutable and cache indefinitely.
Quota & limit enforcement All tier limit checks (gallery count, image count, storage, file size) happen server-side in database functions. The API returns current usage alongside limits so the UI can show progress bars.
Entity filter on images Individual images can be linked to entities via gallery_image_entity_links. The gallery detail endpoint accepts ?entity_type=0&entity_uuid=... to return only images linked to that entity (e.g., "show me only the images assigned to character Elara"). The API also returns the linked entities per image so the UI can show filter chips.
Permission-scoped responses The same gallery endpoint returns different data depending on who's asking: owner sees all images + edit controls; public viewer sees only published images filtered by their content rating preferences.

Client Responsibilities (What the UI Does)

The UI renders what the server sends and handles purely visual/interactive concerns:

Responsibility Details
Render the folder view Display the gallery as a grid/list of images using the signed thumbnail URLs from the API response. No data transformation, no expiry tracking for grid views.
Content blur (client-side only) Apply CSS filter: blur() based on the user's local blur preferences and each image's content_rating. The server returns the full image — blur is a rendering decision.
Drag & drop upload Handle file selection, progress display, and the presigned URL upload flow. The server orchestrates (provides URLs, validates, confirms) but the client drives the UX.
Lightbox / full-size view Click thumbnail → show full-size image (ImageLightbox). The signed original URL is already in the API response — stable, no expiry management.
Image picker for entity URL fields ImagePickerModal (shared component) replaces raw URL inputs. Default view shows recent images for quick selection; Upload tab handles file upload + URL paste + avatar crop; Galleries tab browses user's galleries with a create-new card. Selecting an image writes the gallery:// ref or external URL into the field. See the dedicated section below.
Tag selection Render the grouped checkbox/pill selector for bitmask tags (same pattern as character tag picker). Send tag bitmask values to the server.
GIF stop frame Client-side canvas extraction for the frame scrubber. Send chosen frame index to server.
Form descriptions & guidance Every field in the image editor shows a description explaining what it does — users should never need domain knowledge to use the form.

Data Flow: One Call Per Page

The page names below are the design's. As built, the manager lives on the media site at media.echoofdreams.eu/images, with ?gallery={uuid} selecting a gallery (?gallery=all for All images), and a public gallery's page is media.echoofdreams.eu/gallery/{uuid}.

Page: /vault/galleries
  → GET /api/galleries
  ← { galleries: [...], usage: { count, totalBytes, limits }, tierLimits: {...} }
  UI: render gallery cards + storage usage bar

Page: /vault/galleries/:uuid
  → GET /api/galleries/{uuid}?maxRating=1&page=1&pageSize=20
  ← { gallery: {...}, images: [...], totalImages, page, pageSize, ratingBreakdown: { sfw, suggestive, nsfw } }
  UI: render image grid, filters (rating, tags, entity), upload zone

Page: /vault/galleries/:uuid?entity_type=0&entity_uuid=...  (filtered to one character)
  → GET /api/galleries/{uuid}?entity_type=0&entity_uuid=...
  ← { gallery: {...}, images: [...only images linked to that character...], ... }
  UI: render filtered grid with active "Elara" entity chip

Page: /hub/characters/:slug (character with attached gallery)
  → GET /api/hub/characters/{slug}
  ← { character: {...}, galleries: [{ id, name, coverUrl, imageCount, images: [...first 6 thumbnails...] }] }
  UI: render character page with gallery preview section

Galleries as Folders

Galleries behave as folders — named containers that group related images. This is the core mental model for both creators and consumers.

Folder Semantics

Property Behavior
Nesting Flat in v1 — superseded. Galleries now nest one level deep; see Gallery Folders.
Ownership Each gallery belongs to exactly one user. No shared ownership.
Ordering Images within a gallery have explicit sort_order. Galleries in the user's list are ordered by created_at DESC (newest first) or custom order.
Cover image Each gallery has an optional cover image (any image from within the gallery). If none is set, the first image is used.
Empty state An empty gallery is valid — creators can create the folder structure first, then add images later.

Attaching Galleries to Entities

A gallery can be attached to one or more entities (characters, lorebooks, modes, etc.). This makes the gallery's images available as a media library for that entity. Correction: earlier drafts of this section said attachment "uses the existing entity_links table" — no such table was ever built. Gallery-level granting is specified — not yet built — in Gallery Links & Image Keywords as gallery_entity_grants.

What attachment means:

Server-side: Entity detail endpoints include attached galleries in their response. The GET /api/hub/characters/{slug} response includes a galleries array with cover images and preview thumbnails. No extra client call needed.

Creator-side: In the workbench, the entity linking UI lets creators attach/detach galleries. See Gallery Links & Image Keywords.

Current entity URL fields (like avatar_url on characters, picture_url on lorebooks) store a raw URL string. With galleries, these fields can reference a specific image from an attached gallery using a gallery image reference:

gallery://{galleryUuid}/{imageSlug}

How it works:

  1. Creator opens the character editor, clicks the avatar field
  2. A picker modal shows the character's attached galleries as folder tabs
  3. Creator browses images within a gallery, clicks one to select
  4. The field stores gallery://a1b2c3d4-.../elara-smiling (gallery ID + image slug)
  5. At render time, the server resolves this reference to a presigned URL and returns it in the API response
  6. The UI simply renders the resolved URL — it never parses gallery:// references

Server resolution: Any API response that includes an entity with a gallery:// reference resolves it inline. The character detail endpoint returns avatarUrl: "https://presigned..." — the client sees a normal image URL. The raw gallery:// reference is only visible in the editor.

Fallback: If the referenced image is deleted or the gallery is unlinked, the server returns null for the resolved URL. The UI shows a placeholder/empty state. The raw reference is preserved in the field so it auto-resolves if the gallery is re-linked.


Per-Image Slugs

Every gallery image has an optional slug — a URL-friendly identifier used for:

Slug Rules

Rule Details
Pattern ^[a-z0-9][a-z0-9-]{1,60}[a-z0-9]$ — lowercase alphanumeric + hyphens, 3–62 chars
Uniqueness Unique per gallery (not globally, not per user). Two galleries can each have a portrait-happy image.
Optional Slugs are optional. Images without slugs are referenced by numeric ID in gallery:// URLs.
Auto-suggestion On upload, the server suggests a slug derived from the file name (sanitized, lowercased, truncated). Creator can accept, edit, or clear.
Editable Creators can change an image's slug at any time. The server updates all gallery:// references in the owner's entities automatically (a targeted UPDATE on entity URL fields).

Database Addition

-- Add to gallery_images table:
    slug VARCHAR(62),

-- Unique per gallery (not per user)
    CONSTRAINT uq_image_slug_per_gallery UNIQUE (gallery_id, slug)

CREATE INDEX idx_gallery_images_slug ON gallery_images (gallery_id, slug)
    WHERE slug IS NOT NULL;

UI: Slug Field in Image Editor

The image editor form includes a slug field:

┌─── Image Details ─────────────────────────────┐
│                                                │
│  Slug                                          │
│  [elara-smiling          ]  (auto-generated)   │
│  URL-friendly name for this image. Used when   │
│  linking this image to characters or lorebooks. │
│  Letters, numbers, and hyphens only.           │
│                                                │
│  Content Rating                                │
│  ○ SFW  ○ Suggestive  ○ NSFW                  │
│  How mature is this image's content?           │
│                                                │
│  Tags                                          │
│  Type: [●Portrait] [○Sprite] [○Background]    │
│  Mood: [●Happy] [○Calm] [○Action]             │
│  Categorize this image for filtering.          │
│                                                │
└────────────────────────────────────────────────┘

Per-Image Content Rating & Tags

Content Rating (SFW / Suggestive / NSFW)

Every image has a content_rating flag set by the creator. This is the primary safety/filtering mechanism.

Rating Value DB Description Default blur
SFW Safe for work 0 No mature content Never blurred
Suggestive Mildly mature 1 Revealing clothing, mild violence Blurred by default
NSFW Explicit 2 Nudity, graphic violence, sexual Blurred by default

Server-side:

Client-side:

Tags (Bitmask System)

Gallery image tags use the same bitmask system as characters, lorebooks, and modes — predefined tag indices stored as BIGINT columns. This ensures consistent filtering behavior across the platform (bitwise AND/OR operations) and eliminates normalization issues with free-form text.

Tag categories for gallery images (subset — images need different categories than characters):

Column Bits Category Examples
tags_0 0–63 Content type, Style Portrait, Full body, Landscape, Sprite, Background, Icon, Chibi, Pixel art, Realistic, Anime
tags_1 64–127 Mood, Setting Happy, Sad, Angry, Action, Calm, Indoor, Outdoor, Fantasy, Sci-fi, Modern
tags_2 128–191 Subject, Features Character, Location, Item, Group, Solo, Male, Female, Non-binary, Monster, Animal

Gallery images use 3 BIGINT columns (not 7 like characters) — images need fewer categorization dimensions.

Server-side:

Database schema:

-- On gallery_images table:
    tags_0 BIGINT NOT NULL DEFAULT 0,
    tags_1 BIGINT NOT NULL DEFAULT 0,
    tags_2 BIGINT NOT NULL DEFAULT 0,

CREATE INDEX IF NOT EXISTS idx_gallery_images_tags_0 ON gallery_images(tags_0);
CREATE INDEX IF NOT EXISTS idx_gallery_images_tags_1 ON gallery_images(tags_1);
CREATE INDEX IF NOT EXISTS idx_gallery_images_tags_2 ON gallery_images(tags_2);

Client-side:


Entity Model

A Gallery is a new entity type that groups related images. A Gallery Image is an individual image within a gallery.

Concept Description
Gallery Named collection of images. Owned by a user. Can be linked to characters, lorebooks, etc.
Gallery Image A single image within a gallery. Either uploaded (stored in bucket) or external (raw URL).
Recall Keyword A creator-defined string identifier on an image (e.g., elara_happy, forest_bg). Unique per gallery. Resolved during chat by searching the galleries attached to the active entity.

Entity Type

Galleries use the platform's entity type system. A new entity type is registered (e.g., entity_type = 5 for gallery) enabling:

Public Identifiers: UUIDs, Not Integer IDs

Following the same pattern as characters, greetings, and other entities: integer id columns are internal-only. The client exclusively uses uuid to reference galleries and images.

Principle Details
API routes use UUID All endpoints use {uuid} in paths, never {id}. E.g., GET /api/galleries/{uuid}, not GET /api/galleries/{id}.
API responses return UUID JSON responses include uuid (or map it to id in the DTO). The integer id is never serialized to the client.
gallery:// references use UUID The gallery image reference format is gallery://{galleryUuid}/{imageSlug} — e.g., gallery://a1b2c3d4-e5f6-7890-abcd-ef1234567890/elara-smiling.
Internal joins use integer ID Database FKs, joins, and internal service calls use the integer id for performance. UUID lookup happens once at the API boundary.
Why Integer IDs are sequential and leak information (entity count, creation order). UUIDs are opaque and safe to expose in URLs, API responses, and browser history. This matches the existing pattern on characters.uuid, character_greetings.uuid, etc.

Database Schema

Tables

-- =============================================================================
-- Galleries
-- =============================================================================

CREATE TABLE galleries (
    id SERIAL PRIMARY KEY,
    uuid UUID NOT NULL DEFAULT gen_random_uuid(),  -- public-facing identifier (client never sees id)
    user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,

    name VARCHAR(100) NOT NULL,
    description VARCHAR(500),
    cover_image_id INTEGER,               -- FK added after gallery_images exists

    is_public BOOLEAN NOT NULL DEFAULT FALSE,

    image_count INTEGER NOT NULL DEFAULT 0,   -- denormalized, updated by triggers
    total_size_bytes BIGINT NOT NULL DEFAULT 0, -- denormalized, for quota tracking

    created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);

CREATE UNIQUE INDEX idx_galleries_uuid ON galleries (uuid);
CREATE INDEX idx_galleries_user ON galleries (user_id, created_at DESC);

-- =============================================================================
-- Gallery Images
-- =============================================================================

CREATE TABLE gallery_images (
    id SERIAL PRIMARY KEY,
    uuid UUID NOT NULL DEFAULT gen_random_uuid(),  -- public-facing identifier (client never sees id)
    gallery_id INTEGER NOT NULL REFERENCES galleries(id) ON DELETE CASCADE,
    user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,

    -- Storage: exactly one must be set
    bucket_key VARCHAR(500),              -- uploaded image (Railway Bucket)
    external_url VARCHAR(1000),           -- external URL (user-provided)

    -- Metadata
    file_name VARCHAR(255) NOT NULL,
    content_type VARCHAR(100) NOT NULL,   -- image/png, image/jpeg, image/webp, image/gif
    file_size_bytes INTEGER,              -- NULL for external URLs
    width INTEGER,                        -- extracted on upload
    height INTEGER,                       -- extracted on upload

    -- Thumbnails (generated on upload, NULL for external URLs)
    thumb_card_bucket_key VARCHAR(500),    -- card thumbnail (max 300px, aspect preserved)
    thumb_avatar_bucket_key VARCHAR(500),  -- avatar thumbnail (128x128 square crop)

    -- Avatar crop region (creator-defined zoom & cut for the avatar thumbnail)
    avatar_crop_x REAL,        -- crop origin X as fraction of original width (0.0–1.0)
    avatar_crop_y REAL,        -- crop origin Y as fraction of original height (0.0–1.0)
    avatar_crop_size REAL,     -- crop square side as fraction of the shortest dimension (0.0–1.0, default 1.0 = no zoom)

    -- URL-friendly identifier (unique per gallery, optional)
    slug VARCHAR(62),

    -- Recall keyword for use in chats/effects/triggers
    recall_keyword VARCHAR(50),

    -- Ordering within gallery
    sort_order INTEGER NOT NULL DEFAULT 0,

    -- Content rating
    content_rating SMALLINT NOT NULL DEFAULT 0,  -- 0 = SFW, 1 = Suggestive, 2 = NSFW

    -- GIF stop frame (animated GIFs only)
    gif_stop_frame INTEGER,              -- creator-chosen frame to display when GIF is paused (NULL = first frame)

    -- Tags / notes
    caption VARCHAR(300),
    ai_description VARCHAR(2000),        -- text description of image content for LLM fallback when vision is unavailable
    tags_0 BIGINT NOT NULL DEFAULT 0,     -- tag bits 0-63 (content type, style)
    tags_1 BIGINT NOT NULL DEFAULT 0,     -- tag bits 64-127 (mood, setting)
    tags_2 BIGINT NOT NULL DEFAULT 0,     -- tag bits 128-191 (subject, features)

    created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,

    -- Constraints
    CONSTRAINT chk_image_source CHECK (
        (bucket_key IS NOT NULL AND external_url IS NULL) OR
        (bucket_key IS NULL AND external_url IS NOT NULL)
    ),
    CONSTRAINT uq_recall_keyword_per_gallery UNIQUE (gallery_id, recall_keyword),
    CONSTRAINT uq_image_slug_per_gallery UNIQUE (gallery_id, slug)
);

CREATE UNIQUE INDEX idx_gallery_images_uuid ON gallery_images (uuid);
CREATE INDEX idx_gallery_images_gallery ON gallery_images (gallery_id, sort_order);
CREATE INDEX idx_gallery_images_recall ON gallery_images (gallery_id, recall_keyword)
    WHERE recall_keyword IS NOT NULL;
CREATE INDEX idx_gallery_images_slug ON gallery_images (gallery_id, slug)
    WHERE slug IS NOT NULL;
CREATE INDEX idx_gallery_images_tags_0 ON gallery_images (tags_0);
CREATE INDEX idx_gallery_images_tags_1 ON gallery_images (tags_1);
CREATE INDEX idx_gallery_images_tags_2 ON gallery_images (tags_2);

-- FK for cover image (deferred to avoid circular dependency)
ALTER TABLE galleries
    ADD CONSTRAINT fk_galleries_cover_image
    FOREIGN KEY (cover_image_id) REFERENCES gallery_images(id) ON DELETE SET NULL;

-- =============================================================================
-- Entity Links (gallery <-> character, lorebook, etc.)
-- =============================================================================
-- Gallery-level granting is NOT built. It is specified as `gallery_entity_grants`
-- in Gallery Links & Image Keywords (./gallery-entity-links.md). Earlier drafts
-- of this block referenced an `entity_links` table that was never created.
--
-- Individual images can also be linked directly:
-- This is handled via a lightweight junction table:

CREATE TABLE gallery_image_entity_links (
    gallery_image_id INTEGER NOT NULL REFERENCES gallery_images(id) ON DELETE CASCADE,
    entity_type SMALLINT NOT NULL,
    entity_id INTEGER NOT NULL,

    PRIMARY KEY (gallery_image_id, entity_type, entity_id)
);

CREATE INDEX idx_image_entity_links_target
    ON gallery_image_entity_links (entity_type, entity_id);

The gallery_image_entity_links table serves two purposes:

  1. Assignment — link a specific image to an entity (e.g., "this portrait belongs to character Elara"). This is separate from gallery-level grants (gallery_entity_grants, planned). A gallery can be attached to a character, but only some images in that gallery may be assigned to that character.

  2. Filtering — the gallery detail endpoint accepts ?entity_type=N&entity_id=M to show only images assigned to a specific entity. This is critical for large galleries shared across multiple entities.

Example: A creator has a "Portraits" gallery with 50 images, attached to 5 characters. When editing character Elara, the image picker shows only the 12 images assigned to Elara — not all 50.

Server-side:

Client-side:

Recall Keywords

Recall keywords are creator-scoped identifiers set on gallery images. They are primarily used by the chat pipeline to resolve image references during conversations.

Key principle: When a user chats with a character, {{image:elara_happy}} resolves from the creator's galleries attached to the entity in use — not from the chatting user's own galleries. The creator defines the visual vocabulary; the user consumes it.

Constraints:

Resolution order in the chat pipeline:

When the pipeline encounters {{image:elara_happy}}:

  1. Identify the active entity context — which character/mode/lorebook is driving this conversation?
  2. Collect attached galleries — find all galleries linked to the active entity via gallery_entity_grants (planned)
  3. Search recall keywords — look up elara_happy across the attached galleries' images
  4. Resolve — return the matching image's presigned URL (thumbnail for inline, full-size on demand)
  5. Conflict — if the same keyword exists in multiple attached galleries, the pipeline uses the image from the gallery with the lowest gallery_entity_grants.sort_order (first-attached wins). This is deterministic and creator-controllable.

Why entity-scoped, not user-scoped:

Usage in chats/effects/triggers:

{{image:elara_happy}}       — inline image reference (resolved from entity's attached galleries)
{{sprite:forest_bg}}        — sprite/background reference

User Images in Chat: Persona-Attached Galleries


Storage Architecture

Railway Bucket (Tigris)

All uploaded images are stored in the same Railway Bucket (Tigris, S3-compatible) used by TicketAttachmentStorageService. The existing S3 client configuration and env vars (AWS_S3_BUCKET_NAME, AWS_ENDPOINT_URL, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) are shared.

Bucket key structure:

uploads/{user_id}/{gallery_id}/{uuid}_{sanitized_filename}             — staging: where the browser uploads (transient)
images/{user_id}/{gallery_id}/{uuid}_{sanitized_filename}              — the stored original (written by the server only)
images/{user_id}/{gallery_id}/thumbs/card/{uuid}_{sanitized_filename}
images/{user_id}/{gallery_id}/thumbs/avatar/{uuid}_{sanitized_filename}

(gallery_id is 0 for unsorted images. Images stored before September 2026 keep the same layout under galleries/.)

Upload flow:

  1. Client asks the server for an upload. The server checks the file type and the creator's limits (per-file size and remaining storage), mints a staging key, records a single-use upload ticket, and returns a presigned POST policy the bucket itself enforces — that exact key, that content type, at most the ticket's byte ceiling, for 15 minutes.
  2. Client uploads directly to the bucket with that policy.
  3. Client confirms with the ticket. The server seals the upload — copies it from the staging key to a fresh key no policy covers — and takes the size from that copy: the ticket is spent against it, the gallery_images row keeps its key, and both thumbnails (card, and avatar with the default centered crop) are built from it. The staging object is then deleted.

Sealing is what makes a confirmed upload final. A POST policy stays usable until it expires, whatever happened to the upload, so a picture stored at the policy's own key could be swapped for different bytes after it was checked. Operational detail: docs-internal/architecture/content/GALLERY_UPLOADS.md.

Thumbnails (Two Sizes)

Two thumbnail sizes are generated server-side on upload confirmation. They are stored as separate objects in the bucket under thumbs/card/ and thumbs/avatar/ prefixes.

Thumbnail Size Resize Mode Format Quality Used For
Card 300px max (longest side) ResizeMode.Max — aspect ratio preserved, fits within 300×300 WebP 80% Gallery grid, entity picker, chat inline previews, profile gallery cards
Avatar 128×128px square ResizeMode.Crop — square crop using creator-defined crop region WebP 85% Character/lorebook avatar fields, persona avatars, chat message avatars, any circular/square avatar slot

Both are generated using ImageSharp (server-side, no external dependency).

Why two sizes:

Avatar Crop: Zoom & Cut

When an image is used as an avatar (character portrait, persona icon, etc.), the creator needs control over which part of the image is shown in the square crop. A landscape photo of a character in a forest should crop to the character's face, not show a tiny figure in the center.

Crop parameters (stored on gallery_images):

Field Type Description
avatar_crop_x REAL Crop origin X as a fraction of original width (0.0–1.0). Default: centered.
avatar_crop_y REAL Crop origin Y as a fraction of original height (0.0–1.0). Default: centered.
avatar_crop_size REAL Crop square side as a fraction of the shortest dimension (0.0–1.0). 1.0 = no zoom (largest possible square), 0.5 = 2× zoom, 0.25 = 4× zoom. Default: 1.0.

Server-side:

Client-side (crop editor UI):

┌─── Avatar Crop ───────────────────────────────┐
│                                                │
│  ┌────────────────────────────────────┐       │
│  │                                    │       │
│  │    ┌──────────┐                    │       │
│  │    │ ◯        │  ← drag to pan     │       │
│  │    │  (face)  │                    │       │
│  │    │          │                    │       │
│  │    └──────────┘                    │       │
│  │                                    │       │
│  └────────────────────────────────────┘       │
│                                                │
│  Zoom: [────●─────────] 2.3×                  │
│  Drag the square to choose which part of the  │
│  image appears in avatar slots.                │
│                                                │
│  Preview:  ┌────┐                             │
│            │ ◯  │  ← live 128px preview       │
│            └────┘                             │
│                                                │
└────────────────────────────────────────────────┘

When is the crop editor shown?

External URL images do not get thumbnails — the client displays them at their original URL. This is acceptable because external URLs are the user's responsibility.

Two-Tier Access: Public Thumbnails, Protected Originals — Superseded

Thumbnails and avatar crops are publicly accessible with stable URLs. Only original full-size images require presigned URLs. Public URLs are stored in thumb_card_url and thumb_avatar_url columns on gallery_images. Thumbnails are uploaded with CannedACL.PublicRead and Cache-Control: public, max-age=31536000, immutable.

Asset Access URL type Cacheable Why
Original image Protected Presigned URL (1-hour TTL) Limited (expires) Full-resolution asset — the thing worth protecting from hotlinking and abuse
Card thumbnail Public Static bucket URL Indefinitely 300px max, ~20–50 KB — too small to be useful as stolen content, shown everywhere
Avatar thumbnail Public Static bucket URL Indefinitely 128×128px, ~5–15 KB — displayed on every page, in every chat message, must be fast

Why this split works:

Bucket ACL setup:

galleries/{user_id}/{gallery_id}/{uuid}_*              → private (presigned URLs only)
galleries/{user_id}/{gallery_id}/thumbs/card/{uuid}_*  → public-read
galleries/{user_id}/{gallery_id}/thumbs/avatar/{uuid}_* → public-read

On Tigris/S3, this is configured via bucket policy with prefix-based rules — thumbs/* gets public-read ACL, everything else stays private.

Presigned URLs for Originals — Superseded

Original full-size images are served via presigned GET URLs with a 1-hour TTL. This applies only to the original — thumbnails bypass this entirely.

Why 1 hour (not 15 minutes):

TTL Abuse prevention Cache behavior UX impact
15 min Good Poor — re-download on every page revisit Sluggish for lightbox/full-size viewing
1 hour Moderate Decent — covers a browsing session Good balance for gallery browsing
4 hours Weaker Good Overkill — originals are viewed less frequently

Client-side management (originals only):

Server-side cache headers:


Subscription Tier Limits

The only hard gates are total storage and max file size per upload. Gallery count and image count are not artificially limited — if you have storage budget, you can organize however you want. This avoids constraints that feel arbitrary ("why can't I make a 4th gallery?") and keeps the value proposition simple: pay for space, use it how you like.

Feature Matrix

Feature Free Pro
Total storage 100 MB 5 GB
Max file size 5 MB 20 MB
Galleries Unlimited Unlimited
Images per gallery Unlimited Unlimited
Recall keywords Unlimited Unlimited
Thumbnail generation Yes Yes
External URL images Yes Yes
Gallery linking (to characters, lorebooks) Yes Yes
Avatar crop Yes Yes
Allowed formats PNG, JPEG, WebP, GIF PNG, JPEG, WebP, GIF

Thumbnails and avatars don't count toward storage. The card thumbnail and avatar thumbnail generated by the server are a platform cost — they are not added to the user's total_size_bytes. Only the original uploaded file counts. This prevents a confusing situation where uploading a 2 MB image "costs" 2.3 MB because of generated derivatives the user didn't ask for.

Why only storage and file size?

Subscription Limit Keys

INSERT INTO subscription_tier_limits (tier_id, limit_key, limit_value, category, display_name, display_order) VALUES
    (v_free_id, 'gallery.total_storage_bytes',   '104857600', 'Gallery', 'Total storage',         10),  -- 100 MB
    (v_pro_id,  'gallery.total_storage_bytes',   '5368709120','Gallery', 'Total storage',         10),  -- 5 GB

    (v_free_id, 'gallery.max_file_size_bytes',   '5242880',   'Gallery', 'Max file size',         20),  -- 5 MB
    (v_pro_id,  'gallery.max_file_size_bytes',   '20971520',  'Gallery', 'Max file size',         20);  -- 20 MB

Abuse Prevention: Not a Free File Host

The platform must not become a free image CDN. Several layers prevent this.

(Mechanism note: items 1, 2, and 6 below predate the shipped signed-URL model — the protections hold, but "presigned URL with 1-hour TTL" is now "stable HMAC-signed streaming URL, access-checked at mint time"; see Two-Tier Access.)

1. Protected Originals, Public Thumbnails

Original images are never served at a static public URL — every access goes through a presigned URL that expires after 1 hour (see Two-Tier Access). This means:

Thumbnails and avatars are publicly accessible with stable URLs. This is acceptable because:

2. Referrer / Context Validation on URL Generation

The presigned URL generation endpoint validates that the request comes from a legitimate platform context:

// Endpoint: GET /api/galleries/{galleryUuid}/images/{imageUuid}/url
// Returns: { "url": "https://presigned...", "expiresAt": "...",        ← original (presigned, 1h TTL)
//            "cardThumbUrl": "https://static...",                       ← public, stable, immutable
//            "avatarThumbUrl": "https://static..." }                    ← public, stable, immutable

// Requires auth + (owner OR image is in a gallery linked to a public/accessible entity)

3. Hard Storage Quotas

Every user has a fixed storage budget tracked by the denormalized total_size_bytes on the galleries table (summed across all galleries). The server enforces this on every upload — no exceptions.

Quota checks happen at two points:

  1. Presigned URL generation — rejects before the upload starts
  2. Upload confirmation — double-checks in case of concurrent uploads

4. Image-Only Validation

The upload endpoint validates content type on both the presigned URL request and the upload confirmation:

5. Orphan Cleanup

A scheduled job (daily) scans for:

6. No Unauthenticated Access to Originals

There is no public/anonymous endpoint for original full-size images. Even for images in public galleries linked to public characters:

Thumbnails are public — card and avatar thumbnails for public galleries are served at stable, cacheable URLs. This is by design: they appear on browse pages, search results, and character cards where performance matters most. The low resolution (300px / 128px) makes them unsuitable for content theft.

This means: full-size images are visible to anyone viewing a public profile (as intended) but their URLs are ephemeral. Thumbnails are fast and cacheable for the best browsing experience.

Alternative Considered: Cloudflare Worker Proxy

Instead of presigned URLs, images could be served through the Cloudflare Worker (already used as the edge gateway) with token-based access. This would give static-looking URLs with server-side auth validation.

Pros: Cleaner URLs, cacheable at the edge, no expiry management. Cons: More infrastructure complexity, Cloudflare Worker needs bucket access, adds a new data path.

This is a valid future optimization but presigned URLs are simpler to start with and provide stronger abuse prevention out of the box.

Update: the shipped signed-URL model landed close to this alternative — static-looking, immutable, edge-cacheable URLs — with the auth check moved to mint time instead of per-request validation, so the API stays the only image data path.


Workbench Integration

Galleries are created and managed in the workbench, consistent with other entity types (characters, lorebooks, modes).

The workbench's planned Gallery view (v3, documented in Package Workbench) aggregates visual assets across all nodes in a package graph. User galleries integrate into this:

Outside the workbench, galleries are managed from a dedicated page. As designed:

Route: /vault/galleries              — gallery list
Route: /vault/galleries/:uuid        — gallery detail (grid view, upload, manage)
Route: /creator/:slug/galleries      — public gallery listing on creator profile

As built: the manager is media.echoofdreams.eu/images (the writing app's old /creator/gallery forwards there), and a public gallery's page is media.echoofdreams.eu/gallery/{uuid}, reached by its link. There is no public gallery listing (decided 2026-11-17).


API Endpoints

POST   /api/galleries                                    — create gallery
GET    /api/galleries                                    — list user's galleries + storage usage
GET    /api/galleries/{uuid}                             — get gallery with images (paginated, filtered)
PATCH  /api/galleries/{uuid}                             — update name, description, visibility
DELETE /api/galleries/{uuid}                             — delete gallery + all images

The GET /{uuid} endpoint accepts ?page=, ?pageSize=, ?maxRating=, ?includeTags=, ?excludeTags= query params and returns a ratingBreakdown alongside paginated images.

Image Operations — Done

POST   /api/galleries/{uuid}/images/upload-url           — get presigned upload URL
POST   /api/galleries/{uuid}/images/confirm              — confirm upload, trigger thumbnail gen
POST   /api/galleries/{uuid}/images/external             — add external URL image
PATCH  /api/galleries/{uuid}/images/{imageUuid}          — update slug, caption, ai_description, tags, recall keyword, sort order, content_rating, gif_stop_frame, avatar crop
POST   /api/galleries/{uuid}/images/{imageUuid}/crop     — update avatar crop (cropX, cropY, cropSize) and regenerate avatar thumbnail
DELETE /api/galleries/{uuid}/images/{imageUuid}          — delete image
POST   /api/galleries/{uuid}/images/reorder              — batch update sort order
GET    /api/galleries/public/{uuid}                      — get public gallery with filtered images (no auth required, pageSize clamped to 1-50)

Returns PublicGalleryDetailResponse with creator username, rating breakdown, and filtered images. Supports the same ?maxRating=, ?includeTags=, ?excludeTags= filters.

GET /api/galleries/resolve?ref=gallery://{imageUuid}/… was deleted: nothing called it, and it handed any signed-in account (an account under 18 included) signed URLs for any picture not held for review, whatever its rating. gallery:// stays the picker's hand-off form; the history below is kept for the reference format.

The uuid is the image's, not the gallery's — the same uuid ImagePickerModal mints and the same one gi://{uuid} uses. The trailing slug is advisory: it is never matched, so a reference survives renaming the image or moving it between galleries, and it may be omitted entirely. Because the lookup is gallery-independent it also resolves unsorted images.

Authenticated callers only (.RequireAuthorization(), which guest tokens deliberately cannot satisfy). Possession of the reference is the authorization beyond that — the same "unguessable uuid is the token" model as the rest of the g:// family, and what lets an embedded image render for every reader allowed to see the content it sits in. An anonymous variant was considered and rejected; see docs-internal/architecture/consoles/BLOG_SERVICE.md §"Cover image — gallery integration" for the scheme comparison table.

Status: the endpoint has no caller today. Entity detail endpoints do not call it — they carry avatarImageUuid / pictureImageUuid and resolve server-side — and the client uses the picker's thumbnailUrl directly. It stands as the authenticated resolver for stored gallery:// refs if a surface ever needs one.

Markdown Image Redirect — Done

GET    /api/g/{username}/{gallerySlug}/{imageSlug}?size=card|avatar|original  — 302 redirect to signed image URL
GET    /api/g/img/{imageUuid}                                                 — sibling route for unsorted images (no parent gallery)

Public endpoint (no auth). Resolves g:// markdown references to signed image URLs. Default size is card (300px thumbnail). Falls back through: requested size → original bucket key → external URL. Direct references always resolve regardless of gallery privacy. Used by markdown components (MarkdownContent, ChatMarkdown, PageMarkdown) via the resolveGalleryImageSrc utility.

Recall Keyword Resolution — Not Started

GET    /api/images/resolve?entity_type=0&entity_uuid=...&keywords=elara_happy,forest_bg  — resolve keywords from entity's attached galleries to presigned URLs (for chat pipeline)

Entity Linking — Not Started

POST   /api/galleries/{uuid}/links               — link gallery to entity
DELETE /api/galleries/{uuid}/links/{linkUuid}   — unlink
GET    /api/entities/{type}/{uuid}/galleries    — get galleries linked to entity

Image Storage Service — Done

The existing TicketAttachmentStorageService and the new GalleryImageStorageService both extend a shared BucketStorageBase class that handles S3/Tigris operations. Each service adds its own key prefix logic and validation rules.

GalleryImageStorageService implements IGalleryImageStorageService:

public interface IGalleryImageStorageService
{
    Task<PresignedUploadResult> GenerateUploadUrlAsync(...);
    Task<string> GenerateDownloadUrlAsync(string bucketKey, ...);
    Task DeleteAsync(string bucketKey, ...);
    Task DeleteManyAsync(IEnumerable<string> bucketKeys, ...);
    Task<ThumbnailResult> GenerateThumbnailsAsync(Stream original, string keyPrefix,
        string fileName, float cropX, float cropY, float cropSize, ...);
}

Thumbnail generation uses ImageSharp — card thumbnails (300px max, WebP quality 80) and avatar thumbnails (128×128 square crop, WebP quality 85) are stored under thumbs/card/ and thumbs/avatar/ prefixes.


Client Rendering & UX

The image grid (ImageGridPanel) renders a responsive image grid with:

The design's gallery list page (/vault/galleries, never built under that name) presented galleries as folder cards:

┌─────────────────────────────────────────────────────────────┐
│  My Galleries                                    [+ New]    │
│                                                             │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐     │
│  │  ┌────────┐  │  │  ┌────────┐  │  │              │     │
│  │  │ cover  │  │  │  │ cover  │  │  │   (empty)    │     │
│  │  │ image  │  │  │  │ image  │  │  │  Drop files  │     │
│  │  └────────┘  │  │  └────────┘  │  │  to create   │     │
│  │  Portraits   │  │  Backgrounds │  │              │     │
│  │  24 images   │  │  8 images    │  │              │     │
│  │  ██░░░ 48MB  │  │  █░░░ 12MB   │  │              │     │
│  └──────────────┘  └──────────────┘  └──────────────┘     │
│                                                             │
│  Storage: 60 MB / 100 MB  ████████░░░░░░░░  60%           │
│  Galleries: 2 / 3                                          │
└─────────────────────────────────────────────────────────────┘

UX principles:

Image Detail / Editor Form — Shipped (ImageDetailPanel)

When viewing or editing a single image, every field has a description — no domain knowledge required:

┌─── Image: elara-garden.png ───────────────────────────┐
│                                                        │
│  ┌─────────────────────┐                              │
│  │                     │   File: elara-garden.png     │
│  │   (image preview)   │   Size: 2.4 MB              │
│  │                     │   Dimensions: 1920 × 1080   │
│  └─────────────────────┘   Uploaded: Mar 15, 2026    │
│                                                        │
│  ┌─── Identification ─────────────────────────────┐   │
│  │                                                 │   │
│  │  Slug                                           │   │
│  │  [elara-smiling              ]  24/62 chars     │   │
│  │  URL-friendly name for linking this image to    │   │
│  │  characters or lorebooks. Auto-generated from   │   │
│  │  file name — edit to customize.                 │   │
│  │                                                 │   │
│  │  Caption                          42/300 chars  │   │
│  │  [Elara smiling in the garden           ]       │   │
│  │  Short label shown under the image in the UI.   │   │
│  │                                                 │   │
│  │  Recall Keyword                                 │   │
│  │  [elara_happy                    ]  11/50 chars │   │
│  │  Reference this image in chat with              │   │
│  │  {{image:elara_happy}}. Lowercase + underscores │   │
│  │  only. Must be unique across all your galleries.│   │
│  │                                                 │   │
│  └─────────────────────────────────────────────────┘   │
│                                                        │
│  ┌─── Classification ─────────────────────────────┐   │
│  │                                                 │   │
│  │  Content Rating                                 │   │
│  │  ● SFW  ○ Suggestive  ○ NSFW                  │   │
│  │  How mature is this image? Other users may see  │   │
│  │  Suggestive and NSFW images blurred based on    │   │
│  │  their preferences.                             │   │
│  │                                                 │   │
│  │  Tags                                           │   │
│  │  Type:    [●Portrait] [○Full body] [○Sprite]   │   │
│  │  Mood:    [●Happy] [○Calm] [○Action]           │   │
│  │  Subject: [●Character] [○Solo] [●Female]       │   │
│  │  Categorize this image so it's easy to find    │   │
│  │  with filters.                                  │   │
│  │                                                 │   │
│  └─────────────────────────────────────────────────┘   │
│                                                        │
│  ┌─── AI Context ─────────────────────────────────┐   │
│  │                                                 │   │
│  │  AI Description                   156/2000 chars│   │
│  │  ┌─────────────────────────────────────────┐   │   │
│  │  │ A young woman with long silver hair and │   │   │
│  │  │ violet eyes, smiling warmly...          │   │   │
│  │  └─────────────────────────────────────────┘   │   │
│  │  Describe this image in detail for AI models   │   │
│  │  that can't see pictures. Include appearance,  │   │
│  │  setting, mood, and any important details.     │   │
│  │                                                 │   │
│  └─────────────────────────────────────────────────┘   │
│                                                        │
│                              [Cancel]  [Save Changes]  │
└────────────────────────────────────────────────────────┘

Field grouping: Fields are organized into collapsible sections (Identification, Classification, AI Context) so the form doesn't feel overwhelming. Each section is independently collapsible.

Character counters and limits: Every text field shows current length / max length. The slug field shows a live validation indicator (green check / red X).

Image Picker for Entity URL Fields — Done

The ImagePickerModal shared component is built with Upload and Galleries tabs, server-side search, pagination, and avatar crop, and is integrated (via ImagePickerField) into the entity forms — character and lorebook editors, package about form, account avatar, profile banner editor, and more.

When a character's avatar_url or a lorebook's picture_url needs to reference a gallery image:

┌─── Pick Image ────────────────────────────────┐
│                                                │
│  ┌── Gallery Tabs ──────────────────────────┐ │
│  │ [Portraits]  [Sprites]  [All Galleries]  │ │
│  └──────────────────────────────────────────┘ │
│                                                │
│  ┌────┐ ┌────┐ ┌────┐ ┌────┐ ┌────┐ ┌────┐ │
│  │    │ │    │ │ ✓  │ │    │ │    │ │    │ │
│  │img1│ │img2│ │img3│ │img4│ │img5│ │img6│ │
│  └────┘ └────┘ └────┘ └────┘ └────┘ └────┘ │
│  happy   sad    angry   shy    ...    ...   │
│                                                │
│  Selected: elara-angry (gallery://42/angry)    │
│                                                │
│  [Clear]  [Paste URL instead]  [Select]        │
└────────────────────────────────────────────────┘

Chat Image Rendering — Not Started

When the chat pipeline resolves {{image:keyword}} tokens:

  1. Server identifies the active entity (character/mode) and its attached galleries
  2. Searches for the keyword across attached galleries → gallery_images row
  3. Generates presigned thumbnail URL for inline preview
  4. Client renders inline preview with click-to-expand to full size

A new profile section type galleries displays a creator's public galleries as folder cards:

{
  "key": "galleries",
  "type": "galleries",
  "displayName": "Galleries",
  "content": {
    "items": [
      { "id": 1, "name": "Character Sprites", "slug": "character-sprites", "coverImageUrl": "...", "imageCount": 24, "ratingBreakdown": { "sfw": 20, "suggestive": 3, "nsfw": 1 } },
      { "id": 2, "name": "Scene Backgrounds", "slug": "scene-backgrounds", "coverImageUrl": "...", "imageCount": 8, "ratingBreakdown": { "sfw": 8 } }
    ],
    "totalCount": 3,
    "hasMore": true
  }
}

The server assembles this response — the client renders the folder cards. Rating breakdowns let viewers know what content to expect before opening a gallery.


Image Picker Modal (ImagePickerModal)

A shared component (shared/src/components/common/ImagePickerModal.tsx) that replaces raw URL inputs in entity forms (avatar, picture, cover) with a unified image selection experience. Lives in the shared library so both clientConsole and adminConsole can use it.

Layout

The modal opens with two tab-style cards at the top and a quick-select grid below:

Default:
┌─ Select Image — Elara ──────────── [X] ┐
│  [Upload Image]  [Galleries]            │
│  [🔍 Search by name, slug, keyword...] │
│  ┌──────┐ ┌──────┐ ┌──────┐ ┌──────┐  │
│  │thumb │ │thumb │ │thumb │ │thumb │  │
│  └──────┘ └──────┘ └──────┘ └──────┘  │
│  ┌──────┐ ┌──────┐ ┌──────┐ ┌──────┐  │
│  │thumb │ │thumb │ │thumb │ │thumb │  │
│  └──────┘ └──────┘ └──────┘ └──────┘  │
├─ 1-8 of 12  1/2  ← →   Manage Gal. ──┤
└─────────────────────────────────────────┘

Upload tab open:
┌─ Select Image — Elara ──────────── [X] ┐
│  [Upload Image●]  [Galleries]           │
│  ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐  │
│  │  Choose a file or drag & drop     │  │
│  │  PNG, JPG, GIF, WebP up to 25 MB │  │
│  └ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┘  │
│  ─────── or paste a URL ──────────     │
│  [https://...                 ] [Load] │
│                                         │
│  (after loading an image:)              │
│  [Original preview]                     │
│  ┌─ Avatar Crop ─────────────────────┐ │
│  │ [Image+overlay]  [128px preview]  │ │
│  │ Zoom: [────●──────] 2.3×         │ │
│  └───────────────────────────────────┘ │
│  ☐ Store copy   [✓ Use This Image]    │
├─ 1-8 of 12  1/2  ← →   Manage Gal. ──┤
└─────────────────────────────────────────┘

Gallery selected:
┌─ Select Image — Elara ──────────── [X] ┐
│  [Upload Image]  [Galleries]            │
│  [← Portraits  24 images]              │
│  [🔍 Search by name, slug, keyword...] │
│  ┌──────┐ ┌──────┐ ┌──────┐ ┌──────┐  │
│  │thumb │ │thumb │ │thumb │ │thumb │  │
│  └──────┘ └──────┘ └──────┘ └──────┘  │
├─ 1-8 of 24  1/3  ← →   Manage Gal. ──┤
└─────────────────────────────────────────┘

Props & Integration Points

Prop Type Purpose
images ImagePickerItem[] Gallery images for the grid (caller fetches from API)
galleries GalleryItem[] User's galleries for the Galleries tab
onSelect (result) => void Returns { type, url, thumbnailUrl, name, crop }
onGallerySelect (gallery) => void Called when user picks a gallery — caller should refetch images
onAddImage () => void Enables the Upload tab (file upload handler)
onAddGallery () => void Enables "New Gallery" in gallery list
onManageGalleries () => void Footer link to gallery management page
entityContext { entityType, entityUuid, entityName } Appended to title, used for pre-filtering
allowUrlPaste boolean Show URL paste form in upload tab (default: true)

Avatar Crop in the Picker

When an image is loaded (via file upload or URL), the upload tab shows:

  1. Original image preview — untouched, full aspect ratio
  2. Avatar Crop section — the source image in a 1:1 container with a draggable square overlay + dark mask. Zoom slider (1× to 4×). Live 128px canvas preview.
  3. Crop params (cropX, cropY, cropSize as 0-1 fractions) are included in the ImagePickerResult when confirming.

For external URL images, the crop is client-side only (no server thumbnail). For uploaded gallery images, the crop params are sent to the server for thumbnail generation.

What the Caller Must Provide

The ImagePickerModal is a dumb UI component — it renders what it's given and fires callbacks. The caller (page/form) is responsible for:

Component Location


Implementation Notes

Thumbnail Generation

Use SixLabors.ImageSharp (already available in .NET ecosystem, no native dependencies):

using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Processing;
using SixLabors.ImageSharp.Formats.Webp;

/// Card thumbnail — aspect ratio preserved, fits within 300×300
public async Task<Stream> GenerateCardThumbnailAsync(Stream original)
{
    using var image = await Image.LoadAsync(original);

    image.Mutate(x => x.Resize(new ResizeOptions
    {
        Size = new Size(300, 300),
        Mode = ResizeMode.Max
    }));

    var output = new MemoryStream();
    await image.SaveAsync(output, new WebpEncoder { Quality = 80 });
    output.Position = 0;
    return output;
}

/// Avatar thumbnail — 128×128 square crop using creator-defined crop region
public async Task<Stream> GenerateAvatarThumbnailAsync(
    Stream original, float cropX, float cropY, float cropSize)
{
    using var image = await Image.LoadAsync(original);

    // Calculate crop rectangle from fractional params
    var shortSide = Math.Min(image.Width, image.Height);
    var cropPx = (int)(shortSide * cropSize);
    var x = (int)(image.Width * cropX) - cropPx / 2;
    var y = (int)(image.Height * cropY) - cropPx / 2;

    // Clamp to image bounds
    x = Math.Clamp(x, 0, image.Width - cropPx);
    y = Math.Clamp(y, 0, image.Height - cropPx);

    image.Mutate(ctx => ctx
        .Crop(new Rectangle(x, y, cropPx, cropPx))
        .Resize(128, 128));

    var output = new MemoryStream();
    await image.SaveAsync(output, new WebpEncoder { Quality = 85 });
    output.Position = 0;
    return output;
}

Magic Byte Validation

On upload confirmation, validate the file's actual content (not just headers):

private static readonly Dictionary<string, byte[][]> MagicBytes = new()
{
    ["image/png"]  = new[] { new byte[] { 0x89, 0x50, 0x4E, 0x47 } },
    ["image/jpeg"] = new[] { new byte[] { 0xFF, 0xD8, 0xFF } },
    ["image/gif"]  = new[] { "GIF87a"u8.ToArray(), "GIF89a"u8.ToArray() },
    ["image/webp"] = new[] { "RIFF"u8.ToArray() },  // + check for WEBP at offset 8
};

Database Functions

-- Core functions needed:
fn_create_gallery(user_id, name, description)          → gallery row
fn_update_gallery(gallery_id, user_id, name, ...)      → gallery row
fn_delete_gallery(gallery_id, user_id)                 → deleted bucket keys (for cleanup)
fn_add_gallery_image(gallery_id, user_id, ..., slug, content_rating, tags_0, tags_1, tags_2, gif_stop_frame) → gallery_image row (enforces limits)
fn_update_gallery_image(image_id, user_id, slug, ..., tags_0, tags_1, tags_2) → gallery_image row (validates slug uniqueness per gallery)
fn_delete_gallery_image(image_id, user_id)             → bucket_key + thumb_card_key + thumb_avatar_key
fn_resolve_recall_keywords(gallery_ids[], keywords[])   → array of {keyword, bucket_key, thumb_card_key, thumb_avatar_key, content_rating, gif_stop_frame, ai_description}  (searches within attached galleries, ordered by gallery priority)
fn_resolve_gallery_reference(gallery_uuid, slug)       → gallery_image row (gallery-keyed; NOT the gallery:// resolver — that keys on the image uuid. Unreferenced by product code, kept under test)
fn_resolve_gallery_image_by_slugs(username, gallery_slug, image_slug) → gallery_image row (for g:// markdown references, no privacy check)
fn_get_user_gallery_usage(user_id)                     → {gallery_count, image_count, total_bytes, storage_limit_bytes, file_size_limit_bytes}
fn_suggest_image_slug(gallery_id, file_name)           → suggested slug (sanitized, unique within gallery)
fn_suggest_gallery_slug(user_id, name)                 → suggested slug (sanitized, unique within user's galleries)

Quota enforcement lives in the database functions — fn_add_gallery_image checks total_size_bytes against the user's tier storage limit and file_size_bytes against the per-file limit before inserting. No gallery count or image count limits are enforced. Only original uploads count toward storage — server-generated thumbnails (card + avatar) are a platform cost, not a user cost (see Feature Matrix).

User Deletion

When a user is deleted, the existing UserDeletionService is extended to:

  1. Query all gallery_images with bucket_key IS NOT NULL for the user
  2. Batch delete from the bucket via DeleteManyAsync
  3. Cascade delete handles the database rows (ON DELETE CASCADE from users)

This follows the same pattern as ticket attachment cleanup.


Supported Formats

GIF is a fully supported format from day one — both static and animated GIFs are allowed for all tiers. Animated GIFs are stored and served as-is (no re-encoding), and thumbnails are generated from the first frame (or the creator's chosen stop frame — see below).

AVIF is not accepted on any tier. The server's decoder (ImageSharp 3) has no AVIF codec, so an AVIF upload could never be thumbnailed; offering it was a bug (MEDIA_CONSOLE.md MC-BUG-1, fixed). AVIF can come back with the image-transformations work, once a decoder exists.


Image Metadata — Planned

A photo carries more than its pixels. A phone writes where the picture was taken (GPS coordinates), when, and on which device into the file's EXIF block, and editing software adds XMP and IPTC records with names, software and edit history. Some files also embed a small preview of the uncropped original. None of this is needed to show the picture. Some of it, above all the location, is personal data a creator never meant to publish alongside a character portrait. So every image the platform stores or serves is stored without that metadata: the original, both thumbnails, copies of external images, and image attachments on support tickets.

Design Goals

  1. Nothing identifying survives. GPS position, camera make, model and serial number, capture and edit timestamps, author and software fields, comments and embedded previews are removed from every stored object.
  2. The picture itself is untouched. Originals are stripped losslessly: metadata blocks are removed and the image data is never re-encoded. Quality is unchanged, animated GIFs keep every frame, and the file shrinks only by the metadata it lost.
  3. What the picture needs stays. The ICC colour profile (without it colours shift) and animation data are kept. Orientation is applied: thumbnails are rotated upright, and an original keeps a single EXIF value, its orientation.
  4. One stripper, every writer. A single component does the stripping, and every path that writes an image goes through it: upload confirm, store-a-copy, external-image thumbnails, avatar re-crop, thumbnail backfill and admin regenerate, and support ticket image attachments.
  5. Fail closed. A file whose metadata can't be parsed and removed is refused like a file that isn't an image. It is never stored with its metadata intact.
  6. Before anything serves originals off-platform. Stripping ships before any feature that hands out original files outside the platform, such as image hosting links.

Non-Goals

Design

Originals are stripped at confirm. Today the seal (see the upload flow above) copies the upload inside the bucket, so the bytes never pass through the server and nothing can remove metadata. It becomes a strip-and-write: the server reads the staging object once, removes its metadata, and writes the result to the sealed key. Everything the seal guarantees still holds: the server writes its own key from bytes it read once, and the stripped file's size is what the row records and the quota counts.

Format Removed Kept
JPEG EXIF (except Orientation), XMP, IPTC and Photoshop blocks, comments, the embedded EXIF preview ICC profile, image data
PNG eXIf, tEXt, iTXt, zTXt, tIME chunks colour chunks (iCCP, sRGB, gAMA, cHRM), image data
WebP EXIF and XMP chunks (the header flags are updated to match) ICCP, animation, image data
GIF comment extensions, XMP application extensions the loop extension, frames, timing

AVIF isn't in the table: the gallery doesn't accept it (see Supported Formats). If AVIF comes back with a decoder, its metadata lives in a nested item structure rather than separate blocks, so stripping it needs its own design then. That follows goal 5.

Thumbnails are upright and bare. The source is rotated to its orientation before it is cropped and resized. The WebP thumbnail is then encoded with no EXIF, XMP or IPTC, keeping only the colour profile.

The avatar crop is measured on the upright picture. The crop editor shows the picture as a browser shows it, rotated by its orientation, so the server applies the orientation before it crops. Crop fractions measured on the upright view but applied to unrotated pixels select a different region of a rotated phone photo.

Images already stored are backfilled. A one-off job strips every stored original, writing it to a fresh key the way a seal does, and rebuilds both thumbnails. Image URLs are cached as immutable, so the job also makes sure no cache keeps serving the old files. Rebuilt thumbnails get a new version on their own. Originals get one through the global image cache-buster, and the edge cache for image URLs is purged. A picture's key and thumbnail version are part of an entity's approved public face, so the backfill sends every approved entity that shows a picture back for review. See Open Questions.

Support attachments. Image attachments on support tickets go through the same stripper when they are stored. Only the ticket's owner and staff see them, but a phone screenshot carries the same location data. This lands together with sealing ticket uploads, which is planned in the support migration.

Open Questions

For the owner:

Acceptance Criteria

This work is not done until every box below is verified ✅ against the running product.

User use cases — satisfiable + accessible (verify by driving the UI, not the code):

Behavior:

Invariants that must stay true:

Edges:


Content Rating

Content rating values and server/client responsibilities are defined in the Per-Image Content Rating & Tags section above. This section covers the viewer-side blur behavior.

Content Blur

Viewers control how images at each rating level are displayed via a blur toggle/slider in their user settings. This lets users choose their comfort level independently from what creators upload.

User settings (stored as user preferences):

Setting Key Type Default Description
Content.BlurMode select all all = blur Suggestive + NSFW, suggestive ("Mild Only") = show SFW + Suggestive, blur NSFW, none = show everything
Content.BlurIntensity slider 20 Blur strength in pixels (range: 5–40)

A single BlurMode setting replaces two independent booleans — the three states are mutually exclusive, which avoids impossible combinations (e.g., "blur NSFW but not Suggestive" doesn't make semantic sense since NSFW is a superset of Suggestive).

Client behavior:

Gallery grid integration:


GIF Playback Control

Animated GIFs can be resource-intensive on low-bandwidth or low-power devices. A GIF stop feature lets users globally pause all animated GIFs, and lets creators choose which frame is shown when paused.

User Toggle

A "Stop GIFs" toggle is placed in the user menu (top-level, easily accessible — not buried in settings). When enabled:

Creator Stop Frame

When uploading or editing an animated GIF, the creator can optionally pick a stop frame — the frame displayed when GIF playback is paused by the viewer.

Client rendering (when GIF stop is active):

The client extracts the stop frame from the GIF on load and renders it as a static <canvas> element. For thumbnails, the server pre-renders the stop frame into the WebP thumbnail, so no client-side extraction is needed in grid views.

// Simplified client logic
if (userPrefs.stopGifs && image.contentType === 'image/gif') {
  // In grid view: use server-generated thumbnail (already uses stop frame)
  // In full view: extract stop frame via canvas, render as static image
  renderStaticFrame(image.url, image.gifStopFrame ?? 0)
} else {
  // Normal animated playback
  renderImage(image.url)
}

AI Description (LLM Vision Fallback)

Gallery images have an optional ai_description field — a text description of the image's content intended for LLM consumption when the model doesn't support vision input.

The Problem

Not all LLM models support image/vision input. When a user references an image in chat (via {{image:elara_happy}}), the pipeline needs a way to convey the image's content to the model even if the model is text-only. Without a fallback, the model either ignores the image entirely or gets a useless placeholder like "[image attached]".

How It Works

The ai_description field on gallery_images stores a rich, detailed text description of the image (up to 2,000 characters). This is distinct from caption (which is a short, human-facing label for display in the UI).

Field Purpose Max Length Audience
caption Short display label shown under the image in the UI 300 chars Humans (UI)
ai_description Detailed description of image content for LLM context 2,000 chars LLMs (prompt)

Example:

Pipeline Behavior

When the chat pipeline resolves an {{image:keyword}} token:

  1. Resolve the image — identify the active entity's attached galleries, search for the recall keyword, get the image row (including ai_description, bucket_key, content_rating)
  2. Check model capabilities — does the current model support vision/image input?
  3. Vision-capable model — send the image as a multimodal content part (image URL or base64) alongside any ai_description as supplementary context
  4. Text-only model — substitute the ai_description into the prompt as a text block:
[Image: elara_happy — A young woman with long silver hair and violet eyes, smiling warmly. She wears a deep blue cloak over a white tunic, standing in a lush garden with flowering wisteria arches behind her. Soft afternoon light casts golden highlights across her face. Her posture is relaxed, one hand resting on a stone bench beside her.]
  1. No description and no vision — insert a minimal placeholder: [Image: elara_happy — no description available]

Model Vision Detection

The ModelInfo record already has a Modality field. The pipeline uses this to determine whether to send image content parts or fall back to text descriptions. If Modality is null or doesn't indicate image input support, the fallback path is used.

Creator Workflow

Manual description: Creators write the ai_description when uploading or editing an image. The UI provides a dedicated text area with guidance: "Describe this image in detail for AI models that can't see pictures. Include appearance, setting, mood, and any important details the AI should know about."

Auto-generate description (future): When a vision-capable model is available on the platform, creators can click "Auto-describe" to have the AI generate a description from the image. The creator reviews and edits before saving. This is a convenience feature — the creator always has final control.

Application to Existing Image Fields

The ai_description pattern extends beyond gallery images to all entity images across the platform:

Characters:

Lorebooks:

Lorebook entries:

Personas:

Schema Changes

-- Gallery images (new table — field included in CREATE TABLE above)
-- ai_description VARCHAR(2000)

-- Characters
ALTER TABLE characters ADD COLUMN IF NOT EXISTS avatar_ai_description VARCHAR(2000);
COMMENT ON COLUMN characters.avatar_ai_description IS
    'Text description of the avatar image for LLM context when vision is unavailable';

-- Lorebooks
ALTER TABLE lorebooks ADD COLUMN IF NOT EXISTS picture_ai_description VARCHAR(2000);
COMMENT ON COLUMN lorebooks.picture_ai_description IS
    'Text description of the lorebook picture for LLM context when vision is unavailable';

-- Personas
ALTER TABLE personas ADD COLUMN IF NOT EXISTS avatar_ai_description VARCHAR(2000);
COMMENT ON COLUMN personas.avatar_ai_description IS
    'Text description of the persona avatar for LLM context when vision is unavailable';

Future Considerations

Discoverability & Community Browsing

The initial release focuses on personal asset management, but the architecture is designed to support community discoverability later. Key decisions that keep this path open:

Community gallery browsing (search, trending, curated collections) is not part of the initial scope, and — contrary to an earlier version of this section — it does require architectural work first. Three gates are outstanding, tracked in Gallery Folders § Future public hierarchy and the Anonymous Entry architecture: galleries are not in the anonymous entity-type allowlist; there is no platform-approved anonymous-exposure flag distinct from is_public; and the public gallery endpoint's maxRating is a caller-supplied filter with no server-enforced maturity ceiling, while image ratings genuinely reach NSFW.

Other