Skip to content

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.

Keep FreeVideo out of ComfyUI workflows without FreeVideo nodes

Bowen Xuecada503263d9
diff --git a/scripts/test_freevideo_entry.mjs b/scripts/test_freevideo_entry.mjs
index 0ef2313..5ef1282 100644
--- a/scripts/test_freevideo_entry.mjs
+++ b/scripts/test_freevideo_entry.mjs
@@ -77,7 +77,7 @@ test('main browser entry registers both views and preserves node hooks', async t
};
const previous = new Map();
for (const [name, value] of Object.entries({
- document, navigator: {language: 'en'}, window: events,
+ document, navigator: {language: 'en'}, window: events, addEventListener: (type, fn, options) => events.addEventListener(type, fn, options),
getComputedStyle: element => ({marginTop: '8px', marginBottom: '8px', display: element.hidden ? 'none' : 'block', ...element.style}),
CustomEvent: class extends Event { constructor(name, options) { super(name); this.detail = options?.detail; } },
requestAnimationFrame: callback => callback(), __freevideoEntryTest: dependencies,
@@ -109,7 +109,9 @@ test('main browser entry registers both views and preserves node hooks', async t
.replace("import { regenerateResult, createSecondPassQueue, enableNode } from './studio_queue.js';", 'const {regenerateResult,createSecondPassQueue,enableNode} = globalThis.__freevideoEntryTest;')
.replace("import { secondPassAction } from './result_actions.js';", 'const {secondPassAction} = globalThis.__freevideoEntryTest;')
.replace("import { openImageEditor, icon } from './image_editor.js';", 'const {openImageEditor,icon} = globalThis.__freevideoEntryTest;')
- .replace("import { installNavigation, refreshNavigation, preferredView } from './view_navigation.js';", 'const {installNavigation,refreshNavigation,preferredView} = globalThis.__freevideoEntryTest;')
+ .replace("import { installNavigation, refreshNavigation, preferredView, collapseWorkspaces } from './view_navigation.js';", 'const {installNavigation,refreshNavigation,preferredView} = globalThis.__freevideoEntryTest; const collapseWorkspaces = () => { globalThis.__freevideoEntryTest.collapsed = (globalThis.__freevideoEntryTest.collapsed || 0) + 1; };')
+ .replace("import { isLaunchVisit } from './launch_visit.js';", 'const isLaunchVisit = () => false;')
+ .replace("import { openFreeVideoWorkflow } from './launcher.js';", 'const openFreeVideoWorkflow = (...args) => globalThis.__freevideoEntryTest.openFreeVideoWorkflow?.(...args);')
.replace("import { imageGenerationSupported } from './image_generation.js';", 'const imageGenerationSupported = () => true;')
.replace("import { createCastLibrary } from './cast_library.js';", 'const {createCastLibrary} = globalThis.__freevideoEntryTest;')
.replace("import { agentInterfaceEnabled } from './agent_connect.js';", 'const agentInterfaceEnabled = async () => false;');
@@ -180,8 +182,28 @@ test('main browser entry registers both views and preserves node hooks', async t
node.widgets[0].value = false; node.onConfigure();
assert.equal(node.widgets[0].value, 8, 'Migrate the previous private force-checkbox slot');
node.buttons[0].callback();
+ const quiet = opened.length;
+ extension.afterConfigureGraph();
+ assert.equal(opened.length, quiet, 'a tab restored with the page does not open the workspace on its own');
+ events.dispatchEvent(new Event('pointerdown'));
extension.afterConfigureGraph();
assert.deepEqual(opened, [node, node]);
+ // A workflow without FreeVideo nodes is the user's own: every workspace makes way and none opens.
+ const nodes = app.graph._nodes, collapsed = dependencies.collapsed || 0;
+ app.graph._nodes = [];
+ extension.afterConfigureGraph();
+ assert.equal(dependencies.collapsed, collapsed + 1); assert.deepEqual(opened, [node, node]);
+ // The menu entry opens the workspace of the workflow in front, or FreeVideo's own workflow when it has no node.
+ const entry = extension.commands.find(row => row.id === 'FreeVideo.Open');
+ assert.equal(entry.label, 'FreeVideo'); assert.deepEqual(extension.menuCommands[0].commands, ['FreeVideo.Open']);
+ let workflows = 0;
+ dependencies.openFreeVideoWorkflow = async () => { workflows++; return node; };
+ const before = opened.length;
+ await entry.function();
+ assert.equal(workflows, 1); assert.equal(opened.length, before + 1); assert.equal(app.graph._nodes.length, 0);
+ app.graph._nodes = nodes;
+ await entry.function();
+ assert.equal(workflows, 1); assert.equal(opened.length, before + 2);
rememberedView = 'editor';
const restored = [];
dependencies.openEditorView = (value, options) => restored.push({node:value, studio:options.studio});
diff --git a/web/done_notify.js b/web/done_notify.js
index c2bcec3..d5bf111 100644
--- a/web/done_notify.js
+++ b/web/done_notify.js
@@ -1,12 +1,13 @@
// Tells the user a long run has finished while FreeVideo is in a background tab:
// the tab title flashes and one short beep plays until the page is shown again.
// A desktop notification is sent only when the user turned it on in the settings.
+// Only a queue that ran a FreeVideo node counts: other workflows finish silently.
export const DESKTOP_SETTING = 'FreeVideo.DoneNotify.Desktop';
const LONG_RUN_MS = 20000, FLASH_MS = 1000;
-export function startDoneNotify({api, text, doc = document, win = window, now = () => Date.now(), desktop = () => false,
+export function startDoneNotify({api, text, doc = document, win = window, now = () => Date.now(), desktop = () => false, isFreeVideoNode = () => false,
beep = playBeep, notify = desktopNotice, minimum = LONG_RUN_MS, setTimer = setInterval, clearTimer = clearInterval} = {}) {
- let busySince = null, failed = false, cancelled = false, flashing = null;
+ let busySince = null, failed = false, cancelled = false, flashing = null, involved = false;
const away = () => doc.hidden || (typeof doc.hasFocus === 'function' && !doc.hasFocus());
function stopFlashing() {
@@ -26,25 +27,35 @@ export function startDoneNotify({api, text, doc = document, win = window, now =
const remaining = event?.detail?.exec_info?.queue_remaining;
if (!Number.isFinite(remaining)) return;
if (remaining > 0) {
- if (busySince === null) { busySince = now(); failed = false; cancelled = false; }
+ if (busySince === null) { busySince = now(); failed = false; cancelled = false; involved = false; }
return;
}
if (busySince === null) return;
const elapsed = now() - busySince; busySince = null;
- if (cancelled || elapsed < minimum || !away()) return;
+ if (!involved || cancelled || elapsed < minimum || !away()) return;
remind(!failed);
}
- const error = () => { failed = true; };
+ const error = event => { failed = true; if (/^FreeVideo/.test(String(event?.detail?.node_type || ''))) involved = true; };
+ const freevideo = () => { involved = true; };
+ const executing = event => {
+ const id = typeof event?.detail === 'object' ? event.detail?.node : event?.detail;
+ if (id != null && isFreeVideoNode(id)) involved = true;
+ };
const interrupted = () => { cancelled = true; };
const shown = () => { if (!away()) stopFlashing(); };
api.addEventListener('status', status);
api.addEventListener('execution_error', error);
api.addEventListener('execution_interrupted', interrupted);
+ api.addEventListener('freevideo_progress', freevideo);
+ api.addEventListener('freevideo_prewarm', freevideo);
+ api.addEventListener('executing', executing);
doc.addEventListener('visibilitychange', shown);
win.addEventListener?.('focus', shown);
return {stop() {
api.removeEventListener('status', status); api.removeEventListener('execution_error', error);
api.removeEventListener('execution_interrupted', interrupted);
+ api.removeEventListener('freevideo_progress', freevideo); api.removeEventListener('freevideo_prewarm', freevideo);
+ api.removeEventListener('executing', executing);
doc.removeEventListener('visibilitychange', shown); win.removeEventListener?.('focus', shown); stopFlashing();
}};
}
diff --git a/web/editor.js b/web/editor.js
index 64f4abd..520c7d1 100644
--- a/web/editor.js
+++ b/web/editor.js
@@ -1170,6 +1170,9 @@ export function openEditor({api, app, from = null, panel = {}, components: given
});
const leaving = () => { player.pause(); rememberView(); if (queue.dirty) queue.flush(); };
window.addEventListener('pagehide', leaving);
+ // A workflow without FreeVideo nodes came to the front: the editing view makes way (unsaved edits stay open).
+ const collapse = () => { void handle.close(); };
+ window.addEventListener('freevideo-collapse', collapse);
const handle = {element, state, actions, store, adjust, audio, notify,
async switchView(view) {
if (closing || disposed || view === 'editor') return;
@@ -1198,7 +1201,7 @@ export function openEditor({api, app, from = null, panel = {}, components: given
progressConnection?.stop(); progressObserver?.disconnect(); runProgress.clear(); failures.clear();
stopKeys();
resumeCanvasPointer();
- window.removeEventListener('pagehide', leaving); clearTimeout(noticeTimer);
+ window.removeEventListener('pagehide', leaving); window.removeEventListener('freevideo-collapse', collapse); clearTimeout(noticeTimer);
for (const stop of jobWatchers.values()) stop(); jobWatchers.clear();
queue.dispose({discard: discardOnSwitch}); store.dispose(); if (element.open) element.close(); element.replaceChildren(); element.remove(); if (opened === handle) opened = null;
if (returnFocus?.isConnected) returnFocus.focus({preventScroll: true});
diff --git a/web/freevideo.js b/web/freevideo.js
index cc15a3e..22b12b4 100644
--- a/web/freevideo.js
+++ b/web/freevideo.js
@@ -8,7 +8,9 @@ import { createProgressConnection } from './progress_connection.js';
import { notifyCompatibility } from './compatibility.js';
import { startUpdateChecks } from './updates.js';
import { startDoneNotify, askDesktopPermission, DESKTOP_SETTING } from './done_notify.js';
-import { installNavigation, refreshNavigation, preferredView } from './view_navigation.js';
+import { installNavigation, refreshNavigation, preferredView, collapseWorkspaces } from './view_navigation.js';
+import { isLaunchVisit } from './launch_visit.js';
+import { openFreeVideoWorkflow } from './launcher.js';
import { agentInterfaceEnabled } from './agent_connect.js';
import { attachReferencePicker, referenceItems, syncReferencePrompt, referenceInputs, mediaRows } from './prompt_references.js';
import { expandCast } from './cast_mention.js';
@@ -626,17 +628,38 @@ const progressConnection = createProgressConnection(api, message => {
window.dispatchEvent(new CustomEvent('freevideo-progress', {detail: message}));
});
+const isGenerate = node => node?.comfyClass === 'FreeVideoGenerate' || node?.type === 'FreeVideoGenerate';
+const isFreeVideoNode = id => /^FreeVideo/.test(String(app.graph?.getNodeById(id)?.comfyClass || app.graph?.getNodeById(id)?.type || ''));
+// Only the launcher, a click or a key brings a workspace over a page; a restored tab alone never does.
+const launchVisit = isLaunchVisit(globalThis.location?.search, globalThis.sessionStorage);
+let userActed = false;
+for (const type of ['pointerdown', 'keydown']) globalThis.addEventListener?.(type, () => { userActed = true; }, {capture: true, once: true});
+
+async function openFromMenu() {
+ try {
+ const node = (app.graph?._nodes || []).find(isGenerate) || await openFreeVideoWorkflow();
+ if (!node) throw new Error('FreeVideo workflow unavailable');
+ showStudio(node);
+ } catch (error) {
+ console.warn('FreeVideo menu:', error);
+ app.extensionManager?.toast?.add({severity: 'error', summary: 'FreeVideo', detail: text('Could not complete. Try again.', '没有完成,请重试'), life: 9000});
+ }
+}
+
const desktopNoticeEnabled = () => (app.extensionManager?.setting?.get?.(DESKTOP_SETTING) ?? app.ui?.settings?.getSettingValue?.(DESKTOP_SETTING)) === true;
app.registerExtension({
name: "FreeVideo.UnifiedMedia",
settings: [{id: DESKTOP_SETTING, name: text('Desktop notification when done', '完成时发桌面通知'),
type: 'boolean', defaultValue: false, onChange: value => { if (value) askDesktopPermission(); }}],
+ // The one entry that stays in ComfyUI's own menu, whatever workflow is in front.
+ commands: [{id: 'FreeVideo.Open', label: 'FreeVideo', function: openFromMenu}],
+ menuCommands: [{path: ['Extensions'], commands: ['FreeVideo.Open']}],
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))],
- ['updates', startUpdateChecks], ['done-notify', () => startDoneNotify({api, text, desktop: desktopNoticeEnabled})]]) {
+ for (const [where, start] of [['progress', () => progressConnection.start()], ['navigation', () => installNavigation(showStudio, agentInterfaceEnabled(api), {openWorkflow: openFreeVideoWorkflow})],
+ ['updates', startUpdateChecks], ['done-notify', () => startDoneNotify({api, text, desktop: desktopNoticeEnabled, isFreeVideoNode})]]) {
try { start(); } catch (error) { health({type: 'error', where, error}); }
}
window.addEventListener('pagehide', () => savePromptDraft(api, true));
@@ -731,9 +754,12 @@ app.registerExtension({
progressConnection.refresh();
refreshNavigation();
const rememberedView = preferredView();
- if ((app.graph?.extra?.freevideo_studio || rememberedView === 'editor') && rememberedView !== 'nodes') {
- const node = app.graph._nodes.find(n => n.comfyClass === 'FreeVideoGenerate' || n.type === 'FreeVideoGenerate');
- if (node) requestAnimationFrame(() => {
+ const node = (app.graph?._nodes || []).find(isGenerate);
+ // The user's own workflow is shown as it is. A FreeVideo workflow opens its workspace once the
+ // launcher or the user asked for it, never on its own for a tab restored with the page.
+ if (!node) { collapseWorkspaces(); return; }
+ if (app.graph?.extra?.freevideo_studio && rememberedView !== 'nodes' && (launchVisit || userActed)) {
+ requestAnimationFrame(() => {
const studio = showStudio(node);
if (studio && rememberedView === 'editor') {
void openEditorView(node, {studio, onFailure: error => health({type: 'error', where: 'editor', error})});
@@ -755,6 +781,10 @@ api.addEventListener('executed', event => {
node.freevideoShowResult({...output, freevideo_summary: [{...output.freevideo_summary[0], request_id: prompt_id}]});
}
});
+api.addEventListener('execution_start', () => {
+ // A workflow of the user's own is running: nothing of ours stays over it.
+ if (!(app.graph?._nodes || []).some(isGenerate)) collapseWorkspaces();
+});
api.addEventListener('freevideo_prewarm', event => {
const value = event.detail;
if (value) app.graph?.getNodeById(value.node)?.freevideoShowPrewarm?.(value);
diff --git a/web/launch_visit.js b/web/launch_visit.js
new file mode 100644
index 0000000..d6c57fd
--- /dev/null
+++ b/web/launch_visit.js
@@ -0,0 +1,11 @@
+// The launcher opens ComfyUI with freevideo=launch and then removes it from the address. The tab remembers
+// that, so a refresh of that tab behaves like the visit did; a new tab or the user's own ComfyUI does not.
+const MARK = 'freevideo.launched';
+
+export function isLaunchVisit(search, storage) {
+ const launched = new URLSearchParams(search || '').get('freevideo') === 'launch';
+ try {
+ if (launched) storage?.setItem(MARK, '1');
+ return launched || storage?.getItem(MARK) === '1';
+ } catch { return launched; }
+}
diff --git a/web/launcher.js b/web/launcher.js
index cc7a808..6b97960 100644
--- a/web/launcher.js
+++ b/web/launcher.js
@@ -62,6 +62,21 @@ async function existingStudioWorkflow(target, bundled) {
return restorePromptDraft(api, graph, target.path);
}
+// Opens FreeVideo's own workflow in a tab of its own and returns its generate node. The workflow in front
+// is left as it is: an existing FreeVideo tab comes back with its project, otherwise a new one opens.
+export async function openFreeVideoWorkflow() {
+ const response = await api.fetchApi('/freevideo/launcher/workflow');
+ if (!response.ok) throw new Error(`FreeVideo workflow: HTTP ${response.status}`);
+ const workflow = await restorePromptDraft(api, await response.json());
+ const store = app.extensionManager?.workflow;
+ const existing = store?.getWorkflowByPath?.('workflows/FreeVideo.json')
+ || store?.openWorkflows?.find(row => studioWorkflow(row.changeTracker?.activeState));
+ const restored = existing ? await existingStudioWorkflow(existing, workflow) : null;
+ if (restored) await app.loadGraphData(restored, true, true, existing);
+ else await app.loadGraphData(structuredClone(workflow), true, true, 'FreeVideo');
+ return (app.graph?._nodes || []).find(n => n.comfyClass === 'FreeVideoGenerate' || n.type === 'FreeVideoGenerate') || null;
+}
+
// 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
diff --git a/web/view_navigation.js b/web/view_navigation.js
index 579862f..3f102c9 100644
--- a/web/view_navigation.js
+++ b/web/view_navigation.js
@@ -12,7 +12,7 @@ const cn = languageOverride === 'zh' || (languageOverride !== 'en'
&& String(navigator.language || '').toLowerCase().startsWith('zh'));
const t = (en, zh) => cn ? zh : en;
const preference = 'freevideo.view';
-let toolbar, open, selected, currentView = 'nodes', agentTab = null;
+let toolbar, open, selected, currentView = 'nodes', agentTab = null, opening = null;
const style = document.createElement('link');
style.rel = 'stylesheet'; style.href = new URL('./view_navigation.css', import.meta.url).href;
document.head.append(style);
@@ -21,10 +21,13 @@ export function preferredView() {
try { return localStorage.getItem(preference); } catch { return null; }
}
+let collapsing = false;
+
export function viewChanged(view, node) {
currentView = view;
if (node) selected = node;
- try { localStorage.setItem(preference, view); } catch { /* Private browsing still works. */ }
+ // Making way for the user's own workflow is not a choice of view: the FreeVideo workflow reopens as it was left.
+ if (!collapsing) try { localStorage.setItem(preference, view); } catch { /* Private browsing still works. */ }
refreshNavigation();
}
@@ -63,11 +66,21 @@ export function viewSwitch(view, onStudio, onNodes, onEditor, onAutopilot) {
return group;
}
+const generateNodes = () => (app.graph?._nodes || []).filter(n => n.comfyClass === 'FreeVideoGenerate' || n.type === 'FreeVideoGenerate');
+
+// A workflow without a FreeVideo node is the user's own: nothing of ours stays over it.
+// Each workspace listens for this and closes itself.
+export function collapseWorkspaces() {
+ collapsing = true; setTimeout(() => { collapsing = false; }, 1000);
+ window.dispatchEvent(new Event('freevideo-collapse'));
+ for (const dialog of document.querySelectorAll('dialog.fv-studio[open]')) dialog.close();
+}
+
export function refreshNavigation() {
if (!toolbar) return;
- const nodes = (app.graph?._nodes || []).filter(n => n.comfyClass === 'FreeVideoGenerate' || n.type === 'FreeVideoGenerate');
+ const nodes = generateNodes();
if (!nodes.includes(selected)) selected = nodes[0];
- toolbar.hidden = !app.graph || currentView !== 'nodes';
+ toolbar.hidden = !app.graph || !nodes.length || currentView !== 'nodes';
for (const button of toolbar.querySelectorAll('[data-view]')) {
button.setAttribute('aria-pressed', String(button.dataset.view === currentView));
}
@@ -84,7 +97,7 @@ export function openCreativeWorkspace() {
return true;
}
-export function installNavigation(openStudio, agent = false) {
+export function installNavigation(openStudio, agent = false, {openWorkflow = null} = {}) {
open = openStudio;
if (!toolbar) agentTabReady(agent);
if (toolbar) { refreshNavigation(); return; }
@@ -98,21 +111,27 @@ export function installNavigation(openStudio, agent = false) {
const focused = Object.values(app.canvas?.selected_nodes || {}).find(n => (app.graph?._nodes || []).includes(n)
&& (n.comfyClass === 'FreeVideoGenerate' || n.type === 'FreeVideoGenerate'));
refreshNavigation();
- let node = focused || selected, created = false;
+ let node = focused || selected;
if (!node && create) {
- try {
- node = globalThis.LiteGraph?.createNode('FreeVideoGenerate');
- if (!node) throw new Error('FreeVideo node unavailable');
- app.graph.add(node); app.graph.change?.();
- selected = node; created = true;
- } catch (error) {
- console.warn('FreeVideo edit project:', error);
- app.extensionManager?.toast?.add({severity: 'error', summary: 'FreeVideo',
- detail: t('Could not complete. Try again.', '没有完成,请重试'), life: 9000});
- return null;
- }
+ // The user's own workflow stays as it is: FreeVideo gets a workflow of its own.
+ return (async () => {
+ try {
+ // Clicks while the workflow is opening share that one workflow.
+ const first = !opening;
+ opening ||= Promise.resolve(openWorkflow?.()).finally(() => { opening = null; });
+ node = await opening;
+ if (!node) throw new Error('FreeVideo workflow unavailable');
+ selected = node;
+ return await action(node, first);
+ } catch (error) {
+ console.warn('FreeVideo edit project:', error);
+ app.extensionManager?.toast?.add({severity: 'error', summary: 'FreeVideo',
+ detail: t('Could not complete. Try again.', '没有完成,请重试'), life: 9000});
+ return null;
+ }
+ })();
}
- if (node) return action(node, created);
+ if (node) return action(node, false);
};
const settings = document.createElement('button'); settings.type = 'button';
settings.textContent = t('Settings', '设置'); settings.className = 'fv-view-settings'; settings.onclick = openSetup;