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.
Clean up superseded versions, update the ComfyUI environment in place, explain an incomplete page (0.3.9) (#110)
Bowen Xue3e7b7ec16390
diff --git a/freevideo_engine/comfy_host.py b/freevideo_engine/comfy_host.pyindex 9f7d172..0a81962 100644--- a/freevideo_engine/comfy_host.py+++ b/freevideo_engine/comfy_host.py@@ -45,6 +45,21 @@ def prepare_for_setup(root, comfy, plan_path):return _prepare(root, comfy, machine, None, frontend.get('download', False))+def previous_environment(root, identity):+ """The environment this ComfyUI used before its requirements changed, if still complete."""+ try:+ record = json.loads((root / 'launcher' / 'comfy-host.json').read_text(encoding='utf-8'))+ environment = Path(record['environment'])+ previous = json.loads((environment / 'freevideo-host.json').read_text(encoding='utf-8'))+ except (OSError, ValueError, KeyError, TypeError):+ return None+ python = environment / ('Scripts/python.exe' if os.name == 'nt' else 'bin/python')+ if (isinstance(previous, dict) and all(previous.get(k) == identity[k] for k in ('comfy', 'engine_python', 'python'))+ and environment.parent.resolve() == (root / 'envs').resolve() and python.is_file()):+ return environment+ return None++def _prepare(root, comfy, machine, run, download):source = Path(__file__).resolve().parents[1]env = isolated_environment(root, source)@@ -138,6 +153,11 @@ def _prepare(root, comfy, machine, run, download):engine_python=machine['python'], python=sys.version.split()[0])key = hashlib.sha256(json.dumps(identity, sort_keys=True).encode()).hexdigest()[:16]env_root = root / 'envs' / ('comfyui-' + key)+ if not env_root.exists():+ # An update of ComfyUI changes only requirements.txt: update the+ # environment it already uses, PyTorch included as is, instead of+ # downloading and installing another full environment beside it.+ env_root = previous_environment(root, identity) or env_rootpython = env_root / ('Scripts/python.exe' if os.name == 'nt' else 'bin/python')receipt = env_root / 'freevideo-host.json'if not (python.is_file() and receipt.is_file() and json.loads(receipt.read_text(encoding='utf-8')) == identity):diff --git a/freevideo_engine/comfy_launcher_api.py b/freevideo_engine/comfy_launcher_api.pyindex 71d9ecb..ca719f4 100644--- a/freevideo_engine/comfy_launcher_api.py+++ b/freevideo_engine/comfy_launcher_api.py@@ -1,8 +1,36 @@-"""Read-only launcher handshake and the bundled default workflow."""+"""Launcher handshake, the bundled default workflow, and the page check result."""import json+import logging+import os+import timefrom pathlib import Path+def page_report(value):+ """The browser page's own check, bounded; None for anything else."""+ if not isinstance(value, dict) or value.get('state') not in ('ready', 'error'):+ return None+ rows = lambda key, count, limit: ([p[:limit] for p in value[key][:count] if isinstance(p, str)]+ if isinstance(value.get(key), list) else [])+ text = lambda key, limit: value.get(key)[:limit] if isinstance(value.get(key), str) else ''+ return dict(state=value['state'], problems=rows('problems', 8, 500), errors=rows('errors', 40, 300),+ ready=value.get('ready') is True, launch=value.get('launch') is True, view=text('view', 20),+ agent=text('agent', 300), frontend=text('frontend', 40), page=text('page', 200), at=time.time())+++def save_page_report(engine_root, report):+ """The latest page check and a short history, for diagnostic reports."""+ logs = Path(engine_root) / 'logs'+ logs.mkdir(parents=True, exist_ok=True)+ line = json.dumps(report, ensure_ascii=False)+ temporary = logs / 'page-check.json.tmp'+ temporary.write_text(line, encoding='utf-8')+ os.replace(temporary, logs / 'page-check.json')+ history = logs / 'page-checks.jsonl'+ rows = history.read_text(encoding='utf-8').splitlines()[-19:] if history.is_file() else []+ history.write_text('\n'.join([*rows, line]) + '\n', encoding='utf-8')++def register():from aiohttp import webimport folder_paths@@ -32,3 +60,30 @@ def register():async def workflow(request):value = json.loads((source / 'example_workflows' / 'FreeVideo-All-in-One.json').read_text(encoding='utf-8'))return web.json_response(value)++ # web/health.js posts what it found; the launcher shows a failure to the+ # user. The latest page wins, which is the page the user is looking at.+ page = {}++ @server.routes.post('/freevideo/launcher/ui')+ async def page_check(request):+ try:+ report = page_report(await request.json())+ except ValueError:+ report = None+ if report is None:+ return web.json_response(dict(error='Expected {"state": "ready" | "error", "problems": [...]}'), status=400)+ report['source'] = info['source']+ page.clear(); page.update(report)+ try:+ save_page_report(info['engine_root'], report)+ except OSError as error:+ logging.warning('[FreeVideo] Could not save the page check: %s', error)+ if report['state'] == 'error':+ logging.warning('[FreeVideo] The browser page did not load FreeVideo completely: %s (%s)',+ ' | '.join(report['problems']) or 'no details', report['agent'])+ return web.json_response(dict(ok=True))++ @server.routes.get('/freevideo/launcher/ui')+ async def page_state(request):+ return web.json_response(page)diff --git a/freevideo_engine/comfy_launcher_runtime.py b/freevideo_engine/comfy_launcher_runtime.pyindex 08944cc..cc1005f 100644--- a/freevideo_engine/comfy_launcher_runtime.py+++ b/freevideo_engine/comfy_launcher_runtime.py@@ -228,9 +228,34 @@ def node_target(root):return target+GIT_IGNORE = ('# FreeVideo engine: environments, models and caches, not part of any git checkout.\n'+ '# Keeps an update of a surrounding ComfyUI from copying, moving or deleting them.\n*\n')+++def shield_engine(engine):+ """Keep a surrounding git checkout's operations away from the engine.++ Inside an existing ComfyUI the engine is an untracked folder of tens of+ gigabytes. An updater that stashes or cleans untracked files (git stash -u,+ git add -A, git clean) would copy it into git or move it away. Only the+ launcher's engine folders get the marker, never a source checkout.+ """+ engine = Path(engine)+ marker = engine / '.gitignore'+ if (not engine.is_dir() or os.path.lexists(marker) or (engine / '.git').exists()+ or (engine / 'freevideo_engine').is_dir()):+ return False+ try:+ marker.write_text(GIT_IGNORE, encoding='utf-8')+ except OSError:+ return False+ return True++def deploy(root, source, engine):"""Update only our entry point; preserve source edits, libraries and templates."""root, source, engine = map(lambda p: Path(p).resolve(), (root, source, engine))+ shield_engine(engine)target = node_target(root)target.mkdir(parents=True, exist_ok=True)receipt = target / 'freevideo-launcher.json'@@ -297,6 +322,52 @@ class Controller:# Set by the Qt session: lets the server it starts hand browser update# requests back to this launcher.self.update_bridge = None+ # Earlier FreeVideo copies removed in the background once ComfyUI runs+ # this version; kept out of `state`, which the task thread replaces.+ self.old_versions = dict(released_bytes=0)+ self._old_versions_thread = None++ def retire_old_versions(self, selected):+ """Once ComfyUI runs this version, earlier FreeVideo copies are no longer read."""+ if self._old_versions_thread is not None and self._old_versions_thread.is_alive():+ return+ def work():+ from .desktop_runtime import launcher_root+ from .launcher_update import current_build+ from .version_cleanup import run+ try:+ result = run(launcher_root=launcher_root(), launcher_source=self.source, launcher_build=current_build(),+ running=[sys.executable] if getattr(sys, 'frozen', False) else [],+ engine=selected['engine'], comfy_root=selected['root'],+ engine_source=selected['source'], server_source=server_info(selected['url']).get('source'))+ except Exception as error: # Cleanup never affects using ComfyUI.+ result = dict(released_bytes=0, error=type(error).__name__ + ': ' + str(error))+ self.old_versions = dict(result, released_bytes=self.old_versions['released_bytes'] + result['released_bytes'])+ self._old_versions_thread = threading.Thread(target=work, name='freevideo-old-versions', daemon=True)+ self._old_versions_thread.start()++ def _prepare_frontend(self, selected, *, download=False):+ """Bring the separate ComfyUI environment up to date with this ComfyUI.++ After ComfyUI itself is updated, its requirements change; the same+ environment is updated in place and keeps its PyTorch. Our own idle+ server is stopped first: Windows cannot replace packages it has loaded.+ """+ if self.setup is None:+ folders = SimpleNamespace(base_path=selected['root'], models_dir=str(Path(selected['root']) / 'models'),+ get_folder_paths=lambda _: [])+ self.setup = Setup(Path(selected['source']), folders, LauncherRunner)+ if managed_python(Path(selected['engine']), Path(selected['root'])) is None:+ self._stop_server_for_setup(selected['url'])+ self.setup.state = dict(status='running', action='comfy-host')+ self.setup.events.reset()+ arguments = ['comfy-host', '--comfy', selected['root']]+ if download:+ arguments.append('--download-comfy')+ self.setup.runner.start('comfy-host', selected['engine'], arguments)+ self._wait_setup()+ descriptor = json.loads((Path(selected['engine']) / 'launcher' / 'comfy-host.json').read_text(encoding='utf-8'))+ selected['python'] = descriptor['python']def owns_server(self):return self.server is not None and self.server.poll() is None@@ -540,16 +611,8 @@ class Controller:if selected['separate']:if self.cancelled.is_set():raise RuntimeError('Stopped; files retained')- self.setup.state = dict(status='running', action='comfy-host')- self.setup.events.reset()self.stage('comfy', label='Prepare ComfyUI')- arguments = ['comfy-host', '--comfy', selected['root']]- if selected.get('new_comfy'):- arguments.append('--download-comfy')- self.setup.runner.start('comfy-host', selected['engine'], arguments)- self._wait_setup()- descriptor = json.loads((Path(selected['engine']) / 'launcher' / 'comfy-host.json').read_text(encoding='utf-8'))- selected['python'] = descriptor['python']+ self._prepare_frontend(selected, download=bool(selected.get('new_comfy')))if self.cancelled.is_set():raise RuntimeError('Stopped; files retained')self.stage('nodes', label='Install FreeVideo workflow')@@ -591,8 +654,22 @@ class Controller:# Covers old installations, deleted links and directly connecting to an# existing server, as well as the first installation.self.ensure_shortcut()- self.stage('open', label='Open ComfyUI')+ shield_engine(selected['engine'])url = selected['url']+ frontend_error = None+ if (selected.get('python') and managed_frontend(selected)+ and managed_python(Path(selected['engine']), Path(selected['root'])) is None):+ # ComfyUI was updated since its separate environment was prepared.+ self.sections = [('comfy', 5), ('open', 1)]+ self.stage('comfy', label='Update ComfyUI packages')+ try:+ self._prepare_frontend(selected)+ except Exception as error:+ if self.cancelled.is_set():+ raise+ # Offline, say: the previous environment may still run this ComfyUI.+ frontend_error = str(error)+ self.stage('open', label='Open ComfyUI')info = server_info(url)if matches_server(info, selected['root'], selected['engine'], selected['source']):self.attach_console(info)@@ -680,8 +757,11 @@ class Controller:raise RuntimeError('ComfyUI startup cancelled')if server.poll() is not None:from .failure_details import startup_failure- raise RuntimeError(startup_failure('ComfyUI could not start.', directory / 'comfy.log',- exit_code=server.returncode, context=context))+ message = startup_failure('ComfyUI could not start.', directory / 'comfy.log',+ exit_code=server.returncode, context=context)+ if frontend_error:+ message += '\n\nComfyUI packages could not be updated first: ' + frontend_error+ raise RuntimeError(message)info = server_info(url)if matches_server(info, selected['root'], selected['engine'], selected['source']):self.stage('open', done=1, label='Ready')diff --git a/freevideo_engine/desktop_shortcut.py b/freevideo_engine/desktop_shortcut.pyindex 70cbfd2..84c3f9a 100644--- a/freevideo_engine/desktop_shortcut.py+++ b/freevideo_engine/desktop_shortcut.py@@ -75,6 +75,53 @@ def write_link(path, target, arguments, working_directory, icon):if initialized >= 0: ole.CoUninitialize()+def read_link_targets(paths):+ """The programs Windows shortcuts start, keyed by shortcut; unreadable ones are skipped."""+ import ctypes as c+ class GUID(c.Structure):+ _fields_ = [('data', c.c_ubyte * 16)]+ def __init__(self, value):+ super().__init__()+ self.data[:] = uuid.UUID(value).bytes_le+ ole = c.WinDLL('ole32')+ ole.CoInitializeEx.argtypes = [c.c_void_p, c.c_uint32]; ole.CoInitializeEx.restype = c.c_long+ ole.CoUninitialize.argtypes = []; ole.CoUninitialize.restype = None+ ole.CoCreateInstance.argtypes = [c.POINTER(GUID), c.c_void_p, c.c_uint32, c.POINTER(GUID), c.POINTER(c.c_void_p)]+ ole.CoCreateInstance.restype = c.c_long+ initialized = ole.CoInitializeEx(None, 2)+ if initialized < 0 and initialized != -2147417850:+ raise OSError('Windows shortcut initialization failed: 0x%08x' % (initialized & 0xffffffff))+ def method(obj, index, types, *values):+ table = c.cast(obj, c.POINTER(c.POINTER(c.c_void_p))).contents+ result = c.WINFUNCTYPE(c.c_long, c.c_void_p, *types)(table[index])(obj, *values)+ if result < 0:+ raise OSError('Windows shortcut failed: 0x%08x' % (result & 0xffffffff))+ targets = {}+ try:+ cls = GUID('00021401-0000-0000-c000-000000000046')+ iid = GUID('000214f9-0000-0000-c000-000000000046')+ persist_iid = GUID('0000010b-0000-0000-c000-000000000046')+ for path in paths:+ link, persist = c.c_void_p(), c.c_void_p()+ try:+ if ole.CoCreateInstance(c.byref(cls), None, 1, c.byref(iid), c.byref(link)) < 0:+ continue+ method(link, 0, [c.POINTER(GUID), c.POINTER(c.c_void_p)], c.byref(persist_iid), c.byref(persist))+ method(persist, 5, [c.c_wchar_p, c.c_uint32], str(path), 0) # Load, read-only.+ buffer = c.create_unicode_buffer(32768)+ method(link, 3, [c.c_wchar_p, c.c_int, c.c_void_p, c.c_uint32], buffer, len(buffer), None, 0)+ if buffer.value:+ targets[str(path)] = buffer.value+ except OSError:+ continue+ finally:+ if persist: method(persist, 2, [])+ if link: method(link, 2, [])+ finally:+ if initialized >= 0: ole.CoUninitialize()+ return targets++def launcher_target(engine, source, portable_root=None):if portable_root:target = Path(portable_root) / 'FreeVideo.exe'diff --git a/freevideo_engine/diagnostics.py b/freevideo_engine/diagnostics.pyindex 4ae2566..0922fd7 100644--- a/freevideo_engine/diagnostics.py+++ b/freevideo_engine/diagnostics.py@@ -200,6 +200,40 @@ def latest(root, category):return max(directories, key=lambda p: p.name) if directories else None+def web_files(root, machine):+ """FreeVideo's page files in the source ComfyUI served, against that source's manifest."""+ sources = []+ try:+ sources.append(json.loads((root / 'logs/page-check.json').read_text(encoding='utf-8')).get('source'))+ except (OSError, ValueError, AttributeError):+ pass+ sources.append(machine.get('source'))+ for source in sources:+ if not isinstance(source, str) or not source:+ continue+ source = Path(source)+ try:+ rows = json.loads((source / 'launcher-source.json').read_text(encoding='utf-8'))['sha256']+ rows = rows if isinstance(rows, dict) else None+ except (OSError, ValueError, KeyError, TypeError):+ rows = None+ if not (source / 'web').is_dir():+ return dict(source=str(source), error='The web folder is missing')+ present = {p.relative_to(source).as_posix(): p for p in (source / 'web').rglob('*') if p.is_file()}+ expected = {k: v for k, v in (rows or {}).items() if k.startswith('web/')}+ changed = []+ for name in sorted(set(expected) & set(present)):+ try:+ if hashlib.sha256(present[name].read_bytes()).hexdigest() != expected[name]:+ changed.append(name)+ except OSError:+ changed.append(name)+ return dict(source=str(source), manifest=rows is not None, files=len(present),+ missing=sorted(set(expected) - set(present)), changed=changed,+ extra=sorted(set(present) - set(expected)) if rows is not None else [])+ return dict(error='No FreeVideo source is recorded')++def collect(root, config, run, output, *, complete=False, extra_files=(), notes=''):root, config = root.expanduser().resolve(), config.expanduser().absolute()if run is not None and (not run.is_dir() or is_link(run)):@@ -346,6 +380,13 @@ def collect(root, config, run, output, *, complete=False, extra_files=(), notes=for path in report_files(host_run):add_path('launcher/host-runs/' + host_run.name + '/' +path.relative_to(host_run).as_posix(), path)+ # What the browser page found (web/health.js), and the page files of the+ # source ComfyUI served: a missing or changed file explains a page+ # without FreeVideo's styles or workspace.+ for name in ('page-check.json', 'page-checks.jsonl'):+ if (root / 'logs' / name).is_file():+ add_path('logs/' + name, root / 'logs' / name)+ add('source/web-files.json', json.dumps(web_files(root, machine)).encode())add_path('source/dependencies.json', Path(__file__).with_name('dependencies.json'))source = {p.name: hashlib.sha256(p.read_bytes()).hexdigest() for p in sorted(Path(__file__).parent.glob('*.py'))}add('source/hashes.json', json.dumps(source).encode())diff --git a/freevideo_engine/failure_details.py b/freevideo_engine/failure_details.pyindex 9aa201a..7b7c2c5 100644--- a/freevideo_engine/failure_details.py+++ b/freevideo_engine/failure_details.py@@ -98,6 +98,15 @@ def launcher_failure(value, *, zh=False):action='展开详情或导出报告,查看完整检查结果。' if zh else'Open the details or export the report for the complete results.', kind='kernels')rules = (+ # web/health.js lists the failed files and what to do on the page itself.+ (r'The browser page did not load FreeVideo completely|浏览器页面没有完整加载 FreeVideo', 'page',+ ('FreeVideo did not load completely in the browser', '浏览器里的 FreeVideo 没有完整加载'),+ ('The browser page names the files that failed and what to do. Follow it, then reload the page; if it happens again, export the report.',+ '浏览器页面上列出了出错的文件和处理方法。按提示处理后刷新页面;仍然出现时请导出报告。')),+ (r'The browser has not opened FreeVideo yet|浏览器还没有打开 FreeVideo', 'page-silent',+ ('The browser has not opened FreeVideo', '浏览器还没有打开 FreeVideo'),+ ('Click “Open FreeVideo”. If the page stays blank or keeps loading, open it in a current Chrome or Edge.',+ '请点击“打开 FreeVideo”。如果页面空白或一直在加载,请用最新版 Chrome 或 Edge 打开。')),(r'CUDA_ARCH_UNSUPPORTED', 'gpu-architecture',('This GPU lacks the required compute support', '这张显卡不满足当前计算要求'),('The detected GPU and compute capability are shown below. The CUDA runtime requires native BF16 computation (SM80 or newer). Use a compatible GPU; changing the driver does not change its hardware capability.',diff --git a/freevideo_engine/launcher/Main.qml b/freevideo_engine/launcher/Main.qmlindex 1e81e1d..a0e989b 100644--- a/freevideo_engine/launcher/Main.qml+++ b/freevideo_engine/launcher/Main.qml@@ -728,6 +728,7 @@ ApplicationWindow {FButton { text: t("Create desktop shortcut", "创建桌面快捷方式"); implicitHeight: theme.height; font.pixelSize: theme.micro + 1; enabled: s.can_shortcut && !s.busy; onClicked: backend.action("shortcut", false) }FText { text: ["created","present"].indexOf(s.shortcut.status) >= 0 ? "✓ " + t("Shortcut ready", "快捷方式已就绪") : ""; color: theme.success; font.pixelSize: theme.micro }}+ FText { objectName: "oldVersions"; visible: !!s.old_versions; text: "✓ " + s.old_versions; color: theme.success; font.pixelSize: theme.micro; Layout.fillWidth: true }FCheck { visible: s.needs_consent; text: s.consent; checked: accepted; onToggled: accepted = checked; Layout.fillWidth: true }FButton { visible: s.needs_consent; text: t("Read licenses ↗", "查看许可证 ↗"); flat: true; implicitHeight: theme.heightSm - 2; leftPadding: 32; font.pixelSize: theme.micro + 1; onClicked: backend.link("https://huggingface.co/OpenVDN/vdn-minimax-h3-edge/blob/main/LICENSE") }}diff --git a/freevideo_engine/launcher_copy.py b/freevideo_engine/launcher_copy.pyindex 1fe3c89..02e1c9e 100644--- a/freevideo_engine/launcher_copy.py+++ b/freevideo_engine/launcher_copy.py@@ -45,7 +45,8 @@ ZH = dict([('Prepare ComfyUI GPU packages', '准备 ComfyUI 加速组件'),('Install ComfyUI packages', '安装 ComfyUI 组件'), ('Check ComfyUI dependencies', '检查 ComfyUI 环境'),('Finish ComfyUI setup', '完成 ComfyUI 安装'), ('ComfyUI ready', 'ComfyUI 已就绪'),- ('Prepare ComfyUI', '准备 ComfyUI'), ('Install FreeVideo workflow', '安装 FreeVideo 工作流'),+ ('Prepare ComfyUI', '准备 ComfyUI'), ('Update ComfyUI packages', '更新 ComfyUI 组件'),+ ('Install FreeVideo workflow', '安装 FreeVideo 工作流'),('Open ComfyUI', '打开 ComfyUI'), ('Starting ComfyUI', '启动 ComfyUI'),('Loading nodes and the web interface', '加载节点与界面'),('Checking configuration', '检查配置'), ('Check installation', '检查安装'),diff --git a/freevideo_engine/launcher_session.py b/freevideo_engine/launcher_session.pyindex 57a98c6..61a2982 100644--- a/freevideo_engine/launcher_session.py+++ b/freevideo_engine/launcher_session.py@@ -42,6 +42,8 @@ class Session:page = 'comfy'selected = installed_versions = Nonerelease_details = None+ # The source whose earlier copies were removed once ComfyUI ran it.+ old_versions_retired = Nonedef __init__(self, source=None, *, controller=None, store=None, updater=None, smoke=False):from .offline_packages import Importer@@ -87,6 +89,11 @@ class Session:self.model_groups = []self.browser_attempted = Falseself.browser_error = ''+ # What the opened page reported about loading FreeVideo (web/health.js).+ from .page_check import PageCheck+ self.page_check = PageCheck()+ self.browser_opened = None+ self.page_error = ''self.started = Noneself.closing = Falseself.smoke = smoke@@ -484,6 +491,7 @@ class Session:if not open_browser(address):raise OSError('The system did not accept the browser request')self.browser_error = ''+ self.browser_opened = time.monotonic()except Exception as error:self.browser_error = self.t('ComfyUI is ready. Open the browser again or copy its address.\n','ComfyUI 已就绪,请重试打开浏览器,或复制地址手动打开。\n') + str(error)@@ -905,6 +913,14 @@ class Session:row = self.controller.statebusy = self.controller.busy+ selection = getattr(self.controller, 'selection', None)+ if (row.get('status') == 'open' and not busy and not self.smoke and selection+ and selection.get('source') != self.old_versions_retired):+ # ComfyUI runs this version now: earlier FreeVideo copies are no longer read.+ self.old_versions_retired = selection.get('source')+ retire = getattr(self.controller, 'retire_old_versions', None)+ if retire:+ retire(dict(selection))if self.engine_autoinstall and not busy and row.get('action') == 'inspect' and row.get('status') != 'running':self.engine_autoinstall = Falseselection = row.get('selection') or {}@@ -950,6 +966,7 @@ class Session:elif not self.reload_expected or time.monotonic() >= self.browser_wait:self.reload_expected = Falseself.open_browser()+ self._tick_page_check(row)self._tick_model_upgrade(row, busy)sources = self.controller.terminal_sources()if sources:@@ -958,6 +975,25 @@ class Session:self.tail.read(final=not self.controller.terminal_running(selected))self._tick_updates()+ def _tick_page_check(self, row):+ """Show a page that failed to load FreeVideo, or never reported, in the failure card."""+ if row.get('status') != 'open' or self.closing or self.smoke:+ self.page_check.reset()+ self.browser_opened, self.page_error = None, ''+ return+ address = row['url'].split('/?')[0]+ self.page_check.poll(address)+ self.page_error = self.page_check.text(self.t, self.browser_opened, address)++ def old_versions_text(self):+ """What the background removal of earlier FreeVideo copies freed this session."""+ value = getattr(self.controller, 'old_versions', None)+ released = value.get('released_bytes') if isinstance(value, dict) else None+ if not isinstance(released, int) or released < 2**20:+ return ''+ size = '%.1f GiB' % (released / 2**30) if released >= 2**30 else '%d MiB' % (released // 2**20)+ return self.t('Old versions removed · %s freed', '已清理旧版本 · 释放 %s') % size+def snapshot(self):from .failure_details import launcher_failure, redacted_launcher_errorfrom .launcher_copy import display, progress_view, source_name@@ -966,7 +1002,7 @@ class Session:task = row.get('task', {})progress = progress_view(task.get('progress') or {}, zh)overall = progress_view(row.get('overall') or task.get('phase_progress') or {}, zh)- errors = [self.error, self.browser_error, row.get('error', ''), *row.get('errors', [])]+ errors = [self.error, self.browser_error, self.page_error, row.get('error', ''), *row.get('errors', [])]shortcut = row.get('shortcut') or {}if shortcut.get('status') == 'failed':errors.append(shortcut.get('error', ''))@@ -1044,6 +1080,7 @@ class Session:probe=probe, speeds=speeds, token_set=bool(self.token),log=self.tail.text, logs=[dict(label=display(n, zh), path=str(p)) for n, p in self.controller.terminal_sources()],url=(self._browser_url(row.get('url', '')) if row.get('status') == 'open' else ''), shortcut=shortcut,+ old_versions=self.old_versions_text(),can_shortcut=bool(self.controller.selection and self.controller.selection.get('ready')),update=update, engine_update_available=bool(row.get('engine_update_available')),settings_path=str(self.store.primary),diff --git a/freevideo_engine/page_check.py b/freevideo_engine/page_check.pynew file mode 100644index 0000000..426f381--- /dev/null+++ b/freevideo_engine/page_check.py@@ -0,0 +1,64 @@+"""What the browser page reported about loading FreeVideo (web/health.js).++The launcher reads the report from its ComfyUI server off the UI thread and+shows a failed or silent page in its failure card.+"""+import threading+import time++# A page that loaded FreeVideo always reports; none this long after opening+# the browser means FreeVideo never ran there.+SILENT_AFTER = 90+POLL_EVERY = 3+++class PageCheck:+ def __init__(self):+ self.url = None+ self.report = {}+ self.polled = float('-inf')+ self.thread = None++ def reset(self):+ self.url, self.report = None, {}++ def poll(self, url, now=None):+ """Read the server's latest page report in the background, every few seconds."""+ now = time.monotonic() if now is None else now+ if url != self.url:+ self.url, self.report = url, {}+ if now - self.polled < POLL_EVERY or (self.thread and self.thread.is_alive()):+ return+ self.polled = now++ def read():+ from .comfy_launcher_runtime import get_json+ try:+ value = get_json(url + '/freevideo/launcher/ui', timeout=2)+ except (OSError, ValueError):+ return+ if self.url == url:+ self.report = value if isinstance(value, dict) else {}++ self.thread = threading.Thread(target=read, daemon=True, name='FreeVideo-page-check')+ self.thread.start()++ def text(self, t, opened_at, address, now=None):+ """The failure text for a page that failed or never reported; '' otherwise."""+ report = self.report+ if report.get('state') == 'error':+ problems = [p for p in report.get('problems') or [] if isinstance(p, str) and p]+ lines = [t('The browser page did not load FreeVideo completely.', '浏览器页面没有完整加载 FreeVideo。')]+ lines += ['- ' + p for p in problems] or ['- ' + t('No details were sent.', '页面没有发送详情。')]+ if report.get('agent'):+ lines.append(t('Browser: ', '浏览器:') + str(report['agent']))+ if report.get('frontend'):+ lines.append(t('ComfyUI frontend: ', 'ComfyUI 前端:') + str(report['frontend']))+ return '\n'.join(lines)+ now = time.monotonic() if now is None else now+ if not report.get('state') and opened_at is not None and now - opened_at >= SILENT_AFTER:+ return t('The browser has not opened FreeVideo yet. If no browser window appeared, click “Open FreeVideo”. '+ 'If the page stays blank or keeps loading, open %s in a current Chrome or Edge.',+ '浏览器还没有打开 FreeVideo。如果没有弹出浏览器窗口,请点击“打开 FreeVideo”;'+ '如果页面空白或一直在加载,请用最新版 Chrome 或 Edge 打开 %s。') % address+ return ''diff --git a/freevideo_engine/release_notes.json b/freevideo_engine/release_notes.jsonindex d35a94d..af94bb3 100644--- a/freevideo_engine/release_notes.json+++ b/freevideo_engine/release_notes.json@@ -1,20 +1,26 @@{"schema": 1,- "product_version": "0.3.8",+ "product_version": "0.3.9","en": {- "summary": "Downloads that cannot resume now start again by themselves, and the ComfyUI setup panel explains why Install / repair is unavailable.",+ "summary": "Updates no longer leave earlier versions behind, updating your ComfyUI no longer reinstalls PyTorch, and a FreeVideo page that does not load completely now says why.","changes": [- "When an interrupted model download cannot be resumed, installation now downloads that file again from the start instead of stopping at every retry. The incomplete copy is kept aside.",- "If model preparation stops, the message now names the file and the reason instead of a generic \"preparation stopped\".",- "In the ComfyUI setup panel, a short note under the buttons explains why Install / repair is unavailable: run Detect & review, tick the agreement, or resolve the problems shown in the plan. Changing a setting clears the outdated plan."+ "After an update, the launcher removes the earlier launcher copies and FreeVideo files it no longer uses, and shows how much space was freed. Models, outputs, files you changed and the copies your shortcuts or pinned icons open are kept.",+ "On Windows, the downloaded PyTorch packages (about 1.8 GB) are removed once every environment has them installed. They are only needed to create an environment again.",+ "When ComfyUI runs in FreeVideo's separate environment and you update ComfyUI, the launcher updates that environment before starting it, instead of downloading another one with PyTorch.",+ "An engine folder inside an existing ComfyUI is now ignored by git, so ComfyUI updaters that stash or clean untracked files no longer copy or move its models and environments.",+ "If FreeVideo’s page does not load completely in the browser, for example its styles or the creative workspace are missing, the page now says which file failed, why, and what to do. The launcher shows the same problem, and diagnostic reports include it.",+ "Opening FreeVideo from the launcher now always brings its workflow to the front, even when ComfyUI reopens the tabs from your last session."]},"zh": {- "summary": "无法续传的下载会自动从头重新下载;ComfyUI 内的安装面板会说明「安装/修复」暂不可用的原因。",+ "summary": "更新后不再残留旧版本文件;升级 ComfyUI 后不再重新安装 PyTorch;FreeVideo 页面没有完整加载时会说明原因。","changes": [- "模型下载中断且无法续传时,安装会自动从头重新下载该文件,不再每次重试都停下;未完成的文件会另行保留。",- "模型准备停止时,提示会写明具体的文件和原因,而不是笼统的「准备已停止」。",- "ComfyUI 内的安装面板会在按钮下方说明「安装/修复」暂不可用的原因:需要先「检测并预览」、勾选同意,或先解决计划中标红的问题;修改设置后会清除过期的计划。"+ "更新完成后,启动器会自动删除不再使用的旧版启动器和 FreeVideo 文件,并显示释放的空间。模型、生成结果、你改动过的文件,以及快捷方式或固定图标会打开的副本都会保留。",+ "Windows 上,所有环境都装好 PyTorch 后,会删除已下载的 PyTorch 安装包(约 1.8 GB),这些安装包只在重新创建环境时才需要。",+ "ComfyUI 在 FreeVideo 准备的独立环境中运行时,升级 ComfyUI 后,启动器会在启动前更新这个环境,不再另外下载一整套带 PyTorch 的环境。",+ "放在已有 ComfyUI 里的引擎文件夹现在会被 git 忽略,ComfyUI 更新工具暂存或清理未跟踪文件时,不会再复制或移走其中的模型和环境。",+ "浏览器里的 FreeVideo 页面没有完整加载时(例如样式丢失或创作面板打不开),页面会写明是哪个文件、什么原因、该怎么处理;启动器也会显示同样的问题,诊断报告中也会包含。",+ "从启动器打开 FreeVideo 时,即使 ComfyUI 恢复了上次的标签页,FreeVideo 工作流也会显示在最前面。"]}}diff --git a/freevideo_engine/version_cleanup.py b/freevideo_engine/version_cleanup.pynew file mode 100644index 0000000..cb676a7--- /dev/null+++ b/freevideo_engine/version_cleanup.py@@ -0,0 +1,499 @@+"""Remove FreeVideo's own superseded copies after an update; never models or user files.++Every launcher update leaves the previous executable twice (its download and the+copy behind the desktop shortcut) and the previous source twice (the launcher's+copy and the installation's). An update of the user's ComfyUI used to leave a+whole separate ComfyUI environment, PyTorch included. Once the new version runs+ComfyUI, none of these is read again. Removal is limited to copies FreeVideo+itself wrote:++* updates/<sha256>/ in the launcher folder: the executable that digest names,+ checked, and interrupted downloads; never the running or approved one, a+ newer one downloaded and waiting to start, nor one a shortcut, a pinned+ taskbar item or a Dock item starts;+* source/<version>-<hash>/ in the launcher and installation folders: unmodified+ copies (each file as recorded in launcher-source.json, plus the installation+ binding, compiled bytecode, that version's setup logs and its editable-install+ metadata) older than the launcher's own or the one ComfyUI loads; never+ those, the one a running ComfyUI reports or one an environment installed in+ editable mode;+* launcher/application/<sha256>/ in the installation: the launcher an earlier+ desktop shortcut started, checked by its digest; never the current target or+ one any shortcut, pinned item or Dock item starts;+* envs/comfyui-*: a separate environment for this same ComfyUI folder that the+ current one replaced;+* the downloaded PyTorch wheel archives, once every environment has them.++Every path lies inside its folder and is reached without links or junctions. A+copy still in use is kept for the next run: no running process may name it as+its program, working folder, argument or PYTHONPATH, and Windows must allow+renaming the folder (it refuses while files inside are open). Package caches,+environments in use, models and outputs are never touched.+"""+import hashlib+import json+import os+from pathlib import Path+import re+import shutil+import stat+import sys+import time+import uuid++from .installation_cleanup import local_path+from .monitoring import save+from .system import windows++VERSION = re.compile(r'\d{4}\.\d{1,2}\.\d{1,2}\.\d{1,6}-[0-9a-f]{16}(?:-[0-9a-f]{8})?')+DIGEST = re.compile(r'[0-9a-f]{64}(?:-[0-9a-f]{8})?')+ENVIRONMENT = re.compile(r'comfyui-[0-9a-f]{16}')+RETIRED = re.compile(r'(?P<name>.+)\.retired-[0-9a-f]{8}')+EXECUTABLES = ('FreeVideo.exe', 'FreeVideo-Linux-x86_64.AppImage')+++def tree_bytes(path):+ total = 0+ for directory, folders, files in os.walk(path, followlinks=False):+ for name in files:+ try:+ info = os.lstat(os.path.join(directory, name))+ except OSError:+ continue+ if stat.S_ISREG(info.st_mode):+ total += info.st_size+ return total+++def digest(path):+ value = hashlib.sha256()+ with Path(path).open('rb') as stream:+ for block in iter(lambda: stream.read(1 << 20), b''):+ value.update(block)+ return value.hexdigest()+++def plain_tree(path):+ """No links or junctions anywhere below path; anything unreadable counts as one."""+ def unreadable(error):+ raise error+ try:+ for directory, folders, files in os.walk(path, followlinks=False, onerror=unreadable):+ for name in [*folders, *files]:+ info = os.lstat(os.path.join(directory, name))+ if stat.S_ISLNK(info.st_mode) or getattr(info, 'st_file_attributes', 0) & 0x400:+ return False+ except OSError:+ return False+ return True+++def references():+ """Every path a running process names: its program, working folder, arguments+ and PYTHONPATH, which is how FreeVideo starts workers from a source folder."""+ try:+ import psutil+ except ImportError:+ return None # Unknown: everything counts as in use.+ found = []+ for process in psutil.process_iter(['exe', 'cwd', 'cmdline']):+ info = process.info+ values = [info.get('exe'), info.get('cwd'), *(info.get('cmdline') or ())]+ try:+ values += (process.environ().get('PYTHONPATH') or '').split(os.pathsep)+ except (psutil.Error, OSError):+ pass # Another user's process cannot run our copies.+ found += [os.path.normcase(str(value)) for value in values if value]+ return found+++def started_from(path, running):+ """Whether a running process uses path, by the references captured for this run."""+ if running is None:+ return True+ prefix = os.path.normcase(os.path.abspath(path))+ # The folder itself, a path inside it, or an option ending with it (--root=...).+ return any(value.endswith(prefix) or prefix + os.sep in value for value in running)+++def remove(path, root, running=None):+ """Rename, then delete; a folder Windows cannot rename is still in use.++ A deletion that stops part-way leaves the renamed folder, which a later run+ finishes; nothing else ever has that name.+ """+ path, root = Path(path), Path(root)+ if not local_path(root, path) or not plain_tree(path) or started_from(path, running):+ return 0+ size = tree_bytes(path)+ retired = path.with_name(path.name + '.retired-' + uuid.uuid4().hex[:8])+ try:+ os.rename(path, retired)+ except OSError:+ return 0+ shutil.rmtree(retired, ignore_errors=True)+ return size if not retired.exists() else size - tree_bytes(retired)+++def finish_retired(parent, root, pattern):+ """Folders an earlier run renamed but could not finish deleting."""+ released = 0+ for path in sorted(Path(parent).glob('*.retired-*')):+ match = RETIRED.fullmatch(path.name)+ if match and pattern.fullmatch(match['name']) and path.is_dir() and local_path(Path(root), path):+ size = tree_bytes(path)+ shutil.rmtree(path, ignore_errors=True)+ released += size if not path.exists() else 0+ return released+++def unchanged_source(path):+ """A materialized source exactly as deployed: launcher-source.json still describes every file."""+ try:+ rows = json.loads((path / 'launcher-source.json').read_text(encoding='utf-8'))['sha256']+ if not isinstance(rows, dict) or not rows:+ return False+ seen = set()+ for directory, folders, files in os.walk(path, followlinks=False):+ for name in files:+ item = Path(directory) / name+ relative = item.relative_to(path).as_posix()+ if relative in rows:+ if digest(item) != rows[relative]:+ return False+ seen.add(relative)+ elif relative not in ('launcher-source.json', 'comfyui.json') and not (+ item.parent.name == '__pycache__' and item.suffix == '.pyc') and not (+ # That version's setup logs and editable-install metadata.+ relative.startswith(('.freevideo/comfy-setup/', 'freevideo_engine.egg-info/'))):+ return False # Something the user added.+ return seen == set(rows)+ except (OSError, ValueError, KeyError, TypeError):+ return False+++def editable_sources(engine):+ """Sources an environment installed in editable mode still imports from."""+ from urllib.parse import urlsplit+ from urllib.request import url2pathname+ found = set()+ for pattern in ('envs/*/Lib/site-packages/freevideo_engine-*.dist-info/direct_url.json',+ 'envs/*/lib/python3*/site-packages/freevideo_engine-*.dist-info/direct_url.json'):+ for path in Path(engine).glob(pattern):+ try:+ value = json.loads(path.read_text(encoding='utf-8'))+ url = urlsplit(value['url'])+ if url.scheme == 'file' and (value.get('dir_info') or {}).get('editable'):+ found.add(url2pathname(url.netloc and '//' + url.netloc + url.path or url.path))+ except (OSError, ValueError, KeyError, TypeError, AttributeError):+ found.add(None) # An unreadable record could name any source.+ return found+++def resolved(value):+ try:+ return Path(value).resolve() if value else None+ except (OSError, ValueError, TypeError):+ return None+++def version(path):+ """The build version a source folder is named after, as numbers."""+ try:+ return tuple(int(part) for part in Path(path).name.split('-', 1)[0].split('.'))+ except (ValueError, TypeError):+ return None+++def sources(parent, root, keep, current):+ """Source copies under parent older than the current one.++ A newer copy may belong to a newer launcher that is running; it is never+ an earlier version of this one.+ """+ rows = []+ parent = Path(parent)+ newest = version(current) if current else None+ if newest is None or not parent.is_dir() or not local_path(Path(root), parent):+ return rows+ keep = {path for path in map(resolved, keep) if path}+ for path in sorted(parent.iterdir()):+ if not VERSION.fullmatch(path.name) or path.is_symlink() or not path.is_dir() or path.resolve() in keep:+ continue+ if (version(path) or newest) < newest and unchanged_source(path):+ rows.append(path)+ return rows+++def downloads(parent, root, keep):+ """Launcher updates other than the running and the approved one."""+ rows = []+ parent = Path(parent)+ if not parent.is_dir() or not local_path(Path(root), parent):+ return rows+ for path in sorted(parent.iterdir()):+ if not DIGEST.fullmatch(path.name) or path.is_symlink() or not path.is_dir() or path.name[:64] in keep:+ continue+ try:+ names = [item.name for item in path.iterdir()]+ executables = [name for name in names if name in EXECUTABLES]+ extras = [name for name in names if name not in EXECUTABLES and not (name.startswith('download-') and name.endswith('.partial'))]+ if extras or len(executables) > 1 or (executables and digest(path / executables[0]) != path.name[:64]):+ continue+ except OSError:+ continue # Unreadable: kept.+ rows.append(path)+ return rows+++def applications(parent, root, keep):+ """Launchers behind earlier desktop shortcuts, checked against the digest that names them."""+ rows = []+ parent = Path(parent)+ if not parent.is_dir() or not local_path(Path(root), parent):+ return rows+ keep = {path for path in map(resolved, keep) if path}+ for path in sorted(parent.iterdir()):+ if not DIGEST.fullmatch(path.name) or path.is_symlink() or not path.is_dir() or path.resolve() in keep:+ continue+ try:+ names = sorted(item.name for item in path.iterdir())+ if names == ['FreeVideo.app']:+ # The Mac copy is named by its executable and Info.plist digests.+ contents = path / 'FreeVideo.app' / 'Contents'+ actual = hashlib.sha256((digest(contents / 'MacOS' / 'FreeVideo') ++ digest(contents / 'Info.plist')).encode()).hexdigest()+ elif names in (['FreeVideo.exe'], ['FreeVideo.exe', '_internal'],+ ['FreeVideo-Linux-x86_64.AppImage'], ['FreeVideo-Linux-x86_64.AppImage', 'freevideo.png']):+ actual = digest(path / names[0])+ else:+ continue+ except OSError:+ continue # Unreadable: kept.+ if actual == path.name[:64]:+ rows.append(path)+ return rows+++def environments(engine, current):+ """Separate ComfyUI environments for the current ComfyUI folder that the current one replaced."""+ rows = []+ try:+ current_identity = json.loads((current / 'freevideo-host.json').read_text(encoding='utf-8'))+ except (OSError, ValueError, TypeError):+ return rows+ for path in sorted((engine / 'envs').glob('comfyui-*')):+ if (not ENVIRONMENT.fullmatch(path.name) or path.is_symlink() or not path.is_dir()+ or path.resolve() == current.resolve()):+ continue+ try:+ identity = json.loads((path / 'freevideo-host.json').read_text(encoding='utf-8'))+ except (OSError, ValueError):+ continue # Without a receipt the owner is uncertain.+ if isinstance(identity, dict) and identity.get('comfy') == current_identity.get('comfy'):+ rows.append(path)+ return rows+++def torch_wheels(engine, pythons):+ """Downloaded PyTorch wheels, once every environment has exactly those versions installed."""+ if not windows():+ return [] # Other systems install PyTorch from the package cache.+ from .torch_download import catalog, installed_versions+ directory = engine / 'downloads' / 'torch-wheels'+ if not pythons or not directory.is_dir() or not local_path(engine, directory):+ return []+ rows = catalog()+ for python in pythons:+ installed = installed_versions(python)+ if any(installed.get(row['package']) != row['version'] for row in rows):+ return []+ found = []+ for row in rows:+ for path in (directory / row['filename'], *directory.glob(row['filename'] + '.partial*')):+ try:+ info = path.lstat()+ except OSError:+ continue+ if stat.S_ISREG(info.st_mode) and info.st_nlink == 1:+ found.append(path)+ return found+++def shortcut_targets():+ """Programs the user's own shortcuts, pinned taskbar items or Dock items start.++ Pinning a running launcher records the path of that exact copy, so a copy+ a shortcut names stays even when it is old. None when they cannot be read.+ """+ found = set()+ try:+ if windows():+ from .desktop_shortcut import desktop_directory, read_link_targets+ folders = [desktop_directory()]+ for variable, relative in (('APPDATA', 'Microsoft/Windows/Start Menu'), ('PROGRAMDATA', 'Microsoft/Windows/Start Menu'),+ ('APPDATA', 'Microsoft/Internet Explorer/Quick Launch'), ('PUBLIC', 'Desktop')):+ if os.environ.get(variable):+ folders.append(Path(os.environ[variable]) / relative)+ links = []+ for folder in folders:+ for path in (folder.rglob('*.lnk') if folder.is_dir() else ()):+ try:+ data = path.read_bytes()[:1 << 16]+ except OSError:+ continue+ if b'FreeVideo' in data or 'FreeVideo'.encode('utf-16-le') in data:+ links.append(path)+ found |= {Path(target) for target in read_link_targets(links).values()}+ elif sys.platform == 'linux':+ import shlex+ data = os.environ.get('XDG_DATA_HOME', '')+ folders = [Path(data) if os.path.isabs(data) else Path.home() / '.local/share', Path.home()]+ for path in [*(folders[0] / 'applications').glob('*.desktop'), *(folders[1] / 'Desktop').glob('*.desktop')]:+ try:+ lines = path.read_text(encoding='utf-8', errors='replace').splitlines()+ except OSError:+ continue+ for line in lines:+ if line.startswith('Exec=') and 'FreeVideo' in line:+ try:+ found.add(Path(shlex.split(line[5:].replace('%%', '%'))[0]))+ except (ValueError, IndexError):+ continue+ elif sys.platform == 'darwin':+ import plistlib+ from urllib.parse import unquote, urlsplit+ dock = plistlib.loads((Path.home() / 'Library/Preferences/com.apple.dock.plist').read_bytes())+ for key in ('persistent-apps', 'persistent-others', 'recent-apps'):+ for item in dock.get(key, []):+ url = ((item.get('tile-data') or {}).get('file-data') or {}).get('_CFURLString', '')+ if url.startswith('file://'):+ found.add(Path(unquote(urlsplit(url).path).rstrip('/')))+ except FileNotFoundError:+ pass # No Dock preferences yet.+ except Exception:+ return None+ return {path for path in map(resolved, found) if path}+++def superseded(candidate, current):+ """Whether the running launcher is this build or a newer one of the same kind."""+ if current is None:+ return False+ from .launcher_update import manifest, newer+ try:+ candidate = manifest(candidate)+ return candidate['revision'] == current['revision'] or newer(current, candidate)+ except (ValueError, TypeError, KeyError, AttributeError):+ return False+++def approved_digests(launcher_root, current=None):+ """The approved update, and a found one the running launcher would still offer."""+ keep = set()+ updates = Path(launcher_root) / 'updates'+ for name, read in (('active.json', lambda value: value['candidate']), ('available.json', lambda value: value)):+ try:+ found = read(json.loads((updates / name).read_text(encoding='utf-8')))+ digest = str(found['asset']['sha256'])+ except (OSError, ValueError, TypeError, KeyError):+ continue+ # A reminder of an update older than the running launcher is ignored by+ # the launcher too; only an unknown or newer one keeps its download.+ if name == 'available.json' and superseded(found, current):+ continue+ keep.add(digest)+ return keep+++def run(*, launcher_root=None, launcher_source=None, launcher_build=None, running=(), engine=None,+ comfy_root=None, engine_source=None, server_source=None, receipt=True):+ """Remove what the current launcher and installation no longer use; report what was freed."""+ from .locking import runtime_lock+ result = dict(released_bytes=0, removed=[], kept=[])+ snapshot = references()++ def drop(path, root, kind):+ released = remove(path, root, snapshot)+ if not Path(path).exists():+ result['released_bytes'] += released+ result['removed'].append(dict(kind=kind, path=str(path), bytes=released))+ else:+ result['kept'].append(dict(kind=kind, path=str(path), reason='in use'))++ running = [path for path in map(resolved, running) if path]+ linked = shortcut_targets()+ if linked is None:+ result['kept'].append(dict(kind='launcher-copies', reason='shortcuts unreadable'))+ if launcher_root:+ launcher_root = Path(launcher_root).absolute()+ keep = approved_digests(launcher_root, launcher_build) | {path.parent.name[:64] for path in [*running, *(linked or ())]}+ for path in downloads(launcher_root / 'updates', launcher_root, keep) if linked is not None else ():+ drop(path, launcher_root, 'launcher-update')+ result['released_bytes'] += finish_retired(launcher_root / 'updates', launcher_root, DIGEST)+ editable = editable_sources(engine) if engine else set()+ if None not in editable:+ for path in sources(launcher_root / 'source', launcher_root, {launcher_source, *editable}, launcher_source):+ drop(path, launcher_root, 'launcher-source')+ result['released_bytes'] += finish_retired(launcher_root / 'source', launcher_root, VERSION)+ if engine:+ engine = Path(engine).absolute()+ receipt_source = None+ if comfy_root:+ try:+ from .comfy_launcher_runtime import node_target+ receipt_source = json.loads((node_target(comfy_root) / 'freevideo-launcher.json')+ .read_text(encoding='utf-8')).get('source')+ except (OSError, ValueError, TypeError):+ pass+ editable = editable_sources(engine)+ # Unknown which copy ComfyUI or an environment loads: keep them all.+ if receipt_source and None not in editable:+ for path in sources(engine / 'launcher' / 'source', engine,+ {receipt_source, engine_source, server_source, *editable}, receipt_source):+ drop(path, engine, 'engine-source')+ result['released_bytes'] += finish_retired(engine / 'launcher' / 'source', engine, VERSION)+ try:+ target = json.loads((engine / 'launcher' / 'desktop-shortcut.json').read_text(encoding='utf-8')).get('target')+ except (OSError, ValueError, TypeError):+ target = None+ if target and linked is not None:+ keep = {Path(target).parent, *(path.parent for path in [*running, *linked])}+ for folder in ('application', 'application.noindex'):+ for path in applications(engine / 'launcher' / folder, engine, keep):+ drop(path, engine, 'launcher-copy')+ result['released_bytes'] += finish_retired(engine / 'launcher' / folder, engine, DIGEST)+ # Environments and downloads belong to installation: never race it.+ try:+ with runtime_lock(engine / 'setup.lock', inherit=False), \+ runtime_lock(engine / 'launcher' / 'host-setup.lock', inherit=False):+ pythons, current = [], None+ try:+ machine = json.loads((engine / 'machine.json').read_text(encoding='utf-8'))+ pythons.append(Path(machine['python']))+ except (OSError, ValueError, KeyError, TypeError):+ machine = None+ try:+ host = json.loads((engine / 'launcher' / 'comfy-host.json').read_text(encoding='utf-8'))+ current = Path(host['environment'])+ pythons.append(Path(host['python']))+ except (OSError, ValueError, KeyError, TypeError):+ pass+ if current is not None and current.is_dir() and local_path(engine, current):+ for path in environments(engine, current):+ drop(path, engine, 'comfyui-environment')+ result['released_bytes'] += finish_retired(engine / 'envs', engine, ENVIRONMENT)+ if machine and machine.get('ready') is True and all(python.is_file() for python in pythons):+ for path in torch_wheels(engine, pythons):+ try:+ size = path.stat().st_size+ path.unlink()+ result['released_bytes'] += size+ result['removed'].append(dict(kind='torch-wheel', path=str(path), bytes=size))+ except OSError:+ result['kept'].append(dict(kind='torch-wheel', path=str(path), reason='in use'))+ except OSError as error: # Includes BlockingIOError: an installation holds the lease.+ result['kept'].append(dict(kind='installation', reason=type(error).__name__))+ if receipt and result['removed']:+ save(engine / 'logs' / ('cleanup-' + time.strftime('%Y%m%dT%H%M%SZ', time.gmtime()) + '.json'), result)+ return resultdiff --git a/web/freevideo.js b/web/freevideo.jsindex 81edff7..8fe5e2c 100644--- a/web/freevideo.js+++ b/web/freevideo.js@@ -368,6 +368,12 @@ function syncPrompts(reset = false) {}window.addEventListener('freevideo-media', () => syncPrompts());+// health.js names what failed; files loaded before it queue their reports.+const health = item => (window.__freevideoHealth ||= []).push(item);+function showStudio(node) {+ try { openStudio(node); } catch (error) { console.error('FreeVideo workspace:', error); health({type: 'error', where: 'studio', error}); }+}+const progressConnection = createProgressConnection(api, message => {const node = app.graph?.getNodeById(message.node);if (!node?.freevideoShowProgress) return false;@@ -382,8 +388,13 @@ app.registerExtension({name: "FreeVideo.UnifiedMedia",beforeConfigureGraph() { configuringGraph = true; },async setup() {- progressConnection.start(); installNavigation(openStudio); startUpdateChecks();+ // 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)],+ ['updates', startUpdateChecks]]) {+ try { start(); } catch (error) { health({type: 'error', where, error}); }+ }window.addEventListener('pagehide', () => savePromptDraft(api, true));+ window.FreeVideoUI = {...window.FreeVideoUI, ready: true};await notifyCompatibility();},async beforeRegisterNodeDef(nodeType, nodeData) {@@ -436,7 +447,7 @@ app.registerExtension({prompt.inputEl?.addEventListener?.('input', () => rememberPromptDraft(api, node));}resultPanel(this);- this.addWidget('button', text('Open creative workspace', '打开创作面板'), null, () => openStudio(this), {serialize: false});+ this.addWidget('button', text('Open creative workspace', '打开创作面板'), null, () => showStudio(this), {serialize: false});const removed = this.onRemoved;this.onRemoved = function (...args) { const value = removed?.apply(this, args); requestAnimationFrame(refreshNavigation); return value; };requestAnimationFrame(refreshNavigation);@@ -452,7 +463,7 @@ app.registerExtension({refreshNavigation();if (app.graph?.extra?.freevideo_studio && preferredView() !== 'nodes') {const node = app.graph._nodes.find(n => n.comfyClass === 'FreeVideoGenerate' || n.type === 'FreeVideoGenerate');- if (node) requestAnimationFrame(() => openStudio(node));+ if (node) requestAnimationFrame(() => showStudio(node));}},onNodeOutputsUpdated(outputs) {diff --git a/web/health.js b/web/health.jsnew file mode 100644index 0000000..009c21e--- /dev/null+++ b/web/health.js@@ -0,0 +1,337 @@+// Checks that FreeVideo's page loaded completely and says what is wrong when+// it did not: which file, why, and what to do. It imports nothing and styles+// itself inline, so it still runs when every other FreeVideo file fails.+// Other FreeVideo files report through `window.__freevideoHealth.push(...)`.+const base = new URL('./', import.meta.url);+const query = new URLSearchParams(location.search);+const language = query.get('freevideo_lang');+const cn = language === 'zh' || (language !== 'en' && String(navigator.language || '').toLowerCase().startsWith('zh'));+const t = (en, zh) => cn ? zh : en;+// launcher.js removes this flag during setup; read it before that.+const launchVisit = query.get('freevideo') === 'launch';+// Every script this folder ships; a test keeps the list in step with web/*.js.+export const MODULES = ['branding.js', 'compatibility.js', 'error_panel.js', 'freevideo.js', 'generation_progress.js',+ 'health.js', 'launcher.js', 'library.js', 'motion.js', 'output_download.js', 'preview_scene.js',+ 'progress_connection.js', 'prompt_draft.js', 'prompt_enhance.js', 'prompt_references.js', 'report_issue.js',+ 'result_actions.js', 'sampling_effort.js', 'setup.js', 'share.js', 'studio.js', 'studio_queue.js',+ 'updates.js', 'view_navigation.js'];+const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));+const fileName = url => decodeURIComponent(String(url).split(/[?#]/)[0].split('/').pop() || String(url));+const ours = url => typeof url === 'string' && url.startsWith(base.href);++// Errors seen while the page loads: failed files, and console errors from+// ComfyUI that name the extension or file that failed.+const seen = [];+const note = (kind, text, extra = {}) => { if (seen.length < 60) seen.push({kind, text: String(text).slice(0, 500), ...extra}); };+const describe = value => value instanceof Error ? `${value.name}: ${value.message}`+ : value && typeof value === 'object' && value.error instanceof Error ? describe(value.error)+ : typeof value === 'string' ? value : (() => { try { return JSON.stringify(value); } catch { return String(value); } })();+const consoleError = console.error;+const reports = [];+let listener = null;+function receive(item) {+ if (!item || typeof item !== 'object') return;+ reports.push(item);+ listener?.(item);+}++// Only the first copy of this file listens; see the end of the file.+function install() {+ addEventListener('error', event => {+ const target = event.target;+ if (target && target !== window && (target.href || target.src)) note('resource', target.href || target.src, {url: target.href || target.src});+ else if (event.filename && ours(event.filename)) note('script', `${fileName(event.filename)}: ${event.message}`);+ }, true);+ addEventListener('unhandledrejection', event => {+ const reason = event.reason;+ if (String(reason?.stack || '').includes(base.href)) note('script', describe(reason));+ });+ console.error = function (...args) {+ try {+ const text = args.map(describe).join(' ');+ if (/Error loading extension|Error calling extension|already registered|Failed to fetch dynamically imported module|does not provide an export/i.test(text)+ || text.includes(base.pathname)) note('console', text);+ } catch { /* Never interfere with the page's own logging. */ }+ return consoleError.apply(this, args);+ };+ // Files that loaded first queued their reports in an array.+ const queued = Array.isArray(window.__freevideoHealth) ? window.__freevideoHealth : [];+ window.__freevideoHealth = {push: receive};+ for (const item of queued) receive(item);+}++const comfy = () => window.app?.graph ? window.app : window.comfyAPI?.app?.app?.graph ? window.comfyAPI.app.app : null;+const studioWorkflow = graph => (graph?._nodes || graph?.nodes || []).some(n => n.comfyClass === 'FreeVideoGenerate' || n.type === 'FreeVideoGenerate')+ && !!graph?.extra?.freevideo_studio;+const preferredView = () => { try { return localStorage.getItem('freevideo.view'); } catch { return null; } };+async function waitFor(test, ms) {+ const end = Date.now() + ms;+ for (;;) {+ const value = test();+ if (value || Date.now() >= end) return value;+ await sleep(200);+ }+}++async function probe(url) {+ try {+ const response = await fetch(url, {cache: 'no-store'});+ return {status: response.status, ok: response.ok, type: (response.headers.get('content-type') || '').split(';')[0].trim()};+ } catch (error) {+ return {status: 0, ok: false, type: '', error: describe(error)};+ }+}++const ADVICE = {+ files: t('FreeVideo’s page files are missing or unreadable. In the FreeVideo launcher, open Settings and click “Install / repair”, then open FreeVideo again.',+ 'FreeVideo 的网页文件缺失或无法读取。请在 FreeVideo 启动器的“设置”里点击“安装 / 修复”,完成后重新打开。'),+ type: t('ComfyUI sent the file with the wrong type, so the browser refused it. Restart ComfyUI; if it persists, copy the details and send them to us.',+ 'ComfyUI 发给浏览器的文件类型不对,浏览器拒绝使用。请重启 ComfyUI;仍然出现时,复制详情发给我们。'),+ browser: t('This browser cannot run FreeVideo. Open the same address in a current Chrome or Edge.',+ '当前浏览器无法运行 FreeVideo。请用最新版 Chrome 或 Edge 打开同一个地址。'),+ mixed: t('The browser mixed files from two FreeVideo versions. Press Ctrl+F5 to reload without the cache.',+ '浏览器混用了新旧两个版本的 FreeVideo 文件。请按 Ctrl+F5 强制刷新。'),+ duplicate: t('Keep custom_nodes/FreeVideo, move the other FreeVideo folders out of custom_nodes, then restart ComfyUI.',+ '请保留 custom_nodes/FreeVideo,把其他 FreeVideo 文件夹移出 custom_nodes,然后重启 ComfyUI。'),+ plugin: t('Another ComfyUI extension reported an error at the same time. Turn it off in ComfyUI Settings › Extensions, then reload.',+ '同时有其他 ComfyUI 插件报错。可在 ComfyUI“设置 › 扩展”里暂时停用它,然后刷新页面。'),+ reload: t('Reload the page. If it happens again, copy the details and send them to us.',+ '请刷新页面。仍然出现时,复制详情发给我们。'),+ relaunch: t('Click Start in the FreeVideo launcher again.', '请在 FreeVideo 启动器里重新点击“启动”。'),+};++// One sentence per finding, naming the file and the reason.+async function diagnoseModules() {+ const found = [];+ for (const name of MODULES) {+ const url = new URL(name, base).href, result = await probe(url);+ if (!result.ok) {+ found.push({text: result.status+ ? t(`Script ${name} could not be loaded: the server answered HTTP ${result.status}.`, `脚本 ${name} 无法加载:服务器返回 HTTP ${result.status}。`)+ : t(`Script ${name} could not be loaded: ${result.error}.`, `脚本 ${name} 无法加载:${result.error}。`), advice: 'files'});+ } else if (!/javascript|ecmascript/i.test(result.type)) {+ found.push({text: t(`Script ${name} was refused: the server sent it as “${result.type || 'no type'}”.`,+ `脚本 ${name} 被浏览器拒绝:服务器发送的类型是“${result.type || '未标明'}”。`), advice: 'type'});+ }+ }+ if (found.length) return found;+ // Every file is reachable, so the browser refused one while linking or running it.+ const failed = new Map();+ for (const name of MODULES) {+ try { await import(new URL(name, base).href); } catch (error) {+ const message = describe(error);+ failed.set(message, [...(failed.get(message) || []), name]);+ }+ }+ for (const [message, names] of failed) {+ const list = names.length > 3 ? `${names.slice(0, 3).join(cn ? '、' : ', ')}${t(` and ${names.length - 3} more`, ` 等 ${names.length} 个文件`)}` : names.join(cn ? '、' : ', ');+ found.push({text: t(`The browser could not run ${list}: ${message}`, `浏览器无法运行 ${list}:${message}`),+ advice: /does not provide an export/.test(message) ? 'mixed'+ : /SyntaxError|Unexpected token|Unexpected identifier|is not a function|is not defined|is not a constructor/.test(message) ? 'browser' : 'reload'});+ }+ return found;+}++function themeApplied() {+ const probe = document.createElement('div'); probe.className = 'fv-panel'; probe.hidden = true;+ document.body.append(probe);+ const value = getComputedStyle(probe).getPropertyValue('--fv-bg').trim();+ probe.remove();+ return value === '#111720';+}++async function diagnoseStyles() {+ if (themeApplied()) return [];+ const found = [];+ const links = [...document.querySelectorAll('link[rel="stylesheet"]')].filter(link => ours(link.href));+ const failed = new Set(seen.filter(row => row.kind === 'resource').map(row => row.url));+ for (const link of links) {+ // A stylesheet that failed still gets an empty sheet; ours are never empty.+ let loaded = false;+ try { loaded = !!link.sheet && link.sheet.cssRules.length > 0; } catch { loaded = !!link.sheet; }+ if (loaded && !failed.has(link.href)) continue;+ const name = fileName(link.href), result = await probe(link.href);+ found.push(!result.ok+ ? {text: t(`Stylesheet ${name} could not be loaded: ${result.status ? `HTTP ${result.status}` : result.error}.`,+ `样式文件 ${name} 无法加载:${result.status ? `HTTP ${result.status}` : result.error}。`), advice: 'files'}+ : result.type !== 'text/css'+ ? {text: t(`Stylesheet ${name} was refused: the server sent it as “${result.type || 'no type'}”.`,+ `样式文件 ${name} 被浏览器拒绝:服务器发送的类型是“${result.type || '未标明'}”。`), advice: 'type'}+ : {text: t(`Stylesheet ${name} did not load.`, `样式文件 ${name} 没有生效。`), advice: 'reload'});+ }+ if (!found.length) {+ found.push({text: links.length+ ? t('FreeVideo’s styles loaded but do not apply; another extension may be overriding them.', 'FreeVideo 的样式已下载但没有生效,可能被其他插件的样式覆盖。')+ : t('FreeVideo’s styles were never requested.', 'FreeVideo 的样式文件没有被加载。'), advice: links.length ? 'plugin' : 'reload'});+ }+ return found;+}++// Every custom-node folder that serves FreeVideo's page, from ComfyUI's own list.+async function freevideoFolders() {+ for (const path of ['../../api/extensions', '../../extensions']) {+ try {+ const response = await fetch(new URL(path, base), {cache: 'no-store'});+ if (!response.ok) continue;+ const folders = (await response.json()).map(url => /\/extensions\/([^/]+)\/freevideo\.js$/.exec(String(url))?.[1]).filter(Boolean);+ return [...new Set(folders.map(decodeURIComponent))];+ } catch { /* Try the older route. */ }+ }+ return [];+}++// Errors from other extensions explain a failure only when ours failed too.+function pluginErrors() {+ const names = new Map();+ for (const row of seen) {+ const match = /Error (?:calling|loading) extension '?([^' ]+)'?(?: method '([^']+)')?/.exec(row.text);+ if (!match || match[1].startsWith('FreeVideo') || ours(match[1])) continue;+ if (!names.has(match[1])) names.set(match[1], row.text);+ }+ return [...names].slice(0, 3).map(([name, text]) => ({+ text: t(`Extension ${fileName(name)} reported an error: ${text.slice(0, 240)}`, `插件 ${fileName(name)} 报错:${text.slice(0, 240)}`), advice: 'plugin'}));+}++function reportText(item) {+ const where = {studio: t('The creative workspace could not open', '创作面板打不开'),+ navigation: t('The FreeVideo toolbar could not be added', 'FreeVideo 工具栏没有加载'),+ progress: t('Live progress could not start', '生成进度无法更新'),+ updates: t('Update checks could not start', '更新检查无法启动'),+ launch: t('The FreeVideo workflow did not open', 'FreeVideo 工作流没有打开')}[item.where] || t('FreeVideo reported an error', 'FreeVideo 报错');+ return {text: `${where}${cn ? ':' : ': '}${describe(item.error)}`, advice: item.where === 'launch' ? 'relaunch' : 'reload'};+}++const distinct = problems => problems.filter((problem, index) => problems.findIndex(other => other.text === problem.text) === index);+let card = null, lastProblems = [];+function details(problems) {+ return [`FreeVideo page check · ${new Date().toISOString()}`,+ `Page: ${location.origin}${location.pathname}`,+ `Browser: ${navigator.userAgent}`,+ `ComfyUI frontend: ${window.__COMFYUI_FRONTEND_VERSION__ || 'unknown'}`,+ `FreeVideo UI: ${JSON.stringify(window.FreeVideoUI || {})}`,+ '', 'Problems:', ...problems.map(p => `- ${p.text}`),+ '', 'Errors seen while loading:', ...(seen.length ? seen.map(row => `- [${row.kind}] ${row.text}`) : ['- none'])].join('\n');+}++function show(problems) {+ lastProblems = problems;+ card?.remove();+ card = document.createElement('section');+ card.setAttribute('role', 'alert'); card.className = 'fv-health';+ Object.assign(card.style, {position: 'fixed', top: '16px', left: '50%', transform: 'translateX(-50%)', zIndex: '2147483000',+ width: 'min(600px, calc(100vw - 32px))', maxHeight: 'calc(100vh - 32px)', overflow: 'auto', boxSizing: 'border-box',+ padding: '18px 20px 16px', borderRadius: '12px', background: '#1a222e', color: '#e7edf7',+ border: '1px solid #5a3440', boxShadow: '0 18px 48px rgba(0,0,0,.45)',+ font: '13px/1.55 "Segoe UI","Microsoft YaHei UI","Noto Sans CJK SC","Noto Sans SC",system-ui,sans-serif'});+ const title = document.createElement('div');+ title.textContent = t('FreeVideo did not load completely', 'FreeVideo 没有完整加载');+ Object.assign(title.style, {color: '#f09aa2', fontWeight: '600', fontSize: '16px', marginBottom: '8px'});+ const list = document.createElement('ul');+ Object.assign(list.style, {margin: '0 0 10px', paddingLeft: '18px'});+ for (const problem of problems) {+ const row = document.createElement('li'); row.textContent = problem.text;+ Object.assign(row.style, {margin: '2px 0', overflowWrap: 'anywhere'});+ list.append(row);+ }+ const advice = document.createElement('div');+ advice.textContent = [...new Set(problems.map(p => ADVICE[p.advice] || ADVICE.reload))].join(' ');+ Object.assign(advice.style, {color: '#a5b3c6', marginBottom: '14px'});+ const actions = document.createElement('div');+ Object.assign(actions.style, {display: 'flex', flexWrap: 'wrap', gap: '8px'});+ const action = (label, run, primary = false) => {+ const button = document.createElement('button'); button.type = 'button'; button.textContent = label; button.onclick = run;+ Object.assign(button.style, {height: '32px', padding: '0 14px', borderRadius: '8px', cursor: 'pointer', font: 'inherit',+ border: primary ? '0' : '1px solid #2a3443', background: primary ? '#6db8fa' : '#212a37', color: primary ? '#0d1520' : '#e7edf7',+ fontWeight: primary ? '600' : '400'});+ actions.append(button); return button;+ };+ action(t('Reload page', '刷新页面'), () => location.reload(), true);+ const copy = action(t('Copy details', '复制详情'), async () => {+ const text = details(problems);+ try { await navigator.clipboard.writeText(text); } catch {+ const area = document.createElement('textarea'); area.value = text; document.body.append(area); area.select();+ try { document.execCommand('copy'); } catch { /* The details remain in the console. */ } area.remove();+ }+ copy.textContent = t('Copied', '已复制');+ });+ action(t('Close', '关闭'), () => { card?.remove(); card = null; });+ card.append(title, list, advice, actions);+ document.body.append(card);+ // A modal such as an unstyled workspace sits in the top layer; a manual+ // popover joins it and returns to the front whenever a dialog opens.+ if (typeof card.showPopover === 'function') {+ card.popover = 'manual';+ Object.assign(card.style, {right: 'auto', bottom: 'auto', margin: '0'});+ card.showPopover();+ }+ consoleError.call(console, '[FreeVideo] Page check:\n' + details(problems));+}+new MutationObserver(() => {+ if (!card?.isConnected || typeof card.showPopover !== 'function' || !document.querySelector('dialog[open]')) return;+ try { card.hidePopover(); card.showPopover(); } catch { /* Shown below the dialog instead. */ }+}).observe(document.documentElement, {subtree: true, attributeFilter: ['open']});++let sent = '';+function send(state, problems) {+ // Kept with diagnostic reports, so a report from this computer names the cause.+ const body = JSON.stringify({state, problems: problems.map(p => p.text), errors: seen.map(row => `[${row.kind}] ${row.text}`),+ ready: !!window.FreeVideoUI?.ready, launch: launchVisit, view: preferredView() || '',+ agent: navigator.userAgent, frontend: String(window.__COMFYUI_FRONTEND_VERSION__ || ''), page: location.pathname});+ if (body === sent) return;+ sent = body;+ fetch(new URL('../../api/freevideo/launcher/ui', base), {method: 'POST', headers: {'Content-Type': 'application/json'}, body, keepalive: true})+ .catch(() => { /* An older or stopped server; the card on the page still shows the problem. */ });+}++async function check() {+ const app = await waitFor(comfy, 60000);+ if (!app) {+ const problems = [{text: t('The ComfyUI page did not finish loading within a minute.', 'ComfyUI 页面在一分钟内没有加载完成。'), advice: 'browser'}];+ show(problems); send('error', problems); return;+ }+ // freevideo.js marks itself ready in its setup; launcher.js reports once+ // the workflow is open and in front.+ await waitFor(() => window.FreeVideoUI?.ready, 10000);+ const launched = launchVisit ? await waitFor(() => reports.find(r => r.type === 'launch'), 30000) : null;+ // Opening the workspace waits for an animation frame.+ await sleep(1500);+ const problems = [];+ const ui = window.FreeVideoUI || {};+ if (!ui.ready) problems.push(...await diagnoseModules());+ if (!ui.ready && !problems.length) problems.push({text: t('FreeVideo’s scripts loaded, but ComfyUI did not start them.', 'FreeVideo 的脚本已下载,但 ComfyUI 没有启动它们。'), advice: 'reload'});+ if (!problems.length) problems.push(...await diagnoseStyles());+ if (launchVisit && !problems.length) {+ if (!launched) problems.push({text: t('The FreeVideo workflow did not open: launcher.js did not report back.', 'FreeVideo 工作流没有打开:launcher.js 没有响应。'), advice: 'reload'});+ else if (launched.error) problems.push(reportText(launched));+ else if (!studioWorkflow(app.graph)) problems.push({text: t('ComfyUI shows another workflow; the FreeVideo workflow is in another tab.', 'ComfyUI 显示的是另一个工作流,FreeVideo 工作流在别的标签页里。'), advice: 'relaunch'});+ else if (preferredView() !== 'nodes' && !document.querySelector('dialog.fv-studio[open]')+ && !reports.some(item => item.type === 'error' && item.where === 'studio'))+ problems.push({text: t('The creative workspace did not open.', '创作面板没有打开。'), advice: 'reload'});+ }+ for (const item of reports) if (item.type === 'error') problems.push(reportText(item));+ const copies = await freevideoFolders();+ if (copies.length > 1 || seen.some(row => /already registered/i.test(row.text) && /FreeVideo\./.test(row.text))) {+ const named = copies.map(name => `custom_nodes/${name}`).join(cn ? '、' : ', ');+ problems.push({text: copies.length > 1 ? t(`ComfyUI loaded FreeVideo more than once: ${named}.`, `ComfyUI 加载了多份 FreeVideo:${named}。`)+ : t('ComfyUI loaded FreeVideo more than once.', 'ComfyUI 加载了多份 FreeVideo。'), advice: 'duplicate'});+ }+ if (problems.length) {+ problems.push(...pluginErrors());+ show(distinct(problems)); send('error', distinct(problems));+ } else {+ send('ready', []);+ }+ // Later failures, such as the workspace failing to open from a node.+ listener = item => {+ if (item.type !== 'error') return;+ const problems = distinct([...lastProblems, reportText(item)]);+ show(problems); send('error', problems);+ };+}++// A second FreeVideo folder loads this file again; one check covers both.+if (!window.__freevideoHealthStarted) {+ window.__freevideoHealthStarted = true;+ install();+ check().catch(error => consoleError.call(console, '[FreeVideo] Page check failed:', error));+}diff --git a/web/launcher.js b/web/launcher.jsindex 2b6490a..43defcf 100644--- a/web/launcher.js+++ b/web/launcher.js@@ -2,24 +2,62 @@ import { app } from '../../scripts/app.js';import { api } from '../../scripts/api.js';import { restorePromptDraft } from './prompt_draft.js';+// health.js names what failed; files loaded before it queue their reports.+const health = item => (window.__freevideoHealth ||= []).push(item);+const studioWorkflow = graph => (graph?._nodes || graph?.nodes || []).some(n => n.comfyClass === 'FreeVideoGenerate' || n.type === 'FreeVideoGenerate')+ && !!graph?.extra?.freevideo_studio;+const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));+let configured = performance.now();++// 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 ours back unless the user has+// already moved on. Never awaited from setup: ComfyUI restores only after+// setup returns.+async function keepInFront(workflow, opened) {+ let touched = false;+ const touch = event => { if (!event.target?.closest?.('.fv-studio, .fv-health')) touched = true; };+ addEventListener('pointerdown', touch, true); addEventListener('keydown', touch, true);+ try {+ const begin = performance.now();+ while (performance.now() - begin < 15000+ && (app.extensionManager?.spinner || performance.now() - configured < 600)) await sleep(100);+ if (studioWorkflow(app.graph) || touched) return;+ const store = app.extensionManager?.workflow;+ // Our own tab when ComfyUI still has it; a new one otherwise.+ const target = opened && store?.getWorkflowByPath?.(opened.path) === opened ? opened : 'FreeVideo';+ await app.loadGraphData(structuredClone(workflow), true, true, target);+ } finally {+ removeEventListener('pointerdown', touch, true); removeEventListener('keydown', touch, true);+ }+}+// Explicit launcher navigation only; ordinary ComfyUI visits restore their own// graph. Remove the flag before loading so refreshing never resets user edits.app.registerExtension({name: 'FreeVideo.Launcher',+ afterConfigureGraph() { configured = performance.now(); },async setup() {const url = new URL(window.location.href);if (url.searchParams.get('freevideo') !== 'launch') return;url.searchParams.delete('freevideo');window.history.replaceState(window.history.state, '', url);+ let workflow;try {const response = await api.fetchApi('/freevideo/launcher/workflow');if (!response.ok) throw new Error(`FreeVideo workflow: HTTP ${response.status}`);// A fresh copy of the bundled workflow, with the prompt last written.- const workflow = await restorePromptDraft(api, await response.json());- await app.loadGraphData(workflow, true, true, 'FreeVideo');+ workflow = await restorePromptDraft(api, await response.json());+ await app.loadGraphData(structuredClone(workflow), true, true, 'FreeVideo');} catch (error) {- app.extensionManager?.toast?.add({severity: 'error', summary: 'FreeVideo', detail: String(error), life: 15000});console.error('FreeVideo launcher:', error);+ health({type: 'launch', error});+ return;}+ const opened = app.extensionManager?.workflow?.activeWorkflow;+ keepInFront(workflow, opened).then(() => health({type: 'launch'}), error => {+ console.error('FreeVideo launcher:', error);+ health({type: 'launch', error});+ });},});