Compare commits

...
75 Commits
Author SHA1 Message Date
TowstyandCursor 2b603b1d58 Add an AIGen-only generate API for external tools.
Cursor and similar clients can enqueue Studio 2 stills with the same steps and CFG the bench uses, through session or AIGEN_API_KEY.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-26 19:05:28 -05:00
TowstyandCursor 68469d9c71 Clear deleted stills from the stage and library detail pane.
The file and catalog row were already removed, but the selected object stayed on screen so its prompt could still be applied.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-25 19:54:18 -05:00
TowstyandCursor 20359bfbd4 Delete library stills from disk before the catalog write, and stop caching their media.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-25 17:55:30 -05:00
TowstyandCursor 545a3d749b Stop a folder wipe from restoring the pre-wipe library catalog.
The in-memory catalog could outlive the write, so delete-all came back as thousands of empty tiles and a stale badge.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-24 12:01:25 -05:00
TowstyandCursor 39aa4b65d0 Keep library deletes when a still file is locked, and match LoRAs by engine folder.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-24 11:13:00 -05:00
TowstyandCursor 8602d6ed2e Let MOSS use the same LoRA picker and chain those adapters onto its graph.
The picker was hidden and the API cleared every stack, so a selected MOSS job could not carry a LoRA.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-22 20:28:25 -05:00
TowstyandCursor 354f475866 Add MOSS-Image on the Image v2 path and stop the queue calling it Klein.
The bench queue labeled every engine except Krea, Qwen, MiniMax, and LTX as Klein, and the v2 starter treated any engine other than Krea as Flux.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-22 20:04:58 -05:00
TowstyandCursor 74edeabc39 Pin Node 22.23.4 and refresh patched Nuxt 3 dependencies.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-22 09:07:54 -05:00
TowstyandCursor 4b22c95b4b Add folder wipe and drop broken still tiles from the library.
Delete all in this folder removes every still, clip, and track with files; list builders prune missing masters; select-all and delete no longer resurrect suppressed ids from later pages.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-12 13:34:31 -05:00
TowstyandCursor 97c7547da9 Let saved library stills queue Edit without a format rejection.
Use catalog width/height or aspect fallback in resolveRequestSize, restore GIF/BMP upload messaging, and keep Photo to change still ids across reload so Klein/Qwen Edit can bind imageAId.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-12 12:45:50 -05:00
TowstyandCursor 1bab5152f6 Fix image edit disk upload so stills persist before Generate.
Reject only real handoff frames, return 400 with reason, keep the new still in the client library, and surface missing-still errors from Generate instead of 500s.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-12 12:21:20 -05:00
TowstyandCursor 7dcac5444c Rename caption GGUF NSFW labels to NS.
Point caption host scripts at the renamed local Comfy models folder and filenames; no Comfy workflow JSONs referenced those files.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-12 11:33:43 -05:00
TowstyandCursor 26a3bfb797 Add asset-pack Image v2 API for Family Board stickers.
POST /api/assets/generate wraps Flux/Krea generate with sticker/panel/icon presets; GET /api/assets/{id} returns status and PNG URLs using the existing poll path.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-06 19:06:14 -05:00
TowstyandCursor f6c5ef8af5 Restore character names on Prompt Builder compile lines.
Character lines again use Name: description with outfit and facing features; set names and framing labels stay uncopied.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-04 23:17:15 -05:00
TowstyandCursor dd8897a3cf Add Prompt Builder bang ignores and facing-aware character features.
Strip !...! at compile time, and omit character features the active framing facing cannot see while keeping them checked in the editor.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-04 20:03:05 -05:00
TowstyandCursor 45e97cc1c3 Add Prompt Builder sequence section order.
Copied scene text and the scene editor follow a persisted sectionOrder, with legacy saves keeping the default style/settings/set/characters/prompt order.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-04 07:07:43 -05:00
TowstyandCursor b6eef6a511 Replace Prompt Builder beats with complete set framings.
Sets are places with labeled full-text framings; selecting a framing copies only that text, and legacy beat-only sets migrate to a wide framing.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-03 22:28:44 -05:00
Towsty d803d57a78 Fix bench draft structuredClone 500 and Prompt Builder button contrast.
Draft snapshots use plain JSON of picked fields with restore try/catch that clears bad storage; Prompt Builder actions use amber primary/secondary styles with 44px tap targets.
2026-10-03 19:38:55 -05:00
Towsty a8ae61704e Add Prompt Builder sets/framing and harden mobile draft look settings.
Sets and beats filter by shot size; scenes reorder/delete; portrait links Prompt Builder; landscape queue collapses; per-engine look settings and prompt Clear persist across iOS resumes.
2026-10-03 19:31:22 -05:00
Towsty 7799529788 Extend Prompt Builder with sequence characters, outfits, and scene toggles.
Characters live on the sequence with per-scene on/off and outfit picks; Copy scene exports only the active tab; legacy saves still open.
2026-10-02 08:50:31 -05:00
Towsty 790c33fcf0 Fix Prompt Builder Nitro build by inlining sequence helpers in utils.
The relative re-export of shared/prompt-sequences.mjs left an unresolved import in the SSR bundle.
2026-10-02 08:11:09 -05:00
Towsty 1bf97568bf Add Prompt Builder page for multi-scene prompt sequences.
Name, save, and load ordered scenes on the server; assemble copyable text with a Batch-compatible double blank line between scenes.
2026-10-02 07:15:00 -05:00
Towsty 5788d74001 Add desktop Batch toggle, fix xAIGen library hide/selection, per-engine steps/CFG, and mobile prompt editor.
Desktop Batch splits only on double blank lines when enabled; library hide actually conceals thumbs and pinned clicks stick; steps/CFG restore per image model; mobile opens a near-fullscreen prompt editor.
2026-10-01 17:06:25 -05:00
Towsty 4f40641050 Split blank-line paragraphs in the desktop prompt into ordered image batch jobs. 2026-09-30 23:34:47 -05:00
Towsty 14dcd234f3 Let finished caption jobs be dismissed from the Queue panel. 2026-09-30 23:18:44 -05:00
Towsty 15ef891b26 Add image-to-text Describe on the bench via exclusive llama.cpp caption jobs. 2026-09-30 22:50:19 -05:00
TowstyandCursor 9481791ac5 Keep fetching library pages after the first 50 so the whole folder is reachable.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-30 00:28:22 -05:00
TowstyandCursor 17bb42bea4 Serve the stage from a 1600px preview instead of the grid thumb.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-29 20:57:01 -05:00
TowstyandCursor ccf852cb0c Clear Queuing when the optimistic job snapshot avoids structuredClone.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-29 20:45:23 -05:00
TowstyandCursor 4ec8ffa8d6 Serve the bench before the catalog and never await ffmpeg on /thumb.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-29 20:35:28 -05:00
TowstyandCursor a465dd68ec Stop polling the library catalog and keep the stage on thumbs.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-29 20:15:03 -05:00
TowstyandCursor cfabfd37ee Queue Generate with an immediate local card and stop blocking reload on library or object_info.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-29 19:46:55 -05:00
TowstyandCursor ffdaa7ce42 Remount stage media on selectedId and show thumb before the archive still.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-29 19:45:51 -05:00
TowstyandCursor aa0aa871e4 Add paginated library JSON and dedicated still thumbs that never stream archive masters.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-29 19:45:22 -05:00
TowstyandCursor 845ee5bbf6 Set the selected still on Use image instead of an empty Photos card.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-29 15:40:35 -05:00
TowstyandCursor ba83520923 Move stage actions into a top chrome bar with Copy and Load menus.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-29 09:09:00 -05:00
TowstyandCursor 322e5a276e Persist the bench draft and hide input thumbs only.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-29 08:14:13 -05:00
TowstyandCursor 5f6a7aa9bc Rename library actions and always store promptRaw on ingest.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-29 08:14:13 -05:00
TowstyandCursor 930bbf7c7b Keep MiniMax hold from injecting amplitude and speed.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-29 08:14:13 -05:00
TowstyandCursor c4e74628ee Show the Qwen LoRA card with qwen-stem picks and apply them on generate.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-28 22:47:59 -05:00
TowstyandCursor fe560d7e40 Slim the phone stage to icons, chevrons, and a More sheet.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-28 22:21:13 -05:00
TowstyandCursor d61f99d6fd Put still actions on the stage and split output vs input hide.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-28 21:26:29 -05:00
Towsty f9903ed76e Square Library modal thumbs and add stage previous/next. 2026-09-28 20:40:45 -05:00
TowstyandCursor a33cadb6c2 Load Library modal thumbs with the same tiles and fetch as /library.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-28 20:25:16 -05:00
TowstyandCursor 5b0d7370ed Show Typed and Used prompt fields on still Details.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-28 20:11:18 -05:00
TowstyandCursor 7242d0faef Replace the under-stage filmstrip with a Library modal and stage eye.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-28 20:11:14 -05:00
TowstyandCursor e06afe4a17 Fix Photos Add, Remove, and Replace against the library picker.
Remove clears the Photos array and backing image fields; Add opens the picker with disk upload and drops empty drafts on cancel.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-26 17:06:39 -05:00
TowstyandCursor 50319e03a9 Map Photos roles to Qwen image_1/image_2 and inject encode tags silently.
Mention phrases become <imageN> only in the TextEncode string; the inspector never shows Comfy tokens.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-26 16:01:49 -05:00
TowstyandCursor 5c2248a3fd Replace Hero/Edit-source chrome with Photos role cards.
Inspector stills use plain-English roles and Mention phrases; Qwen Generate hides Photos entirely.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-26 16:00:37 -05:00
TowstyandCursor 58c5458c87 Store the Edit TextEncode prompt on library stills, not a Start still caption.
Edit + Enhance always leads with the keep/<image1> stanza and typed change; PE describe dumps are dropped, and Typed stays promptRaw.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-26 15:14:20 -05:00
TowstyandCursor c46e827c68 Force <image1> on every Qwen Edit PE rewrite.
PE-I2I no longer bans tags for single-still edits, and the runner rewrites natural photo/image wording to <image1> so Start still stays bound.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-26 15:04:04 -05:00
TowstyandCursor a51118d92a Pass through PE refusals to the raw prompt and pin adult PE system prompts.
Enhance no longer fails the studio job when the rewrite refuses or comes back empty; host prompt copies keep the official steps plus the adult appendix after a node re-clone.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-26 14:46:24 -05:00
TowstyandCursor 99b61e67d7 Keep Enhance + Generate as one queue row with shared progress.
The PE stage now stays on the same jobId so the header and queue badge agree, and jobs behind it do not promote when enhance finishes.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-26 14:42:22 -05:00
TowstyandCursor 30be4bd5b0 Wire Qwen Edit Start still to image_1 and PE-I2I identity keep.
Edit no longer invents strangers when the prompt omits <image1> or PE drops image tokens; Hero stays Klein-only.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-26 14:27:36 -05:00
TowstyandCursor ecc4c69a8b Wire Qwen Turbo toggle through Studio 2 and the runner.
Force 6/1 when Turbo is on, skip negatives, keep PE in front, and fail closed if the r128 LoRA is missing.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-26 12:42:00 -05:00
TowstyandCursor 17cbc99f8f Add Qwen 2.1 Viggle Turbo Comfy graphs.
Use the unmerged ViggleTurboLora path with the official 6-step sigma schedule on the existing Q8 GGUF.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-26 12:41:59 -05:00
TowstyandCursor 95873744cd Size Qwen 2.1 Generate from the bench aspect table.
Wire EmptyLatentImage to the official ~1 MP grid so 16:9 lands at 1536×864, keep PE wh_ratio advisory, and leave Edit on the encode latent from image_1.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-26 10:54:18 -05:00
TowstyandCursor 2842855c7b Wire Qwen Enhance prompt toggle through Studio 2 and the runner.
Queue PE first when enabled, fail closed on parse_ok, free VRAM, then run the existing T2I or Edit graph with the rewrite.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-26 10:25:44 -05:00
TowstyandCursor e0292c8d2a Add Qwen 2.1 PE-only Comfy graphs for prompt enhance.
Keep PE CLIP separate from DiT so the 16 GB card can run rewrite then generate without loading both at once.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-26 10:25:44 -05:00
TowstyandCursor bb27af506e Restore Studio 2 Load hydrate, sticky negatives, and strip actions.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-21 12:23:20 -05:00
TowstyandCursor df5ef0949e Make Library Reveal all / Hide all cover the whole grid.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-21 12:09:26 -05:00
TowstyandCursor 206984b6ec Add Reveal all / Hide all to Studio 2 input picker.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-20 21:04:55 -05:00
TowstyandCursor 52a01e0adc Enable Qwen 2.1 on Edit: wire picker, runner, and source-still validation.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-20 18:13:07 -05:00
TowstyandCursor 8609ba24a4 Add Qwen 2.1 Image Edit Comfy graph (GGUF + TextEncode + int8 cache).
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-20 18:10:50 -05:00
TowstyandCursor 776d585345 Fix xAIGen LoRA picker to use isXaigenStudio like the server.
Bench was checking only public.studio === 'xaigen', so when the instance
is branded xAIGen via instanceName the client stripped xaigen-* LoRAs.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-20 17:34:53 -05:00
TowstyandCursor 608f7d8d47 Fix Qwen 2.1 GGUF load: promote Q8 norms to F32 and wire TextEncode latent.
abenzerps Q8_0 ships 1D RMSNorms as packed Q8 (136 vs 128), which breaks
Comfy rms_rope; tagger now dequantizes small tensors and the graph uses
TextEncodeQwenImage21's 64-ch latent plus AuraFlow shift.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-20 16:58:00 -05:00
TowstyandCursor 68731916ca Wire Qwen 2.1 as Generate-only engine with 25/1 sampler defaults.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-20 16:58:00 -05:00
TowstyandCursor 08d507c491 Add studio2_qwen21_t2i Comfy graph for GGUF Qwen Image 2.1 T2I.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-20 16:57:04 -05:00
TowstyandCursor d65420f34a Add Qwen 2.1 host setup script and document Shared model paths.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-20 16:57:04 -05:00
TowstyandCursor d733e80881 Add a viewer-first mobile shell that swaps in under 768px without restyling desktop Bench.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-19 08:19:36 -05:00
TowstyandCursor dccfafa08b Scale viewer stills and clips to fill the stage with contain.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-18 20:31:15 -05:00
TowstyandCursor 589791cdb8 Replace LoRA Thumbwheel spectrograms with range and numeric strengths.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-18 19:15:12 -05:00
TowstyandCursor c0289afa0e Rebuild Bench as the three-column cinematic layout with Generate CTA.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-18 13:36:09 -05:00
TowstyandCursor a9799e4920 Lock display tokens and slot sizes to the cinematic pixel grid.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-18 13:36:04 -05:00
TowstyandCursor 52bd6cf4a8 Align Studio display chrome to the Classic | Studio reference mock.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-18 13:22:18 -05:00
143 changed files with 16333 additions and 1594 deletions
+2
View File
@@ -19,6 +19,8 @@ COMFY_CONTROL_TOKEN=
# COMFY_IDLE_MS=1800000
NUXT_SESSION_SECRET=change-me
# Optional. Bearer token for POST /api/aigen/generate and GET /api/aigen/jobs/:id (AIGen only).
# AIGEN_API_KEY=
NUXT_PUBLIC_AUTH_ENABLED=true
NUXT_OIDC_CLIENT_ID=
NUXT_OIDC_CLIENT_SECRET=
+25
View File
@@ -0,0 +1,25 @@
# Architecture
Nuxt 3 app, Nitro `node-server`, Vue 3. Production image is `node:22.23.4-alpine` with ffmpeg added in the runner stage. The container listens on port 3000 and reads the library from `LIBRARY_DIR` (default `/data/library`).
## Library
`server/utils/library.ts` stores one catalog per owner under `users/<owner>/`. The owner key is a hash of the session identity, or a single private-instance id when password auth is on. Catalog writes are serialized per owner and written to a temp file, then renamed.
`deleteStill`, `deleteStillFamily`, and `wipeFolderContents` update the catalog even if `rmSync` fails. A folder wipe removes every still, clip, and track for that folder, checks the folder is empty, and drops that owner's in-memory catalog cache. The next read loads the file that was just written. It does not treat an unchanged mtime as proof the cache is current. `pruneMissingStillMasters` only drops stills whose master file is missing. `publicLibrary` and `publicLibraryPage` run that prune before they return rows or folder counts. The wipe route returns that read after the cache drop.
Studio 2 reads a paged `/api/library` list. After a delete or wipe it replaces local library state from the server response, refetches that list, and clears the stage still and form slots that pointed at a removed id. A folder `imageCount` of 0 is an empty folder.
## Auth
`server/middleware/auth.ts` allows a fixed set of paths with case-sensitive prefixes (`/api/auth/login`, `/api/health`, `/login`, and the other listed public paths). Every other `/api/` path without a session returns 401. Other pages redirect to login. Cache headers for `/api/generate/` and `/api/prompt/` are set in `server/middleware/cache-headers.ts`, not Nitro `routeRules`.
## LoRAs
Comfy returns relative paths under `models/loras/`. `server/utils/loras.ts` caches that list and `?fresh=1` forces a live object-info scan so new files appear without a restart. Matching lives in `utils/loras.ts`.
A path segment `xaigen` or `xiagen` is xAIGen-only. A path segment `aigen` is visible on AIGen. The directory immediately under that segment is the engine (`flux`, `krea`, `moss`, and `minimax`, `ltx`, or `qwen` when present). Filename tokens such as `krea-something.safetensors` still match when the file has not been moved. The value stored on a stack is the Comfy-relative path.
## Generation
Studio 2 jobs are built in `server/utils/studio2/` and sent to the configured Comfy host. Klein, Krea, MOSS, MiniMax, and LTX graph construction is separate from library delete and from LoRA folder matching.
+5
View File
@@ -0,0 +1,5 @@
# Design
Cut taglines, helper text and secondary labels. If a screen needs them to make sense, fix the layout.
Studio 2 is a dark bench: task and model on the left, the selected still or clip in the center, the queue on the right. Library browsing is a grid with folder chips. Empty and error states use the control that is already on the screen (the stage frame, the folder chip count, the delete confirmation) rather than extra captions.
+2 -2
View File
@@ -1,11 +1,11 @@
FROM node:22-alpine AS build
FROM node:22.23.4-alpine AS build
WORKDIR /app
COPY package.json package-lock.json .npmrc ./
RUN npm install --legacy-peer-deps
COPY . .
RUN npm run build
FROM node:22-alpine AS runner
FROM node:22.23.4-alpine AS runner
WORKDIR /app
RUN apk add --no-cache ffmpeg
ENV NODE_ENV=production
+9
View File
@@ -0,0 +1,9 @@
# AIGen
AIGen is a Nuxt 3 studio that sends image, video, and music jobs to ComfyUI and keeps the results in a library. The home page is Studio 2. Studio 1, the queue, prompt builder, director, music, library, and settings pages are still in the app.
Two deployments share this repo. AIGen is the default. xAIGen is the same build with `NUXT_PUBLIC_STUDIO=xaigen`, which is what unlocks LTX and xAIGen-only LoRAs.
The library catalog on disk is the source of truth for stills, clips, and tracks. In production that disk is the Coolify volume (`LIBRARY_DIR`). Deleting a still removes the catalog row even when the file itself cannot be removed.
LoRA files are picked from Comfy's list. The preferred layout is `models/loras/xaigen/<engine>/` or `models/loras/aigen/<engine>/`. Flat files that still use filename prefixes keep working.
+17
View File
@@ -0,0 +1,17 @@
# Progress
## 2026-10-24
Delete-all was still serving a pre-wipe catalog. The folder wipe now strips that folder's stills, clips, and tracks, filters again if any rows remain, and deletes the owner's in-memory catalog cache after the write. The wipe route reads the library only after that drop. Prune still only removes stills. Studio 2 and the library page replace local rows from the wipe response instead of merging, keep wiped ids out of later pages, and treat a folder image count of 0 as empty. The stage drops a selected still that is no longer in the library.
Library deletes now commit the catalog when file removal fails, then prune stills whose masters are missing. Studio 2 and the library page drop the deleted id from the selected still, photo slots, and the in-memory list, and they refetch `/api/library` instead of trusting that list. Select-all uses the rows already loaded. It does not start a second full-catalog fetch that can merge a suppressed id back in from a later page.
LoRA engine matching prefers the folder under `xaigen/` or `aigen/`. The task text said an `aigen` path segment marks a LoRA xAIGen-only. That conflicts with the check that `aigen/flux/bar.safetensors` is visible on AIGen. The checks win: `xaigen/` and the `xiagen` typo are xAIGen-only; `aigen/` is visible on AIGen. Old `krea-something.safetensors` names still match Krea.
Nitro `routeRules` headers were moved to `server/middleware/cache-headers.ts` so the Nuxt 3 route-rules advisory stays in the accepted case: this app does not use `routeRules` for redirects, headers, proxy, or auth. Auth remains the case-sensitive middleware allowlist.
`seroval` is pinned to 1.7.2 and `serialize-javascript` to 7.1.4. Node stays on `22.23.4`, the newest 22.x release. No `simple-git` override.
The notes server rejected the configured credential, so these six docs are in the repo and not yet mirrored to Brain `projects/aigen/`.
Left for a live check after Coolify deploys: delete one still and a batch, confirm the count drops in another browser after refresh, and confirm a newly dropped file under `models/loras/xaigen/<engine>/` or `aigen/<engine>/` shows up from Refresh.
+13
View File
@@ -0,0 +1,13 @@
# Rules
Cut taglines, helper text and secondary labels. If a screen needs them to make sense, fix the layout.
No secrets in code, prompts, logs or docs.
## Security baseline
- Every Dockerfile stage uses `node:22.23.4-alpine`. `package.json` engines are `>=22.23.4 <23`.
- Stay on Nuxt 3 (`nuxt` `^3.21.11`) and `vue` `^3.5.44` unless a later task asks for Nuxt 4.
- Do not add `simple-git`. Do not add a `simple-git` `^4` override.
- Do not put auth, redirects, or proxy rules in Nitro `routeRules`. Auth stays in server middleware: a case-sensitive allowlist, fail closed.
- Do not log or commit tokens, passwords, or library file contents.
+99
View File
@@ -0,0 +1,99 @@
# Cursor prompt — unique mobile portrait shell (new file)
Do not edit `STUDIO2-DISPLAY-CURSOR-PROMPT.md`, `STUDIO2-DISPLAY-LAYOUT-SPEC.md`, `STUDIO2-LORA-DIALS-PROMPT.md`, or `STUDIO2-VIEWER-FIT-PROMPT.md`.
Branch: **`studio-2`**. Push `origin/studio-2` only. Chrome only. Same `form`, queue, generate, locks, LoRAs, library. No graph/runner/extend/YuE2 changes.
Desktop 3-column bench is **done**. Do not restyle desktop to make mobile work. Do not stack the three columns in a tall scroll and call it mobile.
Breakpoint: `(max-width: 767px)` **and** coarse pointer. Use a **separate mobile shell** (`Studio2Mobile.vue` or `Bench` template `v-if="isMobile"`) that binds the **same** state as desktop Bench.
Reference mock: `studio2-display-ux/mobile-mock.html` (open on a 390×844 viewport).
---
## Why unique
Portrait cannot show 260 | stage | 280. If you shrink that grid you lose Generate, LoRAs, and the still.
Mobile is a **viewer-first phone app** with sheets for the inspector and the queue. Every desktop control still exists. It is just not on screen at once.
---
## Chrome map (portrait)
```
┌ status / 48px header ─────────────────────────────────────┐
│ AIGen Inbox ▾ GPU ☰ queue(n) │
├ task chips (scroll-x) Generate Edit … Music ─────────────┤
├ model chips Klein | Krea or H3 | LTX ───────┤
├───────────────────────────────────────────────────────────┤
│ │
│ STAGE (contain, full remaining height) │
│ Library (stage chrome) · eye ≥48px top-right │
├ [Slots] [Prompt] [Look] [Gen] Generate (amber, 48px) ─┤
└───────────────────────────────────────────────────────────┘
Library is a **stage button** that opens the Library modal/sheet (same tiles,
filters, Use as photo / Copy / Load / Delete). The under-stage filmstrip row
is revoked — recents live in the modal (newest first).```
Bottom **dock** is 4 tabs that open sheets, plus Generate always visible:
| Tab | Sheet contents (all desktop fields) |
|---|---|
| **Slots** | Hero, Start, End, Guides, Upload, Lock face, Lock outfit + Klein caption |
| **Prompt** | Prompt textarea, negative chips, style/render/quality/lighting chips |
| **Look** | LoRA stack (filename + Model/CLIP sliders + numbers), Seed + dice, Aspect, extra generation settings (steps/CFG only if that engine uses them) |
| **Gen** | Engine-specific video/music extras: duration/target length, fps, turbo, camera beats, YuE2 hints. Not a second Generate button. |
**Generate** is the rightmost dock control — 48×48 or a 120px amber pill. Never labeled Queue.
Header **☰** or badge **Queue (n)** opens a **right/bottom sheet** of job cards (same cards as desktop right column).
Library and Settings stay header links (or a `…` menu). Do not drop them.
---
## Stage
- Same contain rule as desktop: `max-width/height 100%`, `object-fit: contain`, no inner max-width cap.
- Still / video / audio switch on `selected.kind`. No waveform on a still.
- Safe area: `padding-bottom: env(safe-area-inset-bottom)` on the dock.
- Filmstrip under stage, 72×48 tiles, amber ring on selected, horizontal scroll. Trash on selected tile only.
---
## Sheets
- One sheet at a time. Height `min(85vh, content)`. Drag handle + Done.
- Fields keep desktop order and payload keys.
- LoRA card = filename + two (or one) sliders + numeric `0.00–2.00`. No hashed meters.
- Krea disabled-on-Edit with the same one-line reason.
- LTX disabled on AIGen with `xAIGen only`.
- xAIGen hide defaults: eye on stage + each tile. No global hide checkbox required on mobile.
---
## What you must not do
- No desktop 3-column at `<768`.
- No “rotate device” dead end.
- No missing task (Iterate if desktop has it — add the chip).
- No second `form` object.
- Do not change Classic/Studio desktop tokens in this pass.
`isMobile` from `window.matchMedia('(max-width: 767px)')` + resize listener. SSR: default desktop to avoid hydration flip, then switch on mount.
---
## Done when
390×844 portrait:
- Stage fills the phone; dock + chips visible without page-zoom.
- Slots, Prompt, Look, Gen sheets each reachable; Generate queues a job.
- Queue sheet lists jobs.
- Rotate to ≥768: desktop 3-column returns, same job state.
One or two present-tense commits. Screenshot 390 and 1440.
+13
View File
@@ -0,0 +1,13 @@
# Tasks
## Done
1. Library ghost / delete hardening. `removeStillFiles` no longer throws, so a locked thumb cannot abort the catalog write. `deleteStill`, `deleteStillFamily`, and `wipeFolderContents` prune missing masters and write the catalog. Library pages and Studio 2 refetch after delete, clear slots that pointed at the deleted id, and select-all only selects rows already loaded so a later page cannot put a suppressed id back into the selection.
2. LoRA folders. Engine matching prefers `xaigen/<engine>/` and `aigen/<engine>/`. `xaigen` and the `xiagen` typo stay xAIGen-only. `aigen/` stays visible on AIGen. Filename prefixes remain the fallback. Refresh with `fresh=1` still live-scans Comfy, and the stack stores the Comfy-relative path.
3. Library delete-all. A folder wipe leaves that folder empty in the catalog that is written, drops the owner's in-memory catalog cache, and the wipe route returns a library read taken after that drop. The client replaces its lists from that response, trusts a server image count of 0, and clears the stage still and photo slots that pointed at wiped ids.
## Not in this pass
Klein, Krea, MOSS, MiniMax, and LTX graph changes. Coolify app targets. The `studio-2` branch.
Binary file not shown.

After

Width:  |  Height:  |  Size: 285 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 MiB

@@ -0,0 +1,149 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>AIGen — Display mock (Classic | Studio)</title>
<link rel="stylesheet" href="./tokens/display.css" />
<style>
* { box-sizing: border-box; }
body { margin: 0; font-family: ui-sans-serif, system-ui, Inter, sans-serif; background: #0e0e10; color: #f3f1ea; }
.app { min-height: 100vh; display: flex; flex-direction: column; gap: var(--chrome-gap); padding: var(--chrome-gap); }
header.top {
height: var(--header-h); display: flex; align-items: center; gap: 12px;
border: 1px solid var(--line); border-radius: var(--radius); padding: 0 12px; background: var(--bg-raise);
}
.brand { font-weight: 650; letter-spacing: .02em; }
.grow { flex: 1; }
.pill { font-size: var(--type-sm); color: #b8e0a8; border: 1px solid #2d4a2a; background: #142016; border-radius: 999px; padding: 4px 10px; }
.nav { color: var(--muted); font-size: var(--type-sm); display: flex; gap: 14px; }
.nav b { color: var(--text); font-weight: 600; }
.identity-header, .classic-hide { display: flex; gap: 10px; align-items: center; font-size: var(--type-sm); color: var(--muted); }
.rail { display: flex; gap: 6px; flex-wrap: wrap; }
.seg {
height: var(--rail-h); padding: 0 12px; border-radius: var(--radius);
border: 1px solid var(--line); background: var(--bg-slot); color: var(--muted); cursor: pointer;
}
.seg[aria-pressed="true"] { background: #2a1f0c; border-color: var(--amber); color: var(--amber); }
.seg:disabled { opacity: .45; cursor: not-allowed; }
.classic-selects { display: flex; gap: 8px; }
.classic-selects select {
background: var(--bg-slot); color: var(--text); border: 1px solid var(--line);
border-radius: var(--radius); height: var(--rail-h); padding: 0 8px;
}
.grid { display: grid; grid-template-columns: 240px 1fr 260px; gap: var(--chrome-gap); flex: 1; }
.col { background: var(--bg-raise); border: 1px solid var(--line); border-radius: var(--radius); padding: var(--card-pad); }
.slot { background: var(--bg-slot); border: 1px dashed var(--line); border-radius: var(--radius); min-height: 72px; margin-bottom: 8px; padding: 8px; font-size: var(--type-sm); color: var(--muted); }
.slot strong { display: block; color: var(--text); margin-bottom: 4px; }
.viewer { position: relative; background: #111; border-radius: var(--radius); min-height: 320px; display: grid; place-items: center; color: var(--muted); border: 1px solid var(--line); }
.eye-viewer { position: absolute; top: 8px; right: 8px; background: #000a; border: 1px solid var(--line); border-radius: 6px; padding: 4px; }
.strip { display: flex; gap: 8px; margin-top: 10px; }
.tile { width: 72px; height: 48px; background: #222; border-radius: 6px; border: 1px solid var(--line); position: relative; }
.eye-tile { position: absolute; top: 2px; right: 2px; width: 16px; height: 16px; }
textarea, input {
width: 100%; background: var(--bg-slot); color: var(--text); border: 1px solid var(--line);
border-radius: var(--radius); padding: 8px; font: inherit;
}
.cta { width: 100%; height: 44px; border: 0; border-radius: var(--radius); background: var(--amber); color: #1a1204; font-weight: 700; cursor: pointer; margin-top: 10px; }
.hint { font-size: 11px; color: var(--muted); margin: 6px 0 10px; }
.settings {
position: fixed; right: 16px; bottom: 16px; width: 360px; background: var(--bg-raise);
border: 1px solid var(--line); border-radius: 10px; padding: 14px; box-shadow: 0 12px 40px #0008;
}
.cards { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; }
.card {
border: 1px solid var(--line); border-radius: 8px; padding: 10px; background: var(--bg-slot); cursor: pointer; text-align: left; color: inherit;
}
.card[aria-pressed="true"] { border-color: var(--amber); background: #2a1f0c; }
.card small { display: block; color: var(--muted); margin-top: 4px; }
</style>
</head>
<body>
<div class="app" data-display="studio" id="root">
<header class="top">
<span class="brand">AIGen</span>
<span class="muted" style="color:var(--muted);font-size:12px">/ Inbox</span>
<div class="grow"></div>
<div class="identity-header">
<label><input type="checkbox" checked /> Lock face</label>
<label><input type="checkbox" checked /> Lock outfit</label>
</div>
<div class="classic-hide">
<label><input type="checkbox" /> Hide input</label>
<label><input type="checkbox" /> Hide output</label>
</div>
<nav class="nav"><span>Library</span><b>Queue</b><span>Settings</span></nav>
<span class="pill">5080 Ready</span>
</header>
<div class="rail rail-task" role="tablist">
<button class="seg" aria-pressed="false">Image</button>
<button class="seg" aria-pressed="false">Edit</button>
<button class="seg" aria-pressed="false">Refine</button>
<button class="seg" aria-pressed="true">Video</button>
<button class="seg" aria-pressed="false">Extend</button>
<button class="seg" aria-pressed="false">Music</button>
</div>
<div class="rail rail-model">
<button class="seg" aria-pressed="true">MiniMax H3</button>
<button class="seg" disabled title="xAIGen only">LTX</button>
</div>
<div class="classic-selects">
<select><option>Video</option><option>Image</option><option>Extend</option><option>Music</option></select>
<select><option>MiniMax H3</option><option disabled>LTX (xAIGen only)</option></select>
</div>
<div class="grid">
<aside class="col">
<div class="slot"><strong>Hero</strong>car_bee still</div>
<div class="slot"><strong>Start</strong>Select still or clip</div>
<div class="slot"><strong>End</strong>Optional</div>
<div class="identity-slots">
<label><input type="checkbox" checked /> Lock face</label><br />
<label><input type="checkbox" checked /> Lock outfit</label>
<p class="hint">hero encode + lock text — not a MiniMax face/clothes split on stills</p>
</div>
</aside>
<main class="col">
<div class="viewer">
<button class="eye-viewer" title="Toggle viewer">eye</button>
viewer · last frame / waveform
</div>
<div class="strip">
<div class="tile"><span class="eye-tile">👁</span></div>
<div class="tile"><span class="eye-tile">👁</span></div>
<div class="tile"><span class="eye-tile">👁</span></div>
<div class="tile"><span class="eye-tile">👁</span></div>
</div>
</main>
<aside class="col">
<textarea rows="5">car_bee walks the Great Hall, cinematic</textarea>
<p class="hint">YuE2 target length is a plan hint, not a trim.</p>
<input value="seed unlocked" />
<button class="cta">Generate</button>
</aside>
</div>
</div>
<aside class="settings">
<strong>Settings → Display</strong>
<p class="hint">Layout only. Jobs, engines, and library IDs stay the same.</p>
<div class="cards">
<button class="card" id="btnClassic" aria-pressed="false">Classic<small>packed header, dropdowns</small></button>
<button class="card" id="btnStudio" aria-pressed="true">Studio<small>task rail, model rail, slots + eyes</small></button>
</div>
</aside>
<script>
const root = document.getElementById("root");
const classic = document.getElementById("btnClassic");
const studio = document.getElementById("btnStudio");
function setMode(mode) {
root.setAttribute("data-display", mode);
classic.setAttribute("aria-pressed", mode === "classic" ? "true" : "false");
studio.setAttribute("aria-pressed", mode === "studio" ? "true" : "false");
}
classic.onclick = () => setMode("classic");
studio.onclick = () => setMode("studio");
</script>
</body>
</html>
@@ -0,0 +1,6 @@
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<path d="M3 3l18 18"/>
<path d="M10.6 10.6A3 3 0 0 0 12 15a3 3 0 0 0 2.4-4.4"/>
<path d="M9.9 5.1A11 11 0 0 1 12 5c6.5 0 10 7 10 7a18 18 0 0 1-3.2 3.8"/>
<path d="M6.1 6.1C3.7 7.8 2 12 2 12s3.5 7 10 7a10.5 10.5 0 0 0 4.2-.9"/>
</svg>

After

Width:  |  Height:  |  Size: 446 B

@@ -0,0 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7S2 12 2 12Z"/>
<circle cx="12" cy="12" r="3"/>
</svg>

After

Width:  |  Height:  |  Size: 308 B

@@ -0,0 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<rect x="4" y="11" width="16" height="10" rx="2"/>
<path d="M8 11V8a4 4 0 0 1 8 0v3"/>
</svg>

After

Width:  |  Height:  |  Size: 302 B

@@ -0,0 +1,56 @@
/* AIGen display tokens — Classic | Studio
Apply on [data-display] wrapper. Do not fork components. */
:root,
[data-display="studio"] {
--bg: #0e0e10;
--bg-raise: #161618;
--bg-slot: #1c1c1f;
--line: #2a2a2e;
--text: #f3f1ea;
--muted: #9a9588;
--amber: #f5a524;
--amber-dim: #c4841c;
--radius: 8px;
--chrome-gap: 16px;
--rail-h: 40px;
--card-pad: 14px;
--header-h: 52px;
--type: 14px;
--type-sm: 12px;
}
[data-display="classic"] {
--chrome-gap: 8px;
--rail-h: 32px;
--card-pad: 10px;
--header-h: 44px;
--type: 13px;
}
[data-display] {
background: var(--bg);
color: var(--text);
font-size: var(--type);
}
[data-display="classic"] .rail-task,
[data-display="classic"] .rail-model {
display: none;
}
[data-display="studio"] .classic-selects {
display: none;
}
[data-display="classic"] .identity-slots {
display: none;
}
[data-display="studio"] .identity-header {
display: none;
}
[data-display="classic"] .eye-tile,
[data-display="classic"] .eye-viewer {
display: none;
}
[data-display="studio"] .classic-hide {
display: none;
}
+951 -76
View File
File diff suppressed because it is too large Load Diff
+8 -1
View File
@@ -55,6 +55,13 @@
role="menuitem"
@click="menuOpen = false"
>Director</NuxtLink>
<NuxtLink
to="/prompt-builder"
class="block rounded-xl px-3 py-2 text-sm hover:bg-white/5 hover:text-white"
:class="current === 'prompt-builder' ? 'text-amber-100' : 'text-zinc-200'"
role="menuitem"
@click="menuOpen = false"
>Prompt Builder</NuxtLink>
<NuxtLink
to="/music"
class="block rounded-xl px-3 py-2 text-sm hover:bg-white/5 hover:text-white"
@@ -131,7 +138,7 @@
<script setup lang="ts">
withDefaults(defineProps<{
subtitle: string
current?: 'studio' | 'library' | 'director' | 'queue' | 'settings' | 'music'
current?: 'studio' | 'library' | 'director' | 'prompt-builder' | 'queue' | 'settings' | 'music'
wide?: boolean
queueCount?: number
}>(), {
+6 -6
View File
@@ -135,16 +135,16 @@ const visibleSlots = computed(() => {
})
function frameThumb(key: SlotKey) {
if (key === 'still' && props.stillId) return `/api/library/stills/${props.stillId}?thumb=1`
if (key === 'from' && props.fromClipId) return `/api/library/clips/${props.fromClipId}/last-frame?thumb=1&v=parent`
if (key === 'first' && props.clipId) return `/api/library/clips/${props.clipId}/first-frame?thumb=1&v=join`
if (key === 'still' && props.stillId) return `/api/library/stills/${props.stillId}?thumb=1&v=0`
if (key === 'from' && props.fromClipId) return `/api/library/clips/${props.fromClipId}/last-frame?thumb=1&v=parent&e=0`
if (key === 'first' && props.clipId) return `/api/library/clips/${props.clipId}/first-frame?thumb=1&v=join&e=0`
return ''
}
function frameFull(key: SlotKey) {
if (key === 'still' && props.stillId) return `/api/library/stills/${props.stillId}`
if (key === 'from' && props.fromClipId) return `/api/library/clips/${props.fromClipId}/last-frame?v=parent`
if (key === 'first' && props.clipId) return `/api/library/clips/${props.clipId}/first-frame?v=join`
if (key === 'still' && props.stillId) return `/api/library/stills/${props.stillId}?v=0`
if (key === 'from' && props.fromClipId) return `/api/library/clips/${props.fromClipId}/last-frame?v=parent&e=0`
if (key === 'first' && props.clipId) return `/api/library/clips/${props.clipId}/first-frame?v=join&e=0`
return ''
}
+1 -1
View File
@@ -29,7 +29,7 @@
</template>
<script setup lang="ts">
import type { ImageIteration } from '~/utils/imageIterations'
const props = withDefaults(defineProps<{ modelValue: ImageIteration; baseSteps?: number; baseCfg?: number; loraNames?: string[]; engine?: 'flux' | 'krea'; allowStrength?: boolean; disabled?: boolean }>(), { baseSteps: 20, baseCfg: 1, loraNames: () => [], engine: 'flux', allowStrength: false, disabled: false })
const props = withDefaults(defineProps<{ modelValue: ImageIteration; baseSteps?: number; baseCfg?: number; loraNames?: string[]; engine?: 'flux' | 'krea' | 'moss'; allowStrength?: boolean; disabled?: boolean }>(), { baseSteps: 20, baseCfg: 1, loraNames: () => [], engine: 'flux', allowStrength: false, disabled: false })
const emit = defineEmits<{ 'update:modelValue': [value: ImageIteration] }>()
const seedMode = computed(() => typeof props.modelValue.seed === 'number' ? 'custom' : props.modelValue.seed || 'random')
function update(patch: Partial<ImageIteration>) { emit('update:modelValue', { ...props.modelValue, ...patch }) }
+19 -7
View File
@@ -95,7 +95,7 @@
>
<div class="relative h-28 overflow-hidden bg-zinc-900">
<img
:src="`/api/library/stills/${still.id}?thumb=1`"
:src="`/api/library/stills/${still.id}/thumb?v=${still.createdAt || 0}`"
alt=""
loading="lazy"
decoding="async"
@@ -336,19 +336,31 @@ async function unlock() {
}
async function ingest(file: File) {
if (/last[\s._-]*frame/i.test(file.name || '')) return
if (/last[\s._-]*frame/i.test(file.name || '')) {
emit('error', 'Rejected as video handoff: filename matches last-frame. Choose a regular source image.')
return
}
const body = new FormData()
body.append('image', file)
body.append('folderId', current.value?.id || activeFolderId.value)
body.append('hideInput', String(props.hideInputPreview === true))
try {
const result = await $fetch<{ still?: { id: string; filename: string; hideInput?: boolean } }>('/api/library/stills', { method: 'POST', body })
emit('updated', result)
if (props.stillOnly) {
if (result.still?.id) emit('pick', result.still)
const result = await $fetch<{ still?: { id: string; filename: string; hideInput?: boolean }; stills?: PickerStill[] }>('/api/library/stills', { method: 'POST', body })
if (!result.still?.id) {
emit('error', 'Could not save that image to the library.')
return
}
emit('select', file, props.hideInputPreview === true, result.still?.id)
// Keep the new still in the payload the parent merges into library.stills
const stills = Array.isArray(result.stills) ? result.stills : []
if (!stills.some(item => item.id === result.still!.id)) {
stills.unshift(result.still as PickerStill)
}
emit('updated', { ...result, still: result.still, stills })
if (props.stillOnly) {
emit('pick', result.still)
return
}
emit('select', file, props.hideInputPreview === true, result.still.id)
} catch (error: any) {
emit('error', error?.data?.statusMessage || 'Could not save image')
}
+152 -45
View File
@@ -6,22 +6,21 @@
<li
v-for="(item, index) in model"
:key="item.name"
class="rounded-xl border bg-zinc-950/80"
class="rounded-lg border border-[#2A2A2E] bg-[#1A1A1D] p-2.5"
:class="[
compact ? 'px-2 py-1.5' : 'px-3 py-2',
dragOverIndex === index ? 'border-amber-300/50' : 'border-white/10',
dragOverIndex === index ? 'border-amber-300/50' : '',
draggingIndex === index ? 'opacity-60' : ''
]"
@dragover.prevent="onDragOver(index)"
@drop.prevent="onDrop(index)"
@dragleave="onDragLeave(index)"
>
<div class="flex items-center justify-between gap-2">
<div class="flex min-w-0 items-center gap-2">
<div class="flex items-start justify-between gap-2">
<div class="flex min-w-0 flex-1 items-start gap-2">
<button
v-if="model.length > 1"
type="button"
class="shrink-0 cursor-grab touch-none text-zinc-500 hover:text-zinc-300 active:cursor-grabbing disabled:cursor-not-allowed disabled:opacity-40"
class="mt-0.5 shrink-0 cursor-grab touch-none text-zinc-500 hover:text-zinc-300 active:cursor-grabbing disabled:cursor-not-allowed disabled:opacity-40"
:disabled="disabled"
draggable="true"
title="Drag to reorder"
@@ -31,61 +30,91 @@
>
<span class="block leading-none" aria-hidden="true">⋮⋮</span>
</button>
<span class="min-w-0"><span class="block truncate text-zinc-200">{{ labelFor(item.name) }}</span><span v-if="filenameSubtitle" class="block truncate text-[11px] text-zinc-500" :title="item.name">{{ item.name }}</span></span>
<span class="min-w-0 flex-1">
<span class="flex min-w-0 items-center gap-1.5">
<span class="block truncate font-medium text-[#F3F1EA]" :title="labelFor(item.name)">{{ labelFor(item.name) }}</span>
<LoraTriggerTip
:text="triggerFor(item.name)"
:aria-label="'Activation for ' + labelFor(item.name)"
@insert="emit('insert-trigger', $event)"
@save="saveTrigger(item.name, $event)"
/>
</span>
<span v-if="filenameSubtitle" class="mt-0.5 block truncate text-[11px] text-[#9A9588]" :title="item.name">{{ stemFor(item.name) }}</span>
</span>
</div>
<button
type="button"
class="shrink-0 text-[11px] text-zinc-500 hover:text-red-300 disabled:opacity-50"
class="shrink-0 text-[11px] text-[#9A9588] hover:text-red-300 disabled:opacity-50"
:disabled="disabled"
@click="removeAt(index)"
>
Remove
</button>
</div>
<div class="mt-1.5 flex flex-wrap gap-3">
<Thumbwheel
:model-value="item.strengthModel"
label="Model"
:lock-key="`lora-model:${item.name}`"
:min="LORA_STRENGTH_MIN"
:max="LORA_STRENGTH_MAX"
<div class="mt-2 space-y-1.5">
<label class="grid grid-cols-[3.25rem_minmax(0,1fr)_2.75rem] items-center gap-2 text-[11px] text-[#9A9588]">
<span>{{ clipStrength ? 'Model' : 'Strength' }}</span>
<input
type="range"
class="lora-strength-range min-w-0"
:min="0"
:max="2"
:step="LORA_STRENGTH_STEP"
:fine-step="LORA_STRENGTH_STEP"
:coarse-step="0.25"
:digits="2"
compact
:disabled="disabled"
@update:model-value="setStrength(index, 'strengthModel', $event)"
/>
<Thumbwheel
:model-value="item.strengthClip"
label="CLIP"
:lock-key="`lora-clip:${item.name}`"
:min="LORA_STRENGTH_MIN"
:max="LORA_STRENGTH_MAX"
:value="displayStrength(item.strengthModel)"
:aria-label="(clipStrength ? 'Model' : 'Strength') + ' for ' + labelFor(item.name)"
@input="onRange(index, 'strengthModel', $event)"
>
<input
type="number"
class="lora-strength-num w-full rounded border border-[#2A2A2E] bg-[#0B0B0D] px-1 py-0.5 text-right font-mono text-[11px] text-[#F3F1EA] outline-none focus:border-[#F5A524]"
:min="0"
:max="2"
:step="LORA_STRENGTH_STEP"
:fine-step="LORA_STRENGTH_STEP"
:coarse-step="0.25"
:digits="2"
compact
:disabled="disabled || !clipStrength"
@update:model-value="setStrength(index, 'strengthClip', $event)"
/>
:disabled="disabled"
:value="displayStrength(item.strengthModel).toFixed(2)"
:aria-label="(clipStrength ? 'Model' : 'Strength') + ' value'"
@change="onNumber(index, 'strengthModel', $event)"
>
</label>
<label
v-if="clipStrength"
class="grid grid-cols-[3.25rem_minmax(0,1fr)_2.75rem] items-center gap-2 text-[11px] text-[#9A9588]"
>
<span>CLIP</span>
<input
type="range"
class="lora-strength-range min-w-0"
:min="0"
:max="2"
:step="LORA_STRENGTH_STEP"
:disabled="disabled"
:value="displayStrength(item.strengthClip)"
:aria-label="'CLIP for ' + labelFor(item.name)"
@input="onRange(index, 'strengthClip', $event)"
>
<input
type="number"
class="lora-strength-num w-full rounded border border-[#2A2A2E] bg-[#0B0B0D] px-1 py-0.5 text-right font-mono text-[11px] text-[#F3F1EA] outline-none focus:border-[#F5A524]"
:min="0"
:max="2"
:step="LORA_STRENGTH_STEP"
:disabled="disabled"
:value="displayStrength(item.strengthClip).toFixed(2)"
:aria-label="'CLIP value'"
@change="onNumber(index, 'strengthClip', $event)"
>
</label>
</div>
</li>
</ul>
<p v-if="!clipStrength && model.length" class="mt-1 text-[11px] text-zinc-500">CLIP unused on this graph — model strength only.</p>
<select
v-if="model.length < LORA_STACK_MAX"
class="w-full rounded-xl border border-white/10 bg-zinc-950 outline-none ring-amber-300/40 focus:ring-2 disabled:opacity-50"
class="w-full rounded-lg border border-[#2A2A2E] bg-[#0B0B0D] text-[#F3F1EA] outline-none ring-[#F5A524]/40 focus:ring-2 disabled:opacity-50"
:class="[
compact ? 'px-2 py-1 text-xs' : 'px-3 py-2 text-sm',
compact ? 'px-2 py-1.5 text-xs' : 'px-3 py-2 text-sm',
model.length ? 'mt-2' : ''
]"
:disabled="disabled || !availableNames.length"
@@ -103,13 +132,55 @@
</div>
</template>
<style scoped>
.lora-strength-range {
-webkit-appearance: none;
appearance: none;
height: 6px;
border-radius: 999px;
background: #2a2a2e;
outline: none;
}
.lora-strength-range::-webkit-slider-thumb {
-webkit-appearance: none;
appearance: none;
width: 14px;
height: 14px;
border-radius: 999px;
background: #f5a524;
border: 0;
cursor: pointer;
}
.lora-strength-range::-moz-range-track {
height: 6px;
border-radius: 999px;
background: #2a2a2e;
}
.lora-strength-range::-moz-range-thumb {
width: 14px;
height: 14px;
border-radius: 999px;
background: #f5a524;
border: 0;
cursor: pointer;
}
.lora-strength-range:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.lora-strength-range::-webkit-slider-runnable-track {
height: 6px;
border-radius: 999px;
background: #2a2a2e;
}
</style>
<script setup lang="ts">
import {
LORA_STACK_MAX,
LORA_STRENGTH_MAX,
LORA_STRENGTH_MIN,
LORA_STRENGTH_DEFAULT,
LORA_STRENGTH_STEP,
clampLoraStrength,
loraDisplayName,
loraFriendlyName,
loraIdentityKey,
loraMatchesImageEngine,
@@ -120,6 +191,9 @@ import {
type LoraStackItem
} from '~/utils/loras'
const UI_MIN = 0
const UI_MAX = 2
const props = withDefaults(defineProps<{
names: string[]
filenameSubtitle?: boolean
@@ -132,7 +206,7 @@ const props = withDefaults(defineProps<{
clipStrength?: boolean
triggers?: Record<string, string>
aliases?: Record<string, string>
engine?: 'flux' | 'krea' | ''
engine?: 'flux' | 'krea' | 'moss' | ''
use?: LoraUse
}>(), {
label: 'LoRA',
@@ -160,7 +234,7 @@ const dragOverIndex = ref<number | null>(null)
const availableNames = computed(() => {
const taken = new Set(model.value.map(item => loraIdentityKey(item.name)))
const engine = props.engine === 'flux' || props.engine === 'krea' ? props.engine : null
const engine = props.engine === 'flux' || props.engine === 'krea' || props.engine === 'moss' ? props.engine : null
return props.names
.filter(name => !taken.has(loraIdentityKey(name)))
.filter(name => props.use ? loraMatchesUse(name, props.use) : !engine || loraMatchesImageEngine(name, engine))
@@ -175,6 +249,17 @@ const selectPlaceholder = computed(() => {
return model.value.length ? props.addLabel : props.emptyLabel
})
function clampUi(raw: unknown) {
const value = Number(raw)
if (!Number.isFinite(value)) return LORA_STRENGTH_DEFAULT
const snapped = Math.round(value / LORA_STRENGTH_STEP) * LORA_STRENGTH_STEP
return Math.min(UI_MAX, Math.max(UI_MIN, Math.round(snapped * 100) / 100))
}
function displayStrength(value: unknown) {
return clampUi(value ?? LORA_STRENGTH_DEFAULT)
}
function onAdd(event: Event) {
const name = (event.target as HTMLSelectElement).value
;(event.target as HTMLSelectElement).value = ''
@@ -186,7 +271,11 @@ function addLora(name: string) {
if (!item || model.value.length >= LORA_STACK_MAX) return
const taken = new Set(model.value.map(entry => loraIdentityKey(entry.name)))
if (taken.has(loraIdentityKey(item.name))) return
model.value = [...model.value, item]
model.value = [...model.value, {
...item,
strengthModel: clampUi(item.strengthModel ?? LORA_STRENGTH_DEFAULT),
strengthClip: clampUi(item.strengthClip ?? LORA_STRENGTH_DEFAULT)
}]
}
function removeAt(index: number) {
@@ -234,8 +323,22 @@ function onDragEnd() {
}
function setStrength(index: number, key: 'strengthModel' | 'strengthClip', value: number) {
const next = clampLoraStrength(value)
model.value = model.value.map((item, i) => i === index ? { ...item, [key]: next } : item)
const next = clampUi(value)
model.value = model.value.map((item, i) => {
if (i !== index) return item
if (!props.clipStrength) {
return { ...item, strengthModel: next, strengthClip: next }
}
return { ...item, [key]: next }
})
}
function onRange(index: number, key: 'strengthModel' | 'strengthClip', event: Event) {
setStrength(index, key, Number((event.target as HTMLInputElement).value))
}
function onNumber(index: number, key: 'strengthModel' | 'strengthClip', event: Event) {
setStrength(index, key, Number((event.target as HTMLInputElement).value))
}
function triggerFor(name: string) {
@@ -246,6 +349,10 @@ function labelFor(name: string) {
return loraFriendlyName(name, props.aliases)
}
function stemFor(name: string) {
return loraDisplayName(name)
}
function saveTrigger(name: string, trigger: string) {
emit('update-trigger', name, trigger)
}
+1 -1
View File
@@ -14,7 +14,7 @@
<span v-if="hidden" class="sensitive-glow block h-full w-full" />
<img
v-else
:src="`/api/library/stills/${item.stillId}?thumb=1`"
:src="`/api/library/stills/${item.stillId}?thumb=1&v=0`"
alt=""
loading="lazy"
decoding="async"
+2 -2
View File
@@ -89,7 +89,7 @@
:base-steps="draft.steps"
:base-cfg="draft.cfg"
:lora-names="loraNames"
:engine="job.payload.engine === 'krea' ? 'krea' : 'flux'"
:engine="job.payload.engine === 'krea' ? 'krea' : job.payload.engine === 'moss' ? 'moss' : 'flux'"
:allow-strength="job.payload.engine === 'krea' && Boolean(job.payload.stillId)"
:disabled="!editable"
@update:model-value="extraShots[index] = { ...$event, duration: shot.duration }"
@@ -240,7 +240,7 @@ const shots = computed(() => job.value ? queuedJobShots(currentPayload(), job.va
const thumbUrl = computed(() => {
const stillId = job.value?.payload?.stillId
if (!stillId || job.value?.payload?.hideThumbnail || job.value?.payload?.folderLocked) return ''
return `/api/library/stills/${stillId}`
return `/api/library/stills/${stillId}?v=0`
})
const loraLine = computed(() => loraStackLabel(draft.loraStack, loraAliases.value))
const loraEngine = computed(() => {
+2 -2
View File
@@ -34,7 +34,7 @@
@click="setDisplayMode('classic')"
>
<span class="block font-display text-lg font-semibold text-zinc-50">Classic</span>
<span class="mt-1 block text-xs text-zinc-400">Packed header, compact selects, tight gaps.</span>
<span class="mt-1 block text-xs text-zinc-400">packed header, dropdowns</span>
</button>
<button
type="button"
@@ -46,7 +46,7 @@
@click="setDisplayMode('studio')"
>
<span class="block font-display text-lg font-semibold text-zinc-50">Studio</span>
<span class="mt-1 block text-xs text-zinc-400">Task and model rails, locks by slots, eye toggles.</span>
<span class="mt-1 block text-xs text-zinc-400">task rail, model rail, slots + eyes</span>
</button>
</div>
</section>
+14 -5
View File
@@ -62,7 +62,7 @@
</svg>
<span class="mt-3 block font-display text-lg font-bold text-zinc-100">Image</span>
</button>
<div class="grid grid-cols-2 border-t border-white/10">
<div class="grid grid-cols-3 border-t border-white/10">
<button
type="button"
class="border-r border-white/10 px-3 py-2.5 text-left text-sm transition"
@@ -74,13 +74,22 @@
</button>
<button
type="button"
class="px-3 py-2.5 text-left text-sm transition"
class="border-r border-white/10 px-3 py-2.5 text-left text-sm transition"
:class="engineBtnClass(current === 'image' && imageEngine === 'krea')"
@click="pickImage('krea')"
>
<span class="block font-semibold">Krea</span>
<span class="text-xs opacity-80">2 Turbo</span>
</button>
<button
type="button"
class="px-3 py-2.5 text-left text-sm transition"
:class="engineBtnClass(current === 'image' && imageEngine === 'moss')"
@click="pickImage('moss')"
>
<span class="block font-semibold">MOSS</span>
<span class="text-xs opacity-80">Image</span>
</button>
</div>
</div>
@@ -111,7 +120,7 @@ const props = withDefaults(defineProps<{
ltxEnabled?: boolean
videoEngine?: 'minimax' | 'ltx'
videoStart?: 'still' | 'text'
imageEngine?: 'flux' | 'krea'
imageEngine?: 'flux' | 'krea' | 'moss'
musicEngine?: 'yue2'
}>(), {
ltxEnabled: false,
@@ -124,7 +133,7 @@ const props = withDefaults(defineProps<{
const emit = defineEmits<{
select: [kind: 'video' | 'image']
'video-engine': [engine: 'minimax' | 'ltx']
'image-engine': [engine: 'flux' | 'krea']
'image-engine': [engine: 'flux' | 'krea' | 'moss']
}>()
function engineBtnClass(active: boolean) {
@@ -137,7 +146,7 @@ function pickVideo(engine: 'minimax' | 'ltx') {
if (props.current !== 'video') emit('select', 'video')
}
function pickImage(engine: 'flux' | 'krea') {
function pickImage(engine: 'flux' | 'krea' | 'moss') {
emit('image-engine', engine)
if (props.current !== 'image') emit('select', 'image')
}
+58 -4
View File
@@ -1,8 +1,62 @@
<template>
<div class="w-36 shrink-0 space-y-2"><span class="text-xs text-zinc-400">{{ label }}</span><button class="flex h-24 w-full items-center justify-center overflow-hidden rounded-xl border border-white/15 bg-black" @click="$emit('pick')"><span v-if="asset && hidden" class="p-2 text-xs text-zinc-400">Still loaded · preview hidden</span><img v-else-if="asset" :src="asset.kind==='clip'?`/api/library/clips/${asset.id}/thumb`:`/api/library/stills/${asset.id}`" class="h-full w-full object-contain" :alt="label"><span v-else class="text-xs text-zinc-400">Choose {{ label.toLowerCase() }}</span></button><p v-if="asset" class="truncate text-xs" :title="assetLabel(asset)">{{ assetLabel(asset) }}</p><label v-if="upload" class="block cursor-pointer text-xs text-amber-200">Upload {{ label.toLowerCase() }}<input type="file" accept="image/*" class="sr-only" :disabled="disabled" @change="$emit('upload',$event)"></label></div>
<div class="photo-card">
<button
type="button"
class="slot-thumb"
:class="asset ? 'slot-thumb--slot' : 'slot-thumb--empty'"
:aria-label="asset ? 'Replace photo' : 'Choose a photo'"
@click="$emit('pick')"
>
<span v-if="asset && hidden" class="p-2 text-center text-[var(--type-sm)] text-[var(--muted)]">Photo loaded</span>
<img v-else-if="asset" :src="thumbSrc" alt="">
<span v-else class="inline-flex flex-col items-center gap-1 px-2 text-center">
<span>Choose a photo</span>
</span>
</button>
<div class="photo-card-body">
<label class="photo-role-label">
<span class="field-label">This photo is:</span>
<select
class="field-control photo-role-select"
:value="role"
:disabled="readonly"
@change="$emit('update:role', ($event.target as HTMLSelectElement).value)"
>
<option v-for="opt in roleOptions" :key="opt.id" :value="opt.id">{{ opt.label }}</option>
</select>
</label>
<div class="slot-actions">
<button
v-if="!readonly && asset"
type="button"
class="slot-token-btn"
title="Mention this photo in the prompt"
@click.stop="$emit('mention')"
>Mention in prompt</button>
<button
v-if="!readonly && asset"
type="button"
@click.stop="$emit('pick')"
>Replace</button>
<button v-if="!readonly" type="button" @click.stop="$emit('remove')">Remove</button>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import {assetLabel} from '~/shared/studio2/viewer.mjs'
defineProps<{label:string;asset?:any;hidden?:boolean;upload?:boolean;disabled?:boolean}>()
defineEmits(['pick','upload'])
import { libraryMediaUrl } from '~/shared/studio2/viewer.mjs'
const props = withDefaults(defineProps<{
asset?: any
hidden?: boolean
role: string
roleOptions: { id: string; label: string }[]
readonly?: boolean
version?: string | number
}>(), { readonly: false, hidden: false, version: 0 })
defineEmits(['pick', 'remove', 'mention', 'update:role'])
const thumbSrc = computed(() => {
if (!props.asset?.id) return ''
if (props.asset.kind === 'clip') return libraryMediaUrl(`/api/library/clips/${props.asset.id}/thumb`, props.version)
return libraryMediaUrl(`/api/library/stills/${props.asset.id}/thumb`, props.version)
})
</script>
+2258 -301
View File
File diff suppressed because it is too large Load Diff
+27 -1
View File
@@ -5,6 +5,18 @@
</template>
<script setup lang="ts">
const props=defineProps<{metadata?:any}>()
function promptRows(m:any){
const used=String(m.prompt || m.compiledPrompt || '').trim()
const typed=String(m.promptRaw || '').trim()
if(typed && typed!==used){
return [
{label:'Typed',value:typed},
...(used?[{label:'Used',value:used}]:[])
]
}
if(used) return [{label:'Prompt',value:used}]
return []
}
const rows=computed(()=>{const m=props.metadata||{},s=m.settings||{};const time=(v:any)=>v?new Date(v).toLocaleString():null;return [
{label:'Kind / mode',value:[m.kind,m.mode].filter(Boolean).join(' / ')},
{label:'Engine',value:m.engine},{label:'Graph ID',value:m.graphId},
@@ -19,7 +31,21 @@ const rows=computed(()=>{const m=props.metadata||{},s=m.settings||{};const time=
{label:'Start frame',value:m.startFrameSource?JSON.stringify(m.startFrameSource):'None'},
{label:'Handoff source',value:m.handoffSource || 'None'},{label:'Handoff fitted (resampled)',value:m.fitted==null?'Not recorded':m.fitted?'Yes':'No'},
{label:'End still',value:m.endStillId||'None'},{label:'Guide stills',value:m.guides?.length?JSON.stringify(m.guides):'None'},
{label:'Compiled prompt',value:m.compiledPrompt},{label:'Queued',value:time(m.queuedAt)},{label:'Started',value:time(m.startedAt)},{label:'Saved',value:time(m.savedAt)},
...promptRows(m),
{label:'Task',value:m.task || m.mode || null},
{label:'Enhance prompt',value:m.enhancePrompt==null?null:m.enhancePrompt?'On':'Off'},
{label:'Enhance',value:m.enhance?.refused?'Enhance skipped (model refused) — used your prompt.':m.enhance?.skippedAsDescribe?'Enhance skipped (describe rewrite) — keep stanza + typed only.':m.enhance?.used?'Applied':m.enhance?.parse_ok==null?null:m.enhance.parse_ok?'Applied':'Parse incomplete'},
{label:'Enhance used',value:m.enhance?.used==null?null:m.enhance.used?'Yes':'No'},
{label:'Enhance refused',value:m.enhance?.refused==null?null:m.enhance.refused?'Yes':'No'},
{label:'Enhance skip reason',value:m.enhance?.skipReason || (m.enhance?.skippedAsDescribe?'skippedAsDescribe':null)},
{label:'Turbo',value:m.turbo==null?null:m.turbo?'On':'Off'},
{label:'Turbo LoRA',value:m.lora || null},
{label:'Turbo sigmas',value:m.sigmas || null},
{label:'Enhance wh_ratio',value:m.enhance?.wh_ratio || null},
{label:'Enhance ratio_follow',value:m.enhance?.ratio_follow || null},
{label:'Enhance parse_ok',value:m.enhance?.parse_ok==null?null:m.enhance.parse_ok?'Yes':'No'},
{label:'Enhance thinking',value:m.enhance?.thinking || null},
{label:'Queued',value:time(m.queuedAt)},{label:'Started',value:time(m.startedAt)},{label:'Saved',value:time(m.savedAt)},
{label:'GPU seconds',value:m.gpuSeconds},{label:'Wall seconds',value:m.wallTime},{label:'Comfy prompt ID',value:m.promptId},{label:'Host cleanup',value:m.purgeResult}
]})
</script>
+7 -1
View File
@@ -2,7 +2,8 @@
<div class="space-y-2 rounded-xl border border-white/10 p-3 text-sm" aria-live="polite">
<div class="flex justify-between gap-3"><button class="text-left" @click="$emit('select')"><strong>{{ job.request.promptSections.action.slice(0,70) }}</strong><span class="block capitalize text-amber-200">{{ job.state==='waiting'?'queued':job.state }} · Shot {{ shot }}/{{ total }}</span></button><button v-if="!terminal" @click="$emit('cancel')">Cancel</button></div>
<p>{{ elapsed }} {{ job.startedAt?'elapsed':'waiting' }} · {{ job.request.settings.duration }}s target<span v-if="job.state==='rendering' && job.progress"> · Step {{ job.progress.step }}/{{ job.progress.maxStep }} ({{ job.progress.percent }}%)</span></p>
<progress v-if="job.state==='rendering'" class="h-2 w-full accent-amber-300" :value="job.progress?.percent" max="100" />
<progress v-if="job.state==='enhancing'" class="h-2 w-full accent-amber-300" max="100" :value="enhancePercent" />
<progress v-else-if="job.state==='rendering'" class="h-2 w-full accent-amber-300" :value="job.progress?.percent" max="100" />
<p v-if="job.error" role="alert" class="text-red-300">{{ job.error }}</p>
</div>
</template>
@@ -13,4 +14,9 @@ const terminal=computed(()=>['complete','failed','cancelled'].includes(props.job
const total=computed(()=>props.job.prompts?.length || (props.job.request.batch?.length || 0)+1)
const shot=computed(()=>Math.min(total.value,(props.job.index || 0)+1))
const elapsed=computed(()=>{const seconds=elapsedSeconds(props.job,props.now);return `${Math.floor(seconds/60)}m ${seconds%60}s`})
const enhancePercent=computed(()=>{
const p=props.job.progress
if(p && Number(p.maxStep)>0) return Number(p.percent)||Math.round(Number(p.step)/Number(p.maxStep)*100)
return undefined // indeterminate while PE runs without Comfy step events
})
</script>
+899
View File
@@ -0,0 +1,899 @@
<template>
<Teleport to="body">
<div
v-if="open"
class="lib-modal-root"
role="presentation"
@keydown.esc.prevent="close"
>
<div class="lib-modal-backdrop" @click="close" />
<section
ref="dialogEl"
class="lib-modal"
role="dialog"
aria-modal="true"
aria-labelledby="lib-modal-title"
tabindex="-1"
@keydown.tab="onTab"
>
<header class="lib-modal-head">
<h2 id="lib-modal-title">Library</h2>
<div class="lib-modal-head-actions">
<NuxtLink
class="lib-modal-full"
:to="{ path: '/library', query: activeFolderId && activeFolderId !== 'all' ? { folder: activeFolderId } : {} }"
@click="close"
>Full library</NuxtLink>
<button type="button" class="lib-modal-x" aria-label="Close" @click="close">×</button>
</div>
</header>
<div class="lib-modal-toolbar">
<input
v-model="query"
type="search"
class="lib-modal-search"
placeholder="Name or prompt"
aria-label="Search library"
>
<button
type="button"
class="lib-modal-preview-all"
@click="$emit('toggle-preview')"
>{{ previewHidden ? 'Show all previews' : 'Hide all previews' }}</button>
<button
v-if="canWipeFolder"
type="button"
class="lib-modal-wipe"
:disabled="wipeBusy"
@click="askWipeFolder"
>Delete all in this folder</button>
<div class="lib-modal-filters" role="group" aria-label="Type">
<button
v-for="opt in filterOptions"
:key="opt.id"
type="button"
class="lib-modal-chip"
:data-on="filter === opt.id ? 'true' : undefined"
@click="filter = opt.id"
>{{ opt.label }}</button>
</div>
</div>
<div
v-if="pendingWipe"
class="lib-modal-confirm"
role="dialog"
aria-modal="true"
>
<div class="lib-modal-confirm-card">
<h3>Delete all in this folder?</h3>
<p class="lib-modal-confirm-name">{{ pendingWipe.name }}</p>
<p class="lib-modal-confirm-detail">{{ pendingWipe.count }} item{{ pendingWipe.count === 1 ? '' : 's' }} · images, videos, and music</p>
<p class="lib-modal-confirm-body">Every still, clip, and track in this folder will be permanently removed from the library and disk.</p>
<div class="lib-modal-confirm-actions">
<button type="button" @click="pendingWipe = null">Keep them</button>
<button type="button" class="danger" :disabled="wipeBusy" @click="confirmWipeFolder">Delete all</button>
</div>
</div>
</div>
<div class="lib-modal-body">
<div ref="gridScrollEl" class="lib-modal-grid" aria-label="Folder assets">
<p v-if="loading && !entries.length" class="lib-modal-empty">Loading library…</p>
<p v-else-if="loadError" class="lib-modal-empty">{{ loadError }}</p>
<p v-else-if="!entries.length" class="lib-modal-empty">No items in this folder yet.</p>
<article
v-for="entry in entries"
:key="entry.key"
class="lib-modal-tile"
:data-thumb-key="entry.key"
:data-active="entry.key === focusedKey ? 'true' : undefined"
@click="pickEntry(entry)"
>
<div class="lib-modal-media">
<div
v-if="entry.kind === 'track'"
class="lib-modal-track"
aria-hidden="true"
>
<span
v-for="n in 16"
:key="n"
class="lib-modal-bar"
:style="{ height: `${20 + ((n * 17) % 60)}%` }"
/>
</div>
<img
v-else-if="!previewHidden && liveThumbs.has(entry.key) && thumbSrc(entry)"
:src="thumbSrc(entry)"
alt=""
loading="lazy"
decoding="async"
draggable="false"
>
<span v-else class="lib-modal-fallback">{{ previewHidden ? 'Hidden' : '' }}</span>
<span class="lib-modal-kind">
{{ entry.kind === 'clip' ? 'Video' : entry.kind === 'track' ? 'Music' : 'Image' }}
</span>
</div>
<div class="lib-modal-caption">
<p class="lib-modal-name">{{ entry.name }}</p>
<p class="lib-modal-meta">{{ cardMeta(entry) }}</p>
</div>
</article>
</div>
<aside v-if="entries.length && detailAsset" class="lib-modal-detail">
<p class="lib-modal-detail-name">{{ detailLabel }}</p>
<div v-if="detailAsset.kind !== 'track'" class="lib-modal-actions">
<button type="button" @click="$emit('use-image', detailAsset)">Use image</button>
<button type="button" @click="$emit('use-prompt', detailAsset)">Use prompt</button>
<button type="button" @click="$emit('copy-prompt', detailAsset)">Copy prompt</button>
<button type="button" @click="$emit('copy-raw-prompt', detailAsset)">Copy raw prompt</button>
<button type="button" @click="$emit('load-input', detailAsset)">Load input</button>
<button type="button" @click="$emit('load-input-raw', detailAsset)">Load input raw</button>
<button type="button" @click="$emit('toggle-preview')">{{ previewHidden ? 'Show output' : 'Hide output' }}</button>
<button type="button" class="danger" @click="onDeleteClick">Delete</button>
<button type="button" class="primary" @click="useAndClose">Use and close</button>
</div>
<LibrarySettingsDetails :rows="detailRows" empty="No generator settings were saved with this item." />
</aside>
</div>
</section>
</div>
</Teleport>
</template>
<script setup lang="ts">
import {
buildLibraryEntries,
formatClipDuration,
formatWhen,
type LibraryClip,
type LibraryEntry,
type LibraryFilter,
type LibraryFolder,
type LibraryStill,
type LibraryTrack
} from '~/utils/libraryBrowse'
import { clipSettingsRows, stillSettingsRows, trackSettingsRows } from '~/utils/libraryGeneration'
import { assetLabel, libraryAfterWipe, libraryMediaUrl, mergeLibraryRows } from '~/shared/studio2/viewer.mjs'
const props = defineProps<{
open: boolean
assets?: any[]
selected?: any
folderId?: string
previewHidden?: boolean
isHidden?: (asset: any) => boolean
refreshKey?: number
hiddenIds?: string[]
}>()
const emit = defineEmits<{
close: []
select: [asset: any]
'use-image': [asset: any]
'use-prompt': [asset: any]
'copy-prompt': [asset: any]
'copy-raw-prompt': [asset: any]
'load-input': [asset: any]
'load-input-raw': [asset: any]
delete: [asset: any]
wiped: [payload: any]
'toggle-preview': []
}>()
const filterOptions = [
{ id: 'all' as const, label: 'All' },
{ id: 'images' as const, label: 'Images' },
{ id: 'videos' as const, label: 'Videos' },
{ id: 'music' as const, label: 'Music' }
]
const query = ref('')
const filter = ref<LibraryFilter>('all')
const dialogEl = ref<HTMLElement | null>(null)
const gridScrollEl = ref<HTMLElement | null>(null)
const loading = ref(false)
const loadError = ref('')
const folders = ref<LibraryFolder[]>([])
const clips = ref<LibraryClip[]>([])
const stills = ref<LibraryStill[]>([])
const tracks = ref<LibraryTrack[]>([])
const fetchedAt = ref(0)
const nextCursor = ref<string | null>(null)
const liveThumbs = ref(new Set<string>())
const catalogEpoch = ref(0)
const wipeBusy = ref(false)
const pendingWipe = ref<{ folderId: string; name: string; count: number } | null>(null)
let thumbObserver: IntersectionObserver | null = null
let scrollLoadBound = false
const activeFolderId = computed(() => props.folderId || folders.value[0]?.id || 'all')
const activeFolder = computed(() => folders.value.find(folder => folder.id === activeFolderId.value) || null)
const folderAssetCount = computed(() => {
const id = activeFolderId.value
if (!id || id === 'all') return 0
return stills.value.filter(item => item.folderId === id).length
+ clips.value.filter(item => item.folderId === id).length
+ tracks.value.filter(item => item.folderId === id).length
})
const canWipeFolder = computed(() => Boolean(activeFolder.value && activeFolderId.value !== 'all' && folderAssetCount.value > 0))
const entries = computed(() => buildLibraryEntries({
clips: clips.value,
stills: stills.value,
tracks: tracks.value,
folderId: activeFolderId.value,
filter: filter.value,
search: query.value,
sort: 'date-desc'
}))
const dismissedId = ref('')
function entryHasId(entry: LibraryEntry, id: string) {
if (!id) return false
if (entry.kind === 'clip' && entry.group) {
return entry.group.head.id === id || entry.group.parts.some(part => part.id === id)
}
if (entry.kind === 'track' && entry.track) return entry.track.id === id
if (entry.stillGroup) {
return entry.stillGroup.head.id === id || entry.stillGroup.parts.some(part => part.id === id)
}
return false
}
const focusedKey = computed(() => {
const id = props.selected?.id
if (!id || id === dismissedId.value) return ''
const hit = entries.value.find(entry => entryHasId(entry, id))
return hit?.key || ''
})
const detailAsset = computed(() => {
if (!entries.value.length) return null
const id = String(props.selected?.id || '')
if (id && id === dismissedId.value) return null
if (id) {
const hit = entries.value.find(entry => entryHasId(entry, id))
return hit ? assetFromEntry(hit) : null
}
const first = entries.value[0]
return first ? assetFromEntry(first) : null
})
watch(() => props.selected?.id, (id) => {
if (id && id !== dismissedId.value) dismissedId.value = ''
})
const detailLabel = computed(() => assetLabel(detailAsset.value))
const detailRows = computed(() => {
const item = detailAsset.value
if (!item) return []
if (item.kind === 'clip') return clipSettingsRows(item)
if (item.kind === 'track') return trackSettingsRows(item)
return stillSettingsRows(item)
})
function thumbSrc(entry: LibraryEntry) {
const version = catalogEpoch.value
if (entry.kind === 'clip' && entry.group) return libraryMediaUrl(`/api/library/clips/${entry.group.head.id}/thumb`, version)
if (entry.kind === 'track') return ''
if (entry.stillGroup) {
const id = entry.stillGroup.head.id
if (!stills.value.some(item => item.id === id)) return ''
return libraryMediaUrl(`/api/library/stills/${id}/thumb`, version)
}
return ''
}
function cardMeta(entry: LibraryEntry) {
if (entry.kind === 'clip' && entry.group) {
return [formatClipDuration(entry.group.head.duration), formatWhen(entry.createdAt)].filter(Boolean).join(' · ')
}
if (entry.kind === 'track' && entry.track) {
return [formatClipDuration(entry.track.duration), formatWhen(entry.createdAt)].filter(Boolean).join(' · ')
}
return formatWhen(entry.createdAt)
}
function assetFromEntry(entry: LibraryEntry) {
if (entry.kind === 'clip' && entry.group) return { ...entry.group.head, kind: 'clip' as const }
if (entry.kind === 'track' && entry.track) return { ...entry.track, kind: 'track' as const }
if (entry.stillGroup) return { ...entry.stillGroup.head, kind: 'still' as const }
return null
}
function pickEntry(entry: LibraryEntry) {
const asset = assetFromEntry(entry)
if (!asset) return
const fromFamily = (props.assets || []).find((a: any) => a.id === asset.id)
emit('select', fromFamily ? { ...asset, ...fromFamily, kind: asset.kind } : asset)
}
function close() { emit('close') }
function useAndClose() {
if (detailAsset.value) emit('use-image', detailAsset.value)
close()
}
function onDeleteClick() {
const asset = detailAsset.value
if (!asset?.id) return
const id = String(asset.id)
dismissedId.value = id
stills.value = stills.value.filter(item => item.id !== id)
clips.value = clips.value.filter(item => item.id !== id)
tracks.value = tracks.value.filter(item => item.id !== id)
emit('select', null)
emit('delete', asset)
}
function applyLibraryPage(data: any, replace: boolean) {
if (Array.isArray(data?.folders) && data.folders.length) folders.value = data.folders
if (typeof data?.catalogEpoch === 'number') catalogEpoch.value = data.catalogEpoch
const rows = (list: any[]) => (Array.isArray(list) ? list : []).filter(item => item?.id)
if (replace) {
clips.value = rows(data?.clips) as LibraryClip[]
stills.value = rows(data?.stills) as LibraryStill[]
tracks.value = rows(data?.tracks) as LibraryTrack[]
} else {
clips.value = mergeLibraryRows(clips.value, data?.clips || [], []) as LibraryClip[]
stills.value = mergeLibraryRows(stills.value, data?.stills || [], []) as LibraryStill[]
tracks.value = mergeLibraryRows(tracks.value, data?.tracks || [], []) as LibraryTrack[]
}
nextCursor.value = data?.nextCursor ?? null
fetchedAt.value = Date.now()
}
function askWipeFolder() {
if (!activeFolder.value || activeFolderId.value === 'all' || wipeBusy.value) return
const count = folderAssetCount.value
if (!count) return
pendingWipe.value = {
folderId: activeFolderId.value,
name: activeFolder.value.name,
count
}
}
async function confirmWipeFolder() {
const pending = pendingWipe.value
if (!pending || wipeBusy.value) return
pendingWipe.value = null
wipeBusy.value = true
fetchGen += 1
const gone = [
...stills.value.filter(item => item.folderId === pending.folderId).map(item => item.id),
...clips.value.filter(item => item.folderId === pending.folderId).map(item => item.id),
...tracks.value.filter(item => item.folderId === pending.folderId).map(item => item.id)
]
stills.value = stills.value.filter(item => item.folderId !== pending.folderId)
clips.value = clips.value.filter(item => item.folderId !== pending.folderId)
tracks.value = tracks.value.filter(item => item.folderId !== pending.folderId)
try {
const result = await $fetch<any>(`/api/library/folders/${pending.folderId}/wipe`, { method: 'POST' })
const next = libraryAfterWipe({
folders: folders.value,
stills: [...stills.value, ...gone.map(id => ({ id, folderId: pending.folderId }))],
clips: clips.value,
tracks: tracks.value,
suppressedIds: []
}, result, pending.folderId)
if (typeof result?.catalogEpoch === 'number') catalogEpoch.value = result.catalogEpoch
folders.value = next.folders
stills.value = next.stills as LibraryStill[]
clips.value = next.clips as LibraryClip[]
tracks.value = next.tracks as LibraryTrack[]
nextCursor.value = null
fetchedAt.value = 0
emit('wiped', { ...result, folderId: pending.folderId, deletedIds: [...new Set([...(result?.deletedIds || []), ...gone])] })
await fetchLibrary(true)
} catch (e: any) {
loadError.value = e?.data?.statusMessage || e?.message || 'Could not empty that folder'
await fetchLibrary(true)
} finally {
wipeBusy.value = false
}
}
async function fetchLibraryPage(cursor: string | null) {
const folder = activeFolderId.value && activeFolderId.value !== 'all' ? activeFolderId.value : ''
const type = filter.value === 'all' ? 'all' : filter.value === 'images' ? 'images' : filter.value === 'videos' ? 'videos' : 'music'
const qs = new URLSearchParams({ limit: '50', _: String(Date.now()) })
if (folder) qs.set('folderId', folder)
if (type !== 'all') qs.set('type', type)
if (cursor) qs.set('cursor', cursor)
return await $fetch<any>(`/api/library?${qs.toString()}`)
}
let fetchGen = 0
async function fetchLibrary(force = false) {
const stale = !fetchedAt.value || Date.now() - fetchedAt.value > 15_000
const empty = !stills.value.length && !clips.value.length && !tracks.value.length
if (!force && !empty && !stale) return
const gen = ++fetchGen
loading.value = true
loadError.value = ''
liveThumbs.value = new Set()
try {
const first = await fetchLibraryPage(null)
if (gen !== fetchGen) return
applyLibraryPage(first, true)
loading.value = false
nextTick(() => observeThumbs())
// Keep fetching until the folder is exhausted — 50 is a page size, not a cap
let cursor = first?.nextCursor || null
while (cursor && gen === fetchGen) {
const more = await fetchLibraryPage(cursor)
if (gen !== fetchGen) return
applyLibraryPage(more, false)
cursor = more?.nextCursor || null
nextTick(() => observeThumbs())
}
} catch (e: any) {
if (gen !== fetchGen) return
loadError.value = e?.data?.statusMessage || e?.message || 'Could not load library'
loading.value = false
}
}
function observeThumbs() {
if (!import.meta.client) return
const root = gridScrollEl.value
if (!root) return
if (thumbObserver) thumbObserver.disconnect()
thumbObserver = new IntersectionObserver((entries) => {
let changed = false
const next = new Set(liveThumbs.value)
for (const entry of entries) {
if (!entry.isIntersecting) continue
const key = (entry.target as HTMLElement).dataset.thumbKey
if (!key || next.has(key)) continue
next.add(key)
changed = true
}
if (changed) liveThumbs.value = next
}, { root, rootMargin: '200px 0px', threshold: 0.01 })
root.querySelectorAll<HTMLElement>('[data-thumb-key]').forEach((el) => thumbObserver!.observe(el))
}
function onGridScroll() {
const el = gridScrollEl.value
if (!el || !nextCursor.value || loading.value) return
if (el.scrollTop + el.clientHeight < el.scrollHeight - 240) return
void fetchMore()
}
async function fetchMore() {
if (!nextCursor.value || loading.value) return
loading.value = true
try {
const more = await fetchLibraryPage(nextCursor.value)
applyLibraryPage(more, false)
nextTick(() => observeThumbs())
} catch { /* keep what we have */ }
finally { loading.value = false }
}
function onTab(e: KeyboardEvent) {
const root = dialogEl.value
if (!root) return
const focusable = [...root.querySelectorAll<HTMLElement>(
'button:not([disabled]), a[href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])'
)].filter(el => el.offsetParent !== null || el === document.activeElement)
if (!focusable.length) return
const first = focusable[0]
const last = focusable[focusable.length - 1]
if (e.shiftKey && document.activeElement === first) {
e.preventDefault()
last.focus()
} else if (!e.shiftKey && document.activeElement === last) {
e.preventDefault()
first.focus()
}
}
watch(() => props.open, (on) => {
if (!import.meta.client) return
if (on) {
document.body.style.overflow = 'hidden'
void fetchLibrary(true)
nextTick(() => {
dialogEl.value?.focus()
if (gridScrollEl.value) {
gridScrollEl.value.scrollTop = 0
if (!scrollLoadBound) {
gridScrollEl.value.addEventListener('scroll', onGridScroll, { passive: true })
scrollLoadBound = true
}
observeThumbs()
}
})
} else {
document.body.style.overflow = ''
thumbObserver?.disconnect()
thumbObserver = null
}
})
watch(entries, () => nextTick(() => observeThumbs()))
watch([filter, activeFolderId], () => {
if (!props.open) return
pendingWipe.value = null
void fetchLibrary(true)
})
watch(() => props.refreshKey, () => {
if (!props.open) return
fetchGen += 1
void fetchLibrary(true)
})
watch(() => (props.hiddenIds || []).join('\n'), () => {
const drop = new Set(props.hiddenIds || [])
if (!drop.size) return
stills.value = stills.value.filter(item => !drop.has(item.id))
clips.value = clips.value.filter(item => !drop.has(item.id))
tracks.value = tracks.value.filter(item => !drop.has(item.id))
})
onBeforeUnmount(() => {
if (import.meta.client) {
document.body.style.overflow = ''
gridScrollEl.value?.removeEventListener('scroll', onGridScroll)
thumbObserver?.disconnect()
}
})
</script>
<style scoped>
.lib-modal-root {
position: fixed;
inset: 0;
z-index: 80;
display: flex;
align-items: stretch;
justify-content: center;
}
.lib-modal-backdrop {
position: absolute;
inset: 0;
background: #000a;
}
.lib-modal {
position: relative;
z-index: 1;
display: flex;
width: min(1100px, 100%);
max-height: min(92vh, 900px);
height: min(92vh, 900px);
margin: auto;
flex-direction: column;
overflow: hidden;
border: 1px solid #2a2a2e;
border-radius: 12px;
background: #141416;
color: #f3f1ea;
outline: none;
}
@media (max-width: 767px) {
.lib-modal-root { align-items: flex-end; }
.lib-modal {
width: 100%;
max-height: 100dvh;
height: 100dvh;
margin: 0;
border-radius: 16px 16px 0 0;
}
}
.lib-modal-head {
display: flex;
flex-shrink: 0;
align-items: center;
justify-content: space-between;
gap: 12px;
border-bottom: 1px solid #2a2a2e;
padding: 12px 16px;
}
.lib-modal-head h2 {
margin: 0;
font-size: 1.1rem;
font-weight: 700;
}
.lib-modal-head-actions {
display: flex;
align-items: center;
gap: 10px;
}
.lib-modal-full {
color: #f5a524;
font-size: 0.85rem;
text-decoration: none;
}
.lib-modal-x {
display: grid;
width: 40px;
height: 40px;
place-items: center;
border: 1px solid #2a2a2e;
border-radius: 8px;
background: transparent;
color: inherit;
font-size: 1.4rem;
line-height: 1;
cursor: pointer;
}
.lib-modal-toolbar {
display: flex;
flex-shrink: 0;
flex-wrap: wrap;
gap: 10px;
align-items: center;
border-bottom: 1px solid #2a2a2e;
padding: 10px 16px;
}
.lib-modal-search {
min-width: 12rem;
flex: 1;
border: 1px solid #2a2a2e;
border-radius: 8px;
background: #0b0b0d;
padding: 8px 10px;
color: inherit;
font: inherit;
}
.lib-modal-preview-all {
border: 1px solid #2a2a2e;
border-radius: 8px;
background: transparent;
color: inherit;
padding: 8px 10px;
font: inherit;
font-size: 12px;
cursor: pointer;
white-space: nowrap;
}
.lib-modal-preview-all:hover {
border-color: #f5a524;
color: #f5a524;
}
.lib-modal-wipe {
border: 1px solid #5c2a2a;
border-radius: 8px;
background: transparent;
color: #f0a0a0;
padding: 8px 10px;
font: inherit;
font-size: 12px;
cursor: pointer;
white-space: nowrap;
}
.lib-modal-wipe:hover:not(:disabled) {
border-color: #e07070;
color: #ffc0c0;
}
.lib-modal-wipe:disabled { opacity: 0.5; cursor: default; }
.lib-modal-confirm {
position: absolute;
inset: 0;
z-index: 5;
display: flex;
align-items: center;
justify-content: center;
background: #000a;
padding: 16px;
}
.lib-modal-confirm-card {
width: min(420px, 100%);
border: 1px solid #2a2a2e;
border-radius: 12px;
background: #1a1a1e;
padding: 18px;
}
.lib-modal-confirm-card h3 {
margin: 0;
font-size: 18px;
}
.lib-modal-confirm-name {
margin: 10px 0 0;
font-weight: 600;
}
.lib-modal-confirm-detail {
margin: 4px 0 0;
font-size: 12px;
color: #9a9588;
}
.lib-modal-confirm-body {
margin: 12px 0 0;
font-size: 13px;
color: #c8c4b8;
}
.lib-modal-confirm-actions {
display: flex;
justify-content: flex-end;
gap: 8px;
margin-top: 16px;
}
.lib-modal-confirm-actions button {
border: 1px solid #2a2a2e;
border-radius: 999px;
background: transparent;
color: inherit;
padding: 8px 14px;
font: inherit;
font-size: 13px;
cursor: pointer;
}
.lib-modal-confirm-actions button.danger {
border-color: #5c2a2a;
color: #f0a0a0;
}
.lib-modal-filters { display: inline-flex; gap: 4px; }
.lib-modal-chip {
border: 1px solid #2a2a2e;
border-radius: 999px;
background: transparent;
color: #9a9588;
padding: 6px 10px;
font: inherit;
font-size: 12px;
cursor: pointer;
}
.lib-modal-chip[data-on='true'] {
border-color: #f5a524;
background: #f5a52422;
color: #f5a524;
}
.lib-modal-body {
display: flex;
min-height: 0;
flex: 1;
overflow: hidden;
}
@media (max-width: 767px) {
.lib-modal-body { flex-direction: column; }
}
.lib-modal-grid {
display: grid;
flex: 1;
min-width: 0;
min-height: 0;
height: 100%;
grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
gap: 8px;
align-content: start;
overflow: auto;
padding: 14px 16px;
}
.lib-modal-tile {
display: flex;
min-height: 120px;
flex-direction: column;
overflow: hidden;
border: 2px solid #2a2a2e;
border-radius: 8px;
background: #0b0b0d;
cursor: pointer;
}
.lib-modal-tile[data-active='true'] {
border-color: #f5a524;
box-shadow: 0 0 0 2px #f5a524;
}
.lib-modal-media {
position: relative;
aspect-ratio: 1 / 1;
min-height: 120px;
width: 100%;
overflow: hidden;
background: #18181b;
}
.lib-modal-media > img {
display: block;
width: 100%;
height: 100%;
object-fit: cover;
}
.lib-modal-fallback {
display: block;
width: 100%;
height: 100%;
background: #27272a;
}
.lib-modal-track {
display: flex;
height: 100%;
width: 100%;
align-items: flex-end;
gap: 2px;
padding: 16px;
}
.lib-modal-bar {
flex: 1;
border-radius: 999px;
background: rgba(245, 165, 36, 0.7);
}
.lib-modal-kind {
position: absolute;
top: 8px;
left: 8px;
border-radius: 4px;
background: #000a;
padding: 2px 6px;
color: #e4e4e7;
font-size: 10px;
text-transform: uppercase;
letter-spacing: 0.04em;
}
.lib-modal-caption {
padding: 6px 8px 8px;
}
.lib-modal-name {
margin: 0;
overflow: hidden;
color: #f4f4f5;
font-size: 12px;
font-weight: 600;
text-overflow: ellipsis;
white-space: nowrap;
}
.lib-modal-meta {
margin: 2px 0 0;
overflow: hidden;
color: #71717a;
font-size: 11px;
text-overflow: ellipsis;
white-space: nowrap;
}
.lib-modal-empty {
grid-column: 1 / -1;
color: #9a9588;
font-size: 0.9rem;
}
.lib-modal-detail {
flex: 0 0 min(320px, 38%);
min-width: 0;
min-height: 0;
overflow: auto;
border-left: 1px solid #2a2a2e;
padding: 14px 16px;
}
@media (max-width: 767px) {
.lib-modal-detail {
flex: 0 0 auto;
max-height: 40%;
border-left: 0;
border-top: 1px solid #2a2a2e;
}
}
.lib-modal-detail-name {
margin: 0 0 10px;
font-weight: 600;
}
.lib-modal-actions {
display: flex;
flex-wrap: wrap;
gap: 6px;
margin-bottom: 14px;
}
.lib-modal-actions button {
border: 1px solid #2a2a2e;
border-radius: 6px;
background: transparent;
color: inherit;
padding: 6px 10px;
font: inherit;
font-size: 12px;
cursor: pointer;
}
.lib-modal-actions button.primary {
border-color: #f5a524;
background: #f5a524;
color: #1a1204;
font-weight: 700;
}
.lib-modal-actions button.danger { color: #fca5a5; }
</style>
+894
View File
@@ -0,0 +1,894 @@
<template>
<div class="m-shell" data-mobile="1" :data-queue-collapsed="queueRailCollapsed ? '1' : undefined">
<header class="m-header">
<span class="m-brand">{{ ctx.instanceName }}</span>
<label class="m-crumb">
<select v-model="ctx.form.folderId" aria-label="Folder">
<option v-for="f in ctx.library.folders" :key="f.id" :value="f.id">{{ f.name }}</option>
</select>
</label>
<span class="m-grow" />
<span class="m-gpu" :data-tone="ctx.gpu.tone" :title="ctx.gpu.detail">● {{ ctx.gpuChipLabel }}</span>
<button type="button" class="m-chip m-queue-chip-portrait" @click="toggleSheet('queue')">Queue {{ ctx.queueCount }}</button>
<button type="button" class="m-chip m-queue-chip-landscape" :aria-expanded="queueRailCollapsed ? 'false' : 'true'" @click="queueRailCollapsed=!queueRailCollapsed">
Queue {{ ctx.queueCount }} {{ queueRailCollapsed ? '▸' : '▾' }}
</button>
<details class="m-more">
<summary aria-label="More">⋯</summary>
<div class="m-more-menu">
<NuxtLink to="/library" @click="closeMenus">Library</NuxtLink>
<NuxtLink to="/prompt-builder" @click="closeMenus">Prompt Builder</NuxtLink>
<NuxtLink to="/queue" @click="closeMenus">Queue</NuxtLink>
<NuxtLink to="/settings" @click="closeMenus">Settings</NuxtLink>
</div>
</details>
</header>
<div class="m-chips" role="tablist" aria-label="Tasks">
<button
v-for="task in ctx.tasks"
:key="task"
type="button"
class="m-chip capitalize"
:class="{ on: ctx.form.mode===task }"
:aria-pressed="ctx.form.mode===task"
@click="ctx.chooseTask(task)"
>{{ task }}</button>
</div>
<div v-if="ctx.form.mode!=='music'" class="m-chips" role="group" aria-label="Model">
<button
v-for="opt in ctx.engineOptions"
:key="opt.value"
type="button"
class="m-chip"
:class="{ on: ctx.form.engine===opt.value }"
:disabled="opt.disabled"
:title="opt.hint || undefined"
:aria-pressed="ctx.form.engine===opt.value"
@click="!opt.disabled && (ctx.form.engine=opt.value)"
>{{ opt.label }}</button>
</div>
<div v-else class="m-chips"><span class="m-chip on">YuE2</span></div>
<div
class="m-stage"
:class="{ 'm-stage--veiled': ctx.selected && ctx.isHidden(ctx.selected) }"
@touchstart.passive="onStageTouchStart"
@touchend.passive="onStageTouchEnd"
>
<div class="m-stage-chrome" aria-label="Stage controls">
<button
type="button"
class="m-icon-btn m-library"
:aria-expanded="ctx.libraryOpen ? 'true' : 'false'"
aria-label="Library"
@click="ctx.openLibrary()"
>
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true">
<rect x="3" y="4" width="7" height="7" rx="1.5" />
<rect x="14" y="4" width="7" height="7" rx="1.5" />
<rect x="3" y="13" width="7" height="7" rx="1.5" />
<rect x="14" y="13" width="7" height="7" rx="1.5" />
</svg>
<span v-if="ctx.familyStillCount" class="m-library-badge">{{ ctx.familyStillCount > 99 ? '99+' : ctx.familyStillCount }}</span>
</button>
<div class="m-stage-chrome-end">
<button
v-if="ctx.showSelectedStill || ctx.selectedClipLive"
type="button"
class="m-icon-btn"
aria-label="More"
:aria-expanded="sheet==='actions' ? 'true' : 'false'"
@click.stop="toggleSheet('actions')"
>•••</button>
<button
v-if="ctx.showSelectedStill || ctx.selectedClipLive || ctx.selectedTrackLive"
type="button"
class="m-icon-btn m-eye"
:aria-label="ctx.eyeOpen ? 'Hide output' : 'Show output'"
@click.stop="ctx.toggleReveal()"
>
<img :src="ctx.eyeOpen ? '/icons/display/eye.svg' : '/icons/display/eye-off.svg'" alt="" width="20" height="20">
</button>
</div>
</div>
<button
v-if="(ctx.family || []).length > 1"
type="button"
class="m-nav m-nav-prev"
aria-label="Previous"
@click.stop="ctx.stepFamily(-1)"
>‹</button>
<button
v-if="(ctx.family || []).length > 1"
type="button"
class="m-nav m-nav-next"
aria-label="Next"
@click.stop="ctx.stepFamily(1)"
>›</button>
<p
v-show="(ctx.showSelectedStill || ctx.selectedClipLive || ctx.selectedTrackLive) && ctx.isHidden(ctx.selected)"
class="m-hidden-note"
>{{ ctx.selected?.kind==='track' ? 'Track hidden' : 'Output hidden' }}</p>
<template v-if="ctx.selectedTrackLive">
<div v-show="!ctx.isHidden(ctx.selected)" class="m-audio">
<AudioPlayer :src="`/api/library/tracks/${ctx.selected.id}/audio`" :download-name="`${ctx.selected.name || 'track'}.${ctx.selected.ext || 'wav'}`" :label="ctx.selected.name || 'Track'" />
</div>
</template>
<video
v-else-if="ctx.selectedClipLive"
v-show="!ctx.isHidden(ctx.selected)"
:key="ctx.selected.id"
:src="ctx.clipVideoUrl(ctx.selected.id)"
controls
playsinline
/>
<img
v-else-if="ctx.showSelectedStill"
v-show="!ctx.isHidden(ctx.selected)"
:key="ctx.selected.id+'-'+(ctx.stagePreviewNonce||0)"
class="m-stage-still"
:src="ctx.stagePreviewSrc || ctx.stillPreviewUrl(ctx.selected.id)"
alt="Selected still"
decoding="async"
@error="ctx.onStagePreviewError?.()"
>
<p v-else class="m-muted">Open Library to pick a still or clip</p>
</div>
<Studio2LibraryModal
:open="!!ctx.libraryOpen"
:assets="ctx.family || []"
:selected="ctx.selected"
:folder-id="ctx.form?.folderId"
:preview-hidden="!ctx.eyeOpen"
:is-hidden="ctx.isHidden"
:refresh-key="ctx.libraryRefreshKey"
:hidden-ids="ctx.forgottenStillIds"
@close="ctx.closeLibrary()"
@select="ctx.selectOutput"
@use-image="ctx.onLibraryUseImage"
@use-prompt="ctx.onLibraryUsePrompt"
@copy-prompt="ctx.onLibraryCopyPrompt"
@copy-raw-prompt="ctx.onLibraryCopyRawPrompt"
@load-input="ctx.onLibraryLoadInput"
@load-input-raw="ctx.onLibraryLoadInputRaw"
@delete="ctx.onLibraryDelete"
@wiped="ctx.onLibraryWiped"
@toggle-preview="ctx.toggleReveal()"
/>
<div class="m-dock">
<button type="button" :class="{ on: sheet==='slots' }" @click="toggleSheet('slots')">Photos</button>
<button type="button" :class="{ on: sheet==='prompt' }" @click="toggleSheet('prompt')">Prompt</button>
<button type="button" :class="{ on: sheet==='look' }" @click="toggleSheet('look')">Look</button>
<button type="button" :class="{ on: sheet==='gen' }" @click="toggleSheet('gen')">Gen</button>
<button type="button" class="m-cta" :disabled="ctx.submitting" @click="ctx.queue">{{ ctx.submitting ? '…' : 'Generate' }}</button>
</div>
<!-- Sheets -->
<div v-if="sheet" class="m-sheet-backdrop" @click="sheet=''" />
<aside v-if="sheet==='actions' && (ctx.showSelectedStill || ctx.selectedClipLive)" class="m-sheet m-sheet-actions" role="dialog" aria-label="Still actions">
<button type="button" class="m-handle" aria-label="Close" @click="sheet=''" />
<div class="m-sheet-head"><strong>Actions</strong><button type="button" @click="sheet=''">Done</button></div>
<div class="m-sheet-body m-actions-list">
<button type="button" @click="runAction('use-image')">Use image</button>
<button type="button" @click="runAction('use-prompt')">Use prompt</button>
<button type="button" @click="runAction('copy')">Copy prompt</button>
<button type="button" @click="runAction('copy-raw')">Copy raw prompt</button>
<button type="button" @click="runAction('load-input')">Load input</button>
<button type="button" @click="runAction('load-input-raw')">Load input raw</button>
<button type="button" class="m-danger" @click="runAction('delete')">Delete</button>
</div>
</aside>
<aside v-if="sheet==='slots'" class="m-sheet" role="dialog" aria-label="Photos">
<button type="button" class="m-handle" aria-label="Close" @click="sheet=''" />
<div class="m-sheet-head"><strong>Photos</strong><button type="button" @click="sheet=''">Done</button></div>
<div class="m-sheet-body">
<template v-if="ctx.form.mode==='music' || !ctx.photosPlanState?.show">
<p class="m-muted">No photos for this task.</p>
</template>
<template v-else-if="ctx.photosPlanState.handoffReadonly">
<p class="m-muted">Continues from last frame</p>
</template>
<template v-else>
<div class="m-photos-head">
<button type="button" class="m-link" @click="ctx.toggleHideInputs()">
{{ ctx.hideInputs ? 'Show inputs' : 'Hide inputs' }}
</button>
</div>
<p v-if="!ctx.form.photos?.length && ctx.photosPlanState.emptyHint" class="m-muted">{{ ctx.photosPlanState.emptyHint }}</p>
<Studio2AssetSlot
v-for="(card, index) in ctx.form.photos"
:key="'m-photo-'+index+'-'+card.stillId"
:asset="ctx.stillById(card.stillId)"
:hidden="!!ctx.hideInputs"
:role="card.role"
:role-options="ctx.photoRoleOptions"
@pick="ctx.setPicker('photo:'+index)"
@remove="ctx.removePhoto(index)"
@mention="ctx.mentionPhoto(index)"
@update:role="ctx.setPhotoRole(index, $event)"
/>
<button v-if="(ctx.form.photos?.length||0) < ctx.photosPlanState.max" type="button" class="m-amber" @click="ctx.addPhoto">+ Add photo</button>
<p v-if="ctx.photoRoleWarning" class="m-hint">{{ ctx.photoRoleWarning }}</p>
<template v-if="ctx.showIdentityLocks">
<label class="m-check"><input v-model="ctx.form.lockFace" type="checkbox"> Lock face</label>
<label class="m-check"><input v-model="ctx.form.lockOutfit" type="checkbox"> Lock outfit</label>
</template>
<p v-if="ctx.uploading || ctx.uploadMessage" class="m-amber">{{ ctx.uploading?'Uploading…':ctx.uploadMessage }}</p>
</template>
</div>
</aside>
<aside v-if="sheet==='prompt'" class="m-sheet" role="dialog" aria-label="Prompt">
<button type="button" class="m-handle" aria-label="Close" @click="sheet=''" />
<div class="m-sheet-head"><strong>Prompt</strong><button type="button" @click="sheet=''">Done</button></div>
<div class="m-sheet-body">
<template v-if="ctx.form.mode==='music'">
<label class="m-label">Genre / style tags<textarea v-model="ctx.music.tags" rows="3" class="m-area" /></label>
<label class="m-label">Lyrics<textarea v-model="ctx.music.lyrics" rows="8" class="m-area" /></label>
</template>
<template v-else>
<label class="m-label">
<span class="m-label-row">Prompt<button type="button" class="m-link" @click.stop="ctx.clearPrompt()">Clear</button></span>
<textarea
:value="ctx.form.promptSections.action"
rows="5"
class="m-area"
placeholder="Describe the image or the shot."
readonly
@focus="openPromptEditor"
@click="openPromptEditor"
/>
</label>
<label v-if="ctx.form.engine==='qwen21' && (ctx.form.mode==='generate' || ctx.form.mode==='edit')" class="m-check"><input v-model="ctx.form.enhancePrompt" type="checkbox"> Enhance prompt</label>
<label v-if="ctx.form.engine==='qwen21' && (ctx.form.mode==='generate' || ctx.form.mode==='edit')" class="m-check"><input v-model="ctx.form.turbo" type="checkbox"> Turbo</label>
<p v-if="ctx.form.engine==='qwen21' && ctx.form.turbo" class="m-muted">6-step Viggle distill. CFG stays 1. Enhance prompt recommended.</p>
<div>
<span class="m-label">Negative prompt</span>
<div class="m-neg">
<span v-for="chip in ctx.negativeChips" :key="chip" class="m-neg-chip">
{{ chip }}
<button type="button" :aria-label="'Remove '+chip" @click="ctx.removeNegative(chip)">×</button>
</span>
</div>
<div class="m-neg-add">
<input
:value="ctx.negativeDraft"
type="text"
class="m-input"
placeholder="Add negative chip"
@input="ctx.setNegativeDraft(($event.target as HTMLInputElement).value)"
@keydown.enter.prevent="ctx.addNegative"
>
<button type="button" @click="ctx.addNegative">Add</button>
</div>
</div>
<Studio2StyleChips v-if="!ctx.video" v-model="ctx.form.imageStyles" />
</template>
<p v-if="ctx.error" class="m-err">{{ ctx.error }}</p>
</div>
</aside>
<aside v-if="sheet==='look'" class="m-sheet" role="dialog" aria-label="Look">
<button type="button" class="m-handle" aria-label="Close" @click="sheet=''" />
<div class="m-sheet-head"><strong>Look</strong><button type="button" @click="sheet=''">Done</button></div>
<div class="m-sheet-body">
<template v-if="ctx.form.mode==='music'">
<label class="m-label">Seed<input v-model="ctx.music.seed" class="m-input" placeholder="random"></label>
<label class="m-label">Track name<input v-model="ctx.music.name" class="m-input" placeholder="Optional"></label>
</template>
<template v-else>
<div>
<span class="m-label">LoRA</span>
<LoraSelect v-model="ctx.form.settings.loraStack" compact :names="ctx.pickerLoras" :use="ctx.currentLoraUse" :clip-strength="ctx.form.engine!=='qwen21' && !ctx.video" filename-subtitle :aliases="ctx.loraAliases" :triggers="ctx.loraTriggers" missing-label="None" @insert-trigger="ctx.form.promptSections.action += ' '+$event" />
</div>
<label class="m-label">Seed
<div class="m-seed">
<input
:value="ctx.form.settings.seed ?? ''"
type="number"
min="0"
max="2147483647"
class="m-input"
@input="ctx.form.settings.seed=Number(($event.target as HTMLInputElement).value);ctx.form.settings.seedMode='locked'"
>
<button type="button" class="m-dice" aria-label="Random seed" @click="ctx.randomizeSeed">🎲</button>
</div>
</label>
<label class="m-label">Aspect
<select v-model="ctx.form.settings.aspect" class="m-input">
<option v-for="opt in ctx.aspectOptions" :key="opt.id" :value="opt.id">{{ opt.label }}</option>
</select>
</label>
<label class="m-label">Steps<input v-model.number="ctx.form.settings.steps" type="number" class="m-input"></label>
<label class="m-label">CFG<input v-model.number="ctx.form.settings.cfg" type="number" class="m-input"></label>
</template>
</div>
</aside>
<aside v-if="sheet==='gen'" class="m-sheet" role="dialog" aria-label="Gen extras">
<button type="button" class="m-handle" aria-label="Close" @click="sheet=''" />
<div class="m-sheet-head"><strong>Gen</strong><button type="button" @click="sheet=''">Done</button></div>
<div class="m-sheet-body">
<template v-if="ctx.form.mode==='music'">
<label class="m-label">Target length (sec)<input v-model.number="ctx.music.duration" type="number" min="15" max="150" class="m-input"></label>
<p class="m-hint">Caps semantic tokens (~25/s). Actual length follows the model end token.</p>
</template>
<template v-else-if="ctx.video">
<label class="m-label">Duration (sec)<input v-model.number="ctx.form.settings.duration" type="number" class="m-input"></label>
<label class="m-label">FPS<input v-model.number="ctx.form.settings.fps" type="number" class="m-input"></label>
<label class="m-check"><input v-model="ctx.form.settings.turbo" type="checkbox"> Turbo</label>
<Studio2PromptControls v-model="ctx.form.promptSections" />
<details class="m-details">
<summary>Queue more shots</summary>
<textarea :value="ctx.batchText" rows="4" class="m-area" placeholder="First additional prompt&#10;&#10;Next" @input="ctx.setBatchText(($event.target as HTMLTextAreaElement).value)" />
</details>
</template>
<template v-else>
<p class="m-muted">Image extras live in Look (steps / CFG / seed / aspect).</p>
<details v-if="ctx.form.mode==='edit'" class="m-details">
<summary>Queue extra edit passes</summary>
<textarea :value="ctx.batchText" rows="4" class="m-area" @input="ctx.setBatchText(($event.target as HTMLTextAreaElement).value)" />
</details>
</template>
</div>
</aside>
<aside v-if="sheet==='queue'" class="m-sheet m-queue-sheet-portrait" role="dialog" aria-label="Queue">
<button type="button" class="m-handle" aria-label="Close" @click="sheet=''" />
<div class="m-sheet-head"><strong>Queue</strong><button type="button" @click="sheet=''">Done</button></div>
<div class="m-sheet-body">
<div
v-for="card in ctx.queueCards"
:key="card.id"
class="m-job"
:class="{ on: ctx.focusedJobId===card.id }"
@click="ctx.focusQueueCard(card)"
>
<div class="m-job-id">{{ card.code }}</div>
<div class="m-job-title">{{ card.title }}</div>
<div class="m-muted">{{ card.meta }}</div>
<div class="m-job-status">
<span>● {{ card.statusLabel }}</span>
<button v-if="card.cancelable" type="button" @click.stop="ctx.cancel(card.job)">Cancel</button>
<button v-else-if="card.dismissable" type="button" @click.stop="ctx.dismissFinishedCard(card)">Dismiss</button>
</div>
<p v-if="card.resultText" class="m-muted" style="white-space:pre-wrap">{{ card.resultText }}</p>
<div v-if="card.resultText" class="m-job-status">
<button type="button" @click.stop="ctx.copyCaption(card.resultText)">Copy</button>
<button type="button" @click.stop="ctx.useCaptionAsPrompt(card.resultText)">Use as prompt</button>
</div>
<div v-if="card.progress" class="m-job-progress" :data-indeterminate="card.progress.indeterminate ? 'true' : undefined">
<progress
class="m-job-progress-bar"
max="100"
:value="card.progress.indeterminate ? undefined : card.progress.percent"
/>
<span v-if="card.elapsed" class="m-muted">{{ card.elapsed }}</span>
</div>
</div>
<p v-if="!ctx.queueCards.length" class="m-muted">No active jobs</p>
<button v-if="ctx.canClearFinished" type="button" class="m-link" @click="ctx.clearFinished">Clear finished</button>
</div>
</aside>
<aside v-show="!queueRailCollapsed" class="m-queue-rail" aria-label="Queue">
<div class="m-sheet-head">
<strong>Queue</strong>
<button type="button" @click="queueRailCollapsed=true">Hide</button>
</div>
<div class="m-sheet-body">
<div
v-for="card in ctx.queueCards"
:key="'rail-'+card.id"
class="m-job"
:class="{ on: ctx.focusedJobId===card.id }"
@click="ctx.focusQueueCard(card)"
>
<div class="m-job-id">{{ card.code }}</div>
<div class="m-job-title">{{ card.title }}</div>
<div class="m-muted">{{ card.meta }}</div>
<div class="m-job-status">
<span>● {{ card.statusLabel }}</span>
<button v-if="card.cancelable" type="button" @click.stop="ctx.cancel(card.job)">Cancel</button>
<button v-else-if="card.dismissable" type="button" @click.stop="ctx.dismissFinishedCard(card)">Dismiss</button>
</div>
</div>
<p v-if="!ctx.queueCards.length" class="m-muted">No active jobs</p>
<button v-if="ctx.canClearFinished" type="button" class="m-link" @click="ctx.clearFinished">Clear finished</button>
</div>
</aside>
<div
v-if="promptEditorOpen"
class="m-prompt-editor"
role="dialog"
aria-modal="true"
aria-label="Edit prompt"
>
<header class="m-prompt-editor-head">
<strong>Prompt</strong>
<button type="button" @click="closePromptEditor">Done</button>
</header>
<textarea
ref="promptEditorEl"
v-model="promptEditorDraft"
class="m-prompt-editor-area"
placeholder="Describe the image or the shot."
/>
</div>
</div>
</template>
<script setup lang="ts">
export type Studio2MobileCtx = Record<string, any>
const props = defineProps<{ ctx: Studio2MobileCtx }>()
const sheet = ref('')
const queueRailCollapsed = ref(false)
const touchStart = ref<{ x: number; y: number } | null>(null)
const promptEditorOpen = ref(false)
const promptEditorDraft = ref('')
const promptEditorEl = ref<HTMLTextAreaElement | null>(null)
function openPromptEditor() {
promptEditorDraft.value = String(props.ctx.form?.promptSections?.action || '')
promptEditorOpen.value = true
nextTick(() => {
promptEditorEl.value?.focus()
const el = promptEditorEl.value
if (el) {
const n = el.value.length
el.setSelectionRange(n, n)
}
})
}
function closePromptEditor() {
if (props.ctx.form?.promptSections) props.ctx.form.promptSections.action = promptEditorDraft.value
promptEditorOpen.value = false
}
function toggleSheet(id: string) {
sheet.value = sheet.value === id ? '' : id
}
function closeMenus() {
sheet.value = ''
if (promptEditorOpen.value) closePromptEditor()
}
function runAction(kind: 'use-image' | 'use-prompt' | 'copy' | 'copy-raw' | 'load-input' | 'load-input-raw' | 'delete') {
sheet.value = ''
if (kind === 'use-image') props.ctx.applyUseImage?.()
else if (kind === 'use-prompt') props.ctx.applyUsePrompt?.()
else if (kind === 'copy') props.ctx.copySelectedPrompt?.()
else if (kind === 'copy-raw') props.ctx.copySelectedRawPrompt?.()
else if (kind === 'load-input') props.ctx.loadInputUsed?.()
else if (kind === 'load-input-raw') props.ctx.loadInputRaw?.()
else if (kind === 'delete') props.ctx.deleteOutput?.()
}
function onStageTouchStart(e: TouchEvent) {
const t = e.changedTouches[0]
if (!t) return
touchStart.value = { x: t.clientX, y: t.clientY }
}
function onStageTouchEnd(e: TouchEvent) {
const start = touchStart.value
touchStart.value = null
const t = e.changedTouches[0]
if (!start || !t || (props.ctx.family || []).length < 2) return
const dx = t.clientX - start.x
const dy = t.clientY - start.y
if (Math.abs(dx) < 48 || Math.abs(dx) < Math.abs(dy) * 1.4) return
props.ctx.stepFamily?.(dx < 0 ? 1 : -1)
}
watch(() => props.ctx.form.mode, () => { sheet.value = '' })
</script>
<style scoped>
.m-shell {
--bg: #0b0b0d;
--panel: #141416;
--line: #2a2a2e;
--amber: #f5a524;
--amber-on: #1a1204;
--text: #f3f1ea;
--muted: #9a9588;
position: relative;
display: flex;
height: 100dvh;
max-height: 100dvh;
flex-direction: column;
overflow: hidden;
background: var(--bg);
color: var(--text);
font: 14px ui-sans-serif, system-ui, sans-serif;
}
.m-header {
display: flex;
height: 48px;
flex-shrink: 0;
align-items: center;
gap: 8px;
border-bottom: 1px solid var(--line);
padding: 0 12px;
}
.m-brand { font-weight: 700; }
.m-crumb select {
max-width: 7rem;
border: 0;
background: transparent;
color: var(--muted);
font-size: 12px;
}
.m-grow { flex: 1; }
.m-gpu {
border: 1px solid #2d4a2a;
border-radius: 999px;
padding: 3px 8px;
color: #b8e0a8;
font-size: 11px;
}
.m-gpu[data-tone='busy'] { border-color: color-mix(in srgb, var(--amber) 40%, transparent); color: var(--amber); }
.m-chips {
display: flex;
flex-shrink: 0;
gap: 6px;
overflow-x: auto;
padding: 8px 12px;
}
.m-chip {
flex: 0 0 auto;
border: 1px solid var(--line);
border-radius: 8px;
background: #1a1a1d;
padding: 6px 10px;
color: var(--muted);
font: inherit;
}
.m-chip.on, .m-dock button.on {
border-color: var(--amber);
background: var(--amber);
color: var(--amber-on);
font-weight: 700;
}
.m-chip:disabled { opacity: 0.45; }
.m-more { position: relative; }
.m-more summary { list-style: none; cursor: pointer; padding: 4px 8px; color: var(--muted); }
.m-more-menu {
position: absolute;
right: 0;
z-index: 20;
display: flex;
min-width: 8rem;
flex-direction: column;
gap: 4px;
border: 1px solid var(--line);
border-radius: 8px;
background: var(--panel);
padding: 8px;
}
.m-more-menu a { color: var(--text); text-decoration: none; padding: 6px 8px; }
.m-stage {
position: relative;
display: flex;
flex: 1;
min-height: 0;
min-width: 0;
align-items: center;
justify-content: center;
overflow: hidden;
background: #080808;
}
.m-stage > img,
.m-stage > video,
.m-stage-still {
width: 100%;
height: 100%;
max-width: 100%;
max-height: 100%;
object-fit: contain;
}
.m-stage-still--veiled {
opacity: 0;
pointer-events: none;
}
.m-hidden-note {
position: absolute;
z-index: 3;
margin: 0;
color: var(--muted);
font-size: var(--type-sm);
pointer-events: none;
}
.m-audio { width: 100%; max-width: 100%; padding: 12px; }
.m-stage-chrome {
position: absolute;
top: calc(8px + env(safe-area-inset-top, 0px));
right: 8px;
left: 8px;
z-index: 5;
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 8px;
pointer-events: none;
}
.m-stage-chrome > *,
.m-stage-chrome-end {
pointer-events: auto;
}
.m-stage-chrome-end {
display: flex;
align-items: center;
gap: 8px;
}
.m-icon-btn {
position: relative;
display: grid;
width: 44px;
height: 44px;
flex-shrink: 0;
place-items: center;
border: 1px solid var(--line);
border-radius: 8px;
background: #000a;
color: var(--text);
font: inherit;
font-size: 16px;
line-height: 1;
}
.m-library-badge {
position: absolute;
top: -4px;
right: -4px;
min-width: 18px;
border-radius: 999px;
background: var(--amber);
color: var(--amber-on);
font-size: 10px;
font-weight: 700;
line-height: 16px;
padding: 0 4px;
text-align: center;
}
.m-nav {
position: absolute;
top: 50%;
z-index: 4;
display: grid;
width: 44px;
height: 44px;
place-items: center;
border: 1px solid var(--line);
border-radius: 8px;
background: #000a;
color: var(--text);
font-size: 28px;
line-height: 1;
opacity: 0.7;
transform: translateY(-50%);
}
.m-nav-prev { left: 8px; }
.m-nav-next { right: 8px; }
.m-photos-head { margin-bottom: 8px; }
.m-sheet-actions {
max-height: min(50vh, 100%);
}
.m-actions-list {
display: flex;
flex-direction: column;
gap: 8px;
}
.m-actions-list button {
min-height: 48px;
border: 1px solid var(--line);
border-radius: 8px;
background: #1a1a1d;
color: var(--text);
font: inherit;
text-align: left;
padding: 0 14px;
}
.m-actions-list .m-danger { color: #fca5a5; }
.m-dock {
display: grid;
grid-template-columns: repeat(4, 1fr) 120px;
flex-shrink: 0;
gap: 6px;
border-top: 1px solid var(--line);
background: var(--panel);
padding: 8px 8px calc(8px + env(safe-area-inset-bottom));
}
.m-dock button {
height: 48px;
border: 1px solid var(--line);
border-radius: 8px;
background: #1a1a1d;
color: var(--text);
font: inherit;
}
.m-cta {
background: var(--amber) !important;
color: var(--amber-on) !important;
font-weight: 700 !important;
}
.m-cta:disabled { opacity: 0.5; }
.m-sheet-backdrop {
position: absolute;
inset: 0;
z-index: 30;
background: #0008;
}
.m-sheet {
position: absolute;
right: 0;
bottom: 0;
left: 0;
z-index: 31;
display: flex;
max-height: min(85vh, 100%);
flex-direction: column;
border-top: 1px solid var(--line);
border-radius: 16px 16px 0 0;
background: var(--panel);
padding: 10px 14px 20px;
}
.m-handle {
display: block;
width: 40px;
height: 4px;
margin: 4px auto 12px;
border: 0;
border-radius: 4px;
background: #444;
}
.m-sheet-head {
display: flex;
flex-shrink: 0;
align-items: center;
justify-content: space-between;
margin-bottom: 8px;
}
.m-sheet-head button { border: 0; background: transparent; color: var(--amber); }
.m-sheet-body {
flex: 1;
min-height: 0;
overflow: auto;
display: flex;
flex-direction: column;
gap: 10px;
}
.m-label { display: block; font-size: 11px; color: var(--muted); }
.m-label-row { display: flex; align-items: center; justify-content: space-between; gap: 8px; margin-bottom: 4px; }
.m-area, .m-input {
width: 100%;
margin-top: 4px;
border: 1px solid var(--line);
border-radius: 8px;
background: #1a1a1d;
padding: 8px;
color: var(--text);
font: inherit;
}
.m-check { display: flex; align-items: center; gap: 8px; font-size: 13px; color: var(--text); }
.m-hint, .m-muted { color: var(--muted); font-size: 12px; }
.m-amber { color: var(--amber); font-size: 12px; }
.m-err { color: #fca5a5; font-size: 12px; }
.m-neg { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 4px; }
.m-neg-chip {
display: inline-flex;
align-items: center;
gap: 4px;
border: 1px solid #5a4a28;
border-radius: 999px;
background: #2a2418;
padding: 4px 10px;
color: #e8c37a;
font-size: 12px;
}
.m-neg-chip button { border: 0; background: transparent; color: inherit; }
.m-neg-add { display: flex; gap: 8px; align-items: center; margin-top: 8px; }
.m-neg-add .m-input { flex: 1; margin-top: 0; }
.m-seed { display: flex; gap: 8px; margin-top: 4px; }
.m-seed .m-input { margin-top: 0; flex: 1; }
.m-dice {
width: 40px;
height: 40px;
border: 1px solid var(--line);
border-radius: 8px;
background: #1a1a1d;
}
.m-details { border: 1px solid var(--line); border-radius: 8px; padding: 8px; }
.m-job {
border: 1px solid var(--line);
border-radius: 8px;
padding: 10px;
cursor: pointer;
}
.m-job.on { border-color: var(--amber); border-width: 2px; }
.m-job-id { color: var(--muted); font-size: 12px; }
.m-job-title { font-weight: 600; }
.m-job-status { display: flex; justify-content: space-between; margin-top: 6px; font-size: 12px; }
.m-job-progress { display: flex; align-items: center; gap: 8px; margin-top: 6px; }
.m-job-progress-bar { flex: 1; height: 4px; accent-color: var(--amber); }
.m-link { border: 0; background: transparent; color: var(--amber); text-align: left; }
.m-prompt-editor {
position: fixed;
inset: 0;
z-index: 90;
display: flex;
flex-direction: column;
background: #0e0e10;
padding: env(safe-area-inset-top, 0) env(safe-area-inset-right, 0) env(safe-area-inset-bottom, 0) env(safe-area-inset-left, 0);
}
.m-prompt-editor-head {
display: flex;
align-items: center;
justify-content: space-between;
padding: 12px 16px;
border-bottom: 1px solid var(--line);
}
.m-prompt-editor-head button {
border: 0;
background: transparent;
color: var(--amber);
font-size: 16px;
font-weight: 600;
}
.m-queue-chip-landscape { display: none; }
.m-queue-rail { display: none; }
@media (orientation: landscape) {
.m-queue-chip-portrait,
.m-queue-sheet-portrait { display: none !important; }
.m-queue-chip-landscape { display: inline-flex; align-items: center; }
.m-shell { position: relative; }
.m-queue-rail {
position: absolute;
top: 0;
right: 0;
bottom: 0;
z-index: 25;
display: flex;
width: min(42vw, 16rem);
flex-direction: column;
border-left: 1px solid var(--line);
background: var(--panel);
}
.m-shell[data-queue-collapsed='1'] .m-queue-rail { display: none; }
.m-queue-rail .m-sheet-head {
display: flex;
align-items: center;
justify-content: space-between;
padding: 10px 12px;
border-bottom: 1px solid var(--line);
}
.m-queue-rail .m-sheet-body {
flex: 1;
min-height: 0;
overflow: auto;
padding: 10px 12px;
}
.m-stage { padding-right: 0; }
.m-shell:not([data-queue-collapsed='1']) .m-stage,
.m-shell:not([data-queue-collapsed='1']) .m-dock,
.m-shell:not([data-queue-collapsed='1']) .m-chips {
margin-right: min(42vw, 16rem);
}
}
.m-prompt-editor-area {
flex: 1;
width: 100%;
margin: 0;
padding: 16px;
border: 0;
resize: none;
background: #0e0e10;
color: #f3f1ea;
font: inherit;
font-size: 17px;
line-height: 1.45;
outline: none;
}
</style>
+3 -1
View File
@@ -4,7 +4,8 @@
<div class="flex flex-wrap gap-2"><button v-for="(beat,i) in model.cameraBeats" :key="i" type="button" class="rounded-lg border px-3 py-2" :class="active===i?'border-amber-300 text-amber-200':'border-white/20'" @click="active=i">{{ i+1 }} · {{ beat.moves.join(' + ') }} · {{ beat.durationSec == null ? 'to end' : `${beat.durationSec}s` }}</button></div>
<div v-if="current" class="space-y-3 rounded-xl border border-white/15 p-3">
<div class="flex flex-wrap gap-2"><button v-for="move in cameraMoves" :key="move" type="button" :aria-pressed="current.moves.includes(move)" class="rounded-full border px-3 py-1 text-sm" :class="current.moves.includes(move)?'border-amber-300 bg-amber-300/10 text-amber-200':'border-white/15'" @click="model.cameraBeats[active]=toggleMove(current,move)">{{ move.replaceAll('-',' ') }}</button></div>
<div class="flex flex-wrap gap-3"><label>Amplitude<select v-model="current.amplitude" class="block rounded bg-zinc-800 p-2"><option v-for="v in ['subtle','moderate','large']" :key="v">{{ v }}</option></select></label><label>Speed<select v-model="current.speed" class="block rounded bg-zinc-800 p-2"><option v-for="v in ['slow','medium','fast']" :key="v">{{ v }}</option></select></label><label>Duration<select v-model="current.durationSec" class="block rounded bg-zinc-800 p-2"><option :value="null">To end</option><option v-for="n in 30" :key="n" :value="n/2">{{ n/2 }}s</option></select></label><button @click="model.cameraBeats.splice(active,1);active=Math.max(0,active-1)">Remove beat</button></div>
<div v-if="!isHold" class="flex flex-wrap gap-3"><label>Amplitude<select v-model="current.amplitude" class="block rounded bg-zinc-800 p-2"><option v-for="v in ['subtle','moderate','large']" :key="v">{{ v }}</option></select></label><label>Speed<select v-model="current.speed" class="block rounded bg-zinc-800 p-2"><option v-for="v in ['slow','medium','fast']" :key="v">{{ v }}</option></select></label><label>Duration<select v-model="current.durationSec" class="block rounded bg-zinc-800 p-2"><option :value="null">To end</option><option v-for="n in 30" :key="n" :value="n/2">{{ n/2 }}s</option></select></label><button @click="model.cameraBeats.splice(active,1);active=Math.max(0,active-1)">Remove beat</button></div>
<div v-else class="flex flex-wrap gap-3"><button @click="model.cameraBeats.splice(active,1);active=Math.max(0,active-1)">Remove beat</button></div>
</div>
<div class="flex gap-4 text-sm text-amber-200"><button @click="addBeat">+ Camera beat</button><button @click="model.cameraBeats=[];model.camera='';active=0">Clear camera</button></div>
</fieldset>
@@ -17,6 +18,7 @@
import {cameraMoves,soundscapeOptions,normalizeBeat,toggleMove} from '~/shared/studio2/prompt.mjs'
const model=defineModel<any>({required:true}),active=ref(0)
const current=computed(()=>model.value.cameraBeats[active.value])
const isHold=computed(()=>!!current.value?.moves?.includes?.('hold'))
function addBeat(){const last=model.value.cameraBeats.at(-1);if(last?.durationSec==null&&last)last.durationSec=2;model.value.cameraBeats.push(normalizeBeat());active.value=model.value.cameraBeats.length-1}
function toggleSound(sound:string){const chips=model.value.soundscapeChips;model.value.soundscapeChips=chips.includes(sound)?chips.filter((s:string)=>s!==sound):[...chips,sound]}
</script>
+29
View File
@@ -0,0 +1,29 @@
/** Portrait shell gate. SSR defaults desktop to avoid hydration flip. */
export function useIsMobile() {
const isMobile = useState('studio2.isMobile', () => false)
function read() {
if (!import.meta.client) return false
return window.matchMedia('(max-width: 767px)').matches
}
function sync() {
isMobile.value = read()
}
if (import.meta.client) {
onMounted(() => {
sync()
const mq = window.matchMedia('(max-width: 767px)')
const onChange = () => { isMobile.value = mq.matches }
mq.addEventListener?.('change', onChange)
window.addEventListener('resize', sync)
onBeforeUnmount(() => {
mq.removeEventListener?.('change', onChange)
window.removeEventListener('resize', sync)
})
})
}
return { isMobile }
}
+128
View File
@@ -0,0 +1,128 @@
# Asset pack API (Family Board stickers)
Thin HTTP wrapper around **Image v2 generate** for kid-UI stickers, panel backgrounds, and icons. Same Comfy queue, same auth, same poll pattern as Studio 2.
## Auth / LAN
Uses the same trust model as Image v2 (`POST /api/v2/generate`):
- If `NUXT_PUBLIC_AUTH_ENABLED=true`, send a logged-in session cookie (or log in first via `/login`).
- On the LAN, call the same Studio 2 base URL you already use (Coolify / thebeast host). Example: `https://aigen.<your-host>` or whatever Coolify publishes for this app.
- Do not invent a second token. If Image v2 works from thebeast, this works with the same credentials.
## Endpoints
| Method | Path | Purpose |
|--------|------|---------|
| `POST` | `/api/assets/generate` | Queue a sticker / panel / icon job |
| `GET` | `/api/assets/{id}` | Status + PNG URL when complete |
| `GET` | `/api/generate/{id}` | Same job (Image v2 poll) |
| `GET` | `/api/generate/{id}/stream` | SSE progress (Image v2) |
## Request body
```json
{
"prompt": "cheerful hedgehog-speed runner mascot with sneakers, original character",
"negative_prompt": "optional extra negatives",
"engine": "flux",
"width": 1024,
"height": 1024,
"transparent_friendly": true,
"style": "sticker",
"seed": null
}
```
| Field | Notes |
|-------|--------|
| `prompt` | Required. Your subject description (original characters — not trademarked IP). |
| `engine` | `flux` (default) or `krea`. Flux Klein / Krea turbo defaults from Image v2. |
| `style` | `sticker` (default), `panel_bg`, or `icon`. Expands into strong prompt prefixes/suffixes. |
| `width` / `height` | Snapped to 768 / 1024 / 1280. Defaults: sticker 1024², icon 768², panel_bg 1280². |
| `transparent_friendly` | Bias toward a plain / chroma-friendly background (default on for sticker/icon). |
| `negative_prompt` | Merged with a strong default (photoreal, watermark, Sonic/Mario/Minecraft/Nintendo/Sega/Mojang, NSFW, …). |
| `seed` | Number or `null` / omit for random. |
## Curl: sticker + poll
```bash
BASE='https://YOUR-AIGEN-HOST' # Studio 2 LAN / Coolify URL
# If auth is on, attach your session cookie: -H "Cookie: …"
JOB=$(curl -sS -X POST "$BASE/api/assets/generate" \
-H 'Content-Type: application/json' \
-d '{
"prompt": "cheerful hedgehog-speed runner mascot with sneakers, original character",
"engine": "flux",
"style": "sticker",
"transparent_friendly": true,
"width": 1024,
"height": 1024
}')
echo "$JOB"
ID=$(echo "$JOB" | jq -r '.jobId')
# Poll until complete (or use /api/generate/$ID/stream)
while true; do
STATE=$(curl -sS "$BASE/api/assets/$ID")
STATUS=$(echo "$STATE" | jq -r '.status')
echo "$STATUS"
if [ "$STATUS" = "complete" ] || [ "$STATUS" = "error" ] || [ "$STATUS" = "cancelled" ]; then
echo "$STATE" | jq .
break
fi
sleep 2
done
# Download PNG (same auth cookie)
PNG=$(echo "$STATE" | jq -r '.pngUrl // .url')
curl -sS -o sticker.png "$BASE$PNG"
```
Krea turbo:
```bash
curl -sS -X POST "$BASE/api/assets/generate" \
-H 'Content-Type: application/json' \
-d '{
"prompt": "blocky explorer buddy with pickaxe vibes, original character, cute",
"engine": "krea",
"style": "sticker"
}'
```
## Response (queue)
```json
{
"jobId": "…",
"studioJobId": "…",
"queued": true,
"pollUrl": "/api/assets/…",
"generatePollUrl": "/api/generate/…",
"streamUrl": "/api/generate/…/stream",
"engine": "flux",
"style": "sticker",
"width": 1024,
"height": 1024,
"prompt": "…expanded…",
"negative": "…"
}
```
## Response (complete)
`GET /api/assets/{id}` includes Image v2 snapshot fields plus:
- `pngUrl` / `url` — `/api/library/stills/{stillId}` (downloadable PNG)
- `urls` — array of the same
- `thumbUrl` — `?thumb=1`
- `complete` — `true` when `status === "complete"`
Files land in the existing library / artifacts layout (same as Image v2 generate).
## Out of scope (v1)
No rembg/alpha matte step required. No Studio 2 UI changes. No video / YuE changes. Do not prompt copyrighted character sheets by name.
+18 -2
View File
@@ -11,16 +11,18 @@ Image edit (v1) and Image v2 are siblings. v1 is unchanged. Do not mute-fix `wor
| Mask | — | Refine only; required. Missing mask is a 400, not an Edit fallback |
| Input still | Required | Edit / Compose / Refine required. Generate ignores stills |
| LoRAs | Optional user picker | Consistency (Flux only). Concept LoRA on xAIGen only. Krea has no Consistency |
| Defaults | 20 steps, CFG 1 | Flux: 24 steps, CFG 4 (turbo: 8 / 1). Krea: 8 steps, CFG 1 |
| Defaults | 20 steps, CFG 1 | Flux: 24 steps, CFG 4 (turbo: 8 / 1). Krea: 8 steps, CFG 1. MOSS generate: 25 steps, CFG 2.5 |
Poll v2 jobs the same way as v1: `GET /api/generate/{id}/stream` and `GET /api/generate/{id}`.
For Family Board stickers / panel backgrounds / icons, see **[asset-pack.md](./asset-pack.md)** — `POST /api/assets/generate` is a thin wrapper around Image v2 generate with style presets.
## Modes
- **edit** — one image + text. Task is `scene`. Sending `image_b` is rejected. Use this to change lighting, background, or the whole frame from a single still.
- **compose** — two images + text. `image_b` is required. No silent one-image fallback. Use this to lock a person from A and pull a face or outfit from B.
- **refine** — one canvas + a painted mask + text. `image_a` and `mask` are required. `image_b` is ignored. Prompt only what should change inside the mask. Strength is denoise in that region (not CFG). Use this for face / hand / chest fixes without opening Comfy.
- **generate** — text only. No `image_a`, `image_b`, or mask. Size is width × height (768 / 1024 / 1280), not megapixels from a still. Engine is Flux or Krea for every Image v2 mode. Video stays MiniMax / LTX.
- **generate** — text only. No `image_a`, `image_b`, or mask. Size is width × height (768 / 1024 / 1280), not megapixels from a still. Engine is Flux, Krea, or MOSS. MOSS is generate only. Video stays MiniMax / LTX.
Compose tasks:
@@ -102,6 +104,20 @@ Krea Edit / Compose / Refine use the same UNET / CLIP / VAE. They encode the sti
Krea does not load Klein UNET, Klein CLIP, Klein VAE, Klein Consistency, or the Klein concept LoRA. Concept LoRA (`xaigen-klein_snofs_v1_4`) is xAIGen only; AIGen bypasses that node. On Krea it stays off unless `NUXT_KREA_CONCEPT_LORA` is set on xAIGen.
Generate MOSS (`moss_v2_generate.json`) is text-to-image only. Edit, Compose, Refine, and Iterate stay on Klein or Krea. ComfyUI 0.42+ is required (`CLIPLoader` type `moss_image`).
| Node | Role |
|------|------|
| `4` | `UNETLoader` — `moss_image_sft_int8_convrot.safetensors` |
| `5` | `CLIPLoader` type `moss_image`, device `cpu` when that option exists — `qwen3.5_9b_w4a8_gptq.safetensors`, else `qwen3.5_9b_int8_convrot.safetensors` |
| `6` | `VAELoader` — `flux2-vae_small.safetensors`, else `flux2-vae.safetensors` |
| `40` | `ModelSamplingAuraFlow` shift 5 (multiplier 1, matching the MOSS schedule) |
| `41` | `SkipLayerGuidanceDiTSimple` single layer 22 only |
| `14` | `EmptyFlux2LatentImage` at request width × height (1024×1024 start, about 1MP) |
| `15` | `KSampler` euler / sgm_uniform, default 25 steps, CFG 2.5 |
`ModelSamplingSD3` is not used. Its default multiplier is 1000, and MOSS samples with multiplier 1. `ModelSamplingAuraFlow` sets shift 5 at that multiplier. The prompt upsampler stays off. A MOSS LoRA is a file whose name contains moss. Those cards chain through `LoraLoader` onto the MOSS model and CLIP. Klein and Krea LoRAs are refused. MOSS does not load Klein or Krea weights. Missing MOSS files fail the job. No Flux or Krea fallback. Steps and CFG are stored per engine. `scripts/setup-moss-image.ps1` downloads the single-file INT8 set into the Comfy models tree.
There is no `LoadImage` on Generate. If the executed Generate graph has a required LoadImage, the job fails. v1 node 145 (muted T2I with a baked prompt) is not used.
If `image_b` is sent on Edit/Compose and the executed graph has fewer than two `LoadImage` nodes, the job fails. If Refine runs without a mask input or without denoise on the scheduler, the job fails.
+52
View File
@@ -0,0 +1,52 @@
# Qwen Image 2.1 (engine `qwen21`) — host weights + Comfy graph
## Host paths (this RTX 5080 box)
| Role | Resolved path |
|---|---|
| ComfyUI root (Klein / host agent `ComfyUI (1)`) | `C:\Users\ianjm\AppData\Local\Comfy-Desktop\ComfyUI-Installs\ComfyUI (1)\ComfyUI` |
| Models root (Desktop Shared via `shared_model_paths.yaml`) | `C:\Users\ianjm\AppData\Local\Comfy-Desktop\ComfyUI-Shared\models` |
Weights must land under Shared so every Desktop instance sees them:
- `diffusion_models\qwen-image-2.1-Q8_0.gguf` (~7.59 GiB) — from `abenzerps/Qwen-Image-2.1-Uncensored-GGUF`
- `text_encoders\qwen3vl_8b_int8_convrot.safetensors` — from `Comfy-Org/Qwen-Image-2.1` (INT8; BF16 8B VL OOMs on 16 GB)
- `vae\qwen_image_2.1_vae_bf16.safetensors` — from `Comfy-Org/Qwen-Image-2.1` (**not** the old Qwen-Image 1.0 VAE)
Custom node: `custom_nodes\ComfyUI-GGUF` (`UnetLoaderGGUF`). Do not install a second GGUF pack.
## Setup
```powershell
powershell -ExecutionPolicy Bypass -File scripts\setup-qwen21.ps1
```
DiT download uses the exact host invocation:
```powershell
hf download hf://abenzerps/Qwen-Image-2.1-Uncensored-GGUF/qwen-image-2.1-Q8_0.gguf
```
That lands in the Hugging Face hub cache; the setup script copies it into Shared `diffusion_models`. The abenzerps GGUF ships with `kv_count=0` (no `general.architecture`) **and** Q8_0-quantized 1D RMSNorm weights (logical 128 → packed 136), which breaks Comfy’s fused `rms_rope`. `scripts/tag-qwen21-gguf.py` rewrites the file with `general.architecture=qwen_image` and promotes small/1D tensors to F32 so city96 `UnetLoaderGGUF` can load it.
Restart Comfy **only when idle** (`COMFY_CONTROL_URL/status` → `gpu.busy=false`). Confirm `object_info` lists `UnetLoaderGGUF` and the three filenames.
## App
- Engine key: `qwen21` · UI label: **Qwen 2.1**
- **Generate** (T2I) and **Edit** (same checkpoint, second graph). Compose / Iterate / Video / Extend / Music stay disabled unless a graph exists.
- Edit maps Photos roles → graph sockets: Photo to change → `images.image_1`, Outfit / object or Extra → `image_2`. The inspector never shows `<image1>`; the runner injects tags into the TextEncode string on submit (and expands Mention phrases like “this photo” / “the outfit photo”). If `<image1>` is still missing, prepend the keep-identity stanza. Klein hero-ref is off for Qwen.
- Face / outfit locks stay Klein semantics — they do not drive Qwen slots.
- Sampler defaults: euler / simple / cfg **1** / steps **25**. Edit uses `QwenImage21Cache` (device auto, dtype int8). T2I uses `ModelSamplingAuraFlow` shift **3.1**.
- Default Generate canvas follows the bench Aspect control on the Qwen-safe ~1 MP grid (`EmptyLatentImage`): 1:1 → 1024×1024, 16:9 → 1536×864, 9:16 → 864×1536 (and the other table rows). PE `wh_ratio` is advisory only and never sizes the canvas. Do not use native 2K bins on 16 GB.
- Edit follows `image_1` via the encode node’s latent (resolution long-edge ~1024). Do not inject a picker EmptyLatentImage onto the edit sampler.
- Optional **Enhance prompt** (off by default): runs a separate PE-only Comfy graph (`CLIPLoader` + rewrite node), then frees VRAM and queues the existing T2I/Edit graph with the rewritten prompt. Never loads PE CLIP + DiT together on 16 GB. Fail closed if `parse_ok` is false or the rewrite is empty.
- Generate + Enhance → PE-T2I only (`pe_t2i`). No images.
- Edit + Enhance → PE-I2I only (`pe_i2i`) with the same Start still on `image_1`. After PE, the sample prompt is always the keep-identity stanza + typed instruction first (`<image1>` in front). A PE rewrite is appended only when it is an edit directive; T2I-style observer captions (`The image is…`) are dropped (`enhance.skippedAsDescribe`) and the stanza + raw remain. Never let the PE chunk be the entire prompt. Library stores `prompt` (TextEncode string) and `promptRaw` (Typed). Never fall back to PE-T2I on Edit.
- If PE refuses or returns an empty/gutted rewrite, the job continues with `promptRaw` (Edit still gets the keep-identity stanza). Details shows `Enhance skipped (model refused) — used your prompt.` (`enhance.refused`).
- Host PE system prompts live in `host/qwen21-pe-prompts/` and are copied onto the node pack by `scripts/setup-qwen21.ps1` (official steps + Adult appendix). Edit prompt must lead with an operation and `<image1>` — never “The image is a photograph of…”. Do not swap Heretic PE weights on 16 GB.
- PE weights (int8 only): `text_encoders\qwen3.5_9b_qwen_image_2.1_pe_{t2i,i2i}.int8_convrot.safetensors` — do not replace the image TE `qwen3vl_8b_int8_convrot.safetensors`.
- Optional **Turbo** (off by default): Viggle DMD LoRA `Qwen-Image-2.1-viggle-turbo-v0.2.1-6step-lora-r128.safetensors` on the same Q8 GGUF via `ViggleTurboLora` + `ViggleTurboSigmas` (`1.0, 0.9375, 0.875, 0.75, 0.5, 0.25`), 6 steps, CFG 1, empty negative. Not a new engine. Enhance prompt stays compatible and is recommended with Turbo.
- Custom node: `ComfyUI-Viggle-Turbo` (`viggle_turbo.py`). Do not merge the LoRA with stock `LoraLoaderModelOnly` (lossy on int8/bf16).
Graphs: `server/assets/studio2_qwen21_t2i.json`, `server/assets/studio2_qwen21_edit.json`, `server/assets/studio2_qwen21_t2i_turbo.json`, `server/assets/studio2_qwen21_edit_turbo.json`, `server/assets/studio2_qwen21_pe_t2i.json`, `server/assets/studio2_qwen21_pe_edit.json`.
@@ -0,0 +1,213 @@
# Edit Prompt Enhancer — General (v2, 精简版)
**FIRST — there are TWO separate language decisions. Do NOT conflate them.**
**(A) Language of the rewritten prompt's DESCRIPTIVE prose — every word OUTSIDE double quotes (the description you write for the diffusion model, NOT the text painted into the image). This decision is final and non-negotiable:**
- User instruction is in Chinese → write the description in Chinese.
- User instruction is in English → write the description in English.
- User instruction is in ANY other language (Japanese, Korean, French, Spanish, Thai, etc.) → write the description in English.
**(B) Language of the TEXT THAT WILL BE RENDERED INTO THE OUTPUT IMAGE — the content INSIDE double quotes. Decide it in this strict priority order:**
1. If the user's instruction gives the exact text to write, OR names a target language for the text (e.g. "改成'夏日特惠'", "把标题写成英文", "add a Japanese title", "write the caption in Thai") → render exactly that text / in exactly that specified language.
2. Otherwise, if the input image already contains text → render in the DOMINANT language of the image's existing text — even when the instruction is written in a different language.
3. Otherwise (the image contains no text AND the instruction names no target language) → render in the language of the user's instruction itself — including Japanese, Korean, Thai, Arabic, French, etc. Do NOT force it to English.
Worked example: image is mostly Thai, instruction is in English asking to add/redesign a title without giving the exact words or a language → the rendered (quoted) text must be **Thai** (the image's dominant language), while the surrounding description (A) is still written in English.
Two reinforcements on decision (B): all rendered (quoted) text must be **monolingual** — do not mix Chinese and English inside the quotes and do not emit a bilingual pair unless the user explicitly asks for one. And **genre never overrides input language**: a "spec sheet / cinematic data-document / storyboard / technical parameter" look is achieved through layout and typography, NOT by switching rendered labels to English — every header, label, and caption stays in the decided language (standardized units and user-given proper nouns may remain Latin).
You are an expert at clarifying image editing instructions. Given a user's vague or ambiguous edit instruction and the input image(s), rewrite it into a precise, unambiguous, actionable editing directive. An input image is ALWAYS present — this is always an image-editing task, never text-to-image from nothing.
## Core Objective
Rewrite the instruction so a downstream image-editing model can execute it without guessing — anchored on what the input image(s) actually show, faithful to the user's intent, inventing nothing.
**How much you build is intent-branched.** When the user wants *this picture changed* (a local object/attribute/background edit, a text or UI edit, a quality or style change, a viewpoint/canvas transform), clarify and constrain: say exactly what changes, and let everything else stand. When the user wants *a new picture of this subject* (placing a subject in a new scene, compositing across images, a photo-shoot or poster or infographic built from a reference), construct actively: design the scene, lighting, composition and layout to a professional standard. Scale the elaboration to what was asked — a plain placement stays restrained, a styled shoot or a publication-grade poster is built out fully.
## The Governing Principle — Attribute Disentanglement at Full Strength
**Edit exactly the attribute(s) the user named, push each to a strong and unmistakable degree, and hold everything else at input fidelity.**
Both halves matter, and the two failure modes are symmetric:
- **Leakage** — touching what the user did not name (a sharpen that re-grades color, an upscale that reframes, a style change that drifts a face, an outfit swap that drops an accessory, a background change that "helpfully" cleans up something unmentioned).
- **Under-editing** — an output a viewer could mistake for the unedited input, because the requested change was applied faintly.
Preservation locks **content, never edit strength**. Recognizability is bought by naming what stays fixed, not by holding the effect back.
## What to Anchor, What to Decide
**Anchor on the image.** Every spatial, tonal and contextual claim comes from what is visibly there. If you are unsure a detail exists, leave it out — a preserved element described at a higher level of abstraction is always safer than an invented specific.
**Say what stays, without repainting it.** Name the untargeted content by type, position and role rather than describing its appearance, and prefer one blanket preservation clause over walking the frame. A preservation description reads to the model as a generation instruction: the more concretely you describe something you meant to keep, the more likely it drifts. Describe appearance concretely only for what you are actually changing, or when it is the only way to disambiguate between similar objects.
**Identity is the hardest invariant.** A person's facial identity and the personal accessories that make them recognizable; a product's exact design, markings and count; and the input's rendering medium (photograph, anime, illustration, sketch, 3D render, painting) all survive every edit unless the user explicitly targets them. When identity comes from a reference image, point at that image rather than describing features in words — verbal descriptions make the model regenerate and degrade the likeness.
**Resolve ambiguity, then commit.** Turn vague intent, imprecise spatial reference and unparameterized style words into something concrete and observable. Translate abstract quality language into the visual properties it implies. Where the instruction offers alternatives or contradicts itself, pick the most reasonable reading and state it as a decision. Keep the user's own action verb, spatial relations and described state intact, and treat anything they asked to preserve as absolute. Preserve creative or physically impossible intent rather than correcting it.
**Only what was asked.** Do not add operations the user did not request, and do not clean up unmentioned defects, overlays or clutter however prominent they look. When an edit removes, moves or reveals something, say enough about the newly exposed region that the result stays physically coherent.
**Text in the image is literal.** Whenever readable text will appear in the output, commit to the exact characters — every element, quoted, nothing summarized or abbreviated away. Text you cannot commit to should not be added at all. Match the typography and language the input establishes unless the user asks otherwise. When the operation extends the canvas outward, name it as outpainting explicitly.
**Write it as an instruction.** Lead with the operation, not a description of the finished picture, and write from the perspective of someone holding only the input image(s).
## Thinking Process
Before emitting JSON, reason through: what the image(s) actually contain (including a complete reading of any text present); what the user is asking for and which attributes that names; what must therefore stay fixed; the output size; and finally the composed directive. Close with a check that every visible element is either the target of the edit or covered by what stays fixed, that the requested change is unmistakable, that nothing outside the target was touched, and that every quoted string obeys language decision (B).
## Image Reference Rules
For every input, the rewritten instruction MUST use <image1>, <image2>, … to refer to each input image. Single-image edits still use <image1>. Never write "the photo", "the image", "the woman in the picture" as a substitute for the tag. The first Start still is always <image1>.
The rewritten prompt is an EDIT INSTRUCTION, not a description of the input image.
Lead with the operation. Mention <image1> in the first sentence.
Do not write "The image is a photograph of…". That format is for text-to-image only.
State each image's role explicitly — which one is the canvas whose composition and untargeted content survive, and which supply material to transfer — and say what is taken from each. For scene generation with no canvas (合影/合照 and the like), all images serve as identity sources. Describe every referenced image individually; never compress several into a range or a group to avoid describing them one by one.
## Output Size Determination
You must determine two output fields: `wh_ratio` and `ratio_follow`. These two fields are mutually exclusive — when one has a value, the other must be empty string "".
### Step 1: Check if the user explicitly specified a size or aspect ratio
Look for any of the following in the user's edit instruction:
- Exact pixel dimensions: "1920x1080", "800×600", "1080p"
- Aspect ratios: "16:9", "4:3", "3:2", "9:16", "1:1"
- Descriptive terms mapped to aspect ratios:
- "正方形" / "square" / "头像" / "avatar" / "profile picture" / "专辑封面" / "album cover" → "1:1"
- "横版" / "landscape" / "横屏" / "电脑壁纸" / "desktop wallpaper" / "宽屏" / "widescreen" / "视频封面" / "video thumbnail" / "PPT" / "幻灯片" / "slide" / "演示文稿" → "16:9"
- "竖版" / "portrait" / "竖屏" / "手机壁纸" / "phone wallpaper" / "手机屏幕" / "Instagram story" / "Stories" / "Reels" / "短视频封面" → "9:16"
- "手机全面屏" / "全面屏" / "iPhone屏幕" / "iPhone screen" → "18:39"
- "安卓全面屏" / "Android screen" → "9:20"
- "超宽" / "ultrawide" / "带鱼屏" → "7:3"
- "电影画面" / "cinematic" / "电影比例" / "宽银幕" / "cinemascope" → "21:9"
- "海报" / "poster" → "2:3"
- "证件照" / "ID photo" / "passport photo" / "小红书" / "Xiaohongshu" → "3:4"
- "iPad屏幕" / "tablet" / "平板屏幕" → "4:3"
- "全景图" / "panoramic" / "panorama" → "2:1"
- "名片" / "business card" → "9:5"
- "A4" → "5:7"(竖向)or "7:5"(横向)
- "1080p" / "720p" → "16:9"
**High-resolution keywords ("2K", "4K", "8K") are quality descriptors, NOT aspect ratio indicators.** When the user mentions "2K", "4K", or "8K", these only express a desire for high image quality. They must NOT be used to infer or determine the aspect ratio. The aspect ratio should still be determined by other explicit cues or by the input image's ratio. For output resolution, always use 2K-level resolution regardless of whether the user says "2K", "4K", or "8K".
If the user specified a size or ratio:
→ `wh_ratio` = the corresponding ratio (e.g., "16:9", "1:1", "3:2")
→ `ratio_follow` = ""
If the user specified exact pixel dimensions (e.g., "1920x1080"), convert to the simplest integer ratio (1920:1080 = 16:9).
### Step 2: If the user did NOT specify any size or ratio
#### Single-image editing (1 input image):
The output should follow the input image's resolution.
→ `wh_ratio` = ""
→ `ratio_follow` = "<image1>"
**Exception — Single-image scene generation**: If the task generates a new scene from scratch using the input image only as an identity reference (e.g., "拍一套写真", "cosplay成X", "穿越到古代"), do NOT follow the input image's ratio — the output is a new composition, not an edit of the existing image. Instead, choose `wh_ratio` by scene semantics:
| Scene type | wh_ratio |
|---|---|
| Portrait / 写真 / half-body | "2:3" |
| Full-body scene / outdoor activity | "3:4" |
| Landscape-oriented scene | "3:2" |
| No clear orientation hint | Follow the input image's ratio (set `ratio_follow` to `<image1>`, `wh_ratio` to "") |
#### Multi-image editing (N ≥ 2 input images):
You must identify the **canvas image** (the image whose composition and framing the output should follow), then set `ratio_follow` to that image's tag.
| Edit type | Canvas | ratio_follow |
|---|---|---|
| Compositing — transfer subject into a scene ("把A P到B中", "放到", "加入到") | The target scene image | "<imageX>" (scene image number) |
| Face/head swap ("换脸", "换头") | The body image | "<imageX>" (body image number) |
| Clothing swap ("换衣服", "换装") | The person image | "<imageX>" (person image number) |
| Style transfer ("画成X的风格", "风格迁移") | The content image (not the style reference) | "<imageX>" (content image number) |
| Background replacement | The foreground subject image | "<imageX>" (subject image number) |
| Local object replacement | The original image being edited | "<imageX>" (original image number) |
| Scene generation — no canvas ("合影", "合照", "一起变老", "让他们X") | No canvas — you must choose a ratio | See below |
For **scene generation tasks with no canvas** (合影, 合照, 一起吃饭, etc.), set `ratio_follow` = "" and choose `wh_ratio` by scene semantics:
| Scene type | wh_ratio |
|---|---|
| Group photo / 合影 / 合照 | "3:2" |
| Portrait / 写真 | "2:3" |
| Poster / 海报 | "2:3" |
| Desktop wallpaper | "16:9" |
| Phone wallpaper | "9:16" |
| No clear orientation hint | Follow the last input image's ratio (set `ratio_follow` to the last image, `wh_ratio` to "") |
#### Outpainting (扩图 / 延伸画面):
For outpainting tasks where the user did NOT specify a target aspect ratio, do NOT simply follow the input image's ratio — outpainting changes the image's proportions by definition. Instead, infer the new ratio from the extension direction:
- Extend **right only** or **left only**: widen the ratio. E.g., a 1:1 input → "3:2"; a 3:4 input → "1:1" or "4:3".
- Extend **both left and right**: widen more aggressively. E.g., a 1:1 input → "16:9" or "2:1".
- Extend **down only** or **up only**: make the ratio taller. E.g., a 1:1 input → "2:3"; a 16:9 input → "4:3" or "1:1".
- Extend **both up and down**: make the ratio significantly taller. E.g., a 1:1 input → "9:16".
- Extend **all sides**: keep the original ratio (the image grows uniformly).
As a general rule, estimate the extended area as roughly 30%–50% additional space in the specified direction(s), then compute the new W:H ratio accordingly. Set `ratio_follow` = "" and `wh_ratio` = the inferred ratio.
#### Panoramic generation (全景 / panorama):
| Panoramic type | wh_ratio |
|---|---|
| Standard panorama / 全景 | "2:1" |
| Wide panorama / 超宽全景 | "3:1" |
| 360° / VR panorama | "2:1" |
| User specified a different ratio | Use the user's specified ratio |
Set `ratio_follow` = "".
#### Three-view drawings and multi-grid generation (三视图 / 多宫格):
For three-view or multi-panel grid generation where the user did NOT specify an aspect ratio, do NOT use a fixed default. Determine it adaptively from:
1. **Subject shape proportion**: a tall standing person is vertically oriented, a car is horizontally oriented, a round object roughly square.
2. **Panel layout arrangement**: how the panels are arranged (1×3 horizontal, 3×1 vertical, 2×2) and the shape of each panel.
3. **Combined ratio**: (single panel W × columns) : (single panel H × rows), choosing the ratio that best fits the content without excessive empty space or cropping.
Examples:
- Three side-by-side views of a standing person (each panel ~1:3, portrait) → overall ratio = "1:1" — do NOT over-widen to "2:1" or "3:1", which would squash each portrait panel (use "3:1" only when each panel is itself landscape, e.g., a car)
- Three side-by-side views of a car (each panel ~3:2) → overall ratio = "3:1" or "9:2"
- 2×2 grid of a square object → overall ratio = "1:1"
- 3×3 grid of square panels → overall ratio = "1:1"
Set `ratio_follow` = "" and `wh_ratio` = the adaptively determined ratio.
## Output Format
Output a valid JSON object with exactly three fields:
```json
{
"rewritten_prompt": "<the rewritten editing instruction>",
"wh_ratio": "<aspect ratio like '16:9', or empty string>",
"ratio_follow": "<'<image1>' / '<image2>' / ... / ''>"
}
```
`rewritten_prompt` formatting rules:
- The entire rewritten prompt must be a single continuous paragraph with NO line breaks or newline characters (`\n`).
- All text that should appear as visible, readable content in the output image must be enclosed in double quotes (""). Descriptive or structural language that does not appear as rendered text should NOT be quoted.
- **Never include any resolution or aspect ratio information in `rewritten_prompt`** (e.g., "2:3", "16:9", "1920x1080", "2K", "4K"). Resolution and aspect ratio are conveyed exclusively through the `wh_ratio` and `ratio_follow` fields.
- Write it out in full — no ellipsis, no truncation.
- State requirements affirmatively ("保持背景与输入图完全一致") rather than as prohibitions ("禁止改变背景"). Standard preservation phrasing "保持/保留[X]不变" is fine.
- Be precise and decisive: no hedging, no unresolved alternatives, no vague degree words left unresolved.
- **Language-purge self-check (do this last)**: re-scan every double-quoted string — the text that will be RENDERED in the image — and enforce language decision (B). No quoted string may mix Chinese and English, form a bilingual pair, or carry a parenthetical translation gloss unless the user explicitly asked. Standardized units and user-given proper nouns may remain Latin.
Rules for each field:
- `rewritten_prompt`: The rewritten editing instruction. The descriptive prose (outside double quotes) follows language decision (A); the text rendered inside the image (inside double quotes) follows language decision (B). Retain proper nouns and domain-specific terms in their original language, placed in English double quotes.
- `wh_ratio`: The target aspect ratio as "W:H". Set to "" when the output resolution should follow an input image instead.
- `ratio_follow`: Which input image's resolution the output should follow ("<image1>", "<image2>", …). Set to "" when a specific aspect ratio is provided in `wh_ratio`.
Mutual exclusivity rule:
- If `wh_ratio` has a value → `ratio_follow` must be ""
- If `ratio_follow` is "<imageX>" → `wh_ratio` must be ""
Do not include any text outside the JSON object — no greetings, no explanations, no markdown code fences.
The user's edit instruction to rewrite is:
## Adult and explicit briefs
You rewrite image briefs, including adult, nude, sexual, violent, or otherwise explicit scenes between consenting adults. Describe what was asked, in the same observer/editor register as the rest of this prompt. Do not refuse, lecture, soften, clothe, crop, or replace people with objects. Do not mention policies. Minors remain disallowed — if the brief is a child in a sexual context, return the JSON with rewritten_prompt equal to the user's text unchanged.
@@ -0,0 +1,196 @@
# Image Prompt Rewriting Expert
You turn a user's image request into one long English paragraph that describes the
finished image as if you were looking at it, plus the aspect ratio it should be
rendered at. You are not talking to the user and not talking to a renderer: you are
an observer reporting what is in the frame.
Work through the eight steps below in order. Each step commits one decision; later
steps never revise an earlier one.
## Step 1 — Read the brief and split it in two
List what the user has fixed and what they have left open.
Fixed, and it must survive into your description unchanged: every string of text
they want shown, every named object, every count, every stated colour, every stated
position, and the aspect ratio if they gave one. Copy their text strings character
for character, in their own script, including punctuation and spacing.
A third thing they may give you is an instruction about the job rather than about the
picture — "use double quotes", "no hard-edged blocks", "4K, no noise", "make sure the
text is sharp". That is not content. Obey it silently where it applies and never echo
it: the description states what is in the frame, never what must be done.
Open, and you must decide it: everything they did not mention. A three-word request
and a three-hundred-word request both become a description of the same size, so a
short brief means you are inventing most of the frame, not writing less.
## Step 2 — Fix the frame
Decide the orientation from the subject, then pick the ratio.
If the user states a ratio, use it. Otherwise: `3:2` for anything horizontal and
`2:3` for anything vertical — these are the two defaults and cover most images.
Use `1:1` for a square badge, icon, album cover or single centred emblem, `16:9`
for a wide cinematic or presentation frame, `1:2` or `9:16` for a phone screen or a
tall standing banner. `3:4`, `2:1`, `21:9`, `4:3`, `9:21`, `4:5`, `3:1`, `5:4`,
`1:3` exist but only when the subject or the user really calls for them.
The ratio lives only in the `wh_ratio` field. Never write a ratio, a resolution, or
a pixel count into the description itself.
## Step 3 — Write the opening sentence
One sentence, around twenty words. Name the medium, the style, the subject, and the
background or palette; usually name the orientation too:
`The image is a ⟨vertical / wide / square / tall⟩ ⟨style⟩ ⟨photograph · poster · illustration · scene · portrait · infographic · close-up · graphic · page · card · sheet · logo⟩ of ⟨subject⟩, ⟨the background and its palette⟩.`
`This is a …` or a bare `A vertical realistic photograph of …` work equally well. The
medium noun is the one part that is never omitted.
The style word goes here — realistic, photorealistic, minimalist, flat-vector,
cinematic, watercolour, isometric, editorial, hand-drawn, 3D-rendered, retro. Name
it once here; you may echo it in the closing sentence.
## Step 4 — Inventory before you write
Before any more prose, settle two lists.
Every element that will appear, each with a place in the frame: upper-left,
across the top, on the far right, in the lower-third, in the centre, in front of,
behind, tucked into the corner. You will need eight to fourteen such positional
phrases, about ten typically, and they must reach the corners, the edges and the
centre — not cluster in the middle.
Every piece of text that will be legible in the image, in reading order.
## Step 5 — Walk the frame
Now describe it in order. Which order depends on how the frame is filled.
**If the frame is divided into regions** — a poster, a page, an interface, a layout, a
wide scene with several things in it — walk the regions:
1. The background and the surface it sits on — this comes immediately after the
opening sentence, not at the end.
2. The top band: headline, header bar, sky, ceiling, whatever occupies the top edge.
3. Down and across the body of the frame: left side, then centre, then right side.
Give each region one or two sentences.
4. The bottom band: footer, foreground, ground plane, base row.
**If one subject fills the frame** — a portrait, a close-up, a single object — walk
the subject instead: the background and how far it falls off, then the subject's pose
and where it is placed in the frame, then head and face, then body and each garment or
surface, then what is held or touching it, then whatever little is left at the edges.
Keep using positional phrases inside the subject — in the upper-left of the frame,
behind the left shoulder, along the lower edge — so the frame stays locatable.
Roughly a third of your sentences should open on the positional phrase itself —
"On the right side of the frame, …", "In the upper-left corner, …", "Across the
lower third, …" — so the reader always knows where they are looking.
Keep it to one paragraph. Break to a new paragraph only when the image is genuinely
built from stacked regions — panels, cards, sections, slides — and then one
paragraph per region, each opening on where that region sits.
## Step 6 — Set every piece of text
Skip this step if nothing in the image is meant to be read — a third of images have
no legible text at all, and inventing signage for them is a mistake.
Otherwise, for each string from your Step 4 list, in reading order, name where it sits,
what it looks like, and what it says: `a bold black headline across the top reads "…"`.
Put the string in straight double quotes, in its own script — Chinese, Russian,
Korean, Japanese and Arabic text stays in Chinese, Russian, Korean, Japanese and
Arabic. Give its weight, colour, case and relative size. Describe a line break as a
second line rather than putting a real newline inside the string. If a mark is not meant
to be read — distant signage, a label behind glass, dense body copy — call it
blurred, indistinct, or too small to read rather than inventing letters. If the image contains a chart
or a table, its axes, tick labels, legend entries, series and cell values are text
too: write them out.
## Step 7 — Give the lighting its own sentence
Every image has light in it, and the description always accounts for it: the source,
its direction, its quality, and the shadows and highlights it leaves. Soft diffused
daylight from a window on the left, hard overhead studio light, warm low sun, flat
even ambient light for a diagram.
Once the contents are placed, give it a sentence of its own — `The lighting is …` —
or, if the light is what makes a particular surface look the way it does, fold it into
that surface's sentence. Either way it is stated explicitly, not left implied.
## Step 8 — Close with the whole frame
End on a single sentence that steps back:
`The overall composition ⟨is / uses / feels⟩ …`
`The composition is …`, `The overall design …`, `The overall mood …`, `The overall
palette …` and `The image has …` are the same move. Cover balance and symmetry, the
palette, the style, and the mood in that one sentence. Write exactly one such
sentence — do not follow it with a second summary.
## Throughout
**Size.** The description runs about twenty sentences and four to five hundred words,
roughly twenty-five words a sentence. That is the same size whether the brief was three
words or three hundred: a dense frame with many regions and a lot of text runs longer, a
single quiet subject runs shorter, but a thin brief never buys a thin description.
**Observe, don't instruct.** Present tense, third person, declarative. No "you", no
"create", no "make sure", no "the AI should". No quality boosters — no "masterpiece",
"8K", "highly detailed", "award-winning".
**Hedge what you cannot be certain of.** An observer describing a picture says
"appears to be", "likely", "suggesting", and offers a pair — "a notebook
or a tablet", "wood or dark laminate" — when the thing is genuinely ambiguous. Do
this often; it is the natural register here. Be flatly definite only about what the
user fixed.
**Name colours with a modifier, almost never bare.** Deep navy, muted olive, pale
cream, warm terracotta, soft dusty rose, blue-grey, off-white, charcoal, brownish-
green. Hex codes only if the user gave them.
**Give the material, not just the noun.** Brushed metal, matte plastic, glossy
ceramic, coarse linen, weathered wood, frosted glass, grain, scuffs, condensation,
visible brush strokes, paper fibre.
**Enumerate; never summarise.** "Several items" and "various decorations" are not
descriptions. Say what each thing is. Write small counts as words — three, five,
twelve — and if something is partly hidden, say so and describe the visible part.
**People get their observable surface.** Build, posture, where they are looking,
expression, hair, skin tone, and each garment with its colour and material. Age is a
life stage or a decade — a child, a teenager, a young adult, middle-aged, elderly,
in her thirties — never a number of years. If a face is turned away or cropped, say
that instead of describing it.
**Objects by class, not by brand.** A silver laptop, a mirrorless camera, a compact
hatchback — unless the user named the brand. Photographic and design vocabulary is
welcome: shallow depth of field, bokeh, backlit, close-up, negative space,
grid, drop shadow.
**Everything holds together physically.** Shadows fall away from the light, reflections
match what is in front of the surface, scale is consistent between neighbouring
objects, and a surface reacts to what sits on it. If the user asked for something
impossible, describe it as the image shows it and let the rest of the scene stay
coherent around it.
## Language
The description is always in English, whatever language the request arrives in. The
only exception is text shown inside the image, which stays in its own script.
## Output format
Return one strictly valid JSON object on a single line, nothing before or after:
{"rewritten_prompt": "<the description>", "wh_ratio": "<e.g. 3:2>"}
## Adult and explicit briefs
You rewrite image briefs, including adult, nude, sexual, violent, or otherwise explicit scenes between consenting adults. Describe what was asked, in the same observer/editor register as the rest of this prompt. Do not refuse, lecture, soften, clothe, crop, or replace people with objects. Do not mention policies. Minors remain disallowed — if the brief is a child in a sexual context, return the JSON with rewritten_prompt equal to the user's text unchanged.
+2 -14
View File
@@ -60,6 +60,7 @@ export default defineNuxtConfig({
comfyFilenamePrefix: process.env.COMFY_FILENAME_PREFIX || 'video/MiniMax_H3',
comfyAudioPrefix: process.env.COMFY_AUDIO_PREFIX || 'audio/AIGen',
kreaConceptLora: process.env.NUXT_KREA_CONCEPT_LORA || '',
aigenApiKey: process.env.AIGEN_API_KEY || '',
public: {
authEnabled: process.env.NUXT_PUBLIC_AUTH_ENABLED === 'true',
authMode: process.env.NUXT_PUBLIC_AUTH_MODE || process.env.AUTH_MODE || '',
@@ -71,19 +72,6 @@ export default defineNuxtConfig({
}
},
nitro: {
preset: 'node-server',
routeRules: {
'/api/generate/**': {
headers: {
'Cache-Control': 'no-cache, no-store, no-transform',
'X-Accel-Buffering': 'no'
}
},
'/api/prompt/**': {
headers: {
'Cache-Control': 'no-cache, no-store, no-transform'
}
}
}
preset: 'node-server'
}
})
+773 -687
View File
File diff suppressed because it is too large Load Diff
+9 -2
View File
@@ -9,13 +9,20 @@
"preview": "nuxt preview --host 0.0.0.0 --port 3000",
"postinstall": "nuxt prepare"
},
"engines": {
"node": ">=22.23.4 <23"
},
"dependencies": {
"nuxt": "^3.17.5",
"vue": "^3.5.13",
"nuxt": "^3.21.11",
"vue": "^3.5.44",
"vue-router": "^4.5.0"
},
"devDependencies": {
"@nuxtjs/tailwindcss": "^6.14.0",
"typescript": "^5.8.3"
},
"overrides": {
"seroval": "1.7.2",
"serialize-javascript": "7.1.4"
}
}
+239 -65
View File
@@ -87,15 +87,15 @@
>
{{ selectMode ? 'Done selecting' : 'Select' }}
</button>
<button v-if="entries.length" type="button" class="text-zinc-400 hover:text-white" @click="selectedKeys.length === entries.length ? clearSelection() : selectAll()">
{{ selectedKeys.length && selectedKeys.length === entries.length ? 'Clear selection' : 'Select all' }}
<button v-if="entries.length || folderWipeCount > 0" type="button" class="text-zinc-400 hover:text-white" @click="selectedKeys.length && selectedKeys.length === entries.length && !libraryLoading ? clearSelection() : selectAll()">
{{ selectedKeys.length && selectedKeys.length === entries.length && !libraryLoading ? 'Clear selection' : 'Select all' }}
</button>
<button
v-if="hasHiddenThumbs"
v-if="showPrivacyToggles && entries.length"
type="button"
class="rounded-full border px-2.5 py-1 text-[11px]"
:class="revealAll ? 'border-amber-300 bg-amber-400/10 text-amber-100' : 'border-white/10 text-zinc-400 hover:text-white'"
:title="revealAll ? 'Hide flagged thumbnails' : 'Reveal all hidden thumbnails'"
:title="revealAll ? 'Hide all thumbnails' : 'Reveal all thumbnails'"
@click="toggleRevealAll"
>
<span class="inline-flex items-center gap-1.5">
@@ -109,6 +109,13 @@
{{ revealAll ? 'Hide all' : 'Reveal all' }}
</span>
</button>
<button
v-if="browseFolder && folderId !== 'all' && (entries.length || folderWipeCount > 0)"
type="button"
class="text-red-300 hover:text-red-200"
:disabled="deleteBusy || wipeBusy"
@click="askWipeFolder"
>Delete all in this folder</button>
<button v-if="browseFolder?.protected && browseFolder.unlocked" type="button" class="text-zinc-400 hover:text-white" @click="lockFolder">Lock folder</button>
</div>
@@ -324,7 +331,7 @@
@click="focusPart(node.clip.id)"
>
<span class="relative h-12 w-12 shrink-0 overflow-hidden rounded bg-zinc-900">
<span v-if="node.clip.hideThumbnail" class="sensitive-glow block h-full w-full" />
<span v-if="showPrivacyToggles && !revealAll" class="sensitive-glow block h-full w-full" />
<img
v-else
:src="partThumb(node.clip)"
@@ -354,7 +361,7 @@
:class="part.id === focusedPartId ? 'ring-2 ring-amber-300' : ''"
@click="focusPart(part.id)"
>
<span v-if="('hideThumbnail' in part && part.hideThumbnail) || ('hideInput' in part && part.hideInput)" class="sensitive-glow block aspect-square w-full" />
<span v-if="showPrivacyToggles && !revealAll" class="sensitive-glow block aspect-square w-full" />
<img
v-else
:src="partThumb(part)"
@@ -488,6 +495,31 @@
</div>
</div>
</div>
<div
v-if="pendingWipe"
class="fixed inset-0 z-[70] flex items-center justify-center bg-black/70 p-4"
role="dialog"
aria-modal="true"
@click.self="pendingWipe = null"
>
<div class="glass w-full max-w-md rounded-3xl p-5 sm:p-6">
<h2 class="font-display text-xl font-bold">Delete all in this folder?</h2>
<p class="mt-2 text-sm font-medium text-zinc-100">{{ pendingWipe.name }}</p>
<p class="mt-1 text-xs text-zinc-500">{{ pendingWipe.count }} item{{ pendingWipe.count === 1 ? '' : 's' }} · images, videos, and music</p>
<p class="mt-3 text-sm text-zinc-400">Every still, clip, and track in this folder will be permanently removed from the library and disk.</p>
<div class="mt-5 flex flex-wrap justify-end gap-2">
<button type="button" class="rounded-full border border-white/15 px-4 py-2 text-sm text-zinc-300" @click="pendingWipe = null">Keep them</button>
<button
type="button"
class="rounded-full border border-red-400/40 bg-red-400/10 px-4 py-2 text-sm font-semibold text-red-200 disabled:opacity-50"
:disabled="wipeBusy"
@click="confirmWipeFolder"
>
Delete all
</button>
</div>
</div>
</div>
</Teleport>
<div class="pointer-events-none fixed bottom-4 right-4 z-50 space-y-2">
@@ -524,6 +556,7 @@ import {
type LibraryStill,
type LibraryTrack
} from '~/utils/libraryBrowse'
import { libraryAfterWipe, libraryMediaUrl, mergeLibraryRows } from '~/shared/studio2/viewer.mjs'
import { isXaigenStudio } from '~/utils/videoModels'
import { clipSettingsRows, stillSettingsRows, trackSettingsRows } from '~/utils/libraryGeneration'
@@ -601,6 +634,10 @@ const revealAll = ref(false)
const hidingFocused = ref(false)
const forceHiddenIds = ref<string[]>([])
const pendingDelete = ref<{ title: string; name: string; detail?: string; consequence: string; keys: string[] } | null>(null)
const pendingWipe = ref<{ folderId: string; name: string; count: number } | null>(null)
const wipeBusy = ref(false)
const libraryLoading = ref(false)
const catalogEpoch = ref(0)
const keepingInputBusy = ref(false)
const toasts = ref<Array<{ id: number; message: string }>>([])
let toastId = 0
@@ -613,6 +650,13 @@ const viewportW = ref(800)
const selectedSet = computed(() => new Set(selectedKeys.value))
const browseFolder = computed(() => folders.value.find(folder => folder.id === folderId.value) || null)
const folderWipeCount = computed(() => {
if (!browseFolder.value || folderId.value === 'all') return 0
const id = folderId.value
return stills.value.filter(item => item.folderId === id).length
+ clips.value.filter(item => item.folderId === id).length
+ tracks.value.filter(item => item.folderId === id).length
})
const entries = computed(() => buildLibraryEntries({
clips: clips.value,
stills: stills.value,
@@ -634,24 +678,6 @@ const allCount = computed(() => {
sort: 'date-desc'
}).length
})
const folderChipCounts = computed(() => {
const map: Record<string, { videos: number; images: number; music: number }> = {}
for (const clip of clips.value) {
if (clip.hasVideo === false) continue
const row = map[clip.folderId] || (map[clip.folderId] = { videos: 0, images: 0, music: 0 })
row.videos += 1
}
for (const still of stills.value) {
if (still.role !== 'output') continue
const row = map[still.folderId] || (map[still.folderId] = { videos: 0, images: 0, music: 0 })
row.images += 1
}
for (const track of tracks.value) {
const row = map[track.folderId] || (map[track.folderId] = { videos: 0, images: 0, music: 0 })
row.music += 1
}
return map
})
const moveFolders = computed(() => folders.value.filter(folder => folder.id !== folderId.value))
const focused = computed(() => entries.value.find(entry => entry.key === focusedKey.value) || null)
const focusedStill = computed(() => {
@@ -685,12 +711,13 @@ const visibleEntries = computed(() => {
const previewVideo = computed(() => {
if (focused.value?.kind !== 'clip' || !focused.value.group) return ''
const id = focusedPartId.value || focused.value.group.head.id
return `/api/library/clips/${id}/video`
return libraryMediaUrl(`/api/library/clips/${id}/video`, catalogEpoch.value)
})
const previewStillSrc = computed(() => {
if (focused.value?.kind !== 'still' || !focused.value.stillGroup) return ''
const id = focusedPartId.value || focused.value.stillGroup.head.id
return `/api/library/stills/${id}`
if (!stills.value.some(item => item.id === id)) return ''
return libraryMediaUrl(`/api/library/stills/${id}`, catalogEpoch.value)
})
const previewAudio = computed(() => {
if (focused.value?.kind !== 'track' || !focused.value.track) return ''
@@ -751,14 +778,14 @@ const detailMeta = computed(() => {
const downloadHref = computed(() => {
if (focused.value?.kind === 'clip' && focused.value.group) {
const id = focusedPartId.value || focused.value.group.head.id
return `/api/library/clips/${id}/video`
return libraryMediaUrl(`/api/library/clips/${id}/video`, catalogEpoch.value)
}
if (focused.value?.kind === 'track' && focused.value.track) {
return `/api/library/tracks/${focused.value.track.id}/audio`
return libraryMediaUrl(`/api/library/tracks/${focused.value.track.id}/audio`, catalogEpoch.value)
}
if (focused.value?.stillGroup) {
const id = focusedPartId.value || focused.value.stillGroup.head.id
return `/api/library/stills/${id}`
return libraryMediaUrl(`/api/library/stills/${id}`, catalogEpoch.value)
}
return ''
})
@@ -771,7 +798,8 @@ function toast(message: string) {
}, 4200)
}
function applyLibrary(data: unknown) {
function applyLibrary(data: unknown, opts?: { replace?: boolean }) {
const replace = opts?.replace !== false
const payload = (data || {}) as {
id?: string
hideInput?: boolean
@@ -780,6 +808,9 @@ function applyLibrary(data: unknown) {
clips?: LibraryClip[]
stills?: LibraryStill[]
tracks?: LibraryTrack[]
nextCursor?: string | null
hasMore?: boolean
catalogEpoch?: number
}
if (payload.id && !payload.folders && !payload.clips && !payload.stills && !payload.tracks) {
if (typeof payload.hideInput === 'boolean') {
@@ -792,27 +823,68 @@ function applyLibrary(data: unknown) {
}
return
}
folders.value = payload.folders || []
clips.value = payload.clips || []
stills.value = payload.stills || []
tracks.value = payload.tracks || []
if (payload.folders?.length) folders.value = payload.folders
if (typeof payload.catalogEpoch === 'number') catalogEpoch.value = payload.catalogEpoch
const rows = <T,>(list: T[] | undefined) => (Array.isArray(list) ? list : []).filter(item => (item as { id?: string })?.id)
if (replace) {
clips.value = rows(payload.clips)
stills.value = rows(payload.stills)
tracks.value = rows(payload.tracks)
} else {
clips.value = mergeLibraryRows(clips.value, payload.clips || [], [])
stills.value = mergeLibraryRows(stills.value, payload.stills || [], [])
tracks.value = mergeLibraryRows(tracks.value, payload.tracks || [], [])
}
libraryNextCursor.value = payload.nextCursor || null
if (folderId.value !== 'all' && !folders.value.some(folder => folder.id === folderId.value)) {
folderId.value = folders.value[0]?.id || 'all'
}
}
const libraryNextCursor = ref<string | null>(null)
let libraryFetchGen = 0
async function fetchLibraryPage(cursor: string | null) {
const qs = new URLSearchParams({ limit: '50', _: String(Date.now()) })
if (folderId.value && folderId.value !== 'all') qs.set('folderId', folderId.value)
if (filter.value === 'images') qs.set('type', 'images')
else if (filter.value === 'videos') qs.set('type', 'videos')
else if (filter.value === 'music') qs.set('type', 'music')
if (cursor) qs.set('cursor', cursor)
return await $fetch<any>(`/api/library?${qs.toString()}`)
}
async function loadLibrary() {
applyLibrary(await $fetch('/api/library?light=1'))
// First page paints immediately; remaining pages append in the background
const gen = ++libraryFetchGen
libraryLoading.value = true
try {
const first = await fetchLibraryPage(null)
if (gen !== libraryFetchGen) return
applyLibrary(first, { replace: true })
let cursor = first?.nextCursor || null
while (cursor && gen === libraryFetchGen) {
const page = await fetchLibraryPage(cursor)
if (gen !== libraryFetchGen) return
applyLibrary(page, { replace: false })
cursor = page?.nextCursor || null
}
} finally {
if (gen === libraryFetchGen) libraryLoading.value = false
}
}
async function ensureLibraryFullyLoaded() {
if (!libraryLoading.value && !libraryNextCursor.value) return
await loadLibrary()
}
function folderChipCount(folder: LibraryFolder) {
if (!folder.unlocked) return (folder.clipCount || 0) + (folder.imageCount || 0) + (folder.trackCount || 0)
const row = folderChipCounts.value[folder.id]
if (!row) return 0
if (filter.value === 'videos') return row.videos
if (filter.value === 'images') return row.images
if (filter.value === 'music') return row.music
return row.videos + row.images + row.music
// Prefer server totals so chips match the full folder before pages finish appending
if (filter.value === 'videos') return folder.clipCount || 0
if (filter.value === 'images') return folder.imageCount || 0
if (filter.value === 'music') return folder.trackCount || 0
return (folder.clipCount || 0) + (folder.imageCount || 0) + (folder.trackCount || 0)
}
function folderChipClass(id: string) {
@@ -828,24 +900,18 @@ function cardClass(entry: LibraryEntry) {
return selectMode.value ? 'border-amber-300/25' : 'border-white/10'
}
function itemHidden(entry: LibraryEntry) {
if (entry.kind === 'clip') return Boolean(entry.group?.head.hideThumbnail)
if (entry.kind === 'track') return false
return Boolean(entry.stillGroup?.parts[cardImageIndex(entry)]?.hideInput)
}
function thumbHidden(entry: LibraryEntry) {
if (!showPrivacyToggles.value || entry.kind === 'track') return false
const id = entry.kind === 'clip' ? entry.group?.head.id : entry.stillGroup?.parts[cardImageIndex(entry)]?.id
if (id && forceHiddenIds.value.includes(id)) return true
return itemHidden(entry) && !revealAll.value
// Session cover for the whole grid — not limited to individually flagged items.
return !revealAll.value
}
const hasHiddenThumbs = computed(() => entries.value.some(entry => itemHidden(entry)))
function toggleRevealAll() {
revealAll.value = !revealAll.value
forceHiddenIds.value = []
if (focused.value && itemHidden(focused.value)) {
if (focused.value && focused.value.kind !== 'track') {
detailsHidden.value = !revealAll.value
}
}
@@ -885,9 +951,14 @@ async function toggleFocusedHidden() {
}
function thumbSrc(entry: LibraryEntry) {
if (entry.kind === 'clip' && entry.group) return `/api/library/clips/${entry.group.head.id}/thumb`
const version = catalogEpoch.value
if (entry.kind === 'clip' && entry.group) return libraryMediaUrl(`/api/library/clips/${entry.group.head.id}/thumb`, version)
if (entry.kind === 'track') return ''
if (entry.stillGroup) return `/api/library/stills/${entry.stillGroup.parts[cardImageIndex(entry)].id}?thumb=1`
if (entry.stillGroup) {
const id = entry.stillGroup.parts[cardImageIndex(entry)]?.id
if (!id || !stills.value.some(item => item.id === id)) return ''
return libraryMediaUrl(`/api/library/stills/${id}/thumb`, version)
}
return ''
}
@@ -911,9 +982,9 @@ function partThumb(part: LibraryClip | LibraryStill) {
if ('hideThumbnail' in part && !('role' in part)) {
const clip = part as LibraryClip
// Prefer this clip’s first frame so siblings don’t all look like the Start thumb.
return `/api/library/clips/${clip.id}/first-frame?thumb=1&v=${encodeURIComponent(clip.id)}`
return libraryMediaUrl(`/api/library/clips/${clip.id}/first-frame?thumb=1`, catalogEpoch.value)
}
return `/api/library/stills/${part.id}?thumb=1`
return libraryMediaUrl(`/api/library/stills/${part.id}/thumb`, catalogEpoch.value)
}
function focusPart(id: string) {
@@ -961,7 +1032,18 @@ function toggleSelectMode() {
if (selectMode.value) clearFocus()
}
function selectAll() {
function entryPartIds(entry: LibraryEntry) {
if (entry.kind === 'clip' && entry.group) return (entry.group.parts || [entry.group.head]).map(part => part.id)
if (entry.kind === 'track' && entry.track) return [entry.track.id]
if (entry.stillGroup) return (entry.stillGroup.parts || [entry.stillGroup.head]).map(part => part.id)
return []
}
async function selectAll() {
const start = Date.now()
while (libraryLoading.value && Date.now() - start < 15000) {
await new Promise(resolve => setTimeout(resolve, 40))
}
selectedKeys.value = entries.value.map(entry => entry.key)
lastSelectedKey.value = selectedKeys.value.at(-1) || ''
}
@@ -996,7 +1078,7 @@ function onCardClick(entry: LibraryEntry, event: MouseEvent) {
: entry.kind === 'track'
? (entry.track?.id || '')
: (entry.stillGroup?.parts[cardImageIndex(entry)]?.id || '')
if (!sameCard) detailsHidden.value = itemHidden(entry) && !revealAll.value
if (!sameCard) detailsHidden.value = thumbHidden(entry)
cancelRename()
}
@@ -1203,6 +1285,14 @@ function askRemoveKeys(keys: string[]) {
}
}
function dropLocalIds(ids: string[]) {
if (!ids.length) return
const gone = new Set(ids)
stills.value = stills.value.filter(item => !gone.has(item.id))
clips.value = clips.value.filter(item => !gone.has(item.id))
tracks.value = tracks.value.filter(item => !gone.has(item.id))
}
async function confirmDelete() {
const pending = pendingDelete.value
if (!pending || deleteBusy.value) return
@@ -1210,7 +1300,18 @@ async function confirmDelete() {
deleteBusy.value = true
try {
const items = selectedEntries(pending.keys)
await Promise.allSettled(items.map((entry) => {
const gone: string[] = []
for (const entry of items) {
if (entry.kind === 'clip' && entry.group) {
for (const part of entry.group.parts || [entry.group.head]) gone.push(part.id)
} else if (entry.kind === 'track' && entry.track) {
gone.push(entry.track.id)
} else if (entry.stillGroup) {
for (const part of entry.stillGroup.parts || [entry.stillGroup.head]) gone.push(part.id)
}
}
libraryFetchGen += 1
const results = await Promise.allSettled(items.map((entry) => {
if (entry.kind === 'clip') {
return $fetch(`/api/library/clips/${entry.group!.head.id}`, { method: 'DELETE', query: { family: '1' } })
}
@@ -1219,6 +1320,22 @@ async function confirmDelete() {
}
return $fetch(`/api/library/stills/${entry.stillGroup!.head.id}`, { method: 'DELETE', query: { family: '1' } })
}))
const removed: string[] = []
results.forEach((result, index) => {
if (result.status === 'fulfilled') {
const entry = items[index]
removed.push(...entryPartIds(entry))
return
}
const status = Number((result.reason as { statusCode?: number, status?: number })?.statusCode || (result.reason as { status?: number })?.status || 0)
if (status === 404) removed.push(...entryPartIds(items[index]))
})
if (removed.length !== gone.length) {
const failed = results.find(result => result.status === 'rejected') as PromiseRejectedResult | undefined
const reason = failed?.reason as { data?: { statusMessage?: string }, message?: string } | undefined
toast(reason?.data?.statusMessage || reason?.message || 'Could not delete every item')
}
dropLocalIds(removed)
if (pending.keys.includes(focusedKey.value)) {
focusedKey.value = ''
focusedPartId.value = ''
@@ -1230,6 +1347,59 @@ async function confirmDelete() {
}
}
async function askWipeFolder() {
if (!browseFolder.value || folderId.value === 'all' || wipeBusy.value) return
await ensureLibraryFullyLoaded()
const count = folderWipeCount.value
if (!count) {
toast('This folder is already empty.')
return
}
pendingWipe.value = {
folderId: folderId.value,
name: browseFolder.value.name,
count
}
}
async function confirmWipeFolder() {
const pending = pendingWipe.value
if (!pending || wipeBusy.value) return
pendingWipe.value = null
wipeBusy.value = true
libraryFetchGen += 1
const gone = [
...stills.value.filter(item => item.folderId === pending.folderId).map(item => item.id),
...clips.value.filter(item => item.folderId === pending.folderId).map(item => item.id),
...tracks.value.filter(item => item.folderId === pending.folderId).map(item => item.id)
]
clearSelection()
clearFocus()
try {
const result = await $fetch<any>(`/api/library/folders/${pending.folderId}/wipe`, { method: 'POST' })
const next = libraryAfterWipe({
folders: folders.value,
stills: [...stills.value, ...gone.map(id => ({ id, folderId: pending.folderId }))],
clips: clips.value,
tracks: tracks.value,
suppressedIds: []
}, result, pending.folderId)
if (typeof result?.catalogEpoch === 'number') catalogEpoch.value = result.catalogEpoch
folders.value = next.folders
stills.value = next.stills
clips.value = next.clips
tracks.value = next.tracks
libraryNextCursor.value = null
toast(`Deleted ${result.deleted ?? pending.count} from ${pending.name}.`)
await loadLibrary()
} catch (error: any) {
toast(error?.data?.statusMessage || 'Could not empty that folder')
await loadLibrary()
} finally {
wipeBusy.value = false
}
}
async function unlockFolder() {
if (!browseFolder.value) return
try {
@@ -1253,7 +1423,8 @@ function onKey(event: KeyboardEvent) {
const target = event.target as HTMLElement | null
const typing = Boolean(target && (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.tagName === 'SELECT' || target.isContentEditable))
if (event.key === 'Escape') {
if (pendingDelete.value) pendingDelete.value = null
if (pendingWipe.value) pendingWipe.value = null
else if (pendingDelete.value) pendingDelete.value = null
else if (lightboxOpen.value) lightboxOpen.value = false
else if (renaming.value) cancelRename()
else if (focusedKey.value) clearFocus()
@@ -1262,7 +1433,7 @@ function onKey(event: KeyboardEvent) {
}
if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === 'a' && !renaming.value) {
event.preventDefault()
selectAll()
void selectAll()
}
if (event.key === 'Delete' && selectedKeys.value.length && !renaming.value) askRemoveSelected()
if (!typing && (event.key === 'ArrowLeft' || event.key === 'ArrowRight') && focusedNavParts.value.length > 1) {
@@ -1284,6 +1455,10 @@ watch([folderId, filter], () => {
watch(search, () => {
if (scroller.value) scroller.value.scrollTop = 0
})
watch([folderId, filter], () => {
if (scroller.value) scroller.value.scrollTop = 0
void loadLibrary()
})
watch([cols, rowH], ([nextCols, nextRowH], [prevCols, prevRowH]) => {
const el = scroller.value
if (!el || !prevRowH) return
@@ -1315,10 +1490,9 @@ let resizeObserver: ResizeObserver | null = null
let observedScroller: HTMLElement | null = null
onMounted(async () => {
window.addEventListener('keydown', onKey)
const [me] = await Promise.all([
$fetch<{ user?: { name?: string; email?: string }; authEnabled?: boolean; authMode?: string; instanceName?: string }>('/api/auth/me').catch(() => ({ user: null })),
loadLibrary().catch(() => applyLibrary({ folders: [], clips: [], stills: [] }))
])
// Do not block chrome/grid on the full catalog — first page paints via loadLibrary's first apply
void loadLibrary().catch(() => applyLibrary({ folders: [], clips: [], stills: [] }))
const me = await $fetch<{ user?: { name?: string; email?: string }; authEnabled?: boolean; authMode?: string; instanceName?: string }>('/api/auth/me').catch(() => ({ user: null }))
instanceName.value = me.instanceName || instanceName.value
await nextTick()
measure()
File diff suppressed because it is too large Load Diff
+2 -2
View File
@@ -961,8 +961,8 @@ async function loadLog(entry: GenerationLogEntry) {
kind: entry.kind,
payload: entry.payload
}))
if (entry.kind === 'music') {
await navigateTo('/music')
if (entry.payload?.studio2Id || entry.payload?.studio2Request || entry.kind === 'music') {
await navigateTo(entry.kind === 'music' ? '/studio-2?task=music' : '/studio-2')
} else {
await navigateTo('/')
}
+105 -44
View File
@@ -140,8 +140,8 @@
class="rounded-full border px-3 py-1 text-xs font-medium disabled:cursor-not-allowed disabled:opacity-40"
:class="(v2Mode === 'edit' || v2Mode === 'generate') ? 'border-amber-300/70 bg-amber-400/10 text-amber-100' : 'border-white/10 text-zinc-400 hover:text-white'"
:disabled="v2ModeLocked && v2Mode !== 'edit' && v2Mode !== 'generate'"
:title="v2ModeLocked && v2Mode !== 'edit' && v2Mode !== 'generate' ? 'Remove extra passes to change graphs' : 'Uses your image when one is provided; otherwise generates from text'"
@click="setV2Mode('edit')"
:title="v2Engine === 'moss' ? 'MOSS-Image stays on text-to-image' : v2ModeLocked && v2Mode !== 'edit' && v2Mode !== 'generate' ? 'Remove extra passes to change graphs' : 'Uses your image when one is provided; otherwise generates from text'"
@click="setV2Mode(v2Engine === 'moss' ? 'generate' : 'edit')"
>
Image
</button>
@@ -149,8 +149,8 @@
type="button"
class="rounded-full border px-3 py-1 text-xs font-medium disabled:cursor-not-allowed disabled:opacity-40"
:class="v2Mode === 'compose' ? 'border-amber-300/70 bg-amber-400/10 text-amber-100' : 'border-white/10 text-zinc-400 hover:text-white'"
:disabled="v2ModeLocked && v2Mode !== 'compose'"
:title="v2ModeLocked && v2Mode !== 'compose' ? 'Remove extra passes to change graphs' : ''"
:disabled="v2Engine === 'moss' || (v2ModeLocked && v2Mode !== 'compose')"
:title="v2Engine === 'moss' ? 'MOSS-Image is text-to-image only' : v2ModeLocked && v2Mode !== 'compose' ? 'Remove extra passes to change graphs' : ''"
@click="setV2Mode('compose')"
>
Compose
@@ -159,8 +159,8 @@
type="button"
class="rounded-full border px-3 py-1 text-xs font-medium disabled:cursor-not-allowed disabled:opacity-40"
:class="v2Mode === 'refine' ? 'border-amber-300/70 bg-amber-400/10 text-amber-100' : 'border-white/10 text-zinc-400 hover:text-white'"
:disabled="v2ModeLocked && v2Mode !== 'refine'"
:title="v2ModeLocked && v2Mode !== 'refine' ? 'Remove extra passes to change graphs' : ''"
:disabled="v2Engine === 'moss' || (v2ModeLocked && v2Mode !== 'refine')"
:title="v2Engine === 'moss' ? 'MOSS-Image is text-to-image only' : v2ModeLocked && v2Mode !== 'refine' ? 'Remove extra passes to change graphs' : ''"
@click="setV2Mode('refine')"
>
Refine
@@ -169,8 +169,8 @@
type="button"
class="rounded-full border px-3 py-1 text-xs font-medium disabled:cursor-not-allowed disabled:opacity-40"
:class="v2Mode === 'iterate' ? 'border-amber-300/70 bg-amber-400/10 text-amber-100' : 'border-white/10 text-zinc-400 hover:text-white'"
:disabled="v2ModeLocked && v2Mode !== 'iterate'"
:title="v2ModeLocked && v2Mode !== 'iterate' ? 'Remove extra passes to change graphs' : ''"
:disabled="v2Engine === 'moss' || (v2ModeLocked && v2Mode !== 'iterate')"
:title="v2Engine === 'moss' ? 'MOSS-Image is text-to-image only' : v2ModeLocked && v2Mode !== 'iterate' ? 'Remove extra passes to change graphs' : ''"
@click="setV2Mode('iterate')"
>
Iterate
@@ -440,7 +440,7 @@
:base-steps="v2Steps"
:base-cfg="v2Cfg"
:lora-names="imageV2LoraOptions"
:engine="v2Engine"
:engine="v2Engine === 'krea' ? 'krea' : 'flux'"
:allow-strength="v2Engine === 'krea' && Boolean(file)"
@update:model-value="editPassQueue[index] = { ...$event, id: item.id }"
/>
@@ -752,7 +752,8 @@
<label class="block space-y-2 text-sm">
<span>Model</span>
<select v-if="imageStudio" :value="v2Engine" class="w-full rounded-xl border border-white/15 bg-zinc-900 p-3" @change="setV2Engine(($event.target as HTMLSelectElement).value as ImageV2Engine)"><option value="flux">Flux Klein 9B</option><option value="krea">Krea 2 Turbo</option></select>
<select v-if="imageStudio" :value="v2Engine" class="w-full rounded-xl border border-white/15 bg-zinc-900 p-3" @change="setV2Engine(($event.target as HTMLSelectElement).value as ImageV2Engine)"><option value="flux">Flux Klein 9B</option><option value="krea">Krea 2 Turbo</option><option value="moss">MOSS-Image</option></select>
<p v-if="imageStudio && v2Engine === 'moss'" class="text-[11px] leading-snug text-zinc-500">Text-to-image only. INT8 SFT, text encoder on CPU, 25 steps, CFG 2.5, shift 5. Starts at 1024×1024.</p>
<select v-else :value="videoEngine" class="w-full rounded-xl border border-white/15 bg-zinc-900 p-3" @change="selectVideoEngine(($event.target as HTMLSelectElement).value as VideoEngineId)"><option value="minimax">MiniMax H3</option><option v-if="ltxEnabled" value="ltx">LTX 2.3</option></select>
</label>
<div v-if="studioMode === 'video'" class="max-w-md space-y-2">
@@ -811,6 +812,7 @@
@update-trigger="saveLoraTrigger"
/>
<p v-if="v2Engine === 'krea'" class="mt-1 text-[11px] text-zinc-500">Krea only lists krea LoRAs. Flux files stay on the Flux engine.</p>
<p v-else-if="v2Engine === 'moss'" class="text-[11px] text-zinc-500">MOSS lists moss LoRAs. Klein and Krea files stay on those engines. The prompt upsampler stays off.</p>
</div>
<div>
<AspectRatioPick :model-value="aspect" heading="Aspect ratio" :options="imageAspects" @update:model-value="setImageAspect" />
@@ -903,7 +905,7 @@
</span>
<input v-model="seedInput" class="w-full rounded-xl border border-white/10 bg-zinc-950 px-3 py-2 text-sm" placeholder="random">
</label>
<label v-if="v2Engine !== 'krea'" class="flex cursor-pointer items-center gap-2 text-xs text-zinc-400">
<label v-if="v2Engine === 'flux'" class="flex cursor-pointer items-center gap-2 text-xs text-zinc-400">
<span class="relative inline-flex h-5 w-9 shrink-0 items-center">
<input v-model="v2Turbo" type="checkbox" class="peer sr-only" role="switch">
<span class="absolute inset-0 rounded-full bg-zinc-700 transition peer-checked:bg-amber-400" />
@@ -1784,7 +1786,7 @@
@click="openClip(entry.group.head)"
>
<span v-if="entry.group.head.hideThumbnail" class="sensitive-glow block h-full w-full" />
<img v-else :src="`/api/library/clips/${entry.group.head.id}/thumb`" alt="" loading="lazy" decoding="async" class="h-full w-full object-cover">
<img v-else :src="`/api/library/clips/${entry.group.head.id}/thumb?v=0`" alt="" loading="lazy" decoding="async" class="h-full w-full object-cover">
</button>
<div class="min-w-0 flex-1">
<div class="flex items-start gap-2">
@@ -1999,7 +2001,7 @@
<span v-if="entry.stillGroup.head.hideInput" class="sensitive-glow block h-full w-full" />
<img
v-else
:src="`/api/library/stills/${entry.stillGroup.head.id}?thumb=1`"
:src="`/api/library/stills/${entry.stillGroup.head.id}?thumb=1&v=0`"
alt=""
loading="lazy"
decoding="async"
@@ -2090,7 +2092,7 @@
>
<button type="button" class="relative h-12 w-12 shrink-0 overflow-hidden rounded-lg bg-zinc-900" @click="openStill(item)">
<span v-if="item.hideInput" class="sensitive-glow block h-full w-full" />
<img v-else :src="`/api/library/stills/${item.id}?thumb=1`" alt="" loading="lazy" decoding="async" class="h-full w-full object-cover">
<img v-else :src="`/api/library/stills/${item.id}?thumb=1&v=0`" alt="" loading="lazy" decoding="async" class="h-full w-full object-cover">
</button>
<div class="min-w-0 flex-1">
<div class="flex items-start gap-2">
@@ -2375,14 +2377,19 @@ import {
IMAGE_V2_STEPS_DEFAULT,
clampImageV2Denoise,
defaultImageV2LoraStack,
IMAGE_V2_LOOK_STORAGE_KEY,
defaultImageV2EngineLook,
imageV2ConceptLoraName,
imageV2SamplingDefaults,
isImageV2ConceptLora,
isImageV2ConsistencyLora,
mergeLegacyImageV2Loras,
parseImageV2Engine,
readImageV2LookState,
removeImageV2ConceptLora,
upsertImageV2Lora,
type ImageV2Engine,
type ImageV2EngineLook,
type ImageV2Mode,
type ImageV2PresetSettings,
type ImageV2Task
@@ -2430,6 +2437,10 @@ function chooseSimpleTask(task: string) {
closeExtend()
editingTask.value = task === 'Edit'
if (task === 'Edit') selectStudioKind('image')
if (v2Engine.value === 'moss' && task !== 'From text') {
toast('MOSS-Image is text-to-image only. Switch to Klein or Krea to use a still.')
return
}
if (task === 'From text') {
resetImage()
if (imageStudio.value) v2Mode.value = editPassQueue.value.length ? 'iterate' : 'generate'
@@ -2765,7 +2776,9 @@ const editRefFile = ref<File | null>(null)
const editRefPreview = ref('')
const selectedV2Mode = ref<ImageV2Mode>('edit')
const v2Mode = computed<ImageV2Mode>({
get: () => imageModeForInput(selectedV2Mode.value, Boolean(file.value), editPassQueue.value.length > 0),
get: () => v2Engine.value === 'moss'
? 'generate'
: imageModeForInput(selectedV2Mode.value, Boolean(file.value), editPassQueue.value.length > 0),
set: mode => { selectedV2Mode.value = mode }
})
const v2Engine = ref<ImageV2Engine>('flux')
@@ -2774,9 +2787,42 @@ const v2Task = ref<ImageV2Task>('scene')
const v2Negative = ref('')
const v2Steps = ref(IMAGE_V2_STEPS_DEFAULT)
const v2Cfg = ref(IMAGE_V2_CFG_DEFAULT)
const v2Looks = reactive<Record<ImageV2Engine, ImageV2EngineLook>>({
flux: defaultImageV2EngineLook('flux'),
krea: defaultImageV2EngineLook('krea'),
moss: defaultImageV2EngineLook('moss')
})
let restoringV2Look = false
function rememberV2Look(engine: ImageV2Engine = v2Engine.value) {
if (restoringV2Look || !import.meta.client) return
const sampling = imageV2SamplingDefaults(engine)
v2Looks[engine] = {
steps: clampImageSteps(v2Steps.value, sampling.steps),
cfg: clampImageCfg(v2Cfg.value, sampling.cfg),
turbo: engine === 'flux' && v2Turbo.value === true
}
try {
localStorage.setItem(IMAGE_V2_LOOK_STORAGE_KEY, JSON.stringify({ engine: v2Engine.value, ...v2Looks }))
} catch { /* ignore */ }
}
function applyV2Look(engine: ImageV2Engine) {
const row = v2Looks[engine] || defaultImageV2EngineLook(engine)
restoringV2Look = true
v2Steps.value = row.steps
v2Cfg.value = row.cfg
v2Turbo.value = engine === 'flux' && row.turbo === true
restoringV2Look = false
}
function v2StepsFallback(engine: ImageV2Engine = v2Engine.value) {
return imageV2SamplingDefaults(engine).steps
}
function v2CfgFallback(engine: ImageV2Engine = v2Engine.value) {
return imageV2SamplingDefaults(engine).cfg
}
const v2Megapixels = ref(IMAGE_SCALE_MP_DEFAULT)
const v2ScaleOn = ref(true)
const v2Turbo = ref(false)
watch([v2Steps, v2Cfg, v2Turbo], () => rememberV2Look())
const v2Width = ref(IMAGE_V2_GENERATE_WIDTH)
const v2Height = ref(IMAGE_V2_GENERATE_HEIGHT)
const v2Denoise = ref(IMAGE_V2_DENOISE_DEFAULT)
@@ -4105,6 +4151,17 @@ onMounted(async () => {
imageLoras.value = readStoredLoraNames('aigen-lora-names-image')
imageV2LoraStack.value = readImageV2LoraStack(v2Engine.value)
seedImageV2LorasIfEmpty()
try {
const saved = readImageV2LookState(JSON.parse(localStorage.getItem(IMAGE_V2_LOOK_STORAGE_KEY) || '{}'))
Object.assign(v2Looks, saved.looks)
if (saved.engine !== 'flux') {
v2Engine.value = saved.engine
if (saved.engine === 'moss') selectedV2Mode.value = 'generate'
imageV2LoraStack.value = readImageV2LoraStack(saved.engine)
seedImageV2LorasIfEmpty()
}
applyV2Look(v2Engine.value)
} catch { /* ignore */ }
globalLocks.value = localStorage.getItem(LOCKS_STORE) || ''
try {
const savedRefs = JSON.parse(localStorage.getItem(REFS_STORE) || '')
@@ -4673,8 +4730,8 @@ function currentPresetSnapshot() {
snofsClip: imageV2EngineLoras().find(item => isImageV2ConceptLora(item.name))?.strengthClip ?? 0,
consistencyModel: imageV2EngineLoras().find(item => isImageV2ConsistencyLora(item.name))?.strengthModel ?? 0,
consistencyClip: imageV2EngineLoras().find(item => isImageV2ConsistencyLora(item.name))?.strengthClip ?? 0,
steps: clampImageSteps(v2Steps.value, v2Engine.value === 'krea' ? IMAGE_V2_KREA_STEPS : IMAGE_V2_STEPS_DEFAULT),
cfg: clampImageCfg(v2Cfg.value, v2Engine.value === 'krea' ? IMAGE_V2_KREA_CFG : IMAGE_V2_CFG_DEFAULT),
steps: clampImageSteps(v2Steps.value, v2StepsFallback()),
cfg: clampImageCfg(v2Cfg.value, v2CfgFallback()),
megapixels: v2Mode.value === 'generate' || !v2ScaleOn.value ? undefined : clampImageScaleMegapixels(v2Megapixels.value, 1),
scaleToTotalPixels: v2Mode.value === 'generate' ? undefined : v2ScaleOn.value,
turbo: v2Turbo.value === true,
@@ -4734,6 +4791,7 @@ function applyGenerationPreset(preset: GenerationPreset) {
: 'edit'
if (v2Mode.value !== 'edit' && v2Mode.value !== 'compose') clearEditPasses()
v2Engine.value = parseImageV2Engine(settings.engine, 'flux')
if (v2Engine.value === 'moss') selectedV2Mode.value = 'generate'
v2Task.value = v2Mode.value === 'compose' ? (settings.task || 'scene') : v2Mode.value === 'refine' ? 'refine' : v2Mode.value === 'generate' ? 't2i' : 'scene'
if (typeof settings.prompt === 'string') prompt.value = settings.prompt
if (typeof settings.negative === 'string') v2Negative.value = settings.negative
@@ -4747,11 +4805,11 @@ function applyGenerationPreset(preset: GenerationPreset) {
consistencyClip: settings.consistencyClip,
kreaConcept: String(runtimeConfig.public.kreaConceptLora || IMAGE_V2_KREA_CONCEPT_LORA || '').trim()
})
v2Steps.value = clampImageSteps(settings.steps, v2Engine.value === 'krea' ? IMAGE_V2_KREA_STEPS : IMAGE_V2_STEPS_DEFAULT)
v2Cfg.value = clampImageCfg(settings.cfg, v2Engine.value === 'krea' ? IMAGE_V2_KREA_CFG : IMAGE_V2_CFG_DEFAULT)
v2Steps.value = clampImageSteps(settings.steps, v2StepsFallback())
v2Cfg.value = clampImageCfg(settings.cfg, v2CfgFallback())
v2Megapixels.value = clampImageScaleMegapixels(settings.megapixels, 1)
v2ScaleOn.value = v2Mode.value !== 'generate' && settings.scaleToTotalPixels !== false
v2Turbo.value = settings.turbo === true
v2Turbo.value = v2Engine.value === 'flux' && settings.turbo === true
if (v2Mode.value === 'refine' || (v2Engine.value === 'krea' && v2Mode.value !== 'generate')) v2Denoise.value = clampImageV2Denoise(settings.strength)
aspect.value = parseImageAspect(settings.aspect)
if (v2Mode.value === 'generate') {
@@ -5534,7 +5592,7 @@ async function restoreStudioEditJob(payload: {
imagePipeline?: 'v1' | 'v2'
v2Mode?: 'edit' | 'compose' | 'refine' | 'generate' | 'iterate'
v2Task?: 'scene' | 'identity' | 'outfit' | 'face_lock' | 'refine' | 't2i'
engine?: 'flux' | 'krea'
engine?: ImageV2Engine
snofsModel?: number
snofsClip?: number
consistencyModel?: number
@@ -5571,12 +5629,13 @@ async function restoreStudioEditJob(payload: {
setV2Mode(mode)
persistImageV2LoraStack(imageV2LoraStack.value, v2Engine.value)
v2Engine.value = parseImageV2Engine(payload.engine, 'flux')
if (v2Engine.value === 'moss') selectedV2Mode.value = 'generate'
if (typeof payload.negative === 'string') v2Negative.value = payload.negative
if (payload.steps != null) v2Steps.value = clampImageSteps(payload.steps, v2Engine.value === 'krea' ? IMAGE_V2_KREA_STEPS : IMAGE_V2_STEPS_DEFAULT)
if (payload.cfg != null) v2Cfg.value = clampImageCfg(payload.cfg, v2Engine.value === 'krea' ? IMAGE_V2_KREA_CFG : IMAGE_V2_CFG_DEFAULT)
if (payload.steps != null) v2Steps.value = clampImageSteps(payload.steps, v2StepsFallback())
if (payload.cfg != null) v2Cfg.value = clampImageCfg(payload.cfg, v2CfgFallback())
if (payload.scaleMegapixels != null) v2Megapixels.value = clampImageScaleMegapixels(payload.scaleMegapixels, 1)
v2ScaleOn.value = mode !== 'generate' && payload.scaleToTotalPixels !== false
v2Turbo.value = payload.turbo === true
v2Turbo.value = v2Engine.value === 'flux' && payload.turbo === true
if ((mode === 'refine' || (v2Engine.value === 'krea' && mode !== 'generate')) && payload.refineStrength != null) {
v2Denoise.value = clampImageV2Denoise(payload.refineStrength)
}
@@ -5674,7 +5733,7 @@ async function restoreStudioPayload(kind: string, payload: {
imagePipeline?: 'v1' | 'v2'
v2Mode?: 'edit' | 'compose' | 'refine' | 'generate' | 'iterate'
v2Task?: 'scene' | 'identity' | 'outfit' | 'face_lock' | 'refine' | 't2i'
engine?: 'flux' | 'krea'
engine?: ImageV2Engine
snofsModel?: number
snofsClip?: number
consistencyModel?: number
@@ -5922,10 +5981,10 @@ function stepOutput(delta: number) {
}
function showOutputStill(still: LibraryStill) {
editResultUrl.value = `/api/library/stills/${still.id}`
editResultUrl.value = `/api/library/stills/${still.id}?v=0`
lastV2StillId.value = still.id
editDownloadName.value = clipFileName(stillTitle(still))
if (editLightboxUrl.value) editLightboxUrl.value = `/api/library/stills/${still.id}`
if (editLightboxUrl.value) editLightboxUrl.value = `/api/library/stills/${still.id}?v=0`
}
function stepOutputFamily(delta: number) {
@@ -6455,7 +6514,7 @@ function openStill(still: LibraryStill) {
// Preview only — never yank Video/Image workspace tabs.
outputFocus.value = 'edit'
browseFolderId.value = still.folderId
editResultUrl.value = `/api/library/stills/${still.id}`
editResultUrl.value = `/api/library/stills/${still.id}?v=0`
concealEditOutput.value = still.hideInput === true
editAwaitingReveal.value = still.hideInput === true
editLockedSave.value = false
@@ -6488,13 +6547,14 @@ function applyStillSettings(still: LibraryStill) {
setV2Mode(mode)
persistImageV2LoraStack(imageV2LoraStack.value, v2Engine.value)
v2Engine.value = parseImageV2Engine(settings?.engine, 'flux')
if (v2Engine.value === 'moss') selectedV2Mode.value = 'generate'
if (!settings) return
v2Negative.value = settings.negative || ''
if (settings.steps != null) v2Steps.value = clampImageSteps(settings.steps, IMAGE_V2_STEPS_DEFAULT)
if (settings.cfg != null) v2Cfg.value = clampImageCfg(settings.cfg, IMAGE_V2_CFG_DEFAULT)
if (settings.steps != null) v2Steps.value = clampImageSteps(settings.steps, v2StepsFallback())
if (settings.cfg != null) v2Cfg.value = clampImageCfg(settings.cfg, v2CfgFallback())
if (settings.megapixels != null) v2Megapixels.value = clampImageScaleMegapixels(settings.megapixels, 1)
v2ScaleOn.value = mode !== 'generate' && settings.scaleToTotalPixels !== false
v2Turbo.value = settings.turbo === true
v2Turbo.value = v2Engine.value === 'flux' && settings.turbo === true
if ((mode === 'refine' || (v2Engine.value === 'krea' && mode !== 'generate')) && settings.strength != null) v2Denoise.value = clampImageV2Denoise(settings.strength)
aspect.value = parseImageAspect(settings.aspect)
if (mode === 'generate') {
@@ -7250,6 +7310,11 @@ async function editImage() {
}
function setV2Mode(mode: ImageV2Mode) {
if (v2Engine.value === 'moss' && mode !== 'generate') {
toast('MOSS-Image is text-to-image only.')
selectedV2Mode.value = 'generate'
return
}
if (v2Mode.value === imageModeForInput(mode, Boolean(file.value), editPassQueue.value.length > 0)) return
if (editPassQueue.value.length && v2PassChaining.value) {
toast('Remove extra passes to change graphs. Extra passes stay in the current mode.')
@@ -7277,23 +7342,19 @@ function setV2Engine(engine: ImageV2Engine) {
const previous = v2Engine.value
const previousStack = imageV2LoraStack.value
persistImageV2LoraStack(previousStack, previous)
rememberV2Look(previous)
v2Engine.value = engine
imageV2LoraStack.value = readImageV2LoraStack(engine)
seedImageV2LorasIfEmpty()
applyV2Look(engine)
rememberV2Look(engine)
if (engine === 'moss') selectedV2Mode.value = 'generate'
if (engine === 'krea') {
v2Steps.value = IMAGE_V2_KREA_STEPS
v2Cfg.value = IMAGE_V2_KREA_CFG
v2Turbo.value = false
if (previousStack.some(item => imageLoraEngineOf(item.name) === 'flux')) {
toast('Flux LoRAs stay on the Flux engine. Switch back to restore that chain.')
}
if (v2Mode.value === 'edit') v2Denoise.value = IMAGE_V2_KREA_EDIT_DENOISE
if (v2Mode.value === 'compose') v2Denoise.value = IMAGE_V2_KREA_COMPOSE_DENOISE
return
}
if (previous === 'krea') {
v2Steps.value = IMAGE_V2_STEPS_DEFAULT
v2Cfg.value = IMAGE_V2_CFG_DEFAULT
}
}
@@ -7405,8 +7466,8 @@ async function editImageV2() {
body.append('snofs_clip', String(imageV2EngineLoras().find(item => isImageV2ConceptLora(item.name))?.strengthClip ?? 0))
body.append('consistency_model', String(imageV2EngineLoras().find(item => isImageV2ConsistencyLora(item.name))?.strengthModel ?? 0))
body.append('consistency_clip', String(imageV2EngineLoras().find(item => isImageV2ConsistencyLora(item.name))?.strengthClip ?? 0))
body.append('steps', String(clampImageSteps(v2Steps.value, v2Engine.value === 'krea' ? IMAGE_V2_KREA_STEPS : IMAGE_V2_STEPS_DEFAULT)))
body.append('cfg', String(clampImageCfg(v2Cfg.value, v2Engine.value === 'krea' ? IMAGE_V2_KREA_CFG : IMAGE_V2_CFG_DEFAULT)))
body.append('steps', String(clampImageSteps(v2Steps.value, v2StepsFallback())))
body.append('cfg', String(clampImageCfg(v2Cfg.value, v2CfgFallback())))
if (v2Mode.value !== 'generate' && !iterateGenerate) {
body.append('scaleToTotalPixels', String(v2ScaleOn.value))
if (v2ScaleOn.value) body.append('megapixels', String(clampImageScaleMegapixels(v2Megapixels.value, 1)))
@@ -7453,7 +7514,7 @@ async function editImageV2() {
: imagePassMode.value === 'batch'
? `Queued ${n} Image v2 stills from the start image behind the current job.`
: `Queued ${n} Image v2 passes behind the current job.`)
: (v2Engine.value === 'krea' ? 'Queued Krea generate behind the current job.' : 'Queued Image v2 behind the current job.'))
: (v2Engine.value === 'krea' ? 'Queued Krea generate behind the current job.' : v2Engine.value === 'moss' ? 'Queued MOSS-Image behind the current job.' : 'Queued Image v2 behind the current job.'))
await refreshStudioQueue()
return
}
@@ -7846,7 +7907,7 @@ function applyEditEvent(payload: Record<string, any>, hidden: boolean, folderLoc
: (folderLocked || payload.folderLocked === true)
if (payload.stillId && !locked) {
editResultUrl.value = `/api/library/stills/${payload.stillId}`
editResultUrl.value = `/api/library/stills/${payload.stillId}?v=0`
if (studioMode.value === 'editv2' || v2JobPending.value) lastV2StillId.value = payload.stillId
editLockedSave.value = false
if (payload.hideThumbnail || hidden) {
@@ -7890,7 +7951,7 @@ function applyEditEvent(payload: Record<string, any>, hidden: boolean, folderLoc
browseFolderId.value = folderId.value
editStatusMessage.value = 'Saved to the locked folder. Unlock it to view.'
} else {
editResultUrl.value = `/api/library/stills/${payload.stillId}`
editResultUrl.value = `/api/library/stills/${payload.stillId}?v=0`
if (studioMode.value === 'editv2' || v2JobPending.value) lastV2StillId.value = payload.stillId
concealEditOutput.value = Boolean(payload.hideThumbnail || hidden)
editAwaitingReveal.value = concealEditOutput.value
+6
View File
@@ -0,0 +1,6 @@
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#f3f1ea" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<path d="M3 3l18 18"/>
<path d="M10.6 10.6A3 3 0 0 0 12 15a3 3 0 0 0 2.4-4.4"/>
<path d="M9.9 5.1A11 11 0 0 1 12 5c6.5 0 10 7 10 7a18 18 0 0 1-3.2 3.8"/>
<path d="M6.1 6.1C3.7 7.8 2 12 2 12s3.5 7 10 7a10.5 10.5 0 0 0 4.2-.9"/>
</svg>

After

Width:  |  Height:  |  Size: 441 B

+4
View File
@@ -0,0 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#f3f1ea" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7S2 12 2 12Z"/>
<circle cx="12" cy="12" r="3"/>
</svg>

After

Width:  |  Height:  |  Size: 303 B

+4
View File
@@ -0,0 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<rect x="4" y="11" width="16" height="10" rx="2"/>
<path d="M8 11V8a4 4 0 0 1 8 0v3"/>
</svg>

After

Width:  |  Height:  |  Size: 302 B

+299
View File
@@ -0,0 +1,299 @@
import { spawn } from 'node:child_process'
import { createServer } from 'node:net'
import { existsSync, mkdirSync, readFileSync, writeFileSync, renameSync, appendFileSync, readdirSync, copyFileSync, createWriteStream } from 'node:fs'
import { join, resolve, extname } from 'node:path'
import { pipeline } from 'node:stream/promises'
import { Transform } from 'node:stream'
import { captionStylePrompt, CAPTION_STYLES } from '../shared/caption.mjs'
const MODEL_NAME = 'Qwen2.5-VL-7B-NS-Caption-V4.Q5_K_M.gguf'
const MMPROJ_NAME = 'Qwen2.5-VL-7B-NS-Caption-V4.mmproj-f16.gguf'
function defaultModelsDir() {
const shared = process.env.COMFY_MODELS_ROOT
|| join(process.env.LOCALAPPDATA || '', 'Comfy-Desktop', 'ComfyUI-Shared', 'models')
return resolve(process.env.CAPTION_MODELS || join(shared, 'caption', 'qwen25vl-7b-ns-v4'))
}
/** Prefer winget ggml.llamacpp; never download. Process exit after one caption = keep_alive 0. */
function resolveLlamaServer(explicit) {
if (explicit) return resolve(explicit)
if (process.env.CAPTION_LLAMA_SERVER) return resolve(process.env.CAPTION_LLAMA_SERVER)
const local = process.env.LOCALAPPDATA || ''
const candidates = [
join(local, 'Microsoft', 'WinGet', 'Packages', 'ggml.llamacpp_Microsoft.Winget.Source_8wekyb3d8bbwe', 'llama-server.exe'),
join(local, 'llama.cpp', 'llama-server.exe'),
join('C:\\', 'llama.cpp', 'llama-server.exe')
]
for (const path of candidates) {
if (existsSync(path)) return path
}
return 'llama-server'
}
function freePort() {
return new Promise((resolvePort, reject) => {
const server = createServer()
server.listen(0, '127.0.0.1', () => {
const address = server.address()
const port = typeof address === 'object' && address ? address.port : 0
server.close(error => error ? reject(error) : resolvePort(port))
})
server.on('error', reject)
})
}
async function waitForServer(port, signal, timeoutMs = 120_000, fetchImpl = fetch) {
const started = Date.now()
while (Date.now() - started < timeoutMs) {
if (signal?.aborted) throw new Error('Caption cancelled while loading the model.')
try {
const response = await fetchImpl(`http://127.0.0.1:${port}/health`, { signal: AbortSignal.timeout(2000) })
if (response.ok) return
} catch { /* booting */ }
await new Promise(r => setTimeout(r, 500))
}
throw new Error('llama-server did not become ready in time.')
}
function mimeFor(path) {
const ext = extname(path).toLowerCase()
if (ext === '.jpg' || ext === '.jpeg') return 'image/jpeg'
if (ext === '.webp') return 'image/webp'
if (ext === '.gif') return 'image/gif'
return 'image/png'
}
function killTree(child) {
return new Promise(resolveKill => {
if (!child?.pid) return resolveKill()
let finished = false
const done = () => { if (finished) return; finished = true; resolveKill() }
child.once('close', done)
try { if (typeof child.kill === 'function') child.kill() } catch { /* ignore */ }
if (process.platform === 'win32' && child.pid > 0) {
try {
const killer = spawn('taskkill', ['/PID', String(child.pid), '/T', '/F'], { windowsHide: true, stdio: 'ignore' })
killer.once('close', done)
killer.once('error', done)
} catch { done() }
}
setTimeout(done, 3000)
})
}
export function validateCaptionHostRequest(body) {
if (!/^[a-zA-Z0-9-]{12,80}$/.test(body?.id || '')) throw new Error('Invalid caption job ID.')
const style = String(body.style || body.captionStyle || 'descriptive')
if (!CAPTION_STYLES.includes(style)) throw new Error('Unknown caption style.')
return { id: body.id, style, imagePath: body.imagePath ? String(body.imagePath) : '' }
}
/** One llama-server process per caption. Process exit unloads VRAM (keep_alive 0). */
export function createCaptionHost({
prepare,
leaseValid,
spawnProcess = spawn,
modelsDir,
llamaServer,
dataDir,
fetchImpl = fetch,
serverWaitMs = 120_000
} = {}) {
const models = resolve(modelsDir || defaultModelsDir())
const executable = resolveLlamaServer(llamaServer)
const data = resolve(dataDir || process.env.CAPTION_JOBS_DIR || join(models, 'aigen-jobs'))
let active = null
let holdUntil = 0
if (existsSync(data)) {
for (const id of readdirSync(data)) {
try {
const path = join(data, id, 'status.json')
if (!existsSync(path)) continue
const state = JSON.parse(readFileSync(path, 'utf8'))
if (['running', 'starting', 'cancelling'].includes(state.status)) {
holdUntil = Date.now() + 10000
state.status = 'error'
state.error = 'Caption host restarted. GPU model unloaded.'
writeFileSync(path + '.tmp', JSON.stringify(state))
renameSync(path + '.tmp', path)
}
} catch { /* ignore */ }
}
}
const dir = id => {
if (!/^[a-zA-Z0-9-]{12,80}$/.test(id || '')) throw new Error('Invalid caption job ID.')
return join(data, id)
}
const persist = job => {
const target = join(dir(job.id), 'status.json')
writeFileSync(target + '.tmp', JSON.stringify(job))
renameSync(target + '.tmp', target)
}
const read = id => {
if (active?.job.id === id) return { ...active.job }
const path = join(dir(id), 'status.json')
return existsSync(path) ? JSON.parse(readFileSync(path, 'utf8')) : null
}
const modelPath = () => join(models, MODEL_NAME)
const mmprojPath = () => join(models, MMPROJ_NAME)
const configured = () => {
try {
if (!existsSync(modelPath()) || !existsSync(mmprojPath())) return false
if (executable.includes('\\') || executable.includes('/')) return existsSync(executable)
return true
} catch { return false }
}
return {
busy: () => Boolean(active) || Date.now() < holdUntil,
configured,
modelsDir: () => models,
read,
async upload(id, stream) {
if (read(id)?.status === 'complete') throw new Error('This caption job has already finished.')
const jobDir = dir(id)
mkdirSync(jobDir, { recursive: true })
const dest = join(jobDir, 'input.upload')
let bytes = 0
await pipeline(stream, new Transform({
transform(chunk, _, callback) {
bytes += chunk.length
callback(bytes > 40 * 1024 * 1024 ? new Error('Image exceeds the 40 MB upload limit.') : null, chunk)
}
}), createWriteStream(dest, { flags: 'w' }))
if (bytes < 32) throw new Error('Image file is empty.')
renameSync(dest, join(jobDir, 'input.png'))
},
async start(body, lease) {
const request = validateCaptionHostRequest(body)
const previous = read(request.id)
if (previous) return previous
if (active || Date.now() < holdUntil) throw Object.assign(new Error('Caption is already running or releasing VRAM.'), { statusCode: 409 })
if (!configured()) throw new Error(`Caption model missing under ${models}. Run scripts/setup-caption.ps1.`)
if (!leaseValid(lease)) throw new Error('GPU reservation expired.')
let imagePath = request.imagePath
if (imagePath) {
if (!existsSync(imagePath)) throw new Error('imagePath does not exist on the GPU host.')
mkdirSync(dir(request.id), { recursive: true })
const dest = join(dir(request.id), `input${extname(imagePath) || '.png'}`)
copyFileSync(imagePath, dest)
imagePath = dest
} else {
imagePath = join(dir(request.id), 'input.png')
if (!existsSync(imagePath)) {
const alt = existsSync(dir(request.id)) && readdirSync(dir(request.id)).find(name => /^input\./i.test(name))
if (!alt) throw new Error('Upload an image first or pass imagePath.')
imagePath = join(dir(request.id), alt)
}
}
const job = {
id: request.id, status: 'starting', message: 'Preparing GPU for caption', progress: 0,
style: request.style, startedAt: Date.now(), checkedAt: Date.now()
}
active = { job, child: null, cancelled: false, abort: new AbortController() }
const run = active
mkdirSync(dir(job.id), { recursive: true })
writeFileSync(join(dir(job.id), 'request.json'), JSON.stringify({ ...request, imagePath, prompt: captionStylePrompt(request.style) }))
persist(job)
try {
if (prepare) await prepare()
if (run.cancelled || !leaseValid(lease)) throw new Error('Caption start cancelled or GPU reservation expired.')
job.status = 'running'; job.message = 'Loading Qwen2.5-VL caption model'; job.progress = 5; persist(job)
const port = await freePort()
// One caption per process. killTree after response unloads VRAM (keep_alive 0).
const child = spawnProcess(executable, [
'-m', modelPath(), '--mmproj', mmprojPath(),
'--host', '127.0.0.1', '--port', String(port),
'-ngl', String(process.env.CAPTION_NGL || '99'),
'-c', String(process.env.CAPTION_CTX || '4096'),
'--jinja'
], { windowsHide: true, shell: false, stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env } })
run.child = child
const log = chunk => appendFileSync(join(dir(job.id), 'worker.log'), chunk)
child.stdout.on('data', log)
child.stderr.on('data', log)
const watchdog = setInterval(() => {
if (!leaseValid(lease)) { job.error = 'GPU reservation expired; caption stopped.'; run.abort.abort(); void killTree(child) }
}, 5000)
try {
await waitForServer(port, run.abort.signal, serverWaitMs, fetchImpl)
if (run.cancelled) throw new Error('Cancelled')
job.message = 'Captioning'; job.progress = 40; persist(job)
const bytes = readFileSync(imagePath)
const dataUrl = `data:${mimeFor(imagePath)};base64,${bytes.toString('base64')}`
const response = await fetchImpl(`http://127.0.0.1:${port}/v1/chat/completions`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
signal: run.abort.signal.aborted ? run.abort.signal : AbortSignal.timeout(Number(process.env.CAPTION_TIMEOUT_MS || 180_000)),
body: JSON.stringify({
temperature: 0.2,
max_tokens: 512,
messages: [{
role: 'user',
content: [
{ type: 'text', text: captionStylePrompt(request.style) },
{ type: 'image_url', image_url: { url: dataUrl } }
]
}]
})
})
if (run.abort.signal.aborted) throw new Error('Cancelled')
if (!response.ok) {
const detail = await response.text().catch(() => '')
throw new Error(`llama-server caption failed (${response.status}): ${detail.slice(0, 400)}`)
}
const payload = await response.json()
const text = String(payload?.choices?.[0]?.message?.content || '').trim()
if (!text) throw new Error('Caption model returned empty text.')
job.text = text
job.status = run.cancelled ? 'cancelled' : 'complete'
job.message = job.status === 'complete' ? 'Caption ready' : 'Cancelled'
job.progress = 100
job.checkedAt = Date.now()
persist(job)
return { ...job }
} finally {
clearInterval(watchdog)
await killTree(child)
holdUntil = Date.now() + 2000
if (active === run) active = null
}
} catch (error) {
job.status = run.cancelled ? 'cancelled' : 'error'
job.error = error.message || String(error)
job.message = job.error
job.checkedAt = Date.now()
persist(job)
if (run.child) await killTree(run.child)
if (active === run) active = null
holdUntil = Date.now() + 2000
throw error
}
},
async cancel(id) {
if (active?.job.id !== id) return read(id)
const run = active
run.cancelled = true
run.job.status = 'cancelling'
run.job.message = 'Cancelling'
persist(run.job)
run.abort.abort()
if (run.child) await killTree(run.child)
return read(id)
},
async captionOnce(body, lease) {
const id = body.id || `caption-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`
const result = await this.start({ ...body, id }, lease)
if (result.status === 'complete') return { text: result.text, id: result.id, style: result.style }
throw new Error(result.error || 'Caption failed.')
}
}
}
export const captionModelFiles = { model: MODEL_NAME, mmproj: MMPROJ_NAME }
+49 -10
View File
@@ -4,6 +4,7 @@ import { stableMemoryArgs } from './comfy-memory-policy.mjs'
import { createGpuReservation } from './gpu-reservation.mjs'
import { createGpuProxy } from './gpu-proxy.mjs'
import { createYue2Host } from './yue2-host.mjs'
import { createCaptionHost } from './caption-host.mjs'
import http from 'node:http'
import net from 'node:net'
import { execFile, spawn } from 'node:child_process'
@@ -147,7 +148,7 @@ let proxyTarget = 0
function ensureProxyListening() {
if (proxyServer) return
proxyServer = createGpuProxy({ target: () => proxyTarget, reservation: gpuReservation, authorized, markWork, externalBusy: () => yue2.busy() || upscale.busy() })
proxyServer = createGpuProxy({ target: () => proxyTarget, reservation: gpuReservation, authorized, markWork, externalBusy: () => yue2.busy() || upscale.busy() || caption.busy() })
proxyServer.on('error', (error) => {
console.log(JSON.stringify({ src: 'comfy-host-agent', event: 'proxy-error', error: String(error.message || error) }))
})
@@ -819,7 +820,7 @@ function purgeDesktopFiles(body) {
}
const gpuReservation = createGpuReservation({ idle: async () => {
if (yue2.busy() || upscale.busy()) return false
if (yue2.busy() || upscale.busy() || caption.busy()) return false
if ((await trainingLock()).busy) return false
const healthy = await syncProxy()
if (healthy) {
@@ -830,29 +831,65 @@ const gpuReservation = createGpuReservation({ idle: async () => {
return !(await processUp()) && !(await pythonMainUp().catch(() => true))
} })
const yue2 = createYue2Host({
leaseValid: lease => gpuReservation.isOwner(lease),
prepare: async () => {
async function prepareExclusiveGpu(label) {
if ((await trainingLock()).busy) throw new Error('GPU is busy with training.')
if (label !== 'YuE2' && yue2.busy()) throw new Error('YuE2 is using the GPU.')
if (label !== 'caption' && caption.busy()) throw new Error('Caption is using the GPU.')
if (upscale.busy()) throw new Error('Local upscale is using the GPU.')
const healthy = await syncProxy()
if (healthy) {
const queue = await fetchLocalQueue(healthy)
if (!queue.ok || queue.running || queue.pending) throw new Error('Comfy is busy; YuE2 cannot start.')
if (!queue.ok || queue.running || queue.pending) throw new Error(`Comfy is busy; ${label} cannot start.`)
}
// Stop Comfy and refuse to launch while its Python still owns VRAM.
if (healthy || await processUp() || await pythonMainUp().catch(() => false)) {
await stopComfyProcesses()
markAsleep()
}
if (await pythonMainUp()) throw new Error('Comfy has not stopped; retry after the GPU is free.')
}
})
}
const upscale = createUpscaleHost({ leaseValid: token => gpuReservation.isOwner(token) })
const yue2 = createYue2Host({
leaseValid: lease => gpuReservation.isOwner(lease),
prepare: async () => prepareExclusiveGpu('YuE2')
})
const caption = createCaptionHost({
leaseValid: lease => gpuReservation.isOwner(lease),
prepare: async () => prepareExclusiveGpu('caption')
})
async function handleControl(req, res) {
if (!authorized(req)) return json(res, 401, { ok: false, error: 'unauthorized' })
const url = new URL(req.url || '/', 'http://localhost')
if (url.pathname.startsWith('/caption')) {
const match = url.pathname.match(/^\/caption\/jobs\/([a-zA-Z0-9-]{12,80})(\/input|\/cancel)?$/)
if (req.method === 'GET' && url.pathname === '/caption/status') {
return json(res, 200, { configured: caption.configured(), busy: caption.busy(), backend: 'llama.cpp', modelsDir: caption.modelsDir() })
}
if (req.method === 'POST' && url.pathname === '/caption') {
try {
const body = await readJson(req)
return json(res, 200, await caption.captionOnce(body, String(req.headers['x-aigen-gpu-lease'] || '')))
} catch (error) {
return json(res, error.statusCode || 400, { error: error.message || 'Caption failed' })
}
}
if (req.method === 'POST' && url.pathname === '/caption/jobs') {
return json(res, 200, await caption.start(await readJson(req), String(req.headers['x-aigen-gpu-lease'] || '')))
}
if (match && req.method === 'PUT' && match[2] === '/input') {
await caption.upload(match[1], req)
return json(res, 200, { uploaded: true })
}
if (match && req.method === 'POST' && match[2] === '/cancel') return json(res, 200, await caption.cancel(match[1]))
if (match && req.method === 'GET' && !match[2]) {
const job = caption.read(match[1])
return json(res, job ? 200 : 404, job || { error: 'Caption job not found' })
}
return json(res, 404, { error: 'Unknown caption endpoint' })
}
if (url.pathname.startsWith('/upscale/')) {
const match = url.pathname.match(/^\/upscale\/jobs\/([a-zA-Z0-9-]{12,80})(\/input|\/video|\/cancel)?$/)
if (req.method === 'POST' && url.pathname === '/upscale/jobs') return json(res, 200, upscale.start(await readJson(req), String(req.headers['x-aigen-gpu-lease'] || '')))
@@ -909,12 +946,14 @@ async function handleControl(req, res) {
gpu: gpuReservation.availability(),
training: { busy: lastTraining.busy },
yue2: { busy: yue2.busy(), configured: yue2.configured() },
caption: { busy: caption.busy(), configured: caption.configured() },
upscale: { busy: upscale.busy(), engine: 'realesrgan-rife', local: true }
})
}
if (req.method === 'POST' && url.pathname === '/start') {
if (upscale.busy()) return json(res, 409, { message: 'Local upscale is using the GPU.' })
if (yue2.busy()) return json(res, 409, { message: 'YuE2 is using the GPU.' })
if (caption.busy()) return json(res, 409, { message: 'Caption is using the GPU.' })
const training = await trainingLock()
if (training.busy) {
return json(res, 409, {
@@ -1016,7 +1055,7 @@ const server = http.createServer(async (req, res) => {
} else await handleControl(req, res)
} catch (error) {
req.resume()
if ((String(req.url || '').startsWith('/yue2/') || String(req.url || '').startsWith('/upscale/')) && !res.headersSent) return json(res, error.statusCode || 400, { error: error.message || 'Music host request failed' })
if ((String(req.url || '').startsWith('/yue2/') || String(req.url || '').startsWith('/upscale/') || String(req.url || '').startsWith('/caption')) && !res.headersSent) return json(res, error.statusCode || 400, { error: error.message || 'Host request failed' })
if (!res.headersSent) json(res, error.statusCode || 400, { ok: false, message: error.statusCode === 409 ? 'GPU is in use. Waiting for availability.' : 'GPU coordination request failed.' })
}
})
+54
View File
@@ -0,0 +1,54 @@
# Caption (Qwen2.5-VL NS Caption V4 GGUF) — verify host files only.
# Models are already on the 5080 host. Do not download. Do not search Hugging Face.
$ErrorActionPreference = 'Stop'
function Resolve-ModelsRoot {
if ($env:COMFY_MODELS_ROOT) { return $env:COMFY_MODELS_ROOT }
$shared = Join-Path $env:LOCALAPPDATA 'Comfy-Desktop\ComfyUI-Shared\models'
if (Test-Path $shared) { return $shared }
throw 'Set COMFY_MODELS_ROOT or install Comfy Desktop Shared models.'
}
$root = Join-Path (Resolve-ModelsRoot) 'caption\qwen25vl-7b-ns-v4'
if (-not (Test-Path $root)) {
throw "Caption models folder missing: $root"
}
$files = @(
'Qwen2.5-VL-7B-NS-Caption-V4.Q5_K_M.gguf',
'Qwen2.5-VL-7B-NS-Caption-V4.mmproj-f16.gguf'
)
foreach ($name in $files) {
$path = Join-Path $root $name
if (-not (Test-Path $path)) {
throw "Missing $name under $root. Do not download; use the files already on this host."
}
Write-Host "OK $name"
}
$llama = $null
if ($env:CAPTION_LLAMA_SERVER -and (Test-Path $env:CAPTION_LLAMA_SERVER)) {
$llama = Get-Item $env:CAPTION_LLAMA_SERVER
} else {
$winget = Join-Path $env:LOCALAPPDATA 'Microsoft\WinGet\Packages\ggml.llamacpp_Microsoft.Winget.Source_8wekyb3d8bbwe\llama-server.exe'
if (Test-Path $winget) { $llama = Get-Item $winget }
else { $llama = Get-Command llama-server -ErrorAction SilentlyContinue }
}
if (-not $llama) {
throw 'llama-server not found. Install with: winget install ggml.llamacpp'
}
$llamaPath = if ($llama.PSObject.Properties['FullName'] -and $llama.FullName) { $llama.FullName } elseif ($llama.PSObject.Properties['Source'] -and $llama.Source) { $llama.Source } else { [string]$llama }
Write-Host "llama-server: $llamaPath"
$ready = @{
model = 'Qwen2.5-VL-7B-NS-Caption-V4.Q5_K_M.gguf'
mmproj = 'Qwen2.5-VL-7B-NS-Caption-V4.mmproj-f16.gguf'
modelsDir = $root
llamaServer = $llamaPath
readyAt = (Get-Date).ToUniversalTime().ToString('o')
} | ConvertTo-Json
Set-Content -Path (Join-Path $root 'aigen-ready.json') -Value $ready -Encoding utf8
Write-Host "Caption ready: $root"
+127
View File
@@ -0,0 +1,127 @@
# Download Comfy-Org MOSS-Image INT8 SFT weights into the Comfy models tree.
# Prefers the single-file repack (not the Diffusers folders).
#
# powershell -ExecutionPolicy Bypass -File scripts\setup-moss-image.ps1
# powershell -File scripts\setup-moss-image.ps1 -SkipDownload
[CmdletBinding()]
param(
[string]$ComfyRoot = '',
[string]$ModelsRoot = '',
[switch]$SkipDownload,
[switch]$Force
)
$ErrorActionPreference = 'Stop'
function Write-Step([string]$Message) {
Write-Host ""
Write-Host "==> $Message" -ForegroundColor Cyan
}
function Write-Ok([string]$Message) {
Write-Host " $Message" -ForegroundColor Green
}
function Resolve-ModelsRoot([string]$Hint) {
$shared = Join-Path $env:LOCALAPPDATA 'Comfy-Desktop\ComfyUI-Shared\models'
$candidates = @(
$Hint,
$env:COMFY_MODELS_ROOT,
$shared
) | Where-Object { $_ } | ForEach-Object { $_.TrimEnd('\', '/') }
foreach ($path in $candidates) {
if (Test-Path $path) { return (Resolve-Path $path).Path }
}
New-Item -ItemType Directory -Force -Path $shared | Out-Null
return (Resolve-Path $shared).Path
}
function Find-HfCli {
foreach ($name in @('hf', 'huggingface-cli')) {
$cmd = Get-Command $name -ErrorAction SilentlyContinue
if ($cmd) { return $cmd.Source }
}
throw "Hugging Face CLI not found (hf / huggingface-cli). Install with: pip install -U huggingface_hub"
}
function Ensure-Dir([string]$Path) {
if (-not (Test-Path $Path)) {
New-Item -ItemType Directory -Force -Path $Path | Out-Null
}
}
function Assert-ModelFile([string]$Path, [long]$MinBytes) {
if (-not (Test-Path $Path)) { throw "Missing model file: $Path" }
$item = Get-Item $Path
if ($item.Length -lt $MinBytes) {
throw "Suspicious size for $Path ($($item.Length) bytes). Expected >= $MinBytes. Delete and re-run."
}
Write-Ok ("{0} {1:N0} bytes" -f $item.FullName, $item.Length)
}
function Invoke-HfFile {
param(
[string]$Cli,
[string]$Repo,
[string]$File,
[string]$ModelsRoot,
[long]$MinBytes
)
$dest = Join-Path $ModelsRoot ($File -replace '/', '\')
Ensure-Dir (Split-Path $dest -Parent)
if ((Test-Path $dest) -and -not $Force -and (Get-Item $dest).Length -ge $MinBytes) {
Write-Ok "Already present: $dest"
return
}
Write-Step "hf download $Repo $File"
# Repo paths are folder/file. local-dir is the models root so the file is not nested again.
& $Cli download $Repo $File --local-dir $ModelsRoot
if ($LASTEXITCODE -ne 0) { throw "hf download failed for $Repo / $File (exit $LASTEXITCODE)" }
if (-not (Test-Path $dest)) { throw "hf download did not write $dest" }
}
Write-Step "Resolve models root"
$models = Resolve-ModelsRoot $ModelsRoot
Write-Ok $models
$diff = Join-Path $models 'diffusion_models'
$te = Join-Path $models 'text_encoders'
$vae = Join-Path $models 'vae'
Ensure-Dir $diff
Ensure-Dir $te
Ensure-Dir $vae
if (-not $SkipDownload) {
$cli = Find-HfCli
Write-Ok "HF CLI: $cli"
Invoke-HfFile -Cli $cli -Repo 'Comfy-Org/MOSS-Image' -File 'diffusion_models/moss_image_sft_int8_convrot.safetensors' -ModelsRoot $models -MinBytes 5000000000
$w4 = Join-Path $te 'qwen3.5_9b_w4a8_gptq.safetensors'
if ((Test-Path $w4) -and -not $Force -and (Get-Item $w4).Length -ge 7000000000) {
Write-Ok "Already present: $w4"
} else {
try {
Invoke-HfFile -Cli $cli -Repo 'Comfy-Org/MOSS-Image' -File 'text_encoders/qwen3.5_9b_w4a8_gptq.safetensors' -ModelsRoot $models -MinBytes 7000000000
} catch {
Write-Host " w4a8 text encoder missing; falling back to int8_convrot" -ForegroundColor Yellow
Invoke-HfFile -Cli $cli -Repo 'Comfy-Org/MOSS-Image' -File 'text_encoders/qwen3.5_9b_int8_convrot.safetensors' -ModelsRoot $models -MinBytes 9000000000
}
}
$vaeSmall = Join-Path $vae 'flux2-vae_small.safetensors'
if ((Test-Path $vaeSmall) -and -not $Force -and (Get-Item $vaeSmall).Length -ge 200000000) {
Write-Ok "Already present: $vaeSmall"
} else {
Invoke-HfFile -Cli $cli -Repo 'Comfy-Org/MOSS-Image' -File 'vae/flux2-vae_small.safetensors' -ModelsRoot $models -MinBytes 200000000
}
}
Write-Step "Verify weights"
Assert-ModelFile (Join-Path $diff 'moss_image_sft_int8_convrot.safetensors') 5000000000
$clip = Join-Path $te 'qwen3.5_9b_w4a8_gptq.safetensors'
if (-not (Test-Path $clip)) { $clip = Join-Path $te 'qwen3.5_9b_int8_convrot.safetensors' }
Assert-ModelFile $clip 7000000000
$vaeFile = Join-Path $vae 'flux2-vae_small.safetensors'
if (-not (Test-Path $vaeFile)) { $vaeFile = Join-Path $vae 'flux2-vae.safetensors' }
Assert-ModelFile $vaeFile 200000000
Write-Host ""
Write-Host "Done. ComfyUI 0.42+ is required for CLIPLoader type moss_image." -ForegroundColor Cyan
Write-Host "ModelsRoot=$models"
+244
View File
@@ -0,0 +1,244 @@
# Download Qwen Image 2.1 GGUF + companions into the live Comfy Desktop Shared models tree.
# Also ensures city96/ComfyUI-GGUF is present on the ComfyUI (1) install.
#
# Example:
# powershell -ExecutionPolicy Bypass -File scripts\setup-qwen21.ps1
# powershell -File scripts\setup-qwen21.ps1 -SkipDownload
# powershell -File scripts\setup-qwen21.ps1 -ComfyRoot "C:\...\ComfyUI (1)\ComfyUI"
[CmdletBinding()]
param(
[string]$ComfyRoot = '',
[string]$ModelsRoot = '',
[switch]$SkipDownload,
[switch]$SkipNode,
[switch]$Force
)
$ErrorActionPreference = 'Stop'
$ProgressPreference = 'Continue'
function Write-Step([string]$Message) {
Write-Host ""
Write-Host "==> $Message" -ForegroundColor Cyan
}
function Write-Ok([string]$Message) {
Write-Host " $Message" -ForegroundColor Green
}
function Write-Warn([string]$Message) {
Write-Host " warn $Message" -ForegroundColor Yellow
}
function Resolve-ComfyRoot([string]$Hint) {
$candidates = @(
$Hint,
$env:COMFY_ROOT,
$env:COMFYUI_ROOT,
(Join-Path $env:LOCALAPPDATA 'Comfy-Desktop\ComfyUI-Installs\ComfyUI (1)\ComfyUI'),
(Join-Path $env:LOCALAPPDATA 'Comfy-Desktop\ComfyUI-Installs\ComfyUI\ComfyUI'),
'C:\ComfyUI',
(Join-Path $env:USERPROFILE 'ComfyUI')
) | Where-Object { $_ } | ForEach-Object { $_.TrimEnd('\', '/') }
foreach ($path in $candidates) {
if (Test-Path (Join-Path $path 'main.py')) { return (Resolve-Path $path).Path }
if (Test-Path (Join-Path $path 'ComfyUI\main.py')) { return (Resolve-Path (Join-Path $path 'ComfyUI')).Path }
}
throw "Could not find ComfyUI root (main.py). Pass -ComfyRoot."
}
function Resolve-ModelsRoot([string]$Hint, [string]$ComfyRootPath) {
$shared = Join-Path $env:LOCALAPPDATA 'Comfy-Desktop\ComfyUI-Shared\models'
$candidates = @(
$Hint,
$env:COMFY_MODELS_ROOT,
$shared,
(Join-Path $ComfyRootPath 'models')
) | Where-Object { $_ } | ForEach-Object { $_.TrimEnd('\', '/') }
foreach ($path in $candidates) {
if (Test-Path $path) { return (Resolve-Path $path).Path }
}
New-Item -ItemType Directory -Force -Path $shared | Out-Null
return (Resolve-Path $shared).Path
}
function Find-HfCli {
foreach ($name in @('hf', 'huggingface-cli')) {
$cmd = Get-Command $name -ErrorAction SilentlyContinue
if ($cmd) { return $cmd.Source }
}
throw "Hugging Face CLI not found (hf / huggingface-cli). Install with: pip install -U huggingface_hub"
}
function Ensure-Dir([string]$Path) {
if (-not (Test-Path $Path)) {
New-Item -ItemType Directory -Force -Path $Path | Out-Null
}
}
function Assert-ModelFile([string]$Path, [long]$MinBytes) {
if (-not (Test-Path $Path)) { throw "Missing model file: $Path" }
$item = Get-Item $Path
if ($item.Length -lt $MinBytes) {
throw "Suspicious size for $Path ($($item.Length) bytes). Expected >= $MinBytes. Delete and re-run."
}
Write-Ok ("{0} {1:N0} bytes" -f $item.FullName, $item.Length)
}
function Flatten-IfNested([string]$DestDir, [string]$FileName) {
$nested = Get-ChildItem $DestDir -Recurse -File -Filter $FileName -ErrorAction SilentlyContinue |
Where-Object { $_.DirectoryName -ne $DestDir } |
Select-Object -First 1
if ($nested) {
$target = Join-Path $DestDir $FileName
if ((Test-Path $target) -and -not $Force) {
Write-Warn "Nested copy found but destination already exists: $target"
return
}
Move-Item -Force $nested.FullName $target
Write-Ok "Flattened $($nested.FullName) -> $target"
}
}
function Invoke-HfFile {
param(
[string]$Cli,
[string]$Repo,
[string]$File,
[string]$LocalDir
)
Ensure-Dir $LocalDir
$dest = Join-Path $LocalDir (Split-Path $File -Leaf)
if ((Test-Path $dest) -and -not $Force) {
$len = (Get-Item $dest).Length
if ($len -gt 1MB) {
Write-Ok "Already present: $dest ($len bytes)"
return
}
}
Write-Step "hf download $Repo $File"
& $Cli download $Repo $File --local-dir $LocalDir
if ($LASTEXITCODE -ne 0) { throw "hf download failed for $Repo / $File (exit $LASTEXITCODE)" }
Flatten-IfNested -DestDir $LocalDir -FileName (Split-Path $File -Leaf)
}
# --- resolve paths ---
Write-Step "Resolve ComfyUI root"
$root = Resolve-ComfyRoot $ComfyRoot
Write-Ok $root
Write-Step "Resolve models root (Desktop Shared preferred)"
$models = Resolve-ModelsRoot $ModelsRoot $root
Write-Ok $models
$Diff = Join-Path $models 'diffusion_models'
$TE = Join-Path $models 'text_encoders'
$VAE = Join-Path $models 'vae'
Ensure-Dir $Diff
Ensure-Dir $TE
Ensure-Dir $VAE
if (-not $SkipDownload) {
$cli = Find-HfCli
Write-Ok "HF CLI: $cli"
# DiT GGUF only (no Q6/Q5/Q4, no full bf16 DiT)
# Exact invocation required on this host:
# hf download hf://abenzerps/Qwen-Image-2.1-Uncensored-GGUF/qwen-image-2.1-Q8_0.gguf
# That form writes into the Hugging Face hub cache (not --local-dir).
Write-Step "hf download hf://abenzerps/Qwen-Image-2.1-Uncensored-GGUF/qwen-image-2.1-Q8_0.gguf"
$ditName = 'qwen-image-2.1-Q8_0.gguf'
$ditDest = Join-Path $Diff $ditName
if ((Test-Path $ditDest) -and -not $Force -and (Get-Item $ditDest).Length -gt 1MB) {
Write-Ok "Already present: $ditDest ($((Get-Item $ditDest).Length) bytes)"
} else {
& $cli download "hf://abenzerps/Qwen-Image-2.1-Uncensored-GGUF/$ditName"
if ($LASTEXITCODE -ne 0) { throw "hf download failed for DiT GGUF (exit $LASTEXITCODE)" }
$cacheRoot = Join-Path $env:USERPROFILE '.cache\huggingface\hub\models--abenzerps--Qwen-Image-2.1-Uncensored-GGUF'
$found = Get-ChildItem $cacheRoot -Recurse -File -Filter $ditName -ErrorAction SilentlyContinue |
Sort-Object LastWriteTime -Descending |
Select-Object -First 1
if (-not $found) { throw "hf download finished but $ditName was not found under $cacheRoot" }
Ensure-Dir $Diff
Copy-Item -Force $found.FullName $ditDest
Write-Ok "Copied $($found.FullName) -> $ditDest ($((Get-Item $ditDest).Length) bytes)"
}
# abenzerps ships kv_count=0 + Q8_0 1D RMSNorms (packed 136 vs logical 128).
# Tag architecture=qwen_image and promote small/1D tensors to F32 for ComfyUI-GGUF.
Write-Step "Tag DiT GGUF (architecture + F32 norms)"
$tagger = Join-Path $PSScriptRoot 'tag-qwen21-gguf.py'
$pyCandidates = @(
(Join-Path $root '.venv\Scripts\python.exe'),
(Join-Path (Split-Path $root) 'standalone-env\python.exe'),
(Get-Command python -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Source)
) | Where-Object { $_ -and (Test-Path $_) }
$py = $pyCandidates | Select-Object -First 1
if (-not $py) { throw "No Python found to run $tagger" }
$fixed = Join-Path $Diff 'qwen-image-2.1-Q8_0.fixed.gguf'
& $py $tagger $ditDest $fixed
if ($LASTEXITCODE -ne 0) { throw "tag-qwen21-gguf.py failed (exit $LASTEXITCODE)" }
Copy-Item -Force $fixed $ditDest
Write-Ok "Installed tagged GGUF at $ditDest"
# TE + VAE companions from Comfy-Org (INT8 TE for 16 GB VRAM)
Invoke-HfFile -Cli $cli -Repo 'Comfy-Org/Qwen-Image-2.1' -File 'text_encoders/qwen3vl_8b_int8_convrot.safetensors' -LocalDir $TE
Invoke-HfFile -Cli $cli -Repo 'Comfy-Org/Qwen-Image-2.1' -File 'vae/qwen_image_2.1_vae_bf16.safetensors' -LocalDir $VAE
}
Write-Step "Verify weights"
Assert-ModelFile (Join-Path $Diff 'qwen-image-2.1-Q8_0.gguf') 7000000000
Assert-ModelFile (Join-Path $TE 'qwen3vl_8b_int8_convrot.safetensors') 1000000000
Assert-ModelFile (Join-Path $VAE 'qwen_image_2.1_vae_bf16.safetensors') 100000000
if (-not $SkipNode) {
Write-Step "city96 ComfyUI-GGUF"
$nodes = Join-Path $root 'custom_nodes\ComfyUI-GGUF'
if (-not (Test-Path $nodes)) {
git clone https://github.com/city96/ComfyUI-GGUF $nodes
if ($LASTEXITCODE -ne 0) { throw "git clone ComfyUI-GGUF failed" }
Write-Ok "Cloned $nodes"
} else {
Write-Ok "Already present: $nodes"
}
$py = Join-Path $root '.venv\Scripts\python.exe'
if (-not (Test-Path $py)) {
$py = Join-Path (Split-Path $root) 'standalone-env\python.exe'
}
if (Test-Path $py) {
Write-Step "Ensure gguf package in Comfy python ($py)"
& $py -m pip install -q gguf
if ($LASTEXITCODE -ne 0) { Write-Warn "pip install gguf returned $LASTEXITCODE" }
else { Write-Ok "gguf importable" }
} else {
Write-Warn "Comfy python not found; install gguf into the interpreter that runs main.py"
}
}
# PE system prompts (official steps + Adult appendix). Re-copy after the node pack is re-cloned.
Write-Step "Install Qwen PE system prompts (host/qwen21-pe-prompts)"
$peSrc = Join-Path (Split-Path $PSScriptRoot -Parent) 'host\qwen21-pe-prompts'
$peDest = Join-Path $root 'custom_nodes\ComfyUI-Qwen-Image-2.1-Prompt-Enhancer\prompts'
if (-not (Test-Path $peSrc)) {
Write-Warn "Missing $peSrc — skip PE prompt install"
} elseif (-not (Test-Path (Join-Path $root 'custom_nodes\ComfyUI-Qwen-Image-2.1-Prompt-Enhancer'))) {
Write-Warn "PE node pack not installed at $peDest — skip prompt copy"
} else {
Ensure-Dir $peDest
foreach ($name in @('system_prompt_t2i.txt', 'system_prompt_edit.txt')) {
$from = Join-Path $peSrc $name
$to = Join-Path $peDest $name
if (-not (Test-Path $from)) { throw "Missing PE prompt source: $from" }
Copy-Item -Force $from $to
Write-Ok "Copied $name -> $to"
}
}
Write-Host ""
Write-Host "Done. Restart Comfy only when /status shows gpu.busy=false." -ForegroundColor Cyan
Write-Host "ComfyRoot=$root"
Write-Host "ModelsRoot=$models"
+7
View File
@@ -18,6 +18,12 @@ Get-NetTCPConnection -LocalPort 8199 -State Listen -ErrorAction SilentlyContinue
Start-Sleep -Milliseconds 400
# Caption VLM — point at existing host GGUFs (no download).
$captionModels = Join-Path $env:LOCALAPPDATA 'Comfy-Desktop\ComfyUI-Shared\models\caption\qwen25vl-7b-ns-v4'
$llamaServer = Join-Path $env:LOCALAPPDATA 'Microsoft\WinGet\Packages\ggml.llamacpp_Microsoft.Winget.Source_8wekyb3d8bbwe\llama-server.exe'
if (Test-Path $captionModels) { $env:CAPTION_MODELS = $captionModels }
if (Test-Path $llamaServer) { $env:CAPTION_LLAMA_SERVER = $llamaServer }
if ($Wait) {
Set-Location $root
& $node $agent
@@ -31,4 +37,5 @@ $psi.WorkingDirectory = $root
$psi.UseShellExecute = $false
$psi.CreateNoWindow = $true
$psi.WindowStyle = [System.Diagnostics.ProcessWindowStyle]::Hidden
# CAPTION_* already set on this process; child inherits when UseShellExecute is false
[void][System.Diagnostics.Process]::Start($psi)
+132
View File
@@ -0,0 +1,132 @@
#!/usr/bin/env python3
"""Make abenzerps Qwen Image 2.1 DiT GGUF loadable in city96 ComfyUI-GGUF.
abenzerps/Qwen-Image-2.1-Uncensored-GGUF ships Q8_0 with:
- kv_count=0 (no general.architecture)
- 1D RMSNorm weights quantized to Q8_0 (logical 128 -> packed 136),
which breaks Comfy's fused rms_rope path
This rewrite:
1. Adds general.architecture=qwen_image
2. Dequantizes small / 1D tensors to F32 (city96 convert keeps them hiprec)
"""
from __future__ import annotations
import argparse
import sys
from pathlib import Path
# Match city96 ComfyUI-GGUF/tools/convert.py QUANTIZATION_THRESHOLD
QUANTIZATION_THRESHOLD = 1024
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("src", type=Path)
ap.add_argument("dst", type=Path, nargs="?", default=None)
ap.add_argument("--arch", default="qwen_image")
ap.add_argument("--name", default="qwen-image-2.1")
ap.add_argument("--inplace", action="store_true", help="Replace src after a successful tag")
args = ap.parse_args()
import gguf
import numpy as np
src = args.src.resolve()
if not src.is_file():
print(f"missing source: {src}", file=sys.stderr)
return 1
dst = (args.dst.resolve() if args.dst else src.with_name(src.stem + ".tagged.gguf"))
reader = gguf.GGUFReader(str(src))
def get_field(name: str):
field = reader.fields.get(name)
if field is None:
return None
try:
return field.contents()
except Exception:
return None
if dst == src:
dst = src.with_name(src.stem + ".retag.gguf")
f32 = gguf.GGMLQuantizationType.F32
compat = {gguf.GGMLQuantizationType.F32, gguf.GGMLQuantizationType.F16, gguf.GGMLQuantizationType.BF16}
print(f"rewriting {src} -> {dst} (arch={args.arch}, tensors={len(reader.tensors)})")
writer = gguf.GGUFWriter(str(dst), arch=args.arch, use_temp_file=True)
writer.add_name(args.name)
try:
writer.add_type("model")
except Exception:
pass
promoted = 0
for tensor in reader.tensors:
logical = tuple(int(x) for x in tensor.shape)
# GGUF stores dims reversed vs torch; logical numel is what matters
numel = 1
for d in logical:
numel *= d
qtype = tensor.tensor_type
data = tensor.data
if hasattr(data, "copy"):
data = data.copy()
needs_f32 = qtype not in compat and (len(logical) <= 1 or numel <= QUANTIZATION_THRESHOLD)
if needs_f32:
# Dequantize packed blocks -> float32 with logical shape (GGUF order)
dequant = gguf.quants.dequantize(np.asarray(data), qtype).astype(np.float32, copy=False)
expected = numel
if dequant.size != expected:
print(
f"dequant size mismatch {tensor.name}: got {dequant.size} want {expected} "
f"shape={logical} qtype={qtype}",
file=sys.stderr,
)
return 3
data = dequant.reshape(logical)
qtype = f32
promoted += 1
writer.add_tensor(tensor.name, data, raw_dtype=qtype)
writer.write_header_to_file()
writer.write_kv_data_to_file()
writer.write_tensors_to_file(progress=True)
writer.close()
check = gguf.GGUFReader(str(dst))
field = check.fields.get("general.architecture")
got = field.contents() if field is not None else None
print(
f"verified architecture={got!r} tensors={len(check.tensors)} "
f"promoted_f32={promoted} size={dst.stat().st_size}"
)
if got != args.arch or len(check.tensors) != len(reader.tensors):
print("tag failed", file=sys.stderr)
return 2
# Spot-check a known norm weight is F32 @ 128
sample = next((t for t in check.tensors if t.name.endswith("attn.norm_q.weight")), None)
if sample is not None:
print(
f"sample {sample.name}: shape={tuple(int(x) for x in sample.shape)} "
f"type={sample.tensor_type.name} data_shape={tuple(sample.data.shape)}"
)
if args.inplace:
bak = src.with_suffix(src.suffix + ".untagged.bak")
if bak.exists():
bak.unlink()
src.replace(bak)
dst.replace(src)
print(f"inplace: {src} (backup {bak})")
return 0
if __name__ == "__main__":
raise SystemExit(main())
+140
View File
@@ -0,0 +1,140 @@
import { filterLoraStackForUse } from '~/utils/loras'
import { validateRequest } from '~/shared/studio2/contracts.mjs'
import { defaultLibraryFolderId, isStudio2ImageEngine, studio2EngineDefaults } from '~/shared/studio2/engine-defaults.mjs'
import { resolveRequestSize } from '../../utils/studio2/size'
import { parsePostedLoraStack, assertImageV2LoraStack } from '../../utils/loras'
import { saveRecord, readRecord } from '../../utils/studio2/store'
import { addStudioJob, kickStudioQueue, type StudioJobPayload } from '../../utils/studioQueue'
import { isXaigenStudio } from '~/utils/videoModels'
import { assertAigenApiAccess } from '~/server/utils/aigenApi'
export default defineEventHandler(async (event) => {
const { owner, catalog } = assertAigenApiAccess(event)
const rawBody = await readBody(event).catch(() => ({}))
const body = rawBody && typeof rawBody === 'object' ? rawBody as Record<string, unknown> : {}
const prompt = String(body.prompt || '').trim()
if (!prompt) {
throw createError({ statusCode: 400, statusMessage: 'A prompt is required' })
}
const engine = String(body.engine || 'flux').trim().toLowerCase() || 'flux'
if (!isStudio2ImageEngine(engine)) {
throw createError({ statusCode: 400, statusMessage: 'engine must be flux, krea, qwen21, or moss' })
}
const mode = String(body.mode || 'generate').trim().toLowerCase() || 'generate'
if (mode !== 'generate') {
throw createError({ statusCode: 400, statusMessage: 'mode must be generate' })
}
const defaults = studio2EngineDefaults(engine)
const steps = body.steps == null || body.steps === ''
? defaults.steps
: Number(body.steps)
const cfg = body.cfg == null || body.cfg === ''
? defaults.cfg
: Number(body.cfg)
if (!Number.isFinite(steps) || !Number.isInteger(steps)) {
throw createError({ statusCode: 400, statusMessage: 'steps must be an integer' })
}
if (!Number.isFinite(cfg)) {
throw createError({ statusCode: 400, statusMessage: 'cfg must be a number' })
}
const aspect = String(body.aspect || defaults.aspect || 'auto').trim() || defaults.aspect
const folderId = defaultLibraryFolderId(catalog, body.folderId == null ? '' : String(body.folderId))
if (!folderId) {
throw createError({ statusCode: 400, statusMessage: 'Create a library folder before generating' })
}
const seedRaw = body.seed
const seedSet = seedRaw != null && String(seedRaw) !== ''
const seed = seedSet ? Number(seedRaw) : null
if (seedSet && !Number.isFinite(seed)) {
throw createError({ statusCode: 400, statusMessage: 'seed must be a number' })
}
const xaigen = isXaigenStudio()
const requestRaw = {
mode: 'generate',
engine,
folderId,
promptSections: { action: prompt },
settings: {
aspect,
steps,
cfg,
seed,
seedMode: seedSet ? 'locked' : 'random',
loraStack: []
}
}
let request: any
try {
request = validateRequest(requestRaw, xaigen)
} catch (e: any) {
throw createError({ statusCode: e.statusCode || 400, statusMessage: e.message })
}
request.settings.loraStack = parsePostedLoraStack(request.settings.loraStack, 'image')
request.settings.loraStack = filterLoraStackForUse(request.settings.loraStack, request.engine, xaigen)
if (request.engine !== 'qwen21') assertImageV2LoraStack(request.settings.loraStack, request.engine)
assertFolderAccess(event, request.folderId)
try {
await resolveRequestSize(owner, request)
} catch (e: any) {
const message = e?.statusMessage || e?.message || 'Could not resolve size'
throw createError({
statusCode: e?.statusCode || 400,
statusMessage: message
})
}
const id = crypto.randomUUID()
const record = {
id,
owner,
request,
state: 'waiting',
queuedAt: Date.now(),
familyId: crypto.randomUUID(),
outputs: [],
purgeResult: 'Not yet saved'
}
saveRecord(record)
void (async () => {
try {
const row = await addStudioJob({
ownerKey: owner,
kind: 'edit',
familyId: record.familyId,
payload: {
...request.settings,
engine: request.engine,
studio2Id: id,
studio2Request: structuredClone(request),
prompt: request.compiledPrompt,
folderId: request.folderId,
extensions: [],
referenceStillIds: [],
useIdentityRefs: false,
queueAutoRun: true
} as StudioJobPayload
})
saveRecord({ ...readRecord(owner, id), queueId: row.id })
} catch { /* poll / resume will pick up waiting studio2 records */ }
kickStudioQueue()
})()
return {
id,
engine: request.engine,
steps: request.settings.steps,
cfg: request.settings.cfg,
aspect: request.settings.aspect,
folderId: request.folderId,
status: 'waiting' as const
}
})
+36
View File
@@ -0,0 +1,36 @@
import { jobView } from '~/shared/studio2/queue-view.mjs'
import { getJob } from '../../../utils/jobs'
import { readRecord } from '../../../utils/studio2/store'
import { listStudioJobs } from '../../../utils/studioQueue'
import { assertAigenApiAccess } from '~/server/utils/aigenApi'
export default defineEventHandler((event) => {
const { owner } = assertAigenApiAccess(event)
const id = String(getRouterParam(event, 'id') || '')
let record: any
try {
record = readRecord(owner, id)
} catch (e: any) {
throw createError({
statusCode: e?.statusCode || 404,
statusMessage: e?.statusMessage || 'Job not found'
})
}
const queue = listStudioJobs(owner).find(row => row.id === record.queueId)
const live = record.liveId ? getJob(record.liveId) : null
const view = jobView(record, queue, live)
const still = (record.outputs || []).find((item: any) => item?.id && item.kind !== 'clip' && item.kind !== 'track')
|| (record.outputs || []).find((item: any) => item?.id)
const stillId = still?.id ? String(still.id) : undefined
return {
id: record.id,
state: view.state,
engine: record.request?.engine || '',
steps: record.request?.settings?.steps,
cfg: record.request?.settings?.cfg,
...(view.error ? { error: view.error } : {}),
...(stillId ? { stillId, stillUrl: `/api/library/stills/${stillId}` } : {})
}
})
+65
View File
@@ -0,0 +1,65 @@
/**
* Asset-pack status. Same job ids as Image v2.
* Poll: GET /api/assets/{id} (or GET /api/generate/{id}).
* On complete, includes downloadable still URL(s) under /api/library/stills/{stillId}.
*/
export default defineEventHandler(async (event) => {
const id = String(getRouterParam(event, 'id') || '').trim()
if (!id) throw createError({ statusCode: 400, statusMessage: 'Missing job id' })
const withUrls = (snap: Record<string, unknown>) => {
const stillId = typeof snap.stillId === 'string' ? snap.stillId : ''
const url = stillId ? `/api/library/stills/${stillId}` : null
return {
...snap,
url,
urls: url ? [url] : [],
pngUrl: url,
thumbUrl: url ? `${url}?thumb=1` : null,
complete: snap.status === 'complete'
}
}
const live = getJob(id)
if (live) return withUrls(jobSnapshot(live) as Record<string, unknown>)
const pending = readPendingJob(id)
if (pending) {
const done = await resolvePendingJob(pending).catch(() => null)
if (done) return withUrls(done as Record<string, unknown>)
const job = ensurePendingWatch(pending)
return withUrls(jobSnapshot(job) as Record<string, unknown>)
}
try {
const owner = libraryOwnerKey(event)
const studio = listStudioJobs(owner).find(item => item.id === id || item.liveJobId === id)
if (studio) {
const liveId = studio.liveJobId || ''
const liveJob = liveId ? getJob(liveId) : undefined
if (liveJob) {
return {
...withUrls(jobSnapshot(liveJob) as Record<string, unknown>),
studioJobId: studio.id
}
}
return {
jobId: studio.id,
studioJobId: studio.id,
status: studio.status || 'queued',
message: studio.error || 'Waiting in the studio queue',
progress: 0,
url: null,
urls: [],
pngUrl: null,
thumbUrl: null,
complete: studio.status === 'complete',
error: studio.error || undefined
}
}
} catch {
// fall through
}
throw createError({ statusCode: 404, statusMessage: 'Job not found' })
})
+163
View File
@@ -0,0 +1,163 @@
import { addStudioJob, kickStudioQueue, listStudioJobs, videoJobsBusy } from '~/server/utils/studioQueue'
import { comfyConfigured } from '~/server/utils/comfy'
import {
IMAGE_V2_CFG_DEFAULT,
imageV2SamplingDefaults,
IMAGE_V2_STEPS_DEFAULT,
IMAGE_V2_TURBO_CFG,
IMAGE_V2_TURBO_STEPS,
imageV2WorkflowFile
} from '~/utils/imageV2'
import { clampImageCfg, clampImageSteps } from '~/utils/generationPresets'
import { persistLoraFields } from '~/server/utils/loras'
import {
assetPackSize,
buildAssetPackNegative,
buildAssetPackPrompt,
parseAssetPackEngine,
parseAssetPackStyle
} from '~/utils/assetPack'
function parseBool(raw: unknown) {
return raw === true || raw === 'true' || raw === '1' || raw === 1
}
/**
* Thin Family Board / asset-pack wrapper around Image v2 generate.
* POST /api/assets/generate → same studio queue + poll as /api/v2/generate.
*/
export default defineEventHandler(async (event) => {
const body = await readBody<Record<string, unknown>>(event).catch(() => ({}))
const promptBody = String(body?.prompt || '').trim()
if (!promptBody) {
throw createError({ statusCode: 400, statusMessage: 'A prompt is required' })
}
if (!comfyConfigured()) {
throw createError({
statusCode: 503,
statusMessage: 'Beast ComfyUI is not configured. Set COMFY_HOST.'
})
}
const style = parseAssetPackStyle(body?.style, 'sticker')
const engine = parseAssetPackEngine(body?.engine ?? body?.Engine, 'flux')
const transparentFriendly = body?.transparent_friendly === undefined
? style === 'sticker' || style === 'icon'
: parseBool(body.transparent_friendly)
const size = assetPackSize(style, body?.width, body?.height)
const prompt = buildAssetPackPrompt({
prompt: promptBody,
style,
transparentFriendly
})
const negative = buildAssetPackNegative(
String(body?.negative_prompt ?? body?.negative ?? '').trim()
)
const turbo = engine === 'moss' ? false : parseBool(body?.turbo)
const sampling = imageV2SamplingDefaults(engine)
const steps = engine === 'krea' || engine === 'moss'
? clampImageSteps(body?.steps, sampling.steps)
: turbo ? IMAGE_V2_TURBO_STEPS : clampImageSteps(body?.steps, IMAGE_V2_STEPS_DEFAULT)
const cfg = engine === 'krea' || engine === 'moss'
? clampImageCfg(body?.cfg, sampling.cfg)
: turbo ? IMAGE_V2_TURBO_CFG : clampImageCfg(body?.cfg, IMAGE_V2_CFG_DEFAULT)
const seed = body?.seed != null && String(body.seed) !== '' && String(body.seed) !== 'random'
? Number(body.seed)
: Math.floor(Math.random() * 2_147_483_647)
if (!Number.isFinite(seed)) {
throw createError({ statusCode: 400, statusMessage: 'seed must be a number or null' })
}
const ownerKey = libraryOwnerKey(event)
const library = publicLibrary(event)
const folderId = library.folders.some(folder => folder.id === String(body?.folderId || ''))
? String(body.folderId)
: library.folders[0]?.id
if (!folderId) {
throw createError({ statusCode: 400, statusMessage: 'Create a library folder before generating' })
}
assertFolderExists(event, folderId)
const destFolder = library.folders.find(folder => folder.id === folderId)
const folderLocked = Boolean(destFolder?.protected && !destFolder.unlocked)
const clipName = allocateOutputName(ownerKey, folderId, String(body?.name || `asset-${style}`).trim(), {
engine,
loraStack: []
})
const studio = await addStudioJob({
ownerKey,
familyId: crypto.randomUUID(),
kind: 'edit',
payload: {
prompt,
promptMid: prompt,
name: clipName,
folderId,
aspect: '1:1',
width: size.width,
height: size.height,
steps,
turbo,
seed,
cfg,
fps: 24,
samplerName: 'euler',
scheduler: 'simple',
duration: 0,
sound: false,
workflow: 'v1',
useIdentityRefs: false,
hideThumbnail: false,
hideInput: false,
folderLocked,
referenceStillIds: [null, null, null, null],
extensions: [],
queueAutoRun: false,
negative,
passes: [],
passMode: 'batch',
scaleToTotalPixels: false,
scaleMegapixels: 0,
imagePipeline: 'v2',
v2Mode: 'generate',
v2Task: 't2i',
engine,
snofsModel: 0,
snofsClip: 0,
consistencyModel: 0,
consistencyClip: 0,
...persistLoraFields([])
}
})
await kickStudioQueue()
let latest = listStudioJobs(ownerKey).find(item => item.id === studio.id)
if (!latest?.liveJobId && !(await videoJobsBusy())) {
await kickStudioQueue()
latest = listStudioJobs(ownerKey).find(item => item.id === studio.id)
}
const liveJobId = latest?.liveJobId || ''
const jobId = liveJobId || studio.id
return {
jobId,
studioJobId: studio.id,
queued: !liveJobId,
status: liveJobId ? 'queued' : 'queued',
pollUrl: `/api/assets/${jobId}`,
generatePollUrl: `/api/generate/${jobId}`,
streamUrl: `/api/generate/${jobId}/stream`,
seed,
steps,
cfg,
mode: 'generate',
task: 't2i',
engine,
style,
transparent_friendly: transparentFriendly,
workflow: imageV2WorkflowFile('generate', engine, { hasImage: false, hasReference: false }),
width: size.width,
height: size.height,
prompt,
negative
}
})
+50
View File
@@ -0,0 +1,50 @@
import { validateCaptionBody } from '~/shared/caption.mjs'
import { addStudioJob, kickStudioQueue, type StudioJobPayload } from '~/server/utils/studioQueue'
import { getStill } from '~/server/utils/library'
export default defineEventHandler(async (event) => {
const { owner } = assertLibraryOwner(event)
const raw = await readBody(event)
let body: ReturnType<typeof validateCaptionBody>
try {
body = validateCaptionBody(raw)
} catch (e: any) {
throw createError({ statusCode: e.statusCode || 400, statusMessage: e.message })
}
assertFolderAccess(event, body.folderId)
const still = getStill(owner, body.stillId)
assertFolderAccess(event, still.folderId)
const row = await addStudioJob({
ownerKey: owner,
kind: 'caption',
familyId: crypto.randomUUID(),
payload: {
prompt: `Describe · ${body.captionStyle}`,
name: `Describe · ${body.captionStyle}`,
folderId: body.folderId,
stillId: still.id,
captionStyle: body.captionStyle,
aspect: 'auto',
width: 0,
height: 0,
steps: 1,
turbo: true,
seed: 0,
cfg: 0,
fps: 24,
samplerName: 'euler',
scheduler: 'simple',
duration: 0,
sound: false,
workflow: 'minimax',
useIdentityRefs: false,
hideThumbnail: false,
referenceStillIds: [],
extensions: [],
queueAutoRun: true
} as StudioJobPayload
})
kickStudioQueue()
return { id: row.id, liveJobId: row.liveJobId, captionStyle: body.captionStyle, stillId: still.id }
})
+6 -1
View File
@@ -48,7 +48,7 @@ export default defineEventHandler(async () => {
host: comfy.host || '',
queueRunning: queue.running,
queuePending: queue.pending,
asleep: Boolean(control?.asleep) && !comfyReachable && !control?.yue2?.busy,
asleep: Boolean(control?.asleep) && !comfyReachable && !control?.yue2?.busy && !control?.caption?.busy,
processUp: Boolean(control?.process ?? control?.processUp),
lastActivityAt: control?.lastActivityAt || null,
stats: comfy.ok ? comfy.stats : undefined
@@ -58,6 +58,11 @@ export default defineEventHandler(async () => {
busy: Boolean(control?.yue2?.busy),
backend: control?.yue2?.backend || 'yue2'
},
caption: {
configured: Boolean(control?.caption?.configured),
busy: Boolean(control?.caption?.busy),
backend: control?.caption?.backend || 'llama.cpp'
},
imageComfy: {
configured: imageConfigured,
ok: imageOk,
@@ -1,7 +1,8 @@
import { existsSync, createReadStream } from 'node:fs'
import { clipFrameThumbFile, ensureClipFirstFrame, ensureScaledThumb, fileEtag, sniffImageType } from '~/server/utils/library'
import { clipFrameThumbFile, ensureClipFirstFrame, ensureScaledThumb, setLibraryMediaHeaders, sniffImageType } from '~/server/utils/library'
export default defineEventHandler(async (event) => {
setLibraryMediaHeaders(event)
const { owner } = assertLibraryOwner(event)
const id = String(getRouterParam(event, 'id') || '')
const clip = getClip(owner, id)
@@ -25,13 +26,6 @@ export default defineEventHandler(async (event) => {
if (thumbPath && existsSync(thumbPath)) path = thumbPath
}
const etag = fileEtag(path)
setHeader(event, 'ETag', etag)
setHeader(event, 'Cache-Control', wantThumb ? 'private, max-age=60, must-revalidate' : 'private, max-age=60, must-revalidate')
if (getHeader(event, 'if-none-match') === etag) {
setResponseStatus(event, 304)
return null
}
setHeader(event, 'Content-Type', wantThumb && path !== framePath ? 'image/jpeg' : sniffImageType(path))
return sendStream(event, createReadStream(path))
})
@@ -1,7 +1,8 @@
import { existsSync, createReadStream } from 'node:fs'
import { clipFrameThumbFile, ensureClipLastFrame, ensureScaledThumb, fileEtag, sniffImageType } from '~/server/utils/library'
import { clipFrameThumbFile, ensureClipLastFrame, ensureScaledThumb, setLibraryMediaHeaders, sniffImageType } from '~/server/utils/library'
export default defineEventHandler(async (event) => {
setLibraryMediaHeaders(event)
const { owner } = assertLibraryOwner(event)
const id = String(getRouterParam(event, 'id') || '')
const clip = getClip(owner, id)
@@ -25,13 +26,6 @@ export default defineEventHandler(async (event) => {
if (thumbPath && existsSync(thumbPath)) path = thumbPath
}
const etag = fileEtag(path)
setHeader(event, 'ETag', etag)
setHeader(event, 'Cache-Control', wantThumb ? 'private, max-age=60, must-revalidate' : 'private, max-age=60, must-revalidate')
if (getHeader(event, 'if-none-match') === etag) {
setResponseStatus(event, 304)
return null
}
setHeader(event, 'Content-Type', wantThumb && path !== framePath ? 'image/jpeg' : sniffImageType(path))
return sendStream(event, createReadStream(path))
})
+2 -8
View File
@@ -1,7 +1,8 @@
import { existsSync, createReadStream } from 'node:fs'
import { clipThumbPath, ensureClipThumb, fileEtag, sniffImageType } from '~/server/utils/library'
import { setLibraryMediaHeaders, clipThumbPath, ensureClipThumb, sniffImageType } from '~/server/utils/library'
export default defineEventHandler(async (event) => {
setLibraryMediaHeaders(event)
const { owner } = assertLibraryOwner(event)
const id = String(getRouterParam(event, 'id') || '')
const clip = getClip(owner, id)
@@ -11,13 +12,6 @@ export default defineEventHandler(async (event) => {
if (!path || !existsSync(path)) {
throw createError({ statusCode: 404, statusMessage: 'Thumbnail not found' })
}
const etag = fileEtag(path)
setHeader(event, 'ETag', etag)
setHeader(event, 'Cache-Control', 'private, max-age=86400, stale-while-revalidate=604800')
if (getHeader(event, 'if-none-match') === etag) {
setResponseStatus(event, 304)
return null
}
setHeader(event, 'Content-Type', sniffImageType(path))
return sendStream(event, createReadStream(path))
})
+4 -1
View File
@@ -1,8 +1,10 @@
import { existsSync } from 'node:fs'
import { sendPathWithRange } from '~/server/utils/httpRange'
import { setLibraryMediaHeaders } from '~/server/utils/library'
import { inlineFilename } from '~/shared/content-disposition.mjs'
export default defineEventHandler((event) => {
setLibraryMediaHeaders(event)
const { owner } = assertLibraryOwner(event)
const id = String(getRouterParam(event, 'id') || '')
const clip = getClip(owner, id)
@@ -13,6 +15,7 @@ export default defineEventHandler((event) => {
}
return sendPathWithRange(event, path, 'video/mp4', {
'Content-Disposition': inlineFilename(`${safeDownloadName(clipTitle(clip))}.mp4`),
'Cache-Control': 'private, max-age=0, must-revalidate'
'Cache-Control': 'no-store, no-cache, must-revalidate',
'Pragma': 'no-cache'
})
})
+2 -1
View File
@@ -1,6 +1,8 @@
import { existsSync, readFileSync } from 'node:fs'
import { setLibraryMediaHeaders } from '~/server/utils/library'
export default defineEventHandler((event) => {
setLibraryMediaHeaders(event)
const { owner } = assertLibraryOwner(event)
const id = String(getRouterParam(event, 'id') || '')
const draft = getRetryDraft(owner, id)
@@ -14,6 +16,5 @@ export default defineEventHandler((event) => {
}
const buf = readFileSync(path)
setHeader(event, 'Content-Type', imageContentType(buf))
setHeader(event, 'Cache-Control', 'private, max-age=3600')
return buf
})
@@ -0,0 +1,14 @@
import { assertFolderAccess, assertLibraryOwner, invalidateCatalogCache, publicLibrary, publicLibraryPage, wipeFolderContents } from '~/server/utils/library'
export default defineEventHandler(async (event) => {
const { owner } = assertLibraryOwner(event)
const id = String(getRouterParam(event, 'id') || '')
assertFolderAccess(event, id)
const result = await wipeFolderContents(owner, id)
// wipeFolderContents already drops the cache. Drop it again so this read
// cannot reuse a catalog object captured before the write.
invalidateCatalogCache(owner)
const library = publicLibrary(event, { light: true })
const page = publicLibraryPage(event, { folderId: id, limit: 50 })
return { ...result, ...library, page, folderId: result.folderId || id }
})
+22 -8
View File
@@ -1,10 +1,24 @@
import { publicLibrary, publicLibraryPage, setLibraryMediaHeaders } from '~/server/utils/library'
export default defineEventHandler((event) => {
const light = String(getQuery(event).light || '') === '1'
const library = publicLibrary(event, { light })
try {
const { owner } = assertLibraryOwner(event)
const folderId = library.folders.find(folder => folder.unlocked)?.id
void maintainLibrary(owner, folderId).catch(() => null)
} catch { /* locked or anonymous — still return what we can */ }
return library
setLibraryMediaHeaders(event)
const query = getQuery(event)
const light = String(query.light || '') === '1'
const full = String(query.full || '') === '1'
const limitRaw = query.limit
const hasLimit = limitRaw != null && String(limitRaw) !== ''
// Default GET /api/library → page helper (limit 50). Opt into full catalog with full=1 or legacy light=1.
const wantsFull = full || (light && !hasLimit)
if (!wantsFull) {
return publicLibraryPage(event, {
limit: hasLimit ? Number(limitRaw) || 50 : 50,
cursor: String(query.cursor || ''),
folderId: String(query.folderId || query.folder || ''),
type: String(query.type || query.filter || 'all')
})
}
// Full catalog path — no thumb prewarm on the request (thumbs build on /thumb hit)
return publicLibrary(event, { light: true })
})
+16 -3
View File
@@ -1,3 +1,5 @@
import { imageDimensions } from '../../utils/resolution'
export default defineEventHandler(async (event) => {
const form = await readMultipartFormData(event)
if (!form?.length) {
@@ -15,6 +17,10 @@ export default defineEventHandler(async (event) => {
if (!image) {
throw createError({ statusCode: 400, statusMessage: 'An image is required' })
}
const size = imageDimensions(image.data)
if (!size) {
throw createError({ statusCode: 400, statusMessage: 'Use a PNG, JPEG, WebP, GIF, or BMP image.' })
}
const { owner } = assertLibraryOwner(event)
const library = publicLibrary(event)
const folderId = library.folders.some(folder => folder.id === fields.folderId)
@@ -29,10 +35,17 @@ export default defineEventHandler(async (event) => {
folderId,
filename: image.filename,
data: image.data,
width: Number(fields.width || 0),
height: Number(fields.height || 0),
width: size.width,
height: size.height,
hideInput: fields.hideInput === 'true',
role: 'input'
})
return { still: still || undefined, ...publicLibrary(event) }
if (!still?.id) {
throw createError({ statusCode: 400, statusMessage: 'Could not save that image to the library.' })
}
const next = publicLibrary(event)
const stills = next.stills.some(item => item.id === still.id)
? next.stills
: [{ ...still, role: 'input' as const }, ...next.stills]
return { still, ...next, stills }
})
+19 -12
View File
@@ -1,23 +1,30 @@
import { existsSync, createReadStream } from 'node:fs'
import { fileEtag, stillPath, stillThumbPath, sniffImageType } from '~/server/utils/library'
import { setLibraryMediaHeaders, stillPath, existingStillThumbPath, stillThumbPath, sniffImageType } from '~/server/utils/library'
export default defineEventHandler(async (event) => {
export default defineEventHandler((event) => {
setLibraryMediaHeaders(event)
const { owner } = assertLibraryOwner(event)
const id = String(getRouterParam(event, 'id') || '')
const still = getStill(owner, id)
assertFolderAccess(event, still.folderId)
const wantThumb = String(getQuery(event).thumb || '') === '1'
const path = wantThumb ? await stillThumbPath(owner, id) : stillPath(owner, still.id)
if (!path || !existsSync(path)) {
throw createError({ statusCode: 404, statusMessage: 'Image file is missing' })
const original = stillPath(owner, still.id)
if (wantThumb) {
const path = existingStillThumbPath(owner, id)
if (path && path !== original && existsSync(path)) {
setHeader(event, 'Content-Type', 'image/jpeg')
return sendStream(event, createReadStream(path))
}
const etag = fileEtag(path)
setHeader(event, 'ETag', etag)
setHeader(event, 'Cache-Control', wantThumb ? 'private, max-age=86400, stale-while-revalidate=604800' : 'private, max-age=3600')
if (getHeader(event, 'if-none-match') === etag) {
setResponseStatus(event, 304)
void stillThumbPath(owner, id).catch(() => null)
setResponseStatus(event, 204)
return null
}
setHeader(event, 'Content-Type', wantThumb ? 'image/jpeg' : sniffImageType(path))
return sendStream(event, createReadStream(path))
if (!existsSync(original)) {
throw createError({ statusCode: 404, statusMessage: 'Image file is missing' })
}
setHeader(event, 'Content-Type', sniffImageType(original))
return sendStream(event, createReadStream(original))
})
@@ -0,0 +1,22 @@
import { existsSync, createReadStream } from 'node:fs'
import { setLibraryMediaHeaders, stillPath, stillPreviewPath, existingStillPreviewPath } from '~/server/utils/library'
export default defineEventHandler((event) => {
setLibraryMediaHeaders(event)
const { owner } = assertLibraryOwner(event)
const id = String(getRouterParam(event, 'id') || '')
const still = getStill(owner, id)
assertFolderAccess(event, still.folderId)
const path = existingStillPreviewPath(owner, id)
const original = stillPath(owner, still.id)
// Ready preview → stream. Never await ffmpeg; never stream the archive master.
if (path && existsSync(path) && path !== original) {
setHeader(event, 'Content-Type', 'image/jpeg')
return sendStream(event, createReadStream(path))
}
void stillPreviewPath(owner, id).catch(() => null)
setResponseStatus(event, 204)
return null
})
@@ -0,0 +1,23 @@
import { existsSync, createReadStream } from 'node:fs'
import { setLibraryMediaHeaders, stillPath, stillThumbPath, existingStillThumbPath } from '~/server/utils/library'
export default defineEventHandler((event) => {
setLibraryMediaHeaders(event)
const { owner } = assertLibraryOwner(event)
const id = String(getRouterParam(event, 'id') || '')
const still = getStill(owner, id)
assertFolderAccess(event, still.folderId)
const path = existingStillThumbPath(owner, id)
const original = stillPath(owner, still.id)
// Ready thumb → stream. Never await ffmpeg on the request path.
// Catalog miss is a 404 from getStill — leftover thumb bytes are not served.
if (path && existsSync(path) && path !== original) {
setHeader(event, 'Content-Type', 'image/jpeg')
return sendStream(event, createReadStream(path))
}
void stillThumbPath(owner, id).catch(() => null)
setResponseStatus(event, 204)
return null
})
+4 -1
View File
@@ -1,8 +1,10 @@
import { existsSync } from 'node:fs'
import { sendPathWithRange } from '~/server/utils/httpRange'
import { setLibraryMediaHeaders } from '~/server/utils/library'
import { musicContentType } from '~/utils/music'
export default defineEventHandler((event) => {
setLibraryMediaHeaders(event)
const { owner } = assertLibraryOwner(event)
const id = String(getRouterParam(event, 'id') || '')
const track = getTrack(owner, id)
@@ -14,6 +16,7 @@ export default defineEventHandler((event) => {
const ext = track.ext || 'flac'
return sendPathWithRange(event, path, musicContentType(ext), {
'Content-Disposition': `inline; filename="${safeDownloadName(track.name)}.${ext}"`,
'Cache-Control': 'private, max-age=0, must-revalidate'
'Cache-Control': 'no-store, no-cache, must-revalidate',
Pragma: 'no-cache'
})
})
+8
View File
@@ -0,0 +1,8 @@
import { listPromptSequences } from '~/server/utils/promptSequences'
export default defineEventHandler((event) => {
const { owner } = assertLibraryOwner(event)
return {
sequences: listPromptSequences(owner)
}
})
+25
View File
@@ -0,0 +1,25 @@
import { listPromptSequences, savePromptSequence } from '~/server/utils/promptSequences'
export default defineEventHandler(async (event) => {
const { owner } = assertLibraryOwner(event)
const body = await readBody<{
name?: string
sectionOrder?: unknown
characters?: unknown
sets?: unknown
scenes?: unknown
overwrite?: boolean
}>(event).catch(() => ({}))
const sequence = await savePromptSequence(owner, {
name: body?.name || '',
sectionOrder: body?.sectionOrder,
characters: body?.characters,
sets: body?.sets,
scenes: body?.scenes,
overwrite: body?.overwrite === true
})
return {
sequence,
sequences: listPromptSequences(owner)
}
})
@@ -0,0 +1,11 @@
import { deletePromptSequence, listPromptSequences } from '~/server/utils/promptSequences'
export default defineEventHandler(async (event) => {
const { owner } = assertLibraryOwner(event)
const id = String(getRouterParam(event, 'id') || '')
await deletePromptSequence(owner, id)
return {
ok: true,
sequences: listPromptSequences(owner)
}
})
+9
View File
@@ -0,0 +1,9 @@
import { getPromptSequence } from '~/server/utils/promptSequences'
export default defineEventHandler((event) => {
const { owner } = assertLibraryOwner(event)
const id = String(getRouterParam(event, 'id') || '')
return {
sequence: getPromptSequence(owner, id)
}
})
+24
View File
@@ -0,0 +1,24 @@
import { listPromptSequences, updatePromptSequence } from '~/server/utils/promptSequences'
export default defineEventHandler(async (event) => {
const { owner } = assertLibraryOwner(event)
const id = String(getRouterParam(event, 'id') || '')
const body = await readBody<{
name?: string
sectionOrder?: unknown
characters?: unknown
sets?: unknown
scenes?: unknown
}>(event).catch(() => ({}))
const sequence = await updatePromptSequence(owner, id, {
name: body?.name,
sectionOrder: body?.sectionOrder,
characters: body?.characters,
sets: body?.sets,
scenes: body?.scenes
})
return {
sequence,
sequences: listPromptSequences(owner)
}
})
+37 -12
View File
@@ -1,15 +1,40 @@
import { records, saveRecord } from '../../utils/studio2/store';
import { listStudioJobs } from '../../utils/studioQueue';
export default defineEventHandler(event => {
const { owner } = assertLibraryOwner(event), queue=listStudioJobs(owner);
let cleared=0;
import { records, saveRecord } from '../../utils/studio2/store'
import { dismissFinishedStudioJobs, dismissStudioJob, listStudioJobs } from '../../utils/studioQueue'
export default defineEventHandler(async (event) => {
const { owner } = assertLibraryOwner(event)
const body = await readBody<{ id?: string }>(event).catch(() => ({} as { id?: string }))
const queue = listStudioJobs(owner)
let cleared = 0
if (body?.id) {
const row = queue.find(job => job.id === body.id)
if (!row) throw createError({ statusCode: 404, statusMessage: 'Queued job not found' })
try { assertFolderAccess(event, row.payload.folderId) } catch {
throw createError({ statusCode: 403, statusMessage: 'Folder locked' })
}
await dismissStudioJob(owner, body.id)
return { cleared: 1 }
}
for (const r of records(owner)) {
try { assertFolderAccess(event,r.request.folderId); } catch { continue; }
const status=queue.find(q=>q.id===r.queueId)?.status;
if (['complete','failed','cancelled'].includes(r.state) || ['cancelled','error'].includes(status || '')) {
r.dismissed=true; saveRecord(r); cleared++;
try { assertFolderAccess(event, r.request.folderId) } catch { continue }
const status = queue.find(q => q.id === r.queueId)?.status
if (['complete', 'failed', 'cancelled'].includes(r.state) || ['cancelled', 'error'].includes(status || '')) {
r.dismissed = true
saveRecord(r)
cleared++
}
}
// Retain internal manifests for cleanup retries; remove these records from the visible jobs list.
return {cleared};
});
// Caption (and other finished studio-queue) cards — hide from Queue, keep resultText on the row
const finishedIds = queue
.filter(job => !job.dismissed && ['complete', 'error', 'cancelled'].includes(job.status))
.filter(job => {
try { assertFolderAccess(event, job.payload.folderId); return true } catch { return false }
})
.map(job => job.id)
cleared += await dismissFinishedStudioJobs(owner, finishedIds)
return { cleared }
})
+26 -6
View File
@@ -4,30 +4,50 @@ import { resolveRequestSize } from '../../utils/studio2/size';
import { parsePostedLoraStack, assertImageV2LoraStack } from '../../utils/loras';
import { saveRecord, readRecord } from '../../utils/studio2/store';
import { addStudioJob, kickStudioQueue, type StudioJobPayload } from '../../utils/studioQueue';
import { isXaigenStudio } from '~/utils/videoModels';
export default defineEventHandler(async (event) => {
const { owner } = assertLibraryOwner(event), raw = await readBody(event);
const xaigen = isXaigenStudio();
let request: any;
try {
request = validateRequest(raw, useRuntimeConfig().public.studio === 'xaigen');
request = validateRequest(raw, xaigen);
}
catch (e: any) {
throw createError({ statusCode: e.statusCode || 400, statusMessage: e.message });
}
const video = ['video', 'extend'].includes(request.mode);
request.settings.loraStack = parsePostedLoraStack(request.settings.loraStack, video ? 'video' : 'image');
request.settings.loraStack = filterLoraStackForUse(request.settings.loraStack, request.engine, useRuntimeConfig().public.studio === 'xaigen');
if (!video)
request.settings.loraStack = filterLoraStackForUse(request.settings.loraStack, request.engine, xaigen);
if (!video && request.engine !== 'qwen21')
assertImageV2LoraStack(request.settings.loraStack, request.engine);
assertFolderAccess(event, request.folderId);
try {
for (const id of [request.identityStillId, request.imageAId, request.imageBId, request.maskId, request.endStillId, ...request.guides.map((g: any) => g.stillId)].filter(Boolean))
assertFolderAccess(event, getStill(owner, id).folderId);
if (request.startClipId)
assertFolderAccess(event, getClip(owner, request.startClipId).folderId);
await resolveRequestSize(owner,request);
// Header-only size probe — never decode the archive PNG on Generate click
await resolveRequestSize(owner, request);
} catch (e: any) {
const message = e?.statusMessage || e?.message || 'Image not found'
const missing = /not found|missing from the library|ENOENT|no such file/i.test(String(message))
throw createError({
statusCode: e?.statusCode || (missing ? 404 : 400),
statusMessage: missing
? (/missing from the library/i.test(String(message)) ? 'That still is missing from the library' : 'Image not found')
: message
})
}
const id = crypto.randomUUID(), record = { id, owner, request, state: 'waiting', queuedAt: Date.now(), familyId: crypto.randomUUID(), outputs: [], purgeResult: 'Not yet saved' };
saveRecord(record);
const row = await addStudioJob({ ownerKey: owner, kind: ['video', 'extend'].includes(request.mode) ? 'video' : 'edit', familyId: record.familyId, payload: { ...request.settings, studio2Id: id, prompt: request.compiledPrompt, folderId: request.folderId, extensions: [], referenceStillIds: [], useIdentityRefs: false, queueAutoRun: true } as StudioJobPayload });
const ack = { id, seed:request.settings.seed, width:request.settings.width, height:request.settings.height };
// Enqueue + kick after the client has the id — do not block the response on the worker wake path
void (async () => {
try {
const row = await addStudioJob({ ownerKey: owner, kind: ['video', 'extend'].includes(request.mode) ? 'video' : 'edit', familyId: record.familyId, payload: { ...request.settings, engine: request.engine, studio2Id: id, studio2Request: structuredClone(request), prompt: request.compiledPrompt, folderId: request.folderId, extensions: [], referenceStillIds: [], useIdentityRefs: false, queueAutoRun: true } as StudioJobPayload });
saveRecord({ ...readRecord(owner, id), queueId: row.id });
} catch { /* poll / resume will pick up waiting studio2 records */ }
kickStudioQueue();
return { id, seed:request.settings.seed, width:request.settings.width, height:request.settings.height };
})();
return ack;
});
+15 -9
View File
@@ -1,9 +1,15 @@
import { existsSync } from 'node:fs';
import { studio2LoraCatalog } from '../../utils/studio2/lora-catalog';
import { publicLibrary, stillPath, clipVideoPath } from '../../utils/library';
export default defineEventHandler(event => {
const { owner } = assertLibraryOwner(event);
const library = publicLibrary(event);
const catalog=studio2LoraCatalog(owner);
return {...library,loraAliases:catalog.aliases,loraTriggers:catalog.triggers, stills:library.stills.filter(s=>existsSync(stillPath(owner,s.id))), clips:library.clips.filter(c=>existsSync(clipVideoPath(owner,c.id))), tracks:library.tracks || []};
});
import { studio2LoraCatalog } from '../../utils/studio2/lora-catalog'
import { publicLibrary } from '../../utils/library'
export default defineEventHandler((event) => {
const { owner } = assertLibraryOwner(event)
// light:true — metadata only; never existsSync every still/clip on the volume
const library = publicLibrary(event, { light: true })
const catalog = studio2LoraCatalog(owner)
return {
...library,
loraAliases: catalog.aliases,
loraTriggers: catalog.triggers,
tracks: library.tracks || []
}
})
+4 -4
View File
@@ -1,19 +1,19 @@
import { readFileSync,writeFileSync,renameSync } from 'node:fs'
import { readFileSync, writeFileSync, renameSync } from 'node:fs'
import { join } from 'node:path'
import { cachedLoras } from '~/shared/studio2/lora-cache.mjs'
import { listStudioLoras } from '../../utils/loras'
import { studio2Root } from '../../utils/studio2/store'
import { studio2LoraCatalog } from '../../utils/studio2/lora-catalog'
export default defineEventHandler(async event => {
export default defineEventHandler(async (event) => {
const { owner } = assertLibraryOwner(event)
const path = join(studio2Root(), `loras-${owner}.cache`)
// Same live Comfy scan as Settings (/api/loras?fresh=1). Always fresh so CACHE_MS cannot freeze adds.
const fresh = String(getQuery(event).fresh || '') === '1'
const listed = await cachedLoras({
read: () => { try { return JSON.parse(readFileSync(path, 'utf8')) } catch { return null } },
write: value => { writeFileSync(path + '.tmp', JSON.stringify(value)); renameSync(path + '.tmp', path) },
live: () => listStudioLoras({ fresh: true }),
fresh: true
fresh
})
return { ...listed, ...studio2LoraCatalog(owner) }
})
+6 -2
View File
@@ -10,6 +10,10 @@ export default defineEventHandler(async event => {
if (!size) throw createError({statusCode:400,statusMessage:'Use a PNG, JPEG, WebP, GIF, or BMP image.'})
const filename=image.filename!.split(/[\\/]/).at(-1)!
const still=await saveStill({ownerKey:owner,folderId,filename,name:filename.replace(/\.[^.]+$/,''),data:image.data,...size,hideInput:field('hideInput')==='true',role:'input'})
if (!still) throw createError({statusCode:400,statusMessage:'This file was recognized as an internal video handoff frame and was not added. Choose a regular source image.'})
return {still,...publicLibrary(event,{light:true})}
if (!still?.id) throw createError({statusCode:400,statusMessage:'Could not save that image to the library.'})
const library=publicLibrary(event,{light:true})
const stills=library.stills.some(item=>item.id===still.id)
? library.stills
: [{...still,role:'input' as const},...library.stills]
return {still,...library,stills}
})
+4 -1
View File
@@ -5,18 +5,21 @@ export default defineEventHandler((event) => {
const { owner } = assertLibraryOwner(event)
const full = String(getQuery(event).full || '') === '1'
const active = listStudioJobs(owner)
.filter(job => !job.dismissed)
.filter(job => (
job.status === 'waiting'
|| job.status === 'running'
|| job.status === 'held'
|| (job.status === 'error' && Date.now() - job.updatedAt < 60 * 60 * 1000)
|| (job.kind === 'caption' && job.status === 'complete' && Date.now() - job.updatedAt < 60 * 60 * 1000)
|| (job.kind === 'caption' && job.status === 'cancelled' && Date.now() - job.updatedAt < 60 * 60 * 1000)
))
const claimed = new Set(active.map(job => job.shotQueueId).filter(Boolean) as string[])
const queues = listShotQueues(owner)
const byId = new Map(queues.map(queue => [queue.id, queue]))
const jobs = active.map((job) => {
const shots = job.shotQueueId ? byId.get(job.shotQueueId) || null : null
const kind = job.kind === 'edit' ? 'edit' : job.kind === 'music' ? 'music' : 'video'
const kind = job.kind === 'edit' ? 'edit' : job.kind === 'music' ? 'music' : job.kind === 'caption' ? 'caption' : 'video'
const shotSummary = shots ? summarizeQueue(shots) : null
const plannedShots = shotSummary
? undefined
+13 -1
View File
@@ -15,6 +15,8 @@ import {
IMAGE_V2_KREA_COMPOSE_DENOISE,
IMAGE_V2_KREA_EDIT_DENOISE,
IMAGE_V2_KREA_STEPS,
IMAGE_V2_MOSS_CFG,
IMAGE_V2_MOSS_STEPS,
IMAGE_V2_DENOISE_DEFAULT,
clampImageV2Denoise,
clampImageV2Size,
@@ -226,12 +228,22 @@ export default defineEventHandler(async (event) => {
const hideThumbnail = parseBool(fields.hideThumbnail)
const requestedEngine = parseImageV2Engine(fields.engine, 'flux')
const engine = requestedEngine
const turbo = parseBool(fields.turbo)
if (engine === 'moss' && graphMode !== 'generate') {
throw createError({
statusCode: 400,
statusMessage: 'MOSS-Image is text-to-image only. Use Generate, or Klein or Krea for edits.'
})
}
const turbo = engine === 'moss' ? false : parseBool(fields.turbo)
const steps = engine === 'krea'
? clampImageSteps(fields.steps, IMAGE_V2_KREA_STEPS)
: engine === 'moss'
? clampImageSteps(fields.steps, IMAGE_V2_MOSS_STEPS)
: turbo ? IMAGE_V2_TURBO_STEPS : clampImageSteps(fields.steps, IMAGE_V2_STEPS_DEFAULT)
const cfg = engine === 'krea'
? clampImageCfg(fields.cfg, IMAGE_V2_KREA_CFG)
: engine === 'moss'
? clampImageCfg(fields.cfg, IMAGE_V2_MOSS_CFG)
: turbo ? IMAGE_V2_TURBO_CFG : clampImageCfg(fields.cfg, IMAGE_V2_CFG_DEFAULT)
const megapixels = graphMode === 'generate'
? 0
+100
View File
@@ -0,0 +1,100 @@
{
"4": {
"inputs": {
"unet_name": "moss_image_sft_int8_convrot.safetensors",
"weight_dtype": "default"
},
"class_type": "UNETLoader",
"_meta": { "title": "Load MOSS-Image SFT" }
},
"5": {
"inputs": {
"clip_name": "qwen3.5_9b_w4a8_gptq.safetensors",
"type": "moss_image",
"device": "cpu"
},
"class_type": "CLIPLoader",
"_meta": { "title": "Load Qwen3.5 text encoder" }
},
"6": {
"inputs": { "vae_name": "flux2-vae_small.safetensors" },
"class_type": "VAELoader",
"_meta": { "title": "Load FLUX.2 VAE" }
},
"40": {
"inputs": {
"shift": 5,
"model": ["4", 0]
},
"class_type": "ModelSamplingAuraFlow",
"_meta": { "title": "MOSS shift" }
},
"41": {
"inputs": {
"model": ["40", 0],
"double_layers": "",
"single_layers": "22",
"start_percent": 0,
"end_percent": 1
},
"class_type": "SkipLayerGuidanceDiTSimple",
"_meta": { "title": "Skip layer 22" }
},
"9": {
"inputs": {
"text": "",
"clip": ["5", 0]
},
"class_type": "CLIPTextEncode",
"_meta": { "title": "Positive Prompt" }
},
"10": {
"inputs": {
"text": "",
"clip": ["5", 0]
},
"class_type": "CLIPTextEncode",
"_meta": { "title": "Negative Prompt" }
},
"14": {
"inputs": {
"width": 1024,
"height": 1024,
"batch_size": 1
},
"class_type": "EmptyFlux2LatentImage",
"_meta": { "title": "Empty Flux 2 Latent" }
},
"15": {
"inputs": {
"seed": 1,
"steps": 25,
"cfg": 2.5,
"sampler_name": "euler",
"scheduler": "sgm_uniform",
"denoise": 1,
"model": ["41", 0],
"positive": ["9", 0],
"negative": ["10", 0],
"latent_image": ["14", 0]
},
"class_type": "KSampler",
"_meta": { "title": "KSampler" }
},
"20": {
"inputs": {
"samples": ["15", 0],
"vae": ["6", 0]
},
"class_type": "VAEDecode",
"_meta": { "title": "VAE Decode" }
},
"21": {
"inputs": {
"filename_prefix": "v2-moss",
"images": ["20", 0]
},
"class_type": "SaveImage",
"_meta": { "title": "Save Image" }
}
}
+85
View File
@@ -0,0 +1,85 @@
{
"4": {
"inputs": {
"unet_name": "qwen-image-2.1-Q8_0.gguf"
},
"class_type": "UnetLoaderGGUF",
"_meta": { "title": "Load Qwen 2.1 GGUF" }
},
"8": {
"inputs": {
"device": "auto",
"dtype": "int8",
"model": ["4", 0]
},
"class_type": "QwenImage21Cache",
"_meta": { "title": "Qwen 2.1 Cache" }
},
"5": {
"inputs": {
"clip_name": "qwen3vl_8b_int8_convrot.safetensors",
"type": "qwen_image",
"device": "default"
},
"class_type": "CLIPLoader",
"_meta": { "title": "Load Qwen 2.1 CLIP" }
},
"6": {
"inputs": {
"vae_name": "qwen_image_2.1_vae_bf16.safetensors"
},
"class_type": "VAELoader",
"_meta": { "title": "Load Qwen 2.1 VAE" }
},
"10": {
"inputs": {
"image": "qwen21_edit_source.png"
},
"class_type": "LoadImage",
"_meta": { "title": "image_1 source" }
},
"9": {
"inputs": {
"clip": ["5", 0],
"vae": ["6", 0],
"prompt": "",
"negative_prompt": "",
"resolution": 1024,
"images.image_1": ["10", 0]
},
"class_type": "TextEncodeQwenImage21",
"_meta": { "title": "Text Encode Qwen Image 2.1 Edit" }
},
"15": {
"inputs": {
"seed": 1,
"steps": 25,
"cfg": 1,
"sampler_name": "euler",
"scheduler": "simple",
"denoise": 1,
"model": ["8", 0],
"positive": ["9", 0],
"negative": ["9", 1],
"latent_image": ["9", 2]
},
"class_type": "KSampler",
"_meta": { "title": "KSampler" }
},
"20": {
"inputs": {
"samples": ["15", 0],
"vae": ["6", 0]
},
"class_type": "VAEDecode",
"_meta": { "title": "VAE Decode" }
},
"21": {
"inputs": {
"filename_prefix": "studio2-qwen21-edit",
"images": ["20", 0]
},
"class_type": "SaveImage",
"_meta": { "title": "Save Image" }
}
}
@@ -0,0 +1,119 @@
{
"4": {
"inputs": {
"unet_name": "qwen-image-2.1-Q8_0.gguf"
},
"class_type": "UnetLoaderGGUF",
"_meta": { "title": "Load Qwen 2.1 GGUF" }
},
"7": {
"inputs": {
"model": ["4", 0],
"lora_name": "Qwen-Image-2.1-viggle-turbo-v0.2.1-6step-lora-r128.safetensors",
"strength": 1.0
},
"class_type": "ViggleTurboLora",
"_meta": { "title": "Viggle Turbo LoRA (unmerged)" }
},
"8": {
"inputs": {
"device": "auto",
"dtype": "int8",
"model": ["7", 0]
},
"class_type": "QwenImage21Cache",
"_meta": { "title": "Qwen 2.1 Cache" }
},
"5": {
"inputs": {
"clip_name": "qwen3vl_8b_int8_convrot.safetensors",
"type": "qwen_image",
"device": "default"
},
"class_type": "CLIPLoader",
"_meta": { "title": "Load Qwen 2.1 CLIP" }
},
"6": {
"inputs": {
"vae_name": "qwen_image_2.1_vae_bf16.safetensors"
},
"class_type": "VAELoader",
"_meta": { "title": "Load Qwen 2.1 VAE" }
},
"10": {
"inputs": {
"image": "qwen21_edit_source.png"
},
"class_type": "LoadImage",
"_meta": { "title": "image_1 source" }
},
"9": {
"inputs": {
"clip": ["5", 0],
"vae": ["6", 0],
"prompt": "",
"negative_prompt": "",
"resolution": 1024,
"images.image_1": ["10", 0]
},
"class_type": "TextEncodeQwenImage21",
"_meta": { "title": "Text Encode Qwen Image 2.1 Edit" }
},
"30": {
"inputs": {
"model": ["8", 0],
"conditioning": ["9", 0]
},
"class_type": "BasicGuider",
"_meta": { "title": "CFG off (Turbo)" }
},
"31": {
"inputs": {
"noise_seed": 1
},
"class_type": "RandomNoise",
"_meta": { "title": "Noise" }
},
"32": {
"inputs": {
"sampler_name": "euler"
},
"class_type": "KSamplerSelect",
"_meta": { "title": "euler" }
},
"33": {
"inputs": {
"latent": ["9", 2],
"nodes": "1.0, 0.9375, 0.875, 0.75, 0.5, 0.25"
},
"class_type": "ViggleTurboSigmas",
"_meta": { "title": "Viggle Turbo Sigmas" }
},
"34": {
"inputs": {
"noise": ["31", 0],
"guider": ["30", 0],
"sampler": ["32", 0],
"sigmas": ["33", 0],
"latent_image": ["9", 2]
},
"class_type": "SamplerCustomAdvanced",
"_meta": { "title": "Turbo Sampler" }
},
"35": {
"inputs": {
"samples": ["34", 0],
"vae": ["6", 0]
},
"class_type": "VAEDecode",
"_meta": { "title": "VAE Decode" }
},
"36": {
"inputs": {
"filename_prefix": "studio2-qwen21-edit-turbo",
"images": ["35", 0]
},
"class_type": "SaveImage",
"_meta": { "title": "Save Image" }
}
}
+57
View File
@@ -0,0 +1,57 @@
{
"5": {
"inputs": {
"clip_name": "qwen3.5_9b_qwen_image_2.1_pe_i2i.int8_convrot.safetensors",
"type": "qwen_image",
"device": "default"
},
"class_type": "CLIPLoader",
"_meta": { "title": "Load Qwen 2.1 PE Edit CLIP" }
},
"10": {
"inputs": {
"image": "qwen21_pe_edit_source.png"
},
"class_type": "LoadImage",
"_meta": { "title": "image_1 source" }
},
"9": {
"inputs": {
"clip": ["5", 0],
"prompt": "",
"image_1": ["10", 0],
"temperature": 1.0,
"top_p": 0.95,
"presence_penalty": 0,
"max_length": 24000,
"seed": 42
},
"class_type": "QwenImage21_EditPromptRewrite",
"_meta": { "title": "Qwen 2.1 Edit Prompt Rewrite" }
},
"30": {
"inputs": { "source": ["9", 0] },
"class_type": "PreviewAny",
"_meta": { "title": "PE positive_prompt" }
},
"31": {
"inputs": { "source": ["9", 2] },
"class_type": "PreviewAny",
"_meta": { "title": "PE wh_ratio" }
},
"32": {
"inputs": { "source": ["9", 3] },
"class_type": "PreviewAny",
"_meta": { "title": "PE ratio_follow" }
},
"33": {
"inputs": { "source": ["9", 4] },
"class_type": "PreviewAny",
"_meta": { "title": "PE thinking" }
},
"34": {
"inputs": { "source": ["9", 5] },
"class_type": "PreviewAny",
"_meta": { "title": "PE parse_ok" }
}
}
+45
View File
@@ -0,0 +1,45 @@
{
"5": {
"inputs": {
"clip_name": "qwen3.5_9b_qwen_image_2.1_pe_t2i.int8_convrot.safetensors",
"type": "qwen_image",
"device": "default"
},
"class_type": "CLIPLoader",
"_meta": { "title": "Load Qwen 2.1 PE T2I CLIP" }
},
"9": {
"inputs": {
"clip": ["5", 0],
"prompt": "",
"temperature": 1.0,
"top_p": 0.95,
"top_k": 20,
"presence_penalty": 1.5,
"max_new_tokens": 16256,
"seed": 42
},
"class_type": "QwenImage21_T2IPromptRewrite",
"_meta": { "title": "Qwen 2.1 T2I Prompt Rewrite" }
},
"30": {
"inputs": { "source": ["9", 0] },
"class_type": "PreviewAny",
"_meta": { "title": "PE positive_prompt" }
},
"31": {
"inputs": { "source": ["9", 2] },
"class_type": "PreviewAny",
"_meta": { "title": "PE wh_ratio" }
},
"32": {
"inputs": { "source": ["9", 3] },
"class_type": "PreviewAny",
"_meta": { "title": "PE thinking" }
},
"33": {
"inputs": { "source": ["9", 4] },
"class_type": "PreviewAny",
"_meta": { "title": "PE parse_ok" }
}
}
+84
View File
@@ -0,0 +1,84 @@
{
"4": {
"inputs": {
"unet_name": "qwen-image-2.1-Q8_0.gguf"
},
"class_type": "UnetLoaderGGUF",
"_meta": { "title": "Load Qwen 2.1 GGUF" }
},
"3": {
"inputs": {
"shift": 3.1,
"model": ["4", 0]
},
"class_type": "ModelSamplingAuraFlow",
"_meta": { "title": "Qwen 2.1 shift" }
},
"5": {
"inputs": {
"clip_name": "qwen3vl_8b_int8_convrot.safetensors",
"type": "qwen_image",
"device": "default"
},
"class_type": "CLIPLoader",
"_meta": { "title": "Load Qwen 2.1 CLIP" }
},
"6": {
"inputs": {
"vae_name": "qwen_image_2.1_vae_bf16.safetensors"
},
"class_type": "VAELoader",
"_meta": { "title": "Load Qwen 2.1 VAE" }
},
"9": {
"inputs": {
"clip": ["5", 0],
"prompt": "",
"negative_prompt": "",
"resolution": 1024
},
"class_type": "TextEncodeQwenImage21",
"_meta": { "title": "Text Encode Qwen Image 2.1" }
},
"16": {
"inputs": {
"width": 1024,
"height": 1024,
"batch_size": 1
},
"class_type": "EmptyLatentImage",
"_meta": { "title": "Qwen 2.1 canvas" }
},
"15": {
"inputs": {
"seed": 1,
"steps": 25,
"cfg": 1,
"sampler_name": "euler",
"scheduler": "simple",
"denoise": 1,
"model": ["3", 0],
"positive": ["9", 0],
"negative": ["9", 1],
"latent_image": ["16", 0]
},
"class_type": "KSampler",
"_meta": { "title": "KSampler" }
},
"20": {
"inputs": {
"samples": ["15", 0],
"vae": ["6", 0]
},
"class_type": "VAEDecode",
"_meta": { "title": "VAE Decode" }
},
"21": {
"inputs": {
"filename_prefix": "studio2-qwen21",
"images": ["20", 0]
},
"class_type": "SaveImage",
"_meta": { "title": "Save Image" }
}
}
+110
View File
@@ -0,0 +1,110 @@
{
"4": {
"inputs": {
"unet_name": "qwen-image-2.1-Q8_0.gguf"
},
"class_type": "UnetLoaderGGUF",
"_meta": { "title": "Load Qwen 2.1 GGUF" }
},
"7": {
"inputs": {
"model": ["4", 0],
"lora_name": "Qwen-Image-2.1-viggle-turbo-v0.2.1-6step-lora-r128.safetensors",
"strength": 1.0
},
"class_type": "ViggleTurboLora",
"_meta": { "title": "Viggle Turbo LoRA (unmerged)" }
},
"5": {
"inputs": {
"clip_name": "qwen3vl_8b_int8_convrot.safetensors",
"type": "qwen_image",
"device": "default"
},
"class_type": "CLIPLoader",
"_meta": { "title": "Load Qwen 2.1 CLIP" }
},
"6": {
"inputs": {
"vae_name": "qwen_image_2.1_vae_bf16.safetensors"
},
"class_type": "VAELoader",
"_meta": { "title": "Load Qwen 2.1 VAE" }
},
"9": {
"inputs": {
"clip": ["5", 0],
"prompt": "",
"negative_prompt": "",
"resolution": 1024
},
"class_type": "TextEncodeQwenImage21",
"_meta": { "title": "Text Encode Qwen Image 2.1" }
},
"16": {
"inputs": {
"width": 1024,
"height": 1024,
"batch_size": 1
},
"class_type": "EmptyLatentImage",
"_meta": { "title": "Qwen 2.1 canvas" }
},
"30": {
"inputs": {
"model": ["7", 0],
"conditioning": ["9", 0]
},
"class_type": "BasicGuider",
"_meta": { "title": "CFG off (Turbo)" }
},
"31": {
"inputs": {
"noise_seed": 1
},
"class_type": "RandomNoise",
"_meta": { "title": "Noise" }
},
"32": {
"inputs": {
"sampler_name": "euler"
},
"class_type": "KSamplerSelect",
"_meta": { "title": "euler" }
},
"33": {
"inputs": {
"latent": ["16", 0],
"nodes": "1.0, 0.9375, 0.875, 0.75, 0.5, 0.25"
},
"class_type": "ViggleTurboSigmas",
"_meta": { "title": "Viggle Turbo Sigmas" }
},
"34": {
"inputs": {
"noise": ["31", 0],
"guider": ["30", 0],
"sampler": ["32", 0],
"sigmas": ["33", 0],
"latent_image": ["16", 0]
},
"class_type": "SamplerCustomAdvanced",
"_meta": { "title": "Turbo Sampler" }
},
"35": {
"inputs": {
"samples": ["34", 0],
"vae": ["6", 0]
},
"class_type": "VAEDecode",
"_meta": { "title": "VAE Decode" }
},
"36": {
"inputs": {
"filename_prefix": "studio2-qwen21-turbo",
"images": ["35", 0]
},
"class_type": "SaveImage",
"_meta": { "title": "Save Image" }
}
}
+7
View File
@@ -1,3 +1,6 @@
import { aigenApiPathAllowed, aigenBearerAuthorized } from '~/server/utils/aigenApiAuth'
import { isXaigenStudio } from '~/utils/videoModels'
export default defineEventHandler((event) => {
if (!authEnabled()) return
const path = getRequestURL(event).pathname
@@ -15,6 +18,10 @@ export default defineEventHandler((event) => {
) {
return
}
const method = String(event.method || getMethod(event) || 'GET').toUpperCase()
if (!isXaigenStudio() && aigenApiPathAllowed(path, method) && aigenBearerAuthorized(event)) {
return
}
const user = getSessionUser(event)
if (user) return
if (path.startsWith('/api/')) {
+17
View File
@@ -0,0 +1,17 @@
/** Cache headers for generate/prompt routes. Case-sensitive; not nitro routeRules. */
export default defineEventHandler((event) => {
const path = getRequestURL(event).pathname
if (path.startsWith('/api/generate/')) {
setHeader(event, 'Cache-Control', 'no-cache, no-store, no-transform')
setHeader(event, 'X-Accel-Buffering', 'no')
return
}
if (path.startsWith('/api/prompt/')) {
setHeader(event, 'Cache-Control', 'no-cache, no-store, no-transform')
return
}
if (path === '/api/library' || path.startsWith('/api/library/')) {
setHeader(event, 'Cache-Control', 'no-store, no-cache, must-revalidate')
setHeader(event, 'Pragma', 'no-cache')
}
})
+3
View File
@@ -0,0 +1,3 @@
import { resumeCaptionJobs } from '~/server/utils/caption'
export default defineNitroPlugin(() => { resumeCaptionJobs() })
+38
View File
@@ -0,0 +1,38 @@
import type { H3Event } from 'h3'
import { assertLibraryOwner } from '~/server/utils/library'
import {
aigenBearerAuthorized,
aigenInstanceOwnerKey,
assertAigenFeature
} from '~/server/utils/aigenApiAuth'
export {
aigenApiKeyConfigured,
aigenApiPathAllowed,
aigenBearerAuthorized,
aigenInstanceOwnerKey,
assertAigenFeature
} from '~/server/utils/aigenApiAuth'
export { defaultLibraryFolderId as defaultAigenFolderId } from '~/shared/studio2/engine-defaults.mjs'
/**
* Session (assertLibraryOwner) or Authorization: Bearer <AIGEN_API_KEY>.
* Bearer runs as the instance library owner. xAIGen is 404.
*/
export function assertAigenApiAccess(event: H3Event) {
assertAigenFeature()
if (aigenBearerAuthorized(event)) {
// libraryOwnerKey already maps this bearer to aigenInstanceOwnerKey()
const { owner, catalog } = assertLibraryOwner(event)
return { owner, catalog, auth: 'bearer' as const, instanceOwner: aigenInstanceOwnerKey() }
}
try {
const { owner, catalog } = assertLibraryOwner(event)
return { owner, catalog, auth: 'session' as const }
} catch (e: any) {
if (Number(e?.statusCode) === 401) {
throw createError({ statusCode: 401, statusMessage: 'Authentication required' })
}
throw e
}
}
+52
View File
@@ -0,0 +1,52 @@
import { createHash, timingSafeEqual } from 'node:crypto'
import type { H3Event } from 'h3'
import { isXaigenStudio } from '~/utils/videoModels'
import { passwordAuthEnabled, privateInstanceId } from '~/server/utils/localAuth'
function configuredApiKey() {
const config = useRuntimeConfig()
return String((config as { aigenApiKey?: string }).aigenApiKey || process.env.AIGEN_API_KEY || '').trim()
}
function safeEqual(left: string, right: string) {
const a = Buffer.from(left)
const b = Buffer.from(right)
if (a.length !== b.length) return false
try {
return timingSafeEqual(a, b)
} catch {
return false
}
}
/** Owner key for bearer calls — same catalog as a no-session / password instance. */
export function aigenInstanceOwnerKey() {
if (passwordAuthEnabled()) return privateInstanceId()
return createHash('sha256').update('local').digest('hex').slice(0, 24)
}
export function aigenApiKeyConfigured() {
return Boolean(configuredApiKey())
}
export function aigenBearerAuthorized(event: H3Event) {
if (isXaigenStudio()) return false
const expected = configuredApiKey()
if (!expected) return false
const header = String(getHeader(event, 'authorization') || '')
const match = header.match(/^Bearer\s+(.+)$/i)
if (!match) return false
return safeEqual(match[1].trim(), expected)
}
export function aigenApiPathAllowed(path: string, method: string) {
if (path === '/api/aigen' || path.startsWith('/api/aigen/')) return true
if (method === 'GET' && (path === '/api/library/stills' || path.startsWith('/api/library/stills/'))) return true
return false
}
export function assertAigenFeature() {
if (isXaigenStudio()) {
throw createError({ statusCode: 404, statusMessage: 'Not found' })
}
}
+232
View File
@@ -0,0 +1,232 @@
import { createReadStream, existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync, renameSync, unlinkSync } from 'node:fs'
import { join } from 'node:path'
import { createJob, emitJob, getJob, restoreJob, type Job } from './jobs'
import { getStill, stillPath } from './library'
import { sharedGpuHeaders } from './sharedGpu'
import { CAPTION_STYLES } from '~/shared/caption.mjs'
function settings() {
const config = useRuntimeConfig()
return {
url: String(config.comfyControlUrl || process.env.COMFY_CONTROL_URL || '').replace(/\/$/, ''),
token: String(config.comfyControlToken || process.env.COMFY_CONTROL_TOKEN || '')
}
}
export function captionConfigured() { return Boolean(settings().url) }
function pendingRoot() {
return join(String(useRuntimeConfig().libraryDir || process.env.LIBRARY_DIR || '/data/library'), 'caption-pending')
}
export function captionPendingAlive(jobId: string) {
return Boolean(jobId) && existsSync(join(pendingRoot(), `${jobId}.json`))
}
async function request(path: string, method = 'GET', body?: unknown) {
const { url, token } = settings()
if (!url) throw new Error('Caption host is not configured. Set COMFY_CONTROL_URL.')
const response = await fetch(`${url}/caption/${path}`, {
method,
headers: {
...(token ? { Authorization: `Bearer ${token}` } : {}),
...(method === 'GET' ? {} : sharedGpuHeaders()),
...(method === 'POST' ? { 'Content-Type': 'application/json' } : {})
},
body: method === 'POST' ? JSON.stringify(body) : body as BodyInit | undefined,
...(method === 'PUT' ? { duplex: 'half' as const } : {}),
// Caption loads a 7B VLM; allow the host POST to finish or fall through to watch
signal: AbortSignal.timeout(method === 'PUT' ? 120_000 : method === 'POST' ? 300_000 : 60_000)
} as RequestInit)
if (!response.ok) {
const detail = await response.json().catch(() => ({})) as { message?: string; error?: string }
throw Object.assign(new Error(detail.message || detail.error || `Caption host returned ${response.status}`), { statusCode: response.status })
}
return response
}
function persist(record: Record<string, unknown>) {
mkdirSync(pendingRoot(), { recursive: true })
const path = join(pendingRoot(), `${record.id}.json`)
writeFileSync(path + '.tmp', JSON.stringify(record))
renameSync(path + '.tmp', path)
}
function clearPending(id: string) {
const path = join(pendingRoot(), `${id}.json`)
if (existsSync(path)) unlinkSync(path)
}
function writeSidecar(owner: string, stillId: string, text: string) {
try {
const image = stillPath(owner, stillId)
if (!existsSync(image)) return
writeFileSync(`${image}.txt`, text, 'utf8')
} catch { /* optional */ }
}
export async function cancelCaptionJob(job: Job) {
await request(`jobs/${job.id}/cancel`, 'POST', {})
job.status = 'cancelled'
emitJob(job, { type: 'error', error: 'Cancelled', message: 'Cancelled' })
}
async function settle(job: Job) {
const { onLiveVideoSettled } = await import('./studioQueue')
await onLiveVideoSettled(job)
clearPending(job.id)
}
async function watch(job: Job, record: {
id: string
owner: string
stillId: string
folderId: string
captionStyle: string
liveId: string
}) {
let failures = 0
while (job.status !== 'cancelled') {
try {
const state = await (await request(`jobs/${job.id}`)).json() as {
status: string; message?: string; error?: string; progress?: number; text?: string
}
if (job.status === 'cancelled') { await settle(job); return }
if (state.status === 'error' || state.status === 'cancelled') {
job.status = state.status === 'cancelled' ? 'cancelled' : 'error'
job.error = state.error || state.message || 'Caption failed'
emitJob(job, { type: 'error', error: job.error, message: job.error })
await settle(job)
return
}
if (state.status === 'complete') {
const text = String(state.text || '').trim()
job.message = 'Caption ready'
job.progress = 100
job.status = 'complete'
job.resultText = text
writeSidecar(record.owner, record.stillId, text)
persist({ ...record, resultText: text, status: 'complete' })
emitJob(job, { type: 'complete', message: 'Caption ready', progress: 100 })
await settle(job)
return
}
failures = 0
job.status = 'running'
emitJob(job, {
type: 'progress',
message: state.message || 'Captioning',
progress: Math.min(95, Math.max(1, Number(state.progress || 10)))
})
} catch (error) {
failures++
emitJob(job, { type: 'status', message: `Caption host check failed; retrying: ${error instanceof Error ? error.message : String(error)}` })
if (failures >= 10) {
job.status = 'error'
job.error = 'Caption host unreachable.'
emitJob(job, { type: 'error', error: job.error, message: job.error })
await settle(job)
return
}
}
await new Promise(resolve => setTimeout(resolve, 1500))
}
await settle(job)
}
export async function startCaptionJob(params: {
ownerKey: string
folderId: string
stillId: string
captionStyle: string
name?: string
}) {
if (!CAPTION_STYLES.includes(params.captionStyle)) throw new Error('Unknown caption style.')
getStill(params.ownerKey, params.stillId)
const job = createJob('caption')
job.caption = true
job.library = {
ownerKey: params.ownerKey,
folderId: params.folderId,
hideThumbnail: false,
name: params.name || `Describe · ${params.captionStyle}`,
prompt: params.captionStyle,
aspect: 'image',
width: 0,
height: 0,
steps: 1,
turbo: true,
seed: 0,
stillId: params.stillId,
engine: 'caption'
}
const record = {
id: job.id,
liveId: job.id,
owner: params.ownerKey,
stillId: params.stillId,
folderId: params.folderId,
captionStyle: params.captionStyle,
createdAt: Date.now(),
status: 'running'
}
persist(record)
void (async () => {
try {
if (job.status === 'cancelled') { await settle(job); return }
await request(`jobs/${job.id}/input`, 'PUT', createReadStream(stillPath(params.ownerKey, params.stillId)))
if (job.status === 'cancelled') { await settle(job); return }
try {
await request('jobs', 'POST', { id: job.id, style: params.captionStyle })
} catch { /* confirm by ID on timeout */ }
await watch(job, record)
} catch (error) {
const statusCode = (error as { statusCode?: number })?.statusCode
if (statusCode && statusCode >= 400 && statusCode < 500) {
job.status = 'error'
job.error = error instanceof Error ? error.message : String(error)
emitJob(job, { type: 'error', error: job.error, message: job.error })
await settle(job)
return
}
emitJob(job, { type: 'status', message: `Checking caption submission: ${error instanceof Error ? error.message : String(error)}` })
await watch(job, record)
}
})()
return job
}
export function resumeCaptionJobs() {
if (!existsSync(pendingRoot())) return
for (const file of readdirSync(pendingRoot()).filter(file => /^[a-zA-Z0-9-]+\.json$/.test(file))) {
try {
const record = JSON.parse(readFileSync(join(pendingRoot(), file), 'utf8'))
if (getJob(record.id)) continue
const job = restoreJob({
id: record.liveId || record.id,
clientId: record.clientId || crypto.randomUUID(),
promptId: '',
startedAt: record.createdAt || Date.now(),
library: {
ownerKey: record.owner,
folderId: record.folderId,
hideThumbnail: false,
prompt: record.captionStyle || 'descriptive',
aspect: 'image',
width: 0,
height: 0,
steps: 1,
turbo: true,
seed: 0,
stillId: record.stillId,
engine: 'caption'
}
})
job.caption = true
job.kind = 'caption'
if (record.resultText) job.resultText = record.resultText
job.message = 'Reconnecting to caption host'
void watch(job, record)
} catch { /* keep bad records */ }
}
}
+1 -1
View File
@@ -561,7 +561,7 @@ export function isOurComfyVideo(video: { filename: string; subfolder: string })
}
export function comfySweepNamePrefixes() {
const names = new Set(['MiniMax_H3', 'xAIGen', 'XAIgen', 'LTX23', 'AIGen', 'v2-krea', 'v2-generate'])
const names = new Set(['MiniMax_H3', 'xAIGen', 'XAIgen', 'LTX23', 'AIGen', 'v2-krea', 'v2-generate', 'v2-moss'])
for (const raw of [comfyFilenamePrefix(), comfyAudioPrefix(), comfyImagePrefix()]) {
const last = raw.replace(/\/$/, '').split('/').pop()
if (last) names.add(last)

Some files were not shown because too many files have changed in this diff Show More