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.

Serve phone page files, page the agent activity list and accept same-origin LAN logins

Bowen Xue1f7d8da8ac3a
diff --git a/freevideo_engine/access_proxy.py b/freevideo_engine/access_proxy.py
index 84f5fe8..8369a2d 100644
--- a/freevideo_engine/access_proxy.py
+++ b/freevideo_engine/access_proxy.py
@@ -15,6 +15,7 @@ import math
import time
import ipaddress
import os
+import re
from pathlib import Path
import ssl
from urllib.parse import urlencode, urlsplit
@@ -24,13 +25,17 @@ from yarl import URL
from . import proxy_identity, lan_password
from .lan_auth import PasswordAuth, DEVICE_COOKIE, REMEMBER_SECONDS, LOGIN_DELAY
+PHONE_WEB = Path(__file__).resolve().parents[1] / 'web'
+PHONE_FILE = re.compile(r'[A-Za-z0-9_][A-Za-z0-9_.-]*\.(?:js|css|html)')
+PHONE_ASSETS = ('assets/freevideo.svg', 'assets/freevideo-light.svg')
+PHONE_TYPES = {'.js': 'text/javascript', '.css': 'text/css', '.html': 'text/html', '.svg': 'image/svg+xml'}
COOKIE = 'freevideo_access'
DAYS = 30
LOGIN_PATH = '/m/login'
# Temporary English copy; keep all password-page text here for Iris.
PASSWORD_COPY = dict(title='FreeVideo', password='Password', remember='Keep me signed in',
submit='Sign in', incorrect='Incorrect password', retry='Try again later ({minutes} minutes).',
- phone='FreeVideo mobile', pending='Mobile pages are coming soon.')
+ phone='FreeVideo mobile')
def password_page(*, error='', retry_after=0, status=401):
@@ -45,7 +50,8 @@ def password_page(*, error='', retry_after=0, status=401):
'<button type="submit">{submit}</button></form></body></html>').format(
**{k: html.escape(v) for k, v in copy.items()}, message=html.escape(message), retry_after=retry_after, action=LOGIN_PATH))
response.headers['Cache-Control'] = 'no-store'
- response.headers['Referrer-Policy'] = 'no-referrer'
+ # Chromium sends Origin: null from a no-referrer page, which the login would refuse.
+ response.headers['Referrer-Policy'] = 'same-origin'
response.headers['Content-Security-Policy'] = "default-src 'none'; form-action 'self'; frame-ancestors 'none'"
if retry_after:
response.headers['Retry-After'] = str(retry_after)
@@ -53,6 +59,19 @@ def password_page(*, error='', retry_after=0, status=401):
return response
+def phone_file(path, root=None):
+ """The page file /m/<name> stands for: .js/.css/.html directly inside web/ and the two wordmark SVGs."""
+ root = (root or PHONE_WEB).resolve()
+ name = 'phone.html' if path == '/m/' else path[len('/m/'):]
+ if not (PHONE_FILE.fullmatch(name) or name in PHONE_ASSETS):
+ return None
+ try:
+ found = (root / name).resolve(strict=True)
+ except (OSError, RuntimeError):
+ return None
+ return found if found.parent in (root, root / 'assets') and found.is_file() else None
+
+
def same_origin(request):
try:
if len(request.headers.getall('Host', [])) != 1 or len(request.headers.getall('Origin', [])) != 1:
@@ -279,14 +298,17 @@ def create(upstream, token, engine=None):
rest = [(k, v) for k, v in request.rel_url.query.items() if k != 'token']
location = request.path + ('?' + urlencode(rest) if rest else '')
return browser_headers(web.Response(status=303, headers={'Location': location}), request)
- if request.path in ('/m/', '/m/csrf') and request.method in ('GET', 'HEAD'):
+ if request.path.startswith('/m/') and request.path != LOGIN_PATH and request.method in ('GET', 'HEAD'):
if not request.get('lan_device'):
return web.Response(status=403)
if request.path == '/m/csrf':
response = web.json_response(dict(csrf=proxy_identity.csrf(hop_secret, request['lan_device'])))
else:
- response = web.Response(text='<!doctype html><title>%s</title><h1>%s</h1><p>%s</p>' % (
- PASSWORD_COPY['title'], PASSWORD_COPY['phone'], PASSWORD_COPY['pending']), content_type='text/html')
+ found = phone_file(request.path)
+ if found is None:
+ return web.Response(status=404, headers={'Cache-Control': 'no-store'})
+ response = web.Response(body=found.read_bytes() if request.method == 'GET' else b'',
+ content_type=PHONE_TYPES[found.suffix], charset='utf-8')
response.headers['Cache-Control'] = 'no-store'
return browser_headers(response, request)
if request.headers.get('Upgrade', '').lower() == 'websocket':
diff --git a/freevideo_engine/agent/routes.py b/freevideo_engine/agent/routes.py
index 8320368..ca03c42 100644
--- a/freevideo_engine/agent/routes.py
+++ b/freevideo_engine/agent/routes.py
@@ -51,6 +51,10 @@ WHITEBOX_PENDING = ('The user started a white-model scene in this conversation (
'failed: say it was not made, and why) and start nothing. A question is never a prompt.')
+
+def _activity_cursor(row):
+ return '%r:%s' % (row['created_at'], row['id'])
+
def local_address(request):
"""The backend's bound port, independent of page origins and forwarding headers."""
socket = request.transport.get_extra_info('sockname') if request.transport else None
@@ -811,23 +815,26 @@ def register():
if (view.get('result') or {}).get('library_id'):
# The work this video became, for the page to show it in My works.
value['work'] = view['result']['library_id']
+ from urllib.parse import quote
+ work = value.get('work')
+ # The saved work the page can play and picture without the agent's token.
+ value['play'] = '/freevideo/agent/chat/video?id=' + quote(work, safe='') if work else None
+ value['thumbnail'] = '/freevideo/library/thumbnail?id=' + quote(work, safe='') if work else None
+ picture = view.get('result') or {}
+ if row['kind'] == 'image' and picture.get('file'):
+ # ComfyUI's own view of the input file, which the page can show without the agent's token.
+ folder, _, leaf = picture['file'].rpartition('/')
+ value['thumbnail'] = '/view?filename=%s&subfolder=%s&type=input' % (quote(leaf, safe=''), quote(folder, safe=''))
if card:
- # A conversation card: the page plays and pictures the saved work itself, without the agent's token.
- from urllib.parse import quote
+ # A conversation card: the page plays and pictures the saved work itself.
value.pop('client')
- work = value.setdefault('work', None)
+ value.setdefault('work', None)
seconds = row['spec'].get('seconds')
size = [row['spec'].get(k) if type(row['spec'].get(k)) is int else None for k in ('width', 'height')]
value.update(seconds=seconds if isinstance(seconds, (int, float)) and not isinstance(seconds, bool) else None,
- width=size[0], height=size[1],
- thumbnail='/freevideo/library/thumbnail?id=' + quote(work, safe='') if work else None,
- play='/freevideo/agent/chat/video?id=' + quote(work, safe='') if work else None)
- picture = view.get('result') or {}
+ width=size[0], height=size[1])
if row['kind'] == 'image' and picture.get('file'):
- # ComfyUI's own view of the input file, which the page can show without the agent's token.
- folder, _, leaf = picture['file'].rpartition('/')
- value.update(width=picture.get('width'), height=picture.get('height'),
- thumbnail='/view?filename=%s&subfolder=%s&type=input' % (quote(leaf, safe=''), quote(folder, safe='')))
+ value.update(width=picture.get('width'), height=picture.get('height'))
return value
def agent_state():
@@ -1166,10 +1173,30 @@ def register():
def read():
# For the studio: what agents are doing, as ComfyUI's own queue and history already show.
now = time.time()
- rows = sorted(jobs.rows(), key=lambda r: r['created_at'], reverse=True)
- shown = [r for r in rows if r['status'] in ACTIVE or (r.get('finished_at') or 0) > now - 1800][:12]
- return dict(active=sum(1 for r in rows if r['status'] in ACTIVE), jobs=[activity_item(r) for r in shown])
- return reply(await asyncio.to_thread(read))
+ rows = sorted(jobs.rows(), key=lambda r: (r['created_at'], r['id']), reverse=True)
+ active = sum(1 for r in rows if r['status'] in ACTIVE)
+ cursor = request.query.get('cursor')
+ if cursor is None:
+ shown = [r for r in rows if r['status'] in ACTIVE or (r.get('finished_at') or 0) > now - 1800][:12]
+ after = shown[-1] if shown else None
+ older = [r for r in rows if after is None or (r['created_at'], r['id']) < (after['created_at'], after['id'])]
+ if after is None and older:
+ # Nothing recent: history starts from the newest job.
+ return dict(active=active, jobs=[], next_cursor=_activity_cursor({'created_at': older[0]['created_at'] + 1, 'id': ''}))
+ else:
+ try:
+ stamp, _, ident = cursor.partition(':')
+ key = (float(stamp), ident)
+ if not math.isfinite(key[0]) or len(cursor) > 80:
+ raise ValueError
+ except ValueError:
+ return None
+ page = [r for r in rows if (r['created_at'], r['id']) < key]
+ shown, older = page[:30], page[30:]
+ return dict(active=active, jobs=[activity_item(r) for r in shown],
+ next_cursor=_activity_cursor(shown[-1]) if shown and older else None)
+ value = await asyncio.to_thread(read)
+ return problem('invalid_request', 'Invalid cursor') if value is None else reply(value)
@routes.post('/freevideo/agent/activity/cancel')
@guarded
diff --git a/freevideo_engine/agent/schema.py b/freevideo_engine/agent/schema.py
index 68ef1c9..5a88c66 100644
--- a/freevideo_engine/agent/schema.py
+++ b/freevideo_engine/agent/schema.py
@@ -450,6 +450,7 @@ def contracts(*, local=False):
routes['GET', suffix] = route('Read generation monitoring', auth=False, lan=True, external=True,
query=obj({'client_id': string()}) if suffix != '/freevideo/progress' else EMPTY,
**({'path': obj({'id': string()}, ('id',))} if '{id}' in suffix else {}))
+ routes['GET', '/freevideo/agent/activity']['query'] = obj({'cursor': string(80)})
routes['GET', '/freevideo/agent/chat']['query'] = obj({'after': number(0, integer=True), 'session': SESSION})
routes['GET', '/freevideo/agent/chat/video']['query'] = obj({'id': string(43, pattern=r'^[0-9]{4}-[0-9]{2}-[0-9]{2}/[0-9a-f]{32}$')}, ('id',))
for method, suffix, summary, extra in (