AI media harness for planning, generating, and editing locally
TypeScript
Add Long Shot scene workflow
Bittif31c1668c5e9
diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.mdindex b1cf34e..7ee3f9c 100644--- a/RELEASE_NOTES.md+++ b/RELEASE_NOTES.md@@ -4,6 +4,7 @@ This alpha update adds LAN generation workers, Linux support, expanded color gra## What's new+- Added Long Shot scenes: generate alternating fresh clips and latent bridges in 1 → 3 → 2 → 5 → 4 order. Bridge controls set how much of the neighboring ending and beginning may change, with joined video and audio used in preview and export. Includes updated Windows/Linux runtimes and LAN worker support; update workers alongside the app.- Video and image generation headers now show the effective step count from the selected generator's active LoRAs, including fixed sampling schedules.- Added Backdrop scenes to generate subjects and action against a selected green, blue, black or white background. Chroma Key now offers matching backdrop modes and automatic border detection, with matte levels, background color removal, despill, shadow removal, edge softness, choke/grow and small-speck/hole cleanup in GPU preview and export.- Timeline clips now offer Speed in Timing, from 25% to 400%. Speed changes preserve the source range, adjust duration and later clips on the same track, and apply to preview and export, including audio pitch.diff --git a/src/components/workspace/GeneratorView.test.tsx b/src/components/workspace/GeneratorView.test.tsxindex 36bb765..7c98f6c 100644--- a/src/components/workspace/GeneratorView.test.tsx+++ b/src/components/workspace/GeneratorView.test.tsx@@ -31,6 +31,30 @@ beforeEach(() => {});afterEach(cleanup);+it("queues Long Shot anchors before their intervening bridges", () => {+ const initial = project();+ initial.generationJobs = Array.from({ length: 7 }, (_, i) => createDraftGenerationJob("Keep walking", { id: String(i + 1), sceneType: "long-shot" }));+ const submitted = vi.fn();+ render(<GeneratorView config={initial} folderPath="C:/project" runtime={readyRuntime}+ onChange={vi.fn()} onGenerate={submitted} onOpenTimeline={() => undefined} />);+ fireEvent.click(screen.getByRole("button", { name: "Generate all" }));+ expect(submitted.mock.calls[0][0].map((item: { job: { id: string } }) => item.job.id)).toEqual(["1", "3", "2", "5", "4", "7", "6"]);+ expect(submitted.mock.calls[0][0][2].request.latentBridge).toMatchObject({ leftSceneId: "1", rightSceneId: "3", leftMarginFrames: 17, rightMarginFrames: 17 });+});++it("persists Long Shot boundary controls and inherits the scene type for new scenes", () => {+ const initial = project();+ initial.generationJobs.forEach((job) => { job.sceneType = "long-shot"; });+ const state = setup(initial);+ fireEvent.click(screen.getByRole("button", { name: "Select scene Second scene" }));+ choose("Edit previous ending", "34 frames (1.42 s)");+ choose("Edit following beginning", "0 frames (0.00 s)");+ expect(state.latest().generationJobs[1]).toMatchObject({ sceneType: "long-shot", bridgeLeftMargin: 34, bridgeRightMargin: 0 });+ expect(screen.queryByLabelText("Start frame for this scene")).toBeNull();+ fireEvent.click(screen.getByRole("button", { name: "Add scene" }));+ expect(state.latest().generationJobs.at(-1)?.sceneType).toBe("long-shot");+});+it("hides unfinished templates from the generator picker", () => {setup();fireEvent.click(screen.getByRole("combobox", { name: /Video generator template/ }));diff --git a/src/components/workspace/GeneratorView.tsx b/src/components/workspace/GeneratorView.tsxindex 38c7d8c..945b9dd 100644--- a/src/components/workspace/GeneratorView.tsx+++ b/src/components/workspace/GeneratorView.tsx@@ -1,4 +1,5 @@import { sceneGenerationRequest, sendBlocker, templateSceneBlocker } from "../../lib/sceneGeneration";+import { longShotBlocker, longShotDependencies, longShotPosition } from "../../lib/longShot";export { templateSceneBlocker } from "../../lib/sceneGeneration";import type { GenerationSubmission } from "../../lib/workQueue";import { loadLoras, subscribeLoras } from "../../lib/loras";@@ -358,7 +359,7 @@ export function GeneratorView({ config, folderPath, runtime = null, generationCoreferences already named by its shots. */const newScene = () => {const job = createDraftGenerationJob("", { steps: defaultGenerationSteps,- sceneType: selectedTemplate.mode === "animate" ? "animate" : "first-last-frame" });+ sceneType: selectedTemplate.mode === "animate" ? "animate" : selected?.sceneType === "long-shot" ? "long-shot" : "first-last-frame" });onChange({ ...config, generationJobs: [...jobs, job] });setSelection({ jobId: job.id, shotId: null });};@@ -404,18 +405,24 @@ export function GeneratorView({ config, folderPath, runtime = null, generationCo* both its output and the exact renderer-input snapshot still exist. */const batchScenesReady: GenerationJob[] = [];const visited = new Set<string>();+ const visiting = new Set<string>();const visitForBatch = (job: GenerationJob): boolean => {- if (continuationBlocker(job, jobs) || templateSceneBlocker(sceneTypeFor(job), selectedTemplate) || sendBlocker(job, config.references)) return false;+ if (continuationBlocker(job, jobs) || longShotBlocker(job, config, false) || templateSceneBlocker(sceneTypeFor(job), selectedTemplate) || sendBlocker(job, config.references)) return false;if (visited.has(job.id)) return true;+ if (visiting.has(job.id)) return false;if (["queued", "generating", "ready"].includes(job.status)) { visited.add(job.id); return true; }const previous = jobs.find((candidate) => candidate.id === continuationSceneId(job, jobs));- if (previous && !visitForBatch(previous)) return false;+ const dependencies = [...(previous ? [previous] : []), ...longShotDependencies(job, jobs)];+ visiting.add(job.id);+ if (dependencies.some((source) => !visitForBatch(source))) { visiting.delete(job.id); return false; }+ visiting.delete(job.id);visited.add(job.id);- const previousWillRender = previous &&- (batchScenesReady.includes(previous) || ["queued", "generating", "ready"].includes(previous.status));+ const priorBridge = longShotPosition(job, jobs)?.previousBridge;+ const previousWillRender = [...dependencies, ...(priorBridge ? [priorBridge] : [])].some((source) =>+ batchScenesReady.includes(source) || ["queued", "generating", "ready"].includes(source.status));if (previousWillRender || sceneGenerationSeed(job) === RANDOM_GENERATION_SEED || job.status !== "completed"|| !job.outputRelativePath- || (!job.latentRelativePath && jobs.some((candidate) => continuationSceneId(candidate, jobs) === job.id))+ || (!job.latentRelativePath && (job.sceneType === "long-shot" || jobs.some((candidate) => continuationSceneId(candidate, jobs) === job.id)))|| !job.generationSnapshot|| job.generationSnapshot !== snapshotFor(job)) batchScenesReady.push(job);return true;@@ -429,6 +436,7 @@ export function GeneratorView({ config, folderPath, runtime = null, generationCoif (job.status === "ready") return "Saving this scene.";const source = jobs.find((candidate) => candidate.id === continuationSceneId(job, jobs));return continuationBlocker(job, jobs)+ ?? longShotBlocker(job, config)?? (source && (!source.latentRelativePath || source.status !== "completed") ? "Generate the selected source scene first, or use Generate all." : null)?? templateSceneBlocker(sceneTypeFor(job), selectedTemplate) ?? sendBlocker(job, config.references);};@@ -437,7 +445,7 @@ export function GeneratorView({ config, folderPath, runtime = null, generationCo.filter((job) => job.status === "completed"&& Boolean(job.generationSnapshot)&& (job.generationSnapshot !== snapshotFor(job)- || jobs.some((source) => source.id === continuationSceneId(job, jobs) && ["queued", "generating", "ready"].includes(source.status))))+ || jobs.some((source) => (source.id === continuationSceneId(job, jobs) || longShotDependencies(job, jobs).includes(source)) && ["queued", "generating", "ready"].includes(source.status)))).map((job) => job.id));const selectedIndicator = selected && changedJobIds.has(selected.id) ? "changed" : selected?.status;diff --git a/src/components/workspace/SceneBoard.tsx b/src/components/workspace/SceneBoard.tsxindex d4b7cbb..e550849 100644--- a/src/components/workspace/SceneBoard.tsx+++ b/src/components/workspace/SceneBoard.tsx@@ -16,6 +16,7 @@ import { referenceOrder, STEP_SECONDS } from "./SceneEditor";import { statusIcon, STATUS_BADGE } from "./sceneStatus";import { ShotThumbnail } from "./ShotThumbnail";import { sceneMediaStartSeconds } from "../../lib/continuationMedia";+import { longShotPlaybackSource } from "../../lib/longShot";import { generationAssetId, type ProjectAsset } from "../../lib/project";export interface GeneratorSelection {@@ -399,6 +400,7 @@ export function SceneBoard({onDrop={(event) => dropShot(event, null)}>{shots.map((shot, index) => {+ const joined = longShotPlaybackSource(job, { assets, generationJobs: jobs });const isSource = dragging?.kind === "shot" && dragging.shotId === shot.id;return <likey={shot.id}@@ -423,8 +425,8 @@ export function SceneBoard({}}><ShotCard- sourceOffsetSeconds={sceneMediaStartSeconds(assets.find((asset) => asset.id === generationAssetId(job.id)))}- job={job}+ sourceOffsetSeconds={joined ? joined.segment.startFrame / 24 : sceneMediaStartSeconds(assets.find((asset) => asset.id === generationAssetId(job.id)))}+ job={joined ? { ...job, outputRelativePath: joined.source.relativePath } : job}shot={shot}index={index}endsAt={index + 1 < shots.length ? shots[index + 1].startSeconds : duration}diff --git a/src/components/workspace/SceneEditor.tsx b/src/components/workspace/SceneEditor.tsxindex 226d7a4..5261132 100644--- a/src/components/workspace/SceneEditor.tsx+++ b/src/components/workspace/SceneEditor.tsx@@ -1,5 +1,6 @@import { Audio16, Dismiss12, Image16, ImageAdd16, Text16, Video16 } from "../ui/icons";import { BACKDROP_OPTIONS, type BackdropColor } from "../../lib/backdrop";+import { longShotPosition } from "../../lib/longShot";import { useId, useMemo, useState, type ReactNode } from "react";import { ComboBox, InfoBar, PropRow, PropSection, ToggleSwitch } from "../ui";import {@@ -265,6 +266,7 @@ function CharacterReplaceInputs({ shot, references, disabled, onChange }: {const SCENE_TYPES: { value: SceneType; label: string }[] = [{ value: "first-last-frame", label: "First & last frame" },{ value: "backdrop", label: "Backdrop" },+ { value: "long-shot", label: "Long Shot" },{ value: "continue", label: "Continue" },{ value: "animate", label: "Animate" },{ value: "pose", label: "Pose" },@@ -298,6 +300,7 @@ export function SceneInspector({ job, shots, references, folderPath = "", scenesconst animate = sceneType === "animate";const continuing = sceneType === "continue";const backdrop = sceneType === "backdrop";+ const longShot = longShotPosition(job, scenes);const pose = sceneType === "pose";const characterReplace = sceneType === "character-replace";const transition = isVideoTransition({ sceneType });@@ -328,6 +331,17 @@ export function SceneInspector({ job, shots, references, folderPath = "", scenesonChange={(value) => onChange({ sceneType: value as SceneType, usePreviousSceneLastFrame: undefined,...(value === "animate" ? { endFrameReferenceId: undefined } : {}) })} /></PropRow>+ {longShot && <>+ <p className="prop-caption">{longShot.bridge+ ? `Bridge between ${longShot.left?.title ?? "the previous scene"} and ${longShot.right?.title ?? "a following Long Shot scene (add one first)"}. Both neighbors must be generated first. Generate all handles this order.`+ : "Generate a fresh clip. The next Long Shot scene bridges this clip to the following fresh clip."}</p>+ {longShot.bridge && ([['bridgeLeftMargin', 'Edit previous ending'], ['bridgeRightMargin', 'Edit following beginning']] as const).map(([key, label]) =>+ <PropRow key={key} label={label} htmlFor={`${id}-${key}`} tooltip="Frames regenerated along with the bridge, at 24 fps. Zero preserves the anchor latents. The joined decode updates playback for both neighbors.">+ <ComboBox id={`${id}-${key}`} aria-label={label} disabled={disabled} value={String(job[key] ?? 17)}+ options={Array.from({ length: 21 }, (_, index) => ({ value: String(index * 17), label: `${index * 17} frames (${(index * 17 / 24).toFixed(2)} s)` }))}+ onChange={(value) => onChange({ [key]: Number(value) })} />+ </PropRow>)}+ </>}{backdrop && <><PropRow label="Backdrop color" htmlFor={`${id}-backdrop`}><ComboBox id={`${id}-backdrop`} aria-label="Scene backdrop color" value={job.backdropColor ?? "green"} disabled={disabled}@@ -418,7 +432,7 @@ export function SceneInspector({ job, shots, references, folderPath = "", scenes/></PropRow>}{!animate && !chosen && defaultLook && <p className="prop-caption">Using project Look: {look.options.find((option) => option.id === defaultLook)?.label ?? defaultLook}.</p>}- {!transition && !pose && !continuing && !backdrop && <>+ {!transition && !pose && !continuing && !backdrop && !longShot && <><PropRow label={animate ? "Repainted frame" : "Start frame"} htmlFor={`${id}-start`} tooltip={animate ? "A frame of the driving video with the character repainted. Keep its pose, framing, background and lighting." : undefined}><ReferenceSelectorid={`${id}-start`}@@ -440,7 +454,7 @@ export function SceneInspector({ job, shots, references, folderPath = "", scenes{addImageButton(animate ? "Add repainted frame" : "Add start frame", onAddStartFrame)}</PropRow></>}- {!animate && !transition && !pose && !continuing && !backdrop && <PropRow label="Last frame" htmlFor={`${id}-end`}>+ {!animate && !transition && !pose && !continuing && !backdrop && !longShot && <PropRow label="Last frame" htmlFor={`${id}-end`}><ReferenceSelector id={`${id}-end`} value={job.endFrameReferenceId ?? ""} disabled={disabled} aria-label="Last frame for this scene"references={references} accept={["image"]} folderPath={folderPath}onChange={(value) => onChange({ endFrameReferenceId: value || undefined })} />diff --git a/src/components/workspace/TimelineView.tsx b/src/components/workspace/TimelineView.tsxindex 117f920..a933312 100644--- a/src/components/workspace/TimelineView.tsx+++ b/src/components/workspace/TimelineView.tsx@@ -1,6 +1,7 @@import { clipEffectCount, ClipEffects } from "./ClipEffects";import { clipPlaybackRate, clipSourceTimeMs, MIN_CLIP_SPEED, MAX_CLIP_SPEED } from "../../lib/clipTiming";import { continuationPlaybackTracks, sceneMediaDurationMs, sceneMediaStartSeconds } from "../../lib/continuationMedia";+import { longShotPlaybackSource } from "../../lib/longShot";import { ProjectStatus } from "./ProjectStatus";import { PreviewEngineStatus } from "./PreviewEngineStatus";import {@@ -1270,6 +1271,7 @@ export function TimelineView({ config, folderPath, generationCompletionTimes = {{panelTab === "scenes" ? (<div className="scene-list" role="tabpanel" aria-label="Scenes">{config.generationJobs.map((job, index) => {+ const joined = longShotPlaybackSource(job, config);const assetIds = new Set([generationAssetId(job.id),...config.assets.filter((asset) => job.outputRelativePath && asset.relativePath === job.outputRelativePath).map((asset) => asset.id),@@ -1296,7 +1298,7 @@ export function TimelineView({ config, folderPath, generationCompletionTimes = {{...tooltipProps(`${job.title} · ${sceneShape(job)}. Drag onto a track to use it.`)}><span className="scene-card__thumb">- {job.status !== "draft" ? <ShotThumbnail folderPath={folderPath} job={job} seconds={0} sourceOffsetSeconds={sceneMediaStartSeconds(assetsById.get(generationAssetId(job.id)))} shotNumber={1} estimatedCompletionAt={generationCompletionTimes[job.id] ?? null} />+ {job.status !== "draft" ? <ShotThumbnail folderPath={folderPath} job={joined ? { ...job, outputRelativePath: joined.source.relativePath } : job} seconds={0} sourceOffsetSeconds={joined ? joined.segment.startFrame / 24 : sceneMediaStartSeconds(assetsById.get(generationAssetId(job.id)))} shotNumber={1} estimatedCompletionAt={generationCompletionTimes[job.id] ?? null} />: <Film20 aria-hidden="true" />}<i>{String(index + 1).padStart(2, "0")}</i><em>{sceneDurationSeconds(job).toFixed(1)}s</em></span>diff --git a/src/lib/agentGeneration.ts b/src/lib/agentGeneration.tsindex 1e4bc18..e107150 100644--- a/src/lib/agentGeneration.ts+++ b/src/lib/agentGeneration.ts@@ -1,4 +1,5 @@import { isTauri } from "./persistence";+import { longShotBlocker } from "./longShot";import { continuationBlocker, continuationSceneId, generationAssetId, sceneGenerationSnapshot } from "./project";import type { ProjectSession } from "./projectSession";import { sceneGenerationRequest, sendBlocker, templateSceneBlocker } from "./sceneGeneration";@@ -35,6 +36,7 @@ export async function generateAgentScene(queue: WorkQueue, session: ProjectSessi}const source = config.generationJobs.find((candidate) => candidate.id === continuationSceneId(job, config.generationJobs));const blocker = continuationBlocker(job, config.generationJobs)+ ?? longShotBlocker(job, config)?? (source && (!source.latentRelativePath || source.status !== "completed") ? "Generate the selected source scene first." : null)?? templateSceneBlocker(job.sceneType ?? "first-last-frame", template) ?? sendBlocker(job, config.references);if (blocker) throw new Error(blocker);diff --git a/src/lib/continuationMedia.ts b/src/lib/continuationMedia.tsindex 829c54a..a5c0203 100644--- a/src/lib/continuationMedia.ts+++ b/src/lib/continuationMedia.ts@@ -1,16 +1,18 @@import { clipPlaybackRate } from "./clipTiming";+import { currentLongShotArchives } from "./longShot";import { GENERATION_FRAME_RATE, generationAssetId, sceneOutputFrames, type GenerationJob, type ProjectAsset, type ProjectConfig, type SceneMediaSegment, type TimelineClip } from "./project";const milliseconds = (frames: number) => frames * 1000 / GENERATION_FRAME_RATE;-export const sceneMediaStartSeconds = (asset?: ProjectAsset) => (asset?.sceneSegments?.at(-1)?.startFrame ?? 0) / GENERATION_FRAME_RATE;+const ownSegment = (asset?: ProjectAsset) => asset?.sceneSegments?.find((part) => generationAssetId(part.sceneId) === asset.id) ?? asset?.sceneSegments?.at(-1);+export const sceneMediaStartSeconds = (asset?: ProjectAsset) => (ownSegment(asset)?.startFrame ?? 0) / GENERATION_FRAME_RATE;/** Editing coordinates stay relative to the scene, even when its file contains* the whole chain. Old, suffix-only assets need no offset. */export const sceneMediaDurationMs = (asset: ProjectAsset): number | null | undefined =>- asset.sceneSegments?.length ? Math.round(milliseconds(asset.sceneSegments.at(-1)!.frameCount)) : asset.durationMs;+ asset.sceneSegments?.length ? Math.round(milliseconds(ownSegment(asset)!.frameCount)) : asset.durationMs;export function assetSceneSegment(asset: ProjectAsset, jobs: readonly GenerationJob[]): SceneMediaSegment | undefined {- if (asset.sceneSegments?.length) return asset.sceneSegments.at(-1);+ if (asset.sceneSegments?.length) return ownSegment(asset);const job = jobs.find((candidate) => generationAssetId(candidate.id) === asset.id);return job?.latentRelativePath && asset.durationMs ? {sceneId: job.id, latentRelativePath: job.latentRelativePath, startFrame: 0,@@ -25,7 +27,7 @@ export function sceneArchiveSegments(config: ProjectConfig, job: GenerationJob,if (!job.latentRelativePath || seen.has(job.id)) return undefined;seen.add(job.id);const asset = config.assets.find((candidate) => candidate.id === generationAssetId(job.id));- if (asset?.sceneSegments?.at(-1)?.latentRelativePath === job.latentRelativePath) return asset.sceneSegments;+ if (ownSegment(asset)?.latentRelativePath === job.latentRelativePath) return asset?.sceneSegments ?? undefined;const frames = sceneOutputFrames(job, config);if (!frames) return undefined;try {@@ -49,6 +51,7 @@ export function sceneArchiveSegments(config: ProjectConfig, job: GenerationJob,* A -> B -> C uses C's joined decode throughout the chain. */export function continuationPlaybackTracks(config: ProjectConfig) {const assets = new Map(config.assets.map((asset) => [asset.id, asset]));+ const longShots = currentLongShotArchives(config);const resolved = new Map<string, TimelineClip>();const sorted = config.timeline.tracks.flatMap((track) => track.clips).sort((a, b) => a.startMs - b.startMs);for (let index = sorted.length - 1; index >= 0; index--) {@@ -57,12 +60,22 @@ export function continuationPlaybackTracks(config: ProjectConfig) {const own = asset && assetSceneSegment(asset, config.generationJobs);let source = asset;let segment = own;+ const joinedLongShot = own && longShots.find((candidate) => candidate.sceneSegments?.some((part) => part.sceneId === own.sceneId && part.latentRelativePath === own.latentRelativePath));+ if (joinedLongShot) {+ const part = joinedLongShot.sceneSegments!.find((part) => part.sceneId === own!.sceneId)!;+ resolved.set(clip.id, { ...clip, assetId: joinedLongShot.id, sourceStartMs: clip.sourceStartMs + milliseconds(part.startFrame) });+ continue;+ }if (own) {const following = sorted.filter((next) => next.id !== clip.id && Math.abs(clip.startMs + clip.durationMs - next.startMs) <= 1).sort((a, b) => Number(b.trackId === clip.trackId) - Number(a.trackId === clip.trackId));for (const next of following) {const nextClip = resolved.get(next.id);const joined = nextClip && assets.get(nextClip.assetId);+ // Long Shot archives are selected above only after validating all+ // dependencies. Never revive a stale archive through legacy adjacency.+ const joinedOwnIndex = joined?.sceneSegments?.findIndex((part) => generationAssetId(part.sceneId) === joined.id) ?? -1;+ if (joinedOwnIndex >= 0 && joinedOwnIndex < joined!.sceneSegments!.length - 1) continue;const matching = joined?.sceneSegments?.find((part) => part.sceneId === own.sceneId && part.latentRelativePath === own.latentRelativePath);// A Start continuation contains only the opening overlap, so do// not pretend that its source file contains the whole original scene.diff --git a/src/lib/longShot.test.ts b/src/lib/longShot.test.tsnew file mode 100644index 0000000..896c301--- /dev/null+++ b/src/lib/longShot.test.ts@@ -0,0 +1,87 @@+import { expect, it } from "vitest";+import { bridgedSceneSegments, currentLongShotArchives, longShotBlocker, longShotInputs, longShotPosition } from "./longShot";+import { createDraftGenerationJob, createProjectConfig, parseProjectConfig, sceneOutputFrames } from "./project";+import { continuationPlaybackTracks, sceneMediaDurationMs, sceneMediaStartSeconds } from "./continuationMedia";+import { sceneGenerationRequest } from "./sceneGeneration";+import { buildExportPlan, defaultExportSettings } from "./export";++function project() {+ const config = createProjectConfig({ name: "Long Shot", prompt: "Walk", aspectRatio: "16:9", resolution: "416p", targetDurationSeconds: 30 });+ config.generationJobs = Array.from({ length: 5 }, (_, i) => ({ ...createDraftGenerationJob("Walk", { id: String(i + 1), sceneType: "long-shot" }),+ durationSeconds: 2, status: "completed" as const, outputRelativePath: `media/${i + 1}.mp4`, latentRelativePath: `latents/${i + 1}.safetensors` }));+ config.assets = config.generationJobs.map((job) => ({ id: `asset-${job.id}`, kind: "generated", name: job.id, relativePath: job.outputRelativePath,+ mimeType: "video/mp4", hasAudio: true, durationMs: Math.round(124 / 24 * 1000), createdAt: config.createdAt,+ sceneSegments: [{ sceneId: job.id, startFrame: 0, frameCount: 124, latentRelativePath: job.latentRelativePath! }] }));+ // The bridge gap is 46 frames; original anchors stay unchanged.+ const b = longShotInputs(config.generationJobs[1], config)!;+ config.assets[1].sceneSegments = bridgedSceneSegments("2", "latents/2.safetensors", 294, 30, b.bridge, b.leftSegments);+ config.assets[1].durationMs = 12250;+ return config;+}++it("alternates within consecutive runs and blocks missing, failed and short anchors", () => {+ const config = project();+ expect(config.generationJobs.map((job) => longShotPosition(job, config.generationJobs)?.bridge)).toEqual([false, true, false, true, false]);+ expect(longShotBlocker(config.generationJobs[1], config)).toBeNull();+ config.generationJobs[2].status = "failed";+ expect(longShotBlocker(config.generationJobs[1], config)).toContain("Generate");+ expect(longShotBlocker(config.generationJobs[1], config, false)).toBeNull();+ config.generationJobs[2].status = "completed";+ config.generationJobs[1].bridgeRightMargin = 119;+ expect(longShotBlocker(config.generationJobs[1], config)).toContain("141 frames");+ config.generationJobs[2].sceneType = "backdrop";+ expect(longShotBlocker(config.generationJobs[1], config)).toContain("following Long Shot");+ expect(longShotPosition(config.generationJobs[3], config.generationJobs)?.bridge).toBe(false);+});++it("chains complete archives to preserve both ends of shared anchors", () => {+ const config = project();+ const next = longShotInputs(config.generationJobs[3], config)!;+ expect(next.bridge).toMatchObject({ leftSceneId: "3", leftRelativePath: "latents/2.safetensors", leftFrames: 294, rightFrames: 124 });+ config.assets[3].sceneSegments = bridgedSceneSegments("4", "latents/4.safetensors", 464, 30, next.bridge, next.leftSegments);+ config.assets[3].durationMs = Math.round(464 / 24 * 1000);+ expect(currentLongShotArchives(config).map((asset) => asset.id)).toEqual(["asset-4", "asset-2"]);+ const segments = config.assets[3].sceneSegments;+ config.timeline.tracks[0].clips = segments.map((part) => ({ id: part.sceneId, assetId: `asset-${part.sceneId}`, trackId: config.timeline.tracks[0].id,+ label: part.sceneId, startMs: Math.round(part.startFrame / 24 * 1000), sourceStartMs: 100, durationMs: Math.round(part.frameCount / 24 * 1000) - 100, status: "generated" }));+ const original = JSON.stringify(config.timeline);+ expect(continuationPlaybackTracks(config)[0].clips.map((clip) => clip.assetId)).toEqual(Array(5).fill("asset-4"));+ expect(continuationPlaybackTracks(config)[0].clips.map((clip) => clip.sourceStartMs)).toEqual(segments.map((part) => 100 + part.startFrame * 1000 / 24));+ const exportPlan = buildExportPlan(config, defaultExportSettings(config));+ expect(exportPlan.audio.map((part) => part.assetId)).toEqual(Array(5).fill("asset-4"));+ expect(JSON.stringify(config.timeline)).toBe(original);+ expect(sceneOutputFrames(config.generationJobs[3], config)).toBe(46);+ expect(sceneMediaDurationMs(config.assets[3])).toBe(1917);+ expect(sceneMediaStartSeconds(config.assets[3])).toBe(294 / 24);+ expect(parseProjectConfig(JSON.parse(JSON.stringify(config))).assets[3].sceneSegments).toEqual(segments);+ // Rerendering an anchor makes every old joined decode ineligible.+ config.generationJobs[2].latentRelativePath = "latents/replaced.safetensors";+ expect(currentLongShotArchives(config)).toEqual([]);+ expect(continuationPlaybackTracks(config)[0].clips.map((clip) => clip.assetId)).toEqual(["asset-1", "asset-2", "asset-3", "asset-4", "asset-5"]);+});++it("rejects suffix-only output and keeps fresh requests independent of saved frame anchors", () => {+ const config = project();+ const input = longShotInputs(config.generationJobs[1], config)!;+ expect(() => bridgedSceneSegments("2", "latents/new.safetensors", 46, 30, input.bridge)).toThrow("both anchors");+ config.generationJobs[0].startFrameReferenceId = "old";+ config.generationJobs[0].usePreviousSceneLastFrame = true;+ const request = sceneGenerationRequest(config.generationJobs[0], config, "C:/project", 8);+ expect(request.latentBridge).toBeUndefined();+ expect(request.previousSceneId).toBeUndefined();+ expect(request.referencePaths).toEqual([]);+});++it("uses standalone bridges when an older bridge is stale, and invalidates suffixes when it returns", () => {+ const config = project();+ // Regenerating 1 makes bridge 2 stale, without preventing a direct bridge 4.+ config.generationJobs[0].latentRelativePath = "latents/new-first.safetensors";+ config.assets[0].sceneSegments![0].latentRelativePath = config.generationJobs[0].latentRelativePath;+ const next = longShotInputs(config.generationJobs[3], config)!;+ expect(next.bridge.leftRelativePath).toBe("latents/3.safetensors");+ config.assets[3].sceneSegments = bridgedSceneSegments("4", "latents/4.safetensors", 294, 30, next.bridge, next.leftSegments);+ expect(currentLongShotArchives(config).map((asset) => asset.id)).toEqual(["asset-4"]);+ const previous = longShotInputs(config.generationJobs[1], config)!;+ config.assets[1].sceneSegments = bridgedSceneSegments("2", "latents/2.safetensors", 294, 30, previous.bridge, previous.leftSegments);+ expect(currentLongShotArchives(config).map((asset) => asset.id)).toEqual(["asset-2"]);+});diff --git a/src/lib/longShot.ts b/src/lib/longShot.tsnew file mode 100644index 0000000..c008d5f--- /dev/null+++ b/src/lib/longShot.ts@@ -0,0 +1,106 @@+import { generationAssetId, sceneDurationSeconds, sceneOutputFrames, type GenerationJob, type ProjectAsset, type ProjectConfig, type SceneGenerationInput, type SceneMediaSegment } from "./project";++export const LONG_SHOT_CONTEXT = 22;+export const bridgeGapFrames = (frames: number) => Math.max(12, Math.ceil((frames - 12) / 17) * 17 + 12);++/** Alternation restarts at the beginning of each consecutive Long Shot run. */+export function longShotPosition(job: GenerationJob, jobs: readonly GenerationJob[]) {+ if (job.sceneType !== "long-shot") return null;+ const index = jobs.findIndex((candidate) => candidate.id === job.id);+ if (index < 0) return null;+ let start = index;+ while (start > 0 && jobs[start - 1].sceneType === "long-shot") start--;+ const bridge = (index - start) % 2 === 1;+ return { index, start, bridge,+ left: bridge ? jobs[index - 1] : undefined,+ right: bridge && jobs[index + 1]?.sceneType === "long-shot" ? jobs[index + 1] : undefined,+ previousBridge: bridge && index - start > 1 ? jobs[index - 2] : undefined };+}++export function longShotDependencies(job: GenerationJob, jobs: readonly GenerationJob[]): GenerationJob[] {+ const position = longShotPosition(job, jobs);+ return position?.bridge ? [position.left, position.right].filter((source): source is GenerationJob => !!source) : [];+}++export function longShotBlocker(job: GenerationJob, config: ProjectConfig, requireCompleted = true): string | null {+ const position = longShotPosition(job, config.generationJobs);+ if (!position?.bridge) return null;+ if (!position.left || !position.right) return "Add a following Long Shot scene before generating this bridge.";+ for (const [source, margin] of [[position.left, job.bridgeLeftMargin ?? 17], [position.right, job.bridgeRightMargin ?? 17]] as const) {+ if (requireCompleted && (source.status !== "completed" || !source.latentRelativePath || !source.outputRelativePath))+ return `Generate “${source.title}” first, or use Generate all. Both neighboring clips need saved latents.`;+ const sourceAsset = config.assets.find((asset) => asset.id === generationAssetId(source.id));+ if (requireCompleted && (sourceAsset?.sceneSegments?.length ?? 0) > 1)+ return `Regenerate “${source.title}” as a fresh Long Shot anchor first.`;+ const plannedFrames = Math.max(22, Math.ceil((sceneDurationSeconds(source) * 24 - 5) / 17) * 17 + 5);+ const frames = requireCompleted ? sceneOutputFrames(source, config) : Math.max(sceneOutputFrames(source, config) ?? 0, plannedFrames);+ if (frames != null && frames < margin + LONG_SHOT_CONTEXT) return `“${source.title}” needs at least ${margin + LONG_SHOT_CONTEXT} frames for this bridge. Reduce its editable margin or lengthen the source.`;+ if (!!source.latentUpscale !== !!job.latentUpscale) return "Use the same Latent upscale setting for the bridge and both neighboring clips.";+ }+ return null;+}++export function currentLongShotArchives(config: Pick<ProjectConfig, "assets" | "generationJobs">): ProjectAsset[] {+ const candidates = config.assets.filter((asset) => {+ const parts = asset.sceneSegments;+ const own = parts?.findIndex((part) => generationAssetId(part.sceneId) === asset.id) ?? -1;+ if (!parts || own <= 0 || own >= parts.length - 1) return false;+ const first = config.generationJobs.findIndex((job) => job.id === parts[0].sceneId);+ if (first < 0 || !parts.every((part, offset) => config.generationJobs[first + offset]?.id === part.sceneId && config.generationJobs[first + offset]?.sceneType === "long-shot")) return false;+ if (!parts.every((part) => config.generationJobs.some((job) => job.id === part.sceneId && job.status === "completed" && job.latentRelativePath === part.latentRelativePath))) return false;+ const owner = config.generationJobs.find((job) => generationAssetId(job.id) === asset.id)!;+ const position = longShotPosition(owner, config.generationJobs);+ if (!position?.bridge || position.left?.id !== parts[own - 1].sceneId || position.right?.id !== parts[own + 1].sceneId) return false;+ return true;+ }).sort((a, b) => config.generationJobs.findIndex((job) => generationAssetId(job.id) === a.id)+ - config.generationJobs.findIndex((job) => generationAssetId(job.id) === b.id));+ const valid: ProjectAsset[] = [];+ for (const asset of candidates) {+ const owner = config.generationJobs.find((job) => generationAssetId(job.id) === asset.id)!;+ const previous = longShotPosition(owner, config.generationJobs)?.previousBridge;+ // A newly completed earlier bridge changes the shared anchor's head.+ // A suffix must incorporate it, but an invalid earlier bridge is optional.+ if (previous && valid.some((candidate) => candidate.id === generationAssetId(previous.id))+ && !asset.sceneSegments!.some((part) => part.sceneId === previous.id)) continue;+ // Reject chains that embed an earlier, now-incompatible joined archive.+ if (asset.sceneSegments!.some((part) => {+ const job = config.generationJobs.find((job) => job.id === part.sceneId)!;+ return job.id !== owner.id && longShotPosition(job, config.generationJobs)?.bridge+ && !valid.some((candidate) => candidate.id === generationAssetId(job.id));+ })) continue;+ valid.push(asset);+ }+ return valid.sort((a, b) => b.sceneSegments!.length - a.sceneSegments!.length);+}++export function longShotPlaybackSource(job: GenerationJob, config: Pick<ProjectConfig, "assets" | "generationJobs">) {+ const source = currentLongShotArchives(config).find((asset) => asset.sceneSegments?.some((part) => part.sceneId === job.id && part.latentRelativePath === job.latentRelativePath));+ const segment = source?.sceneSegments?.find((part) => part.sceneId === job.id);+ return source && segment ? { source, segment } : null;+}++export function longShotInputs(job: GenerationJob, config: ProjectConfig): { bridge: NonNullable<SceneGenerationInput["latentBridge"]>; leftSegments?: SceneMediaSegment[] } | null {+ const position = longShotPosition(job, config.generationJobs);+ if (!position?.bridge) return null;+ const { left, right, previousBridge } = position;+ const prefix = previousBridge && currentLongShotArchives(config).find((asset) => asset.id === generationAssetId(previousBridge.id)+ && asset.sceneSegments?.at(-1)?.sceneId === left?.id);+ const leftSegments = prefix?.sceneSegments ?? (left?.latentRelativePath ? [{ sceneId: left.id, latentRelativePath: left.latentRelativePath, startFrame: 0, frameCount: sceneOutputFrames(left, config) ?? 0 }] : undefined);+ return { bridge: {+ leftSceneId: left?.id ?? "", rightSceneId: right?.id ?? "",+ ...(left?.latentRelativePath ? { leftRelativePath: prefix ? previousBridge!.latentRelativePath! : left.latentRelativePath,+ leftFrames: leftSegments!.at(-1)!.startFrame + leftSegments!.at(-1)!.frameCount } : {}),+ ...(right?.latentRelativePath ? { rightRelativePath: right.latentRelativePath, rightFrames: sceneOutputFrames(right, config) } : {}),+ leftMarginFrames: job.bridgeLeftMargin ?? 17, rightMarginFrames: job.bridgeRightMargin ?? 17, contextFrames: LONG_SHOT_CONTEXT,+ }, leftSegments: leftSegments ?? undefined };+}++export function bridgedSceneSegments(jobId: string, path: string, totalFrames: number, requestedFrames: number,+ bridge: NonNullable<SceneGenerationInput["latentBridge"]>, prefix?: SceneMediaSegment[]): SceneMediaSegment[] {+ const gap = bridgeGapFrames(requestedFrames);+ if (!bridge.leftRelativePath || !bridge.rightRelativePath || !bridge.leftFrames || !bridge.rightFrames+ || totalFrames !== bridge.leftFrames + gap + bridge.rightFrames) throw new Error("The Long Shot output does not contain both anchors and the complete bridge. Update the worker and regenerate.");+ return [...(prefix ?? [{ sceneId: bridge.leftSceneId, latentRelativePath: bridge.leftRelativePath, startFrame: 0, frameCount: bridge.leftFrames }]),+ { sceneId: jobId, latentRelativePath: path, startFrame: bridge.leftFrames, frameCount: gap },+ { sceneId: bridge.rightSceneId, latentRelativePath: bridge.rightRelativePath, startFrame: bridge.leftFrames + gap, frameCount: bridge.rightFrames }];+}diff --git a/src/lib/project.ts b/src/lib/project.tsindex fc0cc58..1e8a59f 100644--- a/src/lib/project.ts+++ b/src/lib/project.ts@@ -454,7 +454,7 @@ export const SCENE_MIN_SECONDS = 0;* length is read as — the length every shot has always been generated at. */export const DEFAULT_SCENE_SECONDS = 6;-export const sceneTypeSchema = z.enum(["first-last-frame", "continue", "animate", "pose", "character-replace", "extend", "bridge", "backdrop"]);+export const sceneTypeSchema = z.enum(["first-last-frame", "continue", "animate", "pose", "character-replace", "extend", "bridge", "backdrop", "long-shot"]);export type SceneType = z.infer<typeof sceneTypeSchema>;export const DEFAULT_CONTINUATION_OVERLAP = 22;export const MAX_CONTINUATION_OVERLAP = 362;@@ -542,6 +542,8 @@ export const generationJobSchema = z.object({id: idSchema,sceneType: sceneTypeSchema.nullish(),backdropColor: z.enum(["green", "blue", "black", "white"]).nullish(),+ bridgeLeftMargin: z.number().int().min(0).max(340).multipleOf(17).nullish(),+ bridgeRightMargin: z.number().int().min(0).max(340).multipleOf(17).nullish(),poseVideoReferenceId: idSchema.nullish(),startVideoReferenceId: idSchema.nullish(),endVideoReferenceId: idSchema.nullish(),@@ -977,7 +979,7 @@ export function audioReferenceBlocker(job: GenerationJob, bound: ProjectReferenc* order. Frame anchors use their first image, even on a multi-image reference;* the same anchor selected for both ends is sent only once. */export function sceneGenerationReferences(job: GenerationJob, references: ProjectReference[]): ProjectReference[] {- if (job.sceneType === "backdrop") {+ if (job.sceneType === "backdrop" || job.sceneType === "long-shot") {const cited = sceneShots(job).flatMap(shotReferenceIds);return references.filter((reference) => cited.includes(reference.id));}@@ -1040,7 +1042,7 @@ export function continuationBlocker(job: GenerationJob, jobs: readonly Generatio/** The saved scene's output length, not the current editable duration. */export function sceneOutputFrames(job: GenerationJob, config: ProjectConfig): number | undefined {const asset = config.assets.find((candidate) => candidate.id === generationAssetId(job.id));- const segment = asset?.sceneSegments?.at(-1);+ const segment = asset?.sceneSegments?.find((part) => part.sceneId === job.id) ?? asset?.sceneSegments?.at(-1);if (segment?.sceneId === job.id) return segment.frameCount;if (asset?.durationMs) return Math.round(asset.durationMs * GENERATION_FRAME_RATE / 1000);try {@@ -1162,6 +1164,12 @@ export function sceneGenerationSeed(job: GenerationJob): number {export interface SceneGenerationInput {prompt: string;+ latentBridge?: {+ leftSceneId: string; rightSceneId: string;+ leftRelativePath?: string; rightRelativePath?: string;+ leftFrames?: number; rightFrames?: number;+ leftMarginFrames: number; rightMarginFrames: number; contextFrames: number;+ };videoTransition?: "extend" | "bridge";frames: number;steps: number;@@ -1195,6 +1203,7 @@ export function sceneGenerationSnapshot(job: GenerationJob, input: SceneGenerati...(job.sceneType ? { sceneType: job.sceneType } : {}),prompt: input.prompt,...(input.videoTransition ? { videoTransition: input.videoTransition } : {}),+ ...(input.latentBridge ? { latentBridge: input.latentBridge } : {}),frames: input.frames,steps: input.steps,...(input.audioSteps !== undefined ? { audioSteps: input.audioSteps } : {}),@@ -1245,6 +1254,9 @@ export function compileMiniMaxH3PromptSegments(}export function compileGenerationJobSegments(job: GenerationJob, references: ProjectReference[] = [], defaultLook?: string | null): PromptSegment[] {+ if (job.sceneType === "long-shot") return compileScenePromptSegments({+ shots: sceneShots(job), soundscape: job.soundscape, music: job.music,+ }, sceneGenerationReferences(job, references), defaultLook);if (job.sceneType === "backdrop") return compileScenePromptSegments({shots: sceneShots(job), soundscape: job.soundscape, music: job.music, backdropColor: job.backdropColor ?? "green",}, sceneGenerationReferences(job, references), defaultLook);diff --git a/src/lib/runtime.ts b/src/lib/runtime.tsindex 6ba5004..4ac9f1f 100644--- a/src/lib/runtime.ts+++ b/src/lib/runtime.ts@@ -9,6 +9,7 @@ import { isTauri } from "./persistence";import type { TemplateLora } from "./loras";import { refreshDownloadedLoras, refreshDownloadedWeights } from "./weightDownloads";import { sceneArchiveSegments, sceneMediaDurationMs } from "./continuationMedia";+import { bridgeGapFrames } from "./longShot";import {actionReferenceIds, createDraftGenerationJob, GENERATION_FRAME_RATE, parseProjectConfig,sceneBriefText, type AgentMessage, type GenerationJob, type ProjectAsset, type ProjectConfig,@@ -94,6 +95,7 @@ export interface AgentTurnResponse {export interface SlopfabGenerationRequest {jobId: string;videoTransition?: "extend" | "bridge";+ latentBridge?: import("./project").SceneGenerationInput["latentBridge"];prompt: string;frames: number;stillImage?: boolean;@@ -269,7 +271,8 @@ export async function resolveSlopfabPlan(request: SlopfabGenerationRequest, confconst tail = source && sceneArchiveSegments(config, source)?.at(-1);const prefix = request.continuationFrom === "start" ? request.continuationOverlapFrames ?? 22: tail ? tail.startFrame + tail.frameCount : request.continuationSourceFrames ?? 22;- const alignedFrames = request.continuationRelativePath ? prefix + Math.ceil(request.frames / 17) * 17+ const alignedFrames = request.latentBridge ? (request.latentBridge.leftFrames ?? 0) + bridgeGapFrames(request.frames) + (request.latentBridge.rightFrames ?? 0)+ : request.continuationRelativePath ? prefix + Math.ceil(request.frames / 17) * 17: Math.ceil(Math.max(5, request.frames - 5) / 17) * 17 + 5;return {canvasWidth: request.canvasWidth,diff --git a/src/lib/sceneGeneration.ts b/src/lib/sceneGeneration.tsindex 81eb9aa..4422528 100644--- a/src/lib/sceneGeneration.ts+++ b/src/lib/sceneGeneration.ts@@ -1,4 +1,5 @@import { generationDimensions } from "./export";+import { longShotInputs } from "./longShot";import {audioReferenceBlocker, characterReplaceBlocker, poseBlocker, isVideoTransition, videoTransitionBlocker,usableAudioReferences, usableVideoReferences, referenceRefmodInputs, compileGenerationJobPrompt,@@ -17,8 +18,10 @@ export function sceneGenerationRequest(job: GenerationJob, config: ProjectConfigconst inputs = sceneFrameInputs(job, config);const bound = inputs.references;const canvas = generationDimensions(config.settings.resolution, config.settings.aspectRatio);+ const longShot = longShotInputs(job, config);return {jobId: job.id,+ ...(longShot ? { latentBridge: longShot.bridge } : {}),...(job.sceneType === "extend" || job.sceneType === "bridge" ? { videoTransition: job.sceneType } : {}),// Recompiled from current state so edits to a bound reference or a// retimed shot reach the engine, rather than sending a prompt frozen atdiff --git a/src/lib/workQueue.test.ts b/src/lib/workQueue.test.tsindex 3b7b2b7..a4f9374 100644--- a/src/lib/workQueue.test.ts+++ b/src/lib/workQueue.test.ts@@ -18,6 +18,7 @@ import { compileImagePrompt } from "./imagePrompt";import { addImageNode, createImageEditScene } from "./imageScene";import { createEmptyImage, makeImagePrimary, restoreGeneratedImage } from "./imageHistory";import { sceneGenerationRequest } from "./sceneGeneration";+import { bridgeGapFrames } from "./longShot";vi.mock("@tauri-apps/api/core", () => ({ invoke: vi.fn() }));vi.mock("@tauri-apps/api/event", () => ({ listen: vi.fn() }));@@ -80,6 +81,50 @@ it("releases submitted snapshots after each generation while keeping completed rexpect(saveGeneratedScene).toHaveBeenCalledTimes(3);});+it("resolves queued Long Shot dependencies after encoding and extends the joined archive", async () => {+ const { queue, first } = setup();+ first.update((config) => ({ ...config, generationJobs: Array.from({ length: 5 }, (_, i) => ({ ...config.generationJobs[0], id: String(i + 1), sceneType: "long-shot" as const })) }));+ vi.mocked(resolveSlopfabPlan).mockImplementation(async (request) => ({ ...plan, alignedFrames: request.latentBridge+ ? request.latentBridge.leftFrames! + bridgeGapFrames(request.frames) + request.latentBridge.rightFrames! : 124 }) as Awaited<ReturnType<typeof resolveSlopfabPlan>>);+ const config = first.getSnapshot().config;+ const submissions = [0, 2, 1, 4, 3].map((i) => ({ job: config.generationJobs[i], snapshot: "queued",+ request: sceneGenerationRequest(config.generationJobs[i], config, first.record.folderPath, 8) }));+ const ids = queue.enqueue(first, submissions);+ // Later UI edits must not change the queued margin.+ first.update((current) => ({ ...current, generationJobs: current.generationJobs.map((job) => job.id === "2" ? { ...job, bridgeLeftMargin: 34 } : job) }));+ for (let index = 0; index < ids.length; index++) {+ await waitFor(() => expect(enqueueSlopfabGeneration).toHaveBeenCalledTimes(index + 1));+ await finish(queue, ids[index]);+ }+ const requests = vi.mocked(enqueueSlopfabGeneration).mock.calls.map(([request]) => request);+ expect(requests[2].latentBridge).toMatchObject({ leftRelativePath: `latents/${ids[0]}.safetensors`, rightRelativePath: `latents/${ids[1]}.safetensors`, leftFrames: 124, rightFrames: 124, leftMarginFrames: 17 });+ const bridgeGap = bridgeGapFrames(requests[2].frames);+ expect(requests[4].latentBridge).toMatchObject({ leftRelativePath: `latents/${ids[2]}.safetensors`, rightRelativePath: `latents/${ids[3]}.safetensors`, leftFrames: 248 + bridgeGap });+ const saved = parseProjectConfig(JSON.parse(JSON.stringify(first.getSnapshot().config)));+ expect(saved.assets.find((asset) => asset.id === "asset-4")?.sceneSegments?.map((part) => part.sceneId)).toEqual(["1", "2", "3", "4", "5"]);+ expect(saved.assets.find((asset) => asset.id === "asset-3")?.sceneSegments).toHaveLength(1);+ expect(JSON.parse(saved.generationJobs[1].generationSnapshot!).latentBridge.leftMarginFrames).toBe(17);+});++it.each(["failure", "reorder"])("refuses a queued Long Shot bridge after anchor %s", async (reason) => {+ const { queue, first } = setup();+ first.update((config) => ({ ...config, generationJobs: Array.from({ length: 3 }, (_, i) => ({ ...config.generationJobs[0], id: String(i + 1), sceneType: "long-shot" as const })) }));+ const config = first.getSnapshot().config;+ const ids = queue.enqueue(first, [0, 2, 1].map((i) => ({ job: config.generationJobs[i], snapshot: "queued",+ request: sceneGenerationRequest(config.generationJobs[i], config, first.record.folderPath, 8) })));+ await waitFor(() => expect(enqueueSlopfabGeneration).toHaveBeenCalledOnce());+ if (reason === "failure") emit("slopfab-job", { jobId: ids[0], state: "failed", detail: "Anchor failed" });+ else {+ first.update((current) => ({ ...current, generationJobs: [...current.generationJobs].reverse() }));+ await finish(queue, ids[0]);+ }+ await waitFor(() => expect(enqueueSlopfabGeneration).toHaveBeenCalledTimes(2));+ await finish(queue, ids[1]);+ await waitFor(() => expect(queue.getSnapshot().find((item) => item.id === ids[2])?.status).toBe("failed"));+ expect(enqueueSlopfabGeneration).toHaveBeenCalledTimes(2);+ expect(queue.getSnapshot().find((item) => item.id === ids[2])?.error).toMatch(reason === "failure" ? /Generate/ : /neighbors changed/);+});+it("releases a cancelled queued snapshot before the running job finishes", async () => {const { queue, first, second } = setup();const [running] = queue.enqueue(first, [submission(first)]);diff --git a/src/lib/workQueue.ts b/src/lib/workQueue.tsindex 7ec76ef..6da0d93 100644--- a/src/lib/workQueue.ts+++ b/src/lib/workQueue.ts@@ -25,6 +25,7 @@ import { ReferenceIconWork } from "./referenceIconWork";import { prepareReferenceVideos, releaseReferenceVideos } from "./referenceVideo";import { prepareReferenceAudios, releaseReferenceAudios } from "./referenceAudio";import { joinedSceneSegments, sceneArchiveSegments } from "./continuationMedia";+import { bridgedSceneSegments, longShotBlocker, longShotInputs } from "./longShot";import type { SceneMediaSegment } from "./project";import { exportReferenceRefmod, refmodExportBlocker, refmodExportRequest, type RefmodExportTarget } from "./refmodExport";@@ -68,6 +69,7 @@ interface PendingWork {};outputFrames?: number;continuationSegments?: SceneMediaSegment[];+ bridgeSegments?: SceneMediaSegment[];imageDraftId?: string;/** The family a regenerated image joins. */imageParentId?: string;@@ -441,6 +443,20 @@ export class WorkQueue {output: { width: work.request.canvasWidth, height: work.request.canvasHeight } });if (work.cancelled) continue;}+ if (work.request.latentBridge) {+ const live = work.session.getSnapshot().config;+ const captured = work.config.generationJobs.find((job) => job.id === work.sceneId)!;+ const current = live.generationJobs.find((job) => job.id === work.sceneId);+ const inputs = current && longShotInputs({ ...current, bridgeLeftMargin: captured.bridgeLeftMargin, bridgeRightMargin: captured.bridgeRightMargin }, live);+ if (!inputs || inputs.bridge.leftSceneId !== work.request.latentBridge.leftSceneId || inputs.bridge.rightSceneId !== work.request.latentBridge.rightSceneId)+ throw new Error("The Long Shot neighbors changed while queued. Queue this scene again.");+ const blocker = longShotBlocker({ ...captured, latentUpscale: work.request.latentUpscale }, live);+ if (blocker) throw new Error(blocker);+ work.request.latentBridge = inputs.bridge;+ work.bridgeSegments = inputs.leftSegments;+ work.snapshot = sceneGenerationSnapshot(captured, work.request);+ this.updateScene(work, { generationSnapshot: work.snapshot });+ }if (work.request.previousSceneId) {const previous = work.session.getSnapshot().config.generationJobs.find((job) => job.id === work.request.previousSceneId);if (!previous?.latentRelativePath || previous.status !== "completed") {@@ -668,7 +684,9 @@ export class WorkQueue {});const assetId = generationAssetId(work.sceneId);const totalFrames = saved.durationMs ? Math.round(saved.durationMs * GENERATION_FRAME_RATE / 1000) : work.outputFrames ?? work.request.frames;- const sceneSegments = joinedSceneSegments(work.sceneId, generationLatentPath(work.id), totalFrames,+ const sceneSegments = work.request.latentBridge+ ? bridgedSceneSegments(work.sceneId, generationLatentPath(work.id), totalFrames, work.request.frames, work.request.latentBridge, work.bridgeSegments)+ : joinedSceneSegments(work.sceneId, generationLatentPath(work.id), totalFrames,Math.ceil(work.request.frames / 17) * 17, work.request.previousSceneId ? {sceneId: work.request.previousSceneId, latentRelativePath: work.request.continuationRelativePath!,frameCount: work.request.continuationSourceFrames ?? totalFrames - Math.ceil(work.request.frames / 17) * 17,