1. System Architecture
Three-Tier Containerized Topology
Docker Compose runs a multi-stage Node 24 API/static server backed by PostgreSQL 17 and
external Chat and Image inference backends over HTTP SSE or gRPC streams.
Client Layer
React 19 + TypeScript + Vite 7
- SSE streaming consumer & 450ms image progress polling
html[data-theme] CSS token system (WhatsApp Dark / Liquid Glass)
- Per-user
localStorage persona avatar cache & zoom lightbox
- 30-second open-chat inactivity ping dispatcher
Orchestration Layer
Express 5 + Zod + gRPC + FlatBuffers
- JWT session auth + salted SHA-256
cc_ personal API tokens
- Two-tier safety engine + zero-reply under-18 warning gate
- UTF-16 surrogate-safe truncation & JSON string sanitization
- Structured logger (
debug, info, warn, error)
Data & Inference Backends
PostgreSQL 17 + Chat & Image AI
- Chat: LM Studio native & OpenAI-compatible SSE endpoints
- Image HTTP: Draw Things
/sdapi/v1/txt2img & generic REST
- Image gRPC: Draw Things
ImageGenerationService + fpzip WASM
- Hot-swappable multi-provider registry in
ai_api_configs
+------------------------+ HTTPS / SSE +-----------------------------------+
| React 19 + Vite SPA | <-------------> | Express 5 Server |
| - Chat & Photo UI | | - Auth (JWT / SHA-256 cc_ keys) |
| - Dual Theme Engine | | - Guardrails & Minor Gate |
| - Admin Control Panel | | - Intent Router & Memory Recap |
+------------------------+ +----+--------------+-------------+--+
| | |
+----------------------------+ | +----------------------+
v v v
+---------------------+ +-----------------------+ +-----------------------+
| PostgreSQL 17 | | Chat Providers | | Image Providers |
| 9 Core Tables | | - LM Studio | | - Draw Things gRPC |
| Token Metering | | - Generic OpenAI SSE | | - Draw Things HTTP |
+---------------------+ +-----------------------+ | - Generic REST/gRPC |
+-----------------------+
2. Chat, Memory & Photo Routing Pipeline
-
Pre-Write Guardrail Evaluation: Inspects prompts against Tier 1 rules
and under-18 restrictions before persisting blocked minor inputs.
-
Fact Extraction & Surrogate-Safe Recap: Extracts structured user
facts into
chat_contexts and summarizes turns beyond the 24-turn window
via truncateSafe so sliced emojis never break downstream PHP/JSON
parsers.
-
Prompt Normalization & Sanitization: Merges consecutive same-role
turns for strict
system → user → assistant alternation and cleanses all
outbound strings with sanitizeJsonValue before
JSON.stringify.
-
Intent & Tag Switching:
detectPhotoIntent or buffered
leading [[PHOTO: ...]] tags transition automatically into contextual image
generation with real-time progress events.
-
Context Isolation & Captions: Manual camera requests
(
POST /api/chats/:id/image) omit recent chat context; AI-detected photos
include bound scenario and turns, followed by one-line prompt-free captions via
formatImageReplyOneLiner.
3. Draw Things gRPC & Tensor Decoding
-
Echo Checkpoint Resolution: Queries the remote Draw Things gRPC server
via
Echo to validate optional Shared Secret auth and match partial model
names (such as epic_photon) to exact .ckpt files.
-
FlatBuffers Binary Configuration: Serializes model name, width,
height, inference steps, guidance scale, sampler parameters, and random seed into native
Draw Things FlatBuffer payloads.
-
Live Step Telemetry & Previews: Tracks
ImageGenerationSignpostProto sampling progress and decodes intermediate
latent frames compressed with fpzip WASM and Float16 pixel buffers into PNG
data URLs.
-
Identity & Aesthetic Controls: Supports per-config
include_persona, keep_face_same (with optional portrait
reference), phi 1.618 framing cues, and separate Safe/Private negative
prompts.
4. Safety, Privacy & Observability
-
Under-18 Warning-Only Protection: Disables
private mode
on creation/toggle, replaces playful deflections with zero-reply SSE/JSON warnings, and
filters both system prompts and buffered LLM replies so under-18 personas never invite
or mention Private Chat.
-
Ephemeral Private Sessions: Records tagged
is_private = 1 are deleted on mode switch back to Safe, browser unload
(keepalive beacon), logout, or next login.
-
Credential & Log Redaction: Passwords use salted
scrypt hashes, personal API keys store SHA-256 digests, custom API
headers deduplicate case-insensitively, and sanitizeLogMeta strips keys,
tokens, and oversized Base64 image strings while DEBUG logs full crafted
Chat/Image prompts.
-
Customizable Appearance & Branding: Admin settings control app-open
default theme, name, tagline, logo, and favicon; users override theme per account.
5. PostgreSQL 17 Data Model
users
Accounts, locked gender, quotas, preferred_theme
api_tokens
SHA-256 personal cc_ access tokens
ai_settings
Global quotas, default_theme, app branding
ai_api_configs
Active & saved Chat / Image provider entries
personalities
Seeded & custom personas with age and voice prompts
chats
User/persona threads with safe/private mode state
chat_contexts
Bound scenario, pinned facts JSON, reference notes
messages
Chat turns, generated image URLs, is_private, tokens
token_usage_logs
Per-request metering for chat tokens and image credits
Verification & Source
Verified with TypeScript strict checks, Vite production builds, and Vitest + Supertest +
pg-mem integration tests covering guardrails, themes, branding, and UTF-16 JSON payloads.