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.

LoRA compatibility pre-check, drag-to-reorder, and failure report export

Bowen Xuef26eb4dda607
diff --git a/freevideo_engine/comfy_nodes.py b/freevideo_engine/comfy_nodes.py
index d3be9e3..87678ee 100644
--- a/freevideo_engine/comfy_nodes.py
+++ b/freevideo_engine/comfy_nodes.py
@@ -458,6 +458,9 @@ class FreeVideoLoRA(io.ComfyNode):
return io.NodeOutput(list(previous or []))
import folder_paths
path = folder_paths.get_full_path_or_raise('loras', lora)
+ if strength != 0:
+ from .lora_check import require_usable
+ require_usable(path)
return io.NodeOutput(list(previous or []) + [{'path': str(Path(path).resolve()), 'strength': strength}])
@@ -473,8 +476,12 @@ class FreeVideoLoRAStack(io.ComfyNode):
def execute(cls, adapters, previous=None):
from .comfy_assets import resolve_loras
import folder_paths
- return io.NodeOutput(resolve_loras(adapters, folder_paths.get_filename_list('loras'),
- lambda name: folder_paths.get_full_path_or_raise('loras', name), previous))
+ from .lora_check import require_usable
+ result = resolve_loras(adapters, folder_paths.get_filename_list('loras'),
+ lambda name: folder_paths.get_full_path_or_raise('loras', name), previous)
+ for row in result[len(previous or []):]:
+ require_usable(row['path'])
+ return io.NodeOutput(result)
@classmethod
def fingerprint_inputs(cls, **kwargs):
diff --git a/freevideo_engine/comfy_upload.py b/freevideo_engine/comfy_upload.py
index 108cfa7..81389b1 100644
--- a/freevideo_engine/comfy_upload.py
+++ b/freevideo_engine/comfy_upload.py
@@ -1,5 +1,6 @@
"""Stream browser media to ComfyUI input without buffering a clip in RAM."""
import asyncio
+import json
from pathlib import Path, PureWindowsPath
import shutil
import uuid
@@ -95,4 +96,17 @@ def register():
return web.json_response({'error': str(error)}, status=400)
return web.json_response(result, headers={'Cache-Control': 'no-store'})
+ @server.routes.get('/freevideo/lora/check')
+ async def lora_check(request):
+ from .comfy_assets import resolve_loras
+ from .lora_check import check_file
+ try:
+ name = request.query.get('name')
+ path = resolve_loras(json.dumps([dict(name=name)]), folder_paths.get_filename_list('loras'),
+ lambda n: folder_paths.get_full_path_or_raise('loras', n))[0]['path']
+ result = await asyncio.to_thread(check_file, path)
+ except (OSError, ValueError, TypeError) as error:
+ return web.json_response({'error': str(error)}, status=400)
+ return web.json_response(result, headers={'Cache-Control': 'no-store'})
+
server._freevideo_upload_registered = True
diff --git a/freevideo_engine/lora_cache.py b/freevideo_engine/lora_cache.py
index c523783..93d7e52 100644
--- a/freevideo_engine/lora_cache.py
+++ b/freevideo_engine/lora_cache.py
@@ -20,6 +20,7 @@ import time
from safetensors.torch import save_file
import torch
+from .lora_names import _targets
from .tensor_io import open_tensors
from .media_request import digest, verify_files
from .monitoring import save
@@ -31,29 +32,6 @@ from . import disk_space
MODULATION = re.compile(r'transformer_blocks\.\d+\.adaln_proj\.')
-def _targets(name):
- prefixes = ('base_model.model.', 'diffusion_model.', 'model.diffusion_model.', 'transformer.')
- while any(name.startswith(prefix) for prefix in prefixes):
- prefix = next(prefix for prefix in prefixes if name.startswith(prefix))
- name = name[len(prefix):]
- # Community H3 trainers also export Kohya-style flattened module names.
- # Only the known H3 block grammar is expanded; underscores inside qkv_proj
- # and out_proj are meaningful and must not become dots.
- name = re.sub(r'^lora_unet_blocks_(\d+)_(attn|mlp)_(out_proj|qkv_proj|fc1|fc2)(?=\.|$)',
- r'blocks.\1.\2.\3', name)
- name = re.sub(r'^blocks\.', 'transformer_blocks.', name)
- name = name.replace('token_refiner.blocks.', 'token_refiner.refiner_blocks.')
- name = name.replace('final_layer.adaln_proj.linear', 'norm_out.linear')
- # Original H3 fc1 uses [gate; value], including token-refiner MLPs.
- # Diffusers adapters already name ff.net.0.proj and need no swap.
- swap = '.mlp.fc1' in name
- for before, after in (('.mlp.fc1', '.ff.net.0.proj'), ('.mlp.fc2', '.ff.net.2'), ('.attn.out_proj', '.attn.to_out.0')):
- name = name.replace(before, after)
- if '.attn.qkv_proj' in name:
- return [(name.replace('.attn.qkv_proj', '.attn.' + suffix), i, False) for i, suffix in enumerate(('to_q', 'to_k', 'to_v'))]
- return [(name, None, swap)]
-
-
def index_adapter(row, targets, skipped=None):
pairs = {}
full = []
diff --git a/freevideo_engine/lora_check.py b/freevideo_engine/lora_check.py
new file mode 100644
index 0000000..f2dd6ff
--- /dev/null
+++ b/freevideo_engine/lora_check.py
@@ -0,0 +1,221 @@
+"""Tell from a LoRA file's header alone whether it can be used with the FreeVideo model.
+
+Only the key names and tensor shapes are read; no weights are loaded. The module
+list below is the model's fixed layout, so the verdict needs no prepared model.
+The engine still makes the exact check when it merges the adapter.
+"""
+import json
+import os
+import re
+import struct
+import threading
+
+from .lora_names import _targets
+
+MAX_HEADER_BYTES = 64 * 1024 * 1024
+BLOCKS, REFINER_BLOCKS = 50, 2
+UNCHECKED = None # known module, shape not asserted here
+
+
+def _layout():
+ shapes = {}
+ for scope, count in (('transformer_blocks', BLOCKS), ('token_refiner.refiner_blocks', REFINER_BLOCKS)):
+ for i in range(count):
+ p = f'{scope}.{i}.'
+ attn = p + ('attn.orig.' if scope == 'transformer_blocks' else 'attn.')
+ for name in ('to_q', 'to_k', 'to_v'):
+ shapes[attn + name] = (7168, 5376)
+ shapes[attn + 'to_out.0'] = (5376, 7168)
+ shapes[p + 'ff.net.0.proj'] = (28672, 5376)
+ shapes[p + 'ff.net.2'] = (5376, 14336)
+ for i in range(BLOCKS):
+ p = f'transformer_blocks.{i}.'
+ shapes[p + 'attn.to_out_linear'] = (5376, 7168)
+ shapes[p + 'adaln_proj.linear'] = UNCHECKED
+ shapes[p + 'attn.linear_attention.alpha.down'] = (128, 5376)
+ shapes[p + 'attn.linear_attention.alpha.up'] = (7168, 128)
+ shapes[p + 'attn.linear_attention.beta_proj'] = (56, 5376)
+ shapes[p + 'attn.linear_attention.output_gate.down'] = (128, 5376)
+ shapes[p + 'attn.linear_attention.output_gate.up'] = (7168, 128)
+ shapes[p + 'attn.softmax_gate.up'] = (56, 5376)
+ shapes[p + 'attn.linear_attention.norm'] = (128,)
+ for name, shape in (('k_sp', (7168, 1, 5, 5)), ('v_sp', (7168, 1, 5, 5)), ('k_tm', (7168, 1, 5)), ('v_tm', (7168, 1, 5))):
+ shapes[p + 'attn.linear_attention.short_conv.' + name] = shape
+ shapes[p + 'attn.orig.norm_k'] = shapes[p + 'attn.orig.norm_q'] = (128,)
+ shapes[p + 'norm1'] = shapes[p + 'norm2'] = (5376,)
+ for i in range(REFINER_BLOCKS):
+ p = f'token_refiner.refiner_blocks.{i}.'
+ shapes[p + 'attn.norm_k'] = shapes[p + 'attn.norm_q'] = (128,)
+ shapes[p + 'norm1'] = shapes[p + 'norm2'] = (5376,)
+ shapes.update({
+ 'context_embedder': (5376, 5120), 'audio_proj_in': (5376, 32), 'audio_proj_out': (32, 5376),
+ 'proj_in': (5376, 96), 'proj_out': (96, 5376), 'time_embedder.linear_1': (5376, 256),
+ 'time_embedder.linear_2': (2688, 5376), 'norm_out.linear': (10752, 2688),
+ 'norm_out.norm': (5376,), 'token_refiner.final_norm': (5376,)})
+ return shapes
+
+
+LAYOUT = _layout()
+UNUSABLE = 'This LoRA was not trained for the FreeVideo model and cannot be used.'
+_CACHE, _LOCK = {}, threading.Lock()
+
+
+def read_header(path):
+ """The safetensors header as {name: shape} plus its metadata; ValueError when it is not one."""
+ with open(path, 'rb') as stream:
+ raw = stream.read(8)
+ if len(raw) != 8:
+ raise ValueError('Not a safetensors file')
+ size = struct.unpack('<Q', raw)[0]
+ if not 2 <= size <= MAX_HEADER_BYTES:
+ raise ValueError('Not a safetensors file')
+ text = stream.read(size)
+ if len(text) != size:
+ raise ValueError('Truncated safetensors header')
+ try:
+ header = json.loads(text.decode('utf-8'))
+ except (UnicodeDecodeError, ValueError) as error:
+ raise ValueError('Not a safetensors file') from error
+ if not isinstance(header, dict):
+ raise ValueError('Not a safetensors file')
+ metadata = header.pop('__metadata__', None)
+ shapes = {}
+ for key, value in header.items():
+ shape = value.get('shape') if isinstance(value, dict) else None
+ if not isinstance(shape, list) or not all(type(n) is int and n >= 0 for n in shape):
+ raise ValueError('Not a safetensors file')
+ shapes[key] = tuple(shape)
+ return shapes, metadata if isinstance(metadata, dict) else {}
+
+
+def _find(target):
+ """The model module a target name refers to (without any #bias mark), or None."""
+ target = target.removesuffix('#bias')
+ if target not in LAYOUT and '.attn.' in target:
+ target = target.replace('.attn.', '.attn.orig.', 1)
+ return target if target in LAYOUT else None
+
+
+FAMILIES = (('wan', re.compile(r'\.(?:self_attn|cross_attn)\.|\.ffn\.\d|^head\.head')),
+ ('hunyuan', re.compile(r'double_blocks|single_blocks')),
+ ('ltx', re.compile(r'\.attn[12]\.')),
+ ('sd', re.compile(r'down_blocks|up_blocks|input_blocks|lora_te|text_model')))
+
+
+def family(keys):
+ """Which other model a file's layer names belong to, or None when they match none we know."""
+ for name, pattern in FAMILIES:
+ if any(pattern.search(key) for key in keys):
+ return name
+ return None
+
+
+def _bad(reason, keys, **detail):
+ return dict(reason=reason, family=family(keys) if reason == 'other-model' else None, **detail)
+
+
+def _block(target):
+ found = re.search(r'blocks\.(\d+)\.', target)
+ return int(found[1]) + 1 if found else None
+
+
+def assess(shapes):
+ """None when the adapter fits, else why not: reason 'other-model' (names of another model), 'shape' (our names,
+ a different size) or 'format' (not a LoRA we can read). 'layer' and the sizes say where. A layer name the table
+ does not list, in a file that matches no other known model, is let through."""
+ keys = list(shapes)
+ pairs, full = {}, []
+ for key in keys:
+ canonical = key.replace('.default.', '.').replace('.lora_down.weight', '.lora_A.weight').replace('.lora_up.weight', '.lora_B.weight')
+ match = re.fullmatch(r'(.+)\.lora_([AB])\.weight', canonical)
+ if match:
+ pairs.setdefault(match[1], {})[match[2]] = shapes[key]
+ elif canonical.endswith('.alpha'):
+ pairs.setdefault(canonical[:-6], {})
+ elif canonical.endswith(('.diff', '.diff_b')):
+ bias = canonical.endswith('.diff_b')
+ full.append((canonical[:-7] if bias else canonical[:-5], shapes[key], bias))
+ else:
+ return _bad('other-model' if family(keys) else 'format', keys, layer=key)
+ if not any('A' in pair for pair in pairs.values()) and not full:
+ return _bad('format', keys, layer=None)
+ wrong = []
+ for name, pair in pairs.items():
+ if not {'A', 'B'} <= pair.keys():
+ return _bad('format', keys, layer=name)
+ a, b = pair['A'], pair['B']
+ if len(a) != 2 or len(b) != 2 or a[0] != b[1] or a[0] <= 0:
+ return _bad('format', keys, layer=name)
+ for target, split, swap in _targets(name):
+ found = _find(target)
+ if found is None:
+ if family(keys):
+ return _bad('other-model', keys, layer=name)
+ continue # a name this table does not list: the engine makes the exact check
+ expected = LAYOUT[found]
+ rows = b[0] if split is None else b[0] // 3
+ if expected is UNCHECKED:
+ continue
+ if (split is not None and b[0] % 3) or (swap and rows % 2) or list(expected) != [rows, a[1]]:
+ wrong.append((found, list(expected), [rows, a[1]]))
+ for name, shape, bias in full:
+ for target, split, swap in _targets(name):
+ found = _find(target)
+ if found is None:
+ if family(keys):
+ return _bad('other-model', keys, layer=name)
+ continue
+ expected = LAYOUT[found]
+ if bias or expected is UNCHECKED:
+ continue
+ actual = list(shape)
+ if split is not None:
+ if not actual or actual[0] % 3:
+ wrong.append((found, list(expected), actual))
+ continue
+ actual[0] //= 3
+ if actual != list(expected) or (swap and (not actual or actual[0] % 2)):
+ wrong.append((found, list(expected), actual))
+ if wrong:
+ layer, expected, actual = wrong[0]
+ return dict(reason='shape', family=None, layer=layer, block=_block(layer), expected=expected, actual=actual, count=len(wrong))
+ return None
+
+
+BASE_FIELDS = ('ss_base_model_version', 'modelspec.architecture', 'base_model', 'modelspec.implementation', 'ss_network_module')
+
+
+def summarize(shapes, metadata):
+ """Counts and a few names from the header; no path, no weights."""
+ first = [[key, list(shapes[key])] for key in list(shapes)[:5]]
+ base = {name: str(metadata[name])[:80] for name in BASE_FIELDS if name in metadata}
+ return dict(keys=len(shapes), first=first, base=base)
+
+
+def check_file(path):
+ """{'usable', 'reason', ...} for a LoRA file, remembered until the file changes."""
+ try:
+ stat = os.stat(path)
+ stamp = (str(path), stat.st_size, stat.st_mtime_ns)
+ except OSError:
+ return {'usable': False, 'reason': 'unreadable'}
+ with _LOCK:
+ if stamp in _CACHE:
+ return dict(_CACHE[stamp])
+ try:
+ shapes, metadata = read_header(path)
+ problem = assess(shapes)
+ result = {'usable': problem is None, 'reason': None, **(problem or {}), 'summary': summarize(shapes, metadata)}
+ except (OSError, ValueError):
+ result = {'usable': False, 'reason': 'unreadable'}
+ with _LOCK:
+ if len(_CACHE) > 256:
+ _CACHE.clear()
+ _CACHE[stamp] = dict(result)
+ return dict(result)
+
+
+def require_usable(path):
+ """Stop a request before generation starts when a LoRA cannot work with the model."""
+ if not check_file(path)['usable']:
+ raise ValueError(UNUSABLE)
diff --git a/freevideo_engine/lora_names.py b/freevideo_engine/lora_names.py
new file mode 100644
index 0000000..9694bb8
--- /dev/null
+++ b/freevideo_engine/lora_names.py
@@ -0,0 +1,25 @@
+"""Names a LoRA file uses for the FreeVideo model, shared by the engine and the pre-check."""
+import re
+
+
+def _targets(name):
+ prefixes = ('base_model.model.', 'diffusion_model.', 'model.diffusion_model.', 'transformer.')
+ while any(name.startswith(prefix) for prefix in prefixes):
+ prefix = next(prefix for prefix in prefixes if name.startswith(prefix))
+ name = name[len(prefix):]
+ # Community H3 trainers also export Kohya-style flattened module names.
+ # Only the known H3 block grammar is expanded; underscores inside qkv_proj
+ # and out_proj are meaningful and must not become dots.
+ name = re.sub(r'^lora_unet_blocks_(\d+)_(attn|mlp)_(out_proj|qkv_proj|fc1|fc2)(?=\.|$)',
+ r'blocks.\1.\2.\3', name)
+ name = re.sub(r'^blocks\.', 'transformer_blocks.', name)
+ name = name.replace('token_refiner.blocks.', 'token_refiner.refiner_blocks.')
+ name = name.replace('final_layer.adaln_proj.linear', 'norm_out.linear')
+ # Original H3 fc1 uses [gate; value], including token-refiner MLPs.
+ # Diffusers adapters already name ff.net.0.proj and need no swap.
+ swap = '.mlp.fc1' in name
+ for before, after in (('.mlp.fc1', '.ff.net.0.proj'), ('.mlp.fc2', '.ff.net.2'), ('.attn.out_proj', '.attn.to_out.0')):
+ name = name.replace(before, after)
+ if '.attn.qkv_proj' in name:
+ return [(name.replace('.attn.qkv_proj', '.attn.' + suffix), i, False) for i, suffix in enumerate(('to_q', 'to_k', 'to_v'))]
+ return [(name, None, swap)]
diff --git a/scripts/test_freevideo_entry.mjs b/scripts/test_freevideo_entry.mjs
index bf0ca41..b3ef8a6 100644
--- a/scripts/test_freevideo_entry.mjs
+++ b/scripts/test_freevideo_entry.mjs
@@ -116,7 +116,8 @@ test('main browser entry registers both views and preserves node hooks', async t
.replace("import { imageGenerationSupported } from './image_generation.js';", 'const imageGenerationSupported = () => true;')
.replace("import { uploadMedia } from './media_upload.js';", 'const {uploadMedia} = globalThis.__freevideoEntryTest;')
.replace("import { createCastLibrary } from './cast_library.js';", 'const {createCastLibrary} = globalThis.__freevideoEntryTest;')
- .replace("import { agentInterfaceEnabled } from './agent_connect.js';", 'const agentInterfaceEnabled = async () => false;');
+ .replace("import { agentInterfaceEnabled } from './agent_connect.js';", 'const agentInterfaceEnabled = async () => false;')
+ .replace("import { installNativeErrorGuard } from './native_errors.js';", 'const installNativeErrorGuard = () => {};');
await import('data:text/javascript;base64,' + Buffer.from(source).toString('base64'));
const extension = extensions.find(row => row.name === 'FreeVideo.UnifiedMedia');
assert.ok(extension, 'the main extension must register');
diff --git a/web/error_panel.js b/web/error_panel.js
index a3a4c77..5326c4b 100644
--- a/web/error_panel.js
+++ b/web/error_panel.js
@@ -1,6 +1,7 @@
// Shared by the Studio and graph view. Text only; never render exception HTML.
import {detectBrowserExtension, browserExtensionAdvice, extensionSteps} from './browser_extension.js';
import {SAMPLING_EFFORTS, STEP_CACHES, tableLevel} from './sampling_effort.js';
+import {failureIssue, failureStage} from './failure_issue.js';
const reports = new WeakSet();
const captured = new WeakMap();
const diagnosticReports = new WeakSet();
@@ -48,9 +49,15 @@ const PLAIN_ERRORS = [
{key: 'video-no-picture', message: 'No picture could be read from this video file. Choose another video.',
title: ['This video could not be read', '无法读取这个视频'],
summary: ['No picture could be read from this video file. Choose another video.', '无法从这个视频文件里读出画面,请换一个视频。']},
+ {key: 'lora-unusable', message: 'This LoRA was not trained for the FreeVideo model and cannot be used.',
+ prefixes: ['LoRA target/shape incompatible with this VDN model', 'Full-difference LoRA target/shape incompatible with this VDN model',
+ 'Unsupported LoRA tensor (no patches are ignored): ', 'Adapter contains no LoRA factors', 'Expected matching 2-D LoRA factors', 'Incomplete LoRA pair'],
+ title: ['This LoRA cannot be used', '此 LoRA 无法使用'],
+ summary: ['This LoRA is not made for the FreeVideo model. Turn it off or remove it, then generate again.', '此 LoRA 不适用于 FreeVideo 的模型。请关闭或移除后重新生成。']},
{key: 'lora-int8', message: 'This LoRA changes parts of the model that the int8 version cannot merge yet, so it cannot be used for now. LoRAs that change only linear layers work.',
- title: ['This LoRA cannot be used with the int8 model yet', '这个 LoRA 暂时不能用于 int8 模型'],
- summary: ['This LoRA changes parts of the model that the int8 version cannot merge yet, so it cannot be used for now. LoRAs that change only linear layers work.', '这个 LoRA 修改了 int8 模型目前还不能合并的部分,暂时无法使用。只修改线性层的 LoRA 可以正常使用。']},
+ title: ['This LoRA cannot be used', '此 LoRA 无法使用'],
+ summary: ['The int8 version cannot merge the layers this LoRA changes yet. Turn it off or remove it, then generate again.',
+ 'int8 版本暂时无法合并此 LoRA 修改的层。请关闭或移除后重新生成。']},
{key: 'fa4-update', message: 'The attention speed-up component on this computer needs an update. Run freevideo setup --fa4-guard in a terminal, then restart FreeVideo.',
title: ['Runtime components need updating', '运行组件需要更新'],
summary: ['The attention speed-up component on this computer needs an update. Run freevideo setup --fa4-guard in a terminal, then restart FreeVideo.', '注意力加速组件需要更新。请在终端运行 freevideo setup --fa4-guard,然后重新启动 FreeVideo。']},
@@ -80,7 +87,8 @@ function knownError(text) {
...(d.step_cache ? {step_cache: d.step_cache} : {})};
} catch { /* Malformed metadata stays in technical details. */ }
}
- return PLAIN_ERRORS.find(error => line === error.message || error.aliases?.includes(line))?.key ?? null;
+ return PLAIN_ERRORS.find(error => line === error.message || error.aliases?.includes(line)
+ || error.prefixes?.some(prefix => line.startsWith(prefix)))?.key ?? null;
}
// When a diagnostic report exists the card hides Export report; the same advice
@@ -362,8 +370,7 @@ export function failureAdvice(value, t, known = knownError(value)) {
['A component needed to run FreeVideo could not load.', 'FreeVideo 所需的运行组件未能加载。'],
['Select "Repair" in the launcher under Settings > Environment. If it still fails, export the report and submit it in a GitHub issue.', '可在启动器“设置 → 环境”里点“修复”。仍然失败时,请导出报告并提交到 GitHub issue。']);
return row('unknown', ['Generation stopped', '生成已停止'],
- ['This generation did not finish.', '这次生成未完成。'],
- ['Click Export report and submit it in a GitHub issue; we will look into it.', '请点“导出报告”,提交到 GitHub issue,我们会专门排查。']);
+ ['', ''], ['', '']);
}
let activeDialog = null;
@@ -414,7 +421,7 @@ export function createErrorPanel(t) {
.fv-failure code{display:inline-block;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:inherit;white-space:nowrap;background:var(--fv-raised);border-radius:var(--fv-r-xs,3px);padding:0 3px}
.fv-failure-dialog{box-sizing:border-box;font-size:14px;width:min(560px,94vw);max-height:88vh;overflow:auto;padding:22px 24px;border:1px solid var(--fv-border,#45454a);border-radius:var(--fv-r-lg,16px);background:var(--fv-bg,#202126);color:var(--fv-ink,#eee);box-shadow:0 24px 80px #0008}
.fv-failure-dialog::backdrop{background:#070a0db8;backdrop-filter:blur(6px)}.fv-failure-dialog>.fv-failure{border:0;margin:0 0 16px;padding:0}.fv-failure-dialog>button,.fv-failure-dialog .fv-failure-primary{display:block;margin-left:auto;background:var(--fv-accent,#6db8fa);border-color:var(--fv-accent,#6db8fa);color:var(--fv-bg,#111720);font-weight:var(--fv-semibold,600)}
-.fv-failure .fv-extension-steps{font-size:14px;line-height:1.6}.fv-failure-reload{order:-1}.fv-failure-footer{display:flex;flex-wrap:wrap;align-items:center;gap:8px}.fv-failure-footer>.fv-failure-actions{margin-right:auto}
+.fv-failure .fv-extension-steps{font-size:14px;line-height:1.6}.fv-failure-reload{order:-1}.fv-failure .fv-failure-copy{margin-top:8px}.fv-failure-footer{display:flex;flex-wrap:wrap;align-items:center;gap:8px}.fv-failure-footer>.fv-failure-actions{margin-right:auto}
.fv-failure-footer button{min-height:var(--fv-h-sm,32px);border:1px solid var(--fv-border,#45454a);border-radius:var(--fv-r-sm,8px);background:var(--fv-raised,#303138);color:var(--fv-ink,#eee);padding:5px 12px;font:inherit;font-weight:var(--fv-medium,500);cursor:pointer}.fv-failure-footer .fv-failure-primary{margin-left:0}`;
document.head.append(style);
}
@@ -423,26 +430,31 @@ export function createErrorPanel(t) {
const title = document.createElement('strong'); title.textContent = t('Generation failed', '生成失败');
const copy = document.createElement('button'); copy.type = 'button'; copy.textContent = t('Copy error', '复制错误');
const download = document.createElement('button'); download.type = 'button'; download.textContent = t('Export report', '导出报告');
+ // A generation that stopped offers two buttons: the report file, or the same facts as a GitHub issue.
+ const github = document.createElement('button'); github.type = 'button'; github.className = 'fv-failure-github';
+ github.textContent = t('Submit to GitHub', '提交到 GitHub');
// Shown only for a browser extension, whose steps end with a reload.
const reload = document.createElement('button'); reload.type = 'button'; reload.className = 'fv-failure-reload';
reload.textContent = t('Reload page', '刷新页面'); reload.hidden = true; reload.onclick = () => globalThis.location?.reload();
const actions = document.createElement('div'); actions.className = 'fv-failure-actions';
// Last in the DOM, first on screen (CSS order), so copy stays the first child.
- actions.append(copy, download, reload);
+ actions.append(copy, download, reload, github);
const explanation = document.createElement('p'), action = document.createElement('p');
const location = document.createElement('p'), cause = document.createElement('p'); cause.className = 'fv-failure-cause';
location.className = 'fv-failure-location';
const privacy = document.createElement('p'); privacy.className = 'fv-failure-privacy';
privacy.textContent = t('Paths and typed text are removed.', '已去掉路径和输入的文字。');
+ const privacyInside = document.createElement('p'); privacyInside.className = 'fv-failure-privacy'; privacyInside.hidden = true;
+ privacyInside.textContent = t('Paths and typed text are removed.', '已去掉路径和输入的文字。');
const downloadStatus = document.createElement('p'); downloadStatus.setAttribute('role', 'status');
- let currentReport = null;
+ let currentReport = null, githubLora = false;
const disclosure = document.createElement('details'), summary = document.createElement('summary');
summary.textContent = t('Technical details', '技术详情');
const detailLocation = document.createElement('p'); detailLocation.className = 'fv-failure-location'; detailLocation.hidden = true;
const detailCause = document.createElement('p'); detailCause.className = 'fv-failure-cause'; detailCause.hidden = true;
const details = document.createElement('textarea'); details.readOnly = true;
details.setAttribute('aria-label', t('Error details', '错误详情')); details.spellcheck = false;
- copy.onclick = async () => {
+ const copyDetails = async button => {
let copied = false;
try { await navigator.clipboard.writeText(details.value); copied = true; } catch {
// Remote ComfyUI commonly uses plain HTTP, where Clipboard API is
@@ -450,7 +462,23 @@ export function createErrorPanel(t) {
disclosure.open = true; details.focus(); details.select();
try { copied = document.execCommand('copy'); } catch { /* manual Ctrl+C */ }
}
- copy.textContent = copied ? t('Copied', '已复制') : t('Press Ctrl+C', '请按 Ctrl+C');
+ button.textContent = copied ? t('Copied', '已复制') : t('Press Ctrl+C', '请按 Ctrl+C');
+ };
+ copy.onclick = () => copyDetails(copy);
+ // A generation failure keeps the raw text inside the collapsed technical details, with its own copy button.
+ const copyInside = document.createElement('button'); copyInside.type = 'button'; copyInside.className = 'fv-failure-copy';
+ copyInside.hidden = true; copyInside.onclick = () => copyDetails(copyInside);
+ // The issue address needs two browser-only modules. They load when the card is shown, so the click opens the
+ // page at once (a page opened after waiting can be blocked as a pop-up).
+ let issueModules = null;
+ const loadIssueModules = () => import('./feedback.js').then(feedback => import('./updates.js').then(updates => { issueModules = {feedback, updates}; })).catch(() => {});
+ github.onclick = async () => {
+ if (!currentReport) return;
+ if (!issueModules) await loadIssueModules();
+ if (!issueModules) return;
+ const draft = failureIssue(currentReport, element.freevideoKind, {lora: githubLora, t});
+ const url = issueModules.feedback.feedbackIssueURL(draft.text, issueModules.updates.productVersion(), draft.summary, draft.title);
+ globalThis.open?.(url, '_blank', 'noopener');
};
download.onclick = () => {
if (!currentReport) return;
@@ -473,7 +501,7 @@ export function createErrorPanel(t) {
if (url) setTimeout(() => URL.revokeObjectURL(url), 30000);
}
};
- disclosure.append(summary, detailLocation, detailCause, details);
+ disclosure.append(summary, detailLocation, detailCause, details, copyInside, privacyInside);
head.append(title, actions); element.append(head, explanation, location, cause, action, disclosure, privacy, downloadStatus);
return {element, show(value, popup = true, context = {}) {
const report = createErrorReport(value, context); currentReport = report;
@@ -490,6 +518,12 @@ export function createErrorPanel(t) {
}
if (advice.kind === 'unknown' && ['submission', 'queue'].includes(report.stage))
advice.action = t('Select "Copy error" to keep the error details.', '可点“复制错误”保留错误详情。');
+ // A generation that stopped without a known cause is named by the stage it stopped in.
+ const generated = report.stage === 'execution' && advice.kind !== 'browser-extension';
+ if (generated && advice.kind === 'unknown') {
+ const stage = failureStage(report);
+ advice.title = stage ? t(`Generation did not finish: ${stage[0]}`, `生成未完成:${stage[1]}`) : t('Generation did not finish', '生成未完成');
+ }
title.textContent = advice.title; explanation.textContent = advice.summary; explanation.hidden = !advice.summary; action.textContent = advice.action;
element.querySelector('.fv-extension-steps')?.remove();
if (advice.kind === 'browser-extension') action.after(extensionSteps(advice));
@@ -521,17 +555,27 @@ export function createErrorPanel(t) {
downloadStatus.textContent = '';
download.hidden = diagnosticReports.has(report);
if (internal && download.hidden)
- action.textContent = t('Use Download report in the preview and submit it in a GitHub issue; we will look into it.',
- '请点预览区的“下载报告”,提交到 GitHub issue,我们会专门排查。');
+ action.textContent = t('Use Download report in the preview and submit it in a GitHub issue.',
+ '请点预览区的“下载报告”,提交到 GitHub issue。');
else if (download.hidden) {
// Advice that ends with "export the report" points at the report this card does offer.
for (const [from, to] of EXPORT_TO_DOWNLOAD)
if (action.textContent.includes(from)) action.textContent = action.textContent.replace(from, to);
}
+ action.hidden = !action.textContent;
privacy.textContent = download.hidden
? t('Select "Download report" in the preview to save the full diagnostic information.', '可在预览区点“下载报告”保存完整诊断信息。')
: t('Paths and typed text are removed.', '已去掉路径和输入的文字。');
copy.textContent = advice.kind === 'sampling-table' ? t('Copy details', '复制详情') : t('Copy error', '复制错误');
+ // A generation failure shows two buttons; copying moves into the technical details.
+ copy.hidden = generated; copyInside.hidden = !generated; copyInside.textContent = copy.textContent;
+ // For a generation failure the note on removed text sits in the technical details, beside the copy button.
+ privacy.hidden = generated; privacyInside.hidden = !generated;
+ const lora = advice.kind === 'lora-unusable' || advice.kind === 'lora-int8';
+ // An int8 limit is not a judgement, so there is no mistake to report.
+ github.hidden = !generated || advice.kind === 'lora-int8'; githubLora = lora;
+ github.textContent = lora ? t('Report a mistake', '报告误判') : t('Submit to GitHub', '提交到 GitHub');
+ if (generated && typeof window !== 'undefined') loadIssueModules();
if (popup) showFailureDialog(report, t);
return report;
}, clear() { currentReport = null; details.value = ''; element.hidden = true; }};
diff --git a/web/failure_issue.js b/web/failure_issue.js
new file mode 100644
index 0000000..cd6fdd6
--- /dev/null
+++ b/web/failure_issue.js
@@ -0,0 +1,37 @@
+// What a failure card sends to GitHub: the redacted report's summary, never the report file,
+// paths or typed text (the report was already cleaned). feedback.js turns it into the address.
+const PHASES = [
+ [/download|dependenc/i, ['downloading files', '下载文件']],
+ [/load/i, ['loading the model', '载入模型']],
+ [/prompt|text|encod|reference/i, ['encoding', '编码']],
+ [/sampl|denois|first|second|refine|pass|step/i, ['sampling', '采样']],
+ [/decod|vae/i, ['decoding', '解码']],
+ [/save|mux|output|write/i, ['saving the video', '保存视频']],
+];
+
+/** The stage a generation stopped in, as [English, Chinese] words, or null when the report does not say. */
+export function failureStage(report) {
+ const named = [report?.progress?.phase, report?.progress?.stage,
+ /^Stage: (\S+)/m.exec(String(report?.details || ''))?.[1]].filter(Boolean);
+ for (const name of named)
+ for (const [pattern, words] of PHASES) if (pattern.test(name)) return words;
+ return null;
+}
+
+/** Title, text and summary for the prefilled issue. `lora` marks a LoRA the check judged wrongly. */
+export function failureIssue(report, kind, {lora = false, t = en => en} = {}) {
+ const stage = failureStage(report);
+ const lines = String(report?.message || '').split(/\r?\n/).filter(line => line.trim());
+ // A traceback ends with the line that names the error; any other message starts with it.
+ const first = (/^Traceback/.test(lines[0] || '') ? lines[lines.length - 1] : lines[0]) || '';
+ const text = [lora ? 'FreeVideo refused this LoRA. The verdict is reported as a misjudgment.' : 'FreeVideo reported a generation failure.',
+ `Stage: ${stage ? stage[0] : report?.stage || 'unknown'}`, `Error: ${first.trim().slice(0, 300)}`,
+ `Kind: ${kind || 'unknown'}`].join('\n');
+ const types = (report?.nodes || []).map(node => node.type).filter(Boolean);
+ const summary = JSON.stringify({kind: kind || 'unknown', stage: report?.stage, exception_type: report?.exception_type,
+ known_error: report?.known_error, nodes: types, settings: report?.settings, progress: report?.progress,
+ tail: String(report?.details || '').slice(-1500)});
+ const title = lora ? t('[Feedback] LoRA compatibility misjudged', '[Feedback] LoRA 兼容判断有误')
+ : t('[Feedback] Generation did not finish', '[Feedback] 生成未完成') + (stage ? t(`: ${stage[0]}`, `:${stage[1]}`) : '');
+ return {title, text, summary};
+}
diff --git a/web/feedback.js b/web/feedback.js
index c2bc7e2..b4aba8f 100644
--- a/web/feedback.js
+++ b/web/feedback.js
@@ -23,14 +23,14 @@ for (const name of ['setup.css', 'feedback.css']) {
// The GitHub page for a suggestion, with the text (and, when asked for, the
// summary) already in it.
-export function feedbackIssueURL(text, version = null, diagnostics = '') {
- return feedbackIssueParts(text, version, diagnostics).url;
+export function feedbackIssueURL(text, version = null, diagnostics = '', title = '[Feedback]') {
+ return feedbackIssueParts(text, version, diagnostics, title).url;
}
// Same, and whether the end of the text had to be left off to fit the address.
-export function feedbackIssueParts(text, version = null, diagnostics = '') {
+export function feedbackIssueParts(text, version = null, diagnostics = '', title = '[Feedback]') {
const build = (body, extra) => {
- const params = new URLSearchParams({ template: 'feedback.yml', title: '[Feedback]', feedback: body });
+ const params = new URLSearchParams({ template: 'feedback.yml', title, feedback: body });
if (version) params.set('version', `v${version}`);
if (extra) params.set('diagnostics', extra);
return `${ISSUE_FORM}?${params}`;
diff --git a/web/freevideo.js b/web/freevideo.js
index ad369b7..6ea9b72 100644
--- a/web/freevideo.js
+++ b/web/freevideo.js
@@ -1,4 +1,5 @@
import { createErrorPanel, errorText } from './error_panel.js';
+import { installNativeErrorGuard } from './native_errors.js';
import { app } from "../../scripts/app.js";
import { api } from "../../scripts/api.js";
import { openEditorView } from './editor_loader.js';
@@ -830,6 +831,7 @@ api.addEventListener('freevideo_prewarm', event => {
if (value) app.graph?.getNodeById(value.node)?.freevideoShowPrewarm?.(value);
});
+installNativeErrorGuard({api, app});
api.addEventListener('execution_error', event => {
// An upstream loader/media node can stop FreeVideo before its own node is
// entered. Retain that error even while the creative workspace is closed.
diff --git a/web/health.js b/web/health.js
index ffd8f98..071ada7 100644
--- a/web/health.js
+++ b/web/health.js
@@ -15,7 +15,7 @@ const launchVisit = query.get('freevideo') === 'launch';
// Every script this folder ships; a test keeps the list in step with web/*.js.
export const MODULES = ['agent_activity.js', 'agent_connect.js', 'agent_session.js', 'autopilot.js', 'autopilot_chat.js', 'autopilot_conversations.js', 'browser_extension.js', 'caret_rect.js', 'chain_support.js', 'capability_view.js', 'cast_generate.js', 'cast_mention.js', 'cast_overlay.js', 'cast_source.js', 'compatibility.js', 'error_panel.js', 'first_run_guide.js', 'fonts.js', 'freevideo.js', 'generation_progress.js',
'editor.js', 'editor_actions.js', 'editor_adjust.js', 'editor_adjust_picture.js', 'editor_picture_fields.js', 'editor_picture_session.js', 'editor_preview_picture.js', 'editor_entry.js', 'editor_expand.js', 'editor_export_dialog.js', 'editor_first_frame.js', 'editor_media_references.js', 'editor_references.js', 'editor_genbar.js', 'editor_geometry.js', 'editor_library.js', 'editor_menu.js', 'editor_model.js', 'editor_frame.js', 'editor_player.js', 'editor_room.js', 'editor_select.js', 'editor_state.js', 'editor_store.js', 'editor_tracks.js', 'editor_generation.js', 'editor_transport.js', 'editor_transport_model.js', 'editor_audio.js', 'editor_audio_model.js', 'editor_audio_notes.js', 'editor_audio_replace.js', 'editor_audio_rules.js', 'editor_speed.js', 'editor_speed_model.js', 'editor_failure.js', 'editor_header_fit.js',
- 'editor_loader.js', 'editor_text_coverage.js', 'editor_text.js', 'editor_toolbar_more.js', 'editor_text_model.js', 'editor_text_layout.js', 'editor_notes.js', 'editor_icons.js', 'dialog_keys.js', 'done_notify.js', 'feedback.js', 'frame_sizes.js', 'health.js', 'image_commands.js', 'image_editor.js', 'image_editor_engine.js', 'image_generation.js', 'launch_visit.js', 'launcher.js', 'length_plan.js', 'lora_triggers.js', 'library.js', 'motion.js', 'output_download.js', 'port_notice.js', 'preview_scene.js',
+ 'editor_loader.js', 'editor_text_coverage.js', 'editor_text.js', 'editor_toolbar_more.js', 'editor_text_model.js', 'editor_text_layout.js', 'editor_notes.js', 'editor_icons.js', 'dialog_keys.js', 'done_notify.js', 'failure_issue.js', 'feedback.js', 'frame_sizes.js', 'health.js', 'image_commands.js', 'image_editor.js', 'image_editor_engine.js', 'image_generation.js', 'launch_visit.js', 'launcher.js', 'length_plan.js', 'lora_triggers.js', 'lora_check.js', 'library.js', 'motion.js', 'native_errors.js', 'output_download.js', 'port_notice.js', 'preview_scene.js',
'progress_connection.js', 'prompt_draft.js', 'prompt_enhance.js', 'prompt_references.js', 'prompt_terms.js', 'request_assets.js', 'report_issue.js', 'studio_recent.js',
'result_actions.js', 'sampling_effort.js', 'setup.js', 'share.js', 'share_layout.js', 'studio.js', 'studio_chain.js', 'studio_extend.js', 'studio_length.js', 'first_frame_row.js', 'optional_inputs.js', 'studio_queue.js', 'studio_size.js',
'toolbar_position.js', 'updates.js', 'view_navigation.js', 'wordmark.js', 'cast_library.js', 'media_upload.js'];
diff --git a/web/lora_check.js b/web/lora_check.js
new file mode 100644
index 0000000..14db459
--- /dev/null
+++ b/web/lora_check.js
@@ -0,0 +1,63 @@
+// What the LoRA check found, as words for the row; the check itself is /freevideo/lora/check.
+const FAMILIES = {wan: 'Wan 2.x', hunyuan: 'HunyuanVideo', ltx: 'LTX-Video', sd: 'Stable Diffusion'};
+const size = shape => Array.isArray(shape) ? shape.join('×') : '';
+
+/** One short reason, and the lines behind it for the "Details" fold. Null when the LoRA can be used. */
+export function describeVerdict(verdict, t) {
+ if (!verdict || verdict.usable !== false) return null;
+ const family = FAMILIES[verdict.family];
+ let reason;
+ if (verdict.reason === 'unreadable') reason = t('the file could not be read. It may be incomplete; download it again.', '文件无法读取,可能未下载完整,请重新下载');
+ else if (verdict.reason === 'format') reason = t('not a LoRA file FreeVideo can read', '不是 FreeVideo 能读取的 LoRA 文件');
+ else if (verdict.reason === 'shape') reason = t('does not match the current model', '和当前模型的结构不匹配');
+ else reason = family ? t(`made for ${family}`, `这是给 ${family} 训练的 LoRA`) : t('not made for the FreeVideo model', '不适用于 FreeVideo 的模型');
+ const summary = verdict.summary || {};
+ const lines = [];
+ if (verdict.reason === 'shape') {
+ const where = Number.isInteger(verdict.block) ? t(`Layer ${verdict.block}: `, `第 ${verdict.block} 层:`) : '';
+ lines.push(where + t(`expected ${size(verdict.expected)}, file has ${size(verdict.actual)}`, `期望 ${size(verdict.expected)},文件是 ${size(verdict.actual)}`));
+ }
+ if (verdict.layer) lines.push(t('Layer: ', '层:') + verdict.layer);
+ if (verdict.count > 1) lines.push(t(`${verdict.count} layers do not match`, `共 ${verdict.count} 层不匹配`));
+ if (Number.isInteger(summary.keys)) lines.push(t(`${summary.keys} tensors`, `共 ${summary.keys} 个张量`));
+ for (const [key, shape] of summary.first || []) lines.push(`${key} ${size(shape)}`);
+ for (const [key, value] of Object.entries(summary.base || {})) lines.push(`${key}: ${value}`);
+ return {reason, lines};
+}
+
+/** The text and header summary for a prefilled issue; never the file or its path. */
+export function feedbackDraft(name, verdict, described, t = (en) => en) {
+ const base = String(name).split('/').pop();
+ const text = ['FreeVideo marked this LoRA as unusable. The verdict is reported as a misjudgment.', `File: ${base}`,
+ `Check result: ${verdict.reason || 'unknown'}${verdict.family ? ` (${verdict.family})` : ''}${described ? `, ${described.reason}` : ''}`].join('\n');
+ const summary = verdict.summary || {};
+ const diagnostics = JSON.stringify({check: {reason: verdict.reason, family: verdict.family, layer: verdict.layer, block: verdict.block,
+ expected: verdict.expected, actual: verdict.actual, count: verdict.count},
+ header: {keys: summary.keys, first: summary.first, base: summary.base}});
+ return {title: (t('[Feedback] LoRA compatibility misjudged: ', '[Feedback] LoRA 兼容判断有误:') + base).slice(0, 120), text, diagnostics};
+}
+
+/** Verdicts by LoRA name, read once per list refresh. A check that fails to run says nothing, so the LoRA stays usable. */
+export function createVerdicts(fetchApi) {
+ let known = new Map(), pending = new Map();
+ return {
+ peek: name => known.get(name),
+ clear() { known = new Map(); pending = new Map(); },
+ async get(name) {
+ if (known.has(name)) return known.get(name);
+ if (!pending.has(name)) {
+ const mine = pending, request = (async () => {
+ try {
+ const response = await fetchApi('/freevideo/lora/check?' + new URLSearchParams({name}), {cache: 'no-store'});
+ const verdict = response.ok ? await response.json() : null;
+ if (verdict && typeof verdict.usable === 'boolean' && mine === pending) known.set(name, verdict);
+ if (!verdict && mine === pending) pending.delete(name);
+ return verdict;
+ } catch { return null; }
+ })();
+ pending.set(name, request);
+ }
+ return pending.get(name);
+ },
+ };
+}
diff --git a/web/native_errors.js b/web/native_errors.js
new file mode 100644
index 0000000..d60baab
--- /dev/null
+++ b/web/native_errors.js
@@ -0,0 +1,65 @@
+// ComfyUI answers every node error with its own overlay (or dialog) carrying a traceback, local
+// paths and a link to ComfyUI's issue tracker. FreeVideo shows its own failure panel instead, so
+// for errors that belong to FreeVideo those two are skipped while the event is delivered; the
+// event itself still reaches ComfyUI's stores and every other listener.
+const EVENT = 'execution_error';
+const DIALOG_KEY = 'global-execution-error';
+
+/** True when the failing node is a FreeVideo node or feeds one (a loader or media node upstream). */
+export function ownsFailure(detail, graph) {
+ const failing = String(detail?.node_id ?? '');
+ if (/^FreeVideo/.test(String(detail?.node_type ?? ''))) return true;
+ if (!failing) return false;
+ for (const node of graph?._nodes || []) {
+ if (!/^FreeVideo/.test(String(node.comfyClass || node.type || ''))) continue;
+ const pending = [node], seen = new Set();
+ while (pending.length) {
+ const current = pending.pop();
+ if (!current || seen.has(String(current.id))) continue;
+ seen.add(String(current.id));
+ for (const input of current.inputs || []) {
+ const link = input.link != null ? current.graph?.links?.[input.link] : null;
+ if (link) pending.push(current.graph?.getNodeById?.(link.origin_id));
+ }
+ }
+ if (seen.has(failing)) return true;
+ }
+ return false;
+}
+
+function stores(app) {
+ try {
+ const pinia = app?.extensionManager?._p
+ || document.querySelector('#vue-app')?.__vue_app__?.config?.globalProperties?.$pinia;
+ return {errors: pinia?._s?.get('executionError'), dialogs: pinia?._s?.get('dialog')};
+ } catch { return {}; }
+}
+
+/** Skip ComfyUI's own error overlay and dialog for FreeVideo errors. Does nothing when the page lacks them. */
+export function installNativeErrorGuard({api, app, owns = detail => ownsFailure(detail, app?.graph)}) {
+ if (!api || api.freevideoNativeErrorGuard) return;
+ api.freevideoNativeErrorGuard = true;
+ // ComfyUI delivers server messages through dispatchCustomEvent (which calls EventTarget's own dispatchEvent).
+ const dispatch = api.dispatchCustomEvent;
+ if (typeof dispatch !== 'function') return;
+ api.dispatchCustomEvent = function (type, detail) {
+ if (type !== EVENT) return dispatch.call(this, type, detail);
+ let quiet = false;
+ try { quiet = !!owns(detail); } catch { /* an unreadable event is left to ComfyUI */ }
+ if (!quiet) return dispatch.call(this, type, detail);
+ const {errors, dialogs} = stores(app);
+ const original = [];
+ const replace = (store, name, make) => {
+ if (typeof store?.[name] !== 'function') return;
+ original.push([store, name, store[name]]);
+ store[name] = make(store[name]);
+ };
+ replace(errors, 'showErrorOverlay', () => () => {});
+ replace(dialogs, 'showDialog', keep => function (options, ...rest) {
+ return options?.key === DIALOG_KEY ? undefined : keep.call(this, options, ...rest);
+ });
+ try { return dispatch.call(this, type, detail); } finally {
+ for (const [store, name, value] of original.reverse()) store[name] = value;
+ }
+ };
+}
diff --git a/web/studio.css b/web/studio.css
index e82dd7f..1bb5e99 100644
--- a/web/studio.css
+++ b/web/studio.css
@@ -141,11 +141,11 @@
.fv-studio .fv-panel .fv-empty{display:grid;place-items:center;padding:22px 15px;min-height:92px;margin-top:12px;font-size:var(--fv-micro);white-space:pre-line;border-color:var(--fv-border);background:var(--fv-card)}
.fv-studio .fv-panel .fv-preview{max-height:170px;margin:10px auto;object-fit:contain}.fv-studio .fv-panel .fv-card{background:var(--fv-card);border-color:var(--fv-border)}
.fv-studio .fv-panel select{min-height:var(--fv-h-sm);padding:5px 8px;max-width:145px;width:auto}.fv-studio .fv-panel button{font-size:var(--fv-micro);padding:5px 10px;min-height:var(--fv-h-sm)}
-.fv-lora-list{display:flex;flex-direction:column;gap:8px;margin:12px 0}.fv-lora-row{display:grid;grid-template-columns:18px minmax(0,1fr) 64px 30px;align-items:center;gap:7px}
+.fv-lora-list{display:flex;flex-direction:column;gap:8px;margin:12px 0}.fv-lora-row{display:grid;grid-template-columns:18px minmax(0,1fr) 64px 30px;align-items:center;gap:7px}.fv-lora-row[data-sortable=true]{grid-template-columns:12px 18px minmax(0,1fr) 64px 30px;--lora-lead:3}
.fv-lora-row select{min-width:0!important;max-width:100%!important;width:100%!important}.fv-lora-row input[type=number]{width:64px!important;padding:6px!important;font-variant-numeric:tabular-nums}.fv-lora-row input[type=checkbox]{accent-color:var(--fv-accent);width:15px;min-height:15px}
-.fv-lora-range{grid-column:2/5;grid-row:3;justify-self:end;font-size:12px;line-height:16px;white-space:nowrap;color:var(--fv-muted)}.fv-lora-range[hidden]{display:none}
-.fv-lora-row[data-enabled=false]{opacity:.45}.fv-lora-order{grid-column:2/5;display:flex;gap:5px;justify-content:flex-end}
-.fv-lora-row .fv-lora-trigger{grid-column:2/5;grid-row:2;width:100%;min-width:0;min-height:28px;height:28px;box-sizing:border-box;border:1px solid var(--fv-border);border-radius:var(--fv-r-sm);padding:4px 8px;background:var(--fv-card);color:var(--fv-ink);font:inherit;font-size:var(--fv-micro)}
+.fv-lora-range{grid-column:var(--lora-lead,2)/span 3;grid-row:3;justify-self:end;font-size:12px;line-height:16px;white-space:nowrap;color:var(--fv-muted)}.fv-lora-range[hidden]{display:none}
+.fv-lora-row[data-enabled=false]{cursor:pointer}.fv-lora-row[data-enabled=false]>:not(.fv-lora-off):not(.fv-lora-grip){opacity:.45}.fv-lora-off{grid-column:var(--lora-lead,2)/span 3;grid-row:4;font-size:var(--fv-micro);color:var(--fv-muted)}.fv-lora-off[hidden]{display:none}.fv-lora-grip{width:12px;height:22px;cursor:grab;touch-action:none;color:var(--fv-muted);background:radial-gradient(circle,currentColor 1.3px,transparent 1.6px) 0 0/6px 7px;border-radius:3px}.fv-lora-grip:hover{color:var(--fv-ink)}.fv-lora-dragging{position:relative;z-index:1;background:var(--fv-card);box-shadow:0 4px 14px rgb(0 0 0/.35);border-radius:var(--fv-r-sm);cursor:grabbing}.fv-lora-dragging .fv-lora-grip{cursor:grabbing}
+.fv-lora-row .fv-lora-trigger{grid-column:var(--lora-lead,2)/span 3;grid-row:2;width:100%;min-width:0;min-height:28px;height:28px;box-sizing:border-box;border:1px solid var(--fv-border);border-radius:var(--fv-r-sm);padding:4px 8px;background:var(--fv-card);color:var(--fv-ink);font:inherit;font-size:var(--fv-micro)}
.fv-lora-trigger::placeholder{color:var(--fv-disabled)}
.fv-studio .fv-lora-row button,.fv-lora-panel .fv-lora-row button{min-height:28px;padding:3px 7px}.fv-lora-note{font-size:var(--fv-micro);color:var(--fv-muted);text-align:center;margin:10px 0 0}.fv-lora-add{display:flex;justify-content:center;gap:8px}
.fv-studio .fv-error{color:var(--fv-danger)}.fv-studio .fv-legacy{font-size:var(--fv-micro);color:var(--fv-muted);padding:12px 0}
@@ -218,3 +218,6 @@
.fv-studio .fv-chain-part-tag[data-kind=error]{color:var(--fv-warning);white-space:normal;max-width:16em;text-align:right}
@media(max-width:680px){.fv-studio .fv-chain-part{gap:8px;padding-left:4px}}
.fv-studio .fv-request-assets{font-size:12px;line-height:1.5;margin:0 0 8px}
+
+.fv-lora-problem{grid-column:var(--lora-lead,2)/span 3;grid-row:4;display:flex;flex-direction:column;align-items:flex-start;gap:6px;font-size:var(--fv-micro)}.fv-lora-problem p{margin:0;color:var(--fv-danger)}.fv-lora-problem[hidden]{display:none}.fv-lora-why summary{cursor:pointer;color:var(--fv-muted)}.fv-lora-why pre{margin:6px 0 0;white-space:pre-wrap;word-break:break-all;color:var(--fv-muted);font:inherit;font-family:ui-monospace,monospace}.fv-lora-row[data-unusable=true] select{color:var(--fv-muted)}
+.fv-lora-row[data-unusable=true]{cursor:default}.fv-lora-row[data-unusable=true] :is(input[type=number],input[type=checkbox]){opacity:.45}.fv-lora-row[data-unusable=true] select{opacity:1}.fv-lora-row[data-unusable=true] :is(.fv-lora-trigger,.fv-lora-range){display:none}
diff --git a/web/studio.js b/web/studio.js
index 7937519..c964f88 100644
--- a/web/studio.js
+++ b/web/studio.js
@@ -5,7 +5,7 @@ import {cleanOptionalPrompt} from './optional_inputs.js';
import { app } from '../../scripts/app.js';
import { api } from '../../scripts/api.js';
import { openSetup } from './setup.js';
-import { feedbackButton } from './feedback.js';
+import { feedbackButton, feedbackIssueURL } from './feedback.js';
import { wordmark } from './wordmark.js';
import { createGenerationProgress, referenceTrimText, thermalText, sharedGpuText, encoderFileText, encoderFilePath } from './generation_progress.js';
import { viewSwitch, viewChanged, agentTabReady, openAutopilot } from './view_navigation.js';
@@ -26,6 +26,7 @@ import { attachMentionOverlay } from './cast_overlay.js';
import { openCastLibrary } from './cast_source.js';
import { uploadMedia } from './media_upload.js';
import { reconcileLoraTriggers } from './lora_triggers.js';
+import { createVerdicts, describeVerdict, feedbackDraft } from './lora_check.js';
import { createSamplingEffort, effortFor, effortsFrom, stepCacheOf } from './sampling_effort.js';
import { resultActions, previewBadge, icon, actionsUnavailable } from './result_actions.js';
import { createPromptEnhancer } from './prompt_enhance.js';
@@ -290,6 +291,10 @@ export function loraPanel(node, panel, {promptNode = null} = {}) {
const actions = el('div', null, 'fv-lora-add'); panel.append(list, actions, note);
let names = [], disposed = false, rendering = false, renderAgain = false;
const drafts = new Map(), errors = new Map(), saves = new Map();
+ let skipped = 0;
+ const idleNote = () => loraWarning() + (skipped ? t(skipped === 1 ? ' 1 other LoRA file in the folder is not in .safetensors format and is not listed.' : ` ${skipped} other LoRA files in the folder are not in .safetensors format and are not listed.`, ` 文件夹中另有 ${skipped} 个 LoRA 文件不是 .safetensors 格式,未列出。`) : '');
+ const verdicts = createVerdicts((path, options) => api.fetchApi(path, options));
+ let focusGrip = null;
const read = () => { const rows = JSON.parse(value(node, 'adapters') || '[]'); if (!Array.isArray(rows) || rows.length > 32) throw new Error(t('Use at most 32 LoRAs', '最多使用 32 个 LoRA')); return rows; };
function syncPrompt(rows) {
const targets = new Set([promptNode, ...(node.graph?._nodes || []).filter(target =>
@@ -326,10 +331,57 @@ export function loraPanel(node, panel, {promptNode = null} = {}) {
for (const trigger of list.querySelectorAll('.fv-lora-trigger')) {
if (trigger.dataset.name === name && !drafts.has(name)) trigger.value = triggerEntry(name).data?.words ?? '';
}
- note.textContent = rows.map(row => errors.get(row.name)).find(Boolean) || loraWarning();
+ note.textContent = rows.map(row => errors.get(row.name)).find(Boolean) || idleNote();
} catch (error) { note.textContent = error.message; }
}
const write = rows => { if (set(node, 'adapters', JSON.stringify(rows))) { syncPrompt(rows); window.dispatchEvent(new CustomEvent('freevideo-loras', {detail: node.id})); } };
+ // A LoRA the model cannot take is switched off here, so it is not sent with the request.
+ function disableUnusable(name) {
+ if (disposed) return;
+ try {
+ const rows = read(); let changed = false;
+ for (const row of rows) if (row.name === name && row.enabled !== false && verdicts.peek(name)?.usable === false) { row.enabled = false; changed = true; }
+ if (changed) write(rows);
+ } catch (error) { note.textContent = error.message; }
+ }
+ const reorder = order => {
+ const rows = read();
+ if (order.length !== rows.length || order.every((from, to) => from === to)) return;
+ write(order.map(from => rows[from]));
+ };
+ // The grip moves the whole row with the pointer; arrow keys do the same one step at a time.
+ function sortGrip(wrap, index) {
+ const grip = el('span', null, 'fv-lora-grip'); grip.tabIndex = 0; grip.setAttribute('role', 'button');
+ grip.setAttribute('aria-label', t('Drag to reorder', '拖动调整顺序')); grip.title = t('Drag to reorder', '拖动调整顺序');
+ grip.onkeydown = event => {
+ const delta = event.key === 'ArrowUp' ? -1 : event.key === 'ArrowDown' ? 1 : 0;
+ const count = list.children.length;
+ if (!delta || index + delta < 0 || index + delta >= count) return;
+ event.preventDefault(); event.stopPropagation();
+ const order = [...Array(count).keys()];
+ [order[index], order[index + delta]] = [order[index + delta], order[index]];
+ focusGrip = index + delta; reorder(order);
+ };
+ grip.onpointerdown = event => {
+ if (event.button > 0) return;
+ event.preventDefault(); wrap.classList.add('fv-lora-dragging');
+ const move = e => {
+ const next = [...list.children].find(row => row !== wrap && e.clientY < row.getBoundingClientRect().top + row.getBoundingClientRect().height / 2);
+ if (next) { if (wrap.nextElementSibling !== next) list.insertBefore(wrap, next); }
+ else if (list.lastElementChild !== wrap) list.append(wrap);
+ };
+ const end = e => {
+ for (const [type, handler] of [['pointermove', move], ['pointerup', end], ['pointercancel', end]]) window.removeEventListener(type, handler);
+ wrap.classList.remove('fv-lora-dragging');
+ const order = [...list.children].map(row => Number(row.dataset.index));
+ if (e.type === 'pointercancel') { render(); return; }
+ reorder(order);
+ };
+ // Moving the row in the DOM drops pointer capture, so the drag listens on the window.
+ for (const [type, handler] of [['pointermove', move], ['pointerup', end], ['pointercancel', end]]) window.addEventListener(type, handler);
+ };
+ return grip;
+ }
function render() {
if (disposed) return;
if (rendering) { renderAgain = true; return; }
@@ -345,7 +397,12 @@ export function loraPanel(node, panel, {promptNode = null} = {}) {
const select = el('select'); select.setAttribute('aria-label', t('LoRA model', 'LoRA 模型'));
const pinned = recentLoras().filter(n => names.includes(n));
for (const name of [...new Set([...pinned, ...names, row.name])].filter(Boolean)) { const option = el('option', name); option.value = name; select.append(option); }
- select.value = row.name; select.title = row.name; select.onchange = () => { row.name = select.value; rememberLora(row.name); write(rows); };
+ select.value = row.name; select.title = row.name;
+ select.onchange = () => {
+ // Leaving a LoRA that could not be used turns the row back on for the new choice.
+ if (verdicts.peek(row.name)?.usable === false) row.enabled = true;
+ row.name = select.value; rememberLora(row.name); write(rows);
+ };
const {input: strength, mark: strengthMark} = loraStrengthBox(row.strength ?? 1, () => { if (strength.value !== '') { row.strength = Number(strength.value); write(rows); } });
strength.setAttribute('aria-label', t('LoRA strength', 'LoRA 强度'));
const trigger = el('input', null, 'fv-lora-trigger'); trigger.type = 'text'; trigger.maxLength = 300;
@@ -373,20 +430,39 @@ export function loraPanel(node, panel, {promptNode = null} = {}) {
select.disabled = strength.disabled = trigger.disabled = row.enabled === false;
const remove = button('×', () => { rows.splice(index, 1); write(rows); }); remove.setAttribute('aria-label', t('Remove LoRA', '移除 LoRA'));
wrap.append(enabled, select, strength, remove, trigger, strengthMark);
- if (rows.length > 1) {
- const order = el('div', null, 'fv-lora-order');
- for (const [label, delta] of [['↑', -1], ['↓', 1]]) {
- const move = button(label, () => { [rows[index], rows[index + delta]] = [rows[index + delta], rows[index]]; write(rows); });
- move.disabled = index + delta < 0 || index + delta >= rows.length;
- move.setAttribute('aria-label', delta < 0 ? t('Move LoRA earlier', 'LoRA 前移') : t('Move LoRA later', 'LoRA 后移')); order.append(move);
- }
- wrap.append(order);
- }
+ wrap.dataset.index = String(index); wrap.dataset.sortable = String(rows.length > 1);
+ if (rows.length > 1) wrap.prepend(sortGrip(wrap, index));
+ const problem = el('div', null, 'fv-lora-problem'); problem.hidden = true; wrap.append(problem);
+ // A switched-off row says so, and a click anywhere on it turns it back on.
+ const off = el('div', t('Off. Click to turn on', '已停用,点击启用'), 'fv-lora-off'); off.hidden = row.enabled !== false; wrap.append(off);
+ wrap.onclick = event => {
+ if (row.enabled !== false || wrap.dataset.unusable === 'true' || event.target.closest('button,select,input,.fv-lora-grip')) return;
+ row.enabled = true; write(rows);
+ };
+ const mark = verdict => {
+ const described = describeVerdict(verdict, t);
+ wrap.dataset.unusable = String(Boolean(described));
+ problem.hidden = !described; off.hidden = off.hidden || Boolean(described);
+ if (!described) return;
+ enabled.checked = false; enabled.disabled = true; strength.disabled = trigger.disabled = true; select.disabled = false;
+ const fold = el('details', null, 'fv-lora-why'), why = el('pre', described.lines.join('\n'));
+ const report = button(t('Report a mistake', '报告误判'), () => {
+ const draft = feedbackDraft(row.name, verdict, described, t);
+ window.open(feedbackIssueURL(draft.text, productVersion(), draft.diagnostics, draft.title), '_blank', 'noopener');
+ });
+ fold.append(el('summary', t('Details', '详情')), why, report);
+ problem.replaceChildren(el('p', t('Cannot be used: ', '不能使用:') + described.reason), fold);
+ if (row.enabled !== false) queueMicrotask(() => disableUnusable(row.name));
+ };
+ const known = verdicts.peek(row.name);
+ if (known) mark(known);
+ else verdicts.get(row.name).then(verdict => { if (verdict && !disposed && wrap.isConnected && select.value === row.name) mark(verdict); });
list.append(wrap);
loadTriggers(row.name).catch(error => { if (!disposed && trigger.isConnected) note.textContent = error.message; });
});
if (rows.length > 1) actions.append(clear);
- note.textContent = rows.map(row => errors.get(row.name)).find(Boolean) || loraWarning();
+ if (focusGrip != null) { list.querySelector(`.fv-lora-row[data-index="${focusGrip}"] .fv-lora-grip`)?.focus(); focusGrip = null; }
+ note.textContent = rows.map(row => errors.get(row.name)).find(Boolean) || idleNote();
} catch (error) {
if (error instanceof DOMException) throw error;
note.textContent = error.message;
@@ -401,7 +477,7 @@ export function loraPanel(node, panel, {promptNode = null} = {}) {
try { const rows = read(); if (rows.length >= 32) throw new Error(t('Use at most 32 LoRAs', '最多使用 32 个 LoRA')); if (!names.length) throw new Error(t('Put LoRA files (.safetensors) in the models/loras folder, then choose "Add".', '把 LoRA 文件(.safetensors)放进 models/loras 文件夹,再点“添加”。')); const next = recentLoras().find(n => names.includes(n) && !rows.some(row => row.name === n)) ?? names[0]; rememberLora(next); rows.push({name: next, strength: 1, enabled: true}); write(rows); } catch (error) { note.textContent = error.message; }
});
async function refresh() {
- try { const response = await api.fetchApi('/models/loras', {cache: 'no-store'}); if (!response.ok) throw new Error(response.statusText); const listed = await response.json(); names = (Array.isArray(listed) ? listed : []).filter(n => typeof n === 'string' && n.toLowerCase().endsWith('.safetensors')); render(); }
+ try { const response = await api.fetchApi('/models/loras', {cache: 'no-store'}); if (!response.ok) throw new Error(response.statusText); const listed = await response.json(); verdicts.clear(); skipped = (Array.isArray(listed) ? listed : []).filter(n => typeof n === 'string' && /\.(ckpt|pt|pth|bin|sft)$/i.test(n)).length; names = (Array.isArray(listed) ? listed : []).filter(n => typeof n === 'string' && n.toLowerCase().endsWith('.safetensors')); render(); }
catch (error) { if (!disposed) note.textContent = error.message; }
}
// Only deselects: the files stay in the folder and the recent names are kept.