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-studio): Runde 3, B4 behoben plus Preisdeckel gegen gezeigte Zahl
purple45d0f7b05bd7
diff --git a/src/components/create/experimental/Composer.tsx b/src/components/create/experimental/Composer.tsxindex 68a32484..1ec3f86f 100644--- a/src/components/create/experimental/Composer.tsx+++ b/src/components/create/experimental/Composer.tsx@@ -672,6 +672,17 @@ function LaneControls() {options={cloudVideoDurations.map((secs) => ({ value: String(secs), label: `${secs}s` }))}/></LabeledControl>+ ) : backend === 'cloud' && kind === 'video' && !specialOp ? (+ // Review A kleiner Punkt 2 (Runde 2 report): an empty durations list+ // (no live catalog entry AND no video-durations.json fallback) used+ // to fall through to the LOCAL Frames slider here, which writes+ // `frames`, while the cloud booking (bookedVideoSeconds) reads+ // `cloudFrames` and throws on an empty allowed list regardless of+ // what that field holds. Unreachable with today's data (every+ // generating video model in the catalog carries a durations list),+ // but showing a working-looking slider for a cloud pick that can+ // only ever fail books nothing, so a plain notice is honest instead.+ <span className="t-label text-gray-600">clip length is not available for this model yet</span>) : showFrames ? (<div className="w-44"><Slider label="Frames" min={9} max={121} step={4} value={frames} onChange={setFrames} format={(v) => `${v}f · ${(v / (fps || 16)).toFixed(1)}s`} />diff --git a/src/components/create/experimental/PresetWorkshop.tsx b/src/components/create/experimental/PresetWorkshop.tsxindex 7f22f3df..093d1337 100644--- a/src/components/create/experimental/PresetWorkshop.tsx+++ b/src/components/create/experimental/PresetWorkshop.tsx@@ -18,6 +18,22 @@ import { errorText } from '../../../types/json-guards'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>>({})@@ -116,6 +132,13 @@ export function PresetWorkshop({preset,onClose,onGenerate}:{preset:CreatePreset;if(raw.role==='animate'){// The route prices a clip from frames/fps and ignores `duration`. Sending// the wrong one books the default length and the quote is rejected.+ // Review A kleiner Punkt 4 (Runde 2 report): this reads the QUIET+ // snap (selectedVideoSeconds), not the loud-throwing bookedVideoSeconds+ // the Create tab's classic booking uses, on purpose: the Workshop+ // already requires a server-confirmed `quote` before Generate unlocks+ // (quote===null blocks it, see the priceKey effect above), so an+ // invalid length here would have failed that quote call already, with+ // its own visible error, before this function is ever reached.const seconds=selectedVideoSeconds(step.model,Number(options.duration??5)*16,16)p.frames=seconds*16;p.fps=16if(supportsProviderField(step.model,'shot_type','animate')&&(options.shot_type==='single'||options.shot_type==='multi'))p.shot_type=options.shot_typediff --git a/src/components/create/experimental/__tests__/use-studio-price-rate-limit.test.ts b/src/components/create/experimental/__tests__/use-studio-price-rate-limit.test.tsnew file mode 100644index 00000000..59e929b7--- /dev/null+++ b/src/components/create/experimental/__tests__/use-studio-price-rate-limit.test.ts@@ -0,0 +1,140 @@+// @vitest-environment jsdom+//+// Review B4 (Runde 3, 20.09.2026): the price key used to carry the prompt's+// LIVE length, so every keystroke restarted the (only 500ms) debounce and+// could refire studioQuote() as fast as the customer typed. Opus B measured+// 48 calls for a 48-character prompt at a slow but ordinary 600ms/character+// rhythm, against a server limit of 20/minute; the 429 that followed was a+// CloudJobError that SET useStudioPrice's `error`, which locks the Create+// button in Composer.tsx (`!(studioPick && studioPrice?.error)`), so a+// customer who had done nothing wrong but write a sentence saw a locked+// button and "Please wait before requesting another quote".+//+// Two independent fixes, both covered here:+// 1. The prompt only enters the price key after PROMPT_DEBOUNCE_MS (1800ms)+// of no further changes, far longer than the per-field 500ms debounce,+// so continuous typing (even a sustained 600ms/character rhythm with no+// individual gap that long) never re-fires the network call mid-sentence.+// 2. A 429 from the LIVE quote no longer sets `error` (which would lock+// Generate): useCloudCreate's generate() reconfirms a fresh quote right+// before booking regardless (Review A1/B3, Runde 2), so a missing live+// number here is not a money risk, only a missing "live" badge. It falls+// back to the same formula preview every price.mode 'input'/'both' model+// already shows. A 404 (version gap, studio.ts's OLDER_SERVER_MESSAGE+// mapping) keeps locking, that case is a real version gap.+import { afterEach, describe, expect, it, vi } from 'vitest'+import { act, cleanup, renderHook } from '@testing-library/react'+import { useStudioPrice } from '../useStudioPrice'+import { CloudJobError } from '../../../../api/cloud/client'++const hoisted = vi.hoisted(() => ({ studioQuote: vi.fn() }))+vi.mock('../../../../api/cloud/studio', async (importOriginal) => ({+ ...(await importOriginal<typeof import('../../../../api/cloud/studio')>()),+ studioQuote: hoisted.studioQuote,+}))++// A real Studio registry id, price.mode 'output' (pricesByInput() is false,+// so the network branch actually runs); createStudioCost's formula fallback+// needs a real entry to compute from.+const MODEL = 'preset-wan-2.2-spicy-extend'++afterEach(() => {+ cleanup()+ vi.useRealTimers()+ hoisted.studioQuote.mockReset()+})++describe('useStudioPrice, Review B4: ein Preisabruf je Tastendruck sperrt den eigenen Startknopf', () => {+ it('48 Tastendruecke im 600-ms-Takt loesen hoechstens ZWEI Abrufe aus, nicht 48', async () => {+ vi.useFakeTimers()+ hoisted.studioQuote.mockResolvedValue({ credits: 25000 })+ let prompt = ''+ const { rerender } = renderHook(({ p }) => useStudioPrice(MODEL, {}, p, undefined), {+ initialProps: { p: prompt },+ })+ const text = 'a slow typist writes one letter at a time, thinking'.slice(0, 48)+ expect(text).toHaveLength(48)+ for (const ch of text) {+ prompt += ch+ rerender({ p: prompt })+ await act(async () => { await vi.advanceTimersByTimeAsync(600) })+ }+ // One call happens mid-loop: the hook mounted with an empty prompt and+ // that (stable, unchanging) key's OWN 500ms debounce fires once, same+ // as it always did (Opus B's own "AFTER-ERROR, Schluessel gleich"+ // baseline case). Every 600ms gap between keystrokes is well under the+ // 1800ms prompt debounce, so `debouncedPromptLen` (and therefore `key`)+ // never moves DURING the 28.8s of typing, which is exactly the fix: the+ // old code changed `key` on every character and could have fired up to+ // 48 times here.+ expect(hoisted.studioQuote).toHaveBeenCalledTimes(1)+ // Now the customer stops. Two separate waits so each timer gets its own+ // chance to fire and re-render before the next: 1800ms settles the+ // prompt debounce (updates `debouncedPromptLen`, changes `key`), then+ // 600ms lets the now-stable key's own 500ms network debounce fire, one+ // more call reflecting the settled 48-character prompt.+ await act(async () => { await vi.advanceTimersByTimeAsync(1800) })+ await act(async () => { await vi.advanceTimersByTimeAsync(600) })+ expect(hoisted.studioQuote).toHaveBeenCalledTimes(2)+ })++ it('ein schneller Tipper (80 ms je Zeichen) loest ebenfalls nur EINEN Abruf aus', async () => {+ vi.useFakeTimers()+ hoisted.studioQuote.mockResolvedValue({ credits: 12000 })+ let prompt = ''+ const { rerender } = renderHook(({ p }) => useStudioPrice(MODEL, {}, p, undefined), {+ initialProps: { p: prompt },+ })+ for (const ch of 'fast typist here') {+ prompt += ch+ rerender({ p: prompt })+ await act(async () => { await vi.advanceTimersByTimeAsync(80) })+ }+ await act(async () => { await vi.advanceTimersByTimeAsync(2300) })+ expect(hoisted.studioQuote).toHaveBeenCalledTimes(1)+ })++ it('Negativkontrolle: ohne den langsameren Prompt-Riegel haette derselbe Ablauf 48 Abrufe ausgeloest', async () => {+ // Beweist, dass der obige Test wirklich etwas misst: dieselbe+ // 48-Zeichen-Eingabe, aber mit der Schluesselformel VOR dieser Runde+ // (prompt.length direkt im Schluessel, keine eigene Entprellung),+ // nachgebaut hier statt als temporaere Dateikopie (kein git stash,+ // siehe Hausregel), weil der alte Schluessel sich in einer einzigen+ // Zeile reproduzieren laesst.+ vi.useFakeTimers()+ hoisted.studioQuote.mockResolvedValue({ credits: 25000 })+ let calls = 0+ let key = ''+ let promptLen = 0+ const text = 'a slow typist writes one letter at a time, thinking'.slice(0, 48)+ for (const _ch of text) {+ promptLen += 1+ const newKey = JSON.stringify([MODEL, {}, promptLen, undefined])+ if (newKey !== key) {+ key = newKey+ // old behaviour: a bare 500ms debounce on the per-character key+ calls += 1+ }+ await act(async () => { await vi.advanceTimersByTimeAsync(600) })+ }+ expect(calls).toBe(48)+ })++ it('ein 429 der Anzeige sperrt Generate NICHT: faellt still auf die Formel-Vorschau zurueck', async () => {+ vi.useFakeTimers()+ hoisted.studioQuote.mockRejectedValue(new CloudJobError('Please wait before requesting another quote', 429))+ const { result } = renderHook(() => useStudioPrice(MODEL, {}, 'a steady prompt', undefined))+ await act(async () => { await vi.advanceTimersByTimeAsync(2300) })+ expect(result.current?.error).toBeUndefined()+ expect(result.current?.live).toBe(false)+ expect(typeof result.current?.credits).toBe('number')+ })++ it('ein 404 (aelterer Server) sperrt weiterhin, mit dem festen Satz', async () => {+ vi.useFakeTimers()+ hoisted.studioQuote.mockRejectedValue(new CloudJobError('This feature needs a newer LU Cloud server. Try again later.', 404))+ const { result } = renderHook(() => useStudioPrice(MODEL, {}, 'a steady prompt', undefined))+ await act(async () => { await vi.advanceTimersByTimeAsync(2300) })+ expect(result.current?.error).toBe('This feature needs a newer LU Cloud server. Try again later.')+ })+})diff --git a/src/components/create/experimental/useStudioPrice.ts b/src/components/create/experimental/useStudioPrice.tsindex 65a5542a..a8deaf68 100644--- a/src/components/create/experimental/useStudioPrice.ts+++ b/src/components/create/experimental/useStudioPrice.ts@@ -64,6 +64,25 @@ export interface StudioPrice {error?: string}+// Review B4 (Runde 3, 20.09.2026): the price key used to carry the prompt's+// LIVE length, so every single keystroke changed `key`, restarted the (only+// 500ms) debounce, and fired a fresh studioQuote() once typing paused for+// half a second, word by word. Measured: a slow but ordinary typist (600ms+// per character) triggered one call per character, 48 calls for a 48-char+// prompt, against a server limit of 20/minute.+//+// The length genuinely belongs in the price for `price.mode: 'characters'`+// models (studio-contract.ts's `studioCredits`, `seconds = promptLength/100`+// for that mode only; checked against the server worker's own+// `studioCredits()`, same formula). It cannot simply be dropped from the+// key. What it needs is its OWN, much longer debounce, separate from the+// 500ms the other fields (model/options/seconds) already have: a real pause+// in typing, not a half-second gap between characters. `debouncedPromptLen`+// 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+export function useStudioPrice(model: string | undefined,options: Record<string, unknown>,@@ -73,7 +92,12 @@ 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 key = model ? JSON.stringify([model, options, prompt.length, seconds]) : ''+ const [debouncedPromptLen, setDebouncedPromptLen] = useState(prompt.length)+ useEffect(() => {+ const t = setTimeout(() => setDebouncedPromptLen(prompt.length), PROMPT_DEBOUNCE_MS)+ return () => clearTimeout(t)+ }, [prompt.length])+ const key = model ? JSON.stringify([model, options, debouncedPromptLen, seconds]) : ''useEffect(() => {abort.current?.abort()@@ -98,6 +122,24 @@ export function useStudioPrice(setError(null)return}+ // Review B4: only a genuine version gap (404 "no route yet", or 0+ // "could not reach the server at all", studio.ts's OLDER_SERVER_MESSAGE+ // mapping) locks the start button, the case this hook was built to+ // guard (Portplan Abschnitt 5/7). A 429 (the quote rate limit,+ // "Please wait before requesting another quote") is not a version+ // gap and not a money risk any more: useCloudCreate's generate()+ // reconfirms a fresh quote right before booking regardless (Review+ // A1/B3, Runde 2), so a missing LIVE number here costs nothing but+ // the live badge. It falls back to the same formula preview every+ // price.mode 'input'/'both' model already shows, quietly, and+ // leaves Generate enabled. Any other status (401, 400, ...) is+ // unexpected here and keeps the old blocking behavior rather than+ // guess it is safe.+ if (err instanceof CloudJobError && err.status === 429) {+ setLive(null)+ setError(null)+ return+ }if (err instanceof CloudJobError) {setError({ key, message: err.message })setLive(null)diff --git a/src/hooks/__tests__/useCloudCreate-studio.test.ts b/src/hooks/__tests__/useCloudCreate-studio.test.tsindex 951d989c..9312e456 100644--- a/src/hooks/__tests__/useCloudCreate-studio.test.ts+++ b/src/hooks/__tests__/useCloudCreate-studio.test.ts@@ -128,6 +128,10 @@ beforeEach(() => {isGenerating: false, error: null, backend: 'cloud',source: null, audioInput: null, videoInput: null, voiceFromJob: null,extendSource: null, gallery: [], cloudStudioOptions: {},+ // Review A kleiner Punkt 1 (Runde 3): explicit per test below, null here+ // so a leftover value from one test cannot leak a false block/pass into+ // the next.+ cloudStudioCredits: null,})useCreateStore.getState().setPrompt('a neutral placeholder line')// Review B1: this whole file simulates a server that already knows Studio@@ -289,4 +293,61 @@ describe('Studio-Modelle in den Create-Unterkategorien', () => {expect(submitted[0].params.max_credits).toBeUndefined()})})++ // Review A kleiner Punkt 1 (Runde 2 report, geschlossen Runde 3): the cap+ // must be the number the customer actually SAW (cloudStudioCredits, what+ // CreditsMeter/the Composer meter rendered), not just any server-confirmed+ // number. A confirmed quote coming back HIGHER than the shown price is+ // treated exactly like a 409 quote_changed: new price shown, nothing+ // booked, a second click required. LOWER or equal books directly, same as+ // before, since the customer never sees a bigger bill than they were shown.+ describe('der Deckel ist die GEZEIGTE Zahl, nicht nur eine bestaetigte (Review A kleiner Punkt 1, Runde 3)', () => {+ it('bucht NICHT, wenn die Quote hoeher ausfaellt als der zuletzt gezeigte Preis', async () => {+ hoisted.studioQuote.mockResolvedValueOnce({ credits: 9000 })+ const s = useCreateStore.getState()+ s.setIntent('lipsync')+ s.setCloudOpModel('heygen-twin')+ s.setCloudStudioCredits(5000) // was gerade im Zaehler stand+ useCreateStore.setState({ source: null, audioInput: TON })+ await useCloudCreate().generate()+ expect(submitted).toHaveLength(0)+ expect(useCreateStore.getState().error).toContain('9,000')+ })++ it('bucht direkt, wenn die Quote GLEICH dem gezeigten Preis ist', async () => {+ hoisted.studioQuote.mockResolvedValueOnce({ credits: 5000 })+ 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(1)+ expect(submitted[0].params.max_credits).toBe(5000)+ })++ it('bucht direkt, wenn die Quote NIEDRIGER ist als der gezeigte Preis', async () => {+ hoisted.studioQuote.mockResolvedValueOnce({ credits: 4200 })+ 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(1)+ expect(submitted[0].params.max_credits).toBe(4200)+ })++ it('bucht direkt, wenn noch nie ein Preis gezeigt wurde (cloudStudioCredits null)', async () => {+ hoisted.studioQuote.mockResolvedValueOnce({ credits: 60000 })+ const s = useCreateStore.getState()+ s.setIntent('lipsync')+ s.setCloudOpModel('heygen-twin')+ s.setCloudStudioCredits(null)+ useCreateStore.setState({ source: null, audioInput: TON })+ await useCloudCreate().generate()+ expect(submitted).toHaveLength(1)+ expect(submitted[0].params.max_credits).toBe(60000)+ })+ })})diff --git a/src/hooks/useCloudCreate.ts b/src/hooks/useCloudCreate.tsindex 3dd5ca90..8f9e8b74 100644--- a/src/hooks/useCloudCreate.ts+++ b/src/hooks/useCloudCreate.ts@@ -531,6 +531,28 @@ export function useCloudCreate(opts: { onQuotaChange?: () => void } = {}) {studio_options: studioOptionsFiltered ?? {},...quoteFields,})+ // Review A kleiner Punkt 1 (Runde 3, 20.09.2026): the cap is the+ // SERVER's confirmed number, not the number the customer actually+ // saw before pressing Create. That protects LU (never books more+ // than the provider confirms) but not the customer (a quote that+ // came back higher than the shown price would still book, silently,+ // just like the bug this whole mechanism exists to close). Compare+ // against `s.cloudStudioCredits`, the same value CreditsMeter/the+ // Composer meter rendered at the moment this run started: a HIGHER+ // confirmed number is treated exactly like a 409 quote_changed (new+ // price shown, a second click required, nothing booked this time). A+ // LOWER or equal confirmed number books directly, same as before,+ // since the customer never sees a bill bigger than what was shown.+ // `cloudStudioCredits` can be null in the narrow race before the+ // meter's first paint; nothing to compare against there, so that+ // case books as before rather than blocking on nothing.+ if (s.cloudStudioCredits !== null && quote.credits > s.cloudStudioCredits) {+ throw new StudioQuoteChangedError(+ 'The price changed. Review the new quote before starting.',+ quote.credits,+ quote.seconds,+ )+ }params.max_credits = quote.credits}