diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md new file mode 100644 index 0000000..6a4cd46 --- /dev/null +++ b/ARCHITECTURE.md @@ -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//`. 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. After those writes, `pruneMissingStillMasters` drops any remaining still whose master file is gone. `publicLibrary` and `publicLibraryPage` run that prune before they return rows or folder counts. + +Studio 2 reads a paged `/api/library` list. After a delete it refetches that list and clears form slots that pointed at the deleted id. + +## 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. diff --git a/DESIGN.md b/DESIGN.md new file mode 100644 index 0000000..90e16d6 --- /dev/null +++ b/DESIGN.md @@ -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. diff --git a/PRD.md b/PRD.md new file mode 100644 index 0000000..fe704a1 --- /dev/null +++ b/PRD.md @@ -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//` or `models/loras/aigen//`. Flat files that still use filename prefixes keep working. diff --git a/PROGRESS.md b/PROGRESS.md new file mode 100644 index 0000000..0dcbc74 --- /dev/null +++ b/PROGRESS.md @@ -0,0 +1,15 @@ +# Progress + +## 2026-10-24 + +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//` or `aigen//` shows up from Refresh. diff --git a/RULES.md b/RULES.md new file mode 100644 index 0000000..c0a84aa --- /dev/null +++ b/RULES.md @@ -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. diff --git a/TASKS.md b/TASKS.md new file mode 100644 index 0000000..c74ed10 --- /dev/null +++ b/TASKS.md @@ -0,0 +1,11 @@ +# 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//` and `aigen//`. `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. + +## Not in this pass + +Klein, Krea, MOSS, MiniMax, and LTX graph changes. Coolify app targets. The `studio-2` branch. diff --git a/components/studio2/Bench.vue b/components/studio2/Bench.vue index e8b14df..45f961f 100644 --- a/components/studio2/Bench.vue +++ b/components/studio2/Bench.vue @@ -362,6 +362,8 @@ :folder-id="form.folderId" :preview-hidden="!eyeOpen" :is-hidden="isHidden" + :refresh-key="libraryRefreshKey" + :hidden-ids="[...forgottenStillIds]" @close="libraryOpen=false" @select="selectOutput" @use-image="onLibraryUseImage" @@ -962,8 +964,14 @@ const gpuChipLabel=computed(()=>{ return gpu.value.label || 'GPU ?' }) const sourceSlot=computed(()=>{const clip=clips.value.find((a:any)=>a.id===form.startClipId);return form.mode==='extend'?(clip?{...clip,kind:'clip'}:null):inputStill.value}) -const pickerAssets=computed(()=>picker.value==='startClipId'?clips.value.map((a:any)=>({...a,kind:'clip'})):stills.value.map((a:any)=>({...a,kind:'still'}))) -const inputStill=computed(()=>stills.value.find((s:any)=>s.id===form.imageAId)) +const forgottenStillIds=ref(new Set()) +const libraryRefreshKey=ref(0) +const pickerAssets=computed(()=>{ + const forget=forgottenStillIds.value + if(picker.value==='startClipId')return clips.value.filter((a:any)=>!forget.has(a.id)).map((a:any)=>({...a,kind:'clip'})) + return stills.value.filter((a:any)=>!forget.has(a.id)).map((a:any)=>({...a,kind:'still'})) +}) +const inputStill=computed(()=>stills.value.find((s:any)=>s.id===form.imageAId&&!forgottenStillIds.value.has(s.id))) const family=computed(()=>folderAssets(library.value,jobs.value,form.folderId)) const familyStillCount=computed(()=>{ const folder=(library.value.folders||[]).find((f:any)=>f.id===form.folderId) @@ -1094,11 +1102,29 @@ function addNegative(){ negativeDraft.value='' } function stillById(id:string){ - if(!id)return null + if(!id||forgottenStillIds.value.has(id))return null return stills.value.find((s:any)=>s.id===id) || (library.value.stills||[]).find((s:any)=>s.id===id) || null } +function clearFormSlots(ids:string[]){ + const gone=new Set(ids.filter(Boolean)) + if(!gone.size)return + const touched=gone.has(form.imageAId)||gone.has(form.imageBId)||gone.has(form.identityStillId)||(form.photos||[]).some((p:any)=>gone.has(p?.stillId)) + if(gone.has(form.imageAId))form.imageAId='' + if(gone.has(form.imageBId))form.imageBId='' + if(gone.has(form.identityStillId))form.identityStillId='' + if(gone.has(form.maskId))form.maskId='' + if(gone.has(form.endStillId))form.endStillId='' + if(gone.has(form.startClipId))form.startClipId='' + form.photos=(form.photos||[]).filter((p:any)=>!gone.has(p?.stillId)) + form.guides=(form.guides||[]).map((g:any)=>gone.has(g?.stillId)?{...g,stillId:''}:g) + if(touched)syncPhotosBindings() + if(selected.value&&gone.has(selected.value.id)){ + selected.value=null + selectionPinned.value=false + } +} /** Photos array is source of truth — never resurrect cards from leftover imageAId. */ function syncPhotosBindings(){ const filled=(form.photos||[]).filter((p:any)=>p?.stillId) @@ -1445,23 +1471,34 @@ function slotHidden(_id:string){ function toggleReveal(_id?:string){ eyeOpen.value=!eyeOpen.value } -async function deleteOutput(){ - if(!selected.value)return - const label=assetLabel(selected.value) +async function deleteOutput(explicit?:any){ + const target=explicit||selected.value + if(!target?.id)return + const label=assetLabel(target) if(import.meta.client && !window.confirm(`Delete ${label}?`))return + const id=String(target.id) + const kind=target.kind==='clip'?'clips/':target.kind==='track'?'tracks/':'stills/' try{ - const kind=selected.value.kind==='clip'?'clips/':selected.value.kind==='track'?'tracks/':'stills/' - const id=selected.value.id await $fetch('/api/library/'+kind+id,{method:'DELETE'}) - library.value={ - ...library.value, - stills:(library.value.stills||[]).filter((s:any)=>s.id!==id), - clips:(library.value.clips||[]).filter((c:any)=>c.id!==id), - tracks:(library.value.tracks||[]).filter((t:any)=>t.id!==id) + }catch(e:any){ + const status=Number(e?.statusCode||e?.status||e?.response?.status||0) + if(status!==404){ + error.value=e?.data?.statusMessage||e?.message + return } - selected.value=null - await refreshJobs() - }catch(e:any){error.value=e.data?.statusMessage||e.message} + } + forgottenStillIds.value=new Set([...forgottenStillIds.value,id]) + clearFormSlots([id]) + library.value={ + ...library.value, + stills:(library.value.stills||[]).filter((s:any)=>s.id!==id), + clips:(library.value.clips||[]).filter((c:any)=>c.id!==id), + tracks:(library.value.tracks||[]).filter((t:any)=>t.id!==id) + } + if(selected.value?.id===id)selected.value=null + libraryRefreshKey.value+=1 + try{await loadLibraryOnce()}catch{/* catalog write already landed */} + await refreshJobs() } function stepFamily(delta:number){ const list=family.value @@ -1500,8 +1537,7 @@ function onLibraryLoadInputRaw(item:any){ loadInputRaw(item) } function onLibraryDelete(item:any){ - if(item)selectOutput(item) - void deleteOutput() + void deleteOutput(item) } function onStageHotkey(e:KeyboardEvent){ if(e.metaKey||e.ctrlKey||e.altKey)return @@ -1929,28 +1965,30 @@ async function loadLibraryOnce(){ // Current folder page only — never the yearly Inbox JSON on / const qs=new URLSearchParams({limit:'50'}) if(form.folderId) qs.set('folderId',form.folderId) + qs.set('_',String(Date.now())) const page=await $fetch(`/api/library?${qs.toString()}`) const pageStills=page.stills||[] + const forget=forgottenStillIds.value const keepIds=[ ...(form.photos||[]).map((p:any)=>p?.stillId).filter(Boolean), form.imageAId,form.imageBId,form.identityStillId,form.maskId,form.endStillId, ...(form.guides||[]).map((g:any)=>g?.stillId).filter(Boolean) - ].filter(Boolean) as string[] - let kept=(library.value.stills||[]).filter((s:any)=>keepIds.includes(s.id)&&!pageStills.some((p:any)=>p.id===s.id)) - const stillMissing=keepIds.filter(id=>!pageStills.some((s:any)=>s.id===id)&&!kept.some((s:any)=>s.id===id)) + ].filter((id:string)=>id&&!forget.has(id)) as string[] + let kept=(library.value.stills||[]).filter((s:any)=>keepIds.includes(s.id)&&!pageStills.some((p:any)=>p.id===s.id)&&!forget.has(s.id)) + const stillMissing=keepIds.filter(id=>!forget.has(id)&&!pageStills.some((s:any)=>s.id===id)&&!kept.some((s:any)=>s.id===id)) // Draft / upload stills must survive reload even when they fall outside the first page if(stillMissing.length){ try{ - const full=await $fetch('/api/library?light=1') - const recovered=(full.stills||[]).filter((s:any)=>stillMissing.includes(s.id)) + const full=await $fetch(`/api/library?light=1&_=${Date.now()}`) + const recovered=(full.stills||[]).filter((s:any)=>stillMissing.includes(s.id)&&!forget.has(s.id)) kept=[...kept,...recovered.filter((s:any)=>!kept.some((k:any)=>k.id===s.id))] }catch{/* keep page + in-memory stills */} } library.value={ folders:page.folders||library.value.folders||[], - stills:[...pageStills,...kept], - clips:page.clips||[], - tracks:page.tracks||[], + stills:[...pageStills,...kept].filter((s:any)=>!forget.has(s.id)), + clips:(page.clips||[]).filter((c:any)=>!forget.has(c.id)), + tracks:(page.tracks||[]).filter((t:any)=>!forget.has(t.id)), drafts:page.drafts||library.value.drafts||[], loraAliases:page.loraAliases||library.value.loraAliases||{}, loraTriggers:page.loraTriggers||library.value.loraTriggers||{}, @@ -2061,6 +2099,8 @@ const mobileCtx=computed(()=>({ focusedJobId:focusedJobId.value, canClearFinished:canClearFinished.value, selected:selected.value, + forgottenStillIds:[...forgottenStillIds.value], + libraryRefreshKey:libraryRefreshKey.value, family:family.value, familyStillCount:familyStillCount.value, libraryOpen:libraryOpen.value, diff --git a/components/studio2/LibraryModal.vue b/components/studio2/LibraryModal.vue index c2cfe75..333a20b 100644 --- a/components/studio2/LibraryModal.vue +++ b/components/studio2/LibraryModal.vue @@ -163,6 +163,8 @@ const props = defineProps<{ folderId?: string previewHidden?: boolean isHidden?: (asset: any) => boolean + refreshKey?: number + hiddenIds?: string[] }>() const emit = defineEmits<{ @@ -286,26 +288,18 @@ function useAndClose() { close() } -function removeLocalAsset(asset: any) { - if (!asset?.id) return - const next = new Set(suppressedDeletedIds.value) - next.add(asset.id) - suppressedDeletedIds.value = next - stills.value = stills.value.filter(s => s.id !== asset.id) - clips.value = clips.value.filter(c => c.id !== asset.id) - tracks.value = tracks.value.filter(t => t.id !== asset.id) +function dropIds() { + return new Set([...(props.hiddenIds || []), ...suppressedDeletedIds.value]) } function onDeleteClick() { const asset = detailAsset.value - if (!asset) return + if (!asset?.id) return emit('delete', asset) - removeLocalAsset(asset) - window.setTimeout(() => { void fetchLibrary(true) }, 500) } function mergeIds(prev: { id: string }[], next: { id: string }[]) { - const drop = suppressedDeletedIds.value + const drop = dropIds() const map = new Map() for (const item of prev) { if (!drop.has(item.id)) map.set(item.id, item) @@ -318,7 +312,7 @@ function mergeIds(prev: { id: string }[], next: { id: string }[]) { function applyLibraryPage(data: any, replace: boolean) { folders.value = data?.folders || folders.value - const drop = suppressedDeletedIds.value + const drop = dropIds() const keep = (list: T[]) => list.filter(item => !drop.has(item.id)) if (replace) { clips.value = keep(data?.clips || []) as LibraryClip[] @@ -375,7 +369,7 @@ async function confirmWipeFolder() { 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' }) + 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) @@ -384,6 +378,14 @@ async function fetchLibraryPage(cursor: string | null) { let fetchGen = 0 +function pageIds(data: { stills?: { id: string }[]; clips?: { id: string }[]; tracks?: { id: string }[] }) { + return [ + ...(data?.stills || []).map(item => item.id), + ...(data?.clips || []).map(item => item.id), + ...(data?.tracks || []).map(item => item.id) + ] +} + 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 @@ -392,9 +394,11 @@ async function fetchLibrary(force = false) { loading.value = true loadError.value = '' liveThumbs.value = new Set() + const serverIds = new Set() try { const first = await fetchLibraryPage(null) if (gen !== fetchGen) return + for (const id of pageIds(first)) serverIds.add(id) applyLibraryPage(first, true) loading.value = false nextTick(() => observeThumbs()) @@ -403,10 +407,14 @@ async function fetchLibrary(force = false) { while (cursor && gen === fetchGen) { const more = await fetchLibraryPage(cursor) if (gen !== fetchGen) return + for (const id of pageIds(more)) serverIds.add(id) applyLibraryPage(more, false) cursor = more?.nextCursor || null nextTick(() => observeThumbs()) } + if (gen === fetchGen) { + suppressedDeletedIds.value = new Set([...suppressedDeletedIds.value].filter(id => serverIds.has(id))) + } } catch (e: any) { if (gen !== fetchGen) return loadError.value = e?.data?.statusMessage || e?.message || 'Could not load library' @@ -497,11 +505,15 @@ watch(entries, () => nextTick(() => observeThumbs())) watch([filter, activeFolderId], () => { if (!props.open) return - suppressedDeletedIds.value = new Set() pendingWipe.value = null void fetchLibrary(true) }) +watch(() => props.refreshKey, () => { + if (!props.open) return + void fetchLibrary(true) +}) + onBeforeUnmount(() => { if (import.meta.client) { document.body.style.overflow = '' diff --git a/components/studio2/Mobile.vue b/components/studio2/Mobile.vue index 3a543fa..85065a9 100644 --- a/components/studio2/Mobile.vue +++ b/components/studio2/Mobile.vue @@ -144,6 +144,8 @@ :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" diff --git a/nuxt.config.ts b/nuxt.config.ts index ba40732..927812d 100644 --- a/nuxt.config.ts +++ b/nuxt.config.ts @@ -71,19 +71,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' } }) diff --git a/package-lock.json b/package-lock.json index edda105..3b26211 100644 --- a/package-lock.json +++ b/package-lock.json @@ -9446,18 +9446,18 @@ } }, "node_modules/serialize-javascript": { - "version": "7.1.2", - "resolved": "https://registry.npmjs.org/serialize-javascript/-/serialize-javascript-7.1.2.tgz", - "integrity": "sha512-GL2BWwVa6JydKO6l/ljVgjAZF4QJ3S7dWDWi53s5GZT8PJzD2fNxi67HANQGKAqPrwEpL5ba7gUBGi0Ls/sEoQ==", + "version": "7.1.4", + "resolved": "https://registry.npmjs.org/serialize-javascript/-/serialize-javascript-7.1.4.tgz", + "integrity": "sha512-FqlEuoTq/zRmA4Lg6aOqyH3lCHbUtCB0bmHCeFniX2GBdDqMJM3FwdvEhlE5Pim1dlt2FfBdVPmUNNiGhhKqpw==", "license": "BSD-3-Clause", "engines": { "node": ">=20.0.0" } }, "node_modules/seroval": { - "version": "1.7.0", - "resolved": "https://registry.npmjs.org/seroval/-/seroval-1.7.0.tgz", - "integrity": "sha512-FU+LUkmDzWNsJ6oubZFN3dGPKny53DRhPJG6nftEaXDL8MIn19+kEE1Gvc+63Go+qPOwVUlKIdKhsu2HN6tksw==", + "version": "1.7.2", + "resolved": "https://registry.npmjs.org/seroval/-/seroval-1.7.2.tgz", + "integrity": "sha512-NPOYrDVbvtuTo5m9InqKE7O6wBASON46OabjyqLUGPvoXNDYp0pReuFYkqOQwGsoj1OpZVj6mIdnRRgt5O1/gQ==", "license": "MIT", "engines": { "node": ">=20" diff --git a/package.json b/package.json index 1e5f28e..6249f63 100644 --- a/package.json +++ b/package.json @@ -20,5 +20,9 @@ "devDependencies": { "@nuxtjs/tailwindcss": "^6.14.0", "typescript": "^5.8.3" + }, + "overrides": { + "seroval": "1.7.2", + "serialize-javascript": "7.1.4" } } diff --git a/pages/library.vue b/pages/library.vue index 1547f96..c3dce9b 100644 --- a/pages/library.vue +++ b/pages/library.vue @@ -851,8 +851,16 @@ function applyLibrary(data: unknown, opts?: { replace?: boolean }) { const libraryNextCursor = ref(null) let libraryFetchGen = 0 +function payloadIds(payload: { stills?: { id: string }[]; clips?: { id: string }[]; tracks?: { id: string }[] }) { + return [ + ...(payload?.stills || []).map(item => item.id), + ...(payload?.clips || []).map(item => item.id), + ...(payload?.tracks || []).map(item => item.id) + ] +} + async function fetchLibraryPage(cursor: string | null) { - const qs = new URLSearchParams({ limit: '50' }) + 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') @@ -865,25 +873,23 @@ async function loadLibrary() { // First page paints immediately; remaining pages append in the background const gen = ++libraryFetchGen libraryLoading.value = true + const serverIds = new Set() try { const first = await fetchLibraryPage(null) if (gen !== libraryFetchGen) return + for (const id of payloadIds(first)) serverIds.add(id) applyLibrary(first, { replace: true }) let cursor = first?.nextCursor || null while (cursor && gen === libraryFetchGen) { const page = await fetchLibraryPage(cursor) if (gen !== libraryFetchGen) return + for (const id of payloadIds(page)) serverIds.add(id) applyLibrary(page, { replace: false }) cursor = page?.nextCursor || null } if (gen === libraryFetchGen) { - // Drop suppressions that the server no longer returns - const live = new Set([ - ...stills.value.map(item => item.id), - ...clips.value.map(item => item.id), - ...tracks.value.map(item => item.id) - ]) - suppressedDeletedIds.value = new Set([...suppressedDeletedIds.value].filter(id => live.has(id))) + // Keep hiding an id the server still returned. Drop it once a full fetch omits it. + suppressedDeletedIds.value = new Set([...suppressedDeletedIds.value].filter(id => serverIds.has(id))) } } finally { if (gen === libraryFetchGen) libraryLoading.value = false @@ -1043,10 +1049,24 @@ function toggleSelectMode() { if (selectMode.value) clearFocus() } +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() { - // Whole folder — not only the page already painted - await ensureLibraryFullyLoaded() - selectedKeys.value = entries.value.map(entry => entry.key) + // Loaded rows only. A fresh full-catalog fetch would merge later pages and + // can put suppressed ids back into the selection. + const start = Date.now() + while (libraryLoading.value && Date.now() - start < 15000) { + await new Promise(resolve => setTimeout(resolve, 40)) + } + const drop = suppressedDeletedIds.value + selectedKeys.value = entries.value + .filter(entry => entryPartIds(entry).every(id => !drop.has(id))) + .map(entry => entry.key) lastSelectedKey.value = selectedKeys.value.at(-1) || '' } @@ -1426,7 +1446,6 @@ watch(searchDraft, (value) => { }) watch([folderId, filter], () => { clearSelection() - suppressedDeletedIds.value = new Set() if (scroller.value) scroller.value.scrollTop = 0 }) watch(search, () => { diff --git a/server/middleware/cache-headers.ts b/server/middleware/cache-headers.ts new file mode 100644 index 0000000..3840a4c --- /dev/null +++ b/server/middleware/cache-headers.ts @@ -0,0 +1,12 @@ +/** 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') + } +}) diff --git a/server/utils/library.ts b/server/utils/library.ts index e9c3d26..ce22980 100644 --- a/server/utils/library.ts +++ b/server/utils/library.ts @@ -398,7 +398,8 @@ function invalidateCatalogCache(owner?: string) { function mutate(owner: string, fn: (catalog: Catalog) => T): Promise { const prev = writeChains.get(owner) || Promise.resolve() const run = prev.then(() => { - const catalog = readCatalog(owner) + // Copy first so a throw cannot leave the cached catalog diverged from disk. + const catalog = structuredClone(readCatalog(owner)) const result = fn(catalog) writeCatalog(owner, catalog) return result @@ -863,15 +864,9 @@ export function deleteFolder(owner: string, id: string) { catalog.clips = catalog.clips.filter(clip => clip.folderId !== id) catalog.stills = catalog.stills.filter(still => still.folderId !== id) catalog.tracks = (catalog.tracks || []).filter(track => track.folderId !== id) - for (const clip of clips) { - rmSync(clipDir(owner, clip.id), { recursive: true, force: true }) - } - for (const still of stills) { - removeStillFiles(owner, still.id) - } - for (const track of tracks) { - rmSync(trackDir(owner, track.id), { recursive: true, force: true }) - } + for (const clip of clips) safeRm(clipDir(owner, clip.id), true) + for (const still of stills) removeStillFiles(owner, still.id) + for (const track of tracks) safeRm(trackDir(owner, track.id), true) return { fallbackFolderId: catalog.folders[0].id } }) } @@ -892,19 +887,11 @@ export function wipeFolderContents(owner: string, folderId: string) { catalog.clips = catalog.clips.filter(clip => clip.folderId !== folderId) catalog.stills = catalog.stills.filter(still => still.folderId !== folderId) catalog.tracks = (catalog.tracks || []).filter(track => track.folderId !== folderId) - catalog.drafts = (catalog.drafts || []).map((draft) => { - if (!draft.stillId || !deletedIds.has(draft.stillId)) return draft - return { ...draft, stillId: undefined, stillFilename: undefined } - }) - for (const clip of clips) { - rmSync(clipDir(owner, clip.id), { recursive: true, force: true }) - } - for (const still of stills) { - removeStillFiles(owner, still.id) - } - for (const track of tracks) { - rmSync(trackDir(owner, track.id), { recursive: true, force: true }) - } + detachDraftStills(catalog, deletedIds) + for (const clip of clips) safeRm(clipDir(owner, clip.id), true) + for (const still of stills) removeStillFiles(owner, still.id) + for (const track of tracks) safeRm(trackDir(owner, track.id), true) + pruneMissingStillMasters(owner, catalog) return { folderId: folder.id, folderName: folder.name, @@ -916,12 +903,29 @@ export function wipeFolderContents(owner: string, folderId: string) { }) } +function detachDraftStills(catalog: Catalog, ids: Set) { + if (!ids.size) return + catalog.drafts = (catalog.drafts || []).map((draft) => { + if (!draft.stillId || !ids.has(draft.stillId)) return draft + return { ...draft, stillId: undefined, stillFilename: undefined } + }) +} + /** Drop catalog stills whose master file is gone — a 204 thumb is not a still. */ function pruneMissingStillMasters(owner: string, catalog: Catalog) { const keep: LibraryStill[] = [] const droppedIds = new Set() for (const still of catalog.stills) { - if (existsSync(stillPath(owner, still.id))) { + let present = false + try { + present = existsSync(stillPath(owner, still.id)) + } catch (error) { + const message = error instanceof Error ? error.message : String(error) + console.error('[library] still master check failed', still.id, message) + keep.push(still) + continue + } + if (present) { keep.push(still) continue } @@ -930,10 +934,7 @@ function pruneMissingStillMasters(owner: string, catalog: Catalog) { } if (!droppedIds.size) return 0 catalog.stills = keep - catalog.drafts = (catalog.drafts || []).map((draft) => { - if (!draft.stillId || !droppedIds.has(draft.stillId)) return draft - return { ...draft, stillId: undefined, stillFilename: undefined } - }) + detachDraftStills(catalog, droppedIds) return droppedIds.size } @@ -1371,10 +1372,20 @@ export function existingStillPreviewPath(owner: string, id: string) { return '' } +/** Never throw — a locked thumb must not abort the catalog write. */ +function safeRm(target: string, recursive = false) { + try { + rmSync(target, recursive ? { recursive: true, force: true } : { force: true }) + } catch (error) { + const message = error instanceof Error ? error.message : String(error) + console.error('[library] file remove failed', message) + } +} + function removeStillFiles(owner: string, id: string) { - rmSync(stillPath(owner, id), { force: true }) - rmSync(stillThumbFile(owner, id), { force: true }) - rmSync(stillPreviewFile(owner, id), { force: true }) + safeRm(stillPath(owner, id)) + safeRm(stillThumbFile(owner, id)) + safeRm(stillPreviewFile(owner, id)) } let thumbSlots = 0 @@ -1899,7 +1910,9 @@ export function deleteStill(owner: string, id: string) { const still = catalog.stills.find(item => item.id === id) if (!still) throw createError({ statusCode: 404, statusMessage: 'Image not found' }) catalog.stills = catalog.stills.filter(item => item.id !== id) + detachDraftStills(catalog, new Set([id])) removeStillFiles(owner, id) + pruneMissingStillMasters(owner, catalog) return still }) } @@ -1922,9 +1935,9 @@ export function deleteStillFamily(owner: string, id: string) { const family = stillsInSameFamily(catalog, still) const ids = new Set(family.map(item => item.id)) catalog.stills = catalog.stills.filter(item => !ids.has(item.id)) - for (const item of family) { - removeStillFiles(owner, item.id) - } + detachDraftStills(catalog, ids) + for (const item of family) removeStillFiles(owner, item.id) + pruneMissingStillMasters(owner, catalog) return family }) } diff --git a/server/utils/loras.ts b/server/utils/loras.ts index b2b75ee..5932e64 100644 --- a/server/utils/loras.ts +++ b/server/utils/loras.ts @@ -217,6 +217,8 @@ async function loadLoraCache(options: { fresh?: boolean } = {}): Promise// show up + // without a restart. Names stay Comfy-relative (slashes included) for the graph. try { const listed = await loadLoraCache(options) return { diff --git a/tests/library-delete-harden.test.mjs b/tests/library-delete-harden.test.mjs new file mode 100644 index 0000000..30ac642 --- /dev/null +++ b/tests/library-delete-harden.test.mjs @@ -0,0 +1,135 @@ +import test from 'node:test' +import assert from 'node:assert/strict' +import { readFileSync } from 'node:fs' +import ts from 'typescript' + +const source = readFileSync(new URL('../server/utils/library.ts', import.meta.url), 'utf8') +const ast = ts.createSourceFile('library.ts', source, ts.ScriptTarget.Latest, true) +const names = [ + 'safeRm', + 'removeStillFiles', + 'detachDraftStills', + 'pruneMissingStillMasters', + 'catalogWithPrunedStills', + 'deleteStill', + 'deleteStillFamily', + 'wipeFolderContents' +] +const functions = ast.statements + .filter(node => ts.isFunctionDeclaration(node) && names.includes(node.name?.text || '')) + .map(node => node.getText(ast).replace(/^export /, '')) + .join('\n') +const js = ts.transpileModule(functions, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText + +function harness() { + const files = new Set() + const thrown = new Set() + let writes = 0 + let stored = null + function readCatalog() { return stored } + function writeCatalog(_owner, catalog) { + stored = catalog === undefined ? _owner : catalog + writes += 1 + } + const api = new Function( + 'rmSync', + 'existsSync', + 'console', + 'stillPath', + 'stillThumbFile', + 'stillPreviewFile', + 'clipDir', + 'trackDir', + 'createError', + 'stillsInSameFamily', + 'mutate', + 'readCatalog', + 'writeCatalog', + `${js}; return { catalogWithPrunedStills, deleteStill, deleteStillFamily, wipeFolderContents };` + )( + (path) => { + if ([...thrown].some(id => String(path).includes(id))) throw new Error('EPERM') + files.delete(path) + }, + (path) => files.has(path), + console, + (owner, id) => `${owner}/stills/${id}`, + (owner, id) => `${owner}/stills/${id}.thumb.jpg`, + (owner, id) => `${owner}/stills/${id}.preview.jpg`, + (owner, id) => `${owner}/clips/${id}`, + (owner, id) => `${owner}/tracks/${id}`, + (error) => Object.assign(new Error(error.statusMessage), error), + (catalog, still) => catalog.stills.filter(item => item.id === still.id || (still.familyId && item.familyId === still.familyId)), + async (_owner, fn) => { + const catalog = readCatalog() + const result = fn(catalog) + writeCatalog(catalog) + return result + }, + readCatalog, + writeCatalog + ) + return { + api, + files, + thrown, + get writes() { return writes }, + set writes(value) { writes = value }, + load(catalog) { stored = catalog } + } +} + +test('deleteStill drops the catalog row when the file remove fails', async () => { + const h = harness() + h.thrown.add('locked') + h.files.add('owner/stills/locked') + const catalog = { + stills: [{ id: 'locked', folderId: 'inbox' }, { id: 'keep', folderId: 'inbox' }], + drafts: [{ id: 'd', stillId: 'locked', stillFilename: 'locked.png' }], + clips: [], + tracks: [], + folders: [{ id: 'inbox' }] + } + h.load(catalog) + h.files.add('owner/stills/keep') + await h.api.deleteStill('owner', 'locked') + assert.equal(h.writes, 1) + assert.deepEqual(catalog.stills.map(item => item.id), ['keep']) + assert.equal(catalog.drafts[0].stillId, undefined) + assert.equal(h.files.has('owner/stills/keep'), true) +}) + +test('pruneMissingStillMasters runs on delete and on catalog read', async () => { + const h = harness() + const catalog = { + stills: [{ id: 'gone', folderId: 'inbox' }, { id: 'keep', folderId: 'inbox' }], + drafts: [{ id: 'd', stillId: 'gone' }], + clips: [], + tracks: [], + folders: [{ id: 'inbox' }] + } + h.load(structuredClone(catalog)) + h.files.add('owner/stills/keep') + const page = h.api.catalogWithPrunedStills('owner') + assert.equal(h.writes, 1) + assert.deepEqual(page.stills.map(item => item.id), ['keep']) + assert.equal(page.drafts[0].stillId, undefined) +}) + +test('wipeFolderContents still clears the folder when a file remove throws', async () => { + const h = harness() + h.thrown.add('locked') + const catalog = { + stills: [{ id: 'locked', folderId: 'inbox' }], + clips: [{ id: 'clip', folderId: 'inbox' }], + tracks: [], + drafts: [], + folders: [{ id: 'inbox', name: 'Inbox' }] + } + h.load(catalog) + const result = await h.api.wipeFolderContents('owner', 'inbox') + assert.equal(result.deleted, 2) + assert.equal(catalog.stills.length, 0) + assert.equal(catalog.clips.length, 0) + assert.equal(h.writes, 1) +}) diff --git a/tests/lora-folders.test.mjs b/tests/lora-folders.test.mjs new file mode 100644 index 0000000..5eafa94 --- /dev/null +++ b/tests/lora-folders.test.mjs @@ -0,0 +1,41 @@ +import test from 'node:test' +import assert from 'node:assert/strict' +import { + filterLorasForImageEngine, + filterLorasForStudio, + imageLoraEngineOf, + inferLoraUse, + isXaigenOnlyLora, + makeLoraStackItem +} from '../utils/loras.ts' + +test('engine folders decide engine and site, filename prefixes stay a fallback', () => { + const krea = 'xaigen/krea/foo.safetensors' + const flux = 'aigen/flux/bar.safetensors' + const flat = 'krea-something.safetensors' + const folderWins = 'aigen/flux/krea-something.safetensors' + const typo = 'xiagen/moss/look.safetensors' + + assert.equal(isXaigenOnlyLora(krea), true) + assert.equal(imageLoraEngineOf(krea), 'krea') + assert.deepEqual(inferLoraUse(krea), ['krea']) + assert.deepEqual(filterLorasForStudio([krea], false), []) + assert.deepEqual(filterLorasForStudio([krea], true), [krea]) + assert.deepEqual(filterLorasForImageEngine([krea, flux], 'krea'), [krea]) + + assert.equal(isXaigenOnlyLora(flux), false) + assert.equal(imageLoraEngineOf(flux), 'flux') + assert.deepEqual(inferLoraUse(flux), ['flux']) + assert.deepEqual(filterLorasForStudio([flux], false), [flux]) + + assert.equal(isXaigenOnlyLora(flat), false) + assert.equal(imageLoraEngineOf(flat), 'krea') + assert.deepEqual(filterLorasForImageEngine([flat], 'krea'), [flat]) + + assert.equal(imageLoraEngineOf(folderWins), 'flux') + assert.equal(isXaigenOnlyLora(typo), true) + assert.equal(imageLoraEngineOf(typo), 'moss') + + const stored = makeLoraStackItem(krea) + assert.equal(stored?.name, krea) +}) diff --git a/utils/loras.ts b/utils/loras.ts index 4327b7b..838f3c9 100644 --- a/utils/loras.ts +++ b/utils/loras.ts @@ -29,10 +29,36 @@ export function loraIdentityKey(name: string) { return loraBasename(name).replace(/^(xai|xia)gen-?/i, '').toLowerCase() } +function loraSegments(name: string) { + return String(name || '').replace(/\\/g, '/').split('/').filter(Boolean) +} + +/** + * Engine directory immediately under `xaigen/`, `xiagen/`, or `aigen/`. + * `aigen/` stays visible on AIGen. Only `xaigen` / `xiagen` are xAIGen-only. + */ +function loraEngineFolder(name: string): 'flux' | 'krea' | 'moss' | 'minimax' | 'ltx' | 'qwen21' | null { + const parts = loraSegments(name) + for (let i = 0; i < parts.length - 1; i += 1) { + if (!/^(?:xaigen|xiagen|aigen)$/i.test(parts[i])) continue + if (/\.(safetensors|sft|ckpt|pt|bin)$/i.test(parts[i + 1])) continue + const next = parts[i + 1].toLowerCase() + if (next === 'flux' || next === 'klein') return 'flux' + if (next === 'krea') return 'krea' + if (next === 'moss') return 'moss' + if (next === 'minimax') return 'minimax' + if (next === 'ltx') return 'ltx' + if (next === 'qwen' || next === 'qwen21' || next === 'qwen2') return 'qwen21' + } + return null +} + export function isXaigenOnlyLora(name: string) { - const base = loraBasename(name) - // Include the common `xiagen-` typo so those files stay off AIGen too. - return String(name || '').replace(/\\/g, '/').split('/').some(part => /^(xai|xia)gen/i.test(part)) || /klein_snofs|snofs_krea/i.test(base) + const parts = loraSegments(name) + const base = parts[parts.length - 1] || '' + // `aigen` is the AIGen tree. `xaigen` / `xiagen` (typo) and filename prefixes stay xAIGen-only. + if (parts.some(part => /^(xai|xia)gen/i.test(part))) return true + return /klein_snofs|snofs_krea/i.test(base) } /** Pick the real Comfy filename: exact path, then same basename ignoring `xaigen-`, then suffix/contains. */ @@ -237,11 +263,8 @@ function hasImageEngineToken(source: string, engine: 'flux' | 'krea' | 'moss') { return new RegExp(`(?:^|[/_.-])${token}`).test(value) } -/** - * Image engine from the filename: `xaigen-flux-…` / `flux-…` vs `xaigen-krea-…` / `krea-…`. - * Klein / SNOFS files without that prefix still count as Flux or Krea. - */ -export function imageLoraEngineOf(name: string): 'flux' | 'krea' | 'moss' | null { +/** Filename / path-token fallback for flat files that have not moved into an engine folder. */ +function imageLoraEngineFromTokens(name: string): 'flux' | 'krea' | 'moss' | null { const raw = String(name || '') const base = loraBasename(raw) const id = loraIdentityKey(raw) @@ -266,6 +289,17 @@ export function imageLoraEngineOf(name: string): 'flux' | 'krea' | 'moss' | null return null } +/** + * Prefer the engine folder directly under `xaigen/` or `aigen/`. + * Flat `krea-…` / `flux-…` filenames still match through the token fallback. + */ +export function imageLoraEngineOf(name: string): 'flux' | 'krea' | 'moss' | null { + const folder = loraEngineFolder(name) + if (folder === 'flux' || folder === 'krea' || folder === 'moss') return folder + if (folder) return null + return imageLoraEngineFromTokens(name) +} + export function loraMatchesImageEngine(name: string, engine: 'flux' | 'krea' | 'moss') { return imageLoraEngineOf(name) === engine } @@ -299,8 +333,10 @@ export function isSystemGraphLora(name: string) { return false } -/** Engine tokens in paths or basenames; unlabelled files are not picker options. */ +/** Engine folder under xaigen/ or aigen/ wins. Otherwise tokens in paths or basenames. */ export function inferLoraUse(name: string): LoraUse[] | null { + const folder = loraEngineFolder(name) + if (folder) return [folder] const value = String(name || '').toLowerCase() const uses: LoraUse[] = [] if (/minimax/.test(value)) uses.push('minimax') @@ -320,6 +356,8 @@ export function isQwenImageLora(name: string) { export function loraMatchesUse(name: string, use: LoraUse) { if (isSystemGraphLora(name)) return false + const folder = loraEngineFolder(name) + if (folder) return folder === use if (use === 'qwen21') return isQwenImageLora(name) return !!inferLoraUse(name)?.includes(use) } @@ -329,6 +367,8 @@ export function filterLoraStackForUse(stack: unknown, use: LoraUse, xaigen: bool if (use === 'ltx' && !xaigen) return [] return filterLoraStackForStudio(stack, xaigen).filter(item => { if (isSystemGraphLora(item.name)) return false + const folder = loraEngineFolder(item.name) + if (folder) return folder === use if (use === 'qwen21') return isQwenImageLora(item.name) const uses = inferLoraUse(item.name) return !uses || uses.includes(use)