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
feat(create): P5 Studio-Zustand und Galerienamen im Desktop-Store
purple0d216ec4a98e
diff --git a/src/api/cloud/jobs.ts b/src/api/cloud/jobs.tsindex 82afe3dc..c4c13198 100644--- a/src/api/cloud/jobs.ts+++ b/src/api/cloud/jobs.ts@@ -8,6 +8,29 @@ import type { RenderOp } from '../../lib/render/cloud-jobs'export interface CloudJobParams {op: RenderOp+ // ── Studio (2026-09): a schema-driven step booked against a server-+ // confirmed quote rather than one of the fixed shapes below. ──+ /** Idempotency key (a UUID minted client-side): a retried submit after a+ * dropped response replays the same job instead of booking twice. */+ client_request_id?: string+ /** The picked step's option values, validated client-side against the same+ * provider schema studio-contract.ts reads (createStore.cloudStudioOptions). */+ studio_options?: Record<string, unknown>+ /** Ceiling from the last confirmed studio-quote; the server re-quotes and+ * answers 409 quote_changed (see QuoteChangedError) if its own number now+ * exceeds this — never books a price the customer never saw. */+ max_credits?: number+ /** Kurze Ueberschrift fuer die Galerie, wenn der Lauf keinen Prompt hat oder+ * der Prompt nicht sagt, was dabei herauskam: der Titel eines Presets, die+ * Beschreibung eines Schrittes. Hoechstens 120 Zeichen, der Server kuerzt. */+ label?: string+ /** Second staged audio input (a Studio step that mixes two tracks). */+ audio2_path?: string+ /** Last frame of a prior step's clip, chained in as this step's image. */+ last_image_path?: string+ /** wan i2v: single shot or a multi-shot cut. Mapped only where the endpoint+ * schema carries the field; the worker checks the same schema. */+ shot_type?: 'single' | 'multi'negative_prompt?: stringwidth?: numberheight?: number@@ -56,6 +79,11 @@ export interface CloudJob {started_at?: string | nullcompleted_at: string | nullerror: string | null+ // Die Anzeigefelder, die die Listenroute (GET /api/jobs) aus den params+ // herausreicht, damit eine neu geladene Galerie den Namen des Laufs+ // wiederherstellt statt jedesmal leer anzufangen.+ prompt?: string+ label?: string}export interface CloudMe {@@ -96,14 +124,51 @@ export async function uploadInput(return path}+export interface CloudJobSubmitResult {+ id: string+ /** A submit retried with the same client_request_id (CloudJobParams) hits+ * the server's idempotency check and replays the original booking instead+ * of charging twice — `used`/`limit` are not recomputed for a replay, only+ * `cost` is guaranteed. */+ quota: { cost: number; used?: number; limit?: number }+ replayed?: boolean+}++/** The server re-quoted at submit time (prepareStudio()) and its own number+ * now exceeds the studio-quote price the customer confirmed. Distinct from+ * a plain CloudJobError so a Studio caller can show the new price instead of+ * a generic failure — see Portplan Abschnitt 4 and Risiko 1. */+export class QuoteChangedError extends CloudJobError {+ readonly credits: number+ constructor(message: string, credits: number) {+ super(message, 409, { code: 'quote_changed' })+ this.credits = credits+ }+}+export async function submitCloudJob(submit: CloudJobSubmit,-): Promise<{ id: string; quota: { cost: number; used: number; limit: number } }> {+): Promise<CloudJobSubmitResult> {const res = await cloudFetch('/api/jobs', {method: 'POST',headers: { 'content-type': 'application/json' },body: JSON.stringify(submit),})+ if (res.status === 409) {+ // Read by hand rather than through jsonOrError: only this one status+ // carries the extra `credits` figure QuoteChangedError needs, and every+ // other 409 (a plain conflict) must still surface as a normal+ // CloudJobError with the server's own message.+ const raw = await res.text().catch(() => '')+ let body: unknown = {}+ try { if (raw.trim()) body = JSON.parse(raw) } catch { /* falls through below */ }+ const b = body as { error?: unknown; code?: unknown; credits?: unknown }+ const msg = typeof b.error === 'string' ? b.error : 'request failed (409)'+ if (b.code === 'quote_changed' && typeof b.credits === 'number') {+ throw new QuoteChangedError(msg, b.credits)+ }+ throw new CloudJobError(msg, 409, { code: typeof b.code === 'string' ? b.code : undefined })+ }return jsonOrError(res)}diff --git a/src/components/create/experimental/CreatePanel.tsx b/src/components/create/experimental/CreatePanel.tsxindex fb5c2a45..5b06235e 100644--- a/src/components/create/experimental/CreatePanel.tsx+++ b/src/components/create/experimental/CreatePanel.tsx@@ -2,6 +2,7 @@ import { motion, AnimatePresence } from 'framer-motion'import { Images, Play, PanelRightClose, Trash2, Download, MonitorOff, AudioLines } from 'lucide-react'import { downloadMediaUrl } from '../../../lib/download-media'import { useCreateStore, type GalleryItem } from '../../../stores/createStore'+import { galleryLabel } from '../../../lib/render/gallery-label'import { galleryItemUrl } from './galleryUrl'import { useComfyMedia } from './useComfyMedia'import { cn } from '../ui/cn'@@ -158,7 +159,7 @@ function GalleryThumb({ g }: { g: GalleryItem }) {return (<span className="w-full h-full flex flex-col items-center justify-center gap-1 bg-white/[0.03] text-gray-400 p-1"><AudioLines size={16} />- <span className="t-label truncate max-w-full px-1">{g.prompt || 'Audio'}</span>+ <span className="t-label truncate max-w-full px-1">{galleryLabel(g)}</span></span>)}diff --git a/src/components/create/experimental/OutputView.tsx b/src/components/create/experimental/OutputView.tsxindex 57cd84a6..895d1ad9 100644--- a/src/components/create/experimental/OutputView.tsx+++ b/src/components/create/experimental/OutputView.tsx@@ -8,27 +8,35 @@ import { isMlxImageHost } from '../../../api/mlx-image'import { refreshResultUrl } from '../../../api/cloud/jobs'import { ICON_LG, ICON_STROKE_MARK } from '../../ui/icon-size'import { markGalleryItemAvailable } from './galleryUrl'+import { galleryLabel } from '../../../lib/render/gallery-label'import { useComfyMedia } from './useComfyMedia'import { cn } from '../ui/cn'// The icon in the waiting circle says which PHASE the render is in, never// which device it runs on. The chip is the loading phase, the spark is-// sampling. R14 Nebenbefund 2 read the chip as a CPU marker that had gone-// missing, because the R13 screenshot caught a load and the R14 pair caught-// two samplings. Checked in git: this mapping has not changed since the-// surface was ported (eaeff304, 2026-07-04), so nothing was lost. The device-// is said in words, by the line at the top of the Create tab.+// sampling/idle, the arrow is decoding. R14 Nebenbefund 2 read the chip as a+// CPU marker that had gone missing, because the R13 screenshot caught a load+// and the R14 pair caught two samplings. The device is said in words, by the+// line at the top of the Create tab.//-// Das Chipsymbol und sein Ring waren gelb. Das war Schmuck fuer eine Phase-// und nie eine Warnung, und genau solche Stellen haben Gelb in der App-// bedeutungslos gemacht. Jetzt Sky, weil es im Wartekreis noch frei war:-// Gruen gehoert dem Sampling, der Akzent dem Dekodieren, Grau dem Warten.-// Die Regel dazu steht in lib/hinweis.ts.+// 19.09.2026, Entscheid von David: das Warten traegt dasselbe Lila wie der+// Rest der App, damit sichtbar ist, dass da etwas passiert. Sky fuer Laden,+// Gruen fuer Sampling waren Schmuck fuer eine Phase, keine Warnung, und genau+// solche Stellen haben Farbe in der App bedeutungslos gemacht — die Phase sagt+// jetzt allein das Symbol, nicht mehr die Farbe.function phaseIcon(phase: ProgressPhase) {- if (phase === 'loading-model' || phase === 'loading-clip' || phase === 'loading-vae') return <Cpu size={20} className="text-sky-300" />- if (phase === 'sampling') return <Sparkles size={20} className="text-green-300" />+ if (phase === 'loading-model' || phase === 'loading-clip' || phase === 'loading-vae') return <Cpu size={20} className="text-lu-accent" />if (phase === 'decoding') return <ImageDown size={20} className="text-lu-accent" />- return <Sparkles size={20} className="text-gray-400" />+ return <Sparkles size={20} className="text-lu-accent" />+}++// Wie schnell die Wellen laufen, sagt die Phase weiterhin. Laden ist der+// laengste, unbestimmte Schritt (der langsamste Takt), Sampling der+// sichtbarste Fortschritt (der schnellste).+function phaseBeat(phase: ProgressPhase): number {+ if (phase === 'loading-model' || phase === 'loading-clip' || phase === 'loading-vae') return 3+ if (phase === 'sampling') return 1.2+ return 2}/**@@ -62,33 +70,37 @@ export function GeneratingView() {const progressText = useCreateStore((s) => s.progressText)const progress = useCreateStore((s) => s.progress)const isLoading = progressPhase === 'loading-model' || progressPhase === 'loading-clip' || progressPhase === 'loading-vae'+ const beat = phaseBeat(progressPhase)return (<div className="flex-1 flex flex-col items-center justify-center p-8"><div className="space-y-6 flex flex-col items-center"><div className="relative w-16 h-16">- {isLoading ? (- <>- <motion.div className="absolute inset-0 rounded-full border border-sky-400/30" animate={{ scale: [1, 1.6], opacity: [0.5, 0] }} transition={{ duration: 3, repeat: Infinity, ease: 'easeOut' }} />- <div className="absolute inset-0 rounded-full border border-sky-400/20 flex items-center justify-center">- <motion.div animate={{ rotate: 360 }} transition={{ duration: 3, repeat: Infinity, ease: 'linear' }}>{phaseIcon(progressPhase)}</motion.div>- </div>- </>- ) : progressPhase === 'sampling' ? (- <>- <motion.div className="absolute inset-0 rounded-full border border-green-400/30" animate={{ scale: [1, 1.8], opacity: [0.4, 0] }} transition={{ duration: 1.2, repeat: Infinity, ease: 'easeOut' }} />- <motion.div className="absolute inset-0 rounded-full border border-green-400/20" animate={{ scale: [1, 1.5], opacity: [0.3, 0] }} transition={{ duration: 1.2, repeat: Infinity, ease: 'easeOut', delay: 0.3 }} />- <div className="absolute inset-0 rounded-full border border-green-400/10 flex items-center justify-center">{phaseIcon(progressPhase)}</div>- </>- ) : (- <>- <motion.div className="absolute inset-0 rounded-full border border-white/20" animate={{ scale: [1, 1.8], opacity: [0.4, 0] }} transition={{ duration: 2, repeat: Infinity, ease: 'easeOut' }} />- <motion.div className="absolute inset-0 rounded-full border border-white/15" animate={{ scale: [1, 1.5], opacity: [0.3, 0] }} transition={{ duration: 2, repeat: Infinity, ease: 'easeOut', delay: 0.5 }} />- <div className="absolute inset-0 rounded-full border border-white/10 flex items-center justify-center">{phaseIcon(progressPhase)}</div>- </>- )}+ {/* Der Schein dahinter. Er atmet langsamer als die Wellen, sonst+ flackert die ganze Flaeche im Takt mit. */}+ <motion.div+ aria-hidden+ className="absolute -inset-8 rounded-full bg-lu-accent/25 blur-2xl"+ animate={{ opacity: [0.3, 0.7, 0.3] }}+ transition={{ duration: beat * 2, repeat: Infinity, ease: 'easeInOut' }}+ />+ {[0, 1, 2].map((i) => (+ <motion.div+ key={i}+ aria-hidden+ className="absolute inset-0 rounded-full border border-lu-accent/45"+ style={{ boxShadow: '0 0 16px rgba(160, 148, 248, 0.45)' }}+ animate={{ scale: [1, 1.95], opacity: [0.6, 0] }}+ transition={{ duration: beat, repeat: Infinity, ease: 'easeOut', delay: (beat / 3) * i }}+ />+ ))}+ <div className="absolute inset-0 rounded-full border border-lu-accent/30 bg-lu-accent/[0.07] flex items-center justify-center" style={{ boxShadow: '0 0 24px rgba(160, 148, 248, 0.3) inset' }}>+ {isLoading ? (+ <motion.div animate={{ rotate: 360 }} transition={{ duration: 3, repeat: Infinity, ease: 'linear' }}>{phaseIcon(progressPhase)}</motion.div>+ ) : phaseIcon(progressPhase)}+ </div></div>- <p className="t-body text-gray-400 tracking-wide">{progressText || 'Generating…'}</p>+ <p className="t-body text-gray-300 tracking-wide">{progressText || 'Generating…'}</p>{isLoading && !isMlxImageHost() && <ColdLoadLine />}{progress > 0 && (<div className="w-56 h-1 bg-white/10 rounded-full overflow-hidden">@@ -235,9 +247,7 @@ export function ResultView({ item, onFullscreen, onSendToEditor, onAnimate }: Re{isAudio ? (<div className="w-[420px] max-w-full flex flex-col items-center gap-3 p-6 rounded-[var(--radius-panel)] border border-white/[0.06] bg-white/[0.02]"><AudioLines size={26} className="text-gray-400" strokeWidth={ICON_STROKE_MARK} />- {item.prompt && (- <p className="t-body text-gray-400 text-center line-clamp-2">{item.prompt}</p>- )}+ <p className="t-body text-gray-400 text-center line-clamp-2">{galleryLabel(item)}</p><audio src={url} controls onError={onError} className="w-full" onLoadedData={() => markGalleryItemAvailable(item)} /></div>) : isVideo ? (diff --git a/src/components/create/experimental/__tests__/waiting-icon-is-a-phase-icon.test.ts b/src/components/create/experimental/__tests__/waiting-icon-is-a-phase-icon.test.tsindex c3a20c54..8641eff2 100644--- a/src/components/create/experimental/__tests__/waiting-icon-is-a-phase-icon.test.ts+++ b/src/components/create/experimental/__tests__/waiting-icon-is-a-phase-icon.test.ts@@ -16,6 +16,15 @@* call it a repair. The device is stated in words by the Create tab banner* (comfyCpuBannerText), which round 14 made honest.*+ * 19.09.2026 (Portplan Studio, Paket P5): David dropped the per-phase COLOR+ * (sky for loading, green for sampling) in favor of one lu-accent purple+ * everywhere, "damit sichtbar ist, dass da etwas passiert" — see+ * OutputView.tsx's phaseIcon/phaseBeat. Sampling and idle always rendered the+ * same Sparkles icon as the fallback branch, so the now-pointless standalone+ * `phase === 'sampling'` check was dropped with the color, not the mapping:+ * the assertion below follows that fallback instead of a branch that no+ * longer exists.+ ** Run: npx vitest run src/components/create/experimental/__tests__/waiting-icon-is-a-phase-icon.test.ts*/import { describe, it, expect } from 'vitest'@@ -36,12 +45,16 @@ const body = (() => {})()describe('the waiting circle icon', () => {- it('marks the loading phases with the chip and sampling with the spark', () => {+ it('marks the loading phases with the chip and sampling (the fallback) with the spark', () => {expect(body).toMatch(/phase === 'loading-model'[\s\S]*?<Cpu /)expect(body).toMatch(/phase === 'loading-clip'/)expect(body).toMatch(/phase === 'loading-vae'/)- expect(body).toMatch(/phase === 'sampling'[\s\S]*?<Sparkles /)expect(body).toMatch(/phase === 'decoding'[\s\S]*?<ImageDown /)+ // No standalone 'sampling' branch any more — it fell through to the+ // fallback Sparkles before the color unification too, so dropping the+ // dead check changed nothing sampling ever showed.+ expect(body).not.toMatch(/phase === 'sampling'/)+ expect(body).toMatch(/return <Sparkles size=\{20\} className="text-lu-accent" \/>\s*$/)})it('NEGATIVE: it reads no device fact, so it cannot claim one', () => {diff --git a/src/lib/render/__tests__/gallery-label.test.ts b/src/lib/render/__tests__/gallery-label.test.tsnew file mode 100644index 00000000..f9fe5327--- /dev/null+++ b/src/lib/render/__tests__/gallery-label.test.ts@@ -0,0 +1,56 @@+/**+ * Wie ein Eintrag der Galerie heisst.+ *+ * Befund von David, 19.09.2026: "Danach kommt nur noch Cloud-Videos. Man kann+ * gar nicht mehr identifizieren, welches Video denn was ist." Zwei Ursachen,+ * beide hier festgenagelt: ein Eintrag ohne Prompt hatte ueberhaupt keinen+ * Namen, und ein Preset-Ergebnis sagte nicht, aus welchem Preset es kam.+ *+ * Port aus uselu apps/web/lib/render/__tests__/gallery-label.test.ts.+ */+import { describe, expect, it } from 'vitest'+import { galleryLabel, galleryLabelShort } from '../gallery-label'+import type { GalleryItem } from '../../../stores/createStore'++const eintrag = (teil: Partial<GalleryItem>): GalleryItem => ({+ id: 'x', type: 'video', filename: '', subfolder: '', prompt: '', negativePrompt: '',+ model: 'wan-2.2-realism', modelType: 'unknown', seed: 0, steps: 0, cfgScale: 0,+ sampler: '', scheduler: '', width: 0, height: 0, batchSize: 1, createdAt: 0, ...teil,+})++describe('the name of a gallery entry', () => {+ it('never falls back to a name that fits every entry', () => {+ // Genau das war der Fehler: "Cloud video" stand ueber allem.+ const ohneAlles = eintrag({ model: 'gibt-es-nicht' })+ expect(galleryLabel(ohneAlles)).toBe('Clip')+ expect(galleryLabel(eintrag({}))).toBe('Clip · Wan 2.2 Realism')+ expect(galleryLabel(eintrag({ type: 'audio', model: 'gibt-es-nicht' }))).toBe('Audio')+ })++ it('shows the prompt when there is one', () => {+ expect(galleryLabel(eintrag({ prompt: 'a red fox trotting through fresh snow' })))+ .toBe('a red fox trotting through fresh snow')+ })++ it('puts the run and the prompt side by side, so one preset run is not the other', () => {+ expect(galleryLabel(eintrag({ label: 'Horror Creature', prompt: 'a gaunt figure' })))+ .toBe('Horror Creature · a gaunt figure')+ })++ it('names a run that has no prompt at all after what it did', () => {+ expect(galleryLabel(eintrag({ label: 'Extended clip' }))).toBe('Extended clip')+ expect(galleryLabel(eintrag({ intent: 'upscale', model: 'flashvsr' })))+ .toBe('Upscaled · FlashVSR')+ })++ it('never repeats itself when the two say the same', () => {+ expect(galleryLabel(eintrag({ label: 'Track', prompt: 'Track' }))).toBe('Track')+ })++ it('shortens to one line and only then marks the cut', () => {+ const lang = eintrag({ prompt: 'x'.repeat(80) })+ expect(galleryLabelShort(lang)).toHaveLength(41)+ expect(galleryLabelShort(lang).endsWith('…')).toBe(true)+ expect(galleryLabelShort(eintrag({ prompt: 'kurz' }))).toBe('kurz')+ })+})diff --git a/src/lib/render/cloud-jobs.ts b/src/lib/render/cloud-jobs.tsindex 180ba040..d5c7f849 100644--- a/src/lib/render/cloud-jobs.ts+++ b/src/lib/render/cloud-jobs.ts@@ -1,7 +1,17 @@// Desktop port: shared render types + intent mapping. The HTTP client (upload/// submit/poll/cancel against lu-labs.ai) lives in api/cloud/jobs.ts.-import type { CreateIntent } from '../../stores/createStore'+// intentToJob's parameter, kept as a LOCAL literal union rather than an+// `import type { CreateIntent } from '../../stores/createStore'`. createStore+// now imports the cloud catalog (cloudCatalogStore, itself typed against+// RenderKind/RenderOp from this file) for addToGallery's backend gate — a+// type-only import back to createStore here would close that into a module+// cycle (`npm run cycles`, madge, counts type-only edges too). The two sets+// must be kept in sync by hand; CreateIntent in stores/createStore.ts is the+// source of truth.+type CreateIntentLike =+ | 'image' | 'edit' | 'removebg' | 'video' | 'animate' | 'upscale' | 'eraser'+ | 'character' | 'lipsync' | 'music' | 'extend' | 'motion'export type RenderKind = 'image' | 'video' | 'audio'// 'upscale'/'eraser' are WaveSpeed utility endpoints (super-resolution /@@ -9,9 +19,12 @@ export type RenderKind = 'image' | 'video' | 'audio'// 2.5.8 adds the specialized ops behind the new Create categories: 'lipsync'// (talking character), 'extend' (continue a clip), 'motion' (motion transfer,// NOT face-swap — banned), 'music', 'tts' and 'lora-train' (Character-Studio).+// 'studio' (2026-09): the guided Create-Studio path — a schema-driven+// endpoint booked with `studio_options` and a server-confirmed quote, rather+// than one of the fixed param shapes above.export type RenderOp =| 'generate' | 'edit' | 'removebg' | 'animate' | 'upscale' | 'eraser'- | 'lipsync' | 'extend' | 'motion' | 'music' | 'tts' | 'lora-train'+ | 'studio' | 'lipsync' | 'extend' | 'motion' | 'music' | 'tts' | 'lora-train'// One shared compute-credit wallet — text + media draw from the same budget// (server shape: uselu /api/jobs/quota).@@ -41,7 +54,7 @@ export interface CloudQuota {* 'character' maps per characterTab (train vs use) — see useCloudCreate; the* default here is the training op, the use-surface submits a plain image* generate with a `loras` reference. */-export function intentToJob(intent: CreateIntent): { kind: RenderKind; op: RenderOp } {+export function intentToJob(intent: CreateIntentLike): { kind: RenderKind; op: RenderOp } {switch (intent) {case 'edit':return { kind: 'image', op: 'edit' }diff --git a/src/lib/render/gallery-label.ts b/src/lib/render/gallery-label.tsnew file mode 100644index 00000000..18116ee6--- /dev/null+++ b/src/lib/render/gallery-label.ts@@ -0,0 +1,66 @@+// Wie ein Eintrag der Galerie heisst.+//+// 19.09.2026, gemeldet von David: "Danach kommt nur noch Cloud-Videos. Man kann+// gar nicht mehr identifizieren, welches Video denn was ist." Zwei Ursachen:+// die Listenroute gab den Prompt nicht heraus, also hiess nach jedem Neuladen+// alles gleich; und ein Lauf ohne Prompt (Schaerfen, Verlaengern, ein Schritt+// aus einem Preset) hatte ueberhaupt nie einen Namen.+//+// Die Reihenfolge steht hier einmal, und jede Ansicht ruft sie auf. Vorher trug+// jede Stelle ihren eigenen Notnamen ("Cloud video", "Generated audio",+// "Audio"), und keiner davon sagte, was der Eintrag ist.+//+// Port aus uselu apps/web/lib/render/gallery-label.ts: der Desktop haelt den+// Katalog in einem Store statt in einer statischen Liste, deshalb kommt+// cloudModelById hier aus cloudCatalogStore statt aus cloud-models.+import type { GalleryItem } from '../../stores/createStore'+import { STUDIO_MODELS } from './studio-contract'+import { cloudModelById } from '../../stores/cloudCatalogStore'++/** Was der Lauf getan hat, wenn niemand etwas geschrieben hat. */+const OP_NAME: Record<string, string> = {+ removebg: 'Background removed',+ upscale: 'Upscaled',+ eraser: 'Object erased',+ extend: 'Extended clip',+ motion: 'Motion transfer',+ lipsync: 'Talking character',+ 'lora-train': 'Character trained',+}++const TYPE_NAME: Record<GalleryItem['type'], string> = {+ image: 'Image',+ video: 'Clip',+ audio: 'Audio',+}++function modelLabel(id: string): string | undefined {+ return STUDIO_MODELS[id]?.label ?? cloudModelById(id)?.label+}++/** Der Name des Eintrags. Nie leer: eine Kachel ohne Namen ist von der+ * daneben nicht zu unterscheiden, und genau das war der Fehler. */+export function galleryLabel(item: GalleryItem): string {+ const prompt = item.prompt?.trim()+ const label = item.label?.trim()+ // Beides, wenn es beides gibt: der Titel sagt, was der Lauf war, der Prompt+ // sagt, welcher von den dreien es ist. David am 19.09.2026 zum Ergebnis+ // eines Presets: "das Endprodukt soll dann auch als ein Ganzes stehen und+ // erkennbar sein, was es ist."+ if (label && prompt) return label === prompt ? label : `${label} · ${prompt}`+ if (prompt) return prompt+ if (label) return label+ const tat = item.intent ? OP_NAME[item.intent] : undefined+ const modell = modelLabel(item.model)+ if (tat) return modell ? `${tat} · ${modell}` : tat+ // Bleibt nur die Gattung, dann wenigstens mit dem Modell daneben: "Clip ·+ // Wan 2.2 Realism" sagt mehr als "Cloud video" und unterscheidet zwei Laeufe.+ return modell ? `${TYPE_NAME[item.type]} · ${modell}` : TYPE_NAME[item.type]+}++/** Derselbe Name, auf eine Zeile gekuerzt. Das Auslassungszeichen steht nur+ * da, wo wirklich etwas fehlt. */+export function galleryLabelShort(item: GalleryItem, max = 40): string {+ const name = galleryLabel(item)+ return name.length > max ? `${name.slice(0, max).trimEnd()}…` : name+}diff --git a/src/stores/__tests__/createStore-migrate.test.ts b/src/stores/__tests__/createStore-migrate.test.tsindex 3401f6df..be80cb2e 100644--- a/src/stores/__tests__/createStore-migrate.test.ts+++ b/src/stores/__tests__/createStore-migrate.test.ts@@ -34,7 +34,7 @@ async function freshStore() {return mod.useCreateStore}-describe('createStore persist migration (v0 → v1)', () => {+describe('createStore persist migration (v0 → v2)', () => {beforeEach(() => localStorage.clear())it('migrates an unversioned v0 blob with mode "i2i" to image/img2img', async () => {@@ -62,12 +62,12 @@ describe('createStore persist migration (v0 → v1)', () => {expect(store.getState().source).toBeNull()})- it('writes version 1 back to storage after rehydrate', async () => {+ it('writes version 2 back to storage after rehydrate', async () => {seedStorage({ mode: 'i2i' })const store = await freshStore()store.getState().setSteps(21)const raw = JSON.parse(localStorage.getItem(KEY) ?? '{}')- expect(raw.version).toBe(1)+ expect(raw.version).toBe(2)expect(raw.state.mode).toBe('image')})})diff --git a/src/stores/__tests__/createStore-studio.test.ts b/src/stores/__tests__/createStore-studio.test.tsnew file mode 100644index 00000000..eb967928--- /dev/null+++ b/src/stores/__tests__/createStore-studio.test.ts@@ -0,0 +1,232 @@+/**+ * Studio-Felder von createStore (Portplan Abschnitt 3e/3f, Paket P5).+ *+ * Vier Faelle, die David/der Plan als Waechter verlangen:+ * 1. Ein Zustand der Version 1 (vor dem Studio) liest cloudStudioOptions als+ * {} ein, nie als undefined — sonst faellt Object.entries() im Composer.+ * 2. Ein LOKALER Lauf laesst den Cloud-Modellwaehler in Ruhe: im Desktop+ * landen in derselben Galerie auch ComfyUI-/MLX-Ergebnisse, anders als im+ * Web, das keine lokale Spur kennt.+ * 3. setCloudOpModel wirft die Studio-Optionen weg (ein liegen gebliebener+ * Wert waere beim naechsten Endpunkt vielleicht nicht erlaubt).+ * 4. mergeGallery ueberschreibt nie einen vorhandenen Prompt/Label.+ */+import { describe, it, expect, vi, beforeEach } from 'vitest'++// Gleiches Muster wie createStore.test.ts / createStore-migrate.test.ts:+// zustand/persist braucht window.localStorage schon beim Laden des Moduls.+vi.hoisted(() => {+ const map = new Map<string, string>()+ const ls = {+ getItem: (k: string) => (map.has(k) ? map.get(k)! : null),+ setItem: (k: string, v: string) => { map.set(k, String(v)) },+ removeItem: (k: string) => { map.delete(k) },+ clear: () => { map.clear() },+ key: (i: number) => [...map.keys()][i] ?? null,+ get length() { return map.size },+ }+ ;(globalThis as unknown as { localStorage: unknown }).localStorage = ls+ const g = globalThis as unknown as { window?: Record<string, unknown> }+ g.window = Object.assign(g.window ?? {}, { localStorage: ls })+})++vi.mock('../../api/mlx-image', () => ({ isMlxImageHost: () => false, MLX_MODEL_PREFIX: 'MLX ' }))+vi.mock('../../api/comfyui', () => ({+ classifyModel: vi.fn(() => 'unknown'),+}))++import { useCreateStore } from '../createStore'+import type { GalleryItem } from '../createStore'++const makeGalleryItem = (id: string, patch: Partial<GalleryItem> = {}): GalleryItem => ({+ id,+ type: 'image',+ filename: `${id}.png`,+ subfolder: '',+ prompt: 'test',+ negativePrompt: '',+ model: 'flux-schnell',+ modelType: 'unknown',+ seed: 42,+ steps: 20,+ cfgScale: 7,+ sampler: 'euler',+ scheduler: 'normal',+ width: 1024,+ height: 1024,+ batchSize: 1,+ createdAt: Date.now(),+ ...patch,+})++describe('createStore Studio fields', () => {+ beforeEach(() => {+ localStorage.clear()+ useCreateStore.setState({+ gallery: [],+ backend: 'local',+ cloudImageModel: '',+ cloudVideoModel: '',+ cloudOpModel: '',+ cloudStudioOptions: {},+ cloudStudioCredits: null,+ })+ })++ // ── 1. Persistenzfall: Version 1 -> Version 2 ──────────────────++ describe('a version-1 blob rehydrates cloudStudioOptions as {}', () => {+ const KEY = 'create-store'++ async function freshStoreFrom(state: Record<string, unknown>, version?: number) {+ localStorage.setItem(KEY, JSON.stringify(version === undefined ? { state } : { state, version }))+ vi.resetModules()+ const mod = await import('../createStore')+ return mod.useCreateStore+ }++ it('a pre-Studio (version 1) blob without the field reads {} and null, never undefined', async () => {+ const store = await freshStoreFrom({ mode: 'image', steps: 33 }, 1)+ const s = store.getState()+ expect(s.cloudStudioOptions).toEqual({})+ expect(s.cloudStudioCredits).toBeNull()+ // The Composer calls Object.entries() on this straight away — must+ // never throw on an old blob.+ expect(() => Object.entries(s.cloudStudioOptions)).not.toThrow()+ expect(Object.entries(s.cloudStudioOptions)).toEqual([])+ })++ it('a version-1 blob that already carries an explicit undefined is caught too', async () => {+ const store = await freshStoreFrom(+ { mode: 'image', cloudStudioOptions: undefined, cloudStudioCredits: undefined },+ 1,+ )+ const s = store.getState()+ expect(s.cloudStudioOptions).toEqual({})+ expect(s.cloudStudioCredits).toBeNull()+ })++ it('a version-2 blob keeps its own saved options across a reload', async () => {+ const store = await freshStoreFrom(+ { mode: 'image', cloudStudioOptions: { duration: 8 } },+ 2,+ )+ expect(store.getState().cloudStudioOptions).toEqual({ duration: 8 })+ })++ it('a saved price never rehydrates, at any version — a price from yesterday is a lie', async () => {+ const store = await freshStoreFrom(+ { mode: 'image', cloudStudioCredits: 4200 },+ 2,+ )+ expect(store.getState().cloudStudioCredits).toBeNull()+ })++ it('writes version 2 into storage after the first change', async () => {+ const store = await freshStoreFrom({ mode: 'image' }, 1)+ store.getState().setSteps(11)+ const raw = JSON.parse(localStorage.getItem(KEY) ?? '{}')+ expect(raw.version).toBe(2)+ })+ })++ // ── 2. addToGallery: nur die Wolken-Spur stellt den Waehler um ─++ describe('addToGallery only steers the cloud model picker on the cloud backend', () => {+ it('a local render leaves cloudImageModel untouched', () => {+ useCreateStore.setState({ backend: 'local', cloudImageModel: 'stays-as-is' })+ useCreateStore.getState().addToGallery(makeGalleryItem('local-1', { model: 'flux-schnell' }))+ expect(useCreateStore.getState().cloudImageModel).toBe('stays-as-is')+ })++ it('a local video render leaves cloudVideoModel untouched too', () => {+ useCreateStore.setState({ backend: 'local', cloudVideoModel: 'stays-as-is' })+ useCreateStore.getState().addToGallery(makeGalleryItem('local-2', { type: 'video', model: 'wan-2.2-720p' }))+ expect(useCreateStore.getState().cloudVideoModel).toBe('stays-as-is')+ })++ it('a cloud image render DOES steer cloudImageModel to the model that made it', () => {+ useCreateStore.setState({ backend: 'cloud', cloudImageModel: 'flux-dev' })+ useCreateStore.getState().addToGallery(makeGalleryItem('cloud-1', { model: 'flux-schnell' }))+ expect(useCreateStore.getState().cloudImageModel).toBe('flux-schnell')+ })++ it('a cloud video render steers cloudVideoModel the same way', () => {+ useCreateStore.setState({ backend: 'cloud', cloudVideoModel: 'wan-2.2-fast' })+ useCreateStore.getState().addToGallery(makeGalleryItem('cloud-2', { type: 'video', model: 'wan-2.2-720p' }))+ expect(useCreateStore.getState().cloudVideoModel).toBe('wan-2.2-720p')+ })++ it('the gallery item still lands regardless of backend', () => {+ useCreateStore.setState({ backend: 'local' })+ useCreateStore.getState().addToGallery(makeGalleryItem('local-3'))+ expect(useCreateStore.getState().gallery).toHaveLength(1)+ expect(useCreateStore.getState().gallery[0].id).toBe('local-3')+ })+ })++ // ── 3. setCloudOpModel wirft die Studio-Optionen weg ────────────++ describe('setCloudOpModel', () => {+ it('clears cloudStudioOptions on every model switch', () => {+ useCreateStore.setState({ cloudStudioOptions: { duration: 5, voice: 'x' } })+ useCreateStore.getState().setCloudOpModel('infinitetalk-fast')+ expect(useCreateStore.getState().cloudOpModel).toBe('infinitetalk-fast')+ expect(useCreateStore.getState().cloudStudioOptions).toEqual({})+ })++ it('does not touch cloudStudioCredits (a stale price is cleared by a fresh quote, not by a model switch)', () => {+ useCreateStore.setState({ cloudStudioCredits: 900 })+ useCreateStore.getState().setCloudOpModel('infinitetalk-fast')+ expect(useCreateStore.getState().cloudStudioCredits).toBe(900)+ })+ })++ // ── 4. mergeGallery ueberschreibt nie ────────────────────────────++ describe('mergeGallery', () => {+ it('backfills a missing prompt/label on an existing item, never overwriting one that is already there', () => {+ useCreateStore.setState({+ gallery: [makeGalleryItem('j1', { jobId: 'j1', prompt: '', label: undefined, createdAt: 1000 })],+ })+ useCreateStore.getState().mergeGallery([+ makeGalleryItem('j1', { jobId: 'j1', prompt: 'a red fox', label: 'Horror Creature', createdAt: 1000 }),+ ])+ const item = useCreateStore.getState().gallery.find((g) => g.jobId === 'j1')+ expect(item?.prompt).toBe('a red fox')+ expect(item?.label).toBe('Horror Creature')+ })++ it('never overwrites a prompt/label the customer already saw', () => {+ useCreateStore.setState({+ gallery: [makeGalleryItem('j2', { jobId: 'j2', prompt: 'old prompt', label: 'Old Label', createdAt: 2000 })],+ })+ useCreateStore.getState().mergeGallery([+ makeGalleryItem('j2', { jobId: 'j2', prompt: 'new prompt', label: 'New Label', createdAt: 2000 }),+ ])+ const item = useCreateStore.getState().gallery.find((g) => g.jobId === 'j2')+ expect(item?.prompt).toBe('old prompt')+ expect(item?.label).toBe('Old Label')+ })++ it('adds an unknown job with the servers metadata', () => {+ useCreateStore.setState({ gallery: [] })+ useCreateStore.getState().mergeGallery([+ makeGalleryItem('j3', { jobId: 'j3', prompt: 'fresh from another device', createdAt: 3000 }),+ ])+ expect(useCreateStore.getState().gallery).toHaveLength(1)+ expect(useCreateStore.getState().gallery[0].prompt).toBe('fresh from another device')+ })++ it('refreshes remoteUrl on an existing item without touching its other fields', () => {+ useCreateStore.setState({+ gallery: [makeGalleryItem('j4', { jobId: 'j4', remoteUrl: 'https://old.example/x', createdAt: 4000 })],+ })+ useCreateStore.getState().mergeGallery([+ makeGalleryItem('j4', { jobId: 'j4', remoteUrl: 'https://fresh.example/x', createdAt: 4000 }),+ ])+ const item = useCreateStore.getState().gallery.find((g) => g.jobId === 'j4')+ expect(item?.remoteUrl).toBe('https://fresh.example/x')+ })+ })+})diff --git a/src/stores/createStore.ts b/src/stores/createStore.tsindex 5217771d..4ebe1c65 100644--- a/src/stores/createStore.ts+++ b/src/stores/createStore.ts@@ -11,12 +11,18 @@ import { isRecord } from '../types/json-guards'*/const RUNTIME_ONLY_KEYS: readonly string[] = ['backend', 'source', 'mask', 'caps', 'isGenerating', 'comfyCorsBlocked',+ // Ein gespeicherter Preis von gestern ist eine Luege (siehe partialize+ // unten): auch wenn ein fremder/aelterer Blob ihn doch mitbringt, darf er+ // nie zurueckkommen.+ 'cloudStudioCredits',]import type { ModelType, ClassifiedModel } from '../api/comfyui'import { classifyModel } from '../api/comfyui'import type { HiresUpscaleMethod } from '../api/hires-fix'import { releaseVideoBlobUrl } from '../api/mlx-video'import { isMlxImageHost } from '../api/mlx-image'+import { STUDIO_MODELS } from '../lib/render/studio-contract'+import { cloudModelsFor } from './cloudCatalogStore'// ModelType includes: flux, flux2, zimage, sdxl, sd15, wan, hunyuan, unknownexport type ProgressPhase = 'idle' | 'queued' | 'loading-model' | 'loading-clip' | 'loading-vae' | 'sampling' | 'decoding' | 'complete'@@ -187,6 +193,9 @@ export interface GalleryItem {jobId?: string/** Which redesign intent produced this item (gallery tagging). */intent?: CreateIntent+ /** Kurze Ueberschrift, wenn der Prompt nicht sagt, was dabei herauskam: der+ * Titel des Presets, die Beschreibung des Schrittes. Siehe gallery-label.ts. */+ label?: string/** MLX video (Mac, Apple Silicon): absolute filesystem path of the finished* mp4, as returned by `video_generate`'s `output` field. Playback/download* go through `dataUrl` (a blob: URL, see above) instead — this is kept@@ -289,6 +298,13 @@ interface CreateState {* (trainer/lipsync/music/extend/motion). One slot for all — modelForOp* coerces a stale cross-intent pick onto the op's own list. */cloudOpModel: string+ /** Studio: the schema-driven option values for the picked cloudOpModel step+ * (studio-contract.ts). Belongs to the model, not the run — a model switch+ * drops them, see setCloudOpModel. */+ cloudStudioOptions: Record<string, unknown>+ /** Studio: the last confirmed studio-quote price, shown next to the start+ * button. Never persisted — a stale price is a lie, see partialize. */+ cloudStudioCredits: number | null/** Runtime-only: the LOCAL model picked inside a specialized lane (ACE* checkpoint / S2V UNet / Animate-VACE UNet). One slot for all lanes —* resolveLocalOpPick coerces a stale cross-lane pick onto the lane's list@@ -379,6 +395,8 @@ interface CreateState {setVideoInput: (m: MediaRef | null) => voidbumpCharactersVersion: () => voidsetCloudOpModel: (id: string) => void+ setCloudStudioOptions: (options: Record<string, unknown>) => void+ setCloudStudioCredits: (credits: number | null) => voidsetLocalOpModel: (name: string) => voidsetAudioModelList: (list: ClassifiedModel[]) => voidsetLipsyncModelList: (list: ClassifiedModel[]) => void@@ -406,6 +424,11 @@ interface CreateState {addToGallery: (item: GalleryItem) => void/** Patch a gallery item in place (e.g. a lazily re-signed remoteUrl). */updateGalleryItem: (id: string, patch: Partial<GalleryItem>) => void+ /** Cloud hydration: merges freshly-listed jobs into the gallery. Existing+ * items (matched by jobId/id) just get a fresh signed URL plus a+ * backfilled prompt/label when they never had one — nothing here ever+ * overwrites what is already on screen. See mergeGallery below. */+ mergeGallery: (items: GalleryItem[]) => voidremoveFromGallery: (id: string) => voidclearGallery: () => voidaddToPromptHistory: (prompt: string) => void@@ -550,6 +573,8 @@ export const useCreateStore = create<CreateState>()(cloudImageModel: '',cloudVideoModel: '',cloudOpModel: '',+ cloudStudioOptions: {} as Record<string, unknown>,+ cloudStudioCredits: null as number | null,localOpModel: '',charactersVersion: 0,caps: { rmbg: false, 'inpaint-nodes': false, dwpose: false } as Record<'rmbg' | 'inpaint-nodes' | 'dwpose', boolean>,@@ -769,7 +794,12 @@ export const useCreateStore = create<CreateState>()(set({ videoInput })},bumpCharactersVersion: () => set((s) => ({ charactersVersion: s.charactersVersion + 1 })),- setCloudOpModel: (cloudOpModel) => set({ cloudOpModel }),+ // Ein Modellwechsel wirft die Studio-Optionen weg: die Felder des einen+ // Endpunkts sind beim naechsten nicht unbedingt erlaubt, und ein+ // uebriggebliebener Wert wuerde das Absenden abweisen.+ setCloudOpModel: (cloudOpModel) => set({ cloudOpModel, cloudStudioOptions: {} }),+ setCloudStudioOptions: (cloudStudioOptions) => set({ cloudStudioOptions }),+ setCloudStudioCredits: (cloudStudioCredits) => set({ cloudStudioCredits }),// Picking a lane model adopts its architecture defaults (like// setVideoModel does) — an inherited 1024×1024 from the Image tab would// OOM a 14B S2V run on consumer VRAM.@@ -865,13 +895,28 @@ export const useCreateStore = create<CreateState>()(setVhsInstallPrompt: (resolver) => set({ vhsInstallPrompt: resolver }),setError: (error) => set({ error }),setLastGenTime: (time) => set({ lastGenTime: time }),+ // Ein frisches Cloud-Ergebnis stellt den Wolken-Modellwaehler auf das+ // Modell, mit dem es entstanden ist, damit man direkt daran+ // weiterarbeiten kann. Ein Studio-Eintrag stellt auf seinen+ // Katalogzwilling (STUDIO_MODELS[...].sourceModel), denn der steht im+ // Waehler; ohne Zwilling bleibt der Waehler, wie er ist.+ //+ // NUR auf der Wolken-Spur: im Desktop landen hier auch lokale ComfyUI-+ // und MLX-Ergebnisse (anders als im Web, das keine lokale Spur kennt),+ // und ein lokaler Lauf darf den Cloud-Waehler nie umstellen (Portplan+ // Abschnitt 3e).addToGallery: (item) => set((s) => {const next = [item, ...s.gallery]// The cap used to drop the oldest renders silently, taking the only// reference to their blob: URLs with them — the bytes stayed pinned// for the rest of the session with nothing left to revoke them by.for (const dropped of next.slice(GALLERY_CAP)) releaseItemMedia(dropped)- return { gallery: next.slice(0, GALLERY_CAP) }+ const gallery = next.slice(0, GALLERY_CAP)+ if (s.backend !== 'cloud') return { gallery }+ const id = STUDIO_MODELS[item.model]?.sourceModel ?? item.model+ if (cloudModelsFor('image').some((m) => m.id === id)) return { gallery, cloudImageModel: id }+ if (cloudModelsFor('video').some((m) => m.id === id)) return { gallery, cloudVideoModel: id }+ return { gallery }}),updateGalleryItem: (id, patch) =>// NOT revoking a replaced dataUrl here on purpose: a patch lands while@@ -879,6 +924,35 @@ export const useCreateStore = create<CreateState>()(// revoking a URL an <img>/<video> may still be loading would break the// very media this patch exists to fix.set((s) => ({ gallery: s.gallery.map((g) => (g.id === id ? { ...g, ...patch } : g)) })),+ // Cloud hydration: the server's job list is the source of truth for+ // hosted renders. Existing items (matched by jobId/id) just get a fresh+ // signed URL plus a backfilled prompt/label when they never had one+ // (an older gallery, from before the list route sent them) — nothing+ // here ever overwrites what is already on screen, so a value the+ // customer already saw cannot jump. Unknown jobs (other device,+ // cleared storage) are added with the server's metadata.+ mergeGallery: (items) => set((s) => {+ const byKey = new Map<string, GalleryItem>()+ for (const g of s.gallery) byKey.set(g.jobId ?? g.id, g)+ for (const it of items) {+ const key = it.jobId ?? it.id+ const prev = byKey.get(key)+ byKey.set(+ key,+ prev+ ? {+ ...prev,+ remoteUrl: it.remoteUrl,+ attestation: it.attestation,+ prompt: prev.prompt || it.prompt,+ label: prev.label ?? it.label,+ }+ : it,+ )+ }+ const merged = [...byKey.values()].sort((a, b) => b.createdAt - a.createdAt)+ return { gallery: merged.slice(0, GALLERY_CAP) }+ }),removeFromGallery: (id) => set((s) => {const gone = s.gallery.find((g) => g.id === id)if (gone) releaseItemMedia(gone)@@ -944,15 +1018,43 @@ export const useCreateStore = create<CreateState>()(musicHowtoSeen: state.musicHowtoSeen,triggerWord: state.triggerWord,trainSteps: state.trainSteps,+ // Studio: the picked step's option values are a preference like the+ // ones above. cloudStudioCredits is NOT here on purpose — a saved+ // price from yesterday is a lie, see the field's own doc comment.+ cloudStudioOptions: state.cloudStudioOptions,}),// Future schema bumps hook into migrate. NOTE: zustand only invokes it// when the stored blob carries a NUMERIC version that differs — legacy// pre-version blobs skip it entirely, so their fixups must live in merge.- version: 1,+ //+ // Bumped 1 -> 2 for the Studio fields (Portplan Abschnitt 3f). This+ // stays inside the R1 DOWNGRADE-KONTRAKT (see lib/persist-version.ts):+ // an older build that still declares version 1 already ships its own+ // migrate (the identity function below, unchanged by this bump), so a+ // downgrade reading a version-2 blob calls THAT migrate, gets the state+ // back unchanged, and loses nothing — the pairing the contract asks+ // for was already in place before this change.+ version: 2,// Explicit annotations for the same reason the state creator carries// them (see above): under `strict: true` zustand v5 loses contextual// typing here and infers the store as Partial<CreateState>.- migrate: (persisted: unknown): CreateState => persisted as CreateState,+ //+ // A version-1 blob is missing cloudStudioOptions/cloudStudioCredits+ // entirely (they did not exist yet) — merge() below already backfills+ // any key absent from the persisted blob from `current`'s defaults, so+ // this migrate only needs to guard the one case merge() cannot: a+ // blob that DOES carry the key but as `undefined` (a JSON round-trip+ // through some storages drops `undefined` values, but not every one+ // does, and `Object.entries()` in the Composer must never see it).+ migrate: (persisted: unknown): CreateState => {+ const p = persisted as Partial<CreateState> | null | undefined+ if (!p || typeof p !== 'object') return persisted as CreateState+ return {+ ...p,+ cloudStudioOptions: (p.cloudStudioOptions ?? {}) as Record<string, unknown>,+ cloudStudioCredits: p.cloudStudioCredits ?? null,+ } as CreateState+ },merge: (persisted: unknown, current: CreateState): CreateState => {// Never let runtime-only fields rehydrate (a foreign/corrupt blob must// not flip the backend axis or inject a stale source/mask), backfill