Skip to content

AI media harness for planning, generating, and editing locally

TypeScript

Add one-use image generation count

Bittib3520e2586c8
diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md
index fe756f7..19ed3a5 100644
--- a/RELEASE_NOTES.md
+++ b/RELEASE_NOTES.md
@@ -4,6 +4,8 @@ This alpha update adds Prompt video scenes, agent image drafts, Sol attention an
## What's new
+- **Image generation count.** Open the arrow beside Generate to queue up to 100 images with different seeds. Count applies to one click, resets afterward and is not saved in the project.
+
- **Generation effects.** Add LCS color steering, tone, sharpness and color stabilization from the video Scene or image root inspector. Effects run during generation, with bypass, reset, step ranges and optional regions. VAE calibration is automatic, cached and cancellable. MOSS disables these controls through the shared model capabilities.
- **MOSS CFG control.** Set CFG before Seed in the image inspector, with a default of 3. Values are remembered per model in each image draft and carried into local and LAN generation. H3 hides the control.
diff --git a/src/components/ImageProject.integration.test.tsx b/src/components/ImageProject.integration.test.tsx
index 7b9b8d8..e6734ff 100644
--- a/src/components/ImageProject.integration.test.tsx
+++ b/src/components/ImageProject.integration.test.tsx
@@ -103,6 +103,38 @@ it.each(["Create Scene", "Create Reference"])("opens and saves the item created
expect(save.mock.calls[1][0].config.generationJobs).toEqual(project.config.generationJobs);
});
+it("queues the count chosen beside Generate once without persisting it", async () => {
+ vi.spyOn(persistence, "isTauri").mockReturnValue(true);
+ vi.spyOn(persistence, "readMediaFileUrl").mockResolvedValue(null);
+ vi.spyOn(runtime, "resolveSlopfabPlan").mockResolvedValue({ alignedFrames: 1, canvasWidth: 768, canvasHeight: 768 } as Awaited<ReturnType<typeof runtime.resolveSlopfabPlan>>);
+ const enqueue = vi.spyOn(runtime, "enqueueSlopfabGeneration").mockResolvedValue(undefined);
+ saveGeneratorTemplateSettings({ defaultTemplateId: "test", templates: [{ id: "test", name: "Test", modelType: "minimax-h3", defaultSteps: 20, attention: "sage2", paths: { ...EMPTY_ENGINE_SETTINGS, transformer: "D:/h3.safetensors" } }] });
+ const project = record();
+ project.config.imageScene!.seed = 25;
+ project.config.assets = [{ id: "original", name: "Original", kind: "image", relativePath: "media/original.jpg", mimeType: "image/jpeg",
+ createdAt: project.config.createdAt, imageGeneration: imageGenerationSnapshot(project.config, "", "test") }];
+ project.config.imageScene!.outputAssetId = "original";
+ const queue = new WorkQueue(vi.fn(async (record) => record));
+ render(<ProjectWorkspace project={project} workQueue={queue} onBack={vi.fn()} onSave={vi.fn()} />);
+ const session = queue.project(project);
+ const before = session.getSnapshot().config;
+ fireEvent.click(screen.getByRole("button", { name: "Generation options" }));
+ fireEvent.change(screen.getByRole("spinbutton", { name: "Count" }), { target: { value: "3" } });
+ expect(session.getSnapshot().config).toBe(before);
+ fireEvent.click(screen.getByRole("button", { name: "Generate (3)" }));
+ await waitFor(() => expect(enqueue).toHaveBeenCalledOnce());
+ expect(queue.getSnapshot().map((item) => item.settings.seed)).toEqual([25, 26, 27]);
+ expect(session.getSnapshot().config.assets).toHaveLength(4);
+ expect(session.getSnapshot().config.assets[0]).toEqual(before.assets[0]);
+ expect(screen.queryByRole("dialog", { name: "Generation options" })).not.toBeInTheDocument();
+ fireEvent.click(screen.getByRole("button", { name: "View Original" }));
+ fireEvent.click(screen.getByRole("button", { name: "Generation options" }));
+ expect(screen.getByRole("spinbutton", { name: "Count" })).toHaveValue(1);
+ fireEvent.click(screen.getByRole("button", { name: "Generate" }));
+ expect(queue.getSnapshot()).toHaveLength(4);
+ expect(enqueue).toHaveBeenCalledOnce();
+});
+
it.each([false, true])("scopes generation controls to each image and queues others (draft: %s)", async (imageDraft) => {
vi.spyOn(persistence, "isTauri").mockReturnValue(true);
vi.spyOn(persistence, "readMediaFileUrl").mockResolvedValue(null);
diff --git a/src/components/ProjectWorkspace.tsx b/src/components/ProjectWorkspace.tsx
index 90a0603..fc6a90e 100644
--- a/src/components/ProjectWorkspace.tsx
+++ b/src/components/ProjectWorkspace.tsx
@@ -286,7 +286,7 @@ export function ProjectWorkspace({ project, initialView, runtime = null, onBack,
<ProjectStatusSlot.Provider value={statusSlot}>
<div className={`project-body${agentOpen ? " project-body--agent" : ""}`} style={agentPane.style}>
<div id={`${panelId}-view`} role="tabpanel" aria-label={VIEW_LABELS[view]} className={`project-content project-content--${view}`}>
- {view === "editor" && <ImageEditor openImage={imageNavigation} onImageOpened={() => setImageNavigation(undefined)} config={config} folderPath={project.folderPath} onChange={changeConfig} onGenerate={(template) => queue.enqueueImage(session, template)} onGenerateCharacterSheet={(template, sourceId, options) => queue.enqueueCharacterSheet(session, template, sourceId, options)} onGenerateExtend={(template, sourceId, options) => queue.enqueueExtendImage(session, template, sourceId, options)} onCancel={(id) => queue.cancel(id)} workItems={projectItems.filter((item) => item.kind === "image")} onOpenGenerator={(jobId) => { setSelectedGenerationJobId(jobId); setView("generator"); }} onOpenReferences={() => setView("references")} />}
+ {view === "editor" && <ImageEditor openImage={imageNavigation} onImageOpened={() => setImageNavigation(undefined)} config={config} folderPath={project.folderPath} onChange={changeConfig} onGenerate={(template, count) => queue.enqueueImage(session, template, count)} onGenerateCharacterSheet={(template, sourceId, options) => queue.enqueueCharacterSheet(session, template, sourceId, options)} onGenerateExtend={(template, sourceId, options) => queue.enqueueExtendImage(session, template, sourceId, options)} onCancel={(id) => queue.cancel(id)} workItems={projectItems.filter((item) => item.kind === "image")} onOpenGenerator={(jobId) => { setSelectedGenerationJobId(jobId); setView("generator"); }} onOpenReferences={() => setView("references")} />}
{view === "timeline" && <TimelineView config={config} openSceneId={selectedGenerationJobId} folderPath={project.folderPath} generationCompletionTimes={generationCompletionTimes} onChange={changeConfig} onMeasured={recordMeasurement} onOpenGenerator={(jobId) => { setSelectedGenerationJobId(jobId); setView("generator"); }} />}
{view === "generator" && <GeneratorView onGenerate={(submissions) => queue.enqueue(session, submissions)} onCancelGeneration={(ids) => queue.cancelScenes(session, ids)} cancellingJobIds={cancellingJobIds} config={config} folderPath={project.folderPath} generationCompletionTimes={generationCompletionTimes} runtime={runtime?.slopfab ?? null} onRuntimeChange={onGeneratorRuntimeChange} onChange={changeConfig} selectedJobId={selectedGenerationJobId} onSelectedJobChange={setSelectedGenerationJobId} onOpenTimeline={() => setView("timeline")} />}
{view === "references" && <ReferencesView openReference={referenceNavigation} onReferenceOpened={() => setReferenceNavigation(undefined)} config={config} folderPath={project.folderPath} onChange={changeConfig} onRegenerateIcon={(id) => queue.regenerateReferenceIcon(session, id)} onExportRefmod={(id, outputPath) => queue.exportReferenceRefmod(session, id, outputPath)} onGenerateBuiltinIcons={() => queue.generateBuiltinReferenceIcons(session)} onRegenerateBuiltinIcon={(id) => queue.regenerateBuiltinReferenceIcon(session, id)} pendingBuiltinIconIds={queue.pendingBuiltinIconIds()} pendingIconIds={new Set(config.references.filter((reference) => queue.isReferenceIconPending(session, reference.id)).map((reference) => reference.id))} onOpenGenerator={(jobId) => { setSelectedGenerationJobId(jobId); setView("generator"); }} />}
diff --git a/src/components/workspace/ImageEditor.test.tsx b/src/components/workspace/ImageEditor.test.tsx
index f3d8a50..8a9866f 100644
--- a/src/components/workspace/ImageEditor.test.tsx
+++ b/src/components/workspace/ImageEditor.test.tsx
@@ -1109,3 +1109,48 @@ it("shows CFG before Seed for MOSS and preserves its value when switching models
cleanup(); setup(saved);
expect(screen.getByRole("spinbutton", { name: "CFG" })).toHaveValue(4.5);
});
+
+
+it("sets a temporary generation count, dismisses its panel and resets after one Generate click", () => {
+ vi.spyOn(persistence, "isTauri").mockReturnValue(true);
+ const template = { ...defaultGeneratorTemplate(), sources: {}, paths: { transformer: "model", textEncoder: "encoder", videoVae: "vae", tokenizer: "tokenizer.json", audioVae: "audio" } };
+ saveGeneratorTemplateSettings({ templates: [template], defaultTemplateId: template.id });
+ const config = parseProjectConfig(fixture);
+ const onGenerate = vi.fn();
+ const onChange = vi.fn();
+ const props = { config, folderPath: "D:/Images", onChange, onGenerate, onCancel: vi.fn() };
+ const { unmount } = render(<ImageEditor {...props} />);
+ const options = screen.getByRole("button", { name: "Generation options" });
+ expect(options.closest(".inspector-actions")).not.toBeNull();
+ fireEvent.click(options);
+ expect(screen.getByRole("dialog", { name: "Generation options" })).toBeInTheDocument();
+ const count = screen.getByRole("spinbutton", { name: "Count" });
+ expect(count).toHaveFocus();
+ expect(count).toHaveValue(1);
+ for (const value of ["0", "101", "2.5", ""]) {
+ fireEvent.change(count, { target: { value } });
+ expect(count).toHaveAttribute("aria-invalid", "true");
+ expect(screen.getByRole("button", { name: "Generate" })).toBeDisabled();
+ }
+ fireEvent.change(count, { target: { value: "3" } });
+ fireEvent.keyDown(count, { key: "Escape" });
+ expect(screen.queryByRole("dialog", { name: "Generation options" })).not.toBeInTheDocument();
+ expect(options).toHaveFocus();
+ fireEvent.click(options);
+ expect(screen.getByRole("spinbutton", { name: "Count" })).toHaveValue(3);
+ fireEvent.click(screen.getByRole("button", { name: "Generate (3)" }));
+ expect(onGenerate).toHaveBeenLastCalledWith(template, 3);
+ expect(screen.queryByRole("dialog", { name: "Generation options" })).not.toBeInTheDocument();
+ fireEvent.click(options);
+ expect(screen.getByRole("spinbutton", { name: "Count" })).toHaveValue(1);
+ fireEvent.keyDown(screen.getByRole("spinbutton", { name: "Count" }), { key: "Escape" });
+ fireEvent.click(screen.getByRole("button", { name: "Generate" }));
+ expect(onGenerate).toHaveBeenLastCalledWith(template, 1);
+ expect(onChange).not.toHaveBeenCalled();
+ fireEvent.click(options);
+ fireEvent.change(screen.getByRole("spinbutton", { name: "Count" }), { target: { value: "4" } });
+ unmount();
+ render(<ImageEditor {...props} />);
+ fireEvent.click(screen.getByRole("button", { name: "Generation options" }));
+ expect(screen.getByRole("spinbutton", { name: "Count" })).toHaveValue(1);
+});
diff --git a/src/components/workspace/ImageEditor.tsx b/src/components/workspace/ImageEditor.tsx
index 449a8b3..2feec08 100644
--- a/src/components/workspace/ImageEditor.tsx
+++ b/src/components/workspace/ImageEditor.tsx
@@ -12,7 +12,7 @@ import { createEmptyImage, imageFamily, imageFamilyRoot, makeImagePrimary, remov
import { isTauri } from "../../lib/persistence";
import { createDraftGenerationJob, isVideoReference, PROJECT_RESOLUTIONS, referenceTypeLabel, type ProjectConfig, type ProjectReference } from "../../lib/project";
import { defaultGeneratorTemplate, generationStepsForTemplate, loadDebugOptionsEnabled, loadGeneratorTemplateSettings, MINIMAX_H3_MODEL_TYPE, generatorModel, templateSupportsImages, subscribeDebugOptions, subscribeGeneratorTemplates, templateUsable, type GeneratorTemplate } from "../../lib/settings";
-import { isWorkActive, type WorkItem } from "../../lib/workQueue";
+import { isWorkActive, MAX_IMAGE_BATCH_COUNT, type WorkItem } from "../../lib/workQueue";
import type { ConfigUpdate } from "./TimelineView";
import { ReferenceImage } from "./ReferenceImage";
import { PromptTextField } from "./PromptTextField";
@@ -31,7 +31,7 @@ import { applyImageCommand } from "../../lib/imageCommands";
import { copyImageNode, getImageNodeClipboard, pasteImageNode, subscribeImageNodeClipboard } from "../../lib/imageNodeClipboard";
import { HierarchyContextMenu } from "./HierarchyContextMenu";
import { useShortcut } from "../../lib/commands";
-import { ComboBox, InfoBar, ItemHeader, PaneHeader, ProgressBar, PropRow, PropSection, Splitter, tooltipProps, useContextMenu, usePaneSize } from "../ui";
+import { ComboBox, Flyout, InfoBar, ItemHeader, PaneHeader, ProgressBar, PropRow, PropSection, Splitter, tooltipProps, useContextMenu, usePaneSize } from "../ui";
import "../../styles/image-editor.css";
const MIN_IMAGE_ZOOM = 0.1;
@@ -49,7 +49,7 @@ function UsedImageSeed({ id, seed, onError }: { id: string; seed: number | undef
export function ImageEditor({ config, folderPath, onChange: changeConfig, onGenerate, onGenerateCharacterSheet, onGenerateExtend, onCancel, onOpenGenerator, onOpenReferences, workItems = [], openImage, onImageOpened }: {
config: ProjectConfig; folderPath: string; onChange: (update: ConfigUpdate) => void;
- onGenerate: (template: GeneratorTemplate) => void; onCancel: (id: string) => Promise<void>; workItems?: readonly WorkItem[];
+ onGenerate: (template: GeneratorTemplate, count: number) => void; onCancel: (id: string) => Promise<void>; workItems?: readonly WorkItem[];
onGenerateCharacterSheet?: (template: GeneratorTemplate, sourceId: string, options: CharacterSheetOptions) => void;
onGenerateExtend?: (template: GeneratorTemplate, sourceId: string, options: ExtendOptions) => void;
onOpenGenerator?: (jobId: string) => void;
@@ -113,6 +113,11 @@ export function ImageEditor({ config, folderPath, onChange: changeConfig, onGene
return saveImageDraft(next, selecting ? undefined : template?.id);
});
const [error, setError] = useState<string | null>(null);
+ const [generationCount, setGenerationCount] = useState("1");
+ const [generationOptionsOpen, setGenerationOptionsOpen] = useState(false);
+ const generationOptionsButton = useRef<HTMLButtonElement>(null);
+ const count = Number(generationCount);
+ const validCount = Number.isInteger(count) && count >= 1 && count <= MAX_IMAGE_BATCH_COUNT;
const debugEnabled = useSyncExternalStore(subscribeDebugOptions, loadDebugOptionsEnabled);
const [debugPrompt, setDebugPrompt] = useState<string | null>(null);
useEffect(() => { if (!debugEnabled) setDebugPrompt(null); }, [debugEnabled]);
@@ -539,7 +544,25 @@ export function ImageEditor({ config, folderPath, onChange: changeConfig, onGene
// A chip for a video or audio reference names it; one deleted says so.
const missingReference = (id: string) => config.references.find((reference) => reference.id === id)?.name ?? "Deleted reference";
const templateInspector = Boolean((extendMode && output && extendOptions) || (output && templateSourceId === output.id) || (runningTemplate && templateSource));
- const generateButton = <button type="button" className="primary-button image-generate-button" data-tooltip={effectsBlocked ?? (imageRoot ? editingBlocked : null) ?? editPlan?.error ?? undefined} disabled={active ? work.cancelling || work.status === "encoding" : Boolean(effectsBlocked) || Boolean(templateSnapshot && output?.imageDraft) || !isTauri() || !template || !templateUsable(template) || (imageRoot ? Boolean(editingBlocked || editPlan?.error) : !imageScenePrompt(scene))} onClick={() => attempt(() => active ? onCancel(work.id) : onGenerate(template!))}>{active ? <Stop14 aria-hidden="true" /> : <Sparkle16 aria-hidden="true" />}{active ? work.cancelling ? "Cancelling…" : "Cancel" : "Generate"}</button>;
+ const generateDisabled = active ? work.cancelling || work.status === "encoding" : Boolean(effectsBlocked) || Boolean(templateSnapshot && output?.imageDraft) || !isTauri() || !template || !templateUsable(template) || (imageRoot ? Boolean(editingBlocked || editPlan?.error) : !imageScenePrompt(scene));
+ const generateButton = <div className={`image-generation-controls${active ? "" : " image-generation-controls--split"}`}>
+ <button type="button" className="primary-button image-generate-button" data-tooltip={effectsBlocked ?? (imageRoot ? editingBlocked : null) ?? editPlan?.error ?? undefined}
+ disabled={generateDisabled || (!active && !validCount)} onClick={() => {
+ if (active) { attempt(() => onCancel(work.id)); return; }
+ setGenerationCount("1"); setGenerationOptionsOpen(false);
+ attempt(() => onGenerate(template!, count));
+ }}>{active ? <Stop14 aria-hidden="true" /> : <Sparkle16 aria-hidden="true" />}{active ? work.cancelling ? "Cancelling?" : "Cancel" : count > 1 && validCount ? `Generate (${count})` : "Generate"}</button>
+ {!active && <button ref={generationOptionsButton} type="button" className="primary-button image-generation-options" aria-label="Generation options"
+ aria-haspopup="dialog" aria-expanded={generationOptionsOpen} data-tooltip="Generation options" disabled={generateDisabled}
+ onClick={() => setGenerationOptionsOpen(!generationOptionsOpen)}><ChevronDown14 aria-hidden="true" /></button>}
+ <Flyout open={generationOptionsOpen && !active} anchor={generationOptionsButton} onClose={() => setGenerationOptionsOpen(false)} placement="top" width={240} aria-label="Generation options" className="image-generation-options-panel">
+ <PropRow label="Count" htmlFor={rootField("generation-count")}>
+ <input id={rootField("generation-count")} className="text-field" type="number" min={1} max={MAX_IMAGE_BATCH_COUNT} step={1}
+ value={generationCount} aria-invalid={!validCount} aria-describedby={rootField("generation-count-help")} onChange={(event) => setGenerationCount(event.target.value)} />
+ </PropRow>
+ <p id={rootField("generation-count-help")}>{validCount ? "Different seeds for each image. Resets after generating." : `Enter a whole number from 1 to ${MAX_IMAGE_BATCH_COUNT}.`}</p>
+ </Flyout>
+ </div>;
return <div ref={editorRoot} className="image-editor" style={{ ...treePane.style, ...inspectorPane.style }}>
<div className="image-canvas-tools" role="toolbar" aria-label="Image tools">
diff --git a/src/lib/workQueue.test.ts b/src/lib/workQueue.test.ts
index 4d40afb..1a24774 100644
--- a/src/lib/workQueue.test.ts
+++ b/src/lib/workQueue.test.ts
@@ -354,6 +354,86 @@ describe("agent scene generation", () => {
describe("image generation work", () => {
const template: GeneratorTemplate = { id: "image-test", name: "MiniMax H3", modelType: "minimax-h3", defaultSteps: 20, attention: "sage2", paths: { ...EMPTY_ENGINE_SETTINGS, transformer: "C:/h3.safetensors" } };
const imageProject = (): ProjectRecord => ({ folderPath: "C:/Image", config: createProjectConfig({ name: "Poster", prompt: "An ocean poster", generationType: "image", aspectRatio: "1:1", resolution: "768p", targetDurationSeconds: 60 }) });
+ it.each([-1, 42, Number.MAX_SAFE_INTEGER])("queues a batch of independent images with unique seeds starting at %s", async (seed) => {
+ const { queue } = setup();
+ const record = imageProject();
+ record.config.imageScene!.seed = seed;
+ const session = queue.project(record);
+ vi.mocked(invoke).mockImplementation(async (_command, args) => ({ relativePath: `media/${(args as { jobId: string }).jobId}.jpg`, width: 768, height: 768 }));
+ const id = queue.enqueueImage(session, template, 3);
+ const items = queue.getSnapshot();
+ expect(items).toHaveLength(3);
+ expect(id).toBe(items[0].id);
+ const seeds = items.map((item) => item.settings.seed);
+ expect(new Set(seeds).size).toBe(3);
+ expect(seeds.every((value) => Number.isSafeInteger(value) && value >= 0)).toBe(true);
+ if (seed >= 0) expect(seeds[0]).toBe(seed);
+ if (seed === Number.MAX_SAFE_INTEGER) expect(seeds).toEqual([seed, 0, 1]);
+ const pending = session.getSnapshot().config;
+ expect(pending.assets).toHaveLength(3);
+ expect(pending.assets.every((asset) => asset.imageDraft && !asset.relativePath)).toBe(true);
+ expect(new Set(items.map((item) => item.imageDraftId)).size).toBe(3);
+ expect(pending.imageScene!.outputAssetId).toBe(items[0].imageDraftId);
+ expect(pending.assets.slice(1).map((asset) => asset.parentAssetId)).toEqual([items[0].imageDraftId, items[0].imageDraftId]);
+ // Duplicate clicks cannot queue the same selected draft again.
+ expect(queue.enqueueImage(session, template, 3)).toBeUndefined();
+ expect(queue.getSnapshot()).toHaveLength(3);
+ for (const [index, item] of items.entries()) {
+ await waitFor(() => expect(enqueueSlopfabGeneration).toHaveBeenCalledTimes(index + 1));
+ const request = vi.mocked(enqueueSlopfabGeneration).mock.calls[index][0];
+ expect(request).toMatchObject({ seed: seeds[index], jobId: item.id, stillImage: true });
+ expect(request.prompt).toBe(vi.mocked(enqueueSlopfabGeneration).mock.calls[0][0].prompt);
+ await finish(queue, item.id);
+ }
+ const result = parseProjectConfig(JSON.parse(JSON.stringify(session.getSnapshot().config)));
+ expect(result.assets).toHaveLength(3);
+ expect(result.assets.every((asset) => !asset.imageDraft)).toBe(true);
+ expect(result.assets.map((asset) => asset.imageGeneration!.usedSeed)).toEqual(seeds);
+ expect(result.imageScene!.outputAssetId).toBe(items[0].imageDraftId);
+ expect(result.imageScene!.seed).toBe(seed);
+ // Count is an argument for one submission, never a project preference.
+ queue.enqueueImage(session, template);
+ expect(queue.getSnapshot()).toHaveLength(4);
+ await queue.cancel(queue.getSnapshot()[3].id);
+ });
+
+ it("keeps batched edits on the same source with frozen settings and independent cancellation", async () => {
+ const { queue } = setup();
+ const record = imageProject();
+ record.config.imageScene = createImageEditScene({ name: "Original", relativePath: "media/source.png", width: 640, height: 480 });
+ record.config.imageScene.nodes[0].description = "Add snow";
+ record.config.imageScene.seed = 10;
+ const session = queue.project(record);
+ queue.enqueueImage(session, template, 3);
+ const items = queue.getSnapshot();
+ const original = structuredClone(session.getSnapshot().config.assets[0]);
+ await waitFor(() => expect(enqueueSlopfabGeneration).toHaveBeenCalledOnce());
+ session.update((config) => ({ ...config, imageScene: { ...config.imageScene!, nodes: config.imageScene!.nodes.map((node) => ({ ...node, description: "Make it sunny" })) } }));
+ await queue.cancel(items[1].id);
+ vi.mocked(invoke).mockResolvedValue({ relativePath: "media/edited.png", width: 640, height: 480 });
+ await finish(queue, items[0].id);
+ await waitFor(() => expect(enqueueSlopfabGeneration).toHaveBeenCalledTimes(2));
+ const request = vi.mocked(enqueueSlopfabGeneration).mock.calls[1][0];
+ expect(request).toMatchObject({ jobId: items[2].id, seed: 12, imageEdit: { sourceRelativePath: "media/source.png" } });
+ expect(request.prompt).toContain("Add snow");
+ expect(request.prompt).not.toContain("Make it sunny");
+ await finish(queue, items[2].id);
+ const config = session.getSnapshot().config;
+ expect(config.assets[0]).toEqual(original);
+ expect(config.assets.find((asset) => asset.id === items[1].imageDraftId)?.imageDraft).toBe(true);
+ expect(config.imageScene!.nodes[0].description).toBe("Make it sunny");
+ expect(queue.getSnapshot().map((item) => item.status)).toEqual(["completed", "cancelled", "completed"]);
+ });
+
+ it.each([0, -1, 1.5, 101, NaN, Infinity])("rejects invalid batch count %s without changing the project", (count) => {
+ const { queue } = setup();
+ const session = queue.project(imageProject());
+ const before = session.getSnapshot().config;
+ expect(() => queue.enqueueImage(session, template, count)).toThrow("Count must be a whole number");
+ expect(session.getSnapshot().config).toBe(before);
+ expect(queue.getSnapshot()).toHaveLength(0);
+ });
+
it("routes MOSS text-to-image requests and refuses video and editing work", async () => {
const { queue, first } = setup();
const moss = { ...mossImageTemplate(), sources: {}, paths: { transformer: "moss", textEncoder: "qwen", videoVae: "flux", tokenizer: "tokenizer.json", audioVae: "" } };
diff --git a/src/lib/workQueue.ts b/src/lib/workQueue.ts
index f594b0c..33cbec2 100644
--- a/src/lib/workQueue.ts
+++ b/src/lib/workQueue.ts
@@ -33,6 +33,7 @@ import { exportReferenceRefmod, refmodExportBlocker, refmodExportRequest, type R
export type WorkStatus = "queued" | "preparing" | "generating" | "encoding" | "completed" | "failed" | "cancelled";
export interface GenerationSubmission { job: GenerationJob; request: SlopfabGenerationRequest; snapshot: string }
+export const MAX_IMAGE_BATCH_COUNT = 100;
function imageGenerationSeed(seed: number): number {
if (seed !== -1) return seed;
@@ -268,7 +269,8 @@ export class WorkQueue {
});
}
- enqueueImage(session: ProjectSession, template: GeneratorTemplate) {
+ 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}.`);
if (!isTauri()) throw new Error("Image generation requires the desktop app and downloaded model weights.");
if (!templateSupportsImages(template)) throw new Error("Choose a prompt generator for images.");
let current = session.getSnapshot().config;
@@ -290,27 +292,44 @@ export class WorkQueue {
...(guidanceScale !== undefined ? { cfgScales: { ...(config.imageScene ?? scene).cfgScales, [template.modelType]: guidanceScale } } : {}),
} }, template.id, true, id));
current = session.getSnapshot().config;
- const config = structuredClone({ ...current, providerSettings: { ...current.providerSettings,
- slopfab: engineProviderSetting(template.paths, current.providerSettings.slopfab, template.attention, template.loras, "prompt", template.additionalSafetensors, false, template.sources, template) } });
+ const firstDraft = current.assets.find((asset) => asset.id === current.imageScene!.outputAssetId)!;
+ const entries = [{ id, draft: firstDraft }, ...Array.from({ length: count - 1 }, () => {
+ const nextId = `image-${crypto.randomUUID()}`;
+ return { id: nextId, draft: { ...structuredClone(firstDraft), id: nextId, parentAssetId: firstDraft.parentAssetId ?? firstDraft.id } };
+ })];
+ const siblings = entries.slice(1).map((entry) => entry.draft);
+ if (siblings.length) {
+ session.update((config) => ({ ...config, assets: [...config.assets, ...siblings.filter((draft) => !config.assets.some((asset) => asset.id === draft.id))] }));
+ current = session.getSnapshot().config;
+ }
const referencePaths = (selected: typeof references) => [
...(edit ? [projectItemPath(session.record.folderPath, edit.source)!] : []),
...selected.flatMap((reference) => referenceImages(reference).map((image) => projectItemPath(session.record.folderPath, image)!)),
];
- const imageDraftId = current.imageScene!.outputAssetId!;
- let finish!: () => void;
- const done = new Promise<void>((resolve) => { finish = resolve; });
- const request: SlopfabGenerationRequest = { ...(guidanceScale !== undefined ? { guidanceScale } : {}), generationEffects: activeGenerationEffects(scene.generationEffects), jobId: id, stillImage: true, frames: 1, prompt: edit ? edit.edits[0].prompt : prompt,
- ...(edit ? { imageEdit: { sourceRelativePath: edit.source.relativePath, edits: edit.edits.map(({ references, ...step }) => ({
- ...step, referencePaths: referencePaths(references), refmods: referenceRefmodInputs(session.record.folderPath, references),
- })) } } : {}),
- canvasWidth: width, canvasHeight: height, steps: generationStepsWithLoras(scene.steps, config), seed: imageGenerationSeed(scene.seed),
- referencePaths: referencePaths(references),
- refmods: referenceRefmodInputs(session.record.folderPath, references),
- };
- this.work.set(id, { id, image: true, imageDraftId, imageGeneration: { ...imageGenerationSnapshot(config, edit ? imageEditDebugPrompt(edit.edits) : prompt, template.id), usedSeed: request.seed }, session, sceneId: scene.nodes.find((node) => node.kind === "root")!.id, config, snapshot: JSON.stringify(config.imageScene), request, submitted: false, cancelled: false, done, finish });
- this.items = [...this.items, { id, kind: "image", imageAssetId: imageDraftId, imageDraftId, projectKey, folderPath: session.record.folderPath, projectName: config.name, sceneId: scene.nodes.find((node) => node.kind === "root")!.id,
- title: "Image · " + config.name, submittedAt: new Date().toISOString(), status: "queued", progress: 0, detail: "Waiting to generate image", error: null, completionAt: null, cancelling: false, needsSave: false,
- settings: { frames: 1, steps: request.steps, seed: request.seed, canvasWidth: width, canvasHeight: height } }];
+ let seed = imageGenerationSeed(scene.seed);
+ const items: WorkItem[] = [];
+ for (const entry of entries) {
+ const imageDraftId = entry.draft.id;
+ const config = structuredClone({ ...current, imageScene: { ...current.imageScene!, outputAssetId: imageDraftId }, providerSettings: { ...current.providerSettings,
+ slopfab: engineProviderSetting(template.paths, current.providerSettings.slopfab, template.attention, template.loras, "prompt", template.additionalSafetensors, false, template.sources, template) } });
+ let finish!: () => void;
+ const done = new Promise<void>((resolve) => { finish = resolve; });
+ const request: SlopfabGenerationRequest = { ...(guidanceScale !== undefined ? { guidanceScale } : {}), generationEffects: activeGenerationEffects(scene.generationEffects), jobId: entry.id, stillImage: true, frames: 1, prompt: edit ? edit.edits[0].prompt : prompt,
+ ...(edit ? { imageEdit: { sourceRelativePath: edit.source.relativePath, edits: edit.edits.map(({ references, ...step }) => ({
+ ...step, referencePaths: referencePaths(references), refmods: referenceRefmodInputs(session.record.folderPath, references),
+ })) } } : {}),
+ canvasWidth: width, canvasHeight: height, steps: generationStepsWithLoras(scene.steps, config), seed,
+ referencePaths: referencePaths(references),
+ refmods: referenceRefmodInputs(session.record.folderPath, references),
+ };
+ this.work.set(entry.id, { id: entry.id, image: true, imageDraftId, imageGeneration: { ...imageGenerationSnapshot(config, edit ? imageEditDebugPrompt(edit.edits) : prompt, template.id), usedSeed: request.seed }, session, sceneId: scene.nodes.find((node) => node.kind === "root")!.id, config, snapshot: JSON.stringify(config.imageScene), request, submitted: false, cancelled: false, done, finish });
+ items.push({ id: entry.id, kind: "image", imageAssetId: imageDraftId, imageDraftId, projectKey, folderPath: session.record.folderPath, projectName: config.name, sceneId: scene.nodes.find((node) => node.kind === "root")!.id,
+ title: "Image · " + config.name, submittedAt: new Date().toISOString(), status: "queued", progress: 0, detail: "Waiting to generate image", error: null, completionAt: null, cancelling: false, needsSave: false,
+ settings: { frames: 1, steps: request.steps, seed: request.seed, canvasWidth: width, canvasHeight: height } });
+ // Wrap without exceeding JSON's exactly representable integer range.
+ seed = seed === Number.MAX_SAFE_INTEGER ? 0 : seed + 1;
+ }
+ this.items = [...this.items, ...items];
this.publish(); this.icons.yieldToVideo(); void this.pump();
return id;
}
diff --git a/src/styles/image-editor.css b/src/styles/image-editor.css
index 8a4d6c4..032747e 100644
--- a/src/styles/image-editor.css
+++ b/src/styles/image-editor.css
@@ -41,6 +41,14 @@
.image-center { min-width: 0; min-height: 0; display: flex; flex-direction: column; background: var(--layer); }
.image-canvas-tools { grid-column: 1 / -1; min-width: 0; display: grid; grid-template-columns: minmax(0, 1fr) auto minmax(0, 1fr); align-items: center; gap: var(--space-2); height: var(--command-row); padding: 0 var(--space-2); border-bottom: 1px solid var(--line); }
.image-generate-button { flex-shrink: 0; white-space: nowrap; }
+.image-generation-controls { display: flex; min-width: 0; }
+.image-generation-controls > .image-generate-button { flex: 1; }
+.image-generation-controls--split > .image-generate-button { border-top-right-radius: 0; border-bottom-right-radius: 0; }
+.image-generation-options { flex: 0 0 var(--control-md); padding: 0; border-left-color: var(--button-primary-stroke-bottom); border-top-left-radius: 0; border-bottom-left-radius: 0; }
+.image-generation-options-panel { padding: var(--space-3); }
+.image-generation-options-panel .ui-prop-row { padding: 0; }
+.image-generation-options-panel p { margin: var(--space-2) 0 0; color: var(--text-secondary); font-size: var(--text-xs); }
+
.image-tools__start, .image-tools__center, .image-tools__end { min-width: 0; display: flex; align-items: center; gap: var(--space-1); }
.image-tools__end { justify-content: flex-end; }
.image-generator { flex-shrink: 1; }