diff --git a/freevideo.ps1 b/freevideo.ps1 index 38f0338c..49ee3489 100644 --- a/freevideo.ps1 +++ b/freevideo.ps1 @@ -144,6 +144,22 @@ try { -Arguments @('python', 'install', '--no-bin', '--no-registry', '--no-progress', '--color', 'never', $versions.python) ` -LogPath $bootstrapLog -Label $pythonLabel ` -Direct:($proxyRoute -eq 'direct') -OutputTail ([ref]$pythonOutput) + if ($pythonExit -ne 0 -and (Test-FreeVideoCertificateFailure $pythonOutput)) { + $originalOutput = $pythonOutput + $originalExit = $pythonExit + $retryOutput = '' + $retryExit = Invoke-FreeVideoBootstrapCommand -Executable $uv ` + -Arguments @('--native-tls', 'python', 'install', '--no-bin', '--no-registry', '--no-progress', '--color', 'never', $versions.python) ` + -LogPath $bootstrapLog -Label ($pythonLabel + ', system certificates') ` + -Direct:($proxyRoute -eq 'direct') -OutputTail ([ref]$retryOutput) + if ($retryExit -eq 0) { + $pythonExit = 0 + $pythonOutput = $retryOutput + } else { + $pythonExit = $originalExit + $pythonOutput = $originalOutput + } + } if ($pythonExit -eq 0) { $installed = $true; break } if (Test-FreeVideoAccessDenied $pythonOutput) { $deniedRoutes[$route] = $true } elseif (Test-FreeVideoSlowDownloadFailure $pythonOutput) { $slowRoutes[$route] = $true } diff --git a/freevideo_engine/bootstrap.py b/freevideo_engine/bootstrap.py index 8ba266c4..4c0738f6 100644 --- a/freevideo_engine/bootstrap.py +++ b/freevideo_engine/bootstrap.py @@ -2061,9 +2061,11 @@ def python_install(self, uv): return custom = self.env.get('UV_PYTHON_INSTALL_MIRROR') if self.network.get('mode') != 'official' else None isolation = ['--no-bin', '--no-registry'] - def attempt(source, route, retry_mode): + def attempt(source, route, retry_mode, native_tls=False): env = network.download_environment( network.route_environment(self.network, 'github', source, self.env, route), retry_mode) + if native_tls: + env['UV_NATIVE_TLS'] = '1' env['UV_PYTHON_INSTALL_MIRROR'] = (custom if source == 'user-python' else network.PYTHON_MIRRORS[source] if source in network.PYTHON_MIRRORS else network.source_url('github', source, self.env) + '/astral-sh/python-build-standalone/releases/download') diff --git a/freevideo_engine/comfy_library.py b/freevideo_engine/comfy_library.py index 6e334b45..5a1bcc68 100644 --- a/freevideo_engine/comfy_library.py +++ b/freevideo_engine/comfy_library.py @@ -273,6 +273,8 @@ def list_videos(output_directory, *, before=None, limit=24, favorite=None): if key[1] + '/video.mp4' in tokens: summary['report_id'] = tokens[key[1] + '/video.mp4'] folders[key[1]], reports[key[1]] = path.parent, report + # A video made without a request of its own (the editor's merged export) can go to 4K but not up one step. + summary['saved_request'] = (path.parent / 'comfy-request.json').is_file() rows.append(dict(summary, id=key[1], bytes=info.st_size, favorite=is_favorite, created_at=datetime.fromtimestamp(info.st_mtime, timezone.utc).isoformat(), cursor=str(key[0]) + ':' + key[1])) @@ -390,6 +392,120 @@ def video_download(output_directory, identity, *, workflow=False): return copy, name, copy +ZIP_MOST_ITEMS = 500 + + +class _ZipSink: + """An unseekable target for zipfile: each take() hands over what was written since the last one.""" + def __init__(self): + self.parts = [] + + def write(self, data): + self.parts.append(bytes(data)) + return len(data) + + def flush(self): + pass + + def take(self): + data, self.parts = b''.join(self.parts), [] + return data + + +def zip_plan(output_directory, input_directory, items): + """Which of the asked-for works can be packed: ``([(kind, key, arcname)], [left out])``. + + A video is named by its saved id and a picture by its file in the image engine's own folder; anything else, + a repeat, or a work that cannot be read now is left out (and named in the zip's skipped.txt).""" + if not isinstance(items, list) or not items or len(items) > ZIP_MOST_ITEMS: + raise ValueError('Invalid selection') + from .work_thumbnails import FOLDER, PICTURE + plan, left, seen, taken = [], [], set(), set() + for item in items: + if not isinstance(item, dict): + raise ValueError('Invalid selection') + kind = item.get('kind') + key = item.get('id') if kind == 'video' else item.get('file') if kind == 'image' else None + if not isinstance(key, str): + raise ValueError('Invalid selection') + if (kind, key) in seen: + continue + seen.add((kind, key)) + try: + if kind == 'video': + path = _video(output_directory, key) + _report(path) + if not path.stat().st_size: + raise ValueError('Video is empty') + stamp = datetime.fromtimestamp(path.stat().st_mtime, timezone.utc).strftime('%Y%m%d_%H%M%S') + name = 'videos/FreeVideo_%s_%s.mp4' % (stamp, key.split('/')[-1][:12]) + else: + leaf = key.rpartition('/')[2] + if not PICTURE.fullmatch(leaf) or key != FOLDER + '/' + leaf: + raise ValueError('Invalid picture') + info = os.lstat(Path(input_directory) / FOLDER / leaf) + if not stat.S_ISREG(info.st_mode): + raise ValueError('Picture is not a plain file') + name = 'images/' + leaf + except (OSError, ValueError): + left.append(key) + continue + base, dot, extension = name.rpartition('.') + number = 1 + while name in taken: + number += 1 + name = '%s-%d.%s' % (base, number, extension) + taken.add(name) + plan.append((kind, key, name)) + return plan, left + + +def zip_stream(output_directory, input_directory, plan, left, *, workflow=False, copies=None): + """The bytes of one zip of the planned works, produced piece by piece (stored, not recompressed, zip64). + + Every video's copy without the prompt and workflow is deleted as soon as it is written, also when the + generator is closed half way. A work that cannot be read by now is added to skipped.txt at the end. + ``copies``, when given, receives the path of each copy as it is made, for a caller that has to delete them itself.""" + import zipfile + from .work_thumbnails import FOLDER + sink = _ZipSink() + left = list(left) + with zipfile.ZipFile(sink, 'w', zipfile.ZIP_STORED, allowZip64=True) as archive: + for kind, key, name in plan: + copy, started = None, False + try: + if kind == 'video': + path, _, copy = video_download(output_directory, key, workflow=workflow) + if copy is not None and copies is not None: + copies.append(copy) + else: + path = Path(input_directory) / FOLDER / key.rpartition('/')[2] + if not stat.S_ISREG(os.lstat(path).st_mode): + raise ValueError('Picture is not a plain file') + with open(path, 'rb') as source: + mtime = time.localtime(os.fstat(source.fileno()).st_mtime)[:6] + entry = zipfile.ZipInfo(name, date_time=max(mtime, (1980, 1, 1, 0, 0, 0))) + entry.compress_type = zipfile.ZIP_STORED + entry.external_attr = 0o644 << 16 + with archive.open(entry, 'w', force_zip64=True) as target: + started = True + while True: + chunk = source.read(1024 * 1024) + if not chunk: + break + target.write(chunk) + yield sink.take() + except (OSError, ValueError, TypeError): + left.append(key + ' (only part of it is in this zip)' if started else key) + finally: + if copy is not None: + copy.unlink(missing_ok=True) + yield sink.take() + if left: + archive.writestr('skipped.txt', 'These works could not be read and are not in this zip:\n' + '\n'.join(left) + '\n') + yield sink.take() + + # What a FreeVideo request writes into its own run folder, including the # prompt-enhancement record and the staging copy monitoring.save keeps when # Windows would not let it replace a JSON record. A creation whose folder @@ -1017,7 +1133,10 @@ def _forget_works(root, facts): def _forget_results(identities, root): - """A result-cache row naming a deleted creation can no longer be reused.""" + """A result-cache row naming a deleted creation can no longer be reused, and the record of finished jobs in the + output folder keeps no line naming it.""" + from . import jobs_journal + jobs_journal.forget(identities, root=root.parent) for index in (root / '.result-cache').glob('*.json'): try: if index.stat().st_size <= 1024 * 1024 and json.loads(index.read_text(encoding='utf-8')).get('id') in identities: @@ -1841,6 +1960,59 @@ async def sizes(request): raise web.HTTPBadRequest(text='Invalid selection') from None return web.json_response(dict(sizes=result), headers={'Cache-Control': 'no-store'}) + @server.routes.post('/freevideo/library/download-zip') + async def download_zip(request): + # One zip of several works. The page posts a form (so the browser streams the answer straight to disk) with + # the choice in its ``payload`` field; a JSON body is read the same way. + try: + if request.content_type == 'application/json': + body = await request.json() + else: + body = json.loads((await request.post()).get('payload')) + if not isinstance(body, dict): + raise ValueError('Invalid selection') + output, source = folder_paths.get_output_directory(), folder_paths.get_input_directory() + plan, left = await asyncio.to_thread(zip_plan, output, source, body.get('items')) + except (OSError, ValueError, TypeError): + raise web.HTTPBadRequest(text='Invalid selection') from None + if not plan: + raise web.HTTPNotFound(text='Saved works unavailable') + if body.get('check') is True: + # What the page asks before posting the form: the answer to a form lands in a hidden frame, where an error + # would be seen by no one. + return web.json_response(dict(ready=len(plan), skipped=len(left)), headers={'Cache-Control': 'no-store'}) + stamp = datetime.now().strftime('%Y%m%d_%H%M%S') + response = web.StreamResponse(headers={'Content-Type': 'application/zip', 'Cache-Control': 'private, no-store', + 'Content-Disposition': 'attachment; filename="FreeVideo_%s.zip"' % stamp, + 'X-FreeVideo-Skipped': str(len(left))}) + copies = [] + pieces = zip_stream(output, source, plan, left, workflow=body.get('workflow') is True, copies=copies) + try: + await response.prepare(request) + while True: + chunk = await asyncio.to_thread(next, pieces, None) + if chunk is None: + break + if chunk: + await response.write(chunk) + await response.write_eof() + finally: + # Also when the browser cancelled: the copies without the prompt and workflow are deleted. + for _ in range(600): + try: + await asyncio.to_thread(pieces.close) + break + except ValueError: # still reading its last piece in another thread + await asyncio.sleep(0.1) + else: + logging.warning('FreeVideo is still preparing a video for a cancelled zip download; its copy is removed when done.') + for copy in copies: + try: + await asyncio.to_thread(copy.unlink, missing_ok=True) + except OSError: + pass # Still open (Windows): the generator removes it itself once it returns. + return response + @server.routes.get('/freevideo/library/download') async def download(request): headers = {'Content-Type': 'video/mp4', 'Cache-Control': 'private, no-store'} diff --git a/freevideo_engine/comfy_source.py b/freevideo_engine/comfy_source.py index 74f95587..fc1da2e5 100644 --- a/freevideo_engine/comfy_source.py +++ b/freevideo_engine/comfy_source.py @@ -1,5 +1,6 @@ """Install a pinned ComfyUI application into a newly selected workspace.""" import json +import subprocess from pathlib import Path from .long_paths import io_path, resolved, plain, plain_errors @@ -50,7 +51,14 @@ def download(target, *, plan, env, run): validate_target(target) spec = specification() if target.exists(): - return network.clone(target, spec['url'], spec['commit'], network=plan, env=env, run=run) + try: + return network.clone(target, spec['url'], spec['commit'], network=plan, env=env, run=run) + except ValueError: + # A folder FreeVideo downloaded (it holds the receipt) that lost files or only + # differs in permissions or line endings is repaired; the user's edits never are. + if not restore_untouched(target, spec['commit'], plan=plan, env=env, run=run): + raise + return network.clone(target, spec['url'], spec['commit'], network=plan, env=env, run=run) stage = target.with_name(target.name + '.freevideo-download') # A finished checkout survives cancellation before publication. network.clone(stage, spec['url'], spec['commit'], network=plan, env=env, run=run) @@ -61,3 +69,67 @@ def download(target, *, plan, env, run): raise ValueError('The ComfyUI destination changed during installation; the downloaded files are retained: ' + str(stage)) stage.rename(target) return target + + +RESTORE_BATCH = 100 + + +WAYS_OUT = ('To download a fresh copy, rename or move this folder, then click "Retry installation". ' + 'To keep using it as it is, choose "Use existing ComfyUI".') + + +def different_message(first): + return first + ' FreeVideo left the folder unchanged. ' + WAYS_OUT + + +def restore_untouched(target, commit, *, plan, env, run): + """Bring back the downloaded files an existing ComfyUI lost or only re-wrote; refuse anything else. + + Returns True when the folder now matches the pinned source, False when this cannot + be judged (not a readable Git checkout, or nothing differs), and raises ValueError + naming the files when the folder holds another version or edited files. + """ + if not io_path(Path(target) / '.git').exists(): + return False + env = dict(env or {}, GIT_TERMINAL_PROMPT='0') + git = env.get('FREEVIDEO_GIT') or 'git' + base = [git, '-c', 'core.longpaths=true', '-C', str(target)] + content = ['-c', 'core.filemode=false', '-c', 'core.autocrlf=false'] + def output(*arguments, settings=()): + command = [base[0], *settings, *base[1:], *arguments] + return network.subprocess_output.output_external(command, env=env, timeout=120, **network.hidden_console()) + try: + head = output('rev-parse', 'HEAD').strip() + # Files whose content changed; a file that only lost its permissions or got other line endings is not one. + changed = [row.split('\t', 2)[2] for row in output( + 'diff', '--numstat', '-z', '--ignore-cr-at-eol', '--diff-filter=d', 'HEAD', settings=content).split('\0') if row] + listed = output('status', '--porcelain', '-z', '--untracked-files=no').split('\0') + except (subprocess.CalledProcessError, subprocess.TimeoutExpired, OSError, IndexError): + return False + if head != commit: + raise ValueError(different_message('The ComfyUI folder %s holds a different version from the one FreeVideo needs.' % plain(target))) + if changed: + shown = ', '.join(changed[:8]) + (', and %d more' % (len(changed) - 8) if len(changed) > 8 else '') + raise ValueError(different_message('Some files in the ComfyUI folder %s differ from the version FreeVideo needs. ' + 'Changed files (%d): %s.' % (plain(target), len(changed), shown))) + names = [row[3:] for row in listed if len(row) > 3] + if not names: + return False + for start in range(0, len(names), RESTORE_BATCH): + command = [git, '-c', 'core.longpaths=true', '-C', str(target), '-c', 'core.autocrlf=false', + 'checkout', '--force', commit, '--', *names[start:start + RESTORE_BATCH]] + if run: + run('ComfyUI-restore', command, env=env) + else: + result = network.subprocess_output.run_external(list(map(str, command)), env=env, stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, **network.hidden_console()) + if result.returncode: + raise RuntimeError(result.stdout[-2500:]) + try: + if output('status', '--porcelain', '--untracked-files=no').strip(): + # The file system cannot hold permissions; Git is told to stop comparing them. + output('config', 'core.fileMode', 'false') + except (subprocess.CalledProcessError, subprocess.TimeoutExpired, OSError): + return False + network.event(plan or {}, category='git', file=Path(target).name, action='restored', commit=commit, files=len(names)) + return True diff --git a/freevideo_engine/desktop_runtime.py b/freevideo_engine/desktop_runtime.py index a86ea79d..129e6802 100644 --- a/freevideo_engine/desktop_runtime.py +++ b/freevideo_engine/desktop_runtime.py @@ -274,6 +274,55 @@ def complete(path): shutil.rmtree(stage, ignore_errors=True) +ENTRY_SCRIPT = 'freevideo.ps1' + + +def entry_ready(source, name=ENTRY_SCRIPT): + try: + return (io_path(source) / name).is_file() and (io_path(source) / name).stat().st_size > 0 + except OSError: + return False + + +def restore_entry(source, name=ENTRY_SCRIPT): + """Put back one entry script that vanished from a deployed source folder after the launcher started. + + The copy comes only from the launcher's own built-in files (or the verified update overlay), + checked against the recorded hash; nothing is downloaded. Returns whether the script is usable.""" + if entry_ready(source, name): + return True + try: + bootstrap = None + origin = expected = None + if getattr(sys, 'frozen', False): + from .top_level_modules import update_modules + bootstrap = update_modules()[2] + active = getattr(bootstrap, 'ACTIVE', None) + if active and resolved(Path(plain(active['source']))) == resolved(Path(plain(source))): + expected = active['manifest']['files'].get(name, {}).get('sha256') + held = io_path(active['folder']) / 'files' / name + origin = held if held.is_file() else io_path(Path(sys._MEIPASS) / 'engine-source') / name + elif getattr(sys, 'frozen', False): + origin = io_path(Path(sys._MEIPASS) / 'engine-source') / name + record = json.loads((io_path(source) / 'launcher-source.json').read_text(encoding='utf-8')) + expected = record['sha256'].get(name) + if origin is None or not expected or not origin.is_file(): + return False + data = origin.read_bytes() + if hashlib.sha256(data).hexdigest() != expected: + return False + target = io_path(source) / name + stage = target.with_name(name + '.' + uuid.uuid4().hex[:8] + '.tmp') + try: + stage.write_bytes(data) + os.replace(stage, target) + finally: + stage.unlink(missing_ok=True) + except Exception: + return False + return entry_ready(source, name) + + def preflight_json(output): decoder = json.JSONDecoder() for offset, character in enumerate(output): @@ -341,6 +390,12 @@ def _run(self, action, root, arguments): with awake(): self._run_awake(action, root, arguments) + def entry_script(self): + """The file in the source folder that command() starts, or None when it starts no script.""" + if windows(): + return ENTRY_SCRIPT + return None if sys.platform == 'darwin' else 'freevideo' + def command(self, root, arguments): powershell = Path(os.environ.get('SystemRoot', r'C:\Windows')) / 'System32/WindowsPowerShell/v1.0/powershell.exe' return [str(powershell), '-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', @@ -362,6 +417,10 @@ def _run_awake(self, action, root, arguments): try: run.mkdir(parents=True) command = self.command(root, arguments) + entry = self.entry_script() + # Only a command that really starts the script needs it (the ComfyUI host runs from Python directly). + if entry and str(self.source / entry) in command and not restore_entry(self.source, entry): + raise RuntimeError('FreeVideo could not find %s in %s' % (entry, plain(self.source))) save(run / 'status.json', dict(action=action, command=command, root=str(root), status='running')) self.events.put(('started', plain(run))) env = self.environment(root) diff --git a/freevideo_engine/diagnostic_resources.py b/freevideo_engine/diagnostic_resources.py index 55f0dcd4..c5f321c8 100644 --- a/freevideo_engine/diagnostic_resources.py +++ b/freevideo_engine/diagnostic_resources.py @@ -830,6 +830,11 @@ def planning(rows): item['idle_cache']['accounting'] = numbers(idle.get('ram_accounting'), ('raw_available_bytes', 'credited_available_bytes', 'pinned_model_bytes', 'reused_encoder_working_bytes')) + returned = mapping(mapping(row.get('recovery')).get('gpu_return')) + if returned: + # How long the card took to give back the released worker's video memory. + item['gpu_return'] = dict(numbers(returned, ('polls', 'seconds', 'expected_free_bytes', 'free_bytes')), + recovered=returned.get('recovered') is True) kernels = mapping(row.get('attention_backends')) if kernels: # Whether the attention choice rested on this GPU's own kernel checks. diff --git a/freevideo_engine/display_adapters.py b/freevideo_engine/display_adapters.py index 3632d047..7adaafb5 100644 --- a/freevideo_engine/display_adapters.py +++ b/freevideo_engine/display_adapters.py @@ -8,6 +8,10 @@ import subprocess DISPLAY_CLASS = r'SYSTEM\CurrentControlSet\Control\Class\{4d36e968-e325-11cf-bfc1-08002be10318}' +PCI_ENUM = r'SYSTEM\CurrentControlSet\Enum\PCI' +NVIDIA_VENDOR = '10de' +# PCI vendors whose cards are never NVIDIA's, for naming a driverless card the display class lists without a vendor. +OTHER_VENDOR_IDS = {'1002': 'AMD graphics', '8086': 'Intel graphics'} BASIC = re.compile(r'basic (?:display|render)', re.I) NVIDIA = 'NVIDIA' NVIDIA_NAME = re.compile(r'nvidia|geforce|quadro|rtx|tesla', re.I) @@ -41,6 +45,90 @@ def windows_names(): return names +ERROR_NO_MORE_ITEMS = 259 +CR_SUCCESS, CR_NO_SUCH_DEVNODE = 0, 13 + + +def _keys(winreg, key): + """Every subkey name of an open key. Only "no more items" ends the list; any other failure raises OSError.""" + names, index = [], 0 + while True: + try: + names.append(winreg.EnumKey(key, index)) + except OSError as error: + if getattr(error, 'winerror', None) == ERROR_NO_MORE_ITEMS or error.errno == ERROR_NO_MORE_ITEMS: + return names + raise + index += 1 + + +def device_present(instance_id): + """True when the device is in the device tree now, False when only a record of a removed device is left. + + Raises OSError when the system cannot say, so the caller treats the answer as unknown. + """ + import ctypes + try: + locate = ctypes.windll.cfgmgr32.CM_Locate_DevNodeW + except (AttributeError, OSError) as error: + raise OSError('device tree not available') from error + handle = ctypes.c_uint32(0) + # Flags 0: only a device that is currently configured is found; the registry keeps removed ones as well. + status = locate(ctypes.byref(handle), ctypes.c_wchar_p(instance_id), 0) + if status == CR_SUCCESS: + return True + if status == CR_NO_SUCH_DEVNODE: + return False + raise OSError('device lookup failed (%s)' % status) + + +def pci_display_vendors(): + """PCI vendor IDs (lower case, four digits) of the display devices present now, driver or not. + + A card without a driver is listed here by its hardware IDs even when the display class names it only as + "Basic Display Adapter" with no vendor. Read-only. The answer is a complete one or an OSError: a key that + cannot be read is never skipped, because a partial list could make an unreadable NVIDIA card look absent. + Records of removed devices are left out. + """ + import winreg + vendors = set() + with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, PCI_ENUM) as head: + for device in _keys(winreg, head): + match = re.match(r'ven_([0-9a-f]{4})&', device, re.I) + if not match: + continue + with winreg.OpenKey(head, device) as parent: + for slot in _keys(winreg, parent): + with winreg.OpenKey(parent, slot) as key: + ids = [] + for name in ('HardwareID', 'CompatibleIDs'): + try: + value, _ = winreg.QueryValueEx(key, name) + except FileNotFoundError: + continue + ids.extend([value] if isinstance(value, str) else list(value or ())) + # PCI class 03 is a display controller (0300 VGA, 0302 3D). + if any(re.search(r'cc_03', str(item), re.I) for item in ids) \ + and device_present('PCI\\' + device + '\\' + slot): + vendors.add(match.group(1).lower()) + return vendors + + +def vendor_of_unknown_adapter(): + """NVIDIA, a name for another vendor, or None when it cannot be told from the system's PCI list.""" + try: + vendors = pci_display_vendors() if os.name == 'nt' else set() + except Exception: + # Any surprise from the registry or the device tree (ctypes.ArgumentError is not an OSError) means unknown; + # this lookup only refines a card note and must never stop the launcher. + return None + if NVIDIA_VENDOR in vendors: + return NVIDIA + if vendors and vendors <= set(OTHER_VENDOR_IDS): + return ' / '.join(OTHER_VENDOR_IDS[item] for item in sorted(vendors)) + return None + + def linux_names(): out = subprocess.run(['lspci', '-mm'], capture_output=True, text=True, timeout=10, check=True).stdout names = [] @@ -74,8 +162,15 @@ def adapters(): if name and (name == NVIDIA or not VIRTUAL.search(name)) and name not in seen: seen.append(name) # An adapter of unknown vendor may be the missing NVIDIA card, so "none detected" would mislead. + # The PCI list names the vendor of a card that has no driver; when it cannot be read the answer stays unknown. if unknown and not any(NVIDIA_NAME.search(name) for name in seen): - return None + vendor = vendor_of_unknown_adapter() + if vendor is None: + return None + if vendor == NVIDIA: + seen.append(NVIDIA) + elif not seen: + seen.append(vendor) return seen diff --git a/freevideo_engine/editor_export.py b/freevideo_engine/editor_export.py index 703fe67e..72ed1664 100644 --- a/freevideo_engine/editor_export.py +++ b/freevideo_engine/editor_export.py @@ -1299,7 +1299,7 @@ def progress(fraction): _check(job['stop'].is_set) _checked_target(target, self.root) _save_report(target, job['project'], time.monotonic() - started, options=job['options']) - job.update(state='done', fraction=1., work=work if job['options'].only == 'video' else None, + job.update(state='done', fraction=1., work=work if job['options'].only == 'video' and not job['options'].lossless else None, **editor_export_options.result_file(work, job['options'])) except Exception as error: # Only this job's UUID folder is owned by the worker. diff --git a/freevideo_engine/editor_export_options.py b/freevideo_engine/editor_export_options.py index c895e371..280729d7 100644 --- a/freevideo_engine/editor_export_options.py +++ b/freevideo_engine/editor_export_options.py @@ -17,14 +17,21 @@ class ExportOptions: # Above 24 the picture is first rendered at 24 fps (intermediate) and then interpolated. fps: int = 24 intermediate: bool = False + # 'lossless': the mixed sound is kept as 16-bit ALAC in a .mov beside the picture, outside the library. + audio: str = 'compatible' @property def filename(self): - return 'audio.' + self.sound_format if self.only == 'sound' else 'video.mp4' + return 'audio.' + self.sound_format if self.only == 'sound' else 'video.mov' if self.lossless else 'video.mp4' + + @property + def lossless(self): + return self.only == 'video' and self.audio == 'lossless' @property def container(self): - return 'wav' if self.only == 'sound' and self.sound_format == 'wav' else 'mp4' + return ('wav' if self.only == 'sound' and self.sound_format == 'wav' + else 'mov' if self.lossless else 'mp4') @property def container_options(self): @@ -40,7 +47,7 @@ def video_options(self): @property def audio_codec(self): - return 'pcm_s16le' if self.container == 'wav' else 'aac' + return 'pcm_s16le' if self.container == 'wav' else 'alac' if self.lossless else 'aac' def status(self): return dict(width=self.width, height=self.height, frames=self.frames, @@ -48,7 +55,8 @@ def status(self): range=dict(start=self.start, frames=self.frames), sound_format=self.sound_format if self.only == 'sound' else None, **({'subtitles': 'none'} if self.only == 'video' and self.subtitles == 'none' else {}), - **({'fps': self.fps} if self.only == 'video' and self.fps != 24 else {})) + **({'fps': self.fps} if self.only == 'video' and self.fps != 24 else {}), + **({'audio': 'lossless'} if self.lossless else {})) FRAME_RATES = (24, 48, 60) @@ -56,13 +64,13 @@ def status(self): def validate(options, width, height, frames): """Validate wire values once; the queue passes the immutable result to render.""" - if not isinstance(options, dict) or set(options) - {'short', 'quality', 'range', 'only', 'sound_format', 'subtitles', 'fps'}: + if not isinstance(options, dict) or set(options) - {'short', 'quality', 'range', 'only', 'sound_format', 'subtitles', 'fps', 'audio'}: raise ValueError('Invalid export options') if 'short' in options and (type(options['short']) is not int or not 144 <= options['short'] <= 4320 or options['short'] % 2): raise ValueError('Invalid export short side') for key, allowed in (('quality', ('high', 'standard', 'small')), ('only', ('sound',)), - ('sound_format', ('m4a', 'wav')), ('subtitles', ('burn', 'none'))): + ('sound_format', ('m4a', 'wav')), ('subtitles', ('burn', 'none')), ('audio', ('lossless',))): if key in options and (type(options[key]) is not str or options[key] not in allowed): raise ValueError('Invalid export ' + key) start, count = 0, frames @@ -86,7 +94,8 @@ def validate(options, width, height, frames): if max(output_width, output_height) > 8192: raise ValueError('Export picture is too large') return ExportOptions(output_width, output_height, start, count, quality=options.get('quality', 'high'), - subtitles=options.get('subtitles', 'burn'), fps=options.get('fps', 24)) + subtitles=options.get('subtitles', 'burn'), fps=options.get('fps', 24), + audio=options.get('audio', 'compatible')) def effective(options, width, height, frames): @@ -108,10 +117,12 @@ def frame_tracks(tracks, start, number): def sound_samples(mixed, options): - if options.container != 'wav': + if options.container not in ('wav', 'mov'): return mixed, 'fltp' import numpy as np samples = np.clip(np.rint(mixed.T * 32768), -32768, 32767).astype(np.int16) + if options.container == 'mov': + return np.ascontiguousarray(samples.T), 's16p' # ALAC takes planar 16-bit return np.ascontiguousarray(samples.reshape(1, -1)), 's16' @@ -126,6 +137,8 @@ def report_values(report, options): if options.only == 'video' and options.fps != 24: # The picture has fps times as many frames per second; the length stays the same. report['geometry'].update(fps=options.fps, frames=-(-options.frames * options.fps // 24)) + if options.lossless: + report['encoding'].update(audio_codec='alac', bits_per_sample=16) if options.only == 'sound': report.pop('video', None) report['audio'] = dict(format=options.sound_format) @@ -138,7 +151,7 @@ def report_values(report, options): def result_file(work, options): - """Use ComfyUI's existing output media route; audio is not a library video.""" + """Use ComfyUI's existing output media route; audio is not a library video, nor is a lossless .mov.""" path = PurePosixPath('FreeVideo') / work / options.filename return dict(path=path.as_posix(), url='/view?' + urlencode( dict(filename=path.name, subfolder=str(path.parent), type='output'))) diff --git a/freevideo_engine/failure_details.py b/freevideo_engine/failure_details.py index 74e6eb76..55b6aed5 100644 --- a/freevideo_engine/failure_details.py +++ b/freevideo_engine/failure_details.py @@ -535,6 +535,24 @@ def _without_ready_curl_diagnostics(text): return ''.join(lines) +COMFY_FOLDER_STEPS = '如需下载新的副本,请将此文件夹改名或移走,然后点“重试安装”;如需按原样继续使用,请选择“使用已有 ComfyUI”。' + + +def comfy_folder_refused(text): + """The Chinese text for comfy_source's refusal of a ComfyUI folder with edited files or another version, or ''.""" + edited = re.search(r'Some files in the ComfyUI folder (.+?) differ from the version FreeVideo needs\. ' + r'Changed files \((\d+)\): (.+?)(?:, and (\d+) more)?\. FreeVideo left the folder unchanged\.', text) + if edited: + folder, count, names, more = edited.groups() + listed = '、'.join(names.split(', ')) + (',另有 %s 个' % more if more else '') + return ('ComfyUI 文件夹 %s 中有文件与 FreeVideo 所需的版本不同。内容有改动的文件(%s 个):%s。FreeVideo 未改动该文件夹。' + % (folder, count, listed)) + COMFY_FOLDER_STEPS + other = re.search(r'The ComfyUI folder (.+?) holds a different version from the one FreeVideo needs\. FreeVideo left the folder unchanged\.', text) + if other: + return 'ComfyUI 文件夹 %s 是另一个版本,与 FreeVideo 所需的版本不同。FreeVideo 未改动该文件夹。' % other.group(1) + COMFY_FOLDER_STEPS + return '' + + def model_mismatch_package(value, zh=False): """Keep only the package's display name before diagnostic paths are redacted.""" from .model_repair import MISMATCH_PATH @@ -552,9 +570,9 @@ def model_mismatch_package(value, zh=False): # The system lists an NVIDIA card but no driver answers. DRIVER_FOR_LISTED_CARD = ( - ('No NVIDIA driver was found', + ('No driver is installed for the NVIDIA graphics card', 'Install the NVIDIA driver, version 580 or newer, restart the computer, then click "Retry installation".'), - ('未找到 NVIDIA 显卡驱动', + ('NVIDIA 显卡未安装驱动', '请安装 580 或更新版本的 NVIDIA 显卡驱动,重启电脑后点击“重试安装”。')) @@ -634,7 +652,7 @@ def source_lines(lines, zh=False): # 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+(?:RTX\s*)?20[0-46-9]0\b' # RTX 20 series (Turing); the laptop RTX 2050 is Ampere and stays supported 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' @@ -751,6 +769,10 @@ class names and errno, no text), when the message is that exception's str(); it detail=('这台 Mac 的图形处理器未通过 FreeVideo 的运行检查。请先导出报告,再点击“提交问题”并附上报告。' if zh else 'The graphics processor of this Mac did not pass FreeVideo’s check. Export the report, ' 'then use "Report a problem" and attach it.'), action='', kind='mac-gpu-check') + if zh: + refused = comfy_folder_refused(text) + if refused: + return dict(title='暂时未能完成', detail=refused, action='', kind='unknown') for pattern, kind, title, action in PLACE_RULES: if re.search(pattern, summary): return dict(title=title[zh], detail='', action=action[zh], kind=kind) diff --git a/freevideo_engine/frame_upscale.py b/freevideo_engine/frame_upscale.py index b41391f6..e262cd7b 100644 --- a/freevideo_engine/frame_upscale.py +++ b/freevideo_engine/frame_upscale.py @@ -31,7 +31,27 @@ TILE, PAD = 512, 34 # GPU memory the worker needs; below it the bridge first frees idle models. NEEDED_GPU_BYTES = 3 * 2**30 // 2 -NOT_A_WORK = 'Choose a finished FreeVideo video to upscale' +NOT_A_WORK = 'Cannot upscale this video' +# Why a video cannot be upscaled, and what to do instead. The message carries the code so the page can show it +# in the user's language (web/error_panel.js), and the code stays the same across languages. +REASONS = dict( + outside='it is not in the FreeVideo output folder. Choose a video from Creations.', + missing='the video file is missing or cannot be read. It may have been moved or deleted. Choose another video from Creations.', + no_request='a merged or imported video can only be upscaled to the largest size. Choose the largest "Upscale to" option in ' + 'the menu, or upscale each clip before merging.', + unfinished='its generation did not finish. Choose a finished video from Creations.', + preview='it is a preview. Generate the full video first, then upscale it.', + fps='it is not 24 fps. Only 24 fps videos can be upscaled. Choose another video.', + streams="this video's format cannot be upscaled. Choose a video generated by FreeVideo.", + size_step='its size can only be upscaled to the largest size. Choose the largest "Upscale to" option in the menu.', + size_4k='it is already the largest size.') + + +class NotUpscalable(ValueError): + """code: a key of REASONS.""" + def __init__(self, code): + super().__init__('%s (%s): %s' % (NOT_A_WORK, code, REASONS[code])) + self.code = code class UpscaleError(RuntimeError): @@ -65,28 +85,47 @@ def size(width, height): return target if max(target) > longest else None +def _saved_request(video): + """The video's saved request, or, for a video made without one (the editor's merged export), the completion + summary the library lists it by. None when neither describes a finished video.""" + path = video.parent / 'comfy-request.json' + try: + if path.is_file(): + state = json.loads(path.read_text(encoding='utf-8')) + return state if isinstance(state, dict) else None + report = json.loads(video.with_suffix('.request.json').read_text(encoding='utf-8')) + except (OSError, ValueError): + return None + if not isinstance(report, dict) or report.get('success') is not True: + return None + return dict(status='complete', output=str(video), geometry=report.get('geometry'), preview=bool(report.get('preview'))) + + def work_request(output_directory, relative): - """A finished, non-preview 24 fps FreeVideo work in this output folder that the 4K size makes larger: - (video, saved state).""" + """A finished, non-preview 24 fps video in this output folder that the 4K size makes larger: (video, saved + state). A video the library lists without a saved request, such as a merged one, qualifies by its summary.""" if not isinstance(relative, str) or not relative.strip(): - raise ValueError(NOT_A_WORK) + raise NotUpscalable('outside') output_root = Path(output_directory).resolve() video = (output_root / relative).resolve() try: video.relative_to(output_root / 'FreeVideo') except ValueError: - raise ValueError(NOT_A_WORK) from None - path = video.parent / 'comfy-request.json' - try: - state = json.loads(path.read_text(encoding='utf-8')) if path.is_file() else {} - except (OSError, ValueError): - state = {} - geometry = state.get('geometry') if isinstance(state, dict) else None - if (not isinstance(state, dict) or state.get('status') != 'complete' or state.get('preview') - or Path(state.get('output', '')).resolve() != video or not isinstance(geometry, dict) - or geometry.get('fps') != 24 or size(geometry.get('width'), geometry.get('height')) is None - or not video.is_file()): - raise ValueError(NOT_A_WORK) + raise NotUpscalable('outside') from None + if not video.is_file(): + raise NotUpscalable('missing') + state = _saved_request(video) + geometry = state.get('geometry') if state else None + if state is None or not isinstance(geometry, dict) or Path(state.get('output') or '').resolve() != video: + raise NotUpscalable('no_request') + if state.get('status') != 'complete': + raise NotUpscalable('unfinished') + if state.get('preview'): + raise NotUpscalable('preview') + if geometry.get('fps') != 24: + raise NotUpscalable('fps') + if size(geometry.get('width'), geometry.get('height')) is None: + raise NotUpscalable('size_4k') return video, state @@ -96,16 +135,20 @@ def inspect(path): try: with av.open(str(path)) as container: if len(container.streams.video) != 1: - raise ValueError(NOT_A_WORK) + raise NotUpscalable('streams') stream = container.streams.video[0] rate = stream.average_rate or stream.guessed_rate width, height = stream.codec_context.width, stream.codec_context.height frames = sum(1 for packet in container.demux(stream) if packet.size) sound = bool(container.streams.audio) except (av.error.FFmpegError, OSError) as error: - raise ValueError(NOT_A_WORK) from error - if rate is None or Fraction(rate) != 24 or frames <= 0 or size(width, height) is None: - raise ValueError(NOT_A_WORK) + raise NotUpscalable('missing') from error + if frames <= 0: + raise NotUpscalable('missing') + if rate is None or Fraction(rate) != 24: + raise NotUpscalable('fps') + if size(width, height) is None: + raise NotUpscalable('size_4k') return dict(width=width, height=height, frames=frames, sound=sound) diff --git a/freevideo_engine/generate.py b/freevideo_engine/generate.py index e4e1bb19..20d1d229 100644 --- a/freevideo_engine/generate.py +++ b/freevideo_engine/generate.py @@ -105,7 +105,9 @@ def child(command, env, descriptor, log, *, ram_budget_bytes=None, gpu=None, on_ sample = memory.sample(process.pid) telemetry.setdefault('ram_start', sample) telemetry['ram_last'] = sample - pressure = inference_pressure(sample, ram_budget_bytes, minimum_available_bytes, + # A callable gives a floor that follows the worker's stage (the Mac engine child). + floor = minimum_available_bytes() if callable(minimum_available_bytes) else minimum_available_bytes + pressure = inference_pressure(sample, ram_budget_bytes, floor, budget_is_estimate=ram_budget_is_estimate) telemetry['ram_guard'] = pressure if pressure['reasons'] and not pressure['enforced_reasons']: @@ -208,6 +210,38 @@ def low_memory_mode(engine): return None +# After the idle worker exits, the driver hands its video memory back a moment +# later, and a fresh measurement taken at once can still count it as used. +GPU_RETURN_SLACK = 512 * 2**20 +GPU_RETURN_RISE = 64 * 2**20 +GPU_RETURN_PATIENCE = 3.0 +GPU_RETURN_LIMIT = 20.0 + + +def await_released_gpu(raw, expected_free, detect, *, clock=time.monotonic, pause=time.sleep): + """Measure again until the video memory the released worker held is free. + + Gives up when the free amount has stopped rising for GPU_RETURN_PATIENCE + seconds (something else holds the memory) or after GPU_RETURN_LIMIT, and + returns the latest measurement either way, so a card that never recovers + is planned from what it really has. Nothing waits when it is already back. + """ + target = expected_free - GPU_RETURN_SLACK + first = clock() + best, rose, polls = raw.vram_free, first, 0 + while raw.vram_free < target: + now = clock() + if now - rose >= GPU_RETURN_PATIENCE or now - first >= GPU_RETURN_LIMIT: + break + pause(.25) + raw = detect() + polls += 1 + if raw.vram_free > best + GPU_RETURN_RISE: + best, rose = raw.vram_free, clock() + return raw, dict(polls=polls, seconds=clock() - first, expected_free_bytes=expected_free, + free_bytes=raw.vram_free, recovered=raw.vram_free >= target) + + def automatic_profile(args, canvas, *, stage, evidence, descriptor=None, environment=None): """Plan with idle-cache accounting; reclaim once if it prevents admission.""" from .hardware import detect @@ -215,8 +249,12 @@ def automatic_profile(args, canvas, *, stage, evidence, descriptor=None, environ from .kernel_capabilities import available_backends from .resident_process import credit, release_idle_cache, ENV, SessionRestarted environment = os.environ if environment is None else environment + released = None for attempt in range(2): raw = detect() + if released is not None: + released_row, expected_free = released + raw, released_row['recovery']['gpu_return'] = await_released_gpu(raw, expected_free, detect) encoding_stage = stage == 'before-encoding' and bool(getattr(args, 'prompt_file', None)) hardware, state = credit(raw, environment, reuse_encoder=encoding_stage) row = dict(stage=stage, raw=raw.to_dict(), adjusted=hardware.to_dict(), idle_cache=state) @@ -383,6 +421,9 @@ def automatic_profile(args, canvas, *, stage, evidence, descriptor=None, environ row['recovery'] = release_idle_cache(environment, lease) except SessionRestarted: row['recovery'] = dict(released=True, reason='Old worker already confirmed stopped') + idle_gpu = (state or {}).get('reclaimable_gpu_bytes') + if type(idle_gpu) is int and idle_gpu > 0 and row['recovery'].get('released'): + released = (row, min(raw.vram_total, raw.vram_free + idle_gpu)) environment.pop(ENV, None) os.environ.pop(ENV, None) diff --git a/freevideo_engine/hardware.py b/freevideo_engine/hardware.py index 34255e6f..78a52cb7 100644 --- a/freevideo_engine/hardware.py +++ b/freevideo_engine/hardware.py @@ -216,8 +216,14 @@ def ok(code): def _static_cache_path(): + """One saved copy per interpreter. The host (ComfyUI's Python) and the engine's own Python both probe, and the + saved key names the interpreter: sharing one file, each overwrote the other's copy, so nearly every video + request paid the full torch probe again (1.3-4 s, a new process importing torch and starting CUDA).""" + import hashlib + import sys from .paths import data_root - return data_root() / 'tuning' / 'hardware-static.json' + name = hashlib.sha256(sys.executable.encode('utf-8', 'surrogatepass')).hexdigest()[:16] + return data_root() / 'tuning' / ('hardware-static-%s.json' % name) def _static_key(observed): diff --git a/freevideo_engine/image_gen/image_pack.py b/freevideo_engine/image_gen/image_pack.py index 6a28fc3f..05d34555 100644 --- a/freevideo_engine/image_gen/image_pack.py +++ b/freevideo_engine/image_gen/image_pack.py @@ -14,6 +14,7 @@ import errno import json import logging +import os import platform from pathlib import Path, PurePosixPath import re @@ -261,21 +262,38 @@ def _path(folder, name, *, kind='record'): def shared_root(root=None): - """Where setup puts the video text encoder (/text_encoders/...), which H3 Image uses as is.""" + """Where setup puts the video text encoder (/text_encoders/...), which H3 Image uses as is. + + The folder setup recorded wins, also when the caller names the model folder (almost every caller does): an + encoder folder chosen apart from the model folder is only in machine.json. The record counts for the model + folder it was written for; any other model folder keeps the encoder folder beside it. Without a named folder an + explicit FREEVIDEO_MODEL_ROOT decides (the portable build sets it for its own process, so with a named folder + the record is judged by the folder alone).""" + from ..paths import data_root, installed_model_root + try: + machine = json.loads((data_root() / 'machine.json').read_text(encoding='utf-8')) + saved = machine['encoder_model_root'] + if isinstance(saved, str) and saved: + if root is None and not os.environ.get('FREEVIDEO_MODEL_ROOT'): + return Path(saved).expanduser() + if root is not None and _same_folder(machine.get('model_root'), root): + return Path(saved).expanduser() + except (OSError, ValueError, KeyError, TypeError): + pass if root is None: - import os - from ..paths import data_root, installed_model_root - if not os.environ.get('FREEVIDEO_MODEL_ROOT'): - try: - saved = json.loads((data_root() / 'machine.json').read_text(encoding='utf-8'))['encoder_model_root'] - if isinstance(saved, str) and saved: - return Path(saved).expanduser() - except (OSError, ValueError, KeyError, TypeError): - pass root = installed_model_root() return Path(root).expanduser().absolute().parent / 'encoder' +def _same_folder(first, second): + # Compared as text after normalising (case and slash direction on Windows), not with samefile: the recorded model + # folder may sit on a drive that is not mounted right now, and samefile raises for a folder that is not there. + try: + return os.path.normcase(os.path.abspath(Path(first).expanduser())) == os.path.normcase(os.path.abspath(Path(second).expanduser())) + except (TypeError, ValueError, OSError): + return False + + def target(row, root=None): if row.get('shared'): return shared_root(root) / _relative(row['file']) diff --git a/freevideo_engine/image_gen/layer_stream.py b/freevideo_engine/image_gen/layer_stream.py index 2be13fd3..546784a0 100644 --- a/freevideo_engine/image_gen/layer_stream.py +++ b/freevideo_engine/image_gen/layer_stream.py @@ -68,20 +68,18 @@ class DiskLayerStream: def __init__(self, layers, index, key, device, ahead=READ_AHEAD, threads=READ_THREADS, keep=()): self.layers, self.index, self.key, self.device = list(layers), index, key, torch.device(device) self.ahead, self.bytes_read = ahead, 0 + self.pin_failed = False # Layers in ``keep`` are read once and stay on the card; the others are streamed each time they run. self.keep = {i for i in keep if 0 <= i < len(self.layers)} self.order = [i for i in range(len(self.layers)) if i not in self.keep] self.pos = {i: p for p, i in enumerate(self.order)} 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 + self.pinned = self._wants_pinned() # 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 = [] + self.kind_params = {} for i, layer in enumerate(self.layers): if i in self.keep: self.kinds.append(None) @@ -89,13 +87,22 @@ def __init__(self, layers, index, key, device, ahead=READ_AHEAD, threads=READ_TH 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.kind_params.setdefault(kind, params) + try: + self._build_ring() + except (RuntimeError, MemoryError): + if not self.pinned: + raise + # The system would not lock that many pages (Windows limits locked memory and counts it against the + # commit limit): serve the same layers from ordinary host buffers. The bytes read and the result are + # the same; only the copy to the card is no longer asynchronous. + self.slots, self.slot_kind, self.free = [], [], {} + release = getattr(torch._C, '_host_emptyCache', None) + if release is not None: + release() # give back the locked pages the failed ring already held + self.pinned = False + self.pin_failed = True + self._build_ring() self.events = {} self.handles = [] for i, layer in enumerate(self.layers): @@ -109,6 +116,21 @@ def __init__(self, layers, index, key, device, ahead=READ_AHEAD, threads=READ_TH self.handles.append(layer.register_forward_pre_hook(self._before(i))) self.handles.append(layer.register_forward_hook(self._after(i))) + def _wants_pinned(self): + return self.device.type == 'cuda' + + def _build_ring(self): + self.slots = [] + self.slot_kind = [] + self.free = {} + for kind, params in self.kind_params.items(): + self.free[kind] = [] + for _ in range(self.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) + def _load_kept(self, i): """Read a kept layer's weights straight onto the card; it never leaves.""" layer = self.layers[i] diff --git a/freevideo_engine/image_gen/moss_pipeline.py b/freevideo_engine/image_gen/moss_pipeline.py index 5454eb69..6938ff5f 100644 --- a/freevideo_engine/image_gen/moss_pipeline.py +++ b/freevideo_engine/image_gen/moss_pipeline.py @@ -194,6 +194,7 @@ def _encode(module, folder, prompts, device, placement, stats): stats['encode_s'] = round(time.time() - started, 2) if stream is not None: stats['encoder_read_gib'] = round(stream.bytes_read / 2**30, 2) + stats['encoder_pinned'] = stream.pinned stream.close() return out @@ -312,6 +313,7 @@ def step(*args, **kwargs): paired.close() if stream is not None: stats['dit_read_gib'] = round(stream.bytes_read / 2**30, 2) + stats['dit_pinned'] = stream.pinned stream.close() scheduler.step = original_step torch.cuda.empty_cache() diff --git a/freevideo_engine/image_gen/worker.py b/freevideo_engine/image_gen/worker.py index ace2e0e9..82153a50 100644 --- a/freevideo_engine/image_gen/worker.py +++ b/freevideo_engine/image_gen/worker.py @@ -177,7 +177,8 @@ def hold(runner, idle_seconds=keep.IDLE_SECONDS): def drop(runner): - """Close the runner and hand its memory back; returns None for the caller's variable.""" + """Close the runner and hand its card memory back; returns None for the caller's variable. The caller still holds the + runner while this runs, so its locked host pages are only returned by release_memory(), called once the variable is None.""" runner.close() import gc gc.collect() @@ -187,6 +188,17 @@ def drop(runner): return None +def release_memory(): + """Collect, then return the card's and the host's cached memory: torch keeps freed locked (pinned) pages cached, and they stay charged to the process, so the next model loaded in this worker would find them still taken.""" + import gc + gc.collect() + torch = sys.modules.get('torch') + if torch is not None and torch.cuda.is_available(): + torch.cuda.empty_cache() + from ..torch_compat import empty_host_cache + empty_host_cache(torch) + + # The process the server's whole process tree starts from, in server mode (see server_mode); None on the desktop. SERVER_ROOT = None # In server mode the worker takes the installation's GPU lease itself, for each picture and each model load, and holds @@ -336,6 +348,7 @@ def send(**row): # A light warm-up only reads files ahead: it neither loads nor drops a model. if load and runner is not None and runner_model != model: runner = drop(runner) + release_memory() if load and runner is None: # No progress rows: nothing on the page is waiting for this. runner = factories.get(model, factory)(pack_dir, device) @@ -345,6 +358,7 @@ def send(**row): print('image worker warm-up failed: %s' % type(error).__name__, file=sys.stderr, flush=True) if runner is not None and not getattr(runner, 'at_boundary', lambda: True)(): runner = drop(runner) + release_memory() wait, crowding = idle_wait(runner, value.get('keep_seconds'), idle_seconds, at_least=max(keep.WARM_SECONDS, until - time.monotonic())) continue @@ -365,6 +379,7 @@ def progress(stage, fraction): if runner is not None and runner_model != model: # One model's weights at a time on the card. runner = drop(runner) + release_memory() if runner is None: context.timing.enter('load') runner = factories.get(model, factory)(pack_dir, device, progress=progress) @@ -468,11 +483,7 @@ def generate(seed): except Exception as error: print('image runner close failed: %s' % type(error).__name__, file=sys.stderr, flush=True) runner = None - import gc - gc.collect() - torch = sys.modules.get('torch') - if torch is not None and torch.cuda.is_available(): - torch.cuda.empty_cache() + release_memory() with inbox.mutex: inbox.busy = False if result is not None: diff --git a/freevideo_engine/installation_diagnostics.py b/freevideo_engine/installation_diagnostics.py index b8a186c5..b2661506 100644 --- a/freevideo_engine/installation_diagnostics.py +++ b/freevideo_engine/installation_diagnostics.py @@ -1,5 +1,6 @@ """Collect the current installation's evidence into a local, redacted report.""" import json +import re from pathlib import Path from .long_paths import io_path, resolved, plain_data, plain_errors @@ -40,7 +41,7 @@ def collect(root, since): # Python and Git downloads in the setup run, and ComfyUI dependency # preparation in launcher/host-runs. The command output remains in the # local manual bundle. - package_attempts = [] + package_attempts, native_tls_sources = [], [] folders = [run] host_root = root / 'launcher' / 'host-runs' if host_root.is_dir(): @@ -51,9 +52,11 @@ def collect(root, since): if folder != run and folder.stat().st_mtime < since - 1: continue package_attempts += source_failures(folder / 'network.jsonl') + native_tls_sources += native_tls_fallbacks(folder / 'network.jsonl') except OSError: continue - return plain_data(dict(state=state, samples=rows, package_attempts=package_attempts[-16:])) + return plain_data(dict(state=state, samples=rows, package_attempts=package_attempts[-16:], + native_tls_fallback=list(dict.fromkeys(native_tls_sources))[-8:])) except (OSError, ValueError, KeyError, TypeError): return {} @@ -82,6 +85,29 @@ def source_failures(path): return rows[-16:] +def native_tls_fallbacks(path): + """The names of the sources where setup retried a download with the system certificate store. + + Only the source name is read, and only as a short lowercase word: nothing else of the event is kept.""" + with io_path(path).open('rb') as stream: + size = stream.seek(0, 2) + stream.seek(max(0, size - 256 * 1024)) + lines = stream.read(256 * 1024).splitlines() + if size > 256 * 1024: + lines = lines[1:] + names = [] + for line in lines: + try: + item = d.mapping(json.loads(line)) + except (ValueError, UnicodeError): + continue + action, source = item.get('action'), item.get('source') + if (isinstance(action, str) and action.endswith('-system-certificates') + and isinstance(source, str) and re.fullmatch(r'[a-z0-9_.-]{1,40}', source)): + names.append(source) + return names + + def _errors(rows): result = [] for row in d.sequence(rows)[:16]: @@ -161,6 +187,12 @@ def enrich(result, value): if key in row and (key == 'returncode' or isinstance(row[key], (str, int, float, bool))): item[key] = row[key] result['errors'].append(item) + # Only a fixed phrase and the source name: the certificate, its issuer and the machine stay out of the report. + notes = [dict(note='native-tls fallback used', source=name) + for name in d.sequence(value.get('native_tls_fallback'))[:8] + if isinstance(name, str) and re.fullmatch(r'[a-z0-9_.-]{1,40}', name)] + if notes: + result['notes'] = notes result['diagnostic_revision'] = 6 return result diff --git a/freevideo_engine/jobs_journal.py b/freevideo_engine/jobs_journal.py index 55c6c518..8c7b5bf8 100644 --- a/freevideo_engine/jobs_journal.py +++ b/freevideo_engine/jobs_journal.py @@ -6,6 +6,7 @@ import json import logging import math +import os import re import threading import time @@ -63,9 +64,43 @@ def _recent(rows, now): return kept[-LIMIT:] +_SWEPT = set() + + +def _sweep(root): + """Once per process and output folder: a row naming a saved video that is no longer in the library goes. This + clears rows left by deletions made before the record forgot them. Nothing is dropped while the library folder + itself is missing (an unplugged drive) or any check fails other than "not found", and a row without a video is kept. Caller holds _LOCK. Never raises.""" + key = str(root) + if key in _SWEPT: + return + _SWEPT.add(key) + try: + library = io_path(root / 'FreeVideo') + if not library.is_dir() or not io_path(root / NAME).is_file(): + return + os.listdir(library) # a library that cannot be listed is not known to be empty + rows = _rows(root) + kept = [] + for row in rows: + if 'result' in row: + try: + (library / row['result'] / 'video.mp4').stat() + except FileNotFoundError: + continue + except OSError: + return # no permission, a drive going away: the answer is open, so nothing is dropped + kept.append(row) + if len(kept) != len(rows): + monitoring.save(root / NAME, dict(jobs=kept)) + except Exception: + _LOG.warning('The finished-job record could not be updated.', exc_info=True) + + def read(*, root): """The recorded jobs, oldest first; an unreadable file gives an empty list.""" with _LOCK: + _sweep(root) return _recent(_rows(root), time.time()) @@ -85,6 +120,21 @@ def append(row, *, root): _LOG.warning('The finished-job record could not be written.', exc_info=True) +def forget(results, *, root): + """A saved video the user deleted for good: the rows naming it go, so no line of the record points at it. Never raises.""" + try: + results = {value for value in results if isinstance(value, str)} + if not results or not io_path(root / NAME).is_file(): + return + with _LOCK: + rows = _rows(root) + kept = [row for row in rows if row.get('result') not in results] + if len(kept) != len(rows): + monitoring.save(root / NAME, dict(jobs=kept)) + except Exception: + _LOG.warning('The finished-job record could not be updated.', exc_info=True) + + def mark_interrupted(*, root): """At start-up: a row still queued or running belongs to a process that is gone.""" try: diff --git a/freevideo_engine/launcher/Main.qml b/freevideo_engine/launcher/Main.qml index f28e5c35..1dea3632 100644 --- a/freevideo_engine/launcher/Main.qml +++ b/freevideo_engine/launcher/Main.qml @@ -147,7 +147,7 @@ ApplicationWindow { // On a Mac, a disk problem is fixed by choosing another disk, not by reporting a fault. // Not a fault: a video is still generating, and the one way on is Retry installation. function reportOpened(error, title) { return s.report_opened === error + "\u0001" + title } - readonly property bool notAFault: s.failure.kind === "setup-busy" || s.failure.kind === "update-busy" + readonly property bool notAFault: s.failure.kind === "setup-busy" || s.failure.kind === "update-busy" || s.failure.kind === "busy" readonly property bool diskFailure: !!disk && (s.failure.kind || "").indexOf("disk") === 0 readonly property bool updateOffered: s.update.engine || (!!s.update.candidate && ["available", "downloading", "ready", "error", "cancelled"].indexOf(s.update.status) >= 0) // An engine update needs no download; offer it as the way to launch. diff --git a/freevideo_engine/macos_compute.py b/freevideo_engine/macos_compute.py index fcd0bf7c..1e2758a1 100644 --- a/freevideo_engine/macos_compute.py +++ b/freevideo_engine/macos_compute.py @@ -20,6 +20,22 @@ RESIDENT_LIMIT = 50 RETENTION_HEADROOM = 4 * GiB GROUPS = (56, 28, 14, 8, 4) +# A sampling worker stops itself below this much available RAM, and a fresh +# worker with the smallest partitions retries once. The request-level guard +# must act only after that: a tripwire at the same 1 GiB ended a request +# 77 minutes in, at 0.76 GiB, before the worker's recoverable stop could run. +WORKER_FLOOR_BYTES = GiB +FLOOR_FAILURE = 'physical RAM emergency floor' +ENGINE_TRIPWIRE_BYTES = GiB * 3 // 4 +SAMPLING_PHASES = ('first-pass', 'refinement') + + +def request_floor(phase, tripwire=ENGINE_TRIPWIRE_BYTES, floor=GiB): + """Request-level floor for the engine child: lower only while a sampling worker runs. + + That worker checks the 1 GiB floor itself and can retry once; decoding and + the other stages cannot recover, so they keep the full floor.""" + return tripwire if phase in SAMPLING_PHASES else floor def working_bytes(tokens, group, *, ff_chunk=4096, window_bytes=1 << 29, frames=72): diff --git a/freevideo_engine/macos_generate.py b/freevideo_engine/macos_generate.py index c558d99c..72003f6a 100644 --- a/freevideo_engine/macos_generate.py +++ b/freevideo_engine/macos_generate.py @@ -23,6 +23,21 @@ from .paths import data_root GiB = 2**30 +from .macos_compute import ENGINE_TRIPWIRE_BYTES, request_floor + + +def engine_floor(receipt, resource): + """A floor read afresh at each guard sample from the stage controller's receipt. + + No readable receipt (not yet written, half written) keeps the full floor.""" + def floor(): + try: + phase = json.loads(Path(receipt).read_text(encoding='utf-8')).get('phase') + except (OSError, ValueError, AttributeError): + phase = None + return request_floor(phase, resource.get('engine_tripwire_bytes', ENGINE_TRIPWIRE_BYTES), + resource['emergency_floor_bytes']) + return floor def policy(args, memory=None): @@ -70,7 +85,7 @@ def amount(name, default): encoder_bytes=allocator, ram_budget_bytes=capacity if getattr(args, 'ram_gib', None) is not None else working, ram_budget_is_estimate=getattr(args, 'ram_gib', None) is None, - emergency_floor_bytes=GiB, query_chunk=128, ff_chunk=256, projection_chunk=256, + emergency_floor_bytes=GiB, engine_tripwire_bytes=ENGINE_TRIPWIRE_BYTES, query_chunk=128, ff_chunk=256, projection_chunk=256, weight_decoder='metal', encoder_weight_decoder='metal', cpu_operator_fallback=False, sampling_lifetime='auto', scope='Live unified-memory bounds and eligible cross-pass weight retention; not proof of workload capacity.') @@ -236,7 +251,8 @@ def execute(value, name, module='freevideo_engine.macos_generate'): return child([sys.executable, '-m', module, '--request', str(request)], env, descriptor, output.with_suffix('.' + name + '.log'), ram_budget_bytes=resource['ram_budget_bytes'], - minimum_available_bytes=resource['emergency_floor_bytes'], + minimum_available_bytes=(engine_floor(output.with_suffix('.engine.json'), resource) + if name == 'engine' else resource['emergency_floor_bytes']), ram_budget_is_estimate=resource['ram_budget_is_estimate']) if adapters: report['phase'] = 'lora' diff --git a/freevideo_engine/macos_runtime.py b/freevideo_engine/macos_runtime.py index 57eeecf3..ae08c090 100644 --- a/freevideo_engine/macos_runtime.py +++ b/freevideo_engine/macos_runtime.py @@ -13,6 +13,7 @@ import time from . import frame_preview +from .macos_compute import FLOOR_FAILURE, WORKER_FLOOR_BYTES from .macos_conditions import BLOCK_SECONDS_SCOPE, runtime_conditions from .sampling_progress import SamplingProgress @@ -560,8 +561,8 @@ def append(owner, duration): previous_kernel_calls = {name: dict(counts) for name, counts in getattr(self, 'kernel_stats', {}).items()} def host_guard(module, inputs): - if system_memory()['available_bytes'] < 2**30: - raise MemoryError('MPS generation reached the 1 GiB physical RAM emergency floor') + if system_memory()['available_bytes'] < WORKER_FLOOR_BYTES: + raise MemoryError('MPS generation reached the 1 GiB ' + FLOOR_FAILURE) guards = [module.register_forward_pre_hook(host_guard, prepend=True) for module, _, _, _ in self.specs] try: with torch.no_grad(): diff --git a/freevideo_engine/macos_stages.py b/freevideo_engine/macos_stages.py index 43b1328d..523d5dc1 100644 --- a/freevideo_engine/macos_stages.py +++ b/freevideo_engine/macos_stages.py @@ -14,6 +14,7 @@ from . import processes, step_resume from .locking import LOCK_ENV, runtime_lock +from .macos_compute import FLOOR_FAILURE from .monitoring import save @@ -43,11 +44,16 @@ def read_receipt(receipt): def memory_exhausted(stage, observed): - """A sampling pass that stopped because MPS reached its allocator limit or Metal failed a command buffer.""" - # The physical RAM floor protects the whole machine, and the outer guard also ends the request. + """A sampling pass that stopped because MPS reached its allocator limit, Metal failed a command + buffer or available RAM fell below the worker's own floor. + + A fresh process with the smallest partitions and no retained layers retries once, keeping a + finished first pass. Its own floor check and the request-level tripwire (lower than the + worker's floor) still end a pass that cannot fit.""" message = str(observed.get('error_message', '')) return (stage in ('first-pass', 'refinement') and observed.get('success') is False - and ('MPS backend out of memory' in message or METAL_FAILURE in message)) + and ('MPS backend out of memory' in message or METAL_FAILURE in message + or FLOOR_FAILURE in message)) def joined_admission(engine, value): diff --git a/freevideo_engine/network.py b/freevideo_engine/network.py index 4b153961..cb479d38 100644 --- a/freevideo_engine/network.py +++ b/freevideo_engine/network.py @@ -805,10 +805,24 @@ def package_environment(network, family, name, environ=None, *, route=None, retr return env +# Keep in sync with the certificate words in slow_download_failure, fv_certificate_failure +# (scripts/bootstrap_linux.sh) and Test-FreeVideoCertificateFailure (windows_bootstrap.ps1). +_CERTIFICATE_KEYWORDS = ( + 'certificate verify failed', 'certificate_verify_failed', + 'invalid peer certificate', 'unknown issuer', +) + + +def _certificate_failure(detail): + detail = detail.lower() + return any(word in detail for word in _CERTIFICATE_KEYWORDS) + + def download_command(network, family, run, env=None, *, category=None, extra_sources=(), notice=None, reorder=None): """Run a source/route callback with the same bounded policy for uv and pip. - Callbacks receive (source, route, retry_mode); each builds its child env from + Callbacks receive (source, route, retry_mode) and a native_tls keyword, True only for + the single same-route retry after a certificate failure; each builds its child env from the original environment, so our fast defaults never become user overrides. """ category = category or family @@ -856,8 +870,30 @@ def download_command(network, family, run, env=None, *, category=None, extra_sou result='success', attempts=len(attempts)-round_start+1) return result except (RuntimeError, subprocess.CalledProcessError) as error: - attempt = dict(_package_attempt(error, name, route, source_host(family, name, env), - time.monotonic() - started), retry_mode=retry_mode) + elapsed = time.monotonic() - started + detail, _ = _package_failure(error) + native_retry = False + # A certificate this machine's system store trusts but uv's bundled roots do not + # (an antivirus or proxy that inspects HTTPS): ask the same route once more + # with the system store. Verification stays on; the first error is kept. + if _certificate_failure(detail): + native_retry = True + event(network, category=category, source=name, route=route, + action=operation + '-system-certificates', **retry_details) + try: + result = run(name, route, retry_mode, native_tls=True) + source_health(network, family, name, True) + route_health(network, family, name, route) + if retry_mode == 'patient': + event(network, category=category, action='download-round-result', retry_mode=retry_mode, + result='success', attempts=len(attempts)-round_start+1) + return result + except (RuntimeError, subprocess.CalledProcessError): + pass + attempt = dict(_package_attempt(error, name, route, source_host(family, name, env), elapsed), + retry_mode=retry_mode) + if native_retry: + attempt['system_certificates_tried'] = True attempts.append(attempt) event(network, category=category, source=name, route=route, action=operation + '-failed', error_type=attempt['error_type'], returncode=attempt['returncode'], @@ -888,8 +924,10 @@ def download_command(network, family, run, env=None, *, category=None, extra_sou def package_command(network, family, run, env=None, *, notice=None): - def attempt(name, route, retry_mode): + def attempt(name, route, retry_mode, native_tls=False): attempt_env = package_environment(network, family, name, env, route=route, retry_mode=retry_mode) + if native_tls: + attempt_env['UV_NATIVE_TLS'] = '1' # Private markers retain per-source/route logs; no package configuration. attempt_env['FREEVIDEO_PACKAGE_SOURCE'] = name attempt_env['FREEVIDEO_PACKAGE_ROUTE'] = route @@ -1841,6 +1879,21 @@ def repository_missing_message(target): 'installation.' % Path(target).name) +def windows_store_retry(error): + """Whether a failed Git fetch is worth one more try with the Windows certificate store. + + A Git built with OpenSSL trusts only the certificates in its own bundle. A program that + inspects HTTPS traffic (security software, a company or school proxy) signs it with a root + that only the Windows store holds, so the browser works and Git reports an unknown issuer. + Git's other backend (Schannel) reads the Windows store; the check itself stays on. + """ + text = str(error).lower() + # Git's own wording is "SSL certificate OpenSSL verify result" in newer builds and "SSL certificate + # problem" in older ones; a Schannel Git already reads the store and names itself in its errors. + return (is_windows() and failure_reason(error)[0] == 'tls' and 'certificate' in text + and not any(word in text for word in ('schannel', 'sec_e_', 'crypt_e_'))) + + def clone(target, url, commit, *, sparse=None, run=None, network=None, env=None): """Fetch only the pinned commit, atomically; never reset existing checkouts. @@ -1951,8 +2004,23 @@ def execute(label, command): original = env env = dict(env, GIT_CONFIG_PARAMETERS=' '.join(filter(None, ( env.get('GIT_CONFIG_PARAMETERS', '').strip(), git_parameter('remote.origin.url=' + endpoint))))) + fetch = ['git', '-C', work, '-c', 'fetch.fsckObjects=true', 'fetch', '--depth=1', '--no-tags', 'origin', commit] try: - execute(target.name + '-fetch-' + name, ['git', '-C', work, '-c', 'fetch.fsckObjects=true', 'fetch', '--depth=1', '--no-tags', 'origin', commit]) + try: + execute(target.name + '-fetch-' + name, fetch) + except RuntimeError as first: + if not windows_store_retry(first): + raise + event(network, category='git', source=name, route=route, file=target.name, action='certificate-store-retry', + reason='windows-certificate-store') + try: + execute(target.name + '-fetch-windows-store-' + name, + fetch[:3] + ['-c', 'http.sslBackend=schannel'] + fetch[3:]) + except RuntimeError as second: + # A Git without that backend says so in words that say nothing about the + # download; the first error stays the one reported then. + unsupported = 'unsupported ssl backend' in str(second).lower() + raise second if failure_reason(second)[0] == 'tls' and not unsupported else first from None finally: env = original execute(target.name + '-checkout', ['git', '-C', work, 'checkout', '--detach', commit]) diff --git a/freevideo_engine/prompt_vlm/core.py b/freevideo_engine/prompt_vlm/core.py index 46785d5c..7ef00df1 100644 --- a/freevideo_engine/prompt_vlm/core.py +++ b/freevideo_engine/prompt_vlm/core.py @@ -101,6 +101,37 @@ def vision_mlp(self, x): return out +_gqa = {} + + +def expand_kv_heads(torch, device): + """True when grouped-query attention must be given expanded key/value heads on this card. + + With an empty mask (a prefill) Transformers calls SDPA with enable_gqa=True, which only the flash + kernel serves. A build without it (PyTorch's Windows builds have none) runs the math kernel, which + holds the whole score matrix: 3.6 GiB for 3463 tokens, growing with the square of the prompt, so an + 8 GB card ran out of memory inside the first forward pass. With the heads expanded first, the + memory-efficient and cuDNN kernels serve the call in 28 MiB. Where flash serves it, nothing changes. + The answer is read once per process and card from PyTorch's own check for flash attention on a tiny + grouped call (it respects the build, the card, the dtype and the switches), and applied by the caller.""" + if device in _gqa: + return _gqa[device] + try: + q = torch.zeros(1, 4, 16, 128, dtype=torch.bfloat16, device=device) + kv = torch.zeros(1, 2, 16, 128, dtype=torch.bfloat16, device=device) + params = torch.backends.cuda.SDPAParams(q, kv, kv, None, 0., True, True) + _gqa[device] = not torch.backends.cuda.can_use_flash_attention(params, False) + except (AttributeError, TypeError, RuntimeError): + _gqa[device] = False # a torch without this check keeps the call as it was + return _gqa[device] + + +def use_expanded_kv_heads(): + """Make Transformers' SDPA attention expand the key/value heads itself (its own repeat_kv).""" + from transformers.integrations import sdpa_attention + sdpa_attention.use_gqa_in_sdpa = lambda attention_mask, key, value: False + + def prepare(model, each_layer=None): """Transform before accelerate installs placement/offload hooks. diff --git a/freevideo_engine/prompt_vlm/rules.py b/freevideo_engine/prompt_vlm/rules.py index 44bac87a..a9753671 100644 --- a/freevideo_engine/prompt_vlm/rules.py +++ b/freevideo_engine/prompt_vlm/rules.py @@ -528,7 +528,8 @@ def parse_json(text): # Each picture model gets the rewriting its own authors publish: MiniMax's caption expansion for H3 Image (its # edit variant when there are reference pictures), Qwen-Image's prompt polish for Qwen (its edit variant with # references). The pictures go in as in upload order, as the generation reads them. -IMAGE_MODELS = {'minimax-h3-image': 16, 'qwen-image-2.1-turbo': 4} # model: reference pictures it takes +# model: reference pictures it takes. MOSS-Image takes none and is rewritten with Qwen-Image's text rewriting (image_style). +IMAGE_MODELS = {'minimax-h3-image': 16, 'qwen-image-2.1-turbo': 4, 'moss-image-sft': 0} # The published instructions alone are 3.4k-7.7k tokens; 16 pictures at image_tokens(16) add 4.8k more. IMAGE_INPUT_TOKENS = 14000 PROSE_PICTURE = re.compile(r'(?\w])') diff --git a/freevideo_engine/prompt_vlm/worker.py b/freevideo_engine/prompt_vlm/worker.py index ad7cbc67..4b44daef 100644 --- a/freevideo_engine/prompt_vlm/worker.py +++ b/freevideo_engine/prompt_vlm/worker.py @@ -426,6 +426,12 @@ def place(budget): raise ValueError('ram_space') model = dispatch_model(model, mapping) device = 'cuda:%d' % card if any(v == card for v in mapping.values()) else 'cpu' + if torch.cuda.is_available(): + # Windows builds have no flash attention: keep the prefill off the math kernel (see core.expand_kv_heads). + expanded = core.expand_kv_heads(torch, 'cuda:%d' % card) + if expanded: + core.use_expanded_kv_heads() + stats['attention_kv_heads'] = 'expanded' if expanded else 'grouped' stats.update(load_seconds=time.monotonic() - loading, placement_seconds=time.monotonic() - placing, accelerations=['merged_gate_up', 'per_image_sdpa', 'chunked_vision_mlp', 'merged_qkv'], backend='freetoken-portable-ops+transformers', diff --git a/freevideo_engine/release_notes.json b/freevideo_engine/release_notes.json index 44fdcb61..23390b27 100644 --- a/freevideo_engine/release_notes.json +++ b/freevideo_engine/release_notes.json @@ -1,40 +1,77 @@ { "schema": 1, - "product_version": "0.6.6", - "important": false, + "product_version": "0.6.7", + "important": true, "en": { - "summary": "0.6.6 gives more control over MOSS-Image pictures and makes them faster on smaller graphics cards, lets a reference video lend only its layout, explains more failures with a next step, and makes the Edit view easier to use in narrow windows and view switches smoother on slower computers.", + "summary": "0.6.7 improves prompt enhancement for MOSS-Image, lets merged videos be upscaled, offers lossless sound on export, gives videos, audio and dropdowns FreeVideo's own play bar and menu, makes the Edit view smoother, explains more failures, and cleans up more thoroughly when a work is deleted.", "changes": [ - "More control over picture layout: draw boxes with Layout in the Image view and give each one a line of description to place each part of the picture. Words in quotation marks are written into the picture.", - "MOSS-Image is faster on smaller graphics cards: a 1024-pixel picture on a 12 GB card is made much faster, with exactly the same result as before.", - "A reference video can lend only its layout: with Composition only, the new video follows the layout of the reference video, not its motion or colours.", - "Original sound plays on phones: an MP3 used as the original sound stays an MP3 in the finished video, so phones and system players can play it.", - "Frames saved in the Edit view also go to the output folder: with Also save pictures to the output folder on in Settings, a frame saved in the Edit view is copied there as well.", - "More failures explain what happened and what to do next, including a task that gets no answer after it is submitted, a picture the assistant cannot start and a Git error during setup.", - "Smoother on slower computers: with fewer processor cores or slow view switches, FreeVideo turns off the switch animation, and the library and short clips play more smoothly.", - "The Edit view is easier to use in a narrow window: the preview and buttons no longer cover each other, and the tracks and the update bar are shown in full.", - "Dialogs and tips are easier to read: their text is no longer disturbed by what lies behind them, and a hover tip appears only when a name is cut short.", - "Fields are easier to fill in: a number typed outside its range is brought back into range with a note under the field. An emptied LoRA strength returns to the strength in use.", - "Tutorial additions: how to export at 48 or 60 fps, and how to use MOSS-Image layout boxes." + "Prompt enhancement for MOSS-Image: with MOSS-Image, prompts are enhanced the way Qwen-Image's are; when the service refuses an enhancement request, the cause is named.", + "Prompt enhancement is steadier on smaller graphics cards: on cards with less video memory, such as 8 GB, enhancing a prompt no longer fails for lack of video memory.", + "Steadier use of Qwen-Image and MOSS-Image together: on a 12 GB card, making a picture with Qwen-Image and then switching to MOSS-Image no longer fails for lack of memory.", + "Upscale takes merged videos: a merged video can be upscaled to the largest size, and a video that cannot be enlarged says why.", + "Sound format on export: the export window adds a Sound option beside the frame rate, Compatible or Lossless. Lossless exports a .mov with uncompressed sound; it is not available with Audio only or for a range without sound.", + "One play bar and one menu: videos and audio use FreeVideo's own play bar, where a click plays or pauses a video and long audio and video can be dragged to any point; every dropdown in FreeVideo pages opens the FreeVideo menu instead of the system list.", + "A smoother Edit view: the preview has more room, the Media, LoRA and Advanced windows are no longer covered by the timeline, the buttons stay on one line in a narrow window, and Escape during a replace-audio step cancels only the replacement.", + "Over-long prompts are explained first: in the Image view and the Edit view, a prompt over the engine's limit says by how much before it is submitted, instead of being refused afterwards.", + "More failures explain what happened: a picture failure names the step where it failed, and a picture moved or deleted in the Edit view is named with a way to import it again.", + "More accurate graphics card notices: the laptop GeForce RTX 2050 is no longer listed as an unsupported card, and an old driver shows the driver update notice.", + "Steadier on a Mac with tight memory: when a Mac runs short of memory midway, generation retries once in a way that uses less memory instead of stopping.", + "Cleaner deletion: related traces in pictures, uploads, thumbnails and logs are removed, and deleted videos no longer appear in the finished-task record." ] }, "zh": { - "summary": "0.6.6 让 MOSS-Image 出图更可控,在显存较小的显卡上也更快;参考视频可以只沿用构图;更多失败会说明原因和下一步;窄窗口下的剪辑视图和低配电脑上的视图切换更顺畅。", + "summary": "0.6.7 改进 MOSS-Image 的提示词增强,合并后的视频可以放大,导出可选无损声音;播放条和下拉菜单统一为 FreeVideo 自己的样式,剪辑视图更顺手,更多失败会说明原因,删除作品时清理得更干净。", "changes": [ - "图片构图更可控:在图像视图中用“布局”画框,并为每个框写一句描述,即可指定画面中各部分的位置。引号中的文字会直接写进画面。", - "MOSS-Image 在显存较小的显卡上更快:12 GB 显卡生成 1024 像素的图片明显加快,画面与之前完全相同。", - "参考视频可以只沿用构图:选择“仅参考构图”时,生成的视频沿用参考视频的构图,不沿用其动作和颜色。", - "MP3 原声可在手机上直接播放:作为原声的 MP3 在成片中保持原样,手机和系统播放器均可直接播放。", - "剪辑视图保存的画面也会存入 output 文件夹:开启设置中的“同时将图片保存到 output 文件夹”后,在剪辑视图中保存的画面同样会复制到 output 文件夹。", - "更多失败会说明原因和下一步:任务提交后无应答、助手请求的图片无法开始、安装时 Git 出错,都会说明发生了什么以及接下来该怎么做。", - "低配电脑上更流畅:处理器核心较少或视图切换较慢时,FreeVideo 会自动关闭切换动画,作品库和短视频播放更加顺畅。", - "窄窗口下的剪辑视图更易用:预览与按钮不再互相遮挡,轨道和更新栏均完整显示。", - "对话框和提示更易阅读:对话框与提示的文字不再受背景内容干扰,悬停提示只在名称显示不全时出现。", - "输入更省心:数字框中输入超出范围的值时,会自动改回范围内并给出提示。清空 LoRA 强度后,会恢复为正在使用的强度。", - "教程补充:新增导出 48 或 60 fps 视频的方法,以及 MOSS-Image 布局框的用法。" + "提示词增强适配 MOSS-Image:使用 MOSS-Image 时,提示词按 Qwen-Image 的改写方式增强;改写请求被服务拒绝时,会说明原因。", + "提示词增强在显存较小的显卡上更稳:在 8 GB 等显存较小的显卡上,提示词增强不再因显存不足而失败。", + "先后使用 Qwen-Image 和 MOSS-Image 更稳:12 GB 显存的显卡上,先用 Qwen-Image 出图再换 MOSS-Image,不再因内存不足而失败。", + "视频放大支持合并后的视频:合并后的视频可以放大到最大尺寸;无法放大的视频会说明原因。", + "导出可选声音格式:导出窗口在帧率旁新增“声音”选项,可选“通用”或“无损”。选择“无损”时导出为 .mov 文件,声音不压缩;内容选“只声音”或所选范围没有声音时不可选。", + "播放条和下拉菜单统一:视频和音频使用 FreeVideo 自己的播放条,点击视频即可播放或暂停,长音频和视频可拖动进度;页面中的所有下拉选择都使用 FreeVideo 菜单,不再弹出系统列表。", + "剪辑视图更顺手:预览更宽敞,“素材”“LoRA”“高级选项”窗口不再被时间线遮住,窄窗口下按钮保持在一行,替换声音时按 Esc 只取消替换。", + "提示词过长时先说明:图像视图和剪辑视图中,超过引擎限制的提示词在提交前就会提示超出多少,不再提交后才被拒绝。", + "更多失败会说明原因:图片失败会指出出错的步骤;剪辑中的图片被移动或删除时,会说明并给出重新导入的办法。", + "显卡提示更准确:笔记本 GeForce RTX 2050 不再被列为不支持的显卡,驱动过旧时会显示更新驱动的提示。", + "Mac 内存紧张时更稳:Mac 生成中途内存不足时,会自动换一种更省内存的方式重试一次,不再直接停止。", + "删除作品清理更干净:图片、上传文件、缩略图和日志中的相关残留一并清除,已删除的视频不再出现在已完成任务记录中。" ] }, "history": [ + { + "product_version": "0.6.6", + "en": { + "summary": "0.6.6 gives more control over MOSS-Image pictures and makes them faster on smaller graphics cards, lets a reference video lend only its layout, explains more failures with a next step, and makes the Edit view easier to use in narrow windows and view switches smoother on slower computers.", + "changes": [ + "More control over picture layout: draw boxes with Layout in the Image view and give each one a line of description to place each part of the picture. Words in quotation marks are written into the picture.", + "MOSS-Image is faster on smaller graphics cards: a 1024-pixel picture on a 12 GB card is made much faster, with exactly the same result as before.", + "A reference video can lend only its layout: with Composition only, the new video follows the layout of the reference video, not its motion or colours.", + "Original sound plays on phones: an MP3 used as the original sound stays an MP3 in the finished video, so phones and system players can play it.", + "Frames saved in the Edit view also go to the output folder: with Also save pictures to the output folder on in Settings, a frame saved in the Edit view is copied there as well.", + "More failures explain what happened and what to do next, including a task that gets no answer after it is submitted, a picture the assistant cannot start and a Git error during setup.", + "Smoother on slower computers: with fewer processor cores or slow view switches, FreeVideo turns off the switch animation, and the library and short clips play more smoothly.", + "The Edit view is easier to use in a narrow window: the preview and buttons no longer cover each other, and the tracks and the update bar are shown in full.", + "Dialogs and tips are easier to read: their text is no longer disturbed by what lies behind them, and a hover tip appears only when a name is cut short.", + "Fields are easier to fill in: a number typed outside its range is brought back into range with a note under the field. An emptied LoRA strength returns to the strength in use.", + "Tutorial additions: how to export at 48 or 60 fps, and how to use MOSS-Image layout boxes." + ] + }, + "zh": { + "summary": "0.6.6 让 MOSS-Image 出图更可控,在显存较小的显卡上也更快;参考视频可以只沿用构图;更多失败会说明原因和下一步;窄窗口下的剪辑视图和低配电脑上的视图切换更顺畅。", + "changes": [ + "图片构图更可控:在图像视图中用“布局”画框,并为每个框写一句描述,即可指定画面中各部分的位置。引号中的文字会直接写进画面。", + "MOSS-Image 在显存较小的显卡上更快:12 GB 显卡生成 1024 像素的图片明显加快,画面与之前完全相同。", + "参考视频可以只沿用构图:选择“仅参考构图”时,生成的视频沿用参考视频的构图,不沿用其动作和颜色。", + "MP3 原声可在手机上直接播放:作为原声的 MP3 在成片中保持原样,手机和系统播放器均可直接播放。", + "剪辑视图保存的画面也会存入 output 文件夹:开启设置中的“同时将图片保存到 output 文件夹”后,在剪辑视图中保存的画面同样会复制到 output 文件夹。", + "更多失败会说明原因和下一步:任务提交后无应答、助手请求的图片无法开始、安装时 Git 出错,都会说明发生了什么以及接下来该怎么做。", + "低配电脑上更流畅:处理器核心较少或视图切换较慢时,FreeVideo 会自动关闭切换动画,作品库和短视频播放更加顺畅。", + "窄窗口下的剪辑视图更易用:预览与按钮不再互相遮挡,轨道和更新栏均完整显示。", + "对话框和提示更易阅读:对话框与提示的文字不再受背景内容干扰,悬停提示只在名称显示不全时出现。", + "输入更省心:数字框中输入超出范围的值时,会自动改回范围内并给出提示。清空 LoRA 强度后,会恢复为正在使用的强度。", + "教程补充:新增导出 48 或 60 fps 视频的方法,以及 MOSS-Image 布局框的用法。" + ] + } + }, { "product_version": "0.6.5", "en": { diff --git a/freevideo_engine/windows_bootstrap.ps1 b/freevideo_engine/windows_bootstrap.ps1 index f0b838ba..423fe43c 100644 --- a/freevideo_engine/windows_bootstrap.ps1 +++ b/freevideo_engine/windows_bootstrap.ps1 @@ -237,3 +237,9 @@ function Get-FreeVideoUv { } throw "uv download failed on all sources. Partial files retained. See $LogPath and retry." } + +function Test-FreeVideoCertificateFailure { + param([string]$Detail) + # Match network._certificate_failure and slow_download_failure certificate keywords. + return ($Detail -match 'certificate verify failed|certificate_verify_failed|invalid peer certificate|unknown issuer') +} diff --git a/freevideo_engine/work_upscale.py b/freevideo_engine/work_upscale.py index 7a353d56..53889782 100644 --- a/freevideo_engine/work_upscale.py +++ b/freevideo_engine/work_upscale.py @@ -11,7 +11,7 @@ from pathlib import Path FACTOR = 1.5 -NOT_A_WORK = ('Choose a finished FreeVideo video to upscale', '请选择一个已完成的 FreeVideo 视频来放大。') +from .frame_upscale import NotUpscalable def size(width, height): @@ -23,28 +23,35 @@ def size(width, height): def work_request(output_directory, relative): - """A finished, non-preview FreeVideo work in this output folder: (video, saved state).""" + """A finished, non-preview FreeVideo work in this output folder: (video, saved state). One step needs the + prompt and seed saved with the work, so a video without a saved request is refused.""" if not isinstance(relative, str) or not relative.strip(): - raise ValueError(NOT_A_WORK[0]) + raise NotUpscalable('outside') output_root = Path(output_directory).resolve() video = (output_root / relative).resolve() try: video.relative_to(output_root / 'FreeVideo') except ValueError: - raise ValueError(NOT_A_WORK[0]) from None + raise NotUpscalable('outside') from None + if not video.is_file(): + raise NotUpscalable('missing') path = video.parent / 'comfy-request.json' try: state = json.loads(path.read_text(encoding='utf-8')) if path.is_file() else {} except (OSError, ValueError): state = {} geometry = state.get('geometry') if isinstance(state, dict) else None - if (not isinstance(state, dict) or state.get('status') != 'complete' or state.get('preview') - or Path(state.get('output', '')).resolve() != video or not isinstance(geometry, dict) - or geometry.get('fps') != 24 or size(geometry.get('width'), geometry.get('height')) is None - or type(state.get('seed')) is not int): - raise ValueError(NOT_A_WORK[0]) - if not video.is_file(): - raise ValueError(NOT_A_WORK[0]) + if (not isinstance(state, dict) or not isinstance(geometry, dict) or type(state.get('seed')) is not int + or Path(state.get('output') or '').resolve() != video): + raise NotUpscalable('no_request') + if state.get('status') != 'complete': + raise NotUpscalable('unfinished') + if state.get('preview'): + raise NotUpscalable('preview') + if geometry.get('fps') != 24: + raise NotUpscalable('fps') + if size(geometry.get('width'), geometry.get('height')) is None: + raise NotUpscalable('size_step') return video, state @@ -62,19 +69,23 @@ def source(path): import av path = Path(path).expanduser().resolve() if path.suffix.lower() != '.mp4' or not path.is_file(): - raise ValueError(NOT_A_WORK[0]) + raise NotUpscalable('missing') try: with av.open(str(path)) as container: if len(container.streams.video) != 1 or not container.streams.audio: - raise ValueError(NOT_A_WORK[0]) + raise NotUpscalable('streams') stream = container.streams.video[0] rate = stream.average_rate or stream.guessed_rate width, height = stream.codec_context.width, stream.codec_context.height frames = sum(1 for _ in container.demux(stream) if _.size) except (av.error.FFmpegError, OSError) as error: - raise ValueError(NOT_A_WORK[0]) from error - if rate is None or Fraction(rate) != 24 or size(width, height) is None or frames <= 0: - raise ValueError(NOT_A_WORK[0]) + raise NotUpscalable('missing') from error + if frames <= 0: + raise NotUpscalable('missing') + if rate is None or Fraction(rate) != 24: + raise NotUpscalable('fps') + if size(width, height) is None: + raise NotUpscalable('size_step') return dict(output=str(path), sha256=_digest(path), bytes=path.stat().st_size, width=width, height=height, frames=frames, fps=24) @@ -130,7 +141,7 @@ def _frames(path, width, height, count): pixels[index] = image index += 1 if not index: - raise ValueError(NOT_A_WORK[0]) + raise NotUpscalable('missing') pixels[index:] = pixels[index - 1] return pixels, index diff --git a/scripts/bootstrap_linux.sh b/scripts/bootstrap_linux.sh index 9adf3448..77ff7b84 100644 --- a/scripts/bootstrap_linux.sh +++ b/scripts/bootstrap_linux.sh @@ -16,6 +16,12 @@ esac fv_note() { printf 'FreeVideo: %s\n' "$*" >&2; } fv_fail() { fv_note "$*"; return 1; } +# Match network._certificate_failure and slow_download_failure certificate keywords. +fv_certificate_failure() { + local detail="${1,,}" + [[ "$detail" =~ certificate\ verify\ failed|certificate_verify_failed|invalid\ peer\ certificate|unknown\ issuer ]] +} + # Match network.slow_download_failure: unavailable artifacts and local errors # may try another source, but must not earn a longer download round. fv_slow_download_failure() { @@ -347,6 +353,30 @@ fv_install_python() ( fv_fail "Could not retain Python installation output. Check $FREEVIDEO_BOOTSTRAP_ROOT/bootstrap.log and retry the same command." exit 1 fi + if (( python_exit != 0 )) && fv_certificate_failure "$attempt_detail"; then + local retry_log='' retry_detail='' retry_exit=0 + local orig_exit=$python_exit orig_detail="$attempt_detail" + [[ -z "$attempt_dir" ]] || retry_log=$(mktemp "$attempt_dir/output.XXXXXX" 2>/dev/null) || retry_log='' + printf 'Python source %s: retrying with the system certificate store\n' "$attempt" >>"$FREEVIDEO_BOOTSTRAP_ROOT/bootstrap.log" + if UV_HTTP_TIMEOUT="${UV_HTTP_TIMEOUT-$timeout}" UV_HTTP_RETRIES="${UV_HTTP_RETRIES-$retries}" \ + UV_PYTHON_INSTALL_MIRROR="$source" fv_with_route "$route" "$uv" --native-tls --no-config \ + python install --no-bin --no-registry --no-progress --color never "$FV_PYTHON_VERSION" 2>&1 | \ + tee -a -- "${retry_log:-/dev/null}" >>"$FREEVIDEO_BOOTSTRAP_ROOT/bootstrap.log"; then + pipe_status=("${PIPESTATUS[@]}") + else + pipe_status=("${PIPESTATUS[@]}") + fi + retry_exit=${pipe_status[0]} + [[ -z "$retry_log" ]] || retry_detail=$(tail -n 12 -- "$retry_log") + [[ -z "$retry_log" ]] || rm -f -- "$retry_log" + if (( retry_exit == 0 )); then + python_exit=0 + attempt_detail="$retry_detail" + else + python_exit=$orig_exit + attempt_detail="$orig_detail" + fi + fi if (( python_exit == 0 )); then fv_python_ok "$UV_PYTHON_INSTALL_DIR/cpython-$FV_PYTHON_VERSION-linux-$FV_ARCH-gnu/bin/python3.12" && exit 0 other_failures=1 diff --git a/scripts/test_freevideo_entry.mjs b/scripts/test_freevideo_entry.mjs index 20f515f3..61f889bf 100644 --- a/scripts/test_freevideo_entry.mjs +++ b/scripts/test_freevideo_entry.mjs @@ -35,6 +35,9 @@ class Element { replaceChildren(...children) { this.children = [...children]; } setAttribute(name, value) { this.attributes[name] = value; } removeAttribute(name) { delete this.attributes[name]; } + addEventListener() {} + removeEventListener() {} + focus() {} querySelector() { return null; } querySelectorAll() { return []; } getClientRects() { return this.unrendered ? [] : [{}]; } @@ -128,6 +131,7 @@ test('main browser entry registers both views and preserves node hooks', async t source = source.replace("from './issue_button.js'", `from '${new URL('../web/issue_button.js', import.meta.url).href}'`); source = source.replace("from './user_message.js'", `from '${new URL('../web/user_message.js', import.meta.url).href}'`); source = source.replace("from './prompt_sections.js'", `from '${new URL('../web/prompt_sections.js', import.meta.url).href}'`); + source = source.replace("from './fv_player.js'", `from '${new URL('../web/fv_player.js', import.meta.url).href}'`); source = source.replace("from './fv_select.js'", `from '${new URL('../web/fv_select.js', import.meta.url).href}'`); source = source.replace("from './tip_words.js'", `from '${new URL('../web/tip_words.js', import.meta.url).href}'`); source = source.replace("from './cut_tip.js'", `from '${new URL('../web/cut_tip.js', import.meta.url).href}'`); diff --git a/web/a11y.css b/web/a11y.css index c2212e21..ef2e9b91 100644 --- a/web/a11y.css +++ b/web/a11y.css @@ -34,6 +34,9 @@ html[data-fv-shell=nodes] canvas[tabindex]:not([tabindex="-1"]):focus-visible{ou /* A view dialog takes focus itself while it opens; it never wears the ring. */ :is(dialog.fv-studio,[data-fv-surface=view]):focus-visible{outline:none!important} +/* Focus returned by script after a mouse press (a view switch) is not keyboard focus: no ring until a key is pressed. */ +:root body [data-fv-pointer-focus=true]:focus-visible{outline:none!important} + /* Windows high contrast: the system colour, always visible. */ @media (forced-colors:active){ :where(body [class^="fv-"],body [class*=" fv-"]) :focus-visible{outline:2px solid Highlight!important} diff --git a/web/agent_activity.js b/web/agent_activity.js index aa1d3814..9cbe39cc 100644 --- a/web/agent_activity.js +++ b/web/agent_activity.js @@ -38,6 +38,10 @@ const REASONS = { // The engine's own sentence when it wrote one; otherwise the same advice the studio gives for that error, // and for an error nobody has a sentence for yet, its first line, so the row never says only "Did not finish". +export function failureReason(job, t) { + const error = job?.error || {}, reason = REASONS[error.code]; + return (reason ? t(...reason) : failureLine(error, t)).replace(/\s+/g, ' ').trim(); +} function failureLine(error, t) { // The engine's reason, then its next step when it has one. const next = (said, step, zh) => said && step ? said.replace(/[。.]$/, '') + (zh ? '。' : '. ') + step : said; @@ -97,7 +101,7 @@ function status(job, t) { if (job.status === 'waiting') return job.waiting_for ? t('Waiting for earlier tasks', '等待前面的任务') : t('Waiting for the GPU', '等待显卡'); return {succeeded: t('Done', '已完成'), failed: t('Failed', '失败'), cancelled: t('Cancelled', '已取消')}[job.status] || job.status; } -function title(job, t) { +export function title(job, t) { const name = NAMES[job.kind] || NAMES.generate; return job.label || (t(name[0], name[1]) + (job.take ? ' · ' + t(`Take ${job.take}`, `第 ${job.take} 条`) : '')); } @@ -165,6 +169,8 @@ function row(job, t, api, refresh, open, cancellationErrors) { body.append(foot); if (cancellationErrors.has(job.id)) details.textContent = cancellationErrors.get(job.id); item.append(body); + // What this row was drawn from: a poll that brings the same task back keeps this very element (see renderPanel). + item.__fvDrawn = JSON.stringify([job, cancellationErrors.get(job.id) ?? null]); return item; } // Running first, then the rest in the order they will run; finished ones after, newest first. @@ -177,16 +183,18 @@ function rows(jobs, t, api, refresh, open, cancellationErrors) { const items = active.map(job => row(job, t, api, refresh, open, cancellationErrors)); if (done.length) { const divider = el('li', 'fv-agent-divider', t('Last 30 minutes', '最近 30 分钟')); - divider.setAttribute('role', 'presentation'); + divider.setAttribute('role', 'presentation'); divider.__fvDrawn = divider.textContent; items.push(divider, ...done.map(job => row(job, t, api, refresh, open, cancellationErrors))); } return items; } // A re-render keeps keyboard focus on the same control. +// Rows already in place stay where they are (moving one would drop the pointer's hover and the tip on it). function refill(root, list, items) { const focused = root.contains(document.activeElement) ? document.activeElement : null; const key = focused && [focused.closest('[data-job]')?.dataset.job, focused.className]; - list.replaceChildren(...items); + items.forEach((item, index) => { if (list.children[index] !== item) list.insertBefore(item, list.children[index] || null); }); + while (list.children.length > items.length) list.lastElementChild.remove(); return key; } @@ -209,16 +217,24 @@ export function createAgentActivity(t, api, host, {interval = [1500, 8000], open function renderPanel() { const header = el('header'); header.append(el('h2', null, t('Assistant tasks', '助手的任务'))); - const list = el('ol'); - const key = refill(panel, list, rows(data.jobs, t, api, poll, job => { setOpen(false); open(job); }, cancellationErrors)); + // A row whose task has not changed since the last poll stays the same element, so the hover tip on it (the + // engine's message on a failed task) is not taken away by the next poll while other tasks run. + const list = panel.querySelector(':scope > ol') || el('ol'); + // A poll must not move a list the reader has scrolled. + const scrolled = list.scrollTop; + const place = node => node.dataset.job ? 'job:' + node.dataset.job : node.className; + const before = new Map([...list.children].map(node => [place(node), node])); + const fresh = rows(data.jobs, t, api, poll, job => { setOpen(false); open(job); }, cancellationErrors) + .map(node => { const kept = before.get(place(node)); return kept && kept.__fvDrawn === node.__fvDrawn ? kept : node; }); + const key = refill(panel, list, fresh); const unreadable = Number.isSafeInteger(data.unreadable) && data.unreadable > 0 ? data.unreadable : 0; const skipped = el('div', 'fv-agent-unreadable', unreadable > 0 ? t(`${unreadable} ${unreadable === 1 ? 'job' : 'jobs'} could not be read`, `另有 ${unreadable} 个任务无法读取`) : ''); skipped.hidden = !unreadable; - // A poll must not move a list the reader has scrolled. - const scrolled = panel.querySelector('ol')?.scrollTop || 0; - panel.replaceChildren(); - panel.append(header, list, skipped); + if (list.parentNode === panel) { + panel.querySelector(':scope > header')?.replaceWith(header); + panel.querySelector(':scope > .fv-agent-unreadable')?.replaceWith(skipped); + } else panel.replaceChildren(header, list, skipped); list.scrollTop = scrolled; if (key) (panel.querySelector(`[data-job="${key[0]}"] .${key[1].split(' ')[0]}`) || panel).focus?.(); } diff --git a/web/agent_tasks.js b/web/agent_tasks.js new file mode 100644 index 00000000..eed6757f --- /dev/null +++ b/web/agent_tasks.js @@ -0,0 +1,51 @@ +// The AI assistant's tasks as rows of the top bar's run status (one row each, the same as a generation task). +// Nothing is read in the background while no task runs: one read when the page starts, one each time the panel opens +// and every few seconds while it is open or a task runs. +import {retryAgentPost} from './agent_session.js'; + +const LIVE = {waiting: 'queued', queued: 'queued', running: 'running', cancelling: 'cancelling'}; +const FAST = 2500, SLOW = 8000, IDLE = 30000; // IDLE: only where the assistant is on, so tasks it starts show on the capsule + +export function createAgentTasks(api) { + let data = {jobs: [], unreadable: 0}, enabled = null, timer = 0, wanted = false, reading = null; + const listeners = new Set(); + const emit = () => { for (const fn of [...listeners]) { try { fn(); } catch { /* A listener must not stop the others. */ } } }; + const rows = () => (data.jobs || []).filter(job => job.status in LIVE).map(job => ({ + id: `agent:${job.id}`, agentId: job.id, source: 'agent', kind: 'agent', view: 'autopilot', cancellable: true, + status: LIVE[job.status], position: Number(job.progress?.queue_position) || 0, + percent: Math.max(0, Math.min(1, Number(job.progress?.fraction) || 0)), + eta_seconds: Number(job.progress?.remaining_seconds) || null, + job})); + async function read() { + try { + // Only an answer is kept; an engine that is not up yet is asked again at the next read. + if (enabled === null) { const response = await api.fetchApi('/freevideo/agent', {cache: 'no-store'}); if (response.ok) enabled = (await response.json()).enabled === true; } + if (!enabled) return; + const response = await api.fetchApi('/freevideo/agent/activity', {cache: 'no-store'}); + if (response.ok) data = await response.json(); + } catch { /* Keep what was read; the next read tries again. */ } + } + async function refresh() { + clearTimeout(timer); timer = 0; + reading ||= read().finally(() => { reading = null; }); + await reading; emit(); + const live = rows().length > 0; + // Not yet answered (the engine was not up) or on: keep asking, slowly when nothing runs. Off: no requests. + if (wanted || live || enabled !== false) timer = setTimeout(refresh, Math.max(wanted ? FAST : live ? SLOW : IDLE, document.hidden ? IDLE : 0)); + } + // Coming back to the page reads at once (a task may have been started meanwhile). + if (typeof window !== 'undefined') window.addEventListener('focus', () => { if (enabled !== false) void refresh(); }); + return { + rows, refresh, + failed: () => (data.jobs || []).filter(job => job.status === 'failed'), + unreadable: () => (Number.isSafeInteger(data.unreadable) && data.unreadable > 0 ? data.unreadable : 0), + // While the status panel is open the list is read often; closed, only while a task runs. + watch(on) { wanted = on; if (on) { if (enabled === false) enabled = null; void refresh(); } }, + subscribe(fn) { listeners.add(fn); return () => listeners.delete(fn); }, + async cancel(id) { + const response = await retryAgentPost(api, '/freevideo/agent/activity/cancel', {id}); + if (!response?.ok) throw new Error('cancel failed'); + await refresh(); + }, + }; +} diff --git a/web/autopilot_chat.js b/web/autopilot_chat.js index 041ad382..1c992f78 100644 --- a/web/autopilot_chat.js +++ b/web/autopilot_chat.js @@ -13,7 +13,7 @@ import {closeDialog} from './motion.js'; import { estimatedFraction, remainingAbove, remainingShown, createDiagnosticReportControl } from './generation_progress.js'; import {createErrorReport, failureAdvice, failureFold} from './error_panel.js'; import {canDeleteConversation, canRenameConversation, conversationMenu, emptyConversations, hasConversations, mergeConversations, removeConversation, runningElsewhere, selectConversation} from './autopilot_conversations.js'; -import {renderImageFailure} from './image_generation.js'; +import {renderImageFailure, originStep} from './image_generation.js'; import {issueButton} from './issue_button.js'; import {about} from './request_assets.js'; import {showEmptyPrompt} from './empty_prompt_notice.js'; @@ -647,6 +647,13 @@ export function agentChat(t, api, {open, edit, shown = () => true, changed = () const target = focus && item.querySelector(focus); (target || item).focus?.({preventScroll: true}); } + // A note of a failed task in the top bar's status panel opens that task's card (its cause, next step and report). + const openTaskCard = event => { + const id = event.detail?.id; if (!id) return; + const look = left => { if (findCard(id)) showCard(id, '.fv-chat-retry:not([hidden]), .fv-report-button, button'); else if (left > 0 && !stopped) setTimeout(() => look(left - 1), 150); else if (!stopped) say(t('That task is no longer in this conversation.', '这条任务已经不在当前对话里了。')); }; + look(20); + }; + window.addEventListener('freevideo-agent-task-open', openTaskCard); side_ = createSideRail(t, { pick: id => showCard(id), stop: id => void cancelJobs([id]), @@ -1426,7 +1433,7 @@ export function agentChat(t, api, {open, edit, shown = () => true, changed = () // "Send again" leads the card's own action row; its label and state are set below with the others. const host = el('div'); const card = renderImageFailure(host, {error: job.error?.code || 'generation_failed', report_id: job.error?.report_id, - stage: job.error?.stage, step: job.error?.step || (job.error?.code ? '' : 'agent_job'), memory: job.error?.memory}, t, + stage: job.error?.stage, step: originStep(job.error, 'agent_job'), memory: job.error?.memory}, t, {productVersion, fetchApi: (path, options) => api.fetchApi(path, options), retry: retry ? {label: AGAIN.resend, onClick: () => retry?.()} : null}); item.replaceChildren(host); @@ -2095,6 +2102,6 @@ export function agentChat(t, api, {open, edit, shown = () => true, changed = () }, stop() { closeMenu(); stopped = true; for (const [session, timer] of undoing) { clearTimeout(timer); finishDelete(session); } tab(); dismissImage?.(); closed.abort(); clearInterval(moving); clearTimeout(timer); timer = null; document.removeEventListener('visibilitychange', visible); document.removeEventListener('pointerdown', outside, true); - stopMenuKeys(); stopSlash?.(); history.dispose(); window.removeEventListener('resize', resize); list.removeEventListener('scroll', listScroll); + stopMenuKeys(); stopSlash?.(); history.dispose(); window.removeEventListener('resize', resize); window.removeEventListener('freevideo-agent-task-open', openTaskCard); list.removeEventListener('scroll', listScroll); log.querySelectorAll('video').forEach(video => video.pause()); }}; } diff --git a/web/cast_generate.js b/web/cast_generate.js index 4273c7a2..5145c17b 100644 --- a/web/cast_generate.js +++ b/web/cast_generate.js @@ -3,7 +3,7 @@ // dialog's Save waits for all five. Pictures are made one by one through the page's image client // and stay in the input folder; the dialog puts them on the card. import { setTip } from './tip_words.js'; -import {createImageGenClient, imageGenProgress, imagePackUnavailableMessage, renderImageFailure, +import {createImageGenClient, imageGenProgress, imagePackUnavailableMessage, renderImageFailure, originStep, IMAGE_GEN_POLL_MS, IMAGE_GEN_INFO_POLL_MS} from './image_generation.js'; import {createImageLoras} from './image_lora.js'; import {createOtherUsageNotice} from './other_usage.js'; @@ -20,7 +20,7 @@ const VIEW_TITLES = Object.freeze({ function el(tag, cls, text) { const e = document.createElement(tag); if (cls) e.className = cls; if (text != null) e.textContent = text; return e; } const failureOf = error => ({error: error?.code || 'generation_failed', report_id: error?.report_id || null, - stage: error?.stage || '', step: error?.step || (error?.code ? '' : 'cast'), fitted: error?.fitted || null, memory: error?.memory || '', other_usage: error?.other_usage || null}); + stage: error?.stage || '', step: originStep(error, 'cast'), fitted: error?.fitted || null, memory: error?.memory || '', other_usage: error?.other_usage || null}); const randomSeed = () => crypto.getRandomValues(new Uint32Array(1))[0] >>> 1; // From a photo: the face close-up comes first, from the photo alone; the front is then made from the photo () @@ -225,7 +225,7 @@ export function createCastGenerator({client, kind = 'character', views = null, f } // A sent request until its picture is made (the picture's name), or null when the run was stopped. async function waitFor(row, alive, progress) { - if (!row.job) throw Object.assign(new Error(row.error || 'generation_failed'), {code: row.error, report_id: row.report_id, memory: row.memory, step: row.error ? '' : 'submit'}); + if (!row.job) throw Object.assign(new Error(row.error || 'generation_failed'), {code: row.error, report_id: row.report_id, memory: row.memory, step: originStep({code: row.error, report_id: row.report_id}, 'submit')}); if (!alive()) { await cancelJob(row.job); return null; } job = row.job; for (;;) { diff --git a/web/cast_room.js b/web/cast_room.js index f671f6a3..388e521d 100644 --- a/web/cast_room.js +++ b/web/cast_room.js @@ -6,6 +6,7 @@ import { agentInterfaceState } from './agent_connect.js'; import { agentSend } from './agent_session.js'; import { uploadMedia } from './media_upload.js'; import { issueButton } from './issue_button.js'; +import { createPlayBar } from './fv_player.js'; import { userMessage } from './user_message.js'; const css = document.createElement('link'); css.rel = 'stylesheet'; css.href = new URL('./cast_room.css', import.meta.url).href; document.head.append(css); @@ -191,9 +192,9 @@ export function createCastRoom({api, t, viewURL: outputURL}) { voiceBox.replaceChildren(); if (card.voice?.clip?.file || card.voice?.clip?.url) { voiceBox.append(el('div', t('Voice', '声音'), 'fv-cast-voice-label')); - const audio = el('audio'); audio.controls = true; audio.preload = 'none'; + const audio = el('audio'); audio.preload = 'none'; audio.src = card.voice.clip.url ? api.apiURL(card.voice.clip.url) : inputURL(card.voice.clip.file); - voiceBox.append(audio); + voiceBox.append(audio, createPlayBar(audio, t).bar); } } async function copyMention() { diff --git a/web/compatibility.js b/web/compatibility.js index a0fb66a8..871b72d8 100644 --- a/web/compatibility.js +++ b/web/compatibility.js @@ -1,4 +1,5 @@ import { api } from '../../scripts/api.js'; +import './fv_select.js'; import './glass/library.js'; import {userMessage} from './user_message.js'; diff --git a/web/editor.css b/web/editor.css index f7e3e9ef..c51cf340 100644 --- a/web/editor.css +++ b/web/editor.css @@ -1,5 +1,5 @@ /* Share the studio shell and header geometry; only the editor rows differ. */ -.fv-studio.fv-editor{--fv-ed-project-h:44px;--fv-ed-generation-row:calc(60px + var(--fv-ed-description-growth,0px));--fv-ed-timeline-h:clamp(220px,calc(100dvh - 640px),320px);overflow:hidden auto;display:grid;grid-template-columns:264px minmax(0,1fr);grid-template-rows:auto var(--fv-ed-project-h) minmax(96px,1fr) 40px var(--fv-ed-generation-row) 40px var(--fv-ed-timeline-h);animation:none;scrollbar-width:thin;scrollbar-color:var(--fv-border) transparent} +.fv-studio.fv-editor{--fv-ed-project-h:44px;--fv-ed-generation-row:calc(60px + var(--fv-ed-description-growth,0px) + var(--fv-ed-note-growth,0px));--fv-ed-timeline-h:min(clamp(220px,calc(100dvh - 640px),320px),max(160px,var(--fv-ed-tracks-fit,320px)));overflow:hidden auto;display:grid;grid-template-columns:264px minmax(0,1fr);grid-template-rows:auto var(--fv-ed-project-h) minmax(96px,1fr) 40px var(--fv-ed-generation-row) 40px var(--fv-ed-timeline-h);animation:none;scrollbar-width:thin;scrollbar-color:var(--fv-border) transparent} @media(min-width:1280px){.fv-studio.fv-editor{grid-template-columns:264px minmax(0,1fr) 264px}} .fv-editor *{box-sizing:border-box} .fv-editor [hidden]{display:none!important} @@ -90,7 +90,7 @@ .fv-ed-picture>img.fv-ed-poster[data-gone=true]{opacity:0} .fv-ed-picture>img.fv-ed-poster[hidden]{display:none} @media(prefers-reduced-motion:reduce){.fv-ed-picture>img.fv-ed-poster{transition:none}} -.fv-ed-picture>audio.fv-ed-source-preview{display:block;position:absolute;bottom:0;left:0;width:100%} +.fv-ed-picture>audio.fv-ed-source-preview{display:none} .fv-ed-transport{grid-column:2;grid-row:4;display:flex;align-items:center;justify-content:center;gap:12px} .fv-editor .fv-ed-play{width:36px;height:36px;border-radius:var(--fv-r-pill);padding:0;background:transparent} .fv-ed-time{font-size:13px;font-variant-numeric:tabular-nums;font-family:ui-monospace,monospace;min-width:100px} @@ -476,6 +476,12 @@ .fv-ed-genbar>.fv-ed-gen-note[data-hx-issue]{white-space:nowrap;overflow:hidden;display:flex;align-items:center;gap:8px} .fv-ed-genbar>.fv-ed-gen-note .fv-issue-button{flex:none;margin-left:0} @media(max-width:680px){.fv-ed-genbar>.fv-ed-gen-note{order:-1;flex:1 1 100%;max-width:none}} +.fv-ed-genbar[data-note-row]{flex-wrap:wrap;align-content:flex-start;row-gap:8px} +.fv-ed-genbar[data-note-row]>.fv-ed-gen-note{order:-1;flex:1 1 100%;max-width:none} +/* On a row of its own the sentence wraps rather than being cut. */ +.fv-ed-genbar[data-note-row]>.fv-ed-gen-note[data-hx-issue],.fv-ed-genbar[data-note-row]>.fv-ed-gen-note{white-space:normal;overflow:visible;text-overflow:clip;height:auto} +.fv-ed-genbar[data-note-row]>.fv-ed-gen-note .fv-ed-gen-note-text{white-space:normal;overflow:visible;text-overflow:clip} +@media(max-width:680px){.fv-ed-genbar>.fv-ed-gen-note[data-hx-issue],.fv-ed-genbar>.fv-ed-gen-note{white-space:normal;overflow:visible;text-overflow:clip;height:auto}.fv-ed-genbar>.fv-ed-gen-note .fv-ed-gen-note-text{white-space:normal;overflow:visible;text-overflow:clip}} /* Under the press: what downloads first (its hover names it and its size). */ .fv-ed-generate-time.fv-ed-generate-download::before{content:"↓ "} .fv-ed-generate-time{opacity:1} @@ -586,6 +592,45 @@ /* The creation panel's own bar stands in for the description, size, duration and quality controls (editor.js). */ .fv-ed-genbar.fv-ed-genbar-borrowed{height:auto;flex-wrap:wrap;align-content:flex-start;align-items:flex-start} +/* The borrowed bar is the creation panel's console with its own frame: the editor adds no second frame around it, and no + backdrop filter, which would make the bar the box its windows (Media, LoRA, Advanced) are placed in and drop them onto the timeline. */ +.fv-editor .fv-ed-genbar.fv-ed-genbar-borrowed{padding:0;border:0;background:none;box-shadow:none;-webkit-backdrop-filter:none;backdrop-filter:none} +/* The picture is what the editor is for: here the description keeps two lines, growing to three, and scrolls past that + (its expand key opens the full box). */ +.fv-editor .fv-ed-genbar-borrowed .fv-studio.fv-create .fvs-console .fv-prompt-editor textarea{min-height:48px;max-height:72px;padding-block:0;box-sizing:border-box} +/* One row of keys under it where the window allows: slightly closer keys and a narrower Generate. A short window keeps + the description at two lines. */ +.fv-editor .fv-ed-genbar-borrowed .fv-studio.fv-create{--fvs-key-w:140px} +.fv-editor .fv-ed-genbar-borrowed .fv-studio.fv-create .fvs-chips{gap:6px} +@media(max-width:1439px){.fv-editor .fv-ed-genbar-borrowed .fv-studio.fv-create .fvs-chips{gap:4px}} +.fv-editor .fv-ed-genbar-borrowed .fv-studio.fv-create .fvs-chips>.fvs-chip-spacer{min-width:0} +/* Where the chips would wrap beside the Generate block (a narrow window; English words are longer), the key stands + beside the description instead and the chips take the full width on one line. The description's tools move from + the key's column to the strip under the text, next to the key, and the text shows two lines while it is not being + typed in, so the console is no taller than before. */ +@media(max-width:1365px){ + .fv-editor:lang(zh) .fv-ed-genbar-borrowed .fv-studio.fv-create .fvs-console .fvs-chips{grid-column:1/-1} + .fv-editor:lang(zh) .fv-ed-genbar-borrowed .fv-studio.fv-create .fvs-console>.fv-runbar{grid-row:1/span 2} + .fv-editor:lang(zh) .fv-ed-genbar-borrowed .fv-studio.fv-create .fvs-console-prompt{display:flex;flex-direction:column} + .fv-editor:lang(zh) .fv-ed-genbar-borrowed .fv-studio.fv-create .fvs-console-prompt>.fv-section{flex:1 1 auto;display:flex;flex-direction:column} + .fv-editor:lang(zh) .fv-ed-genbar-borrowed .fv-studio.fv-create .fvs-console-prompt>.fv-section>.fv-enhance{flex:1 1 auto} + .fv-editor:lang(zh) .fv-ed-genbar-borrowed .fv-studio.fv-create .fvs-console-prompt .fv-enhance>.fv-prompt-editor{flex:1 1 auto;padding-bottom:32px;box-sizing:border-box} + .fv-editor:lang(zh) .fv-ed-genbar-borrowed .fv-studio.fv-create .fvs-console .fv-prompt-tools{top:auto;bottom:0;right:0} + .fv-editor:lang(zh) .fv-ed-genbar-borrowed .fv-studio.fv-create .fvs-console .fv-prompt-editor textarea:not(:focus){max-height:48px} +} +@media(max-width:1439px){ + .fv-editor:lang(en) .fv-ed-genbar-borrowed .fv-studio.fv-create .fvs-console .fvs-chips{grid-column:1/-1} + .fv-editor:lang(en) .fv-ed-genbar-borrowed .fv-studio.fv-create .fvs-console>.fv-runbar{grid-row:1/span 2} + .fv-editor:lang(en) .fv-ed-genbar-borrowed .fv-studio.fv-create .fvs-console-prompt{display:flex;flex-direction:column} + .fv-editor:lang(en) .fv-ed-genbar-borrowed .fv-studio.fv-create .fvs-console-prompt>.fv-section{flex:1 1 auto;display:flex;flex-direction:column} + .fv-editor:lang(en) .fv-ed-genbar-borrowed .fv-studio.fv-create .fvs-console-prompt>.fv-section>.fv-enhance{flex:1 1 auto} + .fv-editor:lang(en) .fv-ed-genbar-borrowed .fv-studio.fv-create .fvs-console-prompt .fv-enhance>.fv-prompt-editor{flex:1 1 auto;padding-bottom:32px;box-sizing:border-box} + .fv-editor:lang(en) .fv-ed-genbar-borrowed .fv-studio.fv-create .fvs-console .fv-prompt-tools{top:auto;bottom:0;right:0} + .fv-editor:lang(en) .fv-ed-genbar-borrowed .fv-studio.fv-create .fvs-console .fv-prompt-editor textarea:not(:focus){max-height:48px} +} +.fv-editor .fv-ed-genbar-borrowed .fv-studio.fv-create .fvs-step-value{min-width:40px} +.fv-editor .fv-ed-genbar-borrowed .fv-studio.fv-create .fvs-chip:not(.fv-reference-trigger,[data-chip=advanced],.fvs-stepper){padding:0 10px} +@media(max-height:820px){.fv-editor .fv-ed-genbar-borrowed .fv-studio.fv-create .fvs-console .fv-prompt-editor textarea{max-height:48px}} .fv-ed-genbar-borrowed>.fv-ed-refs,.fv-ed-genbar-borrowed>.fv-ed-description-box,.fv-ed-genbar-borrowed>.fv-ed-duration,.fv-ed-genbar-borrowed>.fv-ed-first-frame,.fv-ed-genbar-borrowed>.fv-ed-generate,.fv-ed-genbar-borrowed>.fv-ed-pass-options{display:none!important} .fv-ed-genbar-borrowed>.fv-borrowed{flex:1 1 100%;min-width:0;position:static;display:block;width:auto;height:auto;max-height:none;padding:0;border:0;background:none;box-shadow:none;transform:none;inset:auto} .fv-ed-genbar-borrowed>.fv-borrowed>.fv-body{display:block;position:static;width:auto;height:auto;padding:0} diff --git a/web/editor.js b/web/editor.js index daa0d58a..ebc65c05 100644 --- a/web/editor.js +++ b/web/editor.js @@ -25,6 +25,7 @@ import {createAdjustPicture} from './editor_adjust_picture.js'; import {pictureSession} from './editor_picture_session.js'; import {createPictureTools} from './editor_frame.js'; import {openExportDialog} from './editor_export_dialog.js'; +import {replaceMode} from './editor_audio_replace.js'; import {createAudioIntegration, createSpeechSpans, handleAudioShortcut, AUDIO_SHORTCUTS} from './editor_audio.js'; import {createStemsIntegration} from './editor_stems.js'; import {createSpeedComponent, readSpeedAudioSamples, handleSpeedKey, speedShortcuts} from './editor_speed.js'; @@ -434,7 +435,8 @@ export function openEditor({api, app, from = null, panel = {}, components: given // `where` marks a failure: the notice then carries the "Report a problem" button and stays longer to be reached. // Notices stack (newest last, at most three) instead of a new one wiping out the one being read; each can be closed. const noticeTimers = new Set(); - function notify(text, where = null, kind = null, action = null) { + // `report: false` keeps a problem's 20 s and its name but leaves out "Report a problem", for a cause that is not a fault. + function notify(text, where = null, kind = null, action = null, {report = true} = {}) { if (disposed) return; if (!text) { for (const timer of noticeTimers) clearTimeout(timer); noticeTimers.clear(); notices.replaceChildren(); return; } const last = notices.lastElementChild; @@ -443,7 +445,7 @@ export function openEditor({api, app, from = null, panel = {}, components: given const words = el('span', 'fv-ed-notice-text', text); // In the project row the line is cut to one row; its hover says it whole. words.setAttribute('data-fv-tip-name', where ? t('Problem', '问题') : t('Notice', '提示')); words.setAttribute('data-fv-tip-use', text); - if (where) { words.classList.add('fv-copyable'); words.append(issueButton(t, () => ({where, message: text, kind}))); } + if (where && report) { words.classList.add('fv-copyable'); words.append(issueButton(t, () => ({where, message: text, kind}))); } const close = button('', () => { clearTimeout(timer); noticeTimers.delete(timer); card.remove(); }, 'fv-ed-notice-close'); close.append(icon('m4 4 8 8M12 4l-8 8')); close.setAttribute('aria-label', t('Close', '关闭')); tip(close, {name: t('Close', '关闭'), use: t('Dismiss this notice', '关掉这条提示')}); @@ -710,7 +712,23 @@ export function openEditor({api, app, from = null, panel = {}, components: given } finally { startingHeld = false; } } function completeSources() { - return store.getSources(model.references(state.record).map(sourceKey)).then(() => { player.refresh(); tracks?.refresh?.(); }); + return store.getSources(model.references(state.record).map(sourceKey)).then(() => { player.refresh(); tracks?.refresh?.(); sayMissing(); }); + } + // A picture whose file was moved or deleted stays on the timeline as a grey part; the notice bar says so once for each + // such file, however the edit was opened (Iris 11-20). Moving a file is not a fault, so there is no report button. + const toldMissing = new Set(); + function sayMissing() { + if (disposed) return; + for (const track of state.record.tracks) { + if (track.kind !== 'video') continue; + for (const clip of track.clips) { + const key = clip.source && sourceKey(clip.source), value = key && store.sources.get(key); + if (!value?.missing || value._fallback || toldMissing.has(key)) continue; + toldMissing.add(key); + notify(t('The video file cannot be found. It may have been moved or deleted. Import it again.', + '视频文件找不到了,可能已被移动或删除。请重新导入。'), EDITOR_ISSUE, null, null, {report: false}); + } + } } // Music on the second sound track goes through the same bar; the bar shows a chosen piece's own job. const music = createEditorMusic({state, store, t, completeSources, onStatus: () => genbar?.update(barValue)}); @@ -945,6 +963,11 @@ export function openEditor({api, app, from = null, panel = {}, components: given 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; + // Only an open end gets a next part: anything after it on the picture's or its sound's track (such as the rest of + // an imported sound the video was made to) would be pushed back by the new part. + const pair = model.pair(state.record, last.id), edge = last.start + last.frames; + const tracksOf = new Set(pair.map(member => state.record.tracks.find(track => track.clips.includes(member)))); + if ([...tracksOf].some(track => track.clips.some(clip => !pair.includes(clip) && clip.start >= edge))) 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}); @@ -1719,8 +1742,8 @@ export function openEditor({api, app, from = null, panel = {}, components: given }, }; async function viewExport(value) { - // A sound-only export is not a work: it opens as a file the browser plays and can save. - if (value.only === 'sound') { if (value.url) window.open(mediaURL(api, value.url), '_blank', 'noopener'); return; } + // A sound-only or lossless-sound export is not a work: it opens as a file the browser plays or saves. + if (value.only === 'sound' || value.audio === 'lossless') { if (value.url) window.open(mediaURL(api, value.url), '_blank', 'noopener'); return; } const module = await import('./library.js'); module.openLibrary(t, {selectedWork: value.work, extend: async (record, options) => { if (await handle.close() === false) throw new Error(saveWarningText.textContent); @@ -1803,6 +1826,8 @@ export function openEditor({api, app, from = null, panel = {}, components: given // borrow from, the editor's bar is shown as before. if (panel.borrowBar) { let observer = null, arranged = false, unlisten = null, echo = false, lent = false, home = '', arrangeNow = null; // the subscription below outlives one borrow, so what it reads is kept out here + // The description here shows two or three lines: away from it, it reads from the start, not from wherever the caret left it. + const fromStart = event => { if (event.target instanceof HTMLTextAreaElement && event.target.closest('.fv-prompt-editor')) event.target.scrollTop = 0; }; attachBar = () => { if (bar) return; bar = panel.borrowBar({mount: genHost, onSeconds: value => { const field = genbar.duration; if (!field || field.element.hidden || field.input.disabled || !(value > 0)) return; field.input.value = String(Math.round(value)); field.commit(); }, label: () => barLabel || null, disabled: () => !genbar.canGenerate(), @@ -1810,6 +1835,7 @@ export function openEditor({api, app, from = null, panel = {}, components: given onFirstFrame: value => genbar.firstFrame?.set(value)}); if (bar) { genHost.classList.add('fv-ed-genbar-borrowed'); + genHost.addEventListener('focusout', fromStart); // The editor's own first-frame switch is hidden with its bar; the borrowed bar's switch (in its frame pop-up, // where the creation panel keeps it) follows the editor's rule and saves to the edit. genbar.firstFrame?.mirror(next => bar?.firstFrame?.(next)); @@ -1855,7 +1881,7 @@ export function openEditor({api, app, from = null, panel = {}, components: given } }; // Hidden, the editor gives the panel its bar back; shown again, it takes it once more. - detachBar = () => { genbar.firstFrame?.mirror(null); observer?.disconnect(); observer = null; unlisten?.(); unlisten = null; for (const back of guideBack.splice(0)) back(); bar?.release(); bar = null; panel.barActive = false; genHost.classList.remove('fv-ed-genbar-borrowed'); delete element.dataset.barBorrowed; }; + detachBar = () => { genbar.firstFrame?.mirror(null); observer?.disconnect(); observer = null; unlisten?.(); unlisten = null; for (const back of guideBack.splice(0)) back(); bar?.release(); bar = null; panel.barActive = false; genHost.classList.remove('fv-ed-genbar-borrowed'); genHost.removeEventListener('focusout', fromStart); delete element.dataset.barBorrowed; }; cleanupBar = detachBar; attachBar(); } @@ -2180,7 +2206,9 @@ export function openEditor({api, app, from = null, panel = {}, components: given if (event.target !== element) return; event.preventDefault(); if (escapeTaken || topDialog() !== element) return; - if (dismissPopup(event) || tracks?.cancelGesture()) { tookEscape(); return; } + // A pending "replace audio" is an inner layer too: Escape ends it and keeps the selection. + if (dismissPopup(event) || tracks?.cancelGesture() || pictureEdit.cancelDraft() || replaceMode(state).cancel()) { tookEscape(); return; } + if (document.fullscreenElement) { tookEscape(); document.exitFullscreen().catch(() => {}); return; } state.select(null, {history: true}); }); const stopKeys = isolateDialogKeys(element, (event, inside) => { @@ -2198,7 +2226,7 @@ export function openEditor({api, app, from = null, panel = {}, components: given if (event.key.toLowerCase() === 'escape') { if (escapeTaken) { event.preventDefault(); return; } if (dismissPopup(event)) { tookEscape(); return; } - if (tracks?.cancelGesture()) { event.preventDefault(); tookEscape(); return; } + if (tracks?.cancelGesture() || pictureEdit.cancelDraft()) { event.preventDefault(); tookEscape(); return; } if (document.fullscreenElement) { event.preventDefault(); tookEscape(); document.exitFullscreen().catch(() => {}); return; } } if (recording.keyboard(event)) return; @@ -2245,7 +2273,7 @@ export function openEditor({api, app, from = null, panel = {}, components: given if (!menu.hidden && !menu.contains(event.target) && event.target !== title) menu.hidden = true; }); // A page kept for going back (bfcache) keeps its history, so its takes stay. - const leaving = event => { player.pause(); rememberView(); if (queue.dirty) queue.flush(); if (!event?.persisted) releaseTakes({keepalive: true}); }; + const leaving = event => { player.pause(); rememberView(); if (queue.dirty) queue.flush(); if (!event?.persisted) { releaseTakes({keepalive: true}); store.releaseLease(); } }; window.addEventListener('pagehide', leaving); // A workflow without FreeVideo nodes came to the front: the editing view makes way (unsaved edits stay open). const collapse = () => { void handle.close(); }; @@ -2402,6 +2430,16 @@ export function openEditor({api, app, from = null, panel = {}, components: given skeleton.remove(); tracks = module.createTracks(tracksHost, {state, sources: store.sources, t, actions, blockProgress}); listeners.push(notes.attach(tracks.element)); + // The timeline takes the room its rows need, up to its usual height (more rows scroll inside it); the rest goes to the picture. + const trackContent = tracks.element.querySelector('.fv-ed-track-content'), trackScroll = tracks.element.querySelector('.fv-ed-track-scroll'); + if (trackContent && trackScroll && typeof ResizeObserver === 'function') { + const fitTracks = () => { + const around = tracksHost.getBoundingClientRect().height - trackScroll.clientHeight; // the ruler's inset and the scroll bar + if (around >= 0 && trackContent.offsetHeight) element.style.setProperty('--fv-ed-tracks-fit', `${Math.ceil(trackContent.offsetHeight + around)}px`); + }; + const watchTracks = new ResizeObserver(fitTracks); watchTracks.observe(trackContent); watchTracks.observe(tracksHost); + listeners.push(() => watchTracks.disconnect()); fitTracks(); + } transportControls.attachTracks(tracks, module.snapFrame); if (api.addEventListener && api.removeEventListener) { progressConnection = createProgressConnection(api, receiveProgress); progressConnection.start(); diff --git a/web/editor_expand.js b/web/editor_expand.js index fcd598a3..cc8e77cd 100644 --- a/web/editor_expand.js +++ b/web/editor_expand.js @@ -36,6 +36,40 @@ export function createExpandButton({t = en => en, textarea, onGenerate, canGener const path = document.createElementNS('http://www.w3.org/2000/svg', 'path'); path.setAttribute('d', 'M14 4h6v6M20 4l-7 7M10 20H4v-6M4 20l7-7'); svg.append(path); element.append(svg); let dialog = null, large = null, notice = null, count = null, seen = '', pending = false, disposed = false, cleanups = []; + // The small box is written as a whole while the panel is open, which ends its own undo history; so each panel session is one + // step of the box's own, undone and redone from the box with the usual keys (a person who typed in the box afterwards keeps the native ones). + let startText = null; const undone = [], redone = []; + const setText = value => { textarea.value = value; seen = value; textarea.dispatchEvent(new Event('input', {bubbles: true})); }; + const stepKeys = event => { + if (event.target !== textarea || event.defaultPrevented) return; + if (!(event.ctrlKey || event.metaKey) || event.altKey || event.isComposing) return; + // The letter the layout types, so QWERTZ (Z on the physical Y key) is right; only a non-Latin layout, whose keys type other + // letters, falls back to the physical key. + const typed = event.key.toLowerCase(); + const key = /^[a-z]$/.test(typed) ? typed : event.code === 'KeyZ' ? 'z' : event.code === 'KeyY' ? 'y' : typed; + if (key === 'z' && !event.shiftKey) { + const step = undone.at(-1); + if (step && textarea.value === step.after) { event.preventDefault(); event.stopPropagation(); setText(step.before); redone.push(undone.pop()); } + } else if ((key === 'z' && event.shiftKey) || key === 'y') { + const step = redone.at(-1); + if (step && textarea.value === step.before) { event.preventDefault(); event.stopPropagation(); setText(step.after); undone.push(redone.pop()); } + } + }; + // What the person typed in the box themself (script writes carry no input type) is a step too, taken in when a session opens. + let typing = null; + const watchTyping = event => { + if (!event.isTrusted || !event.inputType) return; + if (!typing) typing = {before: typingBefore, after: textarea.value}; else typing.after = textarea.value; + }; + let typingBefore = textarea.value; + const markBefore = () => { if (!typing) typingBefore = textarea.value; }; + textarea.addEventListener('beforeinput', markBefore); textarea.addEventListener('input', watchTyping); + // On the box itself, and nowhere else: a listener on the window would stay after the box is gone. A dialog that takes its keys at the + // window (Studio) routes them to what listenDialogKey registered; the editor's calls the box's onkeydown (the genbar's calls undoKeys). + // Each reaches the same function, and a key it has handled is not handled again. + const stopStepKeys = listenDialogKey(textarea, 'keydown', stepKeys); + // Where the writer left off (text, scroll and caret) for the next visit to the same text. + let reading = {text: null, top: 0, from: 0, to: 0}; const writable = () => !textarea.disabled && !textarea.readOnly; const allowed = () => writable() && !pending && !!canGenerate(); const counted = () => { @@ -55,8 +89,11 @@ export function createExpandButton({t = en => en, textarea, onGenerate, canGener } // Every edit in the panel reaches the small box at once (there is nothing to save). function commit() { - if (!dialog || !textarea.isConnected || !writable() || large.value === textarea.value) return; + if (!dialog || !textarea.isConnected || !writable()) return; + // The caret and selection of the large box are the small box's too. + if (large.value === textarea.value) { textarea.setSelectionRange?.(large.selectionStart, large.selectionEnd); return; } textarea.value = large.value; seen = textarea.value; + textarea.setSelectionRange?.(large.selectionStart, large.selectionEnd); textarea.dispatchEvent(new Event('input', {bubbles: true})); } // Ctrl/⌘+Enter still generates (said in the hover help only); the panel closes once the run is asked for. @@ -70,7 +107,7 @@ export function createExpandButton({t = en => en, textarea, onGenerate, canGener pending = false; if (notice) { notice.textContent = typeof reason === 'string' ? reason : ''; - if (!notice.textContent) close(); + if (!notice.textContent) close(); else if (!large.value.trim()) large.focus(); } sync(); } @@ -78,6 +115,9 @@ export function createExpandButton({t = en => en, textarea, onGenerate, canGener function close() { if (!dialog) return; commit(); + if (startText !== null && textarea.value !== startText) { undone.push({before: startText, after: textarea.value}); redone.length = 0; } + startText = null; + reading = {text: large.value, top: large.scrollTop, from: textarea.selectionStart, to: textarea.selectionEnd}; const current = dialog; dialog = large = notice = count = null; cleanups.splice(0).forEach(stop => stop()); current.oncancel = current.onclose = null; @@ -89,6 +129,9 @@ export function createExpandButton({t = en => en, textarea, onGenerate, canGener function open() { sync(); if (disposed || element.disabled || dialog) return; + startText = textarea.value; + if (typing && typing.after === startText && typing.before !== typing.after) { undone.push({before: typing.before, after: typing.after}); redone.length = 0; } + typing = null; 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'); @@ -145,18 +188,26 @@ export function createExpandButton({t = en => en, textarea, onGenerate, canGener const stop = event => event.stopPropagation(); for (const type of ['pointerdown', 'pointerup', 'pointermove', 'mousedown', 'mouseup', 'mousemove', 'click', 'dblclick', 'wheel', 'contextmenu']) dialog.addEventListener(type, stop); parent.append(dialog); counted(); sync(); dialog.showModal(); - // The caret goes to the end of the text, which is scrolled into view. - const end = large.value.length; - large.focus(); large.setSelectionRange?.(end, end); large.scrollTop = large.scrollHeight; + // The caret and selection are the small box's (a box never given one has them at the end); the caret's line is centred, not + // pressed to an edge, unless the same text is being returned to, which opens where it was left. + const from = textarea.selectionStart ?? large.value.length, to = textarea.selectionEnd ?? large.value.length; + if (reading.text === large.value && reading.from === from && reading.to === to) { large.focus(); large.setSelectionRange?.(from, to); large.scrollTop = reading.top; } + else { + const full = large.value; large.value = full.slice(0, to); + large.scrollTop = 0; const above = large.scrollHeight, view = large.clientHeight; large.value = full; + const top = above <= view ? 0 : above - view / 2; + large.focus(); large.setSelectionRange?.(from, to); large.scrollTop = top; + } } element.onclick = open; textarea.addEventListener('input', sync); textarea.addEventListener('change', sync); const observer = typeof MutationObserver === 'function' ? new MutationObserver(sync) : null; observer?.observe(textarea, {attributes: true, attributeFilter: ['disabled', 'readonly']}); sync(); - return {element, open, close, commit, get isOpen() { return !!dialog; }, dispose() { + return {element, open, close, commit, undoKeys: stepKeys, get isOpen() { return !!dialog; }, dispose() { close(); disposed = true; observer?.disconnect(); textarea.removeEventListener('input', sync); textarea.removeEventListener('change', sync); + stopStepKeys(); textarea.removeEventListener('beforeinput', markBefore); textarea.removeEventListener('input', watchTyping); element.onclick = null; element.remove(); }}; } diff --git a/web/editor_export_dialog.js b/web/editor_export_dialog.js index fc77f922..5434e731 100644 --- a/web/editor_export_dialog.js +++ b/web/editor_export_dialog.js @@ -5,7 +5,7 @@ import {selectedRange} from './editor_transport_model.js'; import {isolateDialogKeys, listenDialogKey, routeDialogKey} from './dialog_keys.js'; export const EXPORT_SETTINGS_KEY = 'freevideo.editor.export-settings'; -const defaults = {short: null, quality: 'high', range: 'whole', only: null, sound_format: 'm4a', fps: 24}; +const defaults = {short: null, quality: 'high', range: 'whole', only: null, sound_format: 'm4a', fps: 24, audio: null}; export const FRAME_RATES = [24, 48, 60]; const active = new WeakSet(); const style = document.createElement('link'); @@ -49,6 +49,8 @@ function settings(record, selection, value, {remembered = false, fps = true} = { range: value.range === 'selected' && exportRange(record, selection) ? 'selected' : 'whole', only: !remembered && value.only === 'sound' ? 'sound' : null, sound_format: value.sound_format === 'wav' ? 'wav' : 'm4a', + // Like sound-only, lossless is not remembered: it makes a .mov outside the library, so it is chosen each time. + audio: !remembered && value.audio === 'lossless' ? 'lossless' : null, // 48/60 only where this machine can make the frames in between. fps: fps && FRAME_RATES.includes(value.fps) ? value.fps : defaults.fps, }; @@ -61,6 +63,7 @@ export function exportOptions(record, selection, value) { if (clean.quality !== 'high') options.quality = clean.quality; if (clean.short != null) options.short = clean.short; if (clean.fps !== defaults.fps) options.fps = clean.fps; + if (clean.audio === 'lossless' && hasSound(record, clean.range === 'selected' ? exportRange(record, selection) : null)) options.audio = 'lossless'; } if (clean.range === 'selected') options.range = exportRange(record, selection); return options; @@ -121,6 +124,8 @@ export async function openExportDialog({parent, state, sources, t = en => en, on group('quality', t('Quality', '画质'), [['high', t('High', '高')], ['standard', t('Standard', '标准')], ['small', t('Small file', '省空间')]]); // Without a graphics card the group is left out, not shown greyed. if (fps) group('fps', t('Frame rate', '帧率'), FRAME_RATES.map(rate => [rate, String(rate)])); + // Without sound in the range or with audio only the group is greyed, not hidden, so the window keeps its height. + group('audio', t('Sound', '声音'), [[null, t('Compatible', '通用')], ['lossless', t('Lossless', '无损')]]); group('range', t('Range', '范围'), [['whole', t('Whole edit', '整条')], ['selected', t('Selected range', '选中的范围')]]); const contentRow = group('only', t('Content', '内容'), [[null, t('Video and audio', '画面和声音')], ['sound', t('Audio only', '只声音')]]); const formatRow = group('sound_format', t('Audio only', '只声音'), [['m4a', 'M4A'], ['wav', 'WAV']], contentRow); @@ -149,13 +154,14 @@ export async function openExportDialog({parent, state, sources, t = en => en, on function update() { if (!exportRange(state.record, state.selection)) value.range = 'whole'; const audible = hasSound(state.record, chosenRange()); - if (!audible) value.only = null; + if (!audible) { value.only = null; value.audio = null; } const sound = value.only === 'sound'; for (const {name, controls, choices} of groups) [...controls.children].forEach((node, i) => { node.setAttribute('aria-pressed', String(value[name] === choices[i][0])); node.disabled = sound && ['short', 'quality', 'fps'].includes(name) || name === 'range' && choices[i][0] === 'selected' && !exportRange(state.record, state.selection) - || name === 'only' && choices[i][0] === 'sound' && !audible; + || name === 'only' && choices[i][0] === 'sound' && !audible + || name === 'audio' && (sound || !audible); }); formatRow.hidden = !sound; const range = chosenRange(), parts = affected(), n = parts.length; @@ -169,7 +175,7 @@ export async function openExportDialog({parent, state, sources, t = en => en, on // Same rounding as the player's total, so one edit never reads 0:31 there and 0:32 here. const total = model.exportFrames(state.record), part = range && !(range.start === 0 && range.frames === total); const time = part ? `${transportTime(range.start)} – ${transportTime(range.start + range.frames)}` : transportTime(total); - summary.textContent = `${time} · ${sound ? value.sound_format.toUpperCase() : `${size.width} × ${size.height}`}`; + summary.textContent = `${time} · ${sound ? value.sound_format.toUpperCase() : `${size.width} × ${size.height}`}${!sound && value.audio === 'lossless' ? ' · MOV' : ''}`; } let closed = false; const cleanups = []; diff --git a/web/editor_genbar.js b/web/editor_genbar.js index 43707a57..02810aa1 100644 --- a/web/editor_genbar.js +++ b/web/editor_genbar.js @@ -484,11 +484,18 @@ export function createEditorGenbar(host, {state, t, actions, text = ''}) { const phone = typeof matchMedia === 'function' ? matchMedia('(max-width: 680px)') : null; const fitNote = () => { if (disposed) return; - const line = phone?.matches && !note.hidden ? Math.ceil(note.getBoundingClientRect().height) + 8 : 0; + // On a wide window the line sits on the bar's row; when its sentence would be cut, or the description would be pressed + // under 140 px, it takes a row of its own above the bar, as it does on a phone (editor.css [data-note-row]). + host.removeAttribute('data-note-row'); + if (!phone?.matches && !note.hidden) { + const words = note.querySelector('.fv-ed-gen-note-text'); + if ((words && words.scrollWidth > words.clientWidth) || input.getBoundingClientRect().width < 140) host.setAttribute('data-note-row', 'true'); + } + const line = (phone?.matches || host.hasAttribute('data-note-row')) && !note.hidden ? Math.ceil(note.getBoundingClientRect().height) + 8 : 0; host.closest('.fv-editor')?.style.setProperty('--fv-ed-note-growth', `${line}px`); }; const noteResize = typeof ResizeObserver === 'function' ? new ResizeObserver(fitNote) : null; - noteResize?.observe(note); phone?.addEventListener?.('change', fitNote); fitNote(); + noteResize?.observe(note); noteResize?.observe(host); noteResize?.observe(input); phone?.addEventListener?.('change', fitNote); fitNote(); // The box shows the description of the planned parts chosen and is written to them when the choice moves // on, the box is left or Generate is pressed. What is typed with no part or range chosen goes to the next // part chosen that has no description yet. @@ -514,6 +521,7 @@ export function createEditorGenbar(host, {state, t, actions, text = ''}) { input.oninput = () => { typed(); render(); }; input.onblur = () => { if (dirty) { commit(); bind(); } }; input.onkeydown = event => { + expand.undoKeys(event); // the editor hands this box its keys here, before its own shortcuts if (event.key !== 'Enter' || event.isComposing || event.keyCode === 229) return; // ⌘/Ctrl+Enter generates, as in the creative panel and the image view; Enter alone starts a new line. if ((event.ctrlKey || event.metaKey) && !event.shiftKey) { diff --git a/web/editor_picture_session.js b/web/editor_picture_session.js index 80cb13c1..653179e0 100644 --- a/web/editor_picture_session.js +++ b/web/editor_picture_session.js @@ -50,6 +50,14 @@ export function pictureSession(state, t) { if (session.canEdit(find(state.record, id))) state.apply(t('Video', '画面'), r => setPicture(r, id, {...PICTURE_DEFAULTS, ...fields})); emit(); }, cancel, + // Escape stops a preview drag, and that is the whole of that key press (the editor then leaves the selection alone). + // A number box of the picture page takes its own Escape (clearing what was typed or its correction) the same way. + cancelDraft() { + if (draft) { cancel(); return true; } + const box = document.activeElement; + if (box?.tagName === 'INPUT' && box.type !== 'range' && box.closest?.('.fv-ed-adjust-picture') && box.onkeydown) { box.onkeydown(new KeyboardEvent('keydown', {key: 'Escape'})); return true; } + return false; + }, change(id, fields) { cancel(); if (!session.canEdit(find(state.record, id))) return; state.apply(t('Video', '画面'), r => setPicture(r, id, fields)); }, keyboard(event) { const input = event.target?.closest?.('.fv-ed-adjust-picture') && event.target?.tagName === 'INPUT'; diff --git a/web/editor_player.js b/web/editor_player.js index b9063b78..bc9d6be2 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 {createPlayBar} from './fv_player.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) { @@ -428,7 +429,8 @@ 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; setHidden(closePreview, true); } + let previewBar = null; + function clearPreview() { if (preview) { previewBar?.destroy(); previewBar = null; 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; @@ -473,9 +475,11 @@ export function createEditorPlayer(host, transport, {state, sources, api, t, err const view = (frame.closest('dialog, :fullscreen') || document.documentElement).getBoundingClientRect(); const room = Math.max(0, (inner - frame.offsetWidth) / 2); const middle = stage.left + (parseFloat(style.paddingLeft) || 0) + inner / 2; - const shift = Math.round(Math.max(-room, Math.min(room, view.left + view.width / 2 - middle))); // Set on the view so the transport's play group lines up with the picture too. const root = frame.closest('.fv-editor') || frame; + // With the adjust drawer open over the stage's right side (below 1280 px) the stage already leaves its room (margin), so + // the picture is centred in what is left, not on the window, or it would sit against the drawer. + const shift = root.dataset?.adjustOpen === 'true' ? 0 : Math.round(Math.max(-room, Math.min(room, view.left + view.width / 2 - middle))); root.style.setProperty('--fv-ed-center-shift', `${shift}px`); // The transport row spans the edit's frame (the project's shape in this stage), so its time starts under the // picture's left edge and its tools end under the right edge. It follows the project's shape, not the part under @@ -518,13 +522,13 @@ export function createEditorPlayer(host, transport, {state, sources, api, t, err if (disposed) return; const previousSize = previewSize || {width: state.record.width, height: state.record.height}; pause(); clearPreview(); const metadata = sources.get(sourceKey(source)); if (!metadata?.video && !metadata?.audio) { render(); return; } - preview = el(metadata.video ? 'video' : 'audio', 'fv-ed-source-preview'); preview.controls = true; preview.playsInline = true; + preview = el(metadata.video ? 'video' : 'audio', 'fv-ed-source-preview'); preview.playsInline = true; if (metadata.video && Number.isFinite(metadata.width) && Number.isFinite(metadata.height) && metadata.width >= 2 && metadata.height >= 2) previewSize = {width: metadata.width, height: metadata.height}; else if (!metadata.video) previewSize = previousSize; previewProject = pictureLayout(state.record); preview.onended = () => { clearPreview(); render(); }; - preview.src = mediaURL(api, metadata.video || metadata.audio); frame.append(preview); closePreview.hidden = false; render(); preview.play().catch(() => {}); + preview.src = mediaURL(api, metadata.video || metadata.audio); frame.append(preview); previewBar = createPlayBar(preview, t); previewBar.bar.classList.add('fv-player-over'); frame.append(previewBar.bar); closePreview.hidden = false; render(); preview.play().catch(() => {}); }, dispose() { disposed = true; playing = false; centring?.disconnect(); opening?.disconnect(); if (typeof window !== 'undefined') window.removeEventListener?.('resize', centre); chainRequest?.abort(); removeChains(); cancelAnimationFrame(raf); unsubscribe(); stopPictureEdit(); clearPreview(); audioPreview.dispose(); allMedia().forEach(media => { media.pause(); media.onloadedmetadata = media.onerror = null; media.removeAttribute('src'); delete media.dataset.source; media.load(); media.remove(); }); playButton.onclick = closePreview.onclick = null; picturePreview.dispose(); pictureGuide.dispose(); audioContext?.close().catch(() => {}); }, diff --git a/web/editor_store.js b/web/editor_store.js index 0f817aa0..fcfb7a45 100644 --- a/web/editor_store.js +++ b/web/editor_store.js @@ -265,6 +265,12 @@ export function createEditorStore(api, {t = en => en, notify = () => {}, onGener const store = { sources, cache, activateProject, + // The page is going away for good: give the lease back now, so deleting this edit from the next page is not refused for up to a minute. + releaseLease() { + const id = activeProject; if (!id) return; + activeProject = null; clock.clearTimeout(sessionTimer); sessionTimer = null; + try { Promise.resolve(request('/freevideo/editor/project/session', {...post({id, session: session.session, release: true}), keepalive: true})).catch(() => {}); } catch {} + }, get uploading() { return uploads.size > 0; }, // What deleting this edit also removes (media only it uses). Empty when the server cannot say. async residue(id) { diff --git a/web/editor_toolbar_more.js b/web/editor_toolbar_more.js index e9786e27..e513f872 100644 --- a/web/editor_toolbar_more.js +++ b/web/editor_toolbar_more.js @@ -1,6 +1,6 @@ // At phone widths the track toolbar keeps one row; the tools outside `keep` move behind ⋯ and come back on a wider window. // 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)'; +const NARROW = '(max-width:680px)', TOUCH = '(pointer:coarse) and (min-width:681px)', TOUCH_WIDE = '(pointer:coarse) and (min-width:1180px)'; 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'; diff --git a/web/editor_tracks.css b/web/editor_tracks.css index 475994cd..1b3b522c 100644 --- a/web/editor_tracks.css +++ b/web/editor_tracks.css @@ -182,6 +182,7 @@ .fv-studio.fv-editor .fv-ed-snap-line{width:1px;background:var(--fv-accent);box-shadow:0 0 0 .5px var(--fv-accent-line)} .fv-studio.fv-editor .fv-ed-snap-line::before{content:"";position:absolute;top:-8px;left:-4px;width:9px;height:9px;background:var(--fv-accent);clip-path:polygon(50% 0,100% 50%,50% 100%,0 50%)} .fv-studio.fv-editor .fv-ed-insertion-line{background:var(--fv-fg)} +.fv-studio.fv-editor .fv-ed-insertion-line.fv-ed-blocked-insertion{background:var(--fv-danger)} /* Playhead: the accent line; its tab sits on the ruler and is easy to take (28 px grip around a 12 × 16 tab). */ .fv-studio.fv-editor .fv-ed-playhead{width:1.5px;margin-left:-.75px;background:var(--fv-accent)} .fv-studio.fv-editor .fv-ed-playhead-handle{left:calc(-14px + var(--fv-ed-handle-shift,0px));top:-16px;width:28px;height:28px;border-radius:var(--fv-r-sm);background:transparent;box-shadow:none} @@ -243,6 +244,8 @@ /* 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} +/* The track area starts 8 px in, so the sticky hint pins 8 px in too: scrolling does not move it. */ +.fv-studio.fv-editor .fv-ed-track-empty{left:8px} /* Crossfade junction (drawn by editor_audio.js inside the timeline): a 28 × 28 target at the top of the join, the diamond drawn inside it. It sits in the upper part of the row so the lower part of the same join still takes a trim. */ .fv-studio.fv-editor .fv-ed-track-view .fv-ed-audio-junction{top:-6px;width:28px;height:28px;transform:translateX(-50%);border:0;border-radius:var(--fv-r-sm);background:transparent!important;box-shadow:none!important} @@ -255,7 +258,7 @@ columns — mute, solo, lock — at the same x on every row; a row without solo leaves that cell empty. The Audio 2 key sits in the same columns as a head: its sign in the icon column, its words in the name column. */ @media(min-width:521px){ - .fv-studio.fv-editor .fv-ed-track-view .fv-ed-track-head{display:grid;grid-template-columns:16px minmax(0,1fr) 84px;align-items:center;column-gap:8px;padding:0 4px 0 12px;justify-content:stretch} + .fv-studio.fv-editor .fv-ed-track-view .fv-ed-track-head{display:grid;grid-template-columns:16px minmax(0,1fr) 84px;align-items:center;column-gap:6px;padding:0 2px 0 12px;justify-content:stretch} /* The icon column shows each track's icon (editor_audio.css hid them when the heads had no columns). */ .fv-studio.fv-editor .fv-ed-track-view .fv-ed-track-head>svg{grid-column:1;display:block;width:16px;height:16px;color:var(--fv-fg3)} .fv-studio.fv-editor .fv-ed-track-view .fv-ed-track-head>span:first-of-type{grid-column:2;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap} @@ -265,8 +268,8 @@ .fv-studio.fv-editor .fv-ed-track-view .fv-ed-audio-track-switch[data-flag=solo]{grid-column:2} .fv-studio.fv-editor .fv-ed-track-view :is(.fv-ed-audio-track-switch,.fv-ed-text-track-controls button)[data-flag=locked]{grid-column:3} .fv-studio.fv-editor .fv-ed-track-view .fv-ed-track-heads>.fv-ed-add-audio{display:flex;gap:0;align-items:center;justify-content:flex-start; - left:0;width:100%;margin:0;padding:0 4px 0 12px;border-radius:0;text-align:left;font-size:0;color:var(--fv-fg3)} - .fv-studio.fv-editor .fv-ed-track-view .fv-ed-track-heads>.fv-ed-add-audio::before{content:attr(data-sign);display:grid;place-items:center;flex:none;width:16px;height:16px;margin-right:8px;font-size:14px;line-height:1} + left:0;width:100%;margin:0;padding:0 2px 0 12px;border-radius:0;text-align:left;font-size:0;color:var(--fv-fg3)} + .fv-studio.fv-editor .fv-ed-track-view .fv-ed-track-heads>.fv-ed-add-audio::before{content:attr(data-sign);display:grid;place-items:center;flex:none;width:16px;height:16px;margin-right:6px;font-size:14px;line-height:1} .fv-studio.fv-editor .fv-ed-track-view .fv-ed-track-heads>.fv-ed-add-audio::after{content:attr(data-label);min-width:0;max-width:100%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:var(--fv-fs-1,12px);line-height:16px} .fv-studio.fv-editor .fv-ed-track-view .fv-ed-track-heads>.fv-ed-add-audio:hover:not(:disabled){background:var(--fv-ctl-bg);color:var(--fv-fg)} } @@ -297,6 +300,6 @@ .fv-studio.fv-editor .fv-ed-track-view .fv-ed-track-heads>.fv-ed-add-audio[data-mode=remove]{top:var(--fv-ed-remove-top,0px)!important;left:6px;right:auto;width:28px;height:28px;padding:0;margin:0;justify-content:center;border-radius:8px;background:var(--fv-ed-timeline,var(--fv-bg))} .fv-studio.fv-editor .fv-ed-track-view .fv-ed-track-heads>.fv-ed-add-audio[data-mode=remove]::after{display:none} .fv-studio.fv-editor .fv-ed-track-view .fv-ed-track-heads>.fv-ed-add-audio[data-mode=remove]::before{margin:0} -.fv-studio.fv-editor .fv-ed-track-view .fv-ed-track-heads>.fv-ed-add-audio[data-mode=remove]:not([data-shown=true]):not(:hover){visibility:hidden} +.fv-studio.fv-editor .fv-ed-track-view .fv-ed-track-heads:not([data-hx-a2hover])>.fv-ed-add-audio[data-mode=remove]:not([data-shown=true]):not(:hover){visibility:hidden} .fv-studio.fv-editor .fv-ed-track-view .fv-ed-track-heads[data-hx-a2hover]>.fv-ed-add-audio[data-mode=remove]{visibility:visible} @media(max-width:520px){.fv-studio.fv-editor .fv-ed-track-view .fv-ed-track-heads>.fv-ed-add-audio[data-mode=remove]{left:calc(100% - 32px)}} diff --git a/web/error_panel.js b/web/error_panel.js index e72c77c2..bd5deff4 100644 --- a/web/error_panel.js +++ b/web/error_panel.js @@ -532,6 +532,31 @@ export function failureAdvice(value, t, known = knownError(value)) { ['Upscaling uses a small model (about 5 MB), which could not be downloaded or verified this time.', '放大要用一个约 5 MB 的小模型,这次没能下载,或下载后校验未通过。'], ['Check the network connection or choose another download source in Settings, then try again. If it happens again, choose "Report a problem" to send us the report.', '请检查网络,或在设置里换一个下载源,然后重试。再次出现时,请点击“提交问题”,把报告发给我们。']); + // A video the upscale refuses (frame_upscale.REASONS): the engine's own code picks the cause and the next step. + const refused = /Cannot upscale this video \((outside|missing|no_request|unfinished|preview|fps|streams|size_step|size_4k)\)/.exec(text)?.[1]; + if (refused) { + const why = { + outside: ['It is not in the FreeVideo output folder.', '它不在 FreeVideo 的输出文件夹里。'], + missing: ['The video file is missing or cannot be read.', '找不到这个视频文件,或文件无法读取。'], + no_request: ['A merged or imported video can only be upscaled to the largest size.', '合并或导入的视频只能放大到最大尺寸。'], + unfinished: ['Its generation did not finish.', '它没有生成完成。'], + preview: ['It is a preview.', '它是预览视频。'], + fps: ['It is not 24 fps.', '它不是 24 fps。'], + streams: ["This video's format cannot be upscaled.", '这个视频的格式不能放大。'], + size_step: ['Its size can only be upscaled to the largest size.', '它的尺寸只能放大到最大尺寸。'], + size_4k: ['It is already the largest size.', '它已经是最大的尺寸。']}[refused]; + const next = { + outside: ['Choose a video from Creations.', '请从作品库里选择视频。'], + missing: ['It may have been moved or deleted. Choose another video from Creations.', '它可能已被移动或删除,请从作品库里另选一个视频。'], + no_request: ['Choose the largest “Upscale to” option in the menu, or upscale each clip before merging.', '请在菜单里选“放大到”最大的那一项,或先放大各个片段再合并。'], + unfinished: ['Choose a finished video from Creations.', '请从作品库里选择已完成的视频。'], + preview: ['Generate the full video first, then upscale it.', '请先生成完整视频,再放大。'], + fps: ['Only 24 fps videos can be upscaled. Choose another video.', '只有 24 fps 的视频可以放大,请另选一个视频。'], + streams: ['Choose a video generated by FreeVideo.', '请选择 FreeVideo 生成的视频。'], + size_step: ['Choose the largest “Upscale to” option in the menu.', '请在菜单里选“放大到”最大的那一项。'], + size_4k: ['', '']}[refused]; + return row('upscale-refused', ['This video cannot be upscaled', '这个视频不能放大'], why, next); + } if (/Not enough disk space to save the 4K video/.test(text)) { const megabytes = /about (\d+) MB is needed/.exec(text)?.[1]; return row('upscale-disk', ['Not enough disk space for the upscaled video', '磁盘空间不足,放大后的视频没能保存'], diff --git a/web/freevideo.js b/web/freevideo.js index ca66dad8..4d2d98fb 100644 --- a/web/freevideo.js +++ b/web/freevideo.js @@ -44,6 +44,7 @@ import { MAX_MIDDLE, secondsOf, defaultTime, timeProblems, timeRange, problemTex import { swapState, requestRows, swapMissing, withPrefix, peopleOf } from './replace_state.js'; import { swapMissingText } from './replace_person.js'; import { issueButton } from './issue_button.js'; +import { createPlayBar } from './fv_player.js'; import { userMessage } from './user_message.js'; import { AUDIO_USE, usesOriginal, checkOriginal, checkedLength, failureText, multipleText, createUseSwitch, originalBlocked, stuckText, liftBlock } from './audio_original.js'; @@ -503,8 +504,8 @@ function mediaPanel(node, mount = null) { }, {once: true}); } } else { - preview.controls = true; preview.preload = "metadata"; if (kind === "video") { preview.muted = true; preview.playsInline = true; } - card.append(preview); + preview.preload = "metadata"; if (kind === "video") { preview.muted = true; preview.playsInline = true; } + card.append(preview, createPlayBar(preview, text).bar); } let showLength = () => {}; if (kind === "video" && row.role === "reference") { diff --git a/web/fv_player.css b/web/fv_player.css new file mode 100644 index 00000000..5e714beb --- /dev/null +++ b/web/fv_player.css @@ -0,0 +1,21 @@ +/* Play bar for a video or audio element (fv_player.js). */ +.fv-player-bar{container-type:inline-size;display:flex;align-items:center;gap:4px;width:100%;box-sizing:border-box;min-height:44px;padding:0 6px;color:var(--fv-ink,#e8e8e8);background:var(--fv-card,#1b1b1f);border-radius:var(--fv-r-md,8px);font:12px var(--fv-font,system-ui)} +.fv-player-key{display:grid;place-items:center;flex:none;width:44px;height:44px;min-height:44px;padding:0;border:0;border-radius:var(--fv-r-md,8px);background:transparent;color:inherit;cursor:pointer} +.fv-player-key:hover{background:var(--fv-ctl-bg,#ffffff14)} +.fv-player-key svg{width:20px;height:20px;fill:currentColor;stroke:currentColor;stroke-width:2.2;stroke-linecap:round;stroke-linejoin:round} +.fv-player-track{position:relative;display:flex;align-items:center;flex:1;min-width:0;height:44px;cursor:pointer;touch-action:none;border-radius:var(--fv-r-md,8px)} +.fv-player-rail{position:relative;display:block;width:100%;height:4px;border-radius:2px;background:var(--fv-border,#ffffff2a)} +.fv-player-done{position:absolute;left:0;top:0;bottom:0;border-radius:2px;background:var(--fv-accent-ink,#66b6ff)} +.fv-player-track::after{content:"";position:absolute;left:var(--fv-player-at,0%);top:50%;width:12px;height:12px;margin:-6px 0 0 -6px;border-radius:50%;background:var(--fv-accent-ink,#66b6ff)} +.fv-player-track[aria-disabled=true]{opacity:.5;cursor:default} +.fv-player-sound{margin-left:-4px} +.fv-player-time{flex:none;min-width:8.5ch;padding:0 8px;text-align:right;color:var(--fv-muted,#9a9aa3);font-variant-numeric:tabular-nums;white-space:nowrap} +video.fv-player-video{cursor:pointer} +@media(max-width:480px){.fv-player-time{min-width:0;padding:0 4px;font-size:11px}} +.fv-player-over{position:absolute;left:0;right:0;bottom:0;width:auto;z-index:3;border-radius:0 0 var(--fv-r-sm,6px) var(--fv-r-sm,6px);background:linear-gradient(transparent,#000b);color:#fff} +.fv-player-over[hidden]{display:none} +.fv-player-over .fv-player-time{color:#ffffffcc} +.fv-player-over .fv-player-rail{background:#ffffff40} +audio:has(+ .fv-player-bar){display:none} +/* Too narrow for a progress bar that can be seen or dragged (a short clip's card): leave the keys and the time, not a lone dot. */ +@container (max-width:210px){.fv-player-track{display:none}.fv-player-time{margin-left:auto}} diff --git a/web/fv_player.js b/web/fv_player.js new file mode 100644 index 00000000..a3cff580 --- /dev/null +++ b/web/fv_player.js @@ -0,0 +1,64 @@ +// Our own play bar for a video or audio element in place of the browser's: a play/pause key, a progress bar that can be +// dragged, and the time. Video also plays and pauses on a click. Every part is at least 44 px to hit. +// Loaded at once so the first bar is never drawn bare; a page without a document (the module checks, the page check) skips it. +if (typeof document !== 'undefined') { const sheet = document.createElement('link'); sheet.rel = 'stylesheet'; sheet.href = new URL('./fv_player.css', import.meta.url).href; document.head.append(sheet); } + +const clock = seconds => { + if (!Number.isFinite(seconds) || seconds < 0) return '0:00'; + const whole = Math.floor(seconds), h = Math.floor(whole / 3600), m = Math.floor(whole % 3600 / 60), s = String(whole % 60).padStart(2, '0'); + return h ? `${h}:${String(m).padStart(2, '0')}:${s}` : `${m}:${s}`; +}; +const PLAY = ''; +const LOUD = ''; +const MUTE = ''; +const PAUSE = ''; + +export function createPlayBar(media, t = (en) => en) { + const bar = document.createElement('div'); bar.className = 'fv-player-bar'; + const key = document.createElement('button'); key.type = 'button'; key.className = 'fv-player-key'; + const track = document.createElement('div'); track.className = 'fv-player-track'; track.tabIndex = 0; track.setAttribute('role', 'slider'); + track.setAttribute('aria-label', t('Progress', '进度')); + const rail = document.createElement('span'); rail.className = 'fv-player-rail'; + const done = document.createElement('span'); done.className = 'fv-player-done'; rail.append(done); track.append(rail); + const time = document.createElement('span'); time.className = 'fv-player-time'; + const sound = document.createElement('button'); sound.type = 'button'; sound.className = 'fv-player-key fv-player-sound'; + bar.append(key, track, time, sound); + let shownPaused = null, shownMuted = null; + let dragging = false; + const length = () => Number.isFinite(media.duration) && media.duration > 0 ? media.duration : 0; + const paint = () => { + const total = length(), at = media.currentTime || 0, share = total ? Math.min(1, at / total) : 0; + if (shownPaused !== media.paused) { + shownPaused = media.paused; key.innerHTML = shownPaused ? PLAY : PAUSE; + key.setAttribute('aria-label', shownPaused ? t('Play', '播放') : t('Pause', '暂停')); + } + const quiet = media.muted || media.volume === 0; + if (shownMuted !== quiet) { + shownMuted = quiet; sound.innerHTML = quiet ? MUTE : LOUD; + sound.setAttribute('aria-label', quiet ? t('Turn sound on', '开启声音') : t('Mute', '静音')); sound.setAttribute('aria-pressed', String(quiet)); + } + done.style.width = share * 100 + '%'; track.style.setProperty('--fv-player-at', share * 100 + '%'); + track.setAttribute('aria-valuemin', '0'); track.setAttribute('aria-valuemax', String(Math.round(total))); + track.setAttribute('aria-valuenow', String(Math.round(at))); track.setAttribute('aria-valuetext', `${clock(at)} / ${clock(total)}`); + track.setAttribute('aria-disabled', total ? 'false' : 'true'); + time.textContent = `${clock(at)} / ${clock(total)}`; + }; + const toggle = () => { if (media.paused) media.play().catch(() => {}); else media.pause(); }; + const seek = seconds => { const total = length(); if (!total) return; media.currentTime = Math.max(0, Math.min(total, seconds)); paint(); }; + const from = event => { const box = track.getBoundingClientRect(); return length() * Math.max(0, Math.min(1, (event.clientX - box.left) / (box.width || 1))); }; + key.onclick = toggle; + sound.onclick = () => { if (media.muted || media.volume === 0) { media.muted = false; if (media.volume === 0) media.volume = 1; } else media.muted = true; paint(); }; + track.onpointerdown = event => { if (!length()) return; dragging = true; track.setPointerCapture?.(event.pointerId); seek(from(event)); event.preventDefault(); }; + track.onpointermove = event => { if (dragging) seek(from(event)); }; + track.onpointerup = track.onpointercancel = () => { dragging = false; }; + track.onkeydown = event => { + const step = event.shiftKey ? 10 : 5, total = length(); + const to = {ArrowLeft: media.currentTime - step, ArrowDown: media.currentTime - step, ArrowRight: media.currentTime + step, ArrowUp: media.currentTime + step, Home: 0, End: total}[event.key]; + if (to === undefined || !total) return; seek(to); event.preventDefault(); event.stopPropagation(); + }; + const events = ['play', 'pause', 'timeupdate', 'loadedmetadata', 'durationchange', 'ended', 'seeked', 'emptied', 'volumechange']; + events.forEach(name => media.addEventListener(name, paint)); paint(); + const click = () => toggle(); + if (media.tagName === 'VIDEO') { media.addEventListener('click', click); media.classList.add('fv-player-video'); } + return {bar, destroy() { events.forEach(name => media.removeEventListener(name, paint)); media.removeEventListener('click', click); bar.remove(); }}; +} diff --git a/web/fv_select.js b/web/fv_select.js index 4b98ade7..ab780f47 100644 --- a/web/fv_select.js +++ b/web/fv_select.js @@ -5,43 +5,56 @@ // filter box above a long list (more than SEARCH_FROM options): typing narrows the items, Enter takes the first, Down enters the list. import { listenDialogKey } from './dialog_keys.js'; const SEARCH_FROM = 12; +const MAX_HEIGHT = 360; // about ten rows: a long list scrolls instead of reaching the top of the window const el = (tag, cls, label) => { const e = document.createElement(tag); if (cls) e.className = cls; if (label) e.textContent = label; return e; }; +const shell = select => { const wrap = el('div', 'fv-select'); wrap.append(select); return wrap; }; +const controlled = new WeakSet(); + +// Puts the face on a native select and opens our own menu on it instead of the system list; the select itself stays the visible face. export function skinSelect(select) { - const wrap = el('div', 'fv-select'); - wrap.append(select); - return wrap; + return menuSelect(select, {overlay: true}).wrap; } const CHECK = ''; // `groups` maps an option's data-group to the heading above its run; an option without a group stands alone below a line. -export function menuSelect(select, {groups = {}, search = null} = {}) { - const wrap = skinSelect(select); - wrap.classList.add('fv-select-menu-host'); - select.classList.add('fv-select-native'); select.tabIndex = -1; select.setAttribute('aria-hidden', 'true'); - const trigger = el('button', 'fv-select-trigger'); trigger.type = 'button'; - trigger.setAttribute('aria-haspopup', 'listbox'); trigger.setAttribute('aria-expanded', 'false'); - const face = el('span', 'fv-select-face'); trigger.append(face); +// overlay: the native select stays visible and is the trigger; bare: and it is not wrapped either (a select the page made by itself). +export function menuSelect(select, {groups = {}, search = null, overlay = false, bare = false} = {}) { + controlled.add(select); + overlay = overlay || bare; + const wrap = bare ? null : shell(select); const menu = el('div', 'fv-select-menu'); menu.hidden = true; menu.setAttribute('role', 'listbox'); menu.tabIndex = -1; - wrap.append(trigger, menu); - let items = [], box = null; + let trigger = select, face = null; + if (overlay) { select.setAttribute('aria-haspopup', 'listbox'); } + else { + wrap.classList.add('fv-select-menu-host'); + select.classList.add('fv-select-native'); select.tabIndex = -1; select.setAttribute('aria-hidden', 'true'); + trigger = el('button', 'fv-select-trigger'); trigger.type = 'button'; + trigger.setAttribute('aria-haspopup', 'listbox'); + face = el('span', 'fv-select-face'); trigger.append(face); + } + trigger.setAttribute('aria-expanded', 'false'); + if (wrap && !overlay) wrap.append(trigger, menu); + let items = [], box = null, watch = 0; const refresh = () => { + if (overlay) return; const label = select.getAttribute('aria-label'); if (label) trigger.setAttribute('aria-label', label); - face.textContent = select.selectedOptions[0]?.textContent || ''; + const chosen = select.selectedOptions[0]; face.textContent = chosen?.dataset.label || chosen?.textContent || ''; trigger.disabled = select.disabled; }; const close = (restore = false) => { if (menu.hidden) return; menu.hidden = true; trigger.setAttribute('aria-expanded', 'false'); menu.replaceChildren(); items = []; - if (menu.parentNode !== wrap) wrap.append(menu); + if (wrap && !overlay) { if (menu.parentNode !== wrap) wrap.append(menu); } else menu.remove(); + clearInterval(watch); document.removeEventListener('pointerdown', outside, true); window.removeEventListener('resize', closeNow); window.removeEventListener('blur', closeNow); if (restore) trigger.focus({preventScroll: true}); }; const closeNow = () => close(); - function outside(event) { if (!wrap.contains(event.target) && !menu.contains(event.target)) close(); } + function outside(event) { if (!(wrap || select).contains(event.target) && !menu.contains(event.target)) close(); } function choose(value) { close(true); if (select.value === value) return; @@ -57,7 +70,7 @@ export function menuSelect(select, {groups = {}, search = null} = {}) { for (const child of select.children) { if (child.tagName === 'HR') { if (started && !needle) menu.append(Object.assign(el('div'), {role: 'separator'})); previous = null; continue; } if (child.hidden || child.disabled) continue; - if (needle && !child.textContent.toLocaleLowerCase().includes(needle)) continue; + if (needle && !child.textContent.toLocaleLowerCase().includes(needle)) continue; // matches the whole name, not just the shown label const group = child.dataset.group || ''; if (started && group !== (previous ?? group)) menu.append(Object.assign(el('div'), {role: 'separator'})); const heading = group && group !== previous ? (typeof groups === 'function' ? groups(group) : groups[group]) : ''; @@ -66,7 +79,7 @@ export function menuSelect(select, {groups = {}, search = null} = {}) { const item = el('button', 'fv-select-item'); item.type = 'button'; item.tabIndex = -1; item.setAttribute('role', 'option'); const mark = el('span', 'fv-select-mark'); mark.innerHTML = CHECK; const chosen = child.value === select.value; item.setAttribute('aria-selected', String(chosen)); - item.append(el('span', 'fv-select-label', child.textContent), mark); + item.append(el('span', 'fv-select-label', child.dataset.label || child.textContent), mark); item.onclick = () => choose(child.value); items.push(item); menu.append(item); } @@ -78,7 +91,7 @@ export function menuSelect(select, {groups = {}, search = null} = {}) { function place() { const rect = trigger.getBoundingClientRect(), room = window.innerHeight - rect.bottom - 8; menu.style.minWidth = `${Math.round(rect.width)}px`; - menu.style.maxHeight = `${Math.max(120, Math.max(room, rect.top - 8))}px`; + menu.style.maxHeight = `${Math.min(MAX_HEIGHT, Math.max(120, Math.max(room, rect.top - 8)))}px`; const height = menu.offsetHeight, above = height > room && room < rect.top - 8; const wantLeft = Math.max(8, Math.min(rect.left, window.innerWidth - menu.offsetWidth - 8)); const wantTop = Math.max(8, above ? rect.top - height - 4 : rect.bottom + 4); @@ -92,8 +105,9 @@ export function menuSelect(select, {groups = {}, search = null} = {}) { if (select.disabled || !menu.hidden) return; box = null; menu.replaceChildren(); // A tray with a glass blur or its own overflow would clip a fixed menu; inside an open dialog it is shown from the dialog itself. - const dialog = wrap.closest('dialog[open]'); - if (dialog && menu.parentNode !== dialog) dialog.append(menu); + const dialog = select.closest('dialog[open]'); + if (dialog) { if (menu.parentNode !== dialog) dialog.append(menu); } + else if (!menu.isConnected || overlay) (wrap && !overlay ? wrap : select.parentNode).append(menu); if (search && select.querySelectorAll('option').length > SEARCH_FROM) { const holder = el('div', 'fv-select-search'); box = el('input'); box.type = 'text'; box.autocomplete = 'off'; box.spellcheck = false; box.placeholder = search.placeholder || ''; box.setAttribute('aria-label', search.placeholder || ''); holder.append(box); menu.append(holder); @@ -102,18 +116,21 @@ export function menuSelect(select, {groups = {}, search = null} = {}) { fill(); menu.hidden = false; trigger.setAttribute('aria-expanded', 'true'); place(); + // A list that is drawn again while its menu is open (the row is replaced) would leave a menu that chooses nothing. + watch = setInterval(() => { if (!select.isConnected || select.disabled) close(); }, 200); document.addEventListener('pointerdown', outside, true); window.addEventListener('resize', closeNow); window.addEventListener('blur', closeNow); const chosen = items.find(item => item.getAttribute('aria-selected') === 'true') || items[0]; chosen?.focus({preventScroll: true}); - chosen?.scrollIntoView({block: 'center'}); + chosen?.scrollIntoView?.({block: 'center'}); if (box && !chosen) box.focus({preventScroll: true}); } - trigger.onclick = () => menu.hidden ? open() : close(true); + if (overlay) trigger.addEventListener('mousedown', event => { if (event.button) return; event.preventDefault(); if (select.disabled) return; trigger.focus({preventScroll: true}); menu.hidden ? open() : close(true); }); + else trigger.onclick = () => menu.hidden ? open() : close(true); const keys = event => { const move = {ArrowDown: 1, ArrowUp: -1}[event.key]; if (menu.hidden) { - if (move) { event.preventDefault(); event.stopPropagation(); open(); } + if (move || (overlay && (event.key === ' ' || event.key === 'Enter') && !event.ctrlKey && !event.metaKey)) { event.preventDefault(); event.stopPropagation(); open(); } return; } event.stopPropagation(); @@ -126,14 +143,28 @@ export function menuSelect(select, {groups = {}, search = null} = {}) { event.preventDefault(); const ring = box ? [box, ...items] : items, at = ring.indexOf(document.activeElement); const next = event.key === 'Home' ? 0 : event.key === 'End' ? ring.length - 1 : (at + move + ring.length) % ring.length; - ring[next]?.focus({preventScroll: true}); ring[next]?.scrollIntoView({block: 'nearest'}); + ring[next]?.focus({preventScroll: true}); ring[next]?.scrollIntoView?.({block: 'nearest'}); } }; // A modal dialog takes every key at the window and hands it only to listeners registered this way. - listenDialogKey(wrap, 'keydown', keys); listenDialogKey(menu, 'keydown', keys); + listenDialogKey(wrap || select, 'keydown', keys); listenDialogKey(menu, 'keydown', keys); select.addEventListener('change', refresh); // A row that is switched on or off sets select.disabled in place; the face follows. - new MutationObserver(() => { refresh(); if (select.disabled) close(); }).observe(select, {attributes: true, attributeFilter: ['disabled']}); + if (!overlay) new MutationObserver(() => { refresh(); if (select.disabled) close(); }).observe(select, {attributes: true, attributeFilter: ['disabled']}); refresh(); - return {wrap, trigger, refresh, close}; + return {wrap, trigger, refresh, close, open}; +} + +// A select that a FreeVideo page made without skinSelect gets the same menu when it is first reached. Only inside FreeVideo's own +// containers (where the theme variables exist, so the menu is opaque): the selects of ComfyUI, of other extensions and of the +// settings dialog (no theme variables there) stay as they are. +const OWN = '.fv-studio, .fv-setup, .fv-panel, .fv-image-editor, .fv-create'; +const reach = event => { + const select = event.target?.closest?.('select'); + if (!select || select.multiple || select.size > 1 || controlled.has(select) || select.classList.contains('fv-select-native') || !select.closest(OWN)) return; + menuSelect(select, {bare: true}); // its own mousedown, added now, opens the menu in this same event +}; +if (typeof document !== 'undefined' && document.addEventListener && !globalThis.__fvSelectMenus) { + globalThis.__fvSelectMenus = true; + document.addEventListener('mousedown', reach, true); document.addEventListener('focusin', reach, true); } diff --git a/web/glass/library.css b/web/glass/library.css index af77d28b..e2f6da52 100644 --- a/web/glass/library.css +++ b/web/glass/library.css @@ -66,6 +66,8 @@ :root:root section.fv-failure p{font-size:var(--fv-fs-2,13px);line-height:1.6;margin:var(--fv-sp-4,4px) 0;color:var(--fv-fg2)} :root:root section.fv-failure .fv-failure-next{color:var(--fv-fg);font-weight:500} :root:root section.fv-failure .fv-failure-privacy,:root:root section.fv-failure .fv-failure-location{font-size:var(--fv-fs-1,12px);color:var(--fv-fg3)} +/* The other programs' use of the card says what was measured, quietly: the privacy line's colour, its own size (Iris). */ +:root:root section.fv-failure .fv-other-usage-failure{color:var(--fv-fg3)} :root:root section.fv-failure :is(.fv-failure-cause,textarea,.fv-failure-location){-webkit-user-select:text;user-select:text} :root:root section.fv-failure textarea{border-color:var(--fv-line2);background:var(--fv-ctl-bg);color:var(--fv-fg);font-size:var(--fv-fs-1,12px);border-radius:var(--fv-r-sm)} :root:root section.fv-failure button,:root:root .fv-failure-footer button,:root:root .fv-failure-buttons>button{border-color:var(--fv-line2);border-radius:var(--fv-r-sm);background:var(--fv-ctl-bg);color:var(--fv-fg);font-size:var(--fv-fs-2,13px)} diff --git a/web/glass/look_lux.css b/web/glass/look_lux.css index 56fc1549..599f848f 100644 --- a/web/glass/look_lux.css +++ b/web/glass/look_lux.css @@ -203,12 +203,18 @@ html[data-fv-lux]:root dialog.fv-studio.fv-image .fv-iv-panel{ } html[data-fv-lux]:root dialog.fv-studio.fv-image .fv-iv-panel{isolation:isolate} /* The edit view: its library and its generate bar are the same L1 glass; the preview and the tracks keep their own - ground, and nothing here draws over a clip. The assistant view's two side panels likewise. */ -html[data-fv-lux]:root dialog.fv-studio.fv-editor :is(.fv-ed-library,.fv-ed-genbar), + ground, and nothing here draws over a clip. The assistant view's two side panels likewise. A bar borrowed from the + creation panel brings its own glass, and a backdrop filter on its holder would drop its windows onto the timeline. */ +html[data-fv-lux]:root dialog.fv-studio.fv-editor :is(.fv-ed-library,.fv-ed-genbar:not(.fv-ed-genbar-borrowed)), html[data-fv-lux]:root dialog.fv-studio.fv-autopilot :is(.fv-chat-rail,.fv-chat-side){ background:var(--lx-g1)!important; -webkit-backdrop-filter:var(--lx-blur1)!important;backdrop-filter:var(--lx-blur1)!important; } +/* The adjust panel docks as the same L1 glass from 1280 px; below that it is a drawer floating over the picture and is opaque. */ +@media(min-width:1280px){html[data-fv-lux]:root dialog.fv-studio.fv-editor .fv-ed-adjust-host{ + background:var(--lx-g1)!important;-webkit-backdrop-filter:var(--lx-blur1)!important;backdrop-filter:var(--lx-blur1)!important}} +@media(max-width:1279px){html[data-fv-lux]:root dialog.fv-studio.fv-editor .fv-ed-adjust-host{ + background:var(--lx-s1)!important;-webkit-backdrop-filter:none!important;backdrop-filter:none!important}} /* Fields and blocks in the image view: the chip face. */ html[data-fv-lux]:root dialog.fv-studio.fv-image :is(.fv-iv-mpick,.fv-iv-search,.fv-iv-seg,.fv-iv-prompt,.fv-iv-field){background:var(--lx-chip);box-shadow:inset 0 0 0 1px var(--lx-chip-edge)!important} html[data-fv-lux]:root dialog.fv-studio.fv-image .fv-iv-prompt:focus-within{box-shadow:inset 0 0 0 1px var(--fv-accent-line)!important} @@ -221,7 +227,7 @@ html[data-fv-lux]:not([data-theme=light]):root dialog.fv-studio.fv-image .fv-iv- html[data-fv-lux][data-theme=light]:root dialog.fv-studio.fv-create .fv-stage{box-shadow:0 24px 50px -30px rgb(30 40 60 / .35)!important} /* ── 10. Glass off, and stillness ───────────────────────────────────────────────────────────────────────────── */ -:is(html[data-glass=solid],html.lite)[data-fv-lux]:root dialog.fv-studio :is(.fvs-console,.fv-recent,.fvs-rail,.fv-iv-panel,.fv-view-switch,.fv-tb-cap,.fv-ed-library,.fv-ed-genbar,.fv-chat-rail,.fv-chat-side){ +:is(html[data-glass=solid],html.lite)[data-fv-lux]:root dialog.fv-studio :is(.fvs-console,.fv-recent,.fvs-rail,.fv-iv-panel,.fv-view-switch,.fv-tb-cap,.fv-ed-library,.fv-ed-adjust-host,.fv-ed-genbar,.fv-chat-rail,.fv-chat-side){ -webkit-backdrop-filter:none!important;backdrop-filter:none!important;background:var(--lx-s1)!important; } :is(html[data-glass=solid],html.lite)[data-fv-lux]:root :is(dialog.fv-studio .fvs-tray[open],dialog.fv-studio .fvs-info-panel,.fvp.fvp-pop){ @@ -230,7 +236,7 @@ html[data-fv-lux][data-theme=light]:root dialog.fv-studio.fv-create .fv-stage{bo /* Glass off also means a weak machine: the light stays, and stays still. */ :is(html[data-glass=solid],html.lite)[data-fv-lux]{--lx-in-play:paused!important} @media (prefers-reduced-transparency:reduce){ - html[data-fv-lux]:root dialog.fv-studio :is(.fvs-console,.fv-recent,.fvs-rail,.fv-iv-panel,.fv-view-switch,.fv-tb-cap,.fv-ed-library,.fv-ed-genbar,.fv-chat-rail,.fv-chat-side){-webkit-backdrop-filter:none!important;backdrop-filter:none!important;background:var(--lx-s1)!important} + html[data-fv-lux]:root dialog.fv-studio :is(.fvs-console,.fv-recent,.fvs-rail,.fv-iv-panel,.fv-view-switch,.fv-tb-cap,.fv-ed-library,.fv-ed-adjust-host,.fv-ed-genbar,.fv-chat-rail,.fv-chat-side){-webkit-backdrop-filter:none!important;backdrop-filter:none!important;background:var(--lx-s1)!important} html[data-fv-lux]:root :is(dialog.fv-studio .fvs-tray[open],dialog.fv-studio .fvs-info-panel,.fvp.fvp-pop){-webkit-backdrop-filter:none!important;backdrop-filter:none!important;background:var(--lx-s2)!important} } @media (prefers-reduced-motion:reduce){ diff --git a/web/glass/polish.css b/web/glass/polish.css index 0295d711..c7281d73 100644 --- a/web/glass/polish.css +++ b/web/glass/polish.css @@ -69,9 +69,7 @@ html:not([data-fv-polish="off"]) :where(.fv-studio,.fv-setup,.fv-panel) progress html:not([data-fv-polish="off"]) :is(.fv-studio,.fv-topbar,.fv-library,.fv-select-menu) :is(button,a,summary,input,textarea,select,[role=button],[role=tab],[role=option],[role=menuitem]){ transition-property:background-color,border-color,color,fill,stroke,opacity,box-shadow,outline-color;transition-duration:.14s;transition-timing-function:cubic-bezier(.2,.8,.2,1); } -/* Keyboard focus: one thin ring, no glow. Text fields take the ring on their own edge. */ -html:not([data-fv-polish="off"]) :is(.fv-studio,.fv-topbar,.fv-library,.fv-select-menu) :is(button,a,summary,[role=button],[role=tab],[role=slider],[role=separator]):focus-visible{outline:2px solid var(--fv-focus);outline-offset:2px} -html:not([data-fv-polish="off"]) :is(.fv-studio,.fv-library) :is(textarea,input:not([type=checkbox],[type=radio],[type=range])):focus-visible{outline:1px solid var(--fv-focus)!important;outline-offset:-1px!important;box-shadow:none} +/* Keyboard focus rings come from a11y.css (one ring for every control). */ html:not([data-fv-polish="off"]) .fv-editor :is(.fv-ed-description-box,.fv-ed-search):focus-within{box-shadow:none;border-color:var(--fv-accent-line)} /* Disabled: dimmed once, no pointer. */ html:not([data-fv-polish="off"]) :is(.fv-studio,.fv-library) :is(button,input,textarea,select):disabled{cursor:default} diff --git a/web/health.js b/web/health.js index 990bb522..52d1b54f 100644 --- a/web/health.js +++ b/web/health.js @@ -13,7 +13,7 @@ const t = (en, zh) => cn ? zh : en; // launcher.js removes this flag during setup; read it before that. const launchVisit = query.get('freevideo') === 'launch'; // Every script this folder ships; a test keeps the list in step with web/*.js. -export const MODULES = ['audio_original.js', 'chat_data.js', 'phone_model.js', 'phone.js', 'lan_access.js', 'monitor_panel.js', 'qrcodegen.js', 'agent_activity.js', 'agent_confirm_settings.js', 'private_pin.js', 'private_settings.js', 'agent_connect.js', 'agent_session.js', 'autopilot.js', 'autopilot_chat.js', 'chat_attachments.js', 'autopilot_conversations.js', 'browser_extension.js', 'caret_rect.js', 'chain_support.js', 'chain_rules.js', 'timed_prompt.js', 'capability_view.js', 'cast_generate.js', 'cast_mention.js', 'cast_overlay.js', 'cast_source.js', 'compatibility.js', 'entry_showcase.js', 'engine_exit.js', 'error_panel.js', 'first_run_guide.js', 'fonts.js', 'freevideo.js', 'generation_progress.js', +export const MODULES = ['fv_player.js', 'audio_original.js', 'chat_data.js', 'phone_model.js', 'phone.js', 'lan_access.js', 'monitor_panel.js', 'qrcodegen.js', 'agent_activity.js', 'agent_tasks.js', 'agent_confirm_settings.js', 'private_pin.js', 'private_settings.js', 'agent_connect.js', 'agent_session.js', 'autopilot.js', 'autopilot_chat.js', 'chat_attachments.js', 'autopilot_conversations.js', 'browser_extension.js', 'caret_rect.js', 'chain_support.js', 'chain_rules.js', 'timed_prompt.js', 'capability_view.js', 'cast_generate.js', 'cast_mention.js', 'cast_overlay.js', 'cast_source.js', 'compatibility.js', 'entry_showcase.js', 'engine_exit.js', 'error_panel.js', 'first_run_guide.js', 'fonts.js', 'freevideo.js', 'generation_progress.js', 'editor.js', 'editor_actions.js', 'editor_lifecycle.js', 'editor_adjust.js', 'editor_adjust_picture.js', 'editor_picture_fields.js', 'editor_picture_session.js', 'editor_preview_picture.js', 'editor_entry.js', 'editor_expand.js', 'editor_export_dialog.js', 'editor_first_frame.js', 'editor_media_references.js', 'editor_references.js', 'middle_frames.js', 'editor_genbar.js', 'editor_duration.js', 'editor_geometry.js', 'editor_library.js', 'editor_menu.js', 'editor_stems.js', 'editor_record.js', 'editor_record_model.js', 'editor_voice.js', 'editor_voice_install.js', 'editor_voice_model.js', 'editor_voice_store.js', 'editor_model.js', 'editor_frame.js', 'editor_player.js', 'editor_room.js', 'editor_select.js', 'editor_state.js', 'editor_store.js', 'editor_tracks.js', 'editor_generation.js', 'editor_transport.js', 'editor_transport_model.js', 'editor_audio.js', 'editor_audio_model.js', 'editor_audio_notes.js', 'editor_audio_replace.js', 'editor_audio_rules.js', 'editor_music.js', 'editor_music_model.js', 'editor_speed.js', 'editor_speed_model.js', 'editor_failure.js', 'editor_header_fit.js', 'studio_header_fit.js', 'editor_loader.js', 'editor_text_coverage.js', 'editor_text.js', 'editor_toolbar_more.js', 'editor_text_model.js', 'editor_text_layout.js', 'editor_notes.js', 'editor_icons.js', 'dialog_keys.js', 'dom_quiet.js', 'done_notify.js', 'file_failure.js', 'has_mirror.js', 'failure_issue.js', 'feedback.js', 'frame_sizes.js', 'health.js', 'image_commands.js', 'image_editor.js', 'image_editor_engine.js', 'image_generation.js', 'image_lora.js', 'image_view.js', 'launch_visit.js', 'launcher.js', 'length_plan.js', 'lora_triggers.js', 'lora_check.js', 'library.js', 'motion.js', 'native_errors.js', 'translate_guard.js', 'output_download.js', 'port_notice.js', 'preview_scene.js', 'progress_connection.js', 'prompt_draft.js', 'prompt_enhance.js', 'prompt_references.js', 'prompt_sections.js', 'prompt_terms.js', 'request_assets.js', 'repair_hint.js', 'report_issue.js', 'issue_button.js', 'studio_recent.js', 'media_queue.js', 'work_media.js', 'task_groups.js', diff --git a/web/image_generation.js b/web/image_generation.js index 68a0ae13..3b32514d 100644 --- a/web/image_generation.js +++ b/web/image_generation.js @@ -61,6 +61,9 @@ export function blankCanvasSize(ratio, sizes = null, tier = 'standard') { const units = Math.floor(Math.sqrt(side ** 2 / (w * h * 32 ** 2))); return {width: w * units * 32, height: h * units * 32}; } +// The step word a caller names for a failure that carries no step. A failure with a reason of its own needs none; the +// catch-all generation_failed, with no stage and no report either, names where it was caught instead of "unreported". +export const originStep = (error, word) => error?.step || (!error?.code || (error.code === 'generation_failed' && !error.stage && !error.report_id) ? word : ''); const failure = (code, info = {}) => Object.assign(new Error(code || 'generation_failed'), { code: code || 'generation_failed', report_id: info.report_id || null, stage: info.stage || '', fitted: info.fitted || null, memory: info.memory || '', @@ -75,7 +78,7 @@ export function createImageGenClient(fetchImpl = globalThis.fetch.bind(globalThi try { response = await fetchImpl(path, options); } catch (error) { throw failure(error instanceof TypeError ? 'connection_lost' : 'engine_error', {stage: 'start'}); } try { value = await response.json(); } catch { throw failure('engine_error', {stage: 'start'}); } if (!response.ok || value[p.error] && !value[p.phase] && !value.state) - throw failure(value[p.error], value[p.error] ? value : {...value, step: `http_${response.status}`}); + throw failure(value[p.error], {...value, step: originStep({...value, code: value[p.error]}, `http_${response.status}`)}); return value; } async function post(action, value, retried = false) { @@ -638,7 +641,7 @@ export function createImageGenSession({client, prepare, apply, onChange = () => if (onBusy && row.status === 'failed' && row.failure?.code === 'busy') { tasks.placed?.(row); onBusy(); return; } forget(); tasks.placed?.(row); if (row.status === 'cancelled') emit({running: false, job: null, stage: '', fraction: 0, waiting: '', stopping: false, error: '', report_id: null, memory: ''}); - else { const reason = row.failure || {}; emit({running: false, job: null, waiting: '', stopping: false, ...failed({...reason, code: reason.code || 'generation_failed', step: reason.step || (reason.code ? '' : 'task_row')})}); } + else { const reason = row.failure || {}; emit({running: false, job: null, waiting: '', stopping: false, ...failed({...reason, code: reason.code || 'generation_failed', step: originStep(reason, 'task_row')})}); } }, {id}); // The row may have ended before subscribe returned. if (ended) { off(); off = null; } @@ -760,7 +763,7 @@ export function createImageGenSession({client, prepare, apply, onChange = () => } const row = await whenFree(async () => { const answer = await client.generate(request_); - if (!answer.job) throw failure(answer.error, answer.error ? answer : {...answer, step: 'submit'}); + if (!answer.job) throw failure(answer.error, {...answer, step: originStep({...answer, code: answer.error}, 'submit')}); return answer; }, alive, resend); if (!row) return; @@ -918,7 +921,7 @@ export function createImageGeneration({client, renderer, t, getDoc, getSelection // The button is only marked unavailable, so a click while the service is being checked is turned away here. const now = session.state(); if (now.checking || !now.info?.installed) return; - if (!prompt.trim()) { + if (!prompt.trim() || prompt.length > 2000) { promptRequired = true; update(); if (mounted) { const {input} = mounted; @@ -1057,7 +1060,10 @@ export function createImageGeneration({client, renderer, t, getDoc, getSelection mounted.failureKey = null; note.textContent = pack ? pack.note : missing ? imagePackUnavailableMessage(state.info, t) - : promptRequired ? t('Enter a prompt first.', '请先填写提示词。') + // A trigger word a LoRA adds in front can take the prompt past what the engine accepts. + : promptRequired ? (prompt.length > 2000 + ? t(`The prompt is over 2,000 characters. Shorten it by ${prompt.length - 2000} and try again.`, `提示词超过 2000 字。请缩短 ${prompt.length - 2000} 字后重试。`) + : t('Enter a prompt first.', '请先填写提示词。')) : state.running && state.waiting ? t(...(QUEUE_LABELS[state.waiting] || QUEUE_LABELS.image)) : state.running && state.fitted ? t(...memoryWords([`Not enough GPU memory. Retrying at ${state.fitted.width}\u00a0×\u00a0${state.fitted.height}`, `显存不足,改用 ${state.fitted.width}\u00a0×\u00a0${state.fitted.height} 重试`], state.info?.unified_memory)) + ' · ' + percent @@ -1144,7 +1150,7 @@ export function createImageGeneration({client, renderer, t, getDoc, getSelection input.addEventListener('blur', () => grow()); input.oninput = () => { prompt = input.value; - if (prompt.trim()) promptRequired = false; + if (prompt.trim() && prompt.length <= 2000) promptRequired = false; clearAttention(); session.clearError(); grow(); }; input.onkeydown = event => { diff --git a/web/image_view.js b/web/image_view.js index 01222cc7..bb675314 100644 --- a/web/image_view.js +++ b/web/image_view.js @@ -1382,6 +1382,21 @@ export function openImageView(node, {studio = null, client: given = null, poll = const seed = seedInput.value === '' ? undefined : Number(seedInput.value); // The boxes as they are now (MOSS only); the frame gives way to the picture being made. const boxes = layoutActive() ? layout.request() : [], drawn = boxes.length ? layout.snapshot().filter(item => item.line.trim()) : null; + // The words the engine will read (the picture marks written out, the pictures listed): it takes 1 to 2,000 characters of them. + const engineSeed = seed ?? Math.floor(Math.random() * 1e9); + const sentWords = () => boxes.length && !prompt.value.trim() ? layout.caption() : engineText(engineSeed); + // False, with the reason said, when the engine would refuse the words; asked again after a rewrite that was still running has finished. + const fits = () => { + const length = sentWords().trim() ? sentWords().length : 0; + if (length > 0 && length <= 2000) return true; + note.dataset.kind = ''; + say(length > 2000 + ? t(`With the picture references counted, the prompt is over 2,000 characters. Shorten it by ${length - 2000} and try again.`, + `加上图片引用后,提示词超过 2000 字。请缩短 ${length - 2000} 字后重试。`) + : t('The prompt has only picture references and no words. Describe the picture you want, then try again.', '提示词里只有图片引用,没有文字。请写上要生成的画面后重试。')); + return false; + }; + if (!fits()) { prompt.focus(); return; } layoutOn = false; say(''); note.dataset.kind = ''; failure = null; const mine = running = {cancelled: false}, withImages = references.length > 0, sent = size(), tierNow = tier; render(); drawWorks(); progressLine.textContent = progressSub.textContent = ''; runReport.replaceChildren(); runReport.dataset.id = ''; doneReport.replaceChildren(); lastReport = null; @@ -1392,6 +1407,7 @@ export function openImageView(node, {studio = null, client: given = null, poll = for (const r of references.slice(0, cap_(model))) names.push(await client.upload(r.file)); if (mine.cancelled) return; if (!enhancerOff() && await enhancer.beforeGenerate() === false) { say(''); if (running === mine) running = null; level.hidden = true; render(); drawWorks(); return; } + if (!fits()) { if (running === mine) running = null; level.hidden = true; render(); drawWorks(); fits(); prompt.focus(); return; } startJobSources(); const loras = loraRow.value(model.id); let id; @@ -1399,7 +1415,7 @@ export function openImageView(node, {studio = null, client: given = null, poll = for (;;) { try { // With boxes and no description, the boxes' lines describe the whole picture. - const words = boxes.length && !prompt.value.trim() ? layout.caption() : engineText(seed ?? Math.floor(Math.random() * 1e9)); + const words = sentWords(); ({id} = await jobs.submit('image', {prompt: words, ...sent, model: model.id, remember: true, images: names, ...(seed === undefined ? {} : {seed}), ...(loras.length ? {loras} : {}), ...(boxes.length ? {layout: boxes} : {})}, {view: 'image', client, meta: {text: prompt.value, withImages, tier: tierNow, width: sent.width, height: sent.height, ...(drawn ? {layout: drawn} : {})}})); break; diff --git a/web/library.css b/web/library.css index 1a21bf73..45665de3 100644 --- a/web/library.css +++ b/web/library.css @@ -170,7 +170,7 @@ dialog.fv-studio.fv-library::backdrop{background:var(--lib-page)} background:transparent;color:var(--fv-fg2);font-size:var(--fv-fs-2,13px);font-weight:500;box-shadow:none} .fv-library .fv-library-selection-actions button[hidden]{display:none} .fv-library .fv-library-selection-actions button:hover:not(:disabled){background:var(--fv-ctl-hover);color:var(--fv-fg)} -.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,.fv-library .fv-library-danger{background:#c8353a;color:#fff;font-weight:600;padding:0 var(--fv-sp-16,16px);white-space:nowrap} .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);max-width:100%;box-sizing:border-box} @@ -368,7 +368,7 @@ dialog.fv-studio.fv-library::backdrop{background:var(--lib-page)} .fv-library[data-detail=true] .fv-library-detail{display:flex}.fv-library[data-detail=true] :is(.fv-library-collection,.fv-library-side){display:none} .fv-library .fv-library-selection{flex-wrap:wrap} .fv-library .fv-library-selection-actions{width:100%;justify-content:flex-end} - .fv-library .fv-library-selection-actions button:not(.fv-library-danger)>span{display:none} + .fv-library .fv-library-selection-actions button:not(.fv-library-danger)>span:not(.fv-lib-icon){display:none} } .fv-library-prompt{display:flex;flex-direction:column;gap:var(--fv-sp-4,4px)} .fv-library-prompt[hidden]{display:none} @@ -397,7 +397,11 @@ dialog.fv-studio.fv-library::backdrop{background:var(--lib-page)} :root dialog.fv-studio.fv-library[data-fv-embedded=true][open]{animation:fv-library-appear var(--fv-dur-2,200ms) var(--fv-ease-out)} .fv-library a.fv-library-menu-item{text-decoration:none} .fv-library-stack{position:absolute;left:var(--fv-sp-8,8px);bottom:var(--fv-sp-8,8px);display:inline-flex;align-items:center;min-width:24px;height:20px;padding:0 var(--fv-sp-4,4px);border-radius:var(--fv-r-sm); - background:rgb(0 0 0 / .55);color:#fff;font-size:var(--fv-fs-1,12px);font-weight:600;pointer-events:none} + background:rgb(0 0 0 / .55);color:#fff;font-size:var(--fv-fs-1,12px);font-weight:600;cursor:pointer} +/* A press area of at least 24 x 24 around the 20 px mark; the look stays. */ +.fv-library-stack::after{content:'';position:absolute;inset:-2px -2px} +.fv-library-stack[aria-expanded=true]{background:var(--fv-accent-fill,#2f7bff);color:#fff} +.fv-library-stack:focus-visible{outline:2px solid #fff;outline-offset:2px;box-shadow:0 0 0 4px rgb(0 0 0 / .6)} /* white ring with a dark outer ring: it reads on any cover and on the pressed blue, in both themes */ .fv-library-stack::before{content:'';flex:none;width:8px;height:8px;margin-right:var(--fv-sp-4,4px);border:1.5px solid currentColor;border-radius:var(--fv-r-xs);box-shadow:2px -2px 0 -1px rgb(0 0 0 / .55),2px -2px 0 0 currentColor} .fv-library-stack[hidden]{display:none} .fv-library .fv-library-selection-actions button:disabled{opacity:.45;cursor:default} @@ -482,7 +486,6 @@ dialog.fv-studio.fv-library::backdrop{background:var(--lib-page)} .fv-library .fv-library-check:hover{border-color:#fff;background:rgb(0 0 0 / .55)} .fv-library-hover{position:absolute;inset:0;width:100%;height:100%;object-fit:cover;opacity:0;pointer-events:none;transition:opacity var(--fv-dur-1,160ms) var(--fv-ease-out,ease-out)} .fv-library-hover[data-on=true]{opacity:1} -.fv-library-stack{cursor:pointer} .fv-library-viewer{--fv-fg:#f3f5f8;--fv-fg2:rgb(243 245 248 / .78);--fv-fg3:rgb(243 245 248 / .56);--fv-line:rgb(255 255 255 / .08);--fv-line2:rgb(255 255 255 / .14); --fv-ctl-bg:rgb(255 255 255 / .06);--fv-ctl-hover:rgb(255 255 255 / .1);background:#0b0c0e;color:var(--fv-fg);color-scheme:dark;animation:fv-library-viewer-in 140ms var(--fv-ease-out,ease-out)} @@ -610,6 +613,8 @@ dialog.fv-library .fv-library-picture>img[data-loaded=true]{opacity:1} .fv-library[data-layout=stage] .fv-library-selection .fv-library-bar-compare{display:none} .fv-library[data-layout=stage] .fv-library-selection-actions{display:flex;flex-wrap:wrap;gap:var(--fv-sp-4,4px);width:100%} .fv-library[data-layout=stage] .fv-library-selection-actions button{flex:1;height:32px;min-height:32px;padding:0 var(--fv-sp-8,8px);font-size:var(--fv-fs-1,12px)} +.fv-library[data-layout=stage] .fv-library-selection-actions button:not(.fv-library-danger){padding:0 10px} +.fv-library[data-layout=stage] .fv-library-selection-actions button:not(.fv-library-danger)>span:not(.fv-lib-icon){display:none} /* Three or four compared on the stage: a 2 x 2, each whole. */ .fv-library-viewer[data-mode=grid] .fv-library-compare-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));grid-template-rows:repeat(2,minmax(0,1fr));gap:var(--fv-sp-8,8px);padding:56px var(--fv-sp-24,24px) var(--fv-sp-24,24px);min-height:0} .fv-library-viewer[data-mode=grid] .fv-library-compare-cell{position:relative;display:grid;min-height:0;margin:0;place-items:center} diff --git a/web/library.js b/web/library.js index b74e622f..d0bfc312 100644 --- a/web/library.js +++ b/web/library.js @@ -4,13 +4,13 @@ import { closeDialog } from './motion.js'; import { resultActions, previewBadge, icon } from './result_actions.js'; import { videoUnavailableText, canExtend } from './studio_extend.js'; import { savedSettings } from './result_reuse.js'; -import { listenDialogKey } from './dialog_keys.js'; +import { listenDialogKey, topDialog } from './dialog_keys.js'; import { isNetworkTypeError, connectionLostText } from './browser_extension.js'; import { issueButton } from './issue_button.js'; import { fileFailureText, responseFileReason } from './file_failure.js'; import { userMessage } from './user_message.js'; import { applyTasks, toggledTask } from './task_groups.js'; -import { outputDownloadURL } from './output_download.js'; +import { outputDownloadURL, zipPayloads, checkZips, postZips } from './output_download.js'; import { attachContextMenu, openContextMenu, contextMenuOpen, compatView, reducedMotion } from './context_menu.js'; import { createMeta, createPictureBin, dayOf, inOrderPictures, matches, needsEverything, pictureRow, readView, saveView, sortRows, workKey, TAG_COLORS } from './library_meta.js'; @@ -584,16 +584,23 @@ export function openLibrary(t, options = {}) { tip(barCancel, t('Cancel', '取消'), t('Keep these creations', '不删除,保留这些作品'), 'Esc'); const barFavorite = button('', () => favoritePicked(), 'fv-quiet fv-library-bar-favorite'); barFavorite.append(line('heart'), el('span', t('Favorite', '收藏'))); + barFavorite.setAttribute('aria-label', t('Favorite', '收藏')); tip(barFavorite, t('Favorite', '收藏'), t('Add the selected creations to Favorites', '把选中的作品加入收藏')); const barTag = button('', () => openTagMenu(barTag, [...picked]), 'fv-quiet fv-library-bar-tag'); barTag.append(line('tag'), el('span', t('Tag', '标签'))); + barTag.setAttribute('aria-label', t('Tag', '标签')); tip(barTag, t('Tag', '标签'), t('Add or remove tags on the selection', '给选中的作品加上或去掉标签')); const barDelete = button('', () => confirmDelete(), 'fv-library-danger'); tip(barDelete, t('Delete', '删除'), t('Delete the selection; undo for 10 seconds', '删除选中的作品,10 秒内可撤销'), 'Delete'); + const barDownload = button('', () => downloadPicked(), 'fv-quiet fv-library-bar-download'); + barDownload.append(line('download'), el('span', t('Download', '下载'))); + barDownload.setAttribute('aria-label', t('Download', '下载')); + tip(barDownload, t('Download', '下载'), t('Save the picked works as a zip file', '将所选作品保存为压缩包')); const barCompare = button('', () => { const keys = [...picked]; if (keys.length === 2) openCompare(keys); }, 'fv-quiet fv-library-bar-compare'); barCompare.append(line('compare'), el('span', t('Compare', '对比'))); + barCompare.setAttribute('aria-label', t('Compare', '对比')); tip(barCompare, t('Compare', '对比'), t('See two creations side by side or with a slider', '并排或用滑块对比两个作品')); - barActions.append(barFavorite, barTag, barCompare, barCancel, barDelete); + barActions.append(barFavorite, barTag, barCompare, barDownload, barCancel, barDelete); bar.append(barLabel, barText, barActions); // The undo note and the selection bar share one sticky dock so they stack instead of covering each other. const dock = el('div', null, 'fv-library-dock'); dock.append(undoBar, bar); @@ -920,7 +927,9 @@ export function openLibrary(t, options = {}) { } // Continue a video into a longer one: the editor opens on it and the room closes. async function extendSaved(saved) { - const isCurrent = () => !disposed && dialog.open && dialog.dataset.closing !== 'true' && works.has(workKey(saved)); + // Still this room's own step: open, in front (a share or delete dialog opened meanwhile keeps its place, as on the + // result bar), and the work still listed. + const isCurrent = () => !disposed && dialog.open && dialog.dataset.closing !== 'true' && topDialog() === dialog && works.has(workKey(saved)); if (!isCurrent()) return; player?.pause(); const run = extend || (async (record, options) => (await import('./studio.js')).openExtendEditor(record, undefined, options)); @@ -939,11 +948,13 @@ export function openLibrary(t, options = {}) { if (!saved) { say(t('This video kept no prompt to reuse.', '这条视频没有保存可复用的提示词。'), true); return; } try { reuseNow().apply(saved); if (reuse) closeDialog(dialog); } catch { say(t('Could not fill in the settings. Try again.', '没能填入设置,请重试。'), true); } } + // A cover with other videos folded under it is named "N results" by the fold (task_groups.js); names loading later keep that. + const foldedCover = card => card.classList.contains('fv-task-head') && card.hasAttribute('aria-expanded'); const cardLabel = row => [workName(row), row.favorite ? t('Favorite', '已收藏') : ''].filter(Boolean).join(' · '); function syncFavorite(row) { const card = cards.get(workKey(row)), badge = card?.querySelector('.fv-library-favorite'); if (badge) badge.hidden = !row.favorite; - card?.setAttribute('aria-label', cardLabel(row)); + if (card && !foldedCover(card)) card.setAttribute('aria-label', cardLabel(row)); } async function saveFavorite(row, favorite, quiet = false) { const id = row.id || row.video.replace(/^FreeVideo\//, '').replace(/\/video\.mp4$/, ''); @@ -1009,6 +1020,12 @@ export function openLibrary(t, options = {}) { const ordered = () => [...grid.querySelectorAll('.fv-library-card')]; // The videos of one task fold under the newest; one task is unfolded at a time, and picking shows every card. let unfolded = null; + // The task of this video unfolds (its others show under it) or folds back; only a task's newest video has the mark. + function toggleTask(row) { + if (!row?.video) return; + unfolded = toggledTask(rows, ordered().map(item => item.dataset.key).filter(isVideo).map(item => works.get(item)?.video), row.video, unfolded); + fold(); + } function fold() { const order = ordered().map(card => card.dataset.key).filter(isVideo).map(key => works.get(key)?.video).filter(Boolean); if (!order.some(video => rows.get(video)?.task === unfolded)) unfolded = null; @@ -1016,10 +1033,26 @@ export function openLibrary(t, options = {}) { const heads = applyTasks({cards: byVideo, rows, order, open: unfolded, selecting, selected: works.get(selected)?.video ?? null, t, label: video => cardLabel(rows.get(video))}); for (const [video, card] of byVideo) { if (!card) continue; - const head = heads.get(video), folded = head && !card.classList.contains('fv-task-open') && !selecting; + // The count mark on a task's newest video is the one control for the fold: pressed while the task is unfolded + // (Iris), pressed again it folds. The others of an unfolded task carry none; while picking, every video shows. + const head = heads.get(video), shownMark = head && !selecting, unfoldedNow = card.classList.contains('fv-task-open'); let stack = card.querySelector('.fv-library-stack'); - if (folded && !stack) { stack = el('span', null, 'fv-library-stack'); card.querySelector('.fv-library-picture')?.append(stack); } - if (stack) { stack.hidden = !folded; if (folded) stack.textContent = String(head.videos.length); } + if (shownMark && !stack) { + stack = el('span', null, 'fv-library-stack'); stack.setAttribute('role', 'button'); stack.tabIndex = 0; + stack.onkeydown = event => { + if (event.key !== 'Enter' && event.key !== ' ') return; + event.preventDefault(); event.stopPropagation(); toggleTask(works.get(card.dataset.key)); + }; + card.querySelector('.fv-library-picture')?.append(stack); + } + if (stack) { + stack.hidden = !shownMark; + if (shownMark) { + stack.textContent = String(head.videos.length); + stack.setAttribute('aria-expanded', String(unfoldedNow)); + stack.setAttribute('aria-label', t(`${head.videos.length} videos from this task`, `同一任务的 ${head.videos.length} 个视频`)); + } + } } countDays(); } @@ -1056,7 +1089,8 @@ export function openLibrary(t, options = {}) { // A card is its picture and its name; size and length stay in the details. card.children[1].textContent = workName(row); card.children[2].textContent = ''; - card.setAttribute('aria-label', cardLabel(row)); cardTip(card, row); + if (!foldedCover(card)) card.setAttribute('aria-label', cardLabel(row)); + cardTip(card, row); } function wantPrompt(row) { if (!row?.id || row.kind === 'image' || prompts.has(row.id) || promptAsked.has(row.id)) return; @@ -1104,10 +1138,7 @@ export function openLibrary(t, options = {}) { pick(key, event.shiftKey); return; } if (selecting) { pick(key, event.shiftKey); return; } - if (isVideo(key) && event.target.closest?.('.fv-library-stack')) { - unfolded = toggledTask(rows, ordered().map(item => item.dataset.key).filter(isVideo).map(item => works.get(item)?.video), row.video, unfolded); - fold(); return; - } + if (isVideo(key) && event.target.closest?.('.fv-library-stack')) { toggleTask(row); return; } if (layout === 'stage') select(key, false); else openViewer(key); }, 'fv-library-card'); card.dataset.key = key; card.dataset.kind = row.kind === 'image' ? 'image' : 'video'; @@ -1446,8 +1477,7 @@ export function openLibrary(t, options = {}) { if (one) { items.push('-'); items.push({id: 'download', icon: 'download', label: one.kind === 'image' ? ['Download picture', '下载图片'] : ['Download video', '下载视频'], run: () => { - const link = el('a'); link.href = one.kind === 'image' ? pictureURL(one) : outputDownloadURL(api, one.video); link.download = one.kind === 'image' ? (one.name || '') : ''; - document.body.append(link); link.click(); link.remove(); + downloadOne(one); }}); if (one.kind !== 'image') { if (one.preview) items.push({id: 'second-pass', icon: 'history', label: ['Run second pass', '继续二采'], @@ -1593,11 +1623,11 @@ export function openLibrary(t, options = {}) { if (fetchSizes) wantedSizes(); const about = size == null ? '' : ` · ${t('about', '约')} ${gb(size)}`; barActions.hidden = false; - barCancel.hidden = !confirming; barFavorite.hidden = barTag.hidden = barCompare.hidden = confirming; + barCancel.hidden = !confirming; barFavorite.hidden = barTag.hidden = barCompare.hidden = barDownload.hidden = confirming; barCompare.disabled = count !== 2 || deleting; if (count !== 2) barCompare.dataset.fvTipWhy = t('Select exactly two creations', '正好选中两个作品时可用'); else delete barCompare.dataset.fvTipWhy; const why = count ? '' : t('Select creations first', '先选择作品'); - for (const control of [barFavorite, barTag, barDelete]) { if (why) control.dataset.fvTipWhy = why; else delete control.dataset.fvTipWhy; } + for (const control of [barFavorite, barTag, barDownload, barDelete]) { if (why) control.dataset.fvTipWhy = why; else delete control.dataset.fvTipWhy; } if (confirming) { barLabel.textContent = t(`Delete ${count} ${count === 1 ? 'creation' : 'creations'}?${size == null ? '' : ` About ${gb(size)}.`}`, `删除 ${count} 个作品?${size == null ? '' : `共约 ${gb(size)}。`}`); barText.textContent = t('They can be brought back for 10 seconds.', '10 秒内可以撤销。'); @@ -1608,7 +1638,7 @@ export function openLibrary(t, options = {}) { barText.textContent = ''; barDelete.textContent = count ? t(`Delete ${count}`, `删除 ${count} 个`) + about : t('Delete', '删除'); barDelete.disabled = deleting || !count; - barFavorite.disabled = barTag.disabled = deleting || !count; + barFavorite.disabled = barTag.disabled = barDownload.disabled = deleting || !count; } barLabel.hidden = !barLabel.textContent; barText.hidden = !barText.textContent; stageFollowsSelection(); @@ -1668,6 +1698,33 @@ export function openLibrary(t, options = {}) { for (const card of ordered()) picked.add(card.dataset.key); confirming = false; syncSelection(); } + // One work: the file itself. Several: one zip file, posted so the browser streams it to disk; notes the count. + function downloadOne(row) { + const link = el('a'); link.href = row.kind === 'image' ? pictureURL(row) : outputDownloadURL(api, row.video); link.download = row.kind === 'image' ? (row.name || '') : ''; + document.body.append(link); link.click(); link.remove(); + } + async function downloadPicked() { + const chosen = [...picked].map(key => works.get(key)).filter(Boolean); + if (!chosen.length || deleting) return; + if (chosen.length === 1) { downloadOne(chosen[0]); return; } + const asked = zipPayloads(chosen); + if (!asked.length) { say(t('These works cannot be downloaded.', '这些作品无法下载。'), true); return; } + let answers; + try { answers = await checkZips(api, asked); } catch { answers = asked.map(() => ({ready: 0, skipped: 0, failed: true})); } + const payloads = asked.filter((_, at) => answers[at].ready > 0); + const count = answers.reduce((sum, answer) => sum + answer.ready, 0); + const left = chosen.length - count; + if (!payloads.length) { + say(answers.some(answer => answer.failed) ? t('Could not start the download. Try again.', '无法开始下载,请重试。') + : t('These works cannot be read.', '无法读取这些作品。'), true); + return; + } + const zips = payloads.length > 1 ? t(` in ${payloads.length} zip files`, `,分成 ${payloads.length} 个压缩包`) : ''; + const missing = left > 0 ? t(`, ${left} could not be read`, `,其中 ${left} 个无法读取`) : ''; + say(t(`Downloading ${count} ${count === 1 ? 'work' : 'works'}${zips}${missing}`, `正在下载 ${count} 个作品${zips}${missing}`), left > 0); + try { await postZips(api, payloads, {alive: () => !disposed}); } + catch { say(t('Could not start the download. Try again.', '无法开始下载,请重试。'), true); } + } async function favoritePicked() { const keys = [...picked], value = !keys.every(key => works.get(key)?.favorite); barFavorite.disabled = true; diff --git a/web/lora_menu.js b/web/lora_menu.js index 1b94ec40..1917e645 100644 --- a/web/lora_menu.js +++ b/web/lora_menu.js @@ -2,11 +2,16 @@ // Files are grouped under their folder, the recently used ones sit on top, and a filter box narrows the list. import {menuSelect} from './fv_select.js'; +const baseOf = name => name.slice(Math.max(name.lastIndexOf('/'), name.lastIndexOf('\\')) + 1).replace(/\.safetensors$/i, ''); const folderOf = name => { const at = Math.max(name.lastIndexOf('/'), name.lastIndexOf('\\')); return at > 0 ? name.slice(0, at) : ''; }; export function loraMenu(select, t, pinned = []) { const recent = new Set(pinned); - for (const option of select.options) option.dataset.group = recent.has(option.value) ? 'recent' : folderOf(option.value); + for (const option of select.children) { + option.dataset.group = recent.has(option.value) ? 'recent' : folderOf(option.value); + // Under a folder heading only the file name is written; the recent list mixes folders and keeps them. + option.dataset.label = option.dataset.group === 'recent' ? option.value.replace(/\.safetensors$/i, '') : baseOf(option.value); + } return menuSelect(select, { groups: group => group === 'recent' ? t('Recent', '最近使用') : group, search: {placeholder: t('Type to filter', '输入文字筛选'), empty: t('No LoRA matches', '没有匹配的 LoRA')}, diff --git a/web/notifications.js b/web/notifications.js index 59a5bf18..e3add1e3 100644 --- a/web/notifications.js +++ b/web/notifications.js @@ -91,6 +91,14 @@ export function noteFromJob(row, previous, now = Date.now()) { reason: reasonOf(row.failure), at: row.finished_at || now}; } // The image models' install, between two reads of the image worker's info: a note when one finishes or fails. +// A failed assistant task: one note with the task's name and its cause; it opens the failure card in the conversation. +export function noteFromAgent(job, {title: name = '', reason = ''} = {}, now = Date.now()) { + if (!job?.id || job.status !== 'failed') return null; + const finished = Date.parse(job.finished_at || '') || 0; + if (!finished || now - finished > LATE_MS) return null; + return {id: `agent:${job.id}:failed`, type: 'agent', job: job.id, status: 'failed', view: 'autopilot', title: String(name).slice(0, 140), reason: String(reason).slice(0, 160), at: finished}; +} +export function addAgentNote(note) { if (note && !store().has(note.id)) store().add(note); } export function installChanges(before = {}, after = {}) { const notes = []; for (const [id, now] of Object.entries(after)) { @@ -130,6 +138,7 @@ const ago = (at, cn = CN) => { export function noteWords(note, cn = CN) { const w = pair => words(pair, cn); if (note.type === 'toast') return {title: note.title || w(['Notice', '提醒']), sub: note.reason || w(['Did not finish', '没有完成'])}; + if (note.type === 'agent') return {title: note.title || w(['Assistant task', '助手任务']), sub: note.reason || w(['See why', '查看原因'])}; if (note.type === 'install') { return note.status === 'done' ? {title: w([`${note.label} is installed`, `${note.label} 已安装`]), sub: w(['Ready to use', '可以使用了'])} : {title: w([`${note.label} did not install`, `${note.label} 安装失败`]), sub: note.reason || w(['Open Images to try again', '打开图像视图重试'])}; @@ -194,6 +203,11 @@ async function openNote(note) { // A notice of a page message has nowhere to go; reading it was the point. if (note.type === 'toast') return; if (note.type === 'install') { await globalThis.FreeVideoShell?.go?.('image').catch(() => {}); return; } + if (note.type === 'agent') { + try { if (globalThis.FreeVideoShell?.view?.() !== 'autopilot') await globalThis.FreeVideoShell?.go?.('autopilot'); } catch { /* The view did not open: stay. */ } + dispatchEvent(new CustomEvent('freevideo-agent-task-open', {detail: {id: note.job}})); + return; + } const row = jobs.get(note.job); if (note.status === 'done' && await openWork({kind: note.kind, view: note.view, file: note.file || row?.result?.file, work: note.work || row?.result?.id || row?.result?.work, video: note.video || row?.result?.video})) return; await visitJob({id: note.job, view: note.view || row?.view, kind: note.kind}); diff --git a/web/output_download.js b/web/output_download.js index 9591c59b..f371dbc8 100644 --- a/web/output_download.js +++ b/web/output_download.js @@ -17,14 +17,68 @@ export function workflowToggle(t, onChange = () => {}) { // The server supplies the download name and streams the existing file, keeping // large videos out of a browser-side Blob and preserving playback/asset paths. +const SAVED_VIDEO = /^FreeVideo\/(\d{4}-\d{2}-\d{2}\/[a-f0-9]{32})\/video\.mp4$/; +// The library id (YYYY-MM-DD/<32 hex>) of a saved video file, or null for any other file. +export const outputVideoId = file => SAVED_VIDEO.exec(typeof file === 'string' ? file : '')?.[1] ?? null; export function outputDownloadPath(file) { - const saved = /^FreeVideo\/(\d{4}-\d{2}-\d{2}\/[a-f0-9]{32})\/video\.mp4$/.exec(file); + const saved = SAVED_VIDEO.exec(file); if (saved) return '/freevideo/library/download?' + new URLSearchParams({id: saved[1], ...(exportKeepsWorkflow() ? {workflow: '1'} : {})}); const split = file.lastIndexOf('/'); return '/view?' + new URLSearchParams({filename: file.slice(split + 1), subfolder: split < 0 ? '' : file.slice(0, split), type: 'output'}); } export const outputDownloadURL = (api, file) => api.apiURL(outputDownloadPath(file)); +// Several library works as one zip file. The browser posts a hidden form into a hidden frame, so the zip streams +// straight to disk (no Blob) and the page stays where it is. One request holds at most ZIP_LIMIT works; more go as +// further requests, one after another. A video that is not a saved library video has no id and is left out. +export const ZIP_LIMIT = 500; +export function zipItems(rows) { + const items = []; + for (const row of rows) { + if (row?.kind === 'image') { if (typeof row.file === 'string' && row.file) items.push({kind: 'image', file: row.file}); continue; } + const id = outputVideoId(row?.video); + if (id) items.push({kind: 'video', id}); + } + return items; +} +export function zipPayloads(rows, workflow = exportKeepsWorkflow()) { + const items = zipItems(rows), payloads = []; + for (let at = 0; at < items.length; at += ZIP_LIMIT) payloads.push({items: items.slice(at, at + ZIP_LIMIT), workflow: Boolean(workflow)}); + return payloads; +} +// What each request can pack right now, asked before the form is posted (the answer to a form lands in a hidden frame, +// where an error would be seen by no one): [{ready, skipped}] in order; a refusal or any non-answer counts as nothing ready. +export async function checkZips(api, payloads) { + const answers = []; + for (const payload of payloads) { + try { + const response = await api.fetchApi('/freevideo/library/download-zip', {method: 'POST', headers: {'Content-Type': 'application/json'}, + body: JSON.stringify({...payload, check: true})}); + const body = response.ok ? await response.json() : null; + answers.push({ready: Number(body?.ready) || 0, skipped: Number(body?.skipped) || 0}); + } catch { answers.push({ready: 0, skipped: 0, failed: true}); } + } + return answers; +} +let zipFrames = 0; +export function postZip(api, payload, {doc = document, keep = 600000} = {}) { + const name = `fv-zip-${Date.now().toString(36)}-${++zipFrames}`; + const frame = doc.createElement('iframe'); frame.name = name; frame.hidden = true; frame.setAttribute('aria-hidden', 'true'); frame.tabIndex = -1; + const form = doc.createElement('form'); form.method = 'post'; form.action = api.apiURL('/freevideo/library/download-zip'); form.target = name; form.hidden = true; + const field = doc.createElement('input'); field.type = 'hidden'; field.name = 'payload'; field.value = JSON.stringify(payload); + form.append(field); doc.body.append(frame, form); + form.submit(); form.remove(); + // The frame stays while the browser takes the file, then goes. + setTimeout(() => frame.remove(), keep); +} +// Sends every payload, about a second apart; resolves when the last one is submitted. +export async function postZips(api, payloads, {doc = document, wait = ms => new Promise(resolve => setTimeout(resolve, ms)), gap = 1000, alive = () => true, keep} = {}) { + for (let at = 0; at < payloads.length; at++) { + if (at) { await wait(gap); if (!alive()) return; } + postZip(api, payloads[at], keep === undefined ? {doc} : {doc, keep}); + } +} + // 'ok'; 'missing' only when the server answered 404 or 410; 'unknown' when offline, timed out or any other answer. export async function fileState(api, path) { const gone = status => status === 404 || status === 410; diff --git a/web/private_settings.js b/web/private_settings.js index 03f71cec..b70afd86 100644 --- a/web/private_settings.js +++ b/web/private_settings.js @@ -5,6 +5,7 @@ // page. An engine older than this page has none of these calls: the whole group then stays hidden and nothing is asked. import { cutTip } from './cut_tip.js'; import { el, icon, tip, button, row, card, groupHead, fold, segmented } from './settings_kit.js'; +import './fv_select.js'; import { privacyOffered } from './private_offers.js'; const amount = bytes => bytes >= 1e9 ? (bytes / 1e9).toFixed(1) + ' GB' : (bytes / 1e6).toFixed(1) + ' MB'; diff --git a/web/prompt_enhance.js b/web/prompt_enhance.js index 49755d24..c7699da3 100644 --- a/web/prompt_enhance.js +++ b/web/prompt_enhance.js @@ -232,6 +232,7 @@ export function createPromptEnhancer({node, input, editor, api, context, setText ? t(`${lengthOf(error, true)}; enhancement supports up to 12,000. Shorten it or use the original.`, `${lengthOf(error, false)},增强最多支持 12,000 字符,请精简或使用原文。`) : t('Enter a prompt of up to 12,000 characters.', '请输入不超过 12,000 字符的提示词。'), invalid_output: t('The rewrite was incomplete. Retry or use the original.', '改写结果不完整,请重试或使用原文。'), + invalid_request: t('Rewriting does not support this model or aspect ratio. Change it or use the original.', '当前模型或画幅不支持改写,请更换或使用原文。'), context_length: t('The scene is too long for this model. Shorten it or use the original.', '内容超出改写模型容量,请精简或使用原文。'), out_of_memory: holderNames(error?.holders) ? t(`Not enough graphics memory to rewrite. In use: ${holderNames(error.holders)}. Close the listed programs and rewrite again, or use the original.`, @@ -255,6 +256,7 @@ export function createPromptEnhancer({node, input, editor, api, context, setText ? t(`${lengthOf(error, true)}; rewriting supports up to 12,000. Shorten it before rewriting again.`, `${lengthOf(error, false)},改写最多支持 12,000 字符,精简后可再改写。`) : t('Rewriting supports prompts of up to 12,000 characters.', '改写只支持不超过 12,000 字符的提示词。'), invalid_output: t('The rewrite was incomplete.', '改写结果不完整。'), + invalid_request: t('Rewriting does not support this model or aspect ratio.', '当前模型或画幅不支持改写。'), context_length: t('The scene is too long for the rewrite model.', '内容超出改写模型容量。'), out_of_memory: holderNames(error?.holders) ? t(`Not enough graphics memory to rewrite. In use: ${holderNames(error.holders)}. Close the listed programs before rewriting again.`, diff --git a/web/settings_room.js b/web/settings_room.js index 23caaa08..84bcdcf6 100644 --- a/web/settings_room.js +++ b/web/settings_room.js @@ -8,6 +8,7 @@ import { setTip } from './tip_words.js'; import { cutTip } from './cut_tip.js'; import { api } from "../../scripts/api.js"; +import './fv_select.js'; import { compatibilityCard } from './compatibility.js'; import { listenDialogKey } from './dialog_keys.js'; import { animateDetails } from './motion.js'; @@ -892,12 +893,26 @@ export async function openSetup(options) { else (dialog.querySelector('.st-ni[aria-current=page]') || closeButton).focus(); }); // 'repair': a failure card's "Open settings" lands on Check installation, the first step its hint names. + // The card's button is hidden while the installer state is still being read (and the page head's one stands in + // when the models are ready), and it is hidden again while a check starts, so for a few seconds each repaint puts + // the focus back on whichever one shows; a key or click of the person's own ends that. + let spotWait = 0; function spotlight() { show('models'); - inspect.scrollIntoView({block: 'center'}); - inspect.focus({preventScroll: true}); - inspect.classList.add('is-spot'); setTimeout(() => inspect.classList.remove('is-spot'), 2400); + clearTimeout(spotWait); + spotWait = setTimeout(() => { spotWait = 0; }, 6000); + landSpot(); } + function landSpot() { + const target = headInspect.hidden ? inspect : headInspect; + if (target.hidden || !dialog.open) return false; + if (target === document.activeElement) return true; + target.scrollIntoView({block: 'center'}); + target.focus({preventScroll: true, focusVisible: true}); // a mouse click on Open settings still gets the ring + target.classList.add('is-spot'); setTimeout(() => target.classList.remove('is-spot'), 2400); + return true; + } + for (const type of ['keydown', 'pointerdown']) dialog.addEventListener(type, () => { clearTimeout(spotWait); spotWait = 0; }, true); // ── Hover tips for the installer's actions ── for (const [control, name, purpose] of [ @@ -1127,6 +1142,7 @@ export async function openSetup(options) { reviewPlan.hidden = kind !== 'plan' && kind !== 'problem'; setText(reviewPlan, kind === 'problem' ? t('See problems', '查看问题') : t('Review plan', '查看计划')); inspect.hidden = busy || kind === 'loading'; + if (spotWait) landSpot(); const extraCount = extra.value.split('\n').map(s => s.trim()).filter(Boolean).length; state.hidden = kind === 'busy' || (kind === 'ready' && !state.textContent); if (kind === 'none' && !state.textContent) state.textContent = t('Check first: models already on this computer are used as they are.', '先检查一遍,电脑上已有的模型会直接使用。'); @@ -1417,8 +1433,10 @@ export async function openSetup(options) { // The full path is in the box above; show its start and last folder on one line. The start gives way to the room // there is (cut with an ellipsis), the last 26 characters stay; copying takes the whole path. const first = missing[0], cut = Math.max(0, first.length - 26), path = el('span', 'st-path st-path-cut fv-copyable'); - path.append(el('span', 'st-path-head', first.slice(0, cut)), el('span', 'st-path-tail', first.slice(cut))); - cutTip(path, first); folderStatus.append(path); + const head = el('span', 'st-path-head', first.slice(0, cut)); + path.append(head, el('span', 'st-path-tail', first.slice(cut))); + // The cut is in the start (the line itself never overflows), so that is what decides the whole-path tip. + cutTip(path, first, head); folderStatus.append(path); } return result; } diff --git a/web/share.js b/web/share.js index a2738f7e..39f332c4 100644 --- a/web/share.js +++ b/web/share.js @@ -5,6 +5,7 @@ import {fontCSS as bundledFontCSS, fontLoaded, loadFont} from './fonts.js'; import {shareLayout} from './share_layout.js'; import {videoUnavailableText} from './studio_extend.js'; import {issueButton} from './issue_button.js'; +import {createPlayBar} from './fv_player.js'; import {userMessage} from './user_message.js'; import {exportKeepsWorkflow, workflowToggle} from './output_download.js'; import {fileFailureText, responseFileReason} from './file_failure.js'; @@ -113,10 +114,11 @@ export async function openShare(record,t){ const abort=new AbortController(); const panel=el('div','fv-share-body'),preview=el('div','fv-share-preview'),canvas=el('canvas'),player=el('video'); canvas.setAttribute('aria-label',t('Sharing image preview','分享图预览')); - player.loop=true;player.playsInline=true;player.muted=true;player.controls=true;player.preload='none';player.hidden=true; + player.loop=true;player.playsInline=true;player.muted=true;player.preload='none';player.hidden=true; const split=record.video.lastIndexOf('/'); player.src=api.apiURL('/view?'+new URLSearchParams({filename:record.video.slice(split+1),subfolder:record.video.slice(0,split),type:'output'})); - preview.append(player,canvas);panel.append(preview); + const playBar=createPlayBar(player,t);playBar.bar.classList.add('fv-player-over');playBar.bar.hidden=true; + preview.append(player,canvas,playBar.bar);panel.append(preview); const footer=el('footer','fv-share-footer'),message=el('span','fv-share-status');message.setAttribute('role','status'); const problem=issueButton(t,()=>({where:['Share','分享'],message:message.textContent}));problem.hidden=true; const say=(text,fault=false)=>{message.textContent=text;problem.hidden=!fault||!text;if(fault&&text)dialog.dataset.error='true';else delete dialog.dataset.error;}; @@ -141,7 +143,7 @@ export async function openShare(record,t){ if(!ready)return; say(kind==='video'&&videoFailed?videoUnavailableText(t):'',kind==='video'&&videoFailed); drawShareCard(canvas,kind==='image'?first:null,logo,metadata,t); - player.hidden=kind!=='video'; + player.hidden=kind!=='video';playBar.bar.hidden=kind!=='video'; if(kind==='video')player.play().catch(error=>{if(!['AbortError','NotAllowedError'].includes(error.name))videoError();});else player.pause(); }; for(const [name,label] of [['image',t('Image','图片')],['video',t('Video','视频')]]){ @@ -196,7 +198,7 @@ export async function openShare(record,t){ 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);}} } dialog.addEventListener('cancel',event=>{event.preventDefault();closeDialog(dialog);}); - dialog.onclose=()=>{disposed=true;clearInterval(watch);abort.abort();exportRequest?.abort();player.pause();player.removeAttribute('src');player.load();dialog.remove();if(opened===dialog)opened=null;}; + dialog.onclose=()=>{disposed=true;clearInterval(watch);abort.abort();exportRequest?.abort();player.pause();playBar.destroy();player.removeAttribute('src');player.load();dialog.remove();if(opened===dialog)opened=null;}; // Start focus on the dialog itself, not with a focus ring on the first tab. document.body.append(dialog);dialog.showModal();dialog.focus();slide();message.textContent=t('Preparing preview…','正在准备预览…'); try{ @@ -209,6 +211,8 @@ export async function openShare(record,t){ shape=drawShareCard(canvas,null,logo,metadata,t);template=canvas.toDataURL('image/png').split(',')[1]; preview.style.aspectRatio=`${shape.width}/${shape.height}`; player.style.cssText=`left:${shape.rect[0]/shape.width*100}%;top:0;width:${shape.rect[2]/shape.width*100}%;height:${shape.rect[3]/shape.height*100}%`; + // The play bar sits on the picture only, not on the info strip the card draws below it. + playBar.bar.style.cssText=`left:${shape.rect[0]/shape.width*100}%;width:${shape.rect[2]/shape.width*100}%;right:auto;bottom:auto;top:calc(${shape.rect[3]/shape.height*100}% - 44px)`; ready=true;choose(kind);save.disabled=false; }catch(error){if(!disposed)say(userMessage(error,t,t('Preview unavailable. Close and try again.','预览暂时无法读取,请关闭后重试。')),true);} } diff --git a/web/studio.css b/web/studio.css index 3b50c76b..f3e63326 100644 --- a/web/studio.css +++ b/web/studio.css @@ -172,6 +172,9 @@ .fv-lora-list{display:flex;flex-direction:column;gap:8px;margin:12px 0}.fv-lora-row{display:grid;grid-template-columns:18px minmax(0,1fr) 64px 30px;align-items:center;gap:7px}.fv-lora-row[data-sortable=true]{grid-template-columns:12px 18px minmax(0,1fr) 64px 30px;--lora-lead:3} .fv-lora-row select{min-width:0!important;max-width:100%!important;width:100%!important}.fv-lora-row input[type=number]{width:64px!important;padding:6px!important;font-variant-numeric:tabular-nums} .fv-lora-range{grid-column:var(--lora-lead,2)/span 3;grid-row:3;justify-self:end;font-size:12px;line-height:16px;white-space:nowrap;color:var(--fv-muted)}.fv-lora-range[hidden]{display:none} +/* The line a typed strength is brought back with ("At most 100") takes the place of the range note (the script hides that one) for as long as it + shows, so the box has one line under it; the next input clears it and the range note is back. */ +.fv-lora-row .fv-field-why{grid-column:var(--lora-lead,2)/-1;grid-row:3;justify-self:end;margin:0;text-align:right} .fv-lora-row[data-enabled=false]{cursor:pointer}.fv-lora-row[data-enabled=false]>:not(.fv-lora-off):not(.fv-lora-grip){opacity:.45}.fv-lora-off{grid-column:var(--lora-lead,2)/span 3;grid-row:4;font-size:var(--fv-micro);color:var(--fv-muted)}.fv-lora-off[hidden]{display:none}.fv-lora-grip{width:12px;height:22px;cursor:grab;touch-action:none;color:var(--fv-muted);background:radial-gradient(circle,currentColor 1.3px,transparent 1.6px) 0 0/6px 7px;border-radius:var(--fv-r-xs)}.fv-lora-grip:hover{color:var(--fv-ink)}.fv-lora-dragging{position:relative;z-index:1;background:var(--fv-card);box-shadow:0 4px 14px rgb(0 0 0/.35);border-radius:var(--fv-r-sm);cursor:grabbing}.fv-lora-dragging .fv-lora-grip{cursor:grabbing} .fv-lora-row .fv-lora-trigger{grid-column:var(--lora-lead,2)/span 3;grid-row:2;width:100%;min-width:0;min-height:28px;height:28px;box-sizing:border-box;border:1px solid var(--fv-border);border-radius:var(--fv-r-sm);padding:4px 8px;background:var(--fv-card);color:var(--fv-ink);font:inherit;font-size:var(--fv-micro)} .fv-lora-trigger::placeholder{color:var(--fv-disabled)} diff --git a/web/studio.js b/web/studio.js index 519f8568..73c9c3ca 100644 --- a/web/studio.js +++ b/web/studio.js @@ -24,7 +24,6 @@ import { createPreviewScene } from './preview_scene.js?v=20261115-still'; import { animateDetails, closeDialog } from './motion.js'; import { openLibrary, setDefaultUpscale, setDefaultUpscaleWork, videoThumbnailURL } from './library.js'; import { createRecentVideos } from './studio_recent.js'; -import { createAgentActivity } from './agent_activity.js'; import { createStudioQueue, randomSeed, turnNodeOn } from './studio_queue.js'; import { isNetworkTypeError, connectionLostText, wrappedFetchOnly } from './browser_extension.js'; import { newEngineExit, engineExitText, watchEngineExit } from './engine_exit.js'; @@ -91,7 +90,9 @@ const shownMessage = error => isNetworkTypeError(error) ? connectionLostText(t) // The usual LoRA strength range is -4 to 4; a value the user types by hand may go further, up to 100. const LORA_USUAL = 4, LORA_LIMIT = 100; let loraRangeCount = 0; -function loraStrengthBox(initial, commit) { +// `said` ({text}) is the line under the box that outlives the list being drawn again: every change writes the list, which +// rebuilds its rows, so the row remembers what its line said and shows it again until the next edit. +function loraStrengthBox(initial, commit, said = null) { // said: {text, value, name} const input = document.createElement('input'), mark = document.createElement('span'); input.type = 'number'; input.step = '.05'; input.min = String(-LORA_LIMIT); input.max = String(LORA_LIMIT); input.value = initial; const note = fieldNote(input, {t, place: () => mark.isConnected ? mark : null}); @@ -104,12 +105,15 @@ function loraStrengthBox(initial, commit) { // A strength past ±100 becomes ±100, and the line under it says so. // An emptied box goes back to the strength in use, and the line says so. let kept = String(initial); - input.oninput = sync; input.onchange = () => { - if (input.value === '' && kept !== '') { input.value = kept; sync(); note.say(t(`Back to ${kept}`, `已恢复为 ${kept}`)); return; } - const ok = note.settle(); sync(); if (ok) { kept = input.value; commit(); } + input.oninput = () => { if (said) said.text = ''; sync(); }; input.onchange = () => { + if (input.value === '' && kept !== '') { input.value = kept; sync(); note.say(t(`Back to ${kept}`, `已恢复为 ${kept}`)); mark.hidden = true; return; } + const ok = note.settle(); sync(); + if (said) { said.text = note.line && !note.line.hidden ? note.line.textContent : ''; said.value = Number(input.value); } + if (note.line && !note.line.hidden) mark.hidden = true; // one line under the box: this one replaces the range note until the next input + if (ok) { kept = input.value; commit(); } }; sync(); - return {input, mark}; + return {input, mark, restore: () => { if (said?.text && said.value === Number(input.value)) { note.say(said.text); mark.hidden = true; } }}; } const css = document.createElement('link'); css.rel = 'stylesheet'; css.href = new URL('./studio.css', import.meta.url).href; document.head.append(css); const effortCss = document.createElement('link'); effortCss.rel = 'stylesheet'; effortCss.href = new URL('./sampling_effort.css', import.meta.url).href; document.head.append(effortCss); @@ -381,6 +385,7 @@ export function loraPanel(node, panel, {promptNode = null} = {}) { const idleNote = () => (skipped ? t(skipped === 1 ? ' 1 other LoRA file in the folder is not in .safetensors format and is not listed.' : ` ${skipped} other LoRA files in the folder are not in .safetensors format and are not listed.`, ` 文件夹中另有 ${skipped} 个 LoRA 文件不是 .safetensors 格式,未列出。`) : ''); const verdicts = createVerdicts((path, options) => api.fetchApi(path, options)); let rowChecks = []; + const strengthSaid = new Map(); // row index -> {text}: the "At most 100" line of its strength box let focusGrip = null; // The list lives in the node as JSON; a broken list is not a reply from FreeVideo, so it gets its own sentence. const listProblem = error => { @@ -439,7 +444,7 @@ export function loraPanel(node, panel, {promptNode = null} = {}) { const reorder = order => { const rows = read(); if (order.length !== rows.length || order.every((from, to) => from === to)) return; - write(order.map(from => rows[from])); + strengthSaid.clear(); write(order.map(from => rows[from])); }; // The grip moves the whole row with the pointer; arrow keys do the same one step at a time. function sortGrip(wrap, index) { @@ -482,6 +487,7 @@ export function loraPanel(node, panel, {promptNode = null} = {}) { rowChecks = []; list.replaceChildren(); clear.remove(); const rows = read(); + for (const key of [...strengthSaid.keys()]) if (key >= rows.length) strengthSaid.delete(key); syncPrompt(rows); rows.forEach((row, index) => { const wrap = el('div', null, 'fv-lora-row'); wrap.dataset.enabled = String(row.enabled !== false); @@ -497,7 +503,10 @@ export function loraPanel(node, panel, {promptNode = null} = {}) { if (verdicts.peek(row.name)?.usable === false) row.enabled = true; row.name = select.value; rememberLora(row.name); write(rows); }; - const {input: strength, mark: strengthMark} = loraStrengthBox(row.strength ?? 1, () => { if (strength.value !== '') { row.strength = Number(strength.value); write(rows); } }); + if (!strengthSaid.has(index)) strengthSaid.set(index, {text: '', value: null, name: row.name}); + // A line belongs to the model and strength it was said for: another model in this place, or a strength set from outside, drops it. + { const said = strengthSaid.get(index); if (said.name !== row.name || said.value !== Number(row.strength ?? 1)) { said.text = ''; said.name = row.name; } } + const {input: strength, mark: strengthMark, restore: restoreStrengthNote} = loraStrengthBox(row.strength ?? 1, () => { if (strength.value !== '') { row.strength = Number(strength.value); write(rows); } }, strengthSaid.get(index)); strength.setAttribute('aria-label', t('LoRA strength', 'LoRA 强度')); const trigger = el('input', null, 'fv-lora-trigger'); trigger.type = 'text'; trigger.maxLength = 300; trigger.dataset.name = row.name; @@ -522,7 +531,7 @@ export function loraPanel(node, panel, {promptNode = null} = {}) { } }; select.disabled = strength.disabled = trigger.disabled = row.enabled === false; - const remove = button('×', () => { rows.splice(index, 1); write(rows); }); remove.setAttribute('aria-label', t('Remove LoRA', '移除 LoRA')); + const remove = button('×', () => { rows.splice(index, 1); strengthSaid.clear(); write(rows); }); remove.setAttribute('aria-label', t('Remove LoRA', '移除 LoRA')); remove.dataset.fvTipName = t('Remove LoRA', '移除 LoRA'); remove.dataset.fvTipUse = t('Take it off the list; the file stays', '从列表移除,文件不删'); wrap.append(enabled, loraMenu(select, t, pinned).wrap, strength, remove, trigger, strengthMark); wrap.dataset.index = String(index); wrap.dataset.sortable = String(rows.length > 1); @@ -568,6 +577,7 @@ export function loraPanel(node, panel, {promptNode = null} = {}) { if (known) mark(known); else check(false); list.append(wrap); + if (list.isConnected) restoreStrengthNote(); loadTriggers(row.name).catch(error => { if (!disposed && trigger.isConnected) note.textContent = userMessage(error, t, t('Could not read the trigger words. Try again.', '没能读取触发词,请重试。')); }); }); if (rows.length > 1) actions.append(clear); @@ -755,7 +765,6 @@ export function openStudio(node, {extendFrom = null} = {}) { const header = el('header', null, 'fv-header'), brand = el('div', null, 'fv-brand'); brand.append(wordmark()); const tools = el('div', null, 'fv-header-actions'); - const agents = createAgentActivity(t, api, dialog); tools.append(agents.element); cleanup.push(agents.dispose); const phoneAccess = createLanAccess(t, api); tools.append(phoneAccess.element); cleanup.push(phoneAccess.dispose); const versionInfo = createVersionInfo(cn); tools.append(versionInfo.element); cleanup.push(versionInfo.dispose); tools.append(guideButton(t), feedbackButton(t), button(t('Settings', '设置'), openSetup, 'fv-quiet')); @@ -3012,6 +3021,9 @@ export function openStudio(node, {extendFrom = null} = {}) { dialog.addEventListener('cancel', e => { e.preventDefault(); if (!closeMenu() && !compare.close() && !promptLibrary?.hide() && !consoleUI?.dismiss() && !recent.dismiss()) closeDialog(dialog); }); const dispose = () => { if (disposed) return; disposed = true; borrowed?.release({disposing: true}); blockOriginal('extend', false); blockOriginal('preview', false); for (const f of cleanup) f(); stage.querySelector('video')?.pause(); dialog.remove(); if (current?.dialog === dialog) { current = null; viewChanged('nodes', node); } }; const onClose = () => { + // The browser's own close event of a switch comes with the next frame; if the panel was opened again before it + // (back from the node view at once), that late event is not a close and must not take the panel away. + if (dialog.open) return; // Parked behind the node view: everything stays as it is (closeDialog may have taken this handler while a // switch held the frames, so it is put back for the real close later). if (dialog.dataset.fvParked === 'true') { stage.querySelector('video')?.pause(); warm?.cancel(); dialog.onclose = onClose; return; } diff --git a/web/task_float.css b/web/task_float.css index c432f3c9..38a3ea2f 100644 --- a/web/task_float.css +++ b/web/task_float.css @@ -76,7 +76,6 @@ .sgf.sgf :where(button, a) { font: inherit; color: inherit; background: none; border: 0; padding: 0; margin: 0; min-height: 0; min-width: 0; border-radius: 0; display: inline-flex; align-items: center; justify-content: center; gap: 0; box-shadow: none; filter: none; transition: none; text-decoration: none; cursor: pointer; font-weight: inherit; } .sgf.sgf.sgf :where(button, a):is(:hover, :active) { filter: none; border-color: transparent; } -.sgf.sgf :where(button, a):focus-visible { outline: 2px solid color-mix(in srgb, #1B94FC 70%, transparent); outline-offset: 2px; } .sgf .sgf-n { height: 28px; padding: 0 4px 0 8px; border-radius: var(--fv-r-lg); display: inline-flex; align-items: center; gap: 0; font-size: 12px; font-weight: 600; color: var(--f-fg); background: var(--f-ctl); transition: background-color 160ms; } .sgf .sgf-n:hover, .sgf .sgf-n[aria-expanded=true] { background: var(--f-ctl-h); } .sgf .sgf-n svg { width: 14px; height: 14px; color: var(--f-fg2); } @@ -133,6 +132,7 @@ /* the stop question anchored to a view's own Stop button: the same second layer */ .sgf.sgf-confirm { z-index: calc(var(--fv-z-float, 2000) + 1); } .sgf.sgf-confirm .sgf-sheet { position: static; width: 300px; } +.sgf.sgf-confirm p { text-wrap: balance; } /* the corner it will land in while dragging */ .sgf-slot { z-index: calc(var(--fv-z-float, 2000) - 1); box-sizing: border-box; border-radius: var(--fv-r-lg); pointer-events: none; diff --git a/web/task_float.js b/web/task_float.js index 5cdf2a3a..36e8ddea 100644 --- a/web/task_float.js +++ b/web/task_float.js @@ -240,23 +240,27 @@ const raise = element => { try { if (element.matches(':popover-open')) element.h // ---------- the stop question, anchored to any button (the floating window's own, or a view's Stop) ---------- // host: where the question goes (a panel it belongs to, so a press on it does not close that panel); by default the // open dialog the button is in, or the page. -export function confirmStop(anchor, {kind = 'video', queued = false, host = null} = {}) { +export function confirmStop(anchor, {kind = 'video', queued = false, host = null, agent = false} = {}) { return new Promise(resolve => { const box = el('div', 'sgf sgf-confirm'); box.setAttribute('popover', 'manual'); box.dataset.fvTipScope = ''; const sheet = el('div', 'sgf-sheet'); sheet.setAttribute('role', 'alertdialog'); const title = el('b', null), text = el('p', null); title.textContent = queued ? t('Remove from the queue?', '取消排队?') : t('Stop generating?', '停止生成?'); - text.textContent = queued ? t('It has not started; it will not be made.', '这项还没有开始,取消后不会生成。') + if (agent) { + title.textContent = queued ? t('Remove from the queue?', '取消排队?') : t('Stop this step?', '停止这一步?'); + text.textContent = queued ? t('It has not started; it will not run.', '这一步还没有开始,取消后不会进行。') + : t('What this step has made so far is not kept. Finished works stay.', '这一步做到一半的不会保留,已经完成的作品不受影响。'); + } else text.textContent = queued ? t('It has not started; it will not be made.', '这项还没有开始,取消后不会生成。') : kind === 'image' ? t('This picture will not be kept.', '这张图不会保留。') : t('What has been made so far is not kept. Queued jobs go on.', '已生成的部分不会保留,排队的任务照常进行。'); const ask = el('div', 'sgf-ask'), acts = el('div', 'sgf-acts'); const keep = el('button', 'pill line'), stop = el('button', 'pill danger'); - keep.type = stop.type = 'button'; keep.textContent = t('Keep going', '继续生成'); stop.textContent = queued ? t('Remove', '取消排队') : t('Stop', '停止'); - tip(keep, t('Keep going', '继续生成'), t('Close this and keep generating', '不停止,接着生成'), 'Esc'); - tip(stop, stop.textContent, queued ? t('Take it out of the queue', '从队列里拿掉这一项') : t('Stop it now; nothing is kept', '立即停止,不保留结果')); + keep.type = stop.type = 'button'; keep.textContent = agent ? t('Keep going', '继续') : t('Keep going', '继续生成'); stop.textContent = queued ? t('Remove', '取消排队') : t('Stop', '停止'); + tip(keep, keep.textContent, agent ? t('Close this and let the step go on', '不停止,让这一步接着做') : t('Close this and keep generating', '不停止,接着生成'), 'Esc'); + tip(stop, stop.textContent, queued ? t('Take it out of the queue', '从队列里拿掉这一项') : agent ? t('Stop this step now; what it made so far is not kept', '立即停止这一步,做到一半的不保留') : t('Stop it now; nothing is kept', '立即停止,不保留结果')); acts.append(keep, stop); ask.append(title, text, acts); sheet.append(ask); box.append(sheet); (host || anchor.closest('dialog[open]') || document.body).append(box); raise(box); const a = anchor.getBoundingClientRect(), w = 300, h = box.offsetHeight || 132; - const x = Math.min(innerWidth - w - 12, Math.max(12, a.left + a.width / 2 - w / 2)), above = a.top - h - 10 > 12; + const x = Math.min(innerWidth - w - 12, Math.max(12, a.left + a.width / 2 - w / 2)), above = a.bottom + 10 + h > innerHeight - 12 && a.top - h - 10 > 12; // below the button; above only where below does not fit box.style.transform = `translate3d(${Math.round(x)}px, ${Math.round(above ? a.top - h - 10 : a.bottom + 10)}px, 0)`; box.dataset.corner = above ? 'b' : 't'; let done = false; diff --git a/web/task_store.js b/web/task_store.js index e26c7dd3..4afbfede 100644 --- a/web/task_store.js +++ b/web/task_store.js @@ -249,6 +249,12 @@ export function imageSource(store, {client, storage = null, poll = 500, now = st if (own && own !== client) clients.set(id, own); store.upsert({id, kind: 'image', source: 'image', status: 'submitting', prompt: meta.text ?? request.prompt ?? '', model: request.model || null, view, meta: {...meta, ...(own?.standIn === true ? {standIn: true} : {})}, percent: 0}); + // A refusal that carries only the catch-all code, with no stage or report, names the submit step; any other keeps its own. + const stepped = (value, code) => { + // The same rule as originStep in image_generation.js (this file takes no imports). + const step = value?.step || (!code || (code === 'generation_failed' && !value?.stage && !value?.report_id) ? 'submit' : ''); + return value instanceof Error ? Object.assign(value, {step}) : {...value, step}; + }; const refuse = (code, value) => { clients.delete(id); if (IMAGE_BUSY.has(code)) store.drop(id); else store.upsert({id, status: 'failed', failure: {code, ...pick(value)}}); @@ -256,8 +262,8 @@ export function imageSource(store, {client, storage = null, poll = 500, now = st }; let reply; try { reply = await mine.generate(request); } - catch (error) { throw refuse(error?.code || 'generation_failed', error?.code ? error : error instanceof Error ? Object.assign(error, {step: 'submit'}) : {step: 'submit'}); } - if (!reply?.job) throw refuse(reply?.error || 'generation_failed', reply?.error ? reply : {...reply, step: 'submit'}); + catch (error) { throw refuse(error?.code || 'generation_failed', stepped(error, error?.code)); } + if (!reply?.job) throw refuse(reply?.error || 'generation_failed', stepped(reply, reply?.error)); keys[id] = {job: reply.job, model: request.model || null, withImages: Boolean(meta.withImages), created_at: store.get(id)?.created_at || now(), view}; save(); // Stopped while the request was on its way: the engine gets the cancel now that the job has a key. diff --git a/web/theme.css b/web/theme.css index 9dfaf0a8..73b3eb4b 100644 --- a/web/theme.css +++ b/web/theme.css @@ -38,7 +38,6 @@ :where(.fv-studio,.fv-setup,.fv-panel) :is(input,select,textarea,button){font-family:inherit} :where(.fv-studio,.fv-setup,.fv-panel) :is(button,a,summary){touch-action:manipulation} :where(.fv-studio,.fv-setup,.fv-panel) button{appearance:none} -:where(.fv-studio,.fv-setup,.fv-panel) :focus-visible{outline:2px solid var(--fv-accent);outline-offset:3px} /* A modal takes focus itself while it fills; its controls carry the ring. */ :where(.fv-studio,.fv-setup,.fv-failure-dialog):focus-visible{outline:none} :where(.fv-studio,.fv-setup,.fv-panel) progress{accent-color:var(--fv-accent);appearance:none;height:6px;border:0;border-radius:var(--fv-r-pill);overflow:hidden;background:var(--fv-raised)} @@ -63,6 +62,7 @@ /* The name reads from the left like any field; .fv-studio button would otherwise centre it. */ .fv-select-menu-host>.fv-select-trigger{display:flex;align-items:center;justify-content:flex-start;width:100%;max-width:100%;min-height:var(--fv-h-sm,32px);padding:4px 34px 4px 10px;border:1px solid var(--fv-border);border-radius:var(--fv-r-sm,8px);background:var(--fv-raised);color:var(--fv-ink);font:inherit;text-align:left;cursor:pointer} .fv-select-menu-host>.fv-select-trigger:hover:not(:disabled){background:var(--fv-hover)}.fv-select-menu-host>.fv-select-trigger:disabled{opacity:.5;cursor:default} +.fv-select-menu-host>.fv-select-trigger{justify-content:flex-start;text-align:left} .fv-select-face{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap} .fv-select-menu{position:fixed;z-index:60;box-sizing:border-box;max-width:calc(100vw - 16px);overflow:auto;padding:6px;background:var(--fv-card);color:var(--fv-ink);border:1px solid var(--fv-border);border-radius:var(--fv-r-sm);font:13px var(--fv-font)} .fv-select-menu[hidden]{display:none} @@ -171,5 +171,5 @@ } /* A long menu list: a filter box stays on top while the items scroll. */ .fv-select-search{position:sticky;top:-6px;z-index:1;margin:-6px -6px 4px;padding:6px;background:var(--fv-card)} -.fv-select-search input{box-sizing:border-box;width:100%;min-height:30px;padding:3px 8px;border:1px solid var(--fv-border);border-radius:var(--fv-r-xs);background:var(--fv-raised);color:var(--fv-ink);font:inherit} +.fv-select-search input{box-sizing:border-box;width:100%;min-height:30px;padding:3px 8px;border:1px solid var(--fv-border);border-radius:var(--fv-r-xs);background:color-mix(in srgb,var(--fv-ink) 5%,var(--fv-card));color:var(--fv-ink);font:inherit} .fv-select-empty{padding:8px 10px;color:var(--fv-muted)} diff --git a/web/topbar.js b/web/topbar.js index 08b53c6f..17f911c3 100644 --- a/web/topbar.js +++ b/web/topbar.js @@ -16,8 +16,10 @@ import { createVersionInfo } from './updates.js'; import { paletteButton, openCreations } from './palette.js'; import { wordmark } from './wordmark.js'; import { jobs, ACTIVE } from './task_store.js'; +import { createAgentTasks } from './agent_tasks.js'; +import { title as agentTitle, failureReason } from './agent_activity.js'; import { isNetworkTypeError, connectionLostText } from './browser_extension.js'; -import { onNotices, mountNotices, markNoticesRead } from './notifications.js'; +import { onNotices, mountNotices, markNoticesRead, noteFromAgent, addAgentNote } from './notifications.js'; import { CN, t0, words, capsuleState, capsuleWords, machineLine, machineFigures, isFailure, FIGURES_KEY, figuresShown } from './topbar_state.js'; export { CN, words, capsuleState, machineLine }; @@ -61,6 +63,9 @@ function tip(element, name, use, key = '') { } // ── The status capsule (TOPBAR.md §4; its state in topbar_state.js) ── +// The AI assistant's tasks count with the others: a task row each, and the capsule's number. +const agentTasks = createAgentTasks(api); +const allJobs = () => [...jobs.list(), ...agentTasks.rows()]; let online = true; const capsules = new Set(); if (browser) { @@ -137,7 +142,7 @@ function bump(capsule) { } function renderCapsule(capsule) { const before = capsule.isConnected ? capsule.getBoundingClientRect().width : 0; - const list = jobs.list(), active = list.filter(row => ACTIVE.has(row.status)).length, finished = list.filter(row => row.status === 'done').length; + const list = allJobs(), active = list.filter(row => ACTIVE.has(row.status)).length, finished = list.filter(row => row.status === 'done').length; const seen = capsule.fvCapsule.seen; if (seen && (active > seen.active || finished > seen.finished)) bump(capsule); capsule.fvCapsule.seen = {active, finished}; @@ -192,7 +197,12 @@ function fitCapsuleWidth(capsule) { return natural > 0 ? Math.ceil(natural / 4 - 0.01) * 4 : 0; } function syncCapsules() { for (const capsule of [...capsules]) { if (capsule.isConnected) renderCapsule(capsule); } } -if (browser) jobs.subscribe(() => syncCapsules()); +if (browser) { jobs.subscribe(() => syncCapsules()); agentTasks.subscribe(() => { noteAgentFailures(); syncCapsules(); }); void agentTasks.refresh(); } +// A failed assistant task becomes a notice (its name and cause), the same as a failed generation: it counts on the capsule. +function noteAgentFailures() { + const t = t0; + for (const job of agentTasks.failed()) addAgentNote(noteFromAgent(job, {title: agentTitle(job, t), reason: failureReason(job, t)})); +} // Subscribed once everything it calls is defined (it answers at once with the current state). if (browser) onNotices(state => { const before = notices?.unread || 0; notices = state; syncCapsules(); if (!before && state.unread) noticeHint(); }); @@ -253,6 +263,7 @@ function statusCapsule(t) { let activity = null; const SECONDS = (t, value) => { const s = Math.max(1, Math.round(value)); return s < 120 ? t(`about ${s} s`, `约 ${s} 秒`) : t(`about ${Math.round(s / 60)} min`, `约 ${Math.round(s / 60)} 分钟`); }; function jobTitle(row, t) { + if (row.source === 'agent') return agentTitle(row.job, t); const text = String(row.meta?.text ?? row.prompt ?? '').replace(/\s+/g, ' ').trim(); return text || ({image: t('Picture', '图片'), video: t('Video', '视频'), chain: t('Long video', '长视频')}[row.kind] || t('Task', '任务')); } @@ -303,6 +314,7 @@ function buildActivity(t) { close(); const view = row.view || (row.kind === 'image' ? 'image' : 'studio'); try { if (globalThis.FreeVideoShell?.view?.() !== view) await globalThis.FreeVideoShell?.go?.(view); } catch { /* The view did not open: stay. */ } + if (row.source === 'agent') return; globalThis.dispatchEvent?.(new CustomEvent('freevideo-task-stage-open', {detail: {view, id: row.id}})); if (row.status === 'done' || isFailure(row)) jobs.markSeen?.(row.id); }; @@ -347,7 +359,7 @@ function buildActivity(t) { stop.onclick = async event => { event.stopPropagation(); stopLost.delete(row.id); // The question sits in this panel, so answering it keeps the panel (and the rest of the list) open. - try { const {confirmStop} = await import('./task_float.js'); if (await confirmStop(stop, {kind: row.kind === 'image' ? 'image' : 'video', queued, host: box})) await jobs.cancel(row.id); } + try { const {confirmStop} = await import('./task_float.js'); if (await confirmStop(stop, {kind: row.kind === 'image' ? 'image' : 'video', queued, host: box, agent: row.source === 'agent'})) await (row.source === 'agent' ? agentTasks.cancel(row.agentId) : jobs.cancel(row.id)); } catch (error) { // The row stays as it is; a lost connection is named where its view label is. if (isNetworkTypeError(error)) { stopLost.set(row.id, Date.now()); drawTasks(); setTimeout(() => { if (isOpen()) drawTasks(); }, LOST_MS + 50); } @@ -358,9 +370,12 @@ function buildActivity(t) { return line; }; const drawTasks = () => { - const list = jobs.list().filter(row => ACTIVE.has(row.status)).sort((a, b) => (b.status === 'running') - (a.status === 'running')); + const list = allJobs().filter(row => ACTIVE.has(row.status)).sort((a, b) => (b.status === 'running') - (a.status === 'running')); heading(tasks, t('Tasks', '任务')); if (list.length) tasks.append(...list.map(taskRow)); else tasks.append(el('p', 'fv-tb-act-empty', t('Nothing is running.', '没有进行中的任务。'))); + // Assistant tasks the engine could not read are counted, not hidden. + const unreadable = agentTasks.unreadable(); + if (unreadable) tasks.append(el('p', 'fv-tb-act-empty fv-tb-act-unreadable', t(`${unreadable} ${unreadable === 1 ? 'job' : 'jobs'} could not be read`, `另有 ${unreadable} 个任务无法读取`))); drawFoot(); }; // 3 · This computer: video memory in large figures, then temperature, load and free disk, right-aligned. @@ -392,6 +407,8 @@ function buildActivity(t) { try { if (!notesMount) { notesMount = mountNotices(notesList, {live: false, limit: 6}); + // Opening a notice leaves the panel, so what it leads to is not left behind it. + notesList.addEventListener('click', event => { if (event.target.closest('.fv-note') && !event.target.closest('.fv-note-x, [data-act]')) close(); }); // An empty section does not show (only rows count, not the list's own empty state). new MutationObserver(() => { notes.hidden = !notesList.querySelector('.fv-note'); }).observe(notesList, {childList: true, subtree: true}); } @@ -449,10 +466,11 @@ function buildActivity(t) { } const isOpen = () => { try { return box.matches(':popover-open'); } catch { return !box.hidden; } }; jobs.subscribe(() => { if (isOpen()) drawTasks(); }); + agentTasks.subscribe(() => { if (isOpen()) drawTasks(); }); box.addEventListener('toggle', async event => { anchor?.setAttribute('aria-expanded', String(event.newState === 'open')); if (event.newState !== 'closed') return; - clearTimeout(timer); confirming = false; + clearTimeout(timer); confirming = false; agentTasks.watch(false); // What was shown in Notices has been seen. if (notesShown) { notesShown = false; markNoticesRead(); } }); @@ -467,7 +485,7 @@ function buildActivity(t) { return {box, isOpen, close, show(capsule) { anchor = capsule; machineState = machine; confirming = false; - drawTasks(); drawComputer(); void drawNotes(); + drawTasks(); drawComputer(); void drawNotes(); agentTasks.watch(true); (capsule.closest('dialog[open]') || document.body).append(box); try { box.showPopover ? box.showPopover() : (box.hidden = false); } catch { box.hidden = false; } place(); diff --git a/web/upscale_offer.js b/web/upscale_offer.js index 0cbb3462..e57f3f5a 100644 --- a/web/upscale_offer.js +++ b/web/upscale_offer.js @@ -7,11 +7,13 @@ export function upscaleSize(width, height) { return {width: width * 3 / 2, height: height * 3 / 2}; } -// The work's own picture: finished (not a preview), 24 fps and of a known length. +// The work's own picture: finished (not a preview), 24 fps, of a known length and with its saved request. export function upscaleSource(row) { const g = row?.geometry || {}; if (!row || row.kind === 'image' || row.preview) return null; if ((g.fps ?? 24) !== 24 || !Number.isSafeInteger(g.frames) || g.frames < 1) return null; + // One step resamples with the prompt and seed saved with the work: a merged video has neither (4K does not need them). + if (row.saved_request === false) return null; const size = upscaleSize(g.width, g.height); return size && {...size, frames: g.frames}; } diff --git a/web/view_navigation.js b/web/view_navigation.js index b8ce76bb..a6f595c8 100644 --- a/web/view_navigation.js +++ b/web/view_navigation.js @@ -94,7 +94,8 @@ export function viewSwitch(view, onStudio, onNodes, onEditor, onAutopilot, onIma if (id === 'autopilot') text.setAttribute('translate', 'no'); button.dataset.label = label; button.dataset.view = id; if (id === 'editor') button.dataset.fvGuide = 'longer'; - button.setAttribute('aria-pressed', String(view === id)); button.onclick = () => { + button.setAttribute('aria-pressed', String(view === id)); button.onclick = event => { + const byPointer = event?.detail > 0; const go = () => { const result = action?.(); if (id === 'autopilot') Promise.resolve(result).then(() => import('./feature_tour.js')).then(({triggerFeatureTour}) => triggerFeatureTour(id)).catch(() => {}); @@ -105,7 +106,7 @@ export function viewSwitch(view, onStudio, onNodes, onEditor, onAutopilot, onIma for (const tab of group.querySelectorAll('[data-view]')) tab.setAttribute('aria-pressed', String(tab === button)); // A view that says no (the editor keeping unsaved work) stays in front, and so does its tab. const result = switchView(id, go); - Promise.resolve(result).then(answer => { if (answer === false) syncTabs(); else keepFocusOnTab(id); }, () => syncTabs()); + Promise.resolve(result).then(answer => { if (answer === false) syncTabs(); else keepFocusOnTab(id, byPointer); }, () => syncTabs()); return result; }; if (id === 'autopilot') { @@ -125,12 +126,15 @@ export function viewSwitch(view, onStudio, onNodes, onEditor, onAutopilot, onIma // The view that was left hid what had focus; focus goes to the pressed tab of the bar now in front, so keys go on // from where the press was (never to the page itself). Focus the user already moved elsewhere stays. -function keepFocusOnTab(id) { +function keepFocusOnTab(id, byPointer = false) { const lost = () => { const at = document.activeElement; return !at || at === document.body || !at.checkVisibility?.(); }; requestAnimationFrame(() => requestAnimationFrame(() => { if (!lost()) return; const tab = [...document.querySelectorAll(`.fv-view-switch [data-view="${id}"][aria-pressed=true]`)].find(b => b.checkVisibility?.()); - tab?.focus({preventScroll: true}); + if (!tab) return; + // Focus put back after a mouse press is not keyboard focus: no ring until a key is used (a11y.css). + if (byPointer) { tab.dataset.fvPointerFocus = 'true'; tab.addEventListener('blur', () => delete tab.dataset.fvPointerFocus, {once: true}); tab.addEventListener('keydown', () => delete tab.dataset.fvPointerFocus, {once: true}); } + tab.focus({preventScroll: true}); })); } diff --git a/web/whatsnew.css b/web/whatsnew.css index 99f5179b..c79cc566 100644 --- a/web/whatsnew.css +++ b/web/whatsnew.css @@ -56,6 +56,9 @@ .fv-whatsnew-top.fv-whatsnew-ed.fv-studio.fv-editor{overflow:hidden;background:var(--fv-card);transition:height .24s var(--fv-ease)} .fv-whatsnew-top .fv-ed-genbar,.fv-whatsnew-top .fv-ed-record{grid-column:auto;grid-row:auto;box-sizing:border-box;min-height:56px} .fv-whatsnew-top .fv-ed-genbar[hidden],.fv-whatsnew-top .fv-ed-record[hidden]{display:none} +/* The bar is as tall as its content at every width, with the 8 px gap above the tracks the wide layout has (editor.css): + the narrow editor's height:100% would size it to the box around it and push a bar that wraps to two rows 4 px over the ruler. */ +.fv-whatsnew-top.fv-whatsnew-ed .fv-ed-genbar{height:auto;margin-bottom:8px} .fv-whatsnew-top .fv-ed-record-end{justify-content:flex-end;align-items:center} .fv-whatsnew-top .fv-ed-record-side{align-items:center;color:var(--fv-muted)} .fv-whatsnew-top .fv-ed-description-box{flex:1} @@ -128,6 +131,8 @@ @media (prefers-reduced-motion:no-preference){.fv-whatsnew-typed i{animation:fv-whatsnew-caret 1s steps(1) infinite}} @keyframes fv-whatsnew-caret{50%{opacity:0}} :root:root .fv-whatsnew .fv-whatsnew-list{display:grid;grid-template-columns:1fr 1fr;gap:var(--fv-sp-8,8px) var(--fv-sp-24,24px);margin:var(--fv-sp-16,16px) var(--fv-sp-24,24px) 0;padding:0;list-style:none;font-size:var(--fv-fs-2,13px);line-height:20px} +/* A plain list (no numbers: the picture page) stays one column at every width, as before the redesign (Iris). */ +:root:root .fv-whatsnew .fv-whatsnew-list[data-plain]{grid-template-columns:1fr} :root:root .fv-whatsnew .fv-whatsnew-list li{display:flex;gap:var(--fv-sp-8,8px);color:var(--fv-fg2,var(--fv-ink))} :root:root .fv-whatsnew .fv-whatsnew-list li::before{content:'';flex:none;width:16px;height:16px;margin-top:2px;background:var(--fv-accent-ink,var(--fv-accent)); -webkit-mask:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' fill='none' stroke='%23000' stroke-width='1.8' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M3.5 8.5l3 3 6-7'/%3E%3C/svg%3E") center/contain no-repeat;