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
- Give creators a proper media library, not just scattered URL fields
- Support linking images to characters, lorebooks, and other entities
- Enable recall keywords so images can be referenced in chats, effects, and triggers
- Prevent abuse as free file hosting
- Keep images platform-internal — not a public CDN
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:
- The entity's detail page shows the attached gallery as an expandable image section
- Entity image URL fields (like
avatar_url,picture_url) gain a "Pick from gallery" button that browses only attached galleries - Attachment is a lightweight link — the gallery and its images remain in one place (the gallery). No duplication.
- An entity can have multiple attached galleries (e.g., a character has "Portraits" and "Sprites")
- A gallery can be attached to multiple entities (e.g., a "Shared Backgrounds" gallery attached to several characters)
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.
Picking a Specific Image from an Attached Gallery
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:
- Creator opens the character editor, clicks the avatar field
- A picker modal shows the character's attached galleries as folder tabs
- Creator browses images within a gallery, clicks one to select
- The field stores
gallery://a1b2c3d4-.../elara-smiling(gallery ID + image slug) - At render time, the server resolves this reference to a presigned URL and returns it in the API response
- 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:
- Human-readable references in
gallery://URLs - Stable identifiers that survive image re-uploads (same slug, new file)
- Readable recall keyword alternatives
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:
- Stored as
content_rating SMALLINT NOT NULL DEFAULT 0ongallery_images - Gallery listing endpoints accept
?maxRating=Nto filter —0(SFW only),1(SFW + Suggestive), or omit for all. Server returns only images at or below the specified rating. - Every gallery detail response includes a
ratingBreakdown: { sfw: 12, suggestive: 3, nsfw: 1 }so the UI can show content composition and let viewers know what's hidden by their current filter. - Public gallery endpoint (
GET /api/galleries/public/{uuid}) supports the same filtering and clampspageSizeto 1–50.
Client-side:
- The rating is set via radio buttons in the image editor (not a dropdown — radio buttons make the options immediately visible)
- Description below: "How mature is this image's content? This affects whether other users see it blurred."
- The content blur system (CSS
filter: blur()) is purely client-side — see the Content Blur section below
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:
- Tags are stored and filtered using the same
tags_match_any/tags_match_nonebitmask functions from58_tag_functions.sql - Gallery listing accepts tag filter bitmasks in query params —
?t0=...&t1=...&t2=...— same pattern as character browse - A new
GalleryImageTags.csinCore/Tags/defines the predefined tag indices
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:
- Tag selection uses a grouped checkbox/pill selector (same UI pattern as character tag picker in the hub browse)
- Tags are organized by category with clear group labels
- Description: "Categorize this image so it's easy to find with filters."
- Selected tags render as colored pills below the selector
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:
- Entity permissions (public, private, unlisted)
- Entity changelog tracking
- Linking via
gallery_entity_grants(see Gallery Links & Image Keywords) - Workbench integration
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);
Per-Image Entity Links & Entity Filtering
The gallery_image_entity_links table serves two purposes:
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.Filtering — the gallery detail endpoint accepts
?entity_type=N&entity_id=Mto 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:
GET /api/galleries/{uuid}returnslinkedEntities— a deduplicated list of all entities that images in this gallery are linked to (with entity name/type/uuid for display). This powers the filter chips in the UI.GET /api/galleries/{uuid}?entity_type=0&entity_uuid=...filters to only images linked to that entity viagallery_image_entity_links- Each image in the response includes its
linkedEntities: [{ entityType, entityUuid, entityName }]array so the UI can show which entities an image belongs to
Client-side:
- The gallery detail page shows entity filter chips above the image grid (e.g.,
[All] [Elara ×] [Forest Kingdom ×] [Tavern Scene ×]) - Clicking a chip filters to that entity's images — this is a URL param change, triggering a new API call with the filter
- In the image editor, a "Linked Entities" section lets creators assign/unassign entities to the image
- The image picker modal (when picking an avatar for a character) automatically pre-filters to that character's assigned images
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:
- Alphanumeric + underscores, lowercase, 3–50 chars
- Pattern:
^[a-z0-9_]{3,50}$ - Unique per gallery (enforced by
uq_recall_keyword_per_gallery). The same keyword can exist in different galleries — resolution is scoped to which galleries are attached to the active entity.
Resolution order in the chat pipeline:
When the pipeline encounters {{image:elara_happy}}:
- Identify the active entity context — which character/mode/lorebook is driving this conversation?
- Collect attached galleries — find all galleries linked to the active entity via
gallery_entity_grants(planned) - Search recall keywords — look up
elara_happyacross the attached galleries' images - Resolve — return the matching image's presigned URL (thumbnail for inline, full-size on demand)
- 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:
- A creator builds a character with specific visual assets. When any user chats with that character, they should see the creator's intended images.
- Different characters by different creators can both use
happyas a keyword — there's no collision because resolution is scoped to the entity's attached galleries. - The creator controls the visual vocabulary per entity. Users don't need to know or manage recall keywords.
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:
- 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.
- Client uploads directly to the bucket with that policy.
- 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_imagesrow 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:
- Card thumbnails preserve the full image composition — important for gallery browsing where users need to see the whole picture.
- Avatar thumbnails are always square and always small — used everywhere the platform shows a circular or square avatar. Without a dedicated crop, wide landscape images or tall portraits look terrible squeezed into a 128px circle.
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:
- On upload, avatar thumbnail is generated with default crop (centered, no zoom —
avatar_crop_size = 1.0) - When the creator adjusts the crop, the server regenerates the avatar thumbnail from the original image using the new crop params and re-uploads to the bucket. The card thumbnail is unaffected.
- Crop values are fractions (0.0–1.0), not pixels — this keeps them resolution-independent and valid even if we later support different avatar sizes.
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 │
│ └────┘ │
│ │
└────────────────────────────────────────────────┘
- The original image is shown at display size with a draggable square overlay representing the crop region
- A zoom slider controls
avatar_crop_size(1× = full width, up to 4× zoom) - Dragging the square updates
avatar_crop_x/avatar_crop_y - A live preview shows the resulting 128px square avatar in real time (client-side canvas crop, no server round-trip for preview)
- On save, the crop params are sent to the server, which regenerates and re-uploads the avatar thumbnail
When is the crop editor shown?
- In the image detail/editor form, as a collapsible "Avatar Crop" section
- In the image picker modal, when selecting an image for an avatar field — a quick crop step appears before confirming selection
- The crop is stored on the image itself, not on the entity using it. This means the same crop is used everywhere that image appears as an avatar. If a creator wants different crops for different contexts, they upload the image twice with different crops.
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:
- Thumbnails are small, lossy, low-resolution derivatives. Nobody is going to use a 128px WebP as their desktop wallpaper or repost a 300px card thumbnail. The abuse vector is the original — that's what needs protection.
- Public thumbnail URLs are stable — the same URL forever (until the image is deleted or the crop is changed). This means real browser caching (
Cache-Control: public, max-age=31536000, immutable), CDN caching, zero expiry management. - Gallery grids, character cards, chat avatars, entity pickers — these all use thumbnails. Making them public eliminates presigned URL generation for the most common access pattern (browsing), dramatically reducing API load and improving page load times.
- When a thumbnail is regenerated (avatar crop change, GIF stop frame change), the bucket key changes (new UUID prefix), so the old cached URL naturally 404s and the client gets the new URL from the next API response.
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 |
- 1 hour is short enough that harvested URLs become useless quickly
- Long enough that opening a lightbox, closing it, and opening it again serves from browser cache
- The API response includes
expiresAtso the client knows when to request a fresh URL
Client-side management (originals only):
- The client stores
expiresAtalongside each original's presigned URL in the Zustand store - Before opening a lightbox/full-size view, check if the URL is still valid (now < expiresAt - 60s buffer)
- If expired, fetch a fresh presigned URL — this is a single lightweight API call, not a full page re-fetch
- For long-lived chat sessions, batch-refresh original URLs before expiry
Server-side cache headers:
- Presigned original URLs:
Cache-Control: private, max-age=3600— browser caches for 1 hour, not shared caches - Public thumbnail URLs:
Cache-Control: public, max-age=31536000, immutable— cached forever, busted by URL change on regeneration
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?
- A user with 100 MB can make 1 gallery with 50 images or 50 galleries with 1 image each — their choice. The platform doesn't care how they organize.
- File size per upload prevents individual monster files that slow down thumbnail generation and presigned URL transfers.
- Total storage is the real cost driver (bucket storage + bandwidth). Limiting it directly is honest and understandable.
- Artificial count limits create frustrating "you hit 20 images, upgrade!" walls that don't correlate with actual cost. A gallery of 100 tiny icons uses less storage than 5 high-res portraits.
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:
- You can't embed a full-size gallery image on an external site — the URL breaks within an hour
- You can't use the platform as a CDN or hotlink originals from other services
- Crawlers/scrapers get expired links for anything worth stealing
Thumbnails and avatars are publicly accessible with stable URLs. This is acceptable because:
- They are small (300px / 128px), lossy WebP derivatives — not useful as stolen high-res content
- Making them public enables aggressive browser and CDN caching, which is critical for performance since thumbnails appear on nearly every page
2. Referrer / Context Validation on URL Generation
The presigned URL generation endpoint validates that the request comes from a legitimate platform context:
- Authentication required — only logged-in users can generate download URLs
- Ownership or permission check — the requesting user must either own the image or have access to the entity it's linked to (e.g., a public character's gallery)
- Rate limiting — presigned URL generation is rate-limited per user to prevent bulk scraping
// 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:
- Presigned URL generation — rejects before the upload starts
- 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:
- Allowed MIME types:
image/png,image/jpeg,image/webp,image/gif— exactly the formats the server's decoder reads (GuardedImageDecoder.AcceptedContentTypes) - Server-side magic byte validation on upload confirmation (don't trust the content-type header alone)
- Non-image files are rejected and the bucket object is deleted
5. Orphan Cleanup
A scheduled job (daily) scans for:
- Orphaned bucket objects — objects in the bucket that have no corresponding
gallery_imagesrow (failed uploads, race conditions) - Deleted user cleanup — when a user is deleted, all their gallery images are batch-deleted from the bucket (uses the existing
DeleteManyAsyncpattern from ticket attachments)
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:
- The profile/character page API resolves original images server-side and returns presigned URLs in the response
- The presigned URLs expire after 1 hour
- External visitors (not logged in) viewing a public profile get presigned URLs for originals embedded in the profile response — they work for 1 hour, and the browser caches the image bytes for that duration
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).
Gallery as a Workbench Entity
- Galleries appear in the workbench entity list alongside characters, lorebooks, etc.
- Standard CRUD: create, rename, delete, set visibility (public/private/unlisted)
- Entity linking: galleries can be linked to characters, lorebooks via the workbench's entity linking UI
Gallery View (Workbench Tab)
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:
- Workbench Gallery view shows both node-embedded assets (sprites, backgrounds) and linked user galleries
- Users can drag images from their galleries onto graph nodes to set sprites, backgrounds, etc.
- The gallery entity picker is available in all asset fields across the workbench
Standalone Gallery Management
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
Gallery CRUD — Done
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
Public Gallery — Done
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.
Gallery Reference Resolution — Removed (2026-10-23)
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/pictureImageUuidand resolve server-side — and the client uses the picker'sthumbnailUrldirectly. It stands as the authenticated resolver for storedgallery://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
Gallery Grid Component — Shipped
The image grid (ImageGridPanel) renders a responsive image grid with:
- Thumbnail view (default) — uses stable signed URLs from the API response (cached indefinitely, no expiry management)
- Lightbox on click (
ImageLightboxshared component) - Lazy loading — thumbnails load as they scroll into view
- Upload dropzone — drag & drop or click to upload (in edit mode)
- Content rating badges — visible on each thumbnail, blurred per user preferences
- Tag pills — shown below thumbnails in expanded view
Gallery as Folder — UI Presentation — Shipped (as the three-panel gallery manager at media.echoofdreams.eu/images)
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:
- Storage usage bar shows at the top level — creators always know how much space they have
- Empty gallery card doubles as a "create" CTA with drag-to-upload affordance
- Each folder card shows: cover image, name, image count, storage used
- Tier limits are visible (not hidden) — "2 of 3 galleries used" prevents surprise blocks
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] │
└────────────────────────────────────────────────┘
- Tabs show only galleries attached to the current entity
- "All Galleries" tab browses the user's full gallery list
- "Paste URL instead" lets the user enter a raw URL (backwards compatible)
- Image slugs are shown below thumbnails for easy identification
Chat Image Rendering — Not Started
When the chat pipeline resolves {{image:keyword}} tokens:
- Server identifies the active entity (character/mode) and its attached galleries
- Searches for the keyword across attached galleries →
gallery_imagesrow - Generates presigned thumbnail URL for inline preview
- Client renders inline preview with click-to-expand to full size
Profile Gallery Section — Not Started
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 state (no tab selected): tab row + search + image grid. The grid shows recent/relevant images for fast selection.
- Upload tab: file picker (click or drag & drop), URL paste with preview, avatar crop editor, "Use This Image" confirm.
- Galleries tab: "New Gallery" create row (EntityPickerModal style) + scrollable list of the user's galleries. Clicking a gallery collapses the tab and shows that gallery's images in the grid with a context bar (← back, gallery name, image count).
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:
- Original image preview — untouched, full aspect ratio
- 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.
- Crop params (
cropX,cropY,cropSizeas 0-1 fractions) are included in theImagePickerResultwhen 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:
- Fetching images from the API (and refetching when a gallery is selected)
- Handling the presigned URL upload flow when
onAddImagefires - Creating galleries when
onAddGalleryfires - Writing the selected
gallery://ref or external URL into the entity's field - Persisting avatar crop params to the image record
Component Location
- Component:
shared/src/components/common/ImagePickerModal.tsx - Showcase:
shared/src/showcase/sections/ImagePickerSection.tsx(at/dev/components) - Exports:
ImagePickerModal,ImagePickerItem,ImagePickerResult,GalleryItemfrom@shared/components
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:
- Query all
gallery_imageswithbucket_key IS NOT NULLfor the user - Batch delete from the bucket via
DeleteManyAsync - 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
- 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.
- 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.
- 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.
- 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.
- 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.
- 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
- Letting a creator keep metadata, such as an artist's copyright fields. Credit belongs in the image's caption and description, which the creator controls. Stripping is unconditional. An opt-in per image could come later.
- Reading metadata for features (sort by capture date, captions from camera data). Nothing is read and nothing is kept.
- Anything in the pixels (a street sign or a face in the background). The picture is the creator's choice.
- Images added by URL without a stored copy. They are served from their own host and aren't ours to rewrite. The thumbnails we generate for them are ours, and those are stripped.
- Recalling copies that browsers or third parties downloaded before the backfill.
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:
- Re-review after the backfill. Stripping changes the key or thumbnail version of every stored picture, and that stales every approved public face that shows one. The options: (a) accept the re-review queue, which is fail-closed and the current rule; or (b) a one-time, audited re-pin for entities whose face changed only through this backfill. Option (b) is the one path that would move an approval pin without a human looking, so it needs its own review of the approval rule.
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):
- UC-1. As a creator, I upload a portrait phone photo from the gallery page (Upload), and it shows upright in the grid, the lightbox and the avatar slot. Same entry point and steps as today, with no extra step.
- UC-2. As a creator, I set the avatar crop on a portrait phone photo, and the avatar shows the region I picked.
- UC-3. As a visitor, any picture I save from a public character page (card, avatar, full size) carries no location, device or timestamp metadata.
- UC-4. As a user, when I attach a phone screenshot to a support ticket, staff receive it without location metadata.
Behavior:
- B1. A JPEG uploaded with EXIF GPS, make/model, capture time, an XMP packet, an IPTC block and an
embedded EXIF preview: the stored original, card thumbnail and avatar thumbnail, each read back
through
/api/imgwith an EXIF reader, carry none of them. - B2. The same holds for PNG (
eXIf/tEXt/iTXt/zTXt), WebP (EXIF/XMPchunks), GIF (comment and XMP extensions). - B3. The stored original's image data is byte-identical to the upload's: JPEG scan data, PNG
IDAT, WebP bitstream and GIF frames. Only metadata differs. - B4. The ICC profile survives in the original and in both thumbnails. A Display-P3 test image keeps its profile.
- B5. For an image with EXIF orientation 6, both thumbnails' pixels are upright and carry no orientation tag, and the original's only EXIF value is its orientation.
- B6. Store-a-copy, external-image thumbnails, avatar re-crop, thumbnail backfill and admin regenerate all write stripped output.
- B7. The quota and
file_size_bytescount the stripped original's size. - B8. After the backfill, a scan of every stored object finds no EXIF GPS, XMP or IPTC. Newly minted image URLs carry a new version, and the edge cache for image URLs was purged.
Invariants that must stay true:
- I1. A confirmed upload is still final: a second POST through the same upload policy after confirm changes nothing the image row describes.
- I2. Animated GIFs and animated WebPs stay animated, with the same frame count and timing.
- I3. Upload entry points, steps and the upload/confirm API are unchanged: no new UI and no new request fields.
- I4. An image added by URL without a stored copy is still served from its own host, unchanged.
Edges:
- E1. A file whose metadata can't be parsed is refused at confirm the way a non-image is: a 400, nothing stored, the upload spent.
- E2. A file with no metadata is stored byte-identical to the upload.
- E3. If stripping fails for an image during the backfill, that image's objects and row are left untouched and the failure is reported, and the backfill carries on with the rest.
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:
- Blurred images show a frosted overlay with the content rating badge visible
- Click/tap to reveal — the image unblurs for the current viewing session only (does not persist)
- The blur is applied via CSS
filter: blur(Npx)on the client — the server always returns the full image, blur is purely a client-side rendering decision - The blur slider lets users fine-tune intensity: light blur (can still make out shapes) to heavy blur (fully obscured)
- Settings are accessible from the user menu for quick toggling without navigating to a settings page
Gallery grid integration:
- Blurred thumbnails show the rating badge (e.g., "Suggestive", "NSFW") centered on the blur overlay
- Gallery list views show a content rating breakdown (e.g., "12 SFW, 3 Suggestive, 1 NSFW")
- Filtering by content rating is available in gallery views
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:
- All animated GIFs across the platform render as static images
- The displayed frame is either the creator's chosen stop frame or the first frame (default)
- The toggle is stored as a user preference:
gallery.stop_gifs(boolean, defaultfalse) - Toggling takes effect immediately without page reload (reactive via Zustand store)
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.
- Stored as
gif_stop_frame INTEGERongallery_images(NULL = use first frame) - The upload/edit UI shows a frame scrubber for animated GIFs: a horizontal strip of keyframes the creator can click to select
- Frame extraction happens client-side (using the canvas API to step through GIF frames) — no server-side processing needed for the preview
- The chosen frame index is sent to the server on confirm/edit and stored in the database
- When generating both thumbnails (card + avatar) for animated GIFs, the server uses the stop frame (if set) instead of the first frame
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:
- Caption: "Elara smiling in the garden"
- AI Description: "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."
Pipeline Behavior
When the chat pipeline resolves an {{image:keyword}} token:
- 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) - Check model capabilities — does the current model support vision/image input?
- Vision-capable model — send the image as a multimodal content part (image URL or base64) alongside any
ai_descriptionas supplementary context - Text-only model — substitute the
ai_descriptioninto 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.]
- 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:
avatar_urlalready stores the character's image URL- A new
avatar_ai_description VARCHAR(2000)field on thecharacterstable describes the avatar for text-only models - The pipeline injects this into the character's system prompt context when the model doesn't support vision
Lorebooks:
picture_urlstores the lorebook's cover image- A new
picture_ai_description VARCHAR(2000)field on thelorebookstable describes the image - Used when lorebook entries reference their parent lorebook's image in context
Lorebook entries:
- Entries can link to gallery images via
gallery_image_entity_links - When an entry's linked image is injected into context, the pipeline uses the gallery image's
ai_descriptionas the fallback
Personas:
avatar_urlstores the persona's image- A new
avatar_ai_description VARCHAR(2000)field on thepersonastable - Injected into the user's persona context block for text-only models
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:
- Galleries already have
is_publicvisibility, which is the creator intent half of discoverability - The planned
gallery_entity_grantssystem will make public galleries linked to public characters/lorebooks discoverable through those entities - Recall keywords are per-user scoped, so a future "browse community galleries" feature won't collide with personal keyword namespaces
- The bitmask tag columns on
gallery_imagesprovide the same high-performance filtering surface used for character/lorebook browse — community gallery browsing can use the sametags_match_any/tags_match_nonefunctions
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
- Gallery sharing & collaboration — not yet supported. Galleries are not registered in
entity_permissions(the table'sentity_typeCHECK excludes gallery), so per-user permission grants, unlisted visibility, and collaborator access do not work out of the box. Access today is a flat owner check plus the singleis_publicboolean. An earlier version of this section claimed otherwise; building real sharing means adding galleries to the permission system first. - Gallery forking — duplicate a public gallery into your own account (for shared sprite sheets, asset packs)
- Asset packs — several pictures used as one asset: a picture plus its overlays (expressions, poses, foreground pieces) and its lighting maps, with a settings descriptor that says how they fit. The platform library's own packs for the visual novel and RPG maps come first, made by staff; packs in your own gallery come later. Engineering spec:
docs-internal/architecture/consoles/ASSET_PACKS.md. - Animated sprites — GIF/APNG frame extraction for sprite sheet generation
- Video & other media types — support for video, audio, spritesheets, and other rich media formats will be evaluated based on community feedback and platform income. These are not ruled out but are not part of the initial scope