Make videos on the computer you already own. FreeVideo runs MiniMax H3 in as little as 8 GB of VRAM and 16 GB of RAM, and adapts its acceleration path to your hardware.
Creation panel keeps settings, prompt and media after refresh, reopen, undo and redo
Bowen Xue499c32756db6
diff --git a/scripts/test_freevideo_entry.mjs b/scripts/test_freevideo_entry.mjsindex de10236..b27a7be 100644--- a/scripts/test_freevideo_entry.mjs+++ b/scripts/test_freevideo_entry.mjs@@ -93,7 +93,7 @@ test('main browser entry registers both views and preserves node hooks', async t.replace("import { outputDownloadURL } from './output_download.js';", 'const {outputDownloadURL} = globalThis.__freevideoEntryTest;').replace("import { shareButton } from './share.js';", 'const {shareButton} = globalThis.__freevideoEntryTest;').replace("import { reportFileName } from './report_issue.js';", 'const {reportFileName} = globalThis.__freevideoEntryTest;')- .replace("import { rememberPromptDraft, savePromptDraft } from './prompt_draft.js';", 'const {rememberPromptDraft,savePromptDraft} = globalThis.__freevideoEntryTest;')+ .replace("import { rememberPromptDraft, savePromptDraft, trackPromptDraft, watchPromptHistory, promptHistoryRestoring } from './prompt_draft.js';", 'const {rememberPromptDraft,savePromptDraft} = globalThis.__freevideoEntryTest; const trackPromptDraft = () => {}; const watchPromptHistory = () => {}; const promptHistoryRestoring = () => false;').replace("import { cleanOptionalWidgets, cleanOptionalPrompt } from './optional_inputs.js';", 'const {cleanOptionalWidgets,cleanOptionalPrompt} = globalThis.__freevideoEntryTest;').replace("import { regenerateResult, upscaleResult } from './studio_queue.js';", 'const {regenerateResult,upscaleResult} = globalThis.__freevideoEntryTest;').replace("import { openImageEditor, icon } from './image_editor.js';", 'const {openImageEditor,icon} = globalThis.__freevideoEntryTest;')diff --git a/web/freevideo.js b/web/freevideo.jsindex 28c1d75..7f8d40e 100644--- a/web/freevideo.js+++ b/web/freevideo.js@@ -13,7 +13,7 @@ import { attachReferencePicker, referenceItems, syncReferencePrompt, referenceInimport { outputDownloadURL } from './output_download.js';import { shareButton } from './share.js';import { reportFileName } from './report_issue.js';-import { rememberPromptDraft, savePromptDraft } from './prompt_draft.js';+import { rememberPromptDraft, savePromptDraft, trackPromptDraft, watchPromptHistory, promptHistoryRestoring } from './prompt_draft.js';import { cleanOptionalWidgets, cleanOptionalPrompt } from './optional_inputs.js';import { regenerateResult, upscaleResult } from './studio_queue.js';import { openImageEditor, icon } from './image_editor.js';@@ -569,6 +569,42 @@ function resultPanel(node) {}let configuringGraph = false;+let configuration = 0;+const watchedGraphs = new WeakSet();+function captureWorkflow(graph) {+ if (!graph || graph !== app.graph || promptHistoryRestoring(app)) return;+ watchPromptHistory(api, app);+ const tracker = app.extensionManager?.workflow?.activeWorkflow?.changeTracker;+ // Current ComfyUI and older installations expose different names.+ (tracker?.captureCanvasState || tracker?.checkState)?.call(tracker);+}+function trackCreationDraft(node) {+ trackPromptDraft(node, () => captureWorkflow(node.graph), () => app.extensionManager?.workflow?.activeWorkflow?.path);+}+function watchCreationGraph(graph) {+ if (!graph || watchedGraphs.has(graph)) return;+ watchedGraphs.add(graph);+ const changed = graph.on_change;+ let queued = false;+ graph.on_change = function (...args) {+ const result = changed?.apply(this, args);+ if (!configuringGraph && graph === app.graph && !queued) {+ queued = true;+ const revision = configuration;+ queueMicrotask(() => {+ queued = false;+ if (configuringGraph || graph !== app.graph || revision !== configuration || promptHistoryRestoring(app)) return;+ // graph.change() only redraws. Capture the finished edit, including+ // properties and the asynchronous media/LoRA panel updates.+ captureWorkflow(graph);+ for (const node of graph._nodes || []) {+ if (node.comfyClass === 'FreeVideoGenerate' || node.type === 'FreeVideoGenerate') rememberPromptDraft(api, node);+ }+ });+ }+ return result;+ };+}function syncPrompts(reset = false) {if (configuringGraph && reset !== true) return;for (const node of app.graph?._nodes || []) if (node.type === 'FreeVideoGenerate') syncReferencePrompt(node, text, reset === true);@@ -593,7 +629,7 @@ const progressConnection = createProgressConnection(api, message => {app.registerExtension({name: "FreeVideo.UnifiedMedia",- beforeConfigureGraph() { configuringGraph = true; },+ beforeConfigureGraph() { configuringGraph = true; configuration++; },async setup() {// One failing part must not take the others down; health.js shows what failed.for (const [where, start] of [['progress', () => progressConnection.start()], ['navigation', () => installNavigation(showStudio, agentInterfaceEnabled(api))],@@ -601,6 +637,7 @@ app.registerExtension({try { start(); } catch (error) { health({type: 'error', where, error}); }}window.addEventListener('pagehide', () => savePromptDraft(api, true));+ void savePromptDraft(api); // Retry this tab's outbox after an interrupted save.window.FreeVideoUI = {...window.FreeVideoUI, ready: true};await notifyCompatibility();},@@ -654,13 +691,17 @@ app.registerExtension({'修改采样步数可能降低生成质量。默认一采 8 步、二采 3 步;其他二采步数需小于一采步数。');}}- const prompt = this.widgets?.find(w => w.name === 'text');- if (prompt) {- // Every edit, in the creation panel or on the node, is the draft the launcher reopens.- const node = this, callback = prompt.callback;- prompt.callback = function (...args) { if (!configuringGraph) rememberPromptDraft(api, node); return callback?.apply(this, args); };- prompt.inputEl?.addEventListener?.('input', () => rememberPromptDraft(api, node));+ for (const widget of this.widgets || []) {+ // Node and creation-panel edits use the same named draft.+ const node = this, callback = widget.callback;+ widget.callback = function (...args) {+ const result = callback?.apply(this, args);+ if (!configuringGraph) rememberPromptDraft(api, node);+ return result;+ };+ widget.inputEl?.addEventListener?.('input', () => { if (!configuringGraph) rememberPromptDraft(api, node); });}+ trackCreationDraft(this);resultPanel(this);this.addWidget('button', text('Open creative workspace', '打开创作面板'), null, () => showStudio(this), {serialize: false});const removed = this.onRemoved;@@ -673,6 +714,13 @@ app.registerExtension({afterConfigureGraph() {syncPrompts(true);configuringGraph = false;+ for (const node of app.graph?._nodes || []) {+ if (node.comfyClass !== 'FreeVideoGenerate' && node.type !== 'FreeVideoGenerate') continue;+ trackCreationDraft(node);+ }+ watchCreationGraph(app.graph);+ // The host activates the target workflow after afterConfigureGraph.+ requestAnimationFrame(() => watchPromptHistory(api, app));progressConnection.reset();progressConnection.refresh();refreshNavigation();diff --git a/web/launcher.js b/web/launcher.jsindex 836d860..5c32c47 100644--- a/web/launcher.js+++ b/web/launcher.js@@ -10,6 +10,41 @@ const studioWorkflow = graph => (graph?._nodes || graph?.nodes || []).some(n =>const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));let configured = performance.now();+async function existingStudioWorkflow(target, bundled) {+ // Restored background tabs are lazy: load() reads the host's saved draft,+ // whereas the workflow store's openWorkflow() only selects the tab record.+ await target.load?.();+ const saved = target.changeTracker?.activeState;+ // Leave the current graph intact; the existing startup check reports an+ // unopened workflow without replacing the user's project.+ if (!saved) return null;+ const graph = structuredClone(saved);+ if (!graph.nodes?.some(node => node.type === 'FreeVideoGenerate')) {+ const node = structuredClone(bundled.nodes.find(node => node.type === 'FreeVideoGenerate'));+ node.id = Math.max(graph.last_node_id || 0, ...graph.nodes.map(node => Number(node.id) || 0)) + 1;+ graph.last_node_id = node.id;+ node.pos = [Math.max(0, ...graph.nodes.map(node => (node.pos?.[0] || 0) + (node.size?.[0] || 400))) + 80, 100];+ for (const input of node.inputs || []) input.link = null;+ for (const output of node.outputs || []) output.links = null;+ graph.nodes.push(node);+ // Reconnect a single unambiguous media source, leaving every existing+ // node and link intact. Multiple media sources keep their own topology.+ const media = graph.nodes.filter(node => node.type === 'FreeVideoMedia');+ const input = node.inputs?.findIndex(input => input.name === 'media') ?? -1;+ const output = media.length === 1 ? media[0].outputs?.findIndex(output => output.type === node.inputs?.[input]?.type) ?? -1 : -1;+ if (input >= 0 && output >= 0 && graph.version === .4) {+ graph.links ||= [];+ const id = Math.max(graph.last_link_id || 0, ...graph.links.map(link => link[0])) + 1;+ graph.links.push([id, media[0].id, output, node.id, input, node.inputs[input].type]);+ (media[0].outputs[output].links ||= []).push(id);+ node.inputs[input].link = id;+ graph.last_link_id = id;+ }+ }+ graph.extra = {...graph.extra, freevideo_studio: true};+ return restorePromptDraft(api, graph, target.path);+}+// ComfyUI restores the previous session's workflow and tabs after every// extension's setup, so that restore can bring another workflow to the front// over ours. Once startup is quiet, bring our tab back into view even if a@@ -17,17 +52,31 @@ let configured = performance.now();// setup returns.async function keepInFront(workflow, opened) {let touched = false;- const touch = event => { if (!event.target?.closest?.('.fv-studio, .fv-health')) touched = true; };+ const touch = event => { if (!event.target?.closest?.('.fv-health')) touched = true; };addEventListener('pointerdown', touch, true); addEventListener('keydown', touch, true);try {const begin = performance.now();while (performance.now() - begin < 15000&& (app.extensionManager?.spinner || performance.now() - configured < 600)) await sleep(100);- // An already visible FreeVideo graph may contain edits; keep that copy.- if (studioWorkflow(app.graph)) return;const store = app.extensionManager?.workflow;+ // Opening the bundled graph before session restore overwrites the cached+ // FreeVideo tab, including its media and connections. Reuse that project.+ if (studioWorkflow(app.graph)) {+ const current = app.graph.serialize(), target = store?.activeWorkflow;+ const restored = await restorePromptDraft(api, structuredClone(current), target?.path || '__existing__');+ if (JSON.stringify(restored) !== JSON.stringify(current))+ await app.loadGraphData(restored, true, true, target || 'FreeVideo');+ return;+ }// The user kept working in our own tab: its edits stay, even without the generate node.if (touched && opened && store?.activeWorkflow === opened) return;+ const existing = store?.getWorkflowByPath?.('workflows/FreeVideo.json')+ || store?.openWorkflows?.find(row => studioWorkflow(row.changeTracker?.activeState));+ if (existing) {+ const restored = await existingStudioWorkflow(existing, workflow);+ if (restored) await app.loadGraphData(restored, true, true, existing);+ return;+ }// Our own tab when ComfyUI still has it; a new one otherwise.const target = opened && store?.getWorkflowByPath?.(opened.path) === opened ? opened : 'FreeVideo';await app.loadGraphData(structuredClone(workflow), true, true, target);diff --git a/web/prompt_draft.js b/web/prompt_draft.jsindex 28ccdb7..7fa30fa 100644--- a/web/prompt_draft.js+++ b/web/prompt_draft.js@@ -1,48 +1,205 @@-// The launcher opens a fresh copy of the bundled workflow each time, so the-// prompt being written, finished or not, is kept in ComfyUI's user data and put-// back into that copy. The untouched starter prompt is the default, not a draft;-// a box emptied after typing is one, and reopens empty.+// The launcher starts from the bundled graph. Keep creation choices by name,+// alongside the existing schema-1 prompt draft; ordinary reloads keep their graph.const FILE = '/userdata/' + encodeURIComponent('freevideo/prompt-draft.json');-let timer = null, pending = null;+const WIDGETS = ['text', 'width', 'height', 'seconds', 'seed', 'control_after_generate', 'two_pass',+ 'base_steps', 'refine_steps', 'force_regenerate', 'preview', 'refine_from', 'continue_from', 'frames', 'first_frame_reference'];+const DEFAULTS = ['', 1344, 768, 10, 2026090903, 'randomize', true, 8, 3, false, false, '', '', 0, false];+const SAVED_WIDGETS = WIDGETS.filter(name => !['text', 'force_regenerate', 'refine_from', 'continue_from', 'frames'].includes(name));+const PROPERTIES = ['freevideo_aspect', 'freevideo_pixels', 'freevideo_seconds', 'freevideo_single',+ 'freevideo_block_seconds', 'freevideo_run_mode', 'freevideo_batch_count'];+const OUTBOX = 'freevideo.prompt-pending';+const clone = value => JSON.parse(JSON.stringify(value));+const equal = (a, b) => JSON.stringify(a) === JSON.stringify(b);+const watched = new WeakMap(), dirty = new Set();+const historyObservers = new WeakSet(), restoringHistory = new WeakSet();+let timer = null, pending = null, inFlight = null, sending = null;+try { pending = JSON.parse(globalThis.sessionStorage?.getItem(OUTBOX) || 'null'); } catch {}++function retain() {+ try {+ if (pending || sending) globalThis.sessionStorage?.setItem(OUTBOX, JSON.stringify(mergePatches(sending, pending)));+ else globalThis.sessionStorage?.removeItem(OUTBOX);+ } catch { /* Saving still works when browser storage is disabled. */ }+}export function promptDraft(node) {const text = node?.widgets?.find(w => w.name === 'text')?.value;if (typeof text !== 'string') return null;const versions = node.properties?.freevideo_prompt_versions;- return {schema: 1, text: node.freevideoStarterPrompt && text === node.freevideoStarterPrompt ? null : text,- versions: versions && typeof versions === 'object' ? versions : null};+ const draft = {schema: 1, text: node.freevideoStarterPrompt && text === node.freevideoStarterPrompt ? null : text,+ versions: versions && typeof versions === 'object' ? clone(versions) : null};+ const widgets = Object.fromEntries((node.widgets || []).filter(w => SAVED_WIDGETS.includes(w.name)).map(w => [w.name, w.value]));+ const properties = Object.fromEntries(PROPERTIES.filter(key => Object.hasOwn(node.properties || {}, key)).map(key => [key, node.properties[key]]));+ if (Object.keys(widgets).length) draft.widgets = clone(widgets);+ if (Object.keys(properties).length) draft.properties = clone(properties);+ return draft;}export function applyPromptDraft(workflow, draft) {const node = workflow?.nodes?.find(row => row.type === 'FreeVideoGenerate');if (!node || !Array.isArray(node.widgets_values) || draft?.schema !== 1) return workflow;if (typeof draft.text === 'string') node.widgets_values[0] = draft.text;+ if (draft.project && node.properties) {+ for (const key of PROPERTIES) if (!Object.hasOwn(draft.properties || {}, key)) delete node.properties[key];+ if (!draft.versions) delete node.properties.freevideo_prompt_versions;+ }+ for (const name of SAVED_WIDGETS) {+ const value = draft.widgets?.[name], index = WIDGETS.indexOf(name);+ if (value === undefined || typeof value !== typeof DEFAULTS[index]+ || (typeof value === 'number' && !Number.isFinite(value))) continue;+ while (node.widgets_values.length <= index) node.widgets_values.push(DEFAULTS[node.widgets_values.length]);+ node.widgets_values[index] = value;+ }+ for (const key of PROPERTIES) if (Object.hasOwn(draft.properties || {}, key)) {+ node.properties ||= {};+ node.properties[key] = draft.properties[key];+ }const versions = draft.versions;if (versions && typeof versions.original === 'string' && typeof versions.rewritten === 'string')- node.properties = {...node.properties, freevideo_prompt_versions: versions};+ node.properties = {...node.properties, freevideo_prompt_versions: clone(versions)};return workflow;}+// Baseline comes from the configured node, never the shared server draft. A stale+// tab therefore contributes only its actual edits, including property resets.+export function trackPromptDraft(node, onChange, project) {+ if (dirty.has(node)) collect(node);+ watched.set(node, {last: promptDraft(node), onChange: onChange || watched.get(node)?.onChange || (() => {}),+ project: project || watched.get(node)?.project});+}++function combine(base, patch) {+ const value = {...(patch.project && (base?.schema !== 1 || (base.project && patch.project !== base.project)) ? patch.snapshot+ : base?.schema === 1 ? base : {schema: 1, text: null, versions: null})};+ for (const key of ['text', 'versions', 'project']) if (Object.hasOwn(patch, key)) value[key] = patch[key];+ for (const group of ['widgets', 'properties']) if (patch[group]) {+ value[group] = {...value[group]};+ for (const [key, entry] of Object.entries(patch[group])) {+ if (entry === null) delete value[group][key]; else value[group][key] = entry;+ }+ }+ return value;+}+function mergePatches(base, patch) {+ if (patch?.project && base?.project && patch.project !== base.project) base = null;+ return {...base, ...patch,+ widgets: {...base?.widgets, ...patch?.widgets}, properties: {...base?.properties, ...patch?.properties}};+}+function addPatch(patch) {+ pending = mergePatches(pending, patch);+ retain();+}+function collect(node, notify = true) {+ dirty.delete(node);+ const next = promptDraft(node), state = watched.get(node);+ if (!next) return;+ const previous = state?.last || {text: null, versions: null};+ const patch = {};+ if (!equal(next.text, previous.text) || !equal(next.versions, previous.versions)) {+ patch.text = next.text; patch.versions = next.versions;+ }+ for (const group of ['widgets', 'properties']) {+ for (const key of new Set([...Object.keys(previous[group] || {}), ...Object.keys(next[group] || {})])) {+ if (!equal(previous[group]?.[key], next[group]?.[key])) {+ (patch[group] ||= {})[key] = next[group]?.[key] ?? null;+ }+ }+ }+ if (Object.keys(patch).length) {+ const project = state?.project?.();+ if (project) { patch.project = project; patch.snapshot = next; }+ addPatch(patch); if (notify) state?.onChange();+ }+ watched.set(node, {last: next, onChange: state?.onChange || (() => {}), project: state?.project});+}+export function rememberPromptDraft(api, node) {- pending = node; clearTimeout(timer);+ dirty.add(node);+ // Compound edits finish their widget callbacks and properties in this turn.+ queueMicrotask(() => { if (dirty.has(node)) collect(node); });+ clearTimeout(timer);timer = setTimeout(() => savePromptDraft(api), 500);}-// keepalive lets the last edit outlive a closing page.+export function promptHistoryRestoring(app) {+ return restoringHistory.has(app.extensionManager?.workflow?.activeWorkflow?.changeTracker);+}++// The host replaces node instances when replaying history. Observe the completed+// undo/redo transaction, comparing against the nodes it replaced, without adding+// a new undo step or treating an ordinary project load as an edit.+export function watchPromptHistory(api, app) {+ const workflow = app.extensionManager?.workflow?.activeWorkflow, tracker = workflow?.changeTracker;+ if (!tracker || historyObservers.has(tracker)) return;+ historyObservers.add(tracker);+ for (const method of ['undo', 'redo']) {+ const replay = tracker[method];+ if (typeof replay !== 'function') continue;+ tracker[method] = async function (...args) {+ if (app.extensionManager?.workflow?.activeWorkflow !== workflow) return replay.apply(this, args);+ for (const node of dirty) collect(node);+ const previous = new Map((app.graph?._nodes || []).map(node => [node.id, promptDraft(node)]));+ restoringHistory.add(tracker);+ let result;+ try { result = await replay.apply(this, args); }+ finally { restoringHistory.delete(tracker); }+ if (app.extensionManager?.workflow?.activeWorkflow !== workflow) return result;+ for (const node of app.graph?._nodes || []) {+ if (node.type !== 'FreeVideoGenerate' && node.comfyClass !== 'FreeVideoGenerate') continue;+ const state = watched.get(node);+ watched.set(node, {...state, project: () => workflow.path,+ last: previous.get(node.id) || {text: null, versions: null}});+ rememberPromptDraft(api, node);+ collect(node, false);+ }+ return result;+ };+ }+}++// Serialize read/merge/write across tabs and keep failed patches for retry. The+// per-tab outbox also survives refreshing during an in-flight request.export async function savePromptDraft(api, keepalive = false) {clearTimeout(timer); timer = null;- const draft = promptDraft(pending); pending = null;- if (!draft) return false;- try {- const reply = await api.fetchApi(FILE + '?overwrite=true', {method: 'POST', body: JSON.stringify(draft), keepalive});- return reply.ok;- } catch { return false; }+ for (const node of dirty) collect(node);+ if (inFlight) {+ if (!await inFlight) return false;+ return pending ? savePromptDraft(api, keepalive) : true;+ }+ if (!pending) return false;+ const patch = pending; pending = null; sending = patch;+ const write = async () => {+ try {+ const reply = await api.fetchApi(FILE, {cache: 'no-store', keepalive});+ if (!reply.ok && reply.status !== 404) throw new Error('draft_read');+ const current = reply.ok ? await reply.json() : null;+ const saved = await api.fetchApi(FILE + '?overwrite=true', {method: 'POST',+ headers: {'Content-Type': 'application/json'}, body: JSON.stringify(combine(current, patch)), keepalive});+ if (!saved.ok) throw new Error('draft_write');+ sending = null; retain(); return true;+ } catch {+ const newer = pending; pending = patch; sending = null;+ if (newer) addPatch(newer); else retain();+ return false;+ }+ };+ inFlight = globalThis.navigator?.locks ? navigator.locks.request('freevideo-prompt-draft', write) : write();+ try { return await inFlight; } finally { inFlight = null; }}-export async function restorePromptDraft(api, workflow) {+export async function restorePromptDraft(api, workflow, project = null) {+ // A refreshed page retries its own unsaved patch before launcher restoration.+ if (pending || inFlight || dirty.size) await savePromptDraft(api);+ let draft;try {const reply = await api.fetchApi(FILE, {cache: 'no-store'});- if (reply.ok) return applyPromptDraft(workflow, await reply.json());- } catch { /* No draft yet, or unreadable: open the bundled prompt. */ }+ if (reply.ok) draft = await reply.json();+ } catch { /* Keep the workflow and any local edits if the server is offline. */ }+ // A failed retry remains authoritative over the older remote copy. Retain+ // the outbox until a later explicit save succeeds, including across reloads.+ const local = pending || sending ? mergePatches(sending, pending) : null;+ if (local && (!project || !local.project || local.project === project)) draft = combine(draft, local);+ // Unscoped schema-1 drafts predate project ownership and must migrate too.+ if (!project || !draft?.project || draft.project === project) return applyPromptDraft(workflow, draft);return workflow;}diff --git a/web/studio.js b/web/studio.jsindex 23b978a..3e021ce 100644--- a/web/studio.js+++ b/web/studio.js@@ -22,7 +22,7 @@ import { reconcileLoraTriggers } from './lora_triggers.js';import { createSamplingEffort } from './sampling_effort.js';import { resultActions, previewBadge, icon } from './result_actions.js';import { createPromptEnhancer } from './prompt_enhance.js';-import { rememberPromptDraft } from './prompt_draft.js';+import { rememberPromptDraft, trackPromptDraft } from './prompt_draft.js';import { canvasDimensions, imageSizeSelection } from './studio_size.js';import { createCapabilityView } from './capability_view.js';import { openEditorView } from './editor_loader.js';@@ -48,7 +48,8 @@ const linked = (node, name) => node?.inputs?.some(input => input.name === name &const value = (node, name) => widget(node, name)?.value;function set(node, name, value) {const w = widget(node, name); if (!w || linked(node, name)) return false;- w.value = value; w.callback?.(value); node.graph?.change(); node.setDirtyCanvas?.(true, true); return true;+ w.value = value; w.callback?.(value); node.graph?.change(); node.setDirtyCanvas?.(true, true);+ rememberPromptDraft(api, node); return true;}function upstream(node, name) {const input = node.inputs?.find(i => i.name === name);@@ -344,6 +345,9 @@ export function openStudio(node, {extendFrom = null} = {}) {const extension = createExtendState(node, name => value(node, name), (name, v) => set(node, name, v));if (extendFrom && !extension.enter(extendFrom)) throw new Error(extendText(t, 'unavailable'));const dialog = el('dialog', null, 'fv-studio'); dialog.setAttribute('aria-label', t('FreeVideo creative workspace', 'FreeVideo 创作面板'));+ // ComfyUI's background dialogs can lock body pointer events. This native+ // modal is above them and must remain interactive when the launcher reopens it.+ dialog.style.pointerEvents = 'auto';current = {node, dialog}; const cleanup = [];const header = el('header', null, 'fv-header'), brand = el('div', null, 'fv-brand');brand.append(wordmark());@@ -863,7 +867,8 @@ export function openStudio(node, {extendFrom = null} = {}) {}const runbar = el('div', null, 'fv-runbar');let busy = false, queued = false, cancelling = false, activePrompt = null, capturing = false;- let runMode = 'single', queueState;+ let runMode = ['single', 'batch', 'loop'].includes(node.properties?.freevideo_run_mode)+ ? node.properties.freevideo_run_mode : 'single', queueState;if (!studioQueues.has(node)) studioQueues.set(node, createStudioQueue(api, node.id, {formatError: (error, snapshot) => createErrorReport(error, {stage: 'submission', snapshot, node, graph: app.graph}),// Direct snapshot submission still feeds the same graph result panel.@@ -923,14 +928,23 @@ export function openStudio(node, {extendFrom = null} = {}) {optionsPanel.append(el('strong', t('Generation mode', '生成方式')));const modeButtons = [];for (const [id, label] of [['single', t('One video', '单次生成')], ['batch', t('Batch', '批量生成')], ['loop', t('Loop', '循环生成')]]) {- const b = button(label, () => { runMode = id; updateRunButton(); });+ const b = button(label, () => {+ runMode = id; node.properties.freevideo_run_mode = id;+ rememberPromptDraft(api, node); updateRunButton();+ });b.dataset.mode = id; modeButtons.push(b); optionsPanel.append(b);}- const count = el('input'); count.type = 'number'; count.min = '2'; count.max = '100'; count.step = '1'; count.value = '4';+ const count = el('input'); count.type = 'number'; count.min = '2'; count.max = '100'; count.step = '1';+ count.value = node.properties?.freevideo_batch_count ?? 4;count.setAttribute('aria-label', t('Number of videos', '生成数量'));const countField = field(t('Number of videos', '生成数量'), count); optionsPanel.append(countField);const modeHelp = el('p', '', 'fv-muted'); optionsPanel.append(modeHelp);- count.oninput = () => updateRunButton();+ count.oninput = () => {+ if (count.value && count.checkValidity()) {+ node.properties.freevideo_batch_count = Number(count.value); rememberPromptDraft(api, node);+ }+ updateRunButton();+ };runOptions.append(optionsToggle, optionsPanel);const generate = button('', submitDraft, 'fv-primary');generate.dataset.fvGuide = 'generate';@@ -985,7 +999,10 @@ export function openStudio(node, {extendFrom = null} = {}) {const submitting = capturing || queueState?.submitting;updateFirstFrame();const multiple = lengthControl.plan?.count > 1;- if (multiple) runMode = 'single';+ // A long/continued video temporarily uses one run. Keep the user's mode+ // preference so returning to a short video and reloading show the same choice.+ runMode = multiple || extension.source ? 'single'+ : ['single', 'batch', 'loop'].includes(node.properties?.freevideo_run_mode) ? node.properties.freevideo_run_mode : runMode;generate.disabled = submitting || chainController?.active || lengthControl.blocked || (runMode === 'loop' && queueState?.looping);generate.textContent = submitting ? t('Adding…', '正在添加…'): runMode === 'batch' ? t(`Add ${count.value || '…'} videos`, `添加 ${count.value || '…'} 条任务`)@@ -1284,5 +1301,7 @@ export function openStudio(node, {extendFrom = null} = {}) {}}).catch(() => {});requestAnimationFrame(() => { if (dialog.open && !dialog.querySelector('.fv-guide-layer') && !document.querySelector('dialog.fv-editor[open]')) (extension.source ? prompt : generate).focus({preventScroll: true}); });+ // Establish the baseline after UI initialization; opening a panel is not an edit.+ trackPromptDraft(node);return dialog;}