From 32c9de1dd3908b2b69be8274dd2c084962d6f0bc Mon Sep 17 00:00:00 2001 From: Bowen Xue Date: Wed, 18 Nov 2026 02:26:34 +0000 Subject: [PATCH 01/97] Release 0.6.2: update notes - Editor save: unexpected errors return a logged 500 with request id, never 404; page shows a failure card with report button - Top bar: the Creations name sits on the same centre line as its icon, the status capsule and search - Launcher tests: the old Tk update window test skips on Windows without an input desktop; the English stacked narrow widths are a known layout failure until 0.6.3 - Creation panel: a prompt with a character mention shows each word once - Character mention browser check follows the current page: a round initial by its drawn shape, the mention in the theme accent, and the live prompt's transparent text - Character mention browser check: a name right after another character is a mention, as a mention sign after any character starts one - Release 0.6.2: update notes in formal wording - Release 0.6.2: ASCII hyphen in the English notes --- docs/community-results.md | 10 ---------- docs/zh-CN/community-results.md | 10 ---------- 2 files changed, 20 deletions(-) diff --git a/docs/community-results.md b/docs/community-results.md index f5492bab..731a881d 100644 --- a/docs/community-results.md +++ b/docs/community-results.md @@ -141,15 +141,6 @@ Thanks to the community members who sent diagnostic reports. FreeVideo already r | 5060 | 8 GB | 64 GB | 1088×1920 | 5.9 s | Medium | 0.4.31 | 1259 s | 0.4.31 | Already optimal¹² | | 3050 | 8 GB | 32 GB | 1344×768 | 5 s | Light | 0.4.35 | 978 s | 0.4.35 | Already optimal¹² | | 4070 Ti SUPER | 16 GB | 32 GB | 1344×768 | 12 s | Light | 0.4.37 | 3427 s | 0.5.3 | 2200 s (−1230 s)¹² | -| 4070 | 12 GB | 64 GB | 1344×768 | 8 s | Light⁵ | 0.4.38 | 269 s | 0.4.38 | Already optimal | -| 5060 Ti | 16 GB | 32 GB | 960×544 | 5.2 s | Light | 0.4.38 | 348 s | 0.4.38 | Already optimal | -| 5060 | 8 GB | 64 GB | 960×1664 | 11.5 s | Light⁵ | 0.4.38 | 1035 s | 0.4.38 | Already optimal¹² | -| 5090 | 32 GB | 128 GB | 1088×1920 | 10 s | Light | 0.5.0 | 638 s | 0.5.0 | Already optimal¹² | -| 3060 Ti | 8 GB | 16 GB | 1344×768 | 5.2 s | Light | 0.5.0 | 2102 s | 0.5.0 | Already optimal¹²,¹⁵ | -| 5060 Ti | 8 GB | 16 GB | 768×1344 | 8 s | Light | 0.4.33 | 594 s | 0.4.33 | Already optimal | -| 5060 Ti | 16 GB | 32 GB | 1344×768 | 10 s | Light | 0.5.1 | 716 s | 0.5.1 | Already optimal | -| 4060 Laptop | 8 GB | 16 GB | 1344×768 | 10 s | Light | 0.5.1 | 882 s | 0.5.1 | Already optimal | -| M4 Max | Unified | 128 GB | 1344×768 | 10.1 s | Light | 0.5.4 | 3399 s | 0.5.4 | Already optimal | - Time: end to end, from submission until the video is saved. - After: the estimated time, derived from the report's stage times and from complete planned runs on our test machines (RTX 3090 and RTX 5060 Ti on Windows, RTX PRO 6000 on Linux) under the reporting machine's VRAM and RAM limits, not from reruns on that machine. @@ -168,4 +159,3 @@ Thanks to the community members who sent diagnostic reports. FreeVideo already r - ¹² Task with a reference: every step also processes the reference video, images or audio, so each step takes longer than a plain request of the same size, up to about twice as long with a long reference. - ¹³ Preview (first pass only). - ¹⁴ Compatibility level 3 was set manually; it is the slowest level and made each step about 2.4 times slower than the automatic setting for this request, and the GPU core clock also stayed at 900 MHz against the 1815 MHz it reached. With the level off, the same request takes about 1100 s. -- ¹⁵ The video model is read from the drive again at every step, at about 110 MB/s on this machine; the graphics card was busy for about 9–13% of the first pass and 36% of the second pass. diff --git a/docs/zh-CN/community-results.md b/docs/zh-CN/community-results.md index 1f5eeb45..d92efdc0 100644 --- a/docs/zh-CN/community-results.md +++ b/docs/zh-CN/community-results.md @@ -141,15 +141,6 @@ | 5060 | 8 GB | 64 GB | 1088×1920 | 5.9 s | 标⁠准 | 0.4.31 | 1259 s | 0.4.31 | 已⁠是⁠最⁠优¹² | | 3050 | 8 GB | 32 GB | 1344×768 | 5 s | 轻⁠量 | 0.4.35 | 978 s | 0.4.35 | 已⁠是⁠最⁠优¹² | | 4070 Ti SUPER | 16 GB | 32 GB | 1344×768 | 12 s | 轻⁠量 | 0.4.37 | 3427 s | 0.5.3 | 2200 s (−1230 s)¹² | -| 4070 | 12 GB | 64 GB | 1344×768 | 8 s | 轻⁠量⁵ | 0.4.38 | 269 s | 0.4.38 | 已⁠是⁠最⁠优 | -| 5060 Ti | 16 GB | 32 GB | 960×544 | 5.2 s | 轻⁠量 | 0.4.38 | 348 s | 0.4.38 | 已⁠是⁠最⁠优 | -| 5060 | 8 GB | 64 GB | 960×1664 | 11.5 s | 轻⁠量⁵ | 0.4.38 | 1035 s | 0.4.38 | 已⁠是⁠最⁠优¹² | -| 5090 | 32 GB | 128 GB | 1088×1920 | 10 s | 轻⁠量 | 0.5.0 | 638 s | 0.5.0 | 已⁠是⁠最⁠优¹² | -| 3060 Ti | 8 GB | 16 GB | 1344×768 | 5.2 s | 轻⁠量 | 0.5.0 | 2102 s | 0.5.0 | 已⁠是⁠最⁠优¹²,¹⁵ | -| 5060 Ti | 8 GB | 16 GB | 768×1344 | 8 s | 轻⁠量 | 0.4.33 | 594 s | 0.4.33 | 已⁠是⁠最⁠优 | -| 5060 Ti | 16 GB | 32 GB | 1344×768 | 10 s | 轻⁠量 | 0.5.1 | 716 s | 0.5.1 | 已⁠是⁠最⁠优 | -| 4060 笔⁠记⁠本 | 8 GB | 16 GB | 1344×768 | 10 s | 轻⁠量 | 0.5.1 | 882 s | 0.5.1 | 已⁠是⁠最⁠优 | -| M4 Max | 统⁠一⁠内⁠存 | 128 GB | 1344×768 | 10.1 s | 轻⁠量 | 0.5.4 | 3399 s | 0.5.4 | 已⁠是⁠最⁠优 | - 用时:从提交到视频保存完成的端到端用时。 - 优化后:预估用时,根据报告中的分段用时,结合测试机(Windows RTX 3090 和 RTX 5060 Ti、Linux RTX PRO 6000)在报告机器的显存和内存上限下运行完整规划的实测推算,不是在报告机器上重跑。 @@ -168,4 +159,3 @@ - ¹² 带参考的任务:每一步还要处理参考视频、参考图片或参考音频,所以每步耗时比相同尺寸的普通请求长;参考较长时约为两倍。 - ¹³ 预览(只做第一遍)。 - ¹⁴ 兼容等级 3 为手动设置,是最慢的等级,对这个请求每步比自动设置慢约 2.4 倍;显卡核心时钟同时固定在 900 MHz(本次运行曾达到 1815 MHz)。关闭该等级后,同样的请求约需 1100 秒。 -- ¹⁵ 视频模型每一步都要从硬盘重新读取,这台机器上读取速度约 110 MB/s;显卡在第一遍约 9–13% 的时间在工作,第二遍约 36%。 From 5c57934c97da8454601da5e847f1a7a1b6ddbbfd Mon Sep 17 00:00:00 2001 From: Bowen Xue Date: Wed, 18 Nov 2026 02:27:05 +0000 Subject: [PATCH 02/97] A card below the hardware floor gets the unsupported-GPU card even when an old driver cannot... A card below the hardware floor gets the unsupported-GPU card even when an old driver cannot report its capability --- freevideo_engine/failure_details.py | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/freevideo_engine/failure_details.py b/freevideo_engine/failure_details.py index 42db886e..66c8bdad 100644 --- a/freevideo_engine/failure_details.py +++ b/freevideo_engine/failure_details.py @@ -591,6 +591,18 @@ def source_lines(lines, zh=False): return list(rows.values())[-SOURCE_CARD_LINES:] +# Graphics card families that all predate compute capability 8.0 (Ampere), by the name the driver reports. +BELOW_COMPUTE_FLOOR = re.compile( + r'\b(?:GeForce\s+)?(?:GT|GTS|GTX)\s*\d' # GeForce 8 to GTX 16 series, including GT 730 + r'|\bGeForce\s+(?:RTX\s*)?20[0-9]0\b' # RTX 20 series (Turing) + r'|\bGeForce\s+(?:8|9|2|3)\d{2,3}\s*(?:GT|GS|M)?\b' # older numbered GeForce cards + r'|\bTITAN\s*(?:X|V|Xp|RTX|Black|Z)?\b' + r'|\bQuadro\s+(?:RTX\s*)?[KMPT]?\d' + r'|\bTesla\s+[KMPVT]\d' + r'|\bGeForce\s+MX\s*(?:[1-4]\d0|550)\b' # MX110 to MX550; the MX570 is Ampere and stays supported + r'|\bNVS\s*\d', re.I) + + def launcher_failure(value, *, zh=False, **options): """Short guidance; a download that failed on every source also lists what each source returned.""" text, lines = _sources_block(str(value)) if value else ('', []) @@ -992,6 +1004,13 @@ def _launcher_failure(value, *, zh=False, other_disk=False, disk_name='', can_re if tools and tools.group(1).endswith((':', ':', '.', '。')): return dict(title=('缺少基础工具' if zh else 'Basic tools are missing'), detail='\n'.join(part for part in tools.groups() if part), action='', kind='system-tools') + # A driver too old to report the compute capability leaves it unknown, and the update card would then be shown for a + # card no driver can help. When the card is named and belongs to a family below the floor, it is the unsupported card. + if 'CUDA_ARCH_UNSUPPORTED' not in text: + named = re.search(r'NVIDIA driver(?: [\w.]+)?(?: \(([^)]*)\))? is older than 580', text, re.I) \ + or re.search(r'\[CUDA_CAPABILITY_UNKNOWN\] Could not determine the CUDA architecture of (.+?) \(SM', text) + if named and named.group(1) and BELOW_COMPUTE_FLOOR.search(named.group(1)): + text += '\n[CUDA_ARCH_UNSUPPORTED] %s (SMunknown; compute capability unknown; driver unknown)' % named.group(1) for pattern, kind, title, action in rules: if re.search(pattern, text, re.I): if kind in WITHOUT_REPAIR and not can_repair: @@ -1017,6 +1036,10 @@ def _launcher_failure(value, *, zh=False, other_disk=False, disk_name='', can_re model, capability = found.groups() detail = ('检测到:%s,计算能力 %s' if zh else 'Detected: %s, compute capability %s') % (model, capability) return dict(title=title[zh], detail=detail + '\n' + action[zh], action='', kind=kind) + found = re.search(r'\[CUDA_ARCH_UNSUPPORTED\]\s+(.+?)\s+\(SMunknown;', text) + if found: + detail = ('检测到:%s' if zh else 'Detected: %s') % found[1] + return dict(title=title[zh], detail=detail + '\n' + action[zh], action='', kind=kind) if kind == 'path-too-long': # A dependency folder Git cannot read is named, above the same next step. found = re.search(r'The path of the dependency folder (.+?) is too long for Git to read', text) From b5a59ebc7875a17f39c8f95fa25291d604ca2771 Mon Sep 17 00:00:00 2001 From: Bowen Xue Date: Wed, 18 Nov 2026 02:30:59 +0000 Subject: [PATCH 03/97] ComfyUI startup card: no raw error text on the card ComfyUI startup card: no raw error text on the card; a known last error is said in the interface language, any other stays in the details --- freevideo_engine/failure_details.py | 45 ++++++++++++++++++++++++----- 1 file changed, 38 insertions(+), 7 deletions(-) diff --git a/freevideo_engine/failure_details.py b/freevideo_engine/failure_details.py index 66c8bdad..79675029 100644 --- a/freevideo_engine/failure_details.py +++ b/freevideo_engine/failure_details.py @@ -458,6 +458,35 @@ def _model_unchanged(tail): APPLICATION_CONTROL = r'WinError 4551|Application Control policy has blocked' +# Error lines ComfyUI may end on, as a sentence for the card; any other line stays in the technical details. +STARTUP_ERRORS = ( + (r'CUDA (?:error: )?out of memory|OutOfMemoryError', ('Not enough video memory', '显存不足')), + (r'^MemoryError|paging file is too small|WinError 1455', ('Not enough memory', '内存不足')), + (r'ModuleNotFoundError|No module named|DLL load failed', ('A required component is missing', '缺少必需的组件')), + (r'PermissionError|Access is denied|WinError 5\b', ('Access was denied', '访问被拒绝')), +) + + +def _startup_cause(summary, zh): + """What ComfyUI said when it quit: the exit code, the custom node that last failed to load and, when it is a + known one, the last error as a sentence. The raw error line is not shown on the card.""" + code = re.search(r'^Process exit code: (-?\d+)', summary, re.M) + errors = [line.strip() for line in summary.splitlines() if re.match(r'^[\w.]+(?:Error|Exception)\b', line.strip())] + known = next((sentence[zh] for pattern, sentence in STARTUP_ERRORS if errors and re.search(pattern, errors[-1])), '') + known = known.rstrip('.。') + # ComfyUI names a custom node it could not load in either of these lines. + nodes = re.findall(r'(?:Cannot import |\(IMPORT FAILED\): ).*?custom_nodes[\\/]([^\\/\r\n]+?)(?: module for custom nodes|\s*$)', + summary, re.M) + node = nodes[-1].strip()[:80] if nodes else '' + if zh: + return ('ComfyUI 在启动时退出' + ('(退出码 %s)' % code.group(1) if code else '') + + (',自定义节点“%s”未能加载' % node if node else '') + + (',最后一条错误:%s。' % known if known else '。')) + return ('ComfyUI quit while starting' + (' (exit code %s)' % code.group(1) if code else '') + + ('. The custom node "%s" did not load' % node if node else '') + + ('. Last error: %s.' % known if known else '.')) + + def _stopped_on_missing_module(text): """ComfyUI itself stopped on an import, not a custom node that logged one and loaded on.""" lines = [line.strip() for line in text.splitlines() if line.strip()] @@ -725,11 +754,12 @@ def _launcher_failure(value, *, zh=False, other_disk=False, disk_name='', can_re if text.startswith('ComfyUI could not start.') and not _stopped_on_application_control(summary): if can_repair and repairs_comfy and (_stopped_on_missing_module(summary) or ENVIRONMENT_FILES in summary): return dict(title=DEPENDENCIES[0][zh], detail='', action=DEPENDENCIES[1][zh], kind='dependencies') + action = ('完整日志在详情里;使用已有的 ComfyUI 时,请用原来的启动器检查。' if zh else + 'Open the details for the full log. For an existing ComfyUI, also check its original launcher.') + # The cause and the next step are one text, as for every card: the card and the settings page show the + # detail when the action is empty. return dict(title='ComfyUI 启动失败' if zh else 'ComfyUI could not start', - detail='ComfyUI 启动时退出了。' if zh else 'ComfyUI quit while starting.', - action='原因在详情里;使用已有的 ComfyUI 时,可以用原来的启动器检查。' if zh else - 'Open details for the exit code and plugin errors. For an existing ComfyUI, also check its original launcher.', - kind='comfy-startup') + detail=_startup_cause(summary, zh) + '\n' + action, action='', kind='comfy-startup') # A file Windows refused to load is no GPU result: the app-control guidance below applies, and the # code the engine adds to the message makes it recognisable in any system language. if ('Failed step: kernels (' in summary and not re.search(APPLICATION_CONTROL, summary) @@ -744,9 +774,10 @@ def _launcher_failure(value, *, zh=False, other_disk=False, disk_name='', can_re '显卡加速检查没有通过。' if zh else 'The GPU acceleration check did not pass.') detail = detail.replace('Required path missing', '缺少必需的文件夹' if zh else 'A required folder is missing') - return dict(title='GPU 检查未通过' if zh else 'GPU validation failed', detail=detail, - action='展开详情或导出报告,查看完整检查结果。' if zh else - 'Open the details or export the report for the complete results.', kind='kernels') + action = ('展开详情或导出报告,查看完整检查结果。' if zh else + 'Open the details or export the report for the complete results.') + return dict(title='GPU 检查未通过' if zh else 'GPU validation failed', detail=detail + '\n' + action, + action='', kind='kernels') if 'Download list error: read' in text.splitlines(): from .model_guidance import DOWNLOAD_COPY return dict(title=DOWNLOAD_COPY['error_read'][zh], detail='', action='', kind='download-list-read') From bbe4a87e27e01001d1a6a42259d76f34097cd076 Mon Sep 17 00:00:00 2001 From: Bowen Xue Date: Wed, 18 Nov 2026 02:31:14 +0000 Subject: [PATCH 04/97] Startup error message: formal wording, and no request to attach a file that could not be saved --- freevideo_engine/startup_error.py | 62 +++++++++++++++++++++++++++++++ scripts/windows_app.py | 29 +++++++++++++-- 2 files changed, 87 insertions(+), 4 deletions(-) create mode 100644 freevideo_engine/startup_error.py diff --git a/freevideo_engine/startup_error.py b/freevideo_engine/startup_error.py new file mode 100644 index 00000000..cac7c05c --- /dev/null +++ b/freevideo_engine/startup_error.py @@ -0,0 +1,62 @@ +"""What a person sees when FreeVideo fails before its window opens. + +Standard library only: the entry points call this when the launcher itself could not load, so nothing it +uses may be the part that failed. The traceback goes to startup-error.txt, never into the message box. +""" +import os +from pathlib import Path +import sys +import tempfile +import traceback + +FILE = 'startup-error.txt' +ISSUES = 'https://github.com/FlashML-org/FreeVideo/issues/new' +TITLE = 'FreeVideo' + + +def launcher_folder(): + """The packaged launcher's own folder (desktop_runtime.launcher_root), without importing the engine.""" + if os.environ.get('FREEVIDEO_LAUNCHER_HOME'): + return Path(os.environ['FREEVIDEO_LAUNCHER_HOME']) + if sys.platform == 'darwin': + return Path.home() / 'Library/Application Support/FreeVideo/launcher' + return Path(os.environ.get('LOCALAPPDATA') or str(Path.home())) / 'FreeVideo-launcher' + + +def save(detail, folder): + """Write the traceback to the first folder that takes it; None when none does.""" + for place in (Path(folder), Path(tempfile.gettempdir())): + try: + place.mkdir(parents=True, exist_ok=True) + path = place / FILE + path.write_text(detail, encoding='utf-8') + return path + except OSError: + continue + return None + + +def message(path): + """The short text for the person, in Chinese and English: what happened, where the details are, where to report.""" + if path: + where = '错误详情已保存到:\nThe details were saved to:\n' + str(path) + report = '请在下面的地址提交问题,并附上这个文件:\nPlease report the problem here and attach the file:\n' + else: + # Nothing to attach: only where to report. + where = '错误详情未能保存。\nThe details could not be saved.' + report = '请在下面的地址提交问题:\nPlease report the problem here:\n' + return 'FreeVideo 未能启动。\nFreeVideo could not start.\n\n' + where + '\n\n' + report + ISSUES + + +def report(folder, detail=None): + """Save the current exception's traceback and tell the person; returns the file it was saved to.""" + detail = detail if detail is not None else traceback.format_exc() + path = save(detail, folder) + text = message(path) + if sys.stderr is not None: + # A console shows the whole traceback; the short text comes last, where the person looks. + sys.stderr.write(detail + '\n' + text + '\n') + elif sys.platform == 'win32': + import ctypes + ctypes.windll.user32.MessageBoxW(None, text, TITLE, 0x10) + return path diff --git a/scripts/windows_app.py b/scripts/windows_app.py index 5610bad5..137d0b0d 100644 --- a/scripts/windows_app.py +++ b/scripts/windows_app.py @@ -1,8 +1,29 @@ """PyInstaller entry point; model modules stay out of the GUI executable.""" -import freevideo_source_bootstrap -freevideo_source_bootstrap.activate() +import sys + + +def _failed(): + """The launcher could not load or stopped with an error: a short message instead of a raw traceback.""" + import traceback + detail = traceback.format_exc() + try: + from freevideo_engine.startup_error import launcher_folder, report + report(launcher_folder(), detail) + except Exception: + # The engine package itself could not load: keep the plain traceback where a person can see it. + if sys.stderr is not None: + sys.stderr.write(detail) + elif sys.platform == 'win32': + import ctypes + ctypes.windll.user32.MessageBoxW(None, detail, 'FreeVideo startup error', 0x10) + raise SystemExit(1) -from freevideo_engine.modern_launcher import main if __name__ == '__main__': - main() + try: + import freevideo_source_bootstrap + freevideo_source_bootstrap.activate() + from freevideo_engine.modern_launcher import main + main() + except Exception: + _failed() From 9f9d1b26fc0f0c6eff837dba4dbfabc3acb1ece3 Mon Sep 17 00:00:00 2001 From: Bowen Xue Date: Wed, 18 Nov 2026 02:31:42 +0000 Subject: [PATCH 05/97] Assistant task failures now say what happened and what to do next instead of only "Did not finish" --- freevideo_engine/agent/errors.py | 185 ++++++++++++++++++++++++++++++- freevideo_engine/agent/jobs.py | 6 +- freevideo_engine/agent/schema.py | 5 +- web/agent_activity.js | 12 +- web/autopilot_chat.js | 14 ++- 5 files changed, 209 insertions(+), 13 deletions(-) diff --git a/freevideo_engine/agent/errors.py b/freevideo_engine/agent/errors.py index 4af205d0..7937f204 100644 --- a/freevideo_engine/agent/errors.py +++ b/freevideo_engine/agent/errors.py @@ -296,6 +296,14 @@ def safe_details(value): return '[redacted]' +# Picture-only codes: the people-facing sentence is the picture card's own (IMAGE_REASONS), word for word. +IMAGE_ONLY = ('small_memory', 'busy_video', 'model_unreadable', 'device_unavailable') +# Program-facing codes: only an Agent or a command-line client meets them, never a person as a task's failure. +PROTOCOL_ONLY = ('forbidden', 'redirect_forbidden', 'method_not_allowed', 'unauthorized', 'no_token', 'invalid_json', + 'unsupported_media_type', 'idempotency_conflict', 'invalid_range', 'invalid_wait', 'invalid_resume', + 'invalid_library_id', 'invalid_capabilities_query') + + # One public sentence shared by conversation cards, HTTP and MCP. Backend text # is classified, never echoed: it can contain prompts, filenames or credentials. FAILURE_REASONS_ZH = { @@ -349,8 +357,61 @@ def safe_details(value): 'chain_too_long': '接续后的视频超过了支持的段数', 'chain_short_parts': '有短于 10 秒的段时,接续后的视频超过了支持的段数', 'chain_rejected': '生成服务无法使用这组参数', - 'generation_failed': '生成没有完成', - 'internal_error': '没有完成', + 'generation_failed': '生成过程中出现了意外错误', + 'internal_error': '处理过程中出现了意外错误', + 'unreachable': 'FreeVideo 服务没有响应', + 'session_full': '这个对话的消息已达到上限', + 'page_session_required': '页面会话已失效', + 'origin_forbidden': '这次操作来自其他网址,已被拒绝', + 'local_only': '这项操作只能在运行 FreeVideo 的电脑上进行', + 'page_required': '这项操作需要在浏览器中打开 FreeVideo 页面', + 'unsupported_comfyui': '已安装的生成组件版本不受支持', + 'busy': '另一项任务正在占用所需的资源', + 'conflict': '这项操作与任务的当前状态冲突', + 'no_video': '来源任务还没有生成完成的视频', + 'invalid_edit': '图片编辑的设置有误', + 'invalid_screenplay': '剧本中有不符合要求的内容', + 'invalid_seed': '图片的随机种子超出了支持的范围', + 'image_size': '图片超过了 5000 万像素的上限', + 'unsupported_media': '读取画面的模型只能读取图片', + 'unknown_shot': '找不到这个镜头', + 'unknown_take': '这个镜头中找不到指定的那一条', + 'take_not_ready': '这一条已过期或没有生成成功', + 'chosen_by_user': '这个镜头已手动选定,不会自动更改', + 'nothing_to_cancel': '没有可以取消的未完成任务', + 'not_allowed': '这部短剧只能在页面上手动停止或继续', + 'already_ended': '这部短剧已经结束', + 'needs_confirmation': '这项操作需要先确认', + 'declined_by_user': '这项操作已被拒绝', + 'turn_abandoned': '这次请求已被放弃', + 'managed_by_production': '这一条属于一部短剧,不能单独继续生成', + 'stale_revision': '卡片在读取后已有改动', + 'changed_by_user': '这部分内容已被手动修改', + 'card_in_use': '有未完成的短剧正在使用这张卡片', + 'already_generating': '这张卡片的参考图正在生成', + 'project_changed': '项目在读取后已有改动', + 'image_changed': '图片在读取后已有改动', + 'clip_busy': '这次操作涉及的片段还在生成', + 'clip_locked': '这次操作涉及的片段在已锁定的轨道上', + 'layer_locked': '这次操作要修改已锁定的图层', + 'audio_full': '这里没有空闲的声音轨', + 'overlap': '这次操作会与不能移动的片段重叠', + 'missing_glyphs': '项目中的文字含有内置字体无法显示的字符', + 'clip_source_unusable': '有片段的源文件缺失,或在片段使用的范围内无法读取', + 'shorten_unavailable': '这里暂时不能自动缩短台词', + 'no_speech_model': '这台电脑上没有安装语音识别模型', + 'speech_language': '语音识别模型不支持这段声音的语言', + 'listen_failed': '识别台词时中途出错', + 'music_download_failed': '配乐模型未能下载', + 'music_failed': '生成配乐时中途出错', + 'stems_download_failed': '声音分离模型未能下载', + 'stems_failed': '分离声音时中途出错', + 'sound_failed': '处理成片声音时中途出错', + 'voice_failed': '更换人声时中途出错', + 'voice_model_missing': '配音模型还没有安装好', + 'no_speech': '所选范围内没有找到说话声', + # Image-only codes keep the sentences the picture card already shows. + **{code: IMAGE_REASONS[code][1] for code in IMAGE_ONLY}, } FAILURE_REASONS_EN = { **LORA_MESSAGE_EN, @@ -403,8 +464,116 @@ def safe_details(value): 'chain_too_long': 'The continued video has more parts than supported', 'chain_short_parts': 'With a part shorter than 10 seconds, the continued video has more parts than supported', 'chain_rejected': 'The generation service cannot use these settings', - 'generation_failed': 'Generation did not finish', - 'internal_error': 'Did not finish', + 'generation_failed': 'An unexpected error stopped generation', + 'internal_error': 'An unexpected error stopped this task', + 'unreachable': 'The FreeVideo service did not respond', + 'session_full': 'This chat has reached its message limit', + 'page_session_required': 'The page session is no longer valid', + 'origin_forbidden': 'This action came from a different web address and was refused', + 'local_only': 'This action is available only on the computer running FreeVideo', + 'page_required': 'This action needs the FreeVideo page open in a browser', + 'unsupported_comfyui': 'The installed generation component version is not supported', + 'busy': 'Another task is using the resources this one needs', + 'conflict': 'This action conflicts with the current state of the task', + 'no_video': 'The source task has no finished video yet', + 'invalid_edit': 'The image edit settings are invalid', + 'invalid_screenplay': 'The screenplay contains invalid content', + 'invalid_seed': 'The picture seed is outside the supported range', + 'image_size': 'The image exceeds the 50-megapixel limit', + 'unsupported_media': 'The model that reads pictures can read only images', + 'unknown_shot': 'This shot cannot be found', + 'unknown_take': 'The chosen take cannot be found in this shot', + 'take_not_ready': 'This take is out of date or did not succeed', + 'chosen_by_user': 'This shot was chosen by hand and is not changed automatically', + 'nothing_to_cancel': 'There is no unfinished task to cancel', + 'not_allowed': 'This short film can be stopped or continued only by hand on the page', + 'already_ended': 'This short film has already ended', + 'needs_confirmation': 'This action needs approval first', + 'declined_by_user': 'This action was declined', + 'turn_abandoned': 'This request was abandoned', + 'managed_by_production': 'This take belongs to a short film and cannot be continued on its own', + 'stale_revision': 'The card has changed since it was read', + 'changed_by_user': 'This part was changed by hand', + 'card_in_use': 'An unfinished short film uses this card', + 'already_generating': 'Reference pictures for this card are already being made', + 'project_changed': 'The project has changed since it was read', + 'image_changed': 'The image has changed since it was read', + 'clip_busy': 'A clip in this action is still generating', + 'clip_locked': 'A clip in this action is on a locked track', + 'layer_locked': 'This action changes a locked layer', + 'audio_full': 'There is no free sound track here', + 'overlap': 'This action would overlap clips that cannot move', + 'missing_glyphs': 'Text in the project contains characters the built-in fonts cannot display', + 'clip_source_unusable': 'A clip\'s source file is missing, or cannot be read over the part the clip uses', + 'shorten_unavailable': 'Lines cannot be shortened automatically here yet', + 'no_speech_model': 'No speech recognition model is installed on this computer', + 'speech_language': 'The speech recognition model does not support the language of this sound', + 'listen_failed': 'An error stopped recognizing the lines', + 'music_download_failed': 'The music model could not be downloaded', + 'music_failed': 'An error stopped composing the music', + 'stems_download_failed': 'The sound separation model could not be downloaded', + 'stems_failed': 'An error stopped separating the sound', + 'sound_failed': 'An error stopped finishing the sound of the cut', + 'voice_failed': 'An error stopped changing the voice', + 'voice_model_missing': 'The dubbing model is not installed yet', + 'no_speech': 'No speech was found in the selection', + **{code: IMAGE_REASONS[code][0] for code in IMAGE_ONLY}, +} +# What a person can do next, for the reasons above whose remedy is not just running the task again. Shown after the +# reason only while the reason itself is the code's sentence (a more specific message keeps its own meaning). +FAILURE_NEXT_ZH = { + 'generation_failed': '再次出现时,请点击“提交问题”', + 'internal_error': '再次出现时,请点击“提交问题”', + 'unreachable': '确认 FreeVideo 已经启动后再试', + 'session_full': '点击“新对话”后继续', + 'page_session_required': '刷新页面后再操作一次', + 'origin_forbidden': '在 FreeVideo 提供的页面中操作', + 'unsupported_comfyui': '在启动器或设置中修复安装', + 'busy': '等该任务完成后再试', + 'no_video': '等来源视频生成完成后再试', + 'image_size': '缩小图片后再试', + 'managed_by_production': '重拍这个镜头,或继续这部短剧', + 'already_generating': '等参考图生成完成后再试', + 'clip_busy': '等片段生成完成后再试', + 'clip_locked': '解锁该轨道后再试', + 'layer_locked': '解锁该图层后再试', + 'audio_full': '先挪开或删除这里的一段声音', + 'overlap': '换一个位置,或先挪开挡住的片段', + 'missing_glyphs': '修改这些文字后再导出', + 'clip_source_unusable': '找回或替换源文件后再导出', + 'shorten_unavailable': '手动改写较短的台词', + 'no_speech_model': '请手动填写字幕', + 'music_download_failed': '配乐模型需要约 20 GB 磁盘空间和网络连接,确认后再试', + 'stems_download_failed': '检查网络连接后再试', + 'voice_model_missing': '先安装配音模型', + 'no_speech': '选择有人说话的一段声音', +} +FAILURE_NEXT_EN = { + 'generation_failed': 'If it happens again, use "Report a problem"', + 'internal_error': 'If it happens again, use "Report a problem"', + 'unreachable': 'Make sure FreeVideo is running, then try again', + 'session_full': 'Click "New chat" to continue', + 'page_session_required': 'Reload the page and repeat the action', + 'origin_forbidden': 'Use the page served by FreeVideo', + 'unsupported_comfyui': 'Repair the installation in the launcher or in Settings', + 'busy': 'Try again when that task finishes', + 'no_video': 'Try again after the source video finishes', + 'image_size': 'Make the image smaller, then try again', + 'managed_by_production': 'Reshoot this shot, or continue the short film', + 'already_generating': 'Try again when the reference pictures are finished', + 'clip_busy': 'Try again when the clip finishes generating', + 'clip_locked': 'Unlock the track, then try again', + 'layer_locked': 'Unlock the layer, then try again', + 'audio_full': 'Move or remove a sound clip here first', + 'overlap': 'Choose another position, or move the clips in the way first', + 'missing_glyphs': 'Change that text, then export again', + 'clip_source_unusable': 'Restore or replace the source file, then export again', + 'shorten_unavailable': 'Write a shorter line by hand', + 'no_speech_model': 'Write the subtitles by hand', + 'music_download_failed': 'The music model needs about 20 GB of free disk space and a network connection; check both, then try again', + 'stems_download_failed': 'Check the network connection, then try again', + 'voice_model_missing': 'Install the dubbing model first', + 'no_speech': 'Choose a stretch of sound with someone speaking', } FAILURE_MESSAGES_ZH = { 'The previous video is too short to continue; it needs to be at least 1.7 s long.': '接续的上一段视频太短,至少需要 1.7 秒', @@ -447,13 +616,21 @@ def failure_reason_en(error): return FAILURE_REASONS_EN.get(error.get('code'), 'Did not finish') +# The people-facing fields reasons() writes; next_zh/next_en only when the reason has a next step. +REASON_KEYS = ('error_zh', 'error_en', 'next_zh', 'next_en') + + def reasons(error): from ..other_usage import fact, join result = dict(error_zh=failure_reason(error), error_en=failure_reason_en(error)) + code = error.get('code') + step = code in FAILURE_NEXT_ZH and result['error_zh'] == FAILURE_REASONS_ZH.get(code) for key, zh in (('error_zh', True), ('error_en', False)): suffix = fact(error.get('other_usage'), zh=zh) if suffix and suffix not in result[key]: result[key] = join(result[key], suffix, zh=zh) + if step: + result.update(next_zh=FAILURE_NEXT_ZH[code], next_en=FAILURE_NEXT_EN[code]) return result diff --git a/freevideo_engine/agent/jobs.py b/freevideo_engine/agent/jobs.py index 5b09c048..885ad9dd 100644 --- a/freevideo_engine/agent/jobs.py +++ b/freevideo_engine/agent/jobs.py @@ -780,7 +780,6 @@ def finish(self, row, status, *, result=None, error=None, save=True): if code == 'invalid_json' and row['kind'] in ('vlm', 'enhance'): code = 'vlm_invalid_json' failure_reasons = errors.reasons(dict(error, code=code)) - reason_zh, reason_en = failure_reasons['error_zh'], failure_reasons['error_en'] if code != error.get('code') or not error.get('request_id') or row['kind'] == 'image': error = errors.build(code, details=error.get('details'), request=row.get('request_id'), action_required=code != 'cancelled', @@ -788,9 +787,10 @@ def finish(self, row, status, *, result=None, error=None, save=True): report_id=error.get('report_id'), memory=error.get('memory'), image_stage=error.get('stage'), other_usage=error.get('other_usage')) if row['kind'] == 'image': - reason_zh, reason_en = error['error_zh'], error['error_en'] + failure_reasons = {k: error[k] for k in errors.REASON_KEYS if k in error} if error is not None: - error = dict(error, request_id=row.get('request_id') or error['request_id'], error_zh=reason_zh, error_en=reason_en) + error = {k: v for k, v in error.items() if k not in errors.REASON_KEYS} + error = dict(error, request_id=row.get('request_id') or error['request_id'], **failure_reasons) if row['kind'] != 'image' and isinstance(report_id, str) and re.fullmatch(r'[a-f0-9]{32}', report_id): error['report_id'] = report_id if error.get('next'): diff --git a/freevideo_engine/agent/schema.py b/freevideo_engine/agent/schema.py index 7eeb1025..db038e19 100644 --- a/freevideo_engine/agent/schema.py +++ b/freevideo_engine/agent/schema.py @@ -807,7 +807,8 @@ def cast_view(): description=nullable(string(1000)), revision=number(1, integer=True), images=array(picture, 0, 6), candidates=array(picture, 0, 6), generating=nullable(generating), generated=nullable(generated), - generate_error=nullable(obj(dict(code=string(), job=JOB, message=string(), error_zh=string(), error_en=string()), ('code', 'job', 'message')))), + generate_error=nullable(obj(dict(code=string(), job=JOB, message=string(), error_zh=string(), error_en=string(), + next_zh=string(), next_en=string()), ('code', 'job', 'message')))), ('id', 'kind', 'name', 'revision', 'images', 'candidates', 'generating')), additionalProperties=True) @@ -1731,7 +1732,7 @@ def openapi(): other_usage=nullable(obj(dict(vram_gib=number(0), ram_gib=number(0), kinds={'type': 'array', 'items': enum(('gpu', 'ram'))}, signature=string()), ('vram_gib', 'ram_gib', 'kinds', 'signature'))), - error_zh=string(), error_en=string()), + error_zh=string(), error_en=string(), next_zh=string(), next_en=string()), ('code', 'message', 'details', 'retryable', 'request_id', 'docs'))})) diff --git a/web/agent_activity.js b/web/agent_activity.js index 555470e5..a4a6a382 100644 --- a/web/agent_activity.js +++ b/web/agent_activity.js @@ -34,6 +34,9 @@ const REASONS = { dependency_failed: ['An earlier step did not succeed', '前序任务未成功'], }; +// Failures without a known cause: the row offers the problem report. +const UNEXPECTED = ['internal_error', 'generation_failed']; + function el(tag, cls, text) { const e = document.createElement(tag); if (cls) e.className = cls; if (text != null) e.textContent = text; return e; } function glyph(path) { const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); @@ -109,14 +112,19 @@ function row(job, t, api, refresh, open, cancellationErrors) { if (job.status === 'running' && p.remaining_seconds > 0) meta.push(left(p.remaining_seconds, t)); const reason = job.status === 'failed' && REASONS[job.error?.code]; if (reason) meta.push(t(...reason)); - else if (job.status === 'failed') meta.push(t(job.error?.error_en || 'Did not finish', job.error?.error_zh || '没有完成')); + else if (job.status === 'failed') { + // The engine's reason, then its next step when it has one. + const e = job.error || {}, next = (said, step, zh) => said && step ? said.replace(/[。.]$/, '') + (zh ? '。' : '. ') + step : said; + meta.push(t(next(e.error_en, e.next_en) || 'Did not finish', next(e.error_zh, e.next_zh, true) || '没有完成')); + } if (job.project) meta.push(job.project); const foot = el('div', 'fv-agent-foot'); const details = el('p', 'fv-agent-meta', meta.join(' · ')); if (reason && job.error?.message) details.title = job.error.message; foot.append(details); const issue = issueButton(t, () => ({where: ['Assistant tasks', '助手任务'], message: details.textContent})); - issue.hidden = !cancellationErrors.has(job.id); foot.append(issue); + // An unexpected failure can be reported from its row, as its next step says. + issue.hidden = !cancellationErrors.has(job.id) && !(job.status === 'failed' && UNEXPECTED.includes(job.error?.code)); foot.append(issue); if (['waiting', 'queued', 'running'].includes(job.status)) { const stop = el('button', 'fv-agent-stop', t('Stop', '停止')); stop.type = 'button'; stop.setAttribute('aria-label', t('Stop ', '停止 ') + title(job, t)); tip(stop, 'stop', t); diff --git a/web/autopilot_chat.js b/web/autopilot_chat.js index 6e5dd8d0..7dba3320 100644 --- a/web/autopilot_chat.js +++ b/web/autopilot_chat.js @@ -70,14 +70,21 @@ const WHITEBOX = { failure: ['Could not start: ', '无法开始生成:'], }; const GENERIC_FAILURE_ZH = '没有完成'; +// The failures whose next step is the problem report (agent/errors.py FAILURE_NEXT_*). +const UNEXPECTED_FAILURES = ['internal_error', 'generation_failed']; +// The engine's next step for a reason, as the sentence after it. +const withNext = (reason, next, zh) => next ? reason.replace(/[。.]$/, '') + (zh ? '。' : '. ') + next : reason; // Sends and failure cards use the same public reason, including the engine's Chinese mapping. function failureReason(value, t) { const error = value.error, reason = error?.error_zh || value.error_zh, reasonEn = error?.error_en || value.error_en; if (error?.code === 'session_full' && (!reason || reason === GENERIC_FAILURE_ZH)) return t('This chat is full. Click "New chat".', '这个对话已满,请点“新对话”。'); + // The next step belongs to the same object as the reason it follows. + const own = error?.error_zh ? error : value; // `message` is written for programs; people read the engine's own English reason. A refusal the engine // did not classify keeps its sentence, as before. - return t(reasonEn || error?.message || 'Did not finish', reason || GENERIC_FAILURE_ZH); + return t(withNext(reasonEn || error?.message || 'Did not finish', reasonEn && own.next_en), + withNext(reason || GENERIC_FAILURE_ZH, reason && own.next_zh, true)); } // A failed job's one reason line. The engine's classified sentence (both languages) is for people; anything else is @@ -1430,10 +1437,13 @@ export function agentChat(t, api, {open, edit, shown = () => true, changed = () // The shared failure style: one reason line, the fold row, then the secondary buttons. const fold = failureFold(t); if (retry) actions.append(...again()); - actions.append(diagnostic.report); + // An unexpected failure says to report it if it happens again: the card carries that button. + const issue = issueButton(t, () => ({where: CHAT_ISSUE, message: [reason.textContent, fold.querySelector('p').textContent].filter(Boolean).join('\n')})); + actions.append(diagnostic.report, issue); links.append(actions); item.replaceChildren(failHead, reason, fold, links); tip(diagnostic.report, 'report', t); apply = next => { current = next; put(reason, failureCardReason(next, t)); + issue.hidden = !UNEXPECTED_FAILURES.includes(next.error?.code); put(failName, jobName(next, t)); put(failChip, statusText(next, t)); failChip.dataset.state = statusKey(next); put(failWhen, localTime(next.finished_at || next.created_at, t)); failWhen.hidden = !failWhen.textContent; const raw = [next.error?.code, next.error?.message, next.error?.request_id].filter(Boolean).join('\n'); From 90dbc542df87596a04c8556f3590d61c5b4bcd5f Mon Sep 17 00:00:00 2001 From: Bowen Xue Date: Wed, 18 Nov 2026 02:38:59 +0000 Subject: [PATCH 06/97] Model upgrade failures state the cause and the next step; card shows no raw step text --- freevideo_engine/engine_exit.py | 15 +++++++++++---- freevideo_engine/failure_details.py | 6 +++++- freevideo_engine/launcher/Main.qml | 9 ++++++++- freevideo_engine/launcher_session.py | 11 ++++++++++- freevideo_engine/model_upgrade.py | 19 ++++++++++++++++--- freevideo_engine/prompt_vlm/installer.py | 18 +++++++++++++++++- 6 files changed, 67 insertions(+), 11 deletions(-) diff --git a/freevideo_engine/engine_exit.py b/freevideo_engine/engine_exit.py index aa5982c2..6dd8586f 100644 --- a/freevideo_engine/engine_exit.py +++ b/freevideo_engine/engine_exit.py @@ -116,11 +116,18 @@ def public(value): def describe(value, zh): - """The launcher's one sentence about a stopped engine, in the language of the window. + """The launcher's sentence about a stopped engine, in the language of the window: when, why as far as known, what next. - The exit status is not in it: it is in the record, the logs and the diagnostic report. + The exit status itself is not in it: it is in the record, the logs and the diagnostic report. """ clock = time.strftime('%H:%M', time.localtime(value['at'])) + kind = value.get('exit_class') + memory = kind in ('system_commit_limit', 'system_no_memory') + ended = kind in ('killed_by_signal', 'terminated_externally') + crashed = kind in ('native_crash', 'abort', 'system_stack_overflow') if zh: - return 'ComfyUI 于 %s 意外停止。请点击“重新连接”重新启动。' % clock - return 'ComfyUI stopped unexpectedly at %s. Click "Connect again" to restart it.' % clock + cause = (',原因是电脑内存不足' if memory else ',被系统或其他程序结束' if ended else ',程序自身崩溃' if crashed else '') + return ('ComfyUI 于 %s 意外停止%s。请点击“重新连接”重新启动;如再次停止,请导出报告,再点击“提交问题”并附上报告。' % (clock, cause)) + cause = (': the computer ran out of memory' if memory else ': the system or another program ended it' if ended + else ': it crashed' if crashed else '') + return 'ComfyUI stopped unexpectedly at %s%s. Click "Connect again" to restart it; if it stops again, export the report and use "Report a problem".' % (clock, cause) diff --git a/freevideo_engine/failure_details.py b/freevideo_engine/failure_details.py index 79675029..d88d5454 100644 --- a/freevideo_engine/failure_details.py +++ b/freevideo_engine/failure_details.py @@ -1106,7 +1106,11 @@ def _launcher_failure(value, *, zh=False, other_disk=False, disk_name='', can_re name = _step_name(step.group(1), zh) if name: title = ('“%s”这一步没有完成' if zh else 'The step "%s" did not finish') % name - detail = '' + # The step's own line is internal. The last other error line is raw text, so it shows only + # when it has a known sentence in this language; otherwise it stays in the technical details. + other = [line for line in causes if not line.startswith(('Failed step:', 'Setup failed:'))] + raw = re.sub(r'^(?:[\w.]+(?:Error|Exception)|ERROR):?\s*', '', other[-1])[:200] if other else '' + detail = raw if raw and lan_error(raw, zh) != raw else '' # A message the launcher raised itself (a ValueError) is the next step already. unexpected = 'Traceback' in text and not re.match(r'(?:[\w.]+\.)?ValueError:', causes[-1] if causes else '') detail = lan_error(detail, zh) diff --git a/freevideo_engine/launcher/Main.qml b/freevideo_engine/launcher/Main.qml index e9704edb..1e567ac7 100644 --- a/freevideo_engine/launcher/Main.qml +++ b/freevideo_engine/launcher/Main.qml @@ -181,6 +181,13 @@ ApplicationWindow { if (code === "active-variant-incomplete") return t("The faster model's files are incomplete, so the old model is kept.", "更快的模型文件不完整,旧模型保留。") return t("The model in use is not a standard FreeVideo model, so nothing was deleted.", "当前使用的模型不是标准安装的模型,为安全起见没有删除任何文件。") } + function upgradeCause(code, step) { + if (code === "disk") return t("There is not enough free disk space for the model files. Free some space first.", "磁盘可用空间不足,放不下模型文件。请先腾出空间。") + if (code === "network") return t("The model download lost its connection. Check the network first.", "模型下载时网络连接中断。请先检查网络。") + if (step === "switch") return t("The switch to the faster model did not finish.", "切换到更快的模型没有完成。") + if (step === "release") return t("The old model could not be removed.", "旧模型未能删除。") + return t("The model download did not finish.", "模型下载没有完成。") + } function upgradeReportText() { // A failed upgrade reports the whole failure, including the step log, not only the first line shown on the card. return upgrade.status === "failed" && upgrade.error ? upgrade.error : upgradeExplanation() @@ -218,7 +225,7 @@ ApplicationWindow { return (u.released_bytes ? t("Freed ", "已释放 ") + bytes(u.released_bytes) + t(".", "。") : "") + (lora ? t(" The old model stays for your fused LoRAs.", "旧模型为需要合并的 LoRA 保留。") : "") if (u.status === "failed") - return (u.blockers && u.blockers.length ? upgradeBlocker(u.blockers[0]) + t(" ", "") : u.error ? u.error.split("\n")[0] + "\n" : "") + return (u.blockers && u.blockers.length ? upgradeBlocker(u.blockers[0]) + t(" ", "") : upgradeCause(u.cause, u.step) + "\n") + (u.step === "release" ? t("The faster model is in use; the old model files are kept for now.", "已在用更快的模型,旧模型文件暂时保留。") : u.step === "switch" && !u.kept ? t("The previous model's files are all kept. Select \"Retry\" on the setup page to restore it.", "原来的模型文件都还在,在安装页点“重试”可恢复。") : t("Your previous model is unchanged and still works. Select \"Try again\", or report a problem.", "原来的模型没有变化,可以继续使用。可以点“重试”,或提交问题。")) diff --git a/freevideo_engine/launcher_session.py b/freevideo_engine/launcher_session.py index 367c3df0..c71a1015 100644 --- a/freevideo_engine/launcher_session.py +++ b/freevideo_engine/launcher_session.py @@ -1154,8 +1154,17 @@ def prompt_model_view(self): failure = '' if active.get('state') == 'failed': failure = {'disk_space': self.t('Not enough disk space.', '磁盘空间不足。'), + 'ram_space': self.t('Not enough free memory to prepare this model. Close other programs, then resume.', + '可用内存不足,无法准备这个模型。请关闭其他程序后点击“继续”。'), + 'network_failed': self.t('The download stopped: the connection to the download server was lost. Resume to continue.', + '下载中断:与下载服务器的连接断开。请点击“继续”接着下载。'), + 'write_failed': self.t('The download stopped: the model files could not be written to this folder. Check the folder, then resume.', + '下载中断:模型文件无法写入这个文件夹。请检查文件夹后点击“继续”。'), + 'verify_failed': self.t('The download stopped: a downloaded file did not pass the check. Resume to download it again.', + '下载中断:下载的文件没有通过校验。请点击“继续”重新下载。'), 'busy': self.t('Another download of this model is running.', '这个模型正在被另一处下载。')}.get( - active.get('reason'), self.t('The download stopped. Resume to continue.', '下载中断了,点继续可接着下载。')) + active.get('reason'), self.t('The download stopped. Resume to continue; if it stops again, export the report and use "Report a problem".', + '下载中断。请点击“继续”;如再次中断,请导出报告,再点击“提交问题”并附上报告。')) return dict(ready=ready, checking=checking, total_bytes=total, enough_disk=enough, busy=busy, install=active, failure=failure, downloaded_bytes=active.get('done', 0), title=self.t(*NAMES['text']), suggest=bool(engine) and not ready and not checking and not busy and enough and not self.form['prompt_hint_dismissed'] diff --git a/freevideo_engine/model_upgrade.py b/freevideo_engine/model_upgrade.py index 9b5ef853..e41cc7e9 100644 --- a/freevideo_engine/model_upgrade.py +++ b/freevideo_engine/model_upgrade.py @@ -18,6 +18,7 @@ the GPU then failed to run - are offered for removal, and removed only on request. """ +import errno import json from pathlib import Path import shutil @@ -32,6 +33,18 @@ RETRY_SECONDS = 30 +def failure_cause(error): + """disk / network / '' for the page to explain; the raw text stays in `error` for the report.""" + text = str(error).lower() + if (isinstance(error, OSError) and error.errno == errno.ENOSPC) or 'no space left' in text or 'not enough disk' in text: + return 'disk' + if isinstance(error, (ConnectionError, TimeoutError)) or any(k in text for k in ( + 'connection reset', 'connection refused', 'connection aborted', 'connection error', 'timed out', + 'name or service not known', 'temporary failure in name resolution', 'network is unreachable')): + return 'network' + return '' + + @plain_errors def offer(root): """Whether this installation should move to int8 and what that costs, or which @@ -262,7 +275,7 @@ def work(): raise RuntimeError(fetched.get('error') or 'The model download stopped; downloaded files are kept.') self.state = dict(self.state, status='downloaded', phase='switch') except Exception as error: - self.state = dict(offered, status='failed', step='download', error=str(error)) + self.state = dict(offered, status='failed', step='download', error=str(error), cause=failure_cause(error)) finally: self.runner = None return self._start(work) @@ -283,7 +296,7 @@ def switching(self): def switch_failed(self, error, kept): """kept: machine.json still describes the previous model, which keeps working.""" - self.state = dict(self.state, status='failed', step='switch', error=error, kept=kept, waiting=None) + self.state = dict(self.state, status='failed', step='switch', error=error, cause='', kept=kept, waiting=None) def release(self, root, expect=TARGET): """Remove the variants not in use once `expect` is in use and complete, waiting out running requests.""" @@ -311,7 +324,7 @@ def work(): self.state = dict(self.state, waiting=True) self.closing.wait(RETRY_SECONDS) except Exception as error: - self.state = dict(self.state, status='failed', step='release', error=str(error), waiting=False) + self.state = dict(self.state, status='failed', step='release', error=str(error), cause=failure_cause(error), waiting=False) return return self._start(work) diff --git a/freevideo_engine/prompt_vlm/installer.py b/freevideo_engine/prompt_vlm/installer.py index f9fd87b0..1192dedf 100644 --- a/freevideo_engine/prompt_vlm/installer.py +++ b/freevideo_engine/prompt_vlm/installer.py @@ -78,4 +78,20 @@ def check(): except Exception as error: known = {'disk_space', 'ram_space'} with self.lock: - self.value.update(state='failed', reason=str(error) if str(error) in known else 'download_failed') + self.value.update(state='failed', reason=str(error) if str(error) in known else failure_reason(error)) + + +def failure_reason(error): + """What stopped the download, in words the card can act on; anything else stays 'download_failed'.""" + import errno + from ..network import DownloadError + text = str(error).lower() + if isinstance(error, OSError) and error.errno == errno.ENOSPC: + return 'disk_space' + if isinstance(error, PermissionError) or (isinstance(error, OSError) and error.errno in (errno.EROFS, errno.EACCES, errno.EIO)): + return 'write_failed' + if any(word in text for word in ('sha256', 'checksum', 'hash mismatch', 'digest')): + return 'verify_failed' + if isinstance(error, (DownloadError, ConnectionError, TimeoutError)) or any(word in text for word in ('timed out', 'connection', 'resolve')): + return 'network_failed' + return 'download_failed' From 3df37d1bfaa26b0421244554f37408fb6ab9e770 Mon Sep 17 00:00:00 2001 From: Bowen Xue Date: Wed, 18 Nov 2026 02:40:40 +0000 Subject: [PATCH 07/97] Editor and upload failures say why: invalid-request and export errors log and carry the... Editor and upload failures say why: invalid-request and export errors log and carry the exception class, music and upload name a full disk or lost network --- freevideo_engine/comfy_editor.py | 7 +++++-- freevideo_engine/comfy_upload.py | 15 ++++++++++++++- freevideo_engine/editor_export.py | 4 ++-- freevideo_engine/editor_music.py | 19 +++++++++++++++---- web/editor.js | 3 ++- web/editor_music.js | 5 ++++- web/media_upload.js | 4 +++- 7 files changed, 45 insertions(+), 12 deletions(-) diff --git a/freevideo_engine/comfy_editor.py b/freevideo_engine/comfy_editor.py index e504abf8..308d1a27 100644 --- a/freevideo_engine/comfy_editor.py +++ b/freevideo_engine/comfy_editor.py @@ -1573,8 +1573,11 @@ async def guarded(request): return web.json_response(dict(error='Editor item unavailable'), status=404, headers=_HEADERS) except OSError as error: return web.json_response(dict(saved=False, retry=True, **_disk_full(error)), status=503, headers=_HEADERS) - except (ValueError, TypeError, KeyError, RecursionError): - return web.json_response(dict(error='Invalid editor request'), status=400, headers=_HEADERS) + except (ValueError, TypeError, KeyError, RecursionError) as error: + # A bad request is the caller's; a TypeError or KeyError may be this code's own bug, so the log keeps the trace. + request_id = uuid.uuid4().hex[:12] + _LOG.log(logging.WARNING if isinstance(error, ValueError) else logging.ERROR, 'Editor request rejected as invalid (%s %s, %s, request_id=%s).', method.upper(), path, type(error).__name__, request_id, exc_info=not isinstance(error, ValueError)) + return web.json_response(dict(error='Invalid editor request', **{'class': type(error).__name__}, request_id=request_id), status=400, headers=_HEADERS) except Exception as error: # An unexpected failure is never a 404: the page reads that as "this engine has no editor API". request_id = uuid.uuid4().hex[:12] diff --git a/freevideo_engine/comfy_upload.py b/freevideo_engine/comfy_upload.py index 9f8705ba..d29d7344 100644 --- a/freevideo_engine/comfy_upload.py +++ b/freevideo_engine/comfy_upload.py @@ -1,6 +1,8 @@ """Stream browser media to ComfyUI input without buffering a clip in RAM.""" import asyncio +import errno import json +import logging import os from pathlib import Path, PurePosixPath, PureWindowsPath import shutil @@ -91,6 +93,16 @@ async def receive(reader, input_directory, *, store_root=None): return result +def failure_body(error): + """The JSON body and status for a failed upload. An OS error's raw text can hold the user's path, so the page gets a reason it can act on.""" + if isinstance(error, OSError): + from .disk_space import ran_out + code = 'disk_full' if ran_out(error) else 'not_writable' if isinstance(error, PermissionError) or error.errno in (errno.EACCES, errno.EROFS) else 'failed' + logging.getLogger(__name__).warning('Media upload failed (%s, %s).', type(error).__name__, code, exc_info=error if code == 'failed' else None) + return {'error': 'Upload failed', 'code': code}, 507 if code == 'disk_full' else 400 + return {'error': str(error), 'code': getattr(error, 'code', 'failed')}, 400 + + def register(): from aiohttp import web import folder_paths @@ -104,7 +116,8 @@ async def upload(request): try: result = await receive(await request.multipart(), folder_paths.get_input_directory()) except (OSError, ValueError) as error: - return web.json_response({'error': str(error), 'code': getattr(error, 'code', 'failed')}, status=400) + body, status = failure_body(error) + return web.json_response(body, status=status) return web.json_response(result) from .lora_triggers import get_trigger, set_trigger diff --git a/freevideo_engine/editor_export.py b/freevideo_engine/editor_export.py index 0401f06a..4e5a96a5 100644 --- a/freevideo_engine/editor_export.py +++ b/freevideo_engine/editor_export.py @@ -1111,7 +1111,7 @@ def _view(self, job): return {**{key: job[key] for key in ('id', 'state', 'fraction', 'work', 'reason')}, 'queued': job['state'] == 'running' and job['id'] in self.pending, **job['options'].status(), 'path': job.get('path'), 'url': job.get('url'), - 'project_id': job['project'].get('id'), 'revision': job['project'].get('revision')} + 'class': job.get('error_class'), 'project_id': job['project'].get('id'), 'revision': job['project'].get('revision')} def submit(self, identity, revision=None, *, options=None): if not isinstance(identity, str) or not _PROJECT_ID.fullmatch(identity): @@ -1226,7 +1226,7 @@ def progress(fraction): if isinstance(error, ExportCancelled) or job['stop'].is_set(): job.update(state='cancelled', reason=None) else: - job.update(state='failed', reason=reason) + job.update(state='failed', reason=reason, error_class=type(error).__name__ if reason == 'failed' else None) def register(): diff --git a/freevideo_engine/editor_music.py b/freevideo_engine/editor_music.py index bd2fcd14..002497b9 100644 --- a/freevideo_engine/editor_music.py +++ b/freevideo_engine/editor_music.py @@ -26,7 +26,18 @@ POLL_SECONDS = .5 _JOB_ID = re.compile(r'm-[0-9a-f]{32}') _FIELDS = {'frames', 'text', 'style', 'mood', 'seed', 'quiet'} -REASONS = ('music_download_failed', 'out_of_memory', 'music_failed', 'invalid_request', 'busy', 'unsupported', 'failed') +REASONS = ('music_download_failed', 'disk_space', 'out_of_memory', 'music_failed', 'invalid_request', 'busy', 'unsupported', 'failed') + + +def _disk_or_network_reason(error, download=False): + """A full disk, or (while downloading) a lost network, as the reason the page already words; None when it is neither.""" + from .disk_space import ran_out + if ran_out(error): + return 'disk_space' + if download and isinstance(error, (ConnectionError, TimeoutError)) or download and type(error).__name__ in ('URLError', 'HTTPError', 'ReadTimeout', 'ConnectTimeout', 'ChunkedEncodingError', 'IncompleteRead'): + return 'music_download_failed' + return None + # Presets: the genre and instruments, then the feeling and pace. Instrumental only, as the Agent asks for. STYLES = { @@ -284,7 +295,7 @@ def phase(name, fraction=None): code = getattr(error, 'code', None) if code not in REASONS: logging.warning('[FreeVideo] Editor music failed', exc_info=error) - code = 'music_failed' + code = _disk_or_network_reason(error) or 'music_failed' job.update(state='failed', phase=None, reason=code) if not isinstance(error, Exception): raise @@ -385,9 +396,9 @@ def progress(fraction): pass except service.MusicError as error: reason = error.reason or 'failed' - except Exception: # noqa: BLE001 - the page says it did not download; the log keeps why + except Exception as error: # noqa: BLE001 - the page says it did not download; the log keeps why logging.warning('[FreeVideo] Music model download failed', exc_info=True) - reason = 'failed' + reason = _disk_or_network_reason(error, download=True) or 'failed' with self.lock: self.value = dict(running=False, fraction=0. if reason or stop.is_set() else 1., reason=reason) diff --git a/web/editor.js b/web/editor.js index 318b4892..acedd67d 100644 --- a/web/editor.js +++ b/web/editor.js @@ -422,7 +422,8 @@ export function openEditor({api, app, from = null, panel = {}, components: given // A plain Error says nothing by its class; when its message is itself a short code (chain_missing) that is the reason. // Any other message may hold a path or the user's words, so it is never copied. const named = value?.name === 'Error' && /^[a-z][a-z0-9_]{2,39}$/.test(value?.message) ? value.message : value?.name; - const code = value?.reason || value?.code || named; + // A failed export names the exception class (a type name, never a message), so the report says what broke. + const code = (value?.reason === 'failed' && value?.class) || value?.reason || value?.code || named; return site + ':' + (String(code || '').replace(/[^A-Za-z0-9_.-]/g, '').slice(0, 40) || 'unknown'); } // `where` marks a failure: the notice then carries the "Report a problem" button and stays longer to be reached. diff --git a/web/editor_music.js b/web/editor_music.js index 5d3bcaff..de408a57 100644 --- a/web/editor_music.js +++ b/web/editor_music.js @@ -31,6 +31,9 @@ export function musicBarStatus(job, t, clock = Date.now) { return {state: 'running', blocks: [], music: true, words: {stage, ...(time ? {time} : {})}}; } +// Reasons the sentence already explains and the user can act on; any other failure carries the report button. +const KNOWN_FAILURES = new Set(['music_download_failed', 'disk_space', 'out_of_memory', 'unsupported', 'missing', 'cancelled']); + // A failed piece's sentence on the bar's failure line. export function musicFailureText(reason, t) { return { @@ -135,7 +138,7 @@ export function createEditorMusic({state, store, t, completeSources = async () = }, failure(selection = state.selection) { const found = target(selection); - return found?.clip?.pending === 'failed' ? {id: found.clip.id, text: musicFailureText(found.clip.reason, t), report: false} : null; + return found?.clip?.pending === 'failed' ? {id: found.clip.id, text: musicFailureText(found.clip.reason, t), report: !KNOWN_FAILURES.has(found.clip.reason)} : null; }, // Seconds the piece will take: this machine's pace from its last piece; unknown before the first. estimate(selection = state.selection) { diff --git a/web/media_upload.js b/web/media_upload.js index c714d1c2..b247d2fe 100644 --- a/web/media_upload.js +++ b/web/media_upload.js @@ -14,6 +14,8 @@ const failures = () => ({ unsupported: text('Choose an image, video or audio file', '请选择图片、视频或音频文件'), multiple: text('Upload one file at a time.', '一次只能上传一个文件。'), invalid: text('This file name cannot be used. Rename the file and try again.', '这个文件名不能使用,请改名后再试。'), + disk_full: text('The upload stopped: the disk is full. Free some space, then try again.', '上传中断:磁盘空间不足,请清理出空间后重试。'), + not_writable: text('The upload stopped: the input folder cannot be written to. Check its write permission, then try again.', '上传中断:输入文件夹无法写入,请检查它的写入权限后重试。'), }); const generic = () => text('The upload did not finish. Try again.', '上传没有完成,请再试一次。'); // A request that never answers is cut off, so the pickers unlock and the failure line shows: two minutes plus four seconds per MiB, so a slow link is not mistaken for a hang. @@ -53,6 +55,6 @@ export async function uploadMedia(api, file, {onProgress = null, timeoutMs = upl result = await response.json(); } catch { if (!response || response.ok) throw new Error(generic()); } finally { clearTimeout(timer); uploadRunning(false); } - if (!response.ok) throw new Error(found[result?.code] || generic()); + if (!response.ok) throw Object.assign(new Error(found[result?.code] || generic()), {code: typeof result?.code === 'string' ? result.code : undefined}); return result; } From 0db1b39e69beb9be9f58af63f15c9bf53d80096b Mon Sep 17 00:00:00 2001 From: Bowen Xue Date: Wed, 18 Nov 2026 02:52:00 +0000 Subject: [PATCH 08/97] Model download: continue when the mount table cannot be read The RAM-backed folder check read the mount table without handling a permission error, so the models step stopped on systems that restrict that file. The check is advisory; an unreadable table now means the type is unknown and the download proceeds. --- freevideo_engine/download_cache.py | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/freevideo_engine/download_cache.py b/freevideo_engine/download_cache.py index df280105..a4b98dd4 100644 --- a/freevideo_engine/download_cache.py +++ b/freevideo_engine/download_cache.py @@ -17,11 +17,15 @@ def mount_type(path, mountinfo=Path('/proc/self/mountinfo')): return None target = Path(path).resolve() matches = [] - for line in mountinfo.read_text(encoding='utf-8').splitlines(): - before, after = line.split(' - ', 1) - mount = Path(re.sub(r'\\([0-7]{3})', lambda m: chr(int(m[1], 8)), before.split()[4])) - if target == mount or mount in target.parents: - matches.append((len(mount.parts), after.split()[0])) + try: + lines = mountinfo.read_text(encoding='utf-8').splitlines() + for line in lines: + before, after = line.split(' - ', 1) + mount = Path(re.sub(r'\\([0-7]{3})', lambda m: chr(int(m[1], 8)), before.split()[4])) + if target == mount or mount in target.parents: + matches.append((len(mount.parts), after.split()[0])) + except (OSError, ValueError, IndexError): + return None # Sandboxed or restricted /proc: the mount type is advisory, so the download proceeds. return max(matches)[1] if matches else None From 45d4e955b75e95647c29fe6b41a2604c46223af6 Mon Sep 17 00:00:00 2001 From: Bowen Xue Date: Wed, 18 Nov 2026 03:00:33 +0000 Subject: [PATCH 09/97] Creation panel: a cleared duration, width or height stays empty, and Generate asks for it and... Creation panel: a cleared duration, width or height stays empty, and Generate asks for it and opens that field The duration stepper no longer brings back the old length when its number is cleared, and the frame panel no longer turns a cleared side into the smallest size. Generate then says which value to fill in and opens the stepper or the frame panel at the empty field. --- web/glass/frame_picker.js | 34 ++++++++++++++++++++++------------ web/studio.js | 14 ++++++++++++-- web/studio_console.js | 12 ++++++++---- 3 files changed, 42 insertions(+), 18 deletions(-) diff --git a/web/glass/frame_picker.js b/web/glass/frame_picker.js index 5da9ff3c..b214983e 100644 --- a/web/glass/frame_picker.js +++ b/web/glass/frame_picker.js @@ -14,7 +14,8 @@ // sizes [{pixels, label?}]: megapixels; a size is named by them (1M, 2M) unless a label is given. Entries marked more are not listed: // any other size is typed as width × height. // sizeFor (ratio, pixels) => {width, height}: the caller's rounding (default: 32-pixel steps, 256–4096 a side). -// custom optional {minSide, maxSide, snap = 32, lock = true}: the width × height fields and the ratio lock. +// custom optional {minSide, maxSide, snap = 32, lock = true, keepEmpty = false}: the width × height fields and the ratio lock. +// keepEmpty: a cleared side stays empty (onChange source 'empty'); without it the side is filled again. // set({limit: {pixels, note?}}): what this computer can make. A typed size above it becomes the largest size // at that shape, and a line under the fields says so. // onChange ({source, side?, shape, ratio, pixels, width, height, locked}) after the user picks ('shape', 'size', @@ -73,7 +74,7 @@ export function createFramePicker({t = en => en, shapes = [], sizes = [], sizeFo onChange = () => {}, onPreview = () => {}, onPaint = () => {}} = {}) { loadStyle(); shapes = shapes.filter(shape => shape.id !== 'custom'); sizes = sizes.filter(size => !size.more); - const state = {shape: shapes[0]?.id ?? null, ratio: shapes[0]?.ratio || 16 / 9, pixels: sizes[0]?.pixels ?? 1, width: 0, height: 0, locked: true, disabled: false, limit: null, custom: false, unavailable: {}, capped: ''}; + const state = {shape: shapes[0]?.id ?? null, ratio: shapes[0]?.ratio || 16 / 9, pixels: sizes[0]?.pixels ?? 1, width: 0, height: 0, locked: true, disabled: false, limit: null, custom: false, unavailable: {}, capped: '', empty: '', ask: false}; const element = el('div', 'fvp'); const emit = (source, side) => onChange({source, side, shape: state.shape, ratio: state.ratio, pixels: state.pixels, width: state.width, height: state.height, locked: state.locked}); const ratioOf = shape => shape.ratio || (shape.id === state.shape ? state.ratio : null) || 1; @@ -100,7 +101,7 @@ export function createFramePicker({t = en => en, shapes = [], sizes = [], sizeFo b.append(art, name); b.setAttribute('aria-label', shape.ratio ? `${shape.label} ${ratioName(shape.ratio)}` : shape.label); b.onclick = () => { if (state.disabled) return; - state.capped = ''; state.shape = shape.id; if (shape.ratio) state.ratio = shape.ratio; Object.assign(state, sizeFor(state.ratio, state.pixels)); + state.capped = ''; state.empty = ''; state.shape = shape.id; if (shape.ratio) state.ratio = shape.ratio; Object.assign(state, sizeFor(state.ratio, state.pixels)); paint(); emit('shape'); }; hover(b, () => { const ratio = ratioOf(shape); return {ratio, ...sizeFor(ratio, state.pixels)}; }); @@ -116,7 +117,7 @@ export function createFramePicker({t = en => en, shapes = [], sizes = [], sizeFo b.append(px, name); b.onclick = () => { if (state.disabled) return; - state.capped = ''; state.pixels = size.pixels; state.custom = false; Object.assign(state, sizeFor(state.ratio, size.pixels)); + state.capped = ''; state.empty = ''; state.pixels = size.pixels; state.custom = false; Object.assign(state, sizeFor(state.ratio, size.pixels)); paint(); emit('size'); }; hover(b, () => ({ratio: state.ratio, ...sizeFor(state.ratio, size.pixels)})); @@ -125,7 +126,7 @@ export function createFramePicker({t = en => en, shapes = [], sizes = [], sizeFo }); let more = null; if (custom) { - const {minSide = 256, maxSide = 4096, snap = 32, lock = true} = custom; + const {minSide = 256, maxSide = 4096, snap = 32, lock = true, keepEmpty = false} = custom; more = {panel: el('div', 'fvp-custom'), width: el('input', 'fvp-dim'), height: el('input', 'fvp-dim'), lock: el('button', 'fvp-lock'), status: el('p', 'fvp-status')}; const {panel, width, height} = more; const field = (input, label, short) => { @@ -142,8 +143,14 @@ export function createFramePicker({t = en => en, shapes = [], sizes = [], sizeFo const fit = v => Math.min(maxSide, Math.max(minSide, Math.round(Number(v) / snap) * snap)); const typed = which => { if (state.disabled) return; - const w = fit(width.value), h = fit(height.value); + // A side left empty stays empty (Generate then asks for it); it is not filled with the smallest size. + // With the ratio locked, a side typed after the other was cleared fills both again. + const other = which === 'width' ? 'height' : 'width', blank = input => !String(input.value).trim(); + if (keepEmpty && blank(more[which])) { state.empty = which; paint(); emit('empty', which); return; } + if (keepEmpty && !state.locked && blank(more[other])) { state[which] = fit(more[which].value); state.empty = other; paint(); emit('empty', other); return; } + const w = fit(keepEmpty ? width.value || state.width : width.value), h = fit(keepEmpty ? height.value || state.height : height.value); if (!(w > 0 && h > 0)) { paint(); return; } + state.empty = ''; if (state.locked) { if (which === 'width') { state.width = w; state.height = fit(w / state.ratio); } else { state.height = h; state.width = fit(h * state.ratio); } } else { state.width = w; state.height = h; state.ratio = w / h; state.shape = 'custom'; } // More than this computer can make: the largest size at this shape is used, and the line under the fields says so. @@ -168,7 +175,7 @@ export function createFramePicker({t = en => en, shapes = [], sizes = [], sizeFo // A size block is lit when the size in force is exactly its size at this frame; otherwise the typed fields are. let preset = false; for (const {b, size, px} of sizeItems) { - const dims = sizeFor(state.ratio, size.pixels), on = dims.width === state.width && dims.height === state.height; + const dims = sizeFor(state.ratio, size.pixels), on = !state.empty && dims.width === state.width && dims.height === state.height; // A size this computer cannot make is listed, greyed, and says so where its pixels would be. const above = state.limit?.pixels > 0 && size.pixels > state.limit.pixels * 1.001; preset ||= on; @@ -180,14 +187,17 @@ export function createFramePicker({t = en => en, shapes = [], sizes = [], sizeFo const {width, height, lock, status, panel, shackle} = more; panel.dataset.on = String(!preset && state.width > 0); width.disabled = height.disabled = lock.disabled = state.disabled; - if (typed || document.activeElement !== width) width.value = String(state.width || ''); - if (typed || document.activeElement !== height) height.value = String(state.height || ''); + if (typed || document.activeElement !== width) width.value = state.empty === 'width' ? '' : String(state.width || ''); + if (typed || document.activeElement !== height) height.value = state.empty === 'height' ? '' : String(state.height || ''); lock.setAttribute('aria-pressed', String(state.locked)); lock.setAttribute('aria-label', state.locked ? t('Ratio locked', '比例锁定') : t('Ratio free', '比例不锁')); shackle.setAttribute('d', state.locked ? 'M5.5 7.5V5.5a2.5 2.5 0 0 1 5 0v2' : 'M5.5 7.5V5.5a2.5 2.5 0 0 1 4.8-1'); const limit = state.limit; - const said = state.capped ? t(`The largest on this computer is ${state.capped}; that size is used.`, `本机最大 ${state.capped},已按最大生成。`) : limit?.note || ''; - status.textContent = said; status.hidden = !said; status.toggleAttribute('data-capped', Boolean(state.capped)); + // Generate stopped on an empty side (the caller sets ask): the panel covers the studio's status line, so it asks here. + if (!state.empty) state.ask = false; + const ask = state.ask && (state.empty === 'height' ? t('Fill in the height.', '请填写高度。') : t('Fill in the width.', '请填写宽度。')); + const said = state.capped ? t(`The largest on this computer is ${state.capped}; that size is used.`, `本机最大 ${state.capped},已按最大生成。`) : ask || limit?.note || ''; + status.textContent = said; status.hidden = !said; status.toggleAttribute('data-capped', Boolean(state.capped || ask)); } onPaint(); } @@ -323,7 +333,7 @@ export function createFrameChip({placement = 'auto', host = null, extra = null, const like = shape || picker.shapes.find(s => s.ratio && Math.abs(s.ratio - state.ratio) < .01); frameName.textContent = like ? (like.ratio ? ratioName(like.ratio) : like.label) : t('Custom', '自定义'); const preset = picker.sizes.find(s => { const d = (options.sizeFor || ((r, p) => frameSize(r, p)))(state.ratio, s.pixels); return d.width === state.width && d.height === state.height; }); - sizeLabel.textContent = preset ? sizeName(preset) : state.width > 0 ? pixelsText(state.width, state.height) : ''; + sizeLabel.textContent = state.empty ? '' : preset ? sizeName(preset) : state.width > 0 ? pixelsText(state.width, state.height) : ''; element.disabled = Boolean(state.disabled); glide(); if (open) place(); } diff --git a/web/studio.js b/web/studio.js index 669ac4eb..b19619a6 100644 --- a/web/studio.js +++ b/web/studio.js @@ -1223,6 +1223,8 @@ export function openStudio(node, {extendFrom = null} = {}) { const width = el('input'), height = el('input'); // Width × height, typed: with the shape kept, the other side follows (32-pixel steps); set free, the shape is custom. let shapeKept = true; + // The side the frame panel's width × height left empty: it stays empty until a size is set again. + let emptySide = ''; const keepShape = button('', () => { shapeKept = !shapeKept; paintKeepShape(); }, 'fvs-keep-shape'); keepShape.append(icon('lock')); function paintKeepShape() { @@ -2479,6 +2481,12 @@ export function openStudio(node, {extendFrom = null} = {}) { [refineSteps, t('Fill in the second-pass steps.', '请填写二采步数。')]]).get(invalid); if (message) { status.dataset.error = 'true'; status.textContent = message; } } + // Width and height are typed in the frame panel: it opens at the empty field. + const side = (invalid === width || invalid === height) && framePicker?.element.checkVisibility() ? [...framePicker.pop.querySelectorAll('.fvp-dim')][invalid === width ? 0 : 1] : null; + if (side) { framePicker.set({empty: emptySide, ask: true}); if (framePicker.pop.dataset.open !== 'true') framePicker.element.click(); side.focus(); return; } + // The duration is typed in the stepper's number: it opens for typing. + const stepValue = invalid === seconds ? dialog.querySelector('.fvs-step-value') : null; + if (stepValue?.checkVisibility()) { stepValue.click(); return; } invalid.focus(); invalid.reportValidity(); return; } // One prompt per line with no lines: say what to write (generating without a prompt is not offered here). @@ -2604,13 +2612,14 @@ export function openStudio(node, {extendFrom = null} = {}) { shapes.dataset.custom = String(shapeIndex < 0); // An empty frame takes the chosen shape; a work on the stage keeps its own (the outline shows the new one). if (!busy && (nextShown || !stageMedia.querySelector('video, img'))) { previewSize(Number(w), Number(h)); if (nextShown) nextSize.textContent = `${w} × ${h}`; } - framePicker?.set({shape: selected, ratio: studioShapes(t).find(([id]) => id === selected)?.[2] || Number(w) / Number(h) || ratio, pixels: Number(mp.value), width: Number(w), height: Number(h), locked: shapeKept, + framePicker?.set({shape: selected, ratio: studioShapes(t).find(([id]) => id === selected)?.[2] || Number(w) / Number(h) || ratio, pixels: Number(mp.value), width: Number(w), height: Number(h), locked: shapeKept, empty: emptySide, unavailable: {input: mediaPicture() ? '' : t('Add a picture in Media first', '先在素材里添加图片')}, disabled: dimensionsLinked || Boolean(extension.source)}); refreshEffortEstimate(); consoleUI?.sync(); } function syncCanvasSize() { + emptySide = ''; width.value = extension.source?.geometry.width ?? value(node, 'width'); height.value = extension.source?.geometry.height ?? value(node, 'height'); updateCanvas(); @@ -2682,12 +2691,13 @@ export function openStudio(node, {extendFrom = null} = {}) { // other size is typed as width × height. sizes: [{pixels: .5, label: '0.5M'}, {pixels: .75, label: '0.75M'}, {pixels: .98, label: '1M'}, {pixels: 1.5, label: '1.5M'}, {pixels: 2, label: '2M'}], sizeFor: (r, p) => { const [w, h] = canvasDimensions(p, r); return {width: w, height: h}; }, - custom: {minSide: 256, maxSide: 4096, snap: 32, lock: true}, + custom: {minSide: 256, maxSide: 4096, snap: 32, lock: true, keepEmpty: true}, onChange: change => { if (change.source === 'shape') [...shapes.children].find(b => b.dataset.ratio === change.shape)?.click(); else if (change.source === 'size') choosePixels(change.pixels); // Typed width × height and the lock go through the panel's own fields, so their rules stay in one place. else if (change.source === 'lock') { if (shapeKept !== change.locked) keepShape.click(); } + else if (change.source === 'empty') { emptySide = change.side; (change.side === 'height' ? height : width).value = ''; } else if (change.source === 'dimensions') { const input = change.side === 'height' ? height : width; input.value = String(change[change.side === 'height' ? 'height' : 'width']); input.onchange(); } updateCanvas(); showNext(); }, diff --git a/web/studio_console.js b/web/studio_console.js index 5741efc9..83f250c9 100644 --- a/web/studio_console.js +++ b/web/studio_console.js @@ -173,8 +173,12 @@ export function durationStepper(t, seconds, {onOpen, max = () => Infinity}) { let done = false; const finish = apply => { if (done) return; done = true; - const n = Number(String(input.value).replace(',', '.')); - if (apply && Number.isFinite(n) && n > 0 && n !== Number(seconds.value)) { + const typed = String(input.value).trim(), n = Number(typed.replace(',', '.')); + // A cleared field leaves the duration empty (Generate then asks for it); the old length does not come back. + if (apply && !typed && seconds.value !== '') { + seconds.value = ''; + seconds.dispatchEvent(new Event('input', {bubbles: true})); seconds.dispatchEvent(new Event('change', {bubbles: true})); + } else if (apply && Number.isFinite(n) && n > 0 && n !== Number(seconds.value)) { seconds.value = String(n); seconds.dispatchEvent(new Event('input', {bubbles: true})); seconds.dispatchEvent(new Event('change', {bubbles: true})); } @@ -190,13 +194,13 @@ export function durationStepper(t, seconds, {onOpen, max = () => Infinity}) { }; void onOpen; function sync() { - const n = Number(seconds.value); + const n = seconds.value === '' ? NaN : Number(seconds.value); const shown = Number.isFinite(n) ? (Number.isInteger(n) ? String(n) : n.toFixed(n < 10 ? 2 : 1).replace(/0+$/, '').replace(/\.$/, '')) : '—'; // The number and its unit apart, so a narrow row can show the number alone; the name says both. const unit = el('span', 'fvs-step-unit', t('s', '秒')); value.replaceChildren(el('span', 'fvs-step-number', shown), unit); value.setAttribute('aria-label', t(`${shown} s`, `${shown} 秒`)); minus.disabled = plus.disabled = seconds.disabled; - minus.disabled ||= n <= 2; + minus.disabled ||= !(n > 2); plus.disabled ||= n >= max(); } seconds.addEventListener('input', sync); seconds.addEventListener('change', sync); From 40292ac002a75ffca898c8bcd116fe8260d4cccc Mon Sep 17 00:00:00 2001 From: Bowen Xue Date: Wed, 18 Nov 2026 03:02:38 +0000 Subject: [PATCH 10/97] H3 Image: plan against the card's free memory on every card, not only beside a resident video worker A picture planned its resident blocks against the whole card (or the caller's limit) unless a resident video worker shared it; another program or this process's own context could hold part of the card, and the plan then overran it. The budget is now always the smaller of the limit and free plus this process's reserved memory, less a kept decoder. The allocator limit stays the caller's limit, so a kept decoder is not counted twice. --- freevideo_engine/image_gen/h3_pipeline.py | 41 ++++++++++++----------- 1 file changed, 21 insertions(+), 20 deletions(-) diff --git a/freevideo_engine/image_gen/h3_pipeline.py b/freevideo_engine/image_gen/h3_pipeline.py index e97783e9..76c334f8 100644 --- a/freevideo_engine/image_gen/h3_pipeline.py +++ b/freevideo_engine/image_gen/h3_pipeline.py @@ -703,27 +703,28 @@ def check(): torch.set_grad_enabled(False) device = torch.device('cuda') total = torch.cuda.get_device_properties(0).total_memory - budget = card_budget(vram_gib) - if shared_card: - # The resident video worker still holds its text encoder on the card after encoding: plan against what - # the card really has free plus what this process already holds, not against its whole size. - free, _ = torch.cuda.mem_get_info() - reserved = torch.cuda.memory_reserved() - budget = min(budget, int(free + reserved)) - # A decoder kept from the previous picture is not part of the next denoise plan. - vae_held = 0 - if kept is not None and 'vae' in kept.items: - vae_held = _tensor_bytes(kept.items['vae'][1]) - budget -= vae_held - # budget = free at plan time + this process's cached memory (reserved) - the kept decoder - stats['budget_parts_gib'] = dict(free=round(free / 2**30, 2), reserved=round(reserved / 2**30, 2), - kept_vae=round(vae_held / 2**30, 2), - allocated=round(torch.cuda.memory_allocated() / 2**30, 2)) - stats['budget_gib'] = round(budget / 2**30, 2) - if kept is not None: - kept.budget = budget + # Plan against what the card really has free plus what this process already holds, never against its whole size + # or the caller's limit alone: a resident video worker's text encoder, another program, or this process's own + # CUDA context may already hold part of it, and the planner fills whatever it is given with resident blocks. + free, _ = torch.cuda.mem_get_info() + reserved = torch.cuda.memory_reserved() + budget = min(card_budget(vram_gib), int(free + reserved)) + # A decoder kept from the previous picture is not part of the next denoise plan. + vae_held = 0 + if kept is not None and 'vae' in kept.items: + vae_held = _tensor_bytes(kept.items['vae'][1]) + budget -= vae_held + # budget = min(limit, free at plan time + this process's cached memory (reserved)) - the kept decoder + stats['budget_parts_gib'] = dict(free=round(free / 2**30, 2), reserved=round(reserved / 2**30, 2), + kept_vae=round(vae_held / 2**30, 2), + allocated=round(torch.cuda.memory_allocated() / 2**30, 2)) + stats['budget_gib'] = round(budget / 2**30, 2) + if kept is not None: + kept.budget = budget if vram_gib: - torch.cuda.set_per_process_memory_fraction(min(1.0, budget / total)) + # The allocator limit is the caller's limit; the plan above already keeps inside the smaller budget, and a + # limit that also left out the kept decoder would count it twice. + torch.cuda.set_per_process_memory_fraction(min(1.0, card_budget(vram_gib) / total)) canvas_h, canvas_w = h3_dit.canvas_size(height, width) if enter is not None: enter('load') From f10d7fa7775b01d64768f0a7feb7803061ba42d2 Mon Sep 17 00:00:00 2001 From: Bowen Xue Date: Wed, 18 Nov 2026 03:03:00 +0000 Subject: [PATCH 11/97] Your creations: after a batch delete the keyboard stays in the library, so Escape still leaves... Your creations: after a batch delete the keyboard stays in the library, so Escape still leaves selecting and the next delete takes only what is picked then When a delete finished, focus outside the library went to the header's Select button, which is hidden since selecting starts from the cards, so it stayed on the page. After a failed delete the failed card stays picked for another try, and Escape, which reaches the library only from inside it, could not leave selecting; a later delete then took that card as well. Focus now goes to the bar's Delete while a card that failed is still picked, and to the library itself otherwise, as when it opens. Nothing on screen changes. tests/browser_library_delete_focus.py: a failed delete leaves focus on Delete inside the library; Escape leaves selecting and clears the picks; the next delete removes only the card picked then; a successful delete keeps focus in the library. --- web/library.js | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/web/library.js b/web/library.js index 6fc3b5cd..8c32afe0 100644 --- a/web/library.js +++ b/web/library.js @@ -1855,8 +1855,11 @@ export function openLibrary(t, options = {}) { } else { undoFailure = ''; setSelecting(false); } render(); showUndo(); - // The delete button is gone; keep the keyboard inside the dialog. - if (!dialog.contains(document.activeElement)) choose.focus(); + // The confirm button is gone; keep the keyboard inside the dialog, so Escape still walks back from here: on the + // bar's Delete while a part that failed is still selected (another try is one press away), on the dialog itself + // otherwise, as when it opened. (The header's Select button is hidden since selecting starts from the cards.) + if (!dialog.contains(document.activeElement) || document.activeElement.closest('[hidden]')) + (selecting && picked.size && !barDelete.hidden ? barDelete : dialog).focus({preventScroll: true}); } // Asks the server about batches this page did not make or cannot vouch for (after a reload, or while a // request of an earlier page still runs), and again until every pending one is settled. From c66a86e949906b7154f3a3cace1499783d111e4f Mon Sep 17 00:00:00 2001 From: Bowen Xue Date: Wed, 18 Nov 2026 03:06:32 +0000 Subject: [PATCH 12/97] Media panel: only its picture button shows the picture tip, other toolbar buttons keep their own --- web/freevideo.js | 2 +- web/tooltip_copy.js | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/web/freevideo.js b/web/freevideo.js index c752fb79..e1d8ef4e 100644 --- a/web/freevideo.js +++ b/web/freevideo.js @@ -213,7 +213,7 @@ function mediaPanel(node, mount = null) { rows.push({file, role: mediaKind(file) === "image" ? use : "reference", enabled: true}); update(rows); } const generateImage = button(text('Generate with AI', 'AI 生成'), text('Generate with AI', 'AI 生成'), () => newImage()); - generateImage.hidden = !imageGenerationSupported(); + generateImage.classList.add('fv-media-generate'); generateImage.hidden = !imageGenerationSupported(); const audioPicker = el('input'); audioPicker.type = 'file'; audioPicker.multiple = true; audioPicker.accept = acceptList(["audio"]); audioPicker.hidden = true; const addAudio = button(text('Reference audio', '参考音频'), diff --git a/web/tooltip_copy.js b/web/tooltip_copy.js index 533b7bfc..4d50e691 100644 --- a/web/tooltip_copy.js +++ b/web/tooltip_copy.js @@ -284,7 +284,7 @@ export const MATCHES = [ ['.fv-action-report,.fv-report-download', 'studio.report'], ['.fv-action-delete>summary', 'studio.delete'], ['.fv-action-second-pass', 'studio.secondPass'], ['.fv-generation-hint-settings', 'studio.hintSettings'], ['.fv-generation-hint-close', 'studio.hintClose'], ['.fv-repair-open', 'common.openSettings'], ['.fv-failure-fold>summary', 'common.details'], ['.fv-failure-copy', 'common.copyDetails'], ['.fv-issue-button', 'common.issue'], - ['.fv-cast-add', 'cast.add'], ['.fv-panel>.fv-toolbar>button', 'cast.generate'], ['.fv-panel>.fv-toolbar select', 'cast.purpose'], ['div.fv-panel[tabindex]', 'cast.drop'], + ['.fv-cast-add', 'cast.add'], ['.fv-media-generate', 'cast.generate'], ['[data-freevideo=media]>.fv-toolbar select', 'cast.purpose'], ['div.fv-panel[tabindex]', 'cast.drop'], // Images. ['.fv-image-go', 'image.generate'], ['.fv-image-add', 'image.addReference'], ['.fv-image-reference-use', 'image.useReference'], From f0b8b089c24c223b1907c9de1defbb42d0ad63ea Mon Sep 17 00:00:00 2001 From: Bowen Xue Date: Wed, 18 Nov 2026 03:08:01 +0000 Subject: [PATCH 13/97] Two-pass: the pinned video model stays resident for the latent upscale when live headroom covers... Two-pass: the pinned video model stays resident for the latent upscale when live headroom covers its small host need, instead of being released and reloaded for the second pass The upscaler stages at most 256 MiB in flight. Against an automatic plan's estimated RAM budget, a plan that pins its weights up to that estimate left no room under it, so the whole pinned engine was released and the second pass pinned it again. Bounded stages are now judged by live headroom; explicit budgets stay strict. --- freevideo_engine/resident_models.py | 30 ++++++++++++++++++++++------- freevideo_engine/resident_worker.py | 3 ++- freevideo_engine/worker.py | 6 +++--- 3 files changed, 28 insertions(+), 11 deletions(-) diff --git a/freevideo_engine/resident_models.py b/freevideo_engine/resident_models.py index 1a55a4a4..06a205a8 100644 --- a/freevideo_engine/resident_models.py +++ b/freevideo_engine/resident_models.py @@ -232,6 +232,8 @@ def __init__(self): self.gpu_budget = None self.gpu_reserve = 0 self.ram_budget = None + # An automatic plan's RAM budget is an estimate (see system.ram_budget_is_estimate). + self.ram_budget_is_estimate = False self.decisions = [] from .streamed_weights import ConvertedStore # Converted decoder layers streamed from the checkpoint; rebuilt on demand. @@ -248,10 +250,12 @@ def __init__(self): self.device_free = None self.device_reserve = 0 - def configure(self, gpu_budget, ram_budget=None, *, gpu_reserve=0): + def configure(self, gpu_budget, ram_budget=None, *, gpu_reserve=0, ram_budget_is_estimate=None): self.gpu_budget = int(gpu_budget) self.gpu_reserve = int(gpu_reserve) self.ram_budget = ram_budget + if ram_budget_is_estimate is not None: + self.ram_budget_is_estimate = bool(ram_budget_is_estimate) self.decisions = [] def take(self, role, identity): @@ -348,14 +352,24 @@ def available(self): return max(0, min(free + torch.cuda.memory_reserved() - allocated - self.gpu_reserve, self.gpu_budget - allocated)) - def ram_fits(self, need=2*GiB): + def ram_fits(self, need=2*GiB, *, bounded=False): + """Whether live RAM takes `need` more bytes beside what this process holds. + + `bounded` marks a stage that stages at most `need` in flight and + releases it at once. Against an automatic plan's estimated budget it + is judged by the live headroom alone: a plan that pinned its weights up + to that estimate leaves no room under it for any stage, and releasing + the whole pinned engine to make that room costs a full reload. An + explicit budget (a capacity test) stays strict. + """ from .ram import ProcessMemory from .system import inference_memory_sample, inference_headroom import os sample = ProcessMemory().sample(os.getpid()) used = inference_memory_sample(sample) return (used is not None and inference_headroom(sample) >= need + 2*GiB and - (self.ram_budget is None or used + need <= self.ram_budget)) + (self.ram_budget is None or (bounded and self.ram_budget_is_estimate) or + used + need <= self.ram_budget)) def settle(self, pinned=0): """Keep as many independent components as the next cold start permits. @@ -494,7 +508,7 @@ def device_ceiling(self): return None return free + torch.cuda.memory_reserved() - def make_room(self, role, peak, *, model=None, ram_need=2*GiB, device=False): + def make_room(self, role, peak, *, model=None, ram_need=2*GiB, device=False, bounded_ram=False): retained = gpu_bytes(model) if model is not None else 0 extra = max(0, int(peak) - retained) # Read once: releasing a model moves its bytes from this pool to the @@ -507,8 +521,10 @@ def available(): if ceiling is not None: room = min(room, max(0, ceiling - torch.cuda.memory_allocated() - reserve)) return room + # Only a bounded stage passes the keyword, so other callers' own ram_fits keep their signature. + fits = (lambda: self.ram_fits(ram_need, bounded=True)) if bounded_ram else (lambda: self.ram_fits(ram_need)) before = available() - if not self.ram_fits(ram_need): + if not fits(): self.converted_store.clear() # Once conditioning is ready the current video cannot use the encoder # again. Reclaim its speculative weights before a VAE needed later in @@ -516,13 +532,13 @@ def available(): def eviction_order(item): return (0 if item == 'encoder' and role != 'encoder' else 1, self.entries[item]['used']) for other in sorted(self.entries, key=eviction_order): - if available() >= extra and self.ram_fits(ram_need): + if available() >= extra and fits(): break if other == role: continue if is_parked(self.entries[other]['model']): # A parked engine holds no GPU memory; only RAM releases it. - if self.ram_fits(ram_need): + if fits(): continue elif self.available() < extra and self.park( other, 'Next %s stage needs GPU memory; host copy kept for the next request' % role, ram_need): diff --git a/freevideo_engine/resident_worker.py b/freevideo_engine/resident_worker.py index 16821745..0f83415f 100644 --- a/freevideo_engine/resident_worker.py +++ b/freevideo_engine/resident_worker.py @@ -76,7 +76,8 @@ def stage(name): if module.endswith('.worker'): from .worker import generate stage('engine_import') - bank.configure(request['gpu_budget_bytes'], request.get('ram_budget_bytes')) + bank.configure(request['gpu_budget_bytes'], request.get('ram_budget_bytes'), + ram_budget_is_estimate=request.get('ram_budget_is_estimate') is True) generate(request, resident=bank) # Only a fully returned video is a success, including its # final cleanup. Keep habit data inside this worker. diff --git a/freevideo_engine/worker.py b/freevideo_engine/worker.py index c486dabf..5fdef416 100644 --- a/freevideo_engine/worker.py +++ b/freevideo_engine/worker.py @@ -512,8 +512,8 @@ def sampling_complete(latents, audio, sampled): # host RAM evicted the second pass's own engine on # tight-RAM machines, which then reloaded every block. from .two_pass import UPSCALER_HOST_BYTES - if need and resident is not None and not resident.ram_fits(UPSCALER_HOST_BYTES): - resident.make_room('latent_upscaler', need, ram_need=UPSCALER_HOST_BYTES) + if need and resident is not None and not resident.ram_fits(UPSCALER_HOST_BYTES, bounded=True): + resident.make_room('latent_upscaler', need, ram_need=UPSCALER_HOST_BYTES, bounded_ram=True) torch.cuda.empty_cache() def upscale_available(): free, _ = torch.cuda.mem_get_info() @@ -554,7 +554,7 @@ def upscale_available(): else: engine.close() if resident is not None: - resident.make_room('latent_upscaler', need, ram_need=UPSCALER_HOST_BYTES) + resident.make_room('latent_upscaler', need, ram_need=UPSCALER_HOST_BYTES, bounded_ram=True) import gc gc.collect() torch.cuda.empty_cache() From 3e4b0bbe10a1b6b5d1c9c50abfd94b3a79c53eed Mon Sep 17 00:00:00 2001 From: Bowen Xue Date: Wed, 18 Nov 2026 03:08:31 +0000 Subject: [PATCH 14/97] Tooltips: a reason a control sets while it is hovered replaces the shown words, and a cleared... Tooltips: a reason a control sets while it is hovered replaces the shown words, and a cleared one clears them --- web/tooltip.js | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/web/tooltip.js b/web/tooltip.js index 0cb1dbec..0b3dc92a 100644 --- a/web/tooltip.js +++ b/web/tooltip.js @@ -320,7 +320,8 @@ function show(element) { if (shown && shown !== element) release(shown); shown = element; // The browser's own tooltip would show the same words a second time. - if (element.hasAttribute('title')) { element.dataset.fvTitle = element.getAttribute('title'); element.removeAttribute('title'); } + // It is left empty rather than removed, so a page that removes it while the tip shows is seen doing so. + if (element.hasAttribute('title')) { element.dataset.fvTitle = element.getAttribute('title'); element.setAttribute('title', ''); } render(content); const box = ensureTip(); box.dataset.motion = reduced() ? 'none' : 'fade'; @@ -337,13 +338,24 @@ function show(element) { function follow(element) { watcher?.disconnect(); if (globalThis.MutationObserver) { - watcher = new MutationObserver(() => { + watcher = new MutationObserver(records => { if (shown !== element) return; + // A title the page sets while the tip shows (Generate's reason, cleared once a prompt is typed) is the tip's + // new words; one with words goes aside like the first, so the browser's own tooltip does not show them too. + // A title the page removes takes its words away, and nothing is put back when the tip goes. + if (records.some(record => record.attributeName === 'title')) { + if (!element.hasAttribute('title')) delete element.dataset.fvTitle; + else { + element.dataset.fvTitle = element.getAttribute('title'); + // Emptying it is the tip's own change, not the page's: its record is dropped. + if (element.dataset.fvTitle) { element.setAttribute('title', ''); watcher.takeRecords(); } + } + } const content = tipContent(element); if (!content) { hideTip({now: true}); return; } render(content); position(element); }); - watcher.observe(element, {attributes: true, attributeFilter: ['disabled', 'aria-disabled', 'data-fv-tip-name', 'data-fv-tip-use', 'data-fv-tip-key', 'data-fv-tip-why', 'data-fv-tip-off', 'data-fv-tip', 'aria-label']}); + watcher.observe(element, {attributes: true, attributeFilter: ['disabled', 'aria-disabled', 'data-fv-tip-name', 'data-fv-tip-use', 'data-fv-tip-key', 'data-fv-tip-why', 'data-fv-tip-off', 'data-fv-tip', 'aria-label', 'title']}); } clearInterval(watch); watch = setInterval(() => { @@ -355,7 +367,8 @@ function follow(element) { function release(element) { if (!element) return; - if (element.dataset.fvTitle !== undefined) { if (!element.hasAttribute('title')) element.setAttribute('title', element.dataset.fvTitle); delete element.dataset.fvTitle; } + // The words go back only where the tip left the title empty; a title the page set or removed since stays as it is. + if (element.dataset.fvTitle !== undefined) { if (element.getAttribute('title') === '') element.setAttribute('title', element.dataset.fvTitle); delete element.dataset.fvTitle; } if (element.dataset.fvDescribedby !== undefined) { const before = element.dataset.fvDescribedby; delete element.dataset.fvDescribedby; if (before) element.setAttribute('aria-describedby', before); else element.removeAttribute('aria-describedby'); From 805f61e8ed64e744782ebc8666223ecfdfbc381d Mon Sep 17 00:00:00 2001 From: Bowen Xue Date: Wed, 18 Nov 2026 03:08:49 +0000 Subject: [PATCH 15/97] AI chat: the downloaded-report card on a failed picture spans the card width The picture failure grid aligns its items to the start, and the report card is an inline-size container, so it shrank to 2 px. Stretch it across the grid column. --- web/autopilot_chat.css | 2 ++ 1 file changed, 2 insertions(+) diff --git a/web/autopilot_chat.css b/web/autopilot_chat.css index 51e1346a..a3038061 100644 --- a/web/autopilot_chat.css +++ b/web/autopilot_chat.css @@ -146,6 +146,8 @@ /* A picture's failure row (Send again, the report) takes the video failure card's button size, not the result bar's 38 px. */ .fv-studio .fv-chat-log .fv-chat-job:is([data-mode=failed],[data-mode=stopped]) .fv-result-links .fv-actions>.fv-action{height:auto;min-width:0;line-height:inherit} .fv-chat-job .fv-report-tip{max-width:100%} +/* The report card spans the picture failure grid (justify-items:start); as an inline-size container it would shrink to nothing. */ +.fv-studio .fv-chat-job:is([data-mode=failed],[data-mode=stopped]) .fv-result-links>.fv-report-tip{justify-self:stretch} .fv-chat-main{grid-template-rows:auto minmax(0,1fr) auto auto} .fv-chat-tools{grid-row:1}.fv-chat-scroll{grid-row:2}.fv-chat-notice-row{grid-row:3}.fv-chat-input{grid-row:4} .fv-chat-input:focus-within{border-color:var(--fv-accent-dim);box-shadow:0 0 0 3px color-mix(in srgb,var(--fv-accent) 13%,transparent)} From 990cd1bd63eb5a48a161a7ce9ce6153f42a3c1ab Mon Sep 17 00:00:00 2001 From: Bowen Xue Date: Wed, 18 Nov 2026 03:09:02 +0000 Subject: [PATCH 16/97] Report tip: in Chinese a clause too long for a narrow line breaks between two words, never... Report tip: in Chinese a clause too long for a narrow line breaks between two words, never before its comma --- web/report_issue.js | 23 +++++++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-) diff --git a/web/report_issue.js b/web/report_issue.js index 7c907941..7e9ecb2b 100644 --- a/web/report_issue.js +++ b/web/report_issue.js @@ -189,6 +189,21 @@ export function showReportTip(bar, anchor, t, {mode = 'invite', submit, onHide = }}})).catch(() => {}); return null; } + // Chinese keeps each clause whole where it fits (keep-all in result_actions.css). Only a clause too long for a + // narrow line gets word boundaries (Intl.Segmenter), so it breaks between two words, never before its comma. + const words = text => { + if (typeof Intl?.Segmenter !== 'function') return [text]; + const parts = []; + for (const run of text.split(/(?<=[,。、;:!?」])/)) { + if ((run.match(/[\u4e00-\u9fff]/g) || []).length <= 12) { parts.push(run); continue; } + let first = true; + for (const {segment} of new Intl.Segmenter('zh', {granularity: 'word'}).segment(run)) { + if (!first && /^[\u4e00-\u9fff]/.test(segment)) parts.push(document.createElement('wbr')); + parts.push(segment); first = false; + } + } + return parts; + }; const tip = el('div', 'fv-report-tip'); tip.setAttribute('role', 'region'); tip.setAttribute('aria-label', t('Send the diagnostic report', '提交诊断报告')); const card = el('div', 'fv-report-tip-card'); @@ -216,14 +231,14 @@ export function showReportTip(bar, anchor, t, {mode = 'invite', submit, onHide = tip.classList.add('fv-report-tip-sent'); anchor.classList.remove('fv-report-attention'); mark.replaceChildren(glyph('done')); title.textContent = t('Last step', '最后一步'); - lead.textContent = savedName?.endsWith('.zip') + lead.replaceChildren(...words(savedName?.endsWith('.zip') ? t(`The report is large, so it was saved as ${savedName}. Please drag it into "Diagnostic report", then select Submit new issue.`, `报告较大,已保存为 ${savedName}。请将它拖入「诊断报告」,再点击 Submit new issue。`) : savedName ? t(`Please drag ${savedName} into "Diagnostic report", then select Submit new issue.`, `请将 ${savedName} 拖入「诊断报告」,再点击 Submit new issue。`) : t('Please drag the downloaded report into "Diagnostic report", then select Submit new issue.', - '请将下载的诊断报告拖入「诊断报告」,再点击 Submit new issue。'); + '请将下载的诊断报告拖入「诊断报告」,再点击 Submit new issue。'))); const link = el('a', null, t("Page didn't open? Open the feedback page", '页面没有打开?点此前往反馈页面')); link.href = address; link.target = '_blank'; link.rel = 'noopener'; note.replaceChildren(link); @@ -240,8 +255,8 @@ export function showReportTip(bar, anchor, t, {mode = 'invite', submit, onHide = } else { title.textContent = t('Share a diagnostic report?', '欢迎提交诊断报告'); } - lead.textContent = t("We'll optimize specifically for your setup, and it helps other users too.", - '我们会针对您的硬件配置进行专门优化,也能帮助其他用户。'); + lead.replaceChildren(...words(t("We'll optimize specifically for your setup, and it helps other users too.", + '我们会针对您的硬件配置进行专门优化,也能帮助其他用户。'))); note.append(glyph('lock', 'fv-report-tip-lock'), t('Hardware, settings and timings only. No prompts, images or videos.', '仅包含硬件信息、生成参数和耗时,不含提示词、参考图或视频。')); const send = el('button', 'fv-action fv-action-primary'); send.type = 'button'; From f08fcaa2cbf51a865ad16f0ae2b21dfd2eb87d52 Mon Sep 17 00:00:00 2001 From: Bowen Xue Date: Wed, 18 Nov 2026 03:09:27 +0000 Subject: [PATCH 17/97] Models that made room for another program load again once the room is free, and opening the... Models that made room for another program load again once the room is free, and opening the picture view loads the picture model where it fits --- freevideo_engine/image_gen/service.py | 32 ++++- freevideo_engine/rewarm.py | 189 ++++++++++++++++++++++++++ freevideo_engine/server_mode.py | 24 +++- web/image_view.js | 11 +- web/image_view_warm.js | 18 ++- 5 files changed, 258 insertions(+), 16 deletions(-) create mode 100644 freevideo_engine/rewarm.py diff --git a/freevideo_engine/image_gen/service.py b/freevideo_engine/image_gen/service.py index 7a1a612c..f53352a7 100644 --- a/freevideo_engine/image_gen/service.py +++ b/freevideo_engine/image_gen/service.py @@ -1277,12 +1277,23 @@ def warm(self, value): picture leaves it. ``mode`` 'eager' (the default) may start a model that is not loaded; 'conservative' only keeps ready a model this worker already holds. Never a job and never in the way of one: skipped while video or a picture is running or queued, while the card is being given to video, or when the plan says the model - does not fit. Nothing about a warm-up shows on the page until a picture is asked for.""" + does not fit. Nothing about a warm-up shows on the page until a picture is asked for. + + ``beside`` (the view was opened, nothing more): a full warm-up only into room that is free; where loading + the model would give back the video models the resident worker keeps, it reads the files ahead instead.""" if (not isinstance(value, dict) or value.get('model') not in image_model.MODELS - or value.get('level', 'light') not in WARM_LEVELS or value.get('mode', 'eager') not in WARM_MODES): + or value.get('level', 'light') not in WARM_LEVELS or value.get('mode', 'eager') not in WARM_MODES + or not isinstance(value.get('beside', False), bool)): raise ValueError('invalid_request') model, level = value['model'], value.get('level', 'light') h3 = model == image_model.H3 + if level == 'full' and value.get('beside'): + # Read before the mutex: it may ask the resident worker what it holds. + try: + if self.takes_video_room(self.installation()[1], model): + level = 'light' + except (OSError, ValueError, RuntimeError): + level = 'light' def skipped(reason): return dict(warm='skipped', reason=reason) @@ -1929,6 +1940,20 @@ def environment(self, root): env.pop(name, None) return env + def takes_video_room(self, machine, model): + """Whether loading ``model`` now would give back what the kept video worker holds, as a picture session does + when it starts: the worker holds more than H3 Image's shared text encoder (or the model is not H3 Image) + and the card has no room for both.""" + from .. import resident_process + owner = resident_process.OWNER + if owner.active or owner.process is None or owner.process.poll() is not None or not owner.endpoint: + return bool(owner.active) + if model == image_model.H3 and self.h3_resident(machine): + held = resident_process.status({resident_process.ENV: str(owner.endpoint)}) + if isinstance(held, dict) and all(row.get('role') == 'encoder' for row in held.get('models') or []): + return False + return not self.server_keeps_video(machine) + def server_keeps_video(self, machine): """With co-residency, whether the video models in the resident worker stay while the picture is made: the card has room for the picture model's files and the picture's reserve beside everything on it now. Where it @@ -2187,7 +2212,8 @@ def respawn(): reason = self.end_reason or ('closed' if self.closed else ('crowded' if keep.CROWDED_LINE in session.tail else 'idle') if session is not None and session.process.poll() == 0 else 'worker_exit') self.end_reason = None - server_mode.released('image', dict(action='released', reason=reason)) + # The model it held comes back when the release only made room (rewarm). + server_mode.released('image', dict(action='released', reason=reason, held=self.loaded_model)) if started_resident and not resident_process.OWNER.active and not server_mode.coresident(): # The picture session started this worker only to hold the encoder between pictures # (with co-residency it stays: it is the video worker too). diff --git a/freevideo_engine/rewarm.py b/freevideo_engine/rewarm.py new file mode 100644 index 00000000..01c5ba9a --- /dev/null +++ b/freevideo_engine/rewarm.py @@ -0,0 +1,189 @@ +"""Bringing a model back once the room it gave up is free again. + +Where idle models stay loaded (``server_mode.keeps_idle``: Linux and Windows), a model lets go when another program +needs the card or host memory runs short, and the picture model when a video needs its room. Without this, it stayed +unloaded until the next job asked for it and paid the whole load then. Now, once that room is free again and has +stayed free for QUIET_SECONDS, the same model is loaded in the background as a warm-up would load it: + +- only into room that is free: the card holds the model's files and the picture reserve beside everything on it now, + and host memory keeps its margin; the other model is never trimmed to make room for it; +- never while a video, a picture or a warm-up runs, or once the model is loaded again by other means; +- at most RELOADS_PER_HOUR times an hour per model, so a program that comes and goes does not make it load over and + over, and only for LIMIT_SECONDS after the release. + +Each return is recorded beside the releases (``server_mode.releases``) with action 'reloaded'. Macs and +FREEVIDEO_KEEP_MODELS=off keep the earlier behaviour. In server mode the picture model's return after a video stays +with server_mode, which loads the configured model. +""" +import logging +import os +import threading +import time + +POLL_SECONDS = 2. +QUIET_SECONDS = 30. +LIMIT_SECONDS = 6 * 3600. +RELOADS_PER_HOUR = 3 +HOST_SPARE_BYTES = 1 << 30 +# The releases that only made room: the model would have stayed. Others (closed, worker_exit, finished, a job's own +# trim, an unreadable card) are not undone. +REASONS = dict(image=('crowded', 'video_start'), video=('other_program_gpu', 'host_memory_low')) +# A warm-up that did not start because a job got there first: try again once it is done. +BUSY = ('busy', 'video_busy') + +_mutex = threading.Lock() +_generation = {} +_reloads = {} + + +def after_release(model, reason, held=None): + """``model`` ('video' or 'image') was released for ``reason``; ``held`` is the picture model it held. Starts the + wait to bring it back and returns the thread, or None when this release is not one to undo.""" + from . import server_mode + if reason not in REASONS.get(model, ()) or not server_mode.keeps_idle(): + return None + if model == 'image' and (not held or (reason == 'video_start' and server_mode.enabled())): + return None + probe = Probe(model, held, reason) + if not probe.ready(): + return None + with _mutex: + generation = _generation[model] = _generation.get(model, 0) + 1 + thread = threading.Thread(target=watch, args=(probe, generation), name='freevideo-rewarm-' + model, daemon=True) + thread.start() + return thread + + +def _allowed(model, now): + with _mutex: + recent = [at for at in _reloads.get(model, ()) if now - at < 3600.] + _reloads[model] = recent + return len(recent) < RELOADS_PER_HOUR + + +def _count(model, now): + with _mutex: + _reloads.setdefault(model, []).append(now) + + +def watch(probe, generation, *, clock=time.monotonic, sleep=time.sleep): + """Wait for quiet room, then load; returns why it ended: 'reloaded', 'replaced' (a newer release of the same + model waits instead), 'off', 'loaded', 'skipped', 'expired'.""" + from .resident_process import OTHER_GPU_GROWTH + model = probe.model + deadline = clock() + LIMIT_SECONDS + since = used = None + while clock() < deadline: + sleep(POLL_SECONDS) + with _mutex: + if _generation.get(model) != generation: + return 'replaced' + try: + if not probe.keeping(): + return 'off' + if probe.loaded(): + return 'loaded' + now_used = None if probe.busy() else probe.room() + except Exception: + logging.warning('[FreeVideo] Reading the room for the %s model failed', model, exc_info=True) + now_used = None + now = clock() + if now_used is None: + since = used = None + continue + # The card's use must hold still: another program still starting or leaving is not room yet. + if since is None or abs(now_used - used) >= OTHER_GPU_GROWTH: + since, used = now, now_used + continue + if now - since < QUIET_SECONDS or not _allowed(model, now): + continue + try: + answer = probe.load() or {} + except Exception: + logging.warning('[FreeVideo] Bringing back the %s model failed', model, exc_info=True) + return 'skipped' + if answer.get('warm') == 'skipped': + if answer.get('reason') in BUSY: + since = used = None + continue + return 'skipped' + _count(model, now) + from . import server_mode + server_mode.reloaded(model, probe.reason) + return 'reloaded' + return 'expired' + + +class Probe: + """What the wait reads and does for one model; the tests replace it.""" + def __init__(self, model, held=None, reason=None): + self.model, self.held, self.reason = model, held, reason + + def services(self): + from . import server_mode + return server_mode._services() + + def ready(self): + videos, images = self.services() + return (videos if self.model == 'video' else images) is not None + + def keeping(self): + from . import server_mode + return server_mode.keeps_idle() + + def busy(self): + from .resident_process import OWNER + videos, images = self.services() + try: + # A warm-up under way (either model) counts: two loads never measure the same free room. + return bool(OWNER.active or (videos is not None and (videos.busy() or videos.alive())) + or (images is not None and (images.busy() or images.loading_full))) + except Exception: + return True + + def loaded(self): + from .resident_process import OWNER + if self.model == 'video': + return OWNER.process is not None and OWNER.process.poll() is None + _, images = self.services() + return images.worker_alive() and images.loaded_model is not None + + def machine(self): + videos, images = self.services() + return (videos if self.model == 'video' else images).installation()[1] + + def need(self, machine): + """Card bytes the model needs free: its files plus the picture reserve.""" + from .image_gen import image_model, keep + if self.model == 'video': + from .video_warm import encoder_file + files = encoder_file(machine) + else: + _, images = self.services() + files = images.warm_files(machine) if self.held == image_model.H3 else images.qwen_files(machine) + size = sum(os.path.getsize(item) for item in files) + return size + keep.RESERVE_BYTES if size > 0 else None + + def room(self): + """The card's used bytes when the model fits now beside everything on it, else None.""" + from .background_room import available_memory + from .resident_process import OWNER, gpu_memory, host_margin + if available_memory() < host_margin() + HOST_SPARE_BYTES: + return None + machine = self.machine() + if self.model == 'image' and OWNER.process is not None and OWNER.process.poll() is None: + # A picture session gives the kept video models back unless they fit beside it: never take them. + _, images = self.services() + if images.takes_video_room(machine, self.held): + return None + memory = gpu_memory(machine.get('gpu_uuid')) + need = self.need(machine) + if not memory or need is None or memory[1] - memory[0] < need: + return None + return memory[0] + + def load(self): + videos, images = self.services() + if self.model == 'video': + return videos.warm(dict(level='full', mode='eager')) + return images.warm(dict(model=self.held, level='full', mode='eager')) diff --git a/freevideo_engine/server_mode.py b/freevideo_engine/server_mode.py index f66a833a..89ec707c 100644 --- a/freevideo_engine/server_mode.py +++ b/freevideo_engine/server_mode.py @@ -12,7 +12,8 @@ model's text encoder and the configured picture model as the server starts, and bringing the picture model back after a video that needed its room. -Every release or trim is recorded with its reason (``releases``), for the running status. +Every release or trim is recorded with its reason (``releases``), for the running status. A model that only made +room for another program, or the picture model for a video, comes back once the room is free again (``rewarm``). """ import logging import os @@ -97,7 +98,7 @@ def image_model(installed, environ=None): def on_release(callback): """Call ``callback(event)`` whenever the video or the picture models are released or trimmed; returns a function - that ends the subscription. ``event``: {'model': 'video' | 'image', 'action': 'released' | 'trimmed', + that ends the subscription. ``event``: {'model': 'video' | 'image', 'action': 'released' | 'trimmed' | 'reloaded', 'reason': str, 'at': unix seconds}. Called on a background thread; it must not block, and what it raises is logged and dropped.""" with _mutex: @@ -122,6 +123,25 @@ def released(model, row): if model == 'image' and event['reason'] == 'video_start' and enabled(): # Until the picture worker can stay through a video, it comes back once the video is done. threading.Thread(target=_after_video, name='freevideo-server-rewarm', daemon=True).start() + if event['action'] == 'released': + try: + from . import rewarm + rewarm.after_release(model, event['reason'], row.get('held')) + except Exception: + logging.warning('[FreeVideo] Could not wait to bring the %s model back', model, exc_info=True) + for callback in listeners: + try: + callback(dict(event)) + except Exception: + logging.warning('[FreeVideo] A server release listener failed', exc_info=True) + + +def reloaded(model, reason): + """``model`` was loaded again after a release for ``reason`` (by rewarm), recorded beside the releases.""" + event = dict(model=model, action='reloaded', reason=str(reason or 'unknown'), at=time.time()) + with _mutex: + _releases[:] = (_releases + [event])[-RELEASES_KEPT:] + listeners = list(_listeners) for callback in listeners: try: callback(dict(event)) diff --git a/web/image_view.js b/web/image_view.js index 1322ceb8..eef69193 100644 --- a/web/image_view.js +++ b/web/image_view.js @@ -33,6 +33,7 @@ import { COMPARE_MAX, compareView } from './image_view_compare.js'; import { queuePanel } from './image_view_queue.js'; import { isHeld, worksClient, saveToWorks } from './image_works.js'; import { createWarmer } from './image_view_warm.js'; +import { preloadMode } from './preload_setting.js'; import { openPictureViewer } from './image_view_viewer.js'; import { LORA_MODEL, imageViewLora } from './image_view_lora.js'; import { hasPictureThumbnail, mediaQueue, pictureThumbnailURL } from './work_media.js'; @@ -224,7 +225,7 @@ export function openImageView(node, {studio = null, client: given = null, poll = else shownFile = rows[0]?.file || ''; // The model made ready ahead (image_view_warm.js); only the model and the level go to the engine. const warmer = createWarmer({getToken: async () => info?.token || ''}); - function warmUp(level) { if (alive && !running && modelState(info, model.id).state === 'ready') warmer.warm(model.id, level); } + function warmUp(level, beside = false) { if (alive && !running && modelState(info, model.id).state === 'ready') warmer.warm(model.id, level, {beside}); } const entry = () => info?.models?.find(m => m.id === model.id) || null; const missing = () => entry() ? entry().ready === false : false; const loading = () => modelState(info, model.id).state === 'downloading'; @@ -1359,9 +1360,11 @@ export function openImageView(node, {studio = null, client: given = null, poll = }; go.addEventListener('click', () => { if (drawer === 'left' && go.dataset.state === 'ready' && (prompt.value.trim() || references.length)) { drawer = ''; paintPanels(); } }, {capture: true}); prompt.addEventListener('input', () => { growPrompt(); render(); }); - // Getting the model ready before Generate is pressed (nothing of it shows): being here a few seconds or touching - // anything says "light"; a prompt being written, a model or shape chosen, or the pointer on Generate says "full". - const warmSoon = setTimeout(() => warmUp('light'), 3000); + // Getting the model ready before Generate is pressed (nothing of it shows): being here a few seconds loads the model + // where the card has free room for it (eager loading; the engine reads the files ahead where it would take the + // video models' room, and the conservative setting keeps it to that); touching anything says "light"; a prompt + // being written, a model or shape chosen, or the pointer on Generate says "full". + const warmSoon = setTimeout(() => preloadMode() === 'eager' ? warmUp('full', true) : warmUp('light'), 3000); let warmTyping = 0; prompt.addEventListener('input', () => { clearTimeout(warmTyping); warmTyping = setTimeout(() => { if (prompt.value.trim()) warmUp('full'); }, 500); }); for (const type of ['pointerdown', 'keydown']) dialog.addEventListener(type, () => warmUp('light'), {capture: true, passive: true}); diff --git a/web/image_view_warm.js b/web/image_view_warm.js index aa903d93..ced280c9 100644 --- a/web/image_view_warm.js +++ b/web/image_view_warm.js @@ -1,7 +1,8 @@ // Getting the image model ready before Generate is pressed: the page tells the engine what the user is likely to -// make next, nothing more (the model, how far to go: "light" or "full", and the user's preload setting; never the -// prompt or the pictures). The setting (Settings › Advanced, key freevideo.preload) is 'eager' unless set to -// 'conservative'; the page asks as before either way and the engine decides. +// make next, nothing more (the model, how far to go: "light" or "full", whether only free room may be used, and the +// user's preload setting; never the prompt or the pictures). The setting (Settings › Advanced, key +// freevideo.preload) is 'eager' unless set to 'conservative'; the page asks as before either way and the engine +// decides. // Nothing of it shows on the page; when Generate is pressed the progress simply starts from where the engine got to. // An engine without the warm call answers 404 once and is not asked again. import { IMAGE_GEN_PROTOCOL } from './image_generation.js'; @@ -26,12 +27,15 @@ export function createWarmer({getToken, fetchImpl = (...args) => globalThis.fetc } return { // At most once per model and level every two seconds; a full warm also stands for a light one. - warm(model, level = 'light') { + // beside: the view was only opened, so the engine loads the model only into free room (never in place of + // the video models it keeps) and otherwise reads the files ahead. + warm(model, level = 'light', {beside = false} = {}) { if (absent || !model) return false; const at = now(), seen = key => at - (last.get(key) ?? -Infinity) < WARM_GAP_MS; - if (seen(`${model}|${level}`) || (level === 'light' && seen(`${model}|full`))) return false; - last.set(`${model}|${level}`, at); - void send('warm', {model, level, mode: preloadMode()}); + const key = beside && level === 'full' ? 'beside' : level; + if (seen(`${model}|${key}`) || (level === 'light' && seen(`${model}|full`))) return false; + last.set(`${model}|${key}`, at); + void send('warm', {model, level, mode: preloadMode(), ...(key === 'beside' ? {beside: true} : {})}); return true; }, // Leaving the view: what was being made ready can stop (sent even as the page goes away). From 5bc407171313cee2bcc9193645475f3f2760a768 Mon Sep 17 00:00:00 2001 From: Bowen Xue Date: Wed, 18 Nov 2026 03:11:39 +0000 Subject: [PATCH 18/97] Editor writes only what changes while the playhead moves Every playhead move refreshed the transport buttons, the preview, the picture tools, the text layer, the button tips and the media library, writing each attribute and text again even when the value was the same. Each such write made the browser restyle around the element, and the editor's :has() rules carried that to the whole view, so scrubbing on slower machines ran at about half the frame rate. These refreshes now write a value only when it changes, and a changing label updates its text in place. --- web/dom_quiet.js | 18 ++++++++++++++++++ web/editor.js | 3 ++- web/editor_library.js | 12 ++++++------ web/editor_player.js | 13 +++++++------ web/editor_preview_picture.js | 5 +++-- web/editor_text.js | 7 ++++--- web/editor_tips.js | 7 +++++-- web/editor_tracks.js | 5 +++-- web/editor_transport.js | 17 +++++++++-------- web/glass/media_tray.js | 5 +++-- web/glass/stage_light.js | 3 ++- 11 files changed, 62 insertions(+), 33 deletions(-) create mode 100644 web/dom_quiet.js diff --git a/web/dom_quiet.js b/web/dom_quiet.js new file mode 100644 index 00000000..5d494132 --- /dev/null +++ b/web/dom_quiet.js @@ -0,0 +1,18 @@ +// Writes that leave a value as it was still make the page restyle around the element, and rules such as :has() carry +// that to the whole view. Refreshes that run on every playhead move write through these, so only real changes reach the page. +export function setHidden(node, value) { if (node && node.hidden !== !!value) node.hidden = !!value; } +export function setDisabled(node, value) { if (node && node.disabled !== !!value) node.disabled = !!value; } +// A lone text child is changed in place: a replaced child counts as an insertion, which :has() rules also follow. +export function setText(node, text) { + if (!node || node.textContent === text) return; + const only = node.firstChild; + if (only && only === node.lastChild && only.nodeType === 3 && text) only.data = text; else node.textContent = text; +} +// null or undefined removes the attribute. A node that cannot be read (a test stand-in) is always written. +export function setAttr(node, name, value) { + if (!node) return; + const current = typeof node.getAttribute === 'function' ? node.getAttribute(name) : undefined; + if (value == null) { if (current !== null) node.removeAttribute(name); } + else if (current !== String(value)) node.setAttribute(name, String(value)); +} +export function setData(node, key, value) { if (node && node.dataset[key] !== String(value)) node.dataset[key] = String(value); } diff --git a/web/editor.js b/web/editor.js index acedd67d..c72a7ceb 100644 --- a/web/editor.js +++ b/web/editor.js @@ -54,6 +54,7 @@ import {tip, modKey} from './editor_tips.js'; import {jobs} from './task_store.js'; import {openingChoice} from './editor_opening.js'; import {CN} from './topbar_state.js'; +import {setDisabled} from './dom_quiet.js'; const editorStyles = Promise.all(['result_actions.css', 'editor.css', 'editor_expand.css', 'editor_tracks.css', 'editor_frame.css', 'editor_adjust.css', 'editor_adjust_picture.css', 'editor_preview_picture.css', 'editor_select.css', 'editor_menu.css', 'editor_text.css', 'editor_notes.css', 'editor_transport.css', 'glass/editor.css'].map(name => { const style = document.createElement('link'); style.rel = 'stylesheet'; style.href = new URL(name, import.meta.url).href; const ready = 'sheet' in style ? new Promise(resolve => { style.onload = style.onerror = resolve; }) : Promise.resolve(); @@ -1952,7 +1953,7 @@ export function openEditor({api, app, from = null, panel = {}, components: given }); } function updateSplit() { - const ids = splitIds(), busy = ids.some(id => model.pair(state.record, id).some(isBusy)); split.disabled = !ids.length || busy; + const ids = splitIds(), busy = ids.some(id => model.pair(state.record, id).some(isBusy)); setDisabled(split, !ids.length || busy); tip(split, {name: t('Split', '剪开'), use: t('Cut the clip in two at the playhead', '在播放头处把片段分成两段'), key: `B / ${modKey}B`, why: !split.disabled ? '' : busy ? t('This part is generating', '这一段正在生成') : t('Put the playhead inside a clip first', '先把播放头放到片段中间')}); } diff --git a/web/editor_library.js b/web/editor_library.js index 74236d44..94f06205 100644 --- a/web/editor_library.js +++ b/web/editor_library.js @@ -3,6 +3,7 @@ import {sourceKey} from './editor_store.js'; import {issueButton} from './issue_button.js'; import {connectionLostText} from './browser_extension.js'; import {tip} from './editor_tips.js'; +import {setAttr, setData, setHidden} from './dom_quiet.js'; const LIBRARY_ISSUE = ['Editor media library', '剪辑器素材库']; const el = (tag, cls, text) => { const e = document.createElement(tag); if (cls) e.className = cls; if (text != null) e.textContent = text; return e; }; const stamp = frames => { const seconds = Math.floor((frames || 0) / 24); return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, '0')}`; }; @@ -214,7 +215,7 @@ export function createEditorLibrary(host, {store, t, actions, state}) { function updateUsed() { const keys = new Set((state?.record.tracks || []).flatMap(track => track.clips) .filter(clip => clip.source).map(clip => sourceKey(clip.source))); - for (const button of grid.querySelectorAll('.fv-ed-source')) button.querySelector('.fv-ed-source-used').hidden = !keys.has(button.dataset.key); + for (const button of grid.querySelectorAll('.fv-ed-source')) setHidden(button.querySelector('.fv-ed-source-used'), !keys.has(button.dataset.key)); } // What a card shows, for reusing it: everything card() reads except the picture's address (a picture already // decoded is kept), plus the removal question when one is open. @@ -229,9 +230,8 @@ export function createEditorLibrary(host, {store, t, actions, state}) { const scroll = host.scrollTop || 0, top = host.getBoundingClientRect().top; const anchor = scroll > 0 ? [...grid.querySelectorAll('.fv-ed-source')].find(node => node.getBoundingClientRect().bottom > top) : null; const anchorTop = anchor?.getBoundingClientRect().top; - works.setAttribute('aria-selected', String(tab === 'work')); imports.setAttribute('aria-selected', String(tab === 'import')); - works.setAttribute('aria-pressed', String(tab === 'work')); imports.setAttribute('aria-pressed', String(tab === 'import')); - search.hidden = tab !== 'work'; + for (const [button, value] of [[works, tab === 'work'], [imports, tab === 'import']]) { setAttr(button, 'aria-selected', value); setAttr(button, 'aria-pressed', value); } + setHidden(search, tab !== 'work'); // A redraw (the imports are read again every few seconds) keeps the focus on the same control. const held = document.activeElement, strip = held && grid.contains?.(held) ? held.closest?.('.fv-ed-source-confirm') : null; const control = ['fv-ed-source-remove', 'fv-ed-source-add'].find(name => held?.className === name); @@ -280,7 +280,7 @@ export function createEditorLibrary(host, {store, t, actions, state}) { : target.card ? card(target.card) : (target.next && card(target.next)) || (tab === 'import' ? importButton : null); node?.focus?.(); } - globalThis.requestAnimationFrame?.(() => { if (!disposed) host.dataset.atEnd = String(host.scrollTop + host.clientHeight >= host.scrollHeight - 2); }); + globalThis.requestAnimationFrame?.(() => { if (!disposed) markEnd(); }); if (scroll > 0) { const replacement = anchor && [...grid.querySelectorAll('.fv-ed-source')].find(node => node.dataset.key === anchor.dataset.key); host.scrollTop = replacement ? scroll + replacement.getBoundingClientRect().top - anchorTop : scroll; @@ -359,7 +359,7 @@ export function createEditorLibrary(host, {store, t, actions, state}) { } host.addEventListener('scroll', scheduleMore, {passive: true}); // The last row cut by the pane's foot fades out (24 px) instead of looking cut off; at the very end there is no fade. - const markEnd = () => { host.dataset.atEnd = String(host.scrollTop + host.clientHeight >= host.scrollHeight - 2); }; + function markEnd() { setData(host, 'atEnd', host.scrollTop + host.clientHeight >= host.scrollHeight - 2); } host.addEventListener('scroll', markEnd, {passive: true}); const resize = new ResizeObserver(scheduleMore); resize.observe(host); // Files dropped on the tracks go to the drop point once ready, in drop order. diff --git a/web/editor_player.js b/web/editor_player.js index aa4ba4de..7233656c 100644 --- a/web/editor_player.js +++ b/web/editor_player.js @@ -9,6 +9,7 @@ import {createAudioPreview, isOriginalSound} from './editor_audio.js'; import {previewSpeed, speedAudioFrame, separateSpeedAudio} from './editor_speed.js'; import {sourceFrame, percent} from './editor_speed_model.js'; import {applyTip} from './editor_tracks_tips.js'; +import {setAttr, setData, setDisabled, setHidden, setText} from './dom_quiet.js'; const el = (tag, cls) => { const e = document.createElement(tag); if (cls) e.className = cls; return e; }; export function audioSeconds(clip, sourceFrame) { // The chain receipt counts samples at 32 kHz, even if the media is 48 kHz. @@ -284,16 +285,16 @@ export function createEditorPlayer(host, transport, {state, sources, api, t, err // The total is what export writes (picture and sound); text past it is not exported. const record = state.record, position = state.playhead, total = model.exportFrames(record); const hasContent = record.tracks.some(track => track.clips.some(clip => clip.source || isText(clip))); - empty.hidden = hasContent || preview?.tagName === 'VIDEO'; frame.dataset.empty = String(!empty.hidden); - playButton.disabled = !total || !hasContent; - time.textContent = `${transportTime(position)} / ${transportTime(total)}`; - transport.dataset.rate = String(playing ? playback.rate : 0); + setHidden(empty, hasContent || preview?.tagName === 'VIDEO'); setData(frame, 'empty', !empty.hidden); + setDisabled(playButton, !total || !hasContent); + setText(time, `${transportTime(position)} / ${transportTime(total)}`); + setData(transport, 'rate', playing ? playback.rate : 0); if (playButton.dataset.playing !== String(playing)) { playButton.dataset.playing = String(playing); const glyph = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); glyph.setAttribute('viewBox', '0 0 16 16'); glyph.setAttribute('aria-hidden', 'true'); glyph.style.width = glyph.style.height = '16px'; const path = document.createElementNS(glyph.namespaceURI, 'path'); path.setAttribute('d', playing ? 'M4 3h3v10H4zM9 3h3v10H9z' : 'm5 3 8 5-8 5z'); path.setAttribute('fill', 'currentColor'); glyph.append(path); playButton.replaceChildren(glyph); } - playButton.setAttribute('aria-label', playing ? t('Pause', '暂停') : t('Play', '播放')); + setAttr(playButton, 'aria-label', playing ? t('Pause', '暂停') : t('Play', '播放')); applyTip(playButton, playing ? 'pause' : 'play', t, {why: playButton.disabled ? t('Put a clip on the timeline first', '先在时间线上放一段素材') : ''}); const shown = Math.min(position, Math.max(0, model.duration(record) - 1)); const map = located(record, shown), videoRow = pictureEdit.previewRow(map.get('v1'), shown), clip = videoRow?.clip; @@ -427,7 +428,7 @@ export function createEditorPlayer(host, transport, {state, sources, api, t, err raf = requestAnimationFrame(tick); } const pictureLayout = record => JSON.stringify([record.width, record.height, record.tracks, record.replacements]); - function clearPreview() { if (preview) { preview.onended = null; preview.pause(); preview.removeAttribute('src'); preview.load(); preview.remove(); preview = null; } previewSize = previewProject = null; closePreview.hidden = true; } + function clearPreview() { if (preview) { preview.onended = null; preview.pause(); preview.removeAttribute('src'); preview.load(); preview.remove(); preview = null; } previewSize = previewProject = null; setHidden(closePreview, true); } closePreview.onclick = () => { clearPreview(); render(); }; function play() { if (disposed || playing || playButton.disabled) return; diff --git a/web/editor_preview_picture.js b/web/editor_preview_picture.js index a8cf592d..dde77003 100644 --- a/web/editor_preview_picture.js +++ b/web/editor_preview_picture.js @@ -2,6 +2,7 @@ import {plan, cssTransform, visibleRect} from './editor_geometry.js'; import {differentPictureShape} from './editor_frame.js'; import {PICTURE_DEFAULTS} from './editor_picture_fields.js'; import {pictureSession} from './editor_picture_session.js'; +import {setHidden} from './dom_quiet.js'; const metrics = new WeakMap(); export function previewPictureTimings(state, reset = false) { const value = metrics.get(state) || {draw: [], layout: []}; @@ -82,8 +83,8 @@ export function createPreviewPicture(host, frame, {state, t}) { && state.selection.ids.every(id => id === clip.id || id === clip.link); const editable = clip => isSelected(clip) && session.canEdit(clip); function reset() { - for (const node of [bed, outside, shade, handles, cropBox, ...lines]) node.hidden = true; - shade.style.display = 'none'; + for (const node of [bed, outside, shade, handles, cropBox, ...lines]) setHidden(node, true); + if (shade.style.display !== 'none') shade.style.display = 'none'; frame.classList.remove('fv-ed-picture-adjusted'); layout = null; key = ''; inputs = drawn = null; frame.querySelectorAll('video').forEach(v => { if (!v.matches('.fv-ed-source-preview')) v.removeAttribute('style'); }); } diff --git a/web/editor_text.js b/web/editor_text.js index 7e4751c3..711e1f3b 100644 --- a/web/editor_text.js +++ b/web/editor_text.js @@ -12,6 +12,7 @@ import {issueButton} from './issue_button.js'; import {skinSelect} from './fv_select.js'; import {tip} from './editor_tips.js'; import {registerMenuItem} from './editor_menu.js'; +import {setAttr, setData, setHidden, setText} from './dom_quiet.js'; const SPEECH_ISSUE = ['Auto subtitles', '自动字幕'], FONT_ISSUE = ['Editor text fonts', '剪辑器文字字体']; const el=(tag,cls,text)=>{const e=document.createElement(tag);if(cls)e.className=cls;if(text!=null)e.textContent=text;return e;}; const clamp=(v,lo,hi)=>Math.max(lo,Math.min(hi,v)); @@ -255,7 +256,7 @@ export function createEditorText({element,state,t,actions,adjust,player,toolbar, function updateWarnings(){ const r=record(),c=selectedText(),s=c&&styleOf(r,model.find(r,c.id)); const missing=projectMissing(r),chars=[...new Set(missing.flatMap(r=>r.chars))]; - notice.hidden=!chars.length&&!loadError;notice.textContent=loadError?fontFailure():missingHint(chars,t);notice.title=notice.textContent; + setHidden(notice,!chars.length&&!loadError);setText(notice,loadError?fontFailure():missingHint(chars,t));setAttr(notice,'title',notice.textContent); for(const [kind,p]of panels){ if(c?.text_kind!==kind)continue; const entry=model.find(r,c.id),absent=table?missingGlyphs(entry.text,s.font,!!s.bold,table):[]; @@ -319,8 +320,8 @@ export function createEditorText({element,state,t,actions,adjust,player,toolbar, if(element.dataset.textAudio2!==audio2)element.dataset.textAudio2=audio2; if(!ready&&record().tracks.some(isTextTrack))ensureFonts(); const entries=textEntries(),c=selectedText(),r=record(),sourcePreview=frame.querySelector('.fv-ed-source-preview'); - canvas.hidden=!ready||(!entries.length&&!c)||!!sourcePreview; - frame.dataset.textSelected=String(!!c&&!sourcePreview); + setHidden(canvas,!ready||(!entries.length&&!c)||!!sourcePreview); + setData(frame,'textSelected',!!c&&!sourcePreview); if(canvas.hidden){boundsLayer.replaceChildren();return;} mapped=frameMap();const {x,y,w,h,cw,ch}=mapped; if(canvas.width!==cw)canvas.width=cw;if(canvas.height!==ch)canvas.height=ch;ctx.clearRect(0,0,cw,ch); diff --git a/web/editor_tips.js b/web/editor_tips.js index cc699b6e..8efa37bf 100644 --- a/web/editor_tips.js +++ b/web/editor_tips.js @@ -1,13 +1,16 @@ // Hover and focus help for the editor's controls: a name, one line on what it does, its key, and when the control is // greyed the reason and how to clear it. The page-wide tooltip (tooltip.js) reads the data-fv-tip-* attributes; the // native title is dropped so two tips never show at once. +import {setAttr} from './dom_quiet.js'; + export const modKey = typeof navigator !== 'undefined' && /Mac|iPhone|iPad/i.test(navigator.userAgentData?.platform || navigator.platform || '') ? '⌘' : 'Ctrl+'; export function tip(element, {name = '', use = '', key = '', why = ''} = {}) { if (!element) return element; - const set = (attribute, value) => { if (value) element.setAttribute(attribute, value); else element.removeAttribute(attribute); }; + // Refreshed on every playhead move: an unchanged tip is left as it is. + const set = (attribute, value) => setAttr(element, attribute, value || null); set('data-fv-tip-name', name); set('data-fv-tip-use', use); set('data-fv-tip-key', key); set('data-fv-tip-why', why); - element.removeAttribute('title'); + set('title', null); return element; } diff --git a/web/editor_tracks.js b/web/editor_tracks.js index aebc1d05..fbfc6fbb 100644 --- a/web/editor_tracks.js +++ b/web/editor_tracks.js @@ -17,6 +17,7 @@ import {renderSpeedBadge} from './editor_speed.js'; import {speedEdited} from './editor_speed_model.js'; import {MUSIC_TRACK, MAX_MUSIC_FRAMES} from './editor_music_model.js'; import {applyTip, switchTip, setTip} from './editor_tracks_tips.js'; +import {setAttr, setData, setHidden, setText} from './dom_quiet.js'; // A range drawn on the music track alone: music for that stretch. const musicRange = selection => selection?.kind === 'range' && selection.tracks?.length === 1 && selection.tracks[0] === MUSIC_TRACK; @@ -463,7 +464,7 @@ export function createTracks(host, {state, sources = {}, t = en => en, actions = playhead.style.left = `${x}px`; // Near time zero the 28 px grip moves right so it stays clear of the heads; the drawn tab stays on the line. playhead.style.setProperty?.('--fv-ed-handle-shift', `${Math.max(0, Math.min(14, 6 - x))}px`); - handle.setAttribute('aria-label', `${t('Play position', '播放位置')}, ${clock(state.playhead)}`); + setAttr(handle, 'aria-label', `${t('Play position', '播放位置')}, ${clock(state.playhead)}`); } function renderRuler() { const {minor, major} = tickSpacing(state.zoom); @@ -741,7 +742,7 @@ export function createTracks(host, {state, sources = {}, t = en => en, actions = // While the playhead is dragged, its time (to a tenth) rides above it on the ruler. function showTime() { const bounds = element.getBoundingClientRect(), x = content.getBoundingClientRect().left - bounds.left + pixels(state.playhead); - tooltip.textContent = preciseClock(state.playhead); tooltip.hidden = false; tooltip.dataset.time = 'true'; + setText(tooltip, preciseClock(state.playhead)); setHidden(tooltip, false); setData(tooltip, 'time', 'true'); tooltip.style.left = `${clamp(x + 10, 8, Math.max(8, bounds.width - 80))}px`; tooltip.style.top = '28px'; } function showGuide(frame) { guide.hidden = frame == null; if (frame != null) guide.style.left = `${pixels(frame)}px`; } diff --git a/web/editor_transport.js b/web/editor_transport.js index bf00134c..e3d6d42e 100644 --- a/web/editor_transport.js +++ b/web/editor_transport.js @@ -2,6 +2,7 @@ import * as model from './editor_model.js'; import {applyTip, tipCopy} from './editor_tracks_tips.js'; import {addMarker, hasMarker, moveMarker, removeMarker, selectedRange, shuttleRate, setSnapping, snappingEnabled, transportSnapPoints} from './editor_transport_model.js'; +import {setAttr, setData, setDisabled} from './dom_quiet.js'; // Other editor features can register rows before the sheet opens. export const shortcuts = []; @@ -144,24 +145,24 @@ export function createEditorTransport({element, preview, transport, toolbar, edi const selection = () => selectedRange(state.record, state.selection, model.duration(state.record)); function refresh() { if (disposed) return; - loop.setAttribute('aria-pressed', String(clock.loop)); - snapping.setAttribute('aria-pressed', String(snappingEnabled(state))); - const bounds = selection(); range.disabled = !bounds; + setAttr(loop, 'aria-pressed', clock.loop); setAttr(snapping, 'aria-pressed', snappingEnabled(state)); + const bounds = selection(); setDisabled(range, !bounds); applyTip(range, 'playRange', t, {why: bounds ? '' : t('Select a clip or draw a range first', '先选中片段或画一段范围')}); - range.setAttribute('aria-pressed', String(!!clock.range)); + setAttr(range, 'aria-pressed', !!clock.range); const total = model.duration(state.record); - toStart.disabled = back.disabled = !total || state.playhead <= 0; toEnd.disabled = forward.disabled = !total || state.playhead >= total; + for (const button of [toStart, back]) setDisabled(button, !total || state.playhead <= 0); + for (const button of [toEnd, forward]) setDisabled(button, !total || state.playhead >= total); const empty = t('The timeline is empty', '时间线是空的'); applyTip(toStart, 'start', t, {why: toStart.disabled ? (total ? t('Already at the start', '已经在开头') : empty) : ''}); applyTip(back, 'previousFrame', t, {why: back.disabled ? (total ? t('Already at the start', '已经在开头') : empty) : ''}); applyTip(forward, 'nextFrame', t, {why: forward.disabled ? (total ? t('Already at the end', '已经在结尾') : empty) : ''}); applyTip(toEnd, 'end', t, {why: toEnd.disabled ? (total ? t('Already at the end', '已经在结尾') : empty) : ''}); if (frame) { - frame.disabled = savingFrame || !model.exportFrames(state.record); + setDisabled(frame, savingFrame || !model.exportFrames(state.record)); applyTip(frame, 'saveFrame', t, {why: savingFrame ? t('Saving this frame…', '正在保存这一帧…') : frame.disabled ? t('There is no picture to save yet', '还没有可以保存的画面') : ''}); } - fullscreen.setAttribute('aria-pressed', String(document.fullscreenElement === fullHost)); - transport.dataset.rate = String(player.playing ? clock.rate : 0); + setAttr(fullscreen, 'aria-pressed', document.fullscreenElement === fullHost); + setData(transport, 'rate', player.playing ? clock.rate : 0); if (layer && !drag) renderMarkers(); } function renderMarkers() { diff --git a/web/glass/media_tray.js b/web/glass/media_tray.js index 197fefc3..12e4822d 100644 --- a/web/glass/media_tray.js +++ b/web/glass/media_tray.js @@ -10,6 +10,7 @@ // into the line under it, the remark into a line with its key, and the drop-down for new pictures into the title row. import './tray_pop.js'; import { mediaQueue } from '../work_media.js'; +import {setHidden} from '../dom_quiet.js'; const CARD_KEYS = {'↑': 'fv-mt-up', '↓': 'fv-mt-down'}; // How many saved works the works page lists (newest first, pictures and videos together). @@ -388,8 +389,8 @@ function markNow(panel) { card.querySelector('.fv-mt-held-note')?.remove(); if (held) (card.querySelector('.fv-preview-wrap') || card).append(make('span', 'fv-mt-held-note', say(panel, 'Not used with frames', '不与首尾帧同用'))); } - panel.fvMtMix.hidden = !blocked; - panel.fvMtRemark.hidden = Boolean(!note || note.hidden) && !blocked; + setHidden(panel.fvMtMix, !blocked); + setHidden(panel.fvMtRemark, Boolean(!note || note.hidden) && !blocked); if (tray && !tray.fvMtPaged) { tray.fvMtPaged = true; showPage(panel, 'media'); // Placed by tray_pop.js: measured with the scrolling parts at their full height, then fitted to the window. diff --git a/web/glass/stage_light.js b/web/glass/stage_light.js index 2e1965b4..8af117b9 100644 --- a/web/glass/stage_light.js +++ b/web/glass/stage_light.js @@ -139,7 +139,8 @@ function dress() { const box = document.createElement('div'); box.className = 'fv-look-light'; box.setAttribute('aria-hidden', 'true'); dialog.prepend(box); } - root.dataset.fvLight = raw ? 'on' : 'off'; + // On the page root: an unchanged value is left alone, or the whole page would restyle. + if (root.dataset.fvLight !== (raw ? 'on' : 'off')) root.dataset.fvLight = raw ? 'on' : 'off'; } let timer = 0, theme = root.dataset.theme; From b40c3b1e62f38c3038696bcfaf69b994e0c2255c Mon Sep 17 00:00:00 2001 From: Bowen Xue Date: Wed, 18 Nov 2026 03:17:13 +0000 Subject: [PATCH 19/97] Touch screens show the actions that a mouse reveals on hover --- web/editor_audio.css | 1 + web/glass/media_tray.css | 5 +++-- web/glass/polish.css | 1 + web/glass/studio.css | 2 ++ web/image_editor.css | 3 ++- web/image_library.css | 1 + web/image_view.css | 2 ++ web/library.css | 1 + web/notifications.css | 3 ++- 9 files changed, 15 insertions(+), 4 deletions(-) diff --git a/web/editor_audio.css b/web/editor_audio.css index 257c9115..9cd89eb8 100644 --- a/web/editor_audio.css +++ b/web/editor_audio.css @@ -16,6 +16,7 @@ .fv-ed-track-view .fv-ed-audio-junction{position:absolute;top:50%;box-sizing:border-box;width:10px;height:10px;min-width:0;min-height:0;transform:translate(-50%,-50%) rotate(45deg);padding:0;background:var(--fv-card);border:1px solid var(--fv-accent);border-radius:var(--fv-r-xs);z-index:7;opacity:0;cursor:pointer} .fv-ed-audio-junction:hover,.fv-ed-audio-junction:focus-visible,.fv-ed-audio-junction[data-active=true]{opacity:1!important} .fv-ed-track-view .fv-ed-audio-junction:disabled{opacity:0!important;pointer-events:none} +@media(hover:none){.fv-ed-track-view .fv-ed-audio-junction:not(:disabled){opacity:1}} .fv-ed-audio-junction[data-active=true]{background:var(--fv-accent)!important} .fv-ed-audio-junction[aria-pressed=true]{box-shadow:0 0 0 2px var(--fv-card),0 0 0 3px var(--fv-accent)} .fv-ed-audio-notice{position:absolute;z-index:12;padding:5px 8px;border:1px solid var(--fv-border);border-radius:var(--fv-r-sm);background:var(--fv-card);color:var(--fv-ink);font-size:12px;pointer-events:none} diff --git a/web/glass/media_tray.css b/web/glass/media_tray.css index 39e9caba..dbcb9fac 100644 --- a/web/glass/media_tray.css +++ b/web/glass/media_tray.css @@ -64,13 +64,14 @@ .fvs-tray .fv-mt .fv-card[data-fv-mt-wide=true]>.fv-mt-held-note{right:calc(66.6% + var(--fv-sp-4))} /* Audio has no picture: its use along the top, the player under it, both across the tile. */ .fvs-tray .fv-mt .fv-card[data-kind=audio]{display:flex!important;flex-direction:column;gap:var(--fv-sp-4);padding:var(--fv-sp-4) var(--fv-sp-8) var(--fv-sp-8)!important} -.fvs-tray .fv-mt .fv-card[data-kind=audio]>.fv-row:first-of-type{padding:0} +.fvs-tray .fv-mt .fv-card[data-kind=audio]>.fv-row:first-of-type{padding:0 24px 0 0} .fvs-tray .fv-mt .fv-card[data-kind=audio]>audio.fv-preview{width:100%!important;margin:0!important} .fvs-tray .fv-mt .fv-card[data-kind=audio]>.fv-mt-held-note{position:static;translate:none;align-self:flex-start} /* Remove (and crop, for a frame of another shape): small keys on the picture's top corners, shown when the tile is pointed at or holds the focus; the crop key always, since it says the frame will be cropped. */ .fvs-tray .fv-mt .fv-card>.fv-mt-keys{position:absolute;top:var(--fv-sp-4);right:var(--fv-sp-4);z-index:2;display:flex;gap:var(--fv-sp-4);pointer-events:none;opacity:0;transition:opacity .16s ease-out} .fvs-tray .fv-mt .fv-card:is(:hover,:focus-within)>.fv-mt-keys{opacity:1} +@media(hover:none){.fvs-tray .fv-mt .fv-card>.fv-mt-keys{opacity:1}} .fvs-tray .fv-mt .fv-card>.fv-mt-keys>button,.fvs-tray .fv-mt .fv-card .fv-shape-note>button{pointer-events:auto;flex:none;display:flex!important;align-items:center;justify-content:center;gap:0!important;width:24px!important;height:24px!important;min-height:24px!important;padding:0!important;border:0!important;border-radius:var(--fv-r-xs)!important;background:var(--fv-on-pic)!important;color:var(--fv-on-fill)!important;font-size:0!important;line-height:0} .fvs-tray .fv-mt .fv-card>.fv-mt-keys>button::after,.fvs-tray .fv-mt .fv-card .fv-shape-note>button::after{content:"";position:absolute;inset:-4px} .fvs-tray .fv-mt .fv-card>.fv-mt-keys>button,.fvs-tray .fv-mt .fv-card .fv-shape-note>button{position:relative} @@ -78,7 +79,7 @@ .fvs-tray .fv-mt .fv-card>.fv-mt-keys>button:disabled{opacity:.4} .fvs-tray .fv-mt .fv-card>.fv-mt-keys>button::before,.fvs-tray .fv-mt .fv-card .fv-shape-note>button::before{content:"";width:14px;height:14px;background:currentColor;-webkit-mask:var(--fv-mt-icon) center/14px no-repeat;mask:var(--fv-mt-icon) center/14px no-repeat} .fvs-tray .fv-mt .fv-mt-remove{--fv-mt-icon:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' fill='none' stroke='black' stroke-width='1.5' stroke-linecap='round'%3E%3Cpath d='m4.5 4.5 7 7m0-7-7 7'/%3E%3C/svg%3E")} -.fvs-tray .fv-mt .fv-card>.fv-mt-keys>:is(.fv-mt-up,.fv-mt-down){display:none} +.fvs-tray .fv-mt .fv-card>.fv-mt-keys>:is(.fv-mt-up,.fv-mt-down){display:none!important} .fvs-tray .fv-mt .fv-card.fv-mt-crop>.fv-mt-keys{right:calc(var(--fv-sp-8) + 24px)} .fvs-tray .fv-mt .fv-card .fv-shape-note{position:absolute;top:var(--fv-sp-4);right:var(--fv-sp-4);left:auto;z-index:2;display:block;margin:0!important;padding:0;border:0;background:none} .fvs-tray .fv-mt .fv-card .fv-shape-note>span{display:none} diff --git a/web/glass/polish.css b/web/glass/polish.css index 7cb3158d..288078de 100644 --- a/web/glass/polish.css +++ b/web/glass/polish.css @@ -178,6 +178,7 @@ html:not([data-fv-polish="off"]) .fv-notes-list .fv-note-row:is(:hover,:focus-wi /* A notice's own close key: 24 px, shown when the row is pointed at or holds the focus. */ html:not([data-fv-polish="off"]) .fv-note-x{display:grid;place-items:center;flex:none;width:24px;height:24px;min-height:0;margin:0;padding:0;border:0;border-radius:var(--fv-r-sm);background:none;box-shadow:none;color:var(--fv-fg3);opacity:0;cursor:pointer} html:not([data-fv-polish="off"]) :is(:is(.fv-note,.fv-note-row):is(:hover,:focus-within) .fv-note-x,.fv-note-x:focus-visible){opacity:1} +@media(hover:none){html:not([data-fv-polish="off"]) .fv-note-x{opacity:1}} html:not([data-fv-polish="off"]) .fv-note-x:hover{background:var(--fv-ctl-hover);color:var(--fv-fg)} /* The computer's figures: one size; the number is the heavier part. */ html:not([data-fv-polish="off"]) .fv-tb-pop .fv-tb-mem-v{font-size:var(--fv-fs-2);line-height:18px} diff --git a/web/glass/studio.css b/web/glass/studio.css index 308f8018..ccc3f95d 100644 --- a/web/glass/studio.css +++ b/web/glass/studio.css @@ -488,6 +488,7 @@ .fvs-library-text.fvs-library-name{display:block;max-width:100%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-weight:500} .fv-studio.fv-create .fvs-library-remove{opacity:0;margin-right:var(--fv-sp-4)} .fvs-library-row:hover .fvs-library-remove,.fv-studio.fv-create .fvs-library-remove:focus-visible{opacity:1} +@media(hover:none){.fv-studio.fv-create .fvs-library-remove{opacity:1}} .fvs-library-empty{margin:var(--fv-sp-16);color:var(--fv-fg3);font-size:var(--fv-fs-2);text-align:center} .fvs-library-foot:empty{display:none} .fvs-library-foot{padding:var(--fv-sp-8) var(--fv-sp-12) var(--fv-sp-12);border-top:1px solid var(--fv-line)} @@ -803,6 +804,7 @@ html body .fv-studio.fv-create .fvs-stepper .fvs-step-input.fvs-step-input:is(:f border:1.5px solid #fff;border-radius:var(--fv-r-pill);background:rgb(0 0 0 / .4);color:#fff;font-size:var(--fv-fs-1);font-weight:600;line-height:1;opacity:0; transition:opacity var(--fv-dur-1) var(--fv-ease-out);cursor:pointer} .fv-studio.fv-create .fvs-rail :is(.fv-recent-card:hover,.fv-recent-card:focus-visible) .fv-recent-check,.fv-studio.fv-create .fvs-rail[data-picking=true] .fv-recent-check{opacity:1} +@media(hover:none){.fv-studio.fv-create .fvs-rail .fv-recent-card>span.fv-recent-check{opacity:1}} .fv-studio.fv-create .fvs-rail .fv-recent-card[data-picked] .fv-recent-check{border-color:var(--fv-accent-fill);background:var(--fv-accent-fill)} .fv-studio.fv-create .fvs-rail .fv-recent-card[data-picked="1"] .fv-recent-check::after{content:"1"} .fv-studio.fv-create .fvs-rail .fv-recent-card[data-picked="2"] .fv-recent-check::after{content:"2"} diff --git a/web/image_editor.css b/web/image_editor.css index e0ed8225..9d5814a6 100644 --- a/web/image_editor.css +++ b/web/image_editor.css @@ -99,8 +99,9 @@ button.fv-ie-size:hover{background:var(--fv-hover);color:var(--fv-ink)} .fv-ie-gen-ref{position:relative;flex:none;width:28px;height:28px} .fv-ie-gen-ref>canvas,.fv-ie-gen-ref>img{display:block;width:28px;height:28px;border-radius:var(--fv-r-sm);object-fit:cover;background:var(--fv-raised)} .fv-ie-gen-ref>b{position:absolute;top:-4px;left:-4px;min-width:14px;height:14px;padding:0 3px;border-radius:var(--fv-r-sm);background:var(--fv-ink);color:var(--fv-card);font-size:10px;font-weight:var(--fv-semibold);line-height:14px;text-align:center;font-variant-numeric:tabular-nums} -.fv-ie-gen-ref-remove{position:absolute;top:-5px;right:-5px;width:16px;height:16px;padding:0;border:0;border-radius:var(--fv-r-sm);background:var(--fv-ink);color:var(--fv-card);font-size:12px;line-height:16px;opacity:0;cursor:pointer} +.fv-ie-gen-ref>.fv-ie-gen-ref-remove{position:absolute;top:-5px;right:-5px;width:16px;height:16px;padding:0;border:0;border-radius:var(--fv-r-sm);background:var(--fv-ink);color:var(--fv-card);font-size:12px;line-height:16px;opacity:0;cursor:pointer} .fv-ie-gen-ref:hover>.fv-ie-gen-ref-remove:not(:disabled),.fv-ie-gen-ref-remove:focus-visible{opacity:1} +@media(hover:none){.fv-ie-gen-ref-remove:not(:disabled){opacity:1}} .fv-ie-gen-ref-add summary{width:28px;height:28px;border:1px dashed var(--fv-border);border-radius:var(--fv-r-sm)} .fv-ie-gen-ref-add summary[aria-disabled=true]{opacity:.4;cursor:default;pointer-events:none} .fv-ie-gen-ref-add .fv-ie-menu-list{top:calc(100% + 6px);right:auto;bottom:auto;left:0} diff --git a/web/image_library.css b/web/image_library.css index 431f78b5..f2a0883f 100644 --- a/web/image_library.css +++ b/web/image_library.css @@ -21,6 +21,7 @@ .fv-works-ref{left:var(--fv-sp-4,4px)} .fv-works-del{right:var(--fv-sp-4,4px)} .fv-works-tile:hover .fv-works-act,.fv-works-act:focus-visible,.fv-works-tile:focus-within .fv-works-act{opacity:1} +@media(hover:none){.fv-works-act{opacity:1}} .fv-works-act:hover{background:rgb(0 0 0/.8)} .fv-works-tick{position:absolute;top:var(--fv-sp-4,4px);left:var(--fv-sp-4,4px);width:18px;height:18px;box-sizing:border-box;border:2px solid #fff;border-radius:var(--fv-r-xs,4px);background:rgb(0 0 0/.35);pointer-events:none;display:none} .fv-works-tile[data-selecting=true] .fv-works-tick{display:block} diff --git a/web/image_view.css b/web/image_view.css index ce1cddd9..34252242 100644 --- a/web/image_view.css +++ b/web/image_view.css @@ -248,6 +248,7 @@ dialog.fv-studio.fv-image:not([open]){display:none!important} .fv-iv .fv-iv-li-s{display:block;font-size:var(--fv-fs-1,12px);line-height:16px;color:var(--fv-fg3);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;text-align:left} .fv-iv .fv-iv-li-end{display:flex;opacity:0;transition:opacity var(--fv-dur-1,160ms);padding-right:4px} .fv-iv .fv-iv-li:hover .fv-iv-li-end,.fv-iv .fv-iv-li:focus-within .fv-iv-li-end{opacity:1} +@media(hover:none){.fv-iv .fv-iv-li-end{opacity:1}} .fv-iv .fv-iv-li-end .fv-iv-icon-btn{width:28px;height:28px;color:var(--fv-fg3)} .fv-iv .fv-iv-pin[aria-pressed=true]{background:transparent;color:#e9b43a!important} .fv-iv .fv-iv-pin[aria-pressed=true] .fv-iv-icon{fill:currentColor} @@ -399,6 +400,7 @@ dialog.fv-studio.fv-image:not([open]){display:none!important} .fv-iv .fv-iv-cx{position:absolute;right:8px;top:8px;width:28px;height:28px;border-radius:var(--fv-r-pill);color:#fff;background:rgb(0 0 0 / .45);opacity:0} .fv-iv .fv-iv-cx:hover{color:#fff;background:rgb(0 0 0 / .65)} .fv-iv .fv-iv-cpane:hover .fv-iv-cx,.fv-iv .fv-iv-cx:focus-visible{opacity:1} +@media(hover:none){.fv-iv .fv-iv-cx{opacity:1}} .fv-iv .fv-iv-cslider .fv-iv-cframe{cursor:ew-resize;touch-action:none} .fv-iv .fv-iv-cs-b{clip-path:inset(0 0 0 var(--cut,50%))} .fv-iv .fv-iv-cs-handle{position:absolute;top:0;bottom:0;left:var(--cut,50%);width:2px;margin-left:-1px;background:#fff;box-shadow:0 0 0 1px rgb(0 0 0 / .25);outline:none} diff --git a/web/library.css b/web/library.css index 048c14de..1587a520 100644 --- a/web/library.css +++ b/web/library.css @@ -223,6 +223,7 @@ dialog.fv-studio.fv-library::backdrop{background:var(--lib-page)} .fv-library .fv-library-enlarge{position:absolute;top:var(--fv-sp-8,8px);right:var(--fv-sp-8,8px);display:grid;place-items:center;width:var(--fv-ctl,32px);height:var(--fv-ctl,32px);min-height:var(--fv-ctl,32px);padding:0;border:0;border-radius:var(--fv-r-sm); background:rgb(0 0 0 / .5);color:#fff;opacity:0;transition:opacity var(--fv-dur-1,160ms) var(--fv-ease-out);box-shadow:none} .fv-library-media:hover .fv-library-enlarge,.fv-library .fv-library-enlarge:focus-visible{opacity:1} +@media(hover:none){.fv-library .fv-library-enlarge{opacity:1}} .fv-library .fv-library-media .fv-preview-badge{top:var(--fv-sp-8,8px);left:var(--fv-sp-8,8px)} .fv-library-caption{display:flex;flex-direction:column;align-items:flex-start;gap:var(--fv-sp-4,4px);font-size:var(--fv-fs-1,12px);color:var(--fv-fg3)} .fv-library-caption strong{font-size:var(--fv-fs-3,16px);font-weight:600;color:var(--fv-fg)} diff --git a/web/notifications.css b/web/notifications.css index 920f0b4d..58a618b9 100644 --- a/web/notifications.css +++ b/web/notifications.css @@ -131,7 +131,8 @@ } :is(.fv-note-row:hover, .fv-note-row:focus-within) .fv-note-x, .fv-note-x:focus-visible { opacity: 1; } .fv-note-x:hover { background: var(--fv-ctl-hover, rgb(255 255 255 / .11)); color: var(--fv-fg, #f3f5f8); } -@media (hover: none) { .fv-note-x { opacity: 1; } } +/* Touch: the key is always shown and presses across 40 px around its 24 px face. */ +@media (hover: none) { .fv-note-x { opacity: 1; position: relative; } .fv-note-x::after { content: ""; position: absolute; inset: -8px; } } .fv-notes-clear { width: auto !important; padding: 0 var(--fv-sp-8, 8px) !important; border-radius: var(--fv-rad-sm, 8px) !important; font: 500 var(--fv-fs-1, 12px)/1 var(--fv-font, system-ui, sans-serif); white-space: nowrap; } @media (prefers-reduced-motion: reduce) { .fv-note-x { transition: none; } } .fv-notes-none { padding: var(--fv-sp-12, 12px) var(--fv-sp-8, 8px); text-align: center; font-size: var(--fv-fs-1, 12px); color: var(--fv-fg3, #99a1ae); } From 77d596bea8ad6c92ccec6349ece8d37518af2258 Mon Sep 17 00:00:00 2001 From: Bowen Xue Date: Wed, 18 Nov 2026 03:20:25 +0000 Subject: [PATCH 20/97] Docs: restore recent community results --- docs/community-results.md | 10 ++++++++++ docs/zh-CN/community-results.md | 10 ++++++++++ 2 files changed, 20 insertions(+) diff --git a/docs/community-results.md b/docs/community-results.md index 731a881d..f5492bab 100644 --- a/docs/community-results.md +++ b/docs/community-results.md @@ -141,6 +141,15 @@ Thanks to the community members who sent diagnostic reports. FreeVideo already r | 5060 | 8 GB | 64 GB | 1088×1920 | 5.9 s | Medium | 0.4.31 | 1259 s | 0.4.31 | Already optimal¹² | | 3050 | 8 GB | 32 GB | 1344×768 | 5 s | Light | 0.4.35 | 978 s | 0.4.35 | Already optimal¹² | | 4070 Ti SUPER | 16 GB | 32 GB | 1344×768 | 12 s | Light | 0.4.37 | 3427 s | 0.5.3 | 2200 s (−1230 s)¹² | +| 4070 | 12 GB | 64 GB | 1344×768 | 8 s | Light⁵ | 0.4.38 | 269 s | 0.4.38 | Already optimal | +| 5060 Ti | 16 GB | 32 GB | 960×544 | 5.2 s | Light | 0.4.38 | 348 s | 0.4.38 | Already optimal | +| 5060 | 8 GB | 64 GB | 960×1664 | 11.5 s | Light⁵ | 0.4.38 | 1035 s | 0.4.38 | Already optimal¹² | +| 5090 | 32 GB | 128 GB | 1088×1920 | 10 s | Light | 0.5.0 | 638 s | 0.5.0 | Already optimal¹² | +| 3060 Ti | 8 GB | 16 GB | 1344×768 | 5.2 s | Light | 0.5.0 | 2102 s | 0.5.0 | Already optimal¹²,¹⁵ | +| 5060 Ti | 8 GB | 16 GB | 768×1344 | 8 s | Light | 0.4.33 | 594 s | 0.4.33 | Already optimal | +| 5060 Ti | 16 GB | 32 GB | 1344×768 | 10 s | Light | 0.5.1 | 716 s | 0.5.1 | Already optimal | +| 4060 Laptop | 8 GB | 16 GB | 1344×768 | 10 s | Light | 0.5.1 | 882 s | 0.5.1 | Already optimal | +| M4 Max | Unified | 128 GB | 1344×768 | 10.1 s | Light | 0.5.4 | 3399 s | 0.5.4 | Already optimal | - Time: end to end, from submission until the video is saved. - After: the estimated time, derived from the report's stage times and from complete planned runs on our test machines (RTX 3090 and RTX 5060 Ti on Windows, RTX PRO 6000 on Linux) under the reporting machine's VRAM and RAM limits, not from reruns on that machine. @@ -159,3 +168,4 @@ Thanks to the community members who sent diagnostic reports. FreeVideo already r - ¹² Task with a reference: every step also processes the reference video, images or audio, so each step takes longer than a plain request of the same size, up to about twice as long with a long reference. - ¹³ Preview (first pass only). - ¹⁴ Compatibility level 3 was set manually; it is the slowest level and made each step about 2.4 times slower than the automatic setting for this request, and the GPU core clock also stayed at 900 MHz against the 1815 MHz it reached. With the level off, the same request takes about 1100 s. +- ¹⁵ The video model is read from the drive again at every step, at about 110 MB/s on this machine; the graphics card was busy for about 9–13% of the first pass and 36% of the second pass. diff --git a/docs/zh-CN/community-results.md b/docs/zh-CN/community-results.md index d92efdc0..1f5eeb45 100644 --- a/docs/zh-CN/community-results.md +++ b/docs/zh-CN/community-results.md @@ -141,6 +141,15 @@ | 5060 | 8 GB | 64 GB | 1088×1920 | 5.9 s | 标⁠准 | 0.4.31 | 1259 s | 0.4.31 | 已⁠是⁠最⁠优¹² | | 3050 | 8 GB | 32 GB | 1344×768 | 5 s | 轻⁠量 | 0.4.35 | 978 s | 0.4.35 | 已⁠是⁠最⁠优¹² | | 4070 Ti SUPER | 16 GB | 32 GB | 1344×768 | 12 s | 轻⁠量 | 0.4.37 | 3427 s | 0.5.3 | 2200 s (−1230 s)¹² | +| 4070 | 12 GB | 64 GB | 1344×768 | 8 s | 轻⁠量⁵ | 0.4.38 | 269 s | 0.4.38 | 已⁠是⁠最⁠优 | +| 5060 Ti | 16 GB | 32 GB | 960×544 | 5.2 s | 轻⁠量 | 0.4.38 | 348 s | 0.4.38 | 已⁠是⁠最⁠优 | +| 5060 | 8 GB | 64 GB | 960×1664 | 11.5 s | 轻⁠量⁵ | 0.4.38 | 1035 s | 0.4.38 | 已⁠是⁠最⁠优¹² | +| 5090 | 32 GB | 128 GB | 1088×1920 | 10 s | 轻⁠量 | 0.5.0 | 638 s | 0.5.0 | 已⁠是⁠最⁠优¹² | +| 3060 Ti | 8 GB | 16 GB | 1344×768 | 5.2 s | 轻⁠量 | 0.5.0 | 2102 s | 0.5.0 | 已⁠是⁠最⁠优¹²,¹⁵ | +| 5060 Ti | 8 GB | 16 GB | 768×1344 | 8 s | 轻⁠量 | 0.4.33 | 594 s | 0.4.33 | 已⁠是⁠最⁠优 | +| 5060 Ti | 16 GB | 32 GB | 1344×768 | 10 s | 轻⁠量 | 0.5.1 | 716 s | 0.5.1 | 已⁠是⁠最⁠优 | +| 4060 笔⁠记⁠本 | 8 GB | 16 GB | 1344×768 | 10 s | 轻⁠量 | 0.5.1 | 882 s | 0.5.1 | 已⁠是⁠最⁠优 | +| M4 Max | 统⁠一⁠内⁠存 | 128 GB | 1344×768 | 10.1 s | 轻⁠量 | 0.5.4 | 3399 s | 0.5.4 | 已⁠是⁠最⁠优 | - 用时:从提交到视频保存完成的端到端用时。 - 优化后:预估用时,根据报告中的分段用时,结合测试机(Windows RTX 3090 和 RTX 5060 Ti、Linux RTX PRO 6000)在报告机器的显存和内存上限下运行完整规划的实测推算,不是在报告机器上重跑。 @@ -159,3 +168,4 @@ - ¹² 带参考的任务:每一步还要处理参考视频、参考图片或参考音频,所以每步耗时比相同尺寸的普通请求长;参考较长时约为两倍。 - ¹³ 预览(只做第一遍)。 - ¹⁴ 兼容等级 3 为手动设置,是最慢的等级,对这个请求每步比自动设置慢约 2.4 倍;显卡核心时钟同时固定在 900 MHz(本次运行曾达到 1815 MHz)。关闭该等级后,同样的请求约需 1100 秒。 +- ¹⁵ 视频模型每一步都要从硬盘重新读取,这台机器上读取速度约 110 MB/s;显卡在第一遍约 9–13% 的时间在工作,第二遍约 36%。 From 4f1fbcbfb7a67dae5acca73cc8bf78f2a2545482 Mon Sep 17 00:00:00 2001 From: Bowen Xue Date: Wed, 18 Nov 2026 03:24:43 +0000 Subject: [PATCH 21/97] Image view: Open folder says so and names the folder when it cannot be opened, instead of doing... Image view: Open folder says so and names the folder when it cannot be opened, instead of doing nothing The caption key, the caption's More menu and the works column's folder key now read the engine's answer. When it could not show the folder (no desktop, or a remote engine), or the request fails, the line above Generate says "The folder could not be opened automatically. Open it in a file manager." followed by the folder, shown whole and selectable; opening it later clears that line. The wording is the one the image history used before 0.6.0. Browser check: tests/browser_image_view_open_folder.py (zh/en, 1440 and 400). --- web/image_view.css | 5 +++++ web/image_view.js | 38 ++++++++++++++++++++++++++++++++++---- 2 files changed, 39 insertions(+), 4 deletions(-) diff --git a/web/image_view.css b/web/image_view.css index 34252242..8463a2f3 100644 --- a/web/image_view.css +++ b/web/image_view.css @@ -266,6 +266,11 @@ dialog.fv-studio.fv-image:not([open]){display:none!important} .fv-iv .fv-iv-slot{display:flex;align-items:center;gap:8px;height:40px;padding:0 4px 0 8px;margin-bottom:8px;border-radius:var(--fv-rad-ctl,12px);font-size:var(--fv-fs-1,12px);color:var(--fv-fg3);overflow:hidden} .fv-iv .fv-iv-slot .fv-iv-icon{width:15px;height:15px} .fv-iv .fv-iv-slot-tx{flex:1;min-width:0;overflow:hidden;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;line-height:16px} +.fv-iv .fv-iv-slot[data-whole]{height:auto;min-height:40px;padding-top:8px;padding-bottom:8px;align-items:flex-start} +.fv-iv .fv-iv-slot[data-whole] .fv-iv-slot-tx{display:block;-webkit-line-clamp:unset;-webkit-user-select:text;user-select:text} +.fv-iv .fv-iv-slot[data-kind=note]{background:rgb(var(--fv-solid3))} +.fv-iv .fv-iv-folder-say,.fv-iv .fv-iv-folder-path{display:block} +.fv-iv .fv-iv-folder-path{overflow-wrap:anywhere} .fv-iv .fv-iv-slot[data-kind=warn]{background:var(--fv-warn-soft);color:var(--fv-warn)} .fv-iv .fv-iv-slot[data-kind=info]{background:var(--fv-accent-soft);color:var(--fv-accent-ink)} .fv-iv .fv-iv-slot-act{height:28px;padding:0 12px;color:inherit;font-weight:600} diff --git a/web/image_view.js b/web/image_view.js index eef69193..33392654 100644 --- a/web/image_view.js +++ b/web/image_view.js @@ -423,7 +423,7 @@ export function openImageView(node, {studio = null, client: given = null, poll = const menuItem = (iconName, text, use, onClick, cls = '') => { const b = el('button', 'fv-iv-menu-item ' + cls); b.type = 'button'; b.setAttribute('role', 'menuitem'); b.append(icon(iconName), el('span', '', text)); tip(b, text, use); b.addEventListener('click', () => { more.hidden = true; onClick(); }); return b; }; const copyPrompt = () => { const text = promptFor(shownFile); try { void navigator.clipboard?.writeText(text); } catch { /* the clipboard may be refused */ } }; const usePromptItem = menuItem('prompt', t('Use prompt', '使用提示词'), t('Put its prompt back in the box', '把它的提示词填回描述框'), () => { const text = promptFor(shownFile); if (text) { prompt.value = text; prompt.dispatchEvent(new Event('input', {bubbles: true})); promptGroup.open(true); } }); - more.append(menuItem('folder', t('Open folder', '打开文件夹'), t('Show the pictures on this computer', '在电脑上打开保存图片的文件夹'), () => void client.historyOpen?.()), + more.append(menuItem('folder', t('Open folder', '打开文件夹'), t('Show the pictures on this computer', '在电脑上打开保存图片的文件夹'), () => void openFolder()), menuItem('copy', t('Copy prompt', '复制提示词'), t('Copy the words this picture was made from', '复制这张图的提示词'), copyPrompt), usePromptItem, menuItem('trash', t('Delete', '删除'), t('Move to recently deleted; can be undone', '移到最近删除,可以撤销'), () => deleteFiles([shownFile]), 'fv-iv-danger')); const moreHost = el('span', 'fv-image-more-host fv-iv-more-host'); moreHost.append(moreButton, more); @@ -433,7 +433,7 @@ export function openImageView(node, {studio = null, client: given = null, poll = const copyInline = inlineBtn('copy', t('Copy prompt', '复制提示词'), t('Copy the words this picture was made from', '复制这张图的提示词'), copyPrompt); const useInline = inlineBtn('prompt', t('Use prompt', '使用提示词'), t('Put its prompt back in the box', '把它的提示词填回描述框'), () => usePromptItem.click()); inline.append(copyInline, useInline, - inlineBtn('folder', t('Open folder', '打开文件夹'), t('Show the pictures on this computer', '在电脑上打开保存图片的文件夹'), () => void client.historyOpen?.()), + inlineBtn('folder', t('Open folder', '打开文件夹'), t('Show the pictures on this computer', '在电脑上打开保存图片的文件夹'), () => void openFolder()), inlineBtn('trash', t('Delete', '删除'), t('Move to recently deleted; can be undone', '移到最近删除,可以撤销'), () => deleteFiles([shownFile]), 'fv-iv-danger')); const capActions = el('div', 'fv-iv-cap-actions'); capActions.append(editThis, asReference, el('i', 'fv-iv-sep'), favBtn, save, inline, moreHost); cap.append(info_, capActions); @@ -544,7 +544,7 @@ export function openImageView(node, {studio = null, client: given = null, poll = onTrash: value => { view = value === false ? 'works' : view === 'trash' ? 'works' : 'trash'; drawWorks(); }, onRestore: files => { restoreWorks(files); if (undoNote) undoNote.files = undoNote.files.filter(f => !files.includes(f)); if (!undoNote?.files.length) undoNote = null; drawWorks(); render(); }, onPurge: () => { void trash.flush(); }, - onOpenFolder: () => void client.historyOpen?.(), + onOpenFolder: () => void openFolder(), onCollapse: () => setPanel('right', false), onRun: () => returnToRun()}); const rightRail = el('div', 'fv-iv-rail fv-iv-rail-right'); const rightRailOpen = button('fv-iv-icon-btn', {iconName: 'panelR', name: t('Show works', '展开作品栏'), use: t('Your pictures, newest first', '你的图片,最新在前')}); @@ -656,6 +656,33 @@ export function openImageView(node, {studio = null, client: given = null, poll = listenDialogKey(prompt, 'paste', event => { const files = [...(event.clipboardData?.files || [])].filter(f => f.type.startsWith('image/')); if (files.length) { event.preventDefault(); addFiles(files); } }); const say = text => { note.textContent = text || ''; if (alive) paintSlot(); }; + // Open folder: when the engine cannot show it (no desktop, or a remote engine: expected there, not a fault), the line + // above Generate says so as a plain note and gives the folder on a line of its own, so the click is never silent; + // opening it later clears that line. (The wording is the one the image history used before 0.6.0.) + let folderNote = null; + async function openFolder() { + let answer; + try { answer = await client.historyOpen?.(); } catch { answer = {opened: false}; } + if (!alive) return; + if (answer?.opened === false) { + const sentence = t('The folder could not be opened automatically. Open it in a file manager.', '无法自动打开该文件夹,请在文件管理器中手动打开'); + const folder = typeof answer.folder === 'string' ? answer.folder : ''; + folderNote = {sentence, folder, text: folder ? `${sentence} ${folder}` : sentence}; + say(folderNote.text); + } else if (folderNote && note.textContent === folderNote.text) { folderNote = null; say(''); } + } + // The folder note's two lines. Its path breaks only where it does not fit (its spaces are shown unbreakable and + // copied as plain spaces, so a copied path still works). + function folderParts() { + const tx = el('span', 'fv-iv-slot-tx'); tx.append(el('span', 'fv-iv-folder-say', folderNote.sentence)); + if (folderNote.folder) tx.append(el('span', 'fv-iv-folder-path', folderNote.folder.replace(/ /g, '\u00a0'))); + tx.addEventListener('copy', event => { + const text = String(globalThis.getSelection?.() || '').replace(/\u00a0/g, ' '); + if (!text || !event.clipboardData) return; + event.clipboardData.setData('text/plain', text); event.preventDefault(); + }); + return [icon('info'), tx]; + } const label = number => t(`Image ${number}`, `图 ${number}`); const subject = number => t(`Subject ${number}`, `主体 ${number}`); // Each model row says how many pictures it takes; the strip holds as many as the most generous one. @@ -891,7 +918,8 @@ export function openImageView(node, {studio = null, client: given = null, poll = // One fixed-height line above Generate: the most pressing thing there is to say. const s = modelState(info, model.id), tooMany = over() > 0; let kind = '', parts = []; - if (note.textContent) { kind = note.dataset.kind === 'busy' ? 'info' : 'warn'; parts = [icon(kind === 'info' ? 'clock' : 'warn'), el('span', 'fv-iv-slot-tx', note.textContent)]; } + if (note.textContent && folderNote && note.textContent === folderNote.text) { kind = 'note'; parts = folderParts(); } + else if (note.textContent) { kind = note.dataset.kind === 'busy' ? 'info' : 'warn'; parts = [icon(kind === 'info' ? 'clock' : 'warn'), el('span', 'fv-iv-slot-tx', note.textContent)]; } else if (tooMany) { kind = 'warn'; parts = [icon('warn'), el('span', 'fv-iv-slot-tx', cap_(model) === 0 ? t(`${model.short} does not take reference pictures. Remove ${over()}.`, `${model.short} 暂不支持参考图,请移除 ${over()} 张。`) : t(`${model.short} takes at most ${cap_(model)}. Remove ${over()}.`, `${model.short} 最多 ${cap_(model)} 张,请移除 ${over()} 张。`))]; @@ -910,6 +938,8 @@ export function openImageView(node, {studio = null, client: given = null, poll = else if (fitted && fitted.file === shownFile) { kind = 'info'; parts = [icon('info'), el('span', 'fv-iv-slot-tx', fittedNote(fitted, t, !!info?.unified_memory))]; } else parts = running ? [el('span', 'fv-iv-slot-tx', t('Generating; you can leave this view', '正在生成,可以离开这个视图'))] : []; slot.dataset.kind = kind; slot.replaceChildren(...parts); + // A folder that could not be opened is read (and copied) in full: that line takes the height it needs. + slot.toggleAttribute('data-whole', kind === 'note'); paintStatus(); } From c92196e60b873732ef61f3fa5e218410db1e5d15 Mon Sep 17 00:00:00 2001 From: Bowen Xue Date: Wed, 18 Nov 2026 03:28:23 +0000 Subject: [PATCH 22/97] Studio: a report saved from the status line says so in the shared notice, not in a card the... Studio: a report saved from the status line says so in the shared notice, not in a card the prompt box covers --- web/notifications.css | 9 ++++++++- web/notifications.js | 15 +++++++++++++++ web/report_issue.js | 7 ++++--- web/studio.js | 20 +++++++++++++++++--- 4 files changed, 44 insertions(+), 7 deletions(-) diff --git a/web/notifications.css b/web/notifications.css index 58a618b9..f14c02d9 100644 --- a/web/notifications.css +++ b/web/notifications.css @@ -114,7 +114,14 @@ @media (max-width: 719px) { .fv-toasts[popover], .fv-toasts { top: auto; bottom: calc(var(--fv-bottombar-top, 96px) + var(--fv-sp-8, 8px)); left: var(--fv-sp-12, 12px); right: var(--fv-sp-12, 12px); width: auto; max-width: none; align-items: stretch; } .fv-toast { transform-origin: 50% 100%; } - .fv-toast-msg { flex: 1; } + /* A narrow strip shows the whole message, never cut short: it wraps between words, and when it would take more + than one line beside its controls (is-stacked, set by showToast) it gets its own row with the controls below it, + right-aligned. The strip grows to fit; a view that keeps a slot for it reads toastHeight(). */ + .fv-toast { height: auto; min-height: var(--fv-ctl-l, 40px); padding-block: var(--fv-sp-4, 4px); border-radius: var(--fv-rad-dock, 20px); } + .fv-toast-msg { flex: 1; white-space: normal; overflow-wrap: break-word; text-overflow: clip; line-height: 18px; } + .fv-toast.is-stacked { flex-wrap: wrap; row-gap: var(--fv-sp-4, 4px); padding-top: var(--fv-sp-8, 8px); } + .fv-toast.is-stacked .fv-toast-msg { flex-basis: calc(100% - 16px - 2 * var(--fv-sp-8, 8px)); } + .fv-toast.is-stacked .fv-toast-act { margin-left: auto; } .fv-toast-msg small { display: none; } } @media (prefers-reduced-motion: reduce) { .fv-toast-life .fg { animation: none; } .fv-toast-act, .fv-toast-x { transition: none; } } diff --git a/web/notifications.js b/web/notifications.js index 982902ce..6abba219 100644 --- a/web/notifications.js +++ b/web/notifications.js @@ -520,15 +520,29 @@ function showToast(item, more) { if (ring && nextRing) nextRing.replaceWith(ring); old.replaceWith(next); if (toastHeld) next.classList.add('is-held'); + stackLong(next); toastResized(); return; } if (old) old.remove(); toastItem = item; toastHeld = false; toastLeft = item.spec.ms; box.append(next); + stackLong(next); if (!reducedMotion() && next.animate) next.animate([{opacity: 0, transform: 'scaleX(.6)'}, {opacity: 1, transform: 'none'}], {duration: 200, easing: EASE}); runTimer(item); + toastResized(); if (item.spec.tone === 'fail') store().add({id: `toast:${Date.now()}`, type: 'toast', status: 'failed', title: item.spec.text, reason: item.spec.detail, at: Date.now()}); } +// On a phone strip a message that wraps beside its controls takes its own row (notifications.css, is-stacked). +function stackLong(el) { + el.classList.remove('is-stacked'); + const msg = el.querySelector('.fv-toast-msg'); + if (!msg || !matchMedia('(max-width: 719px)').matches) return; + if (msg.offsetHeight > 1.5 * (parseFloat(getComputedStyle(msg).lineHeight) || 18)) el.classList.add('is-stacked'); +} +// A view that keeps a slot for the strip (the studio on a phone) hears when the visible notice comes, goes or changes +// height, and reads it from toastHeight(). +export function toastHeight() { return toastRegion?.querySelector('.fv-toast:not(.is-leaving)')?.offsetHeight || 0; } +function toastResized() { dispatchEvent(new CustomEvent('freevideo-toast-resize', {detail: {height: toastHeight()}})); } function hideToast(item) { if (toastItem !== item) return; clearTimeout(toastTimer); toastItem = null; toastHeld = false; @@ -536,6 +550,7 @@ function hideToast(item) { const done = () => { box?.remove(); if (!toastItem && toastRegion && !toastRegion.querySelector('.fv-toast')) { try { toastRegion.hidePopover?.(); } catch { /* Already hidden. */ } toastRegion.remove(); } + toastResized(); }; if (!box) { done(); return; } box.classList.add('is-leaving'); diff --git a/web/report_issue.js b/web/report_issue.js index 7e9ecb2b..06aefbc1 100644 --- a/web/report_issue.js +++ b/web/report_issue.js @@ -177,9 +177,10 @@ export function showReportTip(bar, anchor, t, {mode = 'invite', submit, onHide = anchor.dataset.fvTipUse = t('Save the report; sharing it gets this computer optimized', '保存诊断报告,提交可获专门优化'); return null; } - // A report saved from a result says so in the shared notice under the top bar (it takes no room and its button is - // always reachable); the page under the result has too little height for a card between it and the console. - if (mode === 'downloaded' && underResult && bar.closest('.fv-result-links')) { + // A report saved from a result or from the status line under it says so in the shared notice under the top bar (it + // takes no room and its button is always reachable); the page under the result has too little height for a card + // between it and the console, which would cover it. + if (mode === 'downloaded' && underResult && bar.closest('.fv-result-links, .fv-status')) { onHide?.(); import('./notifications.js').then(({toast}) => toast(t('Diagnostic report downloaded', '诊断报告已下载'), {tone: 'ok', action: { label: t('Go to feedback page', '前往反馈页面提交'), use: t('Open the feedback page to attach the report', '打开反馈页面,附上报告提交'), diff --git a/web/studio.js b/web/studio.js index b19619a6..0c0ae20b 100644 --- a/web/studio.js +++ b/web/studio.js @@ -74,7 +74,7 @@ import { confirmStop, startJobSources } from './task_float.js'; import { resultEffort, effortName } from './sampling_effort.js'; import { createPromptLibrary, rememberPrompt } from './prompt_library.js'; import { createCompare, COMPARE_ICON } from './studio_compare.js'; -import { toast } from './notifications.js'; +import { toast, toastHeight } from './notifications.js'; import { mediaQueue } from './work_media.js'; const languageOverride = typeof location !== 'undefined' @@ -1613,6 +1613,11 @@ export function openStudio(node, {extendFrom = null} = {}) { const STATUS_LINE = 24, phone = window.matchMedia?.('(max-width:760px)'); // The play bar's row: 32 px, 44 on phones where its buttons are touch targets (glass/studio.css). const TOAST_SLOT = 56, playerRoom = () => (phone?.matches ? 44 : 32); + // A status line that takes more than its row on a phone (a failure that wraps, with its report button under it) + // lifts the picture by the difference, so it never runs into the toast slot. + // A notice that wraps to more lines than the slot holds widens the slot while it shows (8 px clear on each side). + const toastSlot = () => Math.max(TOAST_SLOT, toastHeight() + 16); + const statusRoom = () => Math.max(STATUS_LINE, output.querySelector(':scope > .fv-status')?.offsetHeight || 0); function fitPreview() { const style = getComputedStyle(output), gap = parseFloat(style.rowGap) || 0; const width = output.clientWidth - parseFloat(style.paddingLeft) - parseFloat(style.paddingRight); @@ -1622,7 +1627,7 @@ export function openStudio(node, {extendFrom = null} = {}) { // The play bar's row is left out while there is no video to play (glass/studio.css), and its room with it. const playerShown = getComputedStyle(playerRow).display !== 'none'; const room = output.clientHeight - parseFloat(style.paddingTop) - parseFloat(style.paddingBottom) - - (phone?.matches ? 88 + TOAST_SLOT + STATUS_LINE + 2 * gap : 40 + gap) - (playerShown ? playerRoom() + gap : 0); + - (phone?.matches ? 88 + toastSlot() + statusRoom() + 2 * gap : 40 + gap) - (playerShown ? playerRoom() + gap : 0); if (!(width > 0) || !(room > 0) || !Number.isFinite(previewRatio) || previewRatio <= 0) return; const height = Math.max(Math.min(room, 160), Math.min(room, width / previewRatio)); const fittedWidth = Math.min(width, height * previewRatio), fittedHeight = fittedWidth / previewRatio; @@ -1713,9 +1718,18 @@ export function openStudio(node, {extendFrom = null} = {}) { function fault(text) { status.dataset.error = 'true'; status.textContent = text; status.append(statusIssue); } const stats = el('div', null, 'fv-stats'), budget = el('div', '', 'fv-budget'), links = el('div', null, 'fv-result-links'); // New text in the status line replaces the report card under the result. - const statusWatch = new MutationObserver(() => { if (!status.textContent.trim()) return; hideReportTip(links.querySelector('.fv-actions')); hideReportTip(status); }); + let statusHeight = 0; + const statusWatch = new MutationObserver(() => { + // On a phone the picture makes room for the line's height (fitPreview); refit when that height changes. + if (phone?.matches && status.offsetHeight !== statusHeight) { statusHeight = status.offsetHeight; fitPreview(); } + if (!status.textContent.trim()) return; hideReportTip(links.querySelector('.fv-actions')); hideReportTip(status); + }); statusWatch.observe(status, {childList: true, characterData: true, subtree: true}); cleanup.push(() => statusWatch.disconnect()); + let toastRoom = TOAST_SLOT; + const onToastResize = () => { if (phone?.matches && toastSlot() !== toastRoom) { toastRoom = toastSlot(); fitPreview(); } }; + addEventListener('freevideo-toast-resize', onToastResize); + cleanup.push(() => removeEventListener('freevideo-toast-resize', onToastResize)); stats.hidden = true; const metrics = [], metricLabels = []; for (const label of [t('Generation', '生成用时'), t('Total time', '总用时'), t('Peak VRAM', '最高显存'), t('Peak RAM', '最高内存')]) { const box = el('div', null, 'fv-stat'), n = el('strong', '—'), caption = el('span', label); box.append(n, caption); stats.append(box); metrics.push(n); metricLabels.push(caption); } From 87f836ceda507f871cd2f0ad10e5edbc0d57fb73 Mon Sep 17 00:00:00 2001 From: Bowen Xue Date: Wed, 18 Nov 2026 03:31:41 +0000 Subject: [PATCH 23/97] Launcher: an incomplete installation file now says what to do and opens the install folder A missing bundled file (for example engine/comfy/taesd/taesd.py) shows a plain card: extract the whole package again and check that security software has not removed files, with an Open install folder button beside the technical details. --- freevideo_engine/failure_details.py | 4 ++++ freevideo_engine/launcher/Main.qml | 2 ++ freevideo_engine/modern_launcher.py | 16 ++++++++++++++++ 3 files changed, 22 insertions(+) diff --git a/freevideo_engine/failure_details.py b/freevideo_engine/failure_details.py index d88d5454..eec53ebd 100644 --- a/freevideo_engine/failure_details.py +++ b/freevideo_engine/failure_details.py @@ -364,6 +364,10 @@ def file_in_use(text): ('This location cannot be used', '无法使用这个位置'), ('Windows does not let this account create folders in this location. Choose a folder in the user folder or on another drive.', 'Windows 不允许当前账户在这个位置创建文件夹。请改选用户文件夹或其他硬盘上的文件夹。')), + (r'Missing or incomplete bundled file: ', 'missing-file', + ('The installation files are incomplete', '安装文件不完整'), + ('Extract the whole package again, and check that security software has not removed any files.', + '请重新完整解压安装包,并检查安全软件是否删掉了文件。')), (r'The installation folder is on a read-only disk', 'disk-read-only', ('This disk is read-only', '这块硬盘是只读的'), ('This Mac can read the disk but not write to it, as with NTFS disks. Choose a folder on another disk.', diff --git a/freevideo_engine/launcher/Main.qml b/freevideo_engine/launcher/Main.qml index 1e567ac7..ed655439 100644 --- a/freevideo_engine/launcher/Main.qml +++ b/freevideo_engine/launcher/Main.qml @@ -514,6 +514,8 @@ ApplicationWindow { FButton { objectName: "changeSource"; visible: s.failure.kind === "download" || s.failure.kind === "model-source"; text: t("Change source", "切换下载源"); onClicked: { settingsTab = "downloads"; settingsOpen = true } } FButton { objectName: "changeAddress"; visible: s.failure.kind === "port-taken"; text: t("Change address", "更改地址"); onClicked: { settingsTab = "advanced"; settingsOpen = true } } FButton { objectName: "repairCardButton"; primary: true; visible: !!s.repair_offered; text: t("Repair", "修复"); onClicked: backend.action("repair", false) } + FButton { objectName: "openInstallFolder"; visible: s.failure.kind === "missing-file"; primary: true + text: t("Open install folder", "打开安装目录"); onClicked: backend.openInstallFolder() } FButton { objectName: "latestLauncherLink"; visible: s.failure.kind === "older-launcher"; flat: true text: t("Download the latest ↗", "下载最新版 ↗"); onClicked: backend.link("https://github.com/FlashML-org/FreeVideo/releases/latest") } FButton { objectName: "reportProblem"; visible: !diskFailure && !notAFault && s.failure.kind !== "port-taken" && s.failure.kind !== "comfy-restart" && s.failure.kind !== "comfy-folder" && s.failure.kind !== "engine-folder-denied"; text: reportOpened(s.error, s.failure.title || "") ? t("Opened", "已打开") : t("Report a problem", "提交问题"); widthText: t("Report a problem", "提交问题"); enabled: !reportOpened(s.error, s.failure.title || ""); onClicked: backend.reportProblem(s.error, s.failure.title || "") } diff --git a/freevideo_engine/modern_launcher.py b/freevideo_engine/modern_launcher.py index ad0d60f2..0ac36fb5 100644 --- a/freevideo_engine/modern_launcher.py +++ b/freevideo_engine/modern_launcher.py @@ -430,6 +430,22 @@ def openReport(self, error, title): environment=environment_line(version, machine_hardware(engine) if engine else {})) self.invoke(open_browser, url) + @Slot() + def openInstallFolder(self): + from PySide6.QtGui import QDesktopServices + # The package the launcher verifies is the folder it runs from; the installation's engine folder is the fallback. + folder = Path(session.source) + if not folder.is_dir(): + engine = session.installation_engine() + folder = Path(engine).parent if engine else folder + if sys.platform.startswith('linux'): + from .windows_ux import open_folder + if not open_folder(folder.resolve()): + session.action_notice = 'folder_open_failed' + self.refresh() + return + self.invoke(QDesktopServices.openUrl, QUrl.fromLocalFile(str(folder.resolve()))) + @Slot() def openDownloadFolder(self): from PySide6.QtGui import QDesktopServices From c27aa36bb07970394f95f7b01084ad57f65319f4 Mon Sep 17 00:00:00 2001 From: Bowen Xue Date: Wed, 18 Nov 2026 03:32:09 +0000 Subject: [PATCH 24/97] The computer no longer goes to sleep on its own while a video is being made (Windows, Linux incl. The computer no longer goes to sleep on its own while a video is being made (Windows, Linux incl. desktop sleep list); not held on battery --- freevideo_engine/generate.py | 3 +- freevideo_engine/sleep_guard.py | 146 ++++++++++++++++++++++++++++++++ 2 files changed, 148 insertions(+), 1 deletion(-) create mode 100644 freevideo_engine/sleep_guard.py diff --git a/freevideo_engine/generate.py b/freevideo_engine/generate.py index 7104aab2..e67c11b8 100644 --- a/freevideo_engine/generate.py +++ b/freevideo_engine/generate.py @@ -789,7 +789,8 @@ def interrupted(signum, frame): raise KeyboardInterrupt(f'Request interrupted by signal {signum}') previous = processes.termination_handler(interrupted) try: - with runtime_lock() as descriptor: + from .sleep_guard import awake + with runtime_lock() as descriptor, awake(): if active_loras: lora_request = artifacts / 'lora-request.json' lora_result = artifacts / 'lora-result.json' diff --git a/freevideo_engine/sleep_guard.py b/freevideo_engine/sleep_guard.py new file mode 100644 index 00000000..a319c57b --- /dev/null +++ b/freevideo_engine/sleep_guard.py @@ -0,0 +1,146 @@ +"""Keep the computer from sleeping on its own while a video is being made. + +Windows holds an execution-state request, Linux the desktop's and logind's sleep inhibitors, macOS its own power assertion +(macos_power). An explicit sleep, a closed lid and the display turning off keep their normal meaning, and +on battery nothing is held unless the user asked for it. Failing to take the hold never stops a generation. +""" +from contextlib import contextmanager +import os +from pathlib import Path +import shutil +import signal +import subprocess +import sys +import time + +BATTERY_ENV = 'FREEVIDEO_AWAKE_ON_BATTERY' + + +def on_battery(): + """True only when the machine reports running on battery; unknown counts as plugged in.""" + try: + if sys.platform == 'win32': + import ctypes + + class Status(ctypes.Structure): + _fields_ = [('ACLineStatus', ctypes.c_ubyte), ('BatteryFlag', ctypes.c_ubyte), ('BatteryLifePercent', ctypes.c_ubyte), + ('SystemStatusFlag', ctypes.c_ubyte), ('BatteryLifeTime', ctypes.c_uint32), ('BatteryFullLifeTime', ctypes.c_uint32)] + status = Status() + return bool(ctypes.windll.kernel32.GetSystemPowerStatus(ctypes.byref(status))) and status.ACLineStatus == 0 + if sys.platform.startswith('linux'): + supplies = list(Path('/sys/class/power_supply').iterdir()) + kinds = {path: (path / 'type').read_text().strip() for path in supplies if (path / 'type').is_file()} + mains = [path for path, kind in kinds.items() if kind in ('Mains', 'USB')] + if not any(kind == 'Battery' for kind in kinds.values()) or not mains: + return False + return not any((path / 'online').read_text().strip() == '1' for path in mains if (path / 'online').is_file()) + except (OSError, ValueError): + pass + return False + + +WHY = 'Generating a video' + + +def _start(command): + """The helper while it holds its inhibitor, or None when it ended at once (refused or unavailable).""" + try: + # Its own process group, so the release ends the helper and the command it waits on together. + return subprocess.Popen(command, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, start_new_session=True) + except OSError: + return None + + +def _holding(processes, seconds=.3): + """The helpers still running after a short wait; one that is refused exits at once.""" + deadline = time.monotonic() + seconds + for process in processes: + try: + process.wait(timeout=max(0., deadline - time.monotonic())) + except subprocess.TimeoutExpired: + continue + return [process for process in processes if process.poll() is None] + + +def _linux_inhibitors(): + """Helpers that each hold one sleep inhibitor while they run; every hold also ends with this process. + + A desktop suspends an idle computer through logind as the same user, and logind lets that request past + the user's own inhibitors, so the desktop's own list is held too: gnome-session (suspend only, so the + screen still blanks and locks) and KDE's power management. logind's hold covers its own idle action and + a computer without a desktop; where blocking sleep is not allowed (a remote session), the idle hold alone + is kept. + """ + if not shutil.which('tail'): + return [] + wait = ['tail', f'--pid={os.getpid()}', '-f', '/dev/null'] + commands = [] + tool = shutil.which('gnome-session-inhibit') + if tool: + commands.append([tool, '--app-id', 'FreeVideo', '--reason', WHY, '--inhibit', 'suspend', *wait]) + tool = shutil.which('kde-inhibit') + if tool: + commands.append([tool, '--power', *wait]) + logind = shutil.which('systemd-inhibit') + + def hold(what): + return [logind, f'--what={what}', '--who=FreeVideo', f'--why={WHY}', '--mode=block', *wait] + if logind: + commands.append(hold('sleep:idle')) + started = [(command, _start(command)) for command in commands] + held = _holding([process for _, process in started if process is not None]) + if logind and not any(process in held for command, process in started if command[0] == logind): + held += _holding([process for process in [_start(hold('idle'))] if process is not None]) + return held + + +def _release(processes): + for process in processes: + try: + os.killpg(process.pid, signal.SIGTERM) + except OSError: + process.terminate() + for process in processes: + try: + process.wait(timeout=2) + except subprocess.TimeoutExpired: + try: + os.killpg(process.pid, signal.SIGKILL) + except OSError: + process.kill() + process.wait() + + +@contextmanager +def awake(): + """Hold the sleep prevention for the duration of the block; yields whether it is held.""" + if os.environ.get(BATTERY_ENV) != '1' and on_battery(): + yield False + return + release = None + try: + if sys.platform == 'win32': + from .windows_ux import awake as windows_awake + guard = windows_awake() + elif sys.platform == 'darwin': + from .macos_power import awake as mac_awake + guard = mac_awake() + elif sys.platform.startswith('linux'): + release = _linux_inhibitors() or None + guard = None + else: + guard = None + except Exception: + guard = None + if release is not None: + try: + yield True + finally: + _release(release) + return + if guard is None: + yield False + return + with guard as held: + yield held From 21fc638b6d52d7beb0049ec9047c47d8fcb7f487 Mon Sep 17 00:00:00 2001 From: Bowen Xue Date: Wed, 18 Nov 2026 03:32:24 +0000 Subject: [PATCH 25/97] Image generation: several pictures can wait in line, status reports the place --- freevideo_engine/image_gen/failure.py | 2 +- freevideo_engine/image_gen/service.py | 63 ++++++++++++++++----------- freevideo_engine/private_refs.py | 2 +- 3 files changed, 40 insertions(+), 27 deletions(-) diff --git a/freevideo_engine/image_gen/failure.py b/freevideo_engine/image_gen/failure.py index 1107ce22..017798ee 100644 --- a/freevideo_engine/image_gen/failure.py +++ b/freevideo_engine/image_gen/failure.py @@ -31,7 +31,7 @@ 'no_memory': '显存不足,最小尺寸也无法生成。请关闭其他占用显卡的程序后重试。', 'small_memory': '这台 Mac 的内存不足 16 GB,无法生成图片。', 'busy_video': '视频正在生成,完成后再试。', - 'busy': '已有一张图在生成,请等它完成。', + 'busy': '排队的图已满,请等前面的完成后再试。', 'pack_missing': '请先在启动器里下载“图像生成模型”。', 'model_unavailable': '这台电脑不支持所选的图片模型。请改用 Qwen-Image 2.1。', 'model_unreadable': '图像生成模型的文件读不出来。在启动器里修复后再试。', diff --git a/freevideo_engine/image_gen/service.py b/freevideo_engine/image_gen/service.py index f53352a7..b828cb4f 100644 --- a/freevideo_engine/image_gen/service.py +++ b/freevideo_engine/image_gen/service.py @@ -85,6 +85,8 @@ H3_INFERENCE_TIMEOUT = 1800. QUEUE_TIMEOUT = 600. QUEUE_POLL = .1 +# Pictures that may wait behind the running one; a further request is turned away with 'busy'. +QUEUE_LIMIT = 8 INVALID_ERRORS = frozenset(('invalid_request', 'invalid_prompt', 'invalid_dimensions', 'invalid_seed', 'invalid_media', 'invalid_points', 'too_many_images')) | LORA_ERRORS @@ -229,7 +231,7 @@ def __init__(self, installation, input_directory, *, video_busy=None, idle_secon # The last memory_budget reading of each calling thread, for the report. self.budget_reading = threading.local() self.worker_started = False - self.queued = None + self.pending = [] self.habit_root = None self.queue_thread = None self.queue_wake = threading.Event() @@ -1014,7 +1016,7 @@ def segment(self, value): raise ValueError('closed') if self.yielding or self.video_busy(): raise ValueError('busy_video') - if self.busy() or self.queued is not None: + if self.busy() or self.pending: raise ValueError('busy') try: root, machine = self.installation() @@ -1186,13 +1188,13 @@ def admit(self, action, value): raise ValueError('closed') if self.segmenting: raise ValueError('busy') - if self.queued is not None: + if len(self.pending) >= QUEUE_LIMIT: raise ValueError('busy') if self.yielding: context.set_machine(self.last_machine) raise FailureError(self.failed('busy_video', context, video_busy=True)) video = self.video_busy() - waiting = (video or self.busy() or self.thread is not None + waiting = (video or self.busy() or bool(self.pending) or self.thread is not None and self.thread.is_alive() and self.session_stop.is_set()) raw = deepcopy(value) root, machine, prepared = self.prepare(action, raw, context, waiting=waiting) @@ -1206,9 +1208,10 @@ def admit(self, action, value): _, names = self.uploads.popitem(last=False) self.remove_uploads(names) if waiting: - self.queued = dict(key=key, action=action, value=raw, context=context, - state=dict(phase='queued', queued_behind='video' if video else 'image'), - video_since=time.monotonic() if video else None) + self.pending.append(dict(key=key, action=action, value=raw, context=context, + state=dict(phase='queued', queued_behind='video' if video else 'image', + queue_position=len(self.pending) + 1), + video_since=time.monotonic() if video else None)) if self.queue_thread is None or not self.queue_thread.is_alive(): self.queue_thread = threading.Thread(target=self.wait_queued, name='freevideo-image-queue', daemon=True) @@ -1301,7 +1304,7 @@ def skipped(reason): with self.mutex: if self.closed: return skipped('closed') - if self.segmenting or self._busy or self.queued is not None: + if self.segmenting or self._busy or bool(self.pending): return skipped('busy') if self.thread is not None and self.thread.is_alive() and self.session_stop.is_set(): return skipped('busy') @@ -1477,20 +1480,24 @@ def begin(self, key, root, machine, value, context): else: self.requests.put(value) - def discard_queued(self, state): - self.drop_uploads(self.queued['key']) - self.remember(self.queued['key'], state) - self.queued = None + def discard_queued(self, state, pending=None): + """Drop one waiting request (the first unless named) and move the ones behind it up.""" + pending = pending or self.pending[0] + self.drop_uploads(pending['key']) + self.remember(pending['key'], state) + self.pending.remove(pending) + for place, other in enumerate(self.pending, 1): + other['state']['queue_position'] = place self.queue_wake.set() def wait_queued(self): while True: with self.mutex: - pending = self.queued - if pending is None: + if not self.pending: # Clearing under the lock lets a new admission start a reader. self.queue_thread = None return + pending = self.pending[0] if self.closed: self.discard_queued(dict(phase='cancelled')) continue @@ -1499,7 +1506,9 @@ def wait_queued(self): except Exception as error: self.discard_queued(self.failed(classify_exception(error), pending['context'], error=error)) continue - pending['state']['queued_behind'] = 'video' if video else 'image' + for place, other in enumerate(self.pending, 1): + other['state']['queued_behind'] = 'video' if video else 'image' + other['state']['queue_position'] = place if video: if pending['video_since'] is None: pending['video_since'] = time.monotonic() @@ -1526,7 +1535,9 @@ def wait_queued(self): else classify_exception(error)) self.discard_queued(self.failed(code, pending['context'], error=error)) else: - self.queued = None + self.pending.remove(pending) + for place, other in enumerate(self.pending, 1): + other['state']['queue_position'] = place self.begin(pending['key'], root, machine, value, pending['context']) continue self.queue_wake.clear() @@ -1777,8 +1788,9 @@ def matches(candidate): if row.get('phase') in ('complete', 'failed', 'cancelled'): self.drop_uploads(self.key) return row - if self.queued is not None and matches(self.queued['key']): - return deepcopy(self.queued['state']) + for waiting in self.pending: + if matches(waiting['key']): + return deepcopy(waiting['state']) for candidate, state in self.finished.items(): if matches(candidate): self.drop_uploads(candidate) @@ -1817,7 +1829,8 @@ def cancel(self, key): with self.mutex: row = self.status(key) if row['phase'] == 'queued': - self.discard_queued(dict(phase='cancelled')) + mine = next(w for w in self.pending if secrets.compare_digest(key.encode('utf-8'), w['key'].encode('utf-8'))) + self.discard_queued(dict(phase='cancelled'), mine) return dict(phase='cancelled') if key != self.key or not self.busy(): return row @@ -1846,10 +1859,10 @@ def stop_for_generation(self, only_idle=False, video=None): self.segment_stop.set() self.stop.set() self.session_stop.set() - if self.queued is not None: - self.queued['state']['queued_behind'] = 'video' - if self.queued['video_since'] is None: - self.queued['video_since'] = time.monotonic() + for waiting in self.pending: + waiting['state']['queued_behind'] = 'video' + if waiting['video_since'] is None: + waiting['video_since'] = time.monotonic() thread = self.thread try: self.close_segment_worker() @@ -1867,7 +1880,7 @@ def keeps_through_video(self): between jobs (no picture, no placement, no model load asked for or under way), so it holds no lease. Called under the mutex.""" return (self.per_request and server_mode.coresident() and not self._busy and not self.placing - and not self.segmenting and self.segment_worker is None and self.queued is None + and not self.segmenting and self.segment_worker is None and not self.pending and self.thread is not None and self.thread.is_alive() and not self.session_stop.is_set() and self.worker is not None and self.requests.empty() and not self.loading_full) @@ -1912,7 +1925,7 @@ def lease(path, descriptor): def close(self): with self.mutex: self.closed = True - if self.queued is not None: + while self.pending: self.discard_queued(dict(phase='cancelled')) queue_thread = self.queue_thread self.stop_for_generation() diff --git a/freevideo_engine/private_refs.py b/freevideo_engine/private_refs.py index c08d32c6..86fb921d 100644 --- a/freevideo_engine/private_refs.py +++ b/freevideo_engine/private_refs.py @@ -431,7 +431,7 @@ def generating(): running, pending = [], [] image = getattr(server, '_freevideo_image_gen', None) try: - image_busy = bool(image is not None and (image.busy() or image.queued is not None)) + image_busy = bool(image is not None and (image.busy() or bool(image.pending))) except Exception: image_busy = False return bool(running or pending) or image_busy From 095daedb3b4a5d1eb165337c1b4196f630963648 Mon Sep 17 00:00:00 2001 From: Bowen Xue Date: Wed, 18 Nov 2026 03:34:21 +0000 Subject: [PATCH 26/97] Cache and compress the page's files for remote visits Hashed frontend assets are kept by the browser; other page files are checked again with a content ETag and answer 304 when unchanged, so an update is always picked up. JS, CSS and large JSON answers are sent gzip-compressed. FREEVIDEO_PAGE_CACHE=off restores the old behaviour. --- __init__.py | 7 + freevideo_engine/web_cache.py | 254 ++++++++++++++++++++++++++++++++++ 2 files changed, 261 insertions(+) create mode 100644 freevideo_engine/web_cache.py diff --git a/__init__.py b/__init__.py index 6bc06436..aecf6e3f 100644 --- a/__init__.py +++ b/__init__.py @@ -48,6 +48,13 @@ async def comfy_entrypoint(): except Exception as error: import logging logging.warning('[FreeVideo] Opening screen not registered: %s', error) + try: + # The page's files once, compressed, then checked again instead of downloaded again on every visit. + from .freevideo_engine.web_cache import register as page_cache + page_cache() + except Exception as error: + import logging + logging.warning('[FreeVideo] Page file caching not registered: %s', error) from .freevideo_engine.comfy_launcher_api import register as launcher_routes launcher_routes() from .freevideo_engine.comfy_updates import register as update_routes diff --git a/freevideo_engine/web_cache.py b/freevideo_engine/web_cache.py new file mode 100644 index 00000000..0af04a7a --- /dev/null +++ b/freevideo_engine/web_cache.py @@ -0,0 +1,254 @@ +"""The page's own files arrive once, compressed, and are checked again instead of downloaded again. + +ComfyUI marks every .js and .css file ``no-store`` and sends them uncompressed, so each visit downloads the whole +interface (about 30 MB) again; on a remote link that is most of the time before anything appears. This middleware, +which runs inside ComfyUI's ``cache_control`` (that one only adds Cache-Control when none is set): + +* ``/assets/-.``: the frontend build names these after their content, so a new version always has new + addresses; the browser keeps them (``public, max-age=31536000, immutable``). +* every other page file (FreeVideo's ``/extensions/...``, ``/scripts/...``, unhashed files): ``no-cache``, so the + browser asks again on every visit and an unchanged file answers 304 with no body. The ETag is taken from the file's + content, so a file changed by an update is always sent again, even when the update kept its time and size. +* text files (JS, CSS, JSON, SVG, HTML, maps) go out gzip-compressed to browsers that accept it; the compressed copy is + kept in memory until the file changes. +* ``/api/object_info``: ETag from the body and ``no-cache``, so an unchanged node list answers 304; large JSON answers + are compressed. + +The page itself (``/``, ``/index.html``) keeps ComfyUI's ``no-store``: it is the one file that names the hashed +assets, so after an update the first visit reads the new names. Answers that already carry Cache-Control, Content- +Encoding or a Range request are left alone. +""" +import asyncio +import collections +import gzip +import hashlib +import logging +import os +import re +import threading + +IMMUTABLE = 'public, max-age=31536000, immutable' +REVALIDATE = 'no-cache' +HASHED = re.compile(r'^/assets/[^/]+-[A-Za-z0-9_-]{8}\.[A-Za-z0-9]+$') +TEXT = frozenset(('.js', '.mjs', '.css', '.json', '.svg', '.html', '.htm', '.txt', '.map', '.xml', '.wasm')) +PAGE = frozenset(('/', '/index.html')) +OBJECT_INFO = frozenset(('/object_info', '/api/object_info')) +SMALLEST = 1024 # below this gzip saves less than one round trip costs +JSON_SMALLEST = 8192 +LEVEL = 6 +CACHE_BYTES = 64 << 20 # compressed copies kept; the whole interface is about 8 MB compressed + + +# Fixed, so a Windows registry that maps .js to text/plain cannot break module loading. +TYPES = {'.js': 'text/javascript', '.mjs': 'text/javascript', '.css': 'text/css', '.json': 'application/json', + '.map': 'application/json', '.svg': 'image/svg+xml', '.html': 'text/html', '.htm': 'text/html', + '.txt': 'text/plain', '.xml': 'application/xml', '.wasm': 'application/wasm'} + + +def content_type(path): + suffix = os.path.splitext(str(path))[1].lower() + if suffix in TYPES: + return TYPES[suffix] + import mimetypes + return mimetypes.guess_type(str(path))[0] or 'application/octet-stream' + + +def accepts_gzip(request): + for part in request.headers.get('Accept-Encoding', '').lower().split(','): + name, _, quality = part.strip().partition(';') + if name.strip() in ('gzip', '*'): + quality = quality.strip() + if quality.startswith('q='): + try: + return float(quality[2:]) > 0 + except ValueError: + return False + return True + return False + + +def matches(request, etag): + """Whether If-None-Match names this ETag (weak comparison, as for a GET).""" + try: + tags = request.if_none_match + except Exception: + return False + if not tags: + return False + value = etag.strip('"') + return any(tag.value in ('*', value) for tag in tags) + + +class Copies: + """Compressed (or, when gzip does not help, plain) copies of page files, by path, until the file changes.""" + + def __init__(self, limit=CACHE_BYTES): + self.limit = limit + self.size = 0 + self.rows = collections.OrderedDict() + self.lock = threading.Lock() + + def get(self, path): + """(etag, last_modified, body, gzipped) for the file as it is now; None when it cannot be read.""" + try: + info = os.stat(path) + except OSError: + return None + key = (info.st_mtime_ns, info.st_size) + with self.lock: + row = self.rows.get(path) + if row is not None and row[0] == key: + self.rows.move_to_end(path) + return row[1] + try: + with open(path, 'rb') as source: + data = source.read() + except OSError: + return None + digest = hashlib.sha1(data).hexdigest()[:20] + packed = gzip.compress(data, compresslevel=LEVEL, mtime=0) if len(data) >= SMALLEST else data + if len(packed) < len(data) * 0.9: + value = ('"%s-gz"' % digest, info.st_mtime, packed, True) + else: + value = ('"%s"' % digest, info.st_mtime, data, False) + with self.lock: + old = self.rows.pop(path, None) + if old is not None: + self.size -= len(old[1][2]) + self.rows[path] = (key, value) + self.size += len(value[2]) + while self.size > self.limit and len(self.rows) > 1: + _, dropped = self.rows.popitem(last=False) + self.size -= len(dropped[1][2]) + return value + + +class Bodies: + """The last few compressed JSON bodies by content, so an unchanged node list is not compressed again.""" + + def __init__(self, keep=4): + self.keep = keep + self.rows = collections.OrderedDict() + self.lock = threading.Lock() + + def get(self, digest, body): + with self.lock: + if digest in self.rows: + self.rows.move_to_end(digest) + return self.rows[digest] + packed = gzip.compress(body, compresslevel=LEVEL, mtime=0) + with self.lock: + self.rows[digest] = packed + while len(self.rows) > self.keep: + self.rows.popitem(last=False) + return packed + + +def middleware_for(copies=None, bodies=None): + from aiohttp import web + copies = copies or Copies() + bodies = bodies or Bodies() + failed = [] + comfy_compresses = [] + + def warn(error): + if not failed: + failed.append(error) + logging.warning('[FreeVideo] Page files sent without compression: %s', error) + + def headers_from(response, *names): + return {name: response.headers[name] for name in names if name in response.headers} + + async def static(request, response, path): + # A file from web.static (the frontend package or an extension folder). + if 'Cache-Control' in response.headers or 'Content-Encoding' in response.headers: + return response + policy = IMMUTABLE if HASHED.match(request.path) else REVALIDATE + if 'Range' in request.headers or os.path.splitext(str(path))[1].lower() not in TEXT or not accepts_gzip(request): + response.headers['Cache-Control'] = policy + return response + try: + copy = await asyncio.to_thread(copies.get, str(path)) + except Exception as error: + warn(error) + copy = None + if copy is None: + response.headers['Cache-Control'] = policy + return response + etag, modified, body, gzipped = copy + headers = {'Cache-Control': policy, 'ETag': etag, 'Vary': 'Accept-Encoding'} + if matches(request, etag): + return web.Response(status=304, headers=headers) + if gzipped: + headers['Content-Encoding'] = 'gzip' + out = web.Response(body=body, headers=headers) + out.content_type = response.headers.get('Content-Type') or content_type(path) + out.last_modified = modified + return out + + async def json_answer(request, response): + body = response.body + if not isinstance(body, (bytes, bytearray)) or 'Content-Encoding' in response.headers: + return response + etag = None + if request.path in OBJECT_INFO and response.status == 200: + digest = hashlib.sha1(body).hexdigest()[:20] + etag = '"%s"' % digest + if matches(request, etag): + headers = {'ETag': etag, 'Vary': 'Accept-Encoding', 'Cache-Control': response.headers.get('Cache-Control', REVALIDATE)} + return web.Response(status=304, headers=headers) + response.headers['ETag'] = etag + response.headers.setdefault('Cache-Control', REVALIDATE) + if len(body) < JSON_SMALLEST or not accepts_gzip(request) or comfy_compresses[0]: + return response + try: + if etag is not None: + packed = await asyncio.to_thread(bodies.get, etag, bytes(body)) + elif len(body) > (256 << 10): + packed = await asyncio.to_thread(gzip.compress, bytes(body), LEVEL, mtime=0) + else: + packed = gzip.compress(bytes(body), compresslevel=LEVEL, mtime=0) + except Exception as error: + warn(error) + return response + response.body = packed + response.headers['Content-Encoding'] = 'gzip' + response.headers['Vary'] = 'Accept-Encoding' + return response + + @web.middleware + async def page_files(request, handler): + response = await handler(request) + if request.method not in ('GET', 'HEAD') or request.path in PAGE or response.status != 200: + return response + if not comfy_compresses: + # ComfyUI's --enable-compress-response-body compresses JSON itself; never compress twice. + comfy_compresses.append(any(getattr(m, '__name__', '') == 'compress_body' for m in request.app.middlewares)) + if isinstance(response, web.FileResponse): + # Only the page's folders (web.static); a picture or video from /view keeps its own rules. + resource = getattr(getattr(request.match_info, 'route', None), 'resource', None) + path = getattr(response, '_path', None) if isinstance(resource, web.StaticResource) else None + return response if path is None else await static(request, response, path) + if type(response) is web.Response and response.content_type == 'application/json': + return await json_answer(request, response) + return response + + return page_files + + +def register(server=None): + """Install on ComfyUI's page server; called while the custom node loads, before the server starts.""" + if os.environ.get('FREEVIDEO_PAGE_CACHE', '').strip().lower() in ('0', 'off', 'false', 'no'): + return False + if server is None: + from server import PromptServer + server = PromptServer.instance + app = getattr(server, 'app', None) + if server is None or app is None or getattr(server, '_freevideo_page_cache', False): + return False + if app.frozen: + logging.warning('[FreeVideo] Page file caching not added: the page server is not open for additions') + return False + app.middlewares.append(middleware_for()) + server._freevideo_page_cache = True + return True From 02ab58546c2ab12acde8a6e186e4d11ef8286401 Mon Sep 17 00:00:00 2001 From: Bowen Xue Date: Wed, 18 Nov 2026 03:34:34 +0000 Subject: [PATCH 27/97] Setup check ignores an empty or damaged saved record, names the file, and saves its own records... Setup check ignores an empty or damaged saved record, names the file, and saves its own records durably An installation record that was cut short by a power loss or a crash (an empty or zero-filled machine.json, or the plan.json of the previous setup) ended every setup check with "Expecting value: line 1 column 1 (char 0)" and no file name, so the launcher could not get past it. The check now skips such a record, says in its warnings which file it could not read, and continues; a file that cannot be read at all (permissions, a locked disk) still stops with its path. Setup already keeps the former machine.json as machine.before.json, so nothing is renamed or removed. machine.json and the setup plan are now written with a flush to disk, as the download ledgers already are. --- freevideo_engine/bootstrap.py | 37 ++++++++++++++++++++++++++++------- 1 file changed, 30 insertions(+), 7 deletions(-) diff --git a/freevideo_engine/bootstrap.py b/freevideo_engine/bootstrap.py index 3ed9e837..46ab4e0b 100644 --- a/freevideo_engine/bootstrap.py +++ b/freevideo_engine/bootstrap.py @@ -576,15 +576,37 @@ def prepare_end(ui, success=True): ui.end(PREPARE_KEY, success=success) +def read_state(path, warnings=None): + """The JSON record in an installation state file, or {} when there is none that can be used. + + A file that is empty, cut short or not JSON (a power loss can leave a zero-filled one) is + ignored and named in ``warnings``, so one damaged record no longer ends every check; setup + keeps the former machine.json as machine.before.json. A file that cannot be read at all + (permissions, a locked disk) still raises, with its path in the error.""" + path = Path(path) + if not path.is_file(): + return {} + try: + value = json.loads(path.read_text(encoding='utf-8')) + if not isinstance(value, dict): + raise ValueError('not a JSON object') + except ValueError as error: + if warnings is not None: + warnings.append('%s in the installation folder could not be read (%s), so its saved settings were not used.' + % (path.name, str(error)[:80])) + return {} + return value + + def plan(args, *, local_progress=None, stage=None): root = args.root.expanduser().resolve() warnings = [] - saved = json.loads((root / 'machine.json').read_text(encoding='utf-8')) if (root / 'machine.json').is_file() else {} + saved = read_state(root / 'machine.json', warnings) storage = getattr(args, 'storage', None) or saved.get('storage', 'compact') layout = select_layout(getattr(args, 'environment', None), saved) # v0.2.0 stored the encoder directory only in its retained setup plan. prior_path = Path(saved['setup_run']) / 'plan.json' if saved.get('setup_run') else None - prior = json.loads(prior_path.read_text(encoding='utf-8')) if prior_path and prior_path.is_file() else {} + prior = read_state(prior_path, warnings) if prior_path else {} # Hardware detection is the default for fresh installs, updates and retries. # Saved benchmark caps must never silently follow a user onto a larger GPU. keep_limits = getattr(args, 'keep_resource_limits', False) @@ -669,7 +691,8 @@ def plan(args, *, local_progress=None, stage=None): for name in ('machine.json', 'prepared-cache.json'): cache_record = root / name if cache_record.is_file(): - record = json.loads(cache_record.read_text(encoding='utf-8')) + # machine.json was reported above when it was damaged; do not repeat it here. + record = read_state(cache_record, warnings if name != 'machine.json' else None) candidate = record.get('cache') if record.get('model_revision') == revision and candidate and cache_compatible(candidate, **cache_format): if own and Path(candidate).resolve() == Path(own['cache']).resolve(): @@ -1354,12 +1377,12 @@ def initialize(self, value, ui): self.runtime_fd = self.locks.enter_context(runtime_lock(lock_path, wait_seconds=3)) self.run_dir = self.root / 'setup-runs' / (time.strftime('%Y%m%dT%H%M%SZ', time.gmtime()) + '-' + str(os.getpid())) self.run_dir.mkdir(parents=True, exist_ok=False) - save(self.run_dir / 'plan.json', value) + save(self.run_dir / 'plan.json', value, durable=True) previous = self.root / 'machine.json' saved = {} if previous.is_file(): shutil.copyfile(previous, self.run_dir / 'machine.before.json') - saved = json.loads(previous.read_text(encoding='utf-8')) + saved = read_state(previous) self.saved = saved # Changed PyTorch files (runtime_libraries) stop torch from importing, # so no GPU check can pass until the torch step below reinstalls them. @@ -1434,7 +1457,7 @@ def mark_unfinished(self): encoder_model_root=value.get('encoder_dir', saved.get('encoder_model_root')), wheel_cache=value.get('wheel_cache', saved.get('wheel_cache')), vram_gib=value.get('vram_gib', saved.get('vram_gib')), - ram_gib=value.get('ram_gib', saved.get('ram_gib')))) + ram_gib=value.get('ram_gib', saved.get('ram_gib'))), durable=True) def device_environment(self, env): from .triton_compat import environment @@ -2458,7 +2481,7 @@ def built(fraction): self.monitor_thread.join(timeout=5) if self.monitor_thread.is_alive() or self.cancel.is_set(): raise RuntimeError(self.state.get('resource_guard', 'Installation monitoring did not stop cleanly.')) - save(self.root / 'machine.json', configuration) + save(self.root / 'machine.json', configuration, durable=True) self.ui.phase('Setup complete', total, total) return configuration From 72e6be5a9f1b63695c3131f8412138abb5a9f47d Mon Sep 17 00:00:00 2001 From: Bowen Xue Date: Wed, 18 Nov 2026 03:34:49 +0000 Subject: [PATCH 28/97] Create panel: the prompt box grows with its text up to 170 px (120 px in a narrow window), in... Create panel: the prompt box grows with its text up to 170 px (120 px in a narrow window), in every browser; browser test added --- web/glass/studio.css | 5 +++-- web/studio_console.js | 16 ++++++++++++++++ 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/web/glass/studio.css b/web/glass/studio.css index ccc3f95d..901401c8 100644 --- a/web/glass/studio.css +++ b/web/glass/studio.css @@ -402,7 +402,8 @@ .fv-studio.fv-create .fvs-console .fv-runbar{min-width:96px} .fv-studio.fv-create .fvs-console .fv-runrow>.fv-primary{min-height:var(--fv-touch);height:var(--fv-touch);padding:0 var(--fv-sp-12);font-size:var(--fv-fs-2);border-radius:var(--fv-rad-ctl)} .fv-studio.fv-create .fvs-chip .fvs-chip-extra{display:none} - .fv-studio.fv-create .fvs-console .fv-prompt-editor textarea{height:88px;min-height:88px} + .fv-studio.fv-create .fvs-console .fv-prompt-editor textarea{height:88px;min-height:88px;max-height:120px} + @supports (field-sizing:content){.fv-studio.fv-create .fvs-console .fv-prompt-editor textarea{field-sizing:content;height:auto}} .fv-studio.fv-create .fvs-console .fv-prompt-tools{flex-direction:column;height:auto} .fv-studio.fv-create .fvs-console .fv-prompt-tools>.fv-prompt-help{display:none} .fv-studio.fv-create .fvs-stagebar .fv-actions[data-layout=stage] .fv-action:not(.fv-action-primary):not(.fv-action-icon):not(.fv-more-item)>span:last-child{position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%)} @@ -689,7 +690,7 @@ /* Two lines when short, growing with the text up to five. */ /* The description takes the row the enhancement switch had (the switch is a key in the chip row now): three lines when short, growing with the text up to six. */ - .fv-studio.fv-create .fvs-console .fv-prompt-editor textarea{field-sizing:content;height:auto;min-height:calc(56px + var(--fvs-row) + var(--fv-sp-8));max-height:152px;padding:var(--fv-sp-4) 0;font-size:var(--fv-fs-3);line-height:24px} + .fv-studio.fv-create .fvs-console .fv-prompt-editor textarea{field-sizing:content;height:auto;min-height:calc(56px + var(--fvs-row) + var(--fv-sp-8));max-height:170px;padding:var(--fv-sp-4) 0;font-size:var(--fv-fs-3);line-height:24px} .fv-studio.fv-create .fvs-console .fv-prompt-tools{position:absolute;top:0;right:calc(-1 * (var(--fvs-key-w) + var(--fv-sp-16)));height:var(--fv-ctl);gap:var(--fv-sp-4)} /* Chips: one shape, one height, 8 px apart; icon-only chips are square. */ .fv-studio.fv-create .fvs-chips{grid-column:1;grid-row:3;align-self:end;margin-left:0;gap:var(--fv-sp-8);min-height:var(--fvs-row)} diff --git a/web/studio_console.js b/web/studio_console.js index 83f250c9..25968e82 100644 --- a/web/studio_console.js +++ b/web/studio_console.js @@ -27,6 +27,9 @@ export function tip(element, name, use = '', key = '') { return element; } +// The prompt's tallest height: 170 px, 120 px in a narrow window so Generate stays on the first screen. +const promptMax = () => globalThis.matchMedia?.('(max-width:760px)').matches ? 120 : 170; + // trays: [{id, title, element}] where element is a
(its summary is hidden; open is the tray's state) // or any element, which is then wrapped in one. chips: what each chip shows, read again on sync(). export function createConsole({t, body, controls, prompt, runbar, trays, chips, status = [], onTray = () => {}}) { @@ -110,7 +113,20 @@ export function createConsole({t, body, controls, prompt, runbar, trays, chips, for (const [id, item] of rows) item.chip?.setAttribute('aria-expanded', String(id === open)); onTray(open, open ? rows.get(open).details : null); } + // The prompt grows with its text up to 170 px (120 px in a narrow window). Browsers that size a text box by its content (field-sizing) do it + // in CSS; the others get the same height here, so the box is never a fixed strip with a scroll bar inside it. + const sizesItself = Boolean(globalThis.CSS?.supports?.('field-sizing', 'content')); + function fitPrompt() { + if (sizesItself) return; + const area = box.querySelector('.fv-prompt-editor textarea'); if (!area || !area.offsetParent) return; + area.style.height = 'auto'; + const edge = area.offsetHeight - area.clientHeight; + area.style.height = `${Math.min(area.scrollHeight + edge, promptMax())}px`; + } + box.addEventListener('input', event => { if (event.target?.matches?.('.fv-prompt-editor textarea')) fitPrompt(); }); + if (!sizesItself && globalThis.ResizeObserver) new ResizeObserver(() => fitPrompt()).observe(box); function sync() { + fitPrompt(); for (const spec of built) { if (!spec.read) continue; const value = spec.read() || {}; From 18148f037ed4f9af4ff98a3411b56761cfde1fe6 Mon Sep 17 00:00:00 2001 From: Bowen Xue Date: Wed, 18 Nov 2026 03:36:26 +0000 Subject: [PATCH 29/97] Deleting a work for good also removes its report number from the report index The report index names each video's run folder by date and run id. A work removed for good (single delete, a batch once its undo time is over, the failed-run cleanup, leftovers in the trash) now drops its rows from the index and from the running service. At start-up, rows whose run folder no longer exists are dropped, and an index that cannot be read is removed. A batch that can still be undone keeps its report. --- freevideo_engine/comfy_library.py | 12 +++++ freevideo_engine/comfy_progress.py | 78 +++++++++++++++++++++++++----- 2 files changed, 77 insertions(+), 13 deletions(-) diff --git a/freevideo_engine/comfy_library.py b/freevideo_engine/comfy_library.py index a9728b98..8a4e5009 100644 --- a/freevideo_engine/comfy_library.py +++ b/freevideo_engine/comfy_library.py @@ -959,6 +959,12 @@ def _forget_works(root, facts): a note of their prompts so the page forgets them too unless a kept work uses the same prompt.""" if not facts: return + try: + # The report number of each work, which named its run folder. + from .comfy_progress import REPORTS + REPORTS.forget(root, {fact['run'] for fact in facts}) + except Exception: + logging.warning('[FreeVideo] Could not forget the report numbers of a deleted creation.', exc_info=True) try: kept_receipts, kept_prompts = _kept_facts(root) except OSError: @@ -1511,6 +1517,12 @@ def release(): finish_deleted(folder_paths.get_output_directory(), everything=True) except Exception: logging.warning('FreeVideo could not finish removing deleted creations.', exc_info=True) + try: + # Report numbers of works an earlier version deleted without forgetting them. + from .comfy_progress import REPORTS + REPORTS.forget(Path(folder_paths.get_output_directory()).resolve() / 'FreeVideo') + except Exception: + logging.warning('FreeVideo could not tidy the report index.', exc_info=True) threading.Thread(target=release, name='freevideo-release-decoded', daemon=True).start() @server.routes.get('/freevideo/sampling-estimate') diff --git a/freevideo_engine/comfy_progress.py b/freevideo_engine/comfy_progress.py index 4bd14606..b7d510f1 100644 --- a/freevideo_engine/comfy_progress.py +++ b/freevideo_engine/comfy_progress.py @@ -190,6 +190,8 @@ def __init__(self): self.roots = set() self.dispatches = {} self.lock = threading.Lock() + # One writer of report-ids.json at a time: a run being noted and a deleted work being forgotten. + self.index_lock = threading.Lock() def register(self, output): token = uuid.uuid4().hex @@ -233,22 +235,72 @@ def _remember(self, token, output): if index is None: return try: + with self.index_lock: + try: + rows = json.loads(index.read_text('utf-8')) + except (OSError, ValueError): + rows = {} + rows = {key: value for key, value in (rows if isinstance(rows, dict) else {}).items() + if isinstance(value, str)} + self.roots.add(index.parent.parent) + rows[token] = output.relative_to(index.parent.parent).as_posix() + while len(rows) > 256: + del rows[next(iter(rows))] + index.parent.mkdir(parents=True, exist_ok=True) + self._write_index(index, rows) + except Exception: + pass # Reports stay readable in this process; the index is only a convenience. + + @staticmethod + def _write_index(index, rows): + temporary = index.with_name('report-ids.%s.tmp' % uuid.uuid4().hex) + temporary.write_text(json.dumps(rows), 'utf-8') + os.replace(temporary, index) + + def forget(self, root, runs=None): + """A work deleted for good leaves no report number behind: drop the numbers of the given run folders (by + name) from this process and from /.agent/report-ids.json. With runs=None (at start-up), drop the rows + whose run folder no longer exists, which deletions of an earlier version left. An index that cannot be read + is removed: it is only a convenience, and what it holds can no longer be checked.""" + root = Path(root) + names = None if runs is None else {run for run in runs if isinstance(run, str) and run} + if names is not None and not names: + return + with self.lock: + for token in [token for token, output in self.runs.items() if names is not None and Path(output).parent.name in names]: + del self.runs[token] + self.dispatches.pop(token, None) + index = root / '.agent' / 'report-ids.json' + with self.index_lock: try: rows = json.loads(index.read_text('utf-8')) + except FileNotFoundError: + return except (OSError, ValueError): - rows = {} - rows = {key: value for key, value in (rows if isinstance(rows, dict) else {}).items() - if isinstance(value, str)} - self.roots.add(index.parent.parent) - rows[token] = output.relative_to(index.parent.parent).as_posix() - while len(rows) > 256: - del rows[next(iter(rows))] - index.parent.mkdir(parents=True, exist_ok=True) - temporary = index.with_name('report-ids.%s.tmp' % uuid.uuid4().hex) - temporary.write_text(json.dumps(rows), 'utf-8') - os.replace(temporary, index) - except Exception: - pass # Reports stay readable in this process; the index is only a convenience. + rows = None + try: + if not isinstance(rows, dict): + index.unlink() + return + + def keep(relative): + if not isinstance(relative, str) or not relative: + return False + path = Path(relative) + if path.is_absolute() or '..' in path.parts: + return False + if names is not None: + return not names.intersection(path.parts[:-1]) + return (root / path).parent.is_dir() + kept = {token: relative for token, relative in rows.items() if keep(relative)} + if kept == rows: + return + if kept: + self._write_index(index, kept) + else: + index.unlink() + except OSError: + logging.getLogger(__name__).warning('[FreeVideo] Could not update the report index after a deletion.') @staticmethod def tokens(output_directory): From a2d63b21b8b985c3c023396613d22ab77b0d8482 Mon Sep 17 00:00:00 2001 From: Bowen Xue Date: Wed, 18 Nov 2026 03:36:42 +0000 Subject: [PATCH 30/97] Editor: when a continued part finishes generating, the next part is ready at its end, as when a... Editor: when a continued part finishes generating, the next part is ready at its end, as when a work is opened --- web/editor.js | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/web/editor.js b/web/editor.js index c72a7ceb..c3d9653f 100644 --- a/web/editor.js +++ b/web/editor.js @@ -927,9 +927,20 @@ export function openEditor({api, app, from = null, panel = {}, components: given if (completed.size || (!active && previous?.state !== job.state) || (job.output && job.output !== previous?.output)) library?.refresh({outputs: job.output ? [job.output] : [...completed]}); if (!active) jobWatchers.delete(job.id); + if (job.state === 'done' && ['queued', 'running', 'cancelling'].includes(previous?.state)) offerNextPart(job); void startHeld(); return active; } + // A continued video that has just finished gets its next part ready at its end, as opening a work does, so the + // next part continues it too. Only while the viewer is still on that video and nothing else is being sent. + function offerNextPart(job) { + const ids = new Set((job.blocks || []).map(block => block.id)); + const last = state.record.tracks[0].clips.filter(clip => ids.has(clip.id)).sort((a, b) => a.start - b.start).at(-1); + if (!last || !model.continuesBefore(state.record, last.id) || generationBusy || held.length) return; + const picked = state.selection; + if (picked && !(picked.kind === 'clip' && picked.ids.some(id => ids.has(id) || model.find(state.record, id)?.link && ids.has(model.find(state.record, id).link)))) return; + enterClip(clip => clip.id === last.id, projectEpoch, {select: false}); + } function watchJob(id) { if (disposed) return; if (!jobWatchers.has(id)) jobWatchers.set(id, store.watchChain(id, job => job ? deliverChain(job) : chainGone(id))); From 8a345eefd807e946b10aca79426e0b1605419b9c Mon Sep 17 00:00:00 2001 From: Bowen Xue Date: Wed, 18 Nov 2026 03:38:39 +0000 Subject: [PATCH 31/97] Phones: Creations in the top bar is the works entry; drop the duplicate button under the picture --- web/glass/studio.css | 6 ++---- web/studio.js | 6 +----- 2 files changed, 3 insertions(+), 9 deletions(-) diff --git a/web/glass/studio.css b/web/glass/studio.css index 901401c8..bbc332e6 100644 --- a/web/glass/studio.css +++ b/web/glass/studio.css @@ -577,8 +577,6 @@ .fv-studio.fv-create .fvs-tray .fv-effort-estimate{margin-left:0} /* An empty history (nothing made yet) keeps the rail small; it grows only after a generation, which the user started. */ .fv-studio.fv-create .fv-recent.fvs-rail[data-empty=true]{height:fit-content} -.fv-studio.fv-create .fvs-works-phone{display:none} -@media(max-width:760px){.fv-studio.fv-create .fvs-works-phone{display:inline-grid}} .fv-studio.fv-create .fv-controls>.fvs-console-status{top:var(--fv-sp-2);bottom:auto;left:var(--fv-sp-20);right:var(--fv-sp-20)} /* The picture and its bar settle once, without animation, while the panel opens; later changes ease. */ .fv-studio.fv-create[data-fv-loaded=false] :is(.fv-stage,.fv-preview-space,.fv-preview-column,.fv-recent.fvs-rail){transition:none!important} @@ -777,7 +775,7 @@ html body :is(.fv-studio.fv-create .fvs-console,.fv-editor .fv-ed-genbar .fv-ed- .fv-studio.fv-create .fv-stage{transition:width .2s ease,height .2s ease,translate .2s ease} /* With the next generation's empty frame on the stage, the bar names it ("Next · 768 × 1344"); the work's details, history and actions are hidden until a work is shown again. */ -.fv-studio.fv-create .fvs-stagebar[data-next=true] :is(.fvs-info,.fvs-history,.fvs-compare-open,.fvs-works-phone,.fvs-stagebar-end){visibility:hidden} +.fv-studio.fv-create .fvs-stagebar[data-next=true] :is(.fvs-info,.fvs-history,.fvs-compare-open,.fvs-stagebar-end){visibility:hidden} /* The duration's number edits in place (studio_console.js): a field as wide as the number it replaces, with the unit kept after it, so nothing beside the stepper moves; one frame, the field's own, and its focus line for the keyboard only (a click shows the field and the caret). */ @@ -797,7 +795,7 @@ html body .fv-studio.fv-create .fvs-stepper .fvs-step-input.fvs-step-input:is(:f .fv-studio.fv-create .fvs-stagebar[data-next=true] .fvs-stagebar-end{display:none} .fv-studio.fv-create .fvs-stagebar[data-next=true] .fvs-stagebar-start{justify-content:center} .fv-studio.fv-create .fvs-stagebar[data-next=true] .fvs-summary{flex:0 1 auto} -.fv-studio.fv-create .fvs-stagebar[data-next=true] :is(.fvs-info,.fvs-history,.fvs-compare-open,.fvs-works-phone){display:none} +.fv-studio.fv-create .fvs-stagebar[data-next=true] :is(.fvs-info,.fvs-history,.fvs-compare-open){display:none} /* Rail: two videos picked together compare on the stage. Each card has a small check (shown on hover, and on every card while picking); a picked card is outlined and numbered in the order picked. */ .fv-studio.fv-create .fvs-rail .fv-recent-card{position:relative} diff --git a/web/studio.js b/web/studio.js index 0c0ae20b..55b35199 100644 --- a/web/studio.js +++ b/web/studio.js @@ -1812,11 +1812,7 @@ export function openStudio(node, {extendFrom = null} = {}) { onChange: () => syncHistory()}); recent.element.classList.add('sgf-avoid'); recent.element.prepend(worksButton); body.append(recent.element); - // Phones have no rail: Creations sits in the bar under the picture instead. - const worksPhone = button('', () => worksButton.click(), 'fvs-icon-button fvs-works-phone'); - worksPhone.innerHTML = worksButton.querySelector('svg').outerHTML; worksPhone.setAttribute('aria-label', t('Creations', '作品库')); - tip(worksPhone, t('Creations', '作品库'), t('Open your works to sort and manage them', '打开作品库,筛选和管理')); - stageBar.start.prepend(worksPhone); + // Phones have no rail; Creations is the top bar's works entry, there at every width. function syncHistory() { stageBar.element.dataset.empty = String(!result?.video); stageBar.setHistory(recent.index(), recent.rows().length); From d628b19a7f160fc169ad5d61cae1bcd066c18b98 Mon Sep 17 00:00:00 2001 From: Bowen Xue Date: Wed, 18 Nov 2026 03:39:52 +0000 Subject: [PATCH 32/97] Touch: keep drawn widths of top-bar links and steppers, grow only the tap area --- web/glass/settings.css | 2 ++ web/glass/studio.css | 9 +++++++++ web/library.css | 10 ++++++++++ web/topbar.css | 8 +++++++- 4 files changed, 28 insertions(+), 1 deletion(-) diff --git a/web/glass/settings.css b/web/glass/settings.css index 4939aea0..c785b917 100644 --- a/web/glass/settings.css +++ b/web/glass/settings.css @@ -478,3 +478,5 @@ dialog.fv-set .st-search input:focus-visible{outline:none} dialog.fv-set .st-dock.l.is-wide .st-dh h2{display:block} } @media (max-width:719px){dialog.fv-set .st-facts3 dt{flex:none;white-space:nowrap}dialog.fv-set .st-facts3 dd{min-width:0}} +/* Tablets: the search field takes a finger (buttons and switches already reach 44 through their ::after). */ +@media (pointer:coarse){dialog.fv-set .st-search{height:var(--fv-touch)}} diff --git a/web/glass/studio.css b/web/glass/studio.css index bbc332e6..82032564 100644 --- a/web/glass/studio.css +++ b/web/glass/studio.css @@ -891,6 +891,15 @@ html body .fv-studio.fv-create .fvs-console :is(.fvs-console-prompt,.fv-section, .fv-key-menu>button[aria-pressed=true]::before{content:'✓';margin-right:var(--fv-sp-8)} .fv-key-menu>button[aria-pressed=false]::before{content:'';display:inline-block;width:1em;margin-right:var(--fv-sp-8)} @media(max-width:760px){.fv-studio.fv-create .fvs-console .fv-key-more{height:var(--fv-touch)}} +/* Tablets: the duration stepper and the menu beside Generate take a finger too (phones are covered above). */ +@media(pointer:coarse){ + .fv-studio.fv-create :is(.fvs-step,.fvs-step-value){min-height:var(--fv-touch);height:var(--fv-touch)} + /* − and + keep their drawn width so the row wraps as with a mouse; the tap area reaches 44 */ + .fv-studio.fv-create .fvs-step{position:relative} + .fv-studio.fv-create .fvs-step::after{content:"";position:absolute;top:0;bottom:0;left:calc(50% - var(--fv-touch) / 2);right:calc(50% - var(--fv-touch) / 2)} + .fv-studio.fv-create .fvs-stepper{height:var(--fv-touch)} + .fv-studio.fv-create .fvs-console .fv-key-more{width:var(--fv-touch)} + .fv-studio.fv-create .fvs-console .fv-runrow:has(>.fv-key-more:not([hidden]))>.fv-primary{padding-right:calc(var(--fv-touch) + var(--fv-sp-4))}} @media(min-width:761px){ .fv-studio.fv-create .fvs-console .fv-runrow.fv-at-moved>.fv-key-more{height:calc(2 * var(--fvs-row) + var(--fv-sp-8))} .fv-studio.fv-create .fvs-console .fv-runrow.fv-at-moved>.fv-key-more>summary{border-radius:0 var(--fv-rad-ctl) var(--fv-rad-ctl) 0} diff --git a/web/library.css b/web/library.css index 1587a520..7a5de49e 100644 --- a/web/library.css +++ b/web/library.css @@ -622,3 +622,13 @@ dialog.fv-library .fv-library-picture>img[data-loaded=true]{opacity:1} /* A card is its picture and one line, its name. */ .fv-library .fv-library-card>small{display:none} + +/* Tablets: every target takes a finger. */ +@media(pointer:coarse){ + .fv-library .fv-library-tab{height:var(--fv-touch)} + .fv-library .fv-library-place{height:var(--fv-touch);min-height:var(--fv-touch)} + .fv-library-search{height:var(--fv-touch)} + .fv-library .fv-library-tool{height:var(--fv-touch);min-height:var(--fv-touch)} + .fv-library .fv-library-dense-button{width:var(--fv-touch)}} +@media(pointer:coarse) and (min-width:681px) and (max-width:1180px){.fv-library .fv-library-place{width:var(--fv-touch)}} +@media(pointer:coarse) and (max-width:1180px){.fv-library :is(.fv-library-sort-button,.fv-library-filter-button){width:var(--fv-touch)}} diff --git a/web/topbar.css b/web/topbar.css index aca2b2fc..10c491aa 100644 --- a/web/topbar.css +++ b/web/topbar.css @@ -304,7 +304,13 @@ html body .fv-topbar.fv-topbar.fv-topbar.fv-tb-hinting>.fv-tb-right>:not(.fv-tb- /* A finger needs 44 px */ @media(pointer:coarse){ html body .fv-topbar.fv-topbar.fv-topbar :is(.fv-tb-link,.fv-tb-btn,.fv-tb-cap){height:var(--fv-touch);min-height:var(--fv-touch)} - html body .fv-topbar.fv-topbar.fv-topbar .fv-tb-btn{width:var(--fv-touch)}} + html body .fv-topbar.fv-topbar.fv-topbar .fv-tb-btn{width:var(--fv-touch)} + html body .fv-topbar.fv-topbar.fv-topbar>.fv-view-switch{height:calc(var(--fv-touch) + var(--fv-sp-8))} + html body .fv-topbar.fv-topbar.fv-topbar>.fv-view-switch>button{height:var(--fv-touch);min-height:var(--fv-touch);line-height:var(--fv-touch)} + /* the icon links keep their drawn width, so the bar folds as with a mouse; only the tap area grows to 44 */ + html body .fv-topbar.fv-topbar.fv-topbar:is([data-fv-fit="1"],[data-fv-fit="2"]) .fv-tb-link::after{content:"";position:absolute;top:0;bottom:0;left:calc(50% - var(--fv-touch) / 2);right:calc(50% - var(--fv-touch) / 2)} + /* the last one stops at the bar's edge, so the fit check measures the same width as with a mouse */ + html body .fv-topbar.fv-topbar.fv-topbar:is([data-fv-fit="1"],[data-fv-fit="2"]) .fv-tb-links>.fv-tb-link:last-child::after{right:0}} @media(prefers-reduced-motion:reduce){ html body .fv-topbar.fv-topbar.fv-topbar *,html body .fv-topbar.fv-topbar.fv-topbar>.fv-view-switch::before{transition:none!important} html body .fv-topbar.fv-topbar.fv-topbar :is(button,.fv-lan-trigger):active{scale:none}} From 7bb8f1303fd8bbf5e4226f15c76c8e2c39d3499f Mon Sep 17 00:00:00 2001 From: Bowen Xue Date: Wed, 18 Nov 2026 04:04:53 +0000 Subject: [PATCH 33/97] Media tray: keep the use box clear on narrow tiles; Edited becomes a small mark On a tile too narrow for the use box, the crop key and Remove side by side, Remove leaves the picture's corner; every tile's drop-down now lists Remove. Edited is a small pencil mark beside the use box, its words kept as its name. --- web/glass/media_tray.css | 8 ++++++-- web/glass/media_tray.js | 13 ++++++++----- 2 files changed, 14 insertions(+), 7 deletions(-) diff --git a/web/glass/media_tray.css b/web/glass/media_tray.css index dbcb9fac..f80204d6 100644 --- a/web/glass/media_tray.css +++ b/web/glass/media_tray.css @@ -26,7 +26,7 @@ /* While the tiles scroll, their lower edge fades, so a cut tile reads as more below. */ .fvs-tray .fv-mt>.fv-mt-media[data-fv-mt-scroll=true]{-webkit-mask-image:linear-gradient(to bottom,#000 calc(100% - 24px),transparent);mask-image:linear-gradient(to bottom,#000 calc(100% - 24px),transparent)} /* A tile: the picture fills the square; along its foot, the box that turns it on or off and its use. */ -.fvs-tray .fv-mt .fv-card{position:relative;box-sizing:border-box;aspect-ratio:1;min-width:0;margin:0!important;padding:0!important;border:0;border-radius:var(--fv-r-sm);background:var(--fv-ctl-bg);box-shadow:none;overflow:hidden} +.fvs-tray .fv-mt .fv-card{position:relative;container:fv-mt-card/inline-size;box-sizing:border-box;aspect-ratio:1;min-width:0;margin:0!important;padding:0!important;border:0;border-radius:var(--fv-r-sm);background:var(--fv-ctl-bg);box-shadow:none;overflow:hidden} .fvs-tray .fv-mt .fv-card[data-enabled=false] :is(.fv-preview-wrap,video.fv-preview){opacity:.45} .fvs-tray .fv-mt .fv-card .fv-preview-wrap{position:absolute;inset:0;display:block;margin:0!important;padding:0;border-radius:0;overflow:hidden;background:var(--fv-shell-bg)} .fvs-tray .fv-mt .fv-card :is(img,video).fv-preview{position:absolute;inset:0;display:block;width:100%!important;height:100%!important;max-height:none;margin:0!important;aspect-ratio:auto;object-fit:cover!important;object-position:50% 50%;border-radius:0;background:var(--fv-shell-bg)} @@ -41,7 +41,9 @@ .fvs-tray .fv-mt .fv-card>.fv-row:first-of-type select{width:100%!important;height:32px!important;min-height:32px!important;padding:0 var(--fv-sp-20) 0 var(--fv-sp-8)!important;border:0!important;border-radius:0!important; background:transparent!important;color:#fff!important;font-size:var(--fv-fs-1)!important;line-height:32px;box-shadow:none!important} .fvs-tray .fv-mt .fv-card>.fv-row:first-of-type select option{color:var(--fv-fg);background:rgb(var(--fv-solid3))} -.fvs-tray .fv-mt .fv-card .fv-edited{position:absolute;top:var(--fv-sp-4);left:calc(var(--fv-sp-4) + 20px);z-index:1;padding:0 var(--fv-sp-4);border-radius:var(--fv-r-xs);background:var(--fv-on-pic);color:var(--fv-on-fill);font-size:var(--fv-fs-1);line-height:16px;pointer-events:none} +/* Edited: a small pencil mark beside the use box; its words stay as the mark's name. */ +.fvs-tray .fv-mt .fv-card .fv-edited{position:absolute;top:var(--fv-sp-4);left:calc(var(--fv-sp-4) + 20px);z-index:1;box-sizing:border-box;width:16px;height:16px;padding:0;border-radius:var(--fv-r-xs);background:var(--fv-on-pic);color:var(--fv-on-fill);font-size:0;line-height:0;overflow:hidden;pointer-events:none} +.fvs-tray .fv-mt .fv-card .fv-edited::before{content:"";position:absolute;inset:2px;background:currentColor;-webkit-mask:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 12 12' fill='none' stroke='black' stroke-width='1.2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M2 10l.5-2.2L8 2.3l1.7 1.7-5.5 5.5z'/%3E%3C/svg%3E") center/12px no-repeat;mask:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 12 12' fill='none' stroke='black' stroke-width='1.2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M2 10l.5-2.2L8 2.3l1.7 1.7-5.5 5.5z'/%3E%3C/svg%3E") center/12px no-repeat} .fvs-tray .fv-mt .fv-card[data-fv-slot]>.fv-preview-wrap::before{content:none} /* A tile with more to set (a middle frame's time, a video's depth and sound, audio): three squares, the picture in the first, the settings beside it. */ @@ -81,6 +83,8 @@ .fvs-tray .fv-mt .fv-mt-remove{--fv-mt-icon:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' fill='none' stroke='black' stroke-width='1.5' stroke-linecap='round'%3E%3Cpath d='m4.5 4.5 7 7m0-7-7 7'/%3E%3C/svg%3E")} .fvs-tray .fv-mt .fv-card>.fv-mt-keys>:is(.fv-mt-up,.fv-mt-down){display:none!important} .fvs-tray .fv-mt .fv-card.fv-mt-crop>.fv-mt-keys{right:calc(var(--fv-sp-8) + 24px)} +/* A tile too narrow for the use box, the crop key and Remove side by side: Remove is in the tile's drop-down. */ +@container fv-mt-card (width < 100px){.fvs-tray .fv-mt .fv-card.fv-mt-crop>.fv-mt-keys>.fv-mt-remove{display:none!important}} .fvs-tray .fv-mt .fv-card .fv-shape-note{position:absolute;top:var(--fv-sp-4);right:var(--fv-sp-4);left:auto;z-index:2;display:block;margin:0!important;padding:0;border:0;background:none} .fvs-tray .fv-mt .fv-card .fv-shape-note>span{display:none} .fvs-tray .fv-mt .fv-card .fv-shape-note>button{--fv-mt-icon:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' fill='none' stroke='black' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M4.5 1.5v10h10M1.5 4.5h10v10'/%3E%3C/svg%3E")} diff --git a/web/glass/media_tray.js b/web/glass/media_tray.js index 12e4822d..bf8d8eac 100644 --- a/web/glass/media_tray.js +++ b/web/glass/media_tray.js @@ -37,6 +37,9 @@ function markCard(card) { card.dataset.fvMtWide = String(Boolean(card.querySelector(':scope > :is(.fv-time,.fv-depth-only,.fv-sound,audio.fv-preview)'))); const rows = [...card.children].filter(child => child.classList.contains('fv-row')); const controls = rows.length > 1 ? rows.at(-1) : null; + // Edited is a small mark on the picture; its words stay as the mark's name. + const edited = card.querySelector('.fv-edited'); + if (edited && !edited.title) { edited.title = edited.textContent; edited.setAttribute('role', 'img'); edited.setAttribute('aria-label', edited.textContent); } if (!controls || controls.classList.contains('fv-mt-rest')) return; controls.classList.add('fv-mt-rest'); const buttons = [...controls.querySelectorAll(':scope > button')], keys = document.createElement('div'); @@ -45,17 +48,17 @@ function markCard(card) { // The picture itself opens the editor (the panel's own handler on it); 'Original' joins the drop-down, so tiles stay one size. const original = card.dataset.kind === 'image' && buttons.length > 3 ? buttons.find((b, index) => index > 0 && b !== up && b !== down && b !== remove) : null; original?.classList.add('fv-mt-original'); - // Moving earlier or later is in the tile's drop-down, under its uses; the two keys stay in the page for it to press. - if (select && (up || down) && !select.dataset.fvMt) { + // Moving earlier or later, and Remove, are in the tile's drop-down, under its uses; the two keys stay in the page for it to press. + if (select && (up || down || remove) && !select.dataset.fvMt) { select.dataset.fvMt = '1'; select.append(document.createElement('hr')); - for (const [key, value] of [[up, 'fv-mt-earlier'], [down, 'fv-mt-later'], [original, 'fv-mt-original']]) { + for (const [key, value] of [[up, 'fv-mt-earlier'], [down, 'fv-mt-later'], [original, 'fv-mt-original'], [remove, 'fv-mt-remove']]) { if (!key) continue; - const option = document.createElement('option'); option.value = value; option.textContent = key.title || key.textContent; option.disabled = key.disabled; select.append(option); + const option = document.createElement('option'); option.value = value; option.textContent = key === remove ? key.textContent : key.title || key.textContent; option.disabled = key.disabled; select.append(option); } const chosen = select.value; select.addEventListener('change', event => { if (!select.value.startsWith('fv-mt-')) return; - event.stopImmediatePropagation(); const key = {'fv-mt-earlier': up, 'fv-mt-later': down, 'fv-mt-original': original}[select.value]; select.value = chosen; key?.click(); + event.stopImmediatePropagation(); const key = {'fv-mt-earlier': up, 'fv-mt-later': down, 'fv-mt-original': original, 'fv-mt-remove': remove}[select.value]; select.value = chosen; key?.click(); }, true); } for (const button of [up, down, remove]) { From 876decd9d79e00d3ad1eaccd880df7a8679c5120 Mon Sep 17 00:00:00 2001 From: Bowen Xue Date: Wed, 18 Nov 2026 04:08:20 +0000 Subject: [PATCH 34/97] Add MOSS-Image to image generation: picker entry, one-click install, resident or streamed... Add MOSS-Image to image generation: picker entry, one-click install, resident or streamed placement by card size --- freevideo_engine/image_gen/image_model.py | 10 +- freevideo_engine/image_gen/layer_stream.py | 174 +++++++++++ freevideo_engine/image_gen/moss_pipeline.py | 299 +++++++++++++++++++ freevideo_engine/image_gen/moss_runner.py | 77 +++++ freevideo_engine/image_gen/service.py | 62 +++- freevideo_engine/image_gen/staged_weights.py | 70 +++++ freevideo_engine/image_gen/worker.py | 15 +- web/image_view.js | 12 +- web/image_view_history.js | 7 +- web/image_view_models.js | 16 +- web/image_view_size.js | 6 +- web/settings_room.js | 1 + 12 files changed, 716 insertions(+), 33 deletions(-) create mode 100644 freevideo_engine/image_gen/layer_stream.py create mode 100644 freevideo_engine/image_gen/moss_pipeline.py create mode 100644 freevideo_engine/image_gen/moss_runner.py create mode 100644 freevideo_engine/image_gen/staged_weights.py diff --git a/freevideo_engine/image_gen/image_model.py b/freevideo_engine/image_gen/image_model.py index 0d78f1fc..71792229 100644 --- a/freevideo_engine/image_gen/image_model.py +++ b/freevideo_engine/image_gen/image_model.py @@ -12,12 +12,15 @@ QWEN = 'qwen-image-2.1-turbo' H3 = 'minimax-h3-image' -MODELS = (H3, QWEN) +MOSS = 'moss-image-sft' +MODELS = (H3, QWEN, MOSS) FILE = 'image-model.json' # Side of the square whose area each size tier asks for. H3 Image starts at 4 MP (2048 x 2048) and goes to 16 MP; # the same table as the picture page. Qwen keeps its own sizes. H3_AREAS = {'standard': 2048, 'high': 4096} +# MOSS-Image: side of the square whose area each tier asks for (1 MP, 4 MP), in steps of 16. +MOSS_AREAS = {'standard': 1024, 'high': 2048} RATIOS = {'1:1': (1, 1), '16:9': (16, 9), '9:16': (9, 16), '4:3': (4, 3), '3:4': (3, 4)} @@ -50,6 +53,11 @@ def choose(info, remembered_model=None): def size(model, aspect, tier='standard'): """Width and height for an aspect at a tier: H3 Image at 4 or 16 MP in steps of 32, else None (Qwen's table).""" + if model == MOSS: + ratio_w, ratio_h = RATIOS[aspect] + side = MOSS_AREAS.get(tier, MOSS_AREAS['standard']) + scale = math.sqrt(side * side / (ratio_w * ratio_h)) + return tuple(max(256, min(2048, round(value * scale / 16) * 16)) for value in (ratio_w, ratio_h)) if model != H3: return None ratio_w, ratio_h = RATIOS[aspect] diff --git a/freevideo_engine/image_gen/layer_stream.py b/freevideo_engine/image_gen/layer_stream.py new file mode 100644 index 00000000..e9022cbd --- /dev/null +++ b/freevideo_engine/image_gen/layer_stream.py @@ -0,0 +1,174 @@ +"""Layer-by-layer weight streaming from safetensors files, and one layer read shared by two branches. + +``DiskLayerStream`` keeps no host copy of the layers it serves: each layer is read from its file just ahead of +use into a small ring of host buffers (pinned on a CUDA device), copied to the device for the layer's forward, +and dropped afterwards. Host memory stays at the ring plus the page cache, whatever the model's size. + +``run_layers_paired`` applies every layer to two streams (the positive and the negative branch of a guided +step) so the layer is read once for both; the result is the same as running the branches one after the other. +""" +import json +import os +from concurrent.futures import ThreadPoolExecutor + +import torch + +READ_AHEAD = 3 +READ_THREADS = 4 + + +class SafetensorsIndex: + """Byte offsets of tensors in a set of safetensors files, read from the headers only.""" + + def __init__(self, folder, weight_map): + self.folder, self.weight_map, self.headers = folder, weight_map, {} + + def locate(self, key): + path = str(self.folder / self.weight_map[key]) + if path not in self.headers: + with open(path, 'rb') as handle: + size = int.from_bytes(handle.read(8), 'little') + self.headers[path] = (json.loads(handle.read(size)), 8 + size) + header, base = self.headers[path] + begin, end = header[key]['data_offsets'] + return path, base + begin, end - begin + + +def read_into(path, offset, length, buffer): + """Fill ``buffer`` (a contiguous uint8 tensor view) with ``length`` bytes at ``offset``.""" + view = memoryview(buffer.numpy()).cast('B') + descriptor = os.open(path, os.O_RDONLY) + try: + got = 0 + while got < length: + count = os.preadv(descriptor, [view[got:length]], offset + got) + if count <= 0: + raise EOFError('short read from %s' % path) + got += count + finally: + os.close(descriptor) + return length + + +class DiskLayerStream: + """Serve ``layers`` (modules with the same parameter shapes) from ``index``; ``key(i, name)`` names a tensor.""" + + def __init__(self, layers, index, key, device, ahead=READ_AHEAD, threads=READ_THREADS): + self.layers, self.index, self.key, self.device = list(layers), index, key, torch.device(device) + self.ahead, self.bytes_read = ahead, 0 + self.pool = ThreadPoolExecutor(threads) + self.ready = {} + self.pinned = self.device.type == 'cuda' + self.copy_stream = torch.cuda.Stream(self.device) if self.pinned else None + # Layers of one kind share a ring of buffers; a model that mixes kinds (attention and linear-attention + # layers) gets one ring per kind, so a layer is only ever read into a buffer of its own shape. + self.slots = [] + self.slot_kind = [] + self.free = {} + self.kinds = [] + for layer in self.layers: + params = dict(layer.named_parameters()) + kind = tuple((n, tuple(p.shape), p.dtype) for n, p in params.items()) + self.kinds.append(kind) + if kind not in self.free: + self.free[kind] = [] + for _ in range(ahead + 3): + self.free[kind].append(len(self.slots)) + self.slots.append({n: torch.empty(p.shape, dtype=p.dtype, pin_memory=self.pinned) + for n, p in params.items()}) + self.slot_kind.append(kind) + self.events = {} + self.handles = [] + for i, layer in enumerate(self.layers): + for module in layer.modules(): + for name, param in list(module.named_parameters(recurse=False)): + setattr(module, name, torch.nn.Parameter( + torch.empty(0, device=self.device, dtype=param.dtype), requires_grad=False)) + self.handles.append(layer.register_forward_pre_hook(self._before(i))) + self.handles.append(layer.register_forward_hook(self._after(i))) + + def _read(self, i, slot): + out = self.slots[slot] + for name, param in self.layers[i].named_parameters(): + path, offset, length = self.index.locate(self.key(i, name)) + want = out[name].numel() * out[name].element_size() + if length != want: + raise ValueError('%s in %s holds %d bytes, the model expects %d (%s %s); wrong dtype or shape' + % (self.key(i, name), path, length, want, out[name].dtype, tuple(out[name].shape))) + read_into(path, offset, length, out[name].view(torch.uint8).reshape(-1)) + self.bytes_read += length + return slot + + def _take_slot(self, i): + slot = self.free[self.kinds[i]].pop(0) + event = self.events.pop(slot, None) + if event is not None: + event.synchronize() + return slot + + def _kick(self, j): + if 0 <= j < len(self.layers) and j not in self.ready: + slot = self._take_slot(j) + self.ready[j] = (slot, self.pool.submit(self._read, j, slot)) + + def _before(self, i): + def hook(module, args, kwargs=None): + for j in [j for j in self.ready if not i <= j <= i + self.ahead]: + slot, future = self.ready.pop(j) + future.result() + self.free[self.kinds[j]].append(slot) + for j in range(i, i + self.ahead + 1): + if j == i or (0 <= j < len(self.layers) and self.free[self.kinds[j]]): + self._kick(j) + slot, future = self.ready.pop(i) + future.result() + current = torch.cuda.current_stream(self.device) if self.pinned else None + for name, param in module.named_parameters(): + tensor = self.slots[slot][name].to(self.device, non_blocking=self.pinned) + if self.pinned: + tensor.record_stream(current) + param.data = tensor + if self.pinned: + event = torch.cuda.Event() + event.record(current) + self.events[slot] = event + self.free[self.kinds[i]].append(slot) + return hook + + def _after(self, i): + def hook(module, args, output): + for name, param in module.named_parameters(): + param.data = torch.empty(0, device=self.device, dtype=param.dtype) + return hook + + def close(self): + for handle in self.handles: + handle.remove() + self.handles = [] + for slot, future in list(self.ready.values()): + future.exception() # wait for the read; a failed read-ahead was already reported when its layer ran + self.ready.clear() + self.pool.shutdown() + + +def run_layers_paired(layers, first, second, *, skip_second=(), call_hooks=True): + """Apply each layer to both streams; ``first``/``second`` are (x, *extra) tuples passed to ``layer(x, *extra)``. + + A layer index in ``skip_second`` is applied to the first stream only. With ``call_hooks`` the layer's forward + hooks run once per layer around the pair, which is what makes a streamed layer read once for both. + Returns the two final streams. + """ + x1, extra1 = first[0], first[1:] + x2, extra2 = second[0], second[1:] + skip = set(skip_second) + for i, layer in enumerate(layers): + if call_hooks: + for hook in list(layer._forward_pre_hooks.values()): + hook(layer, (x1,)) + x1 = layer.forward(x1, *extra1) + if i not in skip: + x2 = layer.forward(x2, *extra2) + if call_hooks: + for hook in list(layer._forward_hooks.values()): + hook(layer, (x1,), x1) + return x1, x2 diff --git a/freevideo_engine/image_gen/moss_pipeline.py b/freevideo_engine/image_gen/moss_pipeline.py new file mode 100644 index 00000000..699ec99d --- /dev/null +++ b/freevideo_engine/image_gen/moss_pipeline.py @@ -0,0 +1,299 @@ +"""MOSS-Image sampling for the image worker: prompt -> text encoder -> DiT (50 steps, guided) -> VAE -> picture. + +The model code is the file the model's repository ships (``pipeline_moss_image.py``, pinned by hash in the +install pack); this module only places the weights. Placement follows the card: + +* DiT: kept on the card when it fits (``DIT_RESIDENT_GIB``), else its 42 layers are read from the files per use + (``layer_stream.DiskLayerStream``) and each layer serves the positive and the negative branch at once, so a + guided step reads the weights once. Card use stays near 4 GiB, host memory near 4 GiB. +* Text encoder: loaded to the card for the prompt and dropped after it; read from disk per layer below + ``ENCODER_RESIDENT_GIB``. (Keeping it between requests on a very large card is not done yet.) +* VAE: float32, tiled decode. + +Both placements give the same picture (layer streaming only changes where a layer lives while it runs). +""" +import importlib.util +import json +import math +import sys +import time +from pathlib import Path + +DIT_RESIDENT_GIB = 16. +ENCODER_RESIDENT_GIB = 24. +STEPS = 50 +GUIDANCE = 3. +SKIP_LAYERS = (22,) +SIDE_MULTIPLE = 16 +MAX_SIDE = 2048 +MIN_SIDE = 256 + + +class Cancelled(Exception): + pass + + +def fit_size(width, height): + """The nearest sizes MOSS can draw: multiples of 16, each side within [MIN_SIDE, MAX_SIDE].""" + def one(value): + return min(MAX_SIDE, max(MIN_SIDE, round(value / SIDE_MULTIPLE) * SIDE_MULTIPLE)) + return one(width), one(height) + + +def load_module(folder): + """The model's own pipeline file, imported once under its repository name.""" + name = 'pipeline_moss_image' + if name in sys.modules: + return sys.modules[name] + spec = importlib.util.spec_from_file_location(name, str(Path(folder) / 'pipeline_moss_image.py')) + module = importlib.util.module_from_spec(spec) + sys.modules[name] = module + spec.loader.exec_module(module) + return module + + +def folder_key(folder): + """Identity of the installed files: names, sizes and times of the weight files.""" + parts = [] + for path in sorted(Path(folder).rglob('*.safetensors')): + stat = path.stat() + parts.append((str(path.relative_to(folder)), stat.st_size, int(stat.st_mtime))) + return tuple(parts) + + +def plan(vram_gib): + """Where each part goes for a card budget in GiB: {'dit': 'resident'|'stream', 'encoder': ...}.""" + vram = float(vram_gib or 0) + return dict(dit='resident' if vram >= DIT_RESIDENT_GIB else 'stream', + encoder='resident' if vram >= ENCODER_RESIDENT_GIB else 'stream') + + +class PairedForward: + """Replace the DiT's forward by one that runs the positive and the negative branch layer by layer, so a + streamed layer is read once for both. Returns the positive prediction and holds the negative one for the + pipeline's second call of the step.""" + + def __init__(self, transformer, negative, negative_mask, skip, device): + self.tr, self.neg, self.nmask, self.skip, self.device = transformer, negative, negative_mask, skip, device + self.original = transformer.forward + self.pending = None + transformer.forward = self.forward + + def _prepare(self, hidden, timestep, encoder, mask): + import torch + tr = self.tr + batch, _, h, w = hidden.shape + times = torch.as_tensor(timestep, device=hidden.device, dtype=torch.float32).reshape(-1).expand(batch) + half = tr.config.freq_dim // 2 + freq = 10000 ** (-torch.arange(half, device=times.device, dtype=torch.float64) / half) + phase = times.double()[:, None] * freq + emb = torch.cat((phase.cos(), phase.sin()), -1).float() + time_emb = tr.time_embedding(emb.to(tr.time_embedding[0].weight.dtype)).float() + mod = tr.shared_block_modulation(time_emb.to(tr.shared_block_modulation.weight.dtype)).view(batch, 6, -1) + head = tr.video_head_modulation(time_emb.to(tr.video_head_modulation.weight.dtype)).view(batch, 2, -1) + context = encoder[0:1, mask[0].bool()] + video = hidden[0:1].flatten(2).transpose(1, 2) + video = tr.video_embedder(video.to(tr.video_embedder.weight.dtype).contiguous()) + rope = tr.rope(h, w, context.shape[1], hidden.device).to(video.dtype) + text = tr.text_embedder(context, rope[:, h * w:]) + return torch.cat((video, text), 1), rope, mod[0:1], head[0:1], h, w + + def _finish(self, x, head, h, w): + tr = self.tr + x = tr.final_norm_video(x[:, :h * w].to(tr.final_norm_video.weight.dtype)) + x = x * (1 + head[:, 1, None]) + head[:, 0, None] + x = tr.final_linear_video(x.to(tr.final_linear_video.weight.dtype)) + return x.transpose(1, 2).reshape(1, -1, h, w) + + def forward(self, hidden_states, timestep, encoder_hidden_states, encoder_attention_mask=None, + return_dict=True, skip_layers=None): + from diffusers.models.modeling_outputs import Transformer2DModelOutput + from .layer_stream import run_layers_paired + if self.pending is not None: + out, self.pending = self.pending, None + return Transformer2DModelOutput(sample=out) + xp, rp, mp, hp, h, w = self._prepare(hidden_states, timestep, encoder_hidden_states, encoder_attention_mask) + xn, rn, mn, hn, _, _ = self._prepare(hidden_states, timestep, self.neg, self.nmask) + xp, xn = run_layers_paired(self.tr.layers, (xp, rp, mp), (xn, rn, mn), skip_second=self.skip) + self.pending = self._finish(xn, hn, h, w) + return Transformer2DModelOutput(sample=self._finish(xp, hp, h, w)) + + def close(self): + self.tr.forward = self.original + + +class Kept: + """What stays loaded between requests of one worker.""" + + def __init__(self): + self.key = None + self.dit = None # transformer on the card (resident placement only) + self.vae = None + self.negative = None # (embeds, mask) of the empty prompt, cached on the card + + def close(self): + self.dit = self.vae = self.negative = None + try: + import torch + torch.cuda.empty_cache() + except Exception: + pass + + +def _encode(module, folder, prompts, device, placement, stats): + """Encode ``prompts`` with the text encoder; returns a list of (embeds, mask) on the CPU.""" + import torch + from transformers import AutoConfig, AutoModel, AutoTokenizer + from .layer_stream import DiskLayerStream + from .staged_weights import layer_key, open_index + folder = Path(folder) + encoder_dir = folder / 'text_encoder' + tokenizer = AutoTokenizer.from_pretrained(str(folder / 'tokenizer'), local_files_only=True) + stream = None + if placement == 'resident': + text_encoder = AutoModel.from_pretrained(str(encoder_dir), dtype=torch.bfloat16, local_files_only=True) + text_encoder = text_encoder.eval().to(device) + else: + config = AutoConfig.from_pretrained(str(encoder_dir), local_files_only=True) + with torch.device('meta'): + text_encoder = AutoModel.from_config(config, dtype=torch.bfloat16).eval() + language = text_encoder.language_model if hasattr(text_encoder, 'language_model') else text_encoder.model.language_model + index = open_index(encoder_dir) + language.embed_tokens.weight = torch.nn.Parameter( + _one(index, 'language_model.embed_tokens.weight', device), requires_grad=False) + language.norm.weight = torch.nn.Parameter(_one(index, 'language_model.norm.weight', device), requires_grad=False) + language.rotary_emb = type(language.rotary_emb)(config=language.config, device=device) + stream = DiskLayerStream(language.layers, index, layer_key('language_model.'), device) + pipe = module.MOSSImagePipeline(None, module.MOSSImageScheduler(), text_encoder, tokenizer, None) + pipe.__class__._execution_device = property(lambda self: torch.device(device)) + out = [] + started = time.time() + with torch.no_grad(): + for prompt in prompts: + embeds, mask = pipe.encode_prompt(prompt) + out.append((embeds.cpu(), mask.cpu())) + stats['encode_s'] = round(time.time() - started, 2) + if stream is not None: + stats['encoder_read_gib'] = round(stream.bytes_read / 2**30, 2) + stream.close() + return out + + +def _one(index, key, device): + from safetensors import safe_open + with safe_open(str(index.folder / index.weight_map[key]), 'pt', device='cpu') as handle: + return handle.get_tensor(key).to(device) + + +def _build_dit(module, folder, device, placement): + """The DiT with its non-layer weights on the card; returns (transformer, stream or None).""" + import torch + from .layer_stream import DiskLayerStream + from .staged_weights import layer_key, open_index + folder = Path(folder) / 'transformer' + if placement == 'resident': + transformer = module.MOSSImageTransformer.from_pretrained( + str(folder), torch_dtype=torch.bfloat16, local_files_only=True).eval().to(device) + return transformer, None + config = module.MOSSImageTransformer.load_config(str(folder)) + with torch.device('meta'): + transformer = module.MOSSImageTransformer.from_config(config).to(torch.bfloat16).eval() + index = open_index(folder, 'diffusion_pytorch_model.safetensors.index.json') + small = {key: _one(index, key, device) for key in index.weight_map if not key.startswith('layers.')} + transformer.load_state_dict(small, strict=False, assign=True) + for name, buffer in transformer.named_buffers(): + if buffer.is_meta: + raise RuntimeError('MOSS-Image: buffer %s was not loaded from the files' % name) + return transformer, DiskLayerStream(transformer.layers, index, layer_key(''), device) + + +def generate(prompt, width, height, seed, progress=None, cancel=None, *, folder, vram_gib=None, kept=None, + stats=None, steps=STEPS, guidance=GUIDANCE, enter=None): + """Return a PIL image. ``progress(stage, done, total)`` stages are encode, denoise, decode.""" + import torch + progress = progress or (lambda *a: None) + stats = stats if stats is not None else {} + kept = kept if kept is not None else Kept() + device = torch.device('cuda') + width, height = fit_size(width, height) + stats['canvas'] = [width, height] + + def check(): + if cancel is not None and cancel(): + raise Cancelled() + + module = load_module(folder) + key = folder_key(folder) + if kept.key != key: + kept.close() + kept.key = key + free_gib = torch.cuda.mem_get_info()[0] / 2**30 + (torch.cuda.memory_reserved() / 2**30) + budget = min(float(vram_gib), free_gib) if vram_gib else free_gib + placement = plan(budget) + stats['placement'] = placement + check() + progress('encode', 0, 1) + if enter is not None: + enter('encode') + prompts = [prompt] + ([] if kept.negative is not None else ['']) + encoded = _encode(module, folder, prompts, device, placement['encoder'], stats) + embeds, mask = (e.to(device) for e in encoded[0]) + if kept.negative is None: + kept.negative = tuple(t.to(device) for t in encoded[1]) + negative, negative_mask = kept.negative + torch.cuda.empty_cache() + progress('encode', 1, 1) + check() + if enter is not None: + enter('denoise') + started = time.time() + resident = placement['dit'] == 'resident' + if resident and kept.dit is not None: + transformer, stream = kept.dit, None + else: + transformer, stream = _build_dit(module, folder, device, placement['dit']) + if resident: + kept.dit = transformer + stats['dit_load_s'] = round(time.time() - started, 2) + if kept.vae is None: + from diffusers import AutoencoderKLFlux2 + kept.vae = AutoencoderKLFlux2.from_pretrained(str(Path(folder) / 'vae'), torch_dtype=torch.float32, + local_files_only=True).eval().to(device) + kept.vae.enable_tiling() + scheduler = module.MOSSImageScheduler() # the repository's scheduler_config.json holds exactly these defaults + pipe = module.MOSSImagePipeline(transformer, scheduler, None, None, kept.vae) + pipe.__class__._execution_device = property(lambda self: device) + pipe.set_progress_bar_config(disable=True) + paired = None + if stream is not None and guidance != 1.0: + paired = PairedForward(transformer, negative, negative_mask, SKIP_LAYERS, device) + done = [0] + original_step = scheduler.step + + def step(*args, **kwargs): + result = original_step(*args, **kwargs) + done[0] += 1 + progress('denoise', done[0], steps) + check() + return result + scheduler.step = step + progress('denoise', 0, steps) + try: + generator = torch.Generator(device=device).manual_seed(int(seed)) + started = time.time() + torch.cuda.reset_peak_memory_stats() + result = pipe(prompt_embeds=embeds, prompt_attention_mask=mask, negative_prompt_embeds=negative, + negative_prompt_attention_mask=negative_mask, height=height, width=width, + num_inference_steps=steps, generator=generator, output_type='pil', guidance_scale=guidance) + stats['denoise_decode_s'] = round(time.time() - started, 1) + stats['peak_gib'] = round(torch.cuda.max_memory_allocated() / 2**30, 2) + finally: + if paired is not None: + paired.close() + if stream is not None: + stats['dit_read_gib'] = round(stream.bytes_read / 2**30, 2) + stream.close() + scheduler.step = original_step + torch.cuda.empty_cache() + progress('decode', 1, 1) + return result.images[0] diff --git a/freevideo_engine/image_gen/moss_runner.py b/freevideo_engine/image_gen/moss_runner.py new file mode 100644 index 00000000..cd785c68 --- /dev/null +++ b/freevideo_engine/image_gen/moss_runner.py @@ -0,0 +1,77 @@ +"""The MOSS-Image runner the image worker uses for a request that names `moss-image-sft`. + +Same surface as ``H3Runner`` (``generate``, ``idle``, ``at_boundary``, ``stats``, ``close``). Text prompts only: +the model takes no reference pictures, so a request that carries any is refused with a clear error. +""" +import os +import secrets +from pathlib import Path + +from . import image_pack + +STUB_ENV = 'FREEVIDEO_MOSS_STUB' + + +def folder(model_root): + """Where the installed MOSS-Image files are.""" + return image_pack.base(model_root) / 'moss-image' + + +class MossRunner: + full_card = False + + def __init__(self, pack_dir, *, device='cuda', progress=None): + self.pack_dir = Path(pack_dir) + self.model_root = self.pack_dir.parent + self.device = device + self.folder = folder(self.model_root) + self.last_plan = None + self.last_stats = None + self.kept = None + if progress is not None: + progress('load', 1.) + + def generate(self, prompt, *, width, height, seed=None, reference_images=None, progress=None, cancel=None, + setup=None, stage=None, **_): + progress = progress or (lambda stage, fraction: None) + if reference_images: + raise ValueError('moss_text_only') + seed = secrets.randbits(32) if seed is None else seed + self.last_plan = dict(seed=seed) + if os.environ.get(STUB_ENV) == '1': + from .h3_runner import _stub + return _stub(prompt, width=width, height=height, seed=seed, progress=progress, cancel=cancel) + from . import moss_pipeline + setup = setup or {} + names = dict(encode='text') + + def report(name, done, total): + progress(names.get(name, name), done / total if total else 0.) + + stats = {} + self.last_stats = dict(moss=stats) + if self.kept is None: + self.kept = moss_pipeline.Kept() + try: + return moss_pipeline.generate( + prompt, width, height, seed, report, (lambda: bool(cancel and cancel())), folder=self.folder, + vram_gib=setup.get('vram_gib'), kept=self.kept, stats=stats, enter=stage) + except moss_pipeline.Cancelled: + raise InterruptedError('cancelled') from None + finally: + self.last_plan = dict(seed=seed, **{key: stats[key] for key in ('canvas', 'placement') if key in stats}) + + def idle(self, should_stop): + """Nothing to prepare: the kept weights stay on the card.""" + + def at_boundary(self): + return True + + def stats(self): + return dict(plan=self.last_plan, **(self.last_stats or {})) + + def close(self): + if self.kept is not None: + self.kept.close() + self.kept = None + self.last_plan = self.last_stats = None diff --git a/freevideo_engine/image_gen/service.py b/freevideo_engine/image_gen/service.py index b828cb4f..2feaef79 100644 --- a/freevideo_engine/image_gen/service.py +++ b/freevideo_engine/image_gen/service.py @@ -37,6 +37,8 @@ H3_MAX_AREA = image_model.H3_AREAS['high'] ** 2 H3_MAX_SIDE = 8192 H3_GROUP = 'h3-image:' + image_pack.default_tier() +MOSS_GROUP = image_pack.MOSS_GROUP +MOSS_MAX_SIDE = 2048 REPORT_LIMIT = 16 # A point selection's picture stays this long after its last use, and at most this many at once. SEGMENT_KEEP = 900. @@ -83,6 +85,7 @@ HIGH_SIZE_MIN_TOTAL = 6 * 1024 ** 3 INFERENCE_TIMEOUT = 600. H3_INFERENCE_TIMEOUT = 1800. +MOSS_INFERENCE_TIMEOUT = 1800. QUEUE_TIMEOUT = 600. QUEUE_POLL = .1 # Pictures that may wait behind the running one; a further request is turned away with 'busy'. @@ -238,6 +241,7 @@ def __init__(self, installation, input_directory, *, video_busy=None, idle_secon self.finished = OrderedDict() self.pack_installer = None self.h3_installer = None + self.moss_installer = None # Model ids waiting for the other model's download to end; started one by one in memory only. self.pack_queue = [] self.pack_drain = None @@ -318,11 +322,27 @@ def model_rows(self, machine, qwen_ready, qwen_downloading): shared_bytes=0, blocked_by=active if active == image_model.H3 and not qwen_ready else None, install=queued if image_model.QWEN in waiting else qwen_state)) + moss_ready = image_pack.ready(root, group=MOSS_GROUP) + moss_status = {} if moss_ready else image_pack.status(root, group=MOSS_GROUP) + moss_state = None if moss_ready or self.moss_installer is None else self.moss_installer.state() + moss_active = moss_state is not None and moss_state['state'] in ('running', 'paused_for_generation') + moss_rows = image_pack.rows(group=MOSS_GROUP) + rows.append(dict(id=image_model.MOSS, label='MOSS-Image', available=not mac, ready=moss_ready, + downloading=moss_active, sizes=['standard', 'high'], max_images=0, + bytes_total=moss_status.get('total_bytes', sum(r['bytes'] for r in moss_rows)), + bytes=moss_status.get('bytes', 0), bytes_done=(moss_state or {}).get('done', 0), + bytes_needed=moss_status.get('remaining_bytes', 0), shared_bytes=0, + blocked_by=active if active not in (None, image_model.MOSS) and not moss_ready else None, + install=None if moss_ready else queued if image_model.MOSS in waiting + else self.pack_row(self.moss_installer, moss_ready))) + if mac: + rows[-1]['unavailable_reason'] = 'platform' return rows def _active_pack(self): """The image model this engine is downloading now (running or waiting for a video), or None.""" - for model, installer in ((image_model.H3, self.h3_installer), (image_model.QWEN, self.pack_installer)): + for model, installer in ((image_model.H3, self.h3_installer), (image_model.QWEN, self.pack_installer), + (image_model.MOSS, self.moss_installer)): if installer is not None and installer.state()['state'] in ('running', 'paused_for_generation'): return model return None @@ -396,16 +416,22 @@ def pack_row(installer, ready): return row def _pack_installer(self, model, root, engine_root): - attribute = 'h3_installer' if model == image_model.H3 else 'pack_installer' + attribute = {image_model.H3: 'h3_installer', image_model.MOSS: 'moss_installer'}.get(model, 'pack_installer') installer = getattr(self, attribute) if installer is None or installer.root != root or installer.engine_root != engine_root: - options = dict(group=H3_GROUP) if model == image_model.H3 else {} + options = dict(group=self.model_group(model)) if model != image_model.QWEN else {} installer = image_pack.Installer(root, engine_root=engine_root, busy=self.video_busy, **options) setattr(self, attribute, installer) return installer def _pack_ready(self, model, root): - return image_pack.ready(root, group=H3_GROUP) if model == image_model.H3 else image_pack.ready(root) + group = self.model_group(model) + return image_pack.ready(root, group=group) if group else image_pack.ready(root) + + @staticmethod + def model_group(model): + """The installer group of a picture model; None for Qwen-Image, whose files are the default group.""" + return {image_model.H3: H3_GROUP, image_model.MOSS: MOSS_GROUP}.get(model) def _drain_packs(self): """Start each waiting model once the other download has ended; the queue lives in memory only.""" @@ -444,6 +470,10 @@ def pack_action(self, action, *, group='image', model=None): if sys.platform == 'darwin': raise ValueError('invalid_request') group = H3_GROUP + if model == image_model.MOSS: + if sys.platform == 'darwin': + raise ValueError('invalid_request') + group = MOSS_GROUP with self.mutex: if group == 'segment': installer = self.segment_installer @@ -456,20 +486,20 @@ def pack_action(self, action, *, group='image', model=None): self.segment_installer = installer installer.start('install', background=True) return self.info() - target = image_model.H3 if group == H3_GROUP else image_model.QWEN + target = {H3_GROUP: image_model.H3, MOSS_GROUP: image_model.MOSS}.get(group, image_model.QWEN) if action == 'cancel': if model is None: target = self._active_pack() or (self.pack_queue[0] if self.pack_queue else image_model.QWEN) if target in self.pack_queue: self.pack_queue.remove(target) - installer = self.h3_installer if target == image_model.H3 else self.pack_installer + installer = {image_model.H3: self.h3_installer, image_model.MOSS: self.moss_installer}.get(target, self.pack_installer) if installer is not None: installer.cancel() elif target in self.pack_queue: pass elif not self._pack_ready(target, root): - other = image_model.QWEN if target == image_model.H3 else image_model.H3 - if self._active_pack() == other: + other = self._active_pack() + if other is not None and other != target: self.pack_queue.append(target) if self.pack_drain is None: self.pack_drain = threading.Thread(target=self._drain_packs, daemon=True) @@ -1119,6 +1149,11 @@ def request(self, value): raise ValueError('invalid_dimensions') if any(value.get(name) is not None for name in ('mask', 'cast_view', 'loras')): raise ValueError('invalid_request') + elif model == image_model.MOSS: + if any(type(size) is not int or not 256 <= size <= MOSS_MAX_SIDE for size in dimensions): + raise ValueError('invalid_dimensions') + if value.get('images') or any(value.get(name) is not None for name in ('mask', 'cast_view', 'loras')): + raise ValueError('invalid_request') elif any(type(size) is not int or not 256 <= size <= 2048 for size in dimensions): raise ValueError('invalid_dimensions') seed = value.get('seed') @@ -1234,9 +1269,10 @@ def prepare(self, action, value, context, *, waiting=False): # A model this computer does not run (H3 Image on a Mac) is said so; its files are not looked for. if h3 and sys.platform == 'darwin': raise ValueError('model_unavailable') - if not image_pack.ready(machine['model_root'], group=H3_GROUP if h3 else 'image'): + moss = model == image_model.MOSS + if not image_pack.ready(machine['model_root'], group=self.model_group(model) or 'image'): raise ValueError('pack_missing') - if h3 and action != 'generate': + if (h3 or moss) and action != 'generate': raise ValueError('invalid_request') from .image_policy import UNIFIED_MIN_TOTAL unified = self.unified_total(machine) @@ -1255,7 +1291,7 @@ def prepare(self, action, value, context, *, waiting=False): resident_endpoint=self.resident_endpoint()) context.update_request(value) # H3 Image plans its own residency in the worker; the Qwen plan below does not describe it. - context.plan = None if h3 else self.preflight(machine, value, fit=not waiting, reading=context.gpu_reading) + context.plan = None if h3 or moss else self.preflight(machine, value, fit=not waiting, reading=context.gpu_reading) # Live free memory while another job owns the GPU is advisory. Keep # the original request for dispatch, when the owner has released it. if not waiting and context.plan is not None and not context.plan['feasible']: @@ -2271,7 +2307,7 @@ def shrink(self, value, row, context): The ladder is the one start-up fitting uses (32-pixel grid, 512 pixels at the least); the step grows with the size so a big canvas needs few tries. False at the smallest size. """ - if (value.get('model') == image_model.H3 or row.get('code') != 'no_memory' + if (value.get('model') in (image_model.H3, image_model.MOSS) or row.get('code') != 'no_memory' or row.get('stage') in ('load', 'text', 'encode') or self.stop.is_set() or self.session_stop.is_set()): return False @@ -2378,7 +2414,7 @@ def infer(self, session, value): # The picture session may have started the resident worker after this request was prepared. value['h3']['resident_endpoint'] = self.resident_endpoint() loading = True - limit = H3_INFERENCE_TIMEOUT if value.get('model') == image_model.H3 else INFERENCE_TIMEOUT + limit = {image_model.H3: H3_INFERENCE_TIMEOUT, image_model.MOSS: MOSS_INFERENCE_TIMEOUT}.get(value.get('model'), INFERENCE_TIMEOUT) try: session.send(action='generate', **value) except OSError: diff --git a/freevideo_engine/image_gen/staged_weights.py b/freevideo_engine/image_gen/staged_weights.py new file mode 100644 index 00000000..e351e5b7 --- /dev/null +++ b/freevideo_engine/image_gen/staged_weights.py @@ -0,0 +1,70 @@ +"""Helpers for running a model in two stages (encoder, then denoiser) with weights read from disk. + +``open_index`` reads a model folder's safetensors index; ``read_tensors`` loads the tensors outside the streamed +layers (embeddings, norms, input and output projections) straight to a device; ``save_encoding`` and +``load_encoding`` hand the encoder's result to the next stage through a file, so that the encoder's host memory +goes back to the system with its process. +""" +import json +from pathlib import Path + +import torch +from safetensors import safe_open + +from freevideo_engine.image_gen.layer_stream import SafetensorsIndex + +INDEX_NAME = 'model.safetensors.index.json' + + +def open_index(folder, index_name=INDEX_NAME): + """Index of the safetensors files in ``folder``; a folder with one file and no index file is accepted.""" + folder = Path(folder) + index_file = folder / index_name + if index_file.exists(): + weight_map = json.loads(index_file.read_text())['weight_map'] + else: + files = sorted(folder.glob('*.safetensors')) + if len(files) != 1: + raise FileNotFoundError('no %s and %d safetensors files in %s' % (index_name, len(files), folder)) + with safe_open(str(files[0]), 'pt', device='cpu') as handle: + weight_map = {key: files[0].name for key in handle.keys()} + return SafetensorsIndex(folder, weight_map) + + +def read_tensors(index, skip_prefix, device): + """Every tensor whose key does not start with ``skip_prefix``, on ``device``, one file open at a time.""" + by_file = {} + for key, name in index.weight_map.items(): + if not key.startswith(skip_prefix): + by_file.setdefault(name, []).append(key) + tensors = {} + for name, keys in by_file.items(): + with safe_open(str(index.folder / name), 'pt', device='cpu') as handle: + for key in keys: + tensors[key] = handle.get_tensor(key).to(device) + return tensors + + +def layer_key(prefix): + """``key(i, name)`` for ``DiskLayerStream`` when layer ``i`` is stored as ``layers..``.""" + return lambda i, name: '%slayers.%d.%s' % (prefix, i, name) + + +def save_encoding(path, encodings): + """Write ``{name: (embeds, mask)}`` to ``path``; tensors only, so the file can be read back without code.""" + flat = {} + for name, (embeds, mask) in encodings.items(): + flat['%s/embeds' % name] = embeds.detach().cpu().contiguous() + flat['%s/mask' % name] = mask.detach().cpu().contiguous() + from safetensors.torch import save_file + save_file(flat, str(path)) + + +def load_encoding(path, device='cpu'): + """Read what ``save_encoding`` wrote; returns ``{name: (embeds, mask)}``.""" + out = {} + with safe_open(str(path), 'pt', device='cpu') as handle: + for key in handle.keys(): + name, kind = key.rsplit('/', 1) + out.setdefault(name, {})[kind] = handle.get_tensor(key).to(device) + return {name: (pair['embeds'], pair['mask']) for name, pair in out.items()} diff --git a/freevideo_engine/image_gen/worker.py b/freevideo_engine/image_gen/worker.py index 5ac192c9..9368a994 100644 --- a/freevideo_engine/image_gen/worker.py +++ b/freevideo_engine/image_gen/worker.py @@ -280,8 +280,13 @@ def load_h3_runner(pack_dir, device, *, progress=None): return H3Runner(pack_dir, device=device, progress=progress) +def load_moss_runner(pack_dir, device, *, progress=None): + from .moss_runner import MossRunner + return MossRunner(pack_dir, device=device, progress=progress) + + def serve(pack_dir, *, device='cuda', idle_seconds=45., stream=None, output=None, factory=None, h3_factory=None, - server_root=None, lock_path=None): + moss_factory=None, server_root=None, lock_path=None): global SERVER_ROOT, LOCK_PATH SERVER_ROOT = server_root LOCK_PATH = lock_path @@ -289,6 +294,7 @@ def serve(pack_dir, *, device='cuda', idle_seconds=45., stream=None, output=None output = sys.stdout if output is None else output factory = factory or load_runner h3_factory = h3_factory or load_h3_runner + moss_factory = moss_factory or load_moss_runner runner_model = None output_mutex = threading.Lock() @@ -360,7 +366,7 @@ def progress(stage, fraction): runner = drop(runner) if runner is None: context.timing.enter('load') - runner = (h3_factory if model == 'minimax-h3-image' else factory)(pack_dir, device, progress=progress) + runner = {'minimax-h3-image': h3_factory, 'moss-image-sft': moss_factory}.get(model, factory)(pack_dir, device, progress=progress) runner_model = model if hasattr(runner, 'last_plan'): runner.last_plan = None @@ -386,9 +392,10 @@ def generate(seed): seed=seed, reference_images=references, **region, **(dict(loras=loras) if loras else {}), progress=progress, cancel=inbox.cancel.is_set, - **(dict(setup=value['h3']) if model == 'minimax-h3-image' and value.get('h3') else {}), + **(dict(setup=value['h3']) if model in ('minimax-h3-image', 'moss-image-sft') and value.get('h3') else {}), # Which stage a failure belongs to, without a progress row the page would show. - **(dict(preview=preview, stage=context.timing.enter, note=note) if model == 'minimax-h3-image' else {})) + **(dict(preview=preview, stage=context.timing.enter, note=note) if model == 'minimax-h3-image' + else dict(stage=context.timing.enter) if model == 'moss-image-sft' else {})) if value.get('cast_view') == 'back' and len(references) == 1 and not region: from .back_view import generate_back, load_detector diff --git a/web/image_view.js b/web/image_view.js index 33392654..fdb75e31 100644 --- a/web/image_view.js +++ b/web/image_view.js @@ -48,6 +48,7 @@ const remember = id => { try { localStorage.setItem(MODEL_KEY, id); } catch { /* // H3 Image is made for 4 to 16 MP; a smaller picture would still cost a 4 MP canvas, so its tiers start there. const H3_AREAS = Object.freeze({standard: 2048, high: 4096}); +const MOSS_AREAS = Object.freeze({standard: 1024, high: 2048}); // The shape of a picture as a ratio, when it is one of the common ones; otherwise nothing is said. const SHAPES = [[1, 1], [16, 9], [9, 16], [4, 3], [3, 4], [3, 2], [2, 3], [21, 9], [9, 21]]; export function shapeOf(width, height) { @@ -59,18 +60,19 @@ const pictureShape = shapeOf; // A size with the ratio at about the tier's area, in steps of 32 (kept for callers of the two-tier page). export function imageSize(ratio, tier = 'standard', same = null, model = '') { const [w, h] = (ratio === 'same' && same ? [same.width, same.height] : ratio.split(':').map(Number)); - const areas = model === 'minimax-h3-image' ? H3_AREAS : BLANK_CANVAS_AREAS; + const areas = model === 'minimax-h3-image' ? H3_AREAS : model === 'moss-image-sft' ? MOSS_AREAS : BLANK_CANVAS_AREAS; const side = areas[tier] || areas.standard; const scale = Math.sqrt(side * side / (w * h)); - const round = value => Math.max(32, Math.round(value * scale / 32) * 32); + const step = model === 'moss-image-sft' ? 16 : 32; + const round = value => Math.max(model === 'moss-image-sft' ? 256 : 32, Math.min(model === 'moss-image-sft' ? 2048 : Infinity, Math.round(value * scale / step) * step)); return {width: round(w), height: round(h)}; } // Stands in for the engine until it answers (tests and the first skeleton): a flat picture after a short wait. // references: how many pictures each model row reports it takes, as the engine does. history: rows to start with. // install: per model, 'missing' | 'failed' | 'downloading' to start in that state. sizes: the engine's tier list. -export function createFakeImageClient({delay = 600, ready = {'minimax-h3-image': true, 'qwen-image-2.1-turbo': true}, fail = null, steps = 0, - references = {'minimax-h3-image': 0, 'qwen-image-2.1-turbo': 4}, history = [], install = {}, sizes = ['standard', 'high'], fitted = null, bytes = 12.5e9, rate = 5e6} = {}) { +export function createFakeImageClient({delay = 600, ready = {'minimax-h3-image': true, 'qwen-image-2.1-turbo': true, 'moss-image-sft': true}, fail = null, steps = 0, + references = {'minimax-h3-image': 0, 'qwen-image-2.1-turbo': 4, 'moss-image-sft': 0}, history = [], install = {}, sizes = ['standard', 'high'], fitted = null, bytes = 12.5e9, rate = 5e6} = {}) { const items = history.map(row => typeof row === 'string' ? {file: row, name: row.slice(row.lastIndexOf('/') + 1)} : row); let count = 0; const jobs = new Map(), state = {...ready}; const loading = new Map(), failed = new Set(Object.keys(install).filter(id => install[id] === 'failed')); for (const id of Object.keys(install)) { if (install[id] !== 'ready') state[id] = false; if (install[id] === 'downloading') loading.set(id, Date.now() - bytes / rate * .4); } @@ -687,7 +689,7 @@ export function openImageView(node, {studio = null, client: given = null, poll = const subject = number => t(`Subject ${number}`, `主体 ${number}`); // Each model row says how many pictures it takes; the strip holds as many as the most generous one. // Until the engine answers, each model's usual reference count, so the strip has its final height from the first frame. - const USUAL_CAPS = {'minimax-h3-image': 16, 'qwen-image-2.1-turbo': 4}; + const USUAL_CAPS = {'minimax-h3-image': 16, 'qwen-image-2.1-turbo': 4, 'moss-image-sft': 0}; function cap_(m) { if (!info?.models) return USUAL_CAPS[m.id] || 0; const n = Number(info.models.find(r => r.id === m.id)?.max_images); return Number.isInteger(n) && n > 0 ? n : 0; } const most = () => Math.max(0, ...IMAGE_MODELS.map(cap_)); const over = () => Math.max(0, references.length - cap_(model)); diff --git a/web/image_view_history.js b/web/image_view_history.js index 20eb4996..c6068566 100644 --- a/web/image_view_history.js +++ b/web/image_view_history.js @@ -53,7 +53,7 @@ export function stampOf(row, meta = null) { } const dayStart = ms => { const d = new Date(ms); d.setHours(0, 0, 0, 0); return d.getTime(); }; -export const FILTERS = Object.freeze(['all', 'fav', 'minimax-h3-image', 'qwen-image-2.1-turbo']); +export const FILTERS = Object.freeze(['all', 'fav', 'minimax-h3-image', 'qwen-image-2.1-turbo', 'moss-image-sft']); export function filterRows(rows, {filter = 'all', query = '', sort = 'new'} = {}, meta, now = Date.now()) { const q = query.trim().toLowerCase(), today = dayStart(now); const kept = rows.filter(row => { @@ -153,7 +153,7 @@ export function createTrash({client, holdMs = 10000, now = () => Date.now(), set return trash; } -const FILTER_WORDS = {all: ['All', '全部'], fav: ['Favourites', '收藏'], today: ['Today', '今天'], 'minimax-h3-image': ['H3', 'H3'], 'qwen-image-2.1-turbo': ['Qwen', 'Qwen']}; +const FILTER_WORDS = {all: ['All', '全部'], fav: ['Favourites', '收藏'], today: ['Today', '今天'], 'minimax-h3-image': ['H3', 'H3'], 'qwen-image-2.1-turbo': ['Qwen', 'Qwen'], 'moss-image-sft': ['MOSS', 'MOSS']}; const SORT_WORDS = {new: ['Newest first', '最新在前'], old: ['Oldest first', '最早在前'], fav: ['Favourites first', '收藏在前']}; // The column itself. `paint(state)` redraws; tiles are kept by file so pictures never reload on a redraw. @@ -278,7 +278,8 @@ export function historyPanel({pictureURL, thumbURL = pictureURL, queue = null, o b.querySelector('.fv-iv-chip-n').textContent = ''; b.hidden = (f.includes('-') && !n && state.filter !== f); tip(b, t(...FILTER_WORDS[f]), {all: t('Show every picture', '显示全部图片'), fav: t('Only the starred ones', '只看收藏的图片'), today: t('Only pictures made today', '只看今天生成的'), - 'minimax-h3-image': t('Only pictures made with H3 Image', '只看 H3 Image 生成的'), 'qwen-image-2.1-turbo': t('Only pictures made with Qwen-Image', '只看 Qwen-Image 生成的')}[f]); + 'minimax-h3-image': t('Only pictures made with H3 Image', '只看 H3 Image 生成的'), 'qwen-image-2.1-turbo': t('Only pictures made with Qwen-Image', '只看 Qwen-Image 生成的'), + 'moss-image-sft': t('Only pictures made with MOSS-Image', '只看 MOSS-Image 生成的')}[f]); } for (const item of sortItems) item.setAttribute('aria-checked', String(item.dataset.sort === state.sort)); tip(sortBtn, t('Sort', '排序'), t(`Now: ${t(...SORT_WORDS[state.sort])}`, `当前:${t(...SORT_WORDS[state.sort])}`)); diff --git a/web/image_view_models.js b/web/image_view_models.js index e72de4a4..ca9c5539 100644 --- a/web/image_view_models.js +++ b/web/image_view_models.js @@ -8,6 +8,7 @@ import { el, icon, t, tip, button } from './image_view_ui.js'; export const IMAGE_MODELS = Object.freeze([ {id: 'minimax-h3-image', name: 'MiniMax H3 Image', short: 'H3 Image'}, {id: 'qwen-image-2.1-turbo', name: 'Qwen-Image 2.1', short: 'Qwen-Image 2.1'}, + {id: 'moss-image-sft', name: 'MOSS-Image', short: 'MOSS-Image'}, ]); // One model row from the engine's info as a state the page can draw. `info` absent: still asking. @@ -53,13 +54,18 @@ export function statusLine(state) { const ICON_OF = {ready: 'check', failed: 'warn', downloading: 'down', unavailable: 'info', missing: 'cloud', checking: 'clock'}; const gbOf = state => state.total ? (state.total / 1e9).toFixed(1) : ''; function useOf(model, state) { - const size = state.total ? t(`about ${gbOf(state)} GB, files shared with video are not downloaded again`, `约 ${gbOf(state)} GB,和视频共用的文件不重复下载`) : ''; + const shared = model.id !== 'moss-image-sft'; + const size = state.total ? shared ? t(`about ${gbOf(state)} GB, files shared with video are not downloaded again`, `约 ${gbOf(state)} GB,和视频共用的文件不重复下载`) + : t(`about ${gbOf(state)} GB`, `约 ${gbOf(state)} GB`) : ''; return { - ready: model.id === IMAGE_MODELS[0].id ? t('Large, detailed pictures, up to 16 references', '大尺寸、细节多,最多 16 张参考图') : t('Fast pictures, up to 4 references', '出图快,最多 4 张参考图'), - missing: t(`Not installed: Generate installs it first, ${size}`, `未安装:点生成会先安装,${size}`), + ready: model.id === IMAGE_MODELS[0].id ? t('Large, detailed pictures, up to 16 references', '大尺寸、细节多,最多 16 张参考图') + : model.id === 'moss-image-sft' ? t('Pictures from a text prompt', '根据文字提示出图') : t('Fast pictures, up to 4 references', '出图快,最多 4 张参考图'), + missing: state.row?.blocked_by ? t('Not installed: another model is downloading; this one installs after it, or when you press Generate', '未安装:另一个模型正在下载,完成后才会安装这个,也可点生成') + : t(`Not installed: Generate installs it first, ${size}`, `未安装:点生成会先安装,${size}`), downloading: state.paused ? t('Paused while a video generates; resumes after it', '视频生成中,下载已暂停,之后自动继续') : state.verifying ? (state.unknown ? t('Verifying the files; usable when done', '正在校验文件,完成后可以使用') : t(`Verifying the files ${Math.floor(state.fraction * 100)}%; usable when done`, `正在校验文件 ${Math.floor(state.fraction * 100)}%,完成后即可使用`)) : t(`Downloading ${Math.floor((state.fraction || 0) * 100)}%; usable when done`, `正在下载 ${Math.floor((state.fraction || 0) * 100)}%,完成后即可使用`), failed: state.reason || t('The download stopped; press Retry', '下载中断了,点重试'), - unavailable: t('This model does not run on this computer', '这台电脑不能运行这个模型'), + unavailable: model.id === 'moss-image-sft' ? t('MOSS-Image needs an NVIDIA graphics card, which this computer does not have. Choose another model', 'MOSS-Image 需要 NVIDIA 显卡,这台电脑没有。请选别的模型') + : t('This model needs an NVIDIA graphics card, which this computer does not have. Choose another model', '这个模型需要 NVIDIA 显卡,这台电脑没有。请选别的模型'), checking: t('Asking the engine', '正在询问引擎'), }[state.state]; } @@ -126,7 +132,7 @@ export function modelPicker({host, onPick, onInstall, onPause}) { const model = IMAGE_MODELS.find(m => m.id === chosen) || IMAGE_MODELS[0], state = modelState(info, model.id); root.dataset.state = state.state; name.textContent = model.name; - status.replaceChildren(icon(state.unknown ? 'clock' : ICON_OF[state.state] || 'cloud'), el('span', '', pending && state.state === 'downloading' ? t(`${statusLine(state)} · then generates`, `${statusLine(state)} · 完成后生成`) : statusLine(state))); + status.replaceChildren(icon(state.unknown ? 'clock' : ICON_OF[state.state] || 'cloud'), el('span', '', statusLine(state))); // Closed, the row names the model only; it speaks when something needs doing (to download, downloading, failed). status.hidden = state.state === 'ready' || state.state === 'checking'; tip(trigger, t('Model', '模型'), t(`${model.name}: ${useOf(model, state)}. Click to choose another`, `${model.name}:${useOf(model, state)}。点开换别的模型`)); diff --git a/web/image_view_size.js b/web/image_view_size.js index e1641e7a..5871976e 100644 --- a/web/image_view_size.js +++ b/web/image_view_size.js @@ -1,17 +1,19 @@ // Picture size: any area inside the model's range at the chosen shape, in steps of 32 pixels. "Standard" and // "High" are two quick points on the scale, not the only choices. The engine checks width and height, not tiers: -// H3 Image takes 4 to 16 MP (each side 256 to 8192), Qwen-Image 2.1 takes each side 256 to 2048. +// H3 Image takes 4 to 16 MP (each side 256 to 8192), Qwen-Image 2.1 and MOSS-Image take each side 256 to 2048. import { createFrameChip } from './glass/frame_picker.js'; import { el, t, tip } from './image_view_ui.js'; export const SNAP = 32; export const MP = 1e6; -export const H3 = 'minimax-h3-image', QWEN = 'qwen-image-2.1-turbo'; +export const H3 = 'minimax-h3-image', QWEN = 'qwen-image-2.1-turbo', MOSS = 'moss-image-sft'; export const RANGES = Object.freeze({ [H3]: Object.freeze({minArea: 2048 * 2048, maxArea: 4096 * 4096, minSide: 256, maxSide: 8192, step: .5 * MP, presets: Object.freeze({standard: 2048 * 2048, high: 4096 * 4096})}), [QWEN]: Object.freeze({minArea: 0, maxArea: Infinity, minSide: 256, maxSide: 2048, step: .1 * MP, presets: Object.freeze({standard: 1024 * 1024, high: 1280 * 1280})}), + [MOSS]: Object.freeze({minArea: 0, maxArea: 2048 * 2048, minSide: 256, maxSide: 2048, step: .1 * MP, + presets: Object.freeze({standard: 1024 * 1024, high: 2048 * 2048})}), }); export const RATIOS = Object.freeze(['1:1', '4:3', '3:4', '16:9', '9:16', '3:2', '2:3']); const rangeOf = model => RANGES[model] || RANGES[QWEN]; diff --git a/web/settings_room.js b/web/settings_room.js index a313d449..e8632f12 100644 --- a/web/settings_room.js +++ b/web/settings_room.js @@ -205,6 +205,7 @@ export async function openSetup(options) { const IMAGE_WORDS = { 'minimax-h3-image': t('Default for the image view; clear lettering in pictures', '图像视图默认模型,图中文字清晰'), 'qwen-image-2.1-turbo': t('Another look, up to about 4 MP', '另一种画风,最大约 4 MP'), + 'moss-image-sft': t('Pictures from a text prompt, up to about 4 MP', '根据文字提示出图,最大约 4 MP'), }; for (const model of IMAGE_MODELS) { const r = row({iconName: 'img', title: model.short, sub: IMAGE_WORDS[model.id] || '', cls: 'st-mrow'}); From 736c9dd7fb78d6448d548c2cb6969c4b7384f7dc Mon Sep 17 00:00:00 2001 From: Bowen Xue Date: Wed, 18 Nov 2026 04:11:03 +0000 Subject: [PATCH 35/97] Library and sharing: a folder that cannot be read, a video that cannot be deleted or an export... Library and sharing: a folder that cannot be read, a video that cannot be deleted or an export that stops on a file problem answers with the cause (in use, no permission, disk full, source unreadable) --- freevideo_engine/comfy_library.py | 15 +++++++++++++-- freevideo_engine/comfy_share.py | 4 ++++ freevideo_engine/disk_space.py | 15 +++++++++++++++ web/file_failure.js | 17 +++++++++++++++++ web/share.js | 9 +++++++-- 5 files changed, 56 insertions(+), 4 deletions(-) create mode 100644 web/file_failure.js diff --git a/freevideo_engine/comfy_library.py b/freevideo_engine/comfy_library.py index 8a4e5009..5ded2a96 100644 --- a/freevideo_engine/comfy_library.py +++ b/freevideo_engine/comfy_library.py @@ -17,6 +17,7 @@ from .comfy_assets import output_summary from .runtime_alias import is_junction, checked_real_path, AliasUnavailable from .long_paths import io_path, plain +from .disk_space import file_reason from .system import windows _ID = re.compile(r'\d{4}-\d{2}-\d{2}/[0-9a-f]{32}') @@ -1606,6 +1607,9 @@ async def library(request): return web.json_response(rows, headers={'Cache-Control': 'no-store'}) except ValueError as error: raise web.HTTPBadRequest(text=str(error)) from error + except OSError as error: + # The output folder is offline or not readable: say which, so the page can name the cause. + return web.json_response(dict(reason=file_reason(error, write=False)), status=500) @server.routes.get('/freevideo/library/prompt') async def prompt(request): @@ -1707,7 +1711,12 @@ async def delete(request): queue=getattr(server, 'prompt_queue', None)) except DeleteRefused as error: return web.json_response(dict(deleted=False, reason=error.reason, kept=error.kept[:20]), status=409) - except (OSError, ValueError, TypeError): + except FileNotFoundError: + raise web.HTTPNotFound(text='Saved video unavailable') from None + except OSError as error: + # Still there but could not be removed: another program holds it, or the folder is protected. + return web.json_response(dict(deleted=False, reason=file_reason(error, write=True)), status=500) + except (ValueError, TypeError): raise web.HTTPNotFound(text='Saved video unavailable') from None return web.json_response(dict(result, deleted=True)) @@ -1720,8 +1729,10 @@ async def delete_batch(request): queue=getattr(server, 'prompt_queue', None), batch=body.get('batch') if isinstance(body, dict) else None, extend=body.get('extend') or () if isinstance(body, dict) else ()) - except (DeleteRefused, OSError, ValueError, TypeError): + except (DeleteRefused, ValueError, TypeError): raise web.HTTPBadRequest(text='Invalid selection') from None + except OSError as error: + return web.json_response(dict(reason=file_reason(error, write=True)), status=500) return web.json_response(result) @server.routes.post('/freevideo/library/undo') diff --git a/freevideo_engine/comfy_share.py b/freevideo_engine/comfy_share.py index be70099a..46285f84 100644 --- a/freevideo_engine/comfy_share.py +++ b/freevideo_engine/comfy_share.py @@ -236,6 +236,10 @@ async def export(request): raise web.HTTPInsufficientStorage(text='disk_full') from None if not isinstance(error, InterruptedError): logging.warning('FreeVideo sharing export failed.', exc_info=error) + if isinstance(error, OSError) and not isinstance(error, InterruptedError): + # A file problem, not an encoder one: name it (in_use, not_writable, not_readable) without the path. + from .disk_space import file_reason + raise web.HTTPInternalServerError(text=file_reason(error, write=not isinstance(error, FileNotFoundError))) from None raise web.HTTPBadRequest(text='Sharing export could not complete') from None @server.routes.get('/freevideo/share/video') diff --git a/freevideo_engine/disk_space.py b/freevideo_engine/disk_space.py index 9c0e4dac..a3d2b4b7 100644 --- a/freevideo_engine/disk_space.py +++ b/freevideo_engine/disk_space.py @@ -230,6 +230,21 @@ def ran_out(error): return False +def file_reason(error, *, write): + """Why a file operation failed, as a short code the page turns into a sentence: disk_full, in_use (another + program holds the file open), not_writable or not_readable (permission, a read-only or missing folder).""" + if ran_out(error): + return 'disk_full' + seen = set() + while error is not None and id(error) not in seen: + seen.add(id(error)) + if isinstance(error, OSError) and (getattr(error, 'winerror', None) in (32, 33) + or error.errno in (errno.EBUSY, getattr(errno, 'ETXTBSY', errno.EBUSY))): + return 'in_use' + error = error.__cause__ or (None if error.__suppress_context__ else error.__context__) + return 'not_writable' if write else 'not_readable' + + @plain_errors def disk_key(path): """Paths with the same key draw on the same free space.""" diff --git a/web/file_failure.js b/web/file_failure.js new file mode 100644 index 00000000..02f39323 --- /dev/null +++ b/web/file_failure.js @@ -0,0 +1,17 @@ +// The cause of a file failure the engine reported (library delete, library listing, sharing export) as a sentence. +export function fileFailureText(reason, t) { + return { + in_use: t('The file is open in another program. Close that program, then try again.', '文件正被其他程序占用,请关闭该程序后重试。'), + not_writable: t('FreeVideo has no permission to change the output folder. Check the folder, then try again.', 'FreeVideo 无权修改输出文件夹,请检查该文件夹的权限后重试。'), + not_readable: t('The output folder cannot be read. Check that its disk is connected, then try again.', '无法读取输出文件夹,请确认磁盘已连接后重试。'), + disk_full: t('The disk is full. Free some space, then try again.', '磁盘空间已满,请释放空间后重试。'), + }[reason] || ''; +} +// The reason a failed response carries, as text (sharing) or as JSON {reason} (library). +export async function responseFileReason(response) { + try { + const text = (await response.text()).trim(); + if (text.startsWith('{')) return JSON.parse(text).reason || ''; + return text; + } catch { return ''; } +} diff --git a/web/share.js b/web/share.js index 11e83791..a7af6105 100644 --- a/web/share.js +++ b/web/share.js @@ -6,6 +6,8 @@ import {shareLayout} from './share_layout.js'; import {videoUnavailableText} from './studio_extend.js'; import {issueButton} from './issue_button.js'; import {exportKeepsWorkflow, workflowToggle} from './output_download.js'; +import {fileFailureText, responseFileReason} from './file_failure.js'; +import {isNetworkTypeError, connectionLostText} from './browser_extension.js'; const css=document.createElement('link'); css.rel='stylesheet'; css.href=new URL('./share.css',import.meta.url).href; document.head.append(css); const el=(tag,cls,text)=>{const e=document.createElement(tag);if(cls)e.className=cls;if(text)e.textContent=text;return e;}; @@ -179,13 +181,16 @@ export async function openShare(record,t){ body:JSON.stringify({id,template,rect:shape.rect,workflow:exportKeepsWorkflow()})}); if(response.status===409)throw Object.assign(new Error(t('Another export is running. Try again shortly.','已有分享视频正在导出,请稍后再试。')),{reportable:false}); if(response.status===507)throw Object.assign(new Error(t('Exporting the share video failed: the disk is full. Free some space, then export again.','导出分享视频时出错:磁盘空间不够,空出空间后再导出。')),{reportable:false}); - if(!response.ok)throw new Error(t('Export could not complete. Try again.','分享视频导出未完成,请重试。')); + if(!response.ok){ + const known=fileFailureText(await responseFileReason(response),t); + throw Object.assign(new Error(known?t('The share video could not be exported: ','分享视频导出未完成:')+known:t('Export could not complete. Try again.','分享视频导出未完成,请重试。')),{reportable:!known}); + } exported=await response.json(); } if(disposed)return; const a=el('a');a.href=api.apiURL('/freevideo/share/video?'+new URLSearchParams(exported));a.download='';a.click();say(''); }catch(error){if(!disposed){ - say(error.name==='AbortError'?'':kind==='image'?t('Could not save the share image. Try again.','分享图没有保存成功,请重试。'):error.message,error.reportable!==false); + say(error.name==='AbortError'?'':isNetworkTypeError(error)?connectionLostText(t):kind==='image'?t('Could not save the share image. Try again.','分享图没有保存成功,请重试。'):error.message,error.reportable!==false&&!isNetworkTypeError(error)); }} finally{clearInterval(watch);busy=false;if(!disposed){save.disabled=false;keep.input.disabled=false;cancel.hidden=true;delete dialog.dataset.busy;tabs.querySelectorAll('button').forEach(b=>b.disabled=false);}} } From d74f4b3d57f1b1b96caf0deeaeb62dc39b9ee5d4 Mon Sep 17 00:00:00 2001 From: Bowen Xue Date: Wed, 18 Nov 2026 04:12:52 +0000 Subject: [PATCH 36/97] Assistant chat: Tab stays inside the drawer and dialogs, one Technical details section, a... Assistant chat: Tab stays inside the drawer and dialogs, one Technical details section, a deleted chat stays gone --- web/a11y.js | 5 +++++ web/autopilot_chat.js | 22 ++++++++++++++++++---- web/context_menu.js | 4 ++-- web/editor_expand.js | 1 + web/editor_export_dialog.js | 1 + web/tutorial_book_content.js | 4 ++-- 6 files changed, 29 insertions(+), 8 deletions(-) diff --git a/web/a11y.js b/web/a11y.js index e2dbc5c6..612aca5a 100644 --- a/web/a11y.js +++ b/web/a11y.js @@ -131,6 +131,11 @@ function onTab(event) { const active = doc.activeElement; const layer = frontLayer(active); if (!layer) return; + // A container that moves focus on Tab by itself says so with data-fv-own-tab. Its handler runs after this + // window-level trap, so the trap leaves the press to it (one move per press, not two), unless a layer opened + // inside it is in front. + const owner = active?.closest?.('[data-fv-own-tab]'); + if (owner && layer.contains(owner)) return; // Only FreeVideo's own layers; ComfyUI's dialogs keep their behaviour. if (!(layer.className && /(^|\s)(fv-|sgf)/.test(String(layer.className))) && !layer.closest('[class*="fv-"]:not(html)')) return; const stops = tabbables(layer); diff --git a/web/autopilot_chat.js b/web/autopilot_chat.js index 7dba3320..30d34792 100644 --- a/web/autopilot_chat.js +++ b/web/autopilot_chat.js @@ -722,9 +722,16 @@ export function agentChat(t, api, {open, edit, shown = () => true, changed = () const inMenu = target => menu.contains(target) || menuOrigin()?.contains(target); const leaveMenu = event => { if (menuState && !changingMenu && !inMenu(event.relatedTarget)) closeMenu(); }; menu.addEventListener('focusout', leaveMenu); + // Where `keys` below moves focus on Tab itself (the narrow drawer; the open menu in the drawer, and its confirmation + // everywhere), the shared trap in a11y.js stands aside, so each press moves focus once. + function ownTab() { + const own = (node, on) => on ? node.setAttribute('data-fv-own-tab', '') : node.removeAttribute('data-fv-own-tab'); + own(rail, narrow() && chats.getAttribute('aria-expanded') === 'true'); + own(menu, !!menuState && (narrow() || menuState.stage === 'confirm')); + } function drawer(on, restore = false) { if (!on) closeMenu(); - element.dataset.chatsOpen = String(on); chats.setAttribute('aria-expanded', String(on)); + element.dataset.chatsOpen = String(on); chats.setAttribute('aria-expanded', String(on)); ownTab(); if (on) sideDrawer(false); // Only the overlay needs to keep keyboard focus in its list. main.inert = on && narrow(); @@ -765,6 +772,7 @@ export function agentChat(t, api, {open, edit, shown = () => true, changed = () positionMenu(); if (focus) (confirming ? cancel : rename.hidden ? remove : rename).focus({preventScroll: true}); } + ownTab(); } finally { changingMenu = false; } } function closeMenu(restore = false) { @@ -848,7 +856,9 @@ export function agentChat(t, api, {open, edit, shown = () => true, changed = () // A search also finds the chat being read by its tasks' words; the line under the name then shows the one it found. const shot = query && row.id === state.session && !matches(query, row.title) ? shotWords.find(words => matches(query, words)) : null; if (shot) { markText(node.where, shot, query); node.where.dataset.state = 'found'; node.where.hidden = false; } - node.row.hidden = !matches(query, row.title) && !shot || undoing.has(row.id); + // A chat on its way out stays hidden until the server answers; without an undo window its confirmation + // stays open on the row until then. + node.row.hidden = !matches(query, row.title) && !shot || undoing.has(row.id) || deleting.has(row.id) && menuState?.session !== row.id; const group = row.running > 0 ? 'running' : dayGroup(row.updated_at); node.row.dataset.group = group; node.row.dataset.groupLabel = t(...GROUP_WORDS[group]); @@ -1411,9 +1421,13 @@ export function agentChat(t, api, {open, edit, shown = () => true, changed = () {productVersion, fetchApi: (path, options) => api.fetchApi(path, options), retry: retry ? {label: AGAIN.resend, onClick: () => retry?.()} : null}); item.replaceChildren(host); - // The same fold row as a video failure card, between the reason and the buttons. + // Without a diagnostic report the shared card folds the code, step and memory under its own Technical + // details; the program's text and request id join that fold. With a report, the chat's fold (as on a + // video failure card) sits between the reason and the buttons. + const facts = card?.querySelector('.fv-image-failure-details'); const raw = [job.error?.code, job.error?.message, job.error?.request_id].filter(Boolean).join('\n'); - if (card && raw) card.querySelector('.fv-image-failure-reason').after(failureFold(t, raw)); + if (facts) for (const line of [job.error?.message, job.error?.request_id].filter(Boolean)) facts.append(el('div', null, line)); + else if (card && raw) card.querySelector('.fv-image-failure-reason').after(failureFold(t, raw)); if (retry && card) { // In the chat it is the same outlined button as on a video failure card. const again = card.querySelector('.fv-image-retry'); diff --git a/web/context_menu.js b/web/context_menu.js index 2a484e2a..14faaa9e 100644 --- a/web/context_menu.js +++ b/web/context_menu.js @@ -234,7 +234,7 @@ export function openContextMenu(at, rawItems, {label = '', returnFocus = null, o const menuId = `fv-cm-${++serial}`; const root = document.createElement('div'); root.className = 'fv-cm fv-glass fv-g3'; root.id = menuId; root.setAttribute('role', 'menu'); - root.dataset.fvTipScope = ''; root.tabIndex = -1; + root.dataset.fvTipScope = ''; root.dataset.fvOwnTab = ''; root.tabIndex = -1; // Tab closes the menu (below); a11y.js stands aside if (label) root.setAttribute('aria-label', words(label)); if (root.showPopover) root.popover = 'manual'; const rows = items.map((item, index) => itemRow(item, index, menuId)); @@ -354,7 +354,7 @@ export function focusables(root) { export function createLayer({className, label, onKey = () => false, onClose = () => {}}) { const dialog = document.createElement('dialog'); dialog.className = `fv-layer fv-glass fv-g3 ${className}`; - dialog.dataset.fvTipScope = ''; dialog.dataset.fvCommandLayer = ''; + dialog.dataset.fvTipScope = ''; dialog.dataset.fvCommandLayer = ''; dialog.dataset.fvOwnTab = ''; // Tab is the layer's own (below) dialog.setAttribute('aria-label', words(label)); let animation = null, release = null, invoker = null, state = 'closed'; const keys = event => { diff --git a/web/editor_expand.js b/web/editor_expand.js index d9ad8f51..39f4e2c6 100644 --- a/web/editor_expand.js +++ b/web/editor_expand.js @@ -90,6 +90,7 @@ export function createExpandButton({t = en => en, textarea, onGenerate, canGener sync(); if (disposed || element.disabled || dialog) return; dialog = el('dialog', 'fv-ed-expand-dialog'); + dialog.dataset.fvOwnTab = ''; // Tab cycles its three controls below; a11y.js stands aside dialog.setAttribute('role', 'dialog'); dialog.setAttribute('aria-modal', 'true'); dialog.setAttribute('aria-label', t('Description', '描述')); const head = el('div', 'fv-ed-expand-head'), title = el('strong', 'fv-ed-expand-title', t('Description', '描述')); diff --git a/web/editor_export_dialog.js b/web/editor_export_dialog.js index 52c70c17..6d00e8b1 100644 --- a/web/editor_export_dialog.js +++ b/web/editor_export_dialog.js @@ -91,6 +91,7 @@ export async function openExportDialog({parent, state, sources, t = en => en, on try { saved = JSON.parse(localStorage.getItem(EXPORT_SETTINGS_KEY)); } catch { /* Private browsing or old data. */ } const value = settings(state.record, state.selection, saved, {remembered: true}), returnFocus = document.activeElement; const dialog = el('dialog', 'fv-ed-export-dialog'); + dialog.dataset.fvOwnTab = ''; // Tab cycles its buttons below; a11y.js stands aside dialog.setAttribute('aria-label', t('Export', '导出')); const heading = el('h2', '', t('Export', '导出')), rows = el('div', 'fv-ed-export-rows'); const notices = el('div', 'fv-ed-export-notices'); diff --git a/web/tutorial_book_content.js b/web/tutorial_book_content.js index d292ce31..995e758f 100644 --- a/web/tutorial_book_content.js +++ b/web/tutorial_book_content.js @@ -677,8 +677,8 @@ export const TUTORIAL_CHAPTERS = [ alt: {zh: 'AI 全自动:连接助手 的按钮已用红框标出。', en: 'Autopilot, with the button that connects an assistant outlined in red.'}, }, steps: { - zh: ['点顶部的“AI 全自动”。', '点“连接助手”卡片中的按钮复制连接信息,粘贴给所使用的助手。', '状态显示“已连接”或所连助手的名字后,在“对 AI 全自动说…”中描述想做的视频,例如“做一条 1 分钟的竖屏短片:咖啡店的一天”。', '点“发送”,助手会生成并剪辑;可随时点“停止”,完成后点“打开”或“剪辑”。', '在对话列表中点对话旁的“更多”,选“重命名”可修改对话名称。'], - en: ['Choose "Autopilot" at the top.', 'On the "Connect an assistant" card, choose the button to copy the connection details and paste them to the assistant you use.', 'When it shows "Connected" or the assistant\'s name, describe the video under "Ask Autopilot…", for example "Make a 1-minute vertical short film: a day in a coffee shop".', 'Choose "Send". The assistant generates and edits it. Choose "Stop" at any time, and "Open" or "Edit" when it finishes.', 'In the chat list, choose "More" next to a chat, then "Rename" to change its name.'], + zh: ['点顶部的“AI 全自动”。', '点“连接助手”卡片中的按钮复制连接信息,粘贴给所使用的助手。', '状态显示“已连接”或所连助手的名字后,在“对助手说…”中描述想做的视频,例如“做一条 1 分钟的竖屏短片:咖啡店的一天”。', '点“发送”,助手会生成并剪辑;可随时点“停止”,完成后点“打开”或“剪辑”。', '在对话列表中点对话旁的“更多”,选“重命名”可修改对话名称。'], + en: ['Choose "Autopilot" at the top.', 'On the "Connect an assistant" card, choose the button to copy the connection details and paste them to the assistant you use.', 'When it shows "Connected" or the assistant\'s name, describe the video under "Tell the assistant…", for example "Make a 1-minute vertical short film: a day in a coffee shop".', 'Choose "Send". The assistant generates and edits it. Choose "Stop" at any time, and "Open" or "Edit" when it finishes.', 'In the chat list, choose "More" next to a chat, then "Rename" to change its name.'], }, limits: { zh: ['需要先连接助手,未连接时只显示连接说明。', '镜头越多,用时越长。', '助手开拍整部片前、重拍耗时较长时是否先询问,可在“设置”的“AI 助手”中选择。'], From 81878ab253af672b826a909ddc361be63ef30b30 Mon Sep 17 00:00:00 2001 From: Bowen Xue Date: Wed, 18 Nov 2026 04:18:54 +0000 Subject: [PATCH 37/97] Autopilot connection light opens a menu: Reconnect is the main action, the assistant can be... Autopilot connection light opens a menu: Reconnect is the main action, the assistant can be disconnected, and an assistant that went quiet offers no problem report --- freevideo_engine/agent/routes.py | 76 +++++++++++++++--- freevideo_engine/agent/schema.py | 2 +- web/agent_connect.css | 20 +++++ web/agent_connect.js | 129 ++++++++++++++++++++++++++++++- web/autopilot.js | 14 +++- web/autopilot_tips.js | 7 +- 6 files changed, 229 insertions(+), 19 deletions(-) diff --git a/freevideo_engine/agent/routes.py b/freevideo_engine/agent/routes.py index ba8faae8..db2114b6 100644 --- a/freevideo_engine/agent/routes.py +++ b/freevideo_engine/agent/routes.py @@ -44,6 +44,10 @@ MOVED_NEW = ' It starts afresh: do not carry requests over from the earlier conversation unless the user refers to them.' MOVED_BACK = (' It is one the user was in before, and the user means what was said there, not the conversation you just ' 'left. Its last lines are in "before"; all of it: GET /sessions/%s/events.') +# The user disconnected the agent from the page: its waits end with this, and a later wait no longer listens. +DISCONNECTED = ('The user disconnected you from FreeVideo in the app, so the conversation there no longer reaches you. ' + 'Stop waiting now: end your turn with one sentence saying FreeVideo was disconnected. Any other FreeVideo ' + 'call, or POST /connect/hello, connects you again; make one when the user asks you to.') # An agent that connects again finds the conversation where the user left it, and has greeted there once already. RESUMED = ('This conversation is already under way; its last lines are in "before". Do not introduce yourself again: ' 'say nothing until the user speaks, then carry on from there.') @@ -486,7 +490,9 @@ def reply(value, status=200): body_key = web.AppKey('agent_body', dict) contracts = contract.contracts() page_sessions = {} - connection = dict(connected=False, client=None, via=None, last_seen_at=None) + # disconnected_at: when the user disconnected the agent from the page (until its next call that is not a wait); + # refused_at: when a call last came with a key that is not this installation's (an old one, after a reset). + connection = dict(connected=False, client=None, via=None, last_seen_at=None, disconnected_at=None, refused_at=None) refused_connects = set() def note_connect_refusal(code, request): @@ -566,8 +572,12 @@ async def respond(request): except (OSError, ValueError): raise JobError('not_ready', 'Installation not ready') from None if not given or not secrets.compare_digest(given.encode('utf-8'), token.encode('utf-8')): + if given: + connection['refused_at'] = time.time() raise JobError('unauthorized', 'Token missing or incorrect') - connection.update(connected=True, last_seen_at=time.time()) + # A wait after the user disconnected is not a new connection; any other call is. + if not (connection['disconnected_at'] is not None and suffix == '/inbox'): + connection.update(connected=True, last_seen_at=time.time(), disconnected_at=None) connection['client'] = connection['client'] or request.headers.get('X-FreeVideo-Client', 'HTTP client')[:80] connection['via'] = connection['via'] or 'http' request['agent_client'] = request.headers.get('X-FreeVideo-Client', '')[:80] or 'HTTP client' @@ -942,15 +952,34 @@ def activity_item(row, *, card=False): value.update(width=picture.get('width'), height=picture.get('height')) return value - def agent_state(): - seen, now = connection['last_seen_at'], time.time() + def link_state(now=None): + """Whether an agent is connected and, when not, why: 'user' (disconnected from the page), 'refused' (its last + call came with a key that is not this installation's), 'quiet' (no call for ten minutes; quiet_s says how long) + or 'never' (none has called since FreeVideo started).""" + seen, now = connection['last_seen_at'], time.time() if now is None else now connected = seen is not None and 0 <= now - seen < 600 + refused = connection['refused_at'] + if connected: + reason = None + elif connection['disconnected_at'] is not None: + reason = 'user' + elif refused is not None and (seen is None or refused > seen): + reason = 'refused' + else: + reason = 'never' if seen is None else 'quiet' + return dict(connected=connected, reason=reason, + quiet_s=int(now - seen) if reason == 'quiet' and now >= seen else None) + + def agent_state(): + now = time.time() + state = link_state(now) name = (connection['client'] or '').strip() # Programs report their own identifiers; the page shows the name a person knows. shown = ('Claude Code' if name.lower() in ('claude-code', 'claude code', 'claude') else 'Codex' if name.lower().startswith('codex') else name or None) # Every answer to the agent carries the user's unread words, so a recent call will hear them too. - return dict(connected=connected, name=shown, listening=connected and (chat['waiting'] > 0 or now - seen < 90)) + return dict(state, name=shown, + listening=state['connected'] and (chat['waiting'] > 0 or now - connection['last_seen_at'] < 90)) def chat_name(said): """A job the agent left unnamed is called by what the user asked for: the first words after a colon.""" @@ -1586,6 +1615,20 @@ async def reset(request): prepare_token(root) return reply(dict(reset=True)) + @routes.post('/freevideo/agent/connect/disconnect') + @guarded + async def disconnect(request): + # Only the page asks: the agent stops hearing the conversation and shows as not connected until it calls again. + if request.content_type != 'application/json': + return problem('unsupported_media_type', 'Send JSON', 415) + await body(request) + client = chat['client'] + connection.update(connected=False, last_seen_at=None, disconnected_at=time.time()) + store = work_sessions() + if store is not None and client: + store.wake(client) + return reply(dict(agent=agent_state())) + @routes.get(PREFIX + '/connect') @guarded async def connect_guide(request): @@ -1612,7 +1655,7 @@ async def hello(request): connection.update(connected=True, client=value['client'], via=value['via'], last_seen_at=time.time()) chat['told'].pop(request['agent_client'], None) # a newly connected agent has heard from no conversation yet unfinished = await asyncio.to_thread(jobs.productions.list, status='active', limit=5) - return reply(dict(connection, unfinished=unfinished)) + return reply(dict({key: connection[key] for key in ('connected', 'client', 'via', 'last_seen_at')}, unfinished=unfinished)) @routes.get(PREFIX + '/connect/status') @guarded @@ -1621,7 +1664,7 @@ async def connect_status(request): from .editor_runtime import available seen = connection['last_seen_at'] # editing: whether this installation can run project and image edits; the card says so when it cannot. - return reply(dict(connection, connected=seen is not None and 0 <= time.time() - seen < 600, + return reply(dict(client=connection['client'], via=connection['via'], connected=link_state()['connected'], last_seen_at=iso(seen), editing=available())) @routes.get(PREFIX) @@ -2182,6 +2225,16 @@ async def inbox(request): request['agent_session'] = sid # Without a session of its own choosing, the agent listens wherever its user is. follow = store is not None and not request.headers.get('X-FreeVideo-Session', '').strip() + dropped = lambda: connection['disconnected_at'] is not None + def let_go(): + return reply(dict(session=sid, inbox=[], disconnected=True, next=DISCONNECTED)) + if dropped(): + # Waited out as asked, so an agent that keeps calling does not spin; any other call connects it again. + deadline = time.monotonic() + min(50., float(request[query_key].get('wait', '0') or 0)) + while dropped() and time.monotonic() < deadline: + await asyncio.sleep(min(1., deadline - time.monotonic())) + if dropped(): + return let_go() def answer(value): told, chat['told'][client] = chat['told'].get(client), value['session'] scenes = jobs.whitebox.open_for(value['session']) if value['inbox'] else [] @@ -2224,11 +2277,14 @@ def read(): await asyncio.sleep(min(left, 1.)) else: await store.wait(sid, after=mark, seconds=min(left, 25.), by='user', - leave=(lambda here=sid: store.current_for(client) != here) if follow else None) + leave=(lambda here=sid: dropped() or store.current_for(client) != here) if follow else dropped) + if dropped(): + return let_go() finally: chat['waiting'] -= 1 - # The agent was here for the whole wait, not only when it began. - connection['last_seen_at'] = time.time() + # The agent was here for the whole wait, not only when it began; not one the user disconnected. + if not dropped(): + connection['last_seen_at'] = time.time() @routes.get(PREFIX + '/queue') @guarded diff --git a/freevideo_engine/agent/schema.py b/freevideo_engine/agent/schema.py index db038e19..a7db7b77 100644 --- a/freevideo_engine/agent/schema.py +++ b/freevideo_engine/agent/schema.py @@ -626,7 +626,7 @@ def route(summary, body=None, query=None, **kw): for suffix, method, body in (('', 'GET', None), ('/session', 'GET', None), ('/activity', 'GET', None), ('/activity/cancel', 'POST', obj({'id': JOB}, ('id',))), ('/activity/resume', 'POST', obj({'id': JOB}, ('id',))), ('/connect', 'GET', None), - ('/connect/reset', 'POST', EMPTY), ('/chat', 'GET', None), ('/chat/now', 'GET', None), + ('/connect/reset', 'POST', EMPTY), ('/connect/disconnect', 'POST', EMPTY), ('/chat', 'GET', None), ('/chat/now', 'GET', None), ('/chat/video', 'GET', None), ('/chat/list', 'GET', None), ('/chat/new', 'POST', EMPTY), ('/chat/delete', 'POST', obj({'session': SESSION, 'stop': {'type': 'boolean'}}, ('session',))), ('/chat/rename', 'POST', obj({'session': SESSION, 'title': {'type': 'string', 'maxLength': 60}}, ('session', 'title'))), diff --git a/web/agent_connect.css b/web/agent_connect.css index f1a9b764..ae3d4fc5 100644 --- a/web/agent_connect.css +++ b/web/agent_connect.css @@ -81,3 +81,23 @@ .fv-studio.fv-autopilot .fv-header.fv-header[data-place=wrap]{grid-template-columns:auto minmax(0,1fr)} @media(max-width:480px){.fv-studio.fv-autopilot .fv-header{grid-template-columns:auto minmax(0,1fr)}.fv-autopilot-now{font-size:12px}.fv-autopilot-now-name{display:none}.fv-autopilot .fv-header-actions>.fv-quiet{flex:none;white-space:nowrap}.fv-studio .fv-autopilot-now-go{padding:4px 4px 4px 8px}.fv-studio .fv-autopilot-lamp{width:30px;height:30px;padding:0;justify-content:center}.fv-autopilot-lamp>span{display:none}.fv-agent-connect-body{padding:24px}} @media(prefers-reduced-motion:reduce){.fv-autopilot-line{transition:none}} +/* The connection light's menu: disconnect and the steps while connected; why it is off and Reconnect when not. */ +.fv-autopilot .fv-autopilot-body{position:relative} +.fv-agent-link-menu{box-sizing:border-box;position:absolute;z-index:6;display:grid;gap:2px;width:max-content;min-width:200px;max-width:min(320px,calc(100% - 16px));padding:8px;border:1px solid var(--fv-border);border-radius:var(--fv-r-md);background:var(--fv-raised);box-shadow:0 14px 36px #00000073;color:var(--fv-ink);animation:fv-agent-link-enter .16s ease} +.fv-agent-link-menu[hidden],.fv-agent-link-menu [hidden]{display:none} +.fv-agent-link-menu>p{margin:0;padding:4px 12px;font-size:13px;line-height:1.5;white-space:normal;overflow-wrap:anywhere} +.fv-agent-link-menu>.fv-agent-link-next{padding-top:0;color:var(--fv-muted)} +.fv-agent-link-menu>.fv-agent-link-error{color:var(--fv-danger)} +.fv-studio .fv-agent-link-menu .fv-agent-link-item{justify-content:flex-start;width:100%;min-height:0;padding:8px 12px;border:0;border-radius:var(--fv-r-sm);background:none;color:var(--fv-ink);font-size:13px;text-align:start;white-space:nowrap} +.fv-studio .fv-agent-link-menu .fv-agent-link-item:is(:hover,:focus-visible){background:var(--fv-hover);outline:none} +.fv-studio .fv-agent-link-menu .fv-agent-link-danger{color:var(--fv-danger)} +.fv-studio .fv-agent-link-menu .fv-agent-link-danger:is(:hover,:focus-visible){background:var(--fv-danger-subtle)} +.fv-studio .fv-agent-link-menu .fv-agent-link-item:disabled{opacity:.6;cursor:default} +.fv-studio .fv-agent-link-menu .fv-agent-link-main{justify-self:start;width:auto;margin:4px 12px 2px;padding:8px 16px;border:1px solid var(--fv-accent);background:var(--fv-accent);color:var(--fv-bg);font-weight:var(--fv-semibold)} +.fv-studio .fv-agent-link-menu .fv-agent-link-main:is(:hover,:focus-visible){background:var(--fv-accent-hover);border-color:var(--fv-accent-hover);outline:none} +.fv-studio .fv-agent-link-menu .fv-agent-link-main:focus-visible{box-shadow:0 0 0 2px var(--fv-bg),0 0 0 4px var(--fv-accent)} +.fv-agent-link-menu>.fv-issue-button{justify-self:start;margin:4px 12px} +.fv-autopilot .fv-agent-link-menu{border:0;border-radius:var(--fv-rad-pop,16px);background:rgb(var(--ap-tint,24 26 32) / var(--ap-a3,.92));box-shadow:inset 0 0 0 1px var(--ap-edge,var(--fv-border)),var(--ap-sh3,0 14px 36px #00000073);-webkit-backdrop-filter:blur(var(--fv-glass-blur3,40px)) saturate(175%);backdrop-filter:blur(var(--fv-glass-blur3,40px)) saturate(175%);color:var(--ap-fg,var(--fv-ink))} +.fv-agent-connect-body>.fv-agent-connect-reason{margin-top:-8px;font-size:13px;line-height:1.5;color:var(--fv-muted)} +@keyframes fv-agent-link-enter{from{opacity:0}} +@media(prefers-reduced-motion:reduce){.fv-agent-link-menu{animation:none}} diff --git a/web/agent_connect.js b/web/agent_connect.js index 90d43135..0d2f4b85 100644 --- a/web/agent_connect.js +++ b/web/agent_connect.js @@ -69,6 +69,123 @@ export function connectCardBack(card, t, action = null) { tip(back, 'backToChats', t); } +// Why no assistant is connected, from the server's reason, with the next step; null while one is connected. +// report: the state is a failure the user may want to send us (a refused key, a state the page cannot name); an +// assistant that went quiet has most likely finished or been closed, which is not one. +export function linkReason(agent, t) { + if (agent?.connected === true) return null; + const reconnect = t('Choose Reconnect and paste the steps to your assistant.', '请点“重新连接”,把连接说明粘贴给助手。'); + if (agent?.reason === 'user') return {reason: 'user', report: false, + text: t('You disconnected the assistant.', '已断开与助手的连接。'), + next: t('To connect it again, choose Reconnect, or ask it in its own window to continue.', '如需重新连接,请点“重新连接”,或在助手的窗口中让它继续。')}; + if (agent?.reason === 'refused') return {reason: 'refused', report: true, + text: t('The assistant used a connection key that is no longer valid, so FreeVideo refused it.', '助手使用的连接密钥已失效,FreeVideo 拒绝了它。'), + next: t('Choose Reconnect and paste the steps to it again. If it is still refused, restart the assistant.', '请点“重新连接”,把连接说明再粘贴给它一次;仍被拒绝时,请重启助手。')}; + if (agent?.reason === 'quiet') { + const minutes = Math.max(10, Math.round((Number(agent.quiet_s) || 0) / 60)), hours = Math.round(minutes / 60); + const span = minutes >= 120 ? t(`${hours} hours`, `${hours} 小时`) : t(`${minutes} minutes`, `${minutes} 分钟`); + return {reason: 'quiet', report: false, + text: t(`The assistant has not contacted FreeVideo for ${span}; it may have finished or been closed.`, `助手已有 ${span}没有联系 FreeVideo,可能已经结束或被关闭。`), + next: reconnect}; + } + if (agent?.reason === 'never') return {reason: 'never', report: false, + text: t('No assistant has connected since FreeVideo started.', 'FreeVideo 启动后还没有助手连接。'), next: reconnect}; + return {reason: 'unknown', report: true, text: t('The assistant is not connected.', '助手未连接。'), next: reconnect}; +} + +// The reason above the card's button when the card stands in for a connection that ended (not on a first visit). +export function connectCardReason(card, t, agent) { + const line = card?.element?.querySelector('.fv-agent-connect-reason'); + if (!line) return; + const why = linkReason(agent, t); + line.hidden = !why || why.reason === 'never' || why.reason === 'unknown'; + line.textContent = line.hidden ? '' : why.text; +} + +// The connection light's menu. Connected: Disconnect, and the connection steps. Not connected: why, the next step, +// Reconnect and, for a failure, Report a problem. disconnect() sends the page's request (with its page session, which +// this card module never takes itself) and returns the response; steps() opens the connect card; changed() gets the +// state after a disconnect. The menu lives in `host` and opens beside `anchor` (the light). +export function agentLinkMenu(t, host, anchor, {disconnect: send, steps = () => {}, changed = () => {}} = {}) { + const menu = el('div', 'fv-agent-link-menu'); menu.hidden = true; + menu.setAttribute('role', 'dialog'); menu.setAttribute('aria-label', t('Assistant connection', '助手连接')); + menu.id = `fv-agent-link-menu-${Math.random().toString(36).slice(2, 8)}`; + const why = el('p', 'fv-agent-link-why'), next = el('p', 'fv-agent-link-next'), error = el('p', 'fv-agent-link-error'); + error.setAttribute('role', 'alert'); + const item = (text, key, action, kind = '') => { + const button = el('button', `fv-agent-link-item${kind ? ' fv-agent-link-' + kind : ''}`, text); button.type = 'button'; + button.onclick = action; tip(button, key, t); return button; + }; + const disconnect = item(t('Disconnect', '断开'), 'disconnect', () => void drop(), 'danger'); + const howTo = item(t('Connection steps', '连接方式'), 'connectSteps', () => { close(); steps(); }); + // The way out of a lost connection is the menu's main action, before Report a problem. + const reconnect = item(t('Reconnect', '重新连接'), 'reconnect', () => { close(); steps(); }, 'main'); + menu.append(why, next, error, disconnect, howTo, reconnect); + host.append(menu); + anchor.setAttribute('aria-haspopup', 'dialog'); anchor.setAttribute('aria-controls', menu.id); anchor.setAttribute('aria-expanded', 'false'); + let agent = {}, issue = null, issueText = '', failure = null, busy = false; + const report = message => issueButton(t, () => ({where: ['Assistant connection', '助手连接'], message, kind: failure?.code || agent?.reason || null})); + function render() { + const connected = agent?.connected === true, reason = linkReason(agent, t); + why.hidden = next.hidden = connected; why.textContent = reason?.text || ''; next.textContent = reason?.next || ''; + disconnect.hidden = howTo.hidden = !connected; reconnect.hidden = connected; + disconnect.disabled = busy; disconnect.setAttribute('aria-busy', String(busy)); + disconnect.textContent = busy ? t('Disconnecting…', '正在断开…') : t('Disconnect', '断开'); + error.hidden = !failure; error.textContent = failure?.text || ''; + const message = failure ? failure.text : !connected && reason?.report ? reason.text : ''; + // Kept while its sentence stays the same, so a reading that changes nothing keeps the focus where it was. + if (message !== issueText) { issue?.remove(); issue = message ? report(message) : null; issueText = message; if (issue) menu.append(issue); } + } + // A refusal says what to do when it can; otherwise the status and the way to report it. + async function drop() { + if (busy) return; + busy = true; failure = null; render(); + try { + const response = await send(); + const value = await response.json().catch(() => null); + if (!response.ok) { + const code = String(value?.error?.code || '').slice(0, 40) || null; + failure = {code, text: refusalHint(code, t) || t(`Could not disconnect (HTTP ${response.status}). Retry, or report it.`, `断开失败(HTTP ${response.status})。请重试,或提交问题。`)}; + return; + } + close(); changed(value?.agent || null); + } catch { + failure = {code: 'unreachable', text: noAnswerHint('unreachable', t)}; + } finally { busy = false; if (!menu.hidden) render(); } + } + function place() { + const box = host.getBoundingClientRect?.(), at = anchor.getBoundingClientRect?.(); + if (!box || !at) return; + // Local dimensions also handle the view's entry scale. + const sx = box.width / (host.offsetWidth || box.width) || 1, sy = box.height / (host.offsetHeight || box.height) || 1; + const width = menu.offsetWidth || 0, height = menu.offsetHeight || 0, room = host.clientHeight || box.height / sy; + const top = (at.top - box.top) / sy, bottom = (at.bottom - box.top) / sy; + // Up from a light at the foot of the chats, down from one at the top of a narrow window. + const up = bottom > room / 2; + menu.style.left = `${Math.max(8, Math.min((at.left - box.left) / sx, (host.clientWidth || box.width / sx) - width - 8))}px`; + menu.style.top = `${Math.max(8, Math.min(up ? top - height - 8 : bottom + 8, room - height - 8))}px`; + } + const outside = event => { if (!menu.contains(event.target) && !anchor.contains(event.target)) close(); }; + const keys = event => { if (event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); close(true); } }; + function open(state) { + agent = state || {}; failure = null; menu.hidden = false; anchor.setAttribute('aria-expanded', 'true'); + render(); place(); + globalThis.document?.addEventListener?.('pointerdown', outside, true); + menu.addEventListener('keydown', keys); + [disconnect, howTo, reconnect].find(button => !button.hidden)?.focus?.({preventScroll: true}); + } + function close(restore = false) { + if (menu.hidden) return; + menu.hidden = true; anchor.setAttribute('aria-expanded', 'false'); + globalThis.document?.removeEventListener?.('pointerdown', outside, true); + menu.removeEventListener('keydown', keys); + if (restore) anchor.focus?.({preventScroll: true}); + } + // The page's reading changed while the menu is open: a disconnect elsewhere, or the assistant coming back. + function update(state) { if (menu.hidden) return; agent = state || {}; render(); place(); } + return {element: menu, open, close, update, toggle: state => menu.hidden ? open(state) : close(true), get isOpen() { return !menu.hidden; }}; +} + const ICONS = {plug: ['M9 7V3M15 7V3M7 7h10v4a5 5 0 0 1-10 0V7zM12 16v5', 1.8], copy: ['M11 9h7a2 2 0 0 1 2 2v7a2 2 0 0 1-2 2h-7a2 2 0 0 1-2-2v-7a2 2 0 0 1 2-2zM5 15V5a2 2 0 0 1 2-2h8', 2], retry: ['M3 12a9 9 0 1 0 3-6.7L3 8M3 3v5h5', 2]}; function icon(name) { @@ -104,9 +221,11 @@ export function agentConnectCard(t, api, shown = () => true, changed = () => {}) const status = el('p', 'fv-agent-connect-status', t('Getting the connection address…', '正在获取连接地址…')); status.setAttribute('role', 'status'); // The way back to the chats when the card was opened from a disconnected chat (see connectCardBack). const back = el('button', 'fv-agent-connect-back fv-quiet'); back.type = 'button'; back.hidden = true; - body.append(mark, title, intro, actions, sentence, status, back); + // Why the last connection ended, when the card stands in for it (see connectCardReason). + const reason = el('p', 'fv-agent-connect-reason'); reason.hidden = true; + body.append(mark, title, intro, reason, actions, sentence, status, back); - let feedback = false, text = '', failures = 0, refusal = null, noAnswer = null; + let feedback = false, text = '', failures = 0, refusal = null, noAnswer = null, wantFocus = false; let timer, feedbackTimer, controller, generation = 0; const opened = addressKind(globalThis.location?.hostname); const active = () => body.isConnected && shown(); @@ -121,6 +240,8 @@ export function agentConnectCard(t, api, shown = () => true, changed = () => {}) button.disabled = !text && failures < 3; button.title = !text && failures < 3 ? t('Getting the connection address…', '正在获取连接地址…') : ''; tip(button, !text && failures >= 3 ? 'retryAddress' : 'copyConnect', t, {why: button.disabled ? t('Getting the connection address…', '正在获取连接地址…') : ''}); + // Asked for focus (Reconnect from the light) while the address was still loading: it goes there once usable. + if (wantFocus && !button.disabled && active()) { wantFocus = false; button.focus?.({preventScroll: true}); } status.hidden = !!text; status.textContent = !text && failures < 3 ? t('Getting the connection address…', '正在获取连接地址…') : !text ? refusalHint(refusal?.code, t) || noAnswerHint(noAnswer, t) : ''; }; render(); @@ -178,5 +299,7 @@ export function agentConnectCard(t, api, shown = () => true, changed = () => {}) // `state` is the first answer; `enabled` resolves to whether it is on. let state = agentInterfaceState(api); const first = state, enabled = first.then(value => value === 'on'); - return {element: body, state: first, enabled, sync, stop}; + // Puts the keyboard on the card's button now, or as soon as the address has loaded. + function focus() { wantFocus = true; render(); } + return {element: body, state: first, enabled, sync, stop, focus}; } diff --git a/web/autopilot.js b/web/autopilot.js index 412ee1ef..b8f2c5b4 100644 --- a/web/autopilot.js +++ b/web/autopilot.js @@ -1,7 +1,7 @@ import {createLanAccess} from './lan_access.js'; // The Agent's own page, beside the studio and the editing view: the card that connects one, then the conversation with it. import { api } from '../../scripts/api.js'; -import { agentConnectCard, connectCardBack, connectionLabel } from './agent_connect.js'; +import { agentConnectCard, agentLinkMenu, connectCardBack, connectCardReason, connectionLabel } from './agent_connect.js'; import { about, agentChat, jobName, readChatCache } from './autopilot_chat.js'; import { createRequestAssets } from './request_assets.js'; import { openEditorView } from './editor_loader.js'; @@ -14,6 +14,7 @@ import { agentTabReady, openImage, viewChanged, viewSwitch } from './view_naviga import { wordmark } from './wordmark.js'; import { keepViewSwitchPlace } from './view_switch_place.js'; import { tip } from './autopilot_tips.js'; +import { agentPost } from './agent_session.js'; const languageOverride = typeof location !== 'undefined' ? new URLSearchParams(location.search).get('freevideo_lang') : null; @@ -95,6 +96,7 @@ export function openAutopilotView(node, {studio = null, initialPrompt = '', init // can open the card again (how to connect, or connect another), with the way back to the chats. if (connected && !wasConnected) wantCard = false; wasConnected = connected; + linkMenu.update(last.agent); const ready = on === 'on' && last.known, talking = ready && (connected || last.any) && !wantCard; // The card gives way to the conversation: typing can start at once. const arrived = talking && chat.element.hidden && (card.element.contains(document.activeElement) || document.activeElement === lamp); @@ -105,6 +107,7 @@ export function openAutopilotView(node, {studio = null, initialPrompt = '', init if (arrived) chat.input.focus(); lamp.hidden = !ready; lamp.dataset.color = label.color; lampText.textContent = lamp.title = label.text; lamp.setAttribute('aria-label', label.text); lamp.disabled = !connected && !last.any; tip(lamp, connected ? 'connected' : 'disconnected', t, {title: false, why: lamp.disabled ? t('Connect an assistant first; the steps are in the middle', '先连接助手,步骤在中间的卡片里') : ''}); + if (lamp.disabled || !ready) linkMenu.close(); const job = talking ? last.current : null; phoneAccess.observe(job); now.hidden = !job; line.dataset.on = String(!!job); @@ -121,6 +124,7 @@ export function openAutopilotView(node, {studio = null, initialPrompt = '', init } // Opened from a chat whose assistant has gone: the card offers the way back to the chats. connectCardBack(card, t, (connected || last.any) && wantCard ? () => { wantCard = false; show(); chat.input.focus(); } : null); + connectCardReason(card, t, last.known ? last.agent : {connected: true}); card.sync(); // The main block is whichever is in front: the connect card or the conversation's column. The first screen is // final once the interface has answered and, when it is on, the conversation has been read once. @@ -131,7 +135,11 @@ export function openAutopilotView(node, {studio = null, initialPrompt = '', init if (front && on !== null && (on !== 'on' || last.known)) markReady(); } function markReady() { clearTimeout(readyTimer); if (dialog.dataset.fvReady !== 'true') dialog.dataset.fvReady = 'true'; } - lamp.onclick = () => { wantCard = !wantCard; show(); }; + // The light opens its menu (disconnect, reconnect, why it is off); with the card opened from it, it closes the card. + const linkMenu = agentLinkMenu(t, body, lamp, {disconnect: () => agentPost(api, '/freevideo/agent/connect/disconnect', {}), + steps: () => { wantCard = true; show(); card.focus(); }, + changed: agent => { if (agent) { last = {...last, agent}; show(); } chat.refresh(); }}); + lamp.onclick = () => { if (wantCard) { wantCard = false; show(); } else linkMenu.toggle(last.agent); }; go.onclick = () => chat.scrollToJob(currentId); halt.onclick = () => chat.stopAll(); body.append(card.element, chat.element); @@ -153,7 +161,7 @@ export function openAutopilotView(node, {studio = null, initialPrompt = '', init dialog.inert = true; if (current === dialog) current = null; dialog.querySelectorAll('video,audio').forEach(media => media.pause()); - card.stop(); + linkMenu.close(); card.stop(); const then = next; next = goBack; then(); } // Any other view in front (the node view has no dialog of its own) keeps a closed Autopilot out of sight and out of reach. diff --git a/web/autopilot_tips.js b/web/autopilot_tips.js index 9327e2b5..6e00f250 100644 --- a/web/autopilot_tips.js +++ b/web/autopilot_tips.js @@ -12,8 +12,11 @@ export const TIPS = Object.freeze({ expandRight: {name: ['Show tasks', '展开任务栏'], use: ['See what is being made and its details', '查看正在生成的内容和详情']}, chats: {name: ['Chats', '对话'], use: ['Open the chat list', '打开对话列表']}, tasks: {name: ['Tasks', '任务'], use: ['What is being made, and the details', '正在生成的内容和详情']}, - connected: {name: ['Assistant connected', '助手已连接'], use: ['See how it is connected, or add another', '查看连接方式,或再连一个']}, - disconnected: {name: ['Not connected', '未连接'], use: ['Show how to connect an assistant', '查看如何连接助手']}, + connected: {name: ['Assistant connected', '助手已连接'], use: ['Disconnect it, or see how it is connected', '断开,或查看连接方式']}, + disconnected: {name: ['Not connected', '未连接'], use: ['See why, and connect again', '查看原因并重新连接']}, + disconnect: {name: ['Disconnect', '断开'], use: ['It stops hearing this chat until it calls again', '助手不再收到这里的对话,再联系时自动重连']}, + connectSteps: {name: ['Connection steps', '连接方式'], use: ['See how it is connected, or connect another', '查看连接方式,或再连一个']}, + reconnect: {name: ['Reconnect', '重新连接'], use: ['Copy the steps and paste them to your assistant', '复制连接说明,粘贴给助手']}, goRunning: {name: ['Go to the task', '定位到任务'], use: ['Scroll the chat to what is being made', '把对话滚到正在生成的内容']}, stopAll: {name: ['Stop all', '全部停止'], use: ['Stop everything the assistant is making', '停止助手正在生成的全部内容']}, taskSearch: {name: ['Search tasks', '搜索任务'], use: ['Find a task by its prompt or name', '按提示词或名称找到任务']}, From 1594a8bd9e737441b424fc842619e24c922612d6 Mon Sep 17 00:00:00 2001 From: Bowen Xue Date: Wed, 18 Nov 2026 04:25:45 +0000 Subject: [PATCH 38/97] The works library opens the folder that holds the videos: a Video folder button, and Show in... The works library opens the folder that holds the videos: a Video folder button, and Show in folder works for every video; when the folder cannot be opened, the note says so and names it, and a long path wraps and stays long enough to copy. --- freevideo_engine/comfy_library.py | 55 +++++++++++++++++++++++++++++++ web/library.css | 4 +-- web/library.js | 32 +++++++++++++++--- 3 files changed, 85 insertions(+), 6 deletions(-) diff --git a/freevideo_engine/comfy_library.py b/freevideo_engine/comfy_library.py index 5ded2a96..b5a0dabc 100644 --- a/freevideo_engine/comfy_library.py +++ b/freevideo_engine/comfy_library.py @@ -1489,6 +1489,43 @@ def folder_sizes(output_directory, identities): return sizes +def video_folder(output_directory, identity=None): + """The folder holding the saved videos, or one saved video's own folder when `identity` names it.""" + root = Path(output_directory).resolve() / 'FreeVideo' + if identity is None: + folder = root + else: + if not isinstance(identity, str) or not _ID.fullmatch(identity): + raise ValueError('Invalid video identity') + folder = root / identity + if folder.is_symlink() or is_junction(folder): + raise ValueError('Invalid video identity') + if not folder.is_dir(): + if identity is None and Path(output_directory).is_dir(): + return Path(output_directory).resolve() # nothing generated yet: show where videos will be saved + raise FileNotFoundError(str(folder)) + return folder + + +def show_folder(folder): + """Show a folder in this computer's file manager; False when that cannot be done.""" + if windows(): + failure = [] + + def show(): + try: + os.startfile(str(folder)) + except OSError as error: + failure.append(error) + # The shell can block for good without a desktop session (SSH, service); never wait on it here. + thread = threading.Thread(target=show, name='library-open-folder', daemon=True) + thread.start() + thread.join(2) + return thread.is_alive() is False and not failure + from .windows_ux import open_folder + return open_folder(folder) + + def register(): from aiohttp import web import folder_paths @@ -1702,6 +1739,24 @@ async def picture_preview(request): return web.Response(status=304, headers=headers) return web.Response(body=data, content_type='image/webp', headers=headers) + @server.routes.post('/freevideo/library/open-folder') + async def open_folder(request): + # It opens a window on the computer running FreeVideo, so only that computer may ask. + # The custom header keeps other websites from posting to it without the browser's pre-check. + if request.remote not in ('127.0.0.1', '::1') or request.headers.get('X-FreeVideo-Library') != '1': + raise web.HTTPForbidden(text='Open the folder on the computer that runs FreeVideo') + try: + body = await request.json() + identity = body.get('id') if isinstance(body, dict) else None + folder = await asyncio.to_thread(video_folder, folder_paths.get_output_directory(), identity) + except (ValueError, TypeError) as error: + raise web.HTTPBadRequest(text=str(error)) from error + except OSError: + raise web.HTTPNotFound(text='Saved video unavailable') from None + opened = await asyncio.to_thread(show_folder, folder) + return web.json_response(dict(opened=True) if opened else dict(opened=False, folder=str(folder)), + headers={'Cache-Control': 'no-store'}) + @server.routes.post('/freevideo/library/delete') async def delete(request): try: diff --git a/web/library.css b/web/library.css index 7a5de49e..6711ac4b 100644 --- a/web/library.css +++ b/web/library.css @@ -172,10 +172,10 @@ dialog.fv-studio.fv-library::backdrop{background:var(--lib-page)} .fv-library .fv-library-selection-actions .fv-library-danger,.fv-library .fv-library-danger{background:#c8353a;color:#fff;font-weight:600;padding:0 var(--fv-sp-16,16px)} .fv-library .fv-library-selection-actions .fv-library-danger:hover:not(:disabled){background:#d4434a;color:#fff} .fv-library .fv-library-undo{display:flex;flex-wrap:wrap;align-items:center;justify-content:center;gap:var(--fv-sp-4,4px) var(--fv-sp-12,12px);margin:0;min-height:40px;padding:var(--fv-sp-4,4px) var(--fv-sp-8,8px) var(--fv-sp-4,4px) var(--fv-sp-16,16px); - border-radius:var(--fv-r-pill);font-size:var(--fv-fs-2,13px);color:var(--fv-fg)} + border-radius:var(--fv-r-pill);font-size:var(--fv-fs-2,13px);color:var(--fv-fg);max-width:100%;box-sizing:border-box} .fv-library .fv-library-undo[data-warn=true]{color:var(--fv-warn)} .fv-library .fv-library-undo button{height:var(--fv-ctl,32px);min-height:var(--fv-ctl,32px);padding:0 var(--fv-sp-12,12px);border:0;border-radius:var(--fv-r-sm);background:var(--fv-accent-soft);color:var(--fv-accent-ink);font-size:var(--fv-fs-2,13px);font-weight:600} -.fv-library .fv-library-skipped{font-size:var(--fv-fs-1,12px);color:var(--fv-fg3)} +.fv-library .fv-library-skipped{font-size:var(--fv-fs-1,12px);color:var(--fv-fg3);min-width:0;overflow-wrap:anywhere} .fv-library-ring{--fv-left:1;width:16px;height:16px;border-radius:var(--fv-r-pill);background:conic-gradient(var(--fv-accent-ink) calc(var(--fv-left) * 360deg),var(--fv-line2) 0); -webkit-mask:radial-gradient(circle,transparent 4.5px,#000 5px);mask:radial-gradient(circle,transparent 4.5px,#000 5px);animation:fv-library-ring var(--fv-ms,10000ms) linear forwards} @property --fv-left{syntax:'';inherits:false;initial-value:1} diff --git a/web/library.js b/web/library.js index 8c32afe0..426f8518 100644 --- a/web/library.js +++ b/web/library.js @@ -197,6 +197,20 @@ async function askUndoState(path, body) { return (await response.json()).batches || {}; } catch { return null; } } +// Shows the saved videos (or one video's folder) in this computer's file manager; the page says where they are when that fails. +async function openVideoFolder(id) { + try { + const response = await api.fetchApi('/freevideo/library/open-folder', {method: 'POST', headers: {...jsonHeaders, 'X-FreeVideo-Library': '1'}, body: JSON.stringify(id ? {id} : {}), signal: AbortSignal.timeout(5000)}); + if (response.status === 404) return {missing: true}; + if (!response.ok) return null; + return await response.json(); + } catch { return null; } +} +const videoFolderMessage = (t, answer, single = false) => !answer + ? t('Could not open the folder. Open it on the computer that runs FreeVideo.', '没能打开文件夹。请在运行 FreeVideo 的电脑上打开。') + : answer.missing ? t('The video file cannot be found. If you moved the file, refresh the page.', '找不到这条视频的文件。如果移动过文件,请刷新页面。') + : answer.opened === false && answer.folder + ? t(`Could not open the folder. ${single ? 'This video is' : 'The videos are'} in ${answer.folder}`, `没能打开文件夹。视频在 ${answer.folder}`) : ''; // Keeps earlier batches of one click undoable while its next request runs, then gives them the normal time again. async function holdBatches(tokens, running) { const states = await askUndoState('/freevideo/library/hold', {batches: tokens, running}); @@ -494,7 +508,13 @@ export function openLibrary(t, options = {}) { }, 'fv-library-place fv-library-open-folder'); openFolder.append(line('folder'), el('span', t('Picture folder', '图片文件夹'), 'fv-library-place-name')); tip(openFolder, t('Picture folder', '图片文件夹'), t('Show the pictures in the file manager', '在文件管理器里打开图片所在文件夹')); - bottom.append(placeTrash, openFolder); + const openVideoFolderButton = button('', async () => { + const answer = await openVideoFolder(); const text = videoFolderMessage(t, answer); + if (text) say(text, !answer || answer.missing, answer?.folder ? 20000 : 4000); // a path stays long enough to be copied + }, 'fv-library-place fv-library-open-folder fv-library-open-video-folder'); + openVideoFolderButton.append(line('folder'), el('span', t('Video folder', '视频文件夹'), 'fv-library-place-name')); + tip(openVideoFolderButton, t('Video folder', '视频文件夹'), t('Show the videos in the file manager', '在文件管理器里打开视频所在文件夹')); + bottom.append(placeTrash, openVideoFolderButton, openFolder); // --- The shelf: tool row, day groups, the dock for undo and the selection --- const collection = el('section', null, 'fv-library-collection'); collection.setAttribute('aria-label', t('Saved creations', '已保存的作品')); @@ -1421,8 +1441,12 @@ export function openLibrary(t, options = {}) { run: async () => { try { await navigator.clipboard.writeText(promptOf); say(t('Prompt copied.', '已复制提示词。')); } catch { say(t('Could not copy.', '没能复制。'), true); } }}); } if (one) items.push({id: 'folder', icon: 'folder', label: ['Show in folder', '在文件夹中显示'], - disabled: one.kind === 'image' ? '' : ['Use Copy path in the details to find the video file', '可用详情里的“复制路径”找到视频文件'], run: async () => { + if (one.kind !== 'image') { + const answer = await openVideoFolder(one.id); const text = videoFolderMessage(t, answer, true); + if (text) say(text, !answer || answer.missing, answer?.folder ? 20000 : 4000); + return; + } try { const answer = await (await pictures()).historyOpen(); if (answer && answer.opened === false && answer.folder) say(t(`The pictures are in ${answer.folder}`, `图片在 ${answer.folder}`)); } catch { say(t('Could not open the folder.', '没能打开文件夹。'), true); } }}); @@ -1629,10 +1653,10 @@ export function openLibrary(t, options = {}) { let undoNote = null, undoFailure = ''; // A short line in the dock (a favorite saved for many, a folder that could not open). let sayTimer = 0; - function say(text, warn = false) { + function say(text, warn = false, hold = 4000) { clearTimeout(sayTimer); undoNote = text; undoBar.dataset.warn = String(warn); showUndo(); - sayTimer = setTimeout(() => { if (undoNote === text) { undoNote = null; showUndo(); } }, 4000); + sayTimer = setTimeout(() => { if (undoNote === text) { undoNote = null; showUndo(); } }, hold); } // Shows what can still be undone: every batch deleted within the undo time, from any // dialog, tab or page load, and the pictures this page holds. Without any, only the notes remain. From 0746bd9b83983fadf247a6a5f5bcc2113c3b3c6c Mon Sep 17 00:00:00 2001 From: Bowen Xue Date: Wed, 18 Nov 2026 04:27:05 +0000 Subject: [PATCH 39/97] Comment: the opening screen follows only the FreeVideo launcher's visit --- freevideo_engine/comfy_boot.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/freevideo_engine/comfy_boot.py b/freevideo_engine/comfy_boot.py index 26c38887..6ca8291f 100644 --- a/freevideo_engine/comfy_boot.py +++ b/freevideo_engine/comfy_boot.py @@ -3,11 +3,11 @@ ComfyUI serves its own index.html; FreeVideo's interface arrives later, as an extension. Without help, a visit that opens FreeVideo first shows ComfyUI's loading screen and only then FreeVideo. This module adds a small inline style and script at the very start of that page's . When the visit opens FreeVideo (the launcher's -``?freevideo=launch``, a refresh of such a tab, or a browser whose last FreeVideo view is not the node view), the +``?freevideo=launch``, or a refresh of such a tab, unless its last view was the node view), the first frame is FreeVideo's ground with its top bar outline, and ComfyUI stays out of sight until FreeVideo's shell has put its first view in front (shell.js calls ``__freevideoBoot.done()``). If FreeVideo's scripts never load, ComfyUI is -shown after 10 s with a short note, so nobody is left in front of an empty screen. Visits to the node view or to the -user's own ComfyUI are not changed. +shown after 10 s with a short note, so nobody is left in front of an empty screen. Any other way of opening ComfyUI +(a bare address, another launcher) is not changed: only the FreeVideo launcher opens FreeVideo. """ import logging import os From 07e505754c6a084d5bc52e62d0721a4379317137 Mon Sep 17 00:00:00 2001 From: Bowen Xue Date: Wed, 18 Nov 2026 04:27:16 +0000 Subject: [PATCH 40/97] Prompt enhancement: a failed rewrite's memory readings also name where the worker stopped, and... Prompt enhancement: a failed rewrite's memory readings also name where the worker stopped, and the feedback form's contract says readings may carry fixed code identifiers --- web/issue_button.js | 4 ++-- web/prompt_enhance.js | 9 ++++++++- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/web/issue_button.js b/web/issue_button.js index 6e4cbe9d..abbb72f7 100644 --- a/web/issue_button.js +++ b/web/issue_button.js @@ -9,8 +9,8 @@ const ISSUE_FORM = 'https://github.com/FlashML-org/FreeVideo/issues/new'; /** * Title, text and summary for the prefilled form. `where` is [English, Chinese] words for the place - * ("Export", "导出"); `message` is the sentence the user sees; `facts` is an optional flat object of numbers and - * states (never text or paths) that travels in the summary. + * ("Export", "导出"); `message` is the sentence the user sees; `facts` is an optional flat object of numbers, + * states and fixed code identifiers (never user text or paths) that travels in the summary. */ export function issueDraft({where, message, kind = null, facts = null}, t = en => en) { const place = Array.isArray(where) ? where : [String(where || 'FreeVideo'), String(where || 'FreeVideo')]; diff --git a/web/prompt_enhance.js b/web/prompt_enhance.js index 3e570cae..2c3bed20 100644 --- a/web/prompt_enhance.js +++ b/web/prompt_enhance.js @@ -191,6 +191,13 @@ export function createPromptEnhancer({node, input, editor, api, context, setText 'streamed_layers', 'available_memory_at_start_bytes', 'available_memory_before_load_bytes']; const factsOf = diagnostics => Object.fromEntries(MEMORY_FACTS.filter(key => ['number', 'string'].includes(typeof diagnostics?.[key])) .map(key => [key, diagnostics[key]])); + // Where the worker failed: exception class and the last stack frames as module:function:line, no paths and no message text. + const plainName = value => typeof value === 'string' && /^[A-Za-z_][\w.]{0,60}$/.test(value) ? value : null; + const failureOf = row => { + const frames = (Array.isArray(row?.error_details) ? row.error_details : []).map(frame => [plainName(frame?.module), plainName(frame?.function), frame?.line]) + .filter(([module, name, line]) => module && name && Number.isInteger(line)).slice(-5).map(([module, name, line]) => `${module}:${name}:${line}`); + return Object.assign(plainName(row?.exception) ? {failure_exception: row.exception} : {}, frames.length ? {failure_location: frames.join(' > ')} : {}); + }; const gib = value => String(Math.round(value / 2 ** 30)); // Mentions are counted as the character descriptions they expand to, so the count can exceed what the box shows. const lengthOf = (error, english) => { @@ -349,7 +356,7 @@ export function createPromptEnhancer({node, input, editor, api, context, setText } if (row.phase === 'complete') return row; if (row.phase === 'failed') { - memoryFacts = row.error === 'out_of_memory' ? factsOf(row.diagnostics) : null; + memoryFacts = row.error === 'out_of_memory' ? {...factsOf(row.diagnostics), ...failureOf(row)} : null; throw Object.assign(new Error(row.error || 'rewrite_failed'), {ramBytes: row.diagnostics?.ram_required_bytes, holders: row.gpu_holders}); } if (row.phase === 'cancelled') throw new Error(action === 'install' ? 'download_failed' : 'cancelled'); From bddd97406416c2648cedbd760e482a9fbd3371de Mon Sep 17 00:00:00 2001 From: Bowen Xue Date: Wed, 18 Nov 2026 04:43:55 +0000 Subject: [PATCH 41/97] Make the editor comfortable on touch screens wider than a phone On tablets and touch laptops every editor control now has a press area of at least 44 x 44. The tool row grows to 52 px and the play row to 48 px, with its keys kept apart. Undo, redo, split, delete, snapping, the zoom slider and Fit stay on the tool row, and the other tools move behind the "..." menu, whose rows are 44 px tall (record and text also stay at 1180 px and wider). Track heads are 240 px wide with 44 px switches at 1024 px and wider, so track names stay whole, and the ruler corner matches the heads; below that a 44 px icon column opens its switches on a press. Clip trim grips are 24 px wide and the playhead grip is 44 px. Mouse and phone layouts are unchanged. --- web/editor.js | 6 ++- web/editor_toolbar_more.js | 41 ++++++++++------ web/editor_touch.css | 97 ++++++++++++++++++++++++++++++++++++++ web/editor_tracks.css | 2 + web/editor_tracks.js | 12 +++-- 5 files changed, 138 insertions(+), 20 deletions(-) create mode 100644 web/editor_touch.css diff --git a/web/editor.js b/web/editor.js index c3d9653f..fa895de6 100644 --- a/web/editor.js +++ b/web/editor.js @@ -55,7 +55,7 @@ import {jobs} from './task_store.js'; import {openingChoice} from './editor_opening.js'; import {CN} from './topbar_state.js'; import {setDisabled} from './dom_quiet.js'; -const editorStyles = Promise.all(['result_actions.css', 'editor.css', 'editor_expand.css', 'editor_tracks.css', 'editor_frame.css', 'editor_adjust.css', 'editor_adjust_picture.css', 'editor_preview_picture.css', 'editor_select.css', 'editor_menu.css', 'editor_text.css', 'editor_notes.css', 'editor_transport.css', 'glass/editor.css'].map(name => { +const editorStyles = Promise.all(['result_actions.css', 'editor.css', 'editor_expand.css', 'editor_tracks.css', 'editor_frame.css', 'editor_adjust.css', 'editor_adjust_picture.css', 'editor_preview_picture.css', 'editor_select.css', 'editor_menu.css', 'editor_text.css', 'editor_notes.css', 'editor_transport.css', 'glass/editor.css', 'editor_touch.css'].map(name => { const style = document.createElement('link'); style.rel = 'stylesheet'; style.href = new URL(name, import.meta.url).href; const ready = 'sheet' in style ? new Promise(resolve => { style.onload = style.onerror = resolve; }) : Promise.resolve(); document.head.append(style); return ready; @@ -1907,7 +1907,9 @@ export function openEditor({api, app, from = null, panel = {}, components: given editTools.append(secondPassButton); toolbar.append(adjust.toggleButton); const textTools = createEditorText({element, state, t, actions, adjust, player, toolbar, exportBox, tracksHost}); - const toolbarMore = createToolbarMore({toolbar, t, keep: '.fv-ed-undo, .fv-ed-split, .fv-ed-delete, .fv-ed-adjust-toggle, .fv-ed-zoom, .fv-ed-stems-button, .fv-ed-second-pass'}); + const toolbarMore = createToolbarMore({toolbar, t, keep: '.fv-ed-undo, .fv-ed-split, .fv-ed-delete, .fv-ed-adjust-toggle, .fv-ed-zoom, .fv-ed-stems-button, .fv-ed-second-pass', + touchKeep: '.fv-ed-undo, .fv-ed-redo, .fv-ed-split, .fv-ed-delete, .fv-ed-snapping, .fv-ed-adjust-toggle, .fv-ed-zoom, .fv-ed-stems-button, .fv-ed-second-pass', + touchWideKeep: '.fv-ed-record-toggle, .fv-ed-add-text'}); actions.speech.ability().then(value => { if (!disposed) textTools.speech(value); }).catch(() => {}); // The command palette (Ctrl/Cmd+K) offers this view's actions while it is open; a greyed one says why (the control's own reason). { diff --git a/web/editor_toolbar_more.js b/web/editor_toolbar_more.js index 638599aa..e9786e27 100644 --- a/web/editor_toolbar_more.js +++ b/web/editor_toolbar_more.js @@ -1,7 +1,8 @@ // At phone widths the track toolbar keeps one row; the tools outside `keep` move behind ⋯ and come back on a wider window. -const NARROW = '(max-width:480px)'; +// On a wider touch screen the toolbar keeps `touchKeep` (plus `touchWideKeep` from 1180 px) at finger size and the rest go behind ⋯. +const NARROW = '(max-width:480px)', TOUCH = '(pointer:coarse) and (min-width:481px)', TOUCH_WIDE = '(pointer:coarse) and (min-width:1180px)'; -export function createToolbarMore({toolbar, t, keep}) { +export function createToolbarMore({toolbar, t, keep, touchKeep = null, touchWideKeep = null}) { const more = document.createElement('button'); more.type = 'button'; more.className = 'fv-ed-more fv-ed-icon'; more.setAttribute('aria-label', t('More tools', '更多工具')); more.title = more.getAttribute('aria-label'); more.setAttribute('aria-expanded', 'false'); more.hidden = true; @@ -11,9 +12,16 @@ export function createToolbarMore({toolbar, t, keep}) { const panel = document.createElement('div'); panel.className = 'fv-ed-more-panel'; panel.setAttribute('role', 'group'); panel.setAttribute('aria-label', more.title); panel.hidden = true; toolbar.append(more, panel); // Without matchMedia (a bare DOM) the toolbar keeps its wide layout. - const media = typeof window.matchMedia === 'function' ? window.matchMedia(NARROW) : null, moved = []; - const items = () => [...toolbar.children].flatMap(node => node.classList.contains('fv-ed-tool-group') ? [...node.children] : [node]) - .filter(node => node !== more && node !== panel && !node.matches(keep)); + const query = value => typeof window.matchMedia === 'function' ? window.matchMedia(value) : null; + const media = query(NARROW), touch = touchKeep ? query(TOUCH) : null, touchWide = touchKeep && touchWideKeep ? query(TOUCH_WIDE) : null, moved = []; + let movedKeep = ''; + // The keep list in force now; empty when every tool stays on the toolbar. + const current = () => media?.matches ? keep : touch?.matches ? (touchWide?.matches ? `${touchKeep}, ${touchWideKeep}` : touchKeep) : ''; + // On a touch screen a nested group that holds a kept tool opens up too, so its kept tool stays while its neighbours move + // (phones move nested groups whole, as before). + const spread = (node, wanted) => node.classList.contains('fv-ed-tool-group') && (node.parentNode === toolbar || (wanted !== keep && node.querySelector(wanted))) ? [...node.children].flatMap(child => spread(child, wanted)) : [node]; + const items = wanted => [...toolbar.children].flatMap(node => spread(node, wanted)) + .filter(node => node !== more && node !== panel && !node.matches(wanted)); // Each row names its tool; labels are read on opening because tools rename themselves (shortcut hints dropped). function open(value) { if (value) for (const control of panel.querySelectorAll('button')) { control.dataset.moreLabel = (control.getAttribute('aria-label') || control.textContent).replace(/\s*[((][^()()]*[))]$/, ''); control.toggleAttribute('data-more-icon', !!control.querySelector('svg')); } @@ -24,17 +32,20 @@ export function createToolbarMore({toolbar, t, keep}) { } function apply() { open(false); - if (media?.matches && !moved.length) { - for (const node of items()) { - const place = document.createComment('fv-ed-more'); node.before(place); moved.push([node, place]); panel.append(node); - } - } else if (!media?.matches && moved.length) { - for (const [node, place] of moved.splice(0)) { + const wanted = current(); + if (moved.length && wanted !== movedKeep) { + for (const [node, place] of moved.splice(0).reverse()) { place.replaceWith(node); for (const control of node.matches('button') ? [node] : node.querySelectorAll('button')) { delete control.dataset.moreLabel; control.removeAttribute('data-more-icon'); } } } - more.hidden = !media?.matches; + if (wanted && !moved.length) { + for (const node of items(wanted)) { + const place = document.createComment('fv-ed-more'); node.before(place); moved.push([node, place]); panel.append(node); + } + movedKeep = wanted; + } + more.hidden = !wanted; } more.onclick = () => open(panel.hidden); // A chosen tool acts first, then the menu closes; switches keep their pressed look for the next opening. @@ -50,13 +61,15 @@ export function createToolbarMore({toolbar, t, keep}) { }; const outside = event => { if (!panel.hidden && !panel.contains(event.target) && !more.contains(event.target)) open(false); }; document.addEventListener('pointerdown', outside, true); - media?.addEventListener('change', apply); apply(); + const watched = [media, touch, touchWide].filter(Boolean); + for (const list of watched) list.addEventListener('change', apply); + apply(); return { refresh: apply, dismiss(event) { if (panel.hidden) return false; event.preventDefault(); event.stopPropagation(); open(false); more.focus(); return true; }, - dispose() { media?.removeEventListener('change', apply); document.removeEventListener('pointerdown', outside, true); } + dispose() { for (const list of watched) list.removeEventListener('change', apply); document.removeEventListener('pointerdown', outside, true); } }; } diff --git a/web/editor_touch.css b/web/editor_touch.css new file mode 100644 index 00000000..f9e7f850 --- /dev/null +++ b/web/editor_touch.css @@ -0,0 +1,97 @@ +/* ── Touch screens wider than a phone (tablets, touch laptops): every key the finger takes is at least 44 × 44 with a + 16–20 px icon. The tool row grows 40 → 52 and the play row 40 → 48 (20 px in all); the picture keeps its place. + A mouse never matches this block, and phones (≤ 480 px) keep their own layout. ── */ +@media (pointer:coarse) and (min-width:481px){ + /* Rows: play row 48, tool row 52. */ + .fv-studio.fv-editor,.fv-studio.fv-editor:has(.fv-ed-genbar[data-voice=true]){grid-template-rows:auto var(--fv-ed-project-h) minmax(96px,1fr) 48px var(--fv-ed-generation-row) 52px var(--fv-ed-timeline-h)} + .fv-ed-notice-stack{bottom:calc(var(--fv-ed-timeline-h) + 52px + var(--fv-ed-generation-row) + 56px)} + .fv-ed-gen-tray{bottom:calc(100% + 56px)} + + /* Tool row: undo, redo, split, delete, snapping and zoom stay; editor_toolbar_more.js moves the rest behind ⋯. */ + .fv-studio.fv-editor .fv-ed-toolbar{height:52px;gap:8px} + .fv-studio.fv-editor .fv-ed-toolbar .fv-ed-tool-group{gap:0} + .fv-studio.fv-editor .fv-ed-toolbar .fv-ed-tool-group+.fv-ed-tool-group:before{margin-right:4px} + .fv-studio.fv-editor .fv-ed-toolbar>:is(.fv-ed-tool-group,.fv-ed-tool-group>.fv-ed-tool-group) button, + .fv-studio.fv-editor .fv-ed-toolbar>:is(.fv-ed-more,.fv-ed-snapping,.fv-ed-shortcuts,.fv-ed-adjust-toggle,.fv-ed-stems-button){height:44px;min-height:44px;min-width:44px} + .fv-studio.fv-editor .fv-ed-toolbar>:is(.fv-ed-tool-group,.fv-ed-tool-group>.fv-ed-tool-group) .fv-ed-icon, + .fv-studio.fv-editor .fv-ed-toolbar>:is(.fv-ed-more,.fv-ed-snapping,.fv-ed-shortcuts){width:44px;padding:0} + .fv-studio.fv-editor .fv-ed-toolbar :is(button>svg,.fv-ed-more svg){width:18px;height:18px} + /* Zoom: the slider alone (44 px tall, a 24 px knob) and Fit; the − and + keys leave. */ + .fv-studio.fv-editor .fv-ed-toolbar .fv-ed-track-zoom{display:flex;align-items:center;height:44px;gap:4px} + .fv-studio.fv-editor .fv-ed-toolbar .fv-ed-track-zoom>button:not(.fv-ed-fit){display:none} + .fv-studio.fv-editor .fv-ed-toolbar .fv-ed-track-zoom .fv-ed-fit{height:44px;min-height:44px;min-width:44px;padding:0 10px} + .fv-studio.fv-editor .fv-ed-toolbar .fv-ed-zoom-slider{-webkit-appearance:none;appearance:none;width:112px;height:44px;margin:0;background:transparent;touch-action:none} + .fv-studio.fv-editor[data-adjust-available=true] .fv-ed-toolbar .fv-ed-zoom-slider{width:96px} + .fv-studio.fv-editor .fv-ed-toolbar .fv-ed-zoom-slider::-webkit-slider-runnable-track{height:4px;border-radius:2px;background:var(--fv-line2,var(--fv-border))} + .fv-studio.fv-editor .fv-ed-toolbar .fv-ed-zoom-slider::-moz-range-track{height:4px;border-radius:2px;background:var(--fv-line2,var(--fv-border))} + .fv-studio.fv-editor .fv-ed-toolbar .fv-ed-zoom-slider::-webkit-slider-thumb{-webkit-appearance:none;appearance:none;width:24px;height:24px;margin-top:-10px;border:0;border-radius:50%;background:var(--fv-accent);box-shadow:0 1px 3px rgb(0 0 0 / .35)} + .fv-studio.fv-editor .fv-ed-toolbar .fv-ed-zoom-slider::-moz-range-thumb{width:24px;height:24px;border:0;border-radius:50%;background:var(--fv-accent);box-shadow:0 1px 3px rgb(0 0 0 / .35)} + /* The ⋯ menu: 44 px rows. */ + .fv-studio.fv-editor .fv-ed-toolbar .fv-ed-more-panel{max-height:min(380px,60dvh)} + .fv-studio.fv-editor .fv-ed-toolbar .fv-ed-more-panel button{height:44px;min-height:44px;width:100%} + + /* Play row: segment and frame steps 44 × 44, play 56 × 44, the right group 44 × 44; the time is unchanged. */ + .fv-studio.fv-editor :is(.fv-ed-transport-center,.fv-ed-transport-tools) button{width:44px;height:44px;min-height:44px} + .fv-studio.fv-editor .fv-ed-transport-center .fv-ed-play{width:56px;height:44px} + .fv-studio.fv-editor .fv-ed-transport-center,.fv-studio.fv-editor .fv-ed-transport-tools{gap:0} +} +/* From 681 px the play row's side columns never get narrower than their keys (the tools take 220 px), and the play + group stays in its own column, so no two keys overlap in a 560 px row. */ +@media (pointer:coarse) and (min-width:681px){ + .fv-studio.fv-editor .fv-ed-transport{grid-template-columns:minmax(max-content,1fr) auto minmax(max-content,1fr);padding:0 8px} + .fv-studio.fv-editor .fv-ed-transport-center{translate:none} +} +@media (pointer:coarse) and (min-width:481px){ + + /* Clip trim handles look the same; the grip around each is 24 px wide and the clip's full height + (The clip clips its content, so the grip reaches exactly from the clip's top to its foot.) */ + .fv-studio.fv-editor .fv-ed-trim-handle::before{inset:-200px auto;width:24px} + .fv-studio.fv-editor .fv-ed-trim-start::before{left:-2px} + .fv-studio.fv-editor .fv-ed-trim-end::before{right:-2px} + /* The playhead's grip is 44 px wide and 40 px tall; its tab is drawn where it was. */ + .fv-studio.fv-editor .fv-ed-playhead-handle{left:calc(-22px + var(--fv-ed-handle-shift,0px));top:-20px;width:44px;height:40px} + .fv-studio.fv-editor .fv-ed-playhead-handle::after{left:calc(15.5px - var(--fv-ed-handle-shift,0px));top:10px} + + /* Generate bar: every control 44 px tall in the same 60 px row. */ + .fv-studio.fv-editor .fv-ed-genbar .fv-ed-generate{height:44px;min-height:44px} + .fv-studio.fv-editor .fv-ed-genbar .fv-ed-pass-options>summary{height:44px;min-height:44px;width:44px} + .fv-studio.fv-editor .fv-ed-genbar .fv-ed-description-box .fv-ed-description{min-height:42px} + .fv-studio.fv-editor .fv-ed-genbar .fv-ed-description-box{padding-right:92px} + .fv-studio.fv-editor .fv-ed-genbar :is(.fv-ed-history-button,.fv-ed-expand){width:44px;height:44px;min-height:44px;bottom:-1px} + .fv-studio.fv-editor .fv-ed-genbar .fv-ed-expand{right:0} + .fv-studio.fv-editor .fv-ed-genbar .fv-ed-history-button{right:44px} + .fv-studio.fv-editor .fv-ed-genbar .fv-ed-duration input[type=number]{height:44px;min-height:44px} + .fv-studio.fv-editor .fv-ed-genbar :is(.fv-ed-ref-add,.fv-ed-ref-chip){width:44px;height:44px;min-height:44px} + + /* Project row and the side panels: the name, Export, the tabs, search and import are 44 px tall. */ + .fv-studio.fv-editor .fv-ed-project-row :is(.fv-ed-name,.fv-ed-export-main,.fv-ed-save-state), + .fv-studio.fv-editor .fv-ed-export-box>button{height:44px;min-height:44px} + .fv-studio.fv-editor .fv-ed-tabs{height:auto} + .fv-studio.fv-editor .fv-ed-tabs button{height:44px;min-height:44px} + .fv-studio.fv-editor :is(.fv-ed-search,.fv-ed-library-import){height:44px;min-height:44px} + /* A source preview's add and remove keys. */ + .fv-studio.fv-editor :is(.fv-ed-source-add,.fv-ed-source-remove){width:44px;height:44px;min-height:44px} + +} +/* From 1024 px the heads keep their three switches (mute, solo, lock), each 44 × 44, in a 240 px column, so a name like "Audio 2" stays whole. */ +@media (pointer:coarse) and (min-width:1024px){ + .fv-studio.fv-editor .fv-ed-track-view.fv-ed-track-view{--fv-ed-head-width:240px} + .fv-studio.fv-editor .fv-ed-track-view .fv-ed-track-head{grid-template-columns:16px minmax(0,1fr) 132px;padding-right:2px} + .fv-studio.fv-editor .fv-ed-track-view .fv-ed-track-head>:is(.fv-ed-audio-track-controls,.fv-ed-text-track-controls){grid-template-columns:repeat(3,44px)} + .fv-studio.fv-editor .fv-ed-track-view :is(.fv-ed-audio-track-switch,.fv-ed-text-track-controls button){width:44px;min-width:44px;height:44px;min-height:44px} +} +/* Below 1024 px the heads work as on a phone: a 44 px column of track icons (the name is in the head's label); + a press shows that track's switches beside it (44 px keys). */ +@media (pointer:coarse) and (min-width:481px) and (max-width:1023px){ + .fv-studio.fv-editor .fv-ed-track-view.fv-ed-track-view{--fv-ed-head-width:44px} + .fv-studio.fv-editor .fv-ed-track-view .fv-ed-track-head{display:flex;align-items:center;justify-content:center;padding:0;cursor:pointer} + .fv-studio.fv-editor .fv-ed-track-view .fv-ed-track-head>svg{display:block;width:18px;height:18px;color:var(--fv-fg2)} + .fv-studio.fv-editor .fv-ed-track-view .fv-ed-track-head>span:first-of-type{display:none} + .fv-studio.fv-editor .fv-ed-track-view .fv-ed-track-heads>.fv-ed-add-audio{justify-content:center;padding:0} + .fv-studio.fv-editor .fv-ed-track-view .fv-ed-track-heads>.fv-ed-add-audio::before{margin:0} + .fv-studio.fv-editor .fv-ed-track-view .fv-ed-track-heads>.fv-ed-add-audio::after{display:none} + .fv-studio.fv-editor .fv-ed-track-view .fv-ed-track-head>[class$=-track-controls]{display:none} + .fv-studio.fv-editor .fv-ed-track-view .fv-ed-track-head[data-open=true]>[class$=-track-controls]{display:flex;position:absolute;left:calc(100% + 4px);top:50%;transform:translateY(-50%);gap:0;padding:2px;background:var(--fv-card);border:1px solid var(--fv-border);border-radius:var(--fv-r-sm)} + .fv-studio.fv-editor .fv-ed-track-view .fv-ed-track-heads:has(>[data-open=true]){z-index:9} + .fv-studio.fv-editor .fv-ed-track-view :is(.fv-ed-audio-track-switch,.fv-ed-text-track-controls button){width:44px;min-width:44px;height:44px;min-height:44px} +} diff --git a/web/editor_tracks.css b/web/editor_tracks.css index 8d6ec090..f97f9d52 100644 --- a/web/editor_tracks.css +++ b/web/editor_tracks.css @@ -229,6 +229,8 @@ /* The timeline's own surface (glass/editor.css keeps only the outer .fv-ed-tracks surface): heads, the sticky ruler and the area under the rows share the solid timeline tone. */ .fv-studio.fv-editor :is(.fv-ed-track-view,.fv-ed-track-heads,.fv-ed-track-view[data-vertical-overflow=true] .fv-ed-ruler,.fv-ed-track-view[data-vertical-overflow=true] .fv-ed-track-heads::after){background:var(--fv-ed-timeline,var(--fv-bg))} +/* A pseudo-element is not allowed inside :is(), so the ruler corner above the heads gets its own rule. */ +.fv-studio.fv-editor .fv-ed-track-view[data-vertical-overflow=true] .fv-ed-track-heads::after{background:var(--fv-ed-timeline,var(--fv-bg))} /* Time zero sits 8 px in from the heads, so the playhead tab (and a clip's start handle) at the very start is whole, not cut by the edge of the scrolling area under the heads. Every position is measured from this content box. */ .fv-studio.fv-editor .fv-ed-track-content{margin-left:8px} diff --git a/web/editor_tracks.js b/web/editor_tracks.js index fbfc6fbb..00c8974a 100644 --- a/web/editor_tracks.js +++ b/web/editor_tracks.js @@ -273,6 +273,9 @@ export function createTracks(host, {state, sources = {}, t = en => en, actions = target.addEventListener(type, listener, options); listeners.push(() => target.removeEventListener(type, listener, options)); } + // On a wider touch screen the sound and text rows are finger height (48 px); the picture row keeps its size. + const touchRows = typeof matchMedia === 'function' ? matchMedia('(pointer:coarse) and (min-width:1024px)') : null; + const laneHeight = () => touchRows?.matches ? 48 : 40; const locate = id => clips.get(id); const pairIds = id => { const clip = locate(id)?.clip; @@ -641,7 +644,7 @@ export function createTracks(host, {state, sources = {}, t = en => en, actions = row.empty.hidden = track.clips.length > 0; // A picture track with any block description grows a strip for it under the pictures. const noted = !!actions.describedTrack?.(track); row.element.dataset.noted = String(noted); - row.top = top; row.height = track.kind === 'video' ? 64 + (noted ? 22 : 0) : 40; + row.top = top; row.height = track.kind === 'video' ? 64 + (noted ? 22 : 0) : laneHeight(); row.element.style.top = row.head.style.top = `${top}px`; row.element.style.height = row.head.style.height = `${row.height}px`; row.element.setAttribute('aria-label', name); @@ -1292,20 +1295,20 @@ export function createTracks(host, {state, sources = {}, t = en => en, actions = const head = create('div', 'fv-ed-track-head'); head.dataset.track = 'a2'; head.dataset.preview = 'true'; const name = t('Audio 2', '声音 2'); head.title = name; head.append(icon('audio'), create('span', '', name)); row.setAttribute('aria-label', name); - row.style.top = head.style.top = `${top}px`; row.style.height = head.style.height = '40px'; + row.style.top = head.style.top = `${top}px`; row.style.height = head.style.height = `${laneHeight()}px`; const oldName = first.head.title, oldTop = addAudio.style.top, oldHeight = content.style.height; sourcePreview.restore = () => { first.head.title = oldName; first.head.querySelector('span').textContent = oldName; addAudio.style.top = oldTop; setTrackHeight(parseFloat(oldHeight) - 34); }; first.head.title = t('Audio 1', '声音 1'); first.head.querySelector('span').textContent = first.head.title; - addAudio.style.top = `${top + 46}px`; setTrackHeight(top + 40); + addAudio.style.top = `${top + laneHeight() + 6}px`; setTrackHeight(top + laneHeight()); heads.insertBefore(head, addAudio); content.insertBefore(row, overlays); nodes.push(head, row); } for (const {track, clip} of added) { const node = create('div', 'fv-ed-gesture-preview fv-ed-source-placement'); node.dataset.track = track; const row = rows.get(track), top = row?.top ?? rows.get('a1').top + rows.get('a1').height + 6; - node.style.top = `${top}px`; node.style.height = `${row?.height ?? 40}px`; + node.style.top = `${top}px`; node.style.height = `${row?.height ?? laneHeight()}px`; position(node, clip.start, clip.frames); overlays.append(node); nodes.push(node); } return added; @@ -1466,6 +1469,7 @@ export function createTracks(host, {state, sources = {}, t = en => en, actions = else if (event.type === 'zoom') { if (gesture) stopPointer(null, true); layout(); } }); const observer = new ResizeObserver(layout); observer.observe(scroll); + if (touchRows) on(touchRows, 'change', () => { if (!disposed) renderRecord(); }); selectionBox.hidden = previewBox.hidden = guide.hidden = insertion.hidden = true; const audioControls = attachAudioTracks(element, {state, t, actions}); // Track head switches are drawn by the audio and text modules on every change; each gets its name, use and state. From 0a5b3f0c04b1a44bb25c813e4b93aa7f42e111d6 Mon Sep 17 00:00:00 2001 From: Bowen Xue Date: Wed, 18 Nov 2026 04:46:18 +0000 Subject: [PATCH 42/97] Use the full height of tall portrait windows On portrait tablets and rotated monitors wider than a phone, the studio preview now fits the space between the top bar and the prompt bar, and recent works appear as a scrolling grid below it when there is room. The rows are as tall as their cards, and the bottom edge of the grid fades out. Image view picks the 1-4 column grid with the largest tiles, places the open side panel below it and turns the left panel into a floating drawer. Finished Autopilot video and image cards widen to the column. Phone, landscape and desktop layouts are unchanged. --- web/autopilot_glass.css | 9 +++++ web/glass/studio.css | 19 ++++++++++ web/image_view.css | 14 ++++++++ web/image_view.js | 79 ++++++++++++++++++++++++++++++++++++++--- web/studio.js | 31 +++++++++++++--- 5 files changed, 143 insertions(+), 9 deletions(-) diff --git a/web/autopilot_glass.css b/web/autopilot_glass.css index 1d2bd41f..d096e153 100644 --- a/web/autopilot_glass.css +++ b/web/autopilot_glass.css @@ -563,3 +563,12 @@ dialog.fv-studio.fv-autopilot:not([open]){display:none!important} .fv-autopilot .fv-chat-edit-row{min-height:var(--fv-ctl,32px)} /* The play mark on a picture is an icon button: a rounded square on the radius ladder, not a circle. */ .fv-autopilot .fv-chat-play::before{border-radius:var(--fv-r-md)} + +/* A tall window (portrait, wider than a phone): a finished video or picture widens to the column, at most 960 px, + and its picture grows with it; the words keep their 720 px measure and the connection card keeps its size. */ +@media (orientation:portrait) and (min-width:700px){ + .fv-autopilot .fv-chat-scroll{container-type:inline-size} + .fv-autopilot .fv-chat-scroll .fv-chat-job[data-mode=done]:has(.fv-chat-preview){--ap-wide:min(960px,100cqw);width:var(--ap-wide);margin-inline:calc((100% - var(--ap-wide)) / 2)} + .fv-autopilot .fv-chat-job[data-mode=done] .fv-chat-preview{width:calc(var(--ap-wide,720px) * .5)} + .fv-autopilot .fv-chat-job[data-mode=done] .fv-chat-preview[data-shape=tall]{width:calc(var(--ap-wide,720px) * .25)} +} diff --git a/web/glass/studio.css b/web/glass/studio.css index 82032564..dccd93a2 100644 --- a/web/glass/studio.css +++ b/web/glass/studio.css @@ -904,3 +904,22 @@ html body .fv-studio.fv-create .fvs-console :is(.fvs-console-prompt,.fv-section, .fv-studio.fv-create .fvs-console .fv-runrow.fv-at-moved>.fv-key-more{height:calc(2 * var(--fvs-row) + var(--fv-sp-8))} .fv-studio.fv-create .fvs-console .fv-runrow.fv-at-moved>.fv-key-more>summary{border-radius:0 var(--fv-rad-ctl) var(--fv-rad-ctl) 0} } +/* Tall windows (portrait, wider than a phone; studio.js sets data-tall): the picture takes the column less 48 px each + way, the works button's strip left out on the right. When it fills the width with 320 px or more under it + (data-grid), it keeps to the top and the recent works fill that room as a grid of the same cards, behind a 1 px line; + the works button steps aside. */ +.fv-studio.fv-create .fv-body[data-tall=true] .fv-preview-column.fv-preview-column{padding:var(--fv-sp-24) 122px var(--fv-sp-24) 48px;scrollbar-gutter:auto} +.fv-studio.fv-create .fv-body[data-grid=true] .fv-preview-column.fv-preview-column{padding-inline:48px} +.fv-studio.fv-create .fv-body[data-grid=true] .fv-recent.fvs-rail{top:var(--fvs-grid-top,50%);bottom:calc(var(--fvs-dock-h,200px) + var(--fv-sp-16));left:48px;right:48px;width:auto;height:auto;max-height:none; + margin:0;translate:none;padding:var(--fv-sp-16) 0 0;border:0;border-top:1px solid var(--fv-line);border-radius:0;background:none!important;box-shadow:none; + -webkit-backdrop-filter:none!important;backdrop-filter:none!important;transition:none} +.fv-studio.fv-create .fv-body[data-grid=true] .fvs-rail :is(.fv-works-entry,.fv-recent-toggle,.fv-recent-head,.fv-library-message){display:none} +.fv-studio.fv-create .fv-body[data-grid=true] .fvs-rail .fv-recent-list{display:grid;grid-template-columns:repeat(auto-fill,minmax(200px,1fr));grid-auto-rows:max-content;align-content:start;gap:var(--fv-sp-12); + max-height:none;padding:var(--fv-sp-2) var(--fv-sp-2) 32px;overflow-y:auto;scrollbar-width:thin; + -webkit-mask-image:linear-gradient(to bottom,#000 calc(100% - 32px),transparent);mask-image:linear-gradient(to bottom,#000 calc(100% - 32px),transparent)} +/* The fade above keeps the row cut by the bottom edge from ending on a hard line; the last row scrolls clear of it. */ +/* Each row is as tall as its cards: the rail's cards keep min-height 0, which in this fixed-height, scrolling grid would + otherwise squeeze the rows into the visible height and stack the cards on one another. */ +.fv-studio.fv-create .fv-body[data-grid=true] .fvs-rail .fv-recent-card{display:block;min-height:auto;padding:0} +.fv-studio.fv-create .fv-body[data-grid=true] .fvs-rail .fv-recent-card .fv-library-picture{height:auto;aspect-ratio:16/9} +.fv-studio.fv-create .fv-body[data-grid=true] .fvs-rail .fv-recent-card>:is(span:not(.fv-recent-check),small){display:none} diff --git a/web/image_view.css b/web/image_view.css index 8463a2f3..4330ad2d 100644 --- a/web/image_view.css +++ b/web/image_view.css @@ -717,3 +717,17 @@ dialog.fv-studio.fv-image:not([open]){display:none!important} .fvp-pop[data-kind=image-lora] .fv-ie-lora-actions>button:disabled{opacity:.4;cursor:default} .fvp-pop[data-kind=image-lora] .fv-ie-lora-note{margin:0;font-size:var(--fv-fs-1,12px);line-height:18px;color:var(--fv-fg3)} .fvp-pop[data-kind=image-lora] .fv-ie-lora-note:empty{display:none} + +/* ── tall window (portrait, wider than a phone; image_view.js sets data-tall): the works keep to the top in the layout + of one to four columns that gives each picture the most room; the settings float over them as an opaque drawer; + the works panel opens below them and takes the height they leave ── */ +.fv-iv[data-tall=true]{--iv-lw:320px;--iv-rw:320px} +.fv-iv[data-tall=true][data-drawer=left]{--iv-lp:var(--iv-lw)} +.fv-iv[data-tall=true] .fv-iv-panel{z-index:4} +.fv-iv[data-tall=true][data-drawer=left] .fv-iv-left{background:rgb(var(--fv-solid2))!important;-webkit-backdrop-filter:none!important;backdrop-filter:none!important;box-shadow:inset 0 1px 0 var(--fv-edge-hi),var(--fv-sh3)} +.fv-iv[data-tall=true][data-below=true] .fv-iv-stage{bottom:calc(var(--iv-sbar) + var(--iv-below,332px))} +.fv-iv[data-tall=true][data-below=true] .fv-iv-right{top:auto;left:var(--iv-side);right:var(--iv-side);width:auto;height:calc(var(--iv-below,332px) - var(--iv-gut))} +.fv-iv[data-tall=true] .fv-iv-stage[data-state=blank] .fv-iv-frame-box{align-items:flex-start} +.fv-iv[data-tall=true] .fv-iv-stage[data-state=blank] .fv-iv-frame{width:min(calc(100cqw - var(--iv-cover,0px)),calc((100cqh - 88px) * var(--iv-grid-ar,1)));aspect-ratio:var(--iv-grid-ar,1)} +.fv-iv[data-tall=true] .fv-iv-samples{grid-template-columns:repeat(var(--iv-cols,2),minmax(0,1fr));grid-template-rows:repeat(var(--iv-rows,2),minmax(0,1fr))} +.fv-iv[data-tall=true] .fv-iv-compare[data-mode=grid] .fv-iv-compare-panes{grid-template-columns:repeat(var(--iv-cols,2),var(--iv-tw,minmax(0,1fr)));grid-template-rows:repeat(var(--iv-rows,2),var(--iv-th,minmax(0,1fr)));justify-content:center;align-content:start} diff --git a/web/image_view.js b/web/image_view.js index fdb75e31..4bfe6cf9 100644 --- a/web/image_view.js +++ b/web/image_view.js @@ -466,7 +466,7 @@ export function openImageView(node, {studio = null, client: given = null, poll = const copy = button('fv-iv-text-btn', {iconName: 'copy', label: t('Copy prompt', '复制提示词'), name: t('Copy prompt', '复制提示词'), use: t('Copy the words this picture was made from', '复制这张图的提示词')}); copy.addEventListener('click', copyPrompt); const reuse = button('fv-iv-text-btn', {iconName: 'prompt', label: t('Use prompt', '使用提示词'), name: t('Use prompt', '使用提示词'), use: t('Put its prompt back in the box', '把它的提示词填回描述框')}); - reuse.addEventListener('click', () => { prompt.value = text; prompt.dispatchEvent(new Event('input', {bubbles: true})); promptGroup.open(true); if (narrowQuery.matches) setPanel('left', true); }); + reuse.addEventListener('click', () => { prompt.value = text; prompt.dispatchEvent(new Event('input', {bubbles: true})); promptGroup.open(true); if (narrowQuery.matches || tallQuery.matches) setPanel('left', true); }); acts.append(copy, reuse); parts.push(acts); } if (!shownFile) { const e = el('div', 'fv-iv-empty fv-iv-empty-small'); e.append(icon('info'), el('span', '', t('Pick a picture to see its facts', '选一张图片查看信息'))); parts.splice(0, parts.length, e); } @@ -616,8 +616,20 @@ export function openImageView(node, {studio = null, client: given = null, poll = // Under 1280 wide both panels rest as rails and open as drawers over the stage, one at a time, so the picture // keeps the room; the stage still measures from the two rails, so it stays centred. Wide, they dock and fold. const narrowQuery = matchMedia('(min-width: 720px) and (max-width: 1279px)'); - let drawer = ''; + // A tall window (portrait, wider than a phone): the settings open as a drawer over the works, and the works panel + // opens below them, taking the height they leave (at least 320 px), so it never narrows them from the side. + const tallQuery = matchMedia('(orientation: portrait) and (min-width: 720px)'); + let drawer = '', below = false; function paintPanels() { + if (tallQuery.matches) { + if (drawer === 'right') drawer = ''; + left.dataset.collapsed = String(drawer !== 'left'); column.dataset.collapsed = String(!below); + body.dataset.tall = 'true'; body.dataset.below = String(below); body.dataset.narrow = 'true'; body.dataset.drawer = drawer; + body.dataset.left = 'rail'; body.dataset.right = 'rail'; + paintCover(); fitTallSoon(); + return; + } + delete body.dataset.tall; delete body.dataset.below; const narrow = narrowQuery.matches; const leftShown = narrow ? drawer === 'left' : panels.left !== false, rightShown = narrow ? drawer === 'right' : panels.right !== false; left.dataset.collapsed = String(!leftShown); column.dataset.collapsed = String(!rightShown); @@ -629,20 +641,76 @@ export function openImageView(node, {studio = null, client: given = null, poll = // windows) covers its left part, so the frame centres in the rest. function paintCover() { let cover = 0; - if (stage.dataset.state === 'draft' && body.dataset.drawer === 'left' && !matchMedia('(max-width: 719px)').matches) { + if (stage.dataset.state === 'draft' && body.dataset.drawer === 'left' && !tallQuery.matches && !matchMedia('(max-width: 719px)').matches) { const l = left.getBoundingClientRect(), c = canvasArea.getBoundingClientRect(); cover = Math.max(0, Math.round(l.right + 12 - c.left)); } shot.style.setProperty('--iv-cover', `${cover}px`); } function setPanel(side, open) { - if (narrowQuery.matches) drawer = open ? side : drawer === side ? '' : drawer; + if (tallQuery.matches && side === 'right') below = open; + else if (tallQuery.matches || narrowQuery.matches) drawer = open ? side : drawer === side ? '' : drawer; else { panels[side] = open; writeStore(PANEL_KEY, panels); } paintPanels(); if (open && side === 'left') fitSoon(); } narrowQuery.addEventListener('change', () => { drawer = ''; paintPanels(); fitSoon(); }); - // A drawer closes when the stage is touched. + tallQuery.addEventListener('change', () => { drawer = ''; below = false; paintPanels(); fitSoon(); }); + // A drawer closes when the stage is touched; on a tall window, when anything outside it is. stage.addEventListener('pointerdown', () => { if (drawer) { drawer = ''; paintPanels(); } }); + body.addEventListener('pointerdown', event => { if (tallQuery.matches && drawer === 'left' && !left.contains(event.target)) { drawer = ''; paintPanels(); } }); + // The works grid on a tall window (the four samples, or three or four works compared): of one to four columns, the + // layout that gives each picture the most room in the width and height there are; it keeps to the top. With the + // works panel open below, the panel takes the height the grid leaves. + const TALL_PANEL = 320; + let tallFrame = 0; + function fitTallSoon() { cancelAnimationFrame(tallFrame); tallFrame = requestAnimationFrame(() => { tallFrame = 0; fitTall(); }); } + function bestGrid(n, ratio, width, height, gap) { + let best = null; + for (let cols = 1; cols <= Math.min(4, n); cols++) { + const rows = Math.ceil(n / cols); + const w = Math.min((width - (cols - 1) * gap) / cols, ((height - (rows - 1) * gap) / rows) * ratio); + if (w > 0 && (!best || w > best.w + 0.5)) best = {cols, rows, w: Math.floor(w), h: Math.floor(w / ratio)}; + } + return best && {...best, height: best.rows * best.h + (best.rows - 1) * gap, width: best.cols * best.w + (best.cols - 1) * gap}; + } + function fitTall() { + if (!alive) return; + const panes = comparer.element.querySelector('.fv-iv-compare-panes'); + if (!tallQuery.matches) { + for (const target of [shot, panes]) for (const name of ['--iv-cols', '--iv-rows', '--iv-tw', '--iv-th', '--iv-grid-ar']) target?.style.removeProperty(name); + body.style.removeProperty('--iv-below'); + return; + } + const now = parseFloat(body.style.getPropertyValue('--iv-below')) || TALL_PANEL + 12; + let used = 0, spare = 0; + if (stage.dataset.mode === 'compare' && comparer.element.dataset.mode === 'grid' && panes) { + const files = compare?.files || [], ratios = files.map(file => { const m = meta.get(file); return m?.width ? m.width / m.height : 0; }).filter(r => r > 0); + const ratio = ratios.length ? ratios.reduce((a, b) => a + b, 0) / ratios.length : 1; + const extra = below ? now - (TALL_PANEL + 12) : 0, height = panes.clientHeight + extra; + const g = bestGrid(files.length, ratio, panes.clientWidth, height, 12); + if (g) { + for (const [name, value] of [['--iv-cols', g.cols], ['--iv-rows', g.rows], ['--iv-tw', `${g.w}px`], ['--iv-th', `${g.h}px`]]) panes.style.setProperty(name, String(value)); + used = 1; spare = height - g.height; + } + } else if (stage.dataset.state === 'blank') { + const pictures = [...grid.querySelectorAll('img')], first = pictures.find(i => i.naturalWidth); + const ratio = first ? first.naturalWidth / first.naturalHeight : 1; + const extra = below ? now - (TALL_PANEL + 12) : 0, height = canvasArea.clientHeight - 88 + extra; + const g = bestGrid(pictures.length, ratio, canvasArea.clientWidth, height, 12); + if (g) { + for (const [name, value] of [['--iv-cols', g.cols], ['--iv-rows', g.rows]]) shot.style.setProperty(name, String(value)); + shot.style.setProperty('--iv-grid-ar', String(g.width / g.height)); + used = 1; spare = height - g.height; + } + } + const want = below ? Math.round(TALL_PANEL + 12 + (used ? Math.max(0, spare) : 0)) : 0; + if (want) { if (Math.abs(want - now) > 1 || !body.style.getPropertyValue('--iv-below')) body.style.setProperty('--iv-below', `${want}px`); } + else body.style.removeProperty('--iv-below'); + } + const tallWatch = typeof ResizeObserver === 'function' ? new ResizeObserver(() => { if (tallQuery.matches) fitTallSoon(); }) : null; + tallWatch?.observe(body); + for (const image of grid.querySelectorAll('img')) image.addEventListener('load', () => { if (tallQuery.matches) fitTallSoon(); }); + comparer.element.addEventListener('load', () => { if (tallQuery.matches) fitTallSoon(); }, true); leftCollapse.addEventListener('click', () => setPanel('left', false)); railOpen.addEventListener('click', () => setPanel('left', true)); rightRailOpen.addEventListener('click', () => setPanel('right', true)); @@ -1148,6 +1216,7 @@ export function openImageView(node, {studio = null, client: given = null, poll = } comparer.paint(compare); stage.dataset.mode = compare ? 'compare' : 'single'; + if (tallQuery.matches) fitTallSoon(); if (rightTab === 'info' && infoPop.dataset.file !== shownFile) { infoPop.dataset.file = shownFile; paintInfo(); } tabWorksN.textContent = ''; } diff --git a/web/studio.js b/web/studio.js index 55b35199..eefbc9ef 100644 --- a/web/studio.js +++ b/web/studio.js @@ -1618,15 +1618,34 @@ export function openStudio(node, {extendFrom = null} = {}) { // A notice that wraps to more lines than the slot holds widens the slot while it shows (8 px clear on each side). const toastSlot = () => Math.max(TOAST_SLOT, toastHeight() + 16); const statusRoom = () => Math.max(STATUS_LINE, output.querySelector(':scope > .fv-status')?.offsetHeight || 0); + // A tall window (portrait, wider than a phone) gives the picture the column less 48 px each way (the works button's + // strip left out); when the picture fills the width and 320 px or more is left under it, the recent works take that + // room as a grid (glass/studio.css) and the picture keeps to the top. + const tall = window.matchMedia?.('(orientation: portrait) and (min-width: 761px)'); + const TALL_EDGE = 48, TALL_RAIL = 122, GRID_MIN = 320; + let recentCount = () => 0; + const tallChange = () => fitPreview(); + tall?.addEventListener?.('change', tallChange); cleanup.push(() => tall?.removeEventListener?.('change', tallChange)); + function fitTall(gap) { + const playerShown = getComputedStyle(playerRow).display !== 'none'; + const room = output.clientHeight - 2 * (TALL_EDGE / 2) - 40 - gap - (playerShown ? playerRoom() + gap : 0); + const gridWidth = output.clientWidth - 2 * TALL_EDGE, gridHeight = gridWidth / previewRatio; + const grid = recentCount() > 0 && gridHeight <= room && room - gridHeight >= GRID_MIN; + body.dataset.grid = String(grid); + return {room, width: grid ? gridWidth : output.clientWidth - TALL_EDGE - TALL_RAIL, grid, barRoom: 40 + gap + (playerShown ? playerRoom() + gap : 0)}; + } function fitPreview() { + const isTall = !phone?.matches && !!tall?.matches; + if (isTall) body.dataset.tall = 'true'; else { delete body.dataset.tall; delete body.dataset.grid; } const style = getComputedStyle(output), gap = parseFloat(style.rowGap) || 0; - const width = output.clientWidth - parseFloat(style.paddingLeft) - parseFloat(style.paddingRight); + const fit = isTall && Number.isFinite(previewRatio) && previewRatio > 0 ? fitTall(gap) : null; + const width = fit ? fit.width : output.clientWidth - parseFloat(style.paddingLeft) - parseFloat(style.paddingRight); // On a phone a 56 px slot stays free above the console for the shared toast strip, so a toast never covers the // result's bar and its actions; the status line keeps its own row there. Wider windows show only the picture and // its bar here (the status line reads in the notes line at the top of the dock). // The play bar's row is left out while there is no video to play (glass/studio.css), and its room with it. const playerShown = getComputedStyle(playerRow).display !== 'none'; - const room = output.clientHeight - parseFloat(style.paddingTop) - parseFloat(style.paddingBottom) + const room = fit ? fit.room : output.clientHeight - parseFloat(style.paddingTop) - parseFloat(style.paddingBottom) - (phone?.matches ? 88 + toastSlot() + statusRoom() + 2 * gap : 40 + gap) - (playerShown ? playerRoom() + gap : 0); if (!(width > 0) || !(room > 0) || !Number.isFinite(previewRatio) || previewRatio <= 0) return; const height = Math.max(Math.min(room, 160), Math.min(room, width / previewRatio)); @@ -1638,7 +1657,7 @@ export function openStudio(node, {extendFrom = null} = {}) { output.style.setProperty('--fvs-stage-w', `${Math.round(fittedWidth)}px`); // On a phone the picture block sits just above the console (no empty band between them); wider windows centre it. const free = Math.max(0, Math.floor(room - fittedHeight)); - const marginTop = phone?.matches ? free : Math.floor(free / 2); + const marginTop = fit?.grid ? 0 : phone?.matches ? free : Math.floor(free / 2); previewSpace.style.marginTop = `${marginTop}px`; // The next generation's empty frame stays whole while a tray floats over the picture's lower part: it is fitted // and centred in the part left free, and takes the full stage again when the tray closes (200 ms). @@ -1660,6 +1679,8 @@ export function openStudio(node, {extendFrom = null} = {}) { const pictureTop = output.getBoundingClientRect().top - body.getBoundingClientRect().top + parseFloat(style.paddingTop) + marginTop; body.style.setProperty('--fvs-stage-top', `${Math.round(pictureTop)}px`); body.style.setProperty('--fvs-stage-h', `${Math.round(fittedHeight)}px`); + if (fit?.grid) body.style.setProperty('--fvs-grid-top', `${Math.round(pictureTop + fittedHeight + fit.barRoom + 16)}px`); + else body.style.removeProperty('--fvs-grid-top'); // The console and the picture are either the same width or clearly apart (at least 24 px a side), never a // few pixels off. if (!phone?.matches) { @@ -1803,13 +1824,15 @@ export function openStudio(node, {extendFrom = null} = {}) { compareButton.setAttribute('aria-label', t('Compare', '对比')); tip(compareButton, t('Compare', '对比'), t('Side by side or with a divider, with another video', '和另一条视频并排或滑动对比')); // No Compare button on the bar: two videos picked together in the rail compare on the stage (F9 still opens it). + let shownCount = 0; const recent = createRecentVideos(t, {body, rail: true, named: row => savedPrompt(api, row), onSelect: row => { if (compare.active) compare.close(); showResult(row, {chosen: true}); }, onPick: rows => { if (rows.length === 2) { if (compare.active) compare.close(); compare.open(rows[0], rows[1]); } else { if (compare.active) compare.close(); if (rows[0]) showResult(rows[0], {chosen: true}); } }, - onChange: () => syncHistory()}); + onChange: () => { syncHistory(); const count = recent.rows().length; if (count !== shownCount) { shownCount = count; fitPreview(); } }}); + recentCount = () => recent.rows().length; recent.element.classList.add('sgf-avoid'); recent.element.prepend(worksButton); body.append(recent.element); // Phones have no rail; Creations is the top bar's works entry, there at every width. From b02a4e38398a29b9f11f5c9de1bb529860ce79a3 Mon Sep 17 00:00:00 2001 From: Bowen Xue Date: Wed, 18 Nov 2026 04:48:18 +0000 Subject: [PATCH 43/97] New character, Upload images: each of the four views takes a picture of your own (choose or... New character, Upload images: each of the four views takes a picture of your own (choose or drop), Generate makes only the views still empty, and with all four in there is nothing to generate The Upload images tab of a new character made the four views from one picture only. Now the face close-up, front, side and back cells each accept a picture of your own; a picture put in stays through Generate, Generate all again and Stop, and Replace / Remove sit on the cell. Generate then makes the views still empty from the source picture, or from your own front (or face close-up) when there is none; your own face or front is what the other views are made from. With all four in the card saves at once and nothing is generated. Your pictures are saved once, on the card, like any picture added by hand; they go up to the image engine only when a generation needs them as references and are let go with the other uploads when the dialog is left. --- web/cast_generate.js | 30 +++++++++---- web/cast_library.js | 4 +- web/cast_photo.css | 5 +++ web/cast_photo.js | 101 ++++++++++++++++++++++++++++++++++--------- 4 files changed, 109 insertions(+), 31 deletions(-) diff --git a/web/cast_generate.js b/web/cast_generate.js index b237150a..f6277e33 100644 --- a/web/cast_generate.js +++ b/web/cast_generate.js @@ -192,13 +192,16 @@ export function createCastGenerator({client, kind = 'character', views = null, f const setPicture = (index, patch) => emit({pictures: state.pictures.map((row, i) => i === index ? {...row, ...patch} : row)}); const cancelJob = id => Promise.resolve().then(() => client.cancel(id)).catch(() => {}); const done = () => state.pictures.every(row => row.file); + // The set starts again: what was made goes, the pictures the user put in stay (own rows). + const kept = () => state.pictures.map(row => row.own ? row : {view: row.view, file: '', fraction: 0}); // over: the dress pass of a close-up ({file: the close-up, mask: the uploaded mask, again: the second try}). async function runOne(index, alive, over = null) { - const view = plan[index], front = state.pictures[0].original ? state.photo : state.pictures[0].file; + const view = plan[index], front = state.pictures[0].original && !state.pictures[0].own ? state.photo : state.pictures[0].file; const dress = view.outfit && state.outfit ? [state.outfit] : []; // From a photo: each view names the pictures it sees (the photo, the face close-up, the front, the clothes). - const picked = name => { const at = names.indexOf(name), row = at >= 0 ? state.pictures[at] : null; return row?.original ? state.photo : row?.file || ''; }; + // A picture the user put in is an upload of its own (row.file), not the photo. + const picked = name => { const at = names.indexOf(name), row = at >= 0 ? state.pictures[at] : null; return row?.original && !row.own ? state.photo : row?.file || ''; }; // The face close-up sees the face cut out of the photo where the page made one (a small face), else the photo. const roles = {photo: () => (view.view === 'face' && closeUp) || state.photo, face: () => overrides.face || picked('face'), front: () => overrides.front || picked('front'), outfit: () => state.outfit}; const images = over ? [over.file, ...(view.dress.outfit && state.outfit ? [state.outfit] : [])] @@ -326,7 +329,7 @@ export function createCastGenerator({client, kind = 'character', views = null, f closeUp = photo ? face : ''; // Another source, picture or clothes: the set starts again and the pictures made before go. const asked = source ? JSON.stringify([source, photo, wear, outfitImage]) : ''; - if (source && asked !== inputs) { inputs = asked; plan = null; dropClothes(); given = outfitImage; emit({photo, outfit: outfitImage}); outfit = wear; for (const row of state.pictures) if (row.file && !row.original) onDiscard(row.file); emit({pictures: fresh(), description: ''}); } + if (source && asked !== inputs) { inputs = asked; plan = null; dropClothes(); given = outfitImage; emit({photo, outfit: outfitImage}); outfit = wear; for (const row of state.pictures) if (row.file && !row.original) onDiscard(row.file); emit({pictures: kept(), description: ''}); } // After a failure the same description goes on from the picture that failed. const resume = !!state.error && description === state.description && plan && !done() && JSON.stringify(selectedLoras) === JSON.stringify(loras); @@ -338,7 +341,7 @@ export function createCastGenerator({client, kind = 'character', views = null, f for (const row of state.pictures) if (row.file && !row.original) onDiscard(row.file); } emit({running: true, error: '', report_id: null, waiting: '', description, - ...(resume ? {} : {pictures: fresh(), current: 0})}); + ...(resume ? {} : {pictures: kept(), current: 0})}); try { if (!plan) { plan = await client.castViews(description, kind); @@ -389,18 +392,18 @@ export function createCastGenerator({client, kind = 'character', views = null, f const id = job; job = null; ++epoch; unschedule(timer); timer = null; plan = null; clothes = null; // A stopped run is dropped whole: the next Generate starts again from the description. - emit({running: false, current: -1, waiting: '', error: '', report_id: null, pictures: fresh()}); + emit({running: false, current: -1, waiting: '', error: '', report_id: null, pictures: kept()}); return id ? cancelJob(id) : Promise.resolve(); } // The description changed: pictures made from the old one no longer belong to it. function reset() { if (state.running || !(state.pictures.some(row => row.file) || state.error)) return; plan = null; - emit({pictures: fresh(), error: '', report_id: null, current: -1}); + emit({pictures: kept(), error: '', report_id: null, current: -1}); } // One view again with a new seed; the other views stay. The replaced picture is discarded when the new one is in. async function redo(index) { - if (state.running || disposed || !plan || !state.pictures[index]) return; + if (state.running || disposed || !plan || !state.pictures[index] || state.pictures[index].own) return; const current = ++epoch, alive = () => current === epoch && !disposed; const before = state.pictures[index]; seeds[index] = randomSeed(); @@ -422,14 +425,23 @@ export function createCastGenerator({client, kind = 'character', views = null, f emit({running: false, current: -1, waiting: '', ...failureOf(error)}); } } + // A picture the user put in for one view (file: its upload name, or a stand-in until it is uploaded; '' takes it out). + // Generate then makes only the views that are still empty. A made picture it replaces is discarded. + function setOwn(index, file) { + const before = state.pictures[index]; + if (state.running || disposed || !before) return; + if (file) setPicture(index, {file, fraction: 1, original: true, own: true}); + else if (before.own) setPicture(index, {file: '', fraction: 0, original: false, own: false}); + if (file && before.file && !before.original) onDiscard(before.file); + } // The photo itself as the front (it was uploaded for the reference); the generated front is discarded. function useOriginal(file) { if (state.running || disposed) return; const before = state.pictures[0]; - setPicture(0, {file, fraction: 1, original: true}); + setPicture(0, {file, fraction: 1, original: true, own: false}); if (before.file && !before.original) onDiscard(before.file); } - return {start, stop, reset, redo, useOriginal, state: () => state, done, + return {start, stop, reset, redo, useOriginal, setOwn, state: () => state, done, setOverride(role, name) { if (name) overrides[role] = name; else delete overrides[role]; }, dispose() { disposed = true; return stop(); }}; } diff --git a/web/cast_library.js b/web/cast_library.js index 350f12dc..0d52d5b3 100644 --- a/web/cast_library.js +++ b/web/cast_library.js @@ -164,7 +164,7 @@ export function createCastLibrary({api, text, viewURL, uploadOne, onChange = () tipOf(remove, remove.textContent, word(text('Delete this character from the library', '从角色库删除这个角色'), text('Delete this scene from the library', '从角色库删除这个场景'), text('Delete this prop from the library', '从角色库删除这个道具'))); tipOf(cancel, text('Cancel', '取消'), text('Close without saving', '不保存,关闭')); tipOf(save, text('Save', '保存'), text('Keep it in the library to reuse with @', '存进角色库,之后用 @ 引用')); - tipOf(uploadTab, text('Upload images', '上传图片'), views4 && !id ? text('Make the four views from one picture, in its style', '用一张图片按原图风格生成脸部特写、正面、侧面和背面') + tipOf(uploadTab, text('Upload images', '上传图片'), views4 && !id ? text('Add your own views. Empty views are made from one picture in its style.', '放入各视角图片,空着的视角按原图风格生成。') : text('Use pictures from this computer', '用电脑上的图片')); tipOf(aiTab, text('Generate with AI', 'AI 生成'), views4 ? text('Make the face close-up, front, side and back from a description', '按描述生成脸部特写、正面、侧面和背面') : text('Make the pictures from a description', '按描述生成图片')); @@ -180,7 +180,7 @@ export function createCastLibrary({api, text, viewURL, uploadOne, onChange = () }; const aiBusy = () => aiState.busy || !!generator?.isBusy() || Object.keys(makers).some(key => makerStates[key]?.busy || makers[key]?.isBusy()); const makerMissing = {photo: text('Generate the views from the photo first', '先用照片生成各视角'), - image: text('Generate the views from the picture first', '先用图片生成各视角'), ai: text('Generate the images first', '先生成角色图片')}; + image: text('Generate the other views first, or add all four', '先生成其余视角,或放入全部四张图片'), ai: text('Generate the images first', '先生成角色图片')}; // What is still missing before Save works ('' when nothing is); the button says so on hover and when pressed. let missing = ''; const missingNow = () => !name.value.trim() ? text('Enter a name first', '先填写名字') diff --git a/web/cast_photo.css b/web/cast_photo.css index c5c6e717..27490c37 100644 --- a/web/cast_photo.css +++ b/web/cast_photo.css @@ -103,3 +103,8 @@ @container (max-width:520px){ .fv-cp .fv-cg-view>.fv-cp-edited{width:8px;height:8px;padding:0;overflow:hidden;border-radius:50%;background:var(--fv-accent-fill,#1a7fe5);color:transparent;line-height:8px} } + +/* "Upload images": a view can be a picture of the user's own. An empty cell takes a click or a drop; a picture of the user's own has the accent border; with all four in, Generate is not shown. */ +.fv-cp[data-mode=image] .fv-cg-view[data-state=empty]{cursor:pointer} +.fv-cp .fv-cg-view[data-own=true]{border-color:var(--fv-accent-line,#6db8fa)} +.fv-cp-action.fv-cp-none{display:none} diff --git a/web/cast_photo.js b/web/cast_photo.js index ea8f7290..0f91bd82 100644 --- a/web/cast_photo.js +++ b/web/cast_photo.js @@ -74,6 +74,8 @@ export function mountCastPhoto({container, api, text, viewURL, onState = () => { const fetcher = fetchApi || (api ? api.fetchApi.bind(api) : globalThis.fetch.bind(globalThis)); client = client || createImageGenClient(fetcher); const ai = source === 'ai', make = MAKE[source] || MAKE.photo, base = make[0], words = wordsOf(source, tr); + // "Upload images": every view can be a picture of the user's own; Generate then makes only the views still empty. + const canOwn = source === 'image'; // Deletes go out with keepalive, so the ones sent as the tab closes still reach the engine. const keeper = createImageGenClient((url, options = {}) => fetcher(url, options.method === 'POST' ? {...options, keepalive: true} : options)); for (const name of ['./cast_generate.css', './cast_photo.css']) { @@ -195,7 +197,13 @@ export function mountCastPhoto({container, api, text, viewURL, onState = () => { // The views, in the order of the sheet; the face cell is wider. A finished view opens in the image editor on click; // on hover it offers Draw again (and Use the photo on the face), and Restore after an edit. const grid = el('div', 'fv-cg-views'); - const edits = {}; + // edits: view → the view as edited in the image editor. own: view → a picture the user put in for it + // ({file, url, ref}: ref is its upload to the engine, made only when a generation needs it). + const edits = {}, own = {}; + const ownInput = el('input'); ownInput.type = 'file'; ownInput.accept = 'image/*'; ownInput.hidden = true; + let ownFor = ''; + ownInput.onchange = () => { takeOwn(ownFor, ownInput.files); ownInput.value = ''; }; + const choosing = view => { if (generator.state().running) return; ownFor = view; ownInput.click(); }; const cells = Object.fromEntries(SHOW.map(view => { const cell = el('div', 'fv-cg-view'); cell.dataset.view = view; cell.tabIndex = 0; cell.setAttribute('role', 'button'); const title = tr(...VIEW_TITLES[view]); @@ -210,19 +218,53 @@ export function mountCastPhoto({container, api, text, viewURL, onState = () => { if (!photoSlot.get()) return; dropEdit('face'); generator.useOriginal(ORIGINAL); faceChanged = true; render(); }) : null; const restore = tool(tr('Restore', '恢复原图'), tr('Put the picture back as it was made', '换回生成时的样子'), () => { dropEdit(view); if (leads(view)) faceChanged = true; render(); }); + const mine = canOwn ? tool(tr('Add picture', '添加图片'), tr('Use a picture of your own for this view', '这个视角用自己的图片'), () => choosing(view)) : null; + const clear = canOwn ? tool(tr('Remove', '移除'), tr('Remove this picture. Generate makes this view.', '移除这张图片,生成时补上这个视角。'), () => dropOwn(view)) : null; cell.append(image, label, edited, percent, meter, tools); grid.append(cell); - tip(cell, title, tr('Click to edit it in the image editor', '点击在图像编辑器中修改')); - const open = () => { if (cell.dataset.state === 'done' && !generator.state().running) void editView(view); }; + tip(cell, title, canOwn ? tr('Click or drop a picture', '点击或拖入图片') : tr('Click to edit it in the image editor', '点击在图像编辑器中修改')); + const open = () => { if (generator.state().running) return; if (cell.dataset.state === 'done') void editView(view); else if (canOwn && cell.dataset.state === 'empty') choosing(view); }; + if (canOwn) { + cell.addEventListener('dragover', event => { event.preventDefault(); }); + cell.addEventListener('drop', event => { event.preventDefault(); event.stopPropagation(); if (!generator.state().running) takeOwn(view, event.dataTransfer.files); }); + } cell.addEventListener('click', open); cell.addEventListener('keydown', event => { if ((event.key === 'Enter' || event.key === ' ') && event.target === cell) { event.preventDefault(); open(); } }); - return [view, {cell, image, percent, fill, title, edited, again, usePhoto, restore}]; + return [view, {cell, image, percent, fill, title, edited, again, usePhoto, restore, mine, clear}]; })); // A change to these views is one the others can be redrawn from: the face and the front from a picture; the front // from a description. const leads = view => ai ? view === 'front' : view === 'face' || view === 'front'; - const sourceOf = view => { const r = pictureOf(view) || {}; return r.file ? (r.original ? photoSlot?.get()?.url || '' : viewURL(r.file)) : ''; }; + const sourceOf = view => { if (own[view]) return own[view].url; const r = pictureOf(view) || {}; return r.file ? (r.original ? photoSlot?.get()?.url || '' : viewURL(r.file)) : ''; }; const dropEdit = view => { const e = edits[view]; if (!e) return; URL.revokeObjectURL(e.url); delete edits[view]; generator.setOverride(view, ''); }; + // A picture the user puts in for a view (choose or drop): it stands in the view; the others are made around it. + function takeOwn(view, files) { + const file = Array.from(files || []).find(f => /^image\//.test(f.type)); + if (!view || !file || generator.state().running) return; + dropEdit(view); releaseOwn(view); + own[view] = {file, url: URL.createObjectURL(file), ref: ''}; + generator.setOwn(make.indexOf(view), `own:${view}`); + // The views made before were made around the old one of these. + if (leads(view) && generator.state().pictures.some((row, at) => at !== make.indexOf(view) && row.file && !row.own)) faceChanged = true; + attention = ''; render(); + } + function releaseOwn(view) { const o = own[view]; if (!o) return; URL.revokeObjectURL(o.url); delete own[view]; } + function dropOwn(view) { + if (!own[view] || generator.state().running) return; + dropEdit(view); releaseOwn(view); generator.setOwn(make.indexOf(view), ''); render(); + } + // Before a generation uses them as references, the pictures the user put in are uploaded to the engine (once each, + // and let go with the other uploads when the dialog is left); a set made only of them never is. + async function ensureOwn() { + for (const view of SHOW) { + const o = own[view]; if (!o || o.ref) continue; + const ref = await referenceOf({file: o.file}); + if (disposed || own[view] !== o) continue; + o.ref = ref; generator.setOwn(make.indexOf(view), ref); + } + } async function redraw(view) { + if (own[view]) return; + try { await ensureOwn(); } catch (error) { attention = error.message || tr('Could not read this picture. Please choose another one.', '无法读取这张图片,请换一张。'); render(); return; } dropEdit(view); await generator.redo(make.indexOf(view)); if (view === base && generator.state().pictures[0].file) { faceChanged = true; render(); } @@ -245,7 +287,7 @@ export function mountCastPhoto({container, api, text, viewURL, onState = () => { if (leads(view)) faceChanged = true; render(); } - body.append(side, grid); root.append(body); container.append(root); + body.append(side, grid); root.append(body, ownInput); container.append(root); // The main action lives in the dialog's own button row (the host places it): Generate, Stop, then Generate all again. const action = el('button', 'fv-cp-action'); action.type = 'button'; @@ -299,10 +341,14 @@ export function mountCastPhoto({container, api, text, viewURL, onState = () => { } // Shown or hidden by the dialog (only on this tab); missing image models hide it from here. action.dataset.missing = String(!!isMissing); - action.textContent = running ? tr('Stop', '停止') : finished ? tr('Generate all again', '重新生成全部') : tr('Generate', '生成'); + // Pictures of the user's own stay; Generate makes the other views, and with all four in there is nothing to make. + const ownCount = SHOW.filter(view => own[view]).length; + action.textContent = running ? tr('Stop', '停止') : finished ? (ownCount ? tr('Generate the rest again', '重新生成其余视角') : tr('Generate all again', '重新生成全部')) + : ownCount ? tr('Generate the rest', '生成其余视角') : tr('Generate', '生成'); + action.classList.toggle('fv-cp-none', ownCount === SHOW.length); action.dataset.primary = String(!running && !finished); const why = ai ? (!describe.value.trim() ? tr('Describe the character first', '先描述角色') : mode === 'image' && !outfitSlot.get() ? tr('Add a clothes picture first', '先添加服装图') : '') - : !photoSlot.get() ? words.first : mode === 'image' && !outfitSlot.get() ? tr('Add a clothes picture first', '先添加服装图') + : !photoSlot.get() && !own.front && !own.face ? (ownCount ? tr('Add a source picture, or put in the front or face close-up.', '请添加来源图,或放入正面或脸部特写。') : words.first) : mode === 'image' && !outfitSlot.get() ? tr('Add a clothes picture first', '先添加服装图') : mode === 'text' && !field.value.trim() ? tr('Describe the clothes first', '先描述服装') : ''; if (why && !running) { action.setAttribute('aria-disabled', 'true'); action.dataset.fvTipWhy = why; } else { action.removeAttribute('aria-disabled'); delete action.dataset.fvTipWhy; } tip(action, action.textContent, running ? tr('Stop making the views', '停止生成') : words.use); @@ -310,13 +356,19 @@ export function mountCastPhoto({container, api, text, viewURL, onState = () => { const c = cells[view], r = pictureOf(view) || {}, index = make.indexOf(view), active = running && index === state.current && !r.file; const src = r.file ? edits[view]?.url || sourceOf(view) : ''; if (c.image.getAttribute('src') !== src) src ? c.image.src = src : c.image.removeAttribute('src'); - c.cell.dataset.state = r.file ? 'done' : active ? 'running' : 'empty'; c.cell.dataset.original = String(!!r.original); + c.cell.dataset.state = r.file ? 'done' : active ? 'running' : 'empty'; c.cell.dataset.original = String(!!r.original && !own[view]); c.cell.dataset.own = String(!!own[view]); c.cell.setAttribute('aria-label', c.title + (active ? ' ' + Math.floor(r.fraction * 100) + '%' : '')); c.percent.textContent = active && !state.waiting ? Math.floor(r.fraction * 100) + '%' : ''; c.fill.style.width = (active ? r.fraction * 100 : 0) + '%'; - c.edited.hidden = !edits[view]; c.restore.hidden = !edits[view]; c.again.hidden = !r.file && !(state.error && !running); + c.edited.hidden = !edits[view]; c.restore.hidden = !edits[view]; c.again.hidden = !!own[view] || (!r.file && !(state.error && !running)); c.again.disabled = running || (index > 0 && !state.pictures[0].file); if (c.usePhoto) c.usePhoto.hidden = !photoSlot.get() || !!r.original || running; + if (c.mine) { + tip(c.cell, c.title, r.file ? tr('Click to edit it in the image editor, or drop a picture to replace it', '点击在图像编辑器中修改,或拖入图片替换') : tr('Click or drop a picture', '点击或拖入图片')); + const name = r.file ? tr('Replace', '更换') : tr('Add picture', '添加图片'); + if (c.mine.textContent !== name) { c.mine.textContent = name; tip(c.mine, name, r.file ? tr('Use another picture of your own for this view', '这个视角换成自己的另一张图片') : tr('Use a picture of your own for this view', '这个视角用自己的图片')); } + c.mine.hidden = running; c.clear.hidden = running || !own[view]; + } } if (state.error) { const key = `${state.error}:${state.report_id || ''}`; @@ -327,7 +379,7 @@ export function mountCastPhoto({container, api, text, viewURL, onState = () => { : running && state.waiting ? tr('Added to the queue. It starts when the previous one finishes.', '已加入队列,前面的完成后自动开始。') : attention; } note.hidden = !note.textContent && !note.firstChild; note.dataset.failed = String(!!state.error); - rest.hidden = !faceChanged || running || !state.pictures.slice(1).some(row => row.file); rest.disabled = running; + rest.hidden = !faceChanged || running || !state.pictures.slice(1).some(row => row.file && !row.own); rest.disabled = running; const count = state.pictures.filter(r => r.file).length, fraction = running && state.current >= 0 ? state.pictures[state.current]?.fraction || 0 : 0; const progress = generator.done() ? 1 : (count + fraction) / make.length; const summary = JSON.stringify([running, finished, Math.round(progress * 100)]); @@ -340,9 +392,9 @@ export function mountCastPhoto({container, api, text, viewURL, onState = () => { // A small face in the photo: the close-up is made from it cut out and enlarged (cast_face_crop.js), uploaded once per // photo; '' keeps the whole photo. let closeUp = {photo: '', name: ''}; - async function closeUpOf(photo) { + async function closeUpOf(photo, file) { if (closeUp.photo !== photo) { - const made = await faceCloseUp({client, fetcher, name: photo, file: photoSlot.get().file}); + const made = await faceCloseUp({client, fetcher, name: photo, file}); closeUp = {photo, name: made && !disposed ? await referenceOf(made).catch(() => '') : ''}; } return closeUp.name; @@ -350,17 +402,25 @@ export function mountCastPhoto({container, api, text, viewURL, onState = () => { async function begin() { if (action.getAttribute('aria-disabled') === 'true') { attention = action.dataset.fvTipWhy || ''; render(); return; } attention = ''; render(); + let sourceRef = ''; try { - if (!ai) { if (!photoRef) photoRef = await referenceOf(photoSlot.get()); await closeUpOf(photoRef); } + await ensureOwn(); + if (!ai) { + // The picture the views are made from: the source picture, else the user's own front (or face close-up). + const from = photoSlot.get() ? null : own.front || own.face; + if (from) sourceRef = from.ref; + else { if (!photoRef) photoRef = await referenceOf(photoSlot.get()); sourceRef = photoRef; } + if (!own.face) await closeUpOf(sourceRef, (from || photoSlot.get()).file); + } if (mode === 'image' && !outfitRef) outfitRef = await referenceOf(outfitSlot.get()); } catch (error) { attention = error.message || tr('Could not read this picture. Please choose another one.', '无法读取这张图片,请换一张。'); render(); return; } if (disposed) return; - for (const name of [photoRef, closeUp.name, mode === 'image' ? outfitRef : '']) if (name && references.has(name)) references.set(name, true); + for (const name of [sourceRef, own.face ? '' : closeUp.name, mode === 'image' ? outfitRef : '', ...SHOW.map(view => own[view]?.ref)]) if (name && references.has(name)) references.set(name, true); const outfitImage = mode === 'image' ? outfitRef : ''; if (ai) { const selected = picker ? picker.value() : []; void generator.start(describe.value, {source, outfitImage, ...(selected.length ? {loras: selected} : {})}); - } else void generator.start('', {source, photo: photoRef, closeUp: closeUp.name, outfit: mode === 'keep' ? '' : field.value, outfitImage}); + } else void generator.start('', {source, photo: sourceRef, closeUp: own.face ? '' : closeUp.name, outfit: mode === 'keep' ? '' : field.value, outfitImage}); } action.onclick = () => generator.state().running ? void generator.stop() : void begin(); async function checkInfo() { @@ -376,7 +436,7 @@ export function mountCastPhoto({container, api, text, viewURL, onState = () => { window.addEventListener('pagehide', leaving); async function picture(src) { const blob = await (await fetch(src)).blob(); return createImageBitmap(blob); } - const shownFile = view => { const r = pictureOf(view); return edits[view]?.file || (r.original ? photoSlot.get().file : r.file); }; + const shownFile = view => { const r = pictureOf(view); return edits[view]?.file || own[view]?.file || (r.original ? photoSlot.get().file : r.file); }; async function sheet() { const {body: [bw, bh], face: [fw], gap, ground} = SHEET; const width = fw + 3 * bw + 5 * gap, height = bh + 2 * gap; @@ -385,7 +445,7 @@ export function mountCastPhoto({container, api, text, viewURL, onState = () => { let x = gap; for (const view of SHOW) { const r = pictureOf(view), cw = view === 'face' ? fw : bw; - const image = await picture(edits[view]?.url || (r.original ? photoSlot.get().url : viewURL(r.file))); + const image = await picture(edits[view]?.url || own[view]?.url || (r.original ? photoSlot.get().url : viewURL(r.file))); const k = Math.min(cw / image.width, bh / image.height), w = Math.round(image.width * k), h = Math.round(image.height * k); g.drawImage(image, x + Math.round((cw - w) / 2), gap + Math.round((bh - h) / 2), w, h); image.close?.(); x += cw + gap; @@ -403,11 +463,11 @@ export function mountCastPhoto({container, api, text, viewURL, onState = () => { const state = generator.state(); if (!generator.done() || state.running) return []; const views = SHOW.map(view => ({file: shownFile(view), label: view})); - const extra = photoSlot?.get() && !SHOW.some(view => pictureOf(view)?.original) ? [{file: photoSlot.get().file, label: 'other'}] : []; + const extra = photoSlot?.get() && !SHOW.some(view => pictureOf(view)?.original && !own[view]) ? [{file: photoSlot.get().file, label: 'other'}] : []; return [{file: await sheet(), label: 'sheet'}, ...views, ...extra]; }, // The card keeps its own copy of the views it shows; the views stay in the library. - markSaved() { cardSaved = true; generator.state().pictures.forEach((r, at) => { if (r.file && !edits[make[at]]) saved.add(r.file); }); }, + markSaved() { cardSaved = true; generator.state().pictures.forEach((r, at) => { if (r.file && !edits[make[at]] && !own[make[at]]) saved.add(r.file); }); }, isBusy: () => generator.state().running, cancel: () => generator.stop(), destroy() { @@ -415,6 +475,7 @@ export function mountCastPhoto({container, api, text, viewURL, onState = () => { // Cancel, close, Esc: the uploads go; the views stay in the library. leaving(); for (const view of Object.keys(edits)) dropEdit(view); + for (const view of Object.keys(own)) releaseOwn(view); void generator.dispose(); photoSlot?.dispose(); outfitSlot.dispose(); action.remove(); root.remove(); }, element: root, From defdd11cabaf9a57fb4db2f78a775e3368e7244b Mon Sep 17 00:00:00 2001 From: Bowen Xue Date: Wed, 18 Nov 2026 04:48:36 +0000 Subject: [PATCH 44/97] Agent: audio used as it is can continue a saved video Agent: audio used as it is can continue a saved video; ignored first-frame setting and part limit are explained Continuing a saved video with a sound used as it is is accepted by the Agent checks and the chain: the first part starts 22 frames before the selected audio, on the audio of the frames the saved video already holds, and the selection must start at least one second into the file. Up to three pictures may come with the sound. A first-frame setting that the sound makes unused is reported by plan and submit, and the part-limit refusal says why and which way out is open. --- freevideo_engine/agent/guide.py | 2 +- freevideo_engine/agent/jobs.py | 19 ++++++++++-- freevideo_engine/agent/routes.py | 4 ++- freevideo_engine/agent/spec.py | 10 +++++++ freevideo_engine/chain_store.py | 1 + freevideo_engine/original_audio.py | 17 +++++++++-- freevideo_engine/original_audio_chain.py | 38 ++++++++++++++++++------ 7 files changed, 74 insertions(+), 17 deletions(-) diff --git a/freevideo_engine/agent/guide.py b/freevideo_engine/agent/guide.py index dc1939fe..24bbee5c 100644 --- a/freevideo_engine/agent/guide.py +++ b/freevideo_engine/agent/guide.py @@ -75,7 +75,7 @@ 'Tags are numbered per kind in reference order: , ,