1 Commits
Author SHA1 Message Date
rookiestar28 b719d2df86 build: prepare public source 2026-10-13 21:01:12 +08:00
69 changed files with 3701 additions and 9155 deletions
+40 -22
View File
@@ -18,6 +18,22 @@ implementation.
<details>
<summary><strong>1.2.1 — Manual media tools setup and sequence assembly fix</strong></summary>
- The extension no longer downloads or installs FFmpeg. **Settings → Media tools** now opens the
exact download page, shows the archive name and SHA-256, and admits the extracted **bin**
folder after verifying both programs. Retry the action you started once the tools are selected.
- A **?** button beside **Media tools** explains setup, checksum verification and the supported
build in English, Traditional Chinese and Simplified Chinese.
- Tools that 1.2.0 or earlier already set up keep working without changes. Leftover files from an
earlier interrupted setup are removed only when you choose the cleanup control.
- Sequences built from your own ComfyUI video generations now assemble; earlier versions
refused those segments because of their color tag and their millisecond-rounded length.
</details>
<details>
<summary><strong>1.2.0 — Title decorations, editor updates and local perception setup</strong></summary>
- Style titles with strokes, sharp shadows and background padding. Preserve literal line breaks
@@ -152,7 +168,8 @@ Public source and Registry packages include the test suites and their support fi
- **MiniMax H3 model weights** and suitable hardware to generate video. Building and checking
prompts needs no weights.
- **Windows x64 with 64-bit Python** for the clip editor, Production import, longer-video assembly
and final rendering, plus the [media tools](#media-tools), which are found or installed for you.
and final rendering, plus the [media tools](#media-tools), which you provide and the extension
verifies.
The package has no required Python dependencies and never installs or changes ComfyUI, its
frontend or your models.
@@ -216,24 +233,26 @@ still waiting in the browser.
### Media tools
The clip editor, Production import, longer-video assembly and final rendering use one exact FFmpeg
build on Windows x64 with 64-bit Python: the gyan.dev full build `2026-02-26-git-6695528af6`. No
path setup is needed.
build on Windows x64 with 64-bit Python: the gyan.dev full build `2026-02-26-git-6695528af6`.
- **Already installed.** If that build's `ffmpeg.exe` and `ffprobe.exe` are in your Python
environment or on `PATH`, they are found the first time you use a media feature.
- **Not installed.** When a feature needs the tools, a **Media tools** card appears with **Install
and continue**. It downloads the build from its GitHub release (about 235 MB), checks it, keeps
only the two programs with their license and readme, then carries on with what you started.
**Cancel setup** stops the download without changing your work. The same **Install** button is
in **Settings → Media tools**.
- **Where it goes.** The installed copy (about 425 MB) lives in ComfyUI's private user data,
outside this package, and is reused after restarts.
- **Offline or managed computers.** In **Settings → Media tools → Advanced**, enter a folder that
holds both programs of that build and choose **Use this folder**. **Use automatic setup** returns
to the default. The download never uses a proxy, so use this option on computers that need one.
- **Provide the supported tools.** In **Settings → Media tools**, choose **Open download page**
(the [release page](https://github.com/GyanD/codexffmpeg/releases/tag/2026-02-26-git-6695528af6)),
download `ffmpeg-2026-02-26-git-6695528af6-full_build.zip` (about 235 MB), compare the archive
SHA-256 shown on the card, and extract it yourself. Enter the **bin** folder containing both
`ffmpeg.exe` and `ffprobe.exe`, then choose **Use folder**. The extension verifies both programs
before saving the selection. Retry your original action after selecting them. The **?** button
beside **Media tools** shows these steps, including checksum commands, in your language.
- **Automatic discovery.** A supported pair in your Python environment or on `PATH` is found on
first use. Choose **Check again** after changing `PATH`; **Advanced → Search automatically**
clears a saved local selection and restores discovery. An installation made by an earlier
version is still discovered and reused. Earlier setup leftovers are removed only by the explicit
cleanup control, which preserves an older copy until its managed replacement is verified.
- **Offline or managed computers.** Select a locally provided supported pair with **Use folder**.
The extension performs no media-tool download, archive extraction or executable installation.
- **Administrators** can set `H3_CONTEXT_AUTHORIZED_FFMPEG_PATH` and
`H3_CONTEXT_AUTHORIZED_FFPROBE_PATH` to the two programs in one folder; this overrides everything
else. `H3_CONTEXT_AUTHORIZED_MEDIA_SCRATCH_ROOT` can name the temporary media folder.
else. `H3_CONTEXT_AUTHORIZED_MEDIA_SCRATCH_ROOT` can also name the temporary media folder; it is
accepted only together with both program paths.
Any other FFmpeg build, a modified file, Windows on ARM, 32-bit Python or a non-Windows host is not
used, and the card says why. To check a copy yourself, compare these SHA-256 fingerprints:
@@ -920,7 +939,7 @@ Review workflows and screenshots before sharing them. More detail is in
| Problem | What to check |
| --------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
| A media feature says it is unavailable | Open **Settings → Media tools** and follow the card: **Install**, **Check again**, or the reason shown. |
| A media feature says it is unavailable | Open **Settings → Media tools** and follow the card: **Use folder**, **Check again**, or the reason shown. |
| **Import** is missing or does nothing | Select up to three finished segments in Production first. |
| An imported clip is in the bin but not on the timeline | Import only adds sources; press **+** on its card. |
| An imported clip became unavailable | Keep its Production project available, or open a saved project and explicitly relink compatible retained media. A released source is never silently replaced. |
@@ -953,8 +972,7 @@ screenshots.
## License
Apache-2.0; see [LICENSE](LICENSE) and [NOTICE](NOTICE). The bundled Noto Sans fonts use the SIL
Open Font License 1.1. FFmpeg is not included: it is downloaded only when you choose **Install**
and is licensed separately under GPL-3.0-or-later. The official workflow templates are served by
the ComfyUI frontend (Comfy-Org `workflow_templates`, MIT) and are not redistributed here. Models
and provider services have their own terms. This project is not affiliated with or endorsed by
MiniMax.
Open Font License 1.1. FFmpeg is not included: you provide the supported build yourself, and it is
licensed separately under GPL-3.0-or-later. The official workflow templates are served by the
ComfyUI frontend (Comfy-Org `workflow_templates`, MIT) and are not redistributed here. Models and
provider services have their own terms. This project is not affiliated with or endorsed by MiniMax.
+36
View File
@@ -1,3 +1,39 @@
# Release 1.2.1
## Manual media tools setup
- The extension no longer downloads, extracts or installs FFmpeg. **Settings → Media tools**
replaces in-panel installation with a manual setup guide: **Open download page** opens the
exact release page in your browser, and the card shows the archive name and its SHA-256 with a
copy button.
- Enter the extracted **bin** folder and choose **Use folder**. Both programs are verified against
their fixed digests before the selection is saved. A supported pair in your Python environment
or on `PATH` is still found automatically; choose **Check again** after changing `PATH`.
- A **?** button beside **Media tools** explains download, checksum verification (with Windows
commands), extraction, folder selection and why other builds are refused. It is available in
English, Traditional Chinese and Simplified Chinese.
- After you select the tools, retry the original media action yourself; it is not resumed
automatically.
- Clean up known earlier setup leftovers only when requested, preserving unknown files and any
parked runtime without a verified replacement.
## Sequence assembly fix
- Sequences built from your own ComfyUI video generations now assemble. Earlier versions
refused these segments: first because of the color tag ComfyUI writes into its video files,
and then, for 5-second and 15-second segments, because the file states its length rounded to
the millisecond.
- Segments with that color tag are converted to the standard video color space while they are
prepared for assembly. Segments that are already standard are prepared as before.
## Upgrade and limits
Replace the complete package, restart ComfyUI and refresh the browser. Tools that 1.2.0 or an
earlier version already installed are still discovered and verified; no action is needed. The
supported build, platforms and project format are unchanged from 1.2.0.
---
# Release 1.2.0
## Titles and editing
+1 -1
View File
@@ -128,7 +128,7 @@ if os.environ.get("H3_CONTEXT_HOST_TWO_ENDED_BRIDGE_CANARY") == "1":
TWO_ENDED_BRIDGE_CANARY_NODE_ID: "H3 Context (two-ended AV bridge canary)",
}
__version__ = "1.2.0"
__version__ = "1.2.1"
WEB_DIRECTORY = "web"
# CRITICAL: this bounded operator attempt runs after node registration. Its module owner survives
@@ -27,7 +27,7 @@ from .authoring_render_service import RenderExecutionIdentity, RenderServiceErro
# Exact executed corpus evidence; item acceptance still requires the native gate and review.
_ACCEPTED_EVIDENCE: Final[str | None] = (
"sha256:d9fcad4d7d2713faf141f93a53e6f164f231a9972c7708e187681ab3719936f8"
"sha256:26ccf5750cba59f4de3397459af0544ef1b500dbedc519b30e0ef283be5111fc"
)
_PACKAGE = Path(__file__).resolve().parents[1]
_EVIDENCE = _PACKAGE / "contracts" / "authoring_renderer_qualification_v2.json"
@@ -125,6 +125,11 @@ _PROCESS_SLOTS = threading.BoundedSemaphore(qualified_av_limits().process_concur
_PREVIEW_MAX_SOURCE_BYTES = 64 * 1024 * 1024
_PREVIEW_MAX_OUTPUT_BYTES = 8 * 1024 * 1024
_PREVIEW_MAX_DURATION_MS = 30_000
# IMPORTANT: host CreateVideo tags native H3 outputs with the sRGB transfer (`iec61966-2-1`)
# since ComfyUI 0.34.0; stock fixtures carry `bt709`. The M26 crop admits both
# and converts sRGB pixels to BT.709. Requiring `bt709` alone refuses every real generation
# (`m26_source_contribution_invalid`); admitting sRGB without the conversion would relabel colour.
_M26_SRGB_TRANSFER = "iec61966-2-1"
# IMPORTANT: the two encodes a user waits for -- the import normalization here and the
# derivative generator's proxy -- take their thread count from this one rule, and the
# generator's profile fingerprint, which keys its cache, names the rule and its value. The
@@ -579,7 +584,16 @@ def _rational(value: Fraction) -> AVRational:
def _duration_matches(observed: Fraction, expected: Fraction, time_base: Fraction) -> bool:
tolerance = max(time_base, Fraction(1, 1_000_000))
return abs(observed - expected) <= tolerance
if abs(observed - expected) <= tolerance:
return True
# IMPORTANT: MP4 states stream (edit list) and format durations in the movie timescale,
# 1/1000 s for host SaveVideo output. A 124-frame (5 s segment) H3 output decodes 165,334
# samples at 32 kHz but declares 5.167 s, ten ticks away, so a one-tick check refused every
# 5 s and 15 s segment. A declaration on the millisecond grid strictly within one millisecond
# of the decoded timeline is that rounding. Do not widen this to a plain tolerance: an
# off-grid declaration keeps the one-tick bound, and callers use the decoded counts, never
# the declaration.
return (observed * 1000).denominator == 1 and abs(observed - expected) < Fraction(1, 1000)
def _rotation(stream: Mapping[str, object]) -> int:
@@ -2438,6 +2452,7 @@ class QualifiedAVMediaAdapter:
*,
contribution_frames: int,
contribution_samples: int,
convert_srgb: bool = False,
) -> MediaProcessInvocation:
capability = qualified_ffmpeg_capability()
limits = qualified_av_limits()
@@ -2457,7 +2472,16 @@ class QualifiedAVMediaAdapter:
filters = (
"[0:v:0]"
f"trim=start_frame=0:end_frame={contribution_frames},"
"setpts=PTS-STARTPTS,format=yuv420p[v];"
"setpts=PTS-STARTPTS,"
# CRITICAL: the filter reads the source's declared sRGB transfer and converts pixels
# (the Authoring import conversion). BT.709 sources keep their exact crop graph.
+ (
"colorspace=all=bt709,"
"setparams=range=tv:color_primaries=bt709:color_trc=bt709:colorspace=bt709,"
if convert_srgb
else ""
)
+ "format=yuv420p[v];"
"[0:a:0]"
f"atrim=start_sample=0:end_sample={contribution_samples},"
"asetpts=PTS-STARTPTS,aresample=32000,"
@@ -2602,7 +2626,7 @@ class QualifiedAVMediaAdapter:
or video.color_range != target.color_range
or video.color_space != target.color_space
or video.color_primaries != target.color_primaries
or video.color_transfer != target.color_transfer
or video.color_transfer not in (target.color_transfer, _M26_SRGB_TRANSFER)
or video.rotation_degrees != 0
or video.frame_rate != AVRational(24, 1)
or video.decoded_frame_count < contribution_frames
@@ -2623,6 +2647,7 @@ class QualifiedAVMediaAdapter:
derived,
contribution_frames=contribution_frames,
contribution_samples=contribution_samples,
convert_srgb=video.color_transfer == _M26_SRGB_TRANSFER,
),
cancellation,
)
@@ -1,24 +1,13 @@
"""Owned media runtime status/setup routes and the one setup job they drive.
The user-facing contract is small: read the current media tool resolution, install the one fixed
supported build when it is missing, rescan, choose one advanced local tool directory, return to
automatic selection, and cancel a running install. The server chooses the source, the destination
and every command; a client supplies at most an action name, a job identity, one directory and a
config revision.
Nothing here runs at import or registration. The service is a composition-root component built on
first request, and the install job runs on its own thread so no route handler waits on a download.
"""Owned, offline media-runtime discovery, local selection and explicit recovery routes.
No import or registration acquires or installs executable code.
"""
from __future__ import annotations
import asyncio
import json
import re
import secrets
import threading
from collections.abc import Callable, Mapping
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any
from .comfyui_route_seam import (
@@ -32,16 +21,14 @@ from .comfyui_route_seam import (
)
from .composition_root import MEDIA_RUNTIME_SETUP, component
from .media_runtime_discovery_worker import MAX_LOCATOR_CHARS
from .media_runtime_download import DownloadPort, HttpsArchiveDownloader
from .media_runtime_installer import (
InstallerError,
ManagedRuntimeInstaller,
ManagedRuntimeManifest,
managed_runtime_manifest,
from .media_runtime_leftovers import (
RecoveryError,
abandoned_setup_jobs,
parked_runtime_trees,
reclaim_parked_runtimes,
)
from .media_runtime_manager import FEATURES, MediaRuntimeBusy
from .media_runtime_pin import MediaRuntimePin, media_runtime_pin
from .media_runtime_resolution import (
MediaRuntimeConfigError,
MediaRuntimePrivateLayout,
@@ -56,29 +43,22 @@ from .media_runtime_resolution import (
if TYPE_CHECKING:
from .media_runtime_manager import MediaRuntimeManager
STATUS_SCHEMA = "h3.context.media_runtime_status.v3"
JOB_SCHEMA = "h3.context.media_runtime_setup_job.v1"
REQUEST_SCHEMA = "h3.context.media_runtime_setup_request.v1"
STATUS_SCHEMA = "h3.context.media_runtime_status.v4"
REQUEST_SCHEMA = "h3.context.media_runtime_setup_request.v2"
STATUS_ROUTE = "/h3-context/v1/media-runtime"
SETUP_ROUTE = "/h3-context/v1/media-runtime/setup"
JOB_ROUTE = "/h3-context/v1/media-runtime/setup/{job_id}"
MAX_SETUP_REQUEST_BYTES = 8 * 1024
MAX_CONFIG_REVISION = 2**53 - 1
ACTIONS = (
"install_supported",
"rescan",
"use_local_directory",
"restore_auto",
"cancel_setup",
"reclaim_parked_runtime",
)
_JOB_ID = re.compile(r"[0-9a-f]{32}")
_ROUTE_OWNER_ATTRIBUTE = "__h3_context_media_runtime_route_owner__"
_ROUTE_REGISTERED = False
_REQUEST_KEYS: Mapping[str, frozenset[str]] = {
"install_supported": frozenset({"schema", "action"}),
"rescan": frozenset({"schema", "action"}),
"cancel_setup": frozenset({"schema", "action", "job_id"}),
"use_local_directory": frozenset({"schema", "action", "directory", "expected_revision"}),
"restore_auto": frozenset({"schema", "action", "expected_revision"}),
"reclaim_parked_runtime": frozenset({"schema", "action"}),
@@ -92,33 +72,7 @@ FEATURE_REASONS = frozenset(
| {"render_qualification_unavailable"}
| {reason.value for reason in ResolutionReason}
)
JOB_STATES = ("running", "succeeded", "failed", "cancelled")
JOB_PHASES = (
"checking",
"downloading",
"extracting",
"verifying",
"publishing",
"activating",
"done",
)
JOB_REASONS = frozenset(
{
"cancelled",
"already_available",
"advanced_override_active",
"config_invalid",
"local_selection_active",
"installed",
"verification_failed",
"internal_failure",
MediaRuntimeBusy.code,
}
| InstallerError.CODES
| MediaRuntimeConfigError.CODES
| {reason.value for reason in ResolutionReason}
)
RECOVERY_STATES = ("parked_runtime",)
RECOVERY_STATES = ("parked_runtime", "abandoned_setup")
_RECLAIM_ERROR_STATUS: Mapping[str, int] = {
"reclaim_unsafe": 409,
"setup_busy": 409,
@@ -144,7 +98,7 @@ _CONFIG_ERROR_STATUS: Mapping[str, int] = {
REFUSAL_CODES = (
frozenset(_CONFIG_ERROR_STATUS)
| frozenset(_RECLAIM_ERROR_STATUS)
| {"setup_busy", "setup_job_not_found", "internal_failure"}
| {"setup_busy", "internal_failure"}
| {"media_type_rejected", "origin_rejected", "request_too_large"}
)
@@ -159,79 +113,34 @@ class MediaRuntimeSetupError(RuntimeError):
# --------------------------------------------------------------------------------------------
# Job
# Recovery dependencies
@dataclass(slots=True)
class _Job:
job_id: str
cancelled: threading.Event
state: str = "running"
phase: str = "checking"
reason: str | None = None
completed_bytes: int = 0
total_bytes: int = 0
downloader: DownloadPort | None = None
def to_wire(self) -> dict[str, object]:
return {
"schema": JOB_SCHEMA,
"job_id": self.job_id,
"state": self.state,
"phase": self.phase,
"reason": self.reason,
"progress": {
"completed_bytes": self.completed_bytes,
"total_bytes": self.total_bytes,
},
}
def _start_daemon(target: Callable[[], None]) -> None:
threading.Thread(target=target, name="h3-media-runtime-setup", daemon=True).start()
def _new_job_id() -> str:
return secrets.token_hex(16)
InstallerFactory = Callable[..., Any]
ParkedScanner = Callable[[MediaRuntimePrivateLayout, ManagedRuntimeManifest], tuple[Any, ...]]
Reclaimer = Callable[[MediaRuntimePrivateLayout, ManagedRuntimeManifest], int]
ParkedScanner = Callable[[MediaRuntimePrivateLayout, MediaRuntimePin], tuple[Any, ...]]
Reclaimer = Callable[[MediaRuntimePrivateLayout, MediaRuntimePin], int]
class MediaRuntimeSetupService:
"""One setup job per process, and serialized setup actions."""
"""Serialized offline selection and explicit recovery actions."""
def __init__(
self,
*,
resolver: MediaRuntimeResolver,
manager: MediaRuntimeManager | None = None,
downloader_factory: Callable[[], DownloadPort] = HttpsArchiveDownloader,
installer_factory: InstallerFactory = ManagedRuntimeInstaller,
manifest_provider: Callable[[], ManagedRuntimeManifest] = managed_runtime_manifest,
thread_starter: Callable[[Callable[[], None]], None] = _start_daemon,
job_id_factory: Callable[[], str] = _new_job_id,
manifest_provider: Callable[[], MediaRuntimePin] = media_runtime_pin,
parked_scanner: ParkedScanner = parked_runtime_trees,
abandoned_scanner: ParkedScanner = abandoned_setup_jobs,
reclaimer: Reclaimer = reclaim_parked_runtimes,
) -> None:
self._resolver = resolver
self._manager = manager
self._downloader_factory = downloader_factory
self._installer_factory = installer_factory
self._manifest_provider = manifest_provider
self._thread_starter = thread_starter
self._job_id_factory = job_id_factory
self._parked_scanner = parked_scanner
self._abandoned_scanner = abandoned_scanner
self._reclaimer = reclaimer
self._lock = threading.Lock()
# IMPORTANT: one action slot shared by the install job and every config/rescan action.
# The job holds it from start to finish, so a local-directory write cannot race the
# publication rename, and a rescan cannot supersede the job's own activation resolve.
# IMPORTANT: config transitions and cleanup share a nonblocking process action slot.
# Cleanup must not race the binding/config transition that decides whether it is safe.
self._action_slot = threading.Lock()
self._current: _Job | None = None
self._last: _Job | None = None
def __repr__(self) -> str:
return "<MediaRuntimeSetupService>"
@@ -249,41 +158,42 @@ class MediaRuntimeSetupService:
):
self._manager.ensure()
config = self._config_wire()
parked = self._parked()
with self._lock:
job = self._current or self._last
job_wire = None if job is None else job.to_wire()
running = self._current is not None
# The published managed pair is what makes a parked tree safe to remove. The resolver's
# located managed binding is the cheap read here; the reclaim itself re-pins the pair
# under the install lock before deleting anything.
parked, abandoned = self._leftovers()
reclaimable = (
parked
and not running
and resolution.state is ResolutionState.LOCATED
and resolution.source_kind is SourceKind.MANAGED
abandoned
and not parked
or (
parked
and resolution.state is ResolutionState.LOCATED
and resolution.source_kind is SourceKind.MANAGED
)
)
return {
"schema": STATUS_SCHEMA,
"resolution": resolution.to_wire(),
"config": config,
"setup": job_wire,
"install": self._install_wire(),
"manual": self._manual_wire(),
"features": self._features(resolution),
"recovery": (
{"state": "parked_runtime", "reclaimable": reclaimable} if parked else None
),
"actions": list(
self._actions(resolution, config, running=running, reclaimable=reclaimable)
{
"state": "parked_runtime" if parked else "abandoned_setup",
"reclaimable": reclaimable,
}
if parked or abandoned
else None
),
"actions": list(self._actions(resolution, config, reclaimable=reclaimable)),
}
def _parked(self) -> bool:
def _leftovers(self) -> tuple[bool, bool]:
try:
layout = self._resolver.private_layout()
except MediaRuntimeConfigError:
return False
return bool(self._parked_scanner(layout, self._manifest_provider()))
return False, False
manifest = self._manifest_provider()
return bool(self._parked_scanner(layout, manifest)), bool(
self._abandoned_scanner(layout, manifest)
)
def _features(self, resolution: MediaRuntimeResolution) -> dict[str, dict[str, str | None]]:
if self._manager is not None:
@@ -293,13 +203,6 @@ class MediaRuntimeSetupService:
feature: {"state": state, "reason": resolution.reason.value} for feature in FEATURES
}
def job(self, job_id: str) -> dict[str, object]:
with self._lock:
for job in (self._current, self._last):
if job is not None and job.job_id == job_id:
return job.to_wire()
raise MediaRuntimeSetupError("setup_job_not_found", 404)
def _config_wire(self) -> dict[str, object] | None:
try:
config = self._resolver.read_config()
@@ -309,10 +212,11 @@ class MediaRuntimeSetupService:
return {"revision": 0, "selection": MediaRuntimeSelection.AUTO.value}
return {"revision": config.revision, "selection": config.selection.value}
def _install_wire(self) -> dict[str, object]:
def _manual_wire(self) -> dict[str, object]:
manifest = self._manifest_provider()
return {
"profile": manifest.profile_component,
"archive_name": manifest.archive_filename,
"archive_sha256": manifest.archive_sha256,
"source_label": manifest.source_label,
"release_page": manifest.release_page_url,
"license": manifest.license_name,
@@ -324,11 +228,8 @@ class MediaRuntimeSetupService:
resolution: MediaRuntimeResolution,
config: Mapping[str, object] | None,
*,
running: bool,
reclaimable: bool = False,
) -> tuple[str, ...]:
if running:
return ("cancel_setup",)
available = {"rescan"}
if reclaimable:
available.add("reclaim_parked_runtime")
@@ -336,138 +237,8 @@ class MediaRuntimeSetupService:
available.add("use_local_directory")
if config["selection"] == MediaRuntimeSelection.LOCAL.value:
available.add("restore_auto")
elif resolution.install_resolves:
available.add("install_supported")
return tuple(action for action in ACTIONS if action in available)
# -- install job -----------------------------------------------------------------------
def start_install(self) -> dict[str, object]:
with self._lock:
if self._current is not None:
# A duplicate request -- a second click, another tab -- shares the running job.
return self._current.to_wire()
if not self._action_slot.acquire(blocking=False):
raise MediaRuntimeSetupError("setup_busy", 409)
job = _Job(job_id=self._job_id_factory(), cancelled=threading.Event())
self._current = job
wire = job.to_wire()
try:
self._thread_starter(lambda: self._run(job))
except BaseException:
self._finish(job, "failed", "internal_failure")
raise
return wire
def cancel(self, job_id: str) -> dict[str, object]:
with self._lock:
current = self._current
if current is None or current.job_id != job_id:
last = self._last
if last is not None and last.job_id == job_id:
return last.to_wire()
raise MediaRuntimeSetupError("setup_job_not_found", 404)
current.cancelled.set()
downloader = current.downloader
wire = current.to_wire()
if downloader is not None:
downloader.abort()
return wire
def _progress(self, job: _Job, phase: str, completed: int, total: int) -> None:
with self._lock:
job.phase = phase
job.completed_bytes = completed
job.total_bytes = total
def _finish(self, job: _Job, state: str, reason: str) -> None:
with self._lock:
if self._current is not job:
return
job.state = state
# A reason outside the closed vocabulary would make every client refuse the job wire,
# hiding a terminal job behind "status unavailable"; report it as an internal failure.
job.reason = reason if reason in JOB_REASONS else "internal_failure"
job.phase = "done"
job.downloader = None
self._current = None
self._last = job
self._action_slot.release()
def _precheck(self, job: _Job) -> tuple[str, str] | None:
resolution = self._resolver.resolve(rescan=True)
if job.cancelled.is_set():
return "cancelled", "cancelled"
if resolution.state is ResolutionState.LOCATED:
# Supported tools are already usable: no download, no write.
return "succeeded", "already_available"
if resolution.source_kind is SourceKind.EXPLICIT_OVERRIDE:
# An administrator's explicit override controls the result; installing cannot repair
# it and must not be offered as though it could.
return "failed", "advanced_override_active"
if resolution.source_kind is SourceKind.LOCAL_SELECTION:
if resolution.reason in {
ResolutionReason.CONFIG_CORRUPT,
ResolutionReason.CONFIG_UNSUPPORTED,
}:
return "failed", "config_invalid"
return "failed", "local_selection_active"
if resolution.install_resolves:
return None
# IMPORTANT: only a search that examined the managed directory proceeds (see
# `install_resolves`). A timeout or a limit reached before enumeration never proved the
# managed directory is broken, and publication would retire a tree that may be valid.
return "failed", resolution.reason.value
def _run(self, job: _Job) -> None:
try:
verdict = self._precheck(job)
if verdict is not None:
self._finish(job, *verdict)
return
layout = self._resolver.private_layout()
downloader = self._downloader_factory()
with self._lock:
job.downloader = downloader
installer = self._installer_factory(
layout,
manifest=self._manifest_provider(),
downloader=downloader,
job_token=job.job_id,
cancelled=job.cancelled,
progress=lambda phase, done, total: self._progress(job, phase, done, total),
)
installer.run()
self._progress(job, "activating", 0, 0)
if self._activate_managed():
self._finish(job, "succeeded", "installed")
else:
self._finish(job, "failed", "verification_failed")
except InstallerError as exc:
if exc.code == "cancelled":
self._finish(job, "cancelled", "cancelled")
else:
self._finish(job, "failed", exc.code)
except MediaRuntimeConfigError as exc:
self._finish(job, "failed", exc.code)
except MediaRuntimeBusy:
self._finish(job, "failed", MediaRuntimeBusy.code)
except Exception: # noqa: BLE001 - a job thread must always reach a terminal state
self._finish(job, "failed", "internal_failure")
def _activate_managed(self) -> bool:
"""Apply a just-published install in this process; only a managed binding succeeds."""
if self._manager is None:
self._resolver.invalidate()
resolution = self._resolver.resolve(rescan=True)
return (
resolution.state is ResolutionState.LOCATED
and resolution.source_kind is SourceKind.MANAGED
)
binding = self._manager.refresh()
return binding is not None and binding.source_kind is SourceKind.MANAGED
# -- serialized actions ----------------------------------------------------------------
def _exclusive(self, action: Callable[[], object]) -> None:
@@ -528,7 +299,7 @@ class MediaRuntimeSetupService:
layout = self._resolver.private_layout()
try:
self._reclaimer(layout, self._manifest_provider())
except InstallerError as exc:
except RecoveryError as exc:
status = _RECLAIM_ERROR_STATUS.get(exc.code)
if status is None:
raise MediaRuntimeSetupError("internal_failure", 500) from exc
@@ -589,13 +360,6 @@ def dispatch_setup_request(
keys = _REQUEST_KEYS.get(action)
if keys is None or set(payload) != keys:
raise _invalid()
if action == "install_supported":
return 202, service.start_install()
if action == "cancel_setup":
job_id = payload["job_id"]
if type(job_id) is not str or _JOB_ID.fullmatch(job_id) is None:
raise _invalid()
return 200, service.cancel(job_id)
if action == "rescan":
return 200, service.rescan()
if action == "reclaim_parked_runtime":
@@ -639,14 +403,6 @@ _SETUP_POLICY = RoutePolicy(
max_bytes=MAX_SETUP_REQUEST_BYTES,
refusals=(MediaRuntimeSetupError,),
)
_JOB_POLICY = RoutePolicy(
path=JOB_ROUTE,
owner=JOB_SCHEMA,
owner_attribute=_ROUTE_OWNER_ATTRIBUTE,
method="GET",
origin=OriginRule.SAME_ORIGIN_GET,
refusals=(MediaRuntimeSetupError,),
)
def _refusal_body(_status: int, reason: str) -> dict[str, str]:
@@ -659,15 +415,6 @@ def _refusal(error: BaseException) -> RouteResult:
return RouteResult(error.status, {"error": error.code})
def _job_prelude(request: object) -> object:
match_info = getattr(request, "match_info", None)
get_match = getattr(match_info, "get", None)
job_id = get_match("job_id") if callable(get_match) else None
if type(job_id) is not str or _JOB_ID.fullmatch(job_id) is None:
return RouteResult(400, {"error": "invalid_request"})
return job_id
async def _read_status(_payload: bytes, _context: object) -> RouteResult:
service = media_runtime_setup()
return RouteResult(200, await asyncio.to_thread(service.status))
@@ -679,14 +426,8 @@ async def _apply_setup(payload: bytes, _context: object) -> RouteResult:
return RouteResult(status, wire)
async def _read_job(_payload: bytes, context: object) -> RouteResult:
if type(context) is not str:
raise MediaRuntimeSetupError("invalid_request", 400)
return RouteResult(200, media_runtime_setup().job(context))
def ensure_media_runtime_setup_route_registered() -> bool:
"""Register the status, setup and job routes all-or-nothing, without importing host modules."""
"""Register the status and setup routes all-or-nothing, without importing host modules."""
global _ROUTE_REGISTERED
found = host_web_and_routes()
@@ -694,7 +435,7 @@ def ensure_media_runtime_setup_route_registered() -> bool:
_ROUTE_REGISTERED = False
return False
_, routes = found
for policy in (_STATUS_POLICY, _SETUP_POLICY, _JOB_POLICY):
for policy in (_STATUS_POLICY, _SETUP_POLICY):
if (
not route_method_available(routes, policy)
or already_owned(routes, policy, __name__) is False
@@ -707,15 +448,7 @@ def ensure_media_runtime_setup_route_registered() -> bool:
setup = register_owned_route(
_SETUP_POLICY, __name__, _apply_setup, _refusal_body, refusal_mapper=_refusal
)
job = register_owned_route(
_JOB_POLICY,
__name__,
_read_job,
_refusal_body,
refusal_mapper=_refusal,
prelude=_job_prelude,
)
_ROUTE_REGISTERED = status and setup and job
_ROUTE_REGISTERED = status and setup
return _ROUTE_REGISTERED
@@ -723,11 +456,6 @@ __all__ = [
"ACTIONS",
"FEATURE_REASONS",
"FEATURE_STATES",
"JOB_PHASES",
"JOB_REASONS",
"JOB_ROUTE",
"JOB_SCHEMA",
"JOB_STATES",
"MAX_SETUP_REQUEST_BYTES",
"RECOVERY_STATES",
"REFUSAL_CODES",
@@ -1,360 +0,0 @@
"""Fixed-source HTTPS download of the managed media runtime archive.
This transport fetches exactly one kind of object: the pinned release archive named by the
installer manifest. It accepts the manifest's `https://github.com/...` URL and follows at most a
few redirects, each only to the GitHub release-asset hosts. Every hop resolves through the
repository's killable resolver, refuses non-global addresses, and connects to that one validated
address with a default verifying TLS context. No proxy, cookie, credential, prompt or media is
ever sent, and nothing from a response -- including the signed redirect URL -- is logged, returned
or persisted.
The body is streamed into a caller-supplied sink in bounded chunks. Hashing and storage belong to
the installer; this module only guarantees that exactly `expected_bytes` arrived from an admitted
origin, or raises a closed, content-free `DownloadError`.
"""
from __future__ import annotations
import contextlib
import http.client
import socket
import ssl
import threading
import time
from collections.abc import Callable
from typing import Any, Protocol
from urllib.parse import urlsplit
from ..core.prompt_model_provider import PromptModelOutcomeId
from .prompt_model_transport import PromptModelTransportError, resolve_pinned_address_bounded
INITIAL_HOST = "github.com"
ASSET_HOSTS = frozenset({"release-assets.githubusercontent.com", "objects.githubusercontent.com"})
HTTPS_PORT = 443
MAX_REDIRECTS = 3
MAX_LOCATION_CHARS = 8 * 1024
CHUNK_BYTES = 1024 * 1024
CONNECT_TIMEOUT_SECONDS = 15.0
READ_IDLE_TIMEOUT_SECONDS = 60.0
DNS_TIMEOUT_SECONDS = 10.0
DOWNLOAD_DEADLINE_SECONDS = 3600.0
USER_AGENT = "ComfyUI-MinimaxH3-Context-media-setup/1"
_REDIRECT_STATUSES = frozenset({301, 302, 303, 307, 308})
_UNAVAILABLE_STATUSES = frozenset({404, 410})
class DownloadError(RuntimeError):
"""Closed, content-free download failure."""
CODES = frozenset(
{
"cancelled",
"download_failed",
"download_timeout",
"egress_refused",
"network_timeout",
"network_unavailable",
"redirect_refused",
"size_mismatch",
"source_unavailable",
"tls_failed",
}
)
def __init__(self, code: str) -> None:
if code not in self.CODES:
raise ValueError("unknown download error code")
self.code = code
super().__init__(code)
class DownloadPort(Protocol):
def download(
self,
url: str,
*,
expected_bytes: int,
sink: Callable[[bytes], None],
cancelled: threading.Event,
progress: Callable[[int], None],
) -> None: ...
def abort(self) -> None: ...
class _Target:
__slots__ = ("host", "target")
def __init__(self, host: str, target: str) -> None:
self.host = host
self.target = target
def _has_control_characters(value: str) -> bool:
return any(ord(character) < 0x21 or ord(character) == 0x7F for character in value)
def _admit_https(url: object, allowed_hosts: frozenset[str]) -> _Target:
"""Admit one absolute https URL on port 443 whose host is exactly one of `allowed_hosts`."""
if type(url) is not str or not url or len(url) > MAX_LOCATION_CHARS:
raise DownloadError("redirect_refused")
if _has_control_characters(url) or "\\" in url:
raise DownloadError("redirect_refused")
try:
parts = urlsplit(url)
port = parts.port
except ValueError as exc:
raise DownloadError("redirect_refused") from exc
host = parts.hostname
if (
parts.scheme != "https"
or "@" in parts.netloc
or host is None
or host not in allowed_hosts
or parts.netloc.lower() not in {host, f"{host}:{HTTPS_PORT}"}
or port not in {None, HTTPS_PORT}
or not parts.path.startswith("/")
):
raise DownloadError("redirect_refused")
target = parts.path + (f"?{parts.query}" if parts.query else "")
return _Target(host, target)
def admit_source_url(url: object) -> _Target:
"""The manifest URL itself must name the initial release host."""
return _admit_https(url, frozenset({INITIAL_HOST}))
def admit_redirect(location: object, *, from_host: str) -> _Target:
"""Admit one redirect hop.
SECURITY: only the initial release host may redirect, and only to a release-asset host. An
asset host that redirects again, a relative `Location`, another scheme or port, userinfo, or a
look-alike host is refused rather than followed. Widening this set is how a compromised or
spoofed hop turns a pinned archive download into a fetch from anywhere.
"""
if from_host != INITIAL_HOST:
raise DownloadError("redirect_refused")
return _admit_https(location, ASSET_HOSTS)
def _content_length(response: Any) -> int | None:
values = response.msg.get_all("Content-Length") if response.msg is not None else None
if not values:
return None
if len(values) != 1 or not values[0].isascii() or not values[0].isdigit():
raise DownloadError("download_failed")
return int(values[0])
def _map_resolution(exc: PromptModelTransportError) -> DownloadError:
if exc.outcome_id is PromptModelOutcomeId.TIMEOUT:
return DownloadError("network_timeout")
if exc.outcome_id is PromptModelOutcomeId.EGRESS_REFUSED:
return DownloadError("egress_refused")
return DownloadError("network_unavailable")
def _transport_failure(exc: BaseException, cancelled: threading.Event) -> DownloadError:
if cancelled.is_set():
return DownloadError("cancelled")
if isinstance(exc, (socket.timeout, TimeoutError)):
return DownloadError("network_timeout")
if isinstance(exc, ssl.SSLError):
return DownloadError("tls_failed")
if isinstance(exc, http.client.HTTPException):
return DownloadError("download_failed")
return DownloadError("network_unavailable")
class HttpsArchiveDownloader:
"""One download at a time; `abort` may be called from any thread."""
def __init__(
self,
*,
address_resolver: Callable[[str], str] | None = None,
connection_factory: Callable[[str, int, float], Any] | None = None,
clock: Callable[[], float] = time.monotonic,
deadline_seconds: float = DOWNLOAD_DEADLINE_SECONDS,
) -> None:
self._resolver = address_resolver
self._connection_factory = connection_factory
self._clock = clock
self._deadline_seconds = deadline_seconds
self._lock = threading.Lock()
self._connection: Any = None
self._tls_context: ssl.SSLContext | None = None
def __repr__(self) -> str:
return "<HttpsArchiveDownloader>"
def abort(self) -> None:
with self._lock:
connection = self._connection
sock = getattr(connection, "sock", None)
if sock is not None:
try:
# Shutting the socket down, not closing the connection object, is what releases a
# read blocked in another thread without racing that thread's own cleanup.
sock.shutdown(socket.SHUT_RDWR)
except OSError:
pass
def _open(self, host: str, deadline: float) -> Any:
remaining = deadline - self._clock()
if remaining <= 0:
raise DownloadError("download_timeout")
if self._connection_factory is not None:
return self._connection_factory(host, HTTPS_PORT, CONNECT_TIMEOUT_SECONDS)
if self._resolver is None:
try:
# CRITICAL: socket timeouts do not bound platform DNS; the killable resolver does,
# and it refuses any answer that is not globally routable.
pinned = resolve_pinned_address_bounded(
host,
timeout_seconds=min(DNS_TIMEOUT_SECONDS, remaining),
loopback_required=False,
)
except PromptModelTransportError as exc:
raise _map_resolution(exc) from exc
else:
pinned = self._resolver(host)
if self._tls_context is None:
self._tls_context = ssl.create_default_context()
connection = http.client.HTTPSConnection(
host, HTTPS_PORT, timeout=CONNECT_TIMEOUT_SECONDS, context=self._tls_context
)
# The hostname stays on the connection for SNI and certificate verification while the
# socket goes to the one address that was validated.
connection._create_connection = ( # type: ignore[attr-defined]
lambda address, connect_timeout, source: socket.create_connection(
(pinned, address[1]), connect_timeout, source
)
)
return connection
def download(
self,
url: str,
*,
expected_bytes: int,
sink: Callable[[bytes], None],
cancelled: threading.Event,
progress: Callable[[int], None],
) -> None:
if type(expected_bytes) is not int or expected_bytes <= 0:
raise ValueError("expected_bytes")
deadline = self._clock() + self._deadline_seconds
target = admit_source_url(url)
for _hop in range(MAX_REDIRECTS + 1):
if cancelled.is_set():
raise DownloadError("cancelled")
# Name resolution itself is not interruptible; it is bounded by DNS_TIMEOUT_SECONDS.
connection = self._open(target.host, deadline)
with self._lock:
self._connection = connection
try:
# IMPORTANT: a cancel whose `abort` ran while the address was still resolving found
# no socket to shut down. Re-checking only after registering the connection closes
# that window; checking before registering would reopen it.
if cancelled.is_set():
raise DownloadError("cancelled")
next_target = self._exchange(
connection, target, expected_bytes, sink, cancelled, progress, deadline
)
finally:
with self._lock:
self._connection = None
# Closing a failed connection is best effort.
with contextlib.suppress(Exception):
connection.close()
if next_target is None:
return
target = next_target
raise DownloadError("redirect_refused")
def _exchange(
self,
connection: Any,
target: _Target,
expected_bytes: int,
sink: Callable[[bytes], None],
cancelled: threading.Event,
progress: Callable[[int], None],
deadline: float,
) -> _Target | None:
try:
connection.connect()
if cancelled.is_set():
raise DownloadError("cancelled")
sock = getattr(connection, "sock", None)
if sock is not None:
sock.settimeout(READ_IDLE_TIMEOUT_SECONDS)
connection.putrequest("GET", target.target, skip_accept_encoding=True)
connection.putheader("User-Agent", USER_AGENT)
connection.putheader("Accept", "application/octet-stream")
connection.putheader("Accept-Encoding", "identity")
connection.putheader("Connection", "close")
connection.endheaders()
response = connection.getresponse()
status = response.status
if status in _REDIRECT_STATUSES:
locations = response.msg.get_all("Location") if response.msg is not None else None
if not locations or len(locations) != 1:
raise DownloadError("redirect_refused")
return admit_redirect(locations[0], from_host=target.host)
if status in _UNAVAILABLE_STATUSES:
raise DownloadError("source_unavailable")
if status != 200:
raise DownloadError("download_failed")
encoding = response.getheader("Content-Encoding")
if encoding not in {None, "identity"}:
raise DownloadError("download_failed")
declared = _content_length(response)
if declared is not None and declared != expected_bytes:
raise DownloadError("size_mismatch")
except DownloadError:
raise
except (OSError, http.client.HTTPException, ValueError) as exc:
raise _transport_failure(exc, cancelled) from exc
total = 0
while True:
if cancelled.is_set():
raise DownloadError("cancelled")
if self._clock() > deadline:
raise DownloadError("download_timeout")
try:
chunk = response.read(min(CHUNK_BYTES, expected_bytes + 1 - total))
except (OSError, http.client.HTTPException, ValueError) as exc:
raise _transport_failure(exc, cancelled) from exc
if not chunk:
break
total += len(chunk)
if total > expected_bytes:
raise DownloadError("size_mismatch")
# The sink is called outside the transport `try`: a disk-full or unsafe-store failure
# raised there is the installer's own typed error, not a network outcome.
sink(chunk)
progress(total)
if cancelled.is_set():
raise DownloadError("cancelled")
if total != expected_bytes:
raise DownloadError("size_mismatch")
return None
__all__ = [
"ASSET_HOSTS",
"DOWNLOAD_DEADLINE_SECONDS",
"INITIAL_HOST",
"MAX_REDIRECTS",
"DownloadError",
"DownloadPort",
"HttpsArchiveDownloader",
"admit_redirect",
"admit_source_url",
]
@@ -1,960 +0,0 @@
"""Validation, extraction and atomic publication of the one fixed managed media runtime.
The installer turns the pinned Gyan full-build archive into `media-runtime/runtime/<profile>/` under
the host's private H3 root. It never executes a downloaded file, never extracts a member it did not
name, and never publishes a tree whose executables fail the same exact pin every later spawn uses.
Order of work, each step refusing with one closed code before the next begins:
1. take the cross-process install lock and clean earlier jobs' known leftovers;
2. check free space, stream the archive into exclusive staging and compare its SHA-256;
3. validate the whole central directory, then stream only the retained members, hashing each;
4. pin both executables, then rename the finished tree into place, restoring any retired tree on
failure.
Nothing here decides whether an install is wanted; the setup service does that from the resolver.
A `retired/` tree that a job could not restore or remove stays parked until the user explicitly
reclaims it, which happens only under the same lock and after the published pair is re-verified.
"""
from __future__ import annotations
import hashlib
import json
import os
import re
import shutil
import stat
import threading
import zipfile
import zlib
from collections.abc import Callable, Mapping, Sequence
from dataclasses import dataclass
from pathlib import Path
from typing import Any
from ..core.av_reconstruction import qualified_ffmpeg_capability
from ..core.safe_paths import UnsafePathError, ensure_directory, validate_directory
from .executable_admission import (
ExecutableAdmissionError,
FileIdentity,
pin_exact_executable,
windows_open_read_pin,
)
from .media_runtime_download import DownloadError, DownloadPort
from .media_runtime_resolution import MANAGED_PROFILE_COMPONENT, MediaRuntimePrivateLayout
from .segment_artifact_store import (
ArtifactStoreError,
_identity,
_is_link_or_reparse,
_safe_unlink,
_validated_directories,
_windows_open_existing_file,
_windows_open_new_file,
_write_new_file,
)
RELEASE_TAG = "2026-02-26-git-6695528af6"
SOURCE_URL = (
"https://github.com/GyanD/codexffmpeg/releases/download/"
f"{RELEASE_TAG}/ffmpeg-{RELEASE_TAG}-full_build.zip"
)
RELEASE_PAGE_URL = f"https://github.com/GyanD/codexffmpeg/releases/tag/{RELEASE_TAG}"
SOURCE_LABEL = "Gyan.dev FFmpeg full build"
LICENSE_NAME = "GPL-3.0-or-later"
SOURCE_NOTICE_SCHEMA = "h3.context.managed_media_runtime_source.v1"
MAX_ARCHIVE_MEMBERS = 64
MAX_EXPANDED_BYTES = 1024 * 1024 * 1024
MAX_MEMBER_NAME_CHARS = 260
SPACE_MARGIN_BYTES = 64 * 1024 * 1024
MAX_STAGING_ENTRIES = 64
MAX_SWEPT_JOBS = 16
CHUNK_BYTES = 1024 * 1024
STAGING_DIRECTORY = "staging"
LOCK_FILENAME = "install.lock"
ARCHIVE_FILENAME = "archive.zip.part"
TREE_DIRECTORY = "tree"
RETIRED_DIRECTORY = "retired"
SOURCE_NOTICE_FILENAME = "source.json"
JOB_TOKEN = re.compile(r"[0-9a-f]{32}")
_RESERVED_NAMES = frozenset(
{"con", "prn", "aux", "nul"}
| {f"com{index}" for index in range(1, 10)}
| {f"lpt{index}" for index in range(1, 10)}
)
_FORBIDDEN_NAME_CHARACTERS = frozenset('<>"|?*')
class InstallerError(RuntimeError):
"""Closed, content-free installation failure."""
CODES = frozenset(
{
"archive_invalid",
"digest_mismatch",
"insufficient_space",
"permission_denied",
"private_root_invalid",
"publication_failed",
"reclaim_unsafe",
"runtime_busy",
"setup_busy",
"unsupported_platform",
"write_failed",
}
| DownloadError.CODES
)
def __init__(self, code: str) -> None:
if code not in self.CODES:
raise ValueError("unknown installer error code")
self.code = code
super().__init__(code)
# --------------------------------------------------------------------------------------------
# Manifest
@dataclass(frozen=True, slots=True)
class RetainedMember:
archive_name: str
published_name: str
size: int
sha256: str
executable: bool
@dataclass(frozen=True, slots=True)
class ManagedRuntimeManifest:
profile_component: str
source_url: str
release_page_url: str
source_label: str
license_name: str
archive_bytes: int
archive_sha256: str
member_count: int
expanded_bytes: int
top_directory: str
retained: tuple[RetainedMember, ...]
@property
def retained_bytes(self) -> int:
return sum(member.size for member in self.retained)
def managed_runtime_manifest() -> ManagedRuntimeManifest:
"""The one approved profile; executable digests come from the qualified capability."""
capability = qualified_ffmpeg_capability()
return ManagedRuntimeManifest(
profile_component=MANAGED_PROFILE_COMPONENT,
source_url=SOURCE_URL,
release_page_url=RELEASE_PAGE_URL,
source_label=SOURCE_LABEL,
license_name=LICENSE_NAME,
archive_bytes=246_558_061,
archive_sha256=(
"ad18ecdedfca6d51c28cf12f2c96287c" # pragma: allowlist secret
"e1150686578b75bff2efcd06ff34bb30" # pragma: allowlist secret
),
member_count=49,
expanded_bytes=680_107_427,
top_directory=f"ffmpeg-{RELEASE_TAG}-full_build/",
retained=(
RetainedMember(
"bin/ffmpeg.exe",
"bin/ffmpeg.exe",
222_400_512,
capability.ffmpeg_sha256.casefold(),
True,
),
RetainedMember(
"bin/ffprobe.exe",
"bin/ffprobe.exe",
222_195_200,
capability.ffprobe_sha256.casefold(),
True,
),
RetainedMember(
"LICENSE",
"LICENSE.txt",
35_147,
"8ceb4b9ee5adedde47b31e975c1d90c7" # pragma: allowlist secret
"3ad27b6b165a1dcd80c7c545eb65b903", # pragma: allowlist secret
False,
),
RetainedMember(
"README.txt",
"README.txt",
45_177,
"4c76fc9cfe8ffe67b741331f7db9f1ab" # pragma: allowlist secret
"71e9804eefcb2928148edb9044bd59ca", # pragma: allowlist secret
False,
),
),
)
# --------------------------------------------------------------------------------------------
# Archive validation
def _member_parts(name: object, top_directory: str) -> tuple[tuple[str, ...], bool] | None:
"""Split one archive name into safe components under the top directory, or refuse it."""
if type(name) is not str or not name or len(name) > MAX_MEMBER_NAME_CHARS:
return None
if "\\" in name or ":" in name or name.startswith("/"):
return None
if any(ord(character) < 0x20 or ord(character) == 0x7F for character in name):
return None
directory = name.endswith("/")
parts = name[:-1].split("/") if directory else name.split("/")
for part in parts:
if (
part in {"", ".", ".."}
or part != part.rstrip(" .")
or part.split(".", 1)[0].casefold() in _RESERVED_NAMES
or any(character in _FORBIDDEN_NAME_CHARACTERS for character in part)
):
return None
if f"{parts[0]}/" != top_directory:
return None
return tuple(parts), directory
def validate_archive_members(
infos: Sequence[zipfile.ZipInfo], manifest: ManagedRuntimeManifest
) -> Mapping[str, zipfile.ZipInfo]:
"""Admit the whole central directory before any member byte is read.
SECURITY: every member is judged, not only the retained ones. A traversal, link, duplicate or
case-colliding name anywhere in the archive means the bytes are not the reviewed release, and
an archive that is not the reviewed release is not partially trusted.
"""
if len(infos) > MAX_ARCHIVE_MEMBERS or len(infos) != manifest.member_count:
raise InstallerError("archive_invalid")
declared = 0
exact: set[str] = set()
folded: set[str] = set()
directories: set[str] = set()
files: set[str] = set()
admitted: dict[str, zipfile.ZipInfo] = {}
for info in infos:
split = _member_parts(info.filename, manifest.top_directory)
if split is None:
raise InstallerError("archive_invalid")
parts, directory = split
key = "/".join(parts)
if key in exact or key.casefold() in folded:
raise InstallerError("archive_invalid")
exact.add(key)
folded.add(key.casefold())
mode = (info.external_attr >> 16) & 0xFFFF
if (
info.flag_bits & 0x1
or info.compress_type not in {zipfile.ZIP_STORED, zipfile.ZIP_DEFLATED}
or stat.S_ISLNK(mode)
or (directory and info.file_size != 0)
or info.file_size < 0
):
raise InstallerError("archive_invalid")
declared += info.file_size
if declared > MAX_EXPANDED_BYTES:
raise InstallerError("archive_invalid")
for depth in range(1, len(parts)):
directories.add("/".join(parts[:depth]).casefold())
if directory:
directories.add(key.casefold())
else:
files.add(key.casefold())
admitted[key] = info
if declared != manifest.expanded_bytes or files & directories:
raise InstallerError("archive_invalid")
retained: dict[str, zipfile.ZipInfo] = {}
for member in manifest.retained:
key = manifest.top_directory + member.archive_name
found = admitted.get(key)
if found is None or found.is_dir() or found.file_size != member.size:
raise InstallerError("archive_invalid")
retained[member.archive_name] = found
return retained
# --------------------------------------------------------------------------------------------
# Owned file writing
def _os_failure(exc: OSError) -> InstallerError:
winerror = getattr(exc, "winerror", None)
if winerror in {39, 112} or exc.errno == 28:
return InstallerError("insufficient_space")
if winerror in {32, 33}:
return InstallerError("runtime_busy")
if winerror == 5 or exc.errno in {1, 13}:
return InstallerError("permission_denied")
return InstallerError("write_failed")
def _rename_failure(exc: OSError) -> InstallerError:
# A directory rename that Windows refuses with access-denied or a sharing violation almost
# always means a file inside is open -- a running tool -- not a permission problem the user
# could fix, so it is reported as busy.
if getattr(exc, "winerror", None) in {5, 32, 33}:
return InstallerError("runtime_busy")
return _os_failure(exc)
def _lstat_or_none(path: Path) -> os.stat_result | None:
try:
return path.lstat()
except FileNotFoundError:
return None
except OSError as exc:
raise InstallerError("private_root_invalid") from exc
class _NewFileWriter:
"""One exclusively created regular file, streamed, hashed and bounded while written."""
def __init__(self, path: Path, *, maximum_bytes: int, overflow_code: str) -> None:
self.total = 0
self._path = path
self._maximum = maximum_bytes
self._overflow = overflow_code
self._digest = hashlib.sha256()
self._descriptor: int | None = None
self._created: tuple[int, int] | None = None
try:
parent = validate_directory(path.parent)
except UnsafePathError as exc:
raise InstallerError("private_root_invalid") from exc
if parent != path.parent or path.name in {"", ".", ".."}:
raise InstallerError("private_root_invalid")
try:
self._descriptor = (
_windows_open_new_file(path)
if os.name == "nt"
else os.open(
path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_BINARY", 0), 0o600
)
)
opened = os.fstat(self._descriptor)
self._created = (opened.st_dev, opened.st_ino)
current = path.lstat()
except OSError as exc:
self.discard()
raise _os_failure(exc) from exc
if (
not stat.S_ISREG(opened.st_mode)
or opened.st_nlink != 1
or _is_link_or_reparse(path, current)
or (current.st_dev, current.st_ino) != self._created
):
self.discard()
raise InstallerError("private_root_invalid")
def write(self, chunk: bytes) -> None:
if self._descriptor is None:
raise InstallerError("write_failed")
self.total += len(chunk)
if self.total > self._maximum:
raise InstallerError(self._overflow)
self._digest.update(chunk)
view = memoryview(chunk)
while view:
try:
written = os.write(self._descriptor, view)
except OSError as exc:
raise _os_failure(exc) from exc
if written <= 0:
raise InstallerError("write_failed")
view = view[written:]
def finish(self) -> tuple[FileIdentity, str]:
descriptor = self._descriptor
if descriptor is None:
raise InstallerError("write_failed")
try:
os.fsync(descriptor)
opened = os.fstat(descriptor)
current = self._path.lstat()
except OSError as exc:
raise _os_failure(exc) from exc
finally:
self._descriptor = None
os.close(descriptor)
if (
opened.st_nlink != 1
or _is_link_or_reparse(self._path, current)
or _identity(current) != _identity(opened)
):
raise InstallerError("private_root_invalid")
return _identity(opened), self._digest.hexdigest()
def discard(self) -> None:
descriptor = self._descriptor
self._descriptor = None
if descriptor is not None:
try:
os.close(descriptor)
except OSError:
pass
if self._created is None:
return
try:
current = self._path.lstat()
except OSError:
return
if (current.st_dev, current.st_ino) != self._created:
return
try:
_safe_unlink(self._path, missing_ok=True, maximum_links=1)
except ArtifactStoreError:
pass
def _mkdir_owned(path: Path) -> None:
try:
path.mkdir()
metadata = path.lstat()
except OSError as exc:
raise _os_failure(exc) from exc
if _is_link_or_reparse(path, metadata) or not stat.S_ISDIR(metadata.st_mode):
raise InstallerError("private_root_invalid")
def cleanup_job_directory(
job_directory: Path, manifest: ManagedRuntimeManifest, *, include_retired: bool
) -> None:
"""Remove only the files an installer job names, then the directories it created.
IMPORTANT: this is deliberately not a recursive delete. Unknown content is left where it is,
and a `retired/` tree is removed only by the job that published its replacement: a job whose
restore failed still holds the previous runtime there, and a later sweep must not erase it.
"""
trees = [TREE_DIRECTORY, RETIRED_DIRECTORY] if include_retired else [TREE_DIRECTORY]
names = [*(member.published_name for member in manifest.retained), SOURCE_NOTICE_FILENAME]
files = [job_directory / ARCHIVE_FILENAME]
for tree in trees:
files.extend(job_directory / tree / name for name in names)
for path in files:
try:
_safe_unlink(path, missing_ok=True, maximum_links=1)
except ArtifactStoreError:
pass
directories: list[Path] = []
for tree in trees:
nested = sorted(
{Path(name).parent for name in names if Path(name).parent != Path(".")},
key=lambda value: len(value.parts),
reverse=True,
)
directories.extend(job_directory / tree / directory for directory in nested)
directories.append(job_directory / tree)
directories.append(job_directory)
for directory in directories:
try:
directory.rmdir()
except OSError:
pass
# --------------------------------------------------------------------------------------------
# Install lock
def _acquire_install_lock(staging: Path) -> int:
import msvcrt
locking = getattr(msvcrt, "locking") # noqa: B009
path = staging / LOCK_FILENAME
descriptor: int | None = None
try:
with _validated_directories(staging):
# OSError must be translated inside the pinned block: the context manager would
# otherwise re-code a sharing violation as an unsafe store entry.
try:
try:
descriptor = _windows_open_new_file(path)
except OSError:
if _lstat_or_none(path) is None:
raise
descriptor = _windows_open_existing_file(path)
opened = os.fstat(descriptor)
current = path.lstat()
except OSError as exc:
raise InstallerError("setup_busy") from exc
if (
not stat.S_ISREG(opened.st_mode)
or opened.st_nlink != 1
or _is_link_or_reparse(path, current)
or (current.st_dev, current.st_ino) != (opened.st_dev, opened.st_ino)
):
raise InstallerError("private_root_invalid")
except BaseException as exc:
if descriptor is not None:
os.close(descriptor)
if isinstance(exc, ArtifactStoreError):
raise InstallerError("private_root_invalid") from exc
raise
if descriptor is None:
raise InstallerError("setup_busy")
try:
# CRITICAL: a byte-range lock, not a marker file. The OS releases it when the owning
# process dies, so a crashed install can never leave every later install refused, and
# a second ComfyUI process sharing this user directory cannot publish concurrently.
locking(descriptor, getattr(msvcrt, "LK_NBLCK"), 1) # noqa: B009
except OSError as exc:
os.close(descriptor)
raise InstallerError("setup_busy") from exc
return descriptor
def _release_install_lock(descriptor: int) -> None:
import msvcrt
try:
os.lseek(descriptor, 0, os.SEEK_SET)
getattr(msvcrt, "locking")(descriptor, getattr(msvcrt, "LK_UNLCK"), 1) # noqa: B009
except OSError:
pass
finally:
os.close(descriptor)
# --------------------------------------------------------------------------------------------
# Parked runtime recovery
def _plain_entry(path: Path, *, directory: bool) -> bool:
try:
metadata = path.lstat()
except OSError:
return False
if _is_link_or_reparse(path, metadata):
return False
return stat.S_ISDIR(metadata.st_mode) if directory else stat.S_ISREG(metadata.st_mode)
def _holds_named_member(retired: Path, manifest: ManagedRuntimeManifest) -> bool:
names = [*(member.published_name for member in manifest.retained), SOURCE_NOTICE_FILENAME]
for name in names:
parts = Path(name).parts
current = retired
# Every intermediate component must itself be a plain directory: a junctioned `bin`
# would otherwise report a member that lives outside the private root.
for part in parts[:-1]:
current = current / part
if not _plain_entry(current, directory=True):
break
else:
if _plain_entry(current / parts[-1], directory=False):
return True
return False
def parked_runtime_trees(
layout: MediaRuntimePrivateLayout, manifest: ManagedRuntimeManifest
) -> tuple[Path, ...]:
"""Job directories whose `retired/` tree still holds a named runtime member. Read-only.
A tree is parked when a publication could not restore it or its cleanup could not remove it.
The scan is bounded by `MAX_STAGING_ENTRIES`, creates nothing and never follows a link or
junction; an unreadable staging directory reports nothing rather than guessing.
"""
staging = layout.media_runtime / STAGING_DIRECTORY
if not _plain_entry(staging, directory=True):
return ()
parked: list[Path] = []
try:
with os.scandir(staging) as entries:
for index, entry in enumerate(entries):
if index >= MAX_STAGING_ENTRIES:
break
if JOB_TOKEN.fullmatch(entry.name) is None:
continue
job = Path(entry.path)
retired = job / RETIRED_DIRECTORY
if (
_plain_entry(job, directory=True)
and _plain_entry(retired, directory=True)
and _holds_named_member(retired, manifest)
):
parked.append(job)
except OSError:
return ()
return tuple(sorted(parked))
def reclaim_parked_runtimes(
layout: MediaRuntimePrivateLayout,
manifest: ManagedRuntimeManifest,
*,
pin: PinFunction = pin_exact_executable,
) -> int:
"""Remove parked trees' named members after verifying the published replacement.
Returns how many parked job directories no longer hold a named member.
SECURITY/CRITICAL: this runs only on an explicit user action, only under the install lock,
and only once the published pair passes the same exact pins a spawn uses. A parked tree can
be the only copy of the runtime (a publication whose restore failed); deleting it without a
verified replacement leaves no runtime at all. Deletion keeps `cleanup_job_directory`'s
named-member, no-recursion and link-refusal rules; nothing here deletes automatically.
"""
if os.name != "nt":
raise InstallerError("unsupported_platform")
staging = layout.media_runtime / STAGING_DIRECTORY
if _lstat_or_none(staging) is None:
return 0
if not _plain_entry(staging, directory=True):
raise InstallerError("private_root_invalid")
lock = _acquire_install_lock(staging)
try:
parked = parked_runtime_trees(layout, manifest)
if not parked:
return 0
target = layout.runtime_root / manifest.profile_component
if not _plain_entry(target, directory=True) or not _plain_entry(
layout.managed_bin, directory=True
):
raise InstallerError("reclaim_unsafe")
for member in manifest.retained:
if not member.executable:
continue
try:
with pin(layout.managed_bin / Path(member.published_name).name, member.sha256):
pass
except ExecutableAdmissionError as exc:
raise InstallerError("reclaim_unsafe") from exc
for job in parked:
cleanup_job_directory(job, manifest, include_retired=True)
remaining = set(parked_runtime_trees(layout, manifest))
return sum(1 for job in parked if job not in remaining)
finally:
_release_install_lock(lock)
# --------------------------------------------------------------------------------------------
# Installer
ProgressCallback = Callable[[str, int, int], None]
PinFunction = Callable[..., Any]
class ManagedRuntimeInstaller:
"""One installation attempt. `run` either publishes the tree or raises `InstallerError`."""
def __init__(
self,
layout: MediaRuntimePrivateLayout,
*,
manifest: ManagedRuntimeManifest,
downloader: DownloadPort,
job_token: str,
cancelled: threading.Event,
progress: ProgressCallback,
disk_usage: Callable[[str], Any] = shutil.disk_usage,
pin: PinFunction = pin_exact_executable,
) -> None:
if type(job_token) is not str or JOB_TOKEN.fullmatch(job_token) is None:
raise ValueError("job_token")
self._layout = layout
self._manifest = manifest
self._downloader = downloader
self._token = job_token
self._cancelled = cancelled
self._progress = progress
self._disk_usage = disk_usage
self._pin = pin
def __repr__(self) -> str:
return "<ManagedRuntimeInstaller>"
@property
def staging_root(self) -> Path:
return self._layout.media_runtime / STAGING_DIRECTORY
def run(self) -> None:
if os.name != "nt":
raise InstallerError("unsupported_platform")
try:
staging = ensure_directory(self.staging_root)
except UnsafePathError as exc:
raise InstallerError("private_root_invalid") from exc
lock = self._acquire_lock(staging)
try:
self._sweep(staging)
job_directory = staging / self._token
try:
with self._validated(staging):
_mkdir_owned(job_directory)
except ArtifactStoreError as exc:
raise InstallerError("private_root_invalid") from exc
published = False
try:
self._check_space()
identity = self._download(job_directory)
self._extract(job_directory, identity)
self._verify_tree(job_directory / TREE_DIRECTORY)
self._publish(job_directory)
published = True
finally:
cleanup_job_directory(job_directory, self._manifest, include_retired=published)
finally:
self._release_lock(lock)
# -- steps -----------------------------------------------------------------------------
@staticmethod
def _validated(*directories: Path) -> Any:
return _validated_directories(*directories)
def _check_cancel(self) -> None:
if self._cancelled.is_set():
raise InstallerError("cancelled")
def _acquire_lock(self, staging: Path) -> int:
return _acquire_install_lock(staging)
def _release_lock(self, descriptor: int) -> None:
_release_install_lock(descriptor)
def _sweep(self, staging: Path) -> None:
"""Clean earlier jobs' named leftovers; bounded, and only under the install lock."""
candidates: list[Path] = []
try:
with os.scandir(staging) as entries:
for index, entry in enumerate(entries):
if index >= MAX_STAGING_ENTRIES or len(candidates) >= MAX_SWEPT_JOBS:
break
if entry.name == self._token or JOB_TOKEN.fullmatch(entry.name) is None:
continue
path = Path(entry.path)
metadata = path.lstat()
if _is_link_or_reparse(path, metadata) or not stat.S_ISDIR(metadata.st_mode):
continue
candidates.append(path)
except OSError as exc:
raise InstallerError("private_root_invalid") from exc
for candidate in candidates:
cleanup_job_directory(candidate, self._manifest, include_retired=False)
def _check_space(self) -> None:
required = self._manifest.archive_bytes + self._manifest.retained_bytes + SPACE_MARGIN_BYTES
try:
usage = self._disk_usage(str(self._layout.media_runtime))
except OSError as exc:
raise InstallerError("private_root_invalid") from exc
if int(getattr(usage, "free", 0)) < required:
raise InstallerError("insufficient_space")
def _download(self, job_directory: Path) -> FileIdentity:
manifest = self._manifest
self._check_cancel()
self._progress("downloading", 0, manifest.archive_bytes)
writer = _NewFileWriter(
job_directory / ARCHIVE_FILENAME,
maximum_bytes=manifest.archive_bytes,
overflow_code="size_mismatch",
)
try:
self._downloader.download(
manifest.source_url,
expected_bytes=manifest.archive_bytes,
sink=writer.write,
cancelled=self._cancelled,
progress=lambda done: self._progress("downloading", done, manifest.archive_bytes),
)
identity, digest = writer.finish()
except DownloadError as exc:
writer.discard()
raise InstallerError(exc.code) from exc
except BaseException:
writer.discard()
raise
if digest != manifest.archive_sha256:
raise InstallerError("digest_mismatch")
return identity
def _extract(self, job_directory: Path, archive_identity: FileIdentity) -> None:
manifest = self._manifest
self._check_cancel()
self._progress("extracting", 0, manifest.retained_bytes)
archive = job_directory / ARCHIVE_FILENAME
tree = job_directory / TREE_DIRECTORY
try:
with _validated_directories(job_directory):
try:
descriptor = windows_open_read_pin(archive)
except OSError as exc:
raise InstallerError("archive_invalid") from exc
with os.fdopen(descriptor, "rb") as stream:
opened = os.fstat(stream.fileno())
if opened.st_nlink != 1 or _identity(opened) != archive_identity:
raise InstallerError("archive_invalid")
with zipfile.ZipFile(stream) as archive_file:
members = validate_archive_members(archive_file.infolist(), manifest)
_mkdir_owned(tree)
for directory in sorted(
{
Path(member.published_name).parent
for member in manifest.retained
if Path(member.published_name).parent != Path(".")
},
key=lambda value: len(value.parts),
):
_mkdir_owned(tree / directory)
done = 0
for member in manifest.retained:
self._extract_member(
archive_file, members[member.archive_name], tree, member, done
)
done += member.size
self._write_source_notice(tree)
except (zipfile.BadZipFile, zlib.error, EOFError, NotImplementedError) as exc:
raise InstallerError("archive_invalid") from exc
except ArtifactStoreError as exc:
raise InstallerError("private_root_invalid") from exc
except OSError as exc:
raise _os_failure(exc) from exc
def _extract_member(
self,
archive_file: zipfile.ZipFile,
info: zipfile.ZipInfo,
tree: Path,
member: RetainedMember,
done_before: int,
) -> None:
writer = _NewFileWriter(
tree / member.published_name, maximum_bytes=member.size, overflow_code="archive_invalid"
)
try:
with archive_file.open(info) as source:
while True:
self._check_cancel()
chunk = source.read(min(CHUNK_BYTES, member.size + 1 - writer.total))
if not chunk:
break
writer.write(chunk)
self._progress(
"extracting", done_before + writer.total, self._manifest.retained_bytes
)
_identity_unused, digest = writer.finish()
except BaseException:
writer.discard()
raise
if writer.total != member.size or digest != member.sha256:
raise InstallerError("archive_invalid")
def _write_source_notice(self, tree: Path) -> None:
manifest = self._manifest
payload = json.dumps(
{
"schema": SOURCE_NOTICE_SCHEMA,
"profile": manifest.profile_component,
"source_label": manifest.source_label,
"release_page": manifest.release_page_url,
"archive_sha256": manifest.archive_sha256,
"license": manifest.license_name,
"license_file": "LICENSE.txt",
"source_notice_file": "README.txt",
},
indent=2,
sort_keys=True,
).encode("utf-8")
try:
_write_new_file(tree / SOURCE_NOTICE_FILENAME, payload + b"\n")
except ArtifactStoreError as exc:
raise InstallerError("write_failed") from exc
def _admitted_pair(self, bin_directory: Path) -> bool:
for member in self._manifest.retained:
if not member.executable:
continue
try:
with self._pin(bin_directory / Path(member.published_name).name, member.sha256):
pass
except ExecutableAdmissionError:
return False
return True
def _verify_tree(self, tree: Path) -> None:
self._check_cancel()
self._progress("verifying", 0, 0)
for member in self._manifest.retained:
if not member.executable:
continue
try:
with self._pin(tree / member.published_name, member.sha256):
pass
except ExecutableAdmissionError as exc:
raise InstallerError("archive_invalid") from exc
def _publish(self, job_directory: Path) -> None:
self._check_cancel()
self._progress("publishing", 0, 0)
tree = job_directory / TREE_DIRECTORY
retired = job_directory / RETIRED_DIRECTORY
target = self._layout.runtime_root / self._manifest.profile_component
try:
runtime_root = ensure_directory(self._layout.runtime_root)
except UnsafePathError as exc:
raise InstallerError("private_root_invalid") from exc
try:
with _validated_directories(job_directory, runtime_root):
existing = _lstat_or_none(target)
if existing is not None:
if _is_link_or_reparse(target, existing) or not stat.S_ISDIR(existing.st_mode):
raise InstallerError("private_root_invalid")
if self._admitted_pair(target / "bin"):
# Someone already placed the exact pair; keep it and discard ours.
return
try:
os.rename(target, retired)
except OSError as exc:
raise _rename_failure(exc) from exc
try:
# CRITICAL: publication is one directory rename inside pinned parents. A copy,
# or per-file moves, would expose a half-populated profile that the resolver
# can pick up between steps.
os.rename(tree, target)
except OSError as exc:
if existing is not None:
try:
# CRITICAL: restore the retired tree before reporting. Returning with
# it still in staging would leave no runtime directory at all, and the
# next sweep is not allowed to bring it back.
os.rename(retired, target)
except OSError as restore_exc:
raise InstallerError("publication_failed") from restore_exc
raise _rename_failure(exc) from exc
except ArtifactStoreError as exc:
raise InstallerError("private_root_invalid") from exc
__all__ = [
"LICENSE_NAME",
"RELEASE_PAGE_URL",
"SOURCE_LABEL",
"SOURCE_URL",
"InstallerError",
"ManagedRuntimeInstaller",
"ManagedRuntimeManifest",
"RetainedMember",
"cleanup_job_directory",
"managed_runtime_manifest",
"parked_runtime_trees",
"reclaim_parked_runtimes",
"validate_archive_members",
]
@@ -0,0 +1,289 @@
"""Explicit, bounded recovery of earlier media setup leftovers. Never acquires tools."""
from __future__ import annotations
import os
import re
import stat
from collections.abc import Callable
from contextlib import ExitStack
from pathlib import Path
from typing import Any
from .executable_admission import ExecutableAdmissionError, pin_exact_executable
from .media_runtime_pin import MediaRuntimePin
from .media_runtime_resolution import MediaRuntimePrivateLayout
from .segment_artifact_store import (
ArtifactStoreError,
_is_link_or_reparse,
_safe_unlink,
_validated_directories,
_windows_open_existing_file,
_windows_open_new_file,
)
MAX_STAGING_ENTRIES = 64
MAX_SWEPT_JOBS = 16
STAGING_DIRECTORY = "staging"
LOCK_FILENAME = "install.lock"
ARCHIVE_FILENAME = "archive.zip.part"
TREE_DIRECTORY = "tree"
RETIRED_DIRECTORY = "retired"
SOURCE_NOTICE_FILENAME = "source.json"
JOB_TOKEN = re.compile(r"[0-9a-f]{32}")
PinFunction = Callable[..., Any]
class RecoveryError(RuntimeError):
CODES = frozenset(
{"private_root_invalid", "reclaim_unsafe", "setup_busy", "unsupported_platform"}
)
def __init__(self, code: str) -> None:
if code not in self.CODES:
raise ValueError("unknown recovery error code")
self.code = code
super().__init__(code)
def _lstat_or_none(path: Path) -> os.stat_result | None:
try:
return path.lstat()
except FileNotFoundError:
return None
except OSError as exc:
raise RecoveryError("private_root_invalid") from exc
def cleanup_job_directory(
job_directory: Path, manifest: MediaRuntimePin, *, include_retired: bool
) -> None:
"""Remove only the files an installer job names, then the directories it created.
IMPORTANT: this is deliberately not a recursive delete. Unknown content is left where it is,
and a `retired/` tree is removed only by the job that published its replacement: a job whose
restore failed still holds the previous runtime there, and a later sweep must not erase it.
"""
trees = [TREE_DIRECTORY, RETIRED_DIRECTORY] if include_retired else [TREE_DIRECTORY]
names = [*(member.published_name for member in manifest.retained), SOURCE_NOTICE_FILENAME]
files = [job_directory / ARCHIVE_FILENAME]
for tree in trees:
files.extend(job_directory / tree / name for name in names)
for path in files:
try:
_safe_unlink(path, missing_ok=True, maximum_links=1)
except ArtifactStoreError:
pass
directories: list[Path] = []
for tree in trees:
nested = sorted(
{Path(name).parent for name in names if Path(name).parent != Path(".")},
key=lambda value: len(value.parts),
reverse=True,
)
directories.extend(job_directory / tree / directory for directory in nested)
directories.append(job_directory / tree)
directories.append(job_directory)
for directory in directories:
if not _plain_entry(directory, directory=True):
continue
try:
directory.rmdir()
except OSError:
pass
def _acquire_install_lock(staging: Path) -> int:
import msvcrt
locking = getattr(msvcrt, "locking") # noqa: B009
path = staging / LOCK_FILENAME
descriptor: int | None = None
try:
with _validated_directories(staging):
# OSError must be translated inside the pinned block: the context manager would
# otherwise re-code a sharing violation as an unsafe store entry.
try:
try:
descriptor = _windows_open_new_file(path)
except OSError:
if _lstat_or_none(path) is None:
raise
descriptor = _windows_open_existing_file(path)
opened = os.fstat(descriptor)
current = path.lstat()
except OSError as exc:
raise RecoveryError("setup_busy") from exc
if (
not stat.S_ISREG(opened.st_mode)
or opened.st_nlink != 1
or _is_link_or_reparse(path, current)
or (current.st_dev, current.st_ino) != (opened.st_dev, opened.st_ino)
):
raise RecoveryError("private_root_invalid")
except BaseException as exc:
if descriptor is not None:
os.close(descriptor)
if isinstance(exc, ArtifactStoreError):
raise RecoveryError("private_root_invalid") from exc
raise
if descriptor is None:
raise RecoveryError("setup_busy")
try:
# CRITICAL: a byte-range lock, not a marker file. The OS releases it when the owning
# process dies, so a crashed install can never leave every later install refused, and
# a second ComfyUI process sharing this user directory cannot publish concurrently.
locking(descriptor, getattr(msvcrt, "LK_NBLCK"), 1) # noqa: B009
except OSError as exc:
os.close(descriptor)
raise RecoveryError("setup_busy") from exc
return descriptor
def _release_install_lock(descriptor: int) -> None:
import msvcrt
try:
os.lseek(descriptor, 0, os.SEEK_SET)
getattr(msvcrt, "locking")(descriptor, getattr(msvcrt, "LK_UNLCK"), 1) # noqa: B009
except OSError:
pass
finally:
os.close(descriptor)
def _plain_entry(path: Path, *, directory: bool) -> bool:
try:
metadata = path.lstat()
except OSError:
return False
if _is_link_or_reparse(path, metadata):
return False
return stat.S_ISDIR(metadata.st_mode) if directory else stat.S_ISREG(metadata.st_mode)
def _holds_named_member(retired: Path, manifest: MediaRuntimePin) -> bool:
names = [*(member.published_name for member in manifest.retained), SOURCE_NOTICE_FILENAME]
for name in names:
parts = Path(name).parts
current = retired
# Every intermediate component must itself be a plain directory: a junctioned `bin`
# would otherwise report a member that lives outside the private root.
for part in parts[:-1]:
current = current / part
if not _plain_entry(current, directory=True):
break
else:
if _plain_entry(current / parts[-1], directory=False):
return True
return False
def parked_runtime_trees(
layout: MediaRuntimePrivateLayout, manifest: MediaRuntimePin
) -> tuple[Path, ...]:
"""Job directories whose `retired/` tree still holds a named runtime member. Read-only.
A tree is parked when a publication could not restore it or its cleanup could not remove it.
The scan is bounded by `MAX_STAGING_ENTRIES`, creates nothing and never follows a link or
junction; an unreadable staging directory reports nothing rather than guessing.
"""
staging = layout.media_runtime / STAGING_DIRECTORY
if not _plain_entry(staging, directory=True):
return ()
parked: list[Path] = []
try:
with os.scandir(staging) as entries:
for index, entry in enumerate(entries):
if index >= MAX_STAGING_ENTRIES:
break
if JOB_TOKEN.fullmatch(entry.name) is None:
continue
job = Path(entry.path)
retired = job / RETIRED_DIRECTORY
if (
_plain_entry(job, directory=True)
and _plain_entry(retired, directory=True)
and _holds_named_member(retired, manifest)
):
parked.append(job)
except OSError:
return ()
return tuple(sorted(parked))
def abandoned_setup_jobs(
layout: MediaRuntimePrivateLayout, manifest: MediaRuntimePin
) -> tuple[Path, ...]:
"""Read-only scan of named temporary files; parked copies remain a separate recovery state."""
staging = layout.media_runtime / STAGING_DIRECTORY
if not _plain_entry(staging, directory=True):
return ()
jobs: list[Path] = []
try:
with os.scandir(staging) as entries:
for index, entry in enumerate(entries):
if index >= MAX_STAGING_ENTRIES:
break
job = Path(entry.path)
if JOB_TOKEN.fullmatch(entry.name) is None or not _plain_entry(job, directory=True):
continue
if _plain_entry(job / ARCHIVE_FILENAME, directory=False) or (
_plain_entry(job / TREE_DIRECTORY, directory=True)
and _holds_named_member(job / TREE_DIRECTORY, manifest)
):
jobs.append(job)
except OSError:
return ()
return tuple(sorted(jobs))
def reclaim_parked_runtimes(
layout: MediaRuntimePrivateLayout,
manifest: MediaRuntimePin,
*,
pin: PinFunction = pin_exact_executable,
) -> int:
"""Reclaim only known names; old parked tools need a verified managed replacement."""
if os.name != "nt":
raise RecoveryError("unsupported_platform")
staging = layout.media_runtime / STAGING_DIRECTORY
if _lstat_or_none(staging) is None:
return 0
if not _plain_entry(staging, directory=True):
raise RecoveryError("private_root_invalid")
lock = _acquire_install_lock(staging)
try:
parked = parked_runtime_trees(layout, manifest)
abandoned = abandoned_setup_jobs(layout, manifest)
# CRITICAL: share the earlier setup lock and hold both replacement pins through deletion.
# A parked tree may be the only usable copy; an old process may still own an abandoned job.
with ExitStack() as pins:
if parked:
target = layout.runtime_root / manifest.profile_component
if not _plain_entry(target, directory=True) or not _plain_entry(
layout.managed_bin, directory=True
):
raise RecoveryError("reclaim_unsafe")
for member in manifest.retained:
if member.executable:
try:
pins.enter_context(
pin(
layout.managed_bin / Path(member.published_name).name,
member.sha256,
)
)
except ExecutableAdmissionError as exc:
raise RecoveryError("reclaim_unsafe") from exc
jobs = sorted(set(parked) | set(abandoned))[:MAX_SWEPT_JOBS]
for job in jobs:
cleanup_job_directory(job, manifest, include_retired=job in parked)
remaining = set(parked_runtime_trees(layout, manifest)) | set(
abandoned_setup_jobs(layout, manifest)
)
return sum(job not in remaining for job in jobs)
finally:
_release_install_lock(lock)
@@ -0,0 +1,52 @@
"""Data-only display and recovery pins for the supported user-provided media tools."""
from __future__ import annotations
from dataclasses import dataclass
from ..core.av_reconstruction import qualified_ffmpeg_capability
from .media_runtime_resolution import MANAGED_PROFILE_COMPONENT
RELEASE_TAG = "2026-02-26-git-6695528af6"
RELEASE_PAGE_URL = f"https://github.com/GyanD/codexffmpeg/releases/tag/{RELEASE_TAG}"
SOURCE_LABEL = "Gyan.dev FFmpeg full build"
LICENSE_NAME = "GPL-3.0-or-later"
@dataclass(frozen=True, slots=True)
class RuntimeMember:
published_name: str
sha256: str
executable: bool
@dataclass(frozen=True, slots=True)
class MediaRuntimePin:
profile_component: str
release_page_url: str
source_label: str
license_name: str
archive_filename: str
archive_bytes: int
archive_sha256: str
retained: tuple[RuntimeMember, ...]
def media_runtime_pin() -> MediaRuntimePin:
capability = qualified_ffmpeg_capability()
return MediaRuntimePin(
MANAGED_PROFILE_COMPONENT,
RELEASE_PAGE_URL,
SOURCE_LABEL,
LICENSE_NAME,
f"ffmpeg-{RELEASE_TAG}-full_build.zip",
246_558_061,
"ad18ecdedfca6d51c28cf12f2c96287c" # pragma: allowlist secret
"e1150686578b75bff2efcd06ff34bb30", # pragma: allowlist secret
(
RuntimeMember("bin/ffmpeg.exe", capability.ffmpeg_sha256.casefold(), True),
RuntimeMember("bin/ffprobe.exe", capability.ffprobe_sha256.casefold(), True),
RuntimeMember("LICENSE.txt", "", False),
RuntimeMember("README.txt", "", False),
),
)
File diff suppressed because one or more lines are too long
@@ -5,30 +5,30 @@
},
"bundle": {
"path": "comfyui_h3_context/web/h3-context-sidebar.js",
"sha256": "sha256:3b1731ddb750eefeed6ab16b1f9323f12081d7f15a824a8c7a3bd1600f90b770",
"size": 1917831
"sha256": "sha256:fefc67f48395bb9e64ee6cf8c4626e40259f9b2f433a411038b6ed4e238b83c7",
"size": 1909494
},
"embedded_identity": {
"builder_id": "scripts/frontend_build_report.py",
"resolved_dependencies_sha256": "sha256:e8c5539b4443c29794b9d023d1a86e0f58b56d39f6237d1075704827413ed894",
"resolved_dependencies_sha256": "sha256:33a348fa45d49b67b366e4dcd3cb7fab5a76c1ad430397d843d71aaa4991e535",
"schema": "h3-context-build-identity/1",
"source_commit": "196a4ff382547054e79c900af7499c877a4bec57",
"source_inputs_sha256": "sha256:330bd587ee20fa3cb75346d455dc2521068f9663bfb8ed1541425f0a130e36c2",
"source_tree": "853b024f65dcc508736e8272e747cc18d3ebad86"
"source_commit": "c1fe4093d3d9b2befb76329f2fd77d2fdf4e55e9",
"source_inputs_sha256": "sha256:9061ac68afb36d70cc107e7faf769e36697f44761dfc86f7c32aaf99ce0ddcaf",
"source_tree": "0b67dc80be61da56be0bead96e4416e6a297b253"
},
"external_parameters": {
"source_commit": "196a4ff382547054e79c900af7499c877a4bec57",
"source_inputs_sha256": "sha256:330bd587ee20fa3cb75346d455dc2521068f9663bfb8ed1541425f0a130e36c2",
"source_tree": "853b024f65dcc508736e8272e747cc18d3ebad86"
"source_commit": "c1fe4093d3d9b2befb76329f2fd77d2fdf4e55e9",
"source_inputs_sha256": "sha256:9061ac68afb36d70cc107e7faf769e36697f44761dfc86f7c32aaf99ce0ddcaf",
"source_tree": "0b67dc80be61da56be0bead96e4416e6a297b253"
},
"invocation": {
"finished_on": "2026-10-12T04:04:08Z",
"id": "sha256:d173858c211ed1f890f6a9f0dfd1283de4610db0c3244a2c42924a10495b4776",
"started_on": "2026-10-12T04:04:08Z"
"finished_on": "2026-10-13T12:42:44Z",
"id": "sha256:1886793e2acd0eb2f6e0b3f56b2464e808377b41ca5e7c990ade86e1112b7863",
"started_on": "2026-10-13T12:42:44Z"
},
"resolved_dependencies": [
{
"digest": "sha256:92ba0a9a5f29a5c3899eb98141b6c0005d227e7e1d6c04f294c2a82d8f0a6505",
"digest": "sha256:94be69f36c4d65a92277c49327bf2c56010d8c3b0087940515f7836c331b2c7e",
"uri": "contract:h3-context-contract-inventory/1"
},
{
@@ -120,6 +120,7 @@
"frontend/tests/authoringMediaSourceLease.test.ts",
"frontend/tests/authoringVideoSourceOwner.test.ts",
"frontend/tests/e2e/journeys/host/mediaSourceLeases.spec.ts",
"frontend/tests/e2e/journeys/host/productionAuthoringImportHost.spec.ts",
"frontend/tests/e2e/journeys/mediaSourceLeases.spec.ts",
"frontend/tests/nleAssetPreparation.test.tsx",
"frontend/tests/nleMediaBin.test.tsx",
@@ -7518,6 +7519,7 @@
"frontend/tests/authoringMediaLeaseCodec.test.ts",
"frontend/tests/authoringMediaPreparation.test.ts",
"frontend/tests/authoringMediaSourceLease.test.ts",
"frontend/tests/e2e/journeys/host/productionAuthoringImportHost.spec.ts",
"tests/test_m25_48_asset_scoped_leases.py",
"tests/test_m25_75_asset_preparation.py",
"tests/test_m25_75_first_use_counts.py",
@@ -7604,8 +7606,6 @@
"comfyui_h3_context/adapters/media_runtime_discovery_worker.py",
"frontend/src/contracts/authoringMediaLeaseCodec.ts",
"frontend/tests/e2e/journeys/host/mediaSourceLeases.spec.ts",
"tests/test_m25_31_media_runtime_setup.py",
"tests/test_m25_33_media_setup_entry.py",
"tests/test_m25_74_derivative_rework_counts.py",
"tests/test_m25_74_lease_stream_threads.py",
"tests/test_m25_75_asset_preparation.py",
@@ -9473,30 +9473,6 @@
"reachability": "reachable",
"reachability_source": "host_input"
},
{
"authority_paths": [
"comfyui_h3_context/adapters/media_runtime_installer.py"
],
"blockers": [
"unknown_consumer"
],
"boundary": "untrusted_input",
"compatibility": "unknown",
"consumers": [],
"contract_id": "h3.context.managed_media_runtime_source.v1",
"dialect": "not_applicable",
"disposition": "NEED_EVIDENCE",
"evidence": "no reader resolved by the five discovery rules; absence is not disuse",
"fingerprint_domain": "h3.context.managed_media_runtime_source.v1",
"kind": "python_wire",
"persistence": "transient",
"producers": [
"comfyui_h3_context/adapters/media_runtime_installer.py"
],
"publication": "packaged",
"reachability": "unsupported",
"reachability_source": "none"
},
{
"authority_paths": [
"comfyui_h3_context/core/managed_sequence.py"
@@ -10135,8 +10111,6 @@
"comfyui_h3_context/adapters/comfyui_authoring_media_leases.py",
"comfyui_h3_context/adapters/comfyui_media_runtime_setup.py",
"comfyui_h3_context/core/authoring_media.py",
"tests/test_m25_31_media_runtime_setup.py",
"tests/test_m25_33_media_setup_entry.py",
"tests/test_m25_74_derivative_rework_counts.py",
"tests/test_m25_74_lease_stream_threads.py",
"tests/test_m25_75_asset_preparation.py",
@@ -10195,8 +10169,7 @@
"compatibility": "old_readers_unaffected",
"consumers": [
"frontend/src/contracts/mediaRuntimeCodec.ts",
"frontend/tests/fixtures/media_runtime_wire_v3.json",
"tests/test_m25_31_media_runtime_setup.py"
"frontend/tests/fixtures/media_runtime_wire_v4.json"
],
"contract_id": "h3.context.media_runtime_resolution.v1",
"dialect": "not_applicable",
@@ -10212,34 +10185,6 @@
"reachability": "unsupported",
"reachability_source": "none"
},
{
"authority_paths": [
"comfyui_h3_context/adapters/comfyui_media_runtime_setup.py"
],
"blockers": [],
"boundary": "untrusted_input",
"compatibility": "old_readers_unaffected",
"consumers": [
"frontend/src/contracts/mediaRuntimeCodec.ts",
"frontend/tests/e2e/helpers/mediaRuntimeDouble.ts",
"frontend/tests/fixtures/media_runtime_wire_v3.json",
"tests/test_m25_31_media_runtime_setup.py",
"tests/test_m25_33_media_setup_entry.py"
],
"contract_id": "h3.context.media_runtime_setup_job.v1",
"dialect": "not_applicable",
"disposition": "KEEP",
"evidence": "untrusted_input boundary keeps a reader this repository cannot re-migrate",
"fingerprint_domain": "h3.context.media_runtime_setup_job.v1",
"kind": "python_wire",
"persistence": "transient",
"producers": [
"comfyui_h3_context/adapters/comfyui_media_runtime_setup.py"
],
"publication": "packaged",
"reachability": "unsupported",
"reachability_source": "none"
},
{
"authority_paths": [
"comfyui_h3_context/adapters/comfyui_media_runtime_setup.py"
@@ -10252,22 +10197,21 @@
"comfyui_h3_context/adapters/media_runtime_discovery_worker.py",
"comfyui_h3_context/core/authoring_media.py",
"frontend/src/contracts/mediaRuntimeCodec.ts",
"frontend/tests/fixtures/media_runtime_wire_v3.json",
"frontend/tests/e2e/helpers/mediaRuntimeDouble.ts",
"frontend/tests/mediaRuntimeClient.test.ts",
"tests/test_m25_31_media_runtime_setup.py",
"tests/test_m25_33_media_setup_entry.py",
"tests/test_m25_74_derivative_rework_counts.py",
"tests/test_m25_74_lease_stream_threads.py",
"tests/test_m25_75_asset_preparation.py",
"tests/test_m25_generated_media_derivatives.py",
"tests/test_m25_media_derivative_contract.py",
"tests/test_m25_media_derivative_routes.py"
"tests/test_m25_media_derivative_routes.py",
"tests/test_manual_media_tools.py"
],
"contract_id": "h3.context.media_runtime_setup_request.v1",
"contract_id": "h3.context.media_runtime_setup_request.v2",
"dialect": "not_applicable",
"disposition": "KEEP",
"evidence": "untrusted_input boundary keeps a reader this repository cannot re-migrate",
"fingerprint_domain": "h3.context.media_runtime_setup_request.v1",
"fingerprint_domain": "h3.context.media_runtime_setup_request.v2",
"kind": "python_wire",
"persistence": "transient",
"producers": [
@@ -10292,16 +10236,16 @@
"comfyui_h3_context/adapters/workspace_state_service.py",
"frontend/src/contracts/mediaRuntimeCodec.ts",
"frontend/tests/e2e/journeys/host/productionAuthoringImportHost.spec.ts",
"frontend/tests/fixtures/media_runtime_wire_v3.json",
"tests/test_m25_31_media_runtime_setup.py",
"frontend/tests/fixtures/media_runtime_wire_v4.json",
"frontend/tests/mediaRuntimeCodec.test.ts",
"tests/test_m25_32_media_runtime_activation.py",
"tests/test_m25_33_media_setup_entry.py"
"tests/test_manual_media_tools.py"
],
"contract_id": "h3.context.media_runtime_status.v3",
"contract_id": "h3.context.media_runtime_status.v4",
"dialect": "not_applicable",
"disposition": "KEEP",
"evidence": "untrusted_input boundary keeps a reader this repository cannot re-migrate",
"fingerprint_domain": "h3.context.media_runtime_status.v3",
"fingerprint_domain": "h3.context.media_runtime_status.v4",
"kind": "python_wire",
"persistence": "transient",
"producers": [
@@ -10405,6 +10349,7 @@
"frontend/tests/e2e/journeys/host/contentExtentHost.spec.ts",
"frontend/tests/e2e/journeys/host/m25_52EmbeddedAudioWaveform.spec.ts",
"frontend/tests/e2e/journeys/host/m25_53ReferenceFidelity.spec.ts",
"frontend/tests/e2e/journeys/host/productionAuthoringImportHost.spec.ts",
"frontend/tests/nleAuthoringAssetBin.test.tsx",
"frontend/tests/nleAuthoringAssetManifest.test.ts",
"frontend/tests/nleTitleInsertion.test.ts",
@@ -10464,9 +10409,8 @@
"frontend/tests/perceptionHostEntry.test.tsx",
"frontend/tests/perceptionHostSession.test.ts",
"frontend/tests/perceptionHostStatus.test.tsx",
"tests/test_m25_31_media_runtime_setup.py",
"tests/test_m25_32_media_runtime_activation.py",
"tests/test_m25_33_media_setup_entry.py",
"tests/test_manual_media_tools.py",
"tests/test_perception_host_status.py",
"tests/test_perception_settings_lifecycle.py"
],
@@ -11423,9 +11367,8 @@
"frontend/src/contracts/projectRecoveryCodec.ts",
"frontend/tests/fixtures/entryHostModules.ts",
"frontend/tests/projectRecovery.test.tsx",
"tests/test_m25_31_media_runtime_setup.py",
"tests/test_m25_32_media_runtime_activation.py",
"tests/test_m25_33_media_setup_entry.py"
"tests/test_manual_media_tools.py"
],
"contract_id": "h3.context.project_recovery.status.v1",
"dialect": "not_applicable",
@@ -11880,9 +11823,8 @@
"comfyui_h3_context/adapters/workspace_state_service.py",
"frontend/src/contracts/retainedAssetsCodec.ts",
"frontend/tests/retainedAssetFixtures.ts",
"tests/test_m25_31_media_runtime_setup.py",
"tests/test_m25_32_media_runtime_activation.py",
"tests/test_m25_33_media_setup_entry.py"
"tests/test_manual_media_tools.py"
],
"contract_id": "h3.context.retained_assets_status.v1",
"dialect": "not_applicable",
@@ -12960,9 +12902,8 @@
"comfyui_h3_context/adapters/retained_asset_service.py",
"frontend/src/contracts/workspaceStateCodec.ts",
"tests/fixtures/workspace_state_v1.json",
"tests/test_m25_31_media_runtime_setup.py",
"tests/test_m25_32_media_runtime_activation.py",
"tests/test_m25_33_media_setup_entry.py"
"tests/test_manual_media_tools.py"
],
"contract_id": "h3.context.workspace_state_status.v1",
"dialect": "not_applicable",
@@ -15544,6 +15485,6 @@
"reachability_source": "none"
}
],
"fingerprint": "sha256:92ba0a9a5f29a5c3899eb98141b6c0005d227e7e1d6c04f294c2a82d8f0a6505",
"fingerprint": "sha256:94be69f36c4d65a92277c49327bf2c56010d8c3b0087940515f7836c331b2c7e",
"schema": "h3-context-contract-inventory/1"
}
@@ -1 +1 @@
{"profiles":[{"compatibility":["python>=3.10"],"distribution":"minimax-h3-studio==1.2.0","download_policy":"artifact_only","end_user_node_lifecycle":"forbidden","fallback":"none","install_mode":"artifact","model_management":"none","owner":"package","profile_id":"core_manual","removal":"remove_package_owned_files","required":true,"rollback":"reinstall_previous_verified_artifact","runtime_entries":["comfyui_h3_context"],"storage_owner":"package"},{"compatibility":["comfyui-native-node-capabilities-v1","comfyui-frontend-extension-api-v1"],"distribution":"host-provided","download_policy":"forbidden","end_user_node_lifecycle":"forbidden","fallback":"none","install_mode":"host_reuse","model_management":"host_only","owner":"host","profile_id":"comfyui_native","removal":"leave_host_runtime_unchanged","required":true,"rollback":"restore_previous_verified_node_artifact","runtime_entries":["comfyui_h3_context"],"storage_owner":"host"},{"compatibility":["h3-context-ollama-qualification/1"],"distribution":"external-user-managed","download_policy":"forbidden","end_user_node_lifecycle":"forbidden","fallback":"none","install_mode":"external_runtime","model_management":"external_only","owner":"user","profile_id":"external_ollama","removal":"leave_external_runtime_unchanged","required":false,"rollback":"user_managed_external_rollback","runtime_entries":[],"storage_owner":"user"},{"compatibility":["openai-compatible-model-list-and-chat-v1"],"distribution":"external-user-managed","download_policy":"forbidden","end_user_node_lifecycle":"forbidden","fallback":"none","install_mode":"external_runtime","model_management":"external_only","owner":"user","profile_id":"external_openai_compatible_loopback","removal":"leave_external_runtime_unchanged","required":false,"rollback":"user_managed_external_rollback","runtime_entries":[],"storage_owner":"user"},{"compatibility":["openai-compatible-model-list-and-chat-v1"],"distribution":"third-party-service","download_policy":"forbidden","end_user_node_lifecycle":"forbidden","fallback":"none","install_mode":"remote_service","model_management":"provider_managed","owner":"provider","profile_id":"remote_openai_compatible_service","removal":"leave_remote_service_unchanged","required":false,"rollback":"revoke_session_consent_and_clear_selection","runtime_entries":[],"storage_owner":"provider"},{"compatibility":["anthropic-models-and-messages-v1"],"distribution":"third-party-service","download_policy":"forbidden","end_user_node_lifecycle":"forbidden","fallback":"none","install_mode":"remote_service","model_management":"provider_managed","owner":"provider","profile_id":"remote_anthropic_service","removal":"leave_remote_service_unchanged","required":false,"rollback":"revoke_session_consent_and_clear_selection","runtime_entries":[],"storage_owner":"provider"},{"compatibility":["comfyui-frontend-extension-api-v1"],"distribution":"bundled-with-minimax-h3-studio","download_policy":"artifact_only","end_user_node_lifecycle":"forbidden","fallback":"none","install_mode":"bundled_asset","model_management":"none","owner":"package","profile_id":"frontend_extension","removal":"remove_package_owned_bundle","required":true,"rollback":"reinstall_previous_verified_artifact","runtime_entries":["comfyui_h3_context/web/h3-context-sidebar.js"],"storage_owner":"package"}],"schema":"h3-context-installation-profiles/1","version":1}
{"profiles":[{"compatibility":["python>=3.10"],"distribution":"minimax-h3-studio==1.2.1","download_policy":"artifact_only","end_user_node_lifecycle":"forbidden","fallback":"none","install_mode":"artifact","model_management":"none","owner":"package","profile_id":"core_manual","removal":"remove_package_owned_files","required":true,"rollback":"reinstall_previous_verified_artifact","runtime_entries":["comfyui_h3_context"],"storage_owner":"package"},{"compatibility":["comfyui-native-node-capabilities-v1","comfyui-frontend-extension-api-v1"],"distribution":"host-provided","download_policy":"forbidden","end_user_node_lifecycle":"forbidden","fallback":"none","install_mode":"host_reuse","model_management":"host_only","owner":"host","profile_id":"comfyui_native","removal":"leave_host_runtime_unchanged","required":true,"rollback":"restore_previous_verified_node_artifact","runtime_entries":["comfyui_h3_context"],"storage_owner":"host"},{"compatibility":["h3-context-ollama-qualification/1"],"distribution":"external-user-managed","download_policy":"forbidden","end_user_node_lifecycle":"forbidden","fallback":"none","install_mode":"external_runtime","model_management":"external_only","owner":"user","profile_id":"external_ollama","removal":"leave_external_runtime_unchanged","required":false,"rollback":"user_managed_external_rollback","runtime_entries":[],"storage_owner":"user"},{"compatibility":["openai-compatible-model-list-and-chat-v1"],"distribution":"external-user-managed","download_policy":"forbidden","end_user_node_lifecycle":"forbidden","fallback":"none","install_mode":"external_runtime","model_management":"external_only","owner":"user","profile_id":"external_openai_compatible_loopback","removal":"leave_external_runtime_unchanged","required":false,"rollback":"user_managed_external_rollback","runtime_entries":[],"storage_owner":"user"},{"compatibility":["openai-compatible-model-list-and-chat-v1"],"distribution":"third-party-service","download_policy":"forbidden","end_user_node_lifecycle":"forbidden","fallback":"none","install_mode":"remote_service","model_management":"provider_managed","owner":"provider","profile_id":"remote_openai_compatible_service","removal":"leave_remote_service_unchanged","required":false,"rollback":"revoke_session_consent_and_clear_selection","runtime_entries":[],"storage_owner":"provider"},{"compatibility":["anthropic-models-and-messages-v1"],"distribution":"third-party-service","download_policy":"forbidden","end_user_node_lifecycle":"forbidden","fallback":"none","install_mode":"remote_service","model_management":"provider_managed","owner":"provider","profile_id":"remote_anthropic_service","removal":"leave_remote_service_unchanged","required":false,"rollback":"revoke_session_consent_and_clear_selection","runtime_entries":[],"storage_owner":"provider"},{"compatibility":["comfyui-frontend-extension-api-v1"],"distribution":"bundled-with-minimax-h3-studio","download_policy":"artifact_only","end_user_node_lifecycle":"forbidden","fallback":"none","install_mode":"bundled_asset","model_management":"none","owner":"package","profile_id":"frontend_extension","removal":"remove_package_owned_bundle","required":true,"rollback":"reinstall_previous_verified_artifact","runtime_entries":["comfyui_h3_context/web/h3-context-sidebar.js"],"storage_owner":"package"}],"schema":"h3-context-installation-profiles/1","version":1}
@@ -116,7 +116,7 @@ def build_default_installation_profiles() -> InstallationProfileManifest:
profile_id="core_manual",
owner="package",
# IMPORTANT: match package and manifest versions; strict decoding rejects drift.
distribution="minimax-h3-studio==1.2.0",
distribution="minimax-h3-studio==1.2.1",
compatibility=("python>=3.10",),
required=True,
install_mode="artifact",
File diff suppressed because one or more lines are too long
+4 -2
View File
@@ -150,14 +150,16 @@ installing models, changing a running ComfyUI host or queueing generation.
`scripts/product_completeness.py` checks source-declared runtime and developer inputs and performs
an isolated product import/resource smoke. `scripts/registry_payload.py` audits the actual packed
archive against the tracked source. Missing tests, fixtures, configurations, tooling or runtime
archive against the tracked source. `scripts/registry_policy_check.py <archive.zip>` is an offline
check that packaged runtime sources do not download, extract or install executables; it reads
archive members in memory and runs none of them. Missing tests, fixtures, configurations, tooling or runtime
resources fail these checks; private records and generated dependency/cache material stay excluded.
Build a Python source distribution from a Git checkout whose reviewed public inputs are tracked:
```powershell
& .\.venv\Scripts\python.exe -m build --sdist
& .\.venv\Scripts\python.exe scripts/sdist_payload.py --archive dist/minimax_h3_studio-1.2.0.tar.gz
& .\.venv\Scripts\python.exe scripts/sdist_payload.py --archive dist/minimax_h3_studio-1.2.1.tar.gz
```
The standard build backend copies public tracked files into a fresh temporary tree and respects
+1 -1
View File
@@ -10,7 +10,7 @@ Accepted title strokes, shadows and background padding are preserved by Save/Ope
recovery, including undo/redo. Older projects without those settings keep their existing style.
Project format version 1 remains in use, but a project using these optional decorations requires
a reader that supports them. Version 1.1.0 readers refuse such a project rather than silently
discarding the decorations; use version 1.2.0 to reopen it.
discarding the decorations; use version 1.2.0 or later to reopen it.
## Save And Open
+10 -12
View File
@@ -29,8 +29,8 @@ Optional features have their own setup and permission boundaries:
- **Assisted authoring** runs only after you pick a profile and give the permission it asks for.
No provider, model or fallback is ever chosen automatically.
- **Media tools** are found on your computer automatically, but downloading them needs you to
choose **Install**.
- **Media tools** are supplied by you and verified locally. The extension does not download or
install them.
- **Local perception** requires the host operator's existing local setup. Visual analysis also
requires permission to send the selected frames to the local Ollama service. See
@@ -187,16 +187,14 @@ Windows x64 with 64-bit Python (gyan.dev full build `2026-02-26-git-6695528af6`)
- **Only that build is used.** Both programs are checked against fixed SHA-256 digests when found
and again on every use; any other copy is ignored.
- **Finding it** looks, in order, at an administrator's override, a folder you chose in
**Settings**, the copy this extension installed, your Python environment and then `PATH` (at most
**Settings**, a copy set up by an earlier version, your Python environment and then `PATH` (at most
32 folders). It never runs a program to identify it and skips network paths and links.
- **Installing** happens only when you choose **Install**. The archive comes over HTTPS from the
fixed GitHub release, is checked against fixed digests and is unpacked without running anything
from it. Only the two programs and their license and readme are kept, in ComfyUI's private user
data. The download sends no prompt, media or credential, never uses a proxy, and never changes
`PATH` or other packs. On a computer that needs a proxy, choose a folder under **Advanced**
instead.
- **Remove earlier copy** appears only when an interrupted update left an old copy behind, and runs
only when you choose it.
- **Manual setup**: download the exact archive linked in **Media tools**, check its displayed
SHA-256 and extract it yourself. **Use folder** admits only the supported pair in its **bin**
folder, without contacting any remote service. Selecting it does not retry an interrupted media
action; retry that action explicitly. Existing earlier-version installations remain discoverable.
- **Cleanup** runs only when explicitly requested. It removes known earlier temporary names,
preserves unknown files and links, and retains a parked copy without a verified replacement.
- **Running**: FFmpeg runs as a separate process with limits on input size, duration and running
time. Final rendering also limits memory, CPU time and output size.
@@ -259,7 +257,7 @@ raw provider responses first.
## Licenses
The project is Apache-2.0; see `LICENSE` and `NOTICE`. The bundled Noto Sans fonts use the SIL Open
Font License 1.1. FFmpeg is not included; it is downloaded only when you choose **Install** and is
Font License 1.1. FFmpeg is not included: you provide the supported build yourself, and it is
licensed separately under GPL-3.0-or-later. MiniMax models, provider services and other external
assets have their own terms. This project is independent and is not affiliated with or endorsed by
MiniMax.
-8
View File
@@ -1101,12 +1101,8 @@ export type NleShellHarnessSnapshot = Readonly<{
/** the Media tools session as the product holds it (codes only). */
mediaRuntime: Readonly<{
status: string;
jobId: string | null;
jobState: string | null;
pendingKind: string | null;
notice: string | null;
refusal: string | null;
resumeKind: string | null;
}>;
previewRequests: number;
// Legacy-shaped fields, reused with the nle-overlay-only semantics the old harness gave them.
@@ -1247,12 +1243,8 @@ window.nleShellHarness = {
mediaPreparation: mediaPreparation(),
mediaRuntime: {
status: session.mediaRuntime.status,
jobId: session.mediaRuntime.job?.jobId ?? null,
jobState: session.mediaRuntime.job?.state ?? null,
pendingKind: session.mediaRuntime.pending?.kind ?? null,
notice: session.mediaRuntime.notice,
refusal: session.mediaRuntime.refusal,
resumeKind: session.mediaRuntime.resume?.kind ?? null,
},
previewRequests,
commitDurationsMs: [...nleCommitDurationsMs],
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@comfyui-h3-context/frontend",
"version": "1.2.0",
"version": "1.2.1",
"private": true,
"type": "module",
"packageManager": "pnpm@11.3.0",
@@ -16,7 +16,6 @@ import {
import type { AuthoringAdjacentRelation } from "../host/authoringAdjacentPreview";
import type { Locale } from "../i18n/catalog";
import {
intentIdentity,
type MediaRuntimeIntent,
type MediaToolsBinding,
} from "../state/mediaRuntimeState";
@@ -295,19 +294,6 @@ export function AuthoringPreviewMonitor({
overlayGeneration,
],
);
const resume = mediaTools?.state.resume ?? null;
// IMPORTANT: a continuation is consumed once. A token seen at mount belongs to an earlier
// preview; only a later token whose identity is this exact clip, revision and overlay reopens.
const seenResume = useRef(resume?.token ?? 0);
useEffect(() => {
if (resume === null || resume.token === seenResume.current) return;
seenResume.current = resume.token;
if (
resume.kind === "clip_preview" &&
resume.identity === intentIdentity(mediaIntent)
)
reopen((value) => value + 1);
}, [resume, mediaIntent]);
const runtimeBlocked =
snapshot.status === "unavailable" && snapshot.reason === "unsupported";
const activeIdentity =
+378 -450
View File
@@ -1,263 +1,184 @@
// the one Media tools card, in Settings and where import, clip preview or final output is
// blocked by the backend media runtime.
//
// The card renders only the decoded status and the one setup job the session holds. Normal screens
// show availability, the install source, its approximate size, license and release page, and at
// most one primary action; locators, hashes and codec lists never appear. The advanced folder field
// lives in Settings only, behind a disclosure.
import { useEffect, useId, useRef, useState } from "react";
import type { Locale } from "../i18n/catalog";
import {
MEDIA_RUNTIME_FEATURES,
type MediaRuntimeFeature,
type MediaRuntimeFeatureReadiness,
type MediaRuntimeJob,
type MediaRuntimeStatus,
} from "../contracts/mediaRuntimeCodec";
import type { Locale } from "../i18n/catalog";
import {
MEDIA_RUNTIME_INTENT_FEATURE,
type MediaRuntimeIntent,
type MediaRuntimeState,
type MediaToolsBinding,
import type {
MediaRuntimeIntent,
MediaRuntimeState,
MediaToolsBinding,
} from "../state/mediaRuntimeState";
import { plainReason } from "./plainReasons";
import mediaToolsStyles from "./mediaToolsCard.css?inline";
const copy = {
export const mediaToolsCopy = {
en: {
title: "Media tools",
description:
"Import, clip preview and final output use media tools on this ComfyUI host.",
checking: "Checking media tools…",
statusUnavailable: "Media tools status is unavailable.",
checkAgain: "Check again",
"Import, preview and final video use a supported FFmpeg and FFprobe pair.",
needed: "Set up media tools to use this feature.",
ready: "Media tools are ready.",
source: {
managed: "Installed by this extension.",
explicit_override: "Set up by the host administrator.",
local_selection: "Using the folder you chose.",
python_prefix: "Found with this ComfyUI installation.",
system_path: "Found on this computer.",
},
needed: {
settings: "Import, clip preview and final output need media tools.",
import: "Importing needs media tools.",
preview: "Clip preview needs media tools.",
derivatives: "Clip preparation needs media tools.",
assembly: "Sequence assembly needs media tools.",
render: "Final output needs media tools.",
},
details: "{source}, about {size} MB, {license}.",
releasePage: "Release page",
install: "Install",
installAndContinue: "Install and continue",
installAgain: "Install again",
cancel: "Cancel setup",
progress: "Setup progress",
progressBytes: "{done} of {total} MB",
phase: {
checking: "Checking the download…",
downloading: "Downloading media tools…",
extracting: "Extracting media tools…",
verifying: "Verifying media tools…",
publishing: "Installing media tools…",
activating: "Starting media tools…",
done: "Finishing setup…",
},
failed: "Setup did not finish.",
adminControl:
"Change the media tools setting on the ComfyUI host, then check again.",
starting: "Media tools are starting…",
renderUnavailable: "Final output is not available on this host.",
recovery: "An earlier copy of the media tools is kept aside.",
recoveryKept:
"It stays in place until the current media tools are confirmed ready.",
reclaim: "Remove earlier copy",
manual:
"Open the release page, download the exact archive below and extract it yourself. Then enter its bin folder, which contains ffmpeg.exe and ffprobe.exe.",
releasePage: "Open download page",
help: "FFmpeg setup help",
closeHelp: "Close help",
version: "Pinned version",
license: "Licence",
helpDownload:
"Open the download page and choose the exact archive shown here.",
helpVerify:
"Before extracting, compare the archive's SHA-256 with the value shown here. On Windows, use either command, replacing <file> with the archive path:",
helpExtract: "Extract the verified archive yourself.",
helpSelect:
"Enter its bin folder containing ffmpeg.exe and ffprobe.exe, or add that folder to PATH, then choose Check again.",
helpPins:
"Only the pinned FFmpeg and FFprobe executables are supported. A different build is refused because its executable checksums do not match.",
helpEarlier: "A verified setup made by an earlier version keeps working.",
archive: "Archive",
checksum: "Archive SHA-256",
copy: "Copy SHA-256",
copied: "Copied",
copyFailed: "Could not copy. Select and copy the checksum.",
folder: "FFmpeg bin folder",
useFolder: "Use folder",
path: "You can also place the supported pair on PATH, then check again.",
checkAgain: "Check again",
advanced: "Advanced",
folder: "Media tools folder",
useFolder: "Use this folder",
restoreAuto: "Use automatic setup",
dismiss: "Dismiss",
notice: {
continued: "Media tools are ready. Continuing.",
select_again:
"Media tools are ready, but the selection changed. Select again.",
continuation_cleared: "The waiting action was cleared.",
continuation_replaced:
"The earlier waiting action was replaced by this one.",
feature_not_ready:
"Setup finished, but this feature is still unavailable.",
outcome_unknown: "The setup request could not be confirmed. Check again.",
restoreAuto: "Search automatically",
retry: "Tools are selected. Retry the original action when you are ready.",
checking: "Checking media tools…",
unavailable: "Media tool status is unavailable.",
renderUnavailable:
"Final video is unavailable on this host. Selecting tools cannot enable its renderer.",
recovery: "Earlier setup left temporary files or an earlier copy behind.",
reclaim: "Clean up earlier setup files",
recoveryKept:
"The earlier copy is kept until a supported managed replacement is verified.",
source: {
managed: "Set up by an earlier version",
explicit_override: "Host override",
local_selection: "Selected folder",
python_prefix: "Python environment",
system_path: "System PATH",
none: "No source selected",
},
},
"zh-TW": {
title: "媒體工具",
description: "匯入、剪輯預覽與最終輸出會使用此 ComfyUI 主機上的媒體工具。",
checking: "正在檢查媒體工具…",
statusUnavailable: "無法取得媒體工具狀態。",
checkAgain: "再次檢查",
description: "匯入、預覽與最終影片使用支援的 FFmpeg 與 FFprobe 工具組。",
needed: "請設定媒體工具以使用此功能。",
ready: "媒體工具已就緒。",
source: {
managed: "由此擴充功能安裝。",
explicit_override: "由主機管理員設定。",
local_selection: "使用您選擇的資料夾。",
python_prefix: "在此 ComfyUI 安裝中找到。",
system_path: "在此電腦上找到。",
},
needed: {
settings: "匯入、剪輯預覽與最終輸出需要媒體工具。",
import: "匯入需要媒體工具。",
preview: "剪輯預覽需要媒體工具。",
derivatives: "準備剪輯需要媒體工具。",
assembly: "組裝序列需要媒體工具。",
render: "最終輸出需要媒體工具。",
},
details: "{source},約 {size} MB,{license}。",
releasePage: "發行頁面",
install: "安裝",
installAndContinue: "安裝並繼續",
installAgain: "重新安裝",
cancel: "取消安裝",
progress: "安裝進度",
progressBytes: "{done} / {total} MB",
phase: {
checking: "正在檢查下載…",
downloading: "正在下載媒體工具…",
extracting: "正在解壓縮媒體工具…",
verifying: "正在驗證媒體工具…",
publishing: "正在安裝媒體工具…",
activating: "正在啟動媒體工具…",
done: "正在完成安裝…",
},
failed: "安裝未完成。",
adminControl: "請在 ComfyUI 主機上變更媒體工具設定,然後再次檢查。",
starting: "媒體工具正在啟動…",
renderUnavailable: "此主機無法提供最終輸出。",
recovery: "較早的媒體工具副本已另外保留。",
recoveryKept: "在確認目前的媒體工具就緒之前,會保留這份副本。",
reclaim: "移除較早的副本",
manual:
"開啟發行頁面,下載下方指定的壓縮檔並自行解壓縮,再輸入包含 ffmpeg.exe 與 ffprobe.exe 的 bin 資料夾。",
releasePage: "開啟下載網址",
help: "FFmpeg 設定說明",
closeHelp: "關閉說明",
version: "指定版本",
license: "授權",
helpDownload: "開啟下載網址,選擇此處顯示的指定壓縮檔。",
helpVerify:
"解壓縮前,請將壓縮檔的 SHA-256 與此處的校驗碼比對。在 Windows 可使用以下任一指令,將 <file> 換成壓縮檔路徑:",
helpExtract: "自行解壓縮已驗證的壓縮檔。",
helpSelect:
"輸入包含 ffmpeg.exe 與 ffprobe.exe 的 bin 資料夾,或將該資料夾加入 PATH,再按「重新檢查」。",
helpPins:
"僅支援指定的 FFmpeg 與 FFprobe 執行檔。其他版本的執行檔校驗碼不符,因此無法使用。",
helpEarlier: "由先前版本完成且通過驗證的設定可繼續使用。",
archive: "壓縮檔",
checksum: "壓縮檔 SHA-256",
copy: "複製 SHA-256",
copied: "已複製",
copyFailed: "無法複製,請選取並複製校驗碼。",
folder: "FFmpeg bin 資料夾",
useFolder: "使用資料夾",
path: "也可將支援的工具組放入 PATH,再重新檢查。",
checkAgain: "重新檢查",
advanced: "進階",
folder: "媒體工具資料夾",
useFolder: "使用此資料夾",
restoreAuto: "使用自動設定",
dismiss: "關閉",
notice: {
continued: "媒體工具已就緒,正在繼續。",
select_again: "媒體工具已就緒,但選取內容已變更,請重新選取。",
continuation_cleared: "已清除等待中的動作。",
continuation_replaced: "較早等待中的動作已由此動作取代。",
feature_not_ready: "安裝已完成,但此功能仍無法使用。",
outcome_unknown: "無法確認安裝要求的結果,請再次檢查。",
restoreAuto: "自動搜尋",
retry: "工具已選定,準備好後請重試原本的操作。",
checking: "正在檢查媒體工具…",
unavailable: "無法讀取媒體工具狀態。",
renderUnavailable: "此主機無法輸出最終影片,選擇工具無法啟用其渲染器。",
recovery: "先前的設定留下了暫存檔或舊版工具。",
reclaim: "清理先前設定的檔案",
recoveryKept: "在確認受支援的替代工具前,會保留舊版工具。",
source: {
managed: "由先前版本設定",
explicit_override: "主機指定",
local_selection: "選定的資料夾",
python_prefix: "Python 環境",
system_path: "系統 PATH",
none: "尚未選定來源",
},
},
"zh-CN": {
title: "媒体工具",
description: "导入、剪辑预览与最终输出会使用此 ComfyUI 主机上的媒体工具。",
checking: "正在检查媒体工具…",
statusUnavailable: "无法获取媒体工具状态。",
checkAgain: "再次检查",
description: "导入、预览与最终视频使用支持的 FFmpeg 与 FFprobe 工具组。",
needed: "请设置媒体工具以使用此功能。",
ready: "媒体工具已就绪。",
source: {
managed: "由此扩展安装。",
explicit_override: "由主机管理员设置。",
local_selection: "使用你选择的文件夹。",
python_prefix: "在此 ComfyUI 安装中找到。",
system_path: "在此电脑上找到。",
},
needed: {
settings: "导入、剪辑预览与最终输出需要媒体工具。",
import: "导入需要媒体工具。",
preview: "剪辑预览需要媒体工具。",
derivatives: "准备剪辑需要媒体工具。",
assembly: "组装序列需要媒体工具。",
render: "最终输出需要媒体工具。",
},
details: "{source},约 {size} MB,{license}。",
releasePage: "发布页面",
install: "安装",
installAndContinue: "安装并继续",
installAgain: "重新安装",
cancel: "取消安装",
progress: "安装进度",
progressBytes: "{done} / {total} MB",
phase: {
checking: "正在检查下载…",
downloading: "正在下载媒体工具…",
extracting: "正在解压媒体工具…",
verifying: "正在验证媒体工具…",
publishing: "正在安装媒体工具…",
activating: "正在启动媒体工具…",
done: "正在完成安装…",
},
failed: "安装未完成。",
adminControl: "请在 ComfyUI 主机上更改媒体工具设置,然后再次检查。",
starting: "媒体工具正在启动…",
renderUnavailable: "此主机无法提供最终输出。",
recovery: "较早的媒体工具副本已另行保留。",
recoveryKept: "在确认当前的媒体工具就绪之前,会保留这份副本。",
reclaim: "移除较早的副本",
manual:
"打开发布页面,下载下方指定的压缩文件并自行解压,再输入包含 ffmpeg.exe 与 ffprobe.exe 的 bin 文件夹。",
releasePage: "打开下载网址",
help: "FFmpeg 设置说明",
closeHelp: "关闭说明",
version: "指定版本",
license: "许可",
helpDownload: "打开下载网址,选择此处显示的指定压缩文件。",
helpVerify:
"解压前,请将压缩文件的 SHA-256 与此处的校验码比对。在 Windows 可使用以下任一命令,将 <file> 换成压缩文件路径:",
helpExtract: "自行解压已验证的压缩文件。",
helpSelect:
"输入包含 ffmpeg.exe 与 ffprobe.exe 的 bin 文件夹,或将该文件夹加入 PATH,再点击“重新检查”。",
helpPins:
"仅支持指定的 FFmpeg 与 FFprobe 可执行文件。其他版本的可执行文件校验码不符,因此无法使用。",
helpEarlier: "由先前版本完成且通过验证的设置可继续使用。",
archive: "压缩文件",
checksum: "压缩文件 SHA-256",
copy: "复制 SHA-256",
copied: "已复制",
copyFailed: "无法复制,请选中并复制校验码。",
folder: "FFmpeg bin 文件夹",
useFolder: "使用文件夹",
path: "也可将支持的工具组放入 PATH,再重新检查。",
checkAgain: "重新检查",
advanced: "高级",
folder: "媒体工具文件夹",
useFolder: "使用此文件夹",
restoreAuto: "使用自动设置",
dismiss: "关闭",
notice: {
continued: "媒体工具已就绪,正在继续。",
select_again: "媒体工具已就绪,但选择内容已更改,请重新选择。",
continuation_cleared: "已清除等待中的操作。",
continuation_replaced: "较早等待中的操作已被此操作取代。",
feature_not_ready: "安装已完成,但此功能仍不可用。",
outcome_unknown: "无法确认安装请求的结果,请再次检查。",
restoreAuto: "自动搜索",
retry: "工具已选定,准备好后请重试原来的操作。",
checking: "正在检查媒体工具…",
unavailable: "无法读取媒体工具状态。",
renderUnavailable: "此主机无法输出最终视频,选择工具无法启用其渲染器。",
recovery: "先前的设置留下了临时文件或旧版工具。",
reclaim: "清理先前设置的文件",
recoveryKept: "在确认支持的替代工具前,会保留旧版工具。",
source: {
managed: "由先前版本设置",
explicit_override: "主机指定",
local_selection: "选定的文件夹",
python_prefix: "Python 环境",
system_path: "系统 PATH",
none: "尚未选择来源",
},
},
} as const;
export type MediaToolsPlacement =
"settings" | "contextual-sidebar" | "contextual-overlay";
export type MediaToolsView = Readonly<{
kind:
| "checking"
| "status_unavailable"
| "ready"
| "setup_required"
| "render_unavailable"
| "starting"
| "unavailable";
reason?: string | null;
}>;
type MediaToolsView =
| Readonly<{ kind: "checking" }>
| Readonly<{ kind: "status_unavailable" }>
| Readonly<{ kind: "installing"; job: MediaRuntimeJob }>
| Readonly<{ kind: "ready" }>
| Readonly<{ kind: "setup_required" }>
| Readonly<{ kind: "failed"; reason: string | null }>
| Readonly<{ kind: "starting" }>
| Readonly<{ kind: "render_unavailable" }>
| Readonly<{ kind: "unavailable"; reason: string | null }>;
const STARTING_REASONS: ReadonlySet<string> = new Set([
"activating",
"discovering",
"discovery_in_progress",
]);
function fill(value: string, values: Record<string, string | number>): string {
let output = value;
for (const [key, replacement] of Object.entries(values))
output = output.replace(`{${key}}`, String(replacement));
return output;
}
function megabytes(bytes: number): string {
return String(Math.max(1, Math.round(bytes / (1024 * 1024))));
}
function runningJob(state: MediaRuntimeState): MediaRuntimeJob | null {
// IMPORTANT: the session's job is never older than the wire's `setup` (a status read adopts it,
// and only later poll or action results replace it). Falling back to the wire while the session
// holds a terminal job would show a job the user just cancelled as still installing.
if (state.job !== null)
return state.job.state === "running" ? state.job : null;
return state.wire?.setup?.state === "running" ? state.wire.setup : null;
}
/** The readiness a placement is about; Settings summarizes the features the card can repair. */
function readinessFor(
wire: MediaRuntimeStatus,
feature: MediaRuntimeFeature | undefined,
): MediaRuntimeFeatureReadiness {
function readiness(wire: MediaRuntimeStatus, feature?: MediaRuntimeFeature) {
if (feature !== undefined) return wire.features[feature];
const rows = MEDIA_RUNTIME_FEATURES.map((name) => wire.features[name]).filter(
(row) => row.reason !== "render_qualification_unavailable",
@@ -268,54 +189,36 @@ function readinessFor(
wire.features.import
);
}
/** One view per state; a failed read never shows the last good status as ready. */
export function deriveMediaToolsView(
state: MediaRuntimeState,
feature?: MediaRuntimeFeature,
): MediaToolsView {
const job = runningJob(state);
if (job !== null) return { kind: "installing", job };
if (state.status === "unavailable") return { kind: "status_unavailable" };
const wire = state.wire;
if (wire === null) return { kind: "checking" };
const readiness = readinessFor(wire, feature);
if (readiness.state === "ready") return { kind: "ready" };
if (state.job?.state === "failed")
return { kind: "failed", reason: state.job.reason };
if (readiness.state === "setup_required") return { kind: "setup_required" };
if (readiness.reason === "render_qualification_unavailable")
if (state.wire === null) return { kind: "checking" };
const row = readiness(state.wire, feature);
if (row.state === "ready") return { kind: "ready" };
if (row.state === "setup_required") return { kind: "setup_required" };
if (row.reason === "render_qualification_unavailable")
return { kind: "render_unavailable" };
if (readiness.reason !== null && STARTING_REASONS.has(readiness.reason))
if (
["activating", "discovering", "discovery_in_progress"].includes(
row.reason ?? "",
)
)
return { kind: "starting" };
return { kind: "unavailable", reason: readiness.reason };
return { kind: "unavailable", reason: row.reason };
}
/**
* Whether a contextual surface shows the card. `blocked` is the surface's own runtime refusal;
* `proactive` lets a surface show a known `setup_required` before the user is refused.
*/
export function mediaToolsCardVisible(
state: MediaRuntimeState,
feature: MediaRuntimeFeature,
blocked: boolean,
proactive = false,
): boolean {
const readiness =
const row =
state.status === "unavailable" ? undefined : state.wire?.features[feature];
const needsSetup = proactive && readiness?.state === "setup_required";
if (runningJob(state) !== null)
return (
blocked ||
needsSetup ||
(state.pending !== null &&
MEDIA_RUNTIME_INTENT_FEATURE[state.pending.kind] === feature)
);
if (!blocked) return needsSetup;
return (
readiness?.state !== "ready" ||
state.notice !== null ||
state.refusal !== null
(proactive && row?.state === "setup_required") ||
(blocked && (row?.state !== "ready" || state.refusal !== null))
);
}
@@ -329,107 +232,67 @@ export function MediaToolsCard({
placement: MediaToolsPlacement;
binding: MediaToolsBinding;
locale: Locale;
/** The feature a contextual placement is blocked on; Settings leaves it unset. */
feature?: MediaRuntimeFeature;
/** The original action to continue after setup; `null` installs without continuing. */
intent?: MediaRuntimeIntent | null;
}) {
const text = copy[locale];
const titleId = useId();
const folderId = useId();
const text = mediaToolsCopy[locale];
const { state } = binding;
const view = deriveMediaToolsView(state, feature);
const wire = state.wire;
const settings = placement === "settings";
const statusLine = useRef<HTMLParagraphElement | null>(null);
const primary = useRef<HTMLButtonElement | null>(null);
// Focus is moved only for a card the user acted in, so two cards visible in one overlay never
// compete and an unrelated status change never takes focus from where the user is.
const engaged = useRef(false);
const titleId = useId();
const folderId = useId();
const helpId = useId();
const helpTitleId = useId();
const [helpOpen, setHelpOpen] = useState(false);
const helpTrigger = useRef<HTMLButtonElement>(null);
const helpPanel = useRef<HTMLDivElement>(null);
const [folder, setFolder] = useState("");
// Reads happen when a surface can use them: once on the first Settings open, and whenever a
// contextual card mounts because its surface was refused by the runtime.
const [copyState, setCopyState] = useState<"copied" | "copyFailed" | null>(
null,
);
const primary = useRef<HTMLButtonElement>(null);
const engaged = useRef(false);
useEffect(() => {
if (helpOpen) helpPanel.current?.focus();
}, [helpOpen]);
const closeHelp = () => {
setHelpOpen(false);
helpTrigger.current?.focus();
};
const ensure = binding.ensure;
const report = binding.report;
useEffect(() => {
if (feature === undefined) ensure();
else report(feature);
}, [ensure, report, feature]);
const installing = view.kind === "installing";
const initialFocus = useRef(state.focusPrimary);
useEffect(() => {
if (installing && engaged.current) statusLine.current?.focus();
}, [installing]);
const focusPrimary = state.focusPrimary;
const firstFocus = useRef(focusPrimary);
useEffect(() => {
if (focusPrimary === firstFocus.current || !engaged.current) return;
(primary.current ?? statusLine.current)?.focus();
}, [focusPrimary]);
if (state.focusPrimary !== initialFocus.current && engaged.current)
primary.current?.focus();
}, [state.focusPrimary]);
const offers = (
action: "use_local_directory" | "restore_auto" | "reclaim_parked_runtime",
) =>
state.status !== "unavailable" && wire?.actions.includes(action) === true;
const busy = state.busy !== null;
const offers = (action: MediaRuntimeStatus["actions"][number]) =>
wire?.actions.includes(action) === true;
const install = () => binding.install(settings ? null : intent);
let message: string;
let detail: string | null = null;
let action: Readonly<{ label: string; run(): void }> | null = null;
switch (view.kind) {
case "checking":
message = text.checking;
break;
case "status_unavailable":
message = text.statusUnavailable;
action = { label: text.checkAgain, run: binding.rescan };
break;
case "installing":
message = text.phase[view.job.phase];
break;
case "ready":
message = text.ready;
if (settings && wire !== null && wire.resolution.sourceKind !== "none")
detail = text.source[wire.resolution.sourceKind];
break;
case "setup_required":
message = text.needed[feature ?? "settings"];
if (offers("install_supported"))
action = {
label: settings ? text.install : text.installAndContinue,
run: install,
};
break;
case "failed":
message = text.failed;
detail =
view.reason === "advanced_override_active"
? text.adminControl
: plainReason(locale, "mediaRuntime", view.reason);
if (
view.reason !== "advanced_override_active" &&
offers("install_supported")
)
action = { label: text.installAgain, run: install };
break;
case "starting":
message = text.starting;
break;
case "render_unavailable":
message = text.renderUnavailable;
break;
case "unavailable":
message = plainReason(locale, "mediaRuntime", view.reason);
if (offers("rescan"))
action = { label: text.checkAgain, run: binding.rescan };
break;
}
const showInstallSource =
wire !== null && (view.kind === "setup_required" || view.kind === "failed");
const job = view.kind === "installing" ? view.job : null;
const manualVisible =
wire !== null &&
(settings ||
view.kind === "setup_required" ||
view.kind === "unavailable") &&
view.kind !== "render_unavailable";
const message =
view.kind === "ready"
? text.ready
: view.kind === "setup_required"
? text.needed
: view.kind === "render_unavailable"
? text.renderUnavailable
: view.kind === "checking" || view.kind === "starting"
? text.checking
: text.unavailable;
const Heading = settings ? "h3" : "h4";
return (
<section
className={
@@ -438,138 +301,156 @@ export function MediaToolsCard({
aria-labelledby={titleId}
data-h3-media-tools={view.kind}
data-h3-media-tools-placement={placement}
data-h3-media-tools-reason={
view.kind === "failed" || view.kind === "unavailable"
? (view.reason ?? undefined)
: undefined
}
data-h3-media-tools-context={intent?.kind}
onClickCapture={() => {
engaged.current = true;
}}
onKeyDown={(event) => {
if (event.key === "Escape" && helpOpen) {
// Keep help dismissal local so Escape does not also close the enclosing editor.
event.preventDefault();
event.stopPropagation();
closeHelp();
}
}}
>
<Heading id={titleId} className="h3-sec">
{text.title}
</Heading>
<style>{mediaToolsStyles}</style>
<div className="h3s-mt-heading">
<Heading id={titleId} className="h3-sec">
{text.title}
</Heading>
<button
ref={helpTrigger}
type="button"
className="h3-icon-button h3s-mt-help-toggle"
aria-label={text.help}
title={text.help}
aria-expanded={helpOpen}
aria-controls={helpId}
disabled={wire === null}
data-h3-media-tools-action="help"
onClick={() => (helpOpen ? closeHelp() : setHelpOpen(true))}
>
<span aria-hidden="true">?</span>
</button>
</div>
{helpOpen && wire ? (
<div
ref={helpPanel}
id={helpId}
role="region"
aria-labelledby={helpTitleId}
tabIndex={-1}
className="h3s-mt-help"
data-h3-media-tools-help
>
<h4 id={helpTitleId}>{text.help}</h4>
<p>{text.description}</p>
<dl>
<dt>{text.version}</dt>
<dd>
<code>{wire.manual.releasePage.split("/").at(-1)}</code>
</dd>
<dt>{text.archive}</dt>
<dd>
<code>{wire.manual.archiveName}</code>
</dd>
<dt>{text.checksum}</dt>
<dd>
<code>{wire.manual.archiveSha256}</code>
</dd>
<dt>{text.license}</dt>
<dd>{wire.manual.license}</dd>
</dl>
<ol>
<li>{text.helpDownload}</li>
<li>
{text.helpVerify}
<code className="h3s-mt-command">
Get-FileHash -Algorithm SHA256 &lt;file&gt;
</code>
<code className="h3s-mt-command">
certutil -hashfile &lt;file&gt; SHA256
</code>
</li>
<li>{text.helpExtract}</li>
<li>{text.helpSelect}</li>
</ol>
<p>{text.helpPins}</p>
<p>{text.helpEarlier}</p>
<button
type="button"
data-h3-media-tools-action="close-help"
onClick={closeHelp}
>
{text.closeHelp}
</button>
</div>
) : null}
{settings ? <p className="h3ds">{text.description}</p> : null}
<p
ref={statusLine}
className="h3s-mt-state"
role="status"
aria-live="polite"
tabIndex={-1}
data-h3-focus-key={settings ? "settings-media-tools" : undefined}
tabIndex={-1}
>
<span className="h3-val">{message}</span>
{detail !== null ? <span className="h3-meta">{detail}</span> : null}
{view.kind === "ready" && wire ? (
<span className="h3-meta">
{text.source[wire.resolution.sourceKind]}
</span>
) : null}
</p>
{settings &&
view.kind !== "render_unavailable" &&
wire?.features.render.reason === "render_qualification_unavailable" ? (
<p className="h3-meta" data-h3-media-tools-render="unavailable">
{text.renderUnavailable}
</p>
) : null}
{job !== null ? (
<>
<progress
aria-label={text.progress}
max={job.totalBytes > 0 ? job.totalBytes : undefined}
value={job.totalBytes > 0 ? job.completedBytes : undefined}
/>
{job.totalBytes > 0 ? (
<p className="h3-meta" aria-hidden="true">
{fill(text.progressBytes, {
done: megabytes(job.completedBytes),
total: megabytes(job.totalBytes),
})}
</p>
) : null}
</>
) : null}
{showInstallSource ? (
<p className="h3-meta" data-h3-media-tools-source="install">
{fill(text.details, {
source: wire.install.sourceLabel,
size: megabytes(wire.install.approximateBytes),
license: wire.install.license,
})}{" "}
{manualVisible && wire ? (
<div data-h3-media-tools-source="manual">
<p>{text.manual}</p>
<p className="h3-meta">
{wire.manual.sourceLabel} ·{" "}
{Math.round(wire.manual.approximateBytes / 1048576)} MB ·{" "}
{wire.manual.license}
</p>
<a
href={wire.install.releasePage}
className="h3s-mt-download"
data-variant="primary"
data-h3-media-tools-action="download"
href={wire.manual.releasePage}
target="_blank"
rel="noopener noreferrer"
>
{text.releasePage}
</a>
</p>
) : null}
{state.refusal !== null && view.kind !== "status_unavailable" ? (
<p
role="alert"
className="h3s-mt-rejection"
data-h3-media-tools-refusal={state.refusal}
>
{plainReason(locale, "mediaRuntime", state.refusal)}
</p>
) : null}
{state.notice !== null ? (
<p
className="h3s-mt-notice"
role="status"
data-h3-media-tools-notice={state.notice}
>
<span>{text.notice[state.notice]}</span>
<button type="button" onClick={binding.dismiss}>
{text.dismiss}
<p style={{ overflowWrap: "anywhere" }}>
{text.archive}: <code>{wire.manual.archiveName}</code>
</p>
<p style={{ overflowWrap: "anywhere" }}>
{text.checksum}:{" "}
<code data-h3-media-tools-sha>{wire.manual.archiveSha256}</code>
</p>
<button
type="button"
data-h3-media-tools-action="copy"
onClick={() => {
// Clipboard access can be absent on a host served outside a secure browser context.
void Promise.resolve()
.then(() =>
navigator.clipboard.writeText(wire.manual.archiveSha256),
)
.then(
() => setCopyState("copied"),
() => setCopyState("copyFailed"),
);
}}
>
{text.copy}
</button>
</p>
) : null}
{action !== null ? (
<button
ref={primary}
type="button"
data-h3-focus-key="media-tools-primary"
data-h3-media-tools-action="primary"
disabled={busy}
onClick={action.run}
>
{action.label}
</button>
) : null}
{job !== null ? (
<button
ref={primary}
type="button"
data-h3-focus-key="media-tools-primary"
data-h3-media-tools-action="cancel"
// IMPORTANT: a job this page started arrives from the install reply, not a status read,
// so the last status predates it and never lists `cancel_setup`. Only a status that
// describes this same running job may withhold Cancel; otherwise Cancel is dead.
disabled={
busy ||
(wire?.setup?.jobId === job.jobId &&
wire.setup.state === "running" &&
!offers("cancel_setup"))
}
onClick={binding.cancel}
>
{text.cancel}
</button>
) : null}
{settings && wire?.recovery != null && job === null ? (
<div className="h3s-mt-recovery" data-h3-media-tools-recovery="true">
<p>{text.recovery}</p>
{wire.recovery.reclaimable && offers("reclaim_parked_runtime") ? (
<button type="button" disabled={busy} onClick={binding.reclaim}>
{text.reclaim}
</button>
) : (
<p className="h3-meta">{text.recoveryKept}</p>
)}
</div>
) : null}
{settings && wire !== null && job === null ? (
<details className="h3s-mt-advanced">
<summary>{text.advanced}</summary>
{copyState ? <p role="status">{text[copyState]}</p> : null}
<div className="h3s-r">
<label htmlFor={folderId}>{text.folder}</label>
<input
@@ -583,7 +464,10 @@ export function MediaToolsCard({
/>
</div>
<button
ref={primary}
type="button"
data-h3-focus-key="media-tools-primary"
data-h3-media-tools-action="primary"
disabled={
busy || folder.trim() === "" || !offers("use_local_directory")
}
@@ -591,11 +475,55 @@ export function MediaToolsCard({
>
{text.useFolder}
</button>
<p className="h3-meta">{text.path}</p>
</div>
) : null}
{view.kind !== "render_unavailable" ? (
<button
type="button"
disabled={busy}
data-h3-media-tools-action="rescan"
onClick={binding.rescan}
>
{text.checkAgain}
</button>
) : null}
{state.refusal !== null ? (
<p
role="alert"
className="h3s-mt-rejection"
data-h3-media-tools-refusal={state.refusal}
>
{plainReason(locale, "mediaRuntime", state.refusal)}
</p>
) : null}
{state.notice !== null ? (
<p role="status" data-h3-media-tools-notice={state.notice}>
{text.retry}
</p>
) : null}
{settings && wire?.recovery ? (
<div className="h3s-mt-recovery" data-h3-media-tools-recovery="true">
<p>{text.recovery}</p>
{wire.recovery.reclaimable && offers("reclaim_parked_runtime") ? (
<button type="button" disabled={busy} onClick={binding.reclaim}>
{text.reclaim}
</button>
) : (
<p>{text.recoveryKept}</p>
)}
</div>
) : null}
{manualVisible && wire ? (
<details className="h3s-mt-advanced">
<summary>{text.advanced}</summary>
{offers("restore_auto") ? (
<button type="button" disabled={busy} onClick={binding.restoreAuto}>
{text.restoreAuto}
</button>
) : null}
) : (
<p className="h3-meta">{text.path}</p>
)}
</details>
) : null}
</section>
@@ -0,0 +1,75 @@
/* Shared card rules travel with the card into both sidebar and portalled editor roots. */
.h3s-mt-heading {
display: flex;
align-items: center;
gap: 0.5rem;
}
.h3s-mt-heading .h3-sec {
flex: 1;
margin: 0;
}
.h3s-mt-heading .h3s-mt-help-toggle {
--h3-icon-hue: var(--h3-tone-info);
display: inline-flex;
align-items: center;
justify-content: center;
inline-size: 44px;
block-size: 44px;
min-inline-size: 44px;
padding: 0;
border: 1px solid
color-mix(in srgb, var(--h3-icon-hue) 55%, var(--h3-line-strong));
border-radius: var(--h3-radius-control);
color: var(--h3-icon-hue);
background: color-mix(in srgb, var(--h3-icon-hue) 14%, var(--h3-control));
}
.h3s-mt-heading .h3s-mt-help-toggle:hover:not(:disabled) {
background: color-mix(in srgb, var(--h3-icon-hue) 26%, var(--h3-control));
}
.h3s-mt-help,
.h3s-mt-download:focus-visible,
.h3s-mt-heading .h3s-mt-help-toggle:focus-visible {
outline-offset: 2px;
}
.h3s-mt-help:focus-visible,
.h3s-mt-download:focus-visible,
.h3s-mt-heading .h3s-mt-help-toggle:focus-visible {
outline: 2px solid var(--h3-page-outline-context);
}
.h3s-mt-help {
border: 1px solid var(--h3-line-subtle);
border-radius: var(--h3-radius-panel);
padding: 0.75rem;
min-width: 0;
overflow-wrap: anywhere;
}
.h3s-mt-help dd {
margin-inline-start: 0;
margin-block-end: 0.5rem;
}
.h3s-mt-help ol {
padding-inline-start: 1.25rem;
}
.h3s-mt-help li {
margin-block-end: 0.5rem;
}
.h3s-mt-command {
display: block;
margin-block-start: 0.25rem;
}
.h3s-mt-download {
display: inline-flex;
justify-content: center;
align-items: center;
min-height: 36px;
padding: 0.375rem 0.625rem;
border: 1px solid var(--h3-accent);
border-radius: var(--h3-radius-control);
background: var(--h3-accent);
color: var(--h3-accent-text) !important;
font-weight: 700;
text-decoration: none;
}
.h3s-mt-download:hover {
filter: brightness(1.08);
}
+9 -58
View File
@@ -369,30 +369,9 @@ const en: Tables = {
advanced_override_active:
"The host administrator's media tools setting is in effect.",
already_available: "Media tools are already available.",
installed: "Media tools were installed.",
archive_invalid: "The downloaded file was damaged. Install again.",
cancelled: "Setup was cancelled.",
digest_mismatch:
"The download did not match the expected file. Install again.",
size_mismatch:
"The download did not match the expected file. Install again.",
verification_failed:
"The installed media tools could not be verified. Install again.",
download_failed: "The download failed. Install again.",
download_timeout: "The download took too long. Install again.",
network_timeout: "The download took too long. Install again.",
network_unavailable:
"The network is unavailable. Check the connection, then install again.",
egress_refused: "The download address was refused. Try again later.",
redirect_refused: "The download address was refused. Try again later.",
tls_failed:
"A secure connection to the download could not be made. Try again later.",
source_unavailable:
"The download source is unavailable. Try again later.",
insufficient_space: "There is not enough disk space for the media tools.",
permission_denied: "The media tools folder is not writable.",
publication_failed:
"The media tools could not be put in place. Install again.",
local_selection_active:
"A folder you chose is in use. Use automatic setup first.",
media_runtime_busy:
@@ -402,7 +381,7 @@ const en: Tables = {
reclaim_unsafe: "The earlier copy is still needed, so it was kept.",
setup_busy:
"Another media tools action is running. Try again in a moment.",
setup_job_not_found: "The setup could not be found. Check again.",
internal_failure:
"Something went wrong with the media tools. Check again.",
invalid_request: "The request was not accepted. Check again.",
@@ -698,29 +677,15 @@ const zhTW: Tables = {
pair_admitted: "媒體工具已就緒。",
advanced_override_active: "主機管理員的媒體工具設定正在生效。",
already_available: "媒體工具已可使用。",
installed: "已安裝媒體工具。",
archive_invalid: "下載的檔案已損壞,請重新安裝。",
cancelled: "已取消安裝。",
digest_mismatch: "下載內容與預期的檔案不符,請重新安裝。",
size_mismatch: "下載內容與預期的檔案不符,請重新安裝。",
verification_failed: "無法驗證已安裝的媒體工具,請重新安裝。",
download_failed: "下載失敗,請重新安裝。",
download_timeout: "下載耗時過久,請重新安裝。",
network_timeout: "下載耗時過久,請重新安裝。",
network_unavailable: "網路無法使用,請檢查連線後重新安裝。",
egress_refused: "下載位址遭拒,請稍後再試。",
redirect_refused: "下載位址遭拒,請稍後再試。",
tls_failed: "無法與下載來源建立安全連線,請稍後再試。",
source_unavailable: "下載來源目前無法使用,請稍後再試。",
insufficient_space: "磁碟空間不足,無法安裝媒體工具。",
permission_denied: "媒體工具資料夾無法寫入。",
publication_failed: "無法將媒體工具放置到位,請重新安裝。",
local_selection_active: "目前正在使用您選擇的資料夾,請先改用自動設定。",
media_runtime_busy: "媒體工具正在使用中,請在目前工作完成後再試。",
runtime_busy: "媒體工具正在使用中,請在目前工作完成後再試。",
reclaim_unsafe: "較早的副本仍然需要,因此已保留。",
setup_busy: "另一個媒體工具動作正在執行,請稍後再試。",
setup_job_not_found: "找不到此安裝作業,請再次檢查。",
internal_failure: "媒體工具發生錯誤,請再次檢查。",
invalid_request: "要求未被接受,請再次檢查。",
media_type_rejected: "要求未被接受,請再次檢查。",
@@ -1007,29 +972,15 @@ const zhCN: Tables = {
pair_admitted: "媒体工具已就绪。",
advanced_override_active: "主机管理员的媒体工具设置正在生效。",
already_available: "媒体工具已可使用。",
installed: "已安装媒体工具。",
archive_invalid: "下载的文件已损坏,请重新安装。",
cancelled: "已取消安装。",
digest_mismatch: "下载内容与预期的文件不符,请重新安装。",
size_mismatch: "下载内容与预期的文件不符,请重新安装。",
verification_failed: "无法验证已安装的媒体工具,请重新安装。",
download_failed: "下载失败,请重新安装。",
download_timeout: "下载耗时过久,请重新安装。",
network_timeout: "下载耗时过久,请重新安装。",
network_unavailable: "网络不可用,请检查连接后重新安装。",
egress_refused: "下载地址被拒绝,请稍后再试。",
redirect_refused: "下载地址被拒绝,请稍后再试。",
tls_failed: "无法与下载来源建立安全连接,请稍后再试。",
source_unavailable: "下载来源当前不可用,请稍后再试。",
insufficient_space: "磁盘空间不足,无法安装媒体工具。",
permission_denied: "媒体工具文件夹无法写入。",
publication_failed: "无法将媒体工具放置到位,请重新安装。",
local_selection_active: "当前正在使用你选择的文件夹,请先改用自动设置。",
media_runtime_busy: "媒体工具正在使用中,请在当前任务完成后再试。",
runtime_busy: "媒体工具正在使用中,请在当前任务完成后再试。",
reclaim_unsafe: "较早的副本仍然需要,因此已保留。",
setup_busy: "另一个媒体工具操作正在运行,请稍后再试。",
setup_job_not_found: "找不到此安装任务,请再次检查。",
internal_failure: "媒体工具发生错误,请再次检查。",
invalid_request: "请求未被接受,请再次检查。",
media_type_rejected: "请求未被接受,请再次检查。",
+29 -128
View File
@@ -1,17 +1,8 @@
// the fail-closed decoder for the media runtime status (v3) and setup job (v1) wires.
//
// Every key set is exact and every enumerated value is closed. An unknown value is a typed decode
// failure, which the surface shows as "status unavailable" and never as ready: a newer server
// vocabulary must not be read as a capability this client cannot describe. The closed lists below
// are pinned against the server's own vocabularies by `tests/fixtures/media_runtime_wire_v3.json`,
// which the backend suite regenerates from the service and this suite decodes.
// Closed manual media-tool status/request contracts. Unknown keys and vocabulary fail closed.
export const MEDIA_RUNTIME_STATUS_SCHEMA =
"h3.context.media_runtime_status.v3" as const;
export const MEDIA_RUNTIME_JOB_SCHEMA =
"h3.context.media_runtime_setup_job.v1" as const;
"h3.context.media_runtime_status.v4" as const;
export const MEDIA_RUNTIME_REQUEST_SCHEMA =
"h3.context.media_runtime_setup_request.v1" as const;
"h3.context.media_runtime_setup_request.v2" as const;
const RESOLUTION_SCHEMA = "h3.context.media_runtime_resolution.v1";
export const MEDIA_RUNTIME_RESOLUTION_STATES = [
@@ -70,64 +61,15 @@ export const MEDIA_RUNTIME_FEATURE_REASONS = [
"render_qualification_unavailable",
] as const;
export const MEDIA_RUNTIME_ACTIONS = [
"install_supported",
"rescan",
"use_local_directory",
"restore_auto",
"cancel_setup",
"reclaim_parked_runtime",
] as const;
export const MEDIA_RUNTIME_JOB_STATES = [
"running",
"succeeded",
"failed",
"cancelled",
export const MEDIA_RUNTIME_RECOVERY_STATES = [
"parked_runtime",
"abandoned_setup",
] as const;
export const MEDIA_RUNTIME_JOB_PHASES = [
"checking",
"downloading",
"extracting",
"verifying",
"publishing",
"activating",
"done",
] as const;
export const MEDIA_RUNTIME_JOB_REASONS = [
...MEDIA_RUNTIME_RESOLUTION_REASONS,
"advanced_override_active",
"already_available",
"archive_invalid",
"cancelled",
"config_conflict",
"config_invalid",
"config_write_failed",
"digest_mismatch",
"download_failed",
"download_timeout",
"egress_refused",
"installed",
"insufficient_space",
"internal_failure",
"invalid_request",
"local_selection_active",
"media_runtime_busy",
"network_timeout",
"network_unavailable",
"permission_denied",
"publication_failed",
"reclaim_unsafe",
"redirect_refused",
"runtime_busy",
"selection_invalid_path",
"selection_unsupported_pair",
"setup_busy",
"size_mismatch",
"source_unavailable",
"tls_failed",
"verification_failed",
"write_failed",
] as const;
export const MEDIA_RUNTIME_RECOVERY_STATES = ["parked_runtime"] as const;
export const MEDIA_RUNTIME_REFUSAL_CODES = [
"config_conflict",
"config_corrupt",
@@ -146,7 +88,6 @@ export const MEDIA_RUNTIME_REFUSAL_CODES = [
"selection_invalid_path",
"selection_unsupported_pair",
"setup_busy",
"setup_job_not_found",
"unsupported_host",
"unsupported_platform",
"worker_failure",
@@ -158,22 +99,9 @@ export type MediaRuntimeFeatureState =
export type MediaRuntimeFeatureReason =
(typeof MEDIA_RUNTIME_FEATURE_REASONS)[number];
export type MediaRuntimeAction = (typeof MEDIA_RUNTIME_ACTIONS)[number];
export type MediaRuntimeJobState = (typeof MEDIA_RUNTIME_JOB_STATES)[number];
export type MediaRuntimeJobPhase = (typeof MEDIA_RUNTIME_JOB_PHASES)[number];
export type MediaRuntimeJobReason = (typeof MEDIA_RUNTIME_JOB_REASONS)[number];
export type MediaRuntimeRefusalCode =
(typeof MEDIA_RUNTIME_REFUSAL_CODES)[number];
export type MediaRuntimeJob = Readonly<{
schema: typeof MEDIA_RUNTIME_JOB_SCHEMA;
jobId: string;
state: MediaRuntimeJobState;
phase: MediaRuntimeJobPhase;
reason: MediaRuntimeJobReason | null;
completedBytes: number;
totalBytes: number;
}>;
export type MediaRuntimeFeatureReadiness = Readonly<{
state: MediaRuntimeFeatureState;
reason: MediaRuntimeFeatureReason | null;
@@ -190,9 +118,9 @@ export type MediaRuntimeStatus = Readonly<{
revision: number;
selection: (typeof MEDIA_RUNTIME_CONFIG_SELECTIONS)[number];
}> | null;
setup: MediaRuntimeJob | null;
install: Readonly<{
profile: string;
manual: Readonly<{
archiveName: string;
archiveSha256: string;
sourceLabel: string;
releasePage: string;
license: string;
@@ -209,8 +137,8 @@ export type MediaRuntimeStatus = Readonly<{
/** Byte counts share the server's canonical integer range and the manifest's archive bound. */
const MAX_BYTES = 2 ** 53 - 1;
const MAX_TEXT = 256;
const JOB_ID = /^[0-9a-f]{32}$/;
const RELEASE_PAGE = /^https:\/\/github\.com\/[A-Za-z0-9._/-]{1,200}$/;
const RELEASE_PAGE =
/^https:\/\/github\.com\/GyanD\/codexffmpeg\/releases\/tag\/[A-Za-z0-9._-]{1,100}$/;
export class MediaRuntimeDecodeError extends Error {
constructor() {
@@ -264,47 +192,12 @@ function count(value: unknown): number {
return value as number;
}
export function decodeMediaRuntimeJob(value: unknown): MediaRuntimeJob {
const wire = record(value, [
"schema",
"job_id",
"state",
"phase",
"reason",
"progress",
]);
if (wire.schema !== MEDIA_RUNTIME_JOB_SCHEMA) invalid();
if (typeof wire.job_id !== "string" || !JOB_ID.test(wire.job_id)) invalid();
const state = member(wire.state, MEDIA_RUNTIME_JOB_STATES);
const phase = member(wire.phase, MEDIA_RUNTIME_JOB_PHASES);
const reason =
wire.reason === null
? null
: member(wire.reason, MEDIA_RUNTIME_JOB_REASONS);
// A running job has no terminal reason yet, and a terminal job always names one.
if ((state === "running") !== (reason === null)) invalid();
const progress = record(wire.progress, ["completed_bytes", "total_bytes"]);
const completedBytes = count(progress.completed_bytes);
const totalBytes = count(progress.total_bytes);
if (totalBytes > 0 && completedBytes > totalBytes) invalid();
return Object.freeze({
schema: MEDIA_RUNTIME_JOB_SCHEMA,
jobId: wire.job_id,
state,
phase,
reason,
completedBytes,
totalBytes,
});
}
export function decodeMediaRuntimeStatus(value: unknown): MediaRuntimeStatus {
const wire = record(value, [
"schema",
"resolution",
"config",
"setup",
"install",
"manual",
"features",
"recovery",
"actions",
@@ -325,15 +218,23 @@ export function decodeMediaRuntimeStatus(value: unknown): MediaRuntimeStatus {
selection: member(raw.selection, MEDIA_RUNTIME_CONFIG_SELECTIONS),
});
}
const install = record(wire.install, [
"profile",
const manual = record(wire.manual, [
"archive_name",
"archive_sha256",
"source_label",
"release_page",
"license",
"approximate_bytes",
]);
const releasePage = text(install.release_page);
const releasePage = text(manual.release_page);
if (!RELEASE_PAGE.test(releasePage)) invalid();
const archiveName = text(manual.archive_name);
const archiveSha256 = text(manual.archive_sha256);
if (
!/^ffmpeg-[A-Za-z0-9._-]{1,100}-full_build\.zip$/.test(archiveName) ||
!/^[0-9a-f]{64}$/.test(archiveSha256)
)
invalid();
const rawFeatures = record(wire.features, MEDIA_RUNTIME_FEATURES);
const features = {} as Record<
MediaRuntimeFeature,
@@ -376,13 +277,13 @@ export function decodeMediaRuntimeStatus(value: unknown): MediaRuntimeStatus {
sourceKind: member(resolution.source_kind, MEDIA_RUNTIME_SOURCE_KINDS),
}),
config,
setup: wire.setup === null ? null : decodeMediaRuntimeJob(wire.setup),
install: Object.freeze({
profile: text(install.profile),
sourceLabel: text(install.source_label),
manual: Object.freeze({
archiveName,
archiveSha256,
sourceLabel: text(manual.source_label),
releasePage,
license: text(install.license),
approximateBytes: count(install.approximate_bytes),
license: text(manual.license),
approximateBytes: count(manual.approximate_bytes),
}),
features: Object.freeze(features),
recovery,
+12 -49
View File
@@ -1,18 +1,10 @@
// the same-origin client for the / media runtime status, setup and job routes.
//
// Nothing here throws. Every outcome is typed: a decoded status or job, or a closed failure code.
// A POST whose response is lost or unreadable carries `outcomeUnknown`, because the server may have
// started the job; the session then re-reads status and adopts the running job instead of sending
// the action again. The client sends only a closed action name, a job id, one directory string
// and a config revision.
// Same-origin offline selection client. Lost mutations are reconciled by a read, never resent.
import {
MEDIA_RUNTIME_REQUEST_SCHEMA,
decodeMediaRuntimeJob,
decodeMediaRuntimeStatus,
isMediaRuntimeRefusalCode,
type MediaRuntimeAction,
type MediaRuntimeJob,
type MediaRuntimeRefusalCode,
type MediaRuntimeStatus,
} from "../contracts/mediaRuntimeCodec";
@@ -22,7 +14,6 @@ export const MEDIA_RUNTIME_STATUS_ROUTE =
export const MEDIA_RUNTIME_SETUP_ROUTE =
"/h3-context/v1/media-runtime/setup" as const;
const MAX_RESPONSE_CHARS = 16 * 1024;
const JOB_ID = /^[0-9a-f]{32}$/;
export type MediaRuntimeClientCode =
| MediaRuntimeRefusalCode
@@ -41,11 +32,7 @@ export type MediaRuntimeClientFailure = Readonly<{
export type MediaRuntimeStatusResult =
| Readonly<{ ok: true; status: MediaRuntimeStatus }>
| MediaRuntimeClientFailure;
export type MediaRuntimeJobResult =
Readonly<{ ok: true; job: MediaRuntimeJob }> | MediaRuntimeClientFailure;
export type MediaRuntimeActionPayload = Readonly<{
jobId?: string;
directory?: string;
expectedRevision?: number;
}>;
@@ -99,19 +86,15 @@ function requestBody(
): Record<string, unknown> | undefined {
const envelope = { schema: MEDIA_RUNTIME_REQUEST_SCHEMA, action };
switch (action) {
case "install_supported":
case "rescan":
case "reclaim_parked_runtime":
return envelope;
case "cancel_setup":
return payload.jobId !== undefined && JOB_ID.test(payload.jobId)
? { ...envelope, job_id: payload.jobId }
: undefined;
case "use_local_directory":
return typeof payload.directory === "string" &&
payload.directory.length > 0 &&
payload.directory.length <= 4096 &&
Number.isSafeInteger(payload.expectedRevision)
Number.isSafeInteger(payload.expectedRevision) &&
(payload.expectedRevision ?? -1) >= 0
? {
...envelope,
directory: payload.directory,
@@ -119,7 +102,8 @@ function requestBody(
}
: undefined;
case "restore_auto":
return Number.isSafeInteger(payload.expectedRevision)
return Number.isSafeInteger(payload.expectedRevision) &&
(payload.expectedRevision ?? -1) >= 0
? { ...envelope, expected_revision: payload.expectedRevision }
: undefined;
}
@@ -169,30 +153,11 @@ export function createMediaRuntimeClient({
: result;
},
async readJob(
jobId: string,
signal?: AbortSignal,
): Promise<MediaRuntimeJobResult> {
if (!JOB_ID.test(jobId)) return failure("invalid_request", false);
const result = await read(
`${MEDIA_RUNTIME_SETUP_ROUTE}/${jobId}`,
decodeMediaRuntimeJob,
signal,
);
return result.ok
? Object.freeze({ ok: true, job: result.value })
: result;
},
/**
* `install_supported` and `cancel_setup` answer with the job; every other action answers with
* the refreshed status.
*/
async send(
action: MediaRuntimeAction,
payload: MediaRuntimeActionPayload,
signal?: AbortSignal,
): Promise<MediaRuntimeStatusResult | MediaRuntimeJobResult> {
): Promise<MediaRuntimeStatusResult> {
const request = requestBody(action, payload);
if (request === undefined) return failure("invalid_request", false);
let response: Response;
@@ -206,13 +171,13 @@ export function createMediaRuntimeClient({
});
} catch (error) {
// CRITICAL: the request may have left the browser. Only a status re-read may decide
// whether the job started; resending would be a second click the user never made.
// whether the selection changed; resending would be a second click the user never made.
return failure(
aborted(error, signal) ? "aborted" : "transport_failure",
true,
);
}
const expected = action === "install_supported" ? 202 : 200;
const expected = 200;
if (response.status !== expected) {
if (response.status >= 200 && response.status < 300)
return failure("unexpected_status", true);
@@ -220,12 +185,10 @@ export function createMediaRuntimeClient({
}
try {
const value = await body(response);
return action === "install_supported" || action === "cancel_setup"
? Object.freeze({ ok: true, job: decodeMediaRuntimeJob(value) })
: Object.freeze({
ok: true,
status: decodeMediaRuntimeStatus(value),
});
return Object.freeze({
ok: true,
status: decodeMediaRuntimeStatus(value),
});
} catch {
return failure("malformed_response", true);
}
+24 -358
View File
@@ -1,51 +1,30 @@
// Media tools session: status reads, the one setup job, and the validated continuation of
// the user action a setup interrupted.
//
// Reads happen only when someone can use them: the first Settings open, a contextual surface that
// reports a runtime refusal, and a 1 s job poll that stops at the terminal state or on release.
// A continuation runs the original action once, and only after every identity it captured still
// holds. Nothing here queues, submits a workflow, uploads or starts a render.
// Manual selection session. Runtime readiness never retries a media action for the user.
import type {
MediaRuntimeAction,
MediaRuntimeFeature,
MediaRuntimeJob,
MediaRuntimeStatus,
} from "../contracts/mediaRuntimeCodec";
import type {
MediaRuntimeActionPayload,
MediaRuntimeJobResult,
MediaRuntimeStatusResult,
} from "../host/mediaRuntimeClient";
import {
MEDIA_RUNTIME_INTENT_FEATURE,
initialMediaRuntimeState,
intentIdentity,
type MediaRuntimeIntent,
type MediaRuntimeNotice,
type MediaRuntimeState,
type MediaToolsBinding,
} from "../state/mediaRuntimeState";
import type { ShellRuntime } from "./shellSession";
export const MEDIA_RUNTIME_POLL_INTERVAL_MS = 1_000;
/** Consecutive unreadable job polls before the surface reports status unavailable. */
export const MEDIA_RUNTIME_MAX_POLL_FAILURES = 30;
/** Status re-reads while a just-installed feature is still activating. */
/** Status re-reads while a newly selected feature is still activating. */
export const MEDIA_RUNTIME_MAX_ACTIVATION_READS = 10;
export type MediaRuntimeLeaveScope = "page" | "function" | "overlay";
export function createMediaRuntimeSession(ctx: ShellRuntime) {
const { session, deps, actions } = ctx;
// IMPORTANT: every asynchronous result checks the generation it started under. Release bumps
// it, so a late status, job or action response cannot repopulate a released view or continue
// an action the user has already walked away from.
// IMPORTANT: release advances generation; late reads or mutations cannot repopulate a released view.
let generation = 0;
let readAbort: AbortController | undefined;
let pollTimer: ReturnType<typeof setTimeout> | undefined;
let pollingJob: string | undefined;
let resumeToken = 0;
/** The status each feature's report last read, so a remount does not read it again. */
const explained = new Map<MediaRuntimeFeature, MediaRuntimeStatus | null>();
@@ -80,15 +59,7 @@ export function createMediaRuntimeSession(ctx: ShellRuntime) {
}
function adoptStatus(wire: MediaRuntimeStatus): void {
const running = wire.setup?.state === "running" ? wire.setup : null;
patch({
status: "read",
wire,
job: wire.setup ?? state().job,
refusal: null,
});
// A job started by another tab or before a lost response is shared, never started again.
if (running !== null) startPolling(running.jobId);
patch({ status: "read", wire, refusal: null });
}
/** First Settings open: one read, then only what later actions return. */
@@ -100,7 +71,7 @@ export function createMediaRuntimeSession(ctx: ShellRuntime) {
/** A contextual surface was refused by the runtime; learn why unless something already says. */
function mediaRuntimeReport(feature: MediaRuntimeFeature): void {
const current = state();
if (current.status === "reading" || pollingJob !== undefined) return;
if (current.status === "reading") return;
// IMPORTANT: a surface remounts its card every time it re-reads its own capability, so a
// report must not re-read a status that already explains the refusal: a feature the status
// says is not ready, a status this feature's report already read, or a failed read (which
@@ -164,331 +135,34 @@ export function createMediaRuntimeSession(ctx: ShellRuntime) {
).catch(() => undefined);
}
// ------------------------------------------------------------------ job polling
function stopPolling(): void {
if (pollTimer !== undefined) clearTimeout(pollTimer);
pollTimer = undefined;
pollingJob = undefined;
}
function startPolling(jobId: string): void {
if (pollingJob === jobId) return;
stopPolling();
pollingJob = jobId;
const owned = generation;
let failures = 0;
const tick = async (): Promise<void> => {
pollTimer = undefined;
if (owned !== generation || pollingJob !== jobId) return;
const result: MediaRuntimeJobResult =
await deps.mediaRuntimeClient.readJob(jobId);
if (owned !== generation || pollingJob !== jobId) return;
if (result.ok) {
failures = 0;
patch({ job: result.job });
if (result.job.state === "running") {
pollTimer = setTimeout(tick, MEDIA_RUNTIME_POLL_INTERVAL_MS);
return;
}
pollingJob = undefined;
await settleJob(result.job);
return;
}
if (result.code === "setup_job_not_found") {
pollingJob = undefined;
// The server no longer knows the job (a host restart); keeping it would leave the card
// installing forever, because a status without `setup` never replaces the session's job.
patch({ job: null });
await readStatus();
return;
}
failures += 1;
if (failures >= MEDIA_RUNTIME_MAX_POLL_FAILURES) {
pollingJob = undefined;
patch({ status: "unavailable", refusal: result.code });
return;
}
pollTimer = setTimeout(tick, MEDIA_RUNTIME_POLL_INTERVAL_MS);
};
pollTimer = setTimeout(tick, MEDIA_RUNTIME_POLL_INTERVAL_MS);
}
async function settleJob(job: MediaRuntimeJob): Promise<void> {
const owned = generation;
const status = await readStatus();
if (owned !== generation || status === null) return;
const pending = state().pending;
if (job.state === "cancelled") {
patch({
pending: null,
notice: pending === null ? state().notice : "continuation_cleared",
focusPrimary: focusPrimary(),
});
return;
}
if (job.state !== "succeeded") {
// The continuation stays: Install again resumes the same action if it still holds.
patch({ focusPrimary: focusPrimary() });
return;
}
if (pending === null) return;
// The binding is published before consumers finish attaching, so a feature can report
// `activating` for a moment after a successful install. Wait for it, boundedly.
const settled = await settledStatus(
MEDIA_RUNTIME_INTENT_FEATURE[pending.kind],
status,
owned,
);
if (owned !== generation || settled === null) return;
continueIntent(settled);
}
// ------------------------------------------------------------------ continuation
function productionProjection() {
return "projection" in session.productionState
? session.productionState.projection
: undefined;
}
function overlayStillOpen(generationValue: number): boolean {
const surface = session.nleWorkspace.surface;
return (
surface.status === "expanded" && surface.generation === generationValue
);
}
/** Whether every identity the intent captured still holds right now. */
function revalidate(intent: MediaRuntimeIntent): boolean {
switch (intent.kind) {
case "production_import": {
const production = productionProjection();
const importStatus = session.nleWorkspace.import.status;
return (
production !== undefined &&
deps.pageRegistry.getSnapshot().selected === "production" &&
production.workspaceHandle === intent.productionWorkspaceHandle &&
production.workspaceId === intent.productionWorkspaceId &&
production.allowedActions.includes(
"import_production_outputs_to_authoring",
) &&
importStatus !== "importing" &&
importStatus !== "ensuring_target" &&
importStatus !== "uncertain" &&
// IMPORTANT: a generated segment can advance the project revision while
// setup is running. The selected ready outputs are the import authority; pinning the
// revision here discards that still-valid action after every automatic append.
production.selectedSegmentIds.length === intent.segmentIds.length &&
production.selectedSegmentIds.every(
(segmentId, index) => segmentId === intent.segmentIds[index],
) &&
intent.segmentIds.every(
(segmentId, index) =>
production.outputs.find(
(row) => row.segmentId === segmentId && row.state === "ready",
)?.outputHandle === intent.outputHandles[index],
)
);
}
case "clip_preview": {
const authoring = session.authoringState;
const projection =
"projection" in authoring ? authoring.projection : undefined;
return (
projection !== undefined &&
projection.workspaceHandle === intent.workspaceHandle &&
projection.reference.revision === intent.referenceRevision &&
projection.timeline.revision === intent.timelineRevision &&
projection.timeline.contentFingerprint ===
intent.timelineContentFingerprint &&
projection.timeline.clips.some(
(clip) => clip.clipId === intent.clipId,
) &&
(intent.overlayGeneration === null ||
overlayStillOpen(intent.overlayGeneration))
);
}
case "final_render": {
const authoring = session.authoringState;
const historyV2 =
"timelineHistoryV2" in authoring
? authoring.timelineHistoryV2
: undefined;
const receiptV2 =
"lastTimelineReceiptV2" in authoring
? authoring.lastTimelineReceiptV2
: undefined;
const snapshot =
historyV2 !== undefined
? (historyV2.renderSnapshot ?? undefined)
: receiptV2 !== undefined
? (receiptV2.renderSnapshot ?? undefined)
: (("timelineHistory" in authoring
? authoring.timelineHistory?.snapshot
: undefined) ??
("lastTimelineReceipt" in authoring
? authoring.lastTimelineReceipt?.snapshot
: undefined));
return (
snapshot !== undefined &&
snapshot.workspaceHandle === intent.workspaceHandle &&
snapshot.workspaceRevision === intent.workspaceRevision &&
snapshot.timelineRevision === intent.timelineRevision &&
snapshot.publicFingerprint === intent.publicFingerprint &&
overlayStillOpen(intent.overlayGeneration)
);
}
}
}
function continueIntent(status: MediaRuntimeStatus): void {
const intent = state().pending;
if (intent === null) return;
const feature = MEDIA_RUNTIME_INTENT_FEATURE[intent.kind];
if (status.features[feature].state !== "ready") {
patch({
pending: null,
notice: "feature_not_ready",
focusPrimary: focusPrimary(),
});
return;
}
if (!revalidate(intent)) {
patch({
pending: null,
notice: "select_again",
focusPrimary: focusPrimary(),
});
return;
}
// CRITICAL: clear the continuation before running it. Running first would let a render that
// the action itself triggers observe the same pending intent and run it a second time.
resumeToken += 1;
patch({
pending: null,
notice: "continued",
resume: Object.freeze({
kind: intent.kind,
token: resumeToken,
identity: intentIdentity(intent),
}),
});
if (intent.kind === "production_import")
void Promise.resolve(
actions.nleImportSelectedOutputs(intent.segmentIds),
).catch(() => undefined);
else if (intent.kind === "final_render")
void Promise.resolve(
actions.nleReadRenderCapability(intent.overlayGeneration),
).catch(() => undefined);
// `clip_preview` is reopened by the one monitor whose identity matches `resume.identity`.
}
function recordPending(intent: MediaRuntimeIntent | null): void {
if (intent === null) return;
const current = state().pending;
if (current !== null && intentIdentity(current) === intentIdentity(intent))
return;
patch({
pending: intent,
notice: current === null ? null : "continuation_replaced",
});
}
function clearPending(notice: MediaRuntimeNotice = "continuation_cleared") {
if (state().pending === null) return;
patch({ pending: null, notice, focusPrimary: focusPrimary() });
}
/** Leaving a continuation's context drops it; nothing continues somewhere the user left. */
function mediaRuntimeLeaveContext(scope: MediaRuntimeLeaveScope): void {
const pending = state().pending;
if (pending === null) return;
const overlayBound =
pending.kind === "final_render" ||
(pending.kind === "clip_preview" && pending.overlayGeneration !== null);
if (
scope === "page" ||
(scope === "overlay" && overlayBound) ||
(scope === "function" && !overlayBound)
)
clearPending();
}
// ------------------------------------------------------------------ actions
async function mediaRuntimeInstall(
intent: MediaRuntimeIntent | null,
): Promise<void> {
const current = state();
// IMPORTANT: a second click while the first request is in flight is not a second install.
if (current.busy !== null) return;
recordPending(intent);
if (current.job?.state === "running") {
startPolling(current.job.jobId);
return;
}
const owned = generation;
patch({ busy: "install_supported", notice: null, refusal: null });
const result = await deps.mediaRuntimeClient.send("install_supported", {});
if (owned !== generation) return;
patch({ busy: null });
if (!result.ok) {
if (result.outcomeUnknown) {
const status = await readStatus();
if (owned !== generation) return;
if (status?.setup?.state !== "running")
patch({ notice: "outcome_unknown", focusPrimary: focusPrimary() });
return;
}
patch({ refusal: result.code, focusPrimary: focusPrimary() });
if (result.code === "setup_busy") await readStatus();
return;
}
if (!("job" in result)) return;
patch({ job: result.job });
if (result.job.state === "running") startPolling(result.job.jobId);
else await settleJob(result.job);
}
async function mediaRuntimeCancel(): Promise<void> {
const job = state().job;
if (job === null || job.state !== "running" || state().busy !== null)
return;
const owned = generation;
patch({
busy: "cancel_setup",
pending: null,
notice:
state().pending === null ? state().notice : "continuation_cleared",
});
const result = await deps.mediaRuntimeClient.send("cancel_setup", {
jobId: job.jobId,
});
if (owned !== generation) return;
patch({
busy: null,
...(result.ok && "job" in result
? { job: result.job }
: { refusal: result.ok ? null : result.code }),
focusPrimary: focusPrimary(),
});
}
async function statusAction(
action: Exclude<MediaRuntimeAction, "install_supported" | "cancel_setup">,
action: MediaRuntimeAction,
payload: MediaRuntimeActionPayload = {},
): Promise<void> {
if (state().busy !== null) return;
// CRITICAL: a read begun before this mutation must not overwrite its newer config revision.
readAbort?.abort();
readAbort = undefined;
const owned = generation;
patch({ busy: action, refusal: null });
const result: MediaRuntimeStatusResult | MediaRuntimeJobResult =
await deps.mediaRuntimeClient.send(action, payload);
const result: MediaRuntimeStatusResult = await deps.mediaRuntimeClient.send(
action,
payload,
);
if (owned !== generation) return;
patch({ busy: null });
if (result.ok && "status" in result) {
adoptStatus(result.status);
patch({ notice: "retry_action", focusPrimary: focusPrimary() });
// IMPORTANT: refresh a capability only; choosing tools must never import, preview or render.
const surface = session.nleWorkspace.surface;
if (
surface.status === "expanded" &&
result.status.features.render.state === "ready"
)
void Promise.resolve(
actions.nleReadRenderCapability(surface.generation),
).catch(() => undefined);
return;
}
patch({
@@ -522,12 +196,11 @@ export function createMediaRuntimeSession(ctx: ShellRuntime) {
void statusAction("restore_auto", { expectedRevision: revision });
}
/** View release: stop polling, drop requests and continuations, keep nothing. */
/** Release owns every outstanding response. */
function releaseMediaRuntime(): void {
generation += 1;
readAbort?.abort();
readAbort = undefined;
stopPolling();
explained.clear();
session.mediaRuntime = initialMediaRuntimeState;
}
@@ -535,10 +208,6 @@ export function createMediaRuntimeSession(ctx: ShellRuntime) {
const bindingFunctions = Object.freeze({
ensure: mediaRuntimeEnsureStatus,
report: mediaRuntimeReport,
install: (intent: MediaRuntimeIntent | null) =>
void mediaRuntimeInstall(intent),
cancel: () => void mediaRuntimeCancel(),
// Dismissing a notice is acknowledgement only; the continuation, if any, is kept.
dismiss: () => {
if (state().notice !== null) patch({ notice: null });
},
@@ -554,10 +223,7 @@ export function createMediaRuntimeSession(ctx: ShellRuntime) {
}
return {
mediaRuntimeCancel,
mediaRuntimeEnsureStatus,
mediaRuntimeInstall,
mediaRuntimeLeaveContext,
mediaRuntimeReclaim,
mediaRuntimeReport,
mediaRuntimeRescan,
@@ -390,7 +390,7 @@ export function createNleWorkspaceSession(ctx: ShellRuntime) {
if (surface.status !== "opening" && surface.status !== "expanded") return;
stopSequencePolling();
releaseCapabilityRead();
actions.mediaRuntimeLeaveContext("overlay");
// Close cancels only unaccepted local pointer/transport work; accepted commands stay.
patch({
surface: Object.freeze({
@@ -228,7 +228,7 @@ export function createPresentationBinding(ctx: ShellRuntime) {
if (current === id) return;
// programmatic or user navigation closes an expanded editor before the transition.
actions.nleCloseOverlay("top_level_navigation");
actions.mediaRuntimeLeaveContext("page");
actions.workspaceStateLeave?.();
actions.retainedAssetsLeave?.();
actions.perceptionHostLeave?.();
@@ -310,7 +310,6 @@ export function createPresentationBinding(ctx: ShellRuntime) {
onOpen: actions.nleOpenOverlay,
onStartAuthoring: () => void actions.nleStartAuthoring(),
onFunctionChange: () => {
actions.mediaRuntimeLeaveContext("function");
actions.nleCloseOverlay("function_switch");
},
requestedFunction: session.nleWorkspace.functionRequest,
+1 -56
View File
@@ -7,7 +7,6 @@
import type {
MediaRuntimeAction,
MediaRuntimeFeature,
MediaRuntimeJob,
MediaRuntimeStatus,
} from "../contracts/mediaRuntimeCodec";
import type { MediaRuntimeClientCode } from "../host/mediaRuntimeClient";
@@ -50,30 +49,14 @@ export const MEDIA_RUNTIME_INTENT_FEATURE: Readonly<
final_render: "render",
});
export type MediaRuntimeNotice =
| "continued"
| "select_again"
| "continuation_cleared"
| "continuation_replaced"
| "feature_not_ready"
| "outcome_unknown";
export type MediaRuntimeResume = Readonly<{
kind: MediaRuntimeIntentKind;
token: number;
/** `intentIdentity` of the continued intent, so exactly the matching surface reacts. */
identity: string;
}>;
export type MediaRuntimeNotice = "retry_action";
export type MediaRuntimeState = Readonly<{
status: "unread" | "reading" | "read" | "unavailable";
wire: MediaRuntimeStatus | null;
job: MediaRuntimeJob | null;
pending: MediaRuntimeIntent | null;
busy: MediaRuntimeAction | null;
refusal: MediaRuntimeClientCode | null;
notice: MediaRuntimeNotice | null;
resume: MediaRuntimeResume | null;
/** Bumped when focus returns to the card's primary control. */
focusPrimary: number;
}>;
@@ -81,55 +64,17 @@ export type MediaRuntimeState = Readonly<{
export const initialMediaRuntimeState: MediaRuntimeState = Object.freeze({
status: "unread",
wire: null,
job: null,
pending: null,
busy: null,
refusal: null,
notice: null,
resume: null,
focusPrimary: 0,
});
/** A stable, content-free key over an intent's captured identity. */
export function intentIdentity(intent: MediaRuntimeIntent): string {
switch (intent.kind) {
case "production_import":
return JSON.stringify([
intent.kind,
intent.productionWorkspaceHandle,
intent.productionWorkspaceId,
intent.segmentIds,
intent.outputHandles,
]);
case "clip_preview":
return JSON.stringify([
intent.kind,
intent.workspaceHandle,
intent.referenceRevision,
intent.timelineRevision,
intent.timelineContentFingerprint,
intent.clipId,
intent.overlayGeneration,
]);
case "final_render":
return JSON.stringify([
intent.kind,
intent.workspaceHandle,
intent.workspaceRevision,
intent.timelineRevision,
intent.publicFingerprint,
intent.overlayGeneration,
]);
}
}
/** What every surface receives; the functions are stable for the session's lifetime. */
export type MediaToolsBinding = Readonly<{
state: MediaRuntimeState;
ensure(): void;
report(feature: MediaRuntimeFeature): void;
install(intent: MediaRuntimeIntent | null): void;
cancel(): void;
dismiss(): void;
rescan(): void;
reclaim(): void;
+66 -154
View File
@@ -1,221 +1,136 @@
// a stateful route double for the media runtime status, setup and job routes, shared by
// every page of one test so two pages observe the same single job exactly as the backend holds
// one. Every wire it serves is a sample the backend suite regenerates from the service
// (`frontend/tests/fixtures/media_runtime_wire_v3.json`), adjusted only in the fields a transition
// changes. It also answers the output capability read and the clip preview route for the
// contextual rows, so "installed" is the one fact that flips them.
// Stateful offline route double over backend-generated manual setup samples.
import { readFileSync } from "node:fs";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import type { Page, Route } from "@playwright/test";
import { OUTPUT_CAPABILITY } from "../../../src/contracts/authoringOutputCodec";
type Json = Record<string, unknown>;
type Features = Record<string, { state: string; reason: string | null }>;
const ROOT = fileURLToPath(new URL("../../../../", import.meta.url));
const FIXTURE = JSON.parse(
readFileSync(
join(ROOT, "frontend/tests/fixtures/media_runtime_wire_v3.json"),
join(ROOT, "frontend/tests/fixtures/media_runtime_wire_v4.json"),
"utf8",
),
) as { samples: Record<string, Json> };
const PREVIEW_MEDIA = readFileSync(
join(ROOT, "tests/fixtures/m25_12_runtime/cfr-primary.mp4"),
);
const JOB_ID = "abababababababababababababababab";
const STATUS_PATH = "/h3-context/v1/media-runtime";
const SETUP_PATH = "/h3-context/v1/media-runtime/setup";
const SETUP_PATH = `${STATUS_PATH}/setup`;
const CAPABILITY_PATH = "/h3-context/v1/authoring/output-capability";
const PREVIEW_PATH = "/h3-context/v1/authoring/media-preview";
const clone = <T>(value: T): T => JSON.parse(JSON.stringify(value)) as T;
export type RuntimeDoubleOptions = Readonly<{
/** `ready` starts with managed tools; `recovery` adds a reclaimable parked tree. */
initial?: "missing" | "ready" | "recovery";
/** Job polls before the job settles; `Infinity` holds it until `finish()`. */
polls?: number;
/** How the job settles. */
outcome?: "succeeded" | "failed";
/** Final output stays unavailable for a host reason installing cannot repair. */
renderUnqualified?: boolean;
/** Start the job, then drop the install reply on the floor (a lost response). */
loseInstallReply?: boolean;
/**
* The host's first-use shape: tools are present, but final output reports unsupported
* until the first status read activates the runtime in process.
*/
activateOnStatusRead?: boolean;
conflict?: boolean;
loseSelectionReply?: boolean;
}>;
export type RuntimeDouble = Readonly<{
attach(page: Page): Promise<void>;
/** Settles a held job now. */
finish(): void;
counts(): Readonly<{
statusReads: number;
jobReads: number;
installPosts: number;
cancelPosts: number;
reclaimPosts: number;
capabilityReads: number;
previewRequests: number;
}>;
installed(): boolean;
}>;
export function createRuntimeDouble(
options: RuntimeDoubleOptions = {},
): RuntimeDouble {
const polls = options.polls ?? 2;
let installed = options.initial === "ready" || options.initial === "recovery";
export function createRuntimeDouble(options: RuntimeDoubleOptions = {}) {
let ready = options.initial === "ready" || options.initial === "recovery";
let parked = options.initial === "recovery";
let job: Json | null = null;
let jobPolls = 0;
let releaseHeld = false;
let local = false;
let revision = 0;
const counts = {
statusReads: 0,
jobReads: 0,
installPosts: 0,
cancelPosts: 0,
localPosts: 0,
rescanPosts: 0,
restorePosts: 0,
reclaimPosts: 0,
capabilityReads: 0,
previewRequests: 0,
retiredRequests: 0,
};
const running = () => job !== null && job.state === "running";
function settle(): void {
if (!running()) return;
const failed = options.outcome === "failed";
job = {
...job!,
state: failed ? "failed" : "succeeded",
phase: "done",
reason: failed ? "digest_mismatch" : "installed",
progress: { completed_bytes: 0, total_bytes: 0 },
};
if (!failed) installed = true;
}
function status(): Json {
const wire = clone(
FIXTURE.samples[
installed ? "status_ready_recovery" : "status_setup_required"
]!,
);
wire.setup = job === null ? null : clone(job);
const wire = JSON.parse(
JSON.stringify(
FIXTURE.samples[
ready ? "status_ready_recovery" : "status_setup_required"
],
),
) as Json;
wire.recovery = parked
? { state: "parked_runtime", reclaimable: true }
: null;
const features = wire.features as Features;
if (installed && options.renderUnqualified)
features.render = {
wire.config = { revision, selection: local ? "local" : "auto" };
if (local) (wire.resolution as Json).source_kind = "local_selection";
if (ready && options.renderUnqualified)
(wire.features as Record<string, Json>).render = {
state: "unavailable",
reason: "render_qualification_unavailable",
};
wire.actions = running()
? ["cancel_setup"]
: installed
? [
"rescan",
"use_local_directory",
...(parked ? ["reclaim_parked_runtime"] : []),
]
: ["install_supported", "rescan", "use_local_directory"];
wire.actions = [
"rescan",
"use_local_directory",
...(local ? ["restore_auto"] : []),
...(parked ? ["reclaim_parked_runtime"] : []),
];
return wire;
}
const json = (route: Route, statusCode: number, body: unknown) =>
const json = (route: Route, code: number, body: unknown) =>
route.fulfill({
status: statusCode,
status: code,
contentType: "application/json",
body: JSON.stringify(body),
});
async function handle(route: Route): Promise<void> {
const request = route.request();
const path = new URL(request.url()).pathname;
if (path === STATUS_PATH && request.method() === "GET") {
counts.statusReads += 1;
counts.statusReads++;
return json(route, 200, status());
}
if (path === `${SETUP_PATH}/${JOB_ID}` && request.method() === "GET") {
counts.jobReads += 1;
if (job === null)
return json(route, 404, { error: "setup_job_not_found" });
if (running()) {
jobPolls += 1;
job = {
...job,
phase: jobPolls > 1 ? "verifying" : "downloading",
progress: {
completed_bytes: Math.min(jobPolls, 4) * 50_000_000,
total_bytes: 246_558_061,
},
};
if (releaseHeld || jobPolls >= polls) settle();
}
return json(route, 200, job);
}
if (path === SETUP_PATH && request.method() === "POST") {
const body = request.postDataJSON() as {
schema: string;
action: string;
job_id?: string;
directory?: string;
expected_revision?: number;
};
if (body.action === "install_supported") {
counts.installPosts += 1;
if (!running()) {
jobPolls = 0;
releaseHeld = false;
job = {
schema: "h3.context.media_runtime_setup_job.v1",
job_id: JOB_ID,
state: "running",
phase: "checking",
reason: null,
progress: { completed_bytes: 0, total_bytes: 0 },
};
}
if (options.loseInstallReply && counts.installPosts === 1)
return route.abort("connectionreset");
return json(route, 202, job);
}
if (body.action === "cancel_setup") {
counts.cancelPosts += 1;
if (running())
job = {
...job!,
state: "cancelled",
phase: "done",
reason: "cancelled",
progress: { completed_bytes: 0, total_bytes: 0 },
};
return json(route, 200, job);
}
if (body.action === "reclaim_parked_runtime") {
counts.reclaimPosts += 1;
if (body.schema !== "h3.context.media_runtime_setup_request.v2")
return json(route, 400, { error: "invalid_request" });
if (body.action === "use_local_directory") {
counts.localPosts++;
if (options.conflict || body.expected_revision !== revision)
return json(route, 409, { error: "config_conflict" });
if (body.directory !== "C:/media-tools/bin")
return json(route, 422, { error: "selection_unsupported_pair" });
local = true;
ready = true;
revision++;
if (options.loseSelectionReply) return route.abort("connectionreset");
} else if (body.action === "rescan") {
counts.rescanPosts++;
} else if (body.action === "restore_auto") {
counts.restorePosts++;
local = false;
revision++;
} else if (body.action === "reclaim_parked_runtime") {
counts.reclaimPosts++;
parked = false;
return json(route, 200, status());
} else {
counts.retiredRequests++;
return json(route, 400, { error: "invalid_request" });
}
return json(route, 200, status());
}
if (path.startsWith(`${SETUP_PATH}/`)) {
counts.retiredRequests++;
return json(route, 404, { error: "not_found" });
}
if (path === CAPABILITY_PATH) {
counts.capabilityReads += 1;
return json(route, 200, {
...OUTPUT_CAPABILITY,
supported:
installed &&
ready &&
!options.renderUnqualified &&
(!options.activateOnStatusRead || counts.statusReads > 0),
});
}
if (path === PREVIEW_PATH) {
counts.previewRequests += 1;
if (!installed) {
if (!ready) {
const body = JSON.stringify({
schema: "h3.context.authoring_source_preview.error.v1",
requestId: null,
@@ -254,10 +169,7 @@ export function createRuntimeDouble(
await page.route("**/h3-context/v1/authoring/output-capability", handle);
await page.route("**/h3-context/v1/authoring/media-preview", handle);
},
finish() {
releaseHeld = true;
},
counts: () => ({ ...counts }),
installed: () => installed,
});
}
export type RuntimeDouble = ReturnType<typeof createRuntimeDouble>;
+19
View File
@@ -99,6 +99,25 @@ export type SerializedGraph = {
* show, because only a real host announces a configure back to its extensions.
*/
export async function instrumentHostGraphLoads(page: Page): Promise<void> {
// CRITICAL: extension registration precedes workflow-store initialization on a cold host.
// Wait for its authority contract before capture; a longer graph-settle sleep cannot fix it.
await page.waitForFunction(
() => {
const store = (window as any).comfyAPI?.app?.app?.extensionManager
?.workflow;
const active = store?.activeWorkflow;
return (
Array.isArray(store?.openWorkflows) &&
((active === null && store.openWorkflows.length === 0) ||
(active !== null &&
typeof active === "object" &&
!Array.isArray(active) &&
store.openWorkflows.includes(active)))
);
},
undefined,
{ timeout: 30_000 },
);
await page.evaluate(() => {
const runtime = window as unknown as {
comfyAPI: { app: { app: any } };
@@ -14,11 +14,14 @@ import { expect, test, type Page } from "../../host/fixture";
import { diffGraphSurroundings } from "../../../support/surroundingsDiff";
import {
decodeAuthoringProjection,
decodeTimelineHistoryProjection,
decodeTimelineHistoryProjectionV2,
NLE_AUTHORING_SCHEMA,
NLE_AUTHORING_PROFILE_ID,
encodeAuthoringAction,
} from "../../../../src/contracts/authoringWorkbenchCodec";
import {
decodeProductionAuthoringImportResponseV1,
decodeProductionAuthoringImportResponse,
PRODUCTION_AUTHORING_IMPORT_RESPONSE_SCHEMA_V2,
encodeProductionAuthoringImportRequest,
} from "../../../../src/contracts/productionAuthoringImportCodec";
import {
@@ -34,8 +37,15 @@ import {
type OutputStatus,
} from "../../../../src/contracts/authoringOutputCodec";
import { decodeSidebarWorkspaceProjection } from "../../../../src/contracts/sidebarWorkspaceCodec";
import {
NLE_AUTHORING_ASSET_LEASE_REQUEST_SCHEMA,
AUTHORING_MEDIA_LEASE_GEOMETRY_HEADER,
decodeAuthoringMediaGeometry,
} from "../../../../src/contracts/authoringMediaLeaseCodec";
import { sidebarCopy } from "../../../../src/i18n/catalog";
import {
assertCandidateBundleInjection,
appModeQueueDiagnostic,
awaitHostExecution,
beginSettledH3InteractionPhase,
candidateBackendMode,
@@ -57,6 +67,15 @@ import {
watchHostExecution,
} from "../../host/environment";
// CRITICAL: the current editor uses content-extent history/import v2. A legacy v1 decoder
// rejects real initialization before the manual setup journey can verify preview or render.
function decodeImportedProduction(value: unknown) {
const response = decodeProductionAuthoringImportResponse(value);
if (response.schema !== PRODUCTION_AUTHORING_IMPORT_RESPONSE_SCHEMA_V2)
throw new Error("the current host import must return content-extent v2");
return response;
}
type M2548ArtifactLocator = Readonly<{
filename: string;
subfolder: "h3-context-m25-48-fixtures";
@@ -143,14 +162,13 @@ async function postHostAction(
}
// the same causal import, run on a host whose media tools were never configured.
// `ready` asserts the tools are found without setup; `install` starts from missing tools and
// continues the refused import through the Media tools card's one Install and continue click,
// then renders the imported clip. Unset keeps the AC11 row unchanged.
// `ready` uses the discovered pair; `local` selects existing pinned tools, retries import explicitly
// and renders the imported clip. Unset keeps the ordinary row unchanged.
const mediaJourney = process.env.H3_CONTEXT_M25_34_MEDIA_JOURNEY;
const expectedMediaSource = process.env.H3_CONTEXT_M25_34_EXPECTED_SOURCE;
// The install journey always renders; a ready journey renders when asked (the restart row).
// The local journey always renders; a ready journey renders when asked (the restart row).
const renderJourney =
mediaJourney === "install" ||
mediaJourney === "local" ||
(mediaJourney === "ready" && process.env.H3_CONTEXT_M25_34_RENDER === "1");
const ux14Journey = process.env.H3_CONTEXT_M25_56_UX14;
const installedCandidateInventory =
@@ -158,9 +176,9 @@ const installedCandidateInventory =
if (
mediaJourney !== undefined &&
mediaJourney !== "ready" &&
mediaJourney !== "install"
mediaJourney !== "local"
)
throw new Error("H3_CONTEXT_M25_34_MEDIA_JOURNEY must be ready or install");
throw new Error("H3_CONTEXT_M25_34_MEDIA_JOURNEY must be ready or local");
if (mediaJourney === "ready" && expectedMediaSource === undefined)
throw new Error("the ready media journey names its expected source");
if (ux14Journey !== undefined && ux14Journey !== "1")
@@ -200,10 +218,7 @@ type MediaRuntimeStatusSample = Readonly<{
features: Readonly<Record<string, string>>;
reasons: Readonly<Record<string, string>>;
actions: readonly string[];
// The install descriptor is on the wire in every state; only the `install_supported` action is
// the offer, so evidence records the two separately.
installDescribed: boolean;
setupRunning: boolean;
manualDescribed: boolean;
}>;
async function readMediaRuntimeStatus(
@@ -232,11 +247,9 @@ async function readMediaRuntimeStatus(
features,
reasons,
actions: Array.isArray(wire.actions) ? wire.actions.map(String) : [],
installDescribed:
wire.install !== null &&
typeof wire.install === "object" &&
Number(wire.install.approximate_bytes) > 0,
setupRunning: wire.setup?.state === "running",
manualDescribed:
typeof wire.manual?.archive_sha256 === "string" &&
Number(wire.manual?.approximate_bytes) > 0,
};
}
@@ -496,8 +509,8 @@ test(productionImportHostTitle, async ({ context, page }, testInfo) => {
candidateBackendMode !== "exact",
"M25-48 requires its explicit prepared fixture and an exact installed candidate",
);
// The install journey downloads and verifies the fixed archive on the host, then renders.
test.setTimeout((mediaJourney === "install" ? 40 : 10) * 60_000);
// The local journey selects an already present verified pair, then renders the retried import.
test.setTimeout((mediaJourney === "local" ? 40 : 10) * 60_000);
if (hostUrl === undefined) throw new Error("H3_CONTEXT_HOST_URL is required");
const queueBefore = await supportedHostQueueCounts(page);
@@ -585,8 +598,14 @@ test(productionImportHostTitle, async ({ context, page }, testInfo) => {
mediaLeaseControls.push(
Object.freeze({
operation: String(body?.operation ?? ""),
scope: body?.scope,
clipId: body?.clipId,
scope:
body?.schema === NLE_AUTHORING_ASSET_LEASE_REQUEST_SCHEMA
? "asset"
: body?.scope,
clipId:
body?.schema === NLE_AUTHORING_ASSET_LEASE_REQUEST_SCHEMA
? null
: body?.clipId,
derivativeKind: body?.derivativeKind,
status: response.status(),
}),
@@ -866,12 +885,45 @@ test(productionImportHostTitle, async ({ context, page }, testInfo) => {
const submit = container.locator('[data-h3-focus-key="app-submit"]');
await expect(submit).toBeEnabled({ timeout: 30_000 });
const fromSubmission = (await sampleProgress(page)).submitted;
// CRITICAL: a cold Start prepares the canvas without execution; only the subsequent
// explicit Queue current graph action reaches the projector and model-free host queue.
await submit.click();
await expect
.poll(async () => (await sampleProgress(page, fromSubmission)).started, {
timeout: 180_000,
})
.toBe(1);
await expect(submit).toHaveText(sidebarCopy("en").queueCurrentGraph, {
timeout: 30_000,
});
await expect(submit).toBeEnabled();
expect((await sampleProgress(page)).submitted).toBe(fromSubmission);
await submit.click();
try {
await expect
.poll(async () => (await sampleProgress(page, fromSubmission)).started, {
timeout: 180_000,
})
.toBe(1);
} catch (error) {
const diagnostic = await appModeQueueDiagnostic(
page,
"h3-context-m23-32-terminal-waiting",
"__h3QueueCount",
);
console.info(
"HOST_MEDIA_START_DIAGNOSTIC " +
JSON.stringify({
shellStatus: diagnostic.shellStatus,
shellReason: diagnostic.shellReason,
appModeState: diagnostic.appModeState,
appModePhase: diagnostic.appModePhase,
generationBlocker: diagnostic.generationBlocker,
errorClass: diagnostic.errorClass,
graphLoads: diagnostic.graphLoads,
submitDisabled: diagnostic.submitDisabled,
routeCount: routeReceipts.length,
preparationCount: preparations.length,
closeRequestCount: closeRequests.length,
}),
);
throw error;
}
const result = await awaitHostExecution(page, fromSubmission, 180_000);
expect(result.errors).toEqual([]);
expect(reportedArtifactNames(result.outputs)).toEqual([]);
@@ -1218,8 +1270,7 @@ test(productionImportHostTitle, async ({ context, page }, testInfo) => {
Object.fromEntries(MEDIA_FEATURES.map((feature) => [feature, state]));
if (mediaStatusBefore !== null) {
expect(mediaStatusBefore.status).toBe(200);
expect(mediaStatusBefore.schema).toBe("h3.context.media_runtime_status.v3");
expect(mediaStatusBefore.setupRunning).toBe(false);
expect(mediaStatusBefore.schema).toBe("h3.context.media_runtime_status.v4");
}
if (mediaJourney === "ready") {
expect(mediaStatusBefore).toMatchObject({
@@ -1228,9 +1279,9 @@ test(productionImportHostTitle, async ({ context, page }, testInfo) => {
sourceKind: expectedMediaSource,
features: allFeatures("ready"),
});
expect(mediaStatusBefore!.actions).not.toContain("install_supported");
} else if (mediaJourney === "install") {
// Missing tools are installable after an exhaustive search and after one truncated by a long
expect(mediaStatusBefore!.actions).toContain("rescan");
} else if (mediaJourney === "local") {
// Missing tools can be selected after an exhaustive search and after one truncated by a long
// PATH that still examined the managed directory ( B-M2534-01); the reason says which.
expect(["supported_pair_missing", "discovery_limit"]).toContain(
mediaStatusBefore!.resolutionReason,
@@ -1240,9 +1291,9 @@ test(productionImportHostTitle, async ({ context, page }, testInfo) => {
sourceKind: "none",
features: allFeatures("setup_required"),
reasons: allFeatures(mediaStatusBefore!.resolutionReason),
installDescribed: true,
manualDescribed: true,
});
expect(mediaStatusBefore!.actions).toContain("install_supported");
expect(mediaStatusBefore!.actions).toContain("use_local_directory");
}
page.on("response", onResponse);
// IMPORTANT: re-homes Production import into the expanded editor's Media tab. The
@@ -1262,9 +1313,12 @@ test(productionImportHostTitle, async ({ context, page }, testInfo) => {
.poll(() => importWire.length, { timeout: 60_000 })
.toBeGreaterThan(0);
let mediaSetupEvidence: Readonly<Record<string, unknown>> | null = null;
if (mediaJourney === "install") {
// The missing tools refuse the import once; the card beside the refusal offers exactly one
// Install and continue, and the refused import then continues once on the same workspace.
if (mediaJourney === "local") {
// CRITICAL: use an already present pinned pair. The host row never downloads tools and
// selecting a folder never continues the refused import; the original control retries it.
const directory = process.env.H3_CONTEXT_MEDIA_LOCAL_DIRECTORY;
if (!directory)
throw new Error("the local journey requires an existing tool directory");
await expect(
overlay.locator('[data-h3-nle-status="import"]'),
).toHaveAttribute("data-code", "service_unavailable");
@@ -1272,105 +1326,82 @@ test(productionImportHostTitle, async ({ context, page }, testInfo) => {
const card = overlay.locator(
'[data-h3-media-tools-placement="contextual-sidebar"]',
);
await expect(card).toHaveAttribute(
"data-h3-media-tools",
"setup_required",
{
timeout: 60_000,
},
);
const install = card.locator('[data-h3-media-tools-action="primary"]');
await expect(install).toHaveCount(1);
await expect(install).toHaveText("Install and continue");
const visibleInputs = () =>
card.evaluate(
(element) =>
Array.from(
element.querySelectorAll("input, textarea, select"),
).filter((field) => field.checkVisibility()).length,
);
expect(await visibleInputs()).toBe(0);
expect(setupPosts).toEqual([]);
const installStarted = Date.now();
await install.click();
await expect(card).toHaveAttribute("data-h3-media-tools", "installing", {
timeout: 30_000,
});
await expect
.poll(() => importWire.length, { timeout: 30 * 60_000 })
.toBe(2);
const installSeconds = Math.round((Date.now() - installStarted) / 1_000);
expect(setupPosts).toEqual(["install_supported"]);
const [refused, continued] = importWire;
expect(continued!.request.request_id).not.toBe(refused!.request.request_id);
await expect(card).toHaveAttribute("data-h3-media-tools", "setup_required");
await card
.getByRole("textbox", { name: "FFmpeg bin folder" })
.fill(directory);
await card.locator('[data-h3-media-tools-action="primary"]').click();
await expect(card).toHaveCount(0);
expect(setupPosts).toEqual(["use_local_directory"]);
expect(importWire).toHaveLength(1);
await importControl.click();
await expect.poll(() => importWire.length, { timeout: 60_000 }).toBe(2);
const [refused, retried] = importWire;
expect({
...continued!.request,
...retried!.request,
request_id: refused!.request.request_id,
}).toEqual(refused!.request);
const statusAfterInstall = await settledMediaRuntimeStatus(page);
expect(statusAfterInstall).toMatchObject({
const statusAfterSelection = await settledMediaRuntimeStatus(page);
expect(statusAfterSelection).toMatchObject({
resolutionState: "located",
sourceKind: "managed",
sourceKind: "local_selection",
features: allFeatures("ready"),
setupRunning: false,
});
mediaSetupEvidence = Object.freeze({
refusedImportStatus: refused!.status,
refusalCode: "service_unavailable",
cardStateBeforeClick: "setup_required",
primaryActions: 1,
visibleTextInputs: 0,
confirmationClicks: 1,
setupPosts: [...setupPosts],
installSeconds,
continuedImportRequests: 1,
continuedRequestSameWorkspaceAndRevisions: true,
statusAfterInstall: {
resolutionState: statusAfterInstall.resolutionState,
sourceKind: statusAfterInstall.sourceKind,
features: statusAfterInstall.features,
},
refusedImportStatus: 503,
manualSelectionPosts: 1,
automaticRetryRequests: 0,
explicitRetryRequests: 1,
sourceAfterSelection: statusAfterSelection.sourceKind,
});
console.info(
`M25_34_MEDIA_SETUP_EVIDENCE ${JSON.stringify(mediaSetupEvidence)}`,
`MEDIA_MANUAL_SETUP_EVIDENCE ${JSON.stringify(mediaSetupEvidence)}`,
);
}
// IMPORTANT: a refused import cannot publish the follow-up history read. Assert the admitted
// continuation first so a real host rejection remains visible instead of becoming a 60 s wait.
const admittedImport = importWire[importWire.length - 1]!;
expect(admittedImport.status, JSON.stringify(admittedImport.body)).toBe(200);
await expect
.poll(
() =>
authoringWire.filter(
(entry) => entry.action === "read_timeline_history",
).length,
{ timeout: 60_000 },
)
.toBeGreaterThan(0);
page.off("response", onResponse);
// Target creation and history initialization are the shell's separate accepted actions;
// the import is one request; the refresh read follows it. A refused import reads nothing, and
// its continuation reuses the target and history it already created.
expect(authoringWire.map((entry) => entry.action)).toEqual([
// CRITICAL: an explicit import after manual setup re-ensures the same target and reads its
// existing history before importing. Wait for the final refresh, not that pre-import read.
const expectedAuthoringActions = [
"ensure_authoring_from_production",
"initialize_timeline_history",
...(mediaJourney === "local"
? ["ensure_authoring_from_production", "read_timeline_history"]
: []),
"read_timeline_history",
]);
expect(importWire).toHaveLength(mediaJourney === "install" ? 2 : 1);
if (mediaJourney === "install") importWire.shift();
];
await expect
.poll(() => authoringWire.map((entry) => entry.action), {
timeout: 60_000,
})
.toEqual(expectedAuthoringActions);
page.off("response", onResponse);
expect(importWire).toHaveLength(mediaJourney === "local" ? 2 : 1);
if (mediaJourney === "local") importWire.shift();
const ensureEntry = authoringWire[0]!;
expect(ensureEntry.status).toBe(201);
const createdAuthoring = decodeAuthoringProjection(ensureEntry.body);
const initializeEntry = authoringWire[1]!;
expect(initializeEntry.status).toBe(200);
const initializedHistory = decodeTimelineHistoryProjection(
const initializedHistory = decodeTimelineHistoryProjectionV2(
initializeEntry.body,
);
expect(initializedHistory.workspaceHandle).toBe(
createdAuthoring.workspaceHandle,
);
expect(initializedHistory.rejection).toBeNull();
if (mediaJourney === "local") {
expect(authoringWire[2]!.status).toBe(200);
expect(decodeAuthoringProjection(authoringWire[2]!.body)).toEqual(
createdAuthoring,
);
expect(authoringWire[3]!.status).toBe(200);
expect(decodeTimelineHistoryProjectionV2(authoringWire[3]!.body)).toEqual(
initializedHistory,
);
}
const beforeHistory = initializedHistory;
const importRequest = importWire[0]!.request;
expect(importRequest.authoring_workspace_handle).toBe(
@@ -1414,10 +1445,9 @@ test(productionImportHostTitle, async ({ context, page }, testInfo) => {
firstImportResponse.status,
JSON.stringify(firstImportResponse.body),
).toBe(200);
const firstImport = decodeProductionAuthoringImportResponseV1(
firstImportResponse.body,
);
const firstImport = decodeImportedProduction(firstImportResponse.body);
expect(firstImport.receipt.disposition).toBe("created");
expect(firstImport.historyProjection.renderSnapshot).toBeNull();
expect(firstImport.receipt.rows).toEqual([
expect.objectContaining({
segmentId: selectedOutput.segmentId,
@@ -1432,11 +1462,11 @@ test(productionImportHostTitle, async ({ context, page }, testInfo) => {
expect(firstImport.receipt.legacyTimeline.nextRevision).toBe(
firstImport.receipt.legacyTimeline.priorRevision,
);
expect(firstImport.receipt.nle.nextWorkspaceRevision).toBe(
firstImport.receipt.nle.priorWorkspaceRevision + 1,
expect(firstImport.receipt.nleAuthoring.nextWorkspaceRevision).toBe(
firstImport.receipt.nleAuthoring.priorWorkspaceRevision + 1,
);
expect(firstImport.receipt.nle.nextTimelineRevision).toBe(
firstImport.receipt.nle.priorTimelineRevision,
expect(firstImport.receipt.nleAuthoring.nextTimelineRevision).toBe(
firstImport.receipt.nleAuthoring.priorTimelineRevision,
);
const exactReplayResponse = await postHostAction(
@@ -1457,46 +1487,46 @@ test(productionImportHostTitle, async ({ context, page }, testInfo) => {
),
);
expect(afterFirstReadResponse.status).toBe(200);
const afterFirstHistory = decodeTimelineHistoryProjection(
const afterFirstHistory = decodeTimelineHistoryProjectionV2(
afterFirstReadResponse.body,
);
const importedAssetId = firstImport.receipt.rows[0]!.assetId;
const importedOrdinal =
afterFirstHistory.snapshot.assets
afterFirstHistory.authoring.assets
.filter((asset) => asset.kind === "video" || asset.kind === "image")
.findIndex((asset) => asset.assetId === importedAssetId) + 1;
expect(importedOrdinal).toBeGreaterThan(0);
expect(afterFirstHistory.snapshot.assets).toHaveLength(
beforeHistory.snapshot.assets.length + 1,
expect(afterFirstHistory.authoring.assets).toHaveLength(
beforeHistory.authoring.assets.length + 1,
);
expect(
afterFirstHistory.snapshot.assets.some(
afterFirstHistory.authoring.assets.some(
(asset) => asset.assetId === importedAssetId && asset.kind === "video",
),
).toBe(true);
expect(afterFirstHistory.snapshot.workspaceRevision).toBe(
beforeHistory.snapshot.workspaceRevision + 1,
expect(afterFirstHistory.authoring.workspaceRevision).toBe(
beforeHistory.authoring.workspaceRevision + 1,
);
expect(afterFirstHistory.snapshot.workspaceFingerprint).not.toBe(
beforeHistory.snapshot.workspaceFingerprint,
expect(afterFirstHistory.authoring.workspaceFingerprint).not.toBe(
beforeHistory.authoring.workspaceFingerprint,
);
expect(afterFirstHistory.snapshot.publicFingerprint).not.toBe(
beforeHistory.snapshot.publicFingerprint,
expect(afterFirstHistory.authoring.authoringFingerprint).not.toBe(
beforeHistory.authoring.authoringFingerprint,
);
expect(afterFirstHistory.snapshot.timelineRevision).toBe(
beforeHistory.snapshot.timelineRevision,
expect(afterFirstHistory.authoring.timelineRevision).toBe(
beforeHistory.authoring.timelineRevision,
);
expect(afterFirstHistory.snapshot.timelineFingerprint).toBe(
beforeHistory.snapshot.timelineFingerprint,
expect(afterFirstHistory.authoring.timelineFingerprint).toBe(
beforeHistory.authoring.timelineFingerprint,
);
expect(afterFirstHistory.snapshot.tracks).toEqual(
beforeHistory.snapshot.tracks,
expect(afterFirstHistory.authoring.tracks).toEqual(
beforeHistory.authoring.tracks,
);
expect(afterFirstHistory.snapshot.clips).toEqual(
beforeHistory.snapshot.clips,
expect(afterFirstHistory.authoring.clips).toEqual(
beforeHistory.authoring.clips,
);
expect(
afterFirstHistory.snapshot.clips.some(
afterFirstHistory.authoring.clips.some(
(clip) => clip.assetId === importedAssetId,
),
).toBe(false);
@@ -1525,12 +1555,14 @@ test(productionImportHostTitle, async ({ context, page }, testInfo) => {
expectedAuthoringTimelineContentFingerprint:
firstImport.authoringProjection.timeline.contentFingerprint,
expectedNleWorkspaceRevision:
afterFirstHistory.snapshot.workspaceRevision,
expectedNleTimelineRevision: afterFirstHistory.snapshot.timelineRevision,
afterFirstHistory.authoring.workspaceRevision,
expectedNleTimelineRevision: afterFirstHistory.authoring.timelineRevision,
expectedNleTimelineFingerprint:
afterFirstHistory.snapshot.timelineFingerprint,
expectedNlePublicFingerprint:
afterFirstHistory.snapshot.publicFingerprint,
afterFirstHistory.authoring.timelineFingerprint,
authoringSchema: NLE_AUTHORING_SCHEMA,
profileId: NLE_AUTHORING_PROFILE_ID,
expectedNleAuthoringFingerprint:
afterFirstHistory.authoring.authoringFingerprint,
entries: [
{
segmentId: selectedOutput.segmentId!,
@@ -1544,7 +1576,7 @@ test(productionImportHostTitle, async ({ context, page }, testInfo) => {
alreadyImportedRequest,
);
expect(alreadyImportedResponse.status).toBe(200);
const alreadyImported = decodeProductionAuthoringImportResponseV1(
const alreadyImported = decodeImportedProduction(
alreadyImportedResponse.body,
);
expect(alreadyImported.receipt.disposition).toBe("already_imported");
@@ -1568,7 +1600,7 @@ test(productionImportHostTitle, async ({ context, page }, testInfo) => {
),
);
expect(afterReplayReadResponse.status).toBe(200);
const afterReplayHistory = decodeTimelineHistoryProjection(
const afterReplayHistory = decodeTimelineHistoryProjectionV2(
afterReplayReadResponse.body,
);
expect(afterReplayHistory).toEqual(afterFirstHistory);
@@ -1596,12 +1628,13 @@ test(productionImportHostTitle, async ({ context, page }, testInfo) => {
// asset-thumbnail lease contract. Only then insert it as one separate timeline transaction.
// The import was issued from this already-open Media surface.
await expect(overlay).toBeVisible({ timeout: 30_000 });
// IMPORTANT: the v2 bin identifies assets directly; its virtual rows have no ordinal selector.
const importedCard = overlay.locator(
`[data-h3-nle-card-index="${importedOrdinal}"]`,
`[data-h3-nle-asset="${importedAssetId}"]`,
);
await expect(importedCard).toBeVisible();
// IMPORTANT: media cards have no tone contract. Readiness is established by the exact
// thumbnail lease lifecycle and decoded 64 x 64 canvas below; a presentation-only tone
// thumbnail lease lifecycle and decoded wire-bound canvas below; a presentation-only tone
// selector made the supplied-host row impossible before either contract could be observed.
const importedThumbnail = importedCard.locator(
'[data-h3-nle-thumbnail=""]',
@@ -1611,6 +1644,10 @@ test(productionImportHostTitle, async ({ context, page }, testInfo) => {
.poll(() => mediaLeaseControls.length, { timeout: 60_000 })
.toBeGreaterThan(0);
const createResponse = mediaLeaseResponses[0]!;
expect(createResponse.request().postDataJSON()).toMatchObject({
schema: NLE_AUTHORING_ASSET_LEASE_REQUEST_SCHEMA,
assetId: importedAssetId,
});
const createReceipt = (await createResponse.json()) as Record<
string,
unknown
@@ -1654,6 +1691,14 @@ test(productionImportHostTitle, async ({ context, page }, testInfo) => {
status: 200,
},
]);
const thumbnailGeometry = decodeAuthoringMediaGeometry(
await mediaLeaseResponses[1]!.headerValue(
AUTHORING_MEDIA_LEASE_GEOMETRY_HEADER,
),
"thumbnail",
);
if (thumbnailGeometry === null)
throw new Error("the opened thumbnail must bind its decoded geometry");
await expect
.poll(() =>
importedThumbnail.evaluate((canvas) => ({
@@ -1661,7 +1706,10 @@ test(productionImportHostTitle, async ({ context, page }, testInfo) => {
height: (canvas as HTMLCanvasElement).height,
})),
)
.toEqual({ width: 64, height: 64 });
.toEqual({
width: thumbnailGeometry.derivativeWidth,
height: thumbnailGeometry.derivativeHeight,
});
// U08 on the host: before insertion the monitor says the timeline has no clip; it
// never reports the media tools unavailable.
const emptyTimelineNote = overlay.locator('[data-h3-nle-empty="timeline"]');
@@ -1696,26 +1744,26 @@ test(productionImportHostTitle, async ({ context, page }, testInfo) => {
),
);
expect(afterInsertReadResponse.status).toBe(200);
const afterInsertHistory = decodeTimelineHistoryProjection(
const afterInsertHistory = decodeTimelineHistoryProjectionV2(
afterInsertReadResponse.body,
);
expect(afterInsertHistory.snapshot.timelineRevision).toBe(
afterFirstHistory.snapshot.timelineRevision + 1,
expect(afterInsertHistory.authoring.timelineRevision).toBe(
afterFirstHistory.authoring.timelineRevision + 1,
);
expect(
afterInsertHistory.snapshot.clips.filter(
afterInsertHistory.authoring.clips.filter(
(clip) => clip.assetId === importedAssetId,
),
).toHaveLength(1);
expect(afterInsertHistory.snapshot.assets).toEqual(
afterFirstHistory.snapshot.assets,
expect(afterInsertHistory.authoring.assets).toEqual(
afterFirstHistory.authoring.assets,
);
if (mediaJourney !== undefined)
await expect(emptyTimelineNote).toHaveCount(0);
if (renderJourney) {
// U03: the tools installed a moment ago decode the clip in the monitor and render
// the final video, which the browser then decodes. A job status alone proves neither.
const insertedClip = afterInsertHistory.snapshot.clips.find(
const insertedClip = afterInsertHistory.authoring.clips.find(
(clip) => clip.assetId === importedAssetId,
)!;
const monitorCanvas = overlay.locator(".h3-nle-monitor canvas");
@@ -1732,8 +1780,8 @@ test(productionImportHostTitle, async ({ context, page }, testInfo) => {
colors++;
return colors;
});
// The fixed host fixture is 64 x 64 and is sampled once per 16 pixels. Sixteen lit samples
// prove a decoded picture while remaining below the measured 30-sample sparse frame.
// Sample the decoded canvas every sixteen pixels; require a visible picture rather than
// treating a successful lease or a nonzero canvas size alone as playback evidence.
const minimumDecodedPixelSamples = 16;
const seekFrame = insertedClip.startFrame + 12;
const seek = overlay.locator('[data-h3-nle-control="transport.seek"]');
@@ -1748,9 +1796,36 @@ test(productionImportHostTitle, async ({ context, page }, testInfo) => {
"aria-valuetext",
/^\d{2,}:\d{2}:\d{2}:\d{2}$/,
);
await expect
.poll(pixels, { timeout: 60_000 })
.toBeGreaterThanOrEqual(minimumDecodedPixelSamples);
try {
await expect
.poll(pixels, { timeout: 60_000 })
.toBeGreaterThanOrEqual(minimumDecodedPixelSamples);
} catch (error) {
console.info(
`MEDIA_MONITOR_DIAGNOSTIC ${JSON.stringify({
canvas: await monitorCanvas.evaluate((element) => {
const canvas = element as HTMLCanvasElement;
const rect = canvas.getBoundingClientRect();
return {
width: canvas.width,
height: canvas.height,
displayWidth: rect.width,
displayHeight: rect.height,
presentedFrame: canvas.getAttribute(
"data-h3-nle-presented-frame",
),
};
}),
seekFrame,
keptFrame: await seek.getAttribute("aria-valuenow"),
monitor: await overlay
.locator('[data-h3-nle-status="monitor"]')
.textContent(),
leases: mediaLeaseControls,
})}`,
);
throw error;
}
const monitorColors = await pixels();
if (ux14Journey === "1") {
const monitorStatus = overlay.locator('[data-h3-nle-status="monitor"]');
@@ -1926,9 +2001,12 @@ test(productionImportHostTitle, async ({ context, page }, testInfo) => {
frames: rendered.frame_count,
rate: "24/1",
});
// Content, judged by the observer ffmpeg against the imported source file itself: inside
// the clip the rendered picture's centre carries the source's luma; after the clip ends it
// does not. The centre crop lies inside the clip for any fit of the square source.
// CRITICAL: content-extent rendering ends with the last clip, so a legacy fixed-capacity
// black-tail sample is outside the output. Check the exact extent and actual source pixels.
expect(rendered.frame_count).toBe(
afterInsertHistory.authoring.contentEndExclusive,
);
// The centre crop lies inside the clip for any fit of the square source.
const observerFfmpeg = process.env.H3_CONTEXT_M25_34_OBSERVER_FFMPEG;
const sourceMedia = process.env.H3_CONTEXT_M25_34_SOURCE_MEDIA;
if (observerFfmpeg === undefined || sourceMedia === undefined)
@@ -1985,18 +2063,14 @@ test(productionImportHostTitle, async ({ context, page }, testInfo) => {
return Number(match[1]);
};
const insideFrame = insertedClip.startFrame + 12;
const afterFrame =
insertedClip.startFrame + insertedClip.durationFrames + 24;
expect(afterFrame).toBeLessThan(rendered.frame_count);
expect(insideFrame).toBeLessThan(rendered.frame_count);
const sourceLuma = meanLuma(
sourceMedia,
insertedClip.sourceStartFrame + 12,
lumaCropSide,
);
const insideLuma = meanLuma(originalPath, insideFrame, lumaCropSide);
const afterLuma = meanLuma(originalPath, afterFrame, lumaCropSide);
expect(Math.abs(insideLuma - sourceLuma)).toBeLessThanOrEqual(4);
expect(Math.abs(afterLuma - sourceLuma)).toBeGreaterThan(20);
await download.delete();
renderEvidence = Object.freeze({
monitorSeekFrame: seekFrame,
@@ -2018,10 +2092,9 @@ test(productionImportHostTitle, async ({ context, page }, testInfo) => {
},
contentLuma: {
insideFrame,
afterFrame,
contentEndExclusive: afterInsertHistory.authoring.contentEndExclusive,
source: sourceLuma,
inside: insideLuma,
after: afterLuma,
},
});
console.info(
@@ -2230,11 +2303,11 @@ test(productionImportHostTitle, async ({ context, page }, testInfo) => {
firstImport.receipt.legacyTimeline.nextRevision -
firstImport.receipt.legacyTimeline.priorRevision,
nleWorkspaceRevisionDelta:
firstImport.receipt.nle.nextWorkspaceRevision -
firstImport.receipt.nle.priorWorkspaceRevision,
firstImport.receipt.nleAuthoring.nextWorkspaceRevision -
firstImport.receipt.nleAuthoring.priorWorkspaceRevision,
nleTimelineRevisionDelta:
firstImport.receipt.nle.nextTimelineRevision -
firstImport.receipt.nle.priorTimelineRevision,
firstImport.receipt.nleAuthoring.nextTimelineRevision -
firstImport.receipt.nleAuthoring.priorTimelineRevision,
tracksStable: true,
clipsStable: true,
selectionStable: true,
@@ -2324,8 +2397,8 @@ test(productionImportHostTitle, async ({ context, page }, testInfo) => {
});
expect(importEvidence).not.toBeNull();
if (mediaJourney === "ready") expect(setupPosts).toEqual([]);
if (mediaJourney === "install")
expect(setupPosts).toEqual(["install_supported"]);
if (mediaJourney === "local")
expect(setupPosts).toEqual(["use_local_directory"]);
if (renderJourney) expect(renderEvidence).not.toBeNull();
if (ux14Journey === "1") expect(ux14Evidence).not.toBeNull();
@@ -2404,9 +2477,10 @@ test(productionImportHostTitle, async ({ context, page }, testInfo) => {
resolutionReason: mediaStatusBefore!.resolutionReason,
sourceKind: mediaStatusBefore!.sourceKind,
features: mediaStatusBefore!.features,
installDescribed: mediaStatusBefore!.installDescribed,
installActionOffered:
mediaStatusBefore!.actions.includes("install_supported"),
manualDescribed: mediaStatusBefore!.manualDescribed,
localSelectionOffered: mediaStatusBefore!.actions.includes(
"use_local_directory",
),
},
setupPosts: [...setupPosts],
setup: mediaSetupEvidence,
@@ -1,581 +1,216 @@
// AC33-02/03/04/06/09: the Media tools card on the REAL integrated shell
// (frontend/e2e/nleShell.tsx, `mediaSetup=1`). The media runtime status, setup and job routes, the
// output capability read and the clip preview route are answered by one stateful double per test
// (`helpers/mediaRuntimeDouble.ts`) whose wires are the backend-generated v3 samples; import
// requests reach the real import service (`scripts/_import_fixture.py`). Every row drives a
// real transition -- a click or a key, a poll, a settled job -- and reads the outcome from the
// product's own session and request counters, never from a seeded state.
import { test, expect, type Locator, type Page } from "@playwright/test";
import {
createRuntimeDouble,
type RuntimeDouble,
type RuntimeDoubleOptions,
} from "../helpers/mediaRuntimeDouble";
import { test, expect, type Page } from "@playwright/test";
import { createRuntimeDouble } from "../helpers/mediaRuntimeDouble";
import { openIntegratedShell, shellSnapshot } from "../helpers/nleShell";
import { openExportPanel } from "../helpers/nleExport";
import {
startImportFixture,
expectImportBootstrap,
type ImportFixture,
} from "../helpers/nleImportFixture";
import { openExportPanel } from "../helpers/nleExport";
import { openIntegratedShell, shellSnapshot } from "../helpers/nleShell";
const settingsCard = '[data-h3-media-tools-placement="settings"]';
const sidebarCard = '[data-h3-media-tools-placement="contextual-sidebar"]';
const overlayCard = '[data-h3-media-tools-placement="contextual-overlay"]';
const primary = '[data-h3-media-tools-action="primary"]';
const cancel = '[data-h3-media-tools-action="cancel"]';
const importButton = '[data-h3-nle-control="asset.import_production"]';
const editor = '[data-h3-nle-surface="overlay_v1"]';
// The sidebar mount is `min(100%, 704px)`; a 704 px viewport puts every row at the design floor.
test.use({ viewport: { width: 704, height: 900 }, deviceScaleFactor: 1 });
const mediaRuntime = async (page: Page) =>
(await shellSnapshot(page)).mediaRuntime;
/**
* re-homed the Production import into the full editor's Media pane (B-M2561-01): the
* Production page's Clip editor function opens the editor, and the import control and its Media
* tools card live in that pane.
*/
async function openImportPane(page: Page): Promise<void> {
await page
.getByRole("navigation", { name: "H3 Context pages" })
.getByRole("button", { name: "Production" })
.click();
await page.getByRole("tab", { name: "Clip editor" }).click();
await page.locator('[data-h3-nle-entry="open"]').click();
await expect(page.locator(editor)).toBeVisible();
await page.locator('[data-h3-nle-pane="assets"]').click();
for (const locale of ["en", "zh-TW", "zh-CN"]) {
test(`manual setup ${locale}: visible selection, checksum, retry and comparable captures`, async ({
page,
context,
}) => {
await context.grantPermissions(["clipboard-read", "clipboard-write"]);
const double = createRuntimeDouble();
await double.attach(page);
await page.goto(`/nleShell.html?mediaSetup=1&locale=${locale}`);
await page.locator('nav.h3n button[data-page-id="settings"]').click();
const card = page.locator(settingsCard);
await expect(card).toHaveAttribute("data-h3-media-tools", "setup_required");
await expect(card.locator("input")).toBeVisible();
await expect(card.locator(primary)).toBeDisabled();
const beforeHelp = double.counts();
const help = card.locator('[data-h3-media-tools-action="help"]');
await help.focus();
await help.press("Enter");
const panel = card.locator("[data-h3-media-tools-help]");
await expect(panel).toBeVisible();
await expect(help).toHaveAttribute("aria-expanded", "true");
await expect(panel).toContainText("certutil -hashfile <file> SHA256");
await expect(panel).toContainText("Get-FileHash -Algorithm SHA256");
const releasePage = await card
.locator('[data-h3-media-tools-action="download"]')
.getAttribute("href");
expect(releasePage).toMatch(
/^https:\/\/github\.com\/GyanD\/codexffmpeg\/releases\/tag\/[^/]+$/,
);
await expect(panel).toContainText(releasePage!.split("/").at(-1)!);
const checksum = await card
.locator("[data-h3-media-tools-sha]")
.innerText();
await expect(panel).toContainText(checksum);
if (process.env.MEDIA_SETUP_CAPTURE)
await card.screenshot({
path: `${process.env.MEDIA_SETUP_CAPTURE}/help-settings-${locale}.png`,
});
await panel.press("Escape");
await expect(panel).toHaveCount(0);
await expect(help).toBeFocused();
await help.press("Space");
await card.locator('[data-h3-media-tools-action="close-help"]').click();
await expect(help).toBeFocused();
// Only the user's new tab navigates. No request is delegated to the local node.
await context.route(releasePage!, (route) =>
route.fulfill({
status: 200,
contentType: "text/html",
body: "<title>Release page navigation double</title>",
}),
);
const popupReady = page.waitForEvent("popup");
await card.locator('[data-h3-media-tools-action="download"]').click();
const popup = await popupReady;
await popup.waitForLoadState("domcontentloaded");
expect(popup.url()).toBe(releasePage);
expect(await popup.evaluate(() => window.opener === null)).toBe(true);
await popup.close();
expect(double.counts()).toEqual(beforeHelp);
if (process.env.MEDIA_SETUP_CAPTURE)
await card.screenshot({
path: `${process.env.MEDIA_SETUP_CAPTURE}/current-settings-${locale}.png`,
});
await card.locator('[data-h3-media-tools-action="copy"]').click();
expect(await page.evaluate(() => navigator.clipboard.readText())).toBe(
checksum,
);
await card.locator("input").fill("C:/media-tools/bin");
await card.locator(primary).click();
await expect(card).toHaveAttribute("data-h3-media-tools", "ready");
expect(double.counts().localPosts).toBe(1);
await card.locator("details summary").click();
await card.locator("details button").click();
expect(double.counts().restorePosts).toBe(1);
expect((await shellSnapshot(page)).queuedPrompts).toBe(0);
// A fresh missing pair gives the same before/after inline placement and viewport.
const inlineDouble = createRuntimeDouble();
await inlineDouble.attach(page);
await openIntegratedShell(page, "smoke", {
extraParams: { mediaSetup: "1", locale },
expandOverlay: false,
});
await page
.locator("#root")
.getByRole("button", { name: "Open full editor" })
.click();
await openExportPanel(page);
const inline = page.locator(overlayCard);
await expect(inline).toHaveAttribute(
"data-h3-media-tools",
"setup_required",
);
const inlineHelp = inline.locator('[data-h3-media-tools-action="help"]');
await inlineHelp.focus();
await inlineHelp.press("Enter");
await expect(inline.locator("[data-h3-media-tools-help]")).toBeVisible();
if (process.env.MEDIA_SETUP_CAPTURE)
await inline.screenshot({
path: `${process.env.MEDIA_SETUP_CAPTURE}/help-inline-${locale}.png`,
});
expect(await inline.evaluate((e) => e.scrollWidth <= e.clientWidth)).toBe(
true,
);
await inline.locator("[data-h3-media-tools-help]").press("Escape");
await expect(inlineHelp).toBeFocused();
await expect(page.locator("[data-h3-nle-root]")).toBeVisible();
if (process.env.MEDIA_SETUP_CAPTURE)
await inline.screenshot({
path: `${process.env.MEDIA_SETUP_CAPTURE}/current-inline-${locale}.png`,
});
expect(await inline.evaluate((e) => e.scrollWidth <= e.clientWidth)).toBe(
true,
);
await inline.locator("input").fill("C:/media-tools/bin");
await inline.locator(primary).click();
await expect(
page.locator('[data-h3-nle-render="available"]'),
).toBeVisible();
expect((await shellSnapshot(page)).renderJobRequests).toBe(0);
expect(inlineDouble.counts().retiredRequests).toBe(0);
});
}
/** The editor is modal: the Sidebar under it is reachable only once it is closed. */
async function closeEditor(page: Page): Promise<void> {
await page.locator(editor).locator('[data-h3-nle-action="close"]').click();
await expect(page.locator(editor)).toHaveCount(0);
}
async function openSettings(page: Page): Promise<Locator> {
test("stale config is refused without installation work", async ({ page }) => {
const double = createRuntimeDouble({ conflict: true });
await double.attach(page);
await page.goto("/nleShell.html?mediaSetup=1");
await page.locator('nav.h3n button[data-page-id="settings"]').click();
const card = page.locator(settingsCard);
await expect(card).toBeVisible();
return card;
}
async function openShell(
page: Page,
double: RuntimeDouble,
params: Record<string, string> = {},
): Promise<void> {
await double.attach(page);
await page.goto(
`/nleShell.html?${new URLSearchParams({ mediaSetup: "1", ...params })}`,
);
}
async function focusKey(page: Page): Promise<string | null> {
return page.evaluate(
() =>
document.activeElement?.getAttribute("data-h3-focus-key") ??
document.activeElement?.tagName ??
null,
);
}
async function noHorizontalOverflow(page: Page, card: Locator): Promise<void> {
const widths = await card.evaluate((element) => ({
card: [element.scrollWidth, element.clientWidth],
page: [
document.documentElement.scrollWidth,
document.documentElement.clientWidth,
],
}));
expect(widths.card[0]).toBeLessThanOrEqual(widths.card[1]!);
expect(widths.page[0]).toBeLessThanOrEqual(widths.page[1]!);
}
test.describe("Settings", () => {
const LOCALES = [
{
locale: "en",
install: "Install",
release: "Release page",
advanced: "Advanced",
ready: "Media tools are ready.",
},
{
locale: "zh-TW",
install: "安裝",
release: "發行頁面",
advanced: "進階",
ready: "媒體工具已就緒。",
},
{
locale: "zh-CN",
install: "安装",
release: "发布页面",
advanced: "高级",
ready: "媒体工具已就绪。",
},
] as const;
for (const row of LOCALES) {
test(`${row.locale}: one Install by keyboard, polite progress with focus, then ready at 704 px`, async ({
page,
}) => {
const double = createRuntimeDouble({ polls: 3 });
await openShell(page, double, { locale: row.locale });
const card = await openSettings(page);
await expect(card).toHaveAttribute(
"data-h3-media-tools",
"setup_required",
);
await expect(card.locator(primary)).toHaveCount(1);
await expect(card.locator(primary)).toHaveText(row.install);
const link = card.getByRole("link", { name: row.release });
await expect(link).toHaveAttribute("rel", "noopener noreferrer");
await expect(link).toHaveAttribute("target", "_blank");
// No text input on the normal path: the folder field is behind a closed disclosure.
const advanced = card.locator("details.h3s-mt-advanced");
await expect(advanced).not.toHaveAttribute("open", "");
await expect(advanced.locator("summary")).toHaveText(row.advanced);
await expect(card.locator("input:visible")).toHaveCount(0);
await noHorizontalOverflow(page, card);
expect(double.counts().statusReads).toBe(1);
await card.locator(primary).focus();
await page.keyboard.press("Enter");
await expect(card).toHaveAttribute("data-h3-media-tools", "installing");
const line = card.locator('p.h3s-mt-state[role="status"]');
await expect(line).toHaveAttribute("aria-live", "polite");
await expect.poll(() => focusKey(page)).toBe("settings-media-tools");
await expect(card.locator("progress")).toBeVisible();
await expect(card.locator(cancel)).toBeEnabled();
await noHorizontalOverflow(page, card);
await expect(card).toHaveAttribute("data-h3-media-tools", "ready");
await expect(line).toContainText(row.ready);
await expect(card.locator("progress")).toHaveCount(0);
const counts = double.counts();
expect(counts.installPosts).toBe(1);
expect(counts.jobReads).toBe(3);
await noHorizontalOverflow(page, card);
// The poll stopped at the terminal state.
await page.waitForTimeout(2_500);
expect(double.counts().jobReads).toBe(3);
});
}
test("a failed install names its reason and returns focus to Install again", async ({
page,
}) => {
const double = createRuntimeDouble({ polls: 2, outcome: "failed" });
await openShell(page, double);
const card = await openSettings(page);
await card.locator(primary).click();
await expect(card).toHaveAttribute("data-h3-media-tools", "failed");
await expect(card).toHaveAttribute(
"data-h3-media-tools-reason",
"digest_mismatch",
);
await expect(card.locator(primary)).toHaveText("Install again");
await expect.poll(() => focusKey(page)).toBe("media-tools-primary");
await expect(card.locator("[data-h3-media-tools-source]")).toBeVisible();
expect(double.counts().installPosts).toBe(1);
});
test("cancel returns to setup required with focus on Install and no second job", async ({
page,
}) => {
const double = createRuntimeDouble({ polls: Infinity });
await openShell(page, double);
const card = await openSettings(page);
await card.locator(primary).click();
await expect(card).toHaveAttribute("data-h3-media-tools", "installing");
await card.locator(cancel).click();
await expect(card).toHaveAttribute("data-h3-media-tools", "setup_required");
await expect(card.locator(primary)).toHaveText("Install");
await expect.poll(() => focusKey(page)).toBe("media-tools-primary");
await expect
.poll(async () => (await mediaRuntime(page)).jobState)
.toBe("cancelled");
await page.waitForTimeout(2_500);
const counts = double.counts();
expect(counts.cancelPosts).toBe(1);
expect(counts.installPosts).toBe(1);
expect(double.installed()).toBe(false);
await expect(card).toHaveAttribute("data-h3-media-tools", "setup_required");
});
test("a lost install response adopts the running job without sending it again", async ({
page,
}) => {
const double = createRuntimeDouble({ polls: 2, loseInstallReply: true });
await openShell(page, double);
const card = await openSettings(page);
await card.locator(primary).click();
await expect(card).toHaveAttribute("data-h3-media-tools", "ready");
const counts = double.counts();
expect(counts.installPosts).toBe(1);
// The first read on open, the re-read that found the running job, the read after it settled.
expect(counts.statusReads).toBe(3);
expect((await mediaRuntime(page)).notice).toBeNull();
});
test("two pages share the one running job", async ({ page, context }) => {
const double = createRuntimeDouble({ polls: Infinity });
await openShell(page, double);
const first = await openSettings(page);
await first.locator(primary).click();
await expect(first).toHaveAttribute("data-h3-media-tools", "installing");
const second = await context.newPage();
await openShell(second, double);
const secondCard = await openSettings(second);
await expect(secondCard).toHaveAttribute(
"data-h3-media-tools",
"installing",
);
await expect(secondCard.locator(primary)).toHaveCount(0);
expect((await mediaRuntime(second)).jobId).toBe(
(await mediaRuntime(page)).jobId,
);
double.finish();
await expect(first).toHaveAttribute("data-h3-media-tools", "ready");
await expect(secondCard).toHaveAttribute("data-h3-media-tools", "ready");
expect(double.counts().installPosts).toBe(1);
await second.close();
});
test("a reclaimable earlier copy is removed only by its own action", async ({
page,
}) => {
const double = createRuntimeDouble({ initial: "recovery" });
await openShell(page, double);
const card = await openSettings(page);
await expect(card).toHaveAttribute("data-h3-media-tools", "ready");
const recovery = card.locator("[data-h3-media-tools-recovery]");
await expect(recovery).toBeVisible();
await page.waitForTimeout(1_500);
expect(double.counts().reclaimPosts).toBe(0);
await recovery.getByRole("button", { name: "Remove earlier copy" }).click();
await expect(recovery).toHaveCount(0);
await expect(card).toHaveAttribute("data-h3-media-tools", "ready");
expect(double.counts().reclaimPosts).toBe(1);
expect(double.counts().installPosts).toBe(0);
});
test("a host whose renderer is unavailable is told so and offered no install for it", async ({
page,
}) => {
const double = createRuntimeDouble({
initial: "ready",
renderUnqualified: true,
});
await openShell(page, double);
const card = await openSettings(page);
await expect(card).toHaveAttribute("data-h3-media-tools", "ready");
await expect(
card.locator('[data-h3-media-tools-render="unavailable"]'),
).toBeVisible();
await expect(card.locator(primary)).toHaveCount(0);
});
await card.locator("input").fill("C:/media-tools/bin");
await card.locator(primary).click();
await expect(
card.locator('[data-h3-media-tools-refusal="config_conflict"]'),
).toBeVisible();
expect(double.counts().localPosts).toBe(1);
expect(double.counts().retiredRequests).toBe(0);
});
test.describe("import install-and-continue", () => {
let fixture: ImportFixture | undefined;
test.afterEach(async () => {
await fixture?.close();
fixture = undefined;
test("import selects tools but waits for the user's original retry", async ({
page,
}) => {
const double = createRuntimeDouble();
await double.attach(page);
const fixture = await startImportFixture(page, {
refuse: (kind, index) => (kind === "import" && index === 0 ? 503 : null),
});
async function refusedImport(
page: Page,
options: RuntimeDoubleOptions,
params: Record<string, string> = {},
): Promise<{ double: RuntimeDouble; card: Locator }> {
const double = createRuntimeDouble(options);
fixture = await startImportFixture(page, {
// The first import meets a host without media tools: the real route's bodiless 503.
refuse: (kind, index) => (kind === "import" && index === 0 ? 503 : null),
});
await openShell(page, double, { import: "1", target: "ready", ...params });
try {
await page.goto("/nleShell.html?mediaSetup=1&import=1&target=ready");
await expectImportBootstrap(fixture);
await openImportPane(page);
await expect(page.locator(importButton)).toBeEnabled();
await page.locator(importButton).click();
await expect
.poll(async () => (await shellSnapshot(page)).importRefusal)
.toBe("service_unavailable");
const card = page.locator(sidebarCard);
await page.locator('nav.h3n button[data-page-id="production"]').click();
await page.getByRole("tab", { name: "Clip editor" }).click();
await page.locator('[data-h3-nle-entry="open"]').click();
await page.locator('[data-h3-nle-pane="assets"]').click();
const button = page.locator(
'[data-h3-nle-control="asset.import_production"]',
);
await button.click();
const card = page.locator(
'[data-h3-media-tools-placement="contextual-sidebar"]',
);
await expect(card).toHaveAttribute("data-h3-media-tools", "setup_required");
await expect(card.locator(primary)).toHaveText("Install and continue");
return { double, card };
}
test("a double click installs once and continues the original import exactly once", async ({
page,
}) => {
const { double, card } = await refusedImport(page, { polls: 2 });
await card.locator(primary).dblclick();
await card.locator("input").fill("C:/media-tools/bin");
await card.locator(primary).click();
await expect(card).toHaveCount(0);
expect(fixture.importRequests).toHaveLength(1);
await button.click();
await expect
.poll(async () => (await shellSnapshot(page)).importStatus)
.toBe("succeeded");
const after = await shellSnapshot(page);
expect(after.mediaRuntime).toMatchObject({
notice: "continued",
pendingKind: null,
resumeKind: "production_import",
});
expect(double.counts().installPosts).toBe(1);
expect(fixture!.importRequests).toHaveLength(2);
expect(after.queuedPrompts).toBe(0);
expect(after.renderJobRequests).toBe(0);
await page.waitForTimeout(2_500);
expect(fixture!.importRequests).toHaveLength(2);
});
test("leaving the page drops the waiting import with a visible notice", async ({
page,
}) => {
const { double } = await refusedImport(page, { polls: Infinity });
await page.locator(sidebarCard).locator(primary).click();
await expect
.poll(async () => (await mediaRuntime(page)).pendingKind)
.toBe("production_import");
await closeEditor(page);
const settings = await openSettings(page);
await expect(
settings.locator('[data-h3-media-tools-notice="continuation_cleared"]'),
).toBeVisible();
double.finish();
await expect(settings).toHaveAttribute("data-h3-media-tools", "ready");
await page.waitForTimeout(1_500);
expect(fixture!.importRequests).toHaveLength(1);
expect((await mediaRuntime(page)).resumeKind).toBeNull();
});
// B-M2561-01: since the import waits inside the modal editor, and the selection lives on
// the Production function under it. Changing the selection therefore means closing the editor
// first, and closing it drops the waiting import (the leaving rule above). The `select_again`
// guard for a projection that changed underneath a waiting import is proven by the replaced
// workspace case below, which is still reachable without leaving.
test("a selection changed after closing the editor is not imported; the waiting import was dropped", async ({
page,
}) => {
const renderPhaseWarnings: string[] = [];
page.on("console", (message) => {
if (
message.type() === "error" &&
message.text().includes("Render methods should be a pure function")
)
renderPhaseWarnings.push(message.text());
});
const { double, card } = await refusedImport(
page,
{ polls: Infinity },
{ segments: "2" },
);
await card.locator(primary).click();
await expect(card).toHaveAttribute("data-h3-media-tools", "installing");
await closeEditor(page);
await page.getByRole("tab", { name: "Production" }).click();
const second = page.getByRole("checkbox", {
name: "Segment 2",
exact: true,
});
await second.click();
await expect(second).not.toBeChecked();
double.finish();
await expect
.poll(async () => (await mediaRuntime(page)).notice)
.toBe("continuation_cleared");
await page.waitForTimeout(1_500);
expect(fixture!.importRequests).toHaveLength(1);
expect((await mediaRuntime(page)).pendingKind).toBeNull();
// The user is told where the import was: in the reopened Media pane and in Settings.
await openImportPane(page);
await expect(
page
.locator(editor)
.locator('[data-h3-media-tools-notice="continuation_cleared"]'),
).toBeVisible();
await closeEditor(page);
const settings = await openSettings(page);
await expect(
settings.locator('[data-h3-media-tools-notice="continuation_cleared"]'),
).toBeVisible();
expect(fixture!.importRequests).toHaveLength(1);
expect(renderPhaseWarnings).toEqual([]);
});
test("a replaced Production workspace is never imported into", async ({
page,
}) => {
const { double, card } = await refusedImport(page, { polls: Infinity });
await card.locator(primary).click();
await expect(card).toHaveAttribute("data-h3-media-tools", "installing");
await page.evaluate(() =>
window.nleShellHarness.replaceProductionWorkspace(),
);
double.finish();
await expect
.poll(async () => (await mediaRuntime(page)).notice)
.toBe("select_again");
await page.waitForTimeout(1_500);
expect(fixture!.importRequests).toHaveLength(1);
await closeEditor(page);
const settings = await openSettings(page);
await expect(
settings.locator('[data-h3-media-tools-notice="select_again"]'),
).toBeVisible();
});
expect(fixture.importRequests).toHaveLength(2);
expect((await shellSnapshot(page)).queuedPrompts).toBe(0);
expect(double.counts().retiredRequests).toBe(0);
} finally {
await fixture.close();
}
});
test.describe("preview and render install-and-continue", () => {
test("clip preview reopens once after install", async ({ page }) => {
// (one NLE): the selected-clip source preview lives in the full editor's monitor, which
// offers it when this browser cannot composite (no 2D canvas); its Media tools card is the
// overlay placement inside the monitor region.
await page.addInitScript(() => {
const original = HTMLCanvasElement.prototype.getContext;
Object.defineProperty(HTMLCanvasElement.prototype, "getContext", {
configurable: true,
value: function noCanvas2d(
this: HTMLCanvasElement,
type: string,
...rest: unknown[]
) {
if (type === "2d") return null;
return (
original as (
this: HTMLCanvasElement,
type: string,
...rest: unknown[]
) => unknown
).apply(this, [type, ...rest]);
},
});
});
const double = createRuntimeDouble({ polls: 2 });
await double.attach(page);
await openIntegratedShell(page, "smoke", {
extraParams: { mediaSetup: "1" },
beforeOpen: async (shell) => {
await shell
.getByRole("navigation", { name: "H3 Context pages" })
.getByRole("button", { name: "Production" })
.click();
await shell.getByRole("tab", { name: "Clip editor" }).click();
},
expandOverlay: false,
});
await page.locator('[data-h3-nle-entry="open"]').click();
const monitor = page.locator(
'[data-h3-nle-surface="overlay_v1"] [data-h3-nle-area="monitor"]',
);
await expect(
monitor.locator('[data-h3-nle-fallback="selected_source_only"]'),
).toBeVisible();
await page
.locator(
'[data-h3-nle-clip="clip-1"] [data-h3-nle-control="selection.set"]',
)
.click();
await monitor
.getByRole("button", { name: "Selected source only", exact: true })
.click();
const card = monitor.locator(overlayCard);
await expect(card).toHaveAttribute("data-h3-media-tools", "setup_required");
expect(double.counts().previewRequests).toBe(1);
await card.locator(primary).click();
await expect(monitor.locator("section.h3a-preview video")).toBeVisible();
await expect(monitor.locator(overlayCard)).toHaveCount(0);
// The Clip editor tab no longer hosts a clip preview, so no sidebar card appears for it.
await expect(page.locator(sidebarCard)).toHaveCount(0);
const after = await shellSnapshot(page);
expect(after.mediaRuntime).toMatchObject({
resumeKind: "clip_preview",
pendingKind: null,
});
expect(double.counts().previewRequests).toBe(2);
expect(double.counts().installPosts).toBe(1);
await page.waitForTimeout(2_000);
expect(double.counts().previewRequests).toBe(2);
});
test("final output re-reads its capability after install and starts no render", async ({
page,
}) => {
const double = createRuntimeDouble({ polls: 2 });
await double.attach(page);
await openIntegratedShell(page, "smoke", {
extraParams: { mediaSetup: "1" },
});
await openExportPanel(page);
const card = page.locator(overlayCard);
await expect(card).toHaveAttribute("data-h3-media-tools", "setup_required");
const reads = double.counts().capabilityReads;
await card.locator(primary).click();
await expect(
page.locator('[data-h3-nle-render="available"]'),
).toBeVisible();
expect(double.counts().capabilityReads).toBe(reads + 1);
const after = await shellSnapshot(page);
expect(after.renderJobRequests).toBe(0);
expect(after.queuedPrompts).toBe(0);
expect(after.mediaRuntime.resumeKind).toBe("final_render");
});
test("the first open before in-process activation re-reads final output once the status is read", async ({
page,
}) => {
const double = createRuntimeDouble({
initial: "ready",
activateOnStatusRead: true,
});
await double.attach(page);
await openIntegratedShell(page, "smoke", {
extraParams: { mediaSetup: "1" },
});
await openExportPanel(page);
await expect(
page.locator('[data-h3-nle-render="available"]'),
).toBeVisible();
const counts = double.counts();
expect(counts.statusReads).toBe(1);
expect(counts.capabilityReads).toBe(2);
expect(counts.installPosts).toBe(0);
await expect(page.locator(overlayCard)).toHaveCount(0);
await page.waitForTimeout(2_500);
expect(double.counts()).toMatchObject({
statusReads: 1,
capabilityReads: 2,
});
expect((await shellSnapshot(page)).renderJobRequests).toBe(0);
});
test("render_qualification_unavailable offers no install", async ({
page,
}) => {
const double = createRuntimeDouble({
initial: "ready",
renderUnqualified: true,
});
await double.attach(page);
await openIntegratedShell(page, "smoke", {
extraParams: { mediaSetup: "1" },
});
await openExportPanel(page);
await expect(
page.locator('[data-h3-nle-render="backend_render_unavailable"]'),
).toBeVisible();
await expect
.poll(async () => (await mediaRuntime(page)).status)
.toBe("read");
await expect(page.locator(overlayCard)).toHaveCount(0);
await expect(page.locator(primary)).toHaveCount(0);
expect(double.counts().installPosts).toBe(0);
});
});
for (const lost of [false, true]) {
test(
lost
? "lost selection reply rereads without resubmitting"
: "unsupported local pair remains refused",
async ({ page }) => {
const double = createRuntimeDouble({ loseSelectionReply: lost });
await double.attach(page);
await page.goto("/nleShell.html?mediaSetup=1");
await page.locator('nav.h3n button[data-page-id="settings"]').click();
const card = page.locator(settingsCard);
await card
.locator("input")
.fill(lost ? "C:/media-tools/bin" : "C:/wrong/bin");
await card.locator(primary).click();
if (lost)
await expect(card).toHaveAttribute("data-h3-media-tools", "ready");
else
await expect(
card.locator(
'[data-h3-media-tools-refusal="selection_unsupported_pair"]',
),
).toBeVisible();
expect(double.counts().localPosts).toBe(1);
expect(double.counts().retiredRequests).toBe(0);
},
);
}
@@ -4,6 +4,7 @@ import {
fireEvent,
screen,
waitFor,
within,
} from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
@@ -1112,7 +1113,12 @@ describe("entry provider settings failure lifecycle", () => {
});
fireEvent.click(await screen.findByRole("button", { name: "Settings" }));
expect((await screen.findByRole("alert")).textContent).toContain(
const providerSettings = await screen.findByRole("region", {
name: "Assisted authoring provider",
});
expect(
(await within(providerSettings).findByRole("alert")).textContent,
).toContain(
"Provider settings could not be loaded. The current state could not be confirmed.",
);
expect(
-481
View File
@@ -1,481 +0,0 @@
{
"schema": "h3.context.media_runtime_wire_fixture.v1",
"status_schema": "h3.context.media_runtime_status.v3",
"job_schema": "h3.context.media_runtime_setup_job.v1",
"request_schema": "h3.context.media_runtime_setup_request.v1",
"vocabulary": {
"actions": [
"install_supported",
"rescan",
"use_local_directory",
"restore_auto",
"cancel_setup",
"reclaim_parked_runtime"
],
"config_selections": ["auto", "local"],
"feature_reasons": [
"activating",
"activation_failed",
"config_corrupt",
"config_unsupported",
"discovering",
"discovery_in_progress",
"discovery_limit",
"discovery_timeout",
"invalid_config",
"local_selection_invalid_path",
"local_selection_unsupported_pair",
"override_incomplete",
"override_invalid_marker",
"override_invalid_path",
"override_split_directory",
"override_unsupported_pair",
"pair_admitted",
"private_root_invalid",
"render_qualification_unavailable",
"supported_pair_missing",
"unsupported_host",
"unsupported_platform",
"worker_failure"
],
"feature_states": ["ready", "setup_required", "unavailable"],
"features": ["import", "preview", "derivatives", "assembly", "render"],
"job_phases": [
"checking",
"downloading",
"extracting",
"verifying",
"publishing",
"activating",
"done"
],
"job_reasons": [
"advanced_override_active",
"already_available",
"archive_invalid",
"cancelled",
"config_conflict",
"config_corrupt",
"config_invalid",
"config_unsupported",
"config_write_failed",
"digest_mismatch",
"discovery_in_progress",
"discovery_limit",
"discovery_timeout",
"download_failed",
"download_timeout",
"egress_refused",
"installed",
"insufficient_space",
"internal_failure",
"invalid_request",
"local_selection_active",
"local_selection_invalid_path",
"local_selection_unsupported_pair",
"media_runtime_busy",
"network_timeout",
"network_unavailable",
"override_incomplete",
"override_invalid_marker",
"override_invalid_path",
"override_split_directory",
"override_unsupported_pair",
"pair_admitted",
"permission_denied",
"private_root_invalid",
"publication_failed",
"reclaim_unsafe",
"redirect_refused",
"runtime_busy",
"selection_invalid_path",
"selection_unsupported_pair",
"setup_busy",
"size_mismatch",
"source_unavailable",
"supported_pair_missing",
"tls_failed",
"unsupported_host",
"unsupported_platform",
"verification_failed",
"worker_failure",
"write_failed"
],
"job_states": ["running", "succeeded", "failed", "cancelled"],
"recovery_states": ["parked_runtime"],
"refusal_codes": [
"config_conflict",
"config_corrupt",
"config_unsupported",
"config_write_failed",
"discovery_limit",
"discovery_timeout",
"internal_failure",
"invalid_request",
"media_runtime_busy",
"media_type_rejected",
"origin_rejected",
"private_root_invalid",
"reclaim_unsafe",
"request_too_large",
"selection_invalid_path",
"selection_unsupported_pair",
"setup_busy",
"setup_job_not_found",
"unsupported_host",
"unsupported_platform",
"worker_failure"
],
"resolution_reasons": [
"pair_admitted",
"supported_pair_missing",
"unsupported_platform",
"unsupported_host",
"private_root_invalid",
"override_incomplete",
"override_invalid_marker",
"override_invalid_path",
"override_split_directory",
"override_unsupported_pair",
"local_selection_invalid_path",
"local_selection_unsupported_pair",
"config_corrupt",
"config_unsupported",
"discovery_limit",
"discovery_timeout",
"worker_failure",
"discovery_in_progress"
],
"resolution_states": [
"located",
"unavailable",
"invalid_config",
"discovering"
],
"source_kinds": [
"none",
"explicit_override",
"local_selection",
"managed",
"python_prefix",
"system_path"
]
},
"samples": {
"status_setup_required": {
"schema": "h3.context.media_runtime_status.v3",
"resolution": {
"schema": "h3.context.media_runtime_resolution.v1",
"state": "unavailable",
"reason": "supported_pair_missing",
"source_kind": "none"
},
"config": {
"revision": 0,
"selection": "auto"
},
"setup": null,
"install": {
"profile": "gyan-full-2026-02-26-git-6695528af6",
"source_label": "Gyan.dev FFmpeg full build",
"release_page": "https://github.com/GyanD/codexffmpeg/releases/tag/2026-02-26-git-6695528af6",
"license": "GPL-3.0-or-later",
"approximate_bytes": 246558061
},
"features": {
"import": {
"state": "setup_required",
"reason": "supported_pair_missing"
},
"preview": {
"state": "setup_required",
"reason": "supported_pair_missing"
},
"derivatives": {
"state": "setup_required",
"reason": "supported_pair_missing"
},
"assembly": {
"state": "setup_required",
"reason": "supported_pair_missing"
},
"render": {
"state": "setup_required",
"reason": "supported_pair_missing"
}
},
"recovery": null,
"actions": ["install_supported", "rescan", "use_local_directory"]
},
"status_installing": {
"schema": "h3.context.media_runtime_status.v3",
"resolution": {
"schema": "h3.context.media_runtime_resolution.v1",
"state": "unavailable",
"reason": "supported_pair_missing",
"source_kind": "none"
},
"config": {
"revision": 0,
"selection": "auto"
},
"setup": {
"schema": "h3.context.media_runtime_setup_job.v1",
"job_id": "abababababababababababababababab",
"state": "running",
"phase": "downloading",
"reason": null,
"progress": {
"completed_bytes": 1048576,
"total_bytes": 246558061
}
},
"install": {
"profile": "gyan-full-2026-02-26-git-6695528af6",
"source_label": "Gyan.dev FFmpeg full build",
"release_page": "https://github.com/GyanD/codexffmpeg/releases/tag/2026-02-26-git-6695528af6",
"license": "GPL-3.0-or-later",
"approximate_bytes": 246558061
},
"features": {
"import": {
"state": "setup_required",
"reason": "supported_pair_missing"
},
"preview": {
"state": "setup_required",
"reason": "supported_pair_missing"
},
"derivatives": {
"state": "setup_required",
"reason": "supported_pair_missing"
},
"assembly": {
"state": "setup_required",
"reason": "supported_pair_missing"
},
"render": {
"state": "setup_required",
"reason": "supported_pair_missing"
}
},
"recovery": null,
"actions": ["cancel_setup"]
},
"status_install_failed": {
"schema": "h3.context.media_runtime_status.v3",
"resolution": {
"schema": "h3.context.media_runtime_resolution.v1",
"state": "unavailable",
"reason": "supported_pair_missing",
"source_kind": "none"
},
"config": {
"revision": 0,
"selection": "auto"
},
"setup": {
"schema": "h3.context.media_runtime_setup_job.v1",
"job_id": "abababababababababababababababab",
"state": "failed",
"phase": "done",
"reason": "digest_mismatch",
"progress": {
"completed_bytes": 0,
"total_bytes": 0
}
},
"install": {
"profile": "gyan-full-2026-02-26-git-6695528af6",
"source_label": "Gyan.dev FFmpeg full build",
"release_page": "https://github.com/GyanD/codexffmpeg/releases/tag/2026-02-26-git-6695528af6",
"license": "GPL-3.0-or-later",
"approximate_bytes": 246558061
},
"features": {
"import": {
"state": "setup_required",
"reason": "supported_pair_missing"
},
"preview": {
"state": "setup_required",
"reason": "supported_pair_missing"
},
"derivatives": {
"state": "setup_required",
"reason": "supported_pair_missing"
},
"assembly": {
"state": "setup_required",
"reason": "supported_pair_missing"
},
"render": {
"state": "setup_required",
"reason": "supported_pair_missing"
}
},
"recovery": null,
"actions": ["install_supported", "rescan", "use_local_directory"]
},
"status_ready_recovery": {
"schema": "h3.context.media_runtime_status.v3",
"resolution": {
"schema": "h3.context.media_runtime_resolution.v1",
"state": "located",
"reason": "pair_admitted",
"source_kind": "managed"
},
"config": {
"revision": 0,
"selection": "auto"
},
"setup": null,
"install": {
"profile": "gyan-full-2026-02-26-git-6695528af6",
"source_label": "Gyan.dev FFmpeg full build",
"release_page": "https://github.com/GyanD/codexffmpeg/releases/tag/2026-02-26-git-6695528af6",
"license": "GPL-3.0-or-later",
"approximate_bytes": 246558061
},
"features": {
"import": {
"state": "ready",
"reason": null
},
"preview": {
"state": "ready",
"reason": null
},
"derivatives": {
"state": "ready",
"reason": null
},
"assembly": {
"state": "ready",
"reason": null
},
"render": {
"state": "ready",
"reason": null
}
},
"recovery": {
"state": "parked_runtime",
"reclaimable": true
},
"actions": ["rescan", "use_local_directory", "reclaim_parked_runtime"]
},
"status_local_selection": {
"schema": "h3.context.media_runtime_status.v3",
"resolution": {
"schema": "h3.context.media_runtime_resolution.v1",
"state": "located",
"reason": "pair_admitted",
"source_kind": "managed"
},
"config": {
"revision": 4,
"selection": "local"
},
"setup": null,
"install": {
"profile": "gyan-full-2026-02-26-git-6695528af6",
"source_label": "Gyan.dev FFmpeg full build",
"release_page": "https://github.com/GyanD/codexffmpeg/releases/tag/2026-02-26-git-6695528af6",
"license": "GPL-3.0-or-later",
"approximate_bytes": 246558061
},
"features": {
"import": {
"state": "ready",
"reason": null
},
"preview": {
"state": "ready",
"reason": null
},
"derivatives": {
"state": "ready",
"reason": null
},
"assembly": {
"state": "ready",
"reason": null
},
"render": {
"state": "ready",
"reason": null
}
},
"recovery": null,
"actions": ["rescan", "use_local_directory", "restore_auto"]
},
"status_override": {
"schema": "h3.context.media_runtime_status.v3",
"resolution": {
"schema": "h3.context.media_runtime_resolution.v1",
"state": "located",
"reason": "pair_admitted",
"source_kind": "explicit_override"
},
"config": {
"revision": 0,
"selection": "auto"
},
"setup": null,
"install": {
"profile": "gyan-full-2026-02-26-git-6695528af6",
"source_label": "Gyan.dev FFmpeg full build",
"release_page": "https://github.com/GyanD/codexffmpeg/releases/tag/2026-02-26-git-6695528af6",
"license": "GPL-3.0-or-later",
"approximate_bytes": 246558061
},
"features": {
"import": {
"state": "ready",
"reason": null
},
"preview": {
"state": "ready",
"reason": null
},
"derivatives": {
"state": "ready",
"reason": null
},
"assembly": {
"state": "ready",
"reason": null
},
"render": {
"state": "ready",
"reason": null
}
},
"recovery": null,
"actions": ["rescan"]
},
"job_running": {
"schema": "h3.context.media_runtime_setup_job.v1",
"job_id": "abababababababababababababababab",
"state": "running",
"phase": "extracting",
"reason": null,
"progress": {
"completed_bytes": 10,
"total_bytes": 20
}
},
"job_succeeded": {
"schema": "h3.context.media_runtime_setup_job.v1",
"job_id": "abababababababababababababababab",
"state": "succeeded",
"phase": "done",
"reason": "installed",
"progress": {
"completed_bytes": 0,
"total_bytes": 0
}
}
}
}
+200
View File
@@ -0,0 +1,200 @@
{
"samples": {
"status_override": {
"actions": ["rescan"],
"config": {
"revision": 0,
"selection": "auto"
},
"features": {
"assembly": {
"reason": null,
"state": "ready"
},
"derivatives": {
"reason": null,
"state": "ready"
},
"import": {
"reason": null,
"state": "ready"
},
"preview": {
"reason": null,
"state": "ready"
},
"render": {
"reason": null,
"state": "ready"
}
},
"manual": {
"approximate_bytes": 246558061,
"archive_name": "ffmpeg-2026-02-26-git-6695528af6-full_build.zip",
"archive_sha256": "ad18ecdedfca6d51c28cf12f2c96287ce1150686578b75bff2efcd06ff34bb30",
"license": "GPL-3.0-or-later",
"release_page": "https://github.com/GyanD/codexffmpeg/releases/tag/2026-02-26-git-6695528af6",
"source_label": "Gyan.dev FFmpeg full build"
},
"recovery": null,
"resolution": {
"reason": "pair_admitted",
"schema": "h3.context.media_runtime_resolution.v1",
"source_kind": "explicit_override",
"state": "located"
},
"schema": "h3.context.media_runtime_status.v4"
},
"status_ready_recovery": {
"actions": ["rescan", "use_local_directory", "reclaim_parked_runtime"],
"config": {
"revision": 0,
"selection": "auto"
},
"features": {
"assembly": {
"reason": null,
"state": "ready"
},
"derivatives": {
"reason": null,
"state": "ready"
},
"import": {
"reason": null,
"state": "ready"
},
"preview": {
"reason": null,
"state": "ready"
},
"render": {
"reason": null,
"state": "ready"
}
},
"manual": {
"approximate_bytes": 246558061,
"archive_name": "ffmpeg-2026-02-26-git-6695528af6-full_build.zip",
"archive_sha256": "ad18ecdedfca6d51c28cf12f2c96287ce1150686578b75bff2efcd06ff34bb30",
"license": "GPL-3.0-or-later",
"release_page": "https://github.com/GyanD/codexffmpeg/releases/tag/2026-02-26-git-6695528af6",
"source_label": "Gyan.dev FFmpeg full build"
},
"recovery": {
"reclaimable": true,
"state": "parked_runtime"
},
"resolution": {
"reason": "pair_admitted",
"schema": "h3.context.media_runtime_resolution.v1",
"source_kind": "managed",
"state": "located"
},
"schema": "h3.context.media_runtime_status.v4"
},
"status_setup_required": {
"actions": ["rescan", "use_local_directory"],
"config": {
"revision": 0,
"selection": "auto"
},
"features": {
"assembly": {
"reason": "supported_pair_missing",
"state": "setup_required"
},
"derivatives": {
"reason": "supported_pair_missing",
"state": "setup_required"
},
"import": {
"reason": "supported_pair_missing",
"state": "setup_required"
},
"preview": {
"reason": "supported_pair_missing",
"state": "setup_required"
},
"render": {
"reason": "supported_pair_missing",
"state": "setup_required"
}
},
"manual": {
"approximate_bytes": 246558061,
"archive_name": "ffmpeg-2026-02-26-git-6695528af6-full_build.zip",
"archive_sha256": "ad18ecdedfca6d51c28cf12f2c96287ce1150686578b75bff2efcd06ff34bb30",
"license": "GPL-3.0-or-later",
"release_page": "https://github.com/GyanD/codexffmpeg/releases/tag/2026-02-26-git-6695528af6",
"source_label": "Gyan.dev FFmpeg full build"
},
"recovery": null,
"resolution": {
"reason": "supported_pair_missing",
"schema": "h3.context.media_runtime_resolution.v1",
"source_kind": "none",
"state": "unavailable"
},
"schema": "h3.context.media_runtime_status.v4"
}
},
"schema": "h3.context.media_runtime_wire_fixture.v4",
"vocabularies": {
"actions": [
"rescan",
"use_local_directory",
"restore_auto",
"reclaim_parked_runtime"
],
"feature_reasons": [
"activating",
"activation_failed",
"config_corrupt",
"config_unsupported",
"discovering",
"discovery_in_progress",
"discovery_limit",
"discovery_timeout",
"invalid_config",
"local_selection_invalid_path",
"local_selection_unsupported_pair",
"override_incomplete",
"override_invalid_marker",
"override_invalid_path",
"override_split_directory",
"override_unsupported_pair",
"pair_admitted",
"private_root_invalid",
"render_qualification_unavailable",
"supported_pair_missing",
"unsupported_host",
"unsupported_platform",
"worker_failure"
],
"feature_states": ["ready", "setup_required", "unavailable"],
"recovery_states": ["parked_runtime", "abandoned_setup"],
"refusal_codes": [
"config_conflict",
"config_corrupt",
"config_unsupported",
"config_write_failed",
"discovery_limit",
"discovery_timeout",
"internal_failure",
"invalid_request",
"media_runtime_busy",
"media_type_rejected",
"origin_rejected",
"private_root_invalid",
"reclaim_unsafe",
"request_too_large",
"selection_invalid_path",
"selection_unsupported_pair",
"setup_busy",
"unsupported_host",
"unsupported_platform",
"worker_failure"
]
}
}
@@ -0,0 +1,39 @@
import { afterEach, expect, it, vi } from "vitest";
import type { Page } from "@playwright/test";
import { instrumentHostGraphLoads } from "./e2e/host/managed";
// This unit exercises the public store lifecycle, without admitting a real host or bundle.
vi.mock("./e2e/host/candidate", () => ({ hostUrl: "http://127.0.0.1:8188" }));
afterEach(() => {
delete (window as any).comfyAPI;
});
it.each([null, { attached: true }])(
"captures cold workflow authority only after its real store contract is ready: %s",
async (active) => {
const app: any = {
extensionManager: {},
loadGraphData: vi.fn(async () => undefined),
};
(window as any).comfyAPI = { app: { app } };
const waitForFunction = vi.fn(async (predicate: () => boolean) => {
expect(predicate()).toBe(false);
// Model the observed host lifecycle: registration exists before workflow initialization.
app.extensionManager.workflow = {
activeWorkflow: active,
openWorkflows: active ? [active] : [],
};
expect(predicate()).toBe(true);
});
const page = {
waitForFunction,
evaluate: async (operation: () => unknown) => operation(),
} as unknown as Page;
await instrumentHostGraphLoads(page);
expect(waitForFunction).toHaveBeenCalledOnce();
expect((window as any).__h3GraphWorkflowAuthority).toBe(active);
expect((window as any).__h3GraphWorkflowOpenCount).toBe(active ? 1 : 0);
await app.loadGraphData({}, false, false, active);
expect((window as any).__h3GraphWorkflowTargets).toEqual([true]);
},
);
+1 -1
View File
@@ -56,7 +56,7 @@ export const UNEXPORTED_COPY_TABLES: readonly CopyTable[] = [
file: "src/components/AuthoringPreviewMonitor.tsx",
identifier: "copy",
},
{ file: "src/components/MediaToolsCard.tsx", identifier: "copy" },
{ file: "src/components/MediaToolsCard.tsx", identifier: "mediaToolsCopy" },
{ file: "src/components/PerceptionHostStatus.tsx", identifier: "copy" },
{ file: "src/components/ProductionWorkbench.tsx", identifier: "copy" },
{ file: "src/components/ProjectFileControls.tsx", identifier: "COPY" },
+58 -194
View File
@@ -1,210 +1,74 @@
// the media runtime client never throws, sends only closed action envelopes, maps every
// non-success to a closed code, and marks a mutation whose response was lost as outcome-unknown.
import { describe, expect, it, vi } from "vitest";
import wireFixture from "./fixtures/media_runtime_wire_v3.json";
import fixture from "./fixtures/media_runtime_wire_v4.json";
import {
MEDIA_RUNTIME_SETUP_ROUTE,
MEDIA_RUNTIME_STATUS_ROUTE,
createMediaRuntimeClient,
type MediaRuntimeFetch,
} from "../src/host/mediaRuntimeClient";
const samples = wireFixture.samples as unknown as Record<string, unknown>;
const JOB = "abababababababababababababababab";
function respond(status: number, body: unknown) {
return { ok: status >= 200 && status < 300, status, json: async () => body };
const sample = fixture.samples.status_setup_required;
function subject(status = 200, wire: unknown = sample) {
const fetch = vi.fn<MediaRuntimeFetch>(async () => ({
ok: status === 200,
status,
json: async () => wire,
}));
return { fetch, client: createMediaRuntimeClient({ fetchApi: fetch }) };
}
function client(handler: MediaRuntimeFetch) {
const fetchApi = vi.fn(handler);
return { fetchApi, api: createMediaRuntimeClient({ fetchApi }) };
}
describe("status and job reads", () => {
it("reads and decodes the status through a same-origin GET", async () => {
const { fetchApi, api } = client(async () =>
respond(200, samples.status_setup_required),
);
const result = await api.readStatus();
expect(result.ok).toBe(true);
const [path, init] = fetchApi.mock.calls[0]!;
expect(path).toBe(MEDIA_RUNTIME_STATUS_ROUTE);
expect(init).toMatchObject({ method: "GET", credentials: "same-origin" });
expect(init.body).toBeUndefined();
});
it("fails closed on an undecodable status instead of throwing", async () => {
const { api } = client(async () =>
respond(200, { ...(samples.status_override as object), extra: 1 }),
);
expect(await api.readStatus()).toEqual({
ok: false,
code: "malformed_response",
outcomeUnknown: false,
describe("manual setup client", () => {
it("sends a closed same-origin revision-bound local selection", async () => {
const s = subject();
expect(
(
await s.client.send("use_local_directory", {
directory: "C:/tools/bin",
expectedRevision: 0,
})
).ok,
).toBe(true);
const [path, init] = s.fetch.mock.calls[0]!;
expect(path).toBe("/h3-context/v1/media-runtime/setup");
expect(init.credentials).toBe("same-origin");
expect(JSON.parse(init.body as string)).toEqual({
schema: "h3.context.media_runtime_setup_request.v2",
action: "use_local_directory",
directory: "C:/tools/bin",
expected_revision: 0,
});
expect("readJob" in s.client).toBe(false);
});
it("maps transport loss, abort and closed refusal codes", async () => {
it.each([-1, NaN, Infinity, 1.5])(
"never sends an invalid revision %s",
async (revision) => {
const s = subject();
expect(
await s.client.send("restore_auto", { expectedRevision: revision }),
).toMatchObject({ ok: false, code: "invalid_request" });
expect(s.fetch).not.toHaveBeenCalled();
},
);
it("keeps a 409 refusal definite and a lost response uncertain", async () => {
expect(
await client(async () => {
throw new TypeError("network");
}).api.readStatus(),
).toMatchObject({ ok: false, code: "transport_failure" });
const controller = new AbortController();
controller.abort();
expect(
await client(async () => {
throw Object.assign(new Error("x"), { name: "AbortError" });
}).api.readStatus(controller.signal),
).toMatchObject({ ok: false, code: "aborted" });
expect(
await client(async () =>
respond(503, { error: "private_root_invalid" }),
).api.readStatus(),
).toMatchObject({ ok: false, code: "private_root_invalid" });
expect(
await client(async () =>
respond(502, { error: "gateway exploded" }),
).api.readStatus(),
).toEqual({ ok: false, code: "unexpected_status", outcomeUnknown: false });
});
it("reads a job only by a well-formed id", async () => {
const { fetchApi, api } = client(async () =>
respond(200, samples.job_running),
);
expect(await api.readJob("../../etc")).toMatchObject({
await subject(409, { error: "config_conflict" }).client.send(
"restore_auto",
{ expectedRevision: 0 },
),
).toEqual({ ok: false, code: "config_conflict", outcomeUnknown: false });
const s = subject();
s.fetch.mockRejectedValue(new Error("lost"));
expect(await s.client.send("rescan", {})).toEqual({
ok: false,
code: "invalid_request",
code: "transport_failure",
outcomeUnknown: true,
});
expect(fetchApi).not.toHaveBeenCalled();
const result = await api.readJob(JOB);
expect(result).toMatchObject({ ok: true, job: { phase: "extracting" } });
expect(fetchApi.mock.calls[0]![0]).toBe(
`${MEDIA_RUNTIME_SETUP_ROUTE}/${JOB}`,
);
expect(s.fetch).toHaveBeenCalledTimes(1);
});
it("rejects an oversized response body", async () => {
const { api } = client(async () =>
respond(200, { padding: "x".repeat(20_000) }),
);
expect(await api.readStatus()).toMatchObject({
it("refuses stale or malformed responses", async () => {
expect(
await subject(200, { ...sample, setup: null }).client.readStatus(),
).toMatchObject({ ok: false, code: "malformed_response" });
expect(await subject(202).client.send("rescan", {})).toMatchObject({
ok: false,
code: "malformed_response",
code: "unexpected_status",
outcomeUnknown: true,
});
});
});
describe("setup actions", () => {
it("sends only the closed envelope for each action", async () => {
const bodies: unknown[] = [];
const { api } = client(async (_path, init) => {
const body = JSON.parse(String(init.body)) as { action: string };
bodies.push(body);
return body.action === "install_supported"
? respond(202, samples.job_running)
: body.action === "cancel_setup"
? respond(200, {
...(samples.job_running as object),
state: "cancelled",
reason: "cancelled",
})
: respond(200, samples.status_local_selection);
});
await api.send("install_supported", {});
await api.send("cancel_setup", { jobId: JOB });
await api.send("rescan", {});
await api.send("reclaim_parked_runtime", {});
await api.send("use_local_directory", {
directory: "D:/tools/ffmpeg",
expectedRevision: 4,
});
await api.send("restore_auto", { expectedRevision: 4 });
const schema = "h3.context.media_runtime_setup_request.v1";
expect(bodies).toEqual([
{ schema, action: "install_supported" },
{ schema, action: "cancel_setup", job_id: JOB },
{ schema, action: "rescan" },
{ schema, action: "reclaim_parked_runtime" },
{
schema,
action: "use_local_directory",
directory: "D:/tools/ffmpeg",
expected_revision: 4,
},
{ schema, action: "restore_auto", expected_revision: 4 },
]);
});
it("refuses an incomplete payload locally without sending", async () => {
const { fetchApi, api } = client(async () => respond(200, {}));
for (const [action, payload] of [
["cancel_setup", {}],
["cancel_setup", { jobId: "nope" }],
["use_local_directory", { directory: "", expectedRevision: 1 }],
["use_local_directory", { directory: "x" }],
["restore_auto", { expectedRevision: 1.5 }],
] as const)
expect(await api.send(action, payload)).toMatchObject({
ok: false,
code: "invalid_request",
});
expect(fetchApi).not.toHaveBeenCalled();
});
it("returns the job for install and cancel and the status otherwise", async () => {
const install = await client(async () =>
respond(202, samples.job_running),
).api.send("install_supported", {});
expect(install.ok && "job" in install).toBe(true);
const rescan = await client(async () =>
respond(200, samples.status_override),
).api.send("rescan", {});
expect(rescan.ok && "status" in rescan).toBe(true);
});
it("marks a lost or unreadable mutation response as outcome-unknown", async () => {
expect(
await client(async () => {
throw new TypeError("connection reset");
}).api.send("install_supported", {}),
).toEqual({ ok: false, code: "transport_failure", outcomeUnknown: true });
expect(
await client(async () => respond(202, "<html>")).api.send(
"install_supported",
{},
),
).toEqual({ ok: false, code: "malformed_response", outcomeUnknown: true });
// A different success status is not the contract, and the job may still have started.
expect(
await client(async () => respond(200, samples.job_running)).api.send(
"install_supported",
{},
),
).toEqual({ ok: false, code: "unexpected_status", outcomeUnknown: true });
expect(
await client(async () => respond(500, null)).api.send(
"install_supported",
{},
),
).toEqual({ ok: false, code: "unexpected_status", outcomeUnknown: true });
});
it("carries a closed refusal as a known outcome", async () => {
expect(
await client(async () => respond(409, { error: "setup_busy" })).api.send(
"install_supported",
{},
),
).toEqual({ ok: false, code: "setup_busy", outcomeUnknown: false });
expect(
await client(async () =>
respond(409, { error: "reclaim_unsafe" }),
).api.send("reclaim_parked_runtime", {}),
).toEqual({ ok: false, code: "reclaim_unsafe", outcomeUnknown: false });
});
});
+50 -227
View File
@@ -1,241 +1,64 @@
// AC33-01: the media runtime status v3 and setup job v1 decoders fail closed on every
// unknown key or value, and the closed client vocabularies equal the server's. Both sides read
// `fixtures/media_runtime_wire_v3.json`, which the backend suite regenerates from the service.
import { describe, expect, it } from "vitest";
import wireFixture from "./fixtures/media_runtime_wire_v3.json";
import fixture from "./fixtures/media_runtime_wire_v4.json";
import {
decodeMediaRuntimeStatus,
MEDIA_RUNTIME_ACTIONS,
MEDIA_RUNTIME_CONFIG_SELECTIONS,
MEDIA_RUNTIME_FEATURES,
MEDIA_RUNTIME_FEATURE_REASONS,
MEDIA_RUNTIME_FEATURE_STATES,
MEDIA_RUNTIME_JOB_PHASES,
MEDIA_RUNTIME_JOB_REASONS,
MEDIA_RUNTIME_JOB_SCHEMA,
MEDIA_RUNTIME_JOB_STATES,
MEDIA_RUNTIME_RECOVERY_STATES,
MEDIA_RUNTIME_REFUSAL_CODES,
MEDIA_RUNTIME_REQUEST_SCHEMA,
MEDIA_RUNTIME_RESOLUTION_REASONS,
MEDIA_RUNTIME_RESOLUTION_STATES,
MEDIA_RUNTIME_SOURCE_KINDS,
MEDIA_RUNTIME_STATUS_SCHEMA,
MediaRuntimeDecodeError,
decodeMediaRuntimeJob,
decodeMediaRuntimeStatus,
isMediaRuntimeRefusalCode,
} from "../src/contracts/mediaRuntimeCodec";
type Json = Record<string, unknown>;
const samples = wireFixture.samples as unknown as Record<string, Json>;
const clone = <T>(value: T): T => JSON.parse(JSON.stringify(value)) as T;
const sorted = (values: readonly string[]) => [...values].sort();
function rejects(decode: (value: unknown) => unknown, value: unknown) {
expect(() => decode(value)).toThrow(MediaRuntimeDecodeError);
}
describe("media runtime vocabulary parity", () => {
it("pins every closed client list to the server vocabulary", () => {
const v = wireFixture.vocabulary;
expect(wireFixture.status_schema).toBe(MEDIA_RUNTIME_STATUS_SCHEMA);
expect(wireFixture.job_schema).toBe(MEDIA_RUNTIME_JOB_SCHEMA);
expect(wireFixture.request_schema).toBe(MEDIA_RUNTIME_REQUEST_SCHEMA);
expect([...MEDIA_RUNTIME_ACTIONS]).toEqual(v.actions);
expect(sorted(MEDIA_RUNTIME_CONFIG_SELECTIONS)).toEqual(
sorted(v.config_selections),
const raw = () =>
JSON.parse(JSON.stringify(fixture.samples.status_setup_required));
describe("manual runtime codec", () => {
it("decodes the server samples and pins each closed vocabulary", () => {
for (const sample of Object.values(fixture.samples))
expect(decodeMediaRuntimeStatus(sample).schema).toBe(
"h3.context.media_runtime_status.v4",
);
expect([...MEDIA_RUNTIME_ACTIONS].sort()).toEqual(
[...fixture.vocabularies.actions].sort(),
);
expect([...MEDIA_RUNTIME_FEATURES]).toEqual(v.features);
expect(sorted(MEDIA_RUNTIME_FEATURE_STATES)).toEqual(
sorted(v.feature_states),
expect([...MEDIA_RUNTIME_FEATURE_REASONS].sort()).toEqual(
[...fixture.vocabularies.feature_reasons].sort(),
);
expect(sorted(new Set(MEDIA_RUNTIME_FEATURE_REASONS) as never)).toEqual(
sorted(v.feature_reasons),
expect([...MEDIA_RUNTIME_RECOVERY_STATES].sort()).toEqual(
[...fixture.vocabularies.recovery_states].sort(),
);
expect(sorted(MEDIA_RUNTIME_JOB_STATES)).toEqual(sorted(v.job_states));
expect([...MEDIA_RUNTIME_JOB_PHASES]).toEqual(v.job_phases);
expect(sorted(new Set(MEDIA_RUNTIME_JOB_REASONS) as never)).toEqual(
sorted(v.job_reasons),
expect([...MEDIA_RUNTIME_REFUSAL_CODES].sort()).toEqual(
[...fixture.vocabularies.refusal_codes].sort(),
);
expect(sorted(MEDIA_RUNTIME_RECOVERY_STATES)).toEqual(
sorted(v.recovery_states),
);
expect(sorted(MEDIA_RUNTIME_REFUSAL_CODES)).toEqual(
sorted(v.refusal_codes),
);
expect(sorted(MEDIA_RUNTIME_RESOLUTION_REASONS)).toEqual(
sorted(v.resolution_reasons),
);
expect(sorted(MEDIA_RUNTIME_RESOLUTION_STATES)).toEqual(
sorted(v.resolution_states),
);
expect(sorted(MEDIA_RUNTIME_SOURCE_KINDS)).toEqual(sorted(v.source_kinds));
});
it("decodes every representative server wire", () => {
for (const [name, sample] of Object.entries(samples)) {
const decode = name.startsWith("job_")
? decodeMediaRuntimeJob
: decodeMediaRuntimeStatus;
expect(() => decode(sample), name).not.toThrow();
}
const installing = decodeMediaRuntimeStatus(samples.status_installing);
expect(installing.setup).toMatchObject({
state: "running",
phase: "downloading",
reason: null,
completedBytes: 1048576,
});
const recovery = decodeMediaRuntimeStatus(samples.status_ready_recovery);
expect(recovery.recovery).toEqual({
state: "parked_runtime",
reclaimable: true,
});
expect(recovery.actions).toContain("reclaim_parked_runtime");
expect(recovery.resolution.sourceKind).toBe("managed");
expect(
decodeMediaRuntimeStatus(samples.status_setup_required).features.render,
).toEqual({ state: "setup_required", reason: "supported_pair_missing" });
});
});
describe("fail-closed status decode", () => {
const base = () => clone(samples.status_setup_required) as Json;
it("rejects unknown and missing keys at every level", () => {
rejects(decodeMediaRuntimeStatus, { ...base(), locator: "C:/tools" });
const missing = base();
delete missing.recovery;
rejects(decodeMediaRuntimeStatus, missing);
const resolution = base();
(resolution.resolution as Json).path = "x";
rejects(decodeMediaRuntimeStatus, resolution);
const install = base();
(install.install as Json).sha256 = "0".repeat(64);
rejects(decodeMediaRuntimeStatus, install);
const feature = base();
(feature.features as Json).codecs = { state: "ready", reason: null };
rejects(decodeMediaRuntimeStatus, feature);
const recovery = base();
recovery.recovery = {
state: "parked_runtime",
reclaimable: true,
tree: "x",
};
rejects(decodeMediaRuntimeStatus, recovery);
});
it("rejects unknown enumerated values instead of reading them as ready", () => {
const schema = base();
schema.schema = "h3.context.media_runtime_status.v2";
rejects(decodeMediaRuntimeStatus, schema);
const state = base();
(state.features as Record<string, Json>).import = {
state: "partially_ready",
reason: null,
};
rejects(decodeMediaRuntimeStatus, state);
const reason = base();
(reason.features as Record<string, Json>).preview = {
state: "unavailable",
reason: "codec_missing",
};
rejects(decodeMediaRuntimeStatus, reason);
const action = base();
action.actions = ["install_supported", "delete_everything"];
rejects(decodeMediaRuntimeStatus, action);
const duplicate = base();
duplicate.actions = ["rescan", "rescan"];
rejects(decodeMediaRuntimeStatus, duplicate);
const source = base();
(source.resolution as Json).source_kind = "downloads_folder";
rejects(decodeMediaRuntimeStatus, source);
const recovery = base();
recovery.recovery = { state: "orphaned", reclaimable: true };
rejects(decodeMediaRuntimeStatus, recovery);
});
it("rejects readiness that contradicts its reason", () => {
const readyWithReason = base();
(readyWithReason.features as Record<string, Json>).render = {
state: "ready",
reason: "activating",
};
rejects(decodeMediaRuntimeStatus, readyWithReason);
const blockedWithoutReason = base();
(blockedWithoutReason.features as Record<string, Json>).render = {
state: "setup_required",
reason: null,
};
rejects(decodeMediaRuntimeStatus, blockedWithoutReason);
});
it("admits only a bounded GitHub release page and bounded counts", () => {
for (const page of [
"http://github.com/owner/release",
"https://github.com.evil.example/release",
"https://example.com/release",
"javascript:alert(1)",
]) {
const wire = base();
(wire.install as Json).release_page = page;
rejects(decodeMediaRuntimeStatus, wire);
}
for (const bytes of [-1, 1.5, 2 ** 53, "246558061"]) {
const wire = base();
(wire.install as Json).approximate_bytes = bytes;
rejects(decodeMediaRuntimeStatus, wire);
}
const revision = base();
revision.config = { revision: -1, selection: "auto" };
rejects(decodeMediaRuntimeStatus, revision);
});
});
describe("fail-closed job decode", () => {
const base = () => clone(samples.job_running) as Json;
it("rejects unknown keys, phases, reasons and identifiers", () => {
rejects(decodeMediaRuntimeJob, { ...base(), url: "https://x" });
rejects(decodeMediaRuntimeJob, { ...base(), phase: "uploading" });
rejects(decodeMediaRuntimeJob, { ...base(), job_id: "ABABABAB" });
rejects(decodeMediaRuntimeJob, {
...base(),
state: "failed",
reason: "disk_on_fire",
});
});
it("requires a terminal reason exactly when the job is terminal", () => {
rejects(decodeMediaRuntimeJob, { ...base(), reason: "installed" });
rejects(decodeMediaRuntimeJob, {
...base(),
state: "succeeded",
reason: null,
});
});
it("rejects progress beyond its total", () => {
rejects(decodeMediaRuntimeJob, {
...base(),
progress: { completed_bytes: 21, total_bytes: 20 },
});
expect(
decodeMediaRuntimeJob({
...base(),
progress: { completed_bytes: 5, total_bytes: 0 },
}).totalBytes,
).toBe(0);
});
});
describe("refusal codes", () => {
it("admits only the closed server refusal vocabulary", () => {
expect(isMediaRuntimeRefusalCode("setup_busy")).toBe(true);
expect(isMediaRuntimeRefusalCode("reclaim_unsafe")).toBe(true);
expect(isMediaRuntimeRefusalCode("transport_failure")).toBe(false);
expect(isMediaRuntimeRefusalCode(503)).toBe(false);
it.each([
(v: ReturnType<typeof raw>) => {
v.setup = null;
},
(v: ReturnType<typeof raw>) => {
v.schema = "h3.context.media_runtime_status.v3";
},
(v: ReturnType<typeof raw>) => {
v.actions.push("install_supported");
},
(v: ReturnType<typeof raw>) => {
v.manual.archive_sha256 = "not-a-pin";
},
(v: ReturnType<typeof raw>) => {
v.manual.archive_name = "../unsafe.zip";
},
(v: ReturnType<typeof raw>) => {
v.manual.release_page = "https://example.invalid/file";
},
(v: ReturnType<typeof raw>) => {
v.features.preview.state = "unknown";
},
(v: ReturnType<typeof raw>) => {
v.features.preview.reason = null;
},
(v: ReturnType<typeof raw>) => {
v.actions.push(v.actions[0]);
},
])("refuses unknown or unsafe wire %$", (mutate) => {
const value = raw();
mutate(value);
expect(() => decodeMediaRuntimeStatus(value)).toThrow();
});
});
+99 -636
View File
@@ -1,665 +1,128 @@
// AC33-03/04/05: the Media tools session reads only when a surface can use it, shares the
// one setup job, stops polling at a terminal state or on release, and runs a captured action once
// only after every identity it captured still holds.
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import wireFixture from "./fixtures/media_runtime_wire_v3.json";
import {
decodeMediaRuntimeJob,
decodeMediaRuntimeStatus,
type MediaRuntimeJob,
type MediaRuntimeStatus,
} from "../src/contracts/mediaRuntimeCodec";
import type { MediaRuntimeClient } from "../src/host/mediaRuntimeClient";
import {
MEDIA_RUNTIME_MAX_POLL_FAILURES,
createMediaRuntimeSession,
} from "../src/lifecycle/mediaRuntimeSession";
import { describe, expect, it, vi } from "vitest";
import fixture from "./fixtures/media_runtime_wire_v4.json";
import { decodeMediaRuntimeStatus } from "../src/contracts/mediaRuntimeCodec";
import { createMediaRuntimeSession } from "../src/lifecycle/mediaRuntimeSession";
import {
createShellSession,
type ShellRuntime,
} from "../src/lifecycle/shellSession";
import type { MediaRuntimeIntent } from "../src/state/mediaRuntimeState";
type Raw = Record<string, unknown> & {
features: Record<string, { state: string; reason: string | null }>;
};
const samples = wireFixture.samples as unknown as Record<string, Raw>;
const JOB = "abababababababababababababababab";
function status(name: string, mutate?: (raw: Raw) => void): MediaRuntimeStatus {
const raw = JSON.parse(JSON.stringify(samples[name])) as Raw;
mutate?.(raw);
return decodeMediaRuntimeStatus(raw);
}
const READY = status("status_override");
const MISSING = status("status_setup_required");
const INSTALLING = status("status_installing");
function job(
state: MediaRuntimeJob["state"],
reason: string | null = null,
): MediaRuntimeJob {
return decodeMediaRuntimeJob({
...samples.job_running,
state,
phase: state === "running" ? "downloading" : "done",
reason,
});
}
const IMPORT_INTENT: MediaRuntimeIntent = {
kind: "production_import",
productionWorkspaceHandle: "pw_handle",
productionWorkspaceId: "workspace.1",
segmentIds: ["segment.1"],
outputHandles: ["out_ready"],
};
const RENDER_INTENT: MediaRuntimeIntent = {
kind: "final_render",
workspaceHandle: "aw_handle",
workspaceRevision: 3,
timelineRevision: 5,
publicFingerprint: `sha256:${"f".repeat(64)}`,
overlayGeneration: 2,
};
const ready = decodeMediaRuntimeStatus(fixture.samples.status_ready_recovery);
function subject() {
const session = createShellSession();
session.container = document.createElement("div");
session.productionState = {
status: "ready",
projection: {
workspaceHandle: "pw_handle",
workspaceId: "workspace.1",
workspaceRevision: 7,
allowedActions: ["import_production_outputs_to_authoring"],
selectedSegmentIds: ["segment.1"],
outputs: [
{ segmentId: "segment.1", state: "ready", outputHandle: "out_ready" },
],
},
} as unknown as typeof session.productionState;
session.authoringState = {
status: "ready",
timelineHistory: {
snapshot: {
workspaceHandle: "aw_handle",
workspaceRevision: 3,
timelineRevision: 5,
publicFingerprint: `sha256:${"f".repeat(64)}`,
},
},
} as unknown as typeof session.authoringState;
session.nleWorkspace = {
...session.nleWorkspace,
surface: {
...session.nleWorkspace.surface,
status: "expanded",
generation: 2,
},
session.mediaRuntime = {
...session.mediaRuntime,
status: "read",
wire: decodeMediaRuntimeStatus(fixture.samples.status_setup_required),
};
let page = "production";
const client = {
readStatus: vi.fn(async () => ({ ok: true, status: READY })),
readJob: vi.fn(async () => ({ ok: true, job: job("running") })),
send: vi.fn(async () => ({ ok: true, job: job("running") })),
readStatus: vi.fn(async () => ({ ok: true, status: ready })),
send: vi.fn(async () => ({ ok: true, status: ready })),
};
const nleImportSelectedOutputs = vi.fn(async () => undefined);
const nleReadRenderCapability = vi.fn(async () => undefined);
const renderCurrent = vi.fn();
const runtime = {
session,
deps: {
mediaRuntimeClient: client as unknown as MediaRuntimeClient,
pageRegistry: { getSnapshot: () => ({ selected: page }) },
},
actions: {
renderCurrent,
nleImportSelectedOutputs,
nleReadRenderCapability,
},
} as unknown as ShellRuntime;
const media = createMediaRuntimeSession(runtime);
return {
session,
client,
media,
nleImportSelectedOutputs,
nleReadRenderCapability,
state: () => session.mediaRuntime,
setPage: (next: string) => {
page = next;
},
const actions = {
renderCurrent: vi.fn(),
nleImportSelectedOutputs: vi.fn(),
nleReadRenderCapability: vi.fn(),
};
const media = createMediaRuntimeSession({
session,
deps: { mediaRuntimeClient: client },
actions,
} as unknown as ShellRuntime);
return { session, client, actions, media };
}
beforeEach(() => {
vi.useFakeTimers();
});
afterEach(() => {
vi.useRealTimers();
vi.restoreAllMocks();
});
describe("status reads", () => {
it("reads once on the first Settings open and never polls without a job", async () => {
const flush = async () => {
await Promise.resolve();
await Promise.resolve();
await Promise.resolve();
};
describe("manual runtime session", () => {
it("an older GET cannot overwrite the revision returned by folder selection", async () => {
const s = subject();
s.media.mediaRuntimeEnsureStatus();
s.media.mediaRuntimeEnsureStatus();
await vi.advanceTimersByTimeAsync(10_000);
expect(s.client.readStatus).toHaveBeenCalledTimes(1);
expect(s.client.readJob).not.toHaveBeenCalled();
expect(s.state()).toMatchObject({ status: "read", wire: READY });
});
it("fails closed to status unavailable and never keeps a stale ready", async () => {
const s = subject();
s.media.mediaRuntimeEnsureStatus();
await vi.advanceTimersByTimeAsync(0);
s.client.readStatus.mockResolvedValueOnce({
ok: false,
code: "malformed_response",
outcomeUnknown: false,
} as never);
s.media.mediaRuntimeReport("import");
await vi.advanceTimersByTimeAsync(0);
expect(s.state()).toMatchObject({
status: "unavailable",
refusal: "malformed_response",
});
});
it("never re-reads a status that already explains the refusal when a card remounts", async () => {
const s = subject();
s.client.readStatus.mockResolvedValue({ ok: true, status: MISSING });
s.media.mediaRuntimeReport("render");
await vi.advanceTimersByTimeAsync(0);
s.media.mediaRuntimeReport("render");
s.media.mediaRuntimeReport("import");
await vi.advanceTimersByTimeAsync(0);
expect(s.client.readStatus).toHaveBeenCalledTimes(1);
const failed = subject();
failed.client.readStatus.mockResolvedValue({
ok: false,
code: "transport_failure",
outcomeUnknown: false,
} as never);
failed.media.mediaRuntimeReport("preview");
await vi.advanceTimersByTimeAsync(0);
failed.media.mediaRuntimeReport("preview");
await vi.advanceTimersByTimeAsync(10_000);
expect(failed.client.readStatus).toHaveBeenCalledTimes(1);
expect(failed.state().status).toBe("unavailable");
});
it("re-reads the render capability once when the status says final output is ready", async () => {
const s = subject();
s.media.mediaRuntimeReport("render");
await vi.advanceTimersByTimeAsync(0);
expect(s.nleReadRenderCapability).toHaveBeenCalledTimes(1);
expect(s.nleReadRenderCapability).toHaveBeenCalledWith(2);
// The capability answered unsupported again and the card remounted: nothing reads again.
s.media.mediaRuntimeReport("render");
await vi.advanceTimersByTimeAsync(10_000);
expect(s.client.readStatus).toHaveBeenCalledTimes(1);
expect(s.nleReadRenderCapability).toHaveBeenCalledTimes(1);
// Import and preview reports never re-read the render capability.
s.media.mediaRuntimeReport("import");
await vi.advanceTimersByTimeAsync(0);
expect(s.nleReadRenderCapability).toHaveBeenCalledTimes(1);
});
it("waits boundedly for a starting feature before explaining a render refusal", async () => {
const s = subject();
const starting = status("status_override", (raw) => {
raw.features.render = { state: "unavailable", reason: "activating" };
});
s.client.readStatus
.mockResolvedValueOnce({ ok: true, status: starting })
.mockResolvedValueOnce({ ok: true, status: starting })
.mockResolvedValue({ ok: true, status: READY });
s.media.mediaRuntimeReport("render");
await vi.advanceTimersByTimeAsync(0);
expect(s.nleReadRenderCapability).not.toHaveBeenCalled();
await vi.advanceTimersByTimeAsync(2_000);
expect(s.client.readStatus).toHaveBeenCalledTimes(3);
expect(s.nleReadRenderCapability).toHaveBeenCalledTimes(1);
});
it("shares a job another tab started instead of starting a second one", async () => {
const s = subject();
s.client.readStatus.mockResolvedValue({ ok: true, status: INSTALLING });
s.media.mediaRuntimeReport("import");
await vi.advanceTimersByTimeAsync(0);
await s.media.mediaRuntimeInstall(IMPORT_INTENT);
await vi.advanceTimersByTimeAsync(1_000);
expect(s.client.send).not.toHaveBeenCalled();
expect(s.client.readJob).toHaveBeenCalledWith(JOB);
expect(s.state().pending).toEqual(IMPORT_INTENT);
});
});
describe("install and continue", () => {
async function installed(
s: ReturnType<typeof subject>,
intent: MediaRuntimeIntent,
) {
s.client.readStatus.mockResolvedValue({ ok: true, status: MISSING });
await s.media.mediaRuntimeInstall(intent);
s.client.readStatus.mockResolvedValue({ ok: true, status: READY });
s.client.readJob.mockResolvedValueOnce({
ok: true,
job: job("succeeded", "installed"),
});
await vi.advanceTimersByTimeAsync(1_000);
}
it("continues the original import exactly once after a successful install", async () => {
const s = subject();
await installed(s, IMPORT_INTENT);
expect(s.client.send).toHaveBeenCalledTimes(1);
expect(s.nleImportSelectedOutputs).toHaveBeenCalledTimes(1);
expect(s.nleImportSelectedOutputs).toHaveBeenCalledWith(["segment.1"]);
expect(s.state()).toMatchObject({ pending: null, notice: "continued" });
expect(s.state().resume).toMatchObject({ kind: "production_import" });
// The poll stopped at the terminal state; nothing runs a second time.
await vi.advanceTimersByTimeAsync(10_000);
expect(s.client.readJob).toHaveBeenCalledTimes(1);
expect(s.nleImportSelectedOutputs).toHaveBeenCalledTimes(1);
});
it("re-reads the capability for a final render and never starts a render", async () => {
const s = subject();
await installed(s, RENDER_INTENT);
expect(s.nleReadRenderCapability).toHaveBeenCalledWith(2);
expect(s.nleImportSelectedOutputs).not.toHaveBeenCalled();
});
it("ignores a second click while the first install request is in flight", async () => {
const s = subject();
let resolveSend!: (value: unknown) => void;
s.client.send.mockImplementationOnce(
() => new Promise((resolve) => (resolveSend = resolve)) as never,
s.session.mediaRuntime = { ...s.session.mediaRuntime, status: "unread" };
let finish: (
value: Awaited<ReturnType<typeof s.client.readStatus>>,
) => void = () => {};
s.client.readStatus.mockImplementation(
() =>
new Promise((resolve) => {
finish = resolve;
}),
);
const first = s.media.mediaRuntimeInstall(IMPORT_INTENT);
await s.media.mediaRuntimeInstall(IMPORT_INTENT);
s.media.mediaRuntimeEnsureStatus();
s.media.mediaRuntimeUseLocalDirectory("C:/tools/bin");
await flush();
expect(s.session.mediaRuntime.wire).toBe(ready);
finish({
ok: true,
status: decodeMediaRuntimeStatus(fixture.samples.status_setup_required),
});
await flush();
expect(s.session.mediaRuntime.wire).toBe(ready);
expect(s.session.mediaRuntime.status).toBe("read");
});
it("selection carries CAS and never retries the original media action", async () => {
const s = subject();
s.media.mediaRuntimeUseLocalDirectory("C:/tools/bin");
await flush();
expect(s.client.send).toHaveBeenCalledWith("use_local_directory", {
directory: "C:/tools/bin",
expectedRevision: 0,
});
expect(s.session.mediaRuntime.notice).toBe("retry_action");
expect(s.actions.nleImportSelectedOutputs).not.toHaveBeenCalled();
expect("resume" in s.session.mediaRuntime).toBe(false);
});
it("coalesces a double click and ignores late results after release", async () => {
const s = subject();
let finish: (
value: Awaited<ReturnType<typeof s.client.send>>,
) => void = () => {};
s.client.send.mockImplementation(
() =>
new Promise((resolve) => {
finish = resolve;
}) as ReturnType<typeof s.client.send>,
);
s.media.mediaRuntimeRescan();
s.media.mediaRuntimeRescan();
expect(s.client.send).toHaveBeenCalledTimes(1);
resolveSend({ ok: true, job: job("running") });
await first;
await s.media.mediaRuntimeInstall(IMPORT_INTENT);
expect(s.client.send).toHaveBeenCalledTimes(1);
});
it("adopts the running job after a lost install response without resending", async () => {
const s = subject();
s.client.send.mockResolvedValueOnce({
ok: false,
code: "transport_failure",
outcomeUnknown: true,
} as never);
s.client.readStatus.mockResolvedValue({ ok: true, status: INSTALLING });
await s.media.mediaRuntimeInstall(IMPORT_INTENT);
await vi.advanceTimersByTimeAsync(1_000);
expect(s.client.send).toHaveBeenCalledTimes(1);
expect(s.client.readJob).toHaveBeenCalledWith(JOB);
expect(s.state().notice).toBeNull();
});
it("says the outcome is unknown when a lost response left no running job", async () => {
const s = subject();
s.client.send.mockResolvedValueOnce({
ok: false,
code: "transport_failure",
outcomeUnknown: true,
} as never);
s.client.readStatus.mockResolvedValue({ ok: true, status: MISSING });
await s.media.mediaRuntimeInstall(IMPORT_INTENT);
expect(s.client.send).toHaveBeenCalledTimes(1);
expect(s.state().notice).toBe("outcome_unknown");
});
it("re-reads status when another setup action holds the slot", async () => {
const s = subject();
s.client.send.mockResolvedValueOnce({
ok: false,
code: "setup_busy",
outcomeUnknown: false,
} as never);
await s.media.mediaRuntimeInstall(null);
expect(s.state().refusal).toBe(null);
expect(s.client.readStatus).toHaveBeenCalledTimes(1);
});
it("continues after an append advances the project revision but preserves the selected output", async () => {
const s = subject();
s.client.readStatus.mockResolvedValue({ ok: true, status: MISSING });
await s.media.mediaRuntimeInstall(IMPORT_INTENT);
s.session.productionState = {
status: "ready",
projection: {
...(s.session.productionState as { projection: object }).projection,
workspaceRevision: 8,
},
} as unknown as typeof s.session.productionState;
s.client.readStatus.mockResolvedValue({ ok: true, status: READY });
s.client.readJob.mockResolvedValueOnce({
ok: true,
job: job("succeeded", "installed"),
});
await vi.advanceTimersByTimeAsync(1_000);
expect(s.nleImportSelectedOutputs).toHaveBeenCalledWith(["segment.1"]);
expect(s.state()).toMatchObject({ pending: null, notice: "continued" });
});
it("drops the continuation when an appended project changes the captured output", async () => {
const s = subject();
s.client.readStatus.mockResolvedValue({ ok: true, status: MISSING });
await s.media.mediaRuntimeInstall(IMPORT_INTENT);
s.session.productionState = {
status: "ready",
projection: {
...(s.session.productionState as { projection: object }).projection,
workspaceRevision: 8,
outputs: [
{
segmentId: "segment.1",
state: "ready",
outputHandle: "out_replaced",
},
],
},
} as unknown as typeof s.session.productionState;
s.client.readStatus.mockResolvedValue({ ok: true, status: READY });
s.client.readJob.mockResolvedValueOnce({
ok: true,
job: job("succeeded", "installed"),
});
await vi.advanceTimersByTimeAsync(1_000);
expect(s.nleImportSelectedOutputs).not.toHaveBeenCalled();
expect(s.state()).toMatchObject({ pending: null, notice: "select_again" });
});
it("drops the continuation when the selection changed during install", async () => {
const s = subject();
s.client.readStatus.mockResolvedValue({ ok: true, status: MISSING });
await s.media.mediaRuntimeInstall(IMPORT_INTENT);
s.session.productionState = {
status: "ready",
projection: {
...(s.session.productionState as { projection: object }).projection,
selectedSegmentIds: ["segment.2"],
},
} as unknown as typeof s.session.productionState;
s.client.readStatus.mockResolvedValue({ ok: true, status: READY });
s.client.readJob.mockResolvedValueOnce({
ok: true,
job: job("succeeded", "installed"),
});
await vi.advanceTimersByTimeAsync(1_000);
expect(s.nleImportSelectedOutputs).not.toHaveBeenCalled();
expect(s.state().notice).toBe("select_again");
});
it("never continues an uncertain import, which keeps its own retained Retry", async () => {
const s = subject();
s.client.readStatus.mockResolvedValue({ ok: true, status: MISSING });
await s.media.mediaRuntimeInstall(IMPORT_INTENT);
s.session.nleWorkspace = {
...s.session.nleWorkspace,
import: { ...s.session.nleWorkspace.import, status: "uncertain" },
};
s.client.readStatus.mockResolvedValue({ ok: true, status: READY });
s.client.readJob.mockResolvedValueOnce({
ok: true,
job: job("succeeded", "installed"),
});
await vi.advanceTimersByTimeAsync(1_000);
expect(s.nleImportSelectedOutputs).not.toHaveBeenCalled();
expect(s.state().notice).toBe("select_again");
});
it("drops a render continuation when its overlay generation closed", async () => {
const s = subject();
s.client.readStatus.mockResolvedValue({ ok: true, status: MISSING });
await s.media.mediaRuntimeInstall(RENDER_INTENT);
s.session.nleWorkspace = {
...s.session.nleWorkspace,
surface: { ...s.session.nleWorkspace.surface, generation: 3 },
};
s.client.readStatus.mockResolvedValue({ ok: true, status: READY });
s.client.readJob.mockResolvedValueOnce({
ok: true,
job: job("succeeded", "installed"),
});
await vi.advanceTimersByTimeAsync(1_000);
expect(s.nleReadRenderCapability).not.toHaveBeenCalled();
expect(s.state().notice).toBe("select_again");
});
it("waits boundedly for activation, then continues", async () => {
const s = subject();
s.client.readStatus.mockResolvedValue({ ok: true, status: MISSING });
await s.media.mediaRuntimeInstall(IMPORT_INTENT);
const activating = status("status_override", (raw) => {
raw.features.import = { state: "unavailable", reason: "activating" };
});
s.client.readStatus
.mockResolvedValueOnce({ ok: true, status: activating })
.mockResolvedValue({ ok: true, status: READY });
s.client.readJob.mockResolvedValueOnce({
ok: true,
job: job("succeeded", "installed"),
});
await vi.advanceTimersByTimeAsync(1_000);
expect(s.nleImportSelectedOutputs).not.toHaveBeenCalled();
await vi.advanceTimersByTimeAsync(1_000);
expect(s.nleImportSelectedOutputs).toHaveBeenCalledTimes(1);
});
it("reports a feature still not ready instead of continuing", async () => {
const s2 = subject();
s2.client.readStatus.mockResolvedValue({ ok: true, status: MISSING });
await s2.media.mediaRuntimeInstall(IMPORT_INTENT);
s2.client.readJob.mockResolvedValueOnce({
ok: true,
job: job("succeeded", "installed"),
});
await vi.advanceTimersByTimeAsync(1_000);
expect(s2.nleImportSelectedOutputs).not.toHaveBeenCalled();
expect(s2.state()).toMatchObject({
pending: null,
notice: "feature_not_ready",
});
});
it("keeps the continuation after a failed install and returns focus to the card", async () => {
const s = subject();
s.client.readStatus.mockResolvedValue({ ok: true, status: MISSING });
await s.media.mediaRuntimeInstall(IMPORT_INTENT);
const focus = s.state().focusPrimary;
s.client.readJob.mockResolvedValueOnce({
ok: true,
job: job("failed", "digest_mismatch"),
});
await vi.advanceTimersByTimeAsync(1_000);
expect(s.state().pending).toEqual(IMPORT_INTENT);
expect(s.state().focusPrimary).toBe(focus + 1);
expect(s.nleImportSelectedOutputs).not.toHaveBeenCalled();
});
});
describe("clearing a continuation", () => {
it("cancel clears the continuation and never continues", async () => {
const s = subject();
s.client.readStatus.mockResolvedValue({ ok: true, status: MISSING });
await s.media.mediaRuntimeInstall(IMPORT_INTENT);
s.client.send.mockResolvedValueOnce({
ok: true,
job: job("cancelled", "cancelled"),
});
await s.media.mediaRuntimeCancel();
expect(s.client.send).toHaveBeenLastCalledWith("cancel_setup", {
jobId: JOB,
});
expect(s.state()).toMatchObject({
pending: null,
notice: "continuation_cleared",
});
s.client.readJob.mockResolvedValue({
ok: true,
job: job("succeeded", "installed"),
});
await vi.advanceTimersByTimeAsync(2_000);
expect(s.nleImportSelectedOutputs).not.toHaveBeenCalled();
});
it("leaving the page clears any continuation; leaving the overlay clears only its own", async () => {
const s = subject();
s.client.readStatus.mockResolvedValue({ ok: true, status: MISSING });
await s.media.mediaRuntimeInstall(IMPORT_INTENT);
s.media.mediaRuntimeLeaveContext("overlay");
expect(s.state().pending).toEqual(IMPORT_INTENT);
s.media.mediaRuntimeLeaveContext("function");
expect(s.state()).toMatchObject({
pending: null,
notice: "continuation_cleared",
});
const r = subject();
await r.media.mediaRuntimeInstall(RENDER_INTENT);
r.media.mediaRuntimeLeaveContext("function");
expect(r.state().pending).toEqual(RENDER_INTENT);
r.media.mediaRuntimeLeaveContext("page");
expect(r.state().pending).toBeNull();
});
it("a different surface's install replaces the earlier continuation with a notice", async () => {
const s = subject();
await s.media.mediaRuntimeInstall(IMPORT_INTENT);
await s.media.mediaRuntimeInstall(RENDER_INTENT);
expect(s.state()).toMatchObject({
pending: RENDER_INTENT,
notice: "continuation_replaced",
});
expect(s.client.send).toHaveBeenCalledTimes(1);
});
it("release stops polling and ignores a late job answer", async () => {
const s = subject();
s.client.readStatus.mockResolvedValue({ ok: true, status: MISSING });
await s.media.mediaRuntimeInstall(IMPORT_INTENT);
s.media.releaseMediaRuntime();
s.client.readJob.mockResolvedValue({
ok: true,
job: job("succeeded", "installed"),
});
await vi.advanceTimersByTimeAsync(5_000);
expect(s.client.readJob).not.toHaveBeenCalled();
expect(s.state()).toMatchObject({ status: "unread", pending: null });
expect(s.nleImportSelectedOutputs).not.toHaveBeenCalled();
finish({ ok: true, status: ready });
await flush();
expect(s.session.mediaRuntime.status).toBe("unread");
expect(s.session.mediaRuntime.wire).toBeNull();
});
it("forgets a job the server no longer knows and follows the fresh status", async () => {
it("a lost mutation rereads once and is never resubmitted", async () => {
const s = subject();
s.client.readStatus.mockResolvedValue({ ok: true, status: MISSING });
await s.media.mediaRuntimeInstall(null);
s.client.readJob.mockResolvedValue({
ok: false,
code: "setup_job_not_found",
outcomeUnknown: false,
} as never);
await vi.advanceTimersByTimeAsync(1_000);
expect(s.state()).toMatchObject({
status: "read",
wire: MISSING,
job: null,
});
await vi.advanceTimersByTimeAsync(10_000);
expect(s.client.readJob).toHaveBeenCalledTimes(1);
});
it("gives up polling after the bounded failure count", async () => {
const s = subject();
await s.media.mediaRuntimeInstall(null);
s.client.readJob.mockResolvedValue({
s.client.send.mockResolvedValue({
ok: false,
code: "transport_failure",
outcomeUnknown: false,
outcomeUnknown: true,
} as never);
await vi.advanceTimersByTimeAsync(MEDIA_RUNTIME_MAX_POLL_FAILURES * 1_000);
expect(s.client.readJob).toHaveBeenCalledTimes(
MEDIA_RUNTIME_MAX_POLL_FAILURES,
);
expect(s.state().status).toBe("unavailable");
await vi.advanceTimersByTimeAsync(10_000);
expect(s.client.readJob).toHaveBeenCalledTimes(
MEDIA_RUNTIME_MAX_POLL_FAILURES,
);
s.media.mediaRuntimeRescan();
await flush();
await flush();
expect(s.client.send).toHaveBeenCalledTimes(1);
expect(s.client.readStatus).toHaveBeenCalledTimes(1);
expect(s.actions.nleImportSelectedOutputs).not.toHaveBeenCalled();
});
});
describe("status actions", () => {
it("sends the folder and restore actions against the read config revision", async () => {
it("keeps a stale config refusal and permits an explicit retry", async () => {
const s = subject();
s.client.readStatus.mockResolvedValue({
ok: true,
status: status("status_local_selection"),
});
s.media.mediaRuntimeEnsureStatus();
await vi.advanceTimersByTimeAsync(0);
s.client.send.mockResolvedValue({ ok: true, status: READY } as never);
s.media.mediaRuntimeUseLocalDirectory("D:/tools");
await vi.advanceTimersByTimeAsync(0);
expect(s.client.send).toHaveBeenLastCalledWith("use_local_directory", {
directory: "D:/tools",
expectedRevision: 4,
});
s.client.readStatus.mockResolvedValue({
ok: true,
status: status("status_local_selection"),
});
s.media.mediaRuntimeReport("import");
await vi.advanceTimersByTimeAsync(0);
s.media.mediaRuntimeRestoreAuto();
await vi.advanceTimersByTimeAsync(0);
expect(s.client.send).toHaveBeenLastCalledWith("restore_auto", {
expectedRevision: 4,
});
});
it("surfaces a reclaim refusal as a closed code", async () => {
const s = subject();
s.client.send.mockResolvedValueOnce({
s.client.send.mockResolvedValue({
ok: false,
code: "reclaim_unsafe",
code: "config_conflict",
outcomeUnknown: false,
} as never);
s.media.mediaRuntimeReclaim();
await vi.advanceTimersByTimeAsync(0);
expect(s.client.send).toHaveBeenCalledWith("reclaim_parked_runtime", {});
expect(s.state().refusal).toBe("reclaim_unsafe");
s.media.mediaRuntimeRestoreAuto();
await flush();
expect(s.session.mediaRuntime.refusal).toBe("config_conflict");
expect(s.client.readStatus).not.toHaveBeenCalled();
});
it("dismissing a notice keeps the continuation", async () => {
it("a contextual remount does not poll an already explained refusal", async () => {
const s = subject();
await s.media.mediaRuntimeInstall(IMPORT_INTENT);
await s.media.mediaRuntimeInstall(RENDER_INTENT);
s.media.mediaToolsBinding().dismiss();
expect(s.state()).toMatchObject({ notice: null, pending: RENDER_INTENT });
});
it("publishes stable binding functions across renders", () => {
const s = subject();
const first = s.media.mediaToolsBinding();
const second = s.media.mediaToolsBinding();
expect(second.install).toBe(first.install);
expect(second.ensure).toBe(first.ensure);
expect(second.report).toBe(first.report);
s.media.mediaRuntimeReport("preview");
s.media.mediaRuntimeReport("preview");
await flush();
expect(s.client.readStatus).not.toHaveBeenCalled();
});
});
+184 -403
View File
@@ -1,439 +1,220 @@
// AC33-02/03/06/09: the Media tools card states, its single primary action, focus return,
// the advanced folder field kept out of the normal path, and plain copy in all three locales.
import {
act,
cleanup,
fireEvent,
render,
screen,
waitFor,
} from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
import wireFixture from "./fixtures/media_runtime_wire_v3.json";
import fixture from "./fixtures/media_runtime_wire_v4.json";
import { decodeMediaRuntimeStatus } from "../src/contracts/mediaRuntimeCodec";
import {
MediaToolsCard,
mediaToolsCardVisible,
type MediaToolsPlacement,
deriveMediaToolsView,
mediaToolsCopy,
} from "../src/components/MediaToolsCard";
import {
decodeMediaRuntimeJob,
decodeMediaRuntimeStatus,
type MediaRuntimeFeature,
type MediaRuntimeStatus,
} from "../src/contracts/mediaRuntimeCodec";
import type { Locale } from "../src/i18n/catalog";
import {
initialMediaRuntimeState,
type MediaRuntimeIntent,
type MediaRuntimeState,
type MediaToolsBinding,
} from "../src/state/mediaRuntimeState";
type Raw = Record<string, unknown> & {
features: Record<string, { state: string; reason: string | null }>;
actions: string[];
};
const samples = wireFixture.samples as unknown as Record<string, Raw>;
const LOCALES: readonly Locale[] = ["en", "zh-TW", "zh-CN"];
const MACHINE_TOKEN = /\b[a-z][a-z0-9]*_[a-z0-9_]+\b/u;
function wire(name: string, mutate?: (raw: Raw) => void): MediaRuntimeStatus {
const raw = JSON.parse(JSON.stringify(samples[name])) as Raw;
mutate?.(raw);
return decodeMediaRuntimeStatus(raw);
}
const RUNNING = decodeMediaRuntimeJob(samples.job_running);
const IMPORT_INTENT: MediaRuntimeIntent = {
kind: "production_import",
productionWorkspaceHandle: "pw_handle",
productionWorkspaceId: "workspace.1",
segmentIds: ["segment.1"],
outputHandles: ["out_ready"],
};
function read(
status: MediaRuntimeStatus,
extra: Partial<MediaRuntimeState> = {},
): MediaRuntimeState {
function binding(): {
-readonly [K in keyof MediaToolsBinding]: MediaToolsBinding[K];
} {
return {
...initialMediaRuntimeState,
status: "read",
wire: status,
job: status.setup,
...extra,
};
}
function binding(state: MediaRuntimeState) {
return {
state,
state: {
...initialMediaRuntimeState,
status: "read",
wire: decodeMediaRuntimeStatus(fixture.samples.status_setup_required),
},
ensure: vi.fn(),
report: vi.fn(),
install: vi.fn(),
cancel: vi.fn(),
dismiss: vi.fn(),
rescan: vi.fn(),
reclaim: vi.fn(),
useLocalDirectory: vi.fn(),
restoreAuto: vi.fn(),
} satisfies MediaToolsBinding;
}
function mount(
state: MediaRuntimeState,
options: {
placement?: MediaToolsPlacement;
feature?: MediaRuntimeFeature;
intent?: MediaRuntimeIntent | null;
locale?: Locale;
} = {},
) {
const b = binding(state);
const view = (next: MediaToolsBinding) => (
<MediaToolsCard
placement={options.placement ?? "settings"}
binding={next}
locale={options.locale ?? "en"}
feature={options.feature}
intent={options.intent}
/>
);
const result = render(view(b));
return {
b,
card: () =>
result.container.querySelector<HTMLElement>("[data-h3-media-tools]")!,
rerender: (nextState: MediaRuntimeState) => {
const next = { ...b, state: nextState };
result.rerender(view(next));
return next;
},
};
}
afterEach(cleanup);
describe("states", () => {
it("reads once from Settings and reports from a contextual placement", () => {
const settings = mount(initialMediaRuntimeState);
expect(settings.b.ensure).toHaveBeenCalledTimes(1);
expect(settings.b.report).not.toHaveBeenCalled();
expect(settings.card().dataset.h3MediaTools).toBe("checking");
cleanup();
const contextual = mount(initialMediaRuntimeState, {
placement: "contextual-sidebar",
feature: "preview",
});
expect(contextual.b.report).toHaveBeenCalledWith("preview");
expect(contextual.b.ensure).not.toHaveBeenCalled();
describe("manual media tools card", () => {
it("keeps all supported component locale keys in parity", () => {
for (const locale of ["zh-TW", "zh-CN"] as const) {
expect(Object.keys(mediaToolsCopy[locale]).sort()).toEqual(
Object.keys(mediaToolsCopy.en).sort(),
);
}
});
it("offers exactly one Install with the source, size, license and release page", () => {
const { b, card } = mount(read(wire("status_setup_required")));
expect(card().dataset.h3MediaTools).toBe("setup_required");
const primaries = card().querySelectorAll(
'[data-h3-media-tools-action="primary"]',
);
expect(primaries).toHaveLength(1);
expect(primaries[0]!.textContent).toBe("Install");
const source = card().querySelector("[data-h3-media-tools-source]")!;
expect(source.textContent).toContain("Gyan.dev FFmpeg full build");
expect(source.textContent).toContain("about 235 MB");
expect(source.textContent).toContain("GPL-3.0-or-later");
const link = screen.getByRole("link", { name: "Release page" });
expect(link.getAttribute("href")).toMatch(/^https:\/\/github\.com\//);
expect(link.getAttribute("rel")).toBe("noopener noreferrer");
// The only text input sits behind the closed Advanced disclosure.
const inputs = card().querySelectorAll("input");
expect(inputs).toHaveLength(1);
expect(inputs[0]!.closest("details")?.open).toBe(false);
fireEvent.click(primaries[0]!);
expect(b.install).toHaveBeenCalledWith(null);
});
it("names the contextual action Install and continue and passes the captured intent", () => {
const { b, card } = mount(read(wire("status_setup_required")), {
placement: "contextual-sidebar",
feature: "import",
intent: IMPORT_INTENT,
});
expect(card().querySelectorAll("input")).toHaveLength(0);
fireEvent.click(
screen.getByRole("button", { name: "Install and continue" }),
);
expect(b.install).toHaveBeenCalledWith(IMPORT_INTENT);
expect(screen.getByRole("status").textContent).toContain(
"Importing needs media tools.",
);
});
it("shows progress, the phase in a polite status line and Cancel while installing", () => {
const { b, card } = mount(read(wire("status_installing")));
expect(card().dataset.h3MediaTools).toBe("installing");
const progress = card().querySelector("progress")!;
expect(progress.getAttribute("max")).toBe("246558061");
expect(progress.getAttribute("value")).toBe("1048576");
const line = card().querySelector('[role="status"][aria-live="polite"]')!;
expect(line.textContent).toContain("Downloading media tools");
expect(screen.queryByRole("button", { name: "Install" })).toBeNull();
fireEvent.click(screen.getByRole("button", { name: "Cancel setup" }));
expect(b.cancel).toHaveBeenCalled();
expect(card().querySelector("details")).toBeNull();
});
it("offers Cancel for a job this page started after its last status read", () => {
const { b, card } = mount(
read(wire("status_setup_required"), { job: RUNNING }),
);
expect(card().dataset.h3MediaTools).toBe("installing");
const button = screen.getByRole<HTMLButtonElement>("button", {
name: "Cancel setup",
});
expect(button.disabled).toBe(false);
fireEvent.click(button);
expect(b.cancel).toHaveBeenCalled();
});
it("trusts the session's newer terminal job over a status that still says running", () => {
const cancelled = decodeMediaRuntimeJob({
...samples.job_running,
state: "cancelled",
phase: "done",
reason: "cancelled",
});
const { card } = mount(read(wire("status_installing"), { job: cancelled }));
expect(card().dataset.h3MediaTools).toBe("setup_required");
expect(card().querySelector("progress")).toBeNull();
expect(screen.queryByRole("button", { name: "Cancel setup" })).toBeNull();
});
it("names a failed install's reason and offers Install again only when it can help", () => {
const failed = mount(read(wire("status_install_failed")));
expect(failed.card().dataset.h3MediaTools).toBe("failed");
expect(failed.card().textContent).toContain(
"The download did not match the expected file.",
);
expect(screen.getByRole("button", { name: "Install again" })).toBeTruthy();
cleanup();
const override = mount(
read(wire("status_install_failed"), {
job: decodeMediaRuntimeJob({
...samples.job_succeeded,
state: "failed",
reason: "advanced_override_active",
}),
}),
);
expect(override.card().textContent).toContain(
"Change the media tools setting on the ComfyUI host",
);
expect(
override.card().querySelector('[data-h3-media-tools-action="primary"]'),
).toBeNull();
});
it("shows status unavailable with Check again, never the last good status", () => {
const { b, card } = mount(
read(wire("status_override"), {
status: "unavailable",
refusal: "transport_failure",
}),
);
expect(card().dataset.h3MediaTools).toBe("status_unavailable");
expect(card().textContent).not.toContain("Media tools are ready.");
fireEvent.click(screen.getByRole("button", { name: "Check again" }));
expect(b.rescan).toHaveBeenCalled();
});
it("offers Reclaim only for a reclaimable parked runtime", () => {
const reclaimable = mount(read(wire("status_ready_recovery")));
expect(reclaimable.card().dataset.h3MediaTools).toBe("ready");
fireEvent.click(
screen.getByRole("button", { name: "Remove earlier copy" }),
);
expect(reclaimable.b.reclaim).toHaveBeenCalled();
cleanup();
mount(
read(
wire("status_ready_recovery", (raw) => {
raw.recovery = { state: "parked_runtime", reclaimable: false };
raw.actions = ["rescan", "use_local_directory"];
}),
),
);
expect(
screen.queryByRole("button", { name: "Remove earlier copy" }),
).toBeNull();
expect(
screen.getByText(
"It stays in place until the current media tools are confirmed ready.",
),
).toBeTruthy();
});
it("says final output is not available on this host without an install action", () => {
const status = wire("status_override", (raw) => {
raw.features.render = {
state: "unavailable",
reason: "render_qualification_unavailable",
it.each(["en", "zh-TW", "zh-CN"] as const)(
"opens localized wire-backed help and closes with focus restored in %s",
(locale) => {
const b = binding();
b.state = {
...b.state,
wire: {
...b.state.wire!,
manual: {
...b.state.wire!.manual,
releasePage:
"https://github.com/GyanD/codexffmpeg/releases/tag/help-wire-tag",
archiveName: "help-wire-archive.zip",
archiveSha256: "b".repeat(64),
license: "help-wire-licence",
},
},
};
});
const { card } = mount(read(status), {
placement: "contextual-overlay",
feature: "render",
});
expect(card().dataset.h3MediaTools).toBe("render_unavailable");
expect(card().querySelectorAll("button")).toHaveLength(0);
cleanup();
const settings = mount(read(status));
expect(settings.card().dataset.h3MediaTools).toBe("ready");
expect(
settings
.card()
.querySelector('[data-h3-media-tools-render="unavailable"]'),
).not.toBeNull();
const v = render(
<MediaToolsCard placement="settings" binding={b} locale={locale} />,
);
const help = v.container.querySelector<HTMLButtonElement>(
'[data-h3-media-tools-action="help"]',
)!;
expect(help).not.toBeNull();
expect(help.getAttribute("aria-label")).toBeTruthy();
expect(help.getAttribute("aria-expanded")).toBe("false");
fireEvent.click(help);
const panel = v.container.querySelector<HTMLElement>(
"[data-h3-media-tools-help]",
)!;
expect(help.getAttribute("aria-expanded")).toBe("true");
for (const value of [
b.state.wire!.manual.releasePage.split("/").at(-1)!,
b.state.wire!.manual.archiveName,
b.state.wire!.manual.archiveSha256,
b.state.wire!.manual.license,
])
expect(panel.textContent).toContain(value);
expect(panel.textContent).toContain("Get-FileHash -Algorithm SHA256");
expect(panel.textContent).toContain("certutil -hashfile <file> SHA256");
expect(panel.textContent).toContain("ffmpeg.exe");
expect(panel.textContent).toContain("ffprobe.exe");
fireEvent.keyDown(panel, { key: "Escape" });
expect(
v.container.querySelector("[data-h3-media-tools-help]"),
).toBeNull();
expect(document.activeElement).toBe(help);
fireEvent.click(help);
fireEvent.click(
v.container.querySelector('[data-h3-media-tools-action="close-help"]')!,
);
expect(document.activeElement).toBe(help);
expect(b.useLocalDirectory).not.toHaveBeenCalled();
expect(b.rescan).not.toHaveBeenCalled();
},
);
it("promotes only the pinned release page without a node action", () => {
const b = binding();
const v = render(
<MediaToolsCard placement="settings" binding={b} locale="en" />,
);
const link = v.container.querySelector<HTMLAnchorElement>(
'[data-h3-media-tools-action="download"]',
)!;
expect(link).not.toBeNull();
expect(link.getAttribute("href")).toBe(b.state.wire!.manual.releasePage);
expect(link.getAttribute("href")).toContain("/releases/tag/");
expect(link.getAttribute("target")).toBe("_blank");
expect(link.getAttribute("rel")).toBe("noopener noreferrer");
expect(link.closest(".h3-meta")).toBeNull();
expect(b.useLocalDirectory).not.toHaveBeenCalled();
});
it("describes where ready tools came from in Settings only", () => {
mount(read(wire("status_ready_recovery")));
expect(screen.getByText("Installed by this extension.")).toBeTruthy();
cleanup();
mount(read(wire("status_ready_recovery")), {
placement: "contextual-sidebar",
feature: "import",
it("keeps the checksum usable when clipboard access is unavailable", async () => {
Object.defineProperty(navigator, "clipboard", {
configurable: true,
value: undefined,
});
expect(screen.queryByText("Installed by this extension.")).toBeNull();
});
it("uses a chosen folder and restores automatic setup only from Advanced", () => {
const { b } = mount(read(wire("status_local_selection")));
const button = screen.getByRole<HTMLButtonElement>("button", {
name: "Use this folder",
});
expect(button.disabled).toBe(true);
fireEvent.change(screen.getByLabelText("Media tools folder"), {
target: { value: " D:/tools/ffmpeg " },
});
fireEvent.click(button);
expect(b.useLocalDirectory).toHaveBeenCalledWith("D:/tools/ffmpeg");
const v = render(
<MediaToolsCard placement="settings" binding={binding()} locale="en" />,
);
fireEvent.click(
screen.getByRole("button", { name: "Use automatic setup" }),
);
expect(b.restoreAuto).toHaveBeenCalled();
});
it("shows a notice with Dismiss and a refusal as an alert", () => {
const { b } = mount(
read(wire("status_ready_recovery"), {
notice: "select_again",
refusal: "reclaim_unsafe",
}),
v.container.querySelector('[data-h3-media-tools-action="copy"]')!,
);
await screen.findByText("Could not copy. Select and copy the checksum.");
expect(
screen.getByText(
"Media tools are ready, but the selection changed. Select again.",
),
).toBeTruthy();
expect(screen.getByRole("alert").textContent).toBe(
"The earlier copy is still needed, so it was kept.",
);
fireEvent.click(screen.getByRole("button", { name: "Dismiss" }));
expect(b.dismiss).toHaveBeenCalled();
v.container.querySelector("[data-h3-media-tools-sha]")?.textContent,
).toBe(fixture.samples.status_setup_required.manual.archive_sha256);
});
});
describe("focus", () => {
it("moves focus to the status line after Install and to the primary control on a bump", () => {
const missing = read(wire("status_setup_required"));
const view = mount(missing);
const install = screen.getByRole("button", { name: "Install" });
install.focus();
fireEvent.click(install);
view.rerender(read(wire("status_installing")));
expect(document.activeElement?.getAttribute("data-h3-focus-key")).toBe(
"settings-media-tools",
);
view.rerender(read(wire("status_install_failed"), { focusPrimary: 1 }));
expect(document.activeElement?.textContent).toBe("Install again");
expect(document.activeElement?.getAttribute("data-h3-focus-key")).toBe(
"media-tools-primary",
);
});
it("never takes focus for a card the user did not act in", () => {
const outside = document.createElement("button");
document.body.append(outside);
outside.focus();
const view = mount(read(wire("status_setup_required")));
act(() => {
view.rerender(read(wire("status_installing")));
});
view.rerender(read(wire("status_install_failed"), { focusPrimary: 2 }));
expect(document.activeElement).toBe(outside);
outside.remove();
});
});
describe("copy", () => {
it("renders every state in three locales without machine tokens or locators", () => {
const states: MediaRuntimeState[] = [
initialMediaRuntimeState,
read(wire("status_setup_required")),
read(wire("status_installing")),
read(wire("status_install_failed"), {
notice: "outcome_unknown",
refusal: "setup_busy",
}),
read(wire("status_ready_recovery"), { notice: "continued" }),
read(wire("status_local_selection")),
read(wire("status_override"), { status: "unavailable" }),
];
for (const locale of LOCALES)
for (const state of states) {
const { card } = mount(state, { locale });
const text = card().textContent ?? "";
expect(text, locale).not.toMatch(MACHINE_TOKEN);
expect(text).not.toMatch(/[A-Za-z]:[\\/]|sha256|ffprobe\.exe/u);
cleanup();
}
});
});
describe("contextual visibility", () => {
const missing = read(wire("status_setup_required"));
const ready = read(wire("status_override"));
it("shows a blocked surface until the feature is known ready", () => {
expect(
mediaToolsCardVisible(initialMediaRuntimeState, "preview", true),
).toBe(true);
expect(mediaToolsCardVisible(missing, "preview", true)).toBe(true);
expect(mediaToolsCardVisible(ready, "preview", true)).toBe(false);
expect(
mediaToolsCardVisible(
{ ...ready, notice: "select_again" },
"preview",
true,
),
).toBe(true);
});
it("shows an unblocked surface only for a known missing runtime when asked", () => {
expect(mediaToolsCardVisible(missing, "import", false)).toBe(false);
expect(mediaToolsCardVisible(missing, "import", false, true)).toBe(true);
expect(mediaToolsCardVisible(ready, "import", false, true)).toBe(false);
});
it("follows a running job only on the surface whose action is waiting", () => {
const running: MediaRuntimeState = {
...read(wire("status_installing")),
job: RUNNING,
pending: IMPORT_INTENT,
it.each(["en", "zh-TW", "zh-CN"] as const)(
"shows manual instructions and a primary folder selection in %s",
async (locale) => {
const b = binding();
const clipboard = vi.fn(async () => undefined);
Object.defineProperty(navigator, "clipboard", {
configurable: true,
value: { writeText: clipboard },
});
const v = render(
<MediaToolsCard placement="settings" binding={b} locale={locale} />,
);
expect(b.ensure).toHaveBeenCalledTimes(1);
const input = screen.getByRole("textbox");
const button = v.container.querySelector<HTMLButtonElement>(
'[data-h3-media-tools-action="primary"]',
)!;
expect(input.closest("details")).toBeNull();
expect(button.disabled).toBe(true);
fireEvent.change(input, { target: { value: " C:/tools/bin " } });
fireEvent.click(button);
expect(b.useLocalDirectory).toHaveBeenCalledWith("C:/tools/bin");
expect(
screen.getByText(
fixture.samples.status_setup_required.manual.archive_name,
),
).toBeTruthy();
fireEvent.click(
v.container.querySelector('[data-h3-media-tools-action="copy"]')!,
);
await waitFor(() =>
expect(clipboard).toHaveBeenCalledWith(
fixture.samples.status_setup_required.manual.archive_sha256,
),
);
fireEvent.click(
v.container.querySelector('[data-h3-media-tools-action="rescan"]')!,
);
expect(b.rescan).toHaveBeenCalledTimes(1);
expect(v.container.querySelector("progress")).toBeNull();
},
);
it("shows earlier-version readiness and only explicit cleanup", () => {
const b = binding();
b.state = {
...b.state,
wire: decodeMediaRuntimeStatus(fixture.samples.status_ready_recovery),
};
expect(mediaToolsCardVisible(running, "import", false)).toBe(true);
expect(mediaToolsCardVisible(running, "render", false)).toBe(false);
expect(mediaToolsCardVisible(running, "render", true)).toBe(true);
render(<MediaToolsCard placement="settings" binding={b} locale="en" />);
expect(screen.getByText("Set up by an earlier version")).toBeTruthy();
expect(b.reclaim).not.toHaveBeenCalled();
fireEvent.click(
screen.getByRole("button", { name: "Clean up earlier setup files" }),
);
expect(b.reclaim).toHaveBeenCalledTimes(1);
});
it("a failed read cannot display cached readiness", () => {
const b = binding();
expect(deriveMediaToolsView({ ...b.state, status: "unavailable" })).toEqual(
{ kind: "status_unavailable" },
);
});
it("an unavailable renderer has no setup controls", () => {
const b = binding();
const raw = JSON.parse(JSON.stringify(fixture.samples.status_override));
raw.features.render = {
state: "unavailable",
reason: "render_qualification_unavailable",
};
b.state = { ...b.state, wire: decodeMediaRuntimeStatus(raw) };
render(
<MediaToolsCard
placement="contextual-overlay"
feature="render"
binding={b}
locale="en"
/>,
);
expect(screen.queryByRole("textbox")).toBeNull();
expect(screen.queryByRole("button", { name: "Use folder" })).toBeNull();
expect(
screen.queryByRole("link", { name: "Open download page" }),
).toBeNull();
});
});
+21 -77
View File
@@ -12,7 +12,7 @@ import {
} from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
import wireFixture from "./fixtures/media_runtime_wire_v3.json";
import wireFixture from "./fixtures/media_runtime_wire_v4.json";
import { AuthoringPreviewMonitor } from "../src/components/AuthoringPreviewMonitor";
import { NleExportMenu } from "../src/components/nle/NleExportMenu";
import { NleWorkspace } from "../src/components/nle/NleWorkspace";
@@ -29,7 +29,6 @@ import { decodeProductionWorkbenchProjection } from "../src/contracts/production
import { UNSUPPORTED_OUTPUT_CAPABILITY } from "../src/host/authoringOutputCapabilityClient";
import {
initialMediaRuntimeState,
intentIdentity,
type MediaRuntimeIntent,
type MediaRuntimeState,
type MediaToolsBinding,
@@ -54,8 +53,6 @@ function tools(state: MediaRuntimeState): MediaToolsBinding {
state,
ensure: vi.fn(),
report: vi.fn(),
install: vi.fn(),
cancel: vi.fn(),
dismiss: vi.fn(),
rescan: vi.fn(),
reclaim: vi.fn(),
@@ -273,7 +270,7 @@ describe("Production import placement", () => {
expect(screen.getByText(/Import completed/u)).toBeTruthy();
});
it("shows the card under a runtime-refused import and continues the eligible selection", () => {
it("shows the card under a runtime-refused import and offers manual selection", () => {
const media = tools(initialMediaRuntimeState);
const { view } = mount(refused, media);
const card = view.container.querySelector<HTMLElement>(
@@ -284,16 +281,12 @@ describe("Production import placement", () => {
cleanup();
const missing = tools(readState(wire("status_setup_required")));
mount(refused, missing);
fireEvent.click(
screen.getByRole("button", { name: "Install and continue" }),
fireEvent.change(
screen.getByRole("textbox", { name: "FFmpeg bin folder" }),
{ target: { value: "C:/tools/bin" } },
);
expect(missing.install).toHaveBeenCalledWith({
kind: "production_import",
productionWorkspaceHandle: `pw_${"p".repeat(32)}`,
productionWorkspaceId: "workspace.1",
segmentIds: ["segment.1"],
outputHandles: [READY_HANDLE],
});
fireEvent.click(screen.getByRole("button", { name: "Use folder" }));
expect(missing.useLocalDirectory).toHaveBeenCalledWith("C:/tools/bin");
});
it("needs only the original action when the runtime is ready", () => {
@@ -341,7 +334,7 @@ describe("clip preview placement", () => {
overlayGeneration: null,
};
it("reports an unsupported preview, offers setup and reopens once on its own continuation", async () => {
it("reports an unsupported preview, offers setup without automatically reopening", async () => {
vi.spyOn(URL, "createObjectURL").mockReturnValue("blob:active");
vi.spyOn(URL, "revokeObjectURL").mockImplementation(() => undefined);
let runtimeReady = false;
@@ -367,63 +360,16 @@ describe("clip preview placement", () => {
await screen.findByText("Preview unavailable for this source format.");
// The card reports from its mount effect, which can flush after the text is found under load.
await waitFor(() => expect(missing.report).toHaveBeenCalledWith("preview"));
fireEvent.click(
screen.getByRole("button", { name: "Install and continue" }),
fireEvent.change(
screen.getByRole("textbox", { name: "FFmpeg bin folder" }),
{ target: { value: "C:/tools/bin" } },
);
expect(missing.install).toHaveBeenCalledWith(intent);
expect(openPreview).toHaveBeenCalledTimes(1);
fireEvent.click(screen.getByRole("button", { name: "Use folder" }));
expect(missing.useLocalDirectory).toHaveBeenCalledWith("C:/tools/bin");
runtimeReady = true;
// A continuation for another clip does not reopen this one.
const ready = readState(wire("status_override"));
act(() =>
result.rerender(
view(
tools({
...ready,
resume: {
kind: "clip_preview",
token: 1,
identity: intentIdentity({ ...intent, clipId: "clip-2" }),
},
}),
),
),
);
act(() => result.rerender(view(tools(readState(wire("status_override"))))));
expect(openPreview).toHaveBeenCalledTimes(1);
act(() =>
result.rerender(
view(
tools({
...ready,
resume: {
kind: "clip_preview",
token: 2,
identity: intentIdentity(intent),
},
}),
),
),
);
await screen.findByLabelText("Preview clip-1");
expect(openPreview).toHaveBeenCalledTimes(2);
expect(result.container.querySelector("[data-h3-media-tools]")).toBeNull();
// Re-rendering with the same token never reopens it again.
act(() =>
result.rerender(
view(
tools({
...ready,
resume: {
kind: "clip_preview",
token: 2,
identity: intentIdentity(intent),
},
}),
),
),
);
await waitFor(() => expect(openPreview).toHaveBeenCalledTimes(2));
});
it("keeps a genuinely unsupported source format free of setup once the runtime is ready", async () => {
@@ -484,7 +430,7 @@ describe("final output placement and empty timeline", () => {
);
}
it("offers setup under an unsupported render and captures the snapshot and overlay", () => {
it("offers setup under an unsupported render with context wording", () => {
const media = tools(readState(wire("status_setup_required")));
const view = workspace(media);
expect(
@@ -497,15 +443,13 @@ describe("final output placement and empty timeline", () => {
)!;
expect(card.dataset.h3MediaTools).toBe("setup_required");
expect(media.report).toHaveBeenCalledWith("render");
fireEvent.click(
screen.getByRole("button", { name: "Install and continue" }),
fireEvent.change(
screen.getByRole("textbox", { name: "FFmpeg bin folder" }),
{ target: { value: "C:/tools/bin" } },
);
const captured = (media.install as ReturnType<typeof vi.fn>).mock
.calls[0]![0] as MediaRuntimeIntent;
expect(captured).toMatchObject({
kind: "final_render",
overlayGeneration: 1,
});
fireEvent.click(screen.getByRole("button", { name: "Use folder" }));
expect(media.useLocalDirectory).toHaveBeenCalledWith("C:/tools/bin");
expect(card.dataset.h3MediaToolsContext).toBe("final_render");
// The render action itself is never started from here.
expect(screen.queryByRole("button", { name: /render/i })).toBeNull();
});
@@ -49,7 +49,7 @@
"path": "frontend/src/entry.tsx"
}
],
"fingerprint": "sha256:e78cb35dd8e94f1d516edd3ad2fef4ea25cff94efb8f8891d40f9546a2b54e42",
"fingerprint": "sha256:33cc22be286ab3dd149111bf0b2cad35de580dd147bad31b8866f04c98ea53db",
"known_violations": [],
"modules": [
{
@@ -803,7 +803,7 @@
"comfyui_h3_context/core/safe_paths.py"
],
"language": "python",
"lines": 3767,
"lines": 3792,
"path": "comfyui_h3_context/adapters/av_reconstruction_media.py",
"source_reachability": {
"class": "product",
@@ -1354,13 +1354,13 @@
"comfyui_h3_context/adapters/comfyui_route_seam.py",
"comfyui_h3_context/adapters/composition_root.py",
"comfyui_h3_context/adapters/media_runtime_discovery_worker.py",
"comfyui_h3_context/adapters/media_runtime_download.py",
"comfyui_h3_context/adapters/media_runtime_installer.py",
"comfyui_h3_context/adapters/media_runtime_leftovers.py",
"comfyui_h3_context/adapters/media_runtime_manager.py",
"comfyui_h3_context/adapters/media_runtime_pin.py",
"comfyui_h3_context/adapters/media_runtime_resolution.py"
],
"language": "python",
"lines": 745,
"lines": 473,
"path": "comfyui_h3_context/adapters/comfyui_media_runtime_setup.py",
"source_reachability": {
"class": "product",
@@ -2205,42 +2205,16 @@
"retained_reason": "reachable from a shipped entry point"
}
},
{
"imports": [
"comfyui_h3_context/adapters/prompt_model_transport.py",
"comfyui_h3_context/core/prompt_model_provider.py"
],
"language": "python",
"lines": 360,
"path": "comfyui_h3_context/adapters/media_runtime_download.py",
"source_reachability": {
"class": "product",
"evidence": "product_closure",
"owners": [
"comfyui_h3_context/__init__.py",
"comfyui_h3_context/adapters/assisted_draft_execution.py",
"comfyui_h3_context/adapters/authoring_derivative_generator.py",
"comfyui_h3_context/adapters/authoring_derivative_source.py",
"comfyui_h3_context/adapters/authoring_generated_source.py",
"comfyui_h3_context/adapters/authoring_image_source.py",
"comfyui_h3_context/adapters/authoring_native_renderer.py",
"comfyui_h3_context/adapters/authoring_output_preview.py"
],
"retained_reason": "reachable from a shipped entry point"
}
},
{
"imports": [
"comfyui_h3_context/adapters/executable_admission.py",
"comfyui_h3_context/adapters/media_runtime_download.py",
"comfyui_h3_context/adapters/media_runtime_pin.py",
"comfyui_h3_context/adapters/media_runtime_resolution.py",
"comfyui_h3_context/adapters/segment_artifact_store.py",
"comfyui_h3_context/core/av_reconstruction.py",
"comfyui_h3_context/core/safe_paths.py"
"comfyui_h3_context/adapters/segment_artifact_store.py"
],
"language": "python",
"lines": 960,
"path": "comfyui_h3_context/adapters/media_runtime_installer.py",
"lines": 289,
"path": "comfyui_h3_context/adapters/media_runtime_leftovers.py",
"source_reachability": {
"class": "product",
"evidence": "product_closure",
@@ -2285,6 +2259,30 @@
"retained_reason": "reachable from a shipped entry point"
}
},
{
"imports": [
"comfyui_h3_context/adapters/media_runtime_resolution.py",
"comfyui_h3_context/core/av_reconstruction.py"
],
"language": "python",
"lines": 52,
"path": "comfyui_h3_context/adapters/media_runtime_pin.py",
"source_reachability": {
"class": "product",
"evidence": "product_closure",
"owners": [
"comfyui_h3_context/__init__.py",
"comfyui_h3_context/adapters/assisted_draft_execution.py",
"comfyui_h3_context/adapters/authoring_derivative_generator.py",
"comfyui_h3_context/adapters/authoring_derivative_source.py",
"comfyui_h3_context/adapters/authoring_generated_source.py",
"comfyui_h3_context/adapters/authoring_image_source.py",
"comfyui_h3_context/adapters/authoring_native_renderer.py",
"comfyui_h3_context/adapters/authoring_output_preview.py"
],
"retained_reason": "reachable from a shipped entry point"
}
},
{
"imports": [
"comfyui_h3_context/adapters/composition_root.py",
@@ -9071,7 +9069,7 @@
"frontend/src/state/mediaRuntimeState.ts"
],
"language": "typescript",
"lines": 611,
"lines": 597,
"path": "frontend/src/components/AuthoringPreviewMonitor.tsx",
"source_reachability": {
"class": "product",
@@ -9159,7 +9157,7 @@
"frontend/src/state/mediaRuntimeState.ts"
],
"language": "typescript",
"lines": 603,
"lines": 531,
"path": "frontend/src/components/MediaToolsCard.tsx",
"source_reachability": {
"class": "product",
@@ -10784,7 +10782,7 @@
"frontend/src/i18n/catalog.ts"
],
"language": "typescript",
"lines": 1071,
"lines": 1022,
"path": "frontend/src/components/plainReasons.ts",
"source_reachability": {
"class": "product",
@@ -11107,7 +11105,7 @@
{
"imports": [],
"language": "typescript",
"lines": 400,
"lines": 301,
"path": "frontend/src/contracts/mediaRuntimeCodec.ts",
"source_reachability": {
"class": "product",
@@ -12384,7 +12382,7 @@
"frontend/src/contracts/mediaRuntimeCodec.ts"
],
"language": "typescript",
"lines": 236,
"lines": 199,
"path": "frontend/src/host/mediaRuntimeClient.ts",
"source_reachability": {
"class": "product",
@@ -13195,7 +13193,7 @@
"frontend/src/state/mediaRuntimeState.ts"
],
"language": "typescript",
"lines": 571,
"lines": 237,
"path": "frontend/src/lifecycle/mediaRuntimeSession.ts",
"source_reachability": {
"class": "product",
@@ -13362,7 +13360,7 @@
"frontend/src/state/shellState.ts"
],
"language": "typescript",
"lines": 797,
"lines": 796,
"path": "frontend/src/lifecycle/presentationBinding.tsx",
"source_reachability": {
"class": "product",
@@ -14152,7 +14150,7 @@
"frontend/src/host/mediaRuntimeClient.ts"
],
"language": "typescript",
"lines": 138,
"lines": 83,
"path": "frontend/src/state/mediaRuntimeState.ts",
"source_reachability": {
"class": "product",
@@ -14435,18 +14433,6 @@
"response"
]
},
{
"handler": "_read_job",
"method": "GET",
"module": "comfyui_h3_context/adapters/comfyui_media_runtime_setup.py",
"path_symbol": "JOB_ROUTE",
"responsibilities": [
"application",
"decode",
"domain",
"response"
]
},
{
"handler": "_read_managed_sequence",
"method": "GET",
@@ -364,8 +364,9 @@
"adapters.managed_asset_resolution",
"adapters.managed_mode_qualification",
"adapters.managed_sequence_service",
"adapters.media_runtime_installer",
"adapters.media_runtime_leftovers",
"adapters.media_runtime_manager",
"adapters.media_runtime_pin",
"adapters.media_runtime_resolution",
"adapters.production_assembly_execution",
"adapters.production_authoring_import_service",
@@ -1903,10 +1904,10 @@
],
"edge_kind_totals": {
"function_local": 111,
"module_level": 1757,
"module_level": 1755,
"type_checking": 128
},
"fingerprint": "sha256:2ef37a73bfd835e63ffdad70e1cfb182618baa76c4194bc951d39b5f70cd3a10",
"fingerprint": "sha256:5ffe538dc89b42b76e232665ed4f29401792cad5fa5f3a113a35916ac9ba5dab",
"forbidden_imports": [],
"layer_inversions": [],
"modules": [
@@ -1960,6 +1961,7 @@
"tests/test_m25_29_production_authoring_import.py",
"tests/test_m25_30_media_runtime_resolution.py",
"tests/test_m25_32_media_runtime_activation.py",
"tests/test_m25_33_media_setup_entry.py",
"tests/test_m25_authoring_audio_rate_compatibility.py",
"tests/test_m25_authoring_initialization.py",
"tests/test_m25_authoring_media_leases.py",
@@ -1976,6 +1978,7 @@
"tests/test_m26_05_public_assembly_requalification.py",
"tests/test_managed_artifact_scopes.py",
"tests/test_managed_sequence_expiry_recovery.py",
"tests/test_manual_media_tools.py",
"tests/test_media_lease_completion.py",
"tests/test_media_preview.py",
"tests/test_native_composition.py",
@@ -2519,7 +2522,7 @@
"disposition": "movable",
"inbound": 19,
"layer": "adapters",
"lines": 3767,
"lines": 3792,
"module": "adapters.av_reconstruction_media",
"outbound": 10,
"owning_rules": [
@@ -2926,16 +2929,17 @@
"disposition": "movable",
"inbound": 2,
"layer": "adapters",
"lines": 745,
"lines": 473,
"module": "adapters.comfyui_media_runtime_setup",
"outbound": 7,
"owning_rules": [
"direct_module"
"direct_module",
"submodule_as_name"
],
"owning_tests": [
"tests/test_m25_31_media_runtime_setup.py",
"tests/test_m25_32_media_runtime_activation.py",
"tests/test_m25_33_media_setup_entry.py"
"tests/test_m25_33_media_setup_entry.py",
"tests/test_manual_media_tools.py"
],
"reasons": []
},
@@ -3344,7 +3348,6 @@
],
"owning_tests": [
"tests/test_m25_30_media_runtime_resolution.py",
"tests/test_m25_31_media_runtime_setup.py",
"tests/test_m25_33_media_setup_entry.py",
"tests/test_m25_74_derivative_rework_counts.py",
"tests/test_m25_74_executable_pin_scope.py"
@@ -3527,24 +3530,7 @@
"direct_module"
],
"owning_tests": [
"tests/test_m25_30_media_runtime_resolution.py",
"tests/test_m25_31_media_runtime_setup.py",
"tests/test_m25_33_media_setup_entry.py"
],
"reasons": []
},
{
"disposition": "movable",
"inbound": 2,
"layer": "adapters",
"lines": 360,
"module": "adapters.media_runtime_download",
"outbound": 2,
"owning_rules": [
"direct_module"
],
"owning_tests": [
"tests/test_m25_31_media_runtime_setup.py"
"tests/test_m25_30_media_runtime_resolution.py"
],
"reasons": []
},
@@ -3552,14 +3538,13 @@
"disposition": "movable",
"inbound": 1,
"layer": "adapters",
"lines": 960,
"module": "adapters.media_runtime_installer",
"outbound": 6,
"lines": 289,
"module": "adapters.media_runtime_leftovers",
"outbound": 4,
"owning_rules": [
"direct_module"
"submodule_as_name"
],
"owning_tests": [
"tests/test_m25_31_media_runtime_setup.py",
"tests/test_m25_33_media_setup_entry.py"
],
"reasons": []
@@ -3586,7 +3571,22 @@
},
{
"disposition": "movable",
"inbound": 11,
"inbound": 2,
"layer": "adapters",
"lines": 52,
"module": "adapters.media_runtime_pin",
"outbound": 2,
"owning_rules": [
"direct_module"
],
"owning_tests": [
"tests/test_m25_33_media_setup_entry.py"
],
"reasons": []
},
{
"disposition": "movable",
"inbound": 12,
"layer": "adapters",
"lines": 1466,
"module": "adapters.media_runtime_resolution",
@@ -3598,7 +3598,6 @@
"tests/test_comfyui_media_runtime.py",
"tests/test_m23_67_posix_host_roots.py",
"tests/test_m25_30_media_runtime_resolution.py",
"tests/test_m25_31_media_runtime_setup.py",
"tests/test_m25_32_media_runtime_activation.py",
"tests/test_m25_33_media_setup_entry.py",
"tests/test_m25_authoring_output_runtime.py",
@@ -3909,7 +3908,7 @@
},
{
"disposition": "movable",
"inbound": 3,
"inbound": 2,
"layer": "adapters",
"lines": 1583,
"module": "adapters.prompt_model_transport",
@@ -3930,7 +3929,6 @@
"tests/test_m22_19_discovery_census_bound.py",
"tests/test_m22_20_reachability_fidelity.py",
"tests/test_m22_23_boundary_backstop.py",
"tests/test_m25_31_media_runtime_setup.py",
"tests/test_model_discovery_metadata.py",
"tests/test_prompt_model_dialects.py",
"tests/test_prompt_model_session.py",
@@ -4735,7 +4733,6 @@
"tests/test_av_seam_store.py",
"tests/test_m17_14_production_closeout.py",
"tests/test_m25_30_media_runtime_resolution.py",
"tests/test_m25_31_media_runtime_setup.py",
"tests/test_m25_77_clip_audio_amplitude.py",
"tests/test_m25_authoring_audio_rate_compatibility.py",
"tests/test_media_preview.py",
@@ -7335,7 +7332,7 @@
},
{
"disposition": "movable",
"inbound": 23,
"inbound": 22,
"layer": "core",
"lines": 2912,
"module": "core.prompt_model_provider",
@@ -7362,7 +7359,6 @@
"tests/test_m22_20_reachability_fidelity.py",
"tests/test_m22_22_credential_encodability.py",
"tests/test_m22_23_boundary_backstop.py",
"tests/test_m25_31_media_runtime_setup.py",
"tests/test_model_discovery_metadata.py",
"tests/test_prompt_model_budget.py",
"tests/test_prompt_model_dialects.py",
@@ -7996,7 +7992,7 @@
},
{
"disposition": "movable",
"inbound": 21,
"inbound": 20,
"layer": "core",
"lines": 145,
"module": "core.safe_paths",
@@ -3345,17 +3345,6 @@
"kind": "contract",
"rule": "typed_runtime_wire_is_semantic"
},
{
"authority_paths": [
"comfyui_h3_context/adapters/media_runtime_installer.py"
],
"consumer_id": "h3.context.managed_media_runtime_source.v1",
"domain": "semantic",
"domain_version": 1,
"evidence": "a typed runtime wire carries the instance values that decide execution, cache reuse or a receipt",
"kind": "contract",
"rule": "typed_runtime_wire_is_semantic"
},
{
"authority_paths": [
"comfyui_h3_context/core/managed_sequence.py"
@@ -3680,7 +3669,7 @@
"authority_paths": [
"comfyui_h3_context/adapters/comfyui_media_runtime_setup.py"
],
"consumer_id": "h3.context.media_runtime_setup_job.v1",
"consumer_id": "h3.context.media_runtime_setup_request.v2",
"domain": "semantic",
"domain_version": 1,
"evidence": "a typed runtime wire carries the instance values that decide execution, cache reuse or a receipt",
@@ -3691,18 +3680,7 @@
"authority_paths": [
"comfyui_h3_context/adapters/comfyui_media_runtime_setup.py"
],
"consumer_id": "h3.context.media_runtime_setup_request.v1",
"domain": "semantic",
"domain_version": 1,
"evidence": "a typed runtime wire carries the instance values that decide execution, cache reuse or a receipt",
"kind": "contract",
"rule": "typed_runtime_wire_is_semantic"
},
{
"authority_paths": [
"comfyui_h3_context/adapters/comfyui_media_runtime_setup.py"
],
"consumer_id": "h3.context.media_runtime_status.v3",
"consumer_id": "h3.context.media_runtime_status.v4",
"domain": "semantic",
"domain_version": 1,
"evidence": "a typed runtime wire carries the instance values that decide execution, cache reuse or a receipt",
@@ -6275,6 +6253,6 @@
"rule": "declared_identity_site"
}
],
"fingerprint": "sha256:b7989e903645f35a9421163309f225a8f8ff9b5f9fe84e5501bff862f1da760b",
"fingerprint": "sha256:f5fd4abbfce09cdf02c8b74a79c728c427df599d93edad25215292d046c4c4ab",
"schema": "h3-context-fingerprint-domain-assignment/1"
}
File diff suppressed because one or more lines are too long
+31 -26
View File
@@ -27,7 +27,7 @@
},
{
"path": "comfyui_h3_context/contracts/build_provenance_v1.json",
"sha256": "sha256:9d9d5d0e3f2cfd484c7881aa8aef57eab2f38d252354cd180a8c94e3cec68b29",
"sha256": "sha256:2944b1d321c272cc552f22c8ef1033ef8925ea4317015185d89444e4222b7eb0",
"size": 1712
},
{
@@ -42,7 +42,7 @@
},
{
"path": "comfyui_h3_context/contracts/installation_profiles_v1.json",
"sha256": "sha256:cabbf16655a297d8a1e96cfdc869b13d15c0f4e661266c500310a7fac8269c2c",
"sha256": "sha256:48eb69f0fda12aacb0f52d3c0960d240a747fed604da73ef1e1730dec0ca52e7",
"size": 3377
},
{
@@ -67,7 +67,7 @@
},
{
"path": "frontend/package.json",
"sha256": "sha256:5e72016628a9e99d77138c622213e2ed69ed0e380f3f98219855ff193303a33e",
"sha256": "sha256:860f5cebd1d88370b879d96c4288d6be8eb0be714feb89183539b339aa92cdd4",
"size": 1307
},
{
@@ -92,8 +92,8 @@
},
{
"path": "frontend/src/components/AuthoringPreviewMonitor.tsx",
"sha256": "sha256:ac4fdaa79704b704ee380c0e33e90a3c10b07b7338d4951ae67b6b5be16da577",
"size": 20142
"sha256": "sha256:a48026cf7c6f47b61b8c6b39828425ca5ce4c8f05974fbeb99ad383b90be0274",
"size": 19528
},
{
"path": "frontend/src/components/CompositionPreview.tsx",
@@ -107,8 +107,8 @@
},
{
"path": "frontend/src/components/MediaToolsCard.tsx",
"sha256": "sha256:c8ec35586c5c2bebe1092c71cd2055000d2b75534c06f22614c1be82cf308d3a",
"size": 22542
"sha256": "sha256:b678719e43adf6ee7f25ee5b1d965049d8c1fc3c9925556d753e73051d8cccd0",
"size": 19566
},
{
"path": "frontend/src/components/NoticeSurface.tsx",
@@ -190,6 +190,11 @@
"sha256": "sha256:c5f0489d38354b38bf5eae9c42fe900fdfa3d22d23c0146e85281f23dc02892e",
"size": 4308
},
{
"path": "frontend/src/components/mediaToolsCard.css",
"sha256": "sha256:4f48a4cd367ea474fd220816292f63fbc8491226dbba174156f5d85a7af6a8c4",
"size": 1927
},
{
"path": "frontend/src/components/nle/NleAuthoringAssetBin.tsx",
"sha256": "sha256:f4995075266f35d6b919fbcbcf27adaa69db46ef95322e9ced89342deffbf11d",
@@ -492,8 +497,8 @@
},
{
"path": "frontend/src/components/plainReasons.ts",
"sha256": "sha256:e37bfabcb94e149f9f8dad4c48f1ffcbd789093e40c577ade7bc8eedbd13919d",
"size": 57077
"sha256": "sha256:1b0db076f7bb9ceeb7438eac6f652ba9a7e9d522e6b778e7a30649fbf1d28f48",
"size": 53288
},
{
"path": "frontend/src/components/productionStateLabels.ts",
@@ -597,8 +602,8 @@
},
{
"path": "frontend/src/contracts/mediaRuntimeCodec.ts",
"sha256": "sha256:bc0303420c32418f9cd159e2f1ebdf21a750a2d710509e062e5772164cd791ee",
"size": 11850
"sha256": "sha256:24054b7d47089ca4f3a785d0f78be33cefab61a270e6bea6b40df43aed8ca51c",
"size": 8741
},
{
"path": "frontend/src/contracts/nleReferenceUiContract.ts",
@@ -947,8 +952,8 @@
},
{
"path": "frontend/src/host/mediaRuntimeClient.ts",
"sha256": "sha256:0e4f5f6b885ccca1f8c68bc0a24c076ec783e951d19cb0a513f133c4efe0c99a",
"size": 7594
"sha256": "sha256:ec65f95b0d7d49c855113959e0c4f8dcbe4735d84e94b3a129575e9ccb8a5adc",
"size": 6090
},
{
"path": "frontend/src/host/modalKeyboardGuard.ts",
@@ -1172,8 +1177,8 @@
},
{
"path": "frontend/src/lifecycle/mediaRuntimeSession.ts",
"sha256": "sha256:1abab61dd66fb3baa8d730ed939a66b13c3f47edf877410c8dca4429d8e89bd2",
"size": 20982
"sha256": "sha256:5e050b899ca2aeb7bdbe4ad6fb5cb9d06fc26e0446651d415062a6eea645accf",
"size": 8392
},
{
"path": "frontend/src/lifecycle/mountController.tsx",
@@ -1202,8 +1207,8 @@
},
{
"path": "frontend/src/lifecycle/nleWorkspaceSession.ts",
"sha256": "sha256:9d85177435dd344005bf7f93059a0fc596452aff21522fbd1dc047c8a56c5597",
"size": 37574
"sha256": "sha256:572ff3609821d732e656804d38d34e3cccaf325b6e00289465fc474b97202cf7",
"size": 37526
},
{
"path": "frontend/src/lifecycle/perceptionHostSession.ts",
@@ -1212,8 +1217,8 @@
},
{
"path": "frontend/src/lifecycle/presentationBinding.tsx",
"sha256": "sha256:5758715ed8256150d914a434420904b5d90ff73eed35034c95882afedeedea25",
"size": 32378
"sha256": "sha256:f032a1a2c3c81d72941adc3826cd2d00a8e6bf1001aaf4214a3f108e71170843",
"size": 32279
},
{
"path": "frontend/src/lifecycle/projectFileSession.ts",
@@ -1417,8 +1422,8 @@
},
{
"path": "frontend/src/state/mediaRuntimeState.ts",
"sha256": "sha256:6254790c52cd142422ca97066e1eb778de54977e072cac3112a001a9180d53b4",
"size": 4114
"sha256": "sha256:4c4d72048b5aa5ebb53c0290050884976111fbcd4798aff8ce274dee0323fb31",
"size": 2606
},
{
"path": "frontend/src/state/nleWorkspaceState.ts",
@@ -1482,7 +1487,7 @@
},
{
"path": "governance/contracts/sbom.spdx.json",
"sha256": "sha256:3498975e7489c4e593334cb8234e8b6266258f1cc91ca2e6ef266483aa79ec0c",
"sha256": "sha256:724ebdec838086dcedc16c5a4c0a24c177bce233c8c716ab2ba6ddf2f1a7087c",
"size": 80683
},
{
@@ -1492,7 +1497,7 @@
},
{
"path": "pyproject.toml",
"sha256": "sha256:3e9a5ceefc0d388d4d2145f405640651763adefbd041dd480e2827ece916f909",
"sha256": "sha256:273779f45f552e1dd8fac31fdbba1774c1d7d4d151ecb92da7d0eb3067a8df62",
"size": 4112
},
{
@@ -1515,15 +1520,15 @@
"runtime_entries": [
{
"path": "comfyui_h3_context/web/h3-context-sidebar.js",
"sha256": "sha256:3b1731ddb750eefeed6ab16b1f9323f12081d7f15a824a8c7a3bd1600f90b770",
"size": 1917831
"sha256": "sha256:fefc67f48395bb9e64ee6cf8c4626e40259f9b2f433a411038b6ed4e238b83c7",
"size": 1909494
}
],
"schema": "h3-context-supply-chain/1",
"spdx": {
"package_count": 176,
"path": "governance/contracts/sbom.spdx.json",
"sha256": "sha256:3498975e7489c4e593334cb8234e8b6266258f1cc91ca2e6ef266483aa79ec0c",
"sha256": "sha256:724ebdec838086dcedc16c5a4c0a24c177bce233c8c716ab2ba6ddf2f1a7087c",
"version": "SPDX-2.3"
},
"version": 1
+1 -1
View File
@@ -5,7 +5,7 @@ backend-path = ["."]
[project]
name = "minimax-h3-studio"
version = "1.2.0"
version = "1.2.1"
description = "Turn a description into a finished MiniMax H3 video without leaving ComfyUI, prompt, segments, continuity and final cut in one workbench."
readme = "README.md"
requires-python = ">=3.10"
+81 -4
View File
@@ -250,7 +250,7 @@
{
"type": "Hex High Entropy String",
"filename": "comfyui_h3_context\\contracts\\build_provenance_v1.json",
"hashed_secret": "87a37aacaecf9444ad4f25fc00fcce70d6c68ec6",
"hashed_secret": "b5669e9060494dec2105f0c74d8f704a87a449c3",
"is_verified": false,
"line_number": 15,
"is_secret": false
@@ -258,7 +258,7 @@
{
"type": "Hex High Entropy String",
"filename": "comfyui_h3_context\\contracts\\build_provenance_v1.json",
"hashed_secret": "21c648511846f876d3d9840b86ba8c5fdadd5deb",
"hashed_secret": "868e55a24526a3f604cf10ce45f3167c7782cf1d",
"is_verified": false,
"line_number": 17,
"is_secret": false
@@ -16021,9 +16021,86 @@
"filename": "tests\\test_security_audit.py",
"hashed_secret": "2ac6cc12e26f45f3c013f2c80c4291a95c2f9a2b",
"is_verified": false,
"line_number": 497
"line_number": 493
}
],
"frontend\\tests\\fixtures\\media_runtime_wire_v4.json": [
{
"type": "Hex High Entropy String",
"filename": "frontend\\tests\\fixtures\\media_runtime_wire_v4.json",
"hashed_secret": "97c865565d3656458a5a29e764dbab1420ee9f56",
"is_verified": false,
"line_number": 34,
"is_secret": false
}
],
"scripts\\registry_policy_check.py": [
{
"type": "Hex High Entropy String",
"filename": "scripts\\registry_policy_check.py",
"hashed_secret": "1ff6ddf5e4a78673eb708ff6888033848aab76db",
"is_verified": false,
"line_number": 48,
"is_secret": false
},
{
"type": "Hex High Entropy String",
"filename": "scripts\\registry_policy_check.py",
"hashed_secret": "2ce2444dcd1098da85cd4e765e3d7b4e2472f6e0",
"is_verified": false,
"line_number": 51,
"is_secret": false
},
{
"type": "Hex High Entropy String",
"filename": "scripts\\registry_policy_check.py",
"hashed_secret": "31ef50d07547e72f18046c6a302e2695754ec00a",
"is_verified": false,
"line_number": 52,
"is_secret": false
},
{
"type": "Hex High Entropy String",
"filename": "scripts\\registry_policy_check.py",
"hashed_secret": "5ecae9452985891efec3ec78c19e7d1fea9a7582",
"is_verified": false,
"line_number": 53,
"is_secret": false
},
{
"type": "Hex High Entropy String",
"filename": "scripts\\registry_policy_check.py",
"hashed_secret": "db63b01fa635597b112a3639e2924f285ee35a93",
"is_verified": false,
"line_number": 56,
"is_secret": false
},
{
"type": "Hex High Entropy String",
"filename": "scripts\\registry_policy_check.py",
"hashed_secret": "2a9e05f8ae85537fa65cbdecd652b42fc46f4408",
"is_verified": false,
"line_number": 59,
"is_secret": false
},
{
"type": "Hex High Entropy String",
"filename": "scripts\\registry_policy_check.py",
"hashed_secret": "905cb69434b6ef833bc85b53013ae838a2c54f09",
"is_verified": false,
"line_number": 60,
"is_secret": false
}
],
"tests\\test_m25_54_supplied_host_lane.py": [
{
"type": "Base64 High Entropy String",
"filename": "tests\\test_m25_54_supplied_host_lane.py",
"hashed_secret": "00575934ead2bc93a2a88f5f867284e420a8e28b",
"is_verified": false,
"line_number": 103
}
]
},
"generated_at": "2026-10-12T04:46:46Z"
"generated_at": "2026-10-12T13:49:55Z"
}
+223
View File
@@ -0,0 +1,223 @@
"""Offline code-install policy guard for packaged runtime sources and Registry ZIPs.
This is a bounded regression guard, not an assertion of a Registry review outcome.
ZIP members are read in memory; no member is extracted or executed.
"""
from __future__ import annotations
import argparse
import ast
import hashlib
import re
import zipfile
from pathlib import Path, PurePosixPath
ROOT = Path(__file__).resolve().parents[1]
MAX_MEMBER_BYTES = 32 * 1024 * 1024
RETIRED = (
"media_runtime_download",
"media_runtime_installer",
"install_supported",
"cancel_setup",
"media_runtime_setup_job",
"/media-runtime/setup/{job_id}",
)
FORBIDDEN_MODULES = frozenset({"zipfile", "tarfile", "ensurepip", "venv", "pip"})
FORBIDDEN_CALLS = frozenset(
{
"eval",
"exec",
"builtins.eval",
"builtins.exec",
"os.system",
"shutil.unpack_archive",
"base64.b64decode",
"marshal.loads",
"codecs.decode",
"__import__",
}
)
INSTALL_WORD = re.compile(r"(?:^|[\s/\\])(?:pip(?:3)?|ensurepip|uv|venv)(?:$|[\s.])", re.I)
DOWNLOAD_URL = re.compile(r"https?://[^\s\"']*/releases/download/", re.I)
# Exact normalized call shapes, never a whole-module exemption. Existing sandbox/probe calls
# have fixed ownership and remain separately guarded by the runtime security audit.
SUBPROCESS_CALL_PINS = {
"adapters/media_runtime_resolution.py": {
"ad6fa6029288f9009dab9f2d6bd12138d8b3bdd0fe616f819864a4cf9da18899"
}, # fixed isolated discovery worker
"adapters/media_subprocess.py": { # admitted spawn and bounded process-tree termination
"dba75ea2973f80cb095154e0f1cf407ffa9382062e4fb8fc9008235ee6a3c4f9",
"c7a722d3953267817018d913d36991c5e8abeb8f7c3b975e38b5f91ef8e13bf7",
"fb5272f38db378271c33689146c61304f10ba44c215c5dd1c42ebea9c654da7d",
},
"adapters/perception_host.py": {
"6ddd71485e539063b1ba2c571a02c5ce250d52d9a98edc517d7f0f56ac76c2d5"
}, # owned perception worker, admitted interpreter
"adapters/prompt_model_transport.py": { # fixed isolated dependency and address probes
"3ac7acab13247f837f1119eba9efc66cb7c19857153e615acf174f6398708d56",
"a64bc08c2f59c558130553d7d2b882e236715988673d567a6c1f707ccb0034df",
},
}
PCM_DECODE_SHAPE = ast.dump(
ast.parse('base64.b64decode(str(job["samples"]), validate=True)', mode="eval").body,
include_attributes=False,
)
def canonical_shape(node: object) -> str:
"""A call's structure as text that is identical on every supported Python.
IMPORTANT: never hash ``ast.dump`` here. Its text changes between Python versions
(3.13 omits ``None`` and empty-list fields that 3.10 prints), so pins computed on one
interpreter read as unreviewed shapes on another, and the 3.10 CI and Registry
environments refuse a tree the 3.13 gate accepted. Absent, ``None`` and empty fields
are skipped explicitly and positions are never included.
"""
if isinstance(node, ast.AST):
fields = []
for name in node._fields:
value = getattr(node, name, None)
# A constant's value is required even when it is None; only optional fields are
# omitted, which is what makes the text stable across versions.
required = isinstance(node, ast.Constant) and name == "value"
if not required and (value is None or (isinstance(value, list) and not value)):
continue
fields.append(f"{name}={canonical_shape(value)}")
return f"{type(node).__name__}({', '.join(fields)})"
if isinstance(node, list):
return "[" + ", ".join(canonical_shape(value) for value in node) + "]"
return repr(node)
def call_shape(node: ast.Call) -> str:
return hashlib.sha256(canonical_shape(node).encode()).hexdigest()
def _qualified(node: ast.AST, aliases: dict[str, str]) -> str:
if isinstance(node, ast.Name):
return aliases.get(node.id, node.id)
if isinstance(node, ast.Attribute):
return f"{_qualified(node.value, aliases)}.{node.attr}"
return ""
def check_source(name: str, source: str) -> list[str]:
relative = name.split("comfyui_h3_context/", 1)[-1]
failures = [f"{name}: retired acquisition marker" for marker in RETIRED if marker in source]
if DOWNLOAD_URL.search(source):
failures.append(f"{name}: executable release download URL")
if not name.endswith(".py"):
return failures
try:
tree = ast.parse(source, filename=name)
except SyntaxError:
return [*failures, f"{name}: invalid Python"]
aliases: dict[str, str] = {}
for node in ast.walk(tree):
if isinstance(node, ast.Import):
for entry in node.names:
aliases[entry.asname or entry.name.split(".")[0]] = entry.name
if entry.name.split(".")[0] in FORBIDDEN_MODULES:
failures.append(f"{name}:{node.lineno}: archive/install import")
elif isinstance(node, ast.ImportFrom):
module = node.module or ""
for entry in node.names:
aliases[entry.asname or entry.name] = f"{module}.{entry.name}"
if module.split(".")[0] in FORBIDDEN_MODULES:
failures.append(f"{name}:{node.lineno}: archive/install import")
# Resolve simple callable aliases so renaming eval/system is not an escape hatch.
for node in ast.walk(tree):
if isinstance(node, ast.Assign):
value = _qualified(node.value, aliases)
if value:
for target in node.targets:
if isinstance(target, ast.Name):
aliases[target.id] = value
for node in ast.walk(tree):
if not isinstance(node, ast.Call):
continue
call = _qualified(node.func, aliases)
# PCM samples are decoded as bounded float data; this exact call does not decode code.
pcm_data = (
relative == "adapters/perception_worker.py"
and call == "base64.b64decode"
and ast.dump(node, include_attributes=False) == PCM_DECODE_SHAPE
)
if call in FORBIDDEN_CALLS and not pcm_data:
failures.append(f"{name}:{node.lineno}: dynamic execution/archive/obfuscation call")
if call.startswith("subprocess.") and call.rsplit(".", 1)[-1] in {
"Popen",
"run",
"call",
"check_call",
"check_output",
}:
shape = call_shape(node)
if shape not in SUBPROCESS_CALL_PINS.get(relative, set()):
failures.append(f"{name}:{node.lineno}: unreviewed subprocess shape")
literals = [
n.value
for arg in node.args
for n in ast.walk(arg)
if isinstance(n, ast.Constant) and isinstance(n.value, str)
]
if any(INSTALL_WORD.search(value) for value in literals):
failures.append(f"{name}:{node.lineno}: package installer subprocess")
return sorted(set(failures))
def check_path(path: Path) -> list[str]:
failures: list[str] = []
if path.is_dir():
runtime = path / "comfyui_h3_context" if (path / "comfyui_h3_context").is_dir() else path
for member in sorted(runtime.rglob("*")):
if member.is_file() and member.suffix in {".py", ".js"}:
failures.extend(
check_source(
member.relative_to(runtime).as_posix(), member.read_text(encoding="utf-8")
)
)
else:
with zipfile.ZipFile(path) as archive:
names = archive.namelist()
if not any("comfyui_h3_context" in PurePosixPath(name).parts for name in names):
return ["archive: runtime package missing"]
for info in archive.infolist():
parts = PurePosixPath(info.filename).parts
if (
".." in parts
or info.filename.startswith("/")
or info.file_size > MAX_MEMBER_BYTES
):
failures.append("archive: unsafe or oversized member")
continue
if "comfyui_h3_context" not in parts or PurePosixPath(info.filename).suffix not in {
".py",
".js",
}:
continue
try:
source = archive.read(info).decode("utf-8")
except (UnicodeDecodeError, zipfile.BadZipFile):
failures.append("archive: unreadable runtime source")
continue
failures.extend(check_source(info.filename, source))
return sorted(set(failures))
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("path", nargs="?", type=Path, default=ROOT)
args = parser.parse_args()
failures = check_path(args.path)
for failure in failures:
print(failure)
print(f"Registry code-install guard: {'FAIL' if failures else 'PASS'}")
return int(bool(failures))
if __name__ == "__main__":
raise SystemExit(main())
-8
View File
@@ -112,11 +112,6 @@ RUNTIME_ALLOWED_FORBIDDEN_IMPORTS = {
# environment, so a blocked filesystem call can be ended by killing it.
"adapters/media_runtime_discovery_worker.py": frozenset({"ctypes"}),
"adapters/media_runtime_resolution.py": frozenset({"subprocess"}),
# CRITICAL: the managed media runtime download is the only egress the installer has. It fetches
# one fixed release archive over verifying TLS, follows redirects only to the release-asset
# hosts, and connects to the single address the killable resolver validated. Archive
# validation, extraction and publication live in neighbouring modules that get none of this.
"adapters/media_runtime_download.py": frozenset({"http.client", "socket", "ssl"}),
# CRITICAL: the semantic Ollama lane owns one exact nonblocking loopback socket transport so
# its cumulative deadline cannot be renewed by lower-level HTTP timeouts.
"adapters/ollama_native.py": frozenset({"http.client", "socket"}),
@@ -195,9 +190,6 @@ RUNTIME_ALLOWED_NETWORK_CALLS = {
"adapters/prompt_model_transport.py": frozenset(
{"getaddrinfo", "socket.getaddrinfo", "socket.create_connection"}
),
# The media runtime download never resolves a name itself: it reuses the transport's killable
# resolver and only connects to the address that resolver already admitted.
"adapters/media_runtime_download.py": frozenset({"socket.create_connection"}),
}
PRIVATE_PATH_PATTERN = re.compile(
r"(?i)(?:[A-Za-z]:[\\/](?:Users|home|mnt|private|workspace|root|tmp|var)[\\/]|/(?:Users|home|mnt|private|workspace|root|tmp|var)/)"
+2 -1
View File
@@ -43,6 +43,7 @@ ROW_CONTROL_ALLOWLIST = frozenset(
"H3_CONTEXT_HOST_HEADED",
"H3_CONTEXT_M25_34_EXPECTED_SOURCE",
"H3_CONTEXT_M25_34_MEDIA_JOURNEY",
"H3_CONTEXT_MEDIA_LOCAL_DIRECTORY",
"H3_CONTEXT_M25_34_OBSERVER_FFMPEG",
"H3_CONTEXT_M25_34_OBSERVER_FFPROBE",
"H3_CONTEXT_M25_34_RENDER",
@@ -238,7 +239,7 @@ def parse_row_environment(values: Iterable[str]) -> dict[str, str]:
or any(character in content for character in "\r\n\0")
):
raise ValueError(f"invalid value for admitted row control {name}")
if name == "H3_CONTEXT_M25_34_MEDIA_JOURNEY" and content not in {"ready", "install"}:
if name == "H3_CONTEXT_M25_34_MEDIA_JOURNEY" and content not in {"ready", "local"}:
raise ValueError(f"invalid value for admitted row control {name}")
if name == "H3_CONTEXT_M25_34_EXPECTED_SOURCE" and content not in {
"explicit_override",
+2 -2
View File
@@ -2,13 +2,13 @@
"schema": "h3-context-release-matrix/1",
"package": {
"name": "minimax-h3-studio",
"version": "1.2.0",
"version": "1.2.1",
"author": "rookiestar28",
"dependencies": []
},
"artifact": {
"required": ["wheel", "sdist"],
"prefix": "minimax_h3_studio-1.2.0",
"prefix": "minimax_h3_studio-1.2.1",
"forbidden_path_markers": [
"AGENTS.md",
"ROADMAP.md",
+2 -2
View File
@@ -193,13 +193,13 @@ def test_every_registered_http_route_has_mechanical_responsibility_ownership() -
# made declared policy authoritative for route discovery. adds the managed
# sequence action and current-projection routes; adds one manual import route;
# adds the bodiless GET output-capability route; adds the media runtime status, setup and
# setup-job routes. Keep the exact total pinned so another route
# setup routes; manual setup removes the job route. Keep the exact total pinned so another route
# cannot enter without an explicit responsibility review.
# Recovery metadata adds one bounded POST, not a filesystem or execution route.
# Retained media adds separate finite-command and explicit-preview POST edges.
# Editable draft recovery adds one finite, owner-qualified POST edge.
# Operator perception exposes one finite GET readiness projection, without configuration writes.
assert len(routes) == 34
assert len(routes) == 33
assert [row for row in routes if row["module"].endswith("/comfyui_perception_status.py")] == [
{
"handler": "_status",
+341
View File
@@ -26,6 +26,7 @@ from test_av_reconstruction import _plan_kwargs
import comfyui_h3_context.adapters.av_reconstruction_media as media_module
from comfyui_h3_context.adapters.av_reconstruction_media import (
AVMediaAdapterError,
M26DerivedMediaLease,
QualifiedAVMediaAdapter,
)
from comfyui_h3_context.adapters.av_reconstruction_transport import AVTransportError
@@ -668,6 +669,95 @@ def test_inconsistent_probe_timestamps_and_durations_fail_closed(
)
def _millisecond_rounded_probe(
*, audio_samples: int, audio_duration: str, format_duration: str, video_frames: int = 24
) -> bytes:
"""A 24 fps / 32 kHz probe whose audio timeline is ``audio_samples`` long.
Host SaveVideo MP4s state the stream and format durations in the movie timescale (1/1000 s):
a 124-frame (5 s segment) output decodes 165,334 audio samples but declares 5.167 s.
"""
value = cast(
dict[str, Any],
json.loads(
_probe_payload(
sample_rate=32_000,
frame_rate=24,
video_frame_count=video_frames,
video_duration=f"{video_frames / 24:.6f}",
audio_duration=audio_duration,
format_duration=format_duration,
)
),
)
frames = cast(list[dict[str, Any]], value["frames"])
last_audio = [frame for frame in frames if frame["media_type"] == "audio"][-1]
last_audio["duration"] = audio_samples - 31 * 1024
assert 0 < last_audio["duration"] <= 1024
return json.dumps(value, separators=(",", ":")).encode("utf-8")
def _inspect_probe(monkeypatch: pytest.MonkeyPatch, probe_payload: bytes) -> AVMediaDescriptor:
payload = b"synthetic-private-segment"
with tempfile.TemporaryDirectory() as temporary:
adapter, _ = _adapter(Path(temporary), monkeypatch, probe_payload=probe_payload)
return adapter.inspect_payload(
segment_id="segment.1",
artifact_receipt_fingerprint=_fp(b"receipt"),
artifact_output_fingerprint=_fp(payload),
payload=payload,
)
@pytest.mark.parametrize(
("video_frames", "format_duration"),
# The second case makes the audio the longest stream, so the format duration is rounded too.
((24, "1.000000"), (23, "1.000000")),
)
def test_millisecond_rounded_container_durations_are_admitted(
monkeypatch: pytest.MonkeyPatch, video_frames: int, format_duration: str
) -> None:
descriptor = _inspect_probe(
monkeypatch,
_millisecond_rounded_probe(
audio_samples=31_990,
audio_duration="1.000000",
format_duration=format_duration,
video_frames=video_frames,
),
)
# The decoded timeline stays the authority; the rounded declaration is only cross-checked.
assert descriptor.audio is not None
assert descriptor.audio.decoded_sample_count == 31_990
assert descriptor.audio.end_time == AVRational(3_199, 3_200)
assert descriptor.video is not None
assert descriptor.video.decoded_frame_count == video_frames
@pytest.mark.parametrize(
("audio_samples", "audio_duration"),
(
(31_990, "1.001000"), # on the millisecond grid, but 1.3125 ms from the timeline
(31_968, "1.000000"), # exactly 1 ms from the timeline: not a rounding of it
(31_990, "1.000300"), # off the millisecond grid: only the one-tick tolerance applies
),
)
def test_declared_durations_beyond_millisecond_rounding_fail_closed(
monkeypatch: pytest.MonkeyPatch, audio_samples: int, audio_duration: str
) -> None:
with pytest.raises(AVMediaAdapterError, match="inspection_invalid"):
_inspect_probe(
monkeypatch,
_millisecond_rounded_probe(
audio_samples=audio_samples,
audio_duration=audio_duration,
format_duration="1.000000",
),
)
@pytest.mark.parametrize("missing_audio", (False, True))
def test_audio_absence_and_nonzero_timestamps_are_explicit_facts(
monkeypatch: pytest.MonkeyPatch,
@@ -2578,3 +2668,254 @@ def test_m26_media_bridge_crops_exact_frame_and_sample_tail_then_releases_only_l
lease.release()
assert lease._lease.released
assert tuple((root / "scratch").iterdir()) == ()
def _with_video_transfer(payload: bytes, transfer: str) -> bytes:
value = json.loads(payload)
for stream in value["streams"]:
if stream["codec_type"] == "video":
stream["color_transfer"] = transfer
return json.dumps(value, separators=(",", ":")).encode("utf-8")
# The exact pre-conversion crop graph. A BT.709 source must keep it byte for byte, because the
# derived input's receipt and every stored assembly built from it depend on the crop's output.
_BT709_CROP_GRAPH = (
"[0:v:0]trim=start_frame=0:end_frame=360,setpts=PTS-STARTPTS,format=yuv420p[v];"
"[0:a:0]atrim=start_sample=0:end_sample=480000,asetpts=PTS-STARTPTS,aresample=32000,"
"aformat=sample_fmts=fltp:channel_layouts=stereo[a]"
)
@pytest.mark.parametrize(
("transfer", "expected_graph"),
(
("bt709", _BT709_CROP_GRAPH),
(
"iec61966-2-1",
"[0:v:0]trim=start_frame=0:end_frame=360,setpts=PTS-STARTPTS,"
"colorspace=all=bt709,"
"setparams=range=tv:color_primaries=bt709:color_trc=bt709:colorspace=bt709,"
"format=yuv420p[v];"
"[0:a:0]atrim=start_sample=0:end_sample=480000,asetpts=PTS-STARTPTS,aresample=32000,"
"aformat=sample_fmts=fltp:channel_layouts=stereo[a]",
),
("smpte170m", None),
),
)
def test_m26_crop_admits_native_srgb_outputs_by_conversion_only(
monkeypatch: pytest.MonkeyPatch, transfer: str, expected_graph: str | None
) -> None:
"""Host CreateVideo tags native H3 outputs sRGB; the M26 crop must admit and convert them."""
original_payload = b"synthetic-m26-native-output"
derived_payload = b"synthetic-m26-derived-input"
original_probe = _with_video_transfer(
_probe_payload(
video_frame_count=362,
format_duration="15.083333",
video_duration="15.083333",
audio_duration="15.000000",
sample_rate=32_000,
seconds=15,
frame_rate=24,
),
transfer,
)
derived_probe = _probe_payload(
video_frame_count=360,
format_duration="15.000000",
video_duration="15.000000",
audio_duration="15.000000",
sample_rate=32_000,
seconds=15,
frame_rate=24,
)
with tempfile.TemporaryDirectory() as temporary:
root = Path(temporary)
ffmpeg = (root / "ffmpeg.exe").resolve()
ffprobe = (root / "ffprobe.exe").resolve()
ffmpeg.write_bytes(b"synthetic ffmpeg")
ffprobe.write_bytes(b"synthetic ffprobe")
invocations: list[MediaProcessInvocation] = []
probe_calls = 0
def fake_run(
_self: SubprocessMediaRunner,
invocation: MediaProcessInvocation,
cancellation: object = None,
) -> ProcessCapture:
nonlocal probe_calls
del cancellation
invocations.append(invocation)
if invocation.tool == "ffmpeg":
invocation.output_leases[0].path.write_bytes(derived_payload)
return ProcessCapture(
status=ProcessStatus.SUCCEEDED,
exit_code=0,
owned_output_bytes=len(derived_payload),
artifacts=invocation.output_leases,
)
probe_calls += 1
return ProcessCapture(
status=ProcessStatus.SUCCEEDED,
stdout=original_probe if probe_calls == 1 else derived_probe,
exit_code=0,
)
_stub_media_pins(monkeypatch)
monkeypatch.setattr(SubprocessMediaRunner, "run", fake_run)
adapter = QualifiedAVMediaAdapter(
ffmpeg_path=ffmpeg,
ffprobe_path=ffprobe,
scratch_root=(root / "scratch").resolve(),
clock_ms=lambda: 400,
)
def derive() -> M26DerivedMediaLease:
return adapter.derive_m26_input(
segment_id="segment.m26.native",
original_receipt_fingerprint=_fp(b"m26-native-receipt"),
original_source=_ReplaySource(original_payload),
contribution_frames=360,
contribution_samples=480_000,
)
if expected_graph is None:
with pytest.raises(AVMediaAdapterError, match="m26_source_contribution_invalid"):
derive()
assert all(item.tool != "ffmpeg" for item in invocations)
return
lease = derive()
crop = next(item for item in invocations if item.tool == "ffmpeg")
assert crop.argv[crop.argv.index("-filter_complex") + 1] == expected_graph
assert crop.argv[crop.argv.index("-color_trc") + 1] == "bt709"
assert lease.original_descriptor.video is not None
assert lease.original_descriptor.video.color_transfer == transfer
lease.release()
def test_real_native_srgb_output_is_cropped_by_pixel_conversion(tmp_path: Path) -> None:
"""A host-shaped source (sRGB transfer, B-frames) crops to BT.709 with converted pixels."""
ffmpeg_value = os.environ.get("H3_CONTEXT_AUTHORIZED_FFMPEG_PATH")
ffprobe_value = os.environ.get("H3_CONTEXT_AUTHORIZED_FFPROBE_PATH")
if not ffmpeg_value or not ffprobe_value:
pytest.skip("exact authorized media tool paths were not explicitly supplied")
ffmpeg = Path(ffmpeg_value).resolve(strict=True)
ffprobe = Path(ffprobe_value).resolve(strict=True)
source = tmp_path / "native.mp4"
subprocess.run( # noqa: S603 - exact authorized binary, fixed argv.
[
str(ffmpeg),
"-hide_banner",
"-loglevel",
"error",
"-nostdin",
"-f",
"lavfi",
"-i",
"color=c=0x808080:s=864x480:r=24:d=2",
"-f",
"lavfi",
"-i",
"sine=frequency=330:sample_rate=32000:duration=2",
"-map",
"0:v:0",
"-map",
"1:a:0",
"-frames:v",
"48",
"-c:v",
"libx264",
"-preset",
"medium",
"-crf",
"18",
"-pix_fmt",
"yuv420p",
# The VUI carries what the host writes: BT.709 primaries and matrix, sRGB transfer.
"-x264-params",
"colorprim=bt709:transfer=iec61966-2-1:colormatrix=bt709:range=limited",
"-color_range",
"tv",
"-colorspace",
"bt709",
"-color_primaries",
"bt709",
"-color_trc",
"iec61966-2-1",
"-c:a",
"aac",
"-b:a",
"192k",
"-ar",
"32000",
"-ac",
"2",
"-video_track_timescale",
"12288",
"-n",
str(source),
],
stdin=subprocess.DEVNULL,
capture_output=True,
check=True,
timeout=60,
)
payload = source.read_bytes()
adapter = QualifiedAVMediaAdapter(
ffmpeg_path=ffmpeg,
ffprobe_path=ffprobe,
scratch_root=(tmp_path / "scratch").resolve(),
clock_ms=lambda: 1,
)
lease = adapter.derive_m26_input(
segment_id="segment.m26.native.real",
original_receipt_fingerprint=_fp(b"m26-native-real-receipt"),
original_source=_ReplaySource(payload),
contribution_frames=48,
contribution_samples=64_000,
)
try:
assert lease.original_descriptor.video is not None
assert lease.original_descriptor.video.color_transfer == "iec61966-2-1"
descriptor = lease.inspect(
segment_id="segment.m26.native.real",
derived_receipt_fingerprint=_fp(b"m26-native-real-derived"),
)
assert descriptor.video is not None
assert descriptor.video.color_transfer == "bt709"
assert descriptor.video.decoded_frame_count == 48
def middle_luma(path: Path) -> int:
frame = subprocess.run( # noqa: S603 - exact authorized binary, fixed argv.
[
str(ffmpeg),
"-v",
"error",
"-nostdin",
"-i",
str(path),
"-vf",
"select=eq(n\\,24)",
"-frames:v",
"1",
"-f",
"rawvideo",
"-pix_fmt",
"gray",
"-",
],
stdin=subprocess.DEVNULL,
capture_output=True,
check=True,
timeout=60,
).stdout
return frame[240 * 864 + 432]
# sRGB mid-grey re-encoded through the BT.709 curve is darker by about ten luma codes;
# an unchanged value would mean the crop relabelled the transfer instead of converting.
assert middle_luma(source) - middle_luma(lease._lease.path) >= 4
finally:
lease.release()
+2 -4
View File
@@ -81,11 +81,9 @@ ABSENT_ORIGIN_ROUTES = frozenset(
"/h3-context/v1/authoring/render/{handle}",
"/h3-context/v1/authoring/output/{handle}/preview",
"/h3-context/v1/authoring/output/{handle}/download",
# the media runtime status and setup-job reads are same-origin fetch GETs the
# browser sends without Origin; both reject foreign fetch metadata. Neither writes state or
# downloads: status may run bounded local discovery, and the job read is a projection.
# Media status admits same-origin fetch GETs without Origin and rejects foreign fetch
# metadata. It may run bounded local discovery; manual setup has no job projection.
"/h3-context/v1/media-runtime",
"/h3-context/v1/media-runtime/setup/{job_id}",
# The perception GET reads only cached finite readiness; it never retries settings IO.
"/h3-context/v1/perception/status",
}
File diff suppressed because it is too large Load Diff
+8 -31
View File
@@ -422,41 +422,18 @@ def test_cold_absent_to_ready_keeps_the_same_consumers_and_composition(
output.close()
def test_the_setup_install_job_activates_through_refresh(tmp_path: Path) -> None:
def test_rescan_activates_user_supplied_tools_through_refresh(tmp_path: Path) -> None:
harness = Harness(MISSING)
consumer = Consumer()
harness.manager.add_consumer(consumer)
class Installer:
def run(self) -> None:
harness.resolver.result = located(tmp_path)
setup = MediaRuntimeSetupService(
resolver=harness.resolver, # type: ignore[arg-type]
manager=harness.manager,
downloader_factory=lambda: cast(Any, object()),
installer_factory=lambda _layout, **_kwargs: cast(Any, Installer()),
manifest_provider=lambda: cast(
Any,
type(
"Manifest",
(),
{
"profile_component": "p",
"source_label": "s",
"release_page_url": "https://example.invalid/",
"license_name": "l",
"archive_bytes": 1,
},
)(),
),
thread_starter=lambda target: target(),
job_id_factory=lambda: "a" * 32,
parked_scanner=lambda *_: (),
abandoned_scanner=lambda *_: (),
)
job = setup.start_install()
assert setup.job(cast(str, job["job_id"]))["reason"] == "installed"
harness.resolver.result = located(tmp_path)
setup.rescan()
binding = harness.manager.current()
assert binding is not None and binding.source_kind is SourceKind.MANAGED
assert consumer.attached == [binding]
@@ -655,7 +632,7 @@ def test_a_busy_local_selection_is_a_409_with_config_bytes_unchanged(tmp_path: P
setup = MediaRuntimeSetupService(
resolver=harness.resolver, # type: ignore[arg-type]
manager=harness.manager,
thread_starter=lambda target: target(),
abandoned_scanner=lambda *_: (),
)
with harness.manager.lease(), pytest.raises(MediaRuntimeSetupError) as refused:
setup.use_local_directory("C:\\tools", 0)
@@ -751,14 +728,14 @@ def test_status_carries_features_and_no_locator(tmp_path: Path) -> None:
setup = MediaRuntimeSetupService(
resolver=harness.resolver, # type: ignore[arg-type]
manager=harness.manager,
thread_starter=lambda target: target(),
abandoned_scanner=lambda *_: (),
parked_scanner=lambda _layout, _manifest: (),
)
status = setup.status()
# bumped the wire to v3 (adds `recovery`); the feature projection is unchanged.
assert status["schema"] == STATUS_SCHEMA == "h3.context.media_runtime_status.v3"
assert status["schema"] == STATUS_SCHEMA == "h3.context.media_runtime_status.v4"
assert status["features"] == {
feature: {"state": "ready", "reason": None} for feature in FEATURES
}
File diff suppressed because it is too large Load Diff
+16
View File
@@ -86,6 +86,22 @@ class SuppliedHostLaneUnitTests(unittest.TestCase):
with self.subTest(value=value), self.assertRaisesRegex(ValueError, "loopback"):
lane.validate_host_url(value)
def test_manual_media_journey_requires_explicit_local_authority(self) -> None:
self.assertEqual(
lane.parse_row_environment(
[
"H3_CONTEXT_M25_34_MEDIA_JOURNEY=local",
"H3_CONTEXT_MEDIA_LOCAL_DIRECTORY=C:/qualified/bin",
]
),
{
"H3_CONTEXT_M25_34_MEDIA_JOURNEY": "local",
"H3_CONTEXT_MEDIA_LOCAL_DIRECTORY": "C:/qualified/bin", # pragma: allowlist secret
},
)
with self.assertRaises(ValueError):
lane.parse_row_environment(["H3_CONTEXT_M25_34_MEDIA_JOURNEY=install"])
def test_row_selection_and_controls_are_explicit_and_bounded(self) -> None:
row = lane.parse_row(
"tests/e2e/journeys/host/sidebarResizeHost.spec.ts::"
+276
View File
@@ -0,0 +1,276 @@
"""Manual media-tool setup contract: no executable acquisition or implicit retry."""
from __future__ import annotations
import asyncio
import json
import os
import socket
import subprocess
import sys
from collections.abc import Callable
from pathlib import Path
from types import ModuleType, SimpleNamespace
from typing import Any, cast
from unittest.mock import patch
import pytest
from deployment_request_doubles import LOOPBACK_HOST, ListenerTransport
from comfyui_h3_context.adapters import comfyui_media_runtime_setup as setup
from scripts.hc_09_host_seam_test_double import host_prompt_server_module
def test_manual_wire_retires_jobs_and_install_actions() -> None:
assert setup.STATUS_SCHEMA == "h3.context.media_runtime_status.v4"
assert setup.REQUEST_SCHEMA == "h3.context.media_runtime_setup_request.v2"
assert set(setup.ACTIONS) == {
"rescan",
"use_local_directory",
"restore_auto",
"reclaim_parked_runtime",
}
assert not hasattr(setup, "JOB_ROUTE")
assert not hasattr(setup.MediaRuntimeSetupService, "start_install")
@pytest.mark.parametrize("action", ["install_supported", "cancel_setup"])
def test_retired_actions_are_refused_before_any_work(action: str) -> None:
def forbidden() -> None:
pytest.fail("retired action reached implementation")
service = SimpleNamespace(start_install=forbidden, cancel=forbidden)
with pytest.raises(setup.MediaRuntimeSetupError) as error:
setup.dispatch_setup_request(
cast(setup.MediaRuntimeSetupService, service),
{"schema": setup.REQUEST_SCHEMA, "action": action},
)
assert (error.value.code, error.value.status) == ("invalid_request", 400)
class _Routes(list[SimpleNamespace]):
def _decorator(self, method: str, path: str) -> Callable[[Callable[..., Any]], Any]:
def decorate(handler: Callable[..., Any]) -> Callable[..., Any]:
self.append(SimpleNamespace(method=method, path=path, handler=handler))
return handler
return decorate
def get(self, path: str) -> Callable[[Callable[..., Any]], Any]:
return self._decorator("GET", path)
def post(self, path: str) -> Callable[[Callable[..., Any]], Any]:
return self._decorator("POST", path)
class _Headers:
def __init__(self, values: dict[str, list[str]]) -> None:
self._values = values
def getall(self, name: str, default: list[str]) -> list[str]:
return self._values.get(name, [LOOPBACK_HOST] if name == "Host" else default)
class _Content:
def __init__(self, body: bytes) -> None:
self._chunks = [body, b""]
self.reads = 0
async def read(self, _limit: int) -> bytes:
self.reads += 1
return self._chunks.pop(0)
def http_request(
body: bytes = b"",
*,
origin: list[str] | None = None,
site: list[str] | None = None,
content_type: str = "application/json",
job_id: str | None = None,
) -> SimpleNamespace:
headers = {"Origin": ["http://127.0.0.1:8188"] if origin is None else origin}
if site is not None:
headers["Sec-Fetch-Site"] = site
return SimpleNamespace(
content_type=content_type,
content_length=len(body),
content=_Content(body),
headers=_Headers(headers),
transport=ListenerTransport(),
match_info={"job_id": job_id} if job_id is not None else {},
)
def registered() -> dict[tuple[str, str], Callable[..., Any]]:
routes = _Routes()
server = host_prompt_server_module(routes)
aiohttp = ModuleType("aiohttp")
aiohttp.__dict__["web"] = SimpleNamespace(
json_response=lambda value, status=200, headers=None: (status, value),
Response=lambda status=200, body=None, headers=None: (status, body),
)
with patch.dict(sys.modules, {"server": server, "aiohttp": aiohttp}):
with patch.object(routes_module, "_ROUTE_REGISTERED", False):
assert ensure_media_runtime_setup_route_registered()
assert ensure_media_runtime_setup_route_registered()
assert len(routes) == 2
return {(route.method, route.path): route.handler for route in routes}
def test_package_import_builds_no_setup_service_and_opens_no_connection() -> None:
script = (
"import socket, subprocess\n"
"class Refuse(subprocess.Popen):\n"
" def __init__(self, *a, **k):\n"
" raise SystemExit('process spawned during import')\n"
"subprocess.Popen = Refuse\n"
"def refuse(*a, **k):\n"
" raise SystemExit('network used during import')\n"
"socket.create_connection = refuse\n"
"socket.getaddrinfo = refuse\n"
"import comfyui_h3_context\n"
"from comfyui_h3_context.adapters import composition_root as root\n"
"import comfyui_h3_context.adapters.comfyui_media_runtime_setup\n"
"assert root.installed(root.MEDIA_RUNTIME_SETUP) is None\n"
"assert root.installed(root.MEDIA_RUNTIME_RESOLVER) is None\n"
"print('inert')\n"
)
environment = {
key: value for key, value in os.environ.items() if not key.startswith("H3_CONTEXT_")
}
completed = subprocess.run( # noqa: S603
[sys.executable, "-c", script],
capture_output=True,
text=True,
check=False,
cwd=Path(routes_module.__file__).resolve().parents[2],
env=environment,
timeout=120,
)
assert completed.returncode == 0, completed.stderr[-2000:]
assert completed.stdout.strip().endswith("inert")
# Retained HTTP edge and CAS coverage formerly mixed into installer tests.
routes_module = setup
STATUS_SCHEMA = setup.STATUS_SCHEMA
STATUS_ROUTE = setup.STATUS_ROUTE
SETUP_ROUTE = setup.SETUP_ROUTE
ensure_media_runtime_setup_route_registered = setup.ensure_media_runtime_setup_route_registered
@pytest.mark.parametrize(
"raw",
[b"{", b"[]", b"\xff", b'{"action":"rescan","action":"restore_auto"}', b'{"revision":NaN}'],
)
def test_decoder_refuses_ambiguous_or_non_json_bodies(raw: bytes) -> None:
with pytest.raises(setup.MediaRuntimeSetupError):
setup.decode_setup_request(raw)
@pytest.mark.parametrize("revision", [True, -1, 1.5, "0", 2**53])
def test_revision_is_a_bounded_integer_before_any_config_write(revision: object) -> None:
with pytest.raises(setup.MediaRuntimeSetupError):
setup.dispatch_setup_request(
cast(
setup.MediaRuntimeSetupService,
SimpleNamespace(
restore_auto=lambda _revision: pytest.fail("invalid revision reached write")
),
),
{
"schema": setup.REQUEST_SCHEMA,
"action": "restore_auto",
"expected_revision": revision,
},
)
@pytest.mark.parametrize("path,method", [(STATUS_ROUTE, "GET"), (SETUP_ROUTE, "POST")])
def test_foreign_route_leaves_both_manual_routes_unregistered(path: str, method: str) -> None:
routes = _Routes([SimpleNamespace(method=method, path=path, handler=lambda _request: None)])
aiohttp = ModuleType("aiohttp")
aiohttp.__dict__["web"] = SimpleNamespace(json_response=lambda value, status=200: value)
with patch.dict(sys.modules, {"server": host_prompt_server_module(routes), "aiohttp": aiohttp}):
assert not setup.ensure_media_runtime_setup_route_registered()
assert len(routes) == 1
def test_only_status_and_manual_post_register_idempotently() -> None:
assert set(registered()) == {("GET", STATUS_ROUTE), ("POST", SETUP_ROUTE)}
def test_http_rejects_origin_and_retired_actions_before_service_work() -> None:
handlers = registered()
service = SimpleNamespace(
status=lambda: {"schema": STATUS_SCHEMA},
rescan=lambda: (_ for _ in ()).throw(OSError("private path")),
)
def body(action: str) -> bytes:
return json.dumps({"schema": setup.REQUEST_SCHEMA, "action": action}).encode()
async def exercise() -> None:
read = handlers[("GET", STATUS_ROUTE)]
write = handlers[("POST", SETUP_ROUTE)]
assert await read(http_request(origin=[])) == (200, {"schema": STATUS_SCHEMA})
assert await read(http_request(origin=[], site=["cross-site"])) == (
403,
{"error": "origin_rejected"},
)
foreign = http_request(body("rescan"), origin=["https://foreign.example"])
assert await write(foreign) == (403, {"error": "origin_rejected"})
assert foreign.content.reads == 0
assert await write(http_request(b"{}", content_type="text/plain")) == (
415,
{"error": "media_type_rejected"},
)
assert await write(http_request(b"x" * (setup.MAX_SETUP_REQUEST_BYTES + 1))) == (
413,
{"error": "request_too_large"},
)
assert await write(http_request(b"{")) == (400, {"error": "invalid_request"})
for retired in ("install_supported", "cancel_setup"):
assert await write(http_request(body(retired))) == (400, {"error": "invalid_request"})
assert await write(http_request(body("rescan"))) == (500, {"error": "internal_failure"})
with patch.object(setup, "media_runtime_setup", lambda: service):
asyncio.run(exercise())
# IMPORTANT: a local selection must be a drive-absolute Windows directory
# (`lexical_local_directory`), so a POSIX temporary path is refused before this flow starts. Only
# the Linux Hosted backend runs this file off Windows; keep the marker with the real resolver.
@pytest.mark.skipif(os.name != "nt", reason="Windows drive-absolute local directory")
def test_offline_real_resolver_selection_refusal_path_and_restore(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
from test_m25_30_media_runtime_resolution import inputs, make_pair, resolver
def no_network(*_args: object, **_kwargs: object) -> None:
pytest.fail("manual setup attempted network access")
monkeypatch.setattr(socket, "create_connection", no_network)
monkeypatch.setattr(socket, "getaddrinfo", no_network)
pair = make_pair(tmp_path / "supported")
current = [inputs()]
runtime, _, _ = resolver(tmp_path, current[0], current=current)
service = setup.MediaRuntimeSetupService(resolver=runtime)
service.use_local_directory(str(pair), 0)
assert runtime.resolve().source_kind.value == "local_selection"
before = runtime.private_layout().config_file.read_bytes()
for directory in (
tmp_path / "missing",
make_pair(tmp_path / "tampered", ffmpeg=b"wrong build"),
):
with pytest.raises(setup.MediaRuntimeSetupError):
service.use_local_directory(str(directory), 1)
assert runtime.private_layout().config_file.read_bytes() == before
service.restore_auto(1)
config = runtime.read_config()
assert config is not None and config.selection.value == "auto"
current.append(inputs(path=str(pair)))
service.rescan()
assert runtime.resolve().source_kind.value == "system_path"
+67
View File
@@ -0,0 +1,67 @@
import ast
import zipfile
from pathlib import Path
import pytest
from scripts.registry_policy_check import call_shape, canonical_shape, check_path, check_source
@pytest.mark.parametrize(
"source",
[
"import zipfile",
"from tarfile import open",
"exec('x')",
"import os as o\no.system('pip install x')",
"import subprocess as s\ns.run(['python', '-m', 'pip', 'install', 'x'])",
"url='https://github.com/vendor/project/releases/download/v1/code.zip'",
"f = eval\nf('x')",
"import base64\nbase64.b64decode('AA==')",
],
)
def test_policy_mutations_are_detected(source: str) -> None:
assert check_source("candidate.py", source)
def test_release_page_is_permitted() -> None:
assert not check_source(
"candidate.py", "page='https://github.com/vendor/project/releases/tag/v1'"
)
@pytest.mark.parametrize(
"mutation",
["import zipfile", "url='https://github.com/vendor/project/releases/download/v1/code.zip'"],
)
def test_exact_zip_guard_reads_mutations_without_extracting(tmp_path: Path, mutation: str) -> None:
archive = tmp_path / "candidate.zip"
with zipfile.ZipFile(archive, "w") as out:
out.writestr("comfyui_h3_context/__init__.py", mutation)
assert check_path(archive)
assert list(tmp_path.iterdir()) == [archive]
def test_runtime_tree_has_no_acquisition_markers() -> None:
assert check_path(Path(__file__).resolve().parents[1]) == []
def test_unreviewed_spawn_in_a_pinned_module_still_fails() -> None:
assert check_source(
"adapters/media_runtime_resolution.py",
"import subprocess\nsubprocess.run(['ffmpeg', '-version'])",
)
def test_call_shape_text_is_identical_on_every_supported_python() -> None:
# The pins must read the same under the 3.10 CI and Registry interpreters and the 3.13 gate;
# ast.dump does not (3.13 omits None and empty fields), so this golden text runs on both.
node = ast.parse("subprocess.run(['a', 1], check=True, env=None)", mode="eval").body
assert isinstance(node, ast.Call)
assert canonical_shape(node) == (
"Call(func=Attribute(value=Name(id='subprocess', ctx=Load()), attr='run', ctx=Load()), "
"args=[List(elts=[Constant(value='a'), Constant(value=1)], ctx=Load())], "
"keywords=[keyword(arg='check', value=Constant(value=True)), "
"keyword(arg='env', value=Constant(value=None))])"
)
assert call_shape(node) == call_shape(ast.parse(ast.unparse(node), mode="eval").body) # type: ignore[arg-type]
+41 -17
View File
@@ -5,6 +5,7 @@ from __future__ import annotations
import copy
import importlib
import json
import re
import subprocess
from pathlib import Path
from typing import Any, cast
@@ -12,7 +13,26 @@ from typing import Any, cast
import pytest
ROOT = Path(__file__).resolve().parents[1]
VERSION = "1.2.0"
def _current_version() -> str:
# IMPORTANT: these tests build their fixtures from the live version authorities, so VERSION
# must follow pyproject.toml. A hardcoded release number makes every guard test fail with
# VERSION_AUTHORITIES_DISAGREE on the next release's version bump. Read it with a literal
# pattern, not the guard's own reader, so the unit under test does not supply its oracle.
found = re.findall(
r'^version = "([0-9]+\.[0-9]+\.[0-9]+)"$',
(ROOT / "pyproject.toml").read_text(encoding="utf-8"),
flags=re.M,
)
assert len(found) == 1, found
return str(found[0])
VERSION = _current_version()
_MAJOR, _MINOR, _PATCH = VERSION.split(".")
# A well-formed version that differs from every live authority.
OTHER = f"{_MAJOR}.{_MINOR}.{int(_PATCH) + 1}"
PATHS = (
"pyproject.toml",
"frontend/package.json",
@@ -34,17 +54,17 @@ def payloads() -> dict[str, bytes]:
def mismatch(values: dict[str, bytes], field: int) -> None:
path = PATHS[min(field, 5)]
if field in {0, 2, 3}:
values[path] = values[path].replace(b"1.2.0", b"1.2.1")
values[path] = values[path].replace(VERSION.encode(), OTHER.encode())
return
document = json.loads(values[path])
if field == 1:
document["version"] = "1.2.1"
document["version"] = OTHER
elif field == 4:
document["profiles"][0]["distribution"] = "minimax-h3-studio==1.2.1"
document["profiles"][0]["distribution"] = f"minimax-h3-studio=={OTHER}"
elif field == 5:
document["package"]["version"] = "1.2.1"
document["package"]["version"] = OTHER
else:
document["artifact"]["prefix"] = "minimax_h3_studio-1.2.1"
document["artifact"]["prefix"] = f"minimax_h3_studio-{OTHER}"
values[path] = json.dumps(document).encode()
@@ -86,17 +106,18 @@ def test_ambiguous_or_computed_version_authority_is_refused(defect: str) -> None
if defect == "missing":
del values[PATHS[0]]
elif defect == "expected":
expected = "1.2.1"
expected = OTHER
elif defect == "computed":
values[PATHS[2]] = values[PATHS[2]].replace(
b'__version__ = "1.2.0"', b'__version__ = "1.2." + "0"'
f'__version__ = "{VERSION}"'.encode(),
f'__version__ = "{VERSION[:-1]}" + "{VERSION[-1]}"'.encode(),
)
elif defect == "duplicate_assignment":
values[PATHS[2]] += b'\n__version__ = "1.2.0"\n'
values[PATHS[2]] += f'\n__version__ = "{VERSION}"\n'.encode()
elif defect == "duplicate_json":
values[PATHS[1]] = b'{"version":"1.2.1","version":"1.2.0"}'
values[PATHS[1]] = f'{{"version":"{OTHER}","version":"{VERSION}"}}'.encode()
elif defect == "nonfinite":
values[PATHS[1]] = b'{"version":"1.2.0","x":NaN}'
values[PATHS[1]] = f'{{"version":"{VERSION}","x":NaN}}'.encode()
elif defect == "boolean":
values[PATHS[1]] = b'{"version":true}'
elif defect == "duplicate_profile":
@@ -105,8 +126,8 @@ def test_ambiguous_or_computed_version_authority_is_refused(defect: str) -> None
values[PATHS[4]] = json.dumps(document).encode()
else:
values[PATHS[3]] = values[PATHS[3]].replace(
b'distribution="minimax-h3-studio==1.2.0"',
b'distribution="minimax-h3-studio==" + "1.2.0"',
f'distribution="minimax-h3-studio=={VERSION}"'.encode(),
f'distribution="minimax-h3-studio==" + "{VERSION}"'.encode(),
)
with pytest.raises(ValueError, match="VERSION"):
guard().validate_version_authorities(values, expected)
@@ -260,7 +281,7 @@ def test_guard_refusal_performs_zero_pushes_and_preserves_all_remote_refs(
git(repo, "commit", "--quiet", "-m", "test: extra ancestor")
candidate = git(repo, "rev-parse", "HEAD")
elif defect == "wrong_version":
(repo / "frontend/package.json").write_text('{"version":"1.2.1"}')
(repo / "frontend/package.json").write_text(f'{{"version":"{OTHER}"}}')
git(repo, "add", "frontend/package.json")
git(repo, "commit", "--amend", "--quiet", "-m", "test: version disagreement")
candidate = git(repo, "rev-parse", "HEAD")
@@ -366,16 +387,19 @@ def test_invalid_version_shapes_have_zero_remote_effect(remote: Any, defect: str
repo, bare, parent, candidate = remote
expected = VERSION
if defect == "expected":
expected = "1.2.1"
expected = OTHER
elif defect == "missing":
git(repo, "rm", "--quiet", PATHS[0])
elif defect == "computed":
target = repo / PATHS[2]
target.write_bytes(
target.read_bytes().replace(b'__version__ = "1.2.0"', b'__version__ = "1.2." + "0"')
target.read_bytes().replace(
f'__version__ = "{VERSION}"'.encode(),
f'__version__ = "{VERSION[:-1]}" + "{VERSION[-1]}"'.encode(),
)
)
elif defect == "duplicate_json":
(repo / PATHS[1]).write_bytes(b'{"version":"1.2.1","version":"1.2.0"}')
(repo / PATHS[1]).write_bytes(f'{{"version":"{OTHER}","version":"{VERSION}"}}'.encode())
else:
target = repo / PATHS[4]
data = json.loads(target.read_bytes())
+18 -22
View File
@@ -361,39 +361,35 @@ license-files = ["LICENSE", "NOTICE"]
)
)
def test_media_runtime_egress_is_confined_to_the_download_transport(self) -> None:
def test_media_setup_and_recovery_have_no_egress_exception(self) -> None:
body = (
"import http.client\nimport socket\nimport ssl\n\n\n"
"def go():\n return socket.create_connection(('a', 443))\n"
"import http.client\nimport socket\nimport ssl\n\ndef go():\n"
" return socket.create_connection(('a', 443))\n"
)
names = (
"media_runtime_pin.py",
"media_runtime_leftovers.py",
"comfyui_media_runtime_setup.py",
"media_runtime_download.py",
)
with tempfile.TemporaryDirectory() as temporary:
package = Path(temporary) / "comfyui_h3_context"
adapters = package / "adapters"
adapters.mkdir(parents=True)
(adapters / "media_runtime_download.py").write_text(body, encoding="utf-8")
self.assertEqual(audit_runtime_package(package), ())
# The installer and the setup routes handle untrusted archive bytes and client
# requests; neither may open a connection or resolve a name on its own.
for relative in ("media_runtime_installer.py", "comfyui_media_runtime_setup.py"):
(adapters / relative).write_text(body, encoding="utf-8")
(adapters / "media_runtime_download.py").write_text(
"import socket\n\n\ndef go():\n return socket.getaddrinfo('a', None)\n",
encoding="utf-8",
)
for name in names:
(adapters / name).write_text(body, encoding="utf-8")
findings = audit_runtime_package(package)
for relative in ("media_runtime_installer.py", "comfyui_media_runtime_setup.py"):
for name in names:
for line, module in enumerate(("http.client", "socket", "ssl"), start=1):
self.assertIn(
f"adapters/{relative}:{line}: forbidden runtime import {module}", findings
f"adapters/{name}:{line}: forbidden runtime import {module}", findings
)
self.assertTrue(
any(
f"adapters/{name}:" in finding and "forbidden network call" in finding
for finding in findings
)
self.assertIn(
f"adapters/{relative}:7: forbidden network call socket.create_connection", findings
)
self.assertIn(
"adapters/media_runtime_download.py:5: forbidden network call socket.getaddrinfo",
findings,
)
def test_native_render_process_exception_never_grants_neighbor_or_network_imports(self) -> None:
with tempfile.TemporaryDirectory() as temporary:
+2 -2
View File
@@ -18,9 +18,9 @@ ROOT = Path(__file__).resolve().parents[1]
# IMPORTANT: move this pin only with the rebuilt bundle and supply-chain manifest; otherwise HEAD
# fails its own deterministic runtime-parity contract.
RUNTIME_BUNDLE_SHA256 = (
"3b1731ddb750eefeed6ab16b1f9323f12081d7f15a824a8c7a3bd1600f90b770" # pragma: allowlist secret
"fefc67f48395bb9e64ee6cf8c4626e40259f9b2f433a411038b6ed4e238b83c7" # pragma: allowlist secret
)
RUNTIME_BUNDLE_SIZE = 1917831
RUNTIME_BUNDLE_SIZE = 1909494
def supply_chain() -> ModuleType:
+65 -4
View File
@@ -306,6 +306,54 @@ class ToolingContractTests(unittest.TestCase):
)
),
}
# IMPORTANT: the Registry policy check pins exact normalized subprocess call shapes by
# SHA-256, so a new spawn cannot hide behind a whole-module exemption. They digest this
# repository's own public source and authenticate nothing. Pinned here independently,
# split like every literal above, and never learned from the script or the baseline.
registry_call_pins = {
"registry_call_resolution": (
"ad6fa60292-88f9009dab-9f2d6bd121-38d8b3bdd0-fe616f8198-64a4cf9da1-8899".replace(
"-", ""
)
),
"registry_call_spawn": (
"dba75ea297-3f80cb0951-54e0f1cf40-7ffa938206-2e4fb8fc90-08235ee6a3-c4f9".replace(
"-", ""
)
),
"registry_call_spawn_tree": (
"c7a722d395-3267817018-d913d36991-c5e8abeb8f-7c3b975e38-b5f91ef8e1-3bf7".replace(
"-", ""
)
),
"registry_call_spawn_terminate": (
"fb5272f38d-b378271c33-689146c613-04f10ba44c-215c5dd1c4-2ebea9c654-da7d".replace(
"-", ""
)
),
"registry_call_perception": (
"6ddd71485e-539063b1ba-2c571a02c5-ce250d52d9-a98edc517d-7f0f56ac76-c2d5".replace(
"-", ""
)
),
"registry_call_dependency_probe": (
"3ac7acab13-247f837f11-19eba9efc6-6cb7c19857-153e615acf-174f639870-8d56".replace(
"-", ""
)
),
"registry_call_address_probe": (
"a64bc08c2f-59c5581305-53d7d2b882-e236715988-673d567a6c-1f707ccb00-34df".replace(
"-", ""
)
),
}
# The manual media-tool wire fixture repeats the public FFmpeg archive SHA-256 that
# `media_runtime_pin.py` pins; it binds download integrity, never authentication.
media_archive_digest = (
"ad18ecdedf-ca6d51c28c-f12f2c9628-7ce1150686-578b75bff2-efcd06ff34-bb30".replace(
"-", ""
)
)
# CRITICAL: one place that knows what each approved row is *for*. Before these
# literals were named once, hashed, and never referred to again, so nothing in this test --
# or anywhere else -- could tell that a row had gone inert. Seven had, across four files,
@@ -315,6 +363,8 @@ class ToolingContractTests(unittest.TestCase):
approved_literals = {
**font_revisions,
**perception_digests,
**registry_call_pins,
"media_archive_digest": media_archive_digest,
"backend": backend_revision,
"current_backend": current_backend_revision,
"chain_first": chain_first,
@@ -416,6 +466,8 @@ class ToolingContractTests(unittest.TestCase):
"m22_21_tree": ("comfyui_h3_context/contracts/prompt_model_profiles_v5.json",),
"m23_24_commit": ("comfyui_h3_context/contracts/build_provenance_v1.json",),
"m23_24_tree": ("comfyui_h3_context/contracts/build_provenance_v1.json",),
**{identity: ("scripts/registry_policy_check.py",) for identity in registry_call_pins},
"media_archive_digest": ("frontend/tests/fixtures/media_runtime_wire_v4.json",),
}
# CRITICAL: every approved row must still describe something that exists. A row whose
# literal has left the tree is inert -- it can never match again -- and both sides of the
@@ -441,7 +493,7 @@ class ToolingContractTests(unittest.TestCase):
for identity, paths in approved_paths.items()
for path in paths
)
self.assertEqual(sum(expected.values()), 54)
self.assertEqual(sum(expected.values()), 62)
# SECURITY: these four matches are the exact public repository owner/name, not
# credentials. Bind literal, detector and paths; never allow arbitrary Base64 rows.
repository_name = "rookiestar28/" + "ComfyUI-" + "MiniMaxH3-Studio"
@@ -467,7 +519,16 @@ class ToolingContractTests(unittest.TestCase):
)
fixture_match = "ad8649af30-91cf8af0f2-c679b92a47-b82287b425".replace("-", "")
expected[(fixture_path, "AWS Access Key", fixture_match)] = 1
self.assertEqual(sum(expected.values()), 59)
# IMPORTANT: this match is the supplied-host lane test feeding an unsupported journey
# value to its environment parser, which must refuse it. Not a credential; bind the exact
# literal, detector and path, written split so this file holds no matching literal.
refused_assignment = "H3_CONTEXT_" + "M25_34_" + "MEDIA_JOURNEY" + "=install"
refused_path = "tests/test_m25_54_supplied_host_lane.py"
with self.subTest(refused_assignment_path=refused_path):
self.assertIn(refused_assignment, (ROOT / refused_path).read_text(encoding="utf-8"))
refused_hash = hashlib.sha1(refused_assignment.encode(), usedforsecurity=False).hexdigest()
expected[(refused_path, "Base64 High Entropy String", refused_hash)] = 1
self.assertEqual(sum(expected.values()), 68)
# CRITICAL: approve public hex values only inside independently pinned complete inputs.
# Learning this census from scanner output or unpinned files would admit new credentials.
public_hash_inputs = {
@@ -492,7 +553,7 @@ class ToolingContractTests(unittest.TestCase):
for literal in literals:
match_hash = hashlib.sha1(literal, usedforsecurity=False).hexdigest()
expected[(path, "Hex High Entropy String", match_hash)] = 1
self.assertEqual(sum(expected.values()), 1983)
self.assertEqual(sum(expected.values()), 1992)
observed: Counter[tuple[str, str, str]] = Counter()
for path, findings in baseline.get("results", {}).items():
normalized_path = path.replace("\\", "/")
@@ -503,7 +564,7 @@ class ToolingContractTests(unittest.TestCase):
observed[
(normalized_path, finding.get("type", ""), finding.get("hashed_secret", ""))
] += 1
self.assertEqual(sum(observed.values()), 1983)
self.assertEqual(sum(observed.values()), 1992)
self.assertEqual(observed, expected)
def test_hosted_ci_uses_separate_public_lanes(self) -> None: