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>
This commit is contained in:
Towsty
2026-10-12 12:21:20 -05:00
co-authored by Cursor
parent 7dcac5444c
commit 1bab5152f6
7 changed files with 169 additions and 46 deletions
+18 -6
View File
@@ -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')
}
+67 -17
View File
@@ -1132,12 +1132,32 @@ function setPhotoStill(index:number,stillId:string){
if(!Number.isInteger(index)||!form.photos[index])return
if(!stillId){
form.photos.splice(index,1)
}else if(!stillById(stillId)){
// Never fill the card with an id that is not in library.stills
form.photos[index].stillId=''
}else{
form.photos[index].stillId=stillId
}
syncPhotosBindings()
saveBenchDraft(true)
}
function mergeUploadedStill(response:any,still:any){
const prev=library.value||{}
const fromServer=Array.isArray(response?.stills)?response.stills:[]
const others=fromServer.filter((s:any)=>s?.id&&s.id!==still.id)
const kept=(prev.stills||[]).filter((s:any)=>s?.id&&s.id!==still.id&&!others.some((x:any)=>x.id===s.id))
library.value={
...prev,
folders:response?.folders||prev.folders||[],
clips:response?.clips||prev.clips||[],
tracks:response?.tracks||prev.tracks||[],
drafts:response?.drafts||prev.drafts||[],
loraAliases:response?.loraAliases||prev.loraAliases||{},
loraTriggers:response?.loraTriggers||prev.loraTriggers||{},
keepPrompts:response?.keepPrompts||prev.keepPrompts,
stills:[{...still,role:still.role||'input'},...others,...kept]
}
}
function discardEmptyPhotoDraft(index:number){
if(!Number.isInteger(index)||!form.photos[index])return
if(!form.photos[index].stillId)form.photos.splice(index,1)
@@ -1524,21 +1544,33 @@ async function uploadPickerFile(event:Event){
const file=input.files?.[0]
if(!file)return
const key=picker.value
const photoIndex=key.startsWith('photo:')?Number(key.slice(6)):-1
uploading.value=true;uploadMessage.value='';error.value=''
const body=new FormData();body.append('image',file);body.append('folderId',form.folderId);body.append('hideInput',String(xaigen))
try{
const response=await $fetch<any>('/api/studio-2/stills',{method:'POST',body})
library.value=response
measured[response.still.id]={width:response.still.width,height:response.still.height}
if(key.startsWith('photo:')){
setPhotoStill(Number(key.slice(6)),response.still.id)
picker.value=''
pickerRevealAll.value=false
const still=response?.still
if(!still?.id) throw new Error('Could not save that image to the library.')
mergeUploadedStill(response,still)
measured[still.id]={width:still.width,height:still.height}
if(photoIndex>=0){
if(!stillById(still.id)){
discardEmptyPhotoDraft(photoIndex)
error.value='Could not keep that photo in the library.'
}else{
setPhotoStill(photoIndex,still.id)
picker.value=''
pickerRevealAll.value=false
uploadMessage.value=`Loaded ${still.name || file.name}.`
}
}else{
Object.assign(form,applyUploadedStill(form,response,'source'))
Object.assign(form,applyUploadedStill(form,{...response,still},'source'))
uploadMessage.value=`Loaded ${still.name || file.name}.`
}
uploadMessage.value=`Loaded ${response.still.name || file.name}.`
}catch(e:any){error.value=e.data?.statusMessage||e.message}
}catch(e:any){
if(photoIndex>=0) discardEmptyPhotoDraft(photoIndex)
error.value=e.data?.statusMessage||e.message||'Could not save image'
}
finally{uploading.value=false;input.value=''}
}
async function upload(event:Event,target:'source'|'hero'){
@@ -1547,22 +1579,28 @@ async function upload(event:Event,target:'source'|'hero'){
const body=new FormData();body.append('image',file);body.append('folderId',form.folderId);body.append('hideInput',String(xaigen))
try{
const response=await $fetch<any>('/api/studio-2/stills',{method:'POST',body})
library.value=response
measured[response.still.id]={width:response.still.width,height:response.still.height}
const still=response?.still
if(!still?.id) throw new Error('Could not save that image to the library.')
mergeUploadedStill(response,still)
measured[still.id]={width:still.width,height:still.height}
const plan=photosPlanState.value
if(plan.show && !plan.handoffReadonly){
if(!stillById(still.id)){
error.value='Could not keep that photo in the library.'
return
}
const role=target==='hero'
?(plan.roles.includes('person')?'person':plan.defaultRole)
:plan.defaultRole
if(form.photos.length>=plan.max)form.photos[form.photos.length-1]={stillId:response.still.id,role}
else form.photos.push({stillId:response.still.id,role:role||'change'})
if(form.photos.length>=plan.max)form.photos[form.photos.length-1]={stillId:still.id,role}
else form.photos.push({stillId:still.id,role:role||'change'})
syncPhotosBindings()
}else{
Object.assign(form,applyUploadedStill(form,response,target))
Object.assign(form,applyUploadedStill(form,{...response,still},target))
}
uploadMessage.value=`Loaded ${response.still.name || file.name}.`
uploadMessage.value=`Loaded ${still.name || file.name}.`
}
catch(e:any){error.value=e.data?.statusMessage||e.message}
catch(e:any){error.value=e.data?.statusMessage||e.message||'Could not save image'}
finally{uploading.value=false;input.value=''}
}
function loadRevealed(folderId:string){
@@ -1874,9 +1912,16 @@ async function loadLibraryOnce(){
const qs=new URLSearchParams({limit:'50'})
if(form.folderId) qs.set('folderId',form.folderId)
const page=await $fetch<any>(`/api/library?${qs.toString()}`)
const pageStills=page.stills||[]
const keepIds=new Set([
...(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))
const kept=(library.value.stills||[]).filter((s:any)=>keepIds.has(s.id)&&!pageStills.some((p:any)=>p.id===s.id))
library.value={
folders:page.folders||library.value.folders||[],
stills:page.stills||[],
stills:[...pageStills,...kept],
clips:page.clips||[],
tracks:page.tracks||[],
drafts:page.drafts||library.value.drafts||[],
@@ -1884,6 +1929,11 @@ async function loadLibraryOnce(){
loraTriggers:page.loraTriggers||library.value.loraTriggers||{},
keepPrompts:page.keepPrompts||library.value.keepPrompts
}
// Drop filled photo cards whose still left the library
for(let i=(form.photos||[]).length-1;i>=0;i-=1){
const id=form.photos[i]?.stillId
if(id && !stillById(id)) form.photos[i].stillId=''
}
}
async function fetchHealth(){
+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, or WebP' })
}
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 }
})
+17 -6
View File
@@ -21,12 +21,23 @@ export default defineEventHandler(async (event) => {
if (!video && request.engine !== 'qwen21')
assertImageV2LoraStack(request.settings.loraStack, request.engine);
assertFolderAccess(event, request.folderId);
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);
// Header-only size probe — never decode the archive PNG on Generate click
await resolveRequestSize(owner,request);
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);
// 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 ack = { id, seed:request.settings.seed, width:request.settings.width, height:request.settings.height };
+7 -3
View File
@@ -7,9 +7,13 @@ export default defineEventHandler(async event => {
const {owner}=assertLibraryOwner(event),folderId=field('folderId')
assertFolderAccess(event,folderId)
const size=imageDimensions(image.data)
if (!size) throw createError({statusCode:400,statusMessage:'Use a PNG, JPEG, WebP, GIF, or BMP image.'})
if (!size) throw createError({statusCode:400,statusMessage:'Use a PNG, JPEG, or WebP'})
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}
})
+35 -8
View File
@@ -1519,17 +1519,18 @@ function purgeStrayExtensionStills(owner: string, catalog: Catalog) {
const protectedIds = new Set((catalog.drafts || []).map(draft => draft.stillId).filter(Boolean) as string[])
const originalHashes = originalInputHashes(owner, catalog)
const extHashes = extensionFrameHashes(owner, catalog)
const lastHashes = allLastFrameHashes(owner, catalog)
const keep: LibraryStill[] = []
const drop: LibraryStill[] = []
for (const still of catalog.stills) {
const clipId = clipIdFromStillFilename(still.filename)
const namedLastFrame = lastFrameStillName(still.filename)
const namedExtClip = Boolean(clipId && catalog.clips.some(clip => clip.id.toLowerCase() === clipId))
const matchesPipelineFrame = Boolean(still.hash && (lastHashes.has(still.hash) || extHashes.has(still.hash)))
// Only drop real extension-frame bytes (or named handoff files) — never a root-clip last frame
// that a user re-uploaded as a normal source photo.
const matchesExtensionFrame = Boolean(still.hash && extHashes.has(still.hash))
const isOriginal = Boolean(still.hash && originalHashes.has(still.hash))
const dropThis = !protectedIds.has(still.id)
&& (namedLastFrame || namedExtClip || (matchesPipelineFrame && !isOriginal))
&& (namedLastFrame || namedExtClip || (matchesExtensionFrame && !isOriginal))
if (dropThis) drop.push(still)
else keep.push(still)
}
@@ -1586,8 +1587,15 @@ export async function saveStill(params: {
chainIndex?: number
settings?: StillGenerationSettings
}): Promise<LibraryStill | null> {
if (lastFrameStillName(params.filename)) return null
const role = params.role === 'output' ? 'output' : 'input'
// Pipeline outputs may still use last-frame filenames; only user input uploads are rejected here.
if (role === 'input' && lastFrameStillName(params.filename)) {
throw createError({
statusCode: 400,
statusMessage: 'Rejected as video handoff: filename matches last-frame. Choose a regular source image.'
})
}
if (role !== 'input' && lastFrameStillName(params.filename)) return null
const catalog = readCatalog(params.ownerKey)
const folder = catalog.folders.find(item => item.id === params.folderId) || catalog.folders[0]
if (!folder) throw createError({ statusCode: 400, statusMessage: 'No library folder available' })
@@ -1596,7 +1604,15 @@ export async function saveStill(params: {
|| (item.familyId === params.familyId && (item.chainIndex || 0) === (params.chainIndex || 0))
const existing = catalog.stills.find(item => item.folderId === folder.id && item.hash === hash && stillRole(item) === role && sameChain(item))
if (existing) {
if (lastFrameStillName(existing.filename) || isPipelineStill(catalog, existing)) return null
if (role === 'input' && (lastFrameStillName(existing.filename) || isPipelineStill(catalog, existing))) {
throw createError({
statusCode: 400,
statusMessage: lastFrameStillName(existing.filename)
? 'Rejected as video handoff: filename matches last-frame. Choose a regular source image.'
: 'Rejected as video handoff: matches an internal pipeline still. Choose a regular source image.'
})
}
if (role !== 'input' && (lastFrameStillName(existing.filename) || isPipelineStill(catalog, existing))) return null
const hideInput = typeof params.hideInput === 'boolean' ? params.hideInput === true : existing.hideInput
const name = typeof params.name === 'string' ? params.name.trim().slice(0, 80) : existing.name
const prompt = typeof params.prompt === 'string' ? params.prompt : existing.prompt
@@ -1629,8 +1645,12 @@ export async function saveStill(params: {
}
return existing
}
if (role === 'input' && (allLastFrameHashes(params.ownerKey, catalog).has(hash) || extensionFrameHashes(params.ownerKey, catalog).has(hash))) {
return null
// Only reject real extension-frame bytes — not every root-clip last-frame hash (false handoff).
if (role === 'input' && extensionFrameHashes(params.ownerKey, catalog).has(hash)) {
throw createError({
statusCode: 400,
statusMessage: 'Rejected as video handoff: bytes match an extension frame. Choose a regular source image.'
})
}
const still: LibraryStill = {
id: crypto.randomUUID(),
@@ -1702,10 +1722,17 @@ export async function rememberInputStill(params: {
const folder = catalog.folders.find(item => item.id === params.folderId) || catalog.folders[0]
if (!folder) throw createError({ statusCode: 400, statusMessage: 'No library folder available' })
const hash = bytesHash(params.data)
if (extensionFrameHashes(params.ownerKey, catalog).has(hash)) return null
const existing = catalog.stills.find(item => item.folderId === folder.id && item.hash === hash && !isPipelineStill(catalog, item))
if (existing) return existing
if (/^start\.(jpe?g|png|webp)$/i.test(String(params.filename || '').trim())) return null
return saveStill({ ...params, role: 'input' })
try {
return await saveStill({ ...params, role: 'input' })
} catch (error: any) {
// Soft-skip internal handoff frames for video remember paths; upload APIs throw instead.
if (error?.statusCode === 400 && /video handoff/i.test(String(error?.statusMessage || ''))) return null
throw error
}
}
export async function saveRetryDraft(params: {
+9 -3
View File
@@ -1,4 +1,4 @@
import { openSync, readSync, closeSync } from 'node:fs'
import { existsSync, openSync, readSync, closeSync } from 'node:fs'
import { execFile } from 'node:child_process'
import { promisify } from 'node:util'
import { getClip, getStill, clipVideoPath, stillPath } from '../library'
@@ -32,13 +32,19 @@ export async function resolveRequestSize(owner: string, request: any) {
const id = request.imageAId || request.identityStillId
if (id) {
const still = getStill(owner, id)
const path = stillPath(owner, id)
if (!existsSync(path)) {
throw createError({ statusCode: 404, statusMessage: 'That still is missing from the library' })
}
if (still.width && still.height) {
dimensions = { width: still.width, height: still.height }
} else {
// Header only — never read the full archive PNG into memory on Generate click
dimensions = imageDimensions(readImageHeader(stillPath(owner, id)))
dimensions = imageDimensions(readImageHeader(path))
}
if (!dimensions) {
throw createError({ statusCode: 400, statusMessage: 'Use a PNG, JPEG, or WebP' })
}
if (!dimensions) throw new Error('Cannot measure the source still.')
}
}
if (video && request.startClipId && !dimensions?.width) throw new Error('Cannot measure the previous clip.')