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.

Other model folders are saved and used across setup and launch

Bowen Xue2ba0047e353d
diff --git a/freevideo_engine/bootstrap.py b/freevideo_engine/bootstrap.py
index c97dab6..63c5270 100644
--- a/freevideo_engine/bootstrap.py
+++ b/freevideo_engine/bootstrap.py
@@ -592,7 +592,9 @@ def plan(args, *, local_progress=None, stage=None):
local_reuse = None
local_folder = getattr(args, 'reuse_models', None)
local_manifest = getattr(args, 'reuse_models_manifest', None)
- if local_folder or local_manifest:
+ from .launcher_settings import saved_model_libraries
+ saved_libraries = saved_model_libraries()
+ if local_folder or local_manifest or saved_libraries:
from .local_models import scan, scan_many, can_link, key as local_key
previous_reuse = None
approved = getattr(args, 'approved_plan', None)
@@ -606,6 +608,12 @@ def plan(args, *, local_progress=None, stage=None):
if not isinstance(libraries, dict) or libraries.get('version') != 1 or not isinstance(libraries.get('roots'), list):
raise ValueError('Invalid model library manifest')
directories = ([str(local_folder)] if local_folder else []) + libraries['roots']
+ from .local_models import library_roots
+ directories = library_roots(library_roots(directories) + saved_libraries, keep_first=True)
+ scan_library = lambda: scan_many(directories, needed, prior=previous_reuse, callback=local_progress)
+ elif saved_libraries:
+ from .local_models import library_roots
+ directories = library_roots(([str(local_folder)] if local_folder else []) + saved_libraries, keep_first=True)
scan_library = lambda: scan_many(directories, needed, prior=previous_reuse, callback=local_progress)
else:
scan_library = lambda: scan(local_folder, needed, prior=previous_reuse, callback=local_progress)
diff --git a/freevideo_engine/comfy_launcher_runtime.py b/freevideo_engine/comfy_launcher_runtime.py
index e3397ce..94ea39b 100644
--- a/freevideo_engine/comfy_launcher_runtime.py
+++ b/freevideo_engine/comfy_launcher_runtime.py
@@ -975,7 +975,8 @@ class Controller:
extra = values.get('model_dirs', [])
if not isinstance(extra, list) or any(not isinstance(p, str) for p in extra):
raise ValueError('Model folders must be a list of directory paths')
- extra = extra + ([values['models']] if values.get('models') else [])
+ from .launcher_settings import extra_model_directories
+ extra = extra + ([values['models']] if values.get('models') else []) + extra_model_directories()
# A saved folder that no longer exists (for example a removed offline
# package) has nothing to reuse; it must not stop the installation.
extra = [p for p in dict.fromkeys(extra) if p.strip() and io_path(Path(p).expanduser()).is_dir()]
diff --git a/freevideo_engine/comfy_setup.py b/freevideo_engine/comfy_setup.py
index 77f9104..e71834c 100644
--- a/freevideo_engine/comfy_setup.py
+++ b/freevideo_engine/comfy_setup.py
@@ -25,7 +25,8 @@ from .setup_progress import ProgressState
def discover_libraries(folder_paths, environ=None):
env = os.environ if environ is None else environ
- candidates = [str(folder_paths.models_dir)]
+ from .launcher_settings import saved_model_libraries
+ candidates = saved_model_libraries() + [str(folder_paths.models_dir)]
# folder_paths already incorporates extra_model_paths.yaml, including paths
# registered by other nodes. No second, subtly different YAML parser.
for name in ('diffusion_models', 'unet', 'checkpoints', 'text_encoders', 'clip', 'vae'):
@@ -157,14 +158,34 @@ class Setup:
except (OSError, ValueError) as error:
detail = str(error)
from .sampling_assets import total_bytes
+ from .launcher_settings import extra_model_directories
return dict(root=str(root), ready=ready, detail=detail,
- libraries=discover_libraries(self.folder_paths), token=self.token,
+ libraries=discover_libraries(self.folder_paths), extra_libraries=extra_model_directories(), token=self.token,
environment='Managed FreeVideo environment; ComfyUI packages are kept',
restart_required=False, downloads=self.downloads(download_root or root),
resources=self.resource_settings(),
sampling_cache_bytes=total_bytes())
+ @plain_errors
+ def model_directories(self, value):
+ if self.runner.busy:
+ raise ValueError('Wait for setup to finish before saving model folders')
+ from .launcher_settings import model_directory_store
+ choices = model_directory_store().save_model_directories(value.get('extra_libraries'))
+ missing = []
+ for path in choices:
+ try:
+ exists = io_path(Path(path).expanduser()).is_dir()
+ except (OSError, RuntimeError):
+ exists = False
+ if not exists:
+ missing.append(path)
+ self.plan = None
+ self.state.pop('plan_id', None)
+ self.state.pop('plan', None)
+ return dict(saved=True, extra_libraries=choices, missing_libraries=missing)
+
def resource_settings(self, value=None):
from .resource_settings import read, write, setting
root = installation_root(self.source)
@@ -254,7 +275,7 @@ class Setup:
raise ValueError('Invalid setup choices')
# Folders the user chose are validated and kept first; folders found
# automatically fill the remaining places.
- chosen = library_roots(extra)
+ chosen = library_roots(extra, skip_missing=True)
libraries = library_roots(chosen + discover_libraries(self.folder_paths), keep_first=True)
io_path(self.logs).mkdir(parents=True, exist_ok=True)
manifest = self.logs / ('libraries-' + uuid.uuid4().hex + '.json')
@@ -454,6 +475,8 @@ def register():
name = request.match_info['action']
if name == 'inspect':
result = setup.inspect(value)
+ elif name == 'model-directories':
+ result = setup.model_directories(value)
elif name in ('network-probe','network-source'):
result = setup.network_settings(value,probe=name=='network-probe')
elif name == 'network-token':
diff --git a/freevideo_engine/launcher_settings.py b/freevideo_engine/launcher_settings.py
index 10a19ee..4b80a48 100644
--- a/freevideo_engine/launcher_settings.py
+++ b/freevideo_engine/launcher_settings.py
@@ -1,11 +1,12 @@
"""Durable launcher preferences, independent of an EXE's unpack directory."""
+from contextlib import ExitStack, contextmanager
import json
import os
from pathlib import Path
import sys
import time
-from .monitoring import save
+from .monitoring import save as _save
from .long_paths import io_path, plain_data
TEXT = ('comfy', 'destination', 'engine', 'models', 'python', 'url', 'language', 'offline_runtime')
@@ -14,6 +15,12 @@ ARCHIVE = ('path', 'bytes', 'mtime_ns', 'kind', 'root')
ARCHIVE_IDENTITY = ('path', 'bytes', 'mtime_ns')
+def save(path, value):
+ # sanitize() already normalizes the other settings. Keep directory choices
+ # verbatim, including a user's explicit Windows namespace spelling.
+ _save(path, value, plain_paths=False)
+
+
def default_language():
if sys.platform == 'darwin':
from .macos_preferences import preferred_language
@@ -28,6 +35,7 @@ def default_language():
def sanitize(value):
+ extra = value.get('extra_model_dirs', []) if isinstance(value, dict) else []
value = plain_data(value) if isinstance(value, dict) else {}
result = {k: value[k] for k in TEXT if isinstance(value.get(k), str)}
for key in ('separate', 'new_comfy', 'sampling_caches', 'lan_access', 'image_model'):
@@ -67,6 +75,12 @@ def sanitize(value):
resume = value.get('setup')
if isinstance(resume, dict):
result['setup'] = {k: resume[k] for k in ('status', 'action', 'phase') if isinstance(resume.get(k), str)}
+ if 'extra_model_dirs' in value:
+ from .local_models import directory_choices
+ try:
+ result['extra_model_dirs'] = directory_choices(extra)
+ except (OSError, RuntimeError, ValueError, TypeError):
+ result['extra_model_dirs'] = []
return result
@@ -118,7 +132,40 @@ class Store:
values = [read(path) for path in self.paths]
return bool(values) and all(value.get(key) is True for value in values)
+ @contextmanager
+ def exclusive(self, wait=10.):
+ """Serialize read-merge-write between the launcher and the node panel.
+
+ A lock that cannot be taken in time never stops a save: the settings
+ are small and a rare lost update is better than a button that does nothing.
+ """
+ from .locking import runtime_lock
+ stack, deadline = ExitStack(), time.monotonic() + wait
+ while True:
+ try:
+ stack.enter_context(runtime_lock(self.local.with_suffix('.lock'), inherit=False))
+ break
+ except BlockingIOError:
+ if time.monotonic() > deadline:
+ break
+ time.sleep(.05)
+ except (OSError, ValueError):
+ break
+ with stack:
+ yield
+
def write(self, values, language, selection=None, setup=None):
+ with self.exclusive():
+ return self.write_locked(values, language, selection, setup)
+
+ def write_locked(self, values, language, selection=None, setup=None):
+ # A launcher form opened before a node-panel save does not own this
+ # field. Preserve its current value when other preferences are saved.
+ values = dict(values)
+ if 'extra_model_dirs' not in values:
+ current = self.read()
+ if 'extra_model_dirs' in current:
+ values['extra_model_dirs'] = current['extra_model_dirs']
payload = sanitize(dict(values, language=language, installation=selection,
setup=setup, saved_at_ns=time.time_ns()))
failures, written = [], []
@@ -134,3 +181,34 @@ class Store:
if not written:
raise failures[0][1]
return written, failures
+
+ def save_model_directories(self, values):
+ from .local_models import directory_choices
+ choices = directory_choices(values)
+ with self.exclusive():
+ saved = self.read()
+ saved['extra_model_dirs'] = choices
+ self.write_locked(saved, saved.get('language', default_language()),
+ saved.get('installation'), saved.get('setup'))
+ return choices
+
+
+def model_directory_store():
+ from .desktop_runtime import launcher_root
+ return Store(launcher_root())
+
+
+def extra_model_directories():
+ """Untrusted preferences are validated on every read, including startup."""
+ try:
+ return model_directory_store().read().get('extra_model_dirs', [])
+ except (OSError, RuntimeError, ValueError, TypeError):
+ return []
+
+
+def saved_model_libraries():
+ from .local_models import library_roots
+ try:
+ return library_roots(extra_model_directories(), skip_missing=True)
+ except (OSError, RuntimeError, ValueError, TypeError):
+ return []
diff --git a/freevideo_engine/local_models.py b/freevideo_engine/local_models.py
index 3871365..0619cd6 100644
--- a/freevideo_engine/local_models.py
+++ b/freevideo_engine/local_models.py
@@ -16,7 +16,7 @@ MAX_ROOTS = 64
MAX_LISTED = 4096 # Paths accepted before duplicates and nested folders are merged.
-def library_roots(values, *, keep_first=False):
+def library_roots(values, *, keep_first=False, skip_missing=False):
"""Normalize selected libraries without walking entire drives.
The 64-library limit counts distinct folders: a folder named twice, or one
@@ -27,10 +27,14 @@ def library_roots(values, *, keep_first=False):
raise ValueError('Invalid model library list')
roots = []
for value in values:
- if not isinstance(value, str) or not value.strip() or len(value) > 4096:
+ if not isinstance(value, str) or not value.strip() or len(value) > 4096 or '\0' in value:
raise ValueError('Invalid model library path')
path = resolved(Path(value).expanduser())
- if not path.is_dir() or path == Path(path.anchor):
+ if path == Path(path.anchor):
+ raise ValueError('Choose an existing model folder, not an entire drive: ' + plain(path))
+ if not path.is_dir():
+ if skip_missing:
+ continue
raise ValueError('Choose an existing model folder, not an entire drive: ' + plain(path))
if path not in roots:
roots.append(path)
@@ -44,6 +48,35 @@ def library_roots(values, *, keep_first=False):
return [plain(path) for path in roots]
+def directory_choices(values):
+ """Validate preferences without requiring a mounted/existing library.
+
+ Keep the user's spelling; resolution is only for drive-root safety and
+ discovery. Missing directories must survive saving and reopening.
+ """
+ if not isinstance(values, list) or len(values) > MAX_LISTED:
+ raise ValueError('Invalid model library list')
+ choices = []
+ for value in values:
+ if not isinstance(value, str) or len(value) > 4096 or '\0' in value:
+ raise ValueError('Invalid model library path')
+ value = value.strip()
+ if not value:
+ continue
+ path = resolved(Path(value).expanduser())
+ if path == Path(path.anchor):
+ raise ValueError('Choose a model folder, not an entire drive: ' + plain(path))
+ if value not in choices:
+ choices.append(value)
+ # Count canonical distinct/nested paths just as library_roots does, even
+ # when a drive is currently disconnected.
+ roots = list(dict.fromkeys(resolved(Path(p).expanduser()) for p in choices))
+ roots = [p for p in roots if not any(parent in roots for parent in p.parents)]
+ if len(roots) > MAX_ROOTS:
+ raise ValueError('Select at most 64 model libraries')
+ return choices
+
+
def scan_many(directories, rows, *, prior=None, callback=None):
roots = library_roots(directories)
result = dict(root=roots[0] if roots else None, roots=roots, matches={},
diff --git a/freevideo_engine/monitoring.py b/freevideo_engine/monitoring.py
index 2b4ce75..c7ea98f 100644
--- a/freevideo_engine/monitoring.py
+++ b/freevideo_engine/monitoring.py
@@ -12,7 +12,7 @@ from .system import windows
from .long_paths import io_path, plain_data
-def save(path, value, *, staging=None):
+def save(path, value, *, staging=None, plain_paths=True):
path = io_path(path)
path.parent.mkdir(parents=True, exist_ok=True)
# Unique, closed staging file; Windows readers/antivirus may briefly hold
@@ -23,7 +23,7 @@ def save(path, value, *, staging=None):
prefix=path.name + '.' if staging is None else staging, suffix='.tmp',
dir=path.parent, delete=False) as stream:
temporary = Path(stream.name)
- stream.write(json.dumps(plain_data(value), ensure_ascii=False, indent=2) + '\n')
+ stream.write(json.dumps(plain_data(value) if plain_paths else value, ensure_ascii=False, indent=2) + '\n')
for attempt in range(8):
try:
temporary.replace(path)
diff --git a/web/setup.css b/web/setup.css
index a7b2f07..42c5656 100644
--- a/web/setup.css
+++ b/web/setup.css
@@ -65,6 +65,7 @@
/* Text, plans and measurements. */
.fv-setup p{margin:8px 0}
+.fv-setup [role=status]{overflow-wrap:anywhere}
.fv-setup .fv-muted{color:var(--fv-muted);font-size:var(--fv-micro);white-space:pre-wrap}
.fv-setup .fv-model-repair-path{overflow-wrap:anywhere}
.fv-setup progress{display:block;width:100%;height:6px;margin:6px 0}
diff --git a/web/setup.js b/web/setup.js
index 62d8f40..8023227 100644
--- a/web/setup.js
+++ b/web/setup.js
@@ -144,7 +144,8 @@ export async function openSetup() {
const use = node("button", t("Use existing installation", "使用已有安装"));
const install = node("button", t("Install / repair", "安装/修复")); install.disabled = true;
const cancel = node("button", t("Stop setup", "停止安装")); cancel.disabled = true;
- actions.append(inspect, use, install, cancel); installation.append(actions);
+ const saveFolders = node('button', t('Save model folders', '保存模型目录'));
+ actions.append(saveFolders, inspect, use, install, cancel); installation.append(actions);
// Why Install / repair is unavailable, so it never looks like a broken button.
const blocked = note(""); blocked.classList.add("fv-setup-why"); blocked.setAttribute("aria-live", "polite"); blocked.hidden = true;
installation.append(blocked);
@@ -156,8 +157,9 @@ export async function openSetup() {
const motions = [...dialog.querySelectorAll('details')].map(animateDetails);
dialog.addEventListener('cancel', e => { e.preventDefault(); closeDialog(dialog); });
document.body.append(dialog); dialog.showModal();
+ let savedFolders = "", savedMissing = false;
let token, planId, busy = false, probeBusy = false, pollTimer, lastPlanId, planErrors = false, planStale = false, ready = false;
- const fail = error => { installation.open = true; state.textContent = failureText(error.message); state.className = "fv-failure"; state.scrollIntoView({block:'nearest'}); };
+ const fail = error => { installation.open = true; state.textContent = [savedFolders, failureText(error.message)].filter(Boolean).join(" · "); state.className = "fv-failure"; state.scrollIntoView({block:'nearest'}); };
const request = async (action, value) => {
const response = await api.fetchApi("/freevideo/setup" + (action ? "/" + action : root.value ? '?root='+encodeURIComponent(root.value) : ""), action ? {
method: "POST", headers: { "Content-Type": "application/json", "X-FreeVideo-Setup": token }, body: JSON.stringify(value || {}),
@@ -256,7 +258,7 @@ export async function openSetup() {
catch(error) { probeButton.disabled=false; fail(error); }
};
const controls = () => {
- for (const e of [root, extra, copy, samplingCaches, inspect, use, hfToken, applyToken, clearToken]) e.disabled = busy;
+ for (const e of [root, extra, copy, samplingCaches, saveFolders, inspect, use, hfToken, applyToken, clearToken]) e.disabled = busy;
cancel.disabled = !busy; install.disabled = busy || !planId || !accept.checked; accept.disabled = busy; inspect.classList.toggle("fv-primary", !planId); install.classList.toggle("fv-primary", Boolean(planId));
const why = busy || (ready && !planId) ? "" : planStale ? t("Settings changed. Click Detect & review again to update the plan.", "设置已更改,请重新点击「检测并预览」更新安装计划。")
: planErrors ? t("The plan has problems shown in red above. Please resolve them, then click Detect & review again.", "安装计划中有标红的问题,请解决后重新点击「检测并预览」。")
@@ -280,6 +282,7 @@ export async function openSetup() {
applyToken.onclick = () => setToken(hfToken.value);
clearToken.onclick = () => setToken('');
for (const e of [root, extra, copy, samplingCaches]) e.oninput = () => invalidate(true);
+ extra.oninput = () => { if (savedFolders) state.textContent = ""; savedFolders = ""; savedMissing = false; invalidate(true); };
accept.onchange = controls;
function showPlan(value) {
plan.replaceChildren();
@@ -318,8 +321,9 @@ export async function openSetup() {
}
acceptLabel.hidden = busy || !planId;
const p = task.progress || {};
- state.className = task.status === "failed" ? "fv-failure" : task.ready ? "fv-ready" : "";
+ state.className = task.status === "failed" ? "fv-failure" : task.ready && !savedMissing ? "fv-ready" : "";
state.textContent = failureText(task.error) || (task.ready ? t("Ready. Generate with your existing workflow.", "准备就绪,可使用现有工作流生成。") : busy ? p.label || t("Checking configuration and local models…", "正在检查配置和本地模型…") : task.status === "complete" && task.action === "plan" ? (planId ? t("Review the plan, then install.", "请确认计划后安装。") : "") : task.status === "cancelled" ? t("Stopped. Files retained for resuming.", "已停止,文件保留,可继续安装。") : "");
+ state.textContent = [savedFolders, state.textContent].filter(Boolean).join(" · ");
const phases = task.phase_progress || {}, valid = Number.isFinite(p.total) && p.total > 0 && Number.isFinite(p.done) && p.done >= 0 && p.done <= p.total;
overall.hidden = !busy;
overallBar.max = phases.total > 0 ? phases.total : 1; overallBar.value = phases.done || 0;
@@ -340,9 +344,27 @@ export async function openSetup() {
catch (error) { fail(error); }
if (dialog.open && (busy || probeBusy)) pollTimer = setTimeout(poll, 750);
}
+ async function saveModelFolders() {
+ const result = await request('model-directories', {extra_libraries: extra.value.split("\n")});
+ extra.value = result.extra_libraries.join("\n");
+ const missing = result.missing_libraries || [];
+ savedMissing = missing.length > 0;
+ savedFolders = !missing.length ? t('Saved.', '已保存。')
+ : missing.length === 1 ? t(`Saved. This folder was not found: ${missing[0]}`, `已保存。找不到这个目录:${missing[0]}`)
+ : t(`Saved. These folders were not found: ${missing.join(', ')}`, `已保存。找不到这些目录:${missing.join('、')}`);
+ state.textContent = savedFolders; state.className = savedMissing ? '' : 'fv-ready';
+ state.scrollIntoView({block: 'nearest'});
+ return result;
+ }
+ saveFolders.onclick = async () => {
+ invalidate(true); busy = true; controls();
+ try { await saveModelFolders(); }
+ catch (error) { fail(error); }
+ finally { busy = false; controls(); }
+ };
inspect.onclick = async () => {
invalidate(); busy = true; controls();
- try { render(await request("inspect", {root: root.value, extra_libraries: extra.value.split("\n").map(s => s.trim()).filter(Boolean), copy: copy.checked, sampling_caches: samplingCaches.checked})); poll(); }
+ try { await saveModelFolders(); render(await request("inspect", {root: root.value, extra_libraries: extra.value.split("\n").map(s => s.trim()).filter(Boolean), copy: copy.checked, sampling_caches: samplingCaches.checked})); poll(); }
catch (error) { busy = false; controls(); fail(error); }
};
install.onclick = async () => {
@@ -357,6 +379,7 @@ export async function openSetup() {
dialog.onclose = () => { clearTimeout(pollTimer); for (const dispose of motions) dispose(); dialog.remove(); if (current === dialog) current = undefined; };
try {
const info = await request(); token = info.discovery.token; root.value = info.discovery.root;
+ extra.value = (info.discovery.extra_libraries || []).join("\n");
showDownloads(info.discovery.downloads);
showResources(info.discovery.resources);
samplingText.textContent = t('Prepare all quality levels (optional)', '提前下载全部质量档位(可选)')