Skip to content

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.

feat(create): Wolken-Bruecke und Preis fuer das Studio (P3)

purple505a0ab4173a
diff --git a/src/api/cloud/__tests__/studio.test.ts b/src/api/cloud/__tests__/studio.test.ts
new file mode 100644
index 00000000..d7cb7488
--- /dev/null
+++ b/src/api/cloud/__tests__/studio.test.ts
@@ -0,0 +1,174 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+
+// studioQuote() / modelRuntimes(): same cloudFetch layer as every other cloud
+// call (bearer + CLOUD_BASE), P3's honest-failure contract for a server that
+// does not have Studio yet, and the typed 409 pass-through.
+
+const { getAccessToken } = vi.hoisted(() => ({ getAccessToken: vi.fn() }))
+vi.mock('../supabase', () => ({ getAccessToken }))
+
+import { CloudJobError } from '../client'
+import { studioQuote, StudioQuoteChangedError, modelRuntimes } from '../studio'
+import { CLOUD_BASE } from '../config'
+
+const fetchMock = vi.fn()
+
+beforeEach(() => {
+ vi.clearAllMocks()
+ vi.stubGlobal('fetch', fetchMock)
+ getAccessToken.mockResolvedValue('tok-123')
+})
+
+function jsonRes(body: unknown, status = 200): Response {
+ return new Response(JSON.stringify(body), {
+ status,
+ headers: { 'content-type': 'application/json' },
+ })
+}
+
+describe('studioQuote', () => {
+ it('posts model/prompt/params to /api/jobs/studio-quote with the bearer set', async () => {
+ fetchMock.mockResolvedValue(jsonRes({ credits: 4200, seconds: 5 }))
+ const result = await studioQuote('preset-horror', 'a whisper in the dark', {
+ op: 'studio',
+ studio_options: { resolution: '720p' },
+ image_paths: ['u1/f1.png'],
+ })
+ expect(result).toEqual({ credits: 4200, seconds: 5 })
+ expect(fetchMock).toHaveBeenCalledOnce()
+ const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit]
+ expect(url).toBe(`${CLOUD_BASE}/api/jobs/studio-quote`)
+ expect(new Headers(init.headers).get('authorization')).toBe('Bearer tok-123')
+ expect(JSON.parse(String(init.body))).toEqual({
+ model: 'preset-horror',
+ prompt: 'a whisper in the dark',
+ params: { op: 'studio', studio_options: { resolution: '720p' }, image_paths: ['u1/f1.png'] },
+ })
+ })
+
+ // Negativkontrolle: eine 429-Antwort darf NICHT denselben Weg wie 404/CORS
+ // nehmen. Ohne diesen Fall wuerde ein zu weiter Statuscheck (z.B. "!res.ok")
+ // auch die Ratenbremse stumm auf den Server-veraltet-Text umschreiben.
+ it('passes the server text through unchanged on 400 and 429', async () => {
+ fetchMock.mockResolvedValueOnce(jsonRes({ error: 'Enter a prompt before starting' }, 400))
+ await expect(
+ studioQuote('preset-horror', '', { op: 'studio', studio_options: {} }),
+ ).rejects.toMatchObject({ status: 400, message: 'Enter a prompt before starting' })
+
+ fetchMock.mockResolvedValueOnce(jsonRes({ error: 'Please wait before requesting another quote' }, 429))
+ await expect(
+ studioQuote('preset-horror', 'x', { op: 'studio', studio_options: {} }),
+ ).rejects.toMatchObject({ status: 429, message: 'Please wait before requesting another quote' })
+ })
+
+ it('answers a clean 404 with the honest "needs a newer server" text, never a guessed price', async () => {
+ fetchMock.mockResolvedValueOnce(jsonRes({}, 404))
+ const err = await studioQuote('preset-horror', 'x', {
+ op: 'studio',
+ studio_options: {},
+ }).catch((e: unknown) => e)
+ expect(err).toBeInstanceOf(CloudJobError)
+ expect((err as CloudJobError).status).toBe(404)
+ expect((err as CloudJobError).message).toBe(
+ 'This feature needs a newer LU Cloud server. Try again later.',
+ )
+ })
+
+ // Der Fall, den P0 heute noch offen laesst: die Route hat kein CORS, der
+ // Browser blockt die Antwort und fetch() lehnt mit dem rohen Motor-Text ab,
+ // nie mit einem Status. cloudFetch wandelt das selbst schon in eine eigene
+ // CloudJobError um ("Could not reach..."), studioQuote muss diese ZWEITE
+ // Umformulierung noch einmal ueberschreiben, sonst liest der Kunde eine
+ // Verbindungsstoerung statt einer fehlenden Serverfunktion.
+ it('answers a CORS-blocked route the same way as a 404: no fallback formula, no booking', async () => {
+ fetchMock.mockRejectedValueOnce(new TypeError('Failed to fetch'))
+ const err = await studioQuote('preset-horror', 'x', {
+ op: 'studio',
+ studio_options: {},
+ }).catch((e: unknown) => e)
+ expect(err).toBeInstanceOf(CloudJobError)
+ expect((err as CloudJobError).message).toBe(
+ 'This feature needs a newer LU Cloud server. Try again later.',
+ )
+ // Not cloudFetch's own generic wording: a version gap is not a blip.
+ expect((err as CloudJobError).message).not.toMatch(/could not reach/i)
+ })
+
+ it('does not relabel an unrelated failure (not signed in) as a version gap', async () => {
+ getAccessToken.mockResolvedValueOnce(null)
+ const err = await studioQuote('preset-horror', 'x', {
+ op: 'studio',
+ studio_options: {},
+ }).catch((e: unknown) => e)
+ expect(err).toBeInstanceOf(CloudJobError)
+ expect((err as CloudJobError).status).toBe(401)
+ expect((err as CloudJobError).message).not.toBe(
+ 'This feature needs a newer LU Cloud server. Try again later.',
+ )
+ })
+
+ it('reaches a 409 quote_changed as a typed error carrying the fresh credits', async () => {
+ fetchMock.mockResolvedValueOnce(
+ jsonRes({ error: 'The price has changed. Review the new quote before starting.', code: 'quote_changed', credits: 5100, seconds: 6 }, 409),
+ )
+ const err = await studioQuote('preset-horror', 'x', {
+ op: 'studio',
+ studio_options: {},
+ }).catch((e: unknown) => e)
+ expect(err).toBeInstanceOf(StudioQuoteChangedError)
+ expect((err as StudioQuoteChangedError).status).toBe(409)
+ expect((err as StudioQuoteChangedError).code).toBe('quote_changed')
+ expect((err as StudioQuoteChangedError).credits).toBe(5100)
+ expect((err as StudioQuoteChangedError).seconds).toBe(6)
+ expect((err as StudioQuoteChangedError).message).toBe(
+ 'The price has changed. Review the new quote before starting.',
+ )
+ })
+
+ it('a 409 with an unreadable body still yields a typed error, not a crash', async () => {
+ fetchMock.mockResolvedValueOnce(
+ new Response('not json', { status: 409, headers: { 'content-type': 'application/json' } }),
+ )
+ const err = await studioQuote('preset-horror', 'x', {
+ op: 'studio',
+ studio_options: {},
+ }).catch((e: unknown) => e)
+ expect(err).toBeInstanceOf(StudioQuoteChangedError)
+ expect((err as StudioQuoteChangedError).credits).toBe(0)
+ })
+})
+
+describe('modelRuntimes', () => {
+ it('returns the server\'s runtime map on success', async () => {
+ fetchMock.mockResolvedValueOnce(
+ jsonRes({ runtimes: { 'preset-horror': { seconds: 42, samples: 9 } } }),
+ )
+ expect(await modelRuntimes()).toEqual({ 'preset-horror': { seconds: 42, samples: 9 } })
+ const [url] = fetchMock.mock.calls[0] as [string, RequestInit]
+ expect(url).toBe(`${CLOUD_BASE}/api/jobs/runtime`)
+ })
+
+ // Negativkontrolle: ohne diesen Fall koennte modelRuntimes() bei einem
+ // leeren Objekt in der Antwort ({} statt {runtimes: {}}) unbemerkt
+ // `undefined` durchreichen und jeden Aufrufer, der .keys() darauf aufruft,
+ // zum Absturz bringen.
+ it('falls back to an empty map when the body carries no runtimes field', async () => {
+ fetchMock.mockResolvedValueOnce(jsonRes({}))
+ expect(await modelRuntimes()).toEqual({})
+ })
+
+ it('stays silent (empty map) on a 404, never throwing', async () => {
+ fetchMock.mockResolvedValueOnce(jsonRes({}, 404))
+ expect(await modelRuntimes()).toEqual({})
+ })
+
+ it('stays silent (empty map) when the route is CORS-blocked / unreachable', async () => {
+ fetchMock.mockRejectedValueOnce(new TypeError('Failed to fetch'))
+ expect(await modelRuntimes()).toEqual({})
+ })
+
+ it('stays silent (empty map) when signed out, never surfacing a 401', async () => {
+ getAccessToken.mockResolvedValueOnce(null)
+ expect(await modelRuntimes()).toEqual({})
+ })
+})
diff --git a/src/api/cloud/catalog.ts b/src/api/cloud/catalog.ts
index 8d64f187..04836b67 100644
--- a/src/api/cloud/catalog.ts
+++ b/src/api/cloud/catalog.ts
@@ -29,6 +29,11 @@ export async function getCatalog(): Promise<CloudCatalog> {
// v=2: this build understands op-specialized models (trainers, lipsync,
// voice, music, extend, motion) — without the flag the server serves only
// the classic list so pre-2.5.8 clients never mis-list them.
+ //
+ // P3: no query bump for Studio. A server that knows Studio simply adds
+ // `api_schema`/`pricing`/`quote_required` to the entries this same v=2
+ // response already carries, and cloudCatalogStore/runCredits key off the
+ // PRESENCE of those fields, never a version number (portplan Abschnitt 4/7).
const res = await cloudFetch('/api/jobs/catalog?v=2')
return jsonOrError<CloudCatalog>(res)
}
diff --git a/src/api/cloud/studio.ts b/src/api/cloud/studio.ts
new file mode 100644
index 00000000..efd74c01
--- /dev/null
+++ b/src/api/cloud/studio.ts
@@ -0,0 +1,113 @@
+// P3: the two Studio-only cloud routes. Same layer as every other cloud call
+// (cloudFetch: CLOUD_BASE + bearer), never a bare fetch out of a component
+// (Abschnitt 4 des Portplans).
+
+import { cloudFetch, jsonOrError, CloudJobError } from './client'
+import type { ModelRuntime } from '../../lib/render/runtime-format'
+
+export interface StudioQuoteResult {
+ credits: number
+ seconds?: number
+}
+
+export interface StudioQuoteParams {
+ op: 'studio'
+ studio_options: Record<string, unknown>
+ // Whichever staged-upload path fields the picked model's schema needs
+ // (image_paths, source_path, mask_path, audio_path, audio2_path, video_path,
+ // last_image_path, duration, shot_type, ...); the exact set is per-model,
+ // studio-contract.ts is the vertrag, not this type.
+ [field: string]: unknown
+}
+
+const OLDER_SERVER_MESSAGE =
+ 'This feature needs a newer LU Cloud server. Try again later.'
+
+/** Thrown on a 409 from `/api/jobs/studio-quote` (`code: 'quote_changed'`):
+ * the price this call asked about is stale, and `credits` carries the
+ * server's fresh number, typed through instead of buried in `.message`. */
+export class StudioQuoteChangedError extends CloudJobError {
+ readonly credits: number
+ readonly seconds?: number
+ constructor(message: string, credits: number, seconds?: number) {
+ super(message, 409, { code: 'quote_changed' })
+ this.name = 'StudioQuoteChangedError'
+ this.credits = credits
+ this.seconds = seconds
+ }
+}
+
+/**
+ * POST /api/jobs/studio-quote: the provider-confirmed price for one Studio
+ * run, asked before the run books. Never falls back to a client-side formula
+ * on failure: `studio-contract.ts` can PREVIEW a number for the controls, but
+ * only this call's number is what the server will actually charge, and
+ * booking against a guessed one risks a 409 after the customer already
+ * pressed start (Portplan Abschnitt 4/7, Risiko 1+2).
+ *
+ * Two failure shapes both mean "this server does not have Studio yet", and
+ * both get the same honest, English text instead of a technical one:
+ * - a plain 404 (the route answered, CORS present, but no handler, a
+ * server that shipped P0's CORS fix without this route existing yet), and
+ * - a raw network/CORS failure (the route has no `withCors`/`OPTIONS` at
+ * all, the browser never lets the response reach this code; the
+ * documented pre-P0 state of both routes today). cloudFetch already turns
+ * that into its own CloudJobError(status 0, "Could not reach the LU
+ * Cloud server...") for every OTHER cloud call; here it is reworded once
+ * more, because "try again in a moment" reads as a blip and this is a
+ * version gap. Any other rejection (401 not signed in, 408 timeout, a
+ * deliberate abort) is not a version gap and keeps its own status intact.
+ */
+export async function studioQuote(
+ model: string,
+ prompt: string,
+ params: StudioQuoteParams,
+): Promise<StudioQuoteResult> {
+ let res: Response
+ try {
+ res = await cloudFetch('/api/jobs/studio-quote', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ model, prompt, params }),
+ })
+ } catch (err) {
+ if (err instanceof CloudJobError && err.status !== 0) throw err
+ throw new CloudJobError(OLDER_SERVER_MESSAGE, 0, { cause: err })
+ }
+ if (res.status === 404) throw new CloudJobError(OLDER_SERVER_MESSAGE, 404)
+ if (res.status === 409) {
+ const body = (await res.json().catch(() => ({}))) as {
+ error?: string
+ credits?: number
+ seconds?: number
+ }
+ throw new StudioQuoteChangedError(
+ typeof body.error === 'string'
+ ? body.error
+ : 'The price has changed. Review the new quote before starting.',
+ typeof body.credits === 'number' ? body.credits : 0,
+ typeof body.seconds === 'number' ? body.seconds : undefined,
+ )
+ }
+ // 400 (invalid request/options) and 429 (quote rate limit) keep the
+ // server's own text verbatim: jsonOrError throws CloudJobError with
+ // `body.error` unchanged, nothing to reword or translate here.
+ return jsonOrError<StudioQuoteResult>(res)
+}
+
+/**
+ * GET /api/jobs/runtime: measured render times per model, for the "about
+ * 45 sec" hint next to the price. Unreachable (offline, an older server, or
+ * the same pre-P0 CORS gap as studio-quote) means silence, not a guess:
+ * `MIN_SAMPLES` in runtime-format.ts already says this app would rather say
+ * nothing than make one up, so any failure here just yields an empty map.
+ */
+export async function modelRuntimes(): Promise<Record<string, ModelRuntime>> {
+ try {
+ const res = await cloudFetch('/api/jobs/runtime')
+ const body = await jsonOrError<{ runtimes: Record<string, ModelRuntime> }>(res)
+ return body.runtimes ?? {}
+ } catch {
+ return {}
+ }
+}
diff --git a/src/lib/render/cloud-models.ts b/src/lib/render/cloud-models.ts
index 4946e92c..eeccb6e3 100644
--- a/src/lib/render/cloud-models.ts
+++ b/src/lib/render/cloud-models.ts
@@ -5,11 +5,29 @@
// uselu apps/web/lib/render/cloud-models.ts when touching this file.
import type { RenderKind, RenderOp } from './cloud-jobs'
+import type { Schema, StudioModel } from './studio-contract'
export interface CloudModel {
id: string
label: string
kind: RenderKind
+ /** P3: present only on a Studio-capable catalog entry (server field
+ * `api_schema`), the provider's own field schema for the endpoint, so the
+ * Studio controls can be built without a second copy of it. Undefined on
+ * every classic model and on any catalog payload from a server that does
+ * not know Studio yet. */
+ api_schema?: Schema
+ /** P3: the provider's pricing formula for a Studio model (server field
+ * `pricing`, mirrors `StudioModel['price']` in studio-contract.ts). DISPLAY
+ * only, the preview shown before a run starts: a run always books the
+ * number `POST /api/jobs/studio-quote` confirms, never this formula. */
+ pricing?: StudioModel['price']
+ /** P3: marks a Studio model (server field `quote_required`). This is the
+ * ONLY signal "can the server do Studio" ever reads: absence, not a
+ * version number, is what an older catalog payload looks like, and the
+ * presence of this field on at least one entry is what unlocks the preset
+ * shelf. A model carrying it must never be priced from a client formula. */
+ quote_required?: boolean
/** Supports the masked img2img 'edit' op (flux-dev only today). */
edit?: boolean
/** R5-66: an instruction-based edit endpoint that takes prompt + image and
@@ -49,8 +67,14 @@ export interface CloudModel {
cfg?: boolean
/** Whether the hosted endpoint honours negative_prompt. */
negative_prompt?: boolean
- /** Video: clip lengths the model books (5s short / 8s long). */
- clip?: { short: number; long?: number }
+ /** Video: clip lengths the model books (5s short / 8s long).
+ *
+ * `durations` (P3, server field `clip.durations`, from dd29f359): every
+ * length the model actually books, not just the two named buttons; the
+ * booking truth is `bookedVideoSeconds()` in `video-duration.ts` against
+ * this same list. Optional: an older catalog payload omits it and the
+ * short/long pair above still holds. */
+ clip?: { short: number; long?: number; durations?: number[] }
/** Per-run credit cost (base = image or 5s clip, long = 8s clip; music
* models additionally quote per_s for the duration slider).
*
@@ -59,8 +83,14 @@ export interface CloudModel {
* different price. It REPLACES the base rate, it does not add to it, and it
* is set only where the twin really costs more than our base rate covers.
* /api/jobs/catalog emits it on exactly the same terms, so the client never
- * needs a second price table. */
- credits?: { base: number; long?: number; per_s?: number; lora?: number }
+ * needs a second price table.
+ *
+ * `by_duration` (P3, server field `credits.by_duration`, from dd29f359):
+ * the exact price per bookable length, keyed by the length in seconds as
+ * a string (matches `clip.durations`). Lets a client price a length other
+ * than the short/long pair precisely instead of rounding onto one of
+ * them; `runCredits()` in cloudCatalogStore.ts prefers this when present. */
+ credits?: { base: number; long?: number; per_s?: number; lora?: number; by_duration?: Record<string, number> }
}
const CLIP = { short: 5, long: 8 }
@@ -74,7 +104,7 @@ export const CLOUD_MODEL_SEED: CloudModel[] = [
{ id: 'hunyuan-image', label: 'HunyuanImage 2.1', kind: 'image' },
{ id: 'z-image-turbo', label: 'Z-Image Turbo (fast)', kind: 'image' },
{ id: 'chroma', label: 'Chroma Spicy', kind: 'image', adult: true },
- { id: 'prefect-pony', label: 'Prefect Pony XL Spicy', kind: 'image', adult: true },
+ { id: 'prefect-pony', label: 'Prefect Pony XL (illustration) Spicy', kind: 'image', adult: true },
{ id: 'neta-lumina', label: 'Neta Lumina (anime) Spicy', kind: 'image', adult: true },
// Every hosted clip model does both t2v + i2v, so both flags are true. They're
// the enforced contract (Video/Animate pickers + submit filter on them), not a
@@ -110,7 +140,10 @@ export const CLOUD_MODEL_SEED: CloudModel[] = [
{ id: 'flux-lora-trainer', label: 'Flux Character Training', kind: 'image', ops: ['lora-train'] },
{ id: 'z-image-lora-trainer', label: 'Z-Image Character Training', kind: 'image', ops: ['lora-train'] },
{ id: 'qwen-image-lora-trainer', label: 'Qwen Character Training', kind: 'image', ops: ['lora-train'] },
- { id: 'ltx-2-video-lora-trainer', label: 'LTX-2 Video Character Training', kind: 'video', ops: ['lora-train'], t2v: false, i2v: false },
+ // uselu 5be5dec3 (15.09.2026): der LTX-Video-Trainer verlangt Videos als
+ // Trainingsmaterial, diese Oberflaeche laedt nur Fotos hoch. Bewusst NICHT
+ // mitgefuehrt, kein Rueckstand: "do not advertise an input contract this
+ // client cannot satisfy" (Web-Kommentar an derselben Stelle).
{ id: 'flux-schnell-lora', label: 'Flux Schnell + Character', kind: 'image', ops: ['generate'], lora: true, cfg: true },
{ id: 'flux-dev-lora-ultra-fast', label: 'Flux Dev Fast + Character', kind: 'image', ops: ['generate'], lora: true, cfg: true },
{ id: 'z-image-turbo-lora', label: 'Z-Image Turbo + Character', kind: 'image', ops: ['generate'], lora: true },
diff --git a/src/lib/render/runtime-format.ts b/src/lib/render/runtime-format.ts
new file mode 100644
index 00000000..e7443084
--- /dev/null
+++ b/src/lib/render/runtime-format.ts
@@ -0,0 +1,16 @@
+// Die clientseitige Haelfte der Laufzeiten.
+//
+// Getrennt von runtime-stats.ts, weil das Messen `next/headers` braucht und
+// ein Client-Bundle daran zerbricht. Hier steht nur, was beide Seiten lesen
+// duerfen: die Form der Zahl und wie sie geschrieben wird.
+
+export interface ModelRuntime { seconds: number; samples: number }
+
+/** Unter so vielen Laeufen sagen wir gar nichts, statt zu raten. */
+export const MIN_SAMPLES = 3
+
+/** "about 45 sec" / "about 3 min". Kurz genug, um neben dem Preis zu stehen. */
+export function humanRuntime(seconds: number): string {
+ if (seconds < 90) return `about ${Math.max(5, Math.round(seconds / 5) * 5)} sec`
+ return `about ${Math.max(2, Math.round(seconds / 60))} min`
+}
diff --git a/src/stores/__tests__/cloudCatalogStore-studio-price.test.ts b/src/stores/__tests__/cloudCatalogStore-studio-price.test.ts
new file mode 100644
index 00000000..797a32cd
--- /dev/null
+++ b/src/stores/__tests__/cloudCatalogStore-studio-price.test.ts
@@ -0,0 +1,92 @@
+import { describe, it, expect, beforeEach } from 'vitest'
+import { useCloudCatalogStore, runCredits } from '../cloudCatalogStore'
+import { CLOUD_MODEL_SEED } from '../../lib/render/cloud-models'
+import type { CloudCatalog } from '../../api/cloud/catalog'
+
+// P3: der Preisfall fuer den Studio-Zweig und by_duration in runCredits().
+//
+// Studio-Modelle duerfen NIE aus dieser Funktion einen Preis bekommen: der
+// Anbieter bestaetigt ihn live ueber studioQuote() (src/api/cloud/studio.ts),
+// alles andere waere die zweite Preiswahrheit, vor der Portplan Abschnitt 7
+// (Risiko 1) warnt. by_duration lohnt sich, sobald der Katalog eine Laenge
+// fuehrt, die weder die kurze noch die lange Stufe ist.
+
+const studioCatalog: CloudCatalog = {
+ models: [
+ {
+ id: 'preset-horror',
+ label: 'Horror Creature',
+ kind: 'image',
+ quote_required: true,
+ pricing: { mode: 'output', rates: { default: 0.02 } },
+ },
+ {
+ id: 'wan-9',
+ label: 'Wan 9',
+ kind: 'video',
+ clip: { short: 5, long: 8, durations: [3, 5, 8, 10] },
+ credits: { base: 8000, long: 13000, by_duration: { '3': 4800, '5': 8000, '8': 13000, '10': 16200 } },
+ },
+ ],
+ ops: {
+ removebg: 1000,
+ eraser: 2500,
+ upscale_image: 1000,
+ upscale_video_per_s: 500,
+ upscale_video_min: 2500,
+ },
+ voice: { stt: 600, tts_per_1k_chars: 8000 },
+ media_live: true,
+ tier: 'hosted-max',
+ monthly_credits: 2_550_000,
+}
+
+beforeEach(() => {
+ useCloudCatalogStore.setState({
+ fetchedAt: null,
+ models: CLOUD_MODEL_SEED,
+ ops: null,
+ voice: null,
+ mediaLive: null,
+ })
+})
+
+describe('runCredits, Studio-Zweig', () => {
+ it('never prices a quote_required model itself, it returns the caller-supplied fallback', () => {
+ useCloudCatalogStore.getState().setCatalog(studioCatalog)
+ // Negativkontrolle: ein erfundener, klar unterscheidbarer Fallback-Wert.
+ // Kaeme runCredits doch bei einer eigenen Formel heraus, waere die Zahl
+ // hier so gut wie sicher eine andere als 777777.
+ expect(runCredits('image', 'generate', 'preset-horror', undefined, 777_777)).toBe(777_777)
+ })
+
+ it('a classic model right next to a Studio one in the same catalog still prices normally', () => {
+ useCloudCatalogStore.getState().setCatalog(studioCatalog)
+ expect(runCredits('video', 'generate', 'wan-9', 5, 1)).toBe(8000)
+ })
+})
+
+describe('runCredits, by_duration', () => {
+ it('prices an exact catalog length precisely, not rounded onto short/long', () => {
+ useCloudCatalogStore.getState().setCatalog(studioCatalog)
+ expect(runCredits('video', 'generate', 'wan-9', 3, 1)).toBe(4800)
+ expect(runCredits('video', 'generate', 'wan-9', 10, 1)).toBe(16200)
+ })
+
+ it('falls back to the base/long split for a length the by_duration table does not carry', () => {
+ useCloudCatalogStore.getState().setCatalog(studioCatalog)
+ // 6 ist im Katalog nicht gelistet: weder kurz (5) noch die Schwelle 6.5
+ // fuer "long" erreicht, also der Basissatz.
+ expect(runCredits('video', 'generate', 'wan-9', 6, 1)).toBe(8000)
+ })
+
+ it('an older catalog without by_duration keeps the pre-P3 base/long behaviour', () => {
+ useCloudCatalogStore.setState({
+ models: [
+ { id: 'wan-old', label: 'Wan Old', kind: 'video', clip: { short: 5, long: 8 }, credits: { base: 8000, long: 13000 } },
+ ],
+ })
+ expect(runCredits('video', 'generate', 'wan-old', 5, 1)).toBe(8000)
+ expect(runCredits('video', 'generate', 'wan-old', 8, 1)).toBe(13000)
+ })
+})
diff --git a/src/stores/cloudCatalogStore.ts b/src/stores/cloudCatalogStore.ts
index b5f7d9d1..8a7c5ba0 100644
--- a/src/stores/cloudCatalogStore.ts
+++ b/src/stores/cloudCatalogStore.ts
@@ -181,6 +181,15 @@ export function runCredits(
fallback: number,
resolution?: string,
): number {
+ // P3, Studio-Zweig: a Studio model (`quote_required` on the catalog entry)
+ // prices live from POST /api/jobs/studio-quote, see studio.ts and
+ // studio-contract.ts's own `studioCredits()` formula, which is a PREVIEW,
+ // not this function's job. Computing anything below for one would drift
+ // from the provider's real price the moment it changes there, and a run
+ // must never book a different number than what got shown, so this guard
+ // sits before every other branch and returns the caller's own fallback
+ // instead of guessing (Portplan Abschnitt 7, Risiko 1).
+ if (cloudModelById(pickedModel)?.quote_required) return fallback
const { ops } = useCloudCatalogStore.getState()
// Music bills per second: catalog per_s × the requested duration (60 s
// default, mirroring the server's MUSIC_SECONDS fallback).
@@ -204,6 +213,15 @@ export function runCredits(
const model = modelForOp(kind, op, pickedModel)
const credits = cloudModelById(model)?.credits
if (!credits) return fallback
+ // P3, by_duration: dd29f359 lets a video model book any advertised length,
+ // not just the short/long pair; an exact catalog price for the requested
+ // length beats rounding it onto one of the two buckets below. Falls
+ // through to the base/long split when the catalog carries no per-duration
+ // table yet (older payload) or no entry for this exact length.
+ if (kind === 'video' && seconds !== undefined && credits.by_duration) {
+ const exact = credits.by_duration[String(seconds)]
+ if (exact !== undefined) return exact
+ }
return kind === 'video' && seconds !== undefined && seconds >= 6.5
? (credits.long ?? credits.base)
: credits.base