1 Commits
Author SHA1 Message Date
rookiestar28 39ffafa72c build: prepare public source 2026-10-18 06:02:00 +00:00
48 changed files with 1799 additions and 224 deletions
+20 -3
View File
@@ -18,6 +18,21 @@ implementation.
<details>
<summary><strong>1.3.2 — App Mode finishes on current ComfyUI</strong></summary>
- App Mode runs finish again on current ComfyUI versions. ComfyUI now adds extra details to each
saved video, which 1.3.0 did not recognize, so a finished run could stay at "Verifying the exact
saved output" indefinitely.
- If ComfyUI's saved-video message is missing or not recognized when the run finishes, the sidebar
looks the video up in that run's ComfyUI history for up to about 16 seconds. If it still cannot
be matched, the run ends with a message and **Continue with native nodes** instead of waiting.
- The **H3 Reference Registry** node refuses more than three audio tracks in total, including video
soundtracks, before generation starts. This matches the sidebar and the native H3 limit.
</details>
<details>
<summary><strong>1.3.0 — Ordered references, original-size assembly and clearer cut reports</strong></summary>
- Ref2VA now executes linked references from the sidebar and bundled reference graphs.
@@ -439,9 +454,11 @@ Mode so you can work on the canvas yourself.
### During and after a run
A run is queued once through the normal ComfyUI queue. It is reported as finished only after the
saved video has been checked against that run; a video that cannot be matched is reported as
unconfirmed and never retried automatically. If the connection to ComfyUI drops, the sidebar picks
the run up again when it reconnects.
saved video has been checked against that run. If ComfyUI's saved-video message is missing or not
recognized when the run finishes, the sidebar looks the video up in that run's ComfyUI history for
up to about 16 seconds. A video that still cannot be matched is reported as not verified, the saved
file is left unchanged and the run is never queued again automatically. If the connection to
ComfyUI drops, the sidebar picks the run up again when it reconnects.
The finished video is added to the **Production** project shown above the App Mode buttons ("Adds
to Project …" or "Creates Project …"):
+40
View File
@@ -1,3 +1,43 @@
# Release 1.3.2
## App Mode output verification
- App Mode runs finish on current ComfyUI versions. ComfyUI now annotates each saved video entry
with media details and, when its asset system is enabled, an asset identifier. 1.3.0 accepted
only the exact earlier entry shape, so it ignored the saved video, and the finished run stayed at
"Verifying the exact saved output" indefinitely.
- Saved video entries are read by their file name, folder and output type; any other detail is
ignored and never stored.
- If ComfyUI's saved-video message is missing or not recognized when the run finishes, the sidebar
reads that run's ComfyUI history for up to about 16 seconds. Exactly one saved video completes
the run through the same verification as before. Otherwise the run ends with the existing "could
not be verified safely" message and **Continue with native nodes**; the saved file is left
unchanged and nothing is queued again. A saved-video message that arrives while the sidebar is
still waiting still completes the run.
## Reference limits
- The Reference Registry, reference normalization and reference-set authoring refuse more than
three audio tracks in total, including video soundtracks. The Registry node refuses before
generation starts; authoring refuses when a source is added or restored. Before, canvas graphs
could pass up to six audio tracks, and only the native adapter refused them when the run reached
it. The sidebar limits and the native node are unchanged.
## Developer notes
- Tests decode the current ComfyUI saved-output shape. A model-free host row decodes the host's real
saved-output message and history record. The weight-backed sample also checks that the sidebar
reaches its finished state.
## Upgrade and limits
Replace the complete package, restart ComfyUI and refresh the browser. Project, receipt and settings
formats and the other public data formats are unchanged from 1.3.0. A graph that passes more than
three audio tracks in total to the reference nodes was already refused by the native adapter; it is
now refused before generation starts, with a message naming the audio limit.
---
# Release 1.3.0
## Reference generation
+1 -1
View File
@@ -137,7 +137,7 @@ if os.environ.get("H3_CONTEXT_HOST_SEQUENCE_CONTINUATION_CANARY") == "1":
NODE_CLASS_MAPPINGS = {**NODE_CLASS_MAPPINGS, **CANARY_NODES}
NODE_DISPLAY_NAME_MAPPINGS = {**NODE_DISPLAY_NAME_MAPPINGS, **CANARY_DISPLAY_NAMES}
__version__ = "1.3.0"
__version__ = "1.3.2"
WEB_DIRECTORY = "web"
# CRITICAL: this bounded operator attempt runs after node registration. Its module owner survives
@@ -33,6 +33,7 @@ from .core.contracts import (
)
from .core.errors import (
ContextReportError,
ReferenceAudioCapacityError,
)
from .core.full_reference_timeline import FullReferenceTimelineResult
from .core.length import MAX_ACCEPTED_MILLISECONDS, MILLISECONDS_PER_SECOND
@@ -581,6 +582,8 @@ class H3ReferenceRegistryNode:
assets += tuple(video_assets) + standalone_assets
try:
registry = build_reference_registry(assets)
except ReferenceAudioCapacityError as exc:
raise _reference_error(exc.code, str(exc)) from exc
except ReferenceRegistryError as exc:
raise _reference_error("invalid_reference_registry", str(exc)) from exc
if capture_runtime_sources:
@@ -5,26 +5,26 @@
},
"bundle": {
"path": "comfyui_h3_context/web/h3-context-sidebar.js",
"sha256": "sha256:de6c94641926a51b56fdb3092775e58df0013aae3f38497c0bdadd7dde4e2e13",
"size": 1924005
"sha256": "sha256:90615618067ab6143c0f8d422cf5182a913cd1d48e2932b5efc48a26a968c68b",
"size": 1926109
},
"embedded_identity": {
"builder_id": "scripts/frontend_build_report.py",
"resolved_dependencies_sha256": "sha256:1ee0321c7dfdedd8ea381f522cb829443b0daa240fefc67fe81bd165e3c8ac99",
"schema": "h3-context-build-identity/1",
"source_commit": "eb4074c5a6f49dfef1faf5328fae5a72df6ff122",
"source_inputs_sha256": "sha256:2f6153eec6e445c11e3a7918fdbcd9fbb58aedeab2d04de400bef649325acb1b",
"source_tree": "f0b07b4f921948e8ada0f1764f4b91e93d294a89"
"source_commit": "ed87fd861175810dccba668f489fe854b98948d3",
"source_inputs_sha256": "sha256:3c8448a7fa3bedd69e64c71e37755d1a6b1d26c202213708d1ad018e9293c03c",
"source_tree": "e64fdc5846dee0ad62dd97269df7abe6b00722b1"
},
"external_parameters": {
"source_commit": "eb4074c5a6f49dfef1faf5328fae5a72df6ff122",
"source_inputs_sha256": "sha256:2f6153eec6e445c11e3a7918fdbcd9fbb58aedeab2d04de400bef649325acb1b",
"source_tree": "f0b07b4f921948e8ada0f1764f4b91e93d294a89"
"source_commit": "ed87fd861175810dccba668f489fe854b98948d3",
"source_inputs_sha256": "sha256:3c8448a7fa3bedd69e64c71e37755d1a6b1d26c202213708d1ad018e9293c03c",
"source_tree": "e64fdc5846dee0ad62dd97269df7abe6b00722b1"
},
"invocation": {
"finished_on": "2026-10-14T21:14:16Z",
"id": "sha256:bb5b4c731b26fcfe37750dc5a1074b351a29d9c058b783819a083e9be81ce0cf",
"started_on": "2026-10-14T21:14:16Z"
"finished_on": "2026-10-17T21:38:37Z",
"id": "sha256:6019c10662352f6cd7fc5e56f56c2cc5a5a9ecdd47410664ef3f6d6fe949e907",
"started_on": "2026-10-17T21:38:37Z"
},
"resolved_dependencies": [
{
@@ -1 +1 @@
{"profiles":[{"compatibility":["python>=3.10"],"distribution":"minimax-h3-studio==1.3.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.3.2","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}
+6
View File
@@ -243,6 +243,12 @@ class ReferenceRegistryError(ContractValidationError):
"""Raised when canonical assets or their ownership metadata are invalid."""
class ReferenceAudioCapacityError(ReferenceRegistryError):
"""Paired and standalone references exceed the shared native audio capacity."""
code = "too_many_audio"
class ReferenceOrderError(ReferenceRegistryError):
"""Raised when references are reordered, gapped, or in an invalid host group order."""
@@ -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.3.0",
distribution="minimax-h3-studio==1.3.2",
compatibility=("python>=3.10",),
required=True,
install_mode="artifact",
+2 -1
View File
@@ -16,6 +16,7 @@ from .context_reporting import ContextReport, ValidationStatus
from .contracts import AssetRole, MediaKind, ProfileIdentity, PromptProfile, TaskMode
from .errors import ContextReportError, NativeH3AdapterError, ReportLifecycleError
from .length import is_producible
from .reference_limits import H3_BASE_MAX_AUDIO_REFERENCES
from .registry import BackendLabel, ReferenceRegistry
from .validation_lifecycle import ValidatedReportEnvelope, require_execution_ready
@@ -30,7 +31,7 @@ NATIVE_H3_MAX_BINDINGS = 32
NATIVE_H3_BASE_MAX_REFERENCES = 12
NATIVE_H3_BASE_MAX_IMAGES = 9
NATIVE_H3_BASE_MAX_VIDEOS = 3
NATIVE_H3_BASE_MAX_AUDIO = 3
NATIVE_H3_BASE_MAX_AUDIO = H3_BASE_MAX_AUDIO_REFERENCES
NATIVE_H3_BASE_MIN_OUTPUT_SECONDS = Decimal("4")
NATIVE_H3_BASE_MAX_OUTPUT_SECONDS = Decimal("15")
NATIVE_H3_BASE_MIN_TIMED_REFERENCE_SECONDS = Decimal("2")
+2 -1
View File
@@ -40,6 +40,7 @@ from .length import (
is_producible,
resolve_milliseconds,
)
from .reference_limits import H3_BASE_MAX_AUDIO_REFERENCES
from .registry import ReferenceRegistry
# the lattice, the ranges and the conversions live in `.length`, which is
@@ -49,7 +50,7 @@ from .registry import ReferenceRegistry
MAX_USER_INTENT_LENGTH = 65_536
MAX_REFERENCE_IMAGES = 9
MAX_REFERENCE_VIDEOS = 3
MAX_REFERENCE_AUDIO = 6
MAX_REFERENCE_AUDIO = H3_BASE_MAX_AUDIO_REFERENCES
class DurationSource(str, Enum):
@@ -0,0 +1,5 @@
"""Shared native reference capacities, independent of registry and request imports."""
# IMPORTANT: paired soundtracks and standalone audio consume the same native pool.
# Separate three-file allowances admit six files that native preflight must reject.
H3_BASE_MAX_AUDIO_REFERENCES = 3
@@ -50,6 +50,7 @@ from enum import Enum
from .canonical import canonical_fingerprint
from .contracts import MediaKind
from .errors import ContractValidationError
from .reference_limits import H3_BASE_MAX_AUDIO_REFERENCES
from .registry import (
MAX_PAIRED_VIDEO_AUDIO,
MAX_REFERENCE_IMAGES,
@@ -725,6 +726,7 @@ def capacity_projection(state: ReferenceSetState) -> CapacityProjection:
standalone_used = len(state.audios) - paired_used
aggregate_used = len(state.images) + len(state.videos) + len(state.audios)
aggregate_remaining = max(0, capacity.aggregate_max - aggregate_used)
audio_remaining = max(0, H3_BASE_MAX_AUDIO_REFERENCES - len(state.audios))
def remaining(kind_max: int, used: int) -> int:
return min(max(0, kind_max - used), aggregate_remaining)
@@ -738,9 +740,13 @@ def capacity_projection(state: ReferenceSetState) -> CapacityProjection:
video_used=len(state.videos),
video_remaining=remaining(capacity.video_max, len(state.videos)),
paired_audio_used=paired_used,
paired_audio_remaining=remaining(capacity.paired_audio_max, paired_used),
paired_audio_remaining=min(
remaining(capacity.paired_audio_max, paired_used), audio_remaining
),
standalone_audio_used=standalone_used,
standalone_audio_remaining=remaining(capacity.standalone_audio_max, standalone_used),
standalone_audio_remaining=min(
remaining(capacity.standalone_audio_max, standalone_used), audio_remaining
),
timed=capacity.timed,
)
@@ -834,6 +840,10 @@ def _check_add(
standalone_used = len(state.audios) - len(state.bound_audio_ids())
if standalone_used + 1 > capacity.standalone_audio_max:
raise _reject("capacity_standalone_audio", "the standalone audio ceiling is reached")
# IMPORTANT: soundtrack binding changes ownership, not file count. Add and restore
# share this guard; a freed standalone socket must never admit a fourth native audio.
if source.kind is MediaKind.AUDIO and len(state.audios) + 1 > H3_BASE_MAX_AUDIO_REFERENCES:
raise _reject("capacity_audio_total", "the total reference audio ceiling is reached")
aggregate = len(state.images) + len(state.videos) + len(state.audios)
if aggregate + 1 > capacity.aggregate_max:
raise _reject("capacity_aggregate", "the aggregate reference ceiling is reached")
+12 -4
View File
@@ -15,15 +15,17 @@ from enum import Enum
from .contracts import AssetDescriptor, AssetRole, MediaKind
from .errors import (
ContractValidationError,
ReferenceAudioCapacityError,
ReferenceLabelError,
ReferenceOrderError,
ReferenceRegistryError,
)
from .reference_limits import H3_BASE_MAX_AUDIO_REFERENCES
MAX_REFERENCE_IMAGES = 9
MAX_REFERENCE_VIDEOS = 3
MAX_PAIRED_VIDEO_AUDIO = 3
MAX_STANDALONE_AUDIO = 3
MAX_PAIRED_VIDEO_AUDIO = H3_BASE_MAX_AUDIO_REFERENCES
MAX_STANDALONE_AUDIO = H3_BASE_MAX_AUDIO_REFERENCES
MAX_CONNECTION_ORDER = 1000
MAX_WIDTH = 1_048_576
MAX_HEIGHT = 1_048_576
@@ -272,13 +274,19 @@ def _validate_asset_sequence(assets: tuple[ReferenceAsset, ...]) -> None:
f"at most {MAX_REFERENCE_VIDEOS} reference videos are supported"
)
if paired_count > MAX_PAIRED_VIDEO_AUDIO:
raise ReferenceRegistryError(
raise ReferenceAudioCapacityError(
f"at most {MAX_PAIRED_VIDEO_AUDIO} paired video soundtracks are supported"
)
if standalone_count > MAX_STANDALONE_AUDIO:
raise ReferenceRegistryError(
raise ReferenceAudioCapacityError(
f"at most {MAX_STANDALONE_AUDIO} standalone reference audio assets are supported"
)
# IMPORTANT: both label families consume one native audio pool. Checking each socket
# alone admits invalid mixed sets and delays refusal until native execution.
if paired_count + standalone_count > H3_BASE_MAX_AUDIO_REFERENCES:
raise ReferenceAudioCapacityError(
f"at most {H3_BASE_MAX_AUDIO_REFERENCES} total reference audio assets are supported"
)
def _derive_labels(assets: tuple[ReferenceAsset, ...]) -> tuple[BackendLabel, ...]:
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -159,7 +159,7 @@ Build a Python source distribution from a Git checkout whose reviewed public inp
```powershell
& .\.venv\Scripts\python.exe -m build --sdist
& .\.venv\Scripts\python.exe scripts/sdist_payload.py --archive dist/minimax_h3_studio-1.3.0.tar.gz
& .\.venv\Scripts\python.exe scripts/sdist_payload.py --archive dist/minimax_h3_studio-1.3.2.tar.gz
```
The standard build backend copies public tracked files into a fresh temporary tree and respects
+2 -1
View File
@@ -224,7 +224,8 @@ escapes and unsafe URL schemes are refused.
The Ref2VA sidebar checks reference counts and combined file/audio limits from the selected canvas
nodes. Selection does not read or probe their media. Its duration hints are input-preparation
guidance rather than measured duration checks; the nodes that load and execute media apply their
own validation.
own validation. The **H3 Reference Registry** node refuses more than three audio tracks in total,
including video soundtracks, before generation starts.
Text found in media or returned by a provider is information, never an instruction. It cannot
change provider settings, your hard constraints, the workflow or how a run executes. Unknown facts
+4
View File
@@ -518,6 +518,10 @@ export async function mountManagedEntryHarness(
: undefined,
),
);
// a recorded success without an artifact reads `/history`. This double models a host
// that has not stored the prompt yet, so the recovery keeps waiting and the journeys' own
// test-controlled SaveVideo event decides the run, as it did before the recovery existed.
if (path.startsWith("/history/")) return jsonResponse({});
const body = object(JSON.parse(String(init.body ?? "{}"))) ?? {};
const action = typeof body.action === "string" ? body.action : "";
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@comfyui-h3-context/frontend",
"version": "1.3.0",
"version": "1.3.2",
"private": true,
"type": "module",
"packageManager": "pnpm@11.3.0",
+2
View File
@@ -56,6 +56,7 @@ import {
} from "./lifecycle/shellSession";
import { createAppModeSession } from "./lifecycle/appModeSession";
import { createAppModeCorrelation } from "./lifecycle/appModeCorrelation";
import { createManagedArtifactAwait } from "./lifecycle/managedArtifactAwait";
import { createProductionSession } from "./host/productionSession";
import { createAuthoringSession } from "./host/authoringSession";
import { createProviderSession } from "./host/providerSession";
@@ -341,6 +342,7 @@ Object.assign(
shellActions,
createAppModeSession(runtime),
createAppModeCorrelation(runtime),
createManagedArtifactAwait(runtime),
createProductionSession(runtime),
createAuthoringSession(runtime),
createProviderSession(runtime),
+113 -34
View File
@@ -1,4 +1,8 @@
import { sha256Text } from "../contracts/canonicalFingerprint";
import {
saveVideoArtifactFromOutput,
type SaveVideoArtifactEvent,
} from "./saveVideoArtifact";
export const COMFY_PROMPT_HISTORY_OBSERVATION_SCHEMA =
"h3.context.comfy_prompt_history_observation.v1" as const;
@@ -215,17 +219,29 @@ function outputIdentity(outputsValue: unknown): Readonly<{
});
}
export function decodeComfyPromptHistory(
export type ComfyPromptHistorySavedVideos = Readonly<{
promptId: string;
disposition: ComfyPromptHistoryDisposition;
artifacts: readonly SaveVideoArtifactEvent[];
}>;
/** Return the exact prompt's history row, or `undefined` while the host has not stored it. */
function promptHistoryRow(
value: unknown,
promptId: string,
): ComfyPromptHistoryObservationV1 {
):
| Readonly<{
row: Record<string, unknown>;
disposition: ComfyPromptHistoryDisposition;
}>
| undefined {
if (!promptIdentifier.test(promptId))
throw new ComfyPromptHistoryError("invalid_prompt_id", 400);
const root = record(value);
if (root === undefined)
throw new ComfyPromptHistoryError("history_malformed", 422);
const keys = Object.keys(root);
if (keys.length === 0) return notYetObserved(promptId);
if (keys.length === 0) return undefined;
if (keys.length !== 1 || keys[0] !== promptId)
throw new ComfyPromptHistoryError("history_foreign", 409);
const row = record(root[promptId]);
@@ -233,7 +249,52 @@ export function decodeComfyPromptHistory(
if (row === undefined || status === undefined)
throw new ComfyPromptHistoryError("history_malformed", 422);
const disposition = terminalDisposition(status);
if (disposition === "not_yet_observed") return notYetObserved(promptId);
if (disposition === "not_yet_observed") return undefined;
return Object.freeze({ row, disposition });
}
/**
* Decode the SaveVideo artifacts one completed prompt recorded ( recovery read).
*
* The outputs pass the same bounds as the history observation; each node output is decoded by
* the shared SaveVideo decoder, so LoadVideo's `input` preview and temporary previews never count.
*/
export function decodeComfyPromptHistorySavedVideos(
value: unknown,
promptId: string,
): ComfyPromptHistorySavedVideos {
const stored = promptHistoryRow(value, promptId);
if (stored === undefined)
return Object.freeze({
promptId,
disposition: "not_yet_observed" as const,
artifacts: Object.freeze([]),
});
const identity = outputIdentity(stored.row.outputs);
const outputs = record(stored.row.outputs) ?? {};
const artifacts: SaveVideoArtifactEvent[] = [];
for (const nodeId of identity.nodeIds) {
const artifact = saveVideoArtifactFromOutput(
promptId,
nodeId,
outputs[nodeId],
);
if (artifact !== undefined) artifacts.push(artifact);
}
return Object.freeze({
promptId,
disposition: stored.disposition,
artifacts: Object.freeze(artifacts),
});
}
export function decodeComfyPromptHistory(
value: unknown,
promptId: string,
): ComfyPromptHistoryObservationV1 {
const stored = promptHistoryRow(value, promptId);
if (stored === undefined) return notYetObserved(promptId);
const { row, disposition } = stored;
const output = outputIdentity(row.outputs);
const terminalFingerprint = sha256Text(
JSON.stringify({
@@ -260,41 +321,59 @@ export function createComfyPromptHistoryClient({
}) {
if (typeof fetchApi !== "function")
throw new Error("supported same-origin history seam is absent");
async function readHistoryValue(
promptId: string,
signal?: AbortSignal,
): Promise<unknown> {
if (!promptIdentifier.test(promptId))
throw new ComfyPromptHistoryError("invalid_prompt_id", 400);
let response: FetchResponse;
try {
response = await fetchApi(`/history/${encodeURIComponent(promptId)}`, {
method: "GET",
credentials: "same-origin",
headers: { accept: "application/json" },
signal,
});
} catch {
throw new ComfyPromptHistoryError("history_unavailable", 0);
}
if (!response.ok)
throw new ComfyPromptHistoryError(
"history_route_rejected",
response.status,
);
const declaredLength = response.headers.get("content-length");
if (declaredLength !== null) {
const parsed = Number(declaredLength);
if (!Number.isSafeInteger(parsed) || parsed < 0)
throw new ComfyPromptHistoryError("history_malformed", 422);
if (parsed > MAX_HISTORY_BYTES)
throw new ComfyPromptHistoryError("history_oversized", 413);
}
// IMPORTANT: keep history on this bounded stream path; arrayBuffer() would read an
// untrusted missing or under-reported response without enforcing the 1 MiB ceiling.
const body = await readBoundedBody(response.body);
return decodeBody(body);
}
return Object.freeze({
async read(
promptId: string,
signal?: AbortSignal,
): Promise<ComfyPromptHistoryObservationV1> {
if (!promptIdentifier.test(promptId))
throw new ComfyPromptHistoryError("invalid_prompt_id", 400);
let response: FetchResponse;
try {
response = await fetchApi(`/history/${encodeURIComponent(promptId)}`, {
method: "GET",
credentials: "same-origin",
headers: { accept: "application/json" },
signal,
});
} catch {
throw new ComfyPromptHistoryError("history_unavailable", 0);
}
if (!response.ok)
throw new ComfyPromptHistoryError(
"history_route_rejected",
response.status,
);
const declaredLength = response.headers.get("content-length");
if (declaredLength !== null) {
const parsed = Number(declaredLength);
if (!Number.isSafeInteger(parsed) || parsed < 0)
throw new ComfyPromptHistoryError("history_malformed", 422);
if (parsed > MAX_HISTORY_BYTES)
throw new ComfyPromptHistoryError("history_oversized", 413);
}
// IMPORTANT: keep history on this bounded stream path; arrayBuffer() would read an
// untrusted missing or under-reported response without enforcing the 1 MiB ceiling.
const body = await readBoundedBody(response.body);
return decodeComfyPromptHistory(decodeBody(body), promptId);
return decodeComfyPromptHistory(
await readHistoryValue(promptId, signal),
promptId,
);
},
async readSavedVideos(
promptId: string,
signal?: AbortSignal,
): Promise<ComfyPromptHistorySavedVideos> {
return decodeComfyPromptHistorySavedVideos(
await readHistoryValue(promptId, signal),
promptId,
);
},
});
}
+99
View File
@@ -0,0 +1,99 @@
// SaveVideo artifact decoding shared by the `executed` listener and the `/history` recovery read
//. Pure: no host seam, no network.
export type SaveVideoArtifactEvent = Readonly<{
promptId: string;
outputNodeId: string;
locator: Readonly<{
filename: string;
subfolder: string;
type: "output";
}>;
}>;
function record(value: unknown): Record<string, unknown> | undefined {
return value !== null && typeof value === "object" && !Array.isArray(value)
? (value as Record<string, unknown>)
: undefined;
}
function boundedIdentifier(value: unknown): string | undefined {
if (
typeof value !== "string" ||
value.length < 1 ||
value.length > 256 ||
!/^[A-Za-z0-9][A-Za-z0-9._:-]*$/.test(value)
)
return undefined;
return value;
}
/**
* Decode stock SaveVideo's one-result PreviewVideo UI output for one prompt and node.
*
* CRITICAL: the output members stay exact (`images` and `animated` only, one saved entry,
* `animated: [true]`), but the saved entry is read by its three locator fields and any other key is
* ignored. ComfyUI after v0.39.0 annotates every file entry in `executed` and `/history` with
* `metadata` (media properties) and, with assets on, `id`. Refusing unknown entry keys made the
* decoder return nothing on those hosts, and a managed run then waited in `verifying_output`
* forever. Do not reintroduce an exact entry key count or a fixed allow-list of annotation keys:
* the host treats entries as extensible records. The result is rebuilt from the three fields, so no
* annotation ever reaches the coordinator, the journal or storage; the coordinator verifies the
* file itself.
*/
export function saveVideoArtifactFromOutput(
promptIdValue: unknown,
outputNodeIdValue: unknown,
outputValue: unknown,
): SaveVideoArtifactEvent | undefined {
const promptId = boundedIdentifier(promptIdValue);
const outputNodeId = boundedIdentifier(outputNodeIdValue);
const output = record(outputValue);
if (
promptId === undefined ||
outputNodeId === undefined ||
output === undefined ||
Object.keys(output).some((key) => key !== "images" && key !== "animated") ||
!Array.isArray(output.images) ||
output.images.length !== 1 ||
!Array.isArray(output.animated) ||
output.animated.length !== 1 ||
output.animated[0] !== true
)
return undefined;
const saved = record(output.images[0]);
if (
saved === undefined ||
!Object.hasOwn(saved, "filename") ||
!Object.hasOwn(saved, "subfolder") ||
!Object.hasOwn(saved, "type") ||
typeof saved.filename !== "string" ||
saved.filename.length === 0 ||
saved.filename.length > 255 ||
typeof saved.subfolder !== "string" ||
saved.subfolder.length > 512 ||
saved.type !== "output"
)
return undefined;
return Object.freeze({
promptId,
outputNodeId,
locator: Object.freeze({
filename: saved.filename,
subfolder: saved.subfolder,
type: "output" as const,
}),
});
}
/** Decode one ComfyUI `executed` event detail. */
export function saveVideoArtifactFromExecuted(
detailValue: unknown,
): SaveVideoArtifactEvent | undefined {
const detail = record(detailValue);
return saveVideoArtifactFromOutput(
detail?.prompt_id,
detail?.node,
detail?.output,
);
}
+6 -55
View File
@@ -42,6 +42,12 @@ import {
probeSidebarTabManager,
type SeamRefusal,
} from "./hostSeams";
import {
saveVideoArtifactFromExecuted,
type SaveVideoArtifactEvent,
} from "./saveVideoArtifact";
export { saveVideoArtifactFromExecuted, type SaveVideoArtifactEvent };
const tabId = "h3-context";
const SIDEBAR_UNREGISTER_SEAM_ABSENT: SeamRefusal =
@@ -97,15 +103,6 @@ export type ExecutionTerminalEvent = Readonly<{
promptId: string;
kind: ExecutionTerminalKind;
}>;
export type SaveVideoArtifactEvent = Readonly<{
promptId: string;
outputNodeId: string;
locator: Readonly<{
filename: string;
subfolder: string;
type: "output";
}>;
}>;
export type ProjectionGraphContext = {
inspection: GraphInspection;
source: "graph" | "executed";
@@ -153,52 +150,6 @@ function boundedPromptId(value: unknown): string | undefined {
return value;
}
/** Decode only stock SaveVideo's one-result PreviewVideo UI payload. */
export function saveVideoArtifactFromExecuted(
detailValue: unknown,
): SaveVideoArtifactEvent | undefined {
const detail = record(detailValue);
const promptId = boundedPromptId(detail?.prompt_id);
const outputNodeId = boundedPromptId(detail?.node);
const output = record(detail?.output);
if (
promptId === undefined ||
outputNodeId === undefined ||
output === undefined ||
Object.keys(output).some((key) => key !== "images" && key !== "animated") ||
!Array.isArray(output.images) ||
output.images.length !== 1 ||
!Array.isArray(output.animated) ||
output.animated.length !== 1 ||
output.animated[0] !== true
)
return undefined;
const saved = record(output.images[0]);
if (
saved === undefined ||
Object.keys(saved).length !== 3 ||
!Object.hasOwn(saved, "filename") ||
!Object.hasOwn(saved, "subfolder") ||
!Object.hasOwn(saved, "type") ||
typeof saved.filename !== "string" ||
saved.filename.length === 0 ||
saved.filename.length > 255 ||
typeof saved.subfolder !== "string" ||
saved.subfolder.length > 512 ||
saved.type !== "output"
)
return undefined;
return Object.freeze({
promptId,
outputNodeId,
locator: Object.freeze({
filename: saved.filename,
subfolder: saved.subfolder,
type: "output" as const,
}),
});
}
export function projectionFromOutput(outputValue: unknown): {
projection: ProductShellProjection;
workspace: SidebarWorkspaceProjection;
+6 -6
View File
@@ -57,7 +57,6 @@ import {
export function createAppModeCorrelation(ctx: ShellRuntime) {
const { session, deps, actions } = ctx;
const recordedSuccessWithoutArtifact = new WeakSet<ActiveManagedRun>();
function recordManagedStage(
stage: ManagedDiagnosticStage,
@@ -228,7 +227,7 @@ export function createAppModeCorrelation(ctx: ShellRuntime) {
// CRITICAL: a reconnect may be the first response that proves the backend recorded the
// exact success terminal. Keep that admission and its prompt correlation locally, or a
// later SaveVideo event would wait forever for a terminal the host does not replay.
recordedSuccessWithoutArtifact.add(managed);
actions.markRecordedSuccessWithoutArtifact(managed);
if (managed.modelPromptId !== undefined)
managed.pendingTerminals.set(managed.modelPromptId, "success");
}
@@ -626,7 +625,7 @@ export function createAppModeCorrelation(ctx: ShellRuntime) {
outcome.kind === "continue" &&
current.disposition === "verification_pending"
) {
recordedSuccessWithoutArtifact.add(managed);
actions.markRecordedSuccessWithoutArtifact(managed);
if (managed.modelPromptId !== undefined)
managed.pendingTerminals.set(managed.modelPromptId, "success");
await settleManagedDisposition(managed, current);
@@ -694,7 +693,7 @@ export function createAppModeCorrelation(ctx: ShellRuntime) {
// terminal events cannot replace it. Only a matching late artifact may advance this run.
if (
event.kind === "terminal" &&
recordedSuccessWithoutArtifact.has(managed)
actions.hasRecordedSuccessWithoutArtifact(managed)
) {
managed.pendingTerminals.set(event.value.promptId, "success");
return;
@@ -737,9 +736,10 @@ export function createAppModeCorrelation(ctx: ShellRuntime) {
terminalKind === "success" &&
closingArtifact === undefined &&
result.disposition === "verification_pending";
if (pendingVerifiedOutput) recordedSuccessWithoutArtifact.add(managed);
if (pendingVerifiedOutput)
actions.markRecordedSuccessWithoutArtifact(managed);
else {
recordedSuccessWithoutArtifact.delete(managed);
actions.clearRecordedSuccessWithoutArtifact(managed);
managed.pendingTerminals.delete(managed.modelPromptId);
}
managed.pendingArtifacts.delete(managed.modelPromptId);
@@ -0,0 +1,107 @@
// Managed output wait: the backend has recorded the exact success terminal but no SaveVideo
// artifact has closed the run yet. This module owns that waiting state and its exit together
//, so no path can mark a run as waiting without also scheduling the way out.
import { ComfyPromptHistoryError } from "../host/comfyPromptHistory";
import type { SaveVideoArtifactEvent } from "../host/sidebarHost";
import type { ActiveManagedRun, ShellRuntime } from "./shellSession";
/** Delays before each `/history` read while the host has not yet stored the finished prompt. */
const ARTIFACT_HISTORY_DELAYS_MS = [
250, 500, 1_000, 2_000, 4_000, 8_000,
] as const;
export function createManagedArtifactAwait(ctx: ShellRuntime) {
const { session, deps, actions } = ctx;
const recordedSuccessWithoutArtifact = new WeakSet<ActiveManagedRun>();
const historyRecoveries = new WeakSet<ActiveManagedRun>();
function awaitingRecordedArtifact(managed: ActiveManagedRun): boolean {
return (
session.activeManagedRun === managed &&
!managed.completed &&
managed.artifactRecovery === undefined &&
recordedSuccessWithoutArtifact.has(managed)
);
}
/**
* Record that the backend holds the exact success terminal without an artifact.
*
* CRITICAL: this is the only way to enter the wait, and it always schedules the exit. Before
* `verification_pending` could only be left by a matching SaveVideo event. ComfyUI never
* resends `executed`, so an undecodable or lost event left the run in `verifying_output` forever
* with no error and no recovery. One bounded `/history` read now either recovers exactly one
* SaveVideo artifact, which takes the ordinary verified close, or fails the run as
* `artifact_verification_failed`. Do not split the mark from the scheduling, remove the final
* failure, or make it conditional on a host capability: a waiting state without an exit is the
* defect. A late websocket artifact still wins, because every step re-checks that the run is
* still waiting and the failure is queued behind any close already in `managed.transition`.
*/
function markRecordedSuccessWithoutArtifact(managed: ActiveManagedRun): void {
recordedSuccessWithoutArtifact.add(managed);
const promptId = managed.modelPromptId;
if (promptId === undefined || historyRecoveries.has(managed)) return;
historyRecoveries.add(managed);
void recoverArtifactFromHistory(managed, promptId);
}
async function recoverArtifactFromHistory(
managed: ActiveManagedRun,
promptId: string,
): Promise<void> {
let artifacts: readonly SaveVideoArtifactEvent[] | undefined;
for (const delay of ARTIFACT_HISTORY_DELAYS_MS) {
await new Promise<void>((resolve) => setTimeout(resolve, delay));
if (!awaitingRecordedArtifact(managed)) return;
try {
// ComfyUI stores history just after it sends `execution_success`; retry while absent.
const read =
await deps.comfyPromptHistoryClient.readSavedVideos(promptId);
if (read.disposition === "not_yet_observed") continue;
artifacts = read.promptId === promptId ? read.artifacts : undefined;
break;
} catch (error) {
// A foreign, malformed or refused record is final; only an unreachable read is retried.
if (
!(error instanceof ComfyPromptHistoryError) ||
error.code !== "history_unavailable"
)
break;
}
}
managed.transition = managed.transition
.then(() => {
if (!awaitingRecordedArtifact(managed)) return;
if (artifacts !== undefined && artifacts.length === 1) {
actions.recordManagedStage("artifact_history_recovered", managed.run);
actions.enqueueManagedHostEvent(managed, {
kind: "artifact",
value: artifacts[0],
});
return;
}
actions.recordManagedStage("artifact_history_unresolved", managed.run);
actions.failManagedRun(
managed,
"artifact_verification_failed",
"use_native",
);
})
.catch(() => {
actions.failManagedRun(
managed,
"artifact_verification_failed",
"use_native",
);
});
}
return {
markRecordedSuccessWithoutArtifact,
clearRecordedSuccessWithoutArtifact: (managed: ActiveManagedRun) =>
recordedSuccessWithoutArtifact.delete(managed),
hasRecordedSuccessWithoutArtifact: (managed: ActiveManagedRun) =>
recordedSuccessWithoutArtifact.has(managed),
};
}
+2
View File
@@ -120,6 +120,7 @@ import {
import type { HostApi, HostApp } from "../host/hostModuleTypes";
import type { createAppModeSession } from "./appModeSession";
import type { createAppModeCorrelation } from "./appModeCorrelation";
import type { createManagedArtifactAwait } from "./managedArtifactAwait";
import type { createProductionSession } from "../host/productionSession";
import type { createAuthoringSession } from "../host/authoringSession";
import type { createProviderSession } from "../host/providerSession";
@@ -454,6 +455,7 @@ export type ShellDeps = Readonly<{
export type ShellActions = ReturnType<typeof createAppModeSession> &
ReturnType<typeof createAppModeCorrelation> &
ReturnType<typeof createManagedArtifactAwait> &
ReturnType<typeof createProductionSession> &
ReturnType<typeof createAuthoringSession> &
ReturnType<typeof createProviderSession> &
+2
View File
@@ -48,6 +48,8 @@ export const MANAGED_DIAGNOSTIC_STAGES = [
"reconcile_terminalized",
"reconcile_refused",
"reconcile_unavailable",
"artifact_history_recovered",
"artifact_history_unresolved",
] as const;
export type ManagedDiagnosticStage = (typeof MANAGED_DIAGNOSTIC_STAGES)[number];
+145
View File
@@ -223,3 +223,148 @@ describe("exact Comfy prompt history", () => {
).resolves.toMatchObject({ disposition: "not_yet_observed" });
});
});
describe("SaveVideo artifacts recorded in exact prompt history", () => {
const mediaMetadata = {
kind: "video",
width: 1280,
height: 720,
duration: 8,
fps: 24,
frame_count: 192,
};
const saved = {
filename: "managed_00001_.mp4",
subfolder: "video/h3-context",
type: "output",
};
function completed(
outputs: Record<string, unknown>,
terminal = "execution_success",
) {
return {
[promptId]: {
prompt: "private prompt and workflow payload",
status: {
status_str: terminal === "execution_success" ? "success" : "error",
completed: true,
messages: [
["execution_start", { prompt_id: promptId }],
[terminal, { prompt_id: promptId }],
],
},
outputs,
},
};
}
it("decodes the host-annotated SaveVideo entry and ignores input and temporary previews", async () => {
const fetchApi = vi.fn(async () =>
response(
completed({
"12": {
images: [
{
filename: "reference.mp4",
subfolder: "",
type: "input",
metadata: mediaMetadata,
},
],
animated: [true],
},
"21": {
images: [{ filename: "preview.mp4", subfolder: "", type: "temp" }],
animated: [true],
},
"43": {
images: [
{ ...saved, metadata: mediaMetadata, id: "asset-managed-00001" },
],
animated: [true],
},
}),
),
);
const result = await createComfyPromptHistoryClient({
fetchApi,
}).readSavedVideos(promptId);
expect(result).toEqual({
promptId,
disposition: "succeeded",
artifacts: [{ promptId, outputNodeId: "43", locator: saved }],
});
expect(JSON.stringify(result)).not.toContain("asset-managed");
expect(JSON.stringify(result)).not.toContain("private prompt");
expect(fetchApi).toHaveBeenCalledWith(
`/history/${encodeURIComponent(promptId)}`,
expect.objectContaining({ method: "GET", credentials: "same-origin" }),
);
});
it("reports an absent or incomplete row as not yet observed with no artifacts", async () => {
for (const value of [
{},
{
[promptId]: {
status: { status_str: "running", completed: false, messages: [] },
outputs: {},
},
},
]) {
const fetchApi = vi.fn(async () => response(value));
await expect(
createComfyPromptHistoryClient({ fetchApi }).readSavedVideos(promptId),
).resolves.toEqual({
promptId,
disposition: "not_yet_observed",
artifacts: [],
});
}
});
it("returns every SaveVideo candidate and the failed disposition unchanged", async () => {
const fetchApi = vi.fn(async () =>
response(
completed(
{
"43": { images: [saved], animated: [true] },
"44": {
images: [{ ...saved, filename: "second.mp4" }],
animated: [true],
},
},
"execution_error",
),
),
);
const result = await createComfyPromptHistoryClient({
fetchApi,
}).readSavedVideos(promptId);
expect(result.disposition).toBe("failed");
expect(result.artifacts.map((artifact) => artifact.outputNodeId)).toEqual([
"43",
"44",
]);
});
it.each([
[
"a foreign prompt row",
{ "prompt.other.1": completed({})[promptId] },
"history_foreign",
],
[
"a malformed outputs member",
{ [promptId]: { ...completed({})[promptId], outputs: [] } },
"history_malformed",
],
])("refuses %s", async (_name, value, code) => {
const fetchApi = vi.fn(async () => response(value));
await expect(
createComfyPromptHistoryClient({ fetchApi }).readSavedVideos(promptId),
).rejects.toMatchObject({ code });
});
});
@@ -485,6 +485,21 @@ test("M23-32 real host success waits for a later verified artifact", async ({
).toBeVisible();
const submit = container.locator('[data-h3-focus-key="app-submit"]');
await expect(submit).toBeEnabled({ timeout: 30_000 });
// a recorded success without an artifact now reads `/history` and fails typed when the
// completed record holds no SaveVideo output, which this model-free graph never has. Hold the
// browser's history read until the test-controlled late event below is delivered, so this row
// keeps proving the late delivery/verification join instead of racing that exit. The row's own
// `page.request` history read is not routed.
let releaseHistoryReads!: () => void;
const lateEventDelivered = new Promise<void>((resolve) => {
releaseHistoryReads = resolve;
});
const heldHistoryReads: string[] = [];
await page.route(/\/history\/[^/?]+$/, async (route) => {
heldHistoryReads.push(new URL(route.request().url()).pathname);
await lateEventDelivered;
await route.continue();
});
const fromSubmission = (await sampleProgress(page)).submitted;
await submit.click();
await expect
@@ -644,9 +659,10 @@ test("M23-32 real host success waits for a later verified artifact", async ({
),
);
// The host already emitted the successful terminal above. This stock-shape event is
// deliberately test-controlled and names a pre-seeded fixture; it exercises only the
// late delivery/verification join and is never evidence of model generation.
// The host already emitted the successful terminal above. This event is deliberately
// test-controlled and names a pre-seeded fixture; it exercises only the late
// delivery/verification join and is never evidence of model generation. Its entry carries the
// `metadata` and `id` annotations ComfyUI adds after v0.39.0, not the bare locator.
await page.evaluate(
({ acceptedPromptId, outputNodeId, locator }) => {
const api = (
@@ -657,7 +673,23 @@ test("M23-32 real host success waits for a later verified artifact", async ({
detail: {
prompt_id: acceptedPromptId,
node: outputNodeId,
output: { images: [locator], animated: [true] },
output: {
images: [
{
...locator,
metadata: {
kind: "video",
width: 512,
height: 512,
duration: 8,
fps: 24,
frame_count: 192,
},
id: "asset-m23-32-fixture",
},
],
animated: [true],
},
},
}),
);
@@ -668,7 +700,10 @@ test("M23-32 real host success waits for a later verified artifact", async ({
locator: m23TerminalWaitingArtifactLocator!,
},
);
releaseHistoryReads();
await expect.poll(() => closeResponses.length, { timeout: 60_000 }).toBe(2);
// At most the one recovery read was held; the late event closed the run before it returned.
expect(heldHistoryReads.length).toBeLessThanOrEqual(1);
expect(closeRequests).toHaveLength(2);
expect(closeRequests[1]).toEqual({
artifact: "locator",
@@ -893,6 +893,19 @@ test(productionImportHostTitle, async ({ context, page }, testInfo) => {
});
await expect(submit).toBeEnabled();
expect((await sampleProgress(page)).submitted).toBe(fromSubmission);
// hold the browser's `/history` recovery read until the test-controlled late event
// below is delivered; this model-free record has no SaveVideo output, so an unheld read would
// end the run typed before the join this row proves. The row's `page.request` read is not routed.
let releaseHistoryReads!: () => void;
const lateEventDelivered = new Promise<void>((resolve) => {
releaseHistoryReads = resolve;
});
const heldHistoryReads: string[] = [];
await page.route(/\/history\/[^/?]+$/, async (route) => {
heldHistoryReads.push(new URL(route.request().url()).pathname);
await lateEventDelivered;
await route.continue();
});
await submit.click();
try {
await expect
@@ -1120,7 +1133,9 @@ test(productionImportHostTitle, async ({ context, page }, testInfo) => {
locator: m2548ArtifactLocator!,
},
);
releaseHistoryReads();
await expect.poll(() => closeResponses.length, { timeout: 60_000 }).toBe(2);
expect(heldHistoryReads.length).toBeLessThanOrEqual(1);
expect(closeRequests).toHaveLength(2);
expect(closeRequests[1]).toEqual({
artifact: "locator",
@@ -815,6 +815,12 @@ test("authorized Ref2VA sidebar sample executes all media kinds and writes a rea
expect(bytes.length).toBeGreaterThan(1024);
expect(bytes.subarray(4, 8).toString("ascii")).toBe("ftyp");
}
// host success and a readable file are host facts, not product completion. The 1.3.0
// sample passed these checks while the sidebar still waited in output verification; the row now
// also requires the shell to leave verification for `projected`.
await expect(
container.locator('[data-shell-status="projected"]'),
).toHaveCount(1, { timeout: 180_000 });
await testInfo.attach("reference_sample", {
body: Buffer.from(
JSON.stringify({
@@ -0,0 +1,217 @@
import { expect, test } from "../../host/fixture";
import { hostUrl, supportedHostQueueCounts } from "../../host/environment";
import { decodeComfyPromptHistorySavedVideos } from "../../../../src/host/comfyPromptHistory";
import { saveVideoArtifactFromExecuted } from "../../../../src/host/saveVideoArtifact";
/**
* host payload contract.
*
* The product decodes SaveVideo's `executed` payload and its `/history` record, both emitted by
* the host. Every earlier test fed the decoder a payload the repository wrote itself, so when
* ComfyUI started annotating saved entries (`metadata`, asset `id`) the decoder refused them and
* App Mode waited in output verification forever. This row runs no model: it queues
* EmptyImage -> CreateVideo -> SaveVideo on the supplied host and decodes the host's real payloads.
* It writes one tiny MP4 under the host output folder, so it needs explicit per-session
* authorization. Its receipt records entry key names only, never values.
*/
const authorized =
process.env.H3_CONTEXT_SAVED_VIDEO_CONTRACT === "model_free_save_video_v1";
const OUTPUT_SUBFOLDER = "h3-context-contract";
const FILENAME_PREFIX = `${OUTPUT_SUBFOLDER}/saved-video-payload`;
test("M23-92 the host's real SaveVideo payload decodes from executed and history", async ({
page,
}, testInfo) => {
test.skip(
!authorized,
"M23-92 writes one model-free SaveVideo output and needs explicit per-session authorization",
);
test.setTimeout(5 * 60_000);
if (hostUrl === undefined) throw new Error("H3_CONTEXT_HOST_URL is required");
await page.goto(hostUrl, { waitUntil: "domcontentloaded" });
await page.waitForFunction(
() =>
typeof (
window as unknown as {
comfyAPI?: { api?: { api?: { clientId?: unknown } } };
}
).comfyAPI?.api?.api?.clientId === "string",
undefined,
{ timeout: 120_000 },
);
expect(await supportedHostQueueCounts(page)).toEqual({
running: 0,
pending: 0,
});
await page.evaluate(() => {
const runtime = window as unknown as {
comfyAPI: { api: { api: EventTarget } };
__h3SavedVideoContract?: {
executed: unknown[];
terminals: Array<{ name: string; promptId: unknown }>;
};
};
const record = {
executed: [] as unknown[],
terminals: [] as Array<{ name: string; promptId: unknown }>,
};
runtime.__h3SavedVideoContract = record;
const api = runtime.comfyAPI.api.api;
api.addEventListener("executed", (event: Event) =>
record.executed.push(structuredClone((event as CustomEvent).detail)),
);
for (const name of [
"execution_success",
"execution_error",
"execution_interrupted",
])
api.addEventListener(name, (event: Event) =>
record.terminals.push({
name,
promptId: (event as CustomEvent<{ prompt_id?: unknown }>).detail
?.prompt_id,
}),
);
});
const prompt = {
"1": {
class_type: "EmptyImage",
inputs: { width: 64, height: 64, batch_size: 8, color: 0 },
},
"2": { class_type: "CreateVideo", inputs: { images: ["1", 0], fps: 8 } },
"3": {
class_type: "SaveVideo",
inputs: {
video: ["2", 0],
filename_prefix: FILENAME_PREFIX,
format: "mp4",
"format.codec": "h264",
},
},
};
const queued = await page.evaluate(
async ({ endpoint, promptValue }) => {
const clientId = (
window as unknown as {
comfyAPI: { api: { api: { clientId: string } } };
}
).comfyAPI.api.api.clientId;
const result = await fetch(endpoint, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ client_id: clientId, prompt: promptValue }),
});
return { status: result.status, text: await result.text() };
},
{ endpoint: new URL("/prompt", hostUrl).href, promptValue: prompt },
);
expect(queued.status, queued.text).toBe(200);
const promptId = (JSON.parse(queued.text) as { prompt_id?: unknown })
.prompt_id;
if (typeof promptId !== "string")
throw new Error("the host returned no prompt id");
await page.waitForFunction(
(id) =>
(
window as unknown as {
__h3SavedVideoContract: { terminals: Array<{ promptId: unknown }> };
}
).__h3SavedVideoContract.terminals.some(
(terminal) => terminal.promptId === id,
),
promptId,
{ timeout: 120_000 },
);
const observed = await page.evaluate((id) => {
const record = (
window as unknown as {
__h3SavedVideoContract: {
executed: Array<{ prompt_id?: unknown; node?: unknown }>;
terminals: Array<{ name: string; promptId: unknown }>;
};
}
).__h3SavedVideoContract;
return {
terminals: record.terminals
.filter((terminal) => terminal.promptId === id)
.map((terminal) => terminal.name),
executed: record.executed.filter(
(detail) => detail?.prompt_id === id && detail?.node === "3",
),
};
}, promptId);
expect(observed.terminals).toEqual(["execution_success"]);
expect(observed.executed).toHaveLength(1);
const detail = observed.executed[0] as {
output?: { images?: Array<Record<string, unknown>> };
};
const executedEntryKeys = Object.keys(
detail.output?.images?.[0] ?? {},
).sort();
const expected = {
promptId,
outputNodeId: "3",
locator: {
filename: expect.stringMatching(/^saved-video-payload_\d+_\.mp4$/),
subfolder: OUTPUT_SUBFOLDER,
type: "output",
},
};
const live = saveVideoArtifactFromExecuted(detail);
expect(live, `executed entry keys: ${executedEntryKeys.join(",")}`).toEqual(
expected,
);
// ComfyUI stores history just after it sends `execution_success`.
let historyValue: unknown;
await expect
.poll(
async () => {
const response = await page.request.get(
new URL(`/history/${encodeURIComponent(promptId)}`, hostUrl).href,
);
if (!response.ok()) return false;
historyValue = await response.json();
return (
decodeComfyPromptHistorySavedVideos(historyValue, promptId)
.disposition !== "not_yet_observed"
);
},
{ timeout: 60_000 },
)
.toBe(true);
const history = decodeComfyPromptHistorySavedVideos(historyValue, promptId);
const historyRow = (
historyValue as Record<
string,
{ outputs?: Record<string, { images?: Array<Record<string, unknown>> }> }
>
)[promptId];
const historyEntryKeys = Object.keys(
historyRow?.outputs?.["3"]?.images?.[0] ?? {},
).sort();
expect(history.disposition).toBe("succeeded");
expect(
history.artifacts,
`history entry keys: ${historyEntryKeys.join(",")}`,
).toEqual([live]);
const locatorKeys = ["filename", "subfolder", "type"];
await testInfo.attach("saved_video_payload_contract", {
body: Buffer.from(
JSON.stringify({
schema: "h3.context.saved_video_payload_contract.v1",
executed_entry_keys: executedEntryKeys,
history_entry_keys: historyEntryKeys,
host_annotations_present: executedEntryKeys.some(
(key) => !locatorKeys.includes(key),
),
executed_decoded: true,
history_decoded: true,
}),
),
contentType: "application/json",
});
});
@@ -3100,6 +3100,360 @@ describe("entry managed App Mode Production lifecycle", () => {
);
});
describe("M23-92 a recorded success without an artifact always has an exit", () => {
const savedLocator = {
filename: "managed_00001_.mp4",
subfolder: "video/h3-context",
type: "output",
} as const;
const mediaMetadata = {
kind: "video",
width: 1280,
height: 720,
duration: 8,
fps: 24,
frame_count: 192,
};
const inputPreview = {
images: [
{
filename: "reference.mp4",
subfolder: "",
type: "input",
metadata: mediaMetadata,
},
],
animated: [true],
};
const currentHostSaveVideo = {
images: [
{ ...savedLocator, metadata: mediaMetadata, id: "asset-managed-00001" },
],
animated: [true],
};
function completedHistory(
promptId: string,
outputs: Record<string, unknown>,
): unknown {
return {
[promptId]: {
prompt: [],
outputs,
status: {
status_str: "success",
completed: true,
messages: [
["execution_start", { prompt_id: promptId }],
["execution_success", { prompt_id: promptId }],
],
},
},
};
}
function historyResponse(value: unknown) {
const bytes = new TextEncoder().encode(JSON.stringify(value));
return {
ok: true,
status: 200,
headers: {
get: (name: string) =>
name === "content-length" ? String(bytes.length) : null,
},
body: new ReadableStream<Uint8Array>({
start(controller) {
controller.enqueue(bytes);
controller.close();
},
}),
json: async () => value,
};
}
async function startRunAwaitingArtifact(
history: (call: number) => unknown,
completion: "terminal" | "reconnect" = "terminal",
) {
const coordinatorActions: string[] = [];
const closeArtifacts: unknown[] = [];
const historyPaths: string[] = [];
let planned!: EntryGenerationSequenceWire;
let submitted!: EntryGenerationSequenceWire;
let running!: EntryGenerationSequenceWire;
let succeeded!: EntryGenerationSequenceWire;
let initialProduction!: Record<string, unknown>;
const { fixture, container } = await loadEntry(async (path, init) => {
if (path.startsWith("/history/")) {
historyPaths.push(path);
return historyResponse(history(historyPaths.length));
}
const body = JSON.parse(String(init.body)) as {
action?: string;
payload?: { artifact?: unknown };
};
if (path === "/h3-context/v1/production/action")
return {
ok: true,
status: 201,
json: async () => initialProduction,
};
if (path !== "/h3-context/v1/generation/coordinator")
return { ok: false, status: 503, json: async () => ({}) };
const action = String(body.action);
coordinatorActions.push(action);
if (action === "close_managed_run") {
closeArtifacts.push(body.payload?.artifact ?? null);
return {
ok: true,
status: 200,
json: async () =>
body.payload?.artifact === null
? managedCoordinatorResponse(
"verification_pending",
running,
managedProductionStateWire(running, "running", planned),
)
: managedCoordinatorResponse(
"succeeded",
succeeded,
managedProductionStateWire(succeeded, "succeeded", planned),
),
};
}
const responseByAction = {
prepare_managed_run: managedCoordinatorResponse(
"prepared",
planned,
managedProductionStateWire(planned, "planned", planned),
),
submit_managed_run: managedCoordinatorResponse(
"submitted",
submitted,
managedProductionStateWire(submitted, "submitted", planned),
),
read_managed_run: managedCoordinatorResponse(
"verification_pending",
running,
managedProductionStateWire(running, "running", planned),
),
} as const;
const payload =
responseByAction[action as keyof typeof responseByAction];
return payload === undefined
? { ok: false, status: 422, json: async () => ({}) }
: { ok: true, status: 200, json: async () => payload };
});
const { managedJournal } = await import("../src/state/managedJournal");
managedJournal.reset();
const graphFingerprint = appModeFingerprint(
fixture.app.graph.serialize(),
);
const managedFixture = managedEntryFixture(
graphFingerprint,
fixture.workflowState().activeWorkflow,
fixture.app.graph.serialize(),
);
planned = managedFixture.planned;
submitted = managedSequenceStateWire(planned, "submitted");
running = managedSequenceStateWire(planned, "running");
succeeded = managedSequenceStateWire(planned, "succeeded");
initialProduction = managedFixture.production;
fixture.setQueuePromptIds(["prompt.model.1"]);
appModeStartHarness.start = async (_inputs, options = {}) => {
const authority = await options.prepareManaged!(
managedFixture.preparation,
);
authority.bindCanvasIdentity?.(
managedFixture.preparation.managedIdentity,
);
authority.onQueueSubmitted();
const queued = await fixture.api.queuePrompt(-1, {
output: {
"17": {
class_type: "comfyui_h3_context.H3Context.ProductShell",
inputs: {},
},
"6": { class_type: "MiniMaxH3ImageToVideo", inputs: {} },
"43": { class_type: "SaveVideo", inputs: {} },
},
workflow: structuredClone(
managedFixture.preparation.bootstrap.workflow,
),
});
const queueResult = acceptedQueueReceipt(
queued.prompt_id,
queued.number,
);
const result: AppModeStartResult = {
queueResult,
...OWNED_RESULT_IDENTITY,
graphFingerprint,
compiledPromptFingerprint:
planned.eligible_commands[0]!.compiled_prompt_fingerprint,
queuePromptId: queueResult.prompt_id,
route: "existing",
};
await authority.onQueueAccepted(result);
return result;
};
fireEvent.change(
screen.getByRole("spinbutton", { name: "Clip duration (seconds)" }),
{ target: { value: "8" } },
);
await screen.findByText("Delivers 8 s (192 frames).");
await clickReadyAppModeStart();
act(() =>
fixture.dispatchProjection("17", {
promptId: "prompt.model.1",
workspaceId: managedFixture.workspaceId,
requestedSeconds: 8,
taskMode: "t2va",
}),
);
await waitFor(() =>
expect(
container.querySelector('[data-app-mode-phase="generating"]'),
).not.toBeNull(),
);
if (completion === "terminal") {
// No SaveVideo event reaches the shell: that is what an undecodable host entry looked like.
act(() =>
fixture.dispatchExecutionTerminal("success", "prompt.model.1"),
);
} else {
act(() => fixture.dispatchHostSocketDropped());
act(() => fixture.dispatchHostReconnected());
}
await waitFor(() =>
expect(
container.querySelector('[data-app-mode-phase="verifying_output"]'),
).not.toBeNull(),
);
const stages = () =>
managedJournal
.snapshot()
.flatMap((entry) => (entry.kind === "stage" ? [entry.name] : []));
return {
fixture,
container,
coordinatorActions,
closeArtifacts,
historyPaths,
stages,
};
}
const recoveredArtifact = {
output_node_id: "43",
locator: savedLocator,
};
it("recovers the saved video from history when no SaveVideo event was decoded", async () => {
const run = await startRunAwaitingArtifact(() =>
completedHistory("prompt.model.1", {
"12": inputPreview,
"43": currentHostSaveVideo,
}),
);
await waitFor(() =>
expect(
run.container.querySelector('[data-shell-status="projected"]'),
).not.toBeNull(),
);
// Only the three locator fields reach the coordinator; host annotations stay behind.
expect(run.closeArtifacts).toEqual([null, recoveredArtifact]);
expect(run.historyPaths).toEqual([
`/history/${encodeURIComponent("prompt.model.1")}`,
]);
expect(run.stages()).toContain("artifact_history_recovered");
expect(run.fixture.sideEffectCounts().queues).toBe(1);
});
it("fails typed instead of waiting when history records no saved video", async () => {
const run = await startRunAwaitingArtifact(() =>
completedHistory("prompt.model.1", { "12": inputPreview }),
);
await waitFor(() =>
expect(
run.container.querySelector('[data-shell-status="error"]'),
).not.toBeNull(),
);
expect(screen.getByRole("alert").textContent).toContain(
"The saved H3 output could not be verified safely.",
);
expect(
run.container.querySelector('[data-app-mode-phase="verifying_output"]'),
).toBeNull();
expect(run.closeArtifacts).toEqual([null]);
expect(run.stages()).toContain("artifact_history_unresolved");
expect(run.fixture.sideEffectCounts().queues).toBe(1);
});
it("retries history until the host stores the finished prompt", async () => {
const run = await startRunAwaitingArtifact((call) =>
call === 1
? {}
: completedHistory("prompt.model.1", { "43": currentHostSaveVideo }),
);
await waitFor(
() =>
expect(
run.container.querySelector('[data-shell-status="projected"]'),
).not.toBeNull(),
{ timeout: 3_000 },
);
expect(run.historyPaths).toHaveLength(2);
expect(run.closeArtifacts).toEqual([null, recoveredArtifact]);
});
it("lets a late SaveVideo event win without reading history", async () => {
const run = await startRunAwaitingArtifact(() =>
completedHistory("prompt.model.1", {}),
);
act(() => run.fixture.dispatchSaveVideoArtifact("prompt.model.1", "43"));
await waitFor(() =>
expect(
run.container.querySelector('[data-shell-status="projected"]'),
).not.toBeNull(),
);
await new Promise((resolve) => setTimeout(resolve, 400));
expect(
run.container.querySelector('[data-shell-status="projected"]'),
).not.toBeNull();
expect(run.historyPaths).toEqual([]);
expect(run.closeArtifacts).toEqual([null, recoveredArtifact]);
expect(run.stages()).not.toContain("artifact_history_unresolved");
});
it("refuses a history row for another prompt", async () => {
const run = await startRunAwaitingArtifact(() =>
completedHistory("prompt.other.1", { "43": currentHostSaveVideo }),
);
await waitFor(() =>
expect(
run.container.querySelector('[data-shell-status="error"]'),
).not.toBeNull(),
);
expect(run.closeArtifacts).toEqual([null]);
expect(run.stages()).toContain("artifact_history_unresolved");
});
it("recovers after a reconnect reads a recorded success without an artifact", async () => {
const run = await startRunAwaitingArtifact(
() =>
completedHistory("prompt.model.1", { "43": currentHostSaveVideo }),
"reconnect",
);
await waitFor(() =>
expect(
run.container.querySelector('[data-shell-status="projected"]'),
).not.toBeNull(),
);
expect(run.coordinatorActions).toContain("read_managed_run");
expect(run.closeArtifacts).toEqual([recoveredArtifact]);
expect(run.stages()).toContain("artifact_history_recovered");
});
});
it.each([
["error", "failed"],
["interrupted", "interrupted"],
+25 -5
View File
@@ -652,10 +652,21 @@ export function dispatchHostReconnected(): void {
apiEvents.dispatchEvent(new CustomEvent("reconnected", { detail: null }));
}
/**
* Dispatch SaveVideo's `executed` event. The default is the entry shape ComfyUI sends after
* v0.39.0: media `metadata` and an asset `id` beside the locator. `"stock"` is the
* three-key entry older hosts send.
*/
export function dispatchSaveVideoArtifact(
promptId: string,
outputNodeId = "43",
entryShape: "current_host" | "stock" = "current_host",
): void {
const locator = {
filename: "managed_00001_.mp4",
subfolder: "video/h3-context",
type: "output",
};
apiEvents.dispatchEvent(
new CustomEvent("executed", {
detail: {
@@ -663,11 +674,20 @@ export function dispatchSaveVideoArtifact(
prompt_id: promptId,
output: {
images: [
{
filename: "managed_00001_.mp4",
subfolder: "video/h3-context",
type: "output",
},
entryShape === "stock"
? locator
: {
...locator,
metadata: {
kind: "video",
width: 1280,
height: 720,
duration: 8,
fps: 24,
frame_count: 192,
},
id: "asset-managed-00001",
},
],
animated: [true],
},
+9 -5
View File
@@ -13,6 +13,7 @@ import {
} from "../src/host/inputGeometry";
import { saveVideoArtifactFromExecuted } from "../src/host/sidebarHost";
import { createAppModeCorrelation } from "../src/lifecycle/appModeCorrelation";
import { createManagedArtifactAwait } from "../src/lifecycle/managedArtifactAwait";
import { createProductionDestinationStore } from "../src/host/productionDestination";
import {
createShellSession,
@@ -528,6 +529,11 @@ function managedCorrelationHarness(
};
const deps = {
sequenceCoordinator: { send },
// The wait for a recorded success schedules a history read; it stays in flight here so these
// rows observe the event-driven close alone.
comfyPromptHistoryClient: {
readSavedVideos: vi.fn(() => new Promise<never>(() => undefined)),
},
productionActions: { send: productionSend },
productionDestinations,
appModeController: { activeWorkflow: () => workflow },
@@ -543,11 +549,9 @@ function managedCorrelationHarness(
resetAll: vi.fn(),
},
};
const correlation = createAppModeCorrelation({
session,
actions,
deps,
} as unknown as ShellRuntime);
const runtime = { session, actions, deps } as unknown as ShellRuntime;
const correlation = createAppModeCorrelation(runtime);
Object.assign(actions, correlation, createManagedArtifactAwait(runtime));
return {
session,
managed,
+138
View File
@@ -0,0 +1,138 @@
import { describe, expect, it } from "vitest";
import {
saveVideoArtifactFromExecuted,
saveVideoArtifactFromOutput,
} from "../src/host/saveVideoArtifact";
import { saveVideoArtifactFromExecuted as reexported } from "../src/host/sidebarHost";
const locator = {
filename: "managed_00001_.mp4",
subfolder: "video/h3-context",
type: "output",
} as const;
// The entry ComfyUI sends after v0.39.0: media metadata always, the asset id when assets are on.
const mediaMetadata = {
kind: "video",
width: 1280,
height: 720,
duration: 8,
fps: 24,
frame_count: 192,
};
const expected = {
promptId: "prompt.model.1",
outputNodeId: "43",
locator,
};
function executed(entry: unknown, output: Record<string, unknown> = {}) {
return {
prompt_id: "prompt.model.1",
node: "43",
display_node: "43",
output: { images: [entry], animated: [true], ...output },
};
}
describe("SaveVideo artifact decoding across host entry shapes", () => {
it.each([
["stock three-key entry", locator],
["entry with host media metadata", { ...locator, metadata: mediaMetadata }],
[
"entry with host media metadata and asset id",
{ ...locator, metadata: mediaMetadata, id: "asset-managed-00001" },
],
[
"entry with a later unknown host annotation",
{ ...locator, metadata: mediaMetadata, preview_hint: { any: 1 } },
],
])("admits the %s and forwards only the locator", (_name, entry) => {
const artifact = saveVideoArtifactFromExecuted(executed(entry));
expect(artifact).toEqual(expected);
expect(Object.keys(artifact!.locator).sort()).toEqual([
"filename",
"subfolder",
"type",
]);
expect(Object.isFrozen(artifact)).toBe(true);
expect(Object.isFrozen(artifact!.locator)).toBe(true);
expect(JSON.stringify(artifact)).not.toContain("asset-managed");
expect(JSON.stringify(artifact)).not.toContain("frame_count");
});
it("keeps the sidebar host export as the same decoder", () => {
expect(reexported).toBe(saveVideoArtifactFromExecuted);
});
it.each([
["two saved entries", { images: [locator, locator], animated: [true] }],
["no animated flag", { images: [locator] }],
["animated false", { images: [locator], animated: [false] }],
[
"an extra output member",
{ images: [locator], animated: [true], gifs: [locator] },
],
[
"an input preview",
{
images: [{ ...locator, type: "input", metadata: mediaMetadata }],
animated: [true],
},
],
[
"a temporary preview",
{ images: [{ ...locator, type: "temp" }], animated: [true] },
],
[
"a missing subfolder",
{
images: [{ filename: locator.filename, type: "output" }],
animated: [true],
},
],
[
"an empty filename",
{ images: [{ ...locator, filename: "" }], animated: [true] },
],
[
"an oversized filename",
{ images: [{ ...locator, filename: "a".repeat(256) }], animated: [true] },
],
[
"a non-string subfolder",
{ images: [{ ...locator, subfolder: 3 }], animated: [true] },
],
[
"an oversized subfolder",
{
images: [{ ...locator, subfolder: "s".repeat(513) }],
animated: [true],
},
],
["an entry that is not an object", { images: ["x.mp4"], animated: [true] }],
])("still refuses %s", (_name, output) => {
expect(
saveVideoArtifactFromOutput("prompt.model.1", "43", output),
).toBeUndefined();
});
it.each([
["an empty prompt id", "", "43"],
["a prompt id with a path separator", "prompt/1", "43"],
["an oversized node id", "prompt.model.1", "n".repeat(257)],
["a non-string node id", "prompt.model.1", 43],
])("refuses %s", (_name, promptId, nodeId) => {
expect(
saveVideoArtifactFromOutput(promptId, nodeId, {
images: [locator],
animated: [true],
}),
).toBeUndefined();
});
it("refuses an executed detail that is not an object", () => {
expect(saveVideoArtifactFromExecuted(null)).toBeUndefined();
expect(saveVideoArtifactFromExecuted([executed(locator)])).toBeUndefined();
});
});
@@ -49,7 +49,7 @@
"path": "frontend/src/entry.tsx"
}
],
"fingerprint": "sha256:5271181d59c8a49ad54da828f0062ea746a8057c53e7e5cf8a40efc794cb790b",
"fingerprint": "sha256:998efc8156169fc430843a846b6d57a76b1eacd308e2645bb5a63b0c26db8216",
"known_violations": [],
"modules": [
{
@@ -3218,7 +3218,7 @@
"comfyui_h3_context/product_shell_node.py"
],
"language": "python",
"lines": 685,
"lines": 688,
"path": "comfyui_h3_context/context_request_nodes.py",
"source_reachability": {
"class": "product",
@@ -4518,7 +4518,7 @@
"comfyui_h3_context/core/context_reporting.py"
],
"language": "python",
"lines": 407,
"lines": 413,
"path": "comfyui_h3_context/core/errors.py",
"source_reachability": {
"class": "product",
@@ -5476,11 +5476,12 @@
"comfyui_h3_context/core/contracts.py",
"comfyui_h3_context/core/errors.py",
"comfyui_h3_context/core/length.py",
"comfyui_h3_context/core/reference_limits.py",
"comfyui_h3_context/core/registry.py",
"comfyui_h3_context/core/validation_lifecycle.py"
],
"language": "python",
"lines": 684,
"lines": 685,
"path": "comfyui_h3_context/core/native_h3.py",
"source_reachability": {
"class": "product",
@@ -5705,10 +5706,11 @@
"comfyui_h3_context/core/errors.py",
"comfyui_h3_context/core/evidence.py",
"comfyui_h3_context/core/length.py",
"comfyui_h3_context/core/reference_limits.py",
"comfyui_h3_context/core/registry.py"
],
"language": "python",
"lines": 628,
"lines": 629,
"path": "comfyui_h3_context/core/normalization.py",
"source_reachability": {
"class": "product",
@@ -7012,6 +7014,27 @@
"retained_reason": "reachable from a shipped entry point"
}
},
{
"imports": [],
"language": "python",
"lines": 5,
"path": "comfyui_h3_context/core/reference_limits.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_fonts.py",
"comfyui_h3_context/adapters/authoring_generated_source.py",
"comfyui_h3_context/adapters/authoring_image_source.py",
"comfyui_h3_context/adapters/authoring_media_leases.py"
],
"retained_reason": "reachable from a shipped entry point"
}
},
{
"imports": [
"comfyui_h3_context/core/canonical.py",
@@ -7044,10 +7067,11 @@
"comfyui_h3_context/core/canonical.py",
"comfyui_h3_context/core/contracts.py",
"comfyui_h3_context/core/errors.py",
"comfyui_h3_context/core/reference_limits.py",
"comfyui_h3_context/core/registry.py"
],
"language": "python",
"lines": 1239,
"lines": 1249,
"path": "comfyui_h3_context/core/reference_set_authoring.py",
"source_reachability": {
"class": "product",
@@ -7092,10 +7116,11 @@
{
"imports": [
"comfyui_h3_context/core/contracts.py",
"comfyui_h3_context/core/errors.py"
"comfyui_h3_context/core/errors.py",
"comfyui_h3_context/core/reference_limits.py"
],
"language": "python",
"lines": 383,
"lines": 391,
"path": "comfyui_h3_context/core/registry.py",
"source_reachability": {
"class": "product",
@@ -11537,6 +11562,7 @@
"frontend/src/lifecycle/extensionRegistration.tsx",
"frontend/src/lifecycle/extensionSetup.ts",
"frontend/src/lifecycle/interpreter.ts",
"frontend/src/lifecycle/managedArtifactAwait.ts",
"frontend/src/lifecycle/mediaRuntimeSession.ts",
"frontend/src/lifecycle/mountController.tsx",
"frontend/src/lifecycle/nleWorkspaceSession.ts",
@@ -11552,7 +11578,7 @@
"frontend/src/state/managedJournal.ts"
],
"language": "typescript",
"lines": 370,
"lines": 372,
"path": "frontend/src/entry.tsx",
"source_reachability": {
"class": "product",
@@ -12086,10 +12112,11 @@
},
{
"imports": [
"frontend/src/contracts/canonicalFingerprint.ts"
"frontend/src/contracts/canonicalFingerprint.ts",
"frontend/src/host/saveVideoArtifact.ts"
],
"language": "typescript",
"lines": 300,
"lines": 379,
"path": "frontend/src/host/comfyPromptHistory.ts",
"source_reachability": {
"class": "product",
@@ -12921,6 +12948,20 @@
"retained_reason": "reachable from a shipped entry point"
}
},
{
"imports": [],
"language": "typescript",
"lines": 99,
"path": "frontend/src/host/saveVideoArtifact.ts",
"source_reachability": {
"class": "product",
"evidence": "product_closure",
"owners": [
"frontend/src/entry.tsx"
],
"retained_reason": "reachable from a shipped entry point"
}
},
{
"imports": [
"frontend/src/contracts/generationSequenceCodec.ts",
@@ -12972,10 +13013,11 @@
"frontend/src/host/graphAdapter.ts",
"frontend/src/host/hostAvailability.ts",
"frontend/src/host/hostSeams.ts",
"frontend/src/host/saveVideoArtifact.ts",
"frontend/src/performance/performanceBudget.ts"
],
"language": "typescript",
"lines": 851,
"lines": 802,
"path": "frontend/src/host/sidebarHost.ts",
"source_reachability": {
"class": "product",
@@ -13277,6 +13319,24 @@
"retained_reason": "reachable from a shipped entry point"
}
},
{
"imports": [
"frontend/src/host/comfyPromptHistory.ts",
"frontend/src/host/sidebarHost.ts",
"frontend/src/lifecycle/shellSession.ts"
],
"language": "typescript",
"lines": 107,
"path": "frontend/src/lifecycle/managedArtifactAwait.ts",
"source_reachability": {
"class": "product",
"evidence": "product_closure",
"owners": [
"frontend/src/entry.tsx"
],
"retained_reason": "reachable from a shipped entry point"
}
},
{
"imports": [
"frontend/src/contracts/generationSequenceCodec.ts",
@@ -13643,6 +13703,7 @@
"frontend/src/lifecycle/extensionRegistration.tsx",
"frontend/src/lifecycle/extensionSetup.ts",
"frontend/src/lifecycle/interpreter.ts",
"frontend/src/lifecycle/managedArtifactAwait.ts",
"frontend/src/lifecycle/managedProjectMember.ts",
"frontend/src/lifecycle/mediaRuntimeSession.ts",
"frontend/src/lifecycle/mountController.tsx",
@@ -13665,7 +13726,7 @@
"frontend/src/state/sidebarWorkspace.ts"
],
"language": "typescript",
"lines": 472,
"lines": 474,
"path": "frontend/src/lifecycle/shellSession.ts",
"source_reachability": {
"class": "product",
@@ -14274,7 +14335,7 @@
"frontend/src/state/shellState.ts"
],
"language": "typescript",
"lines": 1187,
"lines": 1189,
"path": "frontend/src/state/managedJournal.ts",
"source_reachability": {
"class": "product",
@@ -1922,10 +1922,10 @@
],
"edge_kind_totals": {
"function_local": 113,
"module_level": 1762,
"module_level": 1766,
"type_checking": 128
},
"fingerprint": "sha256:248da3ed5405239e2a8f91ed524f60b2faa712db98e6c2ab99c37ac537baf29d",
"fingerprint": "sha256:d7000bcd7e67d5bff9c9aec75ab8be4c1b16833b223bb5c8bb2ae6aef744989d",
"forbidden_imports": [],
"layer_inversions": [],
"modules": [
@@ -1948,6 +1948,7 @@
"tests/test_package_boundary.py",
"tests/test_package_compatibility_policy.py",
"tests/test_public_manifest.py",
"tests/test_ref2va_reference_contract.py",
"tests/test_segment_artifact_store.py",
"tests/test_sequence_continuation_canary.py"
],
@@ -4256,17 +4257,19 @@
"disposition": "movable",
"inbound": 1,
"layer": "node_ui",
"lines": 685,
"lines": 688,
"module": "context_request_nodes",
"outbound": 12,
"owning_rules": [
"direct_module"
"direct_module",
"submodule_as_name"
],
"owning_tests": [
"tests/test_m24_05_native_declaration.py",
"tests/test_m25_authoring_initialization.py",
"tests/test_m25_authoring_media_leases.py",
"tests/test_m26_03_context_materializer.py",
"tests/test_ref2va_reference_contract.py",
"tests/test_reference_node.py"
],
"reasons": []
@@ -5461,6 +5464,7 @@
"tests/test_qualified_perception.py",
"tests/test_reachability.py",
"tests/test_recompute_closure.py",
"tests/test_ref2va_reference_contract.py",
"tests/test_reference_node.py",
"tests/test_reference_role_resolution.py",
"tests/test_reference_set_authoring.py",
@@ -5643,7 +5647,7 @@
"disposition": "movable",
"inbound": 152,
"layer": "core",
"lines": 407,
"lines": 413,
"module": "core.errors",
"outbound": 1,
"owning_rules": [
@@ -6519,9 +6523,9 @@
"disposition": "movable",
"inbound": 20,
"layer": "core",
"lines": 684,
"lines": 685,
"module": "core.native_h3",
"outbound": 7,
"outbound": 8,
"owning_rules": [
"direct_module",
"hub_symbol",
@@ -6711,9 +6715,9 @@
"disposition": "movable",
"inbound": 19,
"layer": "core",
"lines": 628,
"lines": 629,
"module": "core.normalization",
"outbound": 6,
"outbound": 7,
"owning_rules": [
"direct_module",
"hub_symbol"
@@ -6745,6 +6749,7 @@
"tests/test_pipeline_nodes.py",
"tests/test_production_import.py",
"tests/test_qualified_perception.py",
"tests/test_ref2va_reference_contract.py",
"tests/test_registry.py",
"tests/test_rendering.py",
"tests/test_request_node.py",
@@ -7763,6 +7768,22 @@
],
"reasons": []
},
{
"disposition": "movable",
"inbound": 4,
"layer": "core",
"lines": 5,
"module": "core.reference_limits",
"outbound": 0,
"owning_rules": [
"direct_module"
],
"owning_tests": [
"tests/test_ref2va_reference_contract.py",
"tests/test_reference_set_authoring.py"
],
"reasons": []
},
{
"disposition": "movable",
"inbound": 4,
@@ -7785,15 +7806,17 @@
"disposition": "movable",
"inbound": 3,
"layer": "core",
"lines": 1239,
"lines": 1249,
"module": "core.reference_set_authoring",
"outbound": 4,
"outbound": 5,
"owning_rules": [
"direct_module"
"direct_module",
"submodule_as_name"
],
"owning_tests": [
"tests/test_m25_29_production_authoring_import.py",
"tests/test_project_document_service.py",
"tests/test_ref2va_reference_contract.py",
"tests/test_reference_set_authoring.py",
"tests/test_timeline_authoring.py"
],
@@ -7818,9 +7841,9 @@
"disposition": "movable",
"inbound": 34,
"layer": "core",
"lines": 383,
"lines": 391,
"module": "core.registry",
"outbound": 2,
"outbound": 3,
"owning_rules": [
"direct_module",
"hub_symbol"
File diff suppressed because one or more lines are too long
+30 -20
View File
@@ -27,7 +27,7 @@
},
{
"path": "comfyui_h3_context/contracts/build_provenance_v1.json",
"sha256": "sha256:5e47ead98276adf4004f5a91a0940b6429c0cd58fbb84c9127098e55ef99c272",
"sha256": "sha256:c347f6dbcc354291a0d28c02a2dc352b40022e63f3856507729898aa7cd12963",
"size": 1712
},
{
@@ -42,7 +42,7 @@
},
{
"path": "comfyui_h3_context/contracts/installation_profiles_v1.json",
"sha256": "sha256:01c4f98e20f901afbab47750fc90dc564fb9e0e622ec7a172f59aca05588e0ef",
"sha256": "sha256:a2a89870ff1688c9527f2eb9d95a189d2208af4a4bdb0d7da8ba099812806c02",
"size": 3377
},
{
@@ -67,7 +67,7 @@
},
{
"path": "frontend/package.json",
"sha256": "sha256:bedc8afd3d5fc39057c118f5259424ff0a9b0a27850783cf46f9886cd35743f7",
"sha256": "sha256:f3ebc21e0ec3a93c1b1b112b78fd452b5cd5a13a8decfaf5c00fdee2f74b0961",
"size": 1307
},
{
@@ -697,8 +697,8 @@
},
{
"path": "frontend/src/entry.tsx",
"sha256": "sha256:b02563912837a278619df43a9bcdcfea212b2036f34dfe022c00455954ba9dce",
"size": 13773
"sha256": "sha256:002305e97c737b57e1183346a481d393d6a65c8ab1d3abd77df95496e9c12070",
"size": 13891
},
{
"path": "frontend/src/host-modules.d.ts",
@@ -837,8 +837,8 @@
},
{
"path": "frontend/src/host/comfyPromptHistory.ts",
"sha256": "sha256:07ad7ea33a26e866a01f8f312ff9f1fc6b07d626c628d3bd9d9c85f510439348",
"size": 9698
"sha256": "sha256:7c2464b9578e71c4b8a22976f6a56f9eb97ec50d98375907b50df7b8493c7d1c",
"size": 11950
},
{
"path": "frontend/src/host/durationResolutionClient.ts",
@@ -1085,6 +1085,11 @@
"sha256": "sha256:f6c9c5d61d6b90d334159bb93d531a5c9932439cdd61dac6bca8b1eb30b010be",
"size": 6594
},
{
"path": "frontend/src/host/saveVideoArtifact.ts",
"sha256": "sha256:f2a61c2fc904b264647eea041eaffde8f3168e4395243fb39aaedd2f5d13dbd5",
"size": 3320
},
{
"path": "frontend/src/host/sequenceCoordinator.ts",
"sha256": "sha256:1be0849b84f52f25aaa4be95969528de5aa34a75c9634e88dc7515a37f41306e",
@@ -1097,8 +1102,8 @@
},
{
"path": "frontend/src/host/sidebarHost.ts",
"sha256": "sha256:2f6a5a871ac438bd72b3c35cb99439fc8b33fa6c12b8917a38c046a74e6ec650",
"size": 29513
"sha256": "sha256:4872216df05932844eca85bef069aa23be5da146f63d1af66113adf289d613e3",
"size": 28063
},
{
"path": "frontend/src/host/sidebarWidth.ts",
@@ -1147,8 +1152,8 @@
},
{
"path": "frontend/src/lifecycle/appModeCorrelation.ts",
"sha256": "sha256:4b71286d7945eecfc47f45ff26e8c132b0e42e4a3b8a254d921a9c5180fffd04",
"size": 43539
"sha256": "sha256:c618443682a2bef52a57f9b5d10dc5f5be49ad65be83bf0e54e8a529a69d14c8",
"size": 43512
},
{
"path": "frontend/src/lifecycle/appModeMachine.ts",
@@ -1180,6 +1185,11 @@
"sha256": "sha256:d6070c97ad332f623d5d00ccabac148398e49c31e8b66fb338eb436a356f234c",
"size": 8356
},
{
"path": "frontend/src/lifecycle/managedArtifactAwait.ts",
"sha256": "sha256:f4e046d36ab2e965792c2353cd30313ce48fa50b74b5756ca546d23f604ede29",
"size": 4586
},
{
"path": "frontend/src/lifecycle/managedProjectMember.ts",
"sha256": "sha256:22496f9db441367986fe3e243212bc17a533839adf9d29ae02a5adf7ebef0e23",
@@ -1257,8 +1267,8 @@
},
{
"path": "frontend/src/lifecycle/shellSession.ts",
"sha256": "sha256:4b50ff4f0e79861ea24734cfa994f1c5f5194bf83ad3c681bc23a1f87fbe2d12",
"size": 21564
"sha256": "sha256:7492b2b93a6d2bfff858c0f57db564c0eda7cbd712557ba5af0973cd67f333d7",
"size": 21688
},
{
"path": "frontend/src/lifecycle/workspaceStateSession.ts",
@@ -1432,8 +1442,8 @@
},
{
"path": "frontend/src/state/managedJournal.ts",
"sha256": "sha256:6209af9e1a70c0cb05a36aa02d91f55f944a4f94ac1c6fddf884bad0a8ea8192",
"size": 36902
"sha256": "sha256:1ac11c67217191d5aed283ed6fb1a68634253efc233608ff10de1b59848b9975",
"size": 36967
},
{
"path": "frontend/src/state/mediaRuntimeState.ts",
@@ -1502,7 +1512,7 @@
},
{
"path": "governance/contracts/sbom.spdx.json",
"sha256": "sha256:72005d7e716ad965ce0f74efa9a19427871a26250e3a773534d5b8355f821a88",
"sha256": "sha256:a214babd481f21881e0c0dc0551cba011d9ad3f4eb224c4d3c529aec5e29b68a",
"size": 80683
},
{
@@ -1512,7 +1522,7 @@
},
{
"path": "pyproject.toml",
"sha256": "sha256:7bcb272c3d71143001546788e0c7bdf2f4a7e3e714408b12d3bf9ceddb17e828",
"sha256": "sha256:95daa457dd6bfa5ff9d022300d7b2285105189fc502c5001eec7301915c4d508",
"size": 4112
},
{
@@ -1535,15 +1545,15 @@
"runtime_entries": [
{
"path": "comfyui_h3_context/web/h3-context-sidebar.js",
"sha256": "sha256:de6c94641926a51b56fdb3092775e58df0013aae3f38497c0bdadd7dde4e2e13",
"size": 1924005
"sha256": "sha256:90615618067ab6143c0f8d422cf5182a913cd1d48e2932b5efc48a26a968c68b",
"size": 1926109
}
],
"schema": "h3-context-supply-chain/1",
"spdx": {
"package_count": 176,
"path": "governance/contracts/sbom.spdx.json",
"sha256": "sha256:72005d7e716ad965ce0f74efa9a19427871a26250e3a773534d5b8355f821a88",
"sha256": "sha256:a214babd481f21881e0c0dc0551cba011d9ad3f4eb224c4d3c529aec5e29b68a",
"version": "SPDX-2.3"
},
"version": 1
+1 -1
View File
@@ -5,7 +5,7 @@ backend-path = ["."]
[project]
name = "minimax-h3-studio"
version = "1.3.0"
version = "1.3.2"
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"
+2 -2
View File
@@ -250,7 +250,7 @@
{
"type": "Hex High Entropy String",
"filename": "comfyui_h3_context\\contracts\\build_provenance_v1.json",
"hashed_secret": "5552a6300bdf3b8639714b0314786352b1672c52",
"hashed_secret": "6454595af213beb54c3c87a69cadb8d3f6f30923",
"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": "0e28057c0b5e303f50215268321029e9854b8124",
"hashed_secret": "d36335c4bd1371b049aa640869c68e0c20fccc00",
"is_verified": false,
"line_number": 17,
"is_secret": false
+2 -2
View File
@@ -2,13 +2,13 @@
"schema": "h3-context-release-matrix/1",
"package": {
"name": "minimax-h3-studio",
"version": "1.3.0",
"version": "1.3.2",
"author": "rookiestar28",
"dependencies": []
},
"artifact": {
"required": ["wheel", "sdist"],
"prefix": "minimax_h3_studio-1.3.0",
"prefix": "minimax_h3_studio-1.3.2",
"forbidden_path_markers": [
"AGENTS.md",
"ROADMAP.md",
+6 -2
View File
@@ -111,7 +111,8 @@ def test_inventory_covers_both_stacks_and_the_shipped_entrypoint() -> None:
# Production assembly execution and borrowed media use add two narrow adapter owners.
# IMPORTANT: count every scanner-admitted source owner, including the continuation canary and
# adapter plus the two seam instruments; inactive product routes do not remove their modules.
assert len([row for row in document["modules"] if row["language"] == "python"]) == 347
# The shared native audio capacity adds one dependency-free policy owner.
assert len([row for row in document["modules"] if row["language"] == "python"]) == 348
# /48 add the toolbar/decisions and Media/Text; adds filmstrip ownership;
# replaces one legacy Inspector module with separate tabs and timeline-menu owners;
# adds the monitor transform overlay and its pure gesture mapper; adds the
@@ -137,7 +138,10 @@ def test_inventory_covers_both_stacks_and_the_shipped_entrypoint() -> None:
# Retained media adds its codec, client, disposable lifecycle and Settings/Retain controls.
# Editable draft recovery adds its codec, client, disposable lifecycle and controls.
# Perception readiness adds one codec, client, lifecycle, state and localized Settings control.
assert len([row for row in document["modules"] if row["language"] == "typescript"]) == 277
# The SaveVideo artifact decoder shared by the event and history reads is one pure module, and
# the managed output wait with its history exit is one lifecycle owner that keeps the App Mode
# correlation owner within its enforced module budget.
assert len([row for row in document["modules"] if row["language"] == "typescript"]) == 279
assert document["entrypoints"] == [
{
"kind": "shipped_frontend_runtime",
+1 -1
View File
@@ -262,7 +262,7 @@ class NormalizationTests(unittest.TestCase):
"too_many_videos",
)
over_audio = tuple(
AssetDescriptor(f"audio_{i}", MediaKind.AUDIO, AssetRole.AUDIO_SOURCE) for i in range(7)
AssetDescriptor(f"audio_{i}", MediaKind.AUDIO, AssetRole.AUDIO_SOURCE) for i in range(4)
)
self.assert_error(
normalize_request(
+172
View File
@@ -4,20 +4,192 @@ from __future__ import annotations
import json
import unittest
from decimal import Decimal
from pathlib import Path
from types import SimpleNamespace
from typing import Any, cast
from unittest import mock
from comfyui_h3_context import context_request_nodes
from comfyui_h3_context.core import ContextReport, NativeH3AdapterError, ReferenceRegistry
from comfyui_h3_context.core.contracts import AssetRole, MediaKind, TaskMode
from comfyui_h3_context.core.native_h3 import (
NATIVE_H3_BASE_MAX_AUDIO,
_h3_base_preflight,
_reference_bindings,
)
from comfyui_h3_context.core.normalization import (
MAX_REFERENCE_AUDIO,
RawContextRequest,
normalize_request,
)
from comfyui_h3_context.core.reference_set_authoring import (
AddSource,
AdmittedSourceInput,
ReferenceSetAuthoringError,
ReferenceSetState,
TimedReferenceLimits,
apply_command,
build_h3_base_capacity,
capacity_projection,
create_reference_set,
)
from comfyui_h3_context.core.registry import (
MAX_PAIRED_VIDEO_AUDIO,
MAX_STANDALONE_AUDIO,
MediaMetadata,
ReferenceAsset,
ReferenceRegistryError,
build_reference_registry,
)
from comfyui_h3_context.nodes import H3ReferenceRegistryNode, ReferenceRegistryNodeError
FIXTURES = Path(__file__).resolve().parent / "fixtures"
def _assets(paired: int, standalone: int) -> tuple[ReferenceAsset, ...]:
assets = [ReferenceAsset("image", MediaKind.IMAGE, AssetRole.REFERENCE, 1)]
for index in range(paired):
video_id = f"video-{index}"
assets.append(
ReferenceAsset(
f"paired-{index}",
MediaKind.AUDIO,
AssetRole.AUDIO_SOURCE,
len(assets) + 1,
MediaMetadata(duration_seconds=Decimal("2")),
paired_video_id=video_id,
)
)
assets.append(
ReferenceAsset(
video_id,
MediaKind.VIDEO,
AssetRole.REFERENCE,
len(assets) + 1,
MediaMetadata(duration_seconds=Decimal("2")),
)
)
for index in range(standalone):
assets.append(
ReferenceAsset(
f"audio-{index}",
MediaKind.AUDIO,
AssetRole.AUDIO_SOURCE,
len(assets) + 1,
MediaMetadata(duration_seconds=Decimal("2")),
)
)
return tuple(assets)
def _authoring(row: dict[str, Any]) -> ReferenceSetState:
state = create_reference_set(
build_h3_base_capacity(
authority="test.capacity",
fingerprint="sha256:" + "a" * 64,
timed=TimedReferenceLimits(max_duration_milliseconds=15000, max_frames=360),
)
)
counts = (
(MediaKind.IMAGE, row["images"]),
(MediaKind.VIDEO, row["videos"]),
(MediaKind.AUDIO, row["audio_total"]),
)
for kind, count in counts:
for index in range(count):
source = AdmittedSourceInput(
source_id=f"{kind.value}-{index}",
kind=kind,
fingerprint="sha256:" + "b" * 64,
duration_milliseconds=None if kind is MediaKind.IMAGE else 2000,
)
state, _ = apply_command(state, AddSource(state.revision, source))
return state
class ReferenceAudioAdmissionTests(unittest.TestCase):
def test_audio_constants_share_the_native_total(self) -> None:
from comfyui_h3_context.core import reference_set_authoring
from comfyui_h3_context.core.reference_limits import H3_BASE_MAX_AUDIO_REFERENCES
self.assertEqual(H3_BASE_MAX_AUDIO_REFERENCES, NATIVE_H3_BASE_MAX_AUDIO)
authoring_max = vars(reference_set_authoring)["H3_BASE_MAX_AUDIO_REFERENCES"]
self.assertEqual(authoring_max, NATIVE_H3_BASE_MAX_AUDIO)
self.assertEqual(MAX_REFERENCE_AUDIO, NATIVE_H3_BASE_MAX_AUDIO)
self.assertEqual(MAX_PAIRED_VIDEO_AUDIO, NATIVE_H3_BASE_MAX_AUDIO)
self.assertEqual(MAX_STANDALONE_AUDIO, NATIVE_H3_BASE_MAX_AUDIO)
def test_every_paired_standalone_mix_is_refused_at_first_admission(self) -> None:
for paired in range(4):
for standalone in range(5):
with self.subTest(paired=paired, standalone=standalone):
assets = _assets(paired, standalone)
result = normalize_request(
RawContextRequest(
mode=TaskMode.REF2VA,
user_intent="a scene",
assets=tuple(asset.to_descriptor() for asset in assets),
)
)
if paired + standalone <= 3:
self.assertIsNotNone(result.request)
self.assertEqual(build_reference_registry(assets).assets, assets)
else:
self.assertIsNone(result.request)
self.assertIn("too_many_audio", {d.code for d in result.diagnostics})
with self.assertRaises(ReferenceRegistryError) as raised:
build_reference_registry(assets)
self.assertEqual(getattr(raised.exception, "code", None), "too_many_audio")
def test_node_preserves_total_audio_refusal_before_runtime_capture(self) -> None:
values = {"images": 0, "videos": 2, "audios": 2, "soundtrack": "included"}
with mock.patch.object(
context_request_nodes, "capture_process_authoring_sources"
) as capture:
with self.assertRaises(ReferenceRegistryNodeError) as raised:
_registry(values)
diagnostic = H3ReferenceRegistryNode.VALIDATE_INPUTS(
videos=[object(), object()],
paired_audios=[object(), object()],
audios=[object(), object()],
)
self.assertIn("too_many_audio", str(diagnostic))
capture.assert_not_called()
self.assertEqual([d.code for d in raised.exception.diagnostics], ["too_many_audio"])
def test_authoring_matches_every_shared_capacity_fixture_row(self) -> None:
fixture = json.loads((FIXTURES / "ref2va_reference_capacity_v1.json").read_bytes())
for row in fixture["cases"]:
with self.subTest(case=row["name"]):
try:
_authoring(row)
admitted = True
except ReferenceSetAuthoringError:
admitted = False
self.assertEqual(admitted, row["capacity_allowed"])
def test_audio_capacity_projection_does_not_advertise_a_fourth_file(self) -> None:
state = _authoring({"images": 1, "videos": 0, "audio_total": 3})
self.assertEqual(capacity_projection(state).standalone_audio_remaining, 0)
self.assertEqual(capacity_projection(state).paired_audio_remaining, 0)
def test_native_preflight_keeps_its_defense_in_depth_refusal(self) -> None:
report = cast(
ContextReport,
SimpleNamespace(
request=SimpleNamespace(
requested_duration_seconds=5.0,
effective_duration_seconds=5.0,
reference_registry=SimpleNamespace(assets=_assets(2, 2)),
)
),
)
with self.assertRaises(NativeH3AdapterError) as raised:
_h3_base_preflight(report)
self.assertEqual(raised.exception.code, "h3_base_audio_reference_limit")
def _registry(row: dict[str, Any]) -> ReferenceRegistry:
values = {
**{f"images.image{i}": object() for i in range(row["images"])},
+15 -15
View File
@@ -48,7 +48,6 @@ class DottedReferenceInputTests(unittest.TestCase):
"images.image1": [images[0]],
"paired_audios.paired_audio0": [object(), object()],
"videos.video0": videos[:2],
"audios.audio0": NonIterableMedia(),
}
with mock.patch.object(
context_request_nodes,
@@ -69,10 +68,9 @@ class DottedReferenceInputTests(unittest.TestCase):
("video_2", None),
("video_3", None),
("audio_1", None),
("audio_2", None),
],
)
self.assertEqual([asset.connection_order for asset in registry.assets], list(range(1, 11)))
self.assertEqual([asset.connection_order for asset in registry.assets], list(range(1, 10)))
self.assertEqual(len(captured), 1)
self.assertIs(captured[0]["exact_registry"], registry)
self.assertEqual(
@@ -83,18 +81,20 @@ class DottedReferenceInputTests(unittest.TestCase):
self.assertNotIn("waveform", json.dumps(registry.to_wire()))
def test_dense_children_accept_all_existing_per_kind_maxima(self) -> None:
children = {
**{f"images.image{i}": [NonIterableMedia()] for i in range(9)},
**{f"videos.video{i}": (NonIterableMedia(),) for i in range(3)},
**{f"paired_audios.paired_audio{i}": NonIterableMedia() for i in range(3)},
**{f"audios.audio{i}": NonIterableMedia() for i in range(3)},
}
registry = H3ReferenceRegistryNode().build_registry(**children)[0]
self.assertEqual(len(registry.assets), 18)
self.assertEqual(
[label.label for label in registry.labels][:9], [f"<Picture {i}>" for i in range(1, 10)]
)
self.assertIs(H3ReferenceRegistryNode.VALIDATE_INPUTS(**children), True)
for prefix in ("paired_audios.paired_audio", "audios.audio"):
with self.subTest(audio_socket=prefix):
children = {
**{f"images.image{i}": [NonIterableMedia()] for i in range(9)},
**{f"videos.video{i}": (NonIterableMedia(),) for i in range(3)},
**{f"{prefix}{i}": NonIterableMedia() for i in range(3)},
}
registry = H3ReferenceRegistryNode().build_registry(**children)[0]
self.assertEqual(len(registry.assets), 15)
self.assertEqual(
[label.label for label in registry.labels][:9],
[f"<Picture {i}>" for i in range(1, 10)],
)
self.assertIs(H3ReferenceRegistryNode.VALIDATE_INPUTS(**children), True)
def test_only_finite_canonical_child_names_are_accepted_without_value_disclosure(self) -> None:
names = (
+38 -5
View File
@@ -23,9 +23,11 @@ from __future__ import annotations
import ast
import unittest
from contextlib import AbstractContextManager
from dataclasses import replace
from pathlib import Path
from comfyui_h3_context.core.contracts import MediaKind
from comfyui_h3_context.core.reference_limits import H3_BASE_MAX_AUDIO_REFERENCES
from comfyui_h3_context.core.reference_set_authoring import (
H3_BASE_AGGREGATE_REFERENCE_FILES,
LEGACY_PAIRED_AUDIO_DISPOSITION,
@@ -301,24 +303,54 @@ class CapacityTests(unittest.TestCase):
apply_command(state, AddSource(state.revision, vid(4)))
def test_standalone_audio_ceiling_and_pairing_interplay(self) -> None:
state = added(fresh(), vid(1), aud(1), aud(2), aud(3))
state = added(
create_reference_set(replace(capacity(), standalone_audio_max=2)),
vid(1),
aud(1),
aud(2),
)
with rejection(self, "capacity_standalone_audio"):
apply_command(state, AddSource(state.revision, aud(4)))
apply_command(state, AddSource(state.revision, aud(3)))
state = facts(state, ("vid-1", SoundtrackAvailability.AVAILABLE))
state, _ = apply_command(state, IncludeSoundtrack(state.revision, "vid-1", "aud-1"))
state, _ = apply_command(state, AddSource(state.revision, aud(4)))
state, _ = apply_command(state, AddSource(state.revision, aud(3)))
with rejection(self, "capacity_standalone_audio"):
apply_command(state, ExcludeSoundtrack(state.revision, "vid-1"))
def test_removing_a_paired_video_cannot_overflow_standalone_audio(self) -> None:
# Found by the state-machine sweep: freeing a bound audio through video removal
# must respect the standalone ceiling it re-enters, exactly like exclude does.
state = added(
create_reference_set(replace(capacity(), standalone_audio_max=2)),
vid(1),
aud(1),
aud(2),
)
state = facts(state, ("vid-1", SoundtrackAvailability.AVAILABLE))
state, _ = apply_command(state, IncludeSoundtrack(state.revision, "vid-1", "aud-1"))
state, _ = apply_command(state, AddSource(state.revision, aud(3)))
with rejection(self, "capacity_standalone_audio"):
apply_command(state, RemoveSource(state.revision, "vid-1"))
def test_binding_does_not_free_total_audio_capacity_for_add_or_restore(self) -> None:
state = added(fresh(), vid(1), aud(1), aud(2), aud(3))
state = facts(state, ("vid-1", SoundtrackAvailability.AVAILABLE))
state, _ = apply_command(state, IncludeSoundtrack(state.revision, "vid-1", "aud-1"))
before = state
with rejection(self, "capacity_audio_total"):
apply_command(state, AddSource(state.revision, aud(4)))
self.assertEqual(state, before)
self.assertEqual(capacity_projection(state).standalone_audio_remaining, 0)
state, receipt = apply_command(state, RemoveSource(state.revision, "aud-3"))
state, _ = apply_command(state, AddSource(state.revision, aud(4)))
with rejection(self, "capacity_standalone_audio"):
apply_command(state, RemoveSource(state.revision, "vid-1"))
before = state
with rejection(self, "capacity_audio_total"):
apply_command(state, replace(receipt.inverse, expected_revision=state.revision))
self.assertEqual(state, before)
state, _ = apply_command(state, ExcludeSoundtrack(state.revision, "vid-1"))
self.assertEqual(len(state.audios), 3)
def test_remaining_capacity_never_advertises_an_impossible_maximum(self) -> None:
state = added(fresh(), *[img(n) for n in range(1, 10)], vid(1), vid(2))
@@ -570,6 +602,7 @@ class CommandSequenceInvariantTests(unittest.TestCase):
self.assertLessEqual(capacity_view.aggregate_used, capacity_view.aggregate_max)
self.assertLessEqual(len(state.images), state.capacity.image_max)
self.assertLessEqual(len(state.videos), state.capacity.video_max)
self.assertLessEqual(len(state.audios), H3_BASE_MAX_AUDIO_REFERENCES)
self.assertLessEqual(len(state.bound_audio_ids()), state.capacity.paired_audio_max)
self.assertLessEqual(
len(state.audios) - len(state.bound_audio_ids()),
+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 = (
"de6c94641926a51b56fdb3092775e58df0013aae3f38497c0bdadd7dde4e2e13" # pragma: allowlist secret
"90615618067ab6143c0f8d422cf5182a913cd1d48e2932b5efc48a26a968c68b" # pragma: allowlist secret
)
RUNTIME_BUNDLE_SIZE = 1924005
RUNTIME_BUNDLE_SIZE = 1926109
def supply_chain() -> ModuleType: