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.

Mac: update the app in place from the downloaded DMG

Bowen Xue395318676438
diff --git a/freevideo_engine/launcher_session.py b/freevideo_engine/launcher_session.py
index 49556ca..a83a49f 100644
--- a/freevideo_engine/launcher_session.py
+++ b/freevideo_engine/launcher_session.py
@@ -29,6 +29,7 @@ from .runtime_alias import checked_real_path
# Background launcher release checks while the window stays open.
CHECK_SECONDS = 30 * 60
+SETTLE_SECONDS = 60
# "Later" hides one reminder for this long; a newer release reminds at once.
SNOOZE_SECONDS = 4 * 3600
QUEUE_POLL_SECONDS = 3
@@ -73,6 +74,7 @@ class Session:
bridge_pending = False
bridge_written = (0., None)
update_checked = 0.
+ settle_at = None
page = 'comfy'
selected = installed_versions = engine_identity = bundled_identity = None
release_details = None
@@ -1188,10 +1190,10 @@ class Session:
"""A package the user installs themselves (macOS app, Windows folder): the release
page opens and the reminder closes. True when this update was handled that way."""
row = self.updater.state if self.updater else {}
+ from .launcher_update import manual_install, release_page
if not (row.get('candidate') and row.get('status') != 'checking'
- and self.updater.current.get('packaging') in ('onedir', 'app')):
+ and manual_install(self.updater.current, self.updater)):
return False
- from .launcher_update import release_page
from .windows_ux import open_browser
self.pending_update = None
self.update_intent = None
@@ -1367,6 +1369,15 @@ class Session:
updater.run('check', background=True)
if self.resume_until:
self._check_resumed(now)
+ if updater and updater.current.get('packaging') == 'app' and sys.platform == 'darwin':
+ # A new app has to run for a while before the old one beside it is deleted.
+ self.settle_at = self.settle_at or now + SETTLE_SECONDS
+ if now >= self.settle_at:
+ self.settle_at = float('inf')
+ from . import mac_app_update
+ app = mac_app_update.current_app()
+ if app is not None:
+ mac_app_update.settle(app)
if self.bridge and now - self.bridge_polled >= 1:
self.bridge_polled = now
from .launcher_bridge import take_request
@@ -1502,10 +1513,13 @@ class Session:
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}
- from .launcher_update import error_text, release_page
+ from .launcher_update import error_text, manual_install, release_page
if row.get('error_code'):
view['error'] = error_text(row, self.language.startswith('zh'))
view['release_page'] = release_page(self.updater.current) if self.updater else ''
+ if self.updater and self.updater.install_failed and view.get('candidate'):
+ # The new app did not go in and the old one is back: the reminder says so.
+ view['status'], view['error'] = 'error', 'The update could not be installed.'
key = self.update_key()
view.update(engine=self.engine_update_pending(), current=__version__,
current_release=public_details(self.updater.current) if self.updater else self.release_details,
@@ -1513,7 +1527,7 @@ class Session:
installed=self.installed_version(), phase=self.update_phase(), key=key,
channel=self.updater.current.get('channel') if self.updater else None,
track=self.updater.current.get('track', 'stable') if self.updater else 'stable',
- manual=bool(self.updater and self.updater.current.get('packaging') in ('onedir', 'app')),
+ manual=bool(self.updater and manual_install(self.updater.current, self.updater)),
check_requested=self.pending_check is not None or row.get('status') == 'checking',
check_text=self.t(*ACTION_COPY['checking_update']))
# Versions between the one in use and the update, so skipped notes are not lost.
diff --git a/freevideo_engine/launcher_update.py b/freevideo_engine/launcher_update.py
index 8f684d4..9c8c8bc 100644
--- a/freevideo_engine/launcher_update.py
+++ b/freevideo_engine/launcher_update.py
@@ -57,6 +57,7 @@ API = 'https://api.github.com/repos/' + REPOSITORY
WEB = 'https://github.com/' + REPOSITORY
RELEASE_PAGE = WEB + '/releases/latest'
MAX_EXE_BYTES = 512 * 2**20
+MAX_DMG_BYTES = 2**30
MAC_CHANNEL = 'macos-preview'
# Linux has no release before combined releases, so no platform tag to fall back on.
LINUX_CHANNEL = 'linux-preview'
@@ -167,6 +168,16 @@ def build_track(value):
return value.get('track', 'stable')
+def manual_install(current, client=None):
+ """Whether the user installs the update themselves from the release page."""
+ if current.get('packaging') == 'app':
+ if client is not None and client.install_failed:
+ return True
+ from . import mac_app_update
+ return not mac_app_update.replaceable()
+ return current.get('packaging') == 'onedir'
+
+
def release_page(current):
if build_track(current) == 'nightly':
return 'https://github.com/' + REPOSITORY + '/releases/tag/' + NIGHTLY_TAG
@@ -220,7 +231,7 @@ def manifest(value):
result = build_identity(value)
asset = value.get('asset', {})
if (not isinstance(asset, dict) or type(asset.get('id')) is not int or asset['id'] <= 0
- or type(asset.get('bytes')) is not int or not 2 <= asset['bytes'] <= MAX_EXE_BYTES
+ or type(asset.get('bytes')) is not int or not 2 <= asset['bytes'] <= (MAX_DMG_BYTES if result['channel'] == MAC_CHANNEL else MAX_EXE_BYTES)
or not re.fullmatch(r'[0-9a-f]{64}', str(asset.get('sha256', '')))):
raise ValueError('Invalid launcher update asset')
result['asset'] = {k: asset[k] for k in ('id', 'bytes', 'sha256')}
@@ -672,11 +683,19 @@ def launch_download(candidate, root, *, token='', popen=None):
overlay = source_update.prepared(candidate, root)
if overlay is not None:
return source_update.launch(candidate, root, overlay, token=token, popen=popen)
- if build_target(candidate) == 'macos-arm64':
- raise ValueError('Mac update activation is not available in this development build')
path = executable_path(root, candidate)
if not verified(path, candidate['asset']):
raise DownloadedLauncherUnavailable('Downloaded launcher is missing or changed; download again')
+ if build_target(candidate) == 'macos-arm64':
+ from . import mac_app_update
+ staged = Path(path.parent) / 'staged.txt'
+ try:
+ location = Path(staged.read_text(encoding='utf-8').strip())
+ process = mac_app_update.activate(location, mac_app_update.current_app(), path.parent, popen=popen or subprocess.Popen)
+ except (OSError, ValueError, AttributeError):
+ raise DownloadedLauncherUnavailable('The prepared app is missing; download again')
+ save(Path(root) / 'updates' / 'active.json', dict(approved=True, candidate=candidate))
+ return process
from .linux_bundle import child_environment
env = dict(child_environment(), FREEVIDEO_LAUNCHER_HOME=plain(resolved(root)))
if token:
@@ -778,6 +797,16 @@ class UpdateClient:
self.cancelled = threading.Event()
self.retry = None
self.failures = 0
+ # The swap of an earlier run put the old app back: say so once, and
+ # leave the release page as the way to update this time.
+ self.install_failed = False
+ if self.current.get('packaging') == 'app':
+ marker = io_path(self.root) / 'updates' / 'mac-update-failed.json'
+ try:
+ self.install_failed = marker.is_file()
+ marker.unlink(missing_ok=True)
+ except OSError:
+ pass
@property
def busy(self):
@@ -806,7 +835,7 @@ class UpdateClient:
return
if operation not in ('check', 'download'):
raise ValueError('Unknown update operation')
- if operation == 'download' and self.current.get('packaging') in ('onedir', 'app'):
+ if operation == 'download' and manual_install(self.current):
kind = 'application' if self.current.get('packaging') == 'app' else 'folder'
raise ValueError('Download and extract the updated %s ZIP from the release page' % kind)
self.cancelled.clear()
@@ -844,9 +873,19 @@ class UpdateClient:
found = check(self.current, self.token, language=self.language)
if found and newer(found, candidate):
selected = found
+ def prepare_app(dmg):
+ from . import mac_app_update
+ app = mac_app_update.current_app()
+ if app is None:
+ raise ValueError('Not running from an app bundle')
+ staged = mac_app_update.prepare(dmg, app, dmg.parent)
+ (dmg.parent / 'staged.txt').write_text(str(staged), encoding='utf-8')
def progress(value):
self.state = dict(status='downloading', candidate=selected, progress=value)
- download(selected, self.root, self.token, progress=progress, cancel=self.cancelled, language=self.language)
+ target = download(selected, self.root, self.token, progress=progress, cancel=self.cancelled, language=self.language)
+ # An incremental overlay comes back instead of the DMG; only the DMG is mounted.
+ if self.current.get('packaging') == 'app' and Path(target) == executable_path(self.root, selected):
+ prepare_app(target)
self.state = dict(status='ready', candidate=selected)
self.failures = 0
except Exception as error:
diff --git a/freevideo_engine/launcher_update_ui.py b/freevideo_engine/launcher_update_ui.py
index f08bebf..890f861 100644
--- a/freevideo_engine/launcher_update_ui.py
+++ b/freevideo_engine/launcher_update_ui.py
@@ -3,7 +3,7 @@ import time
import webbrowser
from . import branding
-from .launcher_update import error_text, release_page, launch_download, DownloadedLauncherUnavailable
+from .launcher_update import error_text, manual_install, release_page, launch_download, DownloadedLauncherUnavailable
class UpdateUI:
@@ -68,7 +68,7 @@ class UpdateUI:
self.closed = True
app.close()
elif row['status'] == 'available' or (row['status'] in ('error', 'cancelled') and row.get('candidate')):
- if getattr(self.client, 'current', {}).get('packaging') == 'onedir':
+ if manual_install(getattr(self.client, 'current', {}), self.client):
webbrowser.open(release_page(self.client.current))
else:
self.client.run('download', row['candidate'])
diff --git a/freevideo_engine/mac_app_update.py b/freevideo_engine/mac_app_update.py
new file mode 100644
index 0000000..baf8f79
--- /dev/null
+++ b/freevideo_engine/mac_app_update.py
@@ -0,0 +1,157 @@
+"""Replace the running FreeVideo.app with the one inside a downloaded DMG.
+
+The DMG is checked and copied next to the running app while the old version
+keeps working. Only the final swap waits for the old process to exit, and it
+puts the old app back whenever any step of it fails."""
+import os
+from pathlib import Path
+import plistlib
+import shutil
+import subprocess
+import sys
+import tempfile
+import time
+
+
+MARK = '.FreeVideo-update-'
+BACKUP = '.FreeVideo-backup-'
+MARGIN_BYTES = 256 * 2**20
+HDIUTIL, DITTO, CODESIGN, XATTR = '/usr/bin/hdiutil', '/usr/bin/ditto', '/usr/bin/codesign', '/usr/bin/xattr'
+
+# Plain sh, so the swap does not depend on anything inside the app it replaces.
+SWAP_SCRIPT = r'''#!/bin/sh
+pid="$1"; app="$2"; staged="$3"; backup="$4"; failure="$5"; inject="$6"
+opener="${FREEVIDEO_OPEN:-/usr/bin/open}"
+note() { printf '{"reason": "%s", "at": %s}\n' "$1" "$(date +%s)" > "$failure"; }
+waited=0
+while kill -0 "$pid" 2>/dev/null; do
+ waited=$((waited + 1))
+ if [ "$waited" -gt 600 ]; then note "old app did not exit"; rm -rf "$staged"; exit 1; fi
+ sleep 0.2
+done
+restore() {
+ rm -rf "$app"
+ if [ -d "$backup" ]; then /bin/mv "$backup" "$app"; fi
+ rm -rf "$staged"
+ "$opener" "$app"
+}
+[ "$inject" = "before_backup" ] && { note "injected failure"; rm -rf "$staged"; "$opener" "$app"; exit 1; }
+if ! /bin/mv "$app" "$backup"; then note "could not set the old app aside"; rm -rf "$staged"; "$opener" "$app"; exit 1; fi
+if [ "$inject" = "after_backup" ] || ! /bin/mv "$staged" "$app"; then note "could not put the new app in place"; restore; exit 1; fi
+if [ "$inject" = "after_swap" ] || ! "$opener" "$app"; then
+ note "the new app did not open"; /bin/mv "$app" "$staged" && restore; exit 1
+fi
+# The old app stays until the new launcher has run well; it removes it (settle).
+'''
+
+
+class MacUpdateUnavailable(ValueError):
+ """The app cannot be replaced from here; the release page stays the way to update."""
+
+
+def current_app(executable=None):
+ """The .app bundle the process runs from, or None outside one."""
+ try:
+ path = Path(executable or sys.executable).resolve()
+ except OSError:
+ return None
+ for parent in path.parents:
+ if parent.suffix == '.app' and (parent / 'Contents/MacOS').is_dir():
+ return parent
+ return None
+
+
+def replaceable(app=None):
+ """Whether this app sits where the launcher may swap it for a new one."""
+ app = app or current_app()
+ if app is None or 'AppTranslocation' in str(app) or sys.platform != 'darwin' and not os.environ.get('FREEVIDEO_MAC_UPDATE_TEST'):
+ return False
+ return os.access(app.parent, os.W_OK | os.X_OK) and os.access(app, os.W_OK)
+
+
+def _run(command, run, timeout=1800):
+ return run(command, check=True, capture_output=True, timeout=timeout)
+
+
+def _plist(app):
+ with (app / 'Contents/Info.plist').open('rb') as stream:
+ return plistlib.load(stream)
+
+
+def _size(path):
+ return sum(f.stat().st_size for f in Path(path).rglob('*') if f.is_file() and not f.is_symlink())
+
+
+def clear_stale(app):
+ for entry in app.parent.glob(MARK + '*.app'):
+ shutil.rmtree(entry, ignore_errors=True)
+
+
+def settle(app):
+ """Remove the old versions kept beside a running app; called once it has run well."""
+ for entry in app.parent.glob(BACKUP + '*.app'):
+ shutil.rmtree(entry, ignore_errors=True)
+
+
+def prepare(dmg, app, directory, *, run=subprocess.run):
+ """Copy and check the app inside dmg next to `app`; returns the staged path.
+
+ Nothing here touches the running app. Every failure raises and leaves the
+ old version as it was."""
+ if not replaceable(app):
+ raise MacUpdateUnavailable('This app cannot replace itself where it is installed')
+ clear_stale(app)
+ staged = app.parent / (MARK + '%d-%d.app' % (os.getpid(), int(time.time())))
+ mount = Path(tempfile.mkdtemp(prefix='freevideo-update-mount-'))
+ attached = False
+ try:
+ _run([HDIUTIL, 'attach', '-readonly', '-nobrowse', '-noautoopen', '-mountpoint', str(mount), str(dmg)], run)
+ attached = True
+ apps = sorted(p for p in mount.iterdir() if p.suffix == '.app')
+ if len(apps) != 1 or apps[0].name != app.name:
+ raise ValueError('The downloaded image does not contain %s' % app.name)
+ source = apps[0]
+ free = shutil.disk_usage(app.parent).free
+ if free < _size(source) + MARGIN_BYTES:
+ raise OSError(28, 'Not enough free space next to the app')
+ _run([DITTO, str(source), str(staged)], run)
+ finally:
+ if attached:
+ try:
+ _run([HDIUTIL, 'detach', str(mount)], run, 120)
+ except (subprocess.SubprocessError, OSError):
+ try:
+ _run([HDIUTIL, 'detach', '-force', str(mount)], run, 120)
+ except (subprocess.SubprocessError, OSError):
+ pass
+ shutil.rmtree(mount, ignore_errors=True)
+ try:
+ old, new = _plist(app), _plist(staged)
+ if new.get('CFBundleIdentifier') != old.get('CFBundleIdentifier'):
+ raise ValueError('The downloaded app is a different application')
+ if not (staged / 'Contents/MacOS' / new.get('CFBundleExecutable', '')).is_file():
+ raise ValueError('The downloaded app has no executable')
+ if sys.platform == 'darwin':
+ _run([XATTR, '-dr', 'com.apple.quarantine', str(staged)], run, 120)
+ _run([CODESIGN, '--verify', '--deep', '--strict', str(staged)], run, 300)
+ except BaseException:
+ shutil.rmtree(staged, ignore_errors=True)
+ raise
+ return staged
+
+
+def activate(staged, app, directory, *, popen=subprocess.Popen, inject=''):
+ """Start the swap. It waits for this process to exit, then replaces the app."""
+ staged = Path(staged)
+ if not (staged / 'Contents/Info.plist').is_file():
+ raise FileNotFoundError('The prepared app is missing')
+ directory = Path(directory)
+ script = directory / 'swap-app.sh'
+ script.write_text(SWAP_SCRIPT, encoding='utf-8')
+ script.chmod(0o755)
+ backup = app.parent / (BACKUP + '%d.app' % int(time.time()))
+ failure = directory.parent / 'mac-update-failed.json'
+ failure.unlink(missing_ok=True)
+ with (directory.parent / 'mac-update.log').open('ab') as log:
+ return popen(['/bin/sh', str(script), str(os.getpid()), str(app), str(staged), str(backup), str(failure), inject],
+ stdin=subprocess.DEVNULL, stdout=log, stderr=log, close_fds=True, start_new_session=True)