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.

Make launcher and engine updates hard to miss and finish in one action (#24)

Bowen Xuec67e9dcee31d
diff --git a/freevideo_engine/comfy_launcher_runtime.py b/freevideo_engine/comfy_launcher_runtime.py
index 3775976..d644d4e 100644
--- a/freevideo_engine/comfy_launcher_runtime.py
+++ b/freevideo_engine/comfy_launcher_runtime.py
@@ -195,6 +195,15 @@ def server_info(url):
return dict(status='offline')
+def queue_busy(url):
+ """Whether ComfyUI is running or holding jobs. An unreadable queue counts as idle."""
+ try:
+ value = get_json(url + '/queue', timeout=3)
+ return bool(value.get('queue_running') or value.get('queue_pending'))
+ except (OSError, ValueError, AttributeError):
+ return False
+
+
def matches_server(info, root, engine, source):
return (info.get('status') == 'freevideo'
and all(info.get(k) and Path(info[k]).resolve() == Path(p).resolve()
@@ -285,6 +294,18 @@ class Controller:
self.server_log = None
self.sections = []
self.section = None
+ # Set by the Qt session: lets the server it starts hand browser update
+ # requests back to this launcher.
+ self.update_bridge = None
+
+ def owns_server(self):
+ return self.server is not None and self.server.poll() is None
+
+ def stop_owned_server(self):
+ with self._server_lock:
+ if self.server is not None:
+ processes.stop(self.server, grace=5)
+ self.server = None
def terminal_sources(self):
sources = []
@@ -560,15 +581,30 @@ class Controller:
self.state = dict(self.state, status='open', url=url + '/?freevideo=launch')
return
if info['status'] != 'offline':
- self.state = dict(self.state, status='restart-required', url=url,
- error='ComfyUI is already running. Restart it once to load the installed FreeVideo nodes, then click Connect. Existing jobs are left running.')
- return
+ if not self.owns_server():
+ self.state = dict(self.state, status='restart-required', url=url,
+ error='ComfyUI is already running. Restart it once to load the installed FreeVideo nodes, then click Connect. Existing jobs are left running.')
+ return
+ if queue_busy(url):
+ self.state = dict(self.state, status='restart-required', url=url,
+ error='ComfyUI is still running a job. Click Connect after it finishes to restart with the update; the job is left running.')
+ return
+ # Our own idle server still runs the previous source: restart it.
+ self.stage('open', label='Restart ComfyUI')
+ self.stop_owned_server()
parsed = urlsplit(url)
- with socket.socket(socket.AF_INET6 if parsed.hostname == '::1' else socket.AF_INET, socket.SOCK_STREAM) as check:
- try:
- check.bind((parsed.hostname, parsed.port or 80))
- except OSError as error:
- raise ValueError('This port is in use by another application. Set a different local ComfyUI address.') from error
+ deadline = time.monotonic() + 10
+ while True:
+ with socket.socket(socket.AF_INET6 if parsed.hostname == '::1' else socket.AF_INET, socket.SOCK_STREAM) as check:
+ try:
+ check.bind((parsed.hostname, parsed.port or 80))
+ break
+ except OSError as error:
+ # A server this launcher just stopped can hold the port briefly.
+ if info['status'] != 'offline' and time.monotonic() < deadline:
+ self.cancelled.wait(.5)
+ continue
+ raise ValueError('This port is in use by another application. Set a different local ComfyUI address.') from error
if not selected.get('python') or not Path(selected['python']).is_file():
raise ValueError('ComfyUI Python is missing. Inspect again to prepare a separate environment.')
directory = Path(selected['engine']) / 'launcher' / 'comfy-runs' / (time.strftime('%Y%m%dT%H%M%S') + '-' + secrets.token_hex(4))
@@ -582,6 +618,10 @@ class Controller:
env['PYTHONDONTWRITEBYTECODE'] = '1'
env.update(PYTHONUNBUFFERED='1', PYTHONUTF8='1', PYTHONIOENCODING='utf-8')
env['FREEVIDEO_COMFY_LOG'] = str(self.server_log)
+ from .launcher_bridge import ENV as BRIDGE
+ env.pop(BRIDGE, None)
+ if self.update_bridge:
+ env[BRIDGE] = str(self.update_bridge)
command = [selected['python'], '-u', '-B', str(Path(selected['root']) / 'main.py'), '--listen', parsed.hostname,
'--port', str(parsed.port or 80), '--disable-auto-launch']
managed = managed_frontend(selected)
diff --git a/freevideo_engine/comfy_updates.py b/freevideo_engine/comfy_updates.py
index dadf3b2..19682bc 100644
--- a/freevideo_engine/comfy_updates.py
+++ b/freevideo_engine/comfy_updates.py
@@ -1,6 +1,8 @@
-"""Optional browser update notices; no installation or generation side effects."""
+"""Optional browser update notices. Applying an update is delegated to the
+launcher that started this server; the server itself never installs anything."""
from datetime import datetime, timezone
import json
+import os
from pathlib import Path
import re
import threading
@@ -30,26 +32,62 @@ def installed_build(package):
return None
+def launcher_view(status):
+ """The parts of a launcher status a page may show; None without a launcher."""
+ if not isinstance(status, dict):
+ return None
+ view = {k: status.get(k) for k in ('version', 'phase', 'status', 'progress', 'candidate', 'engine', 'error', 'manual')}
+ view['phase'] = str(view['phase'] or '')
+ return view
+
+
class UpdateStatus:
- """One bounded background check per server, shared by all browser tabs."""
- def __init__(self, current):
+ """One bounded background check per server, shared by all browser tabs.
+
+ When the launcher that started this server is running, its own release
+ check and engine comparison are used instead of a second GitHub request.
+ """
+ def __init__(self, current, bridge=None):
self.current = current
+ self.bridge = bridge
self.state = dict(status='idle' if current else 'source',
current_version=current['version'] if current else None,
available=None)
self.next_check = 0
+ self.client_seen = -1e9
self.lock = threading.Lock()
self.thread = None
- def snapshot(self):
+ def launcher(self):
+ if not self.bridge:
+ return None
+ from .launcher_bridge import read_status
+ return launcher_view(read_status(self.bridge))
+
+ def snapshot(self, *, client=False):
+ launcher = self.launcher()
with self.lock:
- if (self.current and time.monotonic() >= self.next_check
+ now = time.monotonic()
+ if client:
+ self.client_seen = now
+ if (launcher is None and self.current and now >= self.next_check
and not (self.thread and self.thread.is_alive())):
self.state['status'] = 'checking'
self.thread = threading.Thread(target=self._check, daemon=True,
name='FreeVideo-update-check')
self.thread.start()
- return dict(self.state)
+ state = dict(self.state)
+ # Pages that reload themselves after an update polled recently.
+ state['clients'] = int(now - self.client_seen < 20)
+ if launcher is not None:
+ engine = launcher.get('engine') or {}
+ candidate = launcher.get('candidate') if isinstance(launcher.get('candidate'), dict) else None
+ available = (dict(version=str(candidate.get('version'))) if candidate and candidate.get('version') else
+ dict(version=str(engine.get('version'))) if engine.get('pending') and engine.get('version') else None)
+ if self.current or available:
+ state.update(status='available' if available else 'current', available=available)
+ state['launcher'] = launcher
+ return state
def _check(self):
try:
@@ -75,9 +113,29 @@ def register():
if server is None or getattr(server, '_freevideo_updates', None):
return
# Capture once: replacing files on disk cannot update a running engine.
- status = UpdateStatus(installed_build(Path(__file__).parent))
+ from .launcher_bridge import ENV, request as ask_launcher
+ bridge = os.environ.get(ENV) or None
+ status = UpdateStatus(installed_build(Path(__file__).parent), bridge=bridge)
server._freevideo_updates = status
@server.routes.get('/freevideo/updates')
async def updates(request):
- return web.json_response(status.snapshot(), headers={'Cache-Control': 'no-store'})
+ value = status.snapshot(client=request.query.get('client') == '1')
+ return web.json_response(value, headers={'Cache-Control': 'no-store'})
+
+ @server.routes.post('/freevideo/updates/apply')
+ async def apply(request):
+ # An explicit click in the page; the launcher verifies, downloads,
+ # waits for running jobs and restarts. Without one, show the release.
+ if status.launcher() is None:
+ return web.json_response(dict(status='unavailable'), status=409)
+ ask_launcher(bridge)
+ return web.json_response(dict(status='requested'), headers={'Cache-Control': 'no-store'})
+
+ @server.routes.post('/freevideo/updates/cancel')
+ async def cancel(request):
+ # Withdraws an update that still waits for running jobs.
+ if status.launcher() is None:
+ return web.json_response(dict(status='unavailable'), status=409)
+ ask_launcher(bridge, 'cancel')
+ return web.json_response(dict(status='cancelled'), headers={'Cache-Control': 'no-store'})
diff --git a/freevideo_engine/failure_details.py b/freevideo_engine/failure_details.py
index 36d5351..d80b0ab 100644
--- a/freevideo_engine/failure_details.py
+++ b/freevideo_engine/failure_details.py
@@ -91,6 +91,10 @@ def launcher_failure(value, *, zh=False):
action='展开详情或导出报告,查看完整检查结果。' if zh else
'Open the details or export the report for the complete results.', kind='kernels')
rules = (
+ (r'ComfyUI is still running a job', 'busy',
+ ('A video is still generating', '还有视频正在生成'),
+ ('The update is installed. Click Connect again after the job finishes to restart ComfyUI with it.',
+ '更新已装好。等当前任务完成后点“重新连接”,ComfyUI 会重启并使用新版。')),
(r'Installation paused: Windows commit headroom', 'memory-commit',
('Windows memory headroom is low', 'Windows 内存提交余量不足'),
('Close memory-heavy applications, then retry. Downloaded files are retained.',
diff --git a/freevideo_engine/launcher/Main.qml b/freevideo_engine/launcher/Main.qml
index b23dbe1..9cfafe6 100644
--- a/freevideo_engine/launcher/Main.qml
+++ b/freevideo_engine/launcher/Main.qml
@@ -36,11 +36,36 @@ ApplicationWindow {
function number(n) { return typeof n === "number" && isFinite(n) }
function fraction(row) { return row && number(row.total) && row.total > 0 && number(row.done) && row.done <= row.total ? row.done / row.total : -1 }
function bytes(n) { return n >= 1073741824 ? (n/1073741824).toFixed(1)+" GiB" : (n/1048576).toFixed(1)+" MiB" }
+ readonly property bool updateOffered: s.update.engine || (!!s.update.candidate && ["available", "downloading", "ready", "error", "cancelled"].indexOf(s.update.status) >= 0)
+ // An engine update needs no download; offer it as the way to launch.
+ readonly property bool updateFirst: s.page === "launcher" && s.update.engine && !s.update.phase && !s.busy && s.status !== "open" && s.status !== "restart-required" && !s.needs_consent
+ function percent(row) { return row && row.total ? Math.floor(100 * row.done / row.total) + "%" : "" }
+ function updateHeadline() {
+ var phase = s.update.phase
+ if (phase === "downloading") return t("Downloading update ", "正在下载更新 ") + percent(s.update.progress)
+ if (phase === "waiting") return t("Updating after the current video finishes", "当前视频生成完成后自动更新")
+ if (phase === "restarting") return t("Restarting FreeVideo…", "正在重启 FreeVideo…")
+ if (phase === "engine") return t("Updating the engine…", "正在更新引擎…")
+ if (phase === "checking") return t("Checking for updates…", "正在检查更新…")
+ if (s.update.candidate) return t("FreeVideo ", "FreeVideo ") + s.update.candidate.version + t(" is available", " 可以更新")
+ return t("New engine ", "新版引擎 ") + s.update.current + t(" is ready", " 已就绪")
+ }
+ function updateExplanation() {
+ var phase = s.update.phase
+ if (phase === "downloading") return t("FreeVideo restarts when the download finishes. Models and settings are kept.", "下载完成后自动重启,模型和设置都会保留。")
+ if (phase === "waiting") return t("Running videos are not interrupted. FreeVideo restarts on its own afterwards.", "不会中断正在生成的视频,完成后自动重启更新。")
+ if (phase === "restarting" || phase === "engine") return t("ComfyUI restarts once; open FreeVideo pages refresh automatically.", "ComfyUI 会重启一次,已打开的 FreeVideo 页面会自动刷新。")
+ if (phase === "checking") return ""
+ if (s.update.status === "error" && s.update.error) return s.update.error
+ if (s.update.candidate) return t("Current version ", "当前版本 ") + s.update.current + t(". Updating keeps your models and settings and takes about a minute.", "。更新会保留模型和设置,约需 1 分钟。")
+ return t("Installed engine ", "已安装引擎 ") + (s.update.installed || "—") + t(". Updating takes about a minute and keeps your models and settings.", "。更新约需 1 分钟,模型和设置都会保留。")
+ }
function primaryText() {
if (needsRuntime) return t("Choose environment package", "选择运行环境包")
if (s.page === "comfy") return t("Continue", "继续")
if (needsPackages) return t("Choose offline packages", "选择离线包")
if (s.page === "models") return t("Check & continue", "检查并继续")
+ if (updateFirst) return t("Update & launch", "更新并启动")
if (s.page === "launcher") return s.status === "open" ? t("Open FreeVideo", "打开 FreeVideo") : s.status === "restart-required" ? t("Connect again", "重新连接") : t("Launch FreeVideo", "启动 FreeVideo")
return s.status === "review" ? t("Install & launch", "安装并启动") : s.status === "restart-required" ? t("Connect again", "重新连接") : t("Check & resume", "检查并继续")
}
@@ -506,6 +531,28 @@ ApplicationWindow {
ColumnLayout {
objectName: "launcherPage"
visible: s.page === "launcher"; Layout.fillWidth: true; spacing: 16
+ FCard {
+ objectName: "updateBanner"
+ visible: updateOffered || (!!s.update.phase && s.update.phase !== "review")
+ reveal: true; Layout.fillWidth: true; padding: 18; spacing: 10
+ color: theme.accentSubtle; border.color: theme.accentDim
+ RowLayout {
+ Layout.fillWidth: true; spacing: 14
+ FIcon { kind: "download"; ink: theme.accent; Layout.preferredWidth: 22; Layout.preferredHeight: 22 }
+ ColumnLayout {
+ Layout.fillWidth: true; spacing: 2
+ FText { objectName: "updateHeadline"; text: updateHeadline(); font.weight: Font.DemiBold; Layout.fillWidth: true }
+ FText { visible: text !== ""; text: updateExplanation(); color: theme.muted; font.pixelSize: theme.micro; Layout.fillWidth: true }
+ }
+ FButton { objectName: "cancelUpdateButton"; visible: s.update.phase === "waiting"; flat: true; text: t("Cancel update", "取消更新"); onClicked: { manualUpdate = false; backend.dismissUpdate() } }
+ FButton {
+ objectName: "engineUpdateButton"; primary: true; visible: !s.update.phase; enabled: !s.busy
+ text: s.update.status === "ready" && s.update.candidate ? t("Restart & update", "重启并更新") : t("Update now", "立即更新")
+ onClicked: { manualUpdate = !!s.update.candidate; backend.update("") }
+ }
+ }
+ FMeter { visible: s.update.phase === "downloading"; Layout.fillWidth: true; fraction: s.update.progress && s.update.progress.total ? s.update.progress.done / s.update.progress.total : -1; active: visible }
+ }
FCard {
Layout.fillWidth: true; padding: 26; spacing: 18
RowLayout {
@@ -530,11 +577,6 @@ ApplicationWindow {
}
}
FMeter { visible: s.busy; Layout.fillWidth: true; fraction: win.fraction(s.overall); active: s.busy }
- RowLayout {
- visible: s.engine_update_available; Layout.fillWidth: true; spacing: 12
- FText { text: t("Engine update available", "引擎有可用更新"); color: theme.muted; font.pixelSize: theme.micro; Layout.fillWidth: true }
- FButton { objectName: "engineUpdateButton"; text: t("Update", "更新"); flat: true; enabled: !s.busy; onClicked: backend.action("update-engine", false) }
- }
RowLayout {
visible: s.status === "open"; Layout.fillWidth: true; spacing: 8
FButton { text: t("Copy address", "复制地址"); onClicked: backend.copy(s.url) }
@@ -572,12 +614,13 @@ ApplicationWindow {
FButton { objectName: "backButton"; text: t("Back", "上一步"); flat: true; visible: s.page === "models" || s.page === "progress"; enabled: !s.busy; onClicked: backend.action("back", false) }
Item { Layout.fillWidth: true }
FButton { visible: s.busy; text: t("Pause", "暂停"); onClicked: backend.action("stop", false) }
+ FButton { objectName: "launchInstalledButton"; visible: updateFirst; flat: true; text: t("Launch current version", "启动当前版本"); onClicked: backend.action("primary", accepted) }
FButton {
objectName: "primaryButton"; primary: true; implicitWidth: Math.max(160, contentItem.implicitWidth+40); implicitHeight: theme.heightLg
text: s.busy ? t("Working…", "正在处理…") : primaryText()
enabled: !s.busy && !(s.page === "launcher" && s.needs_consent && !accepted)
&& !(s.page === "progress" && s.status === "review" && (!accepted || !!s.error))
- onClicked: { if (needsRuntime) { backend.browseRuntimePackage(); return } if (needsPackages) { backend.browsePackages(); return } backend.action(s.page === "launcher" && s.status === "open" ? "browser" : "primary", accepted); if (s.busy && s.page === "launcher") terminalOpen = true }
+ onClicked: { if (needsRuntime) { backend.browseRuntimePackage(); return } if (needsPackages) { backend.browsePackages(); return } if (updateFirst) { backend.update(""); return } backend.action(s.page === "launcher" && s.status === "open" ? "browser" : "primary", accepted); if (s.busy && s.page === "launcher") terminalOpen = true }
}
}
}
@@ -811,16 +854,16 @@ ApplicationWindow {
ColumnLayout {
id: updateContents; width: updateScroll.availableWidth
spacing: 14
- FText { text: s.update.candidate ? t("Update available", "有可用更新") : t("Updates", "更新"); font.pixelSize: theme.section + 2; font.weight: Font.DemiBold }
- FText { text: s.update.candidate ? t("A new version is available. Updating keeps your models and settings.", "发现新版本,更新会保留模型和设置。") : s.update.status === "current" ? t("You're up to date.", "已是最新版本。") : s.update.status === "development" ? t("Running from source. Update with Git.", "当前从源码运行,请通过 Git 更新。") : s.update.status === "error" ? t("Couldn't check for updates. Try again below.", "暂时无法检查更新,请重试。") : t("Checking the latest release…", "正在检查最新版本…"); color: theme.muted; Layout.fillWidth: true }
+ FText { text: s.update.candidate ? t("Update available", "有可用更新") : s.update.engine ? t("Engine update", "引擎更新") : t("Updates", "更新"); font.pixelSize: theme.section + 2; font.weight: Font.DemiBold }
+ FText { objectName: "updateDialogText"; text: s.update.phase === "waiting" ? t("A video is still generating. FreeVideo restarts and updates as soon as it finishes.", "还有视频正在生成,完成后会自动重启并更新。") : s.update.status === "ready" && s.update.candidate ? t("Downloaded. Restart to finish; models and settings are kept.", "下载完成,重启即可完成更新,模型和设置都会保留。") : s.update.candidate ? t("FreeVideo ", "FreeVideo ") + s.update.candidate.version + t(" is available (current ", " 已发布(当前 ") + s.update.current + t("). Updating keeps your models and settings. FreeVideo restarts after the download; running videos finish first.", ")。更新会保留模型和设置,下载完成后自动重启;正在生成的视频会先完成。") : s.update.engine ? t("This launcher already includes engine ", "启动器已带有新版引擎 ") + s.update.current + t(" (installed ", "(已安装 ") + (s.update.installed || "—") + (s.status === "open" ? t("). Updating takes about a minute, restarts ComfyUI once and keeps your models and settings.", ")。更新约需 1 分钟,会重启一次 ComfyUI,模型和设置都会保留。") : t("). Updating takes about a minute, then FreeVideo starts; models and settings are kept.", ")。更新约需 1 分钟,完成后自动启动,模型和设置都会保留。")) : s.update.status === "current" ? t("You're up to date.", "已是最新版本。") : s.update.status === "development" ? t("Running from source. Update with Git.", "当前从源码运行,请通过 Git 更新。") : s.update.status === "error" ? t("Couldn't check for updates. Try again below.", "暂时无法检查更新,请重试。") : t("Checking the latest release…", "正在检查最新版本…"); color: theme.muted; Layout.fillWidth: true }
FMeter { Layout.fillWidth: true; visible: s.update.status === "downloading"; active: true; fraction: s.update.progress && s.update.progress.total ? s.update.progress.done/s.update.progress.total : -1 }
FText { visible: !!s.update.error; text: s.update.error || ""; color: theme.danger; Layout.fillWidth: true; font.pixelSize: theme.micro }
FField { id: githubToken; visible: !!s.update.error; Layout.fillWidth: true; echoMode: TextInput.Password; placeholderText: t("GitHub token · optional", "GitHub Token · 可选") }
RowLayout {
Layout.fillWidth: true; Layout.topMargin: 8
- FButton { objectName: "updateLaterButton"; text: s.update.candidate ? t("Later", "稍后更新") : t("Close", "关闭"); flat: true; onClicked: { manualUpdate = false; backend.dismissUpdate() } }
+ FButton { objectName: "updateLaterButton"; text: s.update.candidate || s.update.engine ? t("Later", "稍后更新") : t("Close", "关闭"); flat: true; onClicked: { manualUpdate = false; backend.dismissUpdate() } }
Item { Layout.fillWidth: true }
- FButton { objectName: "updateNowButton"; text: s.update.status === "ready" ? t("Restart & update", "重启并更新") : s.update.candidate ? t("Update now", "立即更新") : t("Check again", "重新检查"); primary: true; enabled: ["checking","downloading"].indexOf(s.update.status) < 0; onClicked: { manualUpdate = true; backend.update(githubToken.text) } }
+ FButton { objectName: "updateNowButton"; text: s.update.status === "ready" && s.update.candidate ? t("Restart & update", "重启并更新") : s.update.candidate || s.update.engine ? t("Update now", "立即更新") : t("Check again", "重新检查"); primary: true; enabled: ["checking","downloading"].indexOf(s.update.status) < 0 && s.update.phase !== "waiting"; onClicked: { manualUpdate = !!s.update.candidate || !s.update.engine; backend.update(githubToken.text) } }
}
}
}
diff --git a/freevideo_engine/launcher_bridge.py b/freevideo_engine/launcher_bridge.py
new file mode 100644
index 0000000..43c7a1b
--- /dev/null
+++ b/freevideo_engine/launcher_bridge.py
@@ -0,0 +1,74 @@
+"""File handoff between the launcher and the ComfyUI server it started.
+
+The server only records an explicit browser request; the launcher itself
+checks, downloads the verified release and restarts. Standard library only.
+"""
+import json
+import os
+from pathlib import Path
+import secrets
+import shutil
+import time
+
+from .monitoring import save
+
+ENV = 'FREEVIDEO_LAUNCHER_BRIDGE'
+# The launcher rewrites its status at least this often while it runs.
+HEARTBEAT_SECONDS = 5
+FRESH_SECONDS = 20
+
+
+def create(root):
+ parent = Path(root) / 'bridge'
+ parent.mkdir(parents=True, exist_ok=True)
+ # Folders of launchers that ended without cleanup are only advisory.
+ for old in parent.iterdir():
+ try:
+ if old.is_dir() and time.time() - old.stat().st_mtime > 86400:
+ shutil.rmtree(old, ignore_errors=True)
+ except OSError:
+ pass
+ path = parent / ('%d-%s' % (os.getpid(), secrets.token_hex(4)))
+ path.mkdir()
+ return path
+
+
+def remove(path):
+ if path:
+ shutil.rmtree(path, ignore_errors=True)
+
+
+def write_status(path, value):
+ save(Path(path) / 'status.json', dict(value, updated_at=time.time()))
+
+
+def read_status(path, *, max_age=FRESH_SECONDS):
+ """A recent launcher status, or None when no launcher is listening."""
+ try:
+ value = json.loads((Path(path) / 'status.json').read_text(encoding='utf-8'))
+ if isinstance(value, dict) and abs(time.time() - float(value.get('updated_at', 0))) <= max_age:
+ return value
+ except (OSError, ValueError, TypeError):
+ pass
+ return None
+
+
+def request(path, action='update'):
+ if action not in ('update', 'cancel'):
+ raise ValueError('Unknown launcher request')
+ save(Path(path) / 'request.json', dict(action=action, at=time.time()))
+
+
+def take_request(path):
+ file = Path(path) / 'request.json'
+ try:
+ value = json.loads(file.read_text(encoding='utf-8'))
+ except FileNotFoundError:
+ return None
+ except (OSError, ValueError):
+ value = None
+ try:
+ file.unlink()
+ except OSError:
+ pass
+ return value if isinstance(value, dict) and value.get('action') in ('update', 'cancel') else None
diff --git a/freevideo_engine/launcher_session.py b/freevideo_engine/launcher_session.py
index b3a0c1c..6fb8fbd 100644
--- a/freevideo_engine/launcher_session.py
+++ b/freevideo_engine/launcher_session.py
@@ -1,4 +1,5 @@
"""Widget-independent state for the Qt launcher; uses the existing installer."""
+import json
import locale
import os
from pathlib import Path
@@ -16,8 +17,28 @@ from .model_status import FAMILIES, NAMES
from .setup_progress import progress_text
from .terminal_ui import clean, duration
+# Background launcher release checks while the window stays open.
+CHECK_SECONDS = 30 * 60
+# "Later" hides one reminder for this long; a newer release reminds at once.
+SNOOZE_SECONDS = 4 * 3600
+QUEUE_POLL_SECONDS = 3
+
class Session:
+ # Update flow defaults; __init__ starts each launcher session from these.
+ update_snoozed = {}
+ update_intent = None
+ update_source = 'launcher'
+ update_waiting = update_restarting = False
+ engine_updating = engine_autoinstall = reload_expected = resume_pages = False
+ browser_wait = queue_state = queue_thread = bridge = None
+ clients_polled = queue_polled = resume_until = resume_polled = bridge_polled = 0.
+ bridge_pending = False
+ bridge_written = (0., None)
+ update_checked = 0.
+ page = 'comfy'
+ selected = installed_versions = None
+
def __init__(self, source=None, *, controller=None, store=None, updater=None, smoke=False):
from .offline_packages import Importer
self.importer = Importer()
@@ -57,7 +78,10 @@ class Session:
self.closing = False
self.smoke = smoke
self.reported_setup = None
- self.update_snoozed = False
+ # An explicit update continues from tick() through update_intent:
+ # 'check', 'launcher' or 'engine'. Other defaults are class attributes.
+ self.update_snoozed = {}
+ self.installed_versions = {}
if self.controller.restore(dict(saved, engine=self.form['engine'])):
self.remember(self.controller.selection, persist=False)
self.page = 'launcher'
@@ -71,6 +95,20 @@ class Session:
self.updater = UpdateClient(identity, launcher_root())
if self.updater and not self.updater.busy:
self.updater.run('check')
+ self.update_checked = time.monotonic()
+ if self.updater and not smoke:
+ # A restart from an explicit update finishes by updating the engine.
+ # Check now so the engine reminder does not flash first, and keep
+ # checking briefly in case the previous launcher writes late.
+ self.resume_until = time.monotonic() + 20
+ self._check_resumed(time.monotonic())
+ if controller is None and not smoke:
+ from .launcher_bridge import create
+ try:
+ self.bridge = create(launcher_root())
+ self.controller.update_bridge = self.bridge
+ except OSError:
+ self.bridge = None
if self.form['environment_method'] == 'manual' and self.form['offline_runtime'] and not controller:
root = Path(self.form['offline_runtime'])
if (root / 'portable.json').is_file():
@@ -178,6 +216,7 @@ class Session:
if getattr(self.controller, 'fixed_environment', False) is True:
self.controller.close()
self.controller = Controller(self.source)
+ self.controller.update_bridge = self.bridge
self.page = 'comfy'; return
if name == 'launcher' and self.selected:
if not self.controller.restore({'installation': self.selected}):
@@ -185,11 +224,9 @@ class Session:
self.page = 'launcher'
return
if name == 'update-engine' and self.selected:
- self.persist()
- self.controller.run('inspect', dict(self.form, token=self.token))
- self.page = 'progress'
- self.model_groups = []
- self.started = time.monotonic()
+ self.update_intent, self.update_source = 'engine', 'launcher'
+ self.queue_state = None
+ self._update_engine_when_idle()
return
if name == 'back':
self.page = 'comfy' if self.page == 'models' else 'models'
@@ -332,41 +369,275 @@ class Session:
threading.Thread(target=work, name='freevideo-export-report', daemon=True).start()
+ def engine_update_pending(self):
+ """This launcher carries a newer engine than the installed one.
+
+ An older launcher opened later would otherwise offer a downgrade."""
+ if not (self.selected and self.controller.state.get('engine_update_available')):
+ return False
+ bundled = self.source_stamp(self.source)[1]
+ installed = self.source_stamp(self.selected.get('source'))[1]
+ return not (bundled and installed and installed > bundled)
+
+ def update_key(self):
+ """The current reminder: a newer launcher first, then the bundled engine."""
+ row = self.updater.state if self.updater else {}
+ if row.get('candidate') and row.get('status') in ('available', 'downloading', 'ready', 'error', 'cancelled'):
+ return 'launcher:' + str(row['candidate'].get('revision', ''))
+ if self.engine_update_pending():
+ return 'engine:' + __version__
+ return ''
+
def dismiss_update(self):
- self.update_snoozed = True
+ key = self.update_key()
+ if key:
+ self.update_snoozed = dict(self.update_snoozed, **{key: time.monotonic() + SNOOZE_SECONDS})
+ self.update_intent = None
+ self.update_waiting = False
if self.updater and self.updater.state['status'] == 'downloading':
self.updater.cancelled.set()
+ def _unsnooze(self):
+ key = self.update_key()
+ self.update_snoozed = {k: v for k, v in self.update_snoozed.items() if k != key}
+
def check_update(self, token=''):
if self.updater and not self.updater.busy:
if token.strip():
self.updater.token = token.strip()
+ self.update_checked = time.monotonic()
self.updater.run('check')
- def update(self, token=''):
- if not self.updater or self.updater.busy or self.controller.busy or self.importer.busy:
+ def update(self, token='', source='launcher'):
+ """One explicit update: the newest launcher if one is known, otherwise
+ the engine bundled with this launcher. Downloading, waiting for running
+ ComfyUI jobs and restarting continue from tick()."""
+ if self.controller.busy or self.importer.busy or self.closing:
+ if source == 'browser':
+ self.bridge_pending = True
return
- from .launcher_update import launch_download, RELEASE_PAGE, DownloadedLauncherUnavailable
- from .windows_ux import open_browser
- row = self.updater.state
- if row['status'] == 'ready':
- self.persist()
- try:
- launch_download(row['candidate'], self.updater.root, token=self.updater.token)
- except DownloadedLauncherUnavailable:
- self.error = ''
- self.updater.run('download', row['candidate'])
- return
- self.closing = True
- elif row.get('candidate'):
+ if self.updater and token.strip():
+ self.updater.token = token.strip()
+ self.update_source = source
+ self.queue_state = None
+ row = self.updater.state if self.updater else {}
+ if self.updater and row.get('candidate') and row.get('status') != 'checking':
if self.updater.current.get('packaging') == 'onedir':
+ from .launcher_update import RELEASE_PAGE
+ from .windows_ux import open_browser
+ self.update_intent = None
open_browser(RELEASE_PAGE)
- else:
+ return
+ self._unsnooze()
+ self.update_intent = 'launcher'
+ if row['status'] == 'ready':
+ self._restart_when_idle()
+ elif not self.updater.busy:
self.updater.run('download', row['candidate'])
- else:
- self.updater.token = token.strip()
+ elif self.engine_update_pending():
+ self._unsnooze()
+ self.update_intent = 'engine'
+ self._update_engine_when_idle()
+ elif self.updater and not self.updater.busy:
+ self.update_intent = 'check'
+ self.update_checked = time.monotonic()
self.updater.run('check')
+ def _queue_busy(self):
+ """True or False once known for a server this launcher owns, None before."""
+ owns = getattr(self.controller, 'owns_server', None)
+ if not callable(owns) or owns() is not True:
+ return False
+ now = time.monotonic()
+ if (self.queue_thread is None or not self.queue_thread.is_alive()) and (
+ self.queue_state is None or now - self.queue_polled >= QUEUE_POLL_SECONDS):
+ from .comfy_launcher_runtime import queue_busy
+ url = (self.controller.selection or self.selected or {}).get('url') or self.form['url']
+ self.queue_polled = now
+ def poll():
+ # Off the UI thread: a stalled server must not freeze the window.
+ self.queue_state = queue_busy(url)
+ self.queue_thread = threading.Thread(target=poll, name='freevideo-queue', daemon=True)
+ self.queue_thread.start()
+ return self.queue_state
+
+ def _restart_when_idle(self):
+ row = self.updater.state
+ if row.get('status') != 'ready' or self.update_restarting:
+ return
+ busy = self._queue_busy()
+ self.update_waiting = bool(busy)
+ if busy is not False:
+ return
+ from .launcher_update import DownloadedLauncherUnavailable, handoff, launch_download
+ self.persist()
+ try:
+ handoff(row['candidate'], self.updater.root, self.update_source,
+ pages=self.controller.state.get('status') == 'open')
+ launch_download(row['candidate'], self.updater.root, token=self.updater.token)
+ except DownloadedLauncherUnavailable:
+ self.error = ''
+ self.updater.run('download', row['candidate'])
+ return
+ except Exception:
+ self.update_intent = None
+ raise
+ self.update_restarting = True
+ self._write_bridge_status(force=True)
+ self.closing = True
+
+ def _update_engine_when_idle(self):
+ if self.controller.busy or self.importer.busy:
+ return
+ busy = self._queue_busy()
+ self.update_waiting = bool(busy)
+ if busy is not False:
+ return
+ self.update_intent = None
+ self.engine_updating = self.engine_autoinstall = True
+ # Open pages reload themselves after the restart; without any, open
+ # the browser as soon as ComfyUI is ready.
+ self.reload_expected = (self.update_source == 'browser' or self.resume_pages
+ or self.controller.state.get('status') == 'open')
+ self.browser_attempted = False
+ self.browser_wait = None
+ self.persist()
+ self.controller.run('inspect', dict(self.form, token=self.token))
+ self.page = 'progress'
+ self.model_groups = []
+ self.started = time.monotonic()
+
+ def _tick_updates(self):
+ now = time.monotonic()
+ updater = self.updater
+ if (updater and self.update_intent is None and not updater.busy and now - self.update_checked >= CHECK_SECONDS
+ and updater.state.get('status') in ('idle', 'current', 'available', 'error', 'cancelled')):
+ self.update_checked = now
+ updater.run('check', background=True)
+ if self.resume_until:
+ self._check_resumed(now)
+ if self.bridge and now - self.bridge_polled >= 1:
+ self.bridge_polled = now
+ from .launcher_bridge import take_request
+ request = take_request(self.bridge)
+ if request and request['action'] == 'cancel':
+ self.bridge_pending = False
+ if self.update_intent:
+ self.dismiss_update()
+ elif request or (self.bridge_pending and not self.controller.busy):
+ self.bridge_pending = False
+ self.update(source='browser')
+ row = updater.state if updater else {}
+ if self.update_intent == 'check' and updater and not updater.busy:
+ self.update_intent = None
+ if row.get('candidate') or self.engine_update_pending():
+ self.update(source=self.update_source)
+ elif self.update_intent == 'launcher' and updater and not updater.busy:
+ if row.get('status') == 'ready':
+ self._restart_when_idle()
+ else:
+ self.update_intent, self.update_waiting = None, False
+ elif self.update_intent == 'engine':
+ self._update_engine_when_idle()
+ self._write_bridge_status()
+
+ def _check_resumed(self, now):
+ if now >= self.resume_until or self.update_intent:
+ self.resume_until = 0.
+ elif self.engine_update_pending() and now - self.resume_polled >= 1:
+ self.resume_polled = now
+ from .launcher_update import resumed_update
+ resumed = resumed_update(self.updater.current, self.updater.root)
+ if resumed:
+ self.resume_until = 0.
+ self.update_intent, self.update_source = 'engine', resumed['source']
+ self.resume_pages = resumed.get('pages', False)
+
+ def _clients_connected(self):
+ """A FreeVideo page reconnected to the restarted server."""
+ now = time.monotonic()
+ if now - self.clients_polled < 1:
+ return False
+ self.clients_polled = now
+ from .comfy_launcher_runtime import get_json
+ try:
+ return get_json(self.controller.state['url'].split('/?')[0] + '/freevideo/updates', timeout=1).get('clients', 0) > 0
+ except (OSError, ValueError, KeyError, AttributeError):
+ return False
+
+ def update_phase(self):
+ row = self.updater.state if self.updater else {}
+ if self.update_restarting:
+ return 'restarting'
+ if self.engine_updating:
+ return 'engine'
+ if self.update_waiting:
+ return 'waiting'
+ if row.get('status') == 'downloading':
+ return 'downloading'
+ if self.update_intent and row.get('status') == 'checking':
+ return 'checking'
+ if self.selected and self.page == 'progress' and self.controller.state.get('status') == 'review':
+ return 'review'
+ return ''
+
+ def source_stamp(self, source):
+ """(version, built_at) of an engine source; a source checkout has neither."""
+ if not source:
+ return '', 0
+ if self.installed_versions is None:
+ self.installed_versions = {}
+ if str(source) not in self.installed_versions:
+ package = Path(source) / 'freevideo_engine'
+ try:
+ identity = json.loads((package / 'build-identity.json').read_text(encoding='utf-8'))
+ stamp = str(identity['version']), int(identity['built_at'])
+ except (OSError, ValueError, KeyError, TypeError):
+ try:
+ stamp = (package / 'build-version.txt').read_text(encoding='utf-8').strip(), 0
+ except OSError:
+ stamp = Path(source).name.split('-')[0], 0
+ self.installed_versions[str(source)] = stamp
+ return self.installed_versions[str(source)]
+
+ def installed_version(self):
+ return self.source_stamp((self.selected or {}).get('source'))[0]
+
+ def update_view(self):
+ row = dict(self.updater.state) if self.updater else dict(status='development')
+ # Only display fields from the update manifest, never access tokens.
+ view = {k: row[k] for k in ('status', 'error', 'progress', 'candidate') if k in row}
+ key = self.update_key()
+ view.update(engine=self.engine_update_pending(), current=__version__,
+ installed=self.installed_version(), phase=self.update_phase(), key=key,
+ manual=bool(self.updater and self.updater.current.get('packaging') == 'onedir'))
+ due = ((view.get('candidate') and row['status'] in ('available', 'ready', 'error'))
+ or (view['engine'] and self.page == 'launcher'))
+ view['remind'] = bool(key and due and self.update_snoozed.get(key, 0) <= time.monotonic()
+ and not self.update_intent and not view['phase'])
+ return view
+
+ def _write_bridge_status(self, force=False):
+ if not self.bridge:
+ return
+ view = self.update_view()
+ candidate = view.get('candidate') or {}
+ value = dict(version=__version__, phase=view['phase'], status=view.get('status'),
+ progress=view.get('progress'), manual=view['manual'],
+ candidate=dict(version=candidate['version']) if candidate.get('version') else None,
+ engine=dict(pending=view['engine'], version=__version__, installed=view['installed']),
+ error=str(view.get('error') or '')[:500])
+ now = time.monotonic()
+ last, previous = self.bridge_written
+ if not force and value == previous and now - last < 5:
+ return
+ from .launcher_bridge import write_status
+ try:
+ write_status(self.bridge, value)
+ self.bridge_written = (now, value)
+ except OSError:
+ pass
+
def close(self):
self.importer.cancelled.set()
if getattr(self, '_closed', False):
@@ -378,6 +649,8 @@ class Session:
if self.updater:
self.updater.cancelled.set()
self.controller.close()
+ from .launcher_bridge import remove
+ remove(self.bridge)
self._closed = True
def tick(self):
@@ -403,6 +676,16 @@ class Session:
row = self.controller.state
busy = self.controller.busy
+ if self.engine_autoinstall and not busy and row.get('action') == 'inspect' and row.get('status') != 'running':
+ self.engine_autoinstall = False
+ selection = row.get('selection') or {}
+ if (row.get('status') == 'review' and selection.get('ready') and not row.get('errors')
+ and (row.get('host') or {}).get('ready')):
+ # Nothing new to download or approve: deploy, then restart ComfyUI.
+ self.controller.run('install', True)
+ row, busy = self.controller.state, self.controller.busy
+ if self.engine_updating and not busy and not self.engine_autoinstall:
+ self.engine_updating = False
groups = row.get('task', {}).get('model_groups') or row.get('model_groups') or row.get('plan', {}).get('model_groups')
if groups:
self.model_groups = groups
@@ -428,12 +711,22 @@ class Session:
'request': {'exception': row.get('exception', []), 'phase': self.controller.section or 'installation'},
'log_tails': {'installation': row.get('error', '')}})
if not busy and not self.closing and row.get('status') == 'open' and not self.browser_attempted:
- self.open_browser()
+ # After an update, open pages reload themselves; open a new tab
+ # only if none of them returns.
+ if self.reload_expected and self.browser_wait is None:
+ self.browser_wait = time.monotonic() + 10
+ if self.reload_expected and self._clients_connected():
+ self.browser_attempted = True
+ self.reload_expected = False
+ elif not self.reload_expected or time.monotonic() >= self.browser_wait:
+ self.reload_expected = False
+ self.open_browser()
sources = self.controller.terminal_sources()
if sources:
selected = next((p for _, p in sources if p == self.log_source), sources[-1][1])
self.tail.select(selected)
self.tail.read(final=not self.controller.terminal_running(selected))
+ self._tick_updates()
def snapshot(self):
from .failure_details import launcher_failure, redacted_launcher_error
@@ -484,7 +777,7 @@ class Session:
estimate.append(self.t('Download ', '需下载 ')+'%.1f GiB' % (plan['model_download_bytes']/2**30))
if row.get('disks'):
estimate.append(self.t('Peak disk ~', '磁盘峰值约 ')+'%.1f GiB' % (sum(d.get('needed_bytes', 0) for d in row['disks'])/2**30))
- update = dict(self.updater.state) if self.updater else dict(status='development')
+ update = self.update_view()
probe = self.probe.snapshot()
speeds = []
for group, entries in probe.get('sources', {}).items():
@@ -497,10 +790,6 @@ class Session:
route = self.t('direct', '直连') if entry.get('route') == 'direct' else self.t('current connection', '当前连接')
speeds.append(dict(source=source_name(entry['id'], zh)+' · '+route, group=self.t(*names.get(group, (group, group))),
ok=entry.get('ok', False), rate=speed_text(entry, self.language.startswith('zh'))))
- # Only display fields from the update manifest, never access tokens.
- update = {k: update[k] for k in ('status', 'error', 'progress', 'candidate') if k in update}
- update['remind'] = bool(update.get('candidate') and not self.update_snoozed
- and update['status'] in ('available', 'ready', 'error'))
return dict(version=__version__, zh=self.language.startswith('zh'), form=dict(self.form),
page=self.page, status=row.get('status', 'idle'), busy=self.controller.busy or self.importer.busy,
offline=dict(progress_view(self.importer.state, zh), runtime=bool(self.form['offline_runtime']), models=len(self.form['offline_models'])),
diff --git a/freevideo_engine/launcher_update.py b/freevideo_engine/launcher_update.py
index 735ab4f..c8c3251 100644
--- a/freevideo_engine/launcher_update.py
+++ b/freevideo_engine/launcher_update.py
@@ -237,6 +237,47 @@ def forward_approved(current, root):
return False # A missing/corrupt cached update leaves the original app usable.
+def handoff(candidate, root, source, *, pages=False):
+ """Record which explicit action restarted into a newer launcher, and
+ whether FreeVideo pages may be waiting to reconnect."""
+ save(Path(root) / 'updates' / 'handoff.json',
+ dict(revision=manifest(candidate)['revision'], source=source, pages=bool(pages), at=time.time()))
+
+
+def resumed_update(current, root, *, seconds=600):
+ """Return the explicit update that just started this build, at most once.
+
+ The approved receipt must name this exact build and be recent. Launchers
+ without a handoff record (older releases) still count as an update. The
+ original shortcut later forwards here again, so a marker prevents a second
+ automatic engine update for the same build.
+ """
+ updates = Path(root) / 'updates'
+ try:
+ receipt = updates / 'active.json'
+ value = json.loads(receipt.read_text(encoding='utf-8'))
+ candidate = manifest(value.get('candidate'))
+ age = time.time() - receipt.stat().st_mtime
+ marker = updates / 'resumed.json'
+ if marker.is_file() and json.loads(marker.read_text(encoding='utf-8')).get('revision') == current['revision']:
+ return None
+ except (OSError, ValueError, TypeError, AttributeError):
+ return None
+ if (value.get('approved') is not True or candidate['revision'] != current['revision']
+ or candidate['built_at'] != current['built_at'] or not -60 <= age <= seconds):
+ return None
+ result = dict(source='launcher', pages=False)
+ try:
+ record = json.loads((updates / 'handoff.json').read_text(encoding='utf-8'))
+ if record.get('revision') == current['revision'] and -60 <= time.time() - record.get('at', 0) <= seconds:
+ source = record.get('source') if record.get('source') in ('launcher', 'browser') else 'launcher'
+ result = dict(source=source, pages=record.get('pages') is True or source == 'browser')
+ except (OSError, ValueError, TypeError, AttributeError):
+ pass
+ save(updates / 'resumed.json', dict(revision=current['revision'], at=time.time()))
+ return result
+
+
class UpdateClient:
def __init__(self, current, root, token=None):
# Python 3.9 on Windows can leave a nonexistent relative path relative
@@ -261,7 +302,8 @@ class UpdateClient:
def busy(self):
return self.thread is not None and self.thread.is_alive()
- def run(self, operation, candidate=None):
+ def run(self, operation, candidate=None, *, background=False):
+ """A background check keeps the shown state and ignores offline failures."""
if self.busy:
return
if operation not in ('check', 'download'):
@@ -269,7 +311,9 @@ class UpdateClient:
if operation == 'download' and self.current.get('packaging') == 'onedir':
raise ValueError('Download and extract the updated folder ZIP from the release page')
self.cancelled.clear()
- self.state = dict(status='checking' if operation == 'check' else 'downloading', candidate=candidate)
+ quiet = background and operation == 'check'
+ if not quiet:
+ self.state = dict(status='checking' if operation == 'check' else 'downloading', candidate=candidate)
def work():
try:
if operation == 'check':
@@ -284,6 +328,8 @@ class UpdateClient:
download(candidate, self.root, self.token, progress=progress, cancel=self.cancelled)
self.state = dict(status='ready', candidate=candidate)
except Exception as error:
+ if quiet:
+ return # The next periodic check retries without a reminder.
message = Redactor([(self.token, '<REDACTED>')] if self.token else []).text(str(error))
if isinstance(error, urllib.error.HTTPError) and error.code in (401, 403, 404):
message = 'GitHub update access unavailable. A private repository needs a GitHub token with read access; also check API rate limits.'
diff --git a/freevideo_engine/modern_launcher.py b/freevideo_engine/modern_launcher.py
index 6a9241e..40d35b8 100644
--- a/freevideo_engine/modern_launcher.py
+++ b/freevideo_engine/modern_launcher.py
@@ -58,6 +58,7 @@ def create_ui(session, *, show=True):
changed = Signal()
def __init__(self):
super().__init__(engine)
+ self.alerted = None
self.value = session.snapshot()
self.timer = QTimer(self)
self.timer.setInterval(250)
@@ -83,6 +84,14 @@ def create_ui(session, *, show=True):
if value != self.value:
self.value = value
self.changed.emit()
+ update = value.get('update') or {}
+ if update.get('remind') and update.get('key') != self.alerted and engine.rootObjects():
+ # Flash the taskbar button once per new reminder when the
+ # launcher sits behind the browser.
+ self.alerted = update['key']
+ window = engine.rootObjects()[0]
+ if not window.isActive():
+ window.alert(0)
if session.closing:
self.timer.stop()
app.quit()
diff --git a/web/updates.css b/web/updates.css
index a3e6644..4f68ae8 100644
--- a/web/updates.css
+++ b/web/updates.css
@@ -1,6 +1,12 @@
-.fv-update-notice{box-sizing:border-box;display:flex;align-items:center;gap:10px;flex-wrap:wrap;padding:10px 12px;border:1px solid var(--fv-border);border-radius:var(--fv-r-sm,8px);background:var(--fv-card);color:var(--fv-ink);font:12px/1.5 var(--fv-font);animation:fv-panel-enter .25s ease}
-.fv-update-notice[hidden]{display:none!important}.fv-update-notice>span{flex:1;min-width:160px;overflow-wrap:anywhere}
-.fv-update-notice a,.fv-update-notice button,.fv-studio .fv-update-notice a,.fv-studio .fv-update-notice button{min-height:30px;padding:4px 8px;border:0;border-radius:6px;font:inherit;background:transparent;white-space:nowrap;cursor:pointer;text-decoration:none;color:var(--fv-accent)}
+.fv-update-notice{box-sizing:border-box;display:flex;align-items:center;gap:10px;flex-wrap:wrap;padding:10px 12px;border:1px solid var(--fv-accent);border-radius:var(--fv-r-sm,8px);background:var(--fv-card);box-shadow:inset 3px 0 0 var(--fv-accent);color:var(--fv-ink);font:12px/1.5 var(--fv-font);animation:fv-panel-enter .25s ease}
+.fv-update-notice[hidden]{display:none!important}.fv-update-notice>span{flex:1;min-width:160px;overflow-wrap:anywhere;font-weight:600}
+.fv-update-notice a,.fv-update-notice button,.fv-studio .fv-update-notice a,.fv-studio .fv-update-notice button{min-height:30px;padding:4px 10px;border:0;border-radius:6px;font:inherit;background:transparent;white-space:nowrap;cursor:pointer;text-decoration:none;color:var(--fv-accent)}
.fv-update-notice button,.fv-studio .fv-update-notice button{color:var(--fv-muted)}.fv-update-notice a:hover,.fv-update-notice button:hover{background:var(--fv-hover)}
+.fv-update-notice .fv-update-apply,.fv-studio .fv-update-notice .fv-update-apply{background:var(--fv-accent);color:var(--fv-bg,#0b0b0d);font-weight:600}
+.fv-update-notice .fv-update-apply:hover,.fv-studio .fv-update-notice .fv-update-apply:hover{background:var(--fv-accent-hover)}
+.fv-update-notice button[hidden],.fv-update-notice a[hidden]{display:none!important}
+.fv-update-notice button:disabled{opacity:.5;cursor:default}
+.fv-update-working>span::before{content:'';display:inline-block;width:10px;height:10px;margin-right:8px;border:2px solid var(--fv-accent);border-right-color:transparent;border-radius:50%;vertical-align:-1px;animation:fv-update-spin .9s linear infinite}
+@keyframes fv-update-spin{to{transform:rotate(360deg)}}
.fv-update-notice :focus-visible{outline:2px solid var(--fv-accent);outline-offset:2px}.fv-view-navigation>.fv-update-notice{margin-top:8px;max-width:560px}
-@media(prefers-reduced-motion:reduce){.fv-update-notice{animation:none}}
+@media(prefers-reduced-motion:reduce){.fv-update-notice{animation:none}.fv-update-working>span::before{animation:none}}
diff --git a/web/updates.js b/web/updates.js
index d607d57..ead2a86 100644
--- a/web/updates.js
+++ b/web/updates.js
@@ -3,24 +3,74 @@ import { api } from '../../scripts/api.js';
const releasePage = 'https://github.com/FlashML-org/FreeVideo/releases/tag/windows-preview';
const storageKey = 'freevideo.dismissed-update';
const listeners = new Set();
-let candidate, dismissed, started = false, pending = false, lastCheck = -Infinity;
+// Launcher phases during which the server may disappear and come back updated.
+const working = new Set(['checking', 'downloading', 'waiting', 'restarting', 'engine']);
+let value = null, dismissed, started = false, pending = false, lastCheck = -Infinity, timer = null;
+let loadedVersion, updating = false, offline = false, failure = '';
try { dismissed = sessionStorage.getItem(storageKey); } catch { /* Session memory still works. */ }
-const identity = value => value ? `${value.revision}:${value.built_at}` : '';
+// The launcher passes its language in the first address, which ComfyUI later
+// rewrites; keep it when reloading into an updated engine.
+const languageHint = (() => { try { return new URLSearchParams(location.search).get('freevideo_lang'); } catch { return null; } })();
+const identity = candidate => candidate ? String(candidate.version || '') : '';
const publish = () => { for (const render of listeners) render(); };
+const later = ms => { clearTimeout(timer); timer = setTimeout(checkUpdates, ms); };
export async function checkUpdates() {
- if (pending || Date.now() - lastCheck < 1500 || document.hidden) return;
+ if (pending || Date.now() - lastCheck < 1500 || (document.hidden && !updating)) return;
pending = true; lastCheck = Date.now();
try {
- const response = await api.fetchApi('/freevideo/updates', {cache: 'no-store', signal: AbortSignal.timeout(10000)});
- if (!response.ok) return;
- const value = await response.json();
- candidate = value.available || null;
+ const response = await api.fetchApi('/freevideo/updates?client=1', {cache: 'no-store', signal: AbortSignal.timeout(10000)});
+ if (!response.ok) throw new Error(response.statusText);
+ const next = await response.json();
+ const version = next.current_version ?? null;
+ if (loadedVersion === undefined) loadedVersion = version;
+ else if (version !== loadedVersion) {
+ // The server restarted with another engine; load its matching
+ // interface. ComfyUI keeps the workflow, including the prompt.
+ const url = new URL(location.href);
+ if (languageHint && !url.searchParams.has('freevideo_lang')) {
+ url.searchParams.set('freevideo_lang', languageHint);
+ location.replace(url.href);
+ } else location.reload();
+ return;
+ }
+ value = next; offline = false;
+ const phase = next.launcher?.phase || '';
+ if (working.has(phase)) updating = true;
+ else if (updating && phase !== 'restarting') updating = false;
publish();
// The server returns immediately while its initial network check runs.
- if (value.status === 'checking') setTimeout(checkUpdates, 2000);
- } catch { /* Offline checks do not affect generation; the next poll retries. */ }
- finally { pending = false; }
+ if (next.status === 'checking' || updating) later(2000);
+ } catch {
+ // Offline checks do not affect generation. During an update the
+ // server restarts; keep asking until the updated one answers.
+ offline = true;
+ if (updating) { publish(); later(2000); }
+ } finally { pending = false; }
+}
+
+export async function applyUpdate() {
+ failure = '';
+ try {
+ const response = await api.fetchApi('/freevideo/updates/apply', {method: 'POST', cache: 'no-store', signal: AbortSignal.timeout(10000)});
+ if (!response.ok) throw new Error(response.statusText);
+ updating = true;
+ } catch {
+ failure = 'launcher';
+ }
+ publish();
+ lastCheck = -Infinity;
+ later(800);
+}
+
+export async function cancelUpdate() {
+ try {
+ const response = await api.fetchApi('/freevideo/updates/cancel', {method: 'POST', cache: 'no-store', signal: AbortSignal.timeout(10000)});
+ if (response.ok) updating = false;
+ } catch { /* The launcher keeps its state; the next poll shows it. */ }
+ publish();
+ lastCheck = -Infinity;
+ later(800);
}
export function startUpdateChecks() {
@@ -31,6 +81,8 @@ export function startUpdateChecks() {
void checkUpdates();
setInterval(checkUpdates, 60000);
document.addEventListener('visibilitychange', () => { if (!document.hidden) void checkUpdates(); });
+ // A reconnect after a restart answers at once instead of at the next poll.
+ try { api.addEventListener('reconnected', () => { lastCheck = -Infinity; void checkUpdates(); }); } catch { /* Polling still works. */ }
}
export function createUpdateNotice(cn) {
@@ -38,21 +90,55 @@ export function createUpdateNotice(cn) {
const element = document.createElement('aside'); element.className = 'fv-update-notice';
element.hidden = true; element.setAttribute('role', 'status');
const label = document.createElement('span');
+ const apply = document.createElement('button'); apply.type = 'button'; apply.className = 'fv-update-apply';
+ apply.textContent = t('Update now', '立即更新');
+ apply.title = t('FreeVideo restarts once; running videos finish first.', 'FreeVideo 会重启一次,正在生成的视频会先完成。');
+ apply.onclick = () => { apply.disabled = true; void applyUpdate().finally(() => { apply.disabled = false; }); };
const link = document.createElement('a'); link.href = releasePage;
link.target = '_blank'; link.rel = 'noopener noreferrer';
link.textContent = t('Download update', '下载新版');
link.title = t('After your task finishes, open the new FreeVideo.exe to update.', '当前任务完成后,打开新版 FreeVideo.exe 更新。');
- const later = document.createElement('button'); later.type = 'button';
- later.textContent = t('Later', '稍后');
- later.onclick = () => {
- dismissed = identity(candidate);
+ const dismiss = document.createElement('button'); dismiss.type = 'button';
+ dismiss.textContent = t('Later', '稍后');
+ dismiss.onclick = () => {
+ dismissed = identity(value?.available);
+ failure = '';
try { sessionStorage.setItem(storageKey, dismissed); } catch {}
publish();
};
- element.append(label, link, later);
+ const stop = document.createElement('button'); stop.type = 'button';
+ stop.textContent = t('Cancel update', '取消更新');
+ stop.onclick = () => { stop.disabled = true; void cancelUpdate().finally(() => { stop.disabled = false; }); };
+ element.append(label, apply, link, dismiss, stop);
const render = () => {
- element.hidden = !candidate || dismissed === identity(candidate);
- label.textContent = candidate ? t('FreeVideo update available', 'FreeVideo 有新版本') + ' · ' + candidate.version : '';
+ const launcher = value?.launcher, phase = launcher?.phase || '', candidate = value?.available;
+ const progress = launcher?.progress, percent = progress?.total ? ' ' + Math.floor(100 * progress.done / progress.total) + '%' : '';
+ const busy = updating && (working.has(phase) || offline);
+ let text = '', actions = false;
+ if (busy) {
+ text = offline || phase === 'restarting' || phase === 'engine'
+ ? t('Restarting FreeVideo to finish the update… this page refreshes by itself.', '正在重启 FreeVideo 完成更新…页面会自动刷新。')
+ : phase === 'downloading' ? t('Downloading the update', '正在下载更新') + percent
+ : phase === 'waiting' ? t('The update installs as soon as the current video finishes.', '当前视频生成完成后会自动更新。')
+ : t('Checking for updates…', '正在检查更新…');
+ } else if (phase === 'review') {
+ text = t('Confirm the update in the FreeVideo launcher.', '请在 FreeVideo 启动器中确认本次更新。');
+ } else if (failure) {
+ text = t('Open the FreeVideo launcher to update, or download the new version.', '请在 FreeVideo 启动器中更新,或下载新版。');
+ actions = true;
+ } else if (candidate && dismissed !== identity(candidate)) {
+ text = t('FreeVideo update available', 'FreeVideo 有新版本') + ' · ' + candidate.version;
+ if (launcher?.status === 'error' && launcher.error) text += ' · ' + t('last attempt failed', '上次更新未完成');
+ actions = true;
+ }
+ element.hidden = !text;
+ element.classList.toggle('fv-update-working', busy);
+ label.textContent = text;
+ const direct = !!launcher && !launcher.manual && !failure;
+ apply.hidden = !actions || !direct;
+ link.hidden = !actions || direct;
+ dismiss.hidden = !actions;
+ stop.hidden = !(busy && phase === 'waiting' && !offline);
};
listeners.add(render); render();
return {element, dispose: () => listeners.delete(render)};