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.

Launcher: LAN access switch and any local listening address

Bowen Xue73c4f178caeb
diff --git a/freevideo_engine/access_proxy.py b/freevideo_engine/access_proxy.py
index 4f70e42..c382951 100644
--- a/freevideo_engine/access_proxy.py
+++ b/freevideo_engine/access_proxy.py
@@ -1,6 +1,6 @@
"""Token-protected access to a ComfyUI that listens on this computer only.
-`freevideo server --listen ADDRESS` runs this in front of ComfyUI. The access
+The launcher's LAN switch or `freevideo server --listen ADDRESS` runs this in front of ComfyUI. The access
link carries the token once; the page then keeps it in a cookie, and API
clients send it as a bearer token. Everything else gets 401, so ComfyUI is
never reachable from other computers without it, and not at all when this
@@ -27,9 +27,9 @@ DENIED = """<!doctype html><html><head><meta charset="utf-8"><meta name="viewpor
<title>FreeVideo</title></head><body style="margin:0;min-height:100vh;display:grid;place-items:center;background:#10151e;
color:#e7edf7;font:15px/1.6 'Segoe UI','Noto Sans CJK SC','Noto Sans SC',system-ui,sans-serif"><main style="max-width:520px;
padding:28px 32px;border:1px solid #2a3443;border-radius:12px;background:#1a222e"><h1 style="margin:0 0 10px;font-size:19px">
-This FreeVideo server opens from its access link</h1><p style="margin:0 0 18px;color:#a5b3c6">To show the link, run
-<code>freevideo status</code> on the server.</p><h1 style="margin:0 0 10px;font-size:19px">请使用访问链接打开这台 FreeVideo 服务器</h1>
-<p style="margin:0;color:#a5b3c6">在服务器上运行 <code>freevideo status</code> 即可查看链接。</p></main></body></html>"""
+This FreeVideo server opens from its access link</h1><p style="margin:0 0 18px;color:#a5b3c6">Copy the link in the launcher under Settings → Preferences → Local network. On a Linux server, run
+<code>freevideo status</code> to see it.</p><h1 style="margin:0 0 10px;font-size:19px">请使用访问链接打开这台 FreeVideo 服务器</h1>
+<p style="margin:0;color:#a5b3c6">请在启动器的“设置 → 偏好 → 局域网”中复制链接。Linux 服务器上运行 <code>freevideo status</code> 可以看到链接。</p></main></body></html>"""
def matches(value, token):
diff --git a/freevideo_engine/comfy_launcher.py b/freevideo_engine/comfy_launcher.py
index b909347..406ec78 100644
--- a/freevideo_engine/comfy_launcher.py
+++ b/freevideo_engine/comfy_launcher.py
@@ -19,6 +19,9 @@ from .terminal_ui import clean, duration
from .setup_progress import number, progress_text
+FIREWALL_HINT = ('If Windows asks about the firewall the first time, choose Allow.', 'Windows 首次询问防火墙权限时,请选择“允许”。')
+
+
class Launcher:
def __init__(self, window, source=None, controller=None, update_client=None):
import tkinter as tk
@@ -52,6 +55,9 @@ class Launcher:
self.error_text = ''
self.python = tk.StringVar(value=settings.get('python', ''))
self.url = tk.StringVar(value=settings.get('url', 'http://127.0.0.1:8188'))
+ self.lan_access = tk.BooleanVar(value=settings.get('lan_access', False))
+ self.lan_message = tk.StringVar()
+ self.access_link = tk.StringVar()
self.token = tk.StringVar() # Never stored in settings, commands or receipts.
self.separate = tk.BooleanVar(value=settings.get('separate', False))
self.repair, self.accept = tk.BooleanVar(), tk.BooleanVar()
@@ -73,6 +79,7 @@ class Launcher:
self.terminal_operation = None
self.options = None
self.options_inputs = []
+ self.listen_entry = None
self.download_dialog = None
self.download_probes = {}
if self.controller.restore(dict(settings, engine=self.engine.get())):
@@ -92,7 +99,7 @@ class Launcher:
if update_client is not None:
from .launcher_update_ui import UpdateUI
self.updates = UpdateUI(self, update_client, self.update_row)
- for variable in (self.mode, self.destination, self.comfy, self.engine, self.models, self.model_method, self.python, self.url, self.token, self.separate, self.repair):
+ for variable in (self.mode, self.destination, self.comfy, self.engine, self.models, self.model_method, self.python, self.url, self.lan_access, self.token, self.separate, self.repair):
variable.trace_add('write', self.changed)
window.protocol('WM_DELETE_WINDOW', self.close)
window.bind('<Destroy>', self.cancel_timers, add='+')
@@ -128,7 +135,7 @@ class Launcher:
self.queue_save()
def values(self):
- return dict({name: getattr(self, name).get() for name in ('comfy', 'destination', 'engine', 'models', 'python', 'url', 'token', 'separate', 'repair')},
+ return dict({name: getattr(self, name).get() for name in ('comfy', 'destination', 'engine', 'models', 'python', 'url', 'lan_access', 'token', 'separate', 'repair')},
new_comfy=self.mode.get() == 'new', model_dirs=list(self.model_dirs), model_method=self.model_method.get())
def model_download_link(self, component):
@@ -185,6 +192,8 @@ class Launcher:
if self.loading_settings:
return
self.queue_save()
+ if self.launch_selection and _ and _[0] in (str(self.url), str(self.lan_access)):
+ return # Apply a valid listening change after the saved draft settles.
if self.controller.busy:
return
self.controller.selection = None
@@ -229,14 +238,31 @@ class Launcher:
if name in ('engine', 'models', 'python'):
browse = self.button(row, '…', '…', lambda n=name: self.browse(getattr(self, n), n == 'python'))
browse.pack(side='right', padx=(6, 0)); self.options_inputs.append(browse)
+ if name == 'url':
+ self.listen_entry = entry
+ self.label(body, "With 0.0.0.0 or this computer's LAN IP, devices on the same network can open FreeVideo without the access link.",
+ '填 0.0.0.0 或本机的局域网 IP 后,同一网络中的设备不需要访问链接就能打开 FreeVideo。',
+ style='Muted.TLabel', wraplength=580).pack(fill='x')
+ if sys.platform == 'win32':
+ self.label(body, FIREWALL_HINT[0], FIREWALL_HINT[1], style='Muted.TLabel', wraplength=580).pack(fill='x')
for variable, en, zh in (
+ (self.lan_access, 'LAN access', '局域网访问'),
(self.separate, 'Use a separate ComfyUI environment', '使用独立 ComfyUI 环境'),
(self.repair, 'Repair the engine environment', '修复引擎环境')):
- if fixed_environment:
+ if fixed_environment and variable is not self.lan_access:
continue
check = self.ttk.Checkbutton(body, variable=variable, text=self.t(en, zh))
self.labels.append((check, en, zh)); check.pack(anchor='w', pady=(3, 3))
self.options_inputs.append(check)
+ if variable is self.lan_access:
+ self.ttk.Label(body, textvariable=self.lan_message, style='Muted.TLabel').pack(fill='x')
+ self.label(body, 'When on, other devices on the same network can open FreeVideo with the link below. Anyone with the link can use it, so keep it private.',
+ '开启后,同一网络中的其他设备可以用下面的链接打开 FreeVideo。拿到链接的人都能使用,请勿公开。',
+ style='Muted.TLabel', wraplength=580).pack(fill='x')
+ if sys.platform == 'win32':
+ self.label(body, FIREWALL_HINT[0], FIREWALL_HINT[1], style='Muted.TLabel', wraplength=580).pack(fill='x')
+ self.ttk.Entry(body, textvariable=self.access_link, state='readonly').pack(fill='x', pady=(8, 0))
+ self.button(body, 'Copy link', '复制链接', self.copy_access_link).pack(anchor='w')
self.button(body, 'Done', '完成', dialog.destroy).pack(side='bottom', anchor='e', pady=(10, 0))
compatibility = self.button(body, 'Compatibility settings', '兼容性设置', self.compatibility_settings)
compatibility.pack(side='bottom', anchor='w'); self.options_inputs.append(compatibility)
@@ -310,6 +336,7 @@ class Launcher:
from .comfy_launcher_runtime import local_url
try:
selected['url'] = local_url(self.url.get())
+ selected['lan_access'] = self.lan_access.get()
if self.python.get() and io_path(self.python.get()).is_file():
selected['python'] = self.python.get()
except ValueError:
@@ -320,6 +347,12 @@ class Launcher:
written, failures = self.settings_store.write(self.values(), 'zh' if self.zh else 'en',
self.launch_selection, self.saved_setup)
self.settings_path = written[0]
+ if (self.launch_selection and row.get('status') == 'open' and not self.controller.busy
+ and self.launch_selection != self.controller.selection):
+ if self.launch_selection['url'] != self.controller.selection['url']:
+ self.browser_attempted = False
+ self.controller.run('configure_access', dict(url=self.launch_selection['url'],
+ lan_access=self.launch_selection.get('lan_access') is True))
def queue_save(self):
if self.save_timer is not None:
@@ -342,6 +375,7 @@ class Launcher:
getattr(self, name).set(selection.get(key) or '')
self.mode.set('existing')
self.separate.set(selection.get('separate', False))
+ self.lan_access.set(selection.get('lan_access', False))
self.repair.set(False)
finally:
self.loading_settings = False
@@ -477,6 +511,10 @@ class Launcher:
self.window.clipboard_clear()
self.window.clipboard_append(self.browser_address.get())
+ def copy_access_link(self):
+ self.window.clipboard_clear()
+ self.window.clipboard_append(self.access_link.get())
+
def create_shortcut(self):
if self.controller.busy or not self.controller.selection:
return
@@ -528,7 +566,8 @@ class Launcher:
self.model_list.configure(height=max(2, min(6, len(self.model_dirs))))
self.error_text = '\n'.join(str(e) for e in row.get('errors', []))
if row.get('error'):
- self.error_text += ('\n' if self.error_text else '') + str(row['error'])
+ from .launcher_copy import lan_error
+ self.error_text += ('\n' if self.error_text else '') + lan_error(row['error'], self.zh)
if self.browser_error:
self.error_text += ('\n' if self.error_text else '') + self.browser_error
if row.get('shortcut', {}).get('status') == 'failed':
@@ -553,6 +592,12 @@ class Launcher:
self.launch_paths.configure(text='ComfyUI · ' + selected.get('root', '') + '\n' +
self.t('Engine', '引擎') + ' · ' + selected.get('engine', ''))
self.browser_address.set(row.get('url', '') if state == 'open' else '')
+ links = self.controller.access_links
+ self.lan_message.set(self.t('LAN access has stopped. Turn it on again.', '局域网访问已停止,请重新开启。')
+ if row.get('lan_status') == 'stopped' else
+ self.t('No LAN address found. Connect to Wi-Fi or a wired network first.', '未找到局域网地址,请先连接 Wi-Fi 或有线网络。')
+ if row.get('lan_status') == 'no-address' else '')
+ self.access_link.set(links[0] if state == 'open' and links else '')
if state == 'open':
self.browser_controls.pack(fill='x', pady=(16, 0))
else:
@@ -586,6 +631,8 @@ class Launcher:
for widget in (self.entry, self.browse_button, self.add_model_button, self.remove_model_button, *self.mode_buttons, *self.options_inputs):
if widget.winfo_exists():
widget.state(['disabled'] if busy else ['!disabled'])
+ if self.listen_entry is not None and self.listen_entry.winfo_exists():
+ self.listen_entry.state(['readonly'] if self.lan_access.get() else ['!readonly'])
if busy:
self.stop_button.pack(side='right', padx=(0, 10))
else:
@@ -646,6 +693,8 @@ class Launcher:
self.button(dialog, 'Model licenses', '模型许可证', lambda: webbrowser.open('https://huggingface.co/OpenVDN/vdn-minimax-h3-edge/blob/main/LICENSE')).pack(pady=8)
def poll(self):
+ if not self.controller.busy:
+ self.controller.poll_access_proxy()
if self.poll_timer is not None:
self.window.after_cancel(self.poll_timer)
self.poll_timer = None
@@ -665,7 +714,7 @@ class Launcher:
self.window.destroy(); return
selected = row.get('selection')
if (selected and selected.get('ready') and
- (row.get('deployed') or row.get('status') in ('open', 'restart-required')) and
+ (row.get('deployed') or row.get('lan_status') == 'stopped' or row.get('status') in ('open', 'restart-required')) and
row.get('status') != 'running'):
if selected != self.launch_selection:
self.remember_installation(selected)
@@ -677,7 +726,8 @@ class Launcher:
self.open_browser()
# Include busy separately: the task's final state arrives just before
# the thread exits, and the action must become enabled at that boundary.
- key = (row.get('status'), self.controller.busy, row.get('error'), id(row.get('plan')), row.get('overall', {}).get('label'))
+ key = (row.get('status'), self.controller.busy, row.get('error'), id(row.get('plan')),
+ row.get('overall', {}).get('label'), row.get('lan_status'), tuple(self.controller.access_links))
if key != self.last_state:
self.last_state = key
if row.get('action') == 'install':
diff --git a/freevideo_engine/comfy_launcher_api.py b/freevideo_engine/comfy_launcher_api.py
index 5e7296c..b2a6270 100644
--- a/freevideo_engine/comfy_launcher_api.py
+++ b/freevideo_engine/comfy_launcher_api.py
@@ -123,6 +123,8 @@ def register():
root = Path(folder_paths.__file__).resolve().parent
info = dict(protocol=1, source=str(source), engine_root=str(installation_root(source)),
comfy_root=str(root), data_root=str(Path(folder_paths.base_path).resolve()))
+ from comfy.cli_args import args
+ info['listen'] = args.listen
from .comfy_console import install
try:
info['console_log'] = str(install(info['engine_root']))
diff --git a/freevideo_engine/comfy_launcher_runtime.py b/freevideo_engine/comfy_launcher_runtime.py
index 0670f24..03c9418 100644
--- a/freevideo_engine/comfy_launcher_runtime.py
+++ b/freevideo_engine/comfy_launcher_runtime.py
@@ -6,6 +6,7 @@ An existing server is never stopped by this launcher.
"""
import errno
import hashlib
+import ipaddress
import json
import os
from pathlib import Path
@@ -304,18 +305,55 @@ def probe_host(descriptor, python=None):
def local_url(value):
value = value.strip() or 'http://127.0.0.1:8188'
parsed = urlsplit(value if '://' in value else 'http://' + value)
- if (parsed.scheme != 'http' or parsed.hostname not in ('localhost', '127.0.0.1', '::1')
+ host = parsed.hostname
+ try:
+ ip = ipaddress.ip_address(host) if host != 'localhost' else None
+ except ValueError:
+ raise ValueError('Enter localhost or an IP address of this computer, for example http://127.0.0.1:8188.') from None
+ if (parsed.scheme != 'http' or not host or (ip is not None and ip.is_multicast)
or parsed.username or parsed.password or parsed.query or parsed.fragment or parsed.path not in ('', '/')):
- raise ValueError('Use a local ComfyUI address, for example http://127.0.0.1:8188.')
- port = parsed.port or 80
+ raise ValueError('Enter localhost or an IP address of this computer, for example http://127.0.0.1:8188.')
+ port = parsed.port if parsed.port is not None else 80
if not 1 <= port <= 65535:
raise ValueError('Invalid ComfyUI port')
return urlunsplit(('http', parsed.netloc, '', '', ''))
+def loopback_url(value):
+ """The launcher's browser and control requests always use IPv4 loopback."""
+ parsed = urlsplit(value)
+ return urlunsplit(('http', '127.0.0.1:%d' % (parsed.port or 80), parsed.path, parsed.query, parsed.fragment))
+
+
+def loopback_host(hostname):
+ try:
+ return hostname == 'localhost' or ipaddress.ip_address(hostname).is_loopback
+ except ValueError:
+ return False
+
+
+def listen_hosts(hostname):
+ # A specific interface (including IPv6 loopback) does not accept IPv4
+ # loopback. ComfyUI supports a comma-separated list of listening addresses.
+ if hostname in ('localhost', '127.0.0.1', '0.0.0.0'):
+ return (hostname,)
+ return ('127.0.0.1', hostname)
+
+
+def matches_listener(info, url):
+ """An external server must already listen on the requested interfaces."""
+ wanted = urlsplit(url).hostname
+ hosts = set((info.get('listen') or '').split(','))
+ if hosts == {''}:
+ return wanted in ('localhost', '127.0.0.1', '::1')
+ hosts = {'127.0.0.1' if host == 'localhost' else host for host in hosts}
+ wanted = '127.0.0.1' if wanted == 'localhost' else wanted
+ return wanted in hosts or ('::' if ':' in wanted else '0.0.0.0') in hosts
+
+
def get_json(url, timeout=2):
# Proxy settings must never send loopback requests to an external proxy.
- with build_opener(ProxyHandler({})).open(Request(url, headers={'Accept': 'application/json'}), timeout=timeout) as reply:
+ with build_opener(ProxyHandler({})).open(Request(loopback_url(url), headers={'Accept': 'application/json'}), timeout=timeout) as reply:
value = reply.read(2 * 1024 * 1024 + 1)
if len(value) > 2 * 1024 * 1024:
raise ValueError('ComfyUI response is too large')
@@ -323,6 +361,7 @@ def get_json(url, timeout=2):
def server_info(url):
+ url = loopback_url(url)
try:
value = get_json(url + '/freevideo/launcher')
if (isinstance(value, dict) and value.get('protocol') == PROTOCOL
@@ -343,10 +382,12 @@ def server_info(url):
def bind_check(hostname, port):
"""Raise OSError unless a new server could listen on this local address now."""
- hosts = ('127.0.0.1', '::1') if hostname == 'localhost' else (hostname,)
+ hosts = ('127.0.0.1', '::1') if hostname == 'localhost' else listen_hosts(hostname)
+ if hostname in ('0.0.0.0', '::'):
+ hosts = (*hosts, '127.0.0.1' if hostname == '0.0.0.0' else '::1')
for host in hosts:
try:
- with socket.socket(socket.AF_INET6 if host == '::1' else socket.AF_INET, socket.SOCK_STREAM) as check:
+ with socket.socket(socket.AF_INET6 if ':' in host else socket.AF_INET, socket.SOCK_STREAM) as check:
if sys.platform != 'win32':
# Tolerate TIME_WAIT, as ComfyUI does. On Windows this
# option would let two servers share the port.
@@ -371,7 +412,7 @@ def next_free_address(url, count=12):
except OSError:
continue
candidate = address(parsed.hostname, port)
- if server_info(candidate)['status'] == 'offline':
+ if server_info(loopback_url(candidate))['status'] == 'offline':
return candidate
return None
@@ -406,7 +447,7 @@ def launcher_comfy(selected, info):
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)
+ value = get_json(loopback_url(url) + '/queue', timeout=3)
return bool(value.get('queue_running') or value.get('queue_pending'))
except (OSError, ValueError, AttributeError):
return False
@@ -533,9 +574,15 @@ class Controller:
self.state = dict(status='idle')
self.selection = self.setup = None
self.thread = None
+ self._access_poll_thread = None
self.cancelled = threading.Event()
self.server = None
self.server_url = None
+ self.server_address = None
+ self.access_proxy = None
+ self.access_configuration = None
+ self.access_links = []
+ self.access_polled = 0
self._server_lock = threading.RLock()
self._closed = False
self.server_log = None
@@ -609,6 +656,7 @@ class Controller:
def stop_owned_server(self, *, grace=5):
with self._server_lock:
+ self.stop_access_proxy()
if self.server is not None:
if self.server.poll() is None and self.server_url:
try:
@@ -619,6 +667,75 @@ class Controller:
pass
processes.stop(self.server, grace=grace)
self.server = None
+ self.server_address = None
+
+ def stop_access_proxy(self):
+ with self._server_lock:
+ if self.access_proxy is not None:
+ processes.stop(self.access_proxy, grace=3)
+ self.access_proxy = None
+ self.access_configuration = None
+ self.access_links = []
+ self.state = dict(self.state, lan_status='')
+
+ def _access_stopped(self):
+ self.stop_access_proxy()
+ self.selection = dict(self.selection, lan_access=False)
+ self.state = dict(self.state, selection=dict(self.selection), lan_status='stopped')
+
+ def refresh_access_links(self):
+ from .comfy_service import token
+ from .proxy import local_addresses
+ self.access_polled = time.monotonic()
+ secret = token(self.selection['engine'])
+ self.access_links = [address(host, self.selection['lan_port']) + '/?freevideo=launch&token=' + secret
+ for host in local_addresses()]
+ self.state = dict(self.state, lan_status='' if self.access_links else 'no-address')
+
+ def check_access_proxy(self):
+ """Poll child lifetimes and refresh network links without moving ComfyUI."""
+ if self.access_proxy is None:
+ return
+ if self.server is not None and self.server.poll() is not None:
+ self._access_stopped()
+ self.state = dict(self.state, status='ready')
+ elif self.access_proxy.poll() is not None:
+ self._access_stopped()
+ elif time.monotonic() - self.access_polled >= 5:
+ if self.server is None and server_info(self.selection['url'])['status'] == 'offline':
+ self._access_stopped()
+ self.state = dict(self.state, status='ready')
+ else:
+ self.refresh_access_links()
+
+ def poll_access_proxy(self):
+ """Keep network/file probes and bounded process cleanup off the UI thread.
+
+ The check is not a launcher task: the window stays as it is while it
+ runs. A task started meanwhile waits for it in run().
+ """
+ poll = self._access_poll_thread
+ if self._closed or self.busy or (poll is not None and poll.is_alive()):
+ return
+ child = getattr(self, 'comfy_controller', None) or self
+ proxy = child.access_proxy
+ if proxy is None:
+ return
+ exited = ((child.server is not None and child.server.poll() is not None)
+ or proxy.poll() is not None)
+ if not exited and time.monotonic() - child.access_polled < 5:
+ return
+ def work():
+ try:
+ self.check_access_proxy()
+ except Exception:
+ # A failed token/interface read withdraws the unusable link, keeps
+ # the local page and lets the user turn access on again.
+ child._access_stopped()
+ if child is not self:
+ self._sync_access(False)
+ self._access_poll_thread = threading.Thread(target=work, name='freevideo-access-poll', daemon=True)
+ self._access_poll_thread.start()
def terminal_sources(self):
sources = []
@@ -693,6 +810,8 @@ class Controller:
return False
self.selection = dict(descriptor, source=str(source), engine=str(engine), python=plain(python),
url=local_url(record.get('url') or values.get('url', '')), ready=True,
+ lan_access=record.get('lan_access', values.get('lan_access', False)) is True,
+ lan_port=record.get('lan_port'),
separate=record.get('separate', values.get('separate', False)))
from .desktop_runtime import matching_source
self.state = dict(status='ready', engine_update_available=not matching_source(self.source, source),
@@ -734,21 +853,31 @@ class Controller:
raise RuntimeError('The launcher is closing')
if self.busy:
raise ValueError('A launcher task is already running')
- if operation not in ('inspect', 'install', 'connect', 'launch', 'shortcut'):
+ if operation not in ('inspect', 'install', 'connect', 'launch', 'shortcut', 'configure_access'):
raise ValueError('Unknown launcher action')
if operation == 'install' and (self.state.get('status') != 'review' or self.state.get('errors')):
raise ValueError('Inspect and review a valid installation plan first')
+ poll = self._access_poll_thread
+ if poll is not None:
+ # A link check in flight finishes first, so it cannot overwrite this task's state.
+ poll.join()
self.cancelled.clear()
self.state = dict(self.state, status='running', action=operation, error=None, exception=None, task={}, overall={},
model_groups=[] if operation == 'inspect' else self.state.get('model_groups', []))
- if operation in ('connect', 'launch'):
+ if operation in ('connect', 'launch', 'configure_access'):
self.sections = [('open', 1)]
def work():
try:
getattr(self, '_' + operation)(*args)
except Exception as error:
from .diagnostic_resources import exception_details
- self.state = dict(self.state, status='cancelled' if self.cancelled.is_set() else 'failed',
+ opened = self.state.get('status') == 'open'
+ if operation == 'configure_access':
+ # The address change may already have stopped the old server.
+ # A remembered URL alone cannot prove the local page is usable.
+ opened = bool(self.state.get('url')) and server_info(self.state['url'].split('/?')[0])['status'] == 'freevideo'
+ status = 'open' if opened else 'failed'
+ self.state = dict(self.state, status='cancelled' if self.cancelled.is_set() else status,
error=str(error), exception=exception_details(error))
self.thread = threading.Thread(target=work, daemon=True)
self.thread.start()
@@ -826,7 +955,8 @@ class Controller:
ready = not values.get('sampling_caches') or sampling_installed(machine)
except (OSError, ValueError, KeyError):
pass
- self.selection = dict(descriptor, engine=str(engine), source=str(source), url=url, ready=ready, repair_comfy=repair_comfy)
+ self.selection = dict(descriptor, engine=str(engine), source=str(source), url=url, ready=ready,
+ repair_comfy=repair_comfy, lan_access=values.get('lan_access') is True)
self.state = dict(self.state, selection=dict(self.selection), host=host)
if not ready:
extra = values.get('model_dirs', [])
@@ -879,7 +1009,7 @@ class Controller:
if engine_binding.pending(machine, selected['source']):
# Whoever started it (another launcher, the freevideo command), a ComfyUI of this installation
# that is generating keeps its packages: the switch waits for the job.
- if queue_busy(selected['url']):
+ if queue_busy(loopback_url(self.server_address or self.selection['url'])):
raise RuntimeError('ComfyUI is running a job, so the engine update waits. Try again after it finishes; '
'the job is left running.')
self._stop_server_for_setup(selected['url'])
@@ -900,7 +1030,7 @@ class Controller:
self.port_move = urlsplit(selected['url']).port or 80
selected = self.selection = dict(selected, url=url)
self.state = dict(self.state, selection=dict(selected))
- return url, selected
+ return loopback_url(url), selected
def _stop_server_for_setup(self, url):
"""Setup or source rebinding replaces packages that our ComfyUI's resident worker
@@ -910,7 +1040,7 @@ class Controller:
again. A running job is never stopped."""
if not self.owns_server():
return
- if queue_busy(url):
+ if queue_busy(loopback_url(self.server_address or url)):
raise RuntimeError('ComfyUI is running a job. Try again after it finishes; the job is left running.')
self.stop_owned_server()
@@ -925,8 +1055,75 @@ class Controller:
self.ensure_shortcut()
self.state = dict(self.state, status='open' if previous_status == 'open' else 'ready')
+ def _configure_access(self, values, *, connect=False):
+ if not self.selection or not self.selection.get('ready'):
+ raise ValueError('Choose a completed installation first')
+ enabled = values.get('lan_access') is True
+ url = local_url(values.get('url') or self.selection['url'])
+ if enabled and not loopback_host(urlsplit(url).hostname):
+ url = loopback_url(url)
+ changed = url != self.selection['url'] or (self.owns_server() and self.server_address != url)
+ self.selection = dict(self.selection, url=url, lan_access=False)
+ self.state = dict(self.state, selection=dict(self.selection))
+ if changed:
+ self.stop_access_proxy()
+ if changed or connect:
+ self._connect_comfy()
+ if self.state.get('status') not in ('open', 'running'):
+ return
+ if enabled:
+ self._start_access_proxy()
+ else:
+ self.stop_access_proxy()
+ self.state = dict(self.state, status='open', selection=dict(self.selection))
+
@plain_errors
def _connect(self):
+ self._configure_access(dict(lan_access=(self.selection or {}).get('lan_access')), connect=True)
+
+ def _start_access_proxy(self):
+ from .comfy_service import TOKEN, check_proxy, folder, start_proxy, token
+ self.selection = selected = dict(self.selection, lan_access=False)
+ self.state = dict(self.state, selection=dict(selected))
+ if not self.owns_server():
+ info = server_info(selected['url'])
+ hosts = (info.get('listen') or '').split(',')
+ if not hosts or not all(loopback_host(host) for host in hosts):
+ raise ValueError('The ComfyUI already running is open to the network directly. After its jobs finish, restart it on 127.0.0.1, then turn on LAN access.')
+ configuration = tuple(selected[k] for k in ('root', 'engine', 'source', 'python', 'url'))
+ if (self.access_configuration != configuration or
+ self.access_proxy is not None and self.access_proxy.poll() is not None):
+ self.stop_access_proxy()
+ if self.access_proxy is None:
+ port = selected.get('lan_port')
+ if type(port) is not int or not 1 <= port <= 65535:
+ port = (urlsplit(selected['url']).port or 80) + 1
+ candidate = next_free_address(address('0.0.0.0', port - 1)) if port <= 65535 else None
+ if candidate is None:
+ raise ValueError('The ports for LAN access are in use. Choose another ComfyUI port.')
+ port = urlsplit(candidate).port
+ self.selection = selected = dict(selected, lan_port=port)
+ self.state = dict(self.state, selection=dict(selected))
+ secret = token(selected['engine'])
+ from .windows_ux import external_python
+ with self._server_lock, external_python():
+ if self._closed or self.cancelled.is_set():
+ raise RuntimeError('LAN access startup cancelled')
+ self.access_proxy = start_proxy(selected, listen='0.0.0.0', port=port,
+ upstream=loopback_url(selected['url']), token_file=folder(selected['engine']) / TOKEN, tls=None)
+ try:
+ check_proxy(self.access_proxy, scheme='http', port=port, secret=secret)
+ if self._closed or self.cancelled.is_set():
+ raise RuntimeError('LAN access startup cancelled')
+ except Exception:
+ self._access_stopped()
+ raise
+ self.access_configuration = configuration
+ self.selection = dict(selected, lan_access=True)
+ self.state = dict(self.state, selection=dict(self.selection))
+ self.refresh_access_links()
+
+ def _connect_comfy(self):
self.state = {key: value for key, value in self.state.items() if key != 'moved_from'}
if not self.selection or not self.selection['ready']:
raise ValueError('Choose and inspect ComfyUI first')
@@ -937,7 +1134,7 @@ class Controller:
# existing server, as well as the first installation.
self.ensure_shortcut()
shield_engine(selected['engine'])
- url = selected['url']
+ url = loopback_url(selected['url'])
frontend_error = None
managed = bool(selected.get('python') and managed_frontend(selected))
if managed and (managed_python(Path(selected['engine']), Path(selected['root'])) is None
@@ -967,7 +1164,19 @@ class Controller:
node_packages_failed(Path(selected['engine']))
self.stage('open', label='Open ComfyUI')
info = server_info(url)
- if matches_server(info, selected['root'], selected['engine'], selected['source']):
+ matched = matches_server(info, selected['root'], selected['engine'], selected['source'])
+ if matched and not self.owns_server() and not matches_listener(info, selected['url']):
+ self.state = dict(self.state, status='restart-required', url=url,
+ error='The ComfyUI already running does not use this address. After its jobs finish, restart it with this address and connect again.')
+ return
+ if (self.owns_server() and self.server_address is not None
+ and self.server_address != selected['url']):
+ if queue_busy(loopback_url(self.server_address or self.selection['url'])):
+ raise RuntimeError('A generation is running. Change the address after it finishes.')
+ self.stop_owned_server()
+ info = dict(status='offline')
+ matched = False
+ if matched:
self.attach_console(info)
self.stage('open', done=1, label='Ready')
self.state = dict(self.state, status='open', url=url + '/?freevideo=launch')
@@ -986,14 +1195,14 @@ class Controller:
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):
+ if queue_busy(loopback_url(self.server_address or self.selection['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)
+ parsed = urlsplit(selected['url'])
deadline = time.monotonic() + 10
while True:
try:
@@ -1008,8 +1217,10 @@ class Controller:
# A program that is not ComfyUI holds the address.
url, selected = self._move_address(selected)
moves += 1
- parsed = urlsplit(url)
+ parsed = urlsplit(selected['url'])
continue
+ if error.errno == errno.EADDRNOTAVAIL:
+ raise ValueError('This address does not belong to this computer. Enter one of its IP addresses or 0.0.0.0.') from error
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 io_path(selected['python']).is_file():
raise ValueError('ComfyUI Python is missing. Inspect again to prepare a separate environment.')
@@ -1023,12 +1234,15 @@ class Controller:
env.pop('PYTHONPATH', None)
env['PYTHONDONTWRITEBYTECODE'] = '1'
env.update(PYTHONUNBUFFERED='1', PYTHONUTF8='1', PYTHONIOENCODING='utf-8')
+ from .proxy import bypass_local
+ if not loopback_host(parsed.hostname):
+ env = bypass_local(env, parsed.hostname)
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,
+ command = [selected['python'], '-u', '-B', str(Path(selected['root']) / 'main.py'), '--listen', ','.join(listen_hosts(parsed.hostname)),
'--port', str(parsed.port or 80), '--disable-auto-launch']
managed = managed_frontend(selected)
if managed:
@@ -1066,6 +1280,7 @@ class Controller:
stdout=log, stderr=subprocess.STDOUT, start_new_session=True, supervise=True)
self.server = server
self.server_url = url
+ self.server_address = selected['url']
save(directory / 'launch.json', dict(command=command, pid=server.pid, root=selected['root'], url=url, **context))
self.state = dict(self.state, task=dict(progress=dict(label='Starting ComfyUI', detail='Loading nodes and the web interface'), log=plain(directory)))
waiting_since = time.monotonic()
diff --git a/freevideo_engine/comfy_service.py b/freevideo_engine/comfy_service.py
index 9881096..8142841 100644
--- a/freevideo_engine/comfy_service.py
+++ b/freevideo_engine/comfy_service.py
@@ -293,7 +293,10 @@ def start_proxy(record, *, listen, port, upstream, token_file, tls, hop_secret=N
env[ENV] = hop_secret
for name in ('PYTHONPATH', 'PYTHONHOME', 'VIRTUAL_ENV'):
env.pop(name, None)
+ from .proxy import bypass_local
+ env = bypass_local(env, listen)
log = folder(record['engine']) / 'access-proxy.log'
+ log.parent.mkdir(parents=True, exist_ok=True)
with log.open('ab') as output:
return processes.popen(command, cwd=record['engine'], env=env, stdin=subprocess.DEVNULL,
stdout=output, stderr=subprocess.STDOUT, start_new_session=True, supervise=True)
diff --git a/freevideo_engine/failure_details.py b/freevideo_engine/failure_details.py
index 0d93d7c..c9f18d9 100644
--- a/freevideo_engine/failure_details.py
+++ b/freevideo_engine/failure_details.py
@@ -463,8 +463,9 @@ def launcher_failure(value, *, zh=False, other_disk=False, disk_name='', can_rep
detail = causes[-1] if causes else next((line for line in reversed(lines)
if not line.startswith(('File ', 'Traceback', '^', 'All files retained.', 'Rerun the same setup command'))), '')
detail = re.sub(r'^(?:ValueError|RuntimeError|OSError):\s*', '', detail)
+ from .launcher_copy import lan_error
return dict(title='暂时未能完成' if zh else 'Couldn’t complete this step',
- detail=detail, action='', kind='unknown')
+ detail=lan_error(detail, zh), action='', kind='unknown')
def _read(path, limit, *, tail=False):
diff --git a/freevideo_engine/launcher/Main.qml b/freevideo_engine/launcher/Main.qml
index 3a1b1b4..a6ce92a 100644
--- a/freevideo_engine/launcher/Main.qml
+++ b/freevideo_engine/launcher/Main.qml
@@ -836,6 +836,19 @@ ApplicationWindow {
FButton { text: t("Copy address", "复制地址"); onClicked: backend.copy(s.url) }
FButton { text: t("Show terminal", "查看终端"); flat: true; onClicked: terminalOpen = true }
}
+ Repeater {
+ model: (s.access_links || []).slice(0, 1)
+ delegate: ColumnLayout {
+ required property string modelData
+ Layout.fillWidth: true; spacing: 6
+ FText { objectName: "lanAccessLinkLabel"; text: t("LAN access", "局域网访问"); color: theme.muted; font.pixelSize: theme.micro }
+ RowLayout {
+ Layout.fillWidth: true; spacing: 8
+ FField { objectName: "lanAccessLink"; Layout.fillWidth: true; readOnly: true; text: modelData; onTextChanged: cursorPosition = 0; Component.onCompleted: cursorPosition = 0 }
+ FButton { objectName: "copyLanAccessLink"; text: t("Copy link", "复制链接"); onClicked: backend.copy(modelData) }
+ }
+ }
+ }
}
FCard {
Layout.fillWidth: true; padding: 22; spacing: 12
@@ -954,6 +967,8 @@ ApplicationWindow {
ScrollView {
id: settingsScroll
Layout.fillWidth: true; Layout.fillHeight: true; contentWidth: availableWidth; clip: true
+ // The list never scrolls sideways; its hidden bar would take the clicks along the bottom edge.
+ ScrollBar.horizontal.policy: ScrollBar.AlwaysOff
ColumnLayout {
width: settingsScroll.availableWidth; spacing: 18
ColumnLayout {
@@ -1034,6 +1049,22 @@ ApplicationWindow {
}
FButton { text: t("Version & release notes", "版本与更新说明") + " · " + releaseVersion(currentRelease); flat: true; Layout.fillWidth: true; onClicked: releaseNotesOpen = true }
}
+ FGroup {
+ Layout.fillWidth: true; title: t("Local network", "局域网")
+ FSwitch { objectName: "lanAccessSwitch"; Layout.fillWidth: true; text: t("LAN access", "局域网访问"); checked: !!s.form.lan_access; enabled: !s.busy; onToggled: backend.edit("lan_access", checked) }
+ FText { objectName: "lanAccessMessage"; text: s.lan_message || ""; visible: !!text; color: theme.muted; font.pixelSize: theme.micro; Layout.fillWidth: true }
+ FText { objectName: "lanAccessHint"; text: t("When on, other devices on the same network can open FreeVideo with the link below. Anyone with the link can use it, so keep it private.", "开启后,同一网络中的其他设备可以用下面的链接打开 FreeVideo。拿到链接的人都能使用,请勿公开。"); color: theme.muted; font.pixelSize: theme.micro; Layout.fillWidth: true }
+ FText { objectName: "lanFirewallHint"; visible: Qt.platform.os === "windows"; text: t("If Windows asks about the firewall the first time, choose Allow.", "Windows 首次询问防火墙权限时,请选择“允许”。"); color: theme.muted; font.pixelSize: theme.micro; Layout.fillWidth: true }
+ Repeater {
+ model: s.access_links || []
+ delegate: RowLayout {
+ required property string modelData
+ Layout.fillWidth: true; spacing: 8
+ FField { Layout.fillWidth: true; readOnly: true; text: modelData; onTextChanged: cursorPosition = 0; Component.onCompleted: cursorPosition = 0 }
+ FButton { text: t("Copy link", "复制链接"); onClicked: backend.copy(modelData) }
+ }
+ }
+ }
FGroup {
Layout.fillWidth: true; title: t("Storage", "存储")
RowLayout {
@@ -1107,20 +1138,22 @@ ApplicationWindow {
FButton { text: t("Qt notices & licenses ↗", "Qt 组件与许可证 ↗"); flat: true; implicitHeight: theme.heightSm; leftPadding: 4; font.pixelSize: theme.micro; onClicked: backend.link("https://doc.qt.io/qt-6/licenses-used-in-qt.html") }
}
ColumnLayout {
- Layout.fillWidth: true; visible: settingsTab === "advanced"; spacing: 20; enabled: !s.busy && !s.portable
+ Layout.fillWidth: true; visible: settingsTab === "advanced"; spacing: 20; enabled: !s.busy
FGroup {
Layout.fillWidth: true; title: t("ComfyUI address", "ComfyUI 地址")
- FField { Layout.fillWidth: true; text: s.form.url; onEditingFinished: backend.edit("url", text) }
+ FField { objectName: "listenAddress"; Layout.fillWidth: true; text: s.form.url; enabled: !s.form.lan_access; onEditingFinished: backend.edit("url", text) }
+ FText { objectName: "listenAddressHint"; text: t("With 0.0.0.0 or this computer's LAN IP, devices on the same network can open FreeVideo without the access link.", "填 0.0.0.0 或本机的局域网 IP 后,同一网络中的设备不需要访问链接就能打开 FreeVideo。"); color: theme.muted; font.pixelSize: theme.micro; Layout.fillWidth: true }
+ FText { visible: Qt.platform.os === "windows"; text: t("If Windows asks about the firewall the first time, choose Allow.", "Windows 首次询问防火墙权限时,请选择“允许”。"); color: theme.muted; font.pixelSize: theme.micro; Layout.fillWidth: true }
}
FGroup {
- Layout.fillWidth: true; title: t("Folders · optional", "目录 · 可选")
+ Layout.fillWidth: true; title: t("Folders · optional", "目录 · 可选"); enabled: !s.portable
FText { text: t("Engine folder", "引擎目录"); font.pixelSize: theme.micro; color: theme.muted }
RowLayout { Layout.fillWidth: true; spacing: 8; FField { Layout.fillWidth: true; text: s.form.engine; placeholderText: t("Automatic", "自动选择"); onEditingFinished: backend.edit("engine", text) } FButton { text: t("Browse…", "浏览…"); implicitHeight: theme.height + 4; onClicked: backend.browse("engine") } }
FText { text: t("ComfyUI Python", "ComfyUI Python"); font.pixelSize: theme.micro; color: theme.muted; Layout.topMargin: 4 }
FField { Layout.fillWidth: true; text: s.form.python; placeholderText: t("Path to python.exe", "python.exe 的路径"); onEditingFinished: backend.edit("python", text) }
}
FGroup {
- Layout.fillWidth: true; title: t("Maintenance", "维护")
+ Layout.fillWidth: true; title: t("Maintenance", "维护"); enabled: !s.portable
FSwitch { Layout.fillWidth: true; text: t("Create a separate ComfyUI environment", "创建独立的 ComfyUI 环境"); checked: s.form.separate; onToggled: backend.edit("separate", checked) }
FDivider {}
RowLayout {
diff --git a/freevideo_engine/launcher_copy.py b/freevideo_engine/launcher_copy.py
index a9d5de8..6e8b991 100644
--- a/freevideo_engine/launcher_copy.py
+++ b/freevideo_engine/launcher_copy.py
@@ -137,6 +137,25 @@ def source_name(value, zh=False):
return SOURCES.get(value, (value, value))[bool(zh)]
+LAN_ERRORS = {
+ 'Enter localhost or an IP address of this computer, for example http://127.0.0.1:8188.': '请填写 localhost 或本机的 IP 地址,例如 http://127.0.0.1:8188。',
+ 'This address does not belong to this computer. Enter one of its IP addresses or 0.0.0.0.': '这个地址不属于本机。请填写本机的 IP 地址或 0.0.0.0。',
+ 'The ports for LAN access are in use. Choose another ComfyUI port.': '局域网访问要用的端口已被占用,请换一个 ComfyUI 端口。',
+ 'A generation is running. Change the address after it finishes.': '正在生成,暂时不能修改地址。请在生成完成后再改。',
+ 'The ComfyUI already running does not use this address. After its jobs finish, restart it with this address and connect again.': '已在运行的 ComfyUI 没有使用这个地址。请在任务完成后用这个地址重新启动 ComfyUI,再重新连接。',
+ 'The ComfyUI already running is open to the network directly. After its jobs finish, restart it on 127.0.0.1, then turn on LAN access.': '已在运行的 ComfyUI 正在直接对局域网开放。请在任务完成后改用 127.0.0.1 重新启动它,再开启局域网访问。',
+ 'LAN access startup cancelled': '已取消开启局域网访问。',
+}
+
+
+def lan_error(value, zh=False):
+ value = str(value)
+ if zh:
+ for english, chinese in LAN_ERRORS.items():
+ value = value.replace(english, chinese)
+ return value
+
+
def display(value, zh=False):
value = clean(value)
if not zh:
diff --git a/freevideo_engine/launcher_session.py b/freevideo_engine/launcher_session.py
index 986f354..fae5953 100644
--- a/freevideo_engine/launcher_session.py
+++ b/freevideo_engine/launcher_session.py
@@ -10,7 +10,7 @@ from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit
from . import __version__
from . import disk_space
-from .comfy_launcher_runtime import Controller, layout, local_url, managed_frontend, new_layout
+from .comfy_launcher_runtime import Controller, layout, local_url, loopback_url, managed_frontend, new_layout
from .desktop_runtime import launcher_root, materialize_source
from .download_settings import Probe, read as download_preferences, speed_text
from .launcher_settings import Store, default_language
@@ -70,6 +70,7 @@ class Session:
url='http://127.0.0.1:8188', models='', model_dirs=[], model_method='auto', environment_method='auto',
separate=False, repair=False, new_comfy=True, offline_runtime='', offline_models=[],
imported_archives=[], sampling_caches=not saved.get('installation'))
+ self.form['lan_access'] = False
self.form.update({k: v for k, v in saved.items() if k in self.form})
if 'environment_method' not in saved and self.form['offline_runtime']:
self.form['environment_method'] = 'manual'
@@ -165,6 +166,13 @@ class Session:
return engine
def persist(self):
+ if self.selected and self.form['comfy'] == self.selected.get('root') and self.form['engine'] == self.selected.get('engine'):
+ try:
+ self.selected['url'] = local_url(self.form['url'])
+ if 'lan_access' in self.selected or self.form.get('lan_access') is True:
+ self.selected['lan_access'] = self.form.get('lan_access') is True
+ except ValueError:
+ pass # Save the editable draft while retaining a valid installation.
self.store.write(self.form, self.language, self.selected, self.saved_setup)
def remember(self, selection, persist=True):
@@ -172,6 +180,7 @@ class Session:
self.form.update(comfy=selection['root'], engine=selection['engine'],
python=selection.get('python') or '', url=selection['url'],
separate=selection.get('separate', False), new_comfy=False, repair=False)
+ self.form['lan_access'] = selection.get('lan_access') is True
if persist:
self.persist()
@@ -185,8 +194,10 @@ class Session:
self.token = validate(str(value)); return
if key not in self.form or self.controller.busy or self.importer.busy or self.cleaner.busy:
return
- if key in ('separate', 'repair', 'new_comfy', 'sampling_caches'):
+ if key in ('separate', 'repair', 'new_comfy', 'sampling_caches', 'lan_access'):
value = bool(value)
+ if key == 'url':
+ value = local_url(str(value))
if key == 'environment_method' and value not in ('auto', 'manual'):
raise ValueError('Unknown environment installation method')
if key == 'environment_method' and value == 'manual' and not runtime_packages_supported():
@@ -199,6 +210,23 @@ class Session:
return
self.repair_request = None
self.form[key] = value
+ if (key in ('url', 'lan_access') and self.selected and not self.form['new_comfy']
+ and self.form['comfy'] == self.selected.get('root') and self.form['engine'] == self.selected.get('engine')):
+ selected = dict(self.controller.selection or self.selected, url=local_url(self.form['url']),
+ lan_access=self.form.get('lan_access') is True)
+ previous_status = self.controller.state.get('status')
+ self.selected = selected
+ if key == 'url':
+ self.browser_attempted = False
+ self.browser_error = self.error = ''
+ self.persist()
+ if previous_status == 'open':
+ self.controller.run('configure_access', dict(url=selected['url'], lan_access=selected['lan_access']))
+ else:
+ self.controller.selection = dict(selected)
+ self.controller.state = dict(status='ready', selection=dict(selected), engine_update_available=bool(
+ self.controller.state.get('engine_update_available')))
+ return
if key in ('new_comfy', 'destination', 'comfy'):
# A remembered installation's engine belongs to that installation;
# another location installs into its own FreeVideo-engine.
@@ -400,7 +428,7 @@ class Session:
raise ValueError(self.t('Accept the installation plan and licenses.', '请先同意安装计划及许可证。'))
from .monitoring import save
save(consent, dict(accepted_at=time.time()))
- self.controller.run('launch', {'url': self.form['url']})
+ self.controller.run('launch', {'url': self.form['url'], 'lan_access': self.form.get('lan_access') is True})
elif self.page == 'launcher':
self.controller.run('launch', {'installation': self.selected})
elif self.page == 'progress' and state == 'review':
@@ -1094,6 +1122,8 @@ class Session:
self._closed = True
def tick(self):
+ if isinstance(self.controller, Controller) and not self.controller.busy:
+ self.controller.poll_access_proxy()
imported = self.importer.state
if not self.importer.busy and imported is not self.imported_batch:
self.imported_batch = imported
@@ -1151,7 +1181,7 @@ class Session:
if groups:
self.model_groups = groups
selection = row.get('selection')
- if not busy and selection and selection.get('ready') and (row.get('deployed') or row.get('status') in ('open', 'restart-required')):
+ if not busy and selection and selection.get('ready') and (row.get('deployed') or row.get('lan_status') == 'stopped' or row.get('status') in ('open', 'restart-required')):
self.repair_request = None
if selection != self.selected:
self.remember(selection)
@@ -1312,7 +1342,7 @@ class Session:
row = self.controller.state
task = row.get('task', {})
port_from = int(row['moved_from']) if row.get('status') == 'open' and 'moved_from' in row else 0
- port_to = (urlsplit(row['url']).port or 80) if port_from else 0
+ port_to = (urlsplit(row.get('selection', {}).get('url') or row['url']).port or 80) if port_from else 0
progress = progress_view(task.get('progress') or {}, zh)
overall = progress_view(row.get('overall') or task.get('phase_progress') or {}, zh)
if self.importer.busy:
@@ -1480,6 +1510,12 @@ 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,
+ access_links=(list(self.controller.access_links) if row.get('status') == 'open'
+ and isinstance(self.controller.access_links, list) else []),
+ lan_message=(self.t('LAN access has stopped. Turn it on again.', '局域网访问已停止,请重新开启。')
+ if row.get('lan_status') == 'stopped' else
+ self.t('No LAN address found. Connect to Wi-Fi or a wired network first.', '未找到局域网地址,请先连接 Wi-Fi 或有线网络。')
+ if row.get('lan_status') == 'no-address' else ''),
port_from=port_from, port_to=port_to,
old_versions=self.old_versions_text(), copied_models=self.copied_models_text(),
archives=self.archives_text(), archives_confirm=self.archives_confirm_text(),
diff --git a/freevideo_engine/launcher_settings.py b/freevideo_engine/launcher_settings.py
index e765097..e2a8b8c 100644
--- a/freevideo_engine/launcher_settings.py
+++ b/freevideo_engine/launcher_settings.py
@@ -52,6 +52,9 @@ def sanitize(value):
if isinstance(record, dict) and all(isinstance(record.get(k), str) and record[k] for k in SELECTION):
result['installation'] = {k: record[k] for k in SELECTION}
result['installation']['separate'] = record.get('separate') is True
+ result['installation']['lan_access'] = record.get('lan_access') is True
+ if type(record.get('lan_port')) is int and 1 <= record['lan_port'] <= 65535:
+ result['installation']['lan_port'] = record['lan_port']
if type(value.get('saved_at_ns')) is int:
result['saved_at_ns'] = value['saved_at_ns']
resume = value.get('setup')
diff --git a/freevideo_engine/modern_launcher.py b/freevideo_engine/modern_launcher.py
index 5ed626d..5122321 100644
--- a/freevideo_engine/modern_launcher.py
+++ b/freevideo_engine/modern_launcher.py
@@ -331,6 +331,11 @@ def create_ui(session, *, show=True):
return app, engine, window, bridge
+def save_screenshot(window, bridge, path):
+ if not bridge.value.get('access_links'):
+ window.grabWindow().save(str(path))
+
+
def smoke_test(app, engine, window, bridge, destination):
"""Exercise the packaged QML, manifests and managed-Python entry point."""
import queue
@@ -355,7 +360,7 @@ def smoke_test(app, engine, window, bridge, destination):
raise RuntimeError('Packaged launcher action is not visible: ' + page)
if page == 'progress':
# The last setup step shows the finished ones with a check mark; keep it for the font check.
- window.grabWindow().save(str(destination / 'launcher-steps.png'))
+ save_screenshot(window, bridge, destination / 'launcher-steps.png')
window.setProperty('settingsOpen', True)
app.processEvents()
window.setProperty('settingsOpen', False)
@@ -401,7 +406,7 @@ def smoke_test(app, engine, window, bridge, destination):
save(destination / 'smoke.json', dict(success=bool(result and result['status'] == 'complete' and not imported),
task=result, interface='Qt Quick launcher', build=build, source=str(session.source),
payload=payload, model_modules_imported=imported))
- window.grabWindow().save(str(destination / 'launcher.png'))
+ save_screenshot(window, bridge, destination / 'launcher.png')
if runner.busy:
runner.cancel()
timer.stop()
@@ -440,7 +445,7 @@ def smoke_connect(app, engine, window, bridge, destination, values):
info = server_info(state['url'].split('/?')[0]) if status == 'open' else {}
save(destination / 'connect.json', dict(success=status == 'open' and info.get('status') == 'freevideo',
status=status, error=state.get('error'), url=state.get('url'), server=info))
- window.grabWindow().save(str(destination / 'connected.png'))
+ save_screenshot(window, bridge, destination / 'connected.png')
timer.stop()
app.quit()
timer.timeout.connect(step)
diff --git a/freevideo_engine/portable.py b/freevideo_engine/portable.py
index d182f36..b21fa6d 100644
--- a/freevideo_engine/portable.py
+++ b/freevideo_engine/portable.py
@@ -240,7 +240,7 @@ def initialize(root, progress=lambda **kw: None):
def connect(root, value, machine, progress=lambda **kw: None, cancelled=None, *, url='http://127.0.0.1:8188',
- on_controller=None, previous=None):
+ on_controller=None, previous=None, lan_access=False, lan_port=None):
"""Use the existing ComfyUI connection/startup behavior without installing.
previous: the controller of an earlier attempt, whose ComfyUI may still run.
@@ -252,10 +252,6 @@ def connect(root, value, machine, progress=lambda **kw: None, cancelled=None, *,
# launcher source it was imported with backs one, as in any installation.
deploy(comfy, machine['source'], machine['root'])
controller = Controller(machine['source'], child_environment=lambda: environment(root, value))
- if previous is not None and previous.owns_server():
- # A ComfyUI this launcher started for an earlier attempt, e.g. one that
- # came up without FreeVideo: connecting restarts it instead of asking to.
- controller.server, controller.server_log = previous.server, previous.server_log
controller.shortcut_root = Path(plain(root))
if not machine['gpu_uuid'].startswith(('GPU-', 'MIG-')):
raise ValueError('The CUDA device did not provide a valid GPU identity; rerun the GPU check.')
@@ -266,9 +262,17 @@ def connect(root, value, machine, progress=lambda **kw: None, cancelled=None, *,
controller.cancelled = cancelled
if cancelled.is_set():
raise RuntimeError('Startup cancelled')
+ if previous is not None and previous.owns_server():
+ # A ComfyUI this launcher started for an earlier attempt, e.g. one that
+ # came up without FreeVideo: connecting restarts it instead of asking to.
+ controller.server, controller.server_log = previous.server, previous.server_log
+ if isinstance(previous, Controller):
+ for name in ('server_address', 'server_url', 'access_proxy', 'access_configuration', 'access_links', 'access_polled'):
+ setattr(controller, name, getattr(previous, name))
+ previous.server = previous.access_proxy = None
controller.selection = dict(ready=True, root=plain(comfy), engine=machine['root'],
source=machine['source'], python=machine['python'], url=url,
- portable=False, separate=False)
+ portable=False, separate=False, lan_access=lan_access is True, lan_port=lan_port)
controller.restore_terminal(machine['root'])
if on_controller:
on_controller(controller)
diff --git a/freevideo_engine/portable_launcher.py b/freevideo_engine/portable_launcher.py
index f5a1623..6c2a619 100644
--- a/freevideo_engine/portable_launcher.py
+++ b/freevideo_engine/portable_launcher.py
@@ -7,7 +7,7 @@ import time
from . import component_licenses, launch_view, portable, processes
from .comfy_launcher import Launcher
-from .comfy_launcher_runtime import Controller, local_url, matches_server, server_info
+from .comfy_launcher_runtime import Controller, local_url, loopback_url, matches_listener, matches_server, server_info
from .monitoring import save
from .long_paths import io_path, resolved, plain, plain_text
@@ -36,7 +36,9 @@ class PortableController(Controller):
self.selection = dict(root=plain(portable.inside(self.root, self.bundle['comfy'])),
engine=str(self.root/'engine'), source=str(self.source),
python=plain(portable.inside(self.root, self.bundle['python'])),
- url=local_url(url or 'http://127.0.0.1:8188'), ready=False, separate=False)
+ url=local_url(url or 'http://127.0.0.1:8188'), ready=False, separate=False,
+ lan_access=(values.get('installation') or {}).get('lan_access', values.get('lan_access', False)) is True,
+ lan_port=(values.get('installation') or {}).get('lan_port', (self.selection or {}).get('lan_port')))
self.state = dict(status='bundled', selection=dict(self.selection),
engine_update_available=self.engine_outdated())
self.restore_terminal(self.selection['engine'])
@@ -133,10 +135,28 @@ class PortableController(Controller):
url = self.selection['url']
info = server_info(url)
if matches_server(info, self.selection['root'], self.selection['engine'], self.source):
+ if self.comfy_controller is not None and self.comfy_controller.owns_server():
+ # Our own server on this port: its controller moves the listening
+ # address and the LAN proxy. A server left on the previous source
+ # does not match and restarts below, as before.
+ self.selection['ready'] = True
+ self.ensure_shortcut()
+ self.attach_console(info)
+ try:
+ return self.comfy_controller._configure_access(
+ dict(url=url, lan_access=self.selection['lan_access']), connect=True)
+ finally:
+ self._sync_access()
+ if not matches_listener(info, url):
+ self.state = dict(self.state, status='restart-required', url=loopback_url(url),
+ error='The ComfyUI already running does not use this address. After its jobs finish, restart it with this address and connect again.')
+ return
self.selection['ready'] = True
self.ensure_shortcut()
self.attach_console(info)
- self.state = dict(self.state, status='open', url=url+'/?freevideo=launch', selection=dict(self.selection))
+ self.state = dict(self.state, status='open', url=loopback_url(url)+'/?freevideo=launch', selection=dict(self.selection))
+ if self.selection['lan_access']:
+ self._configure_access(dict(lan_access=True))
return
# Windows keeps a folder made by a run as administrator, or under another
# account, from this account; the bundled Python would only report a
@@ -201,12 +221,54 @@ class PortableController(Controller):
self.progress(dict(stage='comfy', detail='Open FreeVideo workflow'))
opened = portable.connect(self.root, self.bundle, machine, self.progress_keywords,
self.cancelled, url=url, on_controller=self.retain_comfy_controller,
- previous=self.comfy_controller)
+ previous=self.comfy_controller, lan_access=self.selection['lan_access'],
+ lan_port=self.selection.get('lan_port'))
+ if self.comfy_controller is not None:
+ self._sync_access()
self.selection['ready'] = True
self.ensure_shortcut()
self.state = dict(self.state, status='open', url=opened, selection=dict(self.selection),
+ lan_status=self.comfy_controller.state.get('lan_status', '') if self.comfy_controller else '',
overall=dict(done=3, total=3, label='Ready'))
+ def _sync_access(self, status=True):
+ child = self.comfy_controller
+ self.selection.update({key: child.selection[key] for key in ('url', 'lan_access', 'lan_port')
+ if key in child.selection})
+ self.access_links = child.access_links
+ self.state = dict(self.state, selection=dict(self.selection), lan_status=child.state.get('lan_status', ''))
+ if status:
+ self.state = dict(self.state, status=child.state['status'], url=child.state.get('url', ''))
+
+ def _configure_access(self, values, *, connect=False):
+ if connect:
+ return self._launch(dict(installation=dict(self.selection, **values)))
+ if self.comfy_controller is None:
+ pending = self.state.get('engine_update_available', False)
+ try:
+ return super()._configure_access(values)
+ finally:
+ self.state = dict(self.state, engine_update_available=pending)
+ try:
+ self.comfy_controller._configure_access(values)
+ finally:
+ self._sync_access()
+
+ def stop_owned_server(self, *, grace=5):
+ if self.comfy_controller is not None:
+ self.comfy_controller.stop_owned_server(grace=grace)
+ super().stop_owned_server(grace=grace)
+
+ def check_access_proxy(self):
+ if self.comfy_controller is None:
+ return super().check_access_proxy()
+ if self.comfy_controller.access_proxy is None:
+ return
+ status = self.comfy_controller.state.get('status')
+ self.comfy_controller.check_access_proxy()
+ # The package's own state is copied only when this check saw ComfyUI stop.
+ self._sync_access(self.comfy_controller.state.get('status') != status)
+
def ensure_shortcut(self):
from .desktop_shortcut import create_after_install
self.state = dict(self.state, shortcut=create_after_install(
@@ -218,6 +280,10 @@ class PortableController(Controller):
if self._closed or self.cancelled.is_set():
controller.close()
raise RuntimeError('Startup cancelled; all files retained')
+ # An external connection can own a proxy directly on the package
+ # controller. Retire it before handing startup to the inner controller;
+ # later switch-off and polling operate through that inner controller.
+ self.stop_access_proxy()
self.comfy_controller = controller
def close(self):
@@ -266,8 +332,10 @@ class PortableLauncher(Launcher):
if self.loading_settings:
return
self.queue_save()
+ if self.launch_selection and _ and _[0] in (str(self.url), str(self.lan_access)):
+ return # The shared settings saver applies the connection change.
if not self.controller.busy:
- self.controller.restore({'url': self.url.get()})
+ self.controller.restore({'url': self.url.get(), 'lan_access': self.lan_access.get()})
self.launch_selection = dict(self.controller.selection)
self.reset_browser()
self.refresh()
@@ -322,12 +390,7 @@ def portable_session(root):
self.page = 'launcher'
def edit(self, key, value):
- if key == 'url' and not self.controller.busy:
- value = local_url(value)
- self.controller.restore({'url': value})
- self.remember(self.controller.selection)
- self.browser_attempted = False
- elif key in ('language', 'token'):
+ if key in ('url', 'lan_access', 'language', 'token'):
super().edit(key, value)
def action(self, name, accepted=False):
diff --git a/freevideo_engine/proxy.py b/freevideo_engine/proxy.py
index 73c09e1..c3c1de3 100644
--- a/freevideo_engine/proxy.py
+++ b/freevideo_engine/proxy.py
@@ -3,6 +3,7 @@ import os
import re
import shlex
import shutil
+import socket
import subprocess
import sys
from urllib import request
@@ -15,6 +16,62 @@ MODES = ('auto', 'proxy', 'direct')
GIT_PROXY_PATTERN = r'^(http\..*proxy|https\.proxy|remote\..*\.proxy|core\.gitproxy)$'
+def local_addresses():
+ """IPv4 interfaces served by the launcher's 0.0.0.0 proxy, on every OS."""
+ import ipaddress
+ import psutil
+ found = []
+ try:
+ with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as route:
+ route.connect(('8.8.8.8', 80))
+ found.append(route.getsockname()[0])
+ except OSError:
+ pass
+ try:
+ found.extend(row.address for rows in psutil.net_if_addrs().values() for row in rows
+ if row.family == socket.AF_INET)
+ except OSError:
+ pass
+ result = []
+ for host in found:
+ try:
+ ip = ipaddress.ip_address(host)
+ except ValueError:
+ continue
+ if ip.version == 4 and not (ip.is_loopback or ip.is_unspecified or ip.is_link_local):
+ result.append(str(ip))
+ return list(dict.fromkeys(result))
+
+
+def bypass_local(environ, *addresses):
+ """Keep this computer's UI traffic local without changing download routes."""
+ env = dict(environ)
+ if not configured(env):
+ # A lone NO_PROXY makes urllib and its users skip the proxy saved in the
+ # operating system, so add exceptions only beside a proxy variable.
+ return env
+ import ipaddress
+ import psutil
+ hosts = ['localhost', '127.0.0.1', '::1', '0.0.0.0', '::', *addresses]
+ try:
+ hosts.extend(row.address.split('%', 1)[0] for rows in psutil.net_if_addrs().values()
+ for row in rows if row.family in (socket.AF_INET, socket.AF_INET6))
+ except OSError:
+ pass
+ existing = ','.join(env.get(key, '') for key in ('no_proxy', 'NO_PROXY'))
+ entries = [value.strip() for value in existing.split(',') if value.strip()]
+ for host in hosts:
+ if host:
+ entries.append(host)
+ try:
+ if ipaddress.ip_address(host).version == 6:
+ entries.append('[' + host + ']')
+ except ValueError:
+ pass
+ env['no_proxy'] = env['NO_PROXY'] = ','.join(dict.fromkeys(entries))
+ return env
+
+
def inherited(environ=None):
from .linux_bundle import child_environment
env = child_environment(environ)