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>
This commit is contained in:
Towsty
2026-10-24 12:01:25 -05:00
co-authored by Cursor
parent 39aa4b65d0
commit 545a3d749b
12 changed files with 393 additions and 131 deletions
+2 -2
View File
@@ -6,9 +6,9 @@ Nuxt 3 app, Nitro `node-server`, Vue 3. Production image is `node:22.23.4-alpine
`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. 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.
`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 it refetches that list and clears form slots that pointed at the deleted id.
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
+2
View File
@@ -2,6 +2,8 @@
## 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.
+2
View File
@@ -6,6 +6,8 @@
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.
+70 -12
View File
@@ -237,7 +237,7 @@
@click="libraryOpen=true"
>Library<span v-if="familyStillCount" class="stage-library-count">{{ familyStillCount }}</span></button>
<div
v-if="selected && selected.kind!=='track'"
v-if="selected && selected.kind!=='track' && (selected.kind==='clip' || showSelectedStill)"
class="stage-actions"
aria-label="Selected still actions"
>
@@ -282,7 +282,7 @@
<button type="button" class="stage-action-danger" @click="deleteOutput">Delete</button>
</div>
<button
v-if="selected"
v-if="selected && (selected.kind==='clip' || selected.kind==='track' || showSelectedStill)"
type="button"
class="eye-viewer"
:aria-pressed="eyeOpen"
@@ -322,7 +322,7 @@
@loadedmetadata="onVideoTime"
/>
</template>
<template v-else-if="selected">
<template v-else-if="selected && showSelectedStill">
<img
v-show="!isHidden(selected)"
:key="selected.id+'-'+stagePreviewNonce"
@@ -373,6 +373,7 @@
@load-input="onLibraryLoadInput"
@load-input-raw="onLibraryLoadInputRaw"
@delete="onLibraryDelete"
@wiped="onLibraryWiped"
@toggle-preview="toggleReveal()"
/>
</section>
@@ -490,7 +491,7 @@ import {createLoraMemory,loraUse} from '~/shared/studio2/lora-memory.mjs'
import {filterLorasForStudio,filterLorasForUse} from '~/utils/loras'
import {sectionsFrom} from '~/shared/studio2/contracts.mjs'
import {aspectOptions,resolveSize,bindClip,restoreAll,useAsSource,hydrateStudio2Job} from '~/shared/studio2/input.mjs'
import {folderAssets,newestOutput,assetLabel,reconcileSelection,previewHidden} from '~/shared/studio2/viewer.mjs'
import {folderAssets,newestOutput,assetLabel,reconcileSelection,previewHidden,folderImageCount,libraryAfterWipe} from '~/shared/studio2/viewer.mjs'
import {queueJobs,queueEngineLabel,jobStageLabel,jobProgressView,elapsedSeconds} from '~/shared/studio2/queue-view.mjs'
import {gpuStatus} from '~/shared/studio2/status.mjs'
import {CAPTION_STYLES} from '~/shared/caption.mjs'
@@ -973,11 +974,18 @@ const pickerAssets=computed(()=>{
})
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)
const fromFolder=Number(folder?.imageCount||0)
if(fromFolder>0) return fromFolder
return family.value.filter((a:any)=>a.kind==='still').length
const familyStillCount=computed(()=>folderImageCount(
(library.value.folders||[]).find((f:any)=>f.id===form.folderId),
family.value.filter((a:any)=>a.kind==='still').length
))
const showSelectedStill=computed(()=>{
const item=selected.value
if(!item?.id || item.kind==='clip' || item.kind==='track') return false
if(forgottenStillIds.value.has(item.id)) return false
if((library.value.stills||[]).some((s:any)=>s.id===item.id)) return true
const folder=(library.value.folders||[]).find((f:any)=>f.id===(item.folderId||form.folderId))
if(folder && typeof folder.imageCount==='number' && folder.imageCount===0) return false
return true
})
const sourceAsset=computed(()=>form.startClipId?clips.value.find((c:any)=>c.id===form.startClipId):stills.value.find((s:any)=>s.id===(form.imageAId||form.identityStillId||form.photos?.[0]?.stillId)))
const sourceSize=computed(()=>measured[sourceAsset.value?.id] || sourceAsset.value)
@@ -1539,6 +1547,35 @@ function onLibraryLoadInputRaw(item:any){
function onLibraryDelete(item:any){
void deleteOutput(item)
}
function onLibraryWiped(result:any){
const folderId=String(result?.folderId||form.folderId||'')
const next=libraryAfterWipe({
folders:library.value.folders,
stills:library.value.stills,
clips:library.value.clips,
tracks:library.value.tracks,
suppressedIds:[...forgottenStillIds.value]
}, result, folderId)
forgottenStillIds.value=new Set(next.suppressedIds)
clearFormSlots(next.suppressedIds)
if(selected.value && (forgottenStillIds.value.has(selected.value.id) || String(selected.value.folderId||'')===folderId)){
selected.value=null
selectionPinned.value=false
}
library.value={
...library.value,
folders:next.folders,
stills:next.stills,
clips:next.clips,
tracks:next.tracks,
drafts:result?.drafts||[],
loraAliases:result?.loraAliases||library.value.loraAliases||{},
loraTriggers:result?.loraTriggers||library.value.loraTriggers||{},
keepPrompts:result?.keepPrompts||library.value.keepPrompts
}
libraryRefreshKey.value+=1
void loadLibraryOnce()
}
function onStageHotkey(e:KeyboardEvent){
if(e.metaKey||e.ctrlKey||e.altKey)return
const t=e.target as HTMLElement|null
@@ -1707,6 +1744,13 @@ function onTaskSelect(event:Event){chooseTask((event.target as HTMLSelectElement
function chooseClip(id:string){if(!id){form.startClipId='';return}const clip=clips.value.find((c:any)=>c.id===id);if(clip){try{Object.assign(form,bindClip(form,clip,xaigen,loraMemory))}catch(e:any){error.value=e?.message||'Could not copy clip settings.';form.startClipId=clip.id;form.mode='extend';form.engine=xaigen && form.engine==='ltx'?'ltx':'minimax'}}}
function selectOutput(item:any){
stageMenu.value=''
if(item?.id && !forgottenStillIds.value.has(item.id)){
const kind=item.kind==='clip'?'clips':item.kind==='track'?'tracks':'stills'
const list=library.value[kind]||[]
if(!list.some((row:any)=>row.id===item.id)){
library.value={...library.value,[kind]:[...list,{...item,folderId:item.folderId||form.folderId}]}
}
}
selected.value=item
selectionPinned.value=!!item
if(form.mode==='extend' && item?.kind==='clip')chooseClip(item.id)
@@ -1754,7 +1798,10 @@ function ingestNewOutputs(nextJobs:any[]){
const fresh=newestOutput(nextJobs,seenOutputs,form.folderId)
for(const job of nextJobs){
for(const output of job.outputs||[]){
if(seenOutputs.has(output.id)) continue
if(seenOutputs.has(output.id) || forgottenStillIds.value.has(output.id)){
seenOutputs.add(output.id)
continue
}
seenOutputs.add(output.id)
const meta=output.studio2||{}
const folderId=job.request?.folderId||form.folderId
@@ -1778,7 +1825,7 @@ function ingestNewOutputs(nextJobs:any[]){
}
}
}
if(fresh){
if(fresh && !forgottenStillIds.value.has(fresh.id)){
// Merge into catalog above; only auto-select when the user has not pinned a pick.
if(!selectionPinned.value){
const existingFresh=family.value.find(a=>a.id===fresh.id)
@@ -1788,6 +1835,9 @@ function ingestNewOutputs(nextJobs:any[]){
selected.value={...fresh,kind,folderId:form.folderId,studio2:fresh.studio2}
}
}
}else if(selected.value && forgottenStillIds.value.has(selected.value.id)){
selected.value=null
selectionPinned.value=false
}else if(selected.value){
const next=reconcileSelection(selected.value,family.value)
if(form.mode!=='music' && next?.kind==='track'){
@@ -1795,8 +1845,9 @@ function ingestNewOutputs(nextJobs:any[]){
if(nonTrack && !selectionPinned.value) selected.value=nonTrack
else if(next?.id===selected.value.id) selected.value=next
}else if(next) selected.value=next
else { selected.value=null; selectionPinned.value=false }
}else{
selected.value=reconcileSelection(null,family.value)
selected.value=reconcileSelection(null,family.value.filter((a:any)=>!forgottenStillIds.value.has(a.id)))
}
const newestTrack=(library.value.tracks||[]).filter((t:any)=>t.folderId===form.folderId).sort((a:any,b:any)=>(b.createdAt||0)-(a.createdAt||0))[0]
if(form.mode==='music' && newestTrack && !seenOutputs.has(newestTrack.id)){
@@ -1961,12 +2012,15 @@ async function cancel(job:any){
await refreshJobs()
}
let libraryLoadGen=0
async function loadLibraryOnce(){
// Current folder page only — never the yearly Inbox JSON on /
const gen=++libraryLoadGen
const qs=new URLSearchParams({limit:'50'})
if(form.folderId) qs.set('folderId',form.folderId)
qs.set('_',String(Date.now()))
const page=await $fetch<any>(`/api/library?${qs.toString()}`)
if(gen!==libraryLoadGen) return
const pageStills=page.stills||[]
const forget=forgottenStillIds.value
const keepIds=[
@@ -1980,10 +2034,12 @@ async function loadLibraryOnce(){
if(stillMissing.length){
try{
const full=await $fetch<any>(`/api/library?light=1&_=${Date.now()}`)
if(gen!==libraryLoadGen) return
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 */}
}
if(gen!==libraryLoadGen) return
library.value={
folders:page.folders||library.value.folders||[],
stills:[...pageStills,...kept].filter((s:any)=>!forget.has(s.id)),
@@ -2103,6 +2159,7 @@ const mobileCtx=computed(()=>({
libraryRefreshKey:libraryRefreshKey.value,
family:family.value,
familyStillCount:familyStillCount.value,
showSelectedStill:showSelectedStill.value,
libraryOpen:libraryOpen.value,
eyeOpen:eyeOpen.value,
hideInputs:hideInputs.value,
@@ -2144,6 +2201,7 @@ const mobileCtx=computed(()=>({
selectOutput,
stepFamily,
deleteOutput,
onLibraryWiped,
queue,
upload,
cancel,
+31 -42
View File
@@ -154,7 +154,7 @@ import {
type LibraryTrack
} from '~/utils/libraryBrowse'
import { clipSettingsRows, stillSettingsRows, trackSettingsRows } from '~/utils/libraryGeneration'
import { assetLabel } from '~/shared/studio2/viewer.mjs'
import { assetLabel, libraryAfterWipe, mergeLibraryRows, replaceLibraryRows } from '~/shared/studio2/viewer.mjs'
const props = defineProps<{
open: boolean
@@ -177,6 +177,7 @@ const emit = defineEmits<{
'load-input': [asset: any]
'load-input-raw': [asset: any]
delete: [asset: any]
wiped: [payload: any]
'toggle-preview': []
}>()
@@ -298,32 +299,19 @@ function onDeleteClick() {
emit('delete', asset)
}
function mergeIds(prev: { id: string }[], next: { id: string }[]) {
const drop = dropIds()
const map = new Map<string, { id: string }>()
for (const item of prev) {
if (!drop.has(item.id)) map.set(item.id, item)
}
for (const item of next) {
if (!drop.has(item.id)) map.set(item.id, item)
}
return [...map.values()]
}
function applyLibraryPage(data: any, replace: boolean) {
folders.value = data?.folders || folders.value
const drop = dropIds()
const keep = <T extends { id: string }>(list: T[]) => list.filter(item => !drop.has(item.id))
if (Array.isArray(data?.folders) && data.folders.length) folders.value = data.folders
const drop = [...dropIds()]
if (replace) {
clips.value = keep(data?.clips || []) as LibraryClip[]
stills.value = keep(data?.stills || []) as LibraryStill[]
tracks.value = keep(data?.tracks || []) as LibraryTrack[]
clips.value = replaceLibraryRows(data?.clips || [], drop) as LibraryClip[]
stills.value = replaceLibraryRows(data?.stills || [], drop) as LibraryStill[]
tracks.value = replaceLibraryRows(data?.tracks || [], drop) as LibraryTrack[]
} else {
clips.value = mergeIds(clips.value, data?.clips || []) as LibraryClip[]
stills.value = mergeIds(stills.value, data?.stills || []) as LibraryStill[]
tracks.value = mergeIds(tracks.value, data?.tracks || []) as LibraryTrack[]
clips.value = mergeLibraryRows(clips.value, data?.clips || [], drop) as LibraryClip[]
stills.value = mergeLibraryRows(stills.value, data?.stills || [], drop) as LibraryStill[]
tracks.value = mergeLibraryRows(tracks.value, data?.tracks || [], drop) as LibraryTrack[]
}
nextCursor.value = data?.nextCursor || null
nextCursor.value = data?.nextCursor ?? null
fetchedAt.value = Date.now()
}
@@ -343,20 +331,35 @@ async function confirmWipeFolder() {
if (!pending || wipeBusy.value) return
pendingWipe.value = null
wipeBusy.value = true
try {
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)
]
const next = new Set(suppressedDeletedIds.value)
for (const id of gone) next.add(id)
suppressedDeletedIds.value = next
const pendingIds = new Set(suppressedDeletedIds.value)
for (const id of gone) pendingIds.add(id)
suppressedDeletedIds.value = pendingIds
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' })
applyLibraryPage(result, true)
const next = libraryAfterWipe({
folders: folders.value,
stills: [...stills.value, ...gone.map(id => ({ id, folderId: pending.folderId }))],
clips: clips.value,
tracks: tracks.value,
suppressedIds: [...suppressedDeletedIds.value]
}, result, pending.folderId)
suppressedDeletedIds.value = new Set(next.suppressedIds)
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, suppressedIds: next.suppressedIds })
await fetchLibrary(true)
} catch (e: any) {
loadError.value = e?.data?.statusMessage || e?.message || 'Could not empty that folder'
@@ -378,14 +381,6 @@ 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
@@ -394,11 +389,9 @@ async function fetchLibrary(force = false) {
loading.value = true
loadError.value = ''
liveThumbs.value = new Set()
const serverIds = new Set<string>()
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())
@@ -407,14 +400,10 @@ 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'
+2 -1
View File
@@ -125,7 +125,7 @@
playsinline
/>
<img
v-else-if="ctx.selected"
v-else-if="ctx.selected && ctx.showSelectedStill"
v-show="!ctx.isHidden(ctx.selected)"
:key="ctx.selected.id+'-'+(ctx.stagePreviewNonce||0)"
class="m-stage-still"
@@ -155,6 +155,7 @@
@load-input="ctx.onLibraryLoadInput"
@load-input-raw="ctx.onLibraryLoadInputRaw"
@delete="ctx.onLibraryDelete"
@wiped="ctx.onLibraryWiped"
@toggle-preview="ctx.toggleReveal()"
/>
+23 -35
View File
@@ -556,6 +556,7 @@ import {
type LibraryStill,
type LibraryTrack
} from '~/utils/libraryBrowse'
import { libraryAfterWipe, mergeLibraryRows, replaceLibraryRows } from '~/shared/studio2/viewer.mjs'
import { isXaigenStudio } from '~/utils/videoModels'
import { clipSettingsRows, stillSettingsRows, trackSettingsRows } from '~/utils/libraryGeneration'
@@ -821,26 +822,15 @@ function applyLibrary(data: unknown, opts?: { replace?: boolean }) {
return
}
if (payload.folders?.length) folders.value = payload.folders
const drop = suppressedDeletedIds.value
const keep = <T extends { id: string }>(list: T[]) => list.filter(item => !drop.has(item.id))
const drop = [...suppressedDeletedIds.value]
if (replace) {
clips.value = keep(payload.clips || [])
stills.value = keep(payload.stills || [])
tracks.value = keep(payload.tracks || [])
clips.value = replaceLibraryRows(payload.clips || [], drop)
stills.value = replaceLibraryRows(payload.stills || [], drop)
tracks.value = replaceLibraryRows(payload.tracks || [], drop)
} else {
const merge = <T extends { id: string }>(prev: T[], next: T[]) => {
const map = new Map<string, T>()
for (const item of prev) {
if (!drop.has(item.id)) map.set(item.id, item)
}
for (const item of next) {
if (!drop.has(item.id)) map.set(item.id, item)
}
return [...map.values()]
}
clips.value = merge(clips.value, payload.clips || [])
stills.value = merge(stills.value, payload.stills || [])
tracks.value = merge(tracks.value, payload.tracks || [])
clips.value = mergeLibraryRows(clips.value, payload.clips || [], drop)
stills.value = mergeLibraryRows(stills.value, payload.stills || [], drop)
tracks.value = mergeLibraryRows(tracks.value, payload.tracks || [], drop)
}
libraryNextCursor.value = payload.nextCursor || null
if (folderId.value !== 'all' && !folders.value.some(folder => folder.id === folderId.value)) {
@@ -851,14 +841,6 @@ function applyLibrary(data: unknown, opts?: { replace?: boolean }) {
const libraryNextCursor = ref<string | null>(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', _: String(Date.now()) })
if (folderId.value && folderId.value !== 'all') qs.set('folderId', folderId.value)
@@ -873,24 +855,17 @@ async function loadLibrary() {
// First page paints immediately; remaining pages append in the background
const gen = ++libraryFetchGen
libraryLoading.value = true
const serverIds = new Set<string>()
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) {
// 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
}
@@ -1375,7 +1350,7 @@ async function confirmWipeFolder() {
if (!pending || wipeBusy.value) return
pendingWipe.value = null
wipeBusy.value = true
try {
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),
@@ -1384,8 +1359,21 @@ async function confirmWipeFolder() {
markDeletedIds(gone)
clearSelection()
clearFocus()
try {
const result = await $fetch<any>(`/api/library/folders/${pending.folderId}/wipe`, { method: 'POST' })
applyLibrary(result, { replace: true })
const next = libraryAfterWipe({
folders: folders.value,
stills: [...stills.value, ...gone.map(id => ({ id, folderId: pending.folderId }))],
clips: clips.value,
tracks: tracks.value,
suppressedIds: [...suppressedDeletedIds.value]
}, result, pending.folderId)
suppressedDeletedIds.value = new Set(next.suppressedIds)
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) {
+8 -1
View File
@@ -1,7 +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)
return { ...result, ...publicLibrary(event, { light: true }) }
// 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 }
})
+94 -20
View File
@@ -187,7 +187,8 @@ interface Catalog {
}
const writeChains = new Map<string, Promise<unknown>>()
const catalogCache = new Map<string, { catalog: Catalog; mtimeMs: number }>()
const catalogCache = new Map<string, { catalog: Catalog; mtimeMs: number; epoch: number }>()
const catalogEpoch = new Map<string, number>()
export function libraryRoot() {
const config = useRuntimeConfig()
@@ -356,12 +357,19 @@ function ensureOwner(owner: string) {
function readCatalog(owner: string): Catalog {
ensureOwner(owner)
const path = catalogPath(owner)
let mtimeMs = 0
try {
mtimeMs = existsSync(path) ? statSync(path).mtimeMs : 0
} catch { mtimeMs = 0 }
const epoch = catalogEpoch.get(owner) || 0
const hit = catalogCache.get(owner)
if (hit && hit.mtimeMs === mtimeMs && mtimeMs > 0) return hit.catalog
if (hit && hit.epoch === epoch) {
let mtimeMs = 0
try { mtimeMs = existsSync(path) ? statSync(path).mtimeMs : 0 } catch { mtimeMs = 0 }
// Coolify volumes and Windows can return a stale mtime after rename.
// An unchanged or older mtime must not throw away the catalog we just wrote.
if (mtimeMs <= hit.mtimeMs) return hit.catalog
}
const epochAtStart = catalogEpoch.get(owner) || 0
let mtimeMs = 0
try { mtimeMs = existsSync(path) ? statSync(path).mtimeMs : 0 } catch { mtimeMs = 0 }
let catalog: Catalog
try {
@@ -373,10 +381,21 @@ function readCatalog(owner: string): Catalog {
catalog = emptyCatalog()
writeFileSync(path, JSON.stringify(catalog, null, 2))
try { mtimeMs = statSync(path).mtimeMs } catch { mtimeMs = Date.now() }
catalogCache.set(owner, { catalog, mtimeMs })
if ((catalogEpoch.get(owner) || 0) !== epochAtStart) {
const newer = catalogCache.get(owner)
if (newer && newer.epoch === (catalogEpoch.get(owner) || 0)) return newer.catalog
}
catalogCache.set(owner, { catalog, mtimeMs, epoch: catalogEpoch.get(owner) || 0 })
return catalog
}
catalogCache.set(owner, { catalog, mtimeMs })
const epochNow = catalogEpoch.get(owner) || 0
if (epochNow !== epochAtStart) {
const newer = catalogCache.get(owner)
if (newer && newer.epoch === epochNow) return newer.catalog
// A write landed while this parse was in flight. Never cache those bytes.
return readCatalog(owner)
}
catalogCache.set(owner, { catalog, mtimeMs, epoch: epochNow })
return catalog
}
@@ -385,12 +404,18 @@ function writeCatalog(owner: string, catalog: Catalog) {
const tmp = catalogPath(owner) + '.tmp'
writeFileSync(tmp, JSON.stringify(catalog, null, 2))
renameSync(tmp, catalogPath(owner))
const epoch = (catalogEpoch.get(owner) || 0) + 1
catalogEpoch.set(owner, epoch)
// Floor at Date.now() so a stale older mtime cannot look "newer" than this write.
let mtimeMs = Date.now()
try { mtimeMs = statSync(catalogPath(owner)).mtimeMs } catch { /* ignore */ }
catalogCache.set(owner, { catalog, mtimeMs })
try {
const stamped = statSync(catalogPath(owner)).mtimeMs
if (stamped > mtimeMs) mtimeMs = stamped
} catch { /* keep Date.now() */ }
catalogCache.set(owner, { catalog, mtimeMs, epoch })
}
function invalidateCatalogCache(owner?: string) {
export function invalidateCatalogCache(owner?: string) {
if (owner) catalogCache.delete(owner)
else catalogCache.clear()
}
@@ -871,35 +896,77 @@ export function deleteFolder(owner: string, id: string) {
})
}
function sameFolder(folderId: string | undefined, target: string) {
return String(folderId || '') === String(target)
}
/** Remove every row for folderId. A second pass drops anything the first filter left. */
function emptyFolderRows(catalog: Catalog, folderId: string) {
const same = (item: { folderId?: string }) => sameFolder(item.folderId, folderId)
const strip = () => {
catalog.clips = (catalog.clips || []).filter(item => !same(item))
catalog.stills = (catalog.stills || []).filter(item => !same(item))
catalog.tracks = (catalog.tracks || []).filter(item => !same(item))
}
const left = () => [
...(catalog.clips || []).filter(same),
...(catalog.stills || []).filter(same),
...(catalog.tracks || []).filter(same)
]
strip()
let survivors = left()
if (!survivors.length) return
console.error('[library] wipe left folder rows', folderId, survivors.map(item => item.id))
const ids = new Set(survivors.map(item => item.id))
catalog.clips = (catalog.clips || []).filter(item => !ids.has(item.id))
catalog.stills = (catalog.stills || []).filter(item => !ids.has(item.id))
catalog.tracks = (catalog.tracks || []).filter(item => !ids.has(item.id))
survivors = left()
if (!survivors.length) return
console.error('[library] wipe still left folder rows', folderId, survivors.map(item => item.id))
strip()
}
/** Delete every still, clip, and track in a folder — catalog rows and on-disk files. Keeps the folder. */
export function wipeFolderContents(owner: string, folderId: string) {
return mutate(owner, (catalog) => {
const folder = catalog.folders.find(item => item.id === folderId)
if (!folder) throw createError({ statusCode: 404, statusMessage: 'Folder not found' })
const clips = catalog.clips.filter(clip => clip.folderId === folderId)
const stills = catalog.stills.filter(still => still.folderId === folderId)
const tracks = (catalog.tracks || []).filter(track => track.folderId === folderId)
const clips = catalog.clips.filter(clip => sameFolder(clip.folderId, folderId))
const stills = catalog.stills.filter(still => sameFolder(still.folderId, folderId))
const tracks = (catalog.tracks || []).filter(track => sameFolder(track.folderId, folderId))
const deletedIds = new Set([
...clips.map(item => item.id),
...stills.map(item => item.id),
...tracks.map(item => item.id)
])
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)
emptyFolderRows(catalog, folderId)
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)
const remain = [
...catalog.clips.filter(item => sameFolder(item.folderId, folderId)),
...catalog.stills.filter(item => sameFolder(item.folderId, folderId)),
...(catalog.tracks || []).filter(item => sameFolder(item.folderId, folderId))
]
if (remain.length) {
console.error('[library] wipe left folder rows', folderId, remain.map(item => item.id))
emptyFolderRows(catalog, folderId)
}
return {
folderId: folder.id,
folderName: folder.name,
deleted: clips.length + stills.length + tracks.length,
deletedIds: [...deletedIds],
stills: stills.length,
clips: clips.length,
tracks: tracks.length
}
}).then((result) => {
invalidateCatalogCache(owner)
return result
})
}
@@ -911,11 +978,13 @@ function detachDraftStills(catalog: Catalog, ids: Set<string>) {
})
}
/** Drop catalog stills whose master file is gone — a 204 thumb is not a still. */
/** Drop catalog stills whose master file is gone — a 204 thumb is not a still. Never adds a still. */
function pruneMissingStillMasters(owner: string, catalog: Catalog) {
const beforeIds = new Set(catalog.stills.map(still => still.id))
const keep: LibraryStill[] = []
const droppedIds = new Set<string>()
for (const still of catalog.stills) {
if (!beforeIds.has(still.id)) continue
let present = false
try {
present = existsSync(stillPath(owner, still.id))
@@ -932,15 +1001,20 @@ function pruneMissingStillMasters(owner: string, catalog: Catalog) {
droppedIds.add(still.id)
removeStillFiles(owner, still.id)
}
catalog.stills = keep.filter(still => beforeIds.has(still.id))
if (!droppedIds.size) return 0
catalog.stills = keep
detachDraftStills(catalog, droppedIds)
return droppedIds.size
}
function catalogWithPrunedStills(owner: string): Catalog {
const epoch = catalogEpoch.get(owner) || 0
const catalog = readCatalog(owner)
if (pruneMissingStillMasters(owner, catalog)) writeCatalog(owner, catalog)
const before = new Set(catalog.stills.map(still => still.id))
const dropped = pruneMissingStillMasters(owner, catalog)
catalog.stills = catalog.stills.filter(still => before.has(still.id))
if ((catalogEpoch.get(owner) || 0) !== epoch) return readCatalog(owner)
if (dropped) writeCatalog(owner, catalog)
return catalog
}
+46 -2
View File
@@ -7,14 +7,58 @@ export function newestOutput(jobs, seen, folderId) {
return jobs.filter(j=>j.request.folderId===folderId).flatMap(j=>j.outputs || []).filter(a=>!seen.has(a.id)).sort((a,b)=>(a.studio2?.savedAt || 0)-(b.studio2?.savedAt || 0)).at(-1) || null
}
export function reconcileSelection(selected, assets) {
if (!selected?.id) return assets.at(-1) || null
return assets.find(a => a.id === selected.id) || selected
const list = assets || []
if (!selected?.id) return list.at(-1) || null
return list.find(a => a.id === selected.id) || list.at(-1) || null
}
export function activeJobs(jobs) { return jobs.filter(j=>['waking','enhancing','submitting','rendering','saving'].includes(j.state)) }
export function previewHidden(asset, revealed, xaigen) {
if (!xaigen || !asset?.id) return false
return !revealed?.has?.(asset.id)
}
/** A reported imageCount of 0 is an empty folder. Do not replace it with a local list length. */
export function folderImageCount(folder, localStillCount = 0) {
if (folder && typeof folder.imageCount === 'number' && Number.isFinite(folder.imageCount)) return folder.imageCount
return Number(localStillCount) || 0
}
/** Replace library rows from a wipe response. Rows already in the wiped folder stay gone. */
export function libraryAfterWipe(previous, response, folderId) {
const suppressed = new Set(previous?.suppressedIds || [])
const target = String(folderId || '')
for (const list of [previous?.stills, previous?.clips, previous?.tracks, response?.stills, response?.clips, response?.tracks]) {
for (const item of list || []) {
if (item?.id && String(item.folderId || '') === target) suppressed.add(item.id)
}
}
const take = (list) => (Array.isArray(list) ? list : []).filter(item => item?.id && !suppressed.has(item.id))
return {
folders: Array.isArray(response?.folders) ? response.folders : (previous?.folders || []),
stills: take(response?.stills),
clips: take(response?.clips),
tracks: take(response?.tracks),
suppressedIds: [...suppressed]
}
}
/** Later pages and a stale full list must not put a suppressed id back. */
export function mergeLibraryRows(prev, next, suppressedIds) {
const drop = new Set(suppressedIds || [])
const map = new Map()
for (const item of prev || []) {
if (item?.id && !drop.has(item.id)) map.set(item.id, item)
}
for (const item of next || []) {
if (item?.id && !drop.has(item.id)) map.set(item.id, item)
}
return [...map.values()]
}
export function replaceLibraryRows(next, suppressedIds) {
const drop = new Set(suppressedIds || [])
return (next || []).filter(item => item?.id && !drop.has(item.id))
}
export function selectResult(state, asset) { return {...state,selected:asset} }
export function assetLabel(asset) {
if (!asset) return 'None'
+60 -2
View File
@@ -9,6 +9,8 @@ const names = [
'safeRm',
'removeStillFiles',
'detachDraftStills',
'sameFolder',
'emptyFolderRows',
'pruneMissingStillMasters',
'catalogWithPrunedStills',
'deleteStill',
@@ -24,6 +26,8 @@ const js = ts.transpileModule(functions, { compilerOptions: { target: ts.ScriptT
function harness() {
const files = new Set()
const thrown = new Set()
const invalidated = []
const catalogEpoch = new Map()
let writes = 0
let stored = null
function readCatalog() { return stored }
@@ -31,6 +35,7 @@ function harness() {
stored = catalog === undefined ? _owner : catalog
writes += 1
}
function invalidateCatalogCache(owner) { invalidated.push(owner) }
const api = new Function(
'rmSync',
'existsSync',
@@ -45,7 +50,9 @@ function harness() {
'mutate',
'readCatalog',
'writeCatalog',
`${js}; return { catalogWithPrunedStills, deleteStill, deleteStillFamily, wipeFolderContents };`
'catalogEpoch',
'invalidateCatalogCache',
`${js}; return { catalogWithPrunedStills, deleteStill, deleteStillFamily, wipeFolderContents, emptyFolderRows };`
)(
(path) => {
if ([...thrown].some(id => String(path).includes(id))) throw new Error('EPERM')
@@ -67,12 +74,15 @@ function harness() {
return result
},
readCatalog,
writeCatalog
writeCatalog,
catalogEpoch,
invalidateCatalogCache
)
return {
api,
files,
thrown,
invalidated,
get writes() { return writes },
set writes(value) { writes = value },
load(catalog) { stored = catalog }
@@ -132,4 +142,52 @@ test('wipeFolderContents still clears the folder when a file remove throws', asy
assert.equal(catalog.stills.length, 0)
assert.equal(catalog.clips.length, 0)
assert.equal(h.writes, 1)
assert.deepEqual(h.invalidated, ['owner'])
})
test('wipeFolderContents leaves zero rows for that folder and does not touch another folder', async () => {
const h = harness()
const catalog = {
stills: [
{ id: 'a', folderId: 'inbox' },
{ id: 'b', folderId: 'other' }
],
clips: [{ id: 'c', folderId: 'inbox' }],
tracks: [
{ id: 't', folderId: 'inbox' },
{ id: 'u', folderId: 'other' }
],
drafts: [],
folders: [{ id: 'inbox', name: 'Inbox' }, { id: 'other', name: 'Other' }]
}
h.load(catalog)
h.files.add('owner/stills/a')
h.files.add('owner/stills/b')
const result = await h.api.wipeFolderContents('owner', 'inbox')
assert.equal(result.deleted, 3)
assert.deepEqual(catalog.stills.map(item => item.id), ['b'])
assert.deepEqual(catalog.clips, [])
assert.deepEqual(catalog.tracks.map(item => item.id), ['u'])
assert.deepEqual(h.invalidated, ['owner'])
})
test('pruneMissingStillMasters only drops and a second read does not put the still back', async () => {
const h = harness()
const catalog = {
stills: [{ id: 'gone', folderId: 'inbox' }, { id: 'keep', folderId: 'inbox' }],
drafts: [],
clips: [],
tracks: [],
folders: [{ id: 'inbox' }]
}
h.load(catalog)
h.files.add('owner/stills/keep')
const before = new Set(catalog.stills.map(item => item.id))
const page = h.api.catalogWithPrunedStills('owner')
assert.deepEqual(page.stills.map(item => item.id), ['keep'])
for (const still of page.stills) assert.equal(before.has(still.id), true)
assert.ok(page.stills.length < before.size)
h.files.add('owner/stills/gone')
const again = h.api.catalogWithPrunedStills('owner')
assert.deepEqual(again.stills.map(item => item.id), ['keep'])
})
+39
View File
@@ -0,0 +1,39 @@
import test from 'node:test'
import assert from 'node:assert/strict'
import { folderImageCount, libraryAfterWipe, mergeLibraryRows, replaceLibraryRows } from '../shared/studio2/viewer.mjs'
test('folderImageCount trusts a server count of 0', () => {
assert.equal(folderImageCount({ id: 'inbox', imageCount: 0 }, 1762), 0)
assert.equal(folderImageCount({ id: 'inbox', imageCount: 4 }, 1), 4)
assert.equal(folderImageCount(undefined, 3), 3)
})
test('libraryAfterWipe replaces state and does not keep wiped folder rows from a stale list', () => {
const previous = {
folders: [{ id: 'inbox', imageCount: 2 }],
stills: [{ id: 'new-1', folderId: 'inbox' }, { id: 'new-2', folderId: 'inbox' }],
clips: [],
tracks: [],
suppressedIds: ['already-gone']
}
const stale = {
folders: [{ id: 'inbox', imageCount: 0 }, { id: 'other', imageCount: 1 }],
stills: [
{ id: 'ghost', folderId: 'inbox' },
{ id: 'new-1', folderId: 'inbox' },
{ id: 'kept', folderId: 'other' }
],
clips: [{ id: 'clip-ghost', folderId: 'inbox' }],
tracks: []
}
const next = libraryAfterWipe(previous, stale, 'inbox')
assert.deepEqual(next.stills.map(item => item.id), ['kept'])
assert.deepEqual(next.clips, [])
assert.equal(next.folders[0].imageCount, 0)
assert.equal(next.suppressedIds.includes('new-1'), true)
assert.equal(next.suppressedIds.includes('ghost'), true)
assert.equal(next.suppressedIds.includes('already-gone'), true)
const page = mergeLibraryRows(next.stills, stale.stills, next.suppressedIds)
assert.deepEqual(page.map(item => item.id), ['kept'])
assert.deepEqual(replaceLibraryRows(stale.stills, next.suppressedIds).map(item => item.id), ['kept'])
})