Add Codex development reference docs

This commit is contained in:
FengLee
2026-05-12 19:27:52 +08:00
parent 8ee86a970e
commit c9d6915878
7 changed files with 832 additions and 0 deletions

18
AGENTS.md Normal file
View File

@@ -0,0 +1,18 @@
# Codex Mandatory Project Instructions
This repository is the source code for the MiaoJing AI creation platform.
Before any Codex agent changes code, fixes bugs, reviews behavior, or answers implementation-location questions in this repository, it must first read:
1. `CODEX_MIAOJING_MEMORY.md`
2. `docs/codex-miaojing/README.md`
3. The specific index document linked from the memory file for the task area:
- `docs/codex-miaojing/feature-code-index.md`
- `docs/codex-miaojing/bug-location-guide.md`
- `docs/codex-miaojing/api-reference.md`
- `docs/codex-miaojing/architecture.md`
Do not start by broad-searching the repository when the memory and index documents already identify a likely file path. Use those documents as the first routing layer, then verify against the current source before editing.
When a change moves code, adds an API, changes a workflow, or fixes a bug that affects future code-location or diagnosis work, update the relevant document in `docs/codex-miaojing/` and, if needed, update `CODEX_MIAOJING_MEMORY.md` in the same commit.

93
CODEX_MIAOJING_MEMORY.md Normal file
View File

@@ -0,0 +1,93 @@
# Codex MiaoJing Memory
Last source audit: 2026-05-12, based on git commit `8ee86a9` (`Add NewAPI image compatibility and style presets`).
This file is the required entry point for Codex work in this repository. Its job is to prevent repeated rediscovery. Every Codex session working on MiaoJing must read this file first, then jump to the referenced index document before editing.
## Required Reading Order
1. Read this file.
2. Read `docs/codex-miaojing/README.md`.
3. Pick the task-specific document:
- Feature or UI location: `docs/codex-miaojing/feature-code-index.md`
- Bug report or regression: `docs/codex-miaojing/bug-location-guide.md`
- API contract, route, auth, request body: `docs/codex-miaojing/api-reference.md`
- System boundaries, data flow, deployment: `docs/codex-miaojing/architecture.md`
4. Verify the file paths against current source with `rg` or direct file reads.
5. Make the smallest scoped code change that fits the existing architecture.
6. If your change alters code ownership, endpoint behavior, schema expectations, deployment flow, or bug-diagnosis paths, update the docs in the same commit.
## Repository Identity
- Product: MiaoJing AI creation platform.
- Stack: Next.js 16 App Router, React 19, TypeScript, PostgreSQL, local file storage, PM2.
- Package manager: `pnpm` only.
- Primary source directories:
- Pages and API routes: `src/app`
- UI and workflow components: `src/components`
- Business logic and stores: `src/lib`
- Console module entry points: `src/modules`
- Database clients and schema snapshot: `src/storage`
- Deployment and maintenance scripts: `scripts`
## Canonical Local Context
- This local clone was reset to `origin/main` before these docs were written.
- Remote: `https://git.toplee.cn/fenglee/miaojingAI.git`
- If server deployment is requested later, verify the active runtime tree and PM2 cwd before editing. Do not assume a production tree from memory.
## Fast Routing Map
Use this table before searching.
| Task | Start Here | Then Check |
| --- | --- | --- |
| Home page, shell, navigation, footer, announcement popup | `src/app/page.tsx`, `src/components/app-shell.tsx`, `src/components/navbar.tsx`, `src/components/site-footer.tsx`, `src/components/announcement-popup.tsx` | `src/lib/site-config.ts`, `src/app/api/site-config/route.ts`, `src/app/api/announcements/route.ts` |
| Create center tabs | `src/app/create/page.tsx` | `src/components/create/*` |
| Text/image generation | `src/components/create/text-to-image.tsx`, `src/components/create/image-to-image.tsx` | `src/app/api/generation-jobs/route.ts`, `src/app/api/generate/image/route.ts`, `src/lib/generation-job-*` |
| Video generation | `src/components/create/text-to-video.tsx`, `src/components/create/image-to-video.tsx` | `src/app/api/generate/video/route.ts` |
| Reverse prompt | `src/components/create/reverse-prompt-panel.tsx` | `src/app/api/generate/reverse-prompt/route.ts`, `src/app/api/generate/suggest-prompt/route.ts` |
| Model/provider visibility | `src/lib/model-config.ts`, `src/lib/model-config-types.ts`, `src/lib/server-api-config.ts` | `src/app/api/model-config/route.ts`, `src/app/api/admin/system-apis/route.ts`, `src/app/api/admin/providers/route.ts`, `src/app/api/user-api-keys/route.ts` |
| User auth/login/register/profile | `src/lib/session-auth.ts`, `src/lib/auth-store.ts` | `src/app/api/auth/*`, `src/app/api/profile/*` |
| Admin console | `src/app/console/page.tsx`, `src/app/console/dashboard/page.tsx`, `src/modules/console/pages/*` | `src/components/admin/*`, `src/app/api/admin/*` |
| Canvas | `src/app/canvas/page.tsx`, `src/components/canvas/infinite-canvas-workspace.tsx`, `src/components/canvas/react-flow-canvas.tsx` | `src/lib/canvas-store.ts`, `src/lib/canvas-types.ts`, `src/app/api/canvas/projects/*` |
| Gallery and creation history | `src/app/gallery/page.tsx`, `src/app/profile/page.tsx`, `src/components/profile/creation-history-tab.tsx` | `src/lib/creation-history-store.ts`, `src/app/api/gallery/*`, `src/app/api/creation-history/route.ts` |
| Local files/downloads | `src/lib/local-storage.ts`, `src/app/api/local-storage/[...path]/route.ts` | `src/app/api/download/route.ts` |
| Email and policy pages | `src/lib/email-service.ts`, `src/components/site-policy-page.tsx` | `src/app/api/email/*`, `src/app/about/page.tsx`, `src/app/terms/page.tsx`, `src/app/privacy/page.tsx`, `src/app/help/page.tsx` |
| Upgrade/deploy/backup | `scripts/*`, `ecosystem.config.cjs` | `src/app/api/admin/upgrade/route.ts`, `src/components/admin/system-upgrade-tab.tsx` |
## Current Known Source Warning
At the time this document was created, the remote source imports `@/lib/model-display` from:
- `src/components/create/text-to-image.tsx`
- `src/components/create/image-to-image.tsx`
But `src/lib/model-display.ts` is not present after resetting to `origin/main`. If `pnpm run ts-check` fails on this import, treat it as a pre-existing source-state issue unless your task is specifically to repair it.
The documentation commit also attempted `corepack pnpm run ts-check`. It failed before any source edits with:
- missing module/type resolution for `ag-psd`
- missing module/type resolution for `@xyflow/react`
- missing `@/lib/model-display`
- canvas callback implicit-`any` errors in `src/components/canvas/react-flow-canvas.tsx`
Before treating `ag-psd` or `@xyflow/react` as source bugs, run `corepack pnpm install --frozen-lockfile` in a clean environment; those may be local dependency-install state. The missing `@/lib/model-display` file is a source-tree issue at this audited commit.
## Required Change Discipline
- Do not bypass auth helpers. Use `getAuthenticatedUser`, `getAuthenticatedUserId`, `requireAdminUser`, or `requireAdmin`.
- Do not write raw API keys to responses or logs. Use encryption helpers in `src/lib/server-crypto.ts` and safe mapping functions.
- Do not create ad hoc storage paths. Use `src/lib/local-storage.ts` and preserve path traversal checks.
- Do not create a second generation flow without checking `src/lib/generation-job-client.ts`, `src/lib/generation-job-runner.ts`, and `src/lib/generation-job-worker.ts`.
- Do not change admin upgrade behavior without checking both `src/app/api/admin/upgrade/route.ts` and `scripts/admin-upgrade-runner.mjs`.
- Do not change public content rendering without checking both backend persistence (`site-config`, `announcements`) and frontend consumers (`site-config-sync`, policy pages, footer, popup).
## Documentation Maintenance Rule
Any PR/commit that changes one of these areas must update the matching documentation:
- New or changed route: update `docs/codex-miaojing/api-reference.md`.
- Moved, renamed, or newly important code path: update `docs/codex-miaojing/feature-code-index.md`.
- Newly discovered regression pattern or repeat bug: update `docs/codex-miaojing/bug-location-guide.md`.
- New subsystem, persistence model, deployment path, or runtime boundary: update `docs/codex-miaojing/architecture.md`.

View File

@@ -0,0 +1,34 @@
# MiaoJing Codex Developer Index
Last source audit: 2026-05-12, based on git commit `8ee86a9`.
This folder contains the permanent Codex routing documents for MiaoJing development. They are intentionally source-control tracked so every future agent can start from the same map.
## Documents
| Document | Purpose |
| --- | --- |
| `feature-code-index.md` | Feature-to-file map for UI, workflows, stores, services, scripts, and database code. Use this first for implementation work. |
| `bug-location-guide.md` | Symptom-to-code diagnostic manual. Use this first for bug reports and regressions. |
| `api-reference.md` | Route Handler reference for `/api/**`: method, auth, payload, response, storage side effects. |
| `architecture.md` | System architecture, runtime boundaries, data flow, persistence, deployment, and risk points. |
## Required Workflow For Codex Agents
1. Read `AGENTS.md` and `CODEX_MIAOJING_MEMORY.md` at repo root.
2. Read the document in this folder that matches the task.
3. Use direct file reads or `rg` only after choosing likely files from the index.
4. Update these docs when code changes invalidate them.
## Quick Commands
```bash
pnpm run ts-check
pnpm run build
pnpm run lint
pnpm run check:boundaries
pnpm run pm2:restart
```
Use `pnpm`; the project rejects other package managers through `preinstall`.

View File

@@ -0,0 +1,152 @@
# API Reference
Last source audit: 2026-05-12, based on git commit `8ee86a9`.
All routes are Next.js App Router route handlers under `src/app/api/**/route.ts`.
## Auth Conventions
- Bearer token: `Authorization: Bearer <token>`.
- Token creation and verification: `src/lib/session-auth.ts`.
- Authenticated user helpers:
- `getAuthenticatedUser(request)`
- `getAuthenticatedUserId(request)`
- `requireAdminUser(request)`
- `requireAdmin(request)` from `src/lib/admin-auth.ts`
- Internal generation requests use header `x-miaojing-generation-internal`, generated by `src/lib/server-api-config.ts`.
## Response Conventions
- Success responses are JSON unless the route explicitly streams/downloads a file.
- Error responses usually use `{ "error": "message" }` with an HTTP status.
- Admin-only routes return 401 when not logged in and 403 when role is not `admin` or `enterprise_admin`.
## Public/System Routes
| Method | Path | Auth | Source | Purpose |
| --- | --- | --- | --- | --- |
| GET | `/api/health` | Public | `src/app/api/health/route.ts` | Health check. |
| GET | `/api/site-stats` | Public | `src/app/api/site-stats/route.ts` | Read total visits. |
| POST | `/api/site-stats` | Public | `src/app/api/site-stats/route.ts` | Increment visits. |
| GET | `/api/site-config` | Public | `src/app/api/site-config/route.ts` | Read site config, policy Markdown, filing, membership flag. |
| PUT | `/api/site-config` | Admin | `src/app/api/site-config/route.ts` | Update site config and upload logo/favicon data URLs. |
| GET | `/api/announcements` | Public | `src/app/api/announcements/route.ts` | List announcements. |
| POST | `/api/announcements` | Admin | `src/app/api/announcements/route.ts` | Create announcement. Body: `title`, `content`, `startDate`, `endDate`, `enabled`. |
| PUT | `/api/announcements` | Admin | `src/app/api/announcements/route.ts` | Update announcement. Body includes `id` and changed fields. |
| DELETE | `/api/announcements?id=...` | Admin | `src/app/api/announcements/route.ts` | Delete announcement. |
| GET | `/api/model-config` | Public | `src/app/api/model-config/route.ts` | Read managed provider/model configuration for clients. |
| GET | `/api/local-storage/[...path]` | Public by URL | `src/app/api/local-storage/[...path]/route.ts` | Serve local storage object by key. |
| GET | `/api/download?url=...&filename=...` | Public by URL | `src/app/api/download/route.ts` | Download proxy for remote, same-origin, and local-storage URLs. |
## Auth And Account Routes
| Method | Path | Auth | Source | Request | Response |
| --- | --- | --- | --- | --- | --- |
| POST | `/api/auth/login` | Public | `src/app/api/auth/login/route.ts` | `account` or `email` or `phone`, `password`, optional `adminOnly` | User profile data and session token. |
| POST | `/api/auth/register` | Public | `src/app/api/auth/register/route.ts` | `email`, `password`, `nickname`, `phone`, `inviteCode`, `emailCode`, `acceptedTerms` | Created profile/session flow. |
| GET | `/api/auth/admin-exists` | Public | `src/app/api/auth/admin-exists/route.ts` | None | Whether an admin profile exists. |
| POST | `/api/auth/test-api` | Public/auth context depends caller | `src/app/api/auth/test-api/route.ts` | Provider/API config | Tests upstream API. |
| POST | `/api/auth/fetch-models` | Public/auth context depends caller | `src/app/api/auth/fetch-models/route.ts` | Endpoint/API key | Fetch model list from provider. |
| GET | `/api/profile` | User | `src/app/api/profile/route.ts` | None | `{ profile }`. |
| PUT | `/api/profile` | User | `src/app/api/profile/route.ts` | `email`, `nickname`, `phone`, `avatarUrl`, password fields | Updated profile. |
| PUT | `/api/profile/theme` | User | `src/app/api/profile/theme/route.ts` | `theme` | `{ success, preferred_theme }`. |
| GET | `/api/user-api-keys` | User | `src/app/api/user-api-keys/route.ts` | None | `{ keys }`, with previews only. |
| POST | `/api/user-api-keys` | User | `src/app/api/user-api-keys/route.ts` | Single key or `{ keys: [...] }`; fields `provider`, `supplierName`, `apiUrl`, `modelName`, `apiKey`, `type`, `isActive` | Saved keys. |
| PUT | `/api/user-api-keys` | User | `src/app/api/user-api-keys/route.ts` | Same as POST | Saved keys. |
| DELETE | `/api/user-api-keys?id=...` | User | `src/app/api/user-api-keys/route.ts` | Query `id` | `{ success: true }`. |
## Email Routes
| Method | Path | Auth | Source | Purpose |
| --- | --- | --- | --- | --- |
| POST | `/api/email/send-register-code` | Public | `src/app/api/email/send-register-code/route.ts` | Send registration verification code. |
| POST | `/api/email/send-reset-code` | Public | `src/app/api/email/send-reset-code/route.ts` | Send password reset code. |
| POST | `/api/email/reset-password` | Public | `src/app/api/email/reset-password/route.ts` | Reset password with verification code. |
| POST | `/api/email/send-profile-code` | User | `src/app/api/email/send-profile-code/route.ts` | Send profile email-binding code. |
| POST | `/api/email/verify-profile` | User | `src/app/api/email/verify-profile/route.ts` | Verify profile email code. |
| POST | `/api/email/send-notification` | Internal/admin-oriented | `src/app/api/email/send-notification/route.ts` | Send notification email. |
## Generation Routes
| Method | Path | Auth | Source | Request | Response/Side Effects |
| --- | --- | --- | --- | --- | --- |
| POST | `/api/generation-jobs` | User | `src/app/api/generation-jobs/route.ts` | `{ type: "image"|"video", payload: {...} }` | Inserts `generation_jobs`, starts worker, returns `202` with `jobId`, `status`, `estimateSeconds`, `eta`. |
| GET | `/api/generation-jobs/[id]` | User/admin | `src/app/api/generation-jobs/[id]/route.ts` | Path UUID | Job status/result/error/progress. Owner or admin only. |
| POST | `/api/generate/image` | Trusted internal or resolved user/system API context | `src/app/api/generate/image/route.ts` | Image generation payload; supports prompt, negative prompt, reference images, model/system/custom API config, aspect/size/resolution/count/quality. | Calls SDK or OpenAI/New API-compatible endpoint, persists result to local storage, updates job progress when headers include job ID. |
| POST | `/api/generate/video` | Trusted internal or resolved user/system API context | `src/app/api/generate/video/route.ts` | Video generation payload; supports prompt, reference image, model/system/custom API config, ratio/duration/fps-like params. | Calls SDK or custom endpoint, persists media to local storage. |
| POST | `/api/generate/reverse-prompt` | Uses supplied/resolved API config | `src/app/api/generate/reverse-prompt/route.ts` | `image`, `outputMode`, `language`, optional `customApiConfig`/system/custom IDs | Returns prompt fields and may persist reference image. |
| POST | `/api/generate/suggest-prompt` | Uses supplied/resolved API config | `src/app/api/generate/suggest-prompt/route.ts` | `prompt`, optional `customApiConfig`, `systemPrefix` | Returns optimized `prompt` and optional `negativePrompt`. |
Important generation helpers:
- `src/lib/generation-job-client.ts`: frontend create/poll helper.
- `src/lib/generation-job-worker.ts`: queued job processor.
- `src/lib/generation-job-runner.ts`: internal call into generate routes.
- `src/lib/generation-job-estimates.ts`: ETA/progress schema and estimates.
- `src/lib/server-api-config.ts`: resolves `customApiKeyId` and `systemApiId`.
- `src/lib/custom-api-fetch.ts`: upstream request/retry/error parsing.
## Creation History And Gallery
| Method | Path | Auth | Source | Request | Response/Side Effects |
| --- | --- | --- | --- | --- | --- |
| GET | `/api/creation-history` | User | `src/app/api/creation-history/route.ts` | None | Latest 300 completed user works as `records`. |
| POST | `/api/creation-history` | User | `src/app/api/creation-history/route.ts` | Single record or `{ records: [...] }` | Inserts/deduplicates completed works into `works`. |
| DELETE | `/api/creation-history?id=...` | User | `src/app/api/creation-history/route.ts` | Optional `id`; omit to delete all user history | Deletes user's private history rows. |
| GET | `/api/gallery` | Public | `src/app/api/gallery/route.ts` | Query `type=image|video`, `limit`, `offset`, `sort=newest|popular`, `q`/`search` | Public completed works and total. |
| DELETE | `/api/gallery` | Admin | `src/app/api/gallery/route.ts` | Query `id` or body `{ ids: [...] }` | Unpublishes up to 100 works by setting `is_public=false`. |
| POST | `/api/gallery/publish` | User | `src/app/api/gallery/publish/route.ts` | Work metadata, `resultUrl`, optional thumbnail/reference/model fields | Copies media into gallery folders and inserts public completed work. |
## Canvas Routes
| Method | Path | Auth | Source | Request | Response |
| --- | --- | --- | --- | --- | --- |
| GET | `/api/canvas/projects` | User | `src/app/api/canvas/projects/route.ts` | None | `{ projects }`. |
| POST | `/api/canvas/projects` | User | `src/app/api/canvas/projects/route.ts` | Optional `title` | Created `{ project }`. |
| GET | `/api/canvas/projects/[id]` | User | `src/app/api/canvas/projects/[id]/route.ts` | Project ID | `{ project }` or 404. |
| PUT | `/api/canvas/projects/[id]` | User | `src/app/api/canvas/projects/[id]/route.ts` | `title`, `state` | Normalizes state and returns `{ project }`. |
| DELETE | `/api/canvas/projects/[id]` | User | `src/app/api/canvas/projects/[id]/route.ts` | Project ID | `{ ok: true }`. |
## Admin Routes
All routes in this section require admin unless noted.
| Method | Path | Source | Purpose |
| --- | --- | --- | --- |
| GET | `/api/admin/dashboard` | `src/app/api/admin/dashboard/route.ts` | Console dashboard aggregate stats and recent activity. |
| GET | `/api/admin/stats` | `src/app/api/admin/stats/route.ts` | Additional admin stats. |
| GET/PUT/DELETE | `/api/admin/users` | `src/app/api/admin/users/route.ts` | List/update/delete users. |
| POST | `/api/admin/clear-users` | `src/app/api/admin/clear-users/route.ts` | Dangerous user cleanup controlled by env switch. |
| GET/POST/PUT | `/api/admin/orders` | `src/app/api/admin/orders/route.ts` | List/create/update orders. |
| GET/PUT | `/api/admin/payment-methods` | `src/app/api/admin/payment-methods/route.ts` | Payment config. |
| GET/POST/PUT/DELETE | `/api/admin/providers` | `src/app/api/admin/providers/route.ts` | Provider registry CRUD. GET is currently not guarded in source; mutations require admin. |
| GET/POST/PUT/DELETE | `/api/admin/system-apis` | `src/app/api/admin/system-apis/route.ts` | System API config CRUD with encrypted keys and pricing metadata. |
| GET/POST/PUT/DELETE | `/api/admin/model-recommendations` | `src/app/api/admin/model-recommendations/route.ts` | Managed model recommendations. |
| GET/DELETE | `/api/admin/generation-jobs` | `src/app/api/admin/generation-jobs/route.ts` | Admin task listing and deletion. |
| GET | `/api/admin/data-export` | `src/app/api/admin/data-export/route.ts` | Export business data. |
| POST | `/api/admin/data-import` | `src/app/api/admin/data-import/route.ts` | Import business data. |
| GET/PUT/POST | `/api/admin/email-settings` | `src/app/api/admin/email-settings/route.ts` | Read/update/test email settings. |
| GET | `/api/admin/email-recipients` | `src/app/api/admin/email-recipients/route.ts` | Email recipient list. |
| POST | `/api/admin/send-email` | `src/app/api/admin/send-email/route.ts` | Send admin email. |
| GET/POST | `/api/admin/upgrade` | `src/app/api/admin/upgrade/route.ts` | Read upgrade runtime/status/history; upload/start dry run or upgrade package. |
## Persistence Tables Mentioned By APIs
Primary SQL tables touched directly in API routes include:
- `profiles`
- `auth.users`
- `works`
- `credit_transactions`
- `orders`
- `user_api_keys`
- `site_config`
- `site_stats`
- `announcements`
- `generation_jobs`
- `api_providers`
- `system_api_configs`
- `platform_logs`
`src/storage/database/shared/schema.ts` contains a Drizzle snapshot of core tables, while several runtime APIs add compatibility columns/tables with `CREATE TABLE IF NOT EXISTS` or `ALTER TABLE ... ADD COLUMN IF NOT EXISTS`.

View File

@@ -0,0 +1,250 @@
# Architecture
Last source audit: 2026-05-12, based on git commit `8ee86a9`.
## System Overview
MiaoJing is a self-hostable AI multimodal creation platform built on:
- Next.js 16 App Router
- React 19
- TypeScript
- PostgreSQL via `pg`
- Local disk storage through `/api/local-storage/*`
- PM2 process management
- Optional upstream AI providers through SDK, custom API keys, and admin system API configs
The repository contains frontend pages, API route handlers, business services, database helpers, storage helpers, deployment scripts, and PM2 config in one app.
## Runtime Shape
```text
Browser
|
| HTTP
v
Next.js App Router
|
+-- src/app pages
+-- src/app/api route handlers
|
+-- src/components UI and workflow components
|
+-- src/lib business logic and stores
|
+-- src/storage database clients
|
+-- local disk storage via src/lib/local-storage.ts
|
+-- PostgreSQL via src/storage/database/local-db.ts
|
+-- Upstream AI providers via SDK/custom fetch
```
Production is controlled by `ecosystem.config.cjs` and the scripts under `scripts/`. Always verify PM2 cwd and runtime environment before editing a live server.
## Directory Boundaries
| Directory | Responsibility |
| --- | --- |
| `src/app` | Next.js pages, layouts, and API route handlers. |
| `src/components` | Reusable UI and product workflow components. |
| `src/components/ui` | Radix/shadcn-style primitives. Keep generic. |
| `src/components/create` | Create center panels and shared generation UI. |
| `src/components/admin` | Admin console tab components. |
| `src/components/canvas` | Infinite canvas UI and rendering. |
| `src/components/profile` | Profile page tabs and API key manager. |
| `src/lib` | Business logic, stores, model config, auth, storage, email, generation jobs, provider resolution. |
| `src/modules` | Thin module export and console page wrappers. |
| `src/storage` | Database client/schema compatibility. |
| `scripts` | Build, deploy, backup, restore, DB patch, admin upgrade runner. |
| `public` | Public static assets. |
| `assets` | Project-owned source assets. |
## Frontend Architecture
The app is route-driven through `src/app`:
- Public shell: `src/app/layout.tsx` and `src/components/app-shell.tsx`.
- Navigation and global UI: navbar, footer, announcement popup, site config sync, visit tracker.
- Product workflows:
- Create center: `src/app/create/page.tsx` plus `src/components/create/*`.
- Gallery: `src/app/gallery/page.tsx`.
- Profile: `src/app/profile/page.tsx` plus `src/components/profile/*`.
- Canvas: `src/app/canvas/page.tsx` plus `src/components/canvas/*`.
- Admin console: `src/app/console/*`, `src/modules/console/pages/*`, `src/components/admin/*`.
Client stores in `src/lib/*-store.ts` mediate API calls and local UI state. When fixing a UI persistence bug, inspect both the component and the matching store/API route.
## API Architecture
All APIs are route handlers in `src/app/api`.
Major groups:
- `auth/*`: login, register, admin existence, provider API testing.
- `profile/*`: user profile and theme.
- `user-api-keys`: user-owned custom API credentials.
- `model-config`: public model/provider config.
- `generate/*`: direct generation, reverse prompt, prompt suggestion.
- `generation-jobs/*`: queued generation job creation/status.
- `creation-history`: user works/history.
- `gallery/*`: public gallery and publishing.
- `canvas/projects/*`: canvas persistence.
- `admin/*`: console dashboard, users, providers, system APIs, orders, payment, upgrade, data import/export, email settings.
- `site-config`, `site-stats`, `announcements`: public site content and counters.
- `local-storage/*`, `download`: file serving and download proxy.
Auth is not implicit. Each route must call the correct helper:
- User route: `getAuthenticatedUserId` or `getAuthenticatedUser`.
- Admin route: `requireAdmin` or `requireAdminUser`.
- Internal generation route: `isTrustedInternalGenerationRequest`.
## Generation Flow
```text
Create panel
-> src/lib/generation-job-client.ts
-> POST /api/generation-jobs
-> generation_jobs row inserted
-> src/lib/generation-job-worker.ts
-> src/lib/generation-job-runner.ts
-> POST /api/generate/image or /api/generate/video
-> SDK or custom/system API upstream call
-> src/lib/local-storage.ts persists result
-> generation_jobs updated with result/error/progress
-> client polls GET /api/generation-jobs/[id]
-> history/gallery persistence via works APIs
```
Key source files:
- `src/components/create/text-to-image.tsx`
- `src/components/create/image-to-image.tsx`
- `src/components/create/text-to-video.tsx`
- `src/components/create/image-to-video.tsx`
- `src/lib/generation-job-client.ts`
- `src/app/api/generation-jobs/route.ts`
- `src/lib/generation-job-worker.ts`
- `src/lib/generation-job-runner.ts`
- `src/app/api/generate/image/route.ts`
- `src/app/api/generate/video/route.ts`
Do not bypass the job flow unless intentionally implementing synchronous/internal-only behavior.
## Provider Resolution
There are three provider sources:
1. Built-in model config: `src/lib/model-config.ts`.
2. User custom API keys: `src/app/api/user-api-keys/route.ts`, `src/lib/custom-api-store.ts`.
3. Admin system APIs: `src/app/api/admin/system-apis/route.ts`, `src/lib/server-api-config.ts`.
`src/lib/server-api-config.ts` resolves:
- `customApiKeyId` into a user-owned decrypted API config.
- `systemApiId` into an active admin-managed decrypted API config.
- direct `apiKey` passthrough for legacy/custom callers.
Secrets must be encrypted at rest with `src/lib/server-crypto.ts` and never returned in API responses.
## Storage Architecture
`src/lib/local-storage.ts` is the storage abstraction.
- Base path: `LOCAL_STORAGE_DIR`, or repo-local `local-storage` if unset.
- Public URL shape: `/api/local-storage/<key>`.
- File serving route: `src/app/api/local-storage/[...path]/route.ts`.
- Download route: `src/app/api/download/route.ts`.
- Storage key validation prevents traversal through `normalizeKey`, `path.resolve`, and `..` checks.
Generation routes persist generated media into storage. Gallery publish copies referenced result URLs into gallery folders when possible.
## Database Architecture
Main DB entry:
- `src/storage/database/local-db.ts`: PostgreSQL pool from `LOCAL_DB_URL`.
Schema sources:
- `src/storage/database/shared/schema.ts`: Drizzle snapshot for core tables.
- `scripts/init-database.sql`: full initialization.
- Runtime routes/services also ensure compatible columns/tables with `ALTER TABLE ... ADD COLUMN IF NOT EXISTS`.
Core data areas:
- Users: `auth.users`, `profiles`.
- Works: `works`.
- Credits: `credit_transactions`.
- Orders: `orders`.
- API credentials: `user_api_keys`, `system_api_configs`, `api_providers`.
- Site content: `site_config`, `announcements`, `site_stats`.
- Jobs/logs: `generation_jobs`, `platform_logs`.
- Canvas: handled through `src/lib/canvas-store.ts` and canvas project routes.
Because several routes self-migrate compatibility columns, DB bugs often require checking both SQL scripts and route-level `ensure...Schema` functions.
## Admin Console Architecture
Admin console UI is split across:
- Page/wrapper: `src/app/console/page.tsx`, `src/app/console/dashboard/page.tsx`.
- Module pages: `src/modules/console/pages/console-login-page.tsx`, `src/modules/console/pages/console-dashboard-page.tsx`.
- Tabs: `src/components/admin/*`.
- APIs: `src/app/api/admin/*`.
Admin auth flows through the same login endpoint with admin role checks. API routes should use `requireAdmin`.
## Upgrade And Deployment Architecture
Scripts:
- `scripts/build.sh`: builds Next.js and server.
- `scripts/start.sh`: production start path.
- `scripts/deploy-or-upgrade.sh`: deployment/upgrade automation.
- `scripts/admin-upgrade-runner.mjs`: package extraction/build/restart runner.
- `scripts/backup-create.sh`, `backup-list.sh`, `backup-restore.sh`: backups.
- `scripts/apply-database-patch.sh`: DB patch execution.
Runtime:
- `ecosystem.config.cjs` defines PM2 processes and environment roles.
- `src/server.ts` is the custom Node server entry.
- Admin upgrade API and UI:
- `src/app/api/admin/upgrade/route.ts`
- `src/components/admin/system-upgrade-tab.tsx`
When changing deploy/upgrade behavior, validate package limits, disk checks, backup creation, rollback paths, PM2 restart command, and health checks.
## Security Boundaries
- API key storage: encrypted in DB, preview-only responses.
- User auth: bearer session token from `src/lib/session-auth.ts`.
- Admin auth: role must be `admin` or `enterprise_admin`.
- Internal generation: protected by `x-miaojing-generation-internal`.
- Local file serving: must preserve storage key normalization and path traversal guards.
- Admin destructive actions: keep environment gates, admin checks, and limits.
## Verification Strategy
Use the narrowest useful check, then broaden as needed.
| Change Type | Minimum Verification |
| --- | --- |
| Docs only | Link/path sanity with `rg`, `git diff --check`. |
| TypeScript source | `pnpm run ts-check`. |
| API route | `pnpm run ts-check`, route smoke with `curl` where runtime exists. |
| UI workflow | `pnpm run ts-check`, `pnpm run build`, browser/manual or Playwright check if visual. |
| Generation path | `pnpm run ts-check`, `pnpm run build`, job create/poll route check, storage result check. |
| Deployment/upgrade | `pnpm run ts-check`, `pnpm run build`, package/upgrade dry run, PM2 reload, health checks. |
## Known Risk Points
- Some source files import `@/lib/model-display`, but `src/lib/model-display.ts` is absent at the audited commit. This can break `pnpm run ts-check` independent of documentation changes.
- The documentation commit attempted `corepack pnpm run ts-check` and the audited local baseline also reported missing `ag-psd` and `@xyflow/react` module/type resolution plus canvas implicit-`any` errors. Reinstall dependencies with `corepack pnpm install --frozen-lockfile` before diagnosing dependency-resolution errors as source bugs.
- Generation routes are large and mix upstream adapter logic, persistence, and job progress. Prefer small surgical edits.
- Several DB schema changes are applied lazily at runtime; verify migration behavior on fresh and upgraded DBs.
- Production/dev servers can have different checkout paths. Always verify PM2 cwd before live edits.
- Admin upgrade touches file system, build, backup, disk, and PM2 state. Treat it as high-risk.

View File

@@ -0,0 +1,116 @@
# Bug Location Guide
Last source audit: 2026-05-12, based on git commit `8ee86a9`.
Use this guide when the user reports behavior. Start from the symptom row, inspect the listed files, then verify with the current runtime.
## First Five Checks
1. Confirm whether the bug is frontend-only, API-only, persistence, generation worker, or deployment/runtime.
2. Read the task row below and open the smallest likely file set.
3. Search for the exact UI text, endpoint path, DB table, or log prefix with `rg`.
4. Check auth state and request payload before changing business logic.
5. After a fix, run the narrowest useful verification first, then `pnpm run ts-check` and `pnpm run build` when source changes affect TypeScript/runtime.
## Auth, Login, Profile
| Symptom | Check Files | What To Verify |
| --- | --- | --- |
| User cannot log in | `src/app/auth/login/page.tsx`, `src/lib/auth-store.ts`, `src/app/api/auth/login/route.ts`, `src/lib/session-auth.ts` | Request body fields (`account`, `email`, `phone`, `password`), password hash verification, bearer token storage, inactive profile. |
| Admin console opens without login or redirects incorrectly | `src/app/console/page.tsx`, `src/modules/console/pages/console-login-page.tsx`, `src/modules/console/pages/console-dashboard-page.tsx`, `src/app/api/auth/login/route.ts` | `adminOnly` behavior, admin role check, route redirect logic. |
| Registration fails | `src/app/auth/register/page.tsx`, `src/app/api/auth/register/route.ts`, `src/lib/email-service.ts` | `acceptedTerms`, email code, password strength, invite code, duplicate profile. |
| Profile changes disappear after refresh | `src/app/profile/page.tsx`, `src/app/api/profile/route.ts`, `src/lib/auth-store.ts` | PUT writes both `profiles` and `auth.users` where needed; client refreshes returned profile. |
| Theme does not persist | `src/components/account-theme-sync.tsx`, `src/app/api/profile/theme/route.ts`, `src/lib/profile-preferences.ts` | `preferred_theme` schema, token auth, theme normalization. |
## Site Config, Footer, Policies, Announcements
| Symptom | Check Files | What To Verify |
| --- | --- | --- |
| Footer content missing or not Markdown-rendered | `src/components/site-footer.tsx`, `src/components/site-policy-page.tsx`, `src/lib/site-config.ts`, `src/app/api/site-config/route.ts` | Config response fields, Markdown renderer, fallback defaults, PUT persistence. |
| Policy pages start mid-page after navigation | `src/components/site-policy-page.tsx`, `src/app/about/page.tsx`, `src/app/terms/page.tsx`, `src/app/privacy/page.tsx`, `src/app/help/page.tsx` | Scroll reset behavior and shared policy page wrapper. |
| Site name/logo/favicon not updating | `src/components/site-config-sync.tsx`, `src/components/site-brand.tsx`, `src/app/api/site-config/route.ts`, `src/lib/local-storage.ts` | `site_config` row, base64 image save, generated `/api/local-storage/*` URL. |
| Announcement not popping up | `src/components/announcement-popup.tsx`, `src/app/api/announcements/route.ts`, `src/components/app-shell.tsx` | App shell includes popup, active date range, local/session dismissal behavior, GET payload shape. |
| Announcement admin edit fails | `src/components/admin/announcement-tab.tsx`, `src/app/api/announcements/route.ts` | Admin token, required fields, `starts_at`/`expires_at` compatibility. |
## Creation And Generation
| Symptom | Check Files | What To Verify |
| --- | --- | --- |
| Create button does nothing | `src/components/create/text-to-image.tsx`, `src/components/create/image-to-image.tsx`, `src/components/create/text-to-video.tsx`, `src/components/create/image-to-video.tsx`, `src/lib/generation-job-client.ts` | Client validation, auth token, `/api/generation-jobs` POST response, UI disabled/loading state. |
| Job remains queued | `src/app/api/generation-jobs/route.ts`, `src/lib/generation-job-worker.ts`, `src/lib/generation-job-runner.ts` | `processNextGenerationJob()` invoked, stale job handling, DB locks/status, internal base URL. |
| Job remains running forever | `src/app/api/generation-jobs/[id]/route.ts`, `src/lib/generation-job-worker.ts`, `src/lib/generation-job-estimates.ts` | Stale timeout updates, `updated_at`, worker exceptions swallowed into error field. |
| Image generation returns upstream error | `src/app/api/generate/image/route.ts`, `src/lib/custom-api-fetch.ts`, `src/lib/server-api-config.ts` | Resolved custom/system API credentials, endpoint URL, New API normalization, timeout, stream/progress parser. |
| Video generation returns upstream error | `src/app/api/generate/video/route.ts`, `src/lib/custom-api-fetch.ts`, `src/lib/server-api-config.ts` | Reference image upload/compression, endpoint URL, response parser, persistence timeout. |
| Wrong image size or aspect ratio | `src/lib/model-config.ts`, `src/app/api/generate/image/route.ts` | `resolveImageSize`, `resolveCustomApiImageSize`, New API/DALL-E size normalization, prompt aspect hint. |
| Reference image upload too large or fails | `src/components/create/image-to-image.tsx`, `src/components/create/image-to-video.tsx`, `src/lib/browser-image-compression.ts`, `src/lib/server-image-compression.ts`, `src/app/api/generate/image/route.ts`, `src/app/api/generate/video/route.ts` | Browser compression, `MAX_UPSTREAM_REFERENCE_IMAGE_BYTES`, data URL conversion. |
| Generated result previews but does not persist | `src/app/api/generate/image/route.ts`, `src/app/api/generate/video/route.ts`, `src/lib/local-storage.ts`, `src/app/api/creation-history/route.ts` | Media copied to local storage, presigned URL returned, history POST called. |
| Fullscreen/preview/download broken | `src/components/fullscreen-preview.tsx`, `src/components/lightbox.tsx`, `src/components/creation-detail-dialog.tsx`, `src/app/api/download/route.ts` | Dialog state, URL type, download proxy supports local/remote URL. |
| Reverse prompt option missing | `src/components/create/reverse-prompt-panel.tsx`, `src/app/api/generate/reverse-prompt/route.ts` | UI option list and server `outputMode` handling both updated, app rebuilt/restarted if deployed. |
| Prompt optimization fails | `src/app/api/generate/suggest-prompt/route.ts`, `src/lib/server-api-config.ts`, `src/lib/custom-api-fetch.ts` | Text-capable system/custom API, chat response shape, JSON parsing fallback. |
## Models, Providers, API Keys
| Symptom | Check Files | What To Verify |
| --- | --- | --- |
| Model list empty in create/profile | `src/app/api/model-config/route.ts`, `src/lib/model-config.ts`, `src/lib/managed-model-store.ts`, `src/lib/custom-api-store.ts` | Public model config response, admin recommendations, local client store mapping. |
| System API saved but not used | `src/app/api/admin/system-apis/route.ts`, `src/lib/server-api-config.ts`, `src/app/api/generate/image/route.ts`, `src/app/api/generate/video/route.ts` | `systemApiId` in request payload, active config, decrypted key, type matches image/video/text. |
| User custom API saved but not used | `src/app/api/user-api-keys/route.ts`, `src/lib/custom-api-store.ts`, `src/lib/server-api-config.ts` | `customApiKeyId`, owner auth, encrypted key exists, `is_active`. |
| New API image endpoint incompatible | `src/app/api/generate/image/route.ts`, `src/lib/custom-api-fetch.ts` | Provider is `newapi`/`new api`, endpoint normalization, model-specific size/count/quality handling. |
| API key leaked in UI/API | `src/app/api/user-api-keys/route.ts`, `src/app/api/admin/system-apis/route.ts`, `src/lib/server-crypto.ts`, `src/lib/server-api-config.ts` | Response mapping must return preview/empty key only. |
## Gallery And Creation History
| Symptom | Check Files | What To Verify |
| --- | --- | --- |
| History missing after generation | `src/lib/creation-history-store.ts`, `src/app/api/creation-history/route.ts`, create panel component | History POST, `works` insert, URL not data URL except reverse prompt placeholder. |
| Published work not in gallery | `src/lib/creation-history-store.ts`, `src/app/api/gallery/publish/route.ts`, `src/app/api/gallery/route.ts`, `src/app/gallery/page.tsx` | `is_public = true`, `status = completed`, media copied to gallery folder, filters. |
| Gallery delete does not remove public item | `src/app/api/gallery/route.ts`, admin UI route using it | DELETE unpublishes by setting `is_public = false`, not hard delete. |
| Search/filter/sort wrong | `src/app/api/gallery/route.ts`, `src/app/gallery/page.tsx` | Query params `type`, `limit`, `offset`, `sort`, `q/search`; SQL where/order. |
## Canvas
| Symptom | Check Files | What To Verify |
| --- | --- | --- |
| Canvas projects not listed | `src/app/canvas/page.tsx`, `src/components/canvas/infinite-canvas-workspace.tsx`, `src/app/api/canvas/projects/route.ts`, `src/lib/canvas-store.ts` | Auth token, `listCanvasProjects(userId)`, DB/local persistence assumptions. |
| Canvas save drops nodes/groups/connections | `src/lib/canvas-store.ts`, `src/lib/canvas-types.ts`, `src/components/canvas/infinite-canvas-workspace.tsx` | `normalizeCanvasState` preserves all state fields and types. |
| Connection lines missing/duplicated/ugly | `src/components/canvas/react-flow-canvas.tsx`, `src/lib/canvas-types.ts` | Single render source, no duplicate React Flow edges plus overlay lines unless intentional. |
| Canvas image proportions wrong | `src/lib/canvas-types.ts`, `src/components/canvas/react-flow-canvas.tsx`, `src/components/canvas/infinite-canvas-workspace.tsx` | Stored image dimensions and render sizing. |
## Admin Console And Ops
| Symptom | Check Files | What To Verify |
| --- | --- | --- |
| Dashboard stats wrong | `src/modules/console/pages/console-dashboard-page.tsx`, `src/app/api/admin/dashboard/route.ts`, `src/app/api/admin/stats/route.ts` | SQL source tables, safe query fallbacks, admin auth. |
| User management bug | `src/components/admin/user-management-tab.tsx`, `src/app/api/admin/users/route.ts` | Role/tier mapping, active flag, admin auth. |
| Order/payment bug | `src/components/admin/order-management-tab.tsx`, `src/components/admin/payment-tab.tsx`, `src/app/api/admin/orders/route.ts`, `src/app/api/admin/payment-methods/route.ts`, `src/lib/server-payment-config.ts` | Payment config encryption, order status, request shape. |
| Data import/export bug | `src/components/admin/data-management-tab.tsx`, `src/app/api/admin/data-export/route.ts`, `src/app/api/admin/data-import/route.ts` | JSON format, table coverage, admin auth. |
| Admin email send/settings bug | `src/components/admin/settings-tab.tsx`, `src/app/api/admin/email-settings/route.ts`, `src/app/api/admin/send-email/route.ts`, `src/lib/email-service.ts` | SMTP config, template rendering, MIME/body encoding. |
| Upgrade page stuck/fails | `src/components/admin/system-upgrade-tab.tsx`, `src/app/api/admin/upgrade/route.ts`, `scripts/admin-upgrade-runner.mjs` | State dir, package limits, disk checks, backup, PM2 restart command, stale status. |
| Platform logs missing | `src/components/admin/log-management-tab.tsx`, `src/lib/platform-logs.ts`, routes that call `writePlatformLog` | Runtime schema exists, log retention, API calls actually write logs. |
## Storage, Download, Files
| Symptom | Check Files | What To Verify |
| --- | --- | --- |
| `/api/local-storage/...` 404 | `src/app/api/local-storage/[...path]/route.ts`, `src/lib/local-storage.ts` | `LOCAL_STORAGE_DIR`, normalized key, file exists on disk. |
| Download says remote fetch failed | `src/app/api/download/route.ts`, `src/lib/remote-fetch.ts` | URL is http(s), same-origin, or local-storage; upstream reachable; timeout. |
| Path traversal/security concern | `src/lib/local-storage.ts`, `src/app/api/download/route.ts`, `src/app/api/local-storage/[...path]/route.ts` | Keep `normalizeKey`, `path.resolve`, and `..` guards. |
## Deployment And Build
| Symptom | Check Files | What To Verify |
| --- | --- | --- |
| Build or type check fails | `package.json`, `scripts/build.sh`, `next.config.ts`, failing source file, `CODEX_MIAOJING_MEMORY.md` | First run `corepack pnpm install --frozen-lockfile` if dependency modules are missing. Current audited baseline already recorded failures for missing `@/lib/model-display` and canvas type errors. Distinguish pre-existing source errors from your docs/change. |
| PM2 app not updated | `ecosystem.config.cjs`, `scripts/start.sh`, `scripts/deploy-or-upgrade.sh` | Process cwd, role ports, environment variables, `pm2 startOrReload ecosystem.config.cjs --update-env`. |
| Production uses different checkout | `ecosystem.config.cjs`, PM2 process env/cwd | Always verify PM2 cwd before editing production. |
| Upgrade package cleanup failed | `scripts/deploy-or-upgrade.sh`, `scripts/admin-upgrade-runner.mjs`, `src/app/api/admin/upgrade/route.ts` | Cleanup trap, backup paths, state dir, disk space guards. |
## Useful Search Patterns
```bash
rg -n "export async function (GET|POST|PUT|DELETE)" src/app/api
rg -n "writePlatformLog|console\\.error|console\\.warn" src
rg -n "generation_jobs|works|profiles|site_config|system_api_configs" src scripts *.sql
rg -n "localStorage|/api/local-storage|/api/download" src
rg -n "requireAdmin|getAuthenticatedUser|getAuthenticatedUserId" src/app/api src/lib
```

View File

@@ -0,0 +1,169 @@
# Feature Code Location Index
Last source audit: 2026-05-12, based on git commit `8ee86a9`.
Use this document to jump directly to code before broad searching.
## Global Application Shell
| Feature | Primary Files | Notes |
| --- | --- | --- |
| Root layout and providers | `src/app/layout.tsx`, `src/components/app-shell.tsx` | App shell wires navbar, site config sync, visit tracking, theme/account sync, and toaster. |
| Home page | `src/app/page.tsx` | Landing/dashboard-like public entry. Check site config dependencies when changing brand text. |
| Navbar | `src/components/navbar.tsx`, `src/components/site-brand.tsx` | Navigation, brand display, auth-aware links. |
| Footer | `src/components/site-footer.tsx` | Uses site config for policy/help/about links and filing text. |
| Announcement popup | `src/components/announcement-popup.tsx`, `src/app/api/announcements/route.ts` | Frontend popup behavior plus backend announcement CRUD. |
| Site config sync | `src/components/site-config-sync.tsx`, `src/lib/site-config.ts`, `src/app/api/site-config/route.ts` | Site name, tab title, logo, favicon, policy Markdown, filing, membership switch. |
| Visit tracking | `src/components/visit-tracker.tsx`, `src/app/api/site-stats/route.ts` | Public visit counter. |
## Public Pages
| Route | Primary Files | Supporting Files |
| --- | --- | --- |
| `/` | `src/app/page.tsx` | `src/components/app-shell.tsx` |
| `/create` | `src/app/create/page.tsx` | `src/components/create/*` |
| `/gallery` | `src/app/gallery/page.tsx` | `src/lib/creation-history-store.ts`, `src/app/api/gallery/route.ts` |
| `/profile` | `src/app/profile/page.tsx` | `src/components/profile/*`, `src/app/api/profile/route.ts` |
| `/canvas` | `src/app/canvas/page.tsx` | `src/components/canvas/*`, `src/lib/canvas-store.ts` |
| `/about` | `src/app/about/page.tsx` | `src/components/site-policy-page.tsx`, `src/lib/site-policy-defaults.ts` |
| `/terms` | `src/app/terms/page.tsx` | `src/components/site-policy-page.tsx` |
| `/privacy` | `src/app/privacy/page.tsx` | `src/components/site-policy-page.tsx` |
| `/help` | `src/app/help/page.tsx` | `src/components/site-policy-page.tsx` |
## Auth And User Account
| Feature | Primary Files | Notes |
| --- | --- | --- |
| Login UI | `src/app/auth/login/page.tsx` | Calls `/api/auth/login`. |
| Register UI | `src/app/auth/register/page.tsx`, `src/components/auth/registration-agreement-dialog.tsx` | Requires accepted terms and email code except admin invite path. |
| Auth store | `src/lib/auth-store.ts` | Client auth state and token persistence. |
| Session tokens | `src/lib/session-auth.ts` | HMAC token format, bearer parsing, admin checks. |
| Login API | `src/app/api/auth/login/route.ts` | Handles admin fallback and normal users. |
| Register API | `src/app/api/auth/register/route.ts` | Creates `auth.users`, `profiles`, initial credits. |
| Admin exists | `src/app/api/auth/admin-exists/route.ts` | Admin setup checks. |
| API test/model fetch | `src/app/api/auth/test-api/route.ts`, `src/app/api/auth/fetch-models/route.ts` | Used by provider/API configuration UI. |
| Profile API | `src/app/api/profile/route.ts`, `src/app/api/profile/theme/route.ts` | Profile edits, password/email/theme. |
## Creation Center
| Feature | Primary Files | Server/API Files |
| --- | --- | --- |
| Tab container | `src/app/create/page.tsx` | N/A |
| Text to image | `src/components/create/text-to-image.tsx` | `src/app/api/generation-jobs/route.ts`, `src/app/api/generate/image/route.ts` |
| Image to image | `src/components/create/image-to-image.tsx` | `src/app/api/generation-jobs/route.ts`, `src/app/api/generate/image/route.ts` |
| Text to video | `src/components/create/text-to-video.tsx` | `src/app/api/generation-jobs/route.ts`, `src/app/api/generate/video/route.ts` |
| Image to video | `src/components/create/image-to-video.tsx` | `src/app/api/generation-jobs/route.ts`, `src/app/api/generate/video/route.ts` |
| Reverse prompt | `src/components/create/reverse-prompt-panel.tsx` | `src/app/api/generate/reverse-prompt/route.ts`, `src/app/api/generate/suggest-prompt/route.ts` |
| Prompt textarea | `src/components/create/expandable-prompt-textarea.tsx` | Shared prompt input. |
| Style presets | `src/components/create/style-preset-selector.tsx`, `src/lib/model-config.ts` | Style preset selection and image params. |
| Loading/error panels | `src/components/create/generation-loading-panel.tsx`, `src/components/create/generation-error-panel.tsx` | Shared generation status UI. |
| Lightbox/fullscreen | `src/components/lightbox.tsx`, `src/components/fullscreen-preview.tsx`, `src/components/creation-detail-dialog.tsx` | Preview, copy, download, share. |
## Generation System
| Responsibility | Primary Files | Notes |
| --- | --- | --- |
| Client-side job polling | `src/lib/generation-job-client.ts` | Create/poll jobs from create panels. |
| Job creation API | `src/app/api/generation-jobs/route.ts` | Inserts `generation_jobs` and starts worker. |
| Job status API | `src/app/api/generation-jobs/[id]/route.ts` | Owner/admin visibility, stale running job handling. |
| Worker loop | `src/lib/generation-job-worker.ts` | Picks and processes queued jobs. |
| Internal runner | `src/lib/generation-job-runner.ts` | Calls `/api/generate/image` or `/api/generate/video` with internal headers. |
| ETA/progress | `src/lib/generation-job-estimates.ts` | Runtime schema, ETA samples, progress payload. |
| Image route | `src/app/api/generate/image/route.ts` | SDK + custom/system API + New API image compatibility, persistence. |
| Video route | `src/app/api/generate/video/route.ts` | SDK + custom/system API video, persistence. |
| Custom API transport | `src/lib/custom-api-fetch.ts` | Headers, retries, progress JSON parsing, upstream error parsing. |
| Server API resolution | `src/lib/server-api-config.ts` | Resolves user custom API and admin system API IDs into decrypted credentials. |
## Models And Providers
| Feature | Files | Notes |
| --- | --- | --- |
| Built-in model options | `src/lib/model-config.ts`, `src/lib/model-config-types.ts` | Image/video model lists, ratios, sizes, inference helpers. |
| Public model config API | `src/app/api/model-config/route.ts` | Returns model recommendations and provider config to clients. |
| User custom API keys | `src/lib/custom-api-store.ts`, `src/app/api/user-api-keys/route.ts`, `src/components/profile/api-key-manager.tsx` | User-owned encrypted API credentials. |
| Admin provider presets | `src/app/api/admin/providers/route.ts`, `src/components/admin/api-management-tab.tsx` | Provider registry, default API URL/model/type. |
| Admin system API configs | `src/app/api/admin/system-apis/route.ts`, `src/lib/server-api-config.ts` | Encrypted shared system API credentials, pricing metadata. |
| Model recommendations | `src/app/api/admin/model-recommendations/route.ts` | Admin-controlled displayed/recommended model lists. |
## Profile, Credits, Orders
| Feature | Files |
| --- | --- |
| Profile page | `src/app/profile/page.tsx` |
| Profile API | `src/app/api/profile/route.ts`, `src/app/api/profile/theme/route.ts` |
| Creation history tab | `src/components/profile/creation-history-tab.tsx`, `src/lib/creation-history-store.ts`, `src/app/api/creation-history/route.ts` |
| Credits tab/store | `src/components/profile/credits-tab.tsx`, `src/lib/credit-records-store.ts` |
| Orders tab/store | `src/components/profile/orders-tab.tsx`, `src/lib/order-store.ts`, `src/app/api/admin/orders/route.ts` |
| Billing guard | `src/components/billing-plan-guard.tsx`, `src/lib/admin-store.ts` |
## Gallery
| Feature | Files | Notes |
| --- | --- | --- |
| Public gallery page | `src/app/gallery/page.tsx` | Lists public works, search/sort/filter, preview/download. |
| Public gallery API | `src/app/api/gallery/route.ts` | GET public works, admin DELETE unpublishes. |
| Publish API | `src/app/api/gallery/publish/route.ts` | Copies media into gallery folders and inserts public work. |
| History persistence | `src/app/api/creation-history/route.ts`, `src/lib/creation-history-store.ts` | User-private completed works and published state. |
## Canvas
| Feature | Files | Notes |
| --- | --- | --- |
| Canvas page | `src/app/canvas/page.tsx` | Page entry. |
| Workspace | `src/components/canvas/infinite-canvas-workspace.tsx` | High-level canvas UI, project interaction. |
| React Flow canvas | `src/components/canvas/react-flow-canvas.tsx` | Node/edge/rendering interactions. |
| Canvas state types | `src/lib/canvas-types.ts` | Canonical node, layer, viewport, connection types. |
| Canvas persistence | `src/lib/canvas-store.ts` | Normalize/list/create/get/update/delete projects. |
| Canvas APIs | `src/app/api/canvas/projects/route.ts`, `src/app/api/canvas/projects/[id]/route.ts` | Authenticated project CRUD. |
## Admin Console
| Feature | Frontend | API |
| --- | --- | --- |
| Console login | `src/app/console/page.tsx`, `src/modules/console/pages/console-login-page.tsx` | `src/app/api/auth/login/route.ts` with `adminOnly` |
| Console dashboard | `src/app/console/dashboard/page.tsx`, `src/modules/console/pages/console-dashboard-page.tsx` | `src/app/api/admin/dashboard/route.ts`, `src/app/api/admin/stats/route.ts` |
| Users | `src/components/admin/user-management-tab.tsx` | `src/app/api/admin/users/route.ts`, `src/app/api/admin/clear-users/route.ts` |
| API/model management | `src/components/admin/api-management-tab.tsx` | `src/app/api/admin/providers/route.ts`, `src/app/api/admin/system-apis/route.ts`, `src/app/api/admin/model-recommendations/route.ts` |
| Pricing | `src/components/admin/pricing-tab.tsx` | Admin store/site config related routes |
| Payment | `src/components/admin/payment-tab.tsx` | `src/app/api/admin/payment-methods/route.ts`, `src/lib/server-payment-config.ts` |
| Orders | `src/components/admin/order-management-tab.tsx` | `src/app/api/admin/orders/route.ts` |
| Announcements | `src/components/admin/announcement-tab.tsx` | `src/app/api/announcements/route.ts` |
| Data import/export | `src/components/admin/data-management-tab.tsx` | `src/app/api/admin/data-export/route.ts`, `src/app/api/admin/data-import/route.ts` |
| System upgrade | `src/components/admin/system-upgrade-tab.tsx` | `src/app/api/admin/upgrade/route.ts`, `scripts/admin-upgrade-runner.mjs` |
| Logs/tasks | `src/components/admin/log-management-tab.tsx`, `src/components/admin/task-management-tab.tsx` | `src/lib/platform-logs.ts`, `src/app/api/admin/generation-jobs/route.ts` |
| Settings | `src/components/admin/settings-tab.tsx` | `src/app/api/site-config/route.ts`, `src/app/api/admin/email-settings/route.ts`, `src/app/api/admin/send-email/route.ts` |
## Storage And Downloads
| Feature | Files | Notes |
| --- | --- | --- |
| Local storage adapter | `src/lib/local-storage.ts` | Uses `LOCAL_STORAGE_DIR` or repo `local-storage`; normalizes keys. |
| Local file API | `src/app/api/local-storage/[...path]/route.ts` | Serves local storage files by key. |
| Download proxy | `src/app/api/download/route.ts` | Supports remote URL, same-origin URL, and `/api/local-storage/*`. |
| Remote fetch guard | `src/lib/remote-fetch.ts` | Use for server-side external fetches. |
## Database And Persistence
| Area | Files |
| --- | --- |
| Database connection pool | `src/storage/database/local-db.ts` |
| Schema snapshot | `src/storage/database/shared/schema.ts` |
| Supabase compatibility client | `src/storage/database/supabase-client.ts` |
| Init SQL | `scripts/init-database.sql` |
| DB patch runner | `scripts/apply-database-patch.sh` |
| Migration SQL files | `account-profile-migration.sql`, `model-config-migration.sql`, `persistence_migration.sql`, `scripts/database-optimization-patch.sql` |
## Deployment And Runtime
| Feature | Files |
| --- | --- |
| Custom Node server | `src/server.ts` |
| PM2 config | `ecosystem.config.cjs` |
| Build | `scripts/build.sh` |
| Start | `scripts/start.sh` |
| Dev | `scripts/dev.sh` |
| Deploy/upgrade | `scripts/deploy-or-upgrade.sh` |
| Backup | `scripts/backup-create.sh`, `scripts/backup-list.sh`, `scripts/backup-restore.sh` |
| Admin upgrade runner | `scripts/admin-upgrade-runner.mjs` |
| Boundary checks | `scripts/check-boundaries.sh` |