The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.
TypeScript agentai-chatai-studioall-in-onecoding-agentdesktop-appfluximage-generationlinuxllmlocal-ailocal-llmopen-sourceprivacyself-hostedstable-diffusionuncensoreduncensored-aivideo-generationwindows
fix(create): re-prime the shown price after a rejection, debounce the Workshop's quote key
purple888d3ac5e021
diff --git a/src/components/create/experimental/PresetWorkshop.tsx b/src/components/create/experimental/PresetWorkshop.tsxindex 093d1337..608d40be 100644--- a/src/components/create/experimental/PresetWorkshop.tsx+++ b/src/components/create/experimental/PresetWorkshop.tsx@@ -15,31 +15,27 @@ import { SchemaControl, baseFieldClass as fieldClass } from './SchemaControl'import { Select } from '../ui/Select'import { galleryLabelShort } from '../../../lib/render/gallery-label'import { errorText } from '../../../types/json-guards'+import { CloudJobError } from '../../../api/cloud/client'+import { useDebouncedValue } from '../../../hooks/useDebouncedValue'+import { PROMPT_DEBOUNCE_MS } from './useStudioPrice'const label = (s: string) => s.replaceAll('_', ' ').replace(/^./, (c) => c.toUpperCase())-// Review B4 (Runde 3, 20.09.2026): considered giving `priceKey` the same-// longer prompt-debounce as useStudioPrice.ts's fix (same shape: the LIVE-// prompt text in the key, a keystroke restarts the 650ms debounce). Left-// AS-IS here on purpose: B4's concrete measurement (48 studioQuote calls for-// a 48-char prompt at 600ms/char) was run against useStudioPrice.ts, the-// Composer's live meter, which is on-screen for every studio pick the whole-// time a customer is on the cloud Create tab; the Workshop's price effect-// only runs while its own dialog is open, on one step's prompt field at a-// time, a narrower window. More importantly the Workshop already carries no-// money risk either way: quote===null blocks Generate (see B3), so a 429-// here costs the customer a wait, never a booking. A prompt-debounce here-// would need reworking every real-timer waitFor() in this file's test-// coverage (~20 call sites, all under the current 650ms budget); if this-// ever gets measured hitting the same rate limit in practice, it is the-// same one-constant fix as useStudioPrice.ts's PROMPT_DEBOUNCE_MS.-export function PresetWorkshop({preset,onClose,onGenerate}:{preset:CreatePreset;onClose:()=>void;onGenerate:()=>void}) {const [index,setIndex]=useState(0),[prompt,setPrompt]=useState(''),[options,setOptions]=useState<Record<string,unknown>>({})const [paths,setPaths]=useState<Record<string,string|string[]>>({}),[completed,setCompleted]=useState<Record<number,CloudJob>>({})const [measurement,setMeasurement]=useState<{key:string;seconds:number}|null>(null)const [advanced,setAdvanced]=useState(false),[quoting,setQuoting]=useState(false),[quotedKey,setQuotedKey]=useState('')const [busy,setBusy]=useState(false),[error,setError]=useState(''),[quote,setQuote]=useState<number|null>(null),[active,setActive]=useState<string|null>(null)+ // Review B5 (Runde 4, 20.09.2026): true exactly while the MOST RECENT+ // quote attempt for the current priceKey came back 429 (rate limited, not+ // a version gap). While true, the last CONFIRMED quote/quotedKey (from+ // before the rate limit hit) stays usable for Generate even though it no+ // longer matches `priceKey` exactly, see the disabled-condition comments+ // below. Reset to false by any attempt that resolves with a real answer+ // (success, 409, or a genuine error) and by every place that already+ // clears `quote` for an unrelated reason (model switch, step change).+ const [rateLimited,setRateLimited]=useState(false)const lock=useRef(false),requestId=useRef<string|null>(null)const previewsRef=useRef<Record<string,{url:string;type:'image'|'video'}>>({})const carried=useRef<number|null>(null)@@ -101,7 +97,7 @@ export function PresetWorkshop({preset,onClose,onGenerate}:{preset:CreatePreset;const required=requiredRoleInputs(raw.role,step.model)function choose(id:string) {if(id===step.model)return- setPicked(p=>({...p,[index]:id}));setOptions({});setQuote(null);setQuotedKey('');setError('')+ setPicked(p=>({...p,[index]:id}));setOptions({});setQuote(null);setQuotedKey('');setError('');setRateLimited(false)// An upload the next model does not read would still price and submit as a// stray param. Only what it consumes survives the switch.const keep=new Set([...Object.values(roleInputs(raw.role,id)),'source_url'])@@ -155,21 +151,43 @@ export function PresetWorkshop({preset,onClose,onGenerate}:{preset:CreatePreset;const classicCost=(p:CloudJobParams)=>classicCredits(step.kind,step.model,step.op,p)const measurementKey=JSON.stringify([paths,options.order??'meanwhile'])const estimate=model?studioPreviewCredits(step.model,options,measurement?.key===measurementKey?measurement.seconds:undefined,Array.isArray(paths.image_paths)?paths.image_paths.length:1,Array.from(prompt).length):classicCost(params())- const priceKey=JSON.stringify([step.model,prompt,options,paths,index])+ // Review B5 (Runde 4, 20.09.2026): only the PROMPT gets the longer+ // debounce, same as useStudioPrice.ts's fix (model/options/paths/index+ // change rarely, a real edit, not per keystroke). While the customer is+ // still typing, `debouncedPrompt` (and therefore `priceKey`) does not+ // move at all, so the effect below never re-runs mid-sentence and the+ // last confirmed `quote` simply stays where it is, usable, the whole+ // time (Opus B: "den alten bestaetigten Preis stehen lassen, solange nur+ // der Prompt weitergewachsen ist"). Measured before this fix: 48+ // studioQuote calls for a 48-char prompt at an ordinary 600ms/char typing+ // rhythm, the same disease review-studio-B.md's B4 found in the Composer.+ const debouncedPrompt=useDebouncedValue(prompt,PROMPT_DEBOUNCE_MS)+ const priceKey=JSON.stringify([step.model,debouncedPrompt,options,paths,index])+ const schemaRequired=model?studioSchema(step.model).required??[]:[]+ const promptRequired=model?schemaRequired.includes(model.promptField??'prompt'):rolePrompts(raw.role)+ // Review B5 (Runde 4, 20.09.2026): checked against the LIVE prompt, not+ // `debouncedPrompt`. Clearing a required prompt makes the last confirmed+ // quote wrong for what would actually be submitted, and that is a+ // correctness gap, not the keystroke-chatter the debounce above exists to+ // fix, so it must not wait 1800ms to take effect (preset-workshop.test.tsx,+ // "invalidates the prior quote when the prompt is cleared").+ const nothingToPrice=required.some(key=>!paths[key])||(!model&&raw.role==='extend'&&!paths.source_url)||(promptRequired&&!prompt.trim())useEffect(()=>{- setQuote(null);setQuotedKey('');setQuoting(false)const controller=new AbortController()- const schemaRequired=model?studioSchema(step.model).required??[]:[]- if(required.some(key=>!paths[key]))return- if(!model&&raw.role==='extend'&&!paths.source_url)return- if((model?schemaRequired.includes(model.promptField??'prompt'):rolePrompts(raw.role))&&!prompt.trim())return+ // Genuinely nothing to price yet (no upload, no required prompt): the+ // ONLY case that still clears the last quote outright, there is no+ // number to fall back to either.+ if(required.some(key=>!paths[key])||(!model&&raw.role==='extend'&&!paths.source_url)||(promptRequired&&!debouncedPrompt.trim())){+ setQuote(null);setQuotedKey('');setQuoting(false);setRateLimited(false)+ return+ }setQuoting(true)const timer=setTimeout(async()=>{try {let cost:numberif(model){- studioOptions(step.model,prompt,options)- const data=await studioQuote(step.model,prompt,{op:'studio',studio_options:options,...paths})+ studioOptions(step.model,debouncedPrompt,options)+ const data=await studioQuote(step.model,debouncedPrompt,{op:'studio',studio_options:options,...paths})if(!Number.isSafeInteger(data.credits)||data.credits<1)throw new Error('Invalid price response')cost=data.creditsif(!controller.signal.aborted&&Number.isFinite(data.seconds))setMeasurement({key:measurementKey,seconds:data.seconds as number})@@ -181,7 +199,7 @@ export function PresetWorkshop({preset,onClose,onGenerate}:{preset:CreatePreset;if(classic===null)throw new Error('No price is available for this model yet.')cost=classic}- if(!controller.signal.aborted){setQuote(cost);setQuotedKey(priceKey);requestId.current=crypto.randomUUID();setError('')}+ if(!controller.signal.aborted){setQuote(cost);setQuotedKey(priceKey);requestId.current=crypto.randomUUID();setError('');setRateLimited(false)}}catch(e){if(controller.signal.aborted)return// 409 quote_changed: den neuen, vom Anbieter bestaetigten Preis@@ -191,8 +209,20 @@ export function PresetWorkshop({preset,onClose,onGenerate}:{preset:CreatePreset;if(e instanceof StudioQuoteChangedError){setQuote(e.credits);setQuotedKey(priceKey);requestId.current=crypto.randomUUID()if(Number.isFinite(e.seconds))setMeasurement({key:measurementKey,seconds:e.seconds as number})- setError('The price changed. Review the new price before starting.')- } else setError(errorText(e))+ setError('The price changed. Review the new price before starting.');setRateLimited(false)+ } else if(e instanceof CloudJobError&&e.status===429){+ // Review B5: a 429 here is the rate limit, not a version gap and+ // not a sign the last confirmed price is wrong. Leave `quote`/+ // `quotedKey` exactly as they were (the last good number, if any)+ // and mark `rateLimited` so Generate still accepts them even+ // though `quotedKey` no longer matches this newer `priceKey`; no+ // blocking alert, same silent-fallback shape as useStudioPrice.ts.+ setRateLimited(true);setError('')+ } else {+ // A real error (invalid options, no catalog price, ...): the+ // shown number, if any, is genuinely no longer trustworthy.+ setQuote(null);setQuotedKey('');setRateLimited(false);setError(errorText(e))+ }}finally{if(!controller.signal.aborted)setQuoting(false)}},650)@@ -200,8 +230,13 @@ export function PresetWorkshop({preset,onClose,onGenerate}:{preset:CreatePreset;// The key contains every input affecting the quote.// eslint-disable-next-line react-hooks/exhaustive-deps},[priceKey])+ // Review B5: usable when there is genuinely something to price, and it is+ // fresh for the CURRENT key, or the only thing between here and a fresh+ // confirmation is a rate limit (the last confirmed number stands in, see+ // the effect's 429 branch above).+ const priceUsable=!nothingToPrice&"e!==null&&(quotedKey===priceKey||rateLimited)async function generate() {- if(lock.current||quote===null||quotedKey!==priceKey||useCreateStore.getState().isGenerating)return+ if(lock.current||!priceUsable||useCreateStore.getState().isGenerating)returnlock.current=true;setBusy(true);setError('')const store=useCreateStore.getState()store.setIntent(raw.role==='extend'?'extend':raw.role==='animate'?'animate':raw.role==='motion'?'motion':raw.role==='talking'||raw.role==='duo'?'lipsync':raw.role==='edit'?'edit':step.kind==='audio'?'music':step.kind==='video'?'video':'image')@@ -217,28 +252,28 @@ export function PresetWorkshop({preset,onClose,onGenerate}:{preset:CreatePreset;if(job.status!=='succeeded')throw new Error(job.error??`Generation ${job.status}. Completed earlier steps remain in your gallery.`)// Prompt und Titel stehen hier im Browser; der Auftrag vom Server// bringt sie erst beim naechsten Laden mit.- store.addToGallery({...galleryItemFromJob(job),prompt,label:runLabel});setCompleted(c=>({...c,[index]:job}));setQuote(null)+ store.addToGallery({...galleryItemFromJob(job),prompt,label:runLabel});setCompleted(c=>({...c,[index]:job}));setQuote(null);setRateLimited(false)}catch(e){if(e instanceof QuoteChangedError){// Der Server hat beim Buchen neu gerechnet und eine hoehere Zahl// gefunden als die bestaetigte. Zeigen statt buchen: derselbe// Grundsatz wie beim 409 der Preisabfrage oben, nur an der anderen// Stelle des Ablaufs (Portplan Abschnitt 4 Punkt 3).- setQuote(e.credits);setQuotedKey(priceKey);requestId.current=crypto.randomUUID()+ setQuote(e.credits);setQuotedKey(priceKey);requestId.current=crypto.randomUUID();setRateLimited(false)setError(`The price changed to ${e.credits.toLocaleString('en-US')} credits. Review it and start again.`)} else {setError(errorText(e));store.setError(errorText(e))}}finally{setActive(null);store.setIsGenerating(false);setBusy(false);lock.current=false;void refreshQuota()}}- function next(){setIndex(index+1);setPrompt('');setOptions({});setPaths({});dropPreviews();setError('');setQuote(null);setQuotedKey('')}+ function next(){setIndex(index+1);setPrompt('');setOptions({});setPaths({});dropPreviews();setError('');setQuote(null);setQuotedKey('');setRateLimited(false)}/** Drop this step's result and stand where it was made, prompt and uploads* still there. A second run of the same step is one word away, not a* reopened preset that silently resumes on a finished picture. */- function redo(){setCompleted(c=>{const n={...c};delete n[index];return n});setError('');setQuote(null);setQuotedKey('')}+ function redo(){setCompleted(c=>{const n={...c};delete n[index];return n});setError('');setQuote(null);setQuotedKey('');setRateLimited(false)}/** Back to an empty first step. Nothing carried over, model choice included.* Everything already generated stays in the gallery. */- function startOver(){carried.current=null;setIndex(0);setPrompt('');setOptions({});setPaths({});dropPreviews();setCompleted({});setPicked({});setMeasurement(null);setError('');setQuote(null);setQuotedKey('');setAdvanced(false)}+ function startOver(){carried.current=null;setIndex(0);setPrompt('');setOptions({});setPaths({});dropPreviews();setCompleted({});setPicked({});setMeasurement(null);setError('');setQuote(null);setQuotedKey('');setAdvanced(false);setRateLimited(false)}const touched=index>0||Object.keys(completed).length>0||!!prompt||Object.keys(paths).length>0const ideas=promptIdeas(raw.role,preset.category)const runtime=runtimes[step.model]@@ -305,7 +340,7 @@ export function PresetWorkshop({preset,onClose,onGenerate}:{preset:CreatePreset;:<span className="truncate rounded-md border border-white/5 px-2 py-1 t-micro text-gray-500">{choice.label} <span className="ml-2 text-gray-700">Cloud</span></span>}{ideas.length>0&&!result&&<Select size="sm" ariaLabel="Prompt ideas" className="max-w-[160px]" placeholder="+ Prompt idea" value="" onChange={v=>{const idea=ideas.find(i=>i.label===v);if(idea)setPrompt(t=>t.trim()?`${t.trim()}, ${idea.text}`:idea.text)}} options={ideas.map(i=>({value:i.label,label:i.label}))}/>}</div>- <div className="flex items-center gap-3">{active&&<button onClick={()=>void cancelJob(active).catch(e=>setError(e.message))} className="t-micro text-gray-500">Cancel</button>}{busy&&<Loader2 size={12} className="animate-spin text-gray-500"/>}{result ? <><button onClick={redo} disabled={busy} className="flex h-8 items-center gap-1.5 rounded-lg border border-white/10 px-3 t-control text-gray-300 hover:bg-white/5 disabled:opacity-40"><RotateCcw size={11}/>Try again</button>{index<preset.steps.length-1?<button onClick={next} className="flex h-8 items-center gap-2 rounded-lg bg-white/90 px-3 t-control font-medium text-black">Next step<ChevronRight size={12}/></button>:<button onClick={onClose} className="h-8 rounded-lg bg-white/90 px-3 t-control font-medium text-black">Done</button>}</>:<><span aria-live="polite" className="t-control text-gray-400">{quote!==null&"edKey===priceKey?`${quote.toLocaleString('en-US')} credits`:estimate!==null?`≈ ${estimate.toLocaleString('en-US')} credits`:'Upload media to calculate price'}{quoting&&<span className="ml-2 text-gray-500">Checking…</span>}{runtime&&!active&&<span className="ml-2 text-gray-500">· {humanRuntime(runtime.seconds)}</span>}</span><button disabled={busy||quoting||quote===null||quotedKey!==priceKey} onClick={()=>void generate()} className="flex h-8 items-center gap-2 rounded-lg bg-lu-accent px-4 t-control font-medium text-gray-950 hover:bg-lu-accent-hover disabled:opacity-40">Generate<ArrowUp size={12}/></button></>}</div>+ <div className="flex items-center gap-3">{active&&<button onClick={()=>void cancelJob(active).catch(e=>setError(e.message))} className="t-micro text-gray-500">Cancel</button>}{busy&&<Loader2 size={12} className="animate-spin text-gray-500"/>}{result ? <><button onClick={redo} disabled={busy} className="flex h-8 items-center gap-1.5 rounded-lg border border-white/10 px-3 t-control text-gray-300 hover:bg-white/5 disabled:opacity-40"><RotateCcw size={11}/>Try again</button>{index<preset.steps.length-1?<button onClick={next} className="flex h-8 items-center gap-2 rounded-lg bg-white/90 px-3 t-control font-medium text-black">Next step<ChevronRight size={12}/></button>:<button onClick={onClose} className="h-8 rounded-lg bg-white/90 px-3 t-control font-medium text-black">Done</button>}</>:<><span aria-live="polite" className="t-control text-gray-400">{priceUsable&"e!==null?`${quote.toLocaleString('en-US')} credits`:estimate!==null?`≈ ${estimate.toLocaleString('en-US')} credits`:'Upload media to calculate price'}{quoting&&<span className="ml-2 text-gray-500">Checking…</span>}{runtime&&!active&&<span className="ml-2 text-gray-500">· {humanRuntime(runtime.seconds)}</span>}</span><button disabled={busy||quoting||!priceUsable} onClick={()=>void generate()} className="flex h-8 items-center gap-2 rounded-lg bg-lu-accent px-4 t-control font-medium text-gray-950 hover:bg-lu-accent-hover disabled:opacity-40">Generate<ArrowUp size={12}/></button></>}</div></div></div>{modelHint(step.model)&&!result&&<p className="mt-1.5 text-center t-micro leading-4 text-gray-500">{modelHint(step.model)}</p>}diff --git a/src/components/create/experimental/__tests__/preset-workshop.test.tsx b/src/components/create/experimental/__tests__/preset-workshop.test.tsxindex 9a717e94..9dd9349c 100644--- a/src/components/create/experimental/__tests__/preset-workshop.test.tsx+++ b/src/components/create/experimental/__tests__/preset-workshop.test.tsx@@ -1,7 +1,7 @@// @vitest-environment jsdomimport { afterEach, beforeEach, expect, it } from 'vitest'import { useState } from 'react'-import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'import { PresetWorkshop } from '../PresetWorkshop'import { PresetShelf } from '../PresetShelf'import { Modal } from '../../../ui/Modal'@@ -109,14 +109,68 @@ beforeEach(() => {credits: studioPreviewCredits(model, params.studio_options ?? {}, undefined, 1, prompt.length),}))})-afterEach(() => { cleanup(); useCloudCatalogStore.setState({ models: CLOUD_MODEL_SEED }) })+afterEach(() => { cleanup(); vi.useRealTimers(); useCloudCatalogStore.setState({ models: CLOUD_MODEL_SEED }) })++// Review B5 (Runde 4, 20.09.2026): PresetWorkshop fired one studioQuote()+// call per keystroke (48 of 48 for a 48-character prompt), the same disease+// B4 (Runde 3) found and fixed in the Composer's useStudioPrice.ts, reusing+// its debounce helper (useDebouncedValue.ts). Mirrors+// use-studio-price-rate-limit.test.ts's shape, on the actual component+// instead of the hook.+it('48 keystrokes at a 600 ms pace debounce down to at most TWO quote calls (Review B5)', async () => {+ vi.useFakeTimers()+ render(<PresetWorkshop preset={CREATE_PRESETS[1]} onClose={() => {}} onGenerate={() => {}} />)+ const field = screen.getByLabelText('Preset prompt')+ const text = 'a slow typist writes one letter at a time, thinking'.slice(0, 48)+ expect(text).toHaveLength(48)+ let typed = ''+ for (const ch of text) {+ typed += ch+ fireEvent.change(field, { target: { value: typed } })+ await act(async () => { await vi.advanceTimersByTimeAsync(600) })+ }+ // The customer stops: 1800ms settles the prompt debounce, then the+ // effect's own 650ms network debounce fires the (at most) second call.+ await act(async () => { await vi.advanceTimersByTimeAsync(1800) })+ await act(async () => { await vi.advanceTimersByTimeAsync(650) })+ expect(mocks.quote.mock.calls.length).toBeLessThanOrEqual(2)+})++// Review B5: a 429 on the LIVE quote (rate limit, not a version gap) must+// not lock Generate. The last CONFIRMED price stays usable and bookable+// while the rate limit stands; a 404/CORS version gap still blocks, that+// case is covered separately above ("Start bleibt gesperrt...").+it('a 429 on the live quote leaves Generate usable with the last confirmed price (Review B5)', async () => {+ vi.useFakeTimers()+ mocks.quote.mockResolvedValueOnce({ credits: 1500 })+ render(<PresetWorkshop preset={CREATE_PRESETS[1]} onClose={() => {}} onGenerate={() => {}} />)+ fireEvent.change(screen.getByLabelText('Preset prompt'), { target: { value: 'a misty forest creature' } })+ await act(async () => { await vi.advanceTimersByTimeAsync(1800) })+ await act(async () => { await vi.advanceTimersByTimeAsync(650) })+ expect(screen.getAllByText(/1,500 credits/).length).toBeGreaterThan(0)+ expect((screen.getByRole('button', { name: 'Generate' }) as HTMLButtonElement).disabled).toBe(false)++ mocks.quote.mockRejectedValueOnce(new CloudJobError('Please wait before requesting another quote', 429))+ fireEvent.change(screen.getByLabelText('Preset prompt'), { target: { value: 'a misty forest creature, closer up' } })+ await act(async () => { await vi.advanceTimersByTimeAsync(1800) })+ await act(async () => { await vi.advanceTimersByTimeAsync(650) })+ // Still the old, confirmed number, still bookable: no alert, no lock.+ expect(screen.getAllByText(/1,500 credits/).length).toBeGreaterThan(0)+ expect(screen.queryByRole('alert')).toBeNull()+ expect((screen.getByRole('button', { name: 'Generate' }) as HTMLButtonElement).disabled).toBe(false)++ fireEvent.click(screen.getByRole('button', { name: 'Generate' }))+ await act(async () => { await Promise.resolve() })+ expect(mocks.submit).toHaveBeenCalledTimes(1)+ expect(mocks.submit.mock.calls[0][0]).toMatchObject({ params: { max_credits: 1500 } })+})it('prices automatically and starts the category with one Generate click', async () => {const onGenerate = vi.fn()render(<PresetWorkshop preset={CREATE_PRESETS[1]} onClose={() => {}} onGenerate={onGenerate} />)expect(screen.queryByText('Review price')).toBeNull()fireEvent.change(screen.getByLabelText('Preset prompt'), { target: { value: 'A misty forest creature' } })- await waitFor(() => expect((screen.getByRole('button', { name: 'Generate' }) as HTMLButtonElement).disabled).toBe(false), { timeout: 2000 })+ await waitFor(() => expect((screen.getByRole('button', { name: 'Generate' }) as HTMLButtonElement).disabled).toBe(false), { timeout: 3000 })expect(screen.getAllByText(/1,500 credits/).length).toBeGreaterThan(0)fireEvent.click(screen.getByRole('button', { name: 'Generate' }))await waitFor(() => expect(mocks.submit).toHaveBeenCalledTimes(1))@@ -128,7 +182,7 @@ it('prices automatically and starts the category with one Generate click', asyncit('invalidates the prior quote when the prompt is cleared', async () => {render(<PresetWorkshop preset={CREATE_PRESETS[0]} onClose={() => {}} onGenerate={() => {}} />)fireEvent.change(screen.getByLabelText('Preset prompt'), { target: { value: 'A character portrait' } })- await waitFor(() => expect((screen.getByRole('button', { name: 'Generate' }) as HTMLButtonElement).disabled).toBe(false), { timeout: 2000 })+ await waitFor(() => expect((screen.getByRole('button', { name: 'Generate' }) as HTMLButtonElement).disabled).toBe(false), { timeout: 3000 })fireEvent.change(screen.getByLabelText('Preset prompt'), { target: { value: '' } })expect((screen.getByRole('button', { name: 'Generate' }) as HTMLButtonElement).disabled).toBe(true)})@@ -196,7 +250,7 @@ it('re-quotes the server price when the duration changes, and books the new one'render(<PresetWorkshop preset={{ id: 'wan-3.0', title: m.label, summary: '', category: 'Video', adult: false, accent: '', steps: [{ model: 'wan-3.0', kind: 'video', op: 'studio', title: m.label, role: 'animate' }] }} onClose={() => {}} onGenerate={() => {}} />)fireEvent.change(screen.getByLabelText('Preset prompt'), { target: { value: 'A slow pan across the valley' } })fireEvent.change(screen.getByLabelText('Add image'), { target: { files: [new File(['x'], 'a.png', { type: 'image/png' })] } })- await waitFor(() => expect(screen.getByText('25,000 credits')).toBeTruthy(), { timeout: 2000 })+ await waitFor(() => expect(screen.getByText('25,000 credits')).toBeTruthy(), { timeout: 3000 })expect((screen.getByRole('button', { name: 'Generate' }) as HTMLButtonElement).disabled).toBe(false)fireEvent.change(screen.getByLabelText('Duration'), { target: { value: '10' } })@@ -205,7 +259,7 @@ it('re-quotes the server price when the duration changes, and books the new one'expect(screen.queryByText('25,000 credits')).toBeNull()expect((screen.getByRole('button', { name: 'Generate' }) as HTMLButtonElement).disabled).toBe(true)- await waitFor(() => expect(screen.getByText('50,000 credits')).toBeTruthy(), { timeout: 2000 })+ await waitFor(() => expect(screen.getByText('50,000 credits')).toBeTruthy(), { timeout: 3000 })fireEvent.click(screen.getByRole('button', { name: 'Generate' }))await waitFor(() => expect(mocks.submit).toHaveBeenCalledTimes(1))expect(mocks.submit.mock.calls[0][0]).toMatchObject({ model: 'wan-3.0', params: { max_credits: 50000, studio_options: { duration: 10 } } })@@ -243,12 +297,12 @@ it('laesst den Kunden das Modell des Schrittes wechseln und bucht das gewechseltexpect(namen.filter((n) => n === 'Chroma Spicy')).toHaveLength(1)fireEvent.change(screen.getByLabelText('Preset prompt'), { target: { value: 'a portrait in warm light' } })- await waitFor(() => expect((screen.getByRole('button', { name: 'Generate' }) as HTMLButtonElement).disabled).toBe(false), { timeout: 2000 })+ await waitFor(() => expect((screen.getByRole('button', { name: 'Generate' }) as HTMLButtonElement).disabled).toBe(false), { timeout: 3000 })const anbieterfragenVorher = mocks.quote.mock.calls.lengthwaehlen('Model', 'Flux Schnell (fast)')expect((screen.getByRole('button', { name: 'Generate' }) as HTMLButtonElement).disabled).toBe(true)- await waitFor(() => expect(screen.getByText('300 credits')).toBeTruthy(), { timeout: 2000 })+ await waitFor(() => expect(screen.getByText('300 credits')).toBeTruthy(), { timeout: 3000 })fireEvent.click(screen.getByRole('button', { name: 'Generate' }))await waitFor(() => expect(mocks.submit).toHaveBeenCalledTimes(1))expect(mocks.submit.mock.calls[0][0]).toMatchObject({ model: 'flux-schnell', kind: 'image', params: { op: 'generate', max_credits: 300, width: 1024, height: 1024 } })@@ -262,9 +316,9 @@ it('schickt beim klassischen Clip Frames und Fps und nicht duration', async () =waehlen('Model', 'Wan 2.2 720p')fireEvent.change(screen.getByLabelText('Preset prompt'), { target: { value: 'a slow pan across the valley' } })fireEvent.change(screen.getByLabelText('Add image'), { target: { files: [new File(['x'], 'a.png', { type: 'image/png' })] } })- await waitFor(() => expect((screen.getByRole('button', { name: 'Generate' }) as HTMLButtonElement).disabled).toBe(false), { timeout: 2000 })+ await waitFor(() => expect((screen.getByRole('button', { name: 'Generate' }) as HTMLButtonElement).disabled).toBe(false), { timeout: 3000 })fireEvent.change(screen.getByLabelText('Duration'), { target: { value: '8' } })- await waitFor(() => expect((screen.getByRole('button', { name: 'Generate' }) as HTMLButtonElement).disabled).toBe(false), { timeout: 2000 })+ await waitFor(() => expect((screen.getByRole('button', { name: 'Generate' }) as HTMLButtonElement).disabled).toBe(false), { timeout: 3000 })fireEvent.click(screen.getByRole('button', { name: 'Generate' }))await waitFor(() => expect(mocks.submit).toHaveBeenCalledTimes(1))const sent = mocks.submit.mock.calls[0][0]@@ -279,9 +333,9 @@ it('wirft das Ergebnis eines Schrittes auf Wunsch weg und faengt ganz von vorn amocks.poll.mockResolvedValue({ id: 'test-job', status: 'succeeded', kind: 'image', result_url: 'https://example.test/a.png', model: 'preset-chroma', prompt: 'a' })render(<PresetWorkshop preset={CREATE_PRESETS[1]} onClose={() => {}} onGenerate={() => {}} />)fireEvent.change(screen.getByLabelText('Preset prompt'), { target: { value: 'a misty forest creature' } })- await waitFor(() => expect((screen.getByRole('button', { name: 'Generate' }) as HTMLButtonElement).disabled).toBe(false), { timeout: 2000 })+ await waitFor(() => expect((screen.getByRole('button', { name: 'Generate' }) as HTMLButtonElement).disabled).toBe(false), { timeout: 3000 })fireEvent.click(screen.getByRole('button', { name: 'Generate' }))- await waitFor(() => expect(screen.getByAltText('Generated result')).toBeTruthy(), { timeout: 2000 })+ await waitFor(() => expect(screen.getByAltText('Generated result')).toBeTruthy(), { timeout: 3000 })// Nochmal: dasselbe Ergebnis weg, Prompt und Eingaben bleiben stehen.fireEvent.click(screen.getByRole('button', { name: /Try again/ }))@@ -311,9 +365,9 @@ it('bleibt waehrend der Generation offen und meldet den Start nur', async () =>mocks.poll.mockImplementation(async () => { await new Promise((r) => setTimeout(r, 80)); return { id: 'test-job', status: 'succeeded', kind: 'image', result_url: 'https://example.test/a.png', model: 'preset-chroma', prompt: 'a' } })render(<PresetWorkshop preset={CREATE_PRESETS[1]} onClose={() => { offen = false }} onGenerate={() => {}} />)fireEvent.change(screen.getByLabelText('Preset prompt'), { target: { value: 'a misty forest creature' } })- await waitFor(() => expect((screen.getByRole('button', { name: 'Generate' }) as HTMLButtonElement).disabled).toBe(false), { timeout: 2000 })+ await waitFor(() => expect((screen.getByRole('button', { name: 'Generate' }) as HTMLButtonElement).disabled).toBe(false), { timeout: 3000 })fireEvent.click(screen.getByRole('button', { name: 'Generate' }))- await waitFor(() => expect(screen.getByAltText('Generated result')).toBeTruthy(), { timeout: 2000 })+ await waitFor(() => expect(screen.getByAltText('Generated result')).toBeTruthy(), { timeout: 3000 })expect(offen).toBe(true)})@@ -341,7 +395,7 @@ it('zeigt das hochgeladene Bild im Viewer statt der Preset-Illustration', asyncrender(<PresetWorkshop preset={CREATE_PRESETS[4]} onClose={() => {}} onGenerate={() => {}} />)expect(screen.getByAltText('Preset inspiration')).toBeTruthy()fireEvent.change(screen.getByLabelText('Add image'), { target: { files: [new File(['x'], 'a.png', { type: 'image/png' })] } })- await waitFor(() => expect(screen.getByAltText('Your input')).toBeTruthy(), { timeout: 2000 })+ await waitFor(() => expect(screen.getByAltText('Your input')).toBeTruthy(), { timeout: 3000 })expect(screen.queryByAltText('Preset inspiration')).toBeNull()expect((screen.getByAltText('Your input') as HTMLImageElement).src).toBe('blob:test-0')@@ -365,12 +419,12 @@ it('traegt das Ergebnis eines Schrittes von selbst in die Eingabe des naechsten'}))render(<PresetWorkshop preset={CREATE_PRESETS[6]} onClose={() => {}} onGenerate={() => {}} />)fireEvent.change(screen.getByLabelText('Preset prompt'), { target: { value: 'hello there' } })- await waitFor(() => expect((screen.getByRole('button', { name: 'Generate' }) as HTMLButtonElement).disabled).toBe(false), { timeout: 2000 })+ await waitFor(() => expect((screen.getByRole('button', { name: 'Generate' }) as HTMLButtonElement).disabled).toBe(false), { timeout: 3000 })fireEvent.click(screen.getByRole('button', { name: 'Generate' }))- await waitFor(() => expect(screen.getByRole('button', { name: /Next step/ })).toBeTruthy(), { timeout: 2000 })+ await waitFor(() => expect(screen.getByRole('button', { name: /Next step/ })).toBeTruthy(), { timeout: 3000 })fireEvent.click(screen.getByRole('button', { name: /Next step/ }))// Schritt 2 laedt die Stimme selbst hoch und meldet die Eingabe als gesetzt.- await waitFor(() => expect(screen.getByText(/Replace audio/)).toBeTruthy(), { timeout: 2000 })+ await waitFor(() => expect(screen.getByText(/Replace audio/)).toBeTruthy(), { timeout: 3000 })expect(mocks.upload).toHaveBeenCalledTimes(1)expect(mocks.upload.mock.calls[0][1]).toBe('audio')})@@ -387,11 +441,11 @@ it('traegt auch ein Bild von selbst in den naechsten Schritt', async () => {render(<PresetWorkshop preset={CREATE_PRESETS[1]} onClose={() => {}} onGenerate={() => {}} />)expect(CREATE_PRESETS[1].steps[1].model).toBe('open-video')fireEvent.change(screen.getByLabelText('Preset prompt'), { target: { value: 'a tall pale creature' } })- await waitFor(() => expect((screen.getByRole('button', { name: 'Generate' }) as HTMLButtonElement).disabled).toBe(false), { timeout: 2000 })+ await waitFor(() => expect((screen.getByRole('button', { name: 'Generate' }) as HTMLButtonElement).disabled).toBe(false), { timeout: 3000 })fireEvent.click(screen.getByRole('button', { name: 'Generate' }))- await waitFor(() => expect(screen.getByRole('button', { name: /Next step/ })).toBeTruthy(), { timeout: 2000 })+ await waitFor(() => expect(screen.getByRole('button', { name: /Next step/ })).toBeTruthy(), { timeout: 3000 })fireEvent.click(screen.getByRole('button', { name: /Next step/ }))- await waitFor(() => expect(screen.getByText(/Replace image/)).toBeTruthy(), { timeout: 2000 })+ await waitFor(() => expect(screen.getByText(/Replace image/)).toBeTruthy(), { timeout: 3000 })expect(mocks.upload).toHaveBeenCalledTimes(1)expect(mocks.upload.mock.calls[0][1]).toBe('source')await waitFor(() => expect(screen.getByAltText('Your input')).toBeTruthy())@@ -406,11 +460,11 @@ it('zeigt keinen Knopf fuer das vorige Ergebnis und haelt Optionales aus dem Weg}))render(<PresetWorkshop preset={CREATE_PRESETS[1]} onClose={() => {}} onGenerate={() => {}} />)fireEvent.change(screen.getByLabelText('Preset prompt'), { target: { value: 'a tall pale creature' } })- await waitFor(() => expect((screen.getByRole('button', { name: 'Generate' }) as HTMLButtonElement).disabled).toBe(false), { timeout: 2000 })+ await waitFor(() => expect((screen.getByRole('button', { name: 'Generate' }) as HTMLButtonElement).disabled).toBe(false), { timeout: 3000 })fireEvent.click(screen.getByRole('button', { name: 'Generate' }))- await waitFor(() => expect(screen.getByRole('button', { name: /Next step/ })).toBeTruthy(), { timeout: 2000 })+ await waitFor(() => expect(screen.getByRole('button', { name: /Next step/ })).toBeTruthy(), { timeout: 3000 })fireEvent.click(screen.getByRole('button', { name: /Next step/ }))- await waitFor(() => expect(screen.getByText(/Replace image/)).toBeTruthy(), { timeout: 2000 })+ await waitFor(() => expect(screen.getByText(/Replace image/)).toBeTruthy(), { timeout: 3000 })expect(screen.queryByRole('button', { name: 'Use previous result' })).toBeNull()expect(screen.getByText(/Replace image/)).toBeTruthy()expect(screen.getByRole('button', { name: 'Remove input' })).toBeTruthy()@@ -434,7 +488,7 @@ it('Start bleibt gesperrt und zeigt den festen Text, wenn der Server das Studiomocks.quote.mockRejectedValue(new CloudJobError('This feature needs a newer LU Cloud server. Try again later.', 404))render(<PresetWorkshop preset={CREATE_PRESETS[1]} onClose={() => {}} onGenerate={() => {}} />)fireEvent.change(screen.getByLabelText('Preset prompt'), { target: { value: 'a misty forest creature' } })- await waitFor(() => expect(screen.getByRole('alert').textContent).toBe('This feature needs a newer LU Cloud server. Try again later.'), { timeout: 2000 })+ await waitFor(() => expect(screen.getByRole('alert').textContent).toBe('This feature needs a newer LU Cloud server. Try again later.'), { timeout: 3000 })expect((screen.getByRole('button', { name: 'Generate' }) as HTMLButtonElement).disabled).toBe(true)expect(mocks.submit).not.toHaveBeenCalled()})@@ -448,9 +502,9 @@ it('zeigt bei 409 quote_changed den neuen Preis, statt still neu zu buchen', asymocks.submit.mockRejectedValueOnce(new QuoteChangedError('The price has changed.', 4200))render(<PresetWorkshop preset={CREATE_PRESETS[1]} onClose={() => {}} onGenerate={() => {}} />)fireEvent.change(screen.getByLabelText('Preset prompt'), { target: { value: 'a misty forest creature' } })- await waitFor(() => expect((screen.getByRole('button', { name: 'Generate' }) as HTMLButtonElement).disabled).toBe(false), { timeout: 2000 })+ await waitFor(() => expect((screen.getByRole('button', { name: 'Generate' }) as HTMLButtonElement).disabled).toBe(false), { timeout: 3000 })fireEvent.click(screen.getByRole('button', { name: 'Generate' }))- await waitFor(() => expect(screen.getByRole('alert').textContent).toContain('4,200 credits'), { timeout: 2000 })+ await waitFor(() => expect(screen.getByRole('alert').textContent).toContain('4,200 credits'), { timeout: 3000 })expect(screen.getAllByText(/4,200 credits/).length).toBeGreaterThan(0)expect(mocks.submit).toHaveBeenCalledTimes(1)// Der Knopf ist wieder bedienbar, gegen den NEUEN Preis: ein zweiter,@@ -476,7 +530,7 @@ it('schickt bei einem Wiederholungsversuch ohne neue Quote denselben client_requmocks.submit.mockRejectedValueOnce(new Error('network blip'))render(<PresetWorkshop preset={CREATE_PRESETS[1]} onClose={() => {}} onGenerate={() => {}} />)fireEvent.change(screen.getByLabelText('Preset prompt'), { target: { value: 'a misty forest creature' } })- await waitFor(() => expect((screen.getByRole('button', { name: 'Generate' }) as HTMLButtonElement).disabled).toBe(false), { timeout: 2000 })+ await waitFor(() => expect((screen.getByRole('button', { name: 'Generate' }) as HTMLButtonElement).disabled).toBe(false), { timeout: 3000 })fireEvent.click(screen.getByRole('button', { name: 'Generate' }))await waitFor(() => expect(mocks.submit).toHaveBeenCalledTimes(1))fireEvent.click(screen.getByRole('button', { name: 'Generate' }))@@ -495,7 +549,7 @@ it('zeigt bei 409 quote_changed auf die Preisabfrage selbst ebenfalls den neuenmocks.quote.mockRejectedValueOnce(new StudioQuoteChangedError('The price has changed.', 900))render(<PresetWorkshop preset={CREATE_PRESETS[1]} onClose={() => {}} onGenerate={() => {}} />)fireEvent.change(screen.getByLabelText('Preset prompt'), { target: { value: 'a misty forest creature' } })- await waitFor(() => expect(screen.getAllByText(/900 credits/).length).toBeGreaterThan(0), { timeout: 2000 })+ await waitFor(() => expect(screen.getAllByText(/900 credits/).length).toBeGreaterThan(0), { timeout: 3000 })expect(screen.getByRole('alert').textContent).toBe('The price changed. Review the new price before starting.')expect((screen.getByRole('button', { name: 'Generate' }) as HTMLButtonElement).disabled).toBe(false)expect(mocks.submit).not.toHaveBeenCalled()diff --git a/src/components/create/experimental/useStudioPrice.ts b/src/components/create/experimental/useStudioPrice.tsindex a8deaf68..9599e494 100644--- a/src/components/create/experimental/useStudioPrice.ts+++ b/src/components/create/experimental/useStudioPrice.ts@@ -39,6 +39,7 @@ import { createStudioCost, pricesByInput } from '../../../lib/render/create-studimport { studioQuote } from '../../../api/cloud/studio'import { StudioQuoteChangedError } from '../../../api/cloud/studio'import { CloudJobError } from '../../../api/cloud/client'+import { useDebouncedValue } from '../../../hooks/useDebouncedValue'/** Laenge einer Ton- oder Bildspur, im Browser gemessen. */export function mediaSeconds(url: string, kind: 'audio' | 'video'): Promise<number | undefined> {@@ -81,7 +82,13 @@ export interface StudioPrice {// only updates 1800ms after the prompt stops changing, so continuous typing// (even a slow, sustained 600ms/char rhythm with no individual gap that// long) never touches `key` until the customer actually stops.-const PROMPT_DEBOUNCE_MS = 1800+//+// Review B5 (Runde 4, 20.09.2026): the debounce itself lives in+// useDebouncedValue.ts now, shared with PresetWorkshop.tsx's `priceKey`+// (the same disease, measured there too, see that file), one function+// instead of two copies that could drift apart. Exported so the Workshop+// uses the SAME constant, not a second guess at the right number.+export const PROMPT_DEBOUNCE_MS = 1800export function useStudioPrice(model: string | undefined,@@ -92,11 +99,7 @@ export function useStudioPrice(const [live, setLive] = useState<{ key: string; credits: number } | null>(null)const [error, setError] = useState<{ key: string; message: string } | null>(null)const abort = useRef<AbortController | null>(null)- const [debouncedPromptLen, setDebouncedPromptLen] = useState(prompt.length)- useEffect(() => {- const t = setTimeout(() => setDebouncedPromptLen(prompt.length), PROMPT_DEBOUNCE_MS)- return () => clearTimeout(t)- }, [prompt.length])+ const debouncedPromptLen = useDebouncedValue(prompt.length, PROMPT_DEBOUNCE_MS)const key = model ? JSON.stringify([model, options, debouncedPromptLen, seconds]) : ''useEffect(() => {diff --git a/src/hooks/__tests__/useCloudCreate-studio.test.ts b/src/hooks/__tests__/useCloudCreate-studio.test.tsindex 9312e456..4e9d37bc 100644--- a/src/hooks/__tests__/useCloudCreate-studio.test.ts+++ b/src/hooks/__tests__/useCloudCreate-studio.test.ts@@ -314,6 +314,37 @@ describe('Studio-Modelle in den Create-Unterkategorien', () => {expect(useCreateStore.getState().error).toContain('9,000')})+ // Review B6 (Runde 4, 20.09.2026): the previous test used+ // `mockResolvedValueOnce`, so a SECOND call to studioQuote would have+ // hit the default `{ credits: 42 }` mock from beforeEach, hiding a bug+ // where the rejection never re-primes cloudStudioCredits. A DETERMINISTIC+ // mock (mockResolvedValue, the real provider returns the same number for+ // the same inputs) proves the second click actually books: a fix that+ // never updates cloudStudioCredits in the rejection branch would show+ // the exact same rejected error on click two, zero bookings, three+ // quote calls for three clicks, which is exactly what Opus B measured+ // against the un-fixed code.+ it('ein zweiter Klick nach der Ablehnung bucht mit der neuen Zahl (Review B6, deterministische Quote)', async () => {+ hoisted.studioQuote.mockResolvedValue({ credits: 9000 })+ const s = useCreateStore.getState()+ s.setIntent('lipsync')+ s.setCloudOpModel('heygen-twin')+ s.setCloudStudioCredits(5000)+ useCreateStore.setState({ source: null, audioInput: TON })++ await useCloudCreate().generate()+ expect(submitted).toHaveLength(0)+ expect(useCreateStore.getState().error).toContain('9,000')+ // The rejection must have re-primed the comparison value, or the+ // second click fails exactly the same way.+ expect(useCreateStore.getState().cloudStudioCredits).toBe(9000)++ await useCloudCreate().generate()+ expect(submitted).toHaveLength(1)+ expect(submitted[0].params.max_credits).toBe(9000)+ expect(hoisted.studioQuote).toHaveBeenCalledTimes(2)+ })+it('bucht direkt, wenn die Quote GLEICH dem gezeigten Preis ist', async () => {hoisted.studioQuote.mockResolvedValueOnce({ credits: 5000 })const s = useCreateStore.getState()diff --git a/src/hooks/useCloudCreate.ts b/src/hooks/useCloudCreate.tsindex 8f9e8b74..33f2194e 100644--- a/src/hooks/useCloudCreate.ts+++ b/src/hooks/useCloudCreate.ts@@ -648,8 +648,20 @@ export function useCloudCreate(opts: { onQuotaChange?: () => void } = {}) {// studioQuote() call above and the server's own booking check// (QuoteChangedError), or the quote call itself came back stale// (StudioQuoteChangedError, e.g. the provider's price moved between- // two calls). Either way: show the NEW price and stop, never- // silently rebook against it.+ // two calls, or the shown-price guard right above this catch block+ // rejected a quote higher than what the customer saw). Either way:+ // show the NEW price and stop, never silently rebook against it.+ //+ // Review B6 (Runde 4, 20.09.2026): this used to only setError, never+ // touching cloudStudioCredits, the ONE value the shown-price guard+ // compares the next quote against (Composer.tsx's meter is the only+ // writer otherwise, and nothing re-primes it unless the price key+ // itself changes). Without this line a rejected run stayed rejected+ // forever: click again, same stale low number, same rejection, on+ // and on, even though the error text promised "hit Create again"+ // would work. Setting it here means the SECOND click compares the+ // new quote against the number this message just showed, and books.+ st.setCloudStudioCredits(err.credits)st.setError(`The price changed to ${err.credits.toLocaleString('en-US')} credits. Review it, then hit Create again.`)} else if (err instanceof CloudJobError && err.status === 429) {st.setError(throttleMessage(err))diff --git a/src/hooks/useDebouncedValue.ts b/src/hooks/useDebouncedValue.tsnew file mode 100644index 00000000..b4bdda0b--- /dev/null+++ b/src/hooks/useDebouncedValue.ts@@ -0,0 +1,20 @@+import { useEffect, useState } from 'react'++/**+ * Returns `value`, but only after `ms` have passed with no further change.+ *+ * Built for price-quote keys (Review B4/B5, Runde 3/4, 20.09.2026): a field+ * that changes on every keystroke (a typed prompt) must not restart a+ * rate-limited network call every time, but the field still belongs in the+ * key once it settles. Shared between useStudioPrice.ts (the Composer's live+ * meter) and PresetWorkshop.tsx (the same shape, same fix, one function+ * instead of two copies that could drift apart).+ */+export function useDebouncedValue<T>(value: T, ms: number): T {+ const [debounced, setDebounced] = useState(value)+ useEffect(() => {+ const t = setTimeout(() => setDebounced(value), ms)+ return () => clearTimeout(t)+ }, [value, ms])+ return debounced+}