AI media harness for planning, generating, and editing locally
TypeScript
Preserve songs when generating new variations
Bitti5ba7c9f67e99
diff --git a/src/components/workspace/MusicView.test.tsx b/src/components/workspace/MusicView.test.tsxindex ca94e53..06425d1 100644--- a/src/components/workspace/MusicView.test.tsx+++ b/src/components/workspace/MusicView.test.tsx@@ -5,7 +5,7 @@ import { cleanup, fireEvent, render, screen, waitFor, within } from "@testing-liimport { useState } from "react";import { MusicView } from "./MusicView";import { createProjectConfig, type ProjectConfig } from "../../lib/project";-import { newMusicFolder, newSong } from "../../lib/music";+import { newMusicFolder, newSong, newSongVariation } from "../../lib/music";import { readMediaFileUrl } from "../../lib/persistence";import { loadGeneratorTemplateSettings, musicTemplates, saveGeneratorTemplateSettings } from "../../lib/settings";@@ -120,6 +120,21 @@ it("shows missing downloads in the shared selector and status bar, outside the iexpect(screen.getAllByText("Download in Settings")).toHaveLength(2);});+it("selects the new song returned by generation while keeping the original visible", () => {+ const original = { ...newSong(), title: "Evening", style: "Jazz", status: "completed" as const, assetId: "original" };+ const variation = newSongVariation(original, [original]);+ function VariationHarness() {+ const [config, setConfig] = useState<ProjectConfig>({ ...createConfig(), musicSongs: [original] });+ return <MusicView config={config} folderPath="C:/Music" onChange={setConfig} workItems={[]} onCancel={() => {}}+ onGenerate={() => { setConfig((current) => ({ ...current, musicSongs: [...current.musicSongs!, variation] })); return variation.id; }} />;+ }+ render(<VariationHarness />);+ fireEvent.click(screen.getByRole("button", { name: "Generate" }));+ expect(screen.getByRole("button", { name: "Select Evening (2)" })).toHaveAttribute("aria-pressed", "true");+ expect(screen.getByRole("button", { name: "Select Evening" })).toHaveAttribute("aria-pressed", "false");+ expect(screen.getByLabelText("Song title")).toHaveValue("Evening (2)");+});+it("plays generated audio and creates a reference for the context-clicked song", async () => {const first = { ...newSong(), title: "First", status: "completed" as const, assetId: "song-a" };const second = { ...newSong(), title: "Second", status: "completed" as const, assetId: "song-b" };diff --git a/src/components/workspace/MusicView.tsx b/src/components/workspace/MusicView.tsxindex 8e10a38..66b5331 100644--- a/src/components/workspace/MusicView.tsx+++ b/src/components/workspace/MusicView.tsx@@ -18,7 +18,7 @@ const SONG_DRAG_TYPE = "application/x-slopus-music-song";export function MusicView({ config, folderPath, onChange, onGenerate, onCancel, workItems, openSong, onSongOpened }: {openSong?: { id: string }; onSongOpened?: () => void;config: ProjectConfig; folderPath: string; onChange: (update: ConfigUpdate, key?: string) => void;- onGenerate: (songId: string, template: GeneratorTemplate) => void; onCancel: (id: string) => void;+ onGenerate: (songId: string, template: GeneratorTemplate) => string | void; onCancel: (id: string) => void;workItems: readonly WorkItem[];}) {const [templates, setTemplates] = useState(() => loadGeneratorTemplateSettings().templates.filter(templateSupportsMusic));@@ -82,7 +82,7 @@ export function MusicView({ config, folderPath, onChange, onGenerate, onCancel,const generate = () => {if (!selected || !template) return;setError(null);- try { onGenerate(selected.id, template); } catch (reason) { setError(String(reason)); }+ try { const id = onGenerate(selected.id, template); if (id) setSelectedId(id); } catch (reason) { setError(String(reason)); }};const audio = useRef<HTMLAudioElement>(null);diff --git a/src/lib/music.ts b/src/lib/music.tsindex 3f97f15..792a98a 100644--- a/src/lib/music.ts+++ b/src/lib/music.ts@@ -36,6 +36,17 @@ export function newSong(generatorId = "yue2", steps = 32, folderId?: string | nureturn musicSongSchema.parse({ id: `song-${crypto.randomUUID()}`, title: "New song", generatorId, steps, ...(folderId ? { folderId } : {}), createdAt: new Date().toISOString() });}+export function newSongVariation(source: MusicSong, songs: readonly MusicSong[]): MusicSong {+ const base = source.title.replace(/ \(\d+\)$/, "");+ let number = 2, title: string;+ do {+ const suffix = ` (${number++})`;+ title = base.slice(0, 200 - suffix.length) + suffix;+ } while (songs.some((song) => song.title === title));+ return { ...structuredClone(source), id: `song-${crypto.randomUUID()}`, title,+ status: "draft", assetId: null, error: null, createdAt: new Date().toISOString() };+}+export function newMusicFolder(name: string, parentId: string | null): MusicFolder {return musicFolderSchema.parse({ id: `music-folder-${crypto.randomUUID()}`, name, parentId });}diff --git a/src/lib/workQueue.test.ts b/src/lib/workQueue.test.tsindex b6a77f7..3fbd4ca 100644--- a/src/lib/workQueue.test.ts+++ b/src/lib/workQueue.test.ts@@ -101,6 +101,34 @@ it("cancels a queued song without altering another song", async () => {expect(first.getSnapshot().config.musicSongs![0].status).not.toBe("cancelled");});+it.each(["completed", "failed"])("generates a separate song from existing audio and preserves the original when %s", async (outcome) => {+ const { queue, first } = setup();+ const original = { ...newSong("yue2", 24, "jazz"), title: "Evening", style: "Soft jazz", seed: 42,+ status: "completed" as const, assetId: "original-audio", settings: { ...newSong().settings, lyrics: "[Verse]\nGood evening" } };+ const originalAsset = { id: "original-audio", kind: "audio" as const, name: "Evening", relativePath: "media/original.wav", durationMs: 30000, mimeType: "audio/wav", createdAt: original.createdAt };+ first.update((config) => ({ ...config, musicFolders: [{ id: "jazz", name: "Jazz" }], musicSongs: [original], assets: [originalAsset] }));+ const template = musicTemplates()[0];+ template.paths.transformer = "C:/weights/yue2.safetensors"; template.sources = {};+ vi.mocked(invoke).mockResolvedValue({ relativePath: "media/generated/variation.wav", durationMs: 30000 });+ const songId = queue.enqueueMusic(first, original.id, template);+ expect(songId).not.toBe(original.id);+ expect(first.getSnapshot().config.musicSongs).toHaveLength(2);+ expect(first.getSnapshot().config.musicSongs![1]).toMatchObject({ id: songId, title: "Evening (2)", folderId: "jazz", settings: original.settings, seed: 42, steps: 24, assetId: null });+ await waitFor(() => expect(enqueueSlopfabGeneration).toHaveBeenCalledOnce());+ const work = queue.getSnapshot()[0];+ expect(work.sceneId).toBe(songId);+ if (outcome === "completed") {+ await finish(queue, work.id);+ expect(first.getSnapshot().config.musicSongs![1]).toMatchObject({ status: "completed", assetId: work.id });+ expect(first.getSnapshot().config.assets).toHaveLength(2);+ } else {+ emit("slopfab-job", { jobId: work.id, state: "failed", detail: "Generation failed" });+ await waitFor(() => expect(first.getSnapshot().config.musicSongs![1].status).toBe("failed"));+ }+ expect(first.getSnapshot().config.musicSongs![0]).toEqual(original);+ expect(first.getSnapshot().config.assets).toContainEqual(originalAsset);+});+it("releases submitted snapshots after each generation while keeping completed results available", async () => {const { queue, first } = setup();const pending = (queue as unknown as { work: Map<string, unknown> }).work;diff --git a/src/lib/workQueue.ts b/src/lib/workQueue.tsindex 26ff922..2539fc1 100644--- a/src/lib/workQueue.ts+++ b/src/lib/workQueue.ts@@ -1,5 +1,5 @@import { completeSceneGeneration, sceneInput } from "./sceneHistory";-import { musicSongSchema, musicSettingsForModel, updateSong, type MusicSong } from "./music";+import { musicSongSchema, musicSettingsForModel, newSongVariation, updateSong, type MusicSong } from "./music";import { templateSupportsMusic } from "./settings";import { imageCfgScale } from "./generatorModels";import { activeGenerationEffects } from "./generationEffects";@@ -283,10 +283,12 @@ export class WorkQueue {if (!isTauri()) throw new Error("Music generation requires the desktop app and model weights.");if (!templateSupportsMusic(template)) throw new Error("Choose a music generator.");const current = session.getSnapshot().config;- const song = musicSongSchema.parse((current.musicSongs ?? []).find((item) => item.id === songId));- if (!song.style.trim()) throw new Error("Describe the song's style before generating.");+ const source = musicSongSchema.parse((current.musicSongs ?? []).find((item) => item.id === songId));+ if (!source.style.trim()) throw new Error("Describe the song's style before generating.");const projectKey = projectQueueKey(session.record);- if (this.items.some((item) => item.projectKey === projectKey && item.kind === "music" && item.sceneId === songId && isWorkActive(item))) return;+ if (this.items.some((item) => item.projectKey === projectKey && item.kind === "music" && item.sceneId === songId && isWorkActive(item))) return songId;+ const song = source.assetId || source.status === "completed" ? newSongVariation(source, current.musicSongs ?? []) : source;+ songId = song.id;const id = `music-${crypto.randomUUID()}`;const captured = { ...structuredClone(song), generatorId: template.id, seed: imageGenerationSeed(song.seed) };const config = structuredClone({ ...current, providerSettings: { ...current.providerSettings,@@ -296,12 +298,14 @@ export class WorkQueue {let finish!: () => void;const done = new Promise<void>((resolve) => { finish = resolve; });this.work.set(id, { id, music: captured, session, sceneId: songId, request, config, snapshot: JSON.stringify(captured), cancelled: false, submitted: false, done, finish });- session.update((value) => updateSong(value, songId, { status: "queued", error: null, generatorId: template.id }));+ session.update((value) => updateSong(value.musicSongs?.some((item) => item.id === songId) ? value+ : { ...value, musicSongs: [...(value.musicSongs ?? []), song] }, songId, { status: "queued", error: null, generatorId: template.id }));this.items = [...this.items, { id, kind: "music", projectKey, folderPath: session.record.folderPath, projectName: current.name,sceneId: songId, title: song.title, submittedAt: new Date().toISOString(), status: "queued", progress: 0,detail: "Waiting to generate music", error: null, completionAt: null, cancelling: false, needsSave: false,settings: { frames: 0, steps: song.steps, seed: captured.seed, canvasWidth: 0, canvasHeight: 0 } }];this.publish(); void this.pump();+ return songId;}enqueueImage(session: ProjectSession, template: GeneratorTemplate, count = 1) {if (!Number.isInteger(count) || count < 1 || count > MAX_IMAGE_BATCH_COUNT) throw new Error(`Count must be a whole number from 1 to ${MAX_IMAGE_BATCH_COUNT}.`);