diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index ed088d4..3266486 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -20,7 +20,7 @@ jobs: run: | python -m pip install --upgrade pip python -m pip install --index-url https://download.pytorch.org/whl/cpu torch - python -m pip install -r requirements.txt numpy safetensors pytest psutil + python -m pip install -r requirements.txt numpy safetensors pytest psutil opencv-python-headless Pillow - name: Compile Python run: python -m compileall -q . - name: Run tests diff --git a/MANIFEST.sha256 b/MANIFEST.sha256 index 59e38de..a04ebe7 100644 --- a/MANIFEST.sha256 +++ b/MANIFEST.sha256 @@ -1,9 +1,9 @@ dca65fb1393e67f59c6f81f9411e3e745eb8f1097e9a2adf7ffc6f4e3901ca9f __init__.py 3e7a1ec3380be2a222c8a3e9b8a6bb184d3a760478957f48186438f15235bdba branch_provenance.py -4f6feeb2f63a9285b0e76fb2e2618058c7d7c279af1632e1a6ccabcc9ec9a45a .github/workflows/tests.yml +8296f0afc7be47171e439c02fb2988cfeb0df904acbe3fc4f507f426d709157e .github/workflows/tests.yml 0a2f69d4cec89d440f5d5aa1ec68a7c9a741382d313f80dcddf96d13f70b3e68 .gitignore e0d0093229dd4719e97e1ee2c0cf935f6692f323f97af49a6361fd9ffac8a3d2 AGENTS.md -2794b4f4831e5ec9a38b6cb3049736c16d800708057349e80e1a921c90d16a2e CHANGELOG.md +2794b4f4831e5ec9a38b6cb3049736c16d800708057349e80e1a921c90d16a2e CHANGELOG.md c1ed3a0342730450958fb62fd21854a876991f3a4aefb24e5383b0c73cd2312d compatibility.py 4d62508f900af9f93ec320afb900c27cc9a300d1e0c0a94714258498c5ede5fc conditioning.py 64967f4987e3ad9316f3a47f0dcf582eeff39ee0c3485f4184d3532d495534ae constants.py @@ -87,12 +87,12 @@ b470819f16fc179654dc1600721a63f0a5a14e777f4c004d574b499da6886ba5 public_api.py 96f98d727b72d6aefd431061572e187c303365a3e5b4d20cbb2bcf030aa30112 pyproject.toml 94fdc2d545b2d4077a4d70229fd22ba3ccac21d49d1097d2873f76d04e9a3c7a pytest.ini 88aa955161d04d14ebd8d90d6cb6c6206097160a671eb4d1bfe9b3e76ebc6c13 README_JA.md -1f8a6e1a4441ac2fd7a07ddbdfea923ed1da9f3100db49dca729e141de92f4af README.md +9d9fa5ec9db29e2fb52e3c5ed26df02c9c0c2ba39608294f7c62057237830908 README.md 44127adcfa30ee84bff9cd4b2d0c695355209550e76982d374122008728aa5bc reference_audio.py 5cb9bfd6810d3a93a637451980a4cc5c1436e5b84cfd1c7a111cd192e876351b reference_video.py 131bdfbb7a7173c9e7826859c0e648bfb69bd18bf20fa5528c0e18a63f888b26 reference.py 467edb2c188d024c2392aafe7423b3f835e16b10f570da76e2f7dda8a962c1c5 requirements.txt -a65d657466491aba8b2d1004e87071cee2819869813e646789df736a3ccf479e run_storage.py +2ceba1091dad4fa66da7299e8320ff0a8a6dccb948fc918e3101b40f6d8b03f6 run_storage.py 6056de6c0a5322a8a51ba5a114538dca2ef67788cd1afba10fedd483b95f6afa state_io.py 3a359a0467725cc292ccb4c86cf0c3d30bb6a114d01f5345792b09ea3d45441d state.py 43ec4023dc06c941e5d7a04db4b8a89fb58d744ceb986f6eb9bf534d4fdcb87b temporal.py @@ -172,8 +172,8 @@ cff84ae0562ba5fc48f3608ecaa433e74c0af9b689d7dca94ec8c3c4e9dc232f tests/test_v38 ee4dd8f6eb8114706b2625b4471b041a0ea66198f9f825c63e913c896ed87530 tests/test_v38_branch_provenance.py 72a0e3cb334049b66dd36f52c826931067c242fa63557933fd667138b38d6e8d tests/test_v38_review_control.py 83301839f08d275f5648d7782b6d96795e14b1ce79d722e83e57190fe52fb4aa tests/test_v38_review_execution_cap.py -2fec519540e18c55682884647db9fa1c90902da7be3d62261f2801a5c5724a96 tests/test_v38_review_run_storage.py -b228d1a596ade2c3b3495fdf97177e798cec4be774d6ff02d5c6294e09140866 tests/test_v38_review_ui.py +2fec519540e18c55682884647db9fa1c90902da7be3d62261f2801a5c5724a96 tests/test_v38_review_run_storage.py +dfa174feed4b14d819d1c9f36381e5650e97da6d0e59de441895955dd107ff5f tests/test_v38_review_ui.py 75697036f361a9b8ea74f69b15e408670f686c8c0e8a6c1d48fe059cc837d12a tests/test_v38_selective_second_pass_node.py 8026a241301dfc4de518649305458a538ef17a0b1567b113877a2af377738528 tests/test_v38_temporal_window_refine.py 0dbe8a5f71c92f3523942343b40787104c8b96781461ba3ba82934a6bdbe5834 THIRD_PARTY_NOTICES.md @@ -241,12 +241,12 @@ c2883272b05a9a9146b5c6cf614ddae8a3e6893cd910902023aae61360195289 web/easy_bypas 9db0aa94f634578a962d5db49e5c70356040a59df968e3a2e531b327a623081f web/easy_load_image.js 873efcbd15c2d9fa10c9d5fc51a796ad3a18c0c6acceecf499c4b956aa845c6c web/easy_load_video.js 0c68d13a1f8beb7431a32b471f8b0612c42fcc4bf72dd97611a025d158008662 web/easy_v38.js -549a8150bc926bf142758b1610e3730547d6abcfbcddb0b37ed8baaaf86b38cb web/project_id.js +613797b621f07813b7c13417766f6f87aab92eb4c049ddd692577b226f46a894 web/project_id.js be0b8d39e5343680ebea815c3a4fb6ce7a32e065f30e43e013040a40f702cef3 .comfyignore 1d2838cc47694609289ea15132872ad48e1b6c8274da4b7bf188dd3ebf066121 docs/V38_RELEASE_AND_MIGRATION.md -69d0e95d4d8ed8414e9bfb9bbbcb6183efa6d27f27cc8c6dd2f84c9cc5ce3439 tests/test_v38_public_surface_cleanup.py +69d0e95d4d8ed8414e9bfb9bbbcb6183efa6d27f27cc8c6dd2f84c9cc5ce3439 tests/test_v38_public_surface_cleanup.py 0cf8d49bcb71b30437dc893f6218dc4cfb1cd244b647e4fbc2861dea2271a33a web/reference_audio_ui.js -88a9426baa14dc99ecd643cdf58e46e780672d86088b2897aa66952c56b3c126 REGISTRY_MANIFEST.sha256 +88a9426baa14dc99ecd643cdf58e46e780672d86088b2897aa66952c56b3c126 REGISTRY_MANIFEST.sha256 717577efdec5e61600504b77bc2a099ef022c4fe2333e936c3310c7182d8f2a0 docs/V38_OPEN_INTEGRATION_CONTRACT.md 623d528a02b6712cba28c374ba3ad979bc84e2ac5318640692589a04ba6ab15f tests/test_v38_open_integration_contract.py 0bc369ee428b8a5bc8e370a81fbab427262a1fdb7805a78c442c91698d65efba tools/__init__.py diff --git a/README.md b/README.md index 4562ade..7a4a558 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ **Download workflow: [JSON](examples/workflows/MiniMax_H3_Continuum_V38.json) | [ZIP](examples/workflows/MiniMax_H3_Continuum_V38.zip)** — [Latest release](https://github.com/ukr8b3g-cmyk/ComfyUI-H3-Continuum/releases/latest) -⚠️ Hotfix in progress: We’re investigating reported issues with chunk continuation and Review Each Chunk mode in V3.8. A hotfix is being prepared. Thank you for your reports and patience—we’ll update this page when it’s ready. +✅ V3.8 hotfix applied on `main` — September 8, 2026: Review Each Chunk continuation, stale `Regenerate From` state, completed-sequence extension, and Render History queue handling have been repaired. Update with `git pull --ff-only origin main` (or ComfyUI Manager **Update**), restart ComfyUI, and hard-refresh the browser if the old UI remains. Existing saved Takes are preserved. Issue #13 remains a separate open long-continuation quality issue and is not part of this hotfix. exec-55ad0463-8655-409c-b9a6-49d1315cdd78 @@ -463,23 +463,35 @@ If you want a review pause instead, choose `Run = Review Each Chunk` in step 6. #### 9. Add more chunks to a completed sequence -For a compatible saved run without a Last Image constraint, increasing the target can reuse completed chunks. This requires saved progress, not just an existing MP4 file. +**You do not need Render History just to make a completed video longer.** For an ordinary extension, go back to the normal settings, increase the target `Chunks`, and Queue again. `Chunks` is the **final total number of chunks**, not the number you want to add next. -1. Keep the same Sampler/workflow and `Run Name (Optional Override)`. Do not create a new run identity. -2. Keep `Base Seed` unchanged and `Control After Generate = fixed`. -3. Keep `Progress = On — Resume and Takes available`, and keep the saved progress files available. -4. Keep `Seconds per Chunk` and the generation inputs unchanged. -5. Set `Regenerate From = Auto`. -6. Change **only the target count** in `Chunks`: for example, change `3` to `5` to add two chunks. Do not set it to `2`. -7. Choose `Run = Review Each Chunk` for one new review unit per Queue, or `Run = Generate Full Video` to finish all missing chunks. -8. Check `Total Length`, then click the top-right blue `Run` button and check the reuse report described below. +For the simplest and safest extension, keep the existing generation conditions unchanged: the same Sampler/workflow and run identity, `Base Seed`, `Control After Generate = fixed`, `Seconds per Chunk`, prompt, model/LoRA, media, dimensions, sampling schedule, Continuity, and Audio Continuity. Keep `Progress = On — Resume and Takes available` and `Regenerate From = Auto`. -With compatible progress for three 5-second chunks, the new target is 25 seconds. Review mode should first produce Chunk 4 and a 20-second output; continuing again completes Chunk 5. Full-video mode should produce Chunks 4–5 and the 25-second output in one Queue. +**Example: extend a completed 2 × 5-second sequence to 3 × 5 seconds** -**Do not assume append-only reuse with Last Image.** Extending a sequence changes where its final-image constraint belongs. The former last chunk, or a terminal pair, may need regeneration. Likewise, changing the model, prompt, media, dimensions, schedule, or continuation settings can invalidate saved progress. `Progress = On` enables compatibility checking; it does not force incompatible chunks to be reused. +1. Finish the original two chunks. The completed target is `Chunks = 2`, so the saved video is 10 seconds. +2. Click `Back to Settings`. You do **not** need to open `Render History`. +3. Change `Chunks` from `2` to `3`. `Total Length` changes from 10 seconds to 15 seconds. +4. Keep `Progress = On — Resume and Takes available` and `Regenerate From = Auto`. Keep the prompt and the existing generation inputs unchanged for this ordinary extension. +5. Use `Run = Review Each Chunk` if you want to review the new chunk, or `Run = Generate Full Video` if you want all currently missing chunks generated in one Queue. +6. Click the top-right blue `Run` button. + +With compatible saved progress, the expected work is: + +- Chunk 1 → reused; no new Sampling +- Chunk 2 → reused; no new Sampling +- Chunk 3 → newly generated +- final saved sequence → 3 chunks / 15 seconds + +The same rule applies to a larger extension. For example, changing `Chunks` from `3` to `5` means the new target is five total chunks; it does **not** mean “add five.” Review mode first generates Chunk 4, then Chunk 5 on the next accepted continuation. Full-video mode generates the missing Chunks 4–5 in one Queue. + +Switching `Generate Full Video` ↔ `Review Each Chunk` by itself does **not** mean restart from Chunk 1. A Chunk 1 restart happens only when you explicitly choose `Start again from Chunk 1`, explicitly set Advanced `Regenerate From = Chunk 1`, or the backend determines that the stored prefix is incompatible with the current generation contract. + +`Render History` is for a different job: browsing stored Takes, selecting an older Take, or branching with `Continue From Here`. Normal append-style extension does not require History. `Previous Take` / `Next Take` only browse stored results; they do not generate a new chunk. + +**Do not assume append-only reuse with Last Image.** Extending a sequence changes where its final-image constraint belongs. The former last chunk, or a terminal pair, may need regeneration. Likewise, changing the prompt or other generation-contract inputs can invalidate saved progress. `Progress = On` enables compatibility checking; it does not force incompatible chunks to be reused. The extension path is covered by CPU compatibility tests, including two-to-three chunks and Last Image invalidation. It is not the same GPU test as the two-chunk review timing example below; arbitrary extensions and media combinations have not all been GPU-verified. - #### 10. Understand continuation time and check reuse Continuing does not mean saving only the new segment. With compatible saved progress, the normal workflow: diff --git a/REGISTRY_MANIFEST.sha256 b/REGISTRY_MANIFEST.sha256 index bbc9c7b..d8e84d3 100644 --- a/REGISTRY_MANIFEST.sha256 +++ b/REGISTRY_MANIFEST.sha256 @@ -1,7 +1,7 @@ dca65fb1393e67f59c6f81f9411e3e745eb8f1097e9a2adf7ffc6f4e3901ca9f __init__.py be0b8d39e5343680ebea815c3a4fb6ce7a32e065f30e43e013040a40f702cef3 .comfyignore 3e7a1ec3380be2a222c8a3e9b8a6bb184d3a760478957f48186438f15235bdba branch_provenance.py -2794b4f4831e5ec9a38b6cb3049736c16d800708057349e80e1a921c90d16a2e CHANGELOG.md +2794b4f4831e5ec9a38b6cb3049736c16d800708057349e80e1a921c90d16a2e CHANGELOG.md c1ed3a0342730450958fb62fd21854a876991f3a4aefb24e5383b0c73cd2312d compatibility.py 4d62508f900af9f93ec320afb900c27cc9a300d1e0c0a94714258498c5ede5fc conditioning.py 64967f4987e3ad9316f3a47f0dcf582eeff39ee0c3485f4184d3532d495534ae constants.py @@ -28,12 +28,12 @@ a4ce23167b83e8d72b86a802dfde4f4045828433c7c13aab799bd64831dc04a4 nodes.py b470819f16fc179654dc1600721a63f0a5a14e777f4c004d574b499da6886ba5 public_api.py 96f98d727b72d6aefd431061572e187c303365a3e5b4d20cbb2bcf030aa30112 pyproject.toml 88aa955161d04d14ebd8d90d6cb6c6206097160a671eb4d1bfe9b3e76ebc6c13 README_JA.md -1f8a6e1a4441ac2fd7a07ddbdfea923ed1da9f3100db49dca729e141de92f4af README.md +9d9fa5ec9db29e2fb52e3c5ed26df02c9c0c2ba39608294f7c62057237830908 README.md 44127adcfa30ee84bff9cd4b2d0c695355209550e76982d374122008728aa5bc reference_audio.py 5cb9bfd6810d3a93a637451980a4cc5c1436e5b84cfd1c7a111cd192e876351b reference_video.py 131bdfbb7a7173c9e7826859c0e648bfb69bd18bf20fa5528c0e18a63f888b26 reference.py 467edb2c188d024c2392aafe7423b3f835e16b10f570da76e2f7dda8a962c1c5 requirements.txt -a65d657466491aba8b2d1004e87071cee2819869813e646789df736a3ccf479e run_storage.py +2ceba1091dad4fa66da7299e8320ff0a8a6dccb948fc918e3101b40f6d8b03f6 run_storage.py 6056de6c0a5322a8a51ba5a114538dca2ef67788cd1afba10fedd483b95f6afa state_io.py 3a359a0467725cc292ccb4c86cf0c3d30bb6a114d01f5345792b09ea3d45441d state.py 43ec4023dc06c941e5d7a04db4b8a89fb58d744ceb986f6eb9bf534d4fdcb87b temporal.py @@ -100,6 +100,6 @@ c2883272b05a9a9146b5c6cf614ddae8a3e6893cd910902023aae61360195289 web/easy_bypas 9db0aa94f634578a962d5db49e5c70356040a59df968e3a2e531b327a623081f web/easy_load_image.js 873efcbd15c2d9fa10c9d5fc51a796ad3a18c0c6acceecf499c4b956aa845c6c web/easy_load_video.js 0c68d13a1f8beb7431a32b471f8b0612c42fcc4bf72dd97611a025d158008662 web/easy_v38.js -549a8150bc926bf142758b1610e3730547d6abcfbcddb0b37ed8baaaf86b38cb web/project_id.js +613797b621f07813b7c13417766f6f87aab92eb4c049ddd692577b226f46a894 web/project_id.js 0cf8d49bcb71b30437dc893f6218dc4cfb1cd244b647e4fbc2861dea2271a33a web/reference_audio_ui.js 83d28cc0cd549066962dc21ceae05d2b189fe22391b556887eab2cc1800e1e80 examples/workflows/MiniMax_H3_Continuum_V38.zip diff --git a/run_storage.py b/run_storage.py index ec092e8..900757c 100644 --- a/run_storage.py +++ b/run_storage.py @@ -1,21 +1,21 @@ -"""Crash-safe V3.1B raw-latent storage and deterministic auto-resume.""" - -from __future__ import annotations - -import contextvars -import hashlib -import json -import marshal -import os -import re +"""Crash-safe V3.1B raw-latent storage and deterministic auto-resume.""" + +from __future__ import annotations + +import contextvars +import hashlib +import json +import marshal +import os +import re import shutil -import socket import time +import socket import uuid -from datetime import datetime, timezone -from pathlib import Path -from typing import Any - +from datetime import datetime, timezone +from pathlib import Path +from typing import Any + import torch from safetensors import safe_open from safetensors.torch import save_file @@ -53,42 +53,42 @@ from .v3.review_control import ( RUN_STORAGE_SCHEMA_VERSION = 3 RUN_STORAGE_READABLE_SCHEMA_VERSIONS = (2, RUN_STORAGE_SCHEMA_VERSION) -from .conditioning import ( - CONDITIONING_MODES, - conditioning_mode_from_presence, - conditioning_mode_uses_video_vae, -) - - +from .conditioning import ( + CONDITIONING_MODES, + conditioning_mode_from_presence, + conditioning_mode_uses_video_vae, +) + + SAMPLING_CONTRACT_VERSION = 5 REVIEW_CONTROL_VERSION = 1 RUN_STORAGE_OFF = "Off" -RUN_STORAGE_AUTO = "Save + Auto Resume" -RUN_STORAGE_OPTIONS = (RUN_STORAGE_OFF, RUN_STORAGE_AUTO) - -_ACTIVE: contextvars.ContextVar["RunStorageController | None"] = contextvars.ContextVar( - "h3_continuum_run_storage", default=None -) -_RESERVED = { - "CON", "PRN", "AUX", "NUL", - *(f"COM{i}" for i in range(1, 10)), - *(f"LPT{i}" for i in range(1, 10)), -} -_ADDRESS = re.compile(r"0x[0-9a-fA-F]+") - - -class RunStorageError(RuntimeError): - pass - - -def _now() -> str: - return datetime.now(timezone.utc).replace(microsecond=0).isoformat() - - -def _canonical(value: Any) -> str: - return json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=True) - - +RUN_STORAGE_AUTO = "Save + Auto Resume" +RUN_STORAGE_OPTIONS = (RUN_STORAGE_OFF, RUN_STORAGE_AUTO) + +_ACTIVE: contextvars.ContextVar["RunStorageController | None"] = contextvars.ContextVar( + "h3_continuum_run_storage", default=None +) +_RESERVED = { + "CON", "PRN", "AUX", "NUL", + *(f"COM{i}" for i in range(1, 10)), + *(f"LPT{i}" for i in range(1, 10)), +} +_ADDRESS = re.compile(r"0x[0-9a-fA-F]+") + + +class RunStorageError(RuntimeError): + pass + + +def _now() -> str: + return datetime.now(timezone.utc).replace(microsecond=0).isoformat() + + +def _canonical(value: Any) -> str: + return json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=True) + + def _hash(value: Any) -> str: return hashlib.sha256(_canonical(value).encode("utf-8")).hexdigest() @@ -134,134 +134,134 @@ def _canonical_optional_hash(value: Any) -> str: def sanitize_run_name(value: str) -> str: - name = str(value) - if not name or name != name.strip() or len(name) > 96: - raise RunStorageError("Run Name must be 1-96 characters without surrounding spaces") - if any(ord(char) < 32 or char in '<>:"/\\|?*' for char in name): - raise RunStorageError("Run Name contains a reserved path character") - if name.endswith((".", " ")) or name in {".", ".."}: - raise RunStorageError("Run Name must not be a relative path or end with dot/space") - if name.split(".", 1)[0].upper() in _RESERVED: - raise RunStorageError(f"Run Name {name!r} is reserved by Windows") - return name - - -def resolve_run_storage_name( - *, project_id: str, legacy_run_name: str = "", automatic_key: str = "" -) -> str: - """Resolve a stable storage folder while preserving old Run Name workflows.""" - legacy = str(legacy_run_name) - if legacy: - return sanitize_run_name(legacy) - raw_project_id = str(project_id).strip() - if not raw_project_id: - key = str(automatic_key).strip() - if not key: - raise RunStorageError( - "Automatic Resume ID is unavailable; enter a Run Name for this workflow" - ) - digest = hashlib.sha256( - f"H3ContinuumSamplerProduction:{key}".encode("utf-8") - ).hexdigest()[:24] - return f"run_auto_{digest}" - try: - parsed = uuid.UUID(raw_project_id) - except (ValueError, AttributeError, TypeError) as exc: - raise RunStorageError( - "Automatic Project ID is missing or invalid; reload ComfyUI and the workflow" - ) from exc - if parsed.int == 0: - raise RunStorageError("Automatic Project ID must not be the nil UUID") - return f"run_{parsed.hex}" - - -def automatic_project_key(prompt: Any, unique_id: Any) -> str: - """Build a stable key from sampler identity and graph topology only.""" - node_id = str(unique_id).strip() - if not node_id: - raise RunStorageError("Automatic Resume ID requires the sampler node ID") - if not isinstance(prompt, dict): - raise RunStorageError( - "Automatic Resume ID requires the ComfyUI prompt graph; enter a Run Name" - ) - def visit(current_id: str, stack: set[str]) -> dict[str, Any]: - if current_id in stack: - return {"node_id": current_id, "cycle": True} - raw = prompt.get(current_id) - if not isinstance(raw, dict): - return {"node_id": current_id, "missing": True} - links = [] - inputs = raw.get("inputs") or {} - next_stack = set(stack) - next_stack.add(current_id) - if isinstance(inputs, dict): - for name in sorted(inputs): - if current_id == node_id and name == "reference_audio_vae": - audio_link = inputs.get("reference_audio_1") - if not ( - isinstance(audio_link, (list, tuple)) - and len(audio_link) == 2 - and isinstance(audio_link[0], (str, int)) - and isinstance(audio_link[1], int) - and str(audio_link[0]) in prompt - ): - continue - if current_id == node_id and name == "audio_vae": - audio_link = inputs.get("driving_audio") - if not ( - isinstance(audio_link, (list, tuple)) - and len(audio_link) == 2 - and isinstance(audio_link[0], (str, int)) - and isinstance(audio_link[1], int) - and str(audio_link[0]) in prompt - ): - continue - value = inputs[name] - if ( - isinstance(value, (list, tuple)) - and len(value) == 2 - and isinstance(value[0], (str, int)) - and isinstance(value[1], int) - and str(value[0]) in prompt - ): - child_id = str(value[0]) - links.append( - { - "input": str(name), - "output": int(value[1]), - "node": visit(child_id, next_stack), - } - ) - return { - "node_id": current_id, - "class_type": str(raw.get("class_type", "")), - "links": links, - } - return _hash({"sampler_node_id": node_id, "topology": visit(node_id, set())}) - - -def _output_root() -> Path: - try: - import folder_paths - - return Path(folder_paths.get_output_directory()) - except Exception: - return Path.cwd() / "output" - - -def _fsync_file(path: Path) -> None: - # Windows requires a writable descriptor for fsync(). The file contents - # are already complete at this point; opening r+b does not modify them. - with path.open("r+b") as handle: - os.fsync(handle.fileno()) - - + name = str(value) + if not name or name != name.strip() or len(name) > 96: + raise RunStorageError("Run Name must be 1-96 characters without surrounding spaces") + if any(ord(char) < 32 or char in '<>:"/\\|?*' for char in name): + raise RunStorageError("Run Name contains a reserved path character") + if name.endswith((".", " ")) or name in {".", ".."}: + raise RunStorageError("Run Name must not be a relative path or end with dot/space") + if name.split(".", 1)[0].upper() in _RESERVED: + raise RunStorageError(f"Run Name {name!r} is reserved by Windows") + return name + + +def resolve_run_storage_name( + *, project_id: str, legacy_run_name: str = "", automatic_key: str = "" +) -> str: + """Resolve a stable storage folder while preserving old Run Name workflows.""" + legacy = str(legacy_run_name) + if legacy: + return sanitize_run_name(legacy) + raw_project_id = str(project_id).strip() + if not raw_project_id: + key = str(automatic_key).strip() + if not key: + raise RunStorageError( + "Automatic Resume ID is unavailable; enter a Run Name for this workflow" + ) + digest = hashlib.sha256( + f"H3ContinuumSamplerProduction:{key}".encode("utf-8") + ).hexdigest()[:24] + return f"run_auto_{digest}" + try: + parsed = uuid.UUID(raw_project_id) + except (ValueError, AttributeError, TypeError) as exc: + raise RunStorageError( + "Automatic Project ID is missing or invalid; reload ComfyUI and the workflow" + ) from exc + if parsed.int == 0: + raise RunStorageError("Automatic Project ID must not be the nil UUID") + return f"run_{parsed.hex}" + + +def automatic_project_key(prompt: Any, unique_id: Any) -> str: + """Build a stable key from sampler identity and graph topology only.""" + node_id = str(unique_id).strip() + if not node_id: + raise RunStorageError("Automatic Resume ID requires the sampler node ID") + if not isinstance(prompt, dict): + raise RunStorageError( + "Automatic Resume ID requires the ComfyUI prompt graph; enter a Run Name" + ) + def visit(current_id: str, stack: set[str]) -> dict[str, Any]: + if current_id in stack: + return {"node_id": current_id, "cycle": True} + raw = prompt.get(current_id) + if not isinstance(raw, dict): + return {"node_id": current_id, "missing": True} + links = [] + inputs = raw.get("inputs") or {} + next_stack = set(stack) + next_stack.add(current_id) + if isinstance(inputs, dict): + for name in sorted(inputs): + if current_id == node_id and name == "reference_audio_vae": + audio_link = inputs.get("reference_audio_1") + if not ( + isinstance(audio_link, (list, tuple)) + and len(audio_link) == 2 + and isinstance(audio_link[0], (str, int)) + and isinstance(audio_link[1], int) + and str(audio_link[0]) in prompt + ): + continue + if current_id == node_id and name == "audio_vae": + audio_link = inputs.get("driving_audio") + if not ( + isinstance(audio_link, (list, tuple)) + and len(audio_link) == 2 + and isinstance(audio_link[0], (str, int)) + and isinstance(audio_link[1], int) + and str(audio_link[0]) in prompt + ): + continue + value = inputs[name] + if ( + isinstance(value, (list, tuple)) + and len(value) == 2 + and isinstance(value[0], (str, int)) + and isinstance(value[1], int) + and str(value[0]) in prompt + ): + child_id = str(value[0]) + links.append( + { + "input": str(name), + "output": int(value[1]), + "node": visit(child_id, next_stack), + } + ) + return { + "node_id": current_id, + "class_type": str(raw.get("class_type", "")), + "links": links, + } + return _hash({"sampler_node_id": node_id, "topology": visit(node_id, set())}) + + +def _output_root() -> Path: + try: + import folder_paths + + return Path(folder_paths.get_output_directory()) + except Exception: + return Path.cwd() / "output" + + +def _fsync_file(path: Path) -> None: + # Windows requires a writable descriptor for fsync(). The file contents + # are already complete at this point; opening r+b does not modify them. + with path.open("r+b") as handle: + os.fsync(handle.fileno()) + + def _fsync_dir(path: Path) -> None: - if os.name == "nt": - return - descriptor = os.open(str(path), os.O_RDONLY) - try: - os.fsync(descriptor) + if os.name == "nt": + return + descriptor = os.open(str(path), os.O_RDONLY) + try: + os.fsync(descriptor) finally: os.close(descriptor) @@ -287,8 +287,7 @@ def _replace_json_atomically(temporary: Path, destination: Path) -> None: winerror = getattr(exc, "winerror", None) error_code = winerror if winerror is not None else exc.errno transient = ( - os.name == "nt" - and error_code in _WINDOWS_REPLACE_RETRY_WINERRORS + error_code in _WINDOWS_REPLACE_RETRY_WINERRORS and delay is not None ) if transient: @@ -314,101 +313,101 @@ def _replace_json_atomically(temporary: Path, destination: Path) -> None: def _write_json(path: Path, payload: dict[str, Any]) -> None: - path.parent.mkdir(parents=True, exist_ok=True) - temporary = path.with_name(f".{path.name}.{uuid.uuid4().hex}.tmp") - try: - with temporary.open("w", encoding="utf-8", newline="\n") as handle: + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_name(f".{path.name}.{uuid.uuid4().hex}.tmp") + try: + with temporary.open("w", encoding="utf-8", newline="\n") as handle: json.dump(payload, handle, ensure_ascii=False, sort_keys=True, indent=2) handle.write("\n") handle.flush() os.fsync(handle.fileno()) _replace_json_atomically(temporary, path) _fsync_dir(path.parent) - finally: - if temporary.exists(): - temporary.unlink() - - -def _read_json(path: Path) -> dict[str, Any]: - value = json.loads(path.read_text(encoding="utf-8")) - if not isinstance(value, dict): - raise RunStorageError(f"{path.name} must contain a JSON object") - return value - - -def _file_sha256(path: Path) -> str: - digest = hashlib.sha256() - with path.open("rb") as handle: - for block in iter(lambda: handle.read(1024 * 1024), b""): - digest.update(block) - return digest.hexdigest() - - -def _qualified(value: Any) -> str: - if value is None: - return "none" - target = value if isinstance(value, type) or callable(value) else type(value) - module = getattr(target, "__module__", "") - name = getattr(target, "__qualname__", getattr(target, "__name__", type(target).__name__)) - return f"{module}.{name}" - - + finally: + if temporary.exists(): + temporary.unlink() + + +def _read_json(path: Path) -> dict[str, Any]: + value = json.loads(path.read_text(encoding="utf-8")) + if not isinstance(value, dict): + raise RunStorageError(f"{path.name} must contain a JSON object") + return value + + +def _file_sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def _qualified(value: Any) -> str: + if value is None: + return "none" + target = value if isinstance(value, type) or callable(value) else type(value) + module = getattr(target, "__module__", "") + name = getattr(target, "__qualname__", getattr(target, "__name__", type(target).__name__)) + return f"{module}.{name}" + + def _tensor_probe(tensor: torch.Tensor, *, dtype: torch.dtype | None = None) -> dict[str, Any]: - flat = tensor.detach().reshape(-1) - count = int(flat.numel()) - positions = sorted({0, count // 4, count // 2, 3 * count // 4, count - 1}) if count else [] - if positions: - index = torch.tensor(positions, device=flat.device) + flat = tensor.detach().reshape(-1) + count = int(flat.numel()) + positions = sorted({0, count // 4, count // 2, 3 * count // 4, count - 1}) if count else [] + if positions: + index = torch.tensor(positions, device=flat.device) values = flat[index] if dtype is not None and dtype != tensor.dtype: values = values.to(dtype=dtype) sample = values.contiguous().cpu().view(torch.uint8).numpy().tobytes() - else: - sample = b"" - return { - "shape": list(tensor.shape), + else: + sample = b"" + return { + "shape": list(tensor.shape), "dtype": str(dtype if dtype is not None else tensor.dtype), - "sample_sha256": hashlib.sha256(sample).hexdigest(), - } - - -def _tensor_exact(tensor: torch.Tensor) -> dict[str, Any]: - value = tensor.detach().contiguous().cpu() - raw = value.view(torch.uint8).numpy().tobytes() - return { - "shape": list(value.shape), - "dtype": str(value.dtype), - "exact_sha256": hashlib.sha256(raw).hexdigest(), - } - - -def _observe(value: Any, *, depth: int = 0) -> tuple[Any, bool]: - if depth > 10: - return {"type": _qualified(value), "truncated": True}, False - if value is None or isinstance(value, (bool, int, float, str)): - return value, True - if isinstance(value, Path): - return str(value), True - if torch.is_tensor(value): - try: - return {"tensor": _tensor_probe(value)}, True - except Exception: - return {"tensor_type": _qualified(value)}, False - if isinstance(value, dict): - result: dict[str, Any] = {} - safe = True - for key in sorted(value, key=lambda item: str(item)): - observed, item_safe = _observe(value[key], depth=depth + 1) - result[str(key)] = observed - safe = safe and item_safe - return result, safe + "sample_sha256": hashlib.sha256(sample).hexdigest(), + } + + +def _tensor_exact(tensor: torch.Tensor) -> dict[str, Any]: + value = tensor.detach().contiguous().cpu() + raw = value.view(torch.uint8).numpy().tobytes() + return { + "shape": list(value.shape), + "dtype": str(value.dtype), + "exact_sha256": hashlib.sha256(raw).hexdigest(), + } + + +def _observe(value: Any, *, depth: int = 0) -> tuple[Any, bool]: + if depth > 10: + return {"type": _qualified(value), "truncated": True}, False + if value is None or isinstance(value, (bool, int, float, str)): + return value, True + if isinstance(value, Path): + return str(value), True + if torch.is_tensor(value): + try: + return {"tensor": _tensor_probe(value)}, True + except Exception: + return {"tensor_type": _qualified(value)}, False + if isinstance(value, dict): + result: dict[str, Any] = {} + safe = True + for key in sorted(value, key=lambda item: str(item)): + observed, item_safe = _observe(value[key], depth=depth + 1) + result[str(key)] = observed + safe = safe and item_safe + return result, safe if isinstance(value, (list, tuple)): - result = [] - safe = True - for item in value: - observed, item_safe = _observe(item, depth=depth + 1) - result.append(observed) - safe = safe and item_safe + result = [] + safe = True + for item in value: + observed, item_safe = _observe(item, depth=depth + 1) + result.append(observed) + safe = safe and item_safe return result, safe if isinstance(value, (set, frozenset)): # Set repr order varies with PYTHONHASHSEED; keep every item and its type. @@ -417,88 +416,88 @@ def _observe(value: Any, *, depth: int = 0) -> tuple[Any, bool]: "type": _qualified(value), "items": sorted((item for item, _ in items), key=_canonical), }, all(safe for _, safe in items) - if callable(value): - code = getattr(value, "__code__", None) - descriptor: dict[str, Any] = {"callable": _qualified(value)} - safe = True - if code is not None: - descriptor["code_sha256"] = hashlib.sha256( - marshal.dumps(code) - ).hexdigest() - defaults, defaults_safe = _observe(getattr(value, "__defaults__", None), depth=depth + 1) - kwdefaults, kw_safe = _observe(getattr(value, "__kwdefaults__", None), depth=depth + 1) - closure_values = tuple(cell.cell_contents for cell in (getattr(value, "__closure__", None) or ())) - closure, closure_safe = _observe(closure_values, depth=depth + 1) - descriptor.update(defaults=defaults, kwdefaults=kwdefaults, closure=closure) - safe = defaults_safe and kw_safe and closure_safe - elif hasattr(value, "__dict__"): - attributes, safe = _observe(vars(value), depth=depth + 1) - descriptor["attributes"] = attributes - else: - safe = False - return descriptor, safe - if hasattr(value, "__dict__"): - attributes, safe = _observe(vars(value), depth=depth + 1) - return {"type": _qualified(value), "attributes": attributes}, safe - rendered = _ADDRESS.sub("0x...", repr(value)) - return {"type": _qualified(value), "repr": rendered[:256]}, False - - -def _model_signature(model: Any, legacy_fingerprint: str) -> tuple[dict[str, Any], bool]: - base = getattr(model, "model", None) - inner = getattr(base, "diffusion_model", None) - wrappers, wrappers_safe = _observe(getattr(model, "wrappers", {}) or {}) - patches, patches_safe = _observe(getattr(model, "patches", {}) or {}) - options = getattr(model, "model_options", {}) or {} - transformer = options.get("transformer_options", {}) or {} - transformer_values = { - str(key): transformer[key] - for key in transformer - if key not in {"h3_continuum_join_context"} - } - observed_transformer, transformer_safe = _observe(transformer_values) - weights: list[dict[str, Any]] = [] - weights_safe = True - try: - parameters = list(inner.named_parameters()) if inner is not None else [] - for position in sorted({0, len(parameters) // 2, len(parameters) - 1}) if parameters else []: - name, parameter = parameters[position] - weights.append({"name": str(name), **_tensor_probe(parameter)}) - except Exception: - weights_safe = False - descriptor = { - "legacy_fingerprint": str(legacy_fingerprint), - "model_patcher": _qualified(model), - "base": _qualified(base), - "inner": _qualified(inner), - "dtype": str(getattr(model, "model_dtype", lambda: "unknown")()), - "model_size": int(getattr(model, "model_size", lambda: 0)() or 0), - "wrappers": wrappers, - "transformer_options": observed_transformer, - "patches": patches, - "weight_probe": weights, - "runtime_observation": { - "wrappers_complete": bool(wrappers_safe), - "patches_complete": bool(patches_safe), - "transformer_options_complete": bool(transformer_safe), - }, - } - return descriptor, weights_safe and bool(weights) - - -def _sampler_signature(sampler: Any) -> tuple[dict[str, Any], bool]: - function = getattr(sampler, "sampler_function", None) - observed, safe = _observe({ - "extra_options": getattr(sampler, "extra_options", {}) or {}, - "inpaint_options": getattr(sampler, "inpaint_options", {}) or {}, - }) - return { - "type": _qualified(sampler), - "function": _qualified(function) if function is not None else "unknown", - "options": observed, - }, function is not None and safe - - + if callable(value): + code = getattr(value, "__code__", None) + descriptor: dict[str, Any] = {"callable": _qualified(value)} + safe = True + if code is not None: + descriptor["code_sha256"] = hashlib.sha256( + marshal.dumps(code) + ).hexdigest() + defaults, defaults_safe = _observe(getattr(value, "__defaults__", None), depth=depth + 1) + kwdefaults, kw_safe = _observe(getattr(value, "__kwdefaults__", None), depth=depth + 1) + closure_values = tuple(cell.cell_contents for cell in (getattr(value, "__closure__", None) or ())) + closure, closure_safe = _observe(closure_values, depth=depth + 1) + descriptor.update(defaults=defaults, kwdefaults=kwdefaults, closure=closure) + safe = defaults_safe and kw_safe and closure_safe + elif hasattr(value, "__dict__"): + attributes, safe = _observe(vars(value), depth=depth + 1) + descriptor["attributes"] = attributes + else: + safe = False + return descriptor, safe + if hasattr(value, "__dict__"): + attributes, safe = _observe(vars(value), depth=depth + 1) + return {"type": _qualified(value), "attributes": attributes}, safe + rendered = _ADDRESS.sub("0x...", repr(value)) + return {"type": _qualified(value), "repr": rendered[:256]}, False + + +def _model_signature(model: Any, legacy_fingerprint: str) -> tuple[dict[str, Any], bool]: + base = getattr(model, "model", None) + inner = getattr(base, "diffusion_model", None) + wrappers, wrappers_safe = _observe(getattr(model, "wrappers", {}) or {}) + patches, patches_safe = _observe(getattr(model, "patches", {}) or {}) + options = getattr(model, "model_options", {}) or {} + transformer = options.get("transformer_options", {}) or {} + transformer_values = { + str(key): transformer[key] + for key in transformer + if key not in {"h3_continuum_join_context"} + } + observed_transformer, transformer_safe = _observe(transformer_values) + weights: list[dict[str, Any]] = [] + weights_safe = True + try: + parameters = list(inner.named_parameters()) if inner is not None else [] + for position in sorted({0, len(parameters) // 2, len(parameters) - 1}) if parameters else []: + name, parameter = parameters[position] + weights.append({"name": str(name), **_tensor_probe(parameter)}) + except Exception: + weights_safe = False + descriptor = { + "legacy_fingerprint": str(legacy_fingerprint), + "model_patcher": _qualified(model), + "base": _qualified(base), + "inner": _qualified(inner), + "dtype": str(getattr(model, "model_dtype", lambda: "unknown")()), + "model_size": int(getattr(model, "model_size", lambda: 0)() or 0), + "wrappers": wrappers, + "transformer_options": observed_transformer, + "patches": patches, + "weight_probe": weights, + "runtime_observation": { + "wrappers_complete": bool(wrappers_safe), + "patches_complete": bool(patches_safe), + "transformer_options_complete": bool(transformer_safe), + }, + } + return descriptor, weights_safe and bool(weights) + + +def _sampler_signature(sampler: Any) -> tuple[dict[str, Any], bool]: + function = getattr(sampler, "sampler_function", None) + observed, safe = _observe({ + "extra_options": getattr(sampler, "extra_options", {}) or {}, + "inpaint_options": getattr(sampler, "inpaint_options", {}) or {}, + }) + return { + "type": _qualified(sampler), + "function": _qualified(function) if function is not None else "unknown", + "options": observed, + }, function is not None and safe + + def _module_parameter_dtype(module: Any, name: str, parameter: torch.Tensor) -> torch.dtype: """Observe ordinary weights at Core's declared load dtype without casting them.""" # Quantized/custom Tensor representations retain their original fingerprint. @@ -515,145 +514,145 @@ def _module_parameter_dtype(module: Any, name: str, parameter: torch.Tensor) -> def _module_signature(module: Any) -> tuple[dict[str, Any], bool]: - descriptor: dict[str, Any] = {"type": _qualified(module)} - if module is None or not hasattr(module, "named_parameters"): - descriptor["error"] = "named_parameters unavailable" - return descriptor, False + descriptor: dict[str, Any] = {"type": _qualified(module)} + if module is None or not hasattr(module, "named_parameters"): + descriptor["error"] = "named_parameters unavailable" + return descriptor, False try: parameters = list(module.named_parameters()) dtypes = { name: _module_parameter_dtype(module, name, parameter) for name, parameter in parameters } - except Exception as exc: - descriptor["error"] = f"named_parameters failed: {type(exc).__name__}" - return descriptor, False - layout = [ - { - "name": str(name), - "shape": list(parameter.shape), + except Exception as exc: + descriptor["error"] = f"named_parameters failed: {type(exc).__name__}" + return descriptor, False + layout = [ + { + "name": str(name), + "shape": list(parameter.shape), "dtype": str(dtypes[name]), - } - for name, parameter in parameters - ] - descriptor.update( - tensor_count=len(parameters), - parameter_count=sum(int(parameter.numel()) for _, parameter in parameters), - parameter_layout_sha256=_hash(layout), - ) - probes = [] - probes_safe = bool(parameters) - for position in sorted({0, len(parameters) // 2, len(parameters) - 1}) if parameters else []: - name, parameter = parameters[position] - try: + } + for name, parameter in parameters + ] + descriptor.update( + tensor_count=len(parameters), + parameter_count=sum(int(parameter.numel()) for _, parameter in parameters), + parameter_layout_sha256=_hash(layout), + ) + probes = [] + probes_safe = bool(parameters) + for position in sorted({0, len(parameters) // 2, len(parameters) - 1}) if parameters else []: + name, parameter = parameters[position] + try: probes.append({"name": str(name), **_tensor_probe(parameter, dtype=dtypes[name])}) - except Exception as exc: - probes.append({"name": str(name), "error": type(exc).__name__}) - probes_safe = False - descriptor["weight_probe"] = probes - return descriptor, probes_safe - - -def _patcher_signature(patcher: Any) -> tuple[dict[str, Any], bool]: - if patcher is None: - return {"type": "missing"}, False - state, safe = _observe({ - "wrappers": getattr(patcher, "wrappers", {}) or {}, - "patches": getattr(patcher, "patches", {}) or {}, - "object_patches": getattr(patcher, "object_patches", {}) or {}, - "model_options": getattr(patcher, "model_options", {}) or {}, - }) - return { - "type": _qualified(patcher), - "model_type": _qualified(getattr(patcher, "model", None)), - "state": state, - }, safe - - -def _clip_signature(clip: Any) -> tuple[dict[str, Any], bool]: - cond_stage = getattr(clip, "cond_stage_model", None) - tokenizer = getattr(clip, "tokenizer", None) - tokenizer_wrapper = getattr(tokenizer, "qwen3vl_32b", None) - tokenizer_core = getattr(tokenizer_wrapper, "tokenizer", None) - module_value, module_safe = _module_signature(cond_stage) - patcher_value, patcher_safe = _patcher_signature(getattr(clip, "patcher", None)) - options, options_safe = _observe({ - "tokenizer_options": getattr(clip, "tokenizer_options", {}) or {}, - "layer_idx": getattr(clip, "layer_idx", None), - "use_clip_schedule": bool(getattr(clip, "use_clip_schedule", False)), - }) - tokenizer_config = { - "wrapper_type": _qualified(tokenizer), - "model_wrapper_type": _qualified(tokenizer_wrapper), - "core_type": _qualified(tokenizer_core), - } - for name in ( - "name_or_path", "vocab_size", "model_max_length", "padding_side", - "truncation_side", "bos_token_id", "eos_token_id", "pad_token_id", - ): - value = getattr(tokenizer_core, name, None) - if value is None or isinstance(value, (bool, int, float, str)): - tokenizer_config[name] = value - tokenizer_safe = tokenizer is not None and tokenizer_wrapper is not None and tokenizer_core is not None - descriptor = { - "wrapper_type": _qualified(clip), - "conditioner": module_value, - "patcher": patcher_value, - "tokenizer": tokenizer_config, - "options": options, - "runtime_observation": { - "patcher_complete": bool(patcher_safe), - "options_complete": bool(options_safe), - }, - } - return descriptor, module_safe and tokenizer_safe - - -def _video_vae_signature(video_vae: Any, *, required: bool) -> tuple[dict[str, Any], bool]: - if not required: - return {"required": False}, True - first_stage = getattr(video_vae, "first_stage_model", None) - module_value, module_safe = _module_signature(first_stage) - patcher_value, patcher_safe = _patcher_signature(getattr(video_vae, "patcher", None)) - config = { - "required": True, - "wrapper_type": _qualified(video_vae), - "first_stage": module_value, - "patcher": patcher_value, - "vae_dtype": str(getattr(video_vae, "vae_dtype", "unknown")), - "latent_channels": getattr(video_vae, "latent_channels", None), - "downscale_ratio": getattr(video_vae, "downscale_ratio", None), - "upscale_ratio": getattr(video_vae, "upscale_ratio", None), - "chunked_io": bool(getattr(first_stage, "comfy_has_chunked_io", False)), - } - observed, config_safe = _observe(config) - observed["runtime_observation"] = { - "patcher_complete": bool(patcher_safe), - "config_complete": bool(config_safe), - } - return observed, module_safe - - -def _audio_vae_signature(audio_vae: Any) -> tuple[dict[str, Any], bool]: - first_stage = getattr(audio_vae, "first_stage_model", None) - module_value, module_safe = _module_signature(first_stage) - patcher_value, patcher_safe = _patcher_signature(getattr(audio_vae, "patcher", None)) - config = { - "wrapper_type": _qualified(audio_vae), - "first_stage": module_value, - "patcher": patcher_value, - "vae_dtype": str(getattr(audio_vae, "vae_dtype", "unknown")), - "audio_sample_rate": getattr(audio_vae, "audio_sample_rate", 32000), - "latent_channels": getattr(audio_vae, "latent_channels", None), - } - observed, config_safe = _observe(config) - observed["runtime_observation"] = { - "patcher_complete": bool(patcher_safe), - "config_complete": bool(config_safe), - } - return observed, module_safe - - + except Exception as exc: + probes.append({"name": str(name), "error": type(exc).__name__}) + probes_safe = False + descriptor["weight_probe"] = probes + return descriptor, probes_safe + + +def _patcher_signature(patcher: Any) -> tuple[dict[str, Any], bool]: + if patcher is None: + return {"type": "missing"}, False + state, safe = _observe({ + "wrappers": getattr(patcher, "wrappers", {}) or {}, + "patches": getattr(patcher, "patches", {}) or {}, + "object_patches": getattr(patcher, "object_patches", {}) or {}, + "model_options": getattr(patcher, "model_options", {}) or {}, + }) + return { + "type": _qualified(patcher), + "model_type": _qualified(getattr(patcher, "model", None)), + "state": state, + }, safe + + +def _clip_signature(clip: Any) -> tuple[dict[str, Any], bool]: + cond_stage = getattr(clip, "cond_stage_model", None) + tokenizer = getattr(clip, "tokenizer", None) + tokenizer_wrapper = getattr(tokenizer, "qwen3vl_32b", None) + tokenizer_core = getattr(tokenizer_wrapper, "tokenizer", None) + module_value, module_safe = _module_signature(cond_stage) + patcher_value, patcher_safe = _patcher_signature(getattr(clip, "patcher", None)) + options, options_safe = _observe({ + "tokenizer_options": getattr(clip, "tokenizer_options", {}) or {}, + "layer_idx": getattr(clip, "layer_idx", None), + "use_clip_schedule": bool(getattr(clip, "use_clip_schedule", False)), + }) + tokenizer_config = { + "wrapper_type": _qualified(tokenizer), + "model_wrapper_type": _qualified(tokenizer_wrapper), + "core_type": _qualified(tokenizer_core), + } + for name in ( + "name_or_path", "vocab_size", "model_max_length", "padding_side", + "truncation_side", "bos_token_id", "eos_token_id", "pad_token_id", + ): + value = getattr(tokenizer_core, name, None) + if value is None or isinstance(value, (bool, int, float, str)): + tokenizer_config[name] = value + tokenizer_safe = tokenizer is not None and tokenizer_wrapper is not None and tokenizer_core is not None + descriptor = { + "wrapper_type": _qualified(clip), + "conditioner": module_value, + "patcher": patcher_value, + "tokenizer": tokenizer_config, + "options": options, + "runtime_observation": { + "patcher_complete": bool(patcher_safe), + "options_complete": bool(options_safe), + }, + } + return descriptor, module_safe and tokenizer_safe + + +def _video_vae_signature(video_vae: Any, *, required: bool) -> tuple[dict[str, Any], bool]: + if not required: + return {"required": False}, True + first_stage = getattr(video_vae, "first_stage_model", None) + module_value, module_safe = _module_signature(first_stage) + patcher_value, patcher_safe = _patcher_signature(getattr(video_vae, "patcher", None)) + config = { + "required": True, + "wrapper_type": _qualified(video_vae), + "first_stage": module_value, + "patcher": patcher_value, + "vae_dtype": str(getattr(video_vae, "vae_dtype", "unknown")), + "latent_channels": getattr(video_vae, "latent_channels", None), + "downscale_ratio": getattr(video_vae, "downscale_ratio", None), + "upscale_ratio": getattr(video_vae, "upscale_ratio", None), + "chunked_io": bool(getattr(first_stage, "comfy_has_chunked_io", False)), + } + observed, config_safe = _observe(config) + observed["runtime_observation"] = { + "patcher_complete": bool(patcher_safe), + "config_complete": bool(config_safe), + } + return observed, module_safe + + +def _audio_vae_signature(audio_vae: Any) -> tuple[dict[str, Any], bool]: + first_stage = getattr(audio_vae, "first_stage_model", None) + module_value, module_safe = _module_signature(first_stage) + patcher_value, patcher_safe = _patcher_signature(getattr(audio_vae, "patcher", None)) + config = { + "wrapper_type": _qualified(audio_vae), + "first_stage": module_value, + "patcher": patcher_value, + "vae_dtype": str(getattr(audio_vae, "vae_dtype", "unknown")), + "audio_sample_rate": getattr(audio_vae, "audio_sample_rate", 32000), + "latent_channels": getattr(audio_vae, "latent_channels", None), + } + observed, config_safe = _observe(config) + observed["runtime_observation"] = { + "patcher_complete": bool(patcher_safe), + "config_complete": bool(config_safe), + } + return observed, module_safe + + def _apply_nonce_contract( contract: dict[str, Any], *, requested_nonce: int, effective_nonce: int, ) -> dict[str, Any]: @@ -661,43 +660,43 @@ def _apply_nonce_contract( result["last_frame_hash"] = _canonical_optional_hash( result.get("last_frame_hash") ) - boundary = int(result["reroll_from_chunk"]) - if boundary <= 0: - mode = "inactive" - requested_nonce = 0 - effective_nonce = 0 - else: - mode = "explicit" if int(requested_nonce) >= 1 else "auto" - global_hash = _hash(result["global"]) - chunk_contracts = [] - chunk_hashes = [] - for position, prompt_hash in enumerate(result["prompt_hashes"]): - number = position + 1 - affected = boundary > 0 and number >= boundary - chunk_contract = { - "global_hash": global_hash, - "chunk_number": number, - "prompt_hash": str(prompt_hash), - "reroll_boundary": boundary if affected else 0, - "effective_reroll_nonce": int(effective_nonce) if affected else 0, - "last_frame_hash": str(result["last_frame_hash"]) if number == int(result["chunk_count"]) else "", - } - timeline_chunks = result.get("timeline_video_chunk_contracts") or [] - if position < len(timeline_chunks): - chunk_contract["timeline_video"] = dict(timeline_chunks[position]) - chunk_contracts.append(chunk_contract) - chunk_hashes.append(_hash(chunk_contract)) - result.update( - effective_reroll_nonce=int(effective_nonce), - chunk_contracts=chunk_contracts, - chunk_contract_hashes=chunk_hashes, - nonce_lifecycle={ - "mode": mode, - "requested_nonce": int(requested_nonce), - "effective_nonce": int(effective_nonce), - "lineage_sha256": str(result["nonce_lineage_sha256"]), - "request_sha256": str(result["nonce_request_sha256"]), - }, + boundary = int(result["reroll_from_chunk"]) + if boundary <= 0: + mode = "inactive" + requested_nonce = 0 + effective_nonce = 0 + else: + mode = "explicit" if int(requested_nonce) >= 1 else "auto" + global_hash = _hash(result["global"]) + chunk_contracts = [] + chunk_hashes = [] + for position, prompt_hash in enumerate(result["prompt_hashes"]): + number = position + 1 + affected = boundary > 0 and number >= boundary + chunk_contract = { + "global_hash": global_hash, + "chunk_number": number, + "prompt_hash": str(prompt_hash), + "reroll_boundary": boundary if affected else 0, + "effective_reroll_nonce": int(effective_nonce) if affected else 0, + "last_frame_hash": str(result["last_frame_hash"]) if number == int(result["chunk_count"]) else "", + } + timeline_chunks = result.get("timeline_video_chunk_contracts") or [] + if position < len(timeline_chunks): + chunk_contract["timeline_video"] = dict(timeline_chunks[position]) + chunk_contracts.append(chunk_contract) + chunk_hashes.append(_hash(chunk_contract)) + result.update( + effective_reroll_nonce=int(effective_nonce), + chunk_contracts=chunk_contracts, + chunk_contract_hashes=chunk_hashes, + nonce_lifecycle={ + "mode": mode, + "requested_nonce": int(requested_nonce), + "effective_nonce": int(effective_nonce), + "lineage_sha256": str(result["nonce_lineage_sha256"]), + "request_sha256": str(result["nonce_request_sha256"]), + }, ) return result @@ -785,21 +784,21 @@ def _legacy_absent_last_frame_compatible( def build_sampling_contract( - *, model: Any, model_fingerprint_value: str, clip: Any, video_vae: Any, - sampler: Any, - sigmas: torch.Tensor, prompt_plan: dict[str, Any], width: int, - height: int, chunk_seconds: float, continuity: str, - audio_continuity: bool, base_seed: int, reroll_from_chunk: int, - reroll_nonce: int, first_frame_hash: str, last_frame_hash: str, - strict_compatibility: bool, reference_contract: dict[str, Any] | None = None, - conditioning_mode: str | None = None, - upstream_graph_contract: dict[str, Any] | None = None, - upstream_graph_safe: bool | None = None, - upstream_graph_reasons: list[str] | None = None, - reference_audio_contract: dict[str, Any] | None = None, - reference_audio_vae: Any = None, - driving_audio_contract: dict[str, Any] | None = None, - driving_audio_vae: Any = None, + *, model: Any, model_fingerprint_value: str, clip: Any, video_vae: Any, + sampler: Any, + sigmas: torch.Tensor, prompt_plan: dict[str, Any], width: int, + height: int, chunk_seconds: float, continuity: str, + audio_continuity: bool, base_seed: int, reroll_from_chunk: int, + reroll_nonce: int, first_frame_hash: str, last_frame_hash: str, + strict_compatibility: bool, reference_contract: dict[str, Any] | None = None, + conditioning_mode: str | None = None, + upstream_graph_contract: dict[str, Any] | None = None, + upstream_graph_safe: bool | None = None, + upstream_graph_reasons: list[str] | None = None, + reference_audio_contract: dict[str, Any] | None = None, + reference_audio_vae: Any = None, + driving_audio_contract: dict[str, Any] | None = None, + driving_audio_vae: Any = None, reference_video_contract: dict[str, Any] | None = None, timeline_video_contract: dict[str, Any] | None = None, guide_contract: dict[str, Any] | None = None, @@ -807,144 +806,144 @@ def build_sampling_contract( ) -> tuple[dict[str, Any], bool, list[str]]: last_frame_hash = _canonical_optional_hash(last_frame_hash) model_value, model_safe = _model_signature(model, model_fingerprint_value) - clip_value, clip_safe = _clip_signature(clip) - has_first = str(first_frame_hash).lower() not in {"", "none", "null"} - has_last = str(last_frame_hash).lower() not in {"", "none", "null"} - inferred_mode = conditioning_mode_from_presence( - has_first=has_first, - has_last=has_last, - has_reference=reference_contract is not None, - ) - conditioning_mode = inferred_mode if conditioning_mode is None else str(conditioning_mode) - if conditioning_mode not in CONDITIONING_MODES: - raise RunStorageError(f"unknown conditioning mode: {conditioning_mode!r}") - if conditioning_mode != inferred_mode: - raise RunStorageError( - "conditioning mode does not match the connected image inputs: " - f"declared={conditioning_mode}, inferred={inferred_mode}" - ) - uses_video_vae = ( + clip_value, clip_safe = _clip_signature(clip) + has_first = str(first_frame_hash).lower() not in {"", "none", "null"} + has_last = str(last_frame_hash).lower() not in {"", "none", "null"} + inferred_mode = conditioning_mode_from_presence( + has_first=has_first, + has_last=has_last, + has_reference=reference_contract is not None, + ) + conditioning_mode = inferred_mode if conditioning_mode is None else str(conditioning_mode) + if conditioning_mode not in CONDITIONING_MODES: + raise RunStorageError(f"unknown conditioning mode: {conditioning_mode!r}") + if conditioning_mode != inferred_mode: + raise RunStorageError( + "conditioning mode does not match the connected image inputs: " + f"declared={conditioning_mode}, inferred={inferred_mode}" + ) + uses_video_vae = ( conditioning_mode_uses_video_vae(conditioning_mode) or reference_video_contract is not None or timeline_video_contract is not None or guide_contract is not None - ) - if uses_video_vae: - video_vae_value, video_vae_safe = _video_vae_signature( - video_vae, required=True - ) - else: - video_vae_value, video_vae_safe = None, True - sampler_value, sampler_safe = _sampler_signature(sampler) - if reference_audio_contract is not None: - audio_vae_value, audio_vae_safe = _audio_vae_signature(reference_audio_vae) - else: - audio_vae_value, audio_vae_safe = None, True - if driving_audio_contract is not None: - driving_audio_vae_value, driving_audio_vae_safe = _audio_vae_signature( - driving_audio_vae - ) - else: - driving_audio_vae_value, driving_audio_vae_safe = None, True - if not torch.is_tensor(sigmas) or sigmas.ndim != 1: - raise RunStorageError("Run Storage requires a one-dimensional SIGMAS tensor") - chunks = int(prompt_plan["chunks"]) - prompt_hashes = [str(value) for value in prompt_plan["hashes"]] - boundary = int(reroll_from_chunk) - graph_authoritative = upstream_graph_contract is not None - if graph_authoritative: - routes = upstream_graph_contract.get("routes", {}) - model_value = { - "runtime": model_value, - "graph_route": routes.get("model"), - } - clip_value = { - "runtime": clip_value, - "graph_route": routes.get("clip"), - } - if uses_video_vae: - video_vae_value = { - "runtime": video_vae_value, - "graph_route": routes.get("video_vae"), - } - if reference_audio_contract is not None: - audio_vae_value = { - "runtime": audio_vae_value, - "graph_route": routes.get("reference_audio_vae"), - } - if driving_audio_contract is not None: - driving_audio_vae_value = { - "runtime": driving_audio_vae_value, - "graph_route": routes.get("audio_vae"), - } - global_contract = { - "sampling_contract_version": SAMPLING_CONTRACT_VERSION, - "conditioning_mode": conditioning_mode, - "model": model_value, - "clip": clip_value, - "sampler": sampler_value, - "sigmas": _tensor_exact(sigmas), - "width": int(width), "height": int(height), - "chunk_seconds": float(chunk_seconds), - "continuity": str(continuity), - "audio_continuity": bool(audio_continuity), - "base_seed": int(base_seed), - "strict_compatibility": bool(strict_compatibility), - "continuum_interop_api": 1, - "actual_prefix_steps": CONTINUUM_ACTUAL_PREFIX_STEPS, - } - if graph_authoritative: - global_contract["upstream_graph"] = dict(upstream_graph_contract) - if execution_semantics is not None: - global_contract["execution_semantics"] = dict(execution_semantics) - if uses_video_vae: - global_contract["video_vae"] = video_vae_value - if has_first: - global_contract["first_frame_hash"] = str(first_frame_hash) - if reference_contract is not None: - global_contract["reference"] = dict(reference_contract) - if has_first or has_last: - from .reference import HYBRID_PRESENTATION_VERSION - - picture_order: list[str] = [] - if has_first: - picture_order.append("first_frame") - if has_last: - picture_order.append("last_frame") - picture_order.extend( - f"reference_image_{index}" - for index in range(1, int(reference_contract.get("count", 0)) + 1) - ) - global_contract["hybrid_qwen_presentation"] = { - "version": HYBRID_PRESENTATION_VERSION, - "picture_order": picture_order, - } - if reference_audio_contract is not None: - global_contract["reference_audio"] = dict(reference_audio_contract) - global_contract["reference_audio_vae"] = audio_vae_value - if driving_audio_contract is not None: - global_contract["driving_audio"] = dict(driving_audio_contract) - global_contract["driving_audio_vae"] = driving_audio_vae_value + ) + if uses_video_vae: + video_vae_value, video_vae_safe = _video_vae_signature( + video_vae, required=True + ) + else: + video_vae_value, video_vae_safe = None, True + sampler_value, sampler_safe = _sampler_signature(sampler) + if reference_audio_contract is not None: + audio_vae_value, audio_vae_safe = _audio_vae_signature(reference_audio_vae) + else: + audio_vae_value, audio_vae_safe = None, True + if driving_audio_contract is not None: + driving_audio_vae_value, driving_audio_vae_safe = _audio_vae_signature( + driving_audio_vae + ) + else: + driving_audio_vae_value, driving_audio_vae_safe = None, True + if not torch.is_tensor(sigmas) or sigmas.ndim != 1: + raise RunStorageError("Run Storage requires a one-dimensional SIGMAS tensor") + chunks = int(prompt_plan["chunks"]) + prompt_hashes = [str(value) for value in prompt_plan["hashes"]] + boundary = int(reroll_from_chunk) + graph_authoritative = upstream_graph_contract is not None + if graph_authoritative: + routes = upstream_graph_contract.get("routes", {}) + model_value = { + "runtime": model_value, + "graph_route": routes.get("model"), + } + clip_value = { + "runtime": clip_value, + "graph_route": routes.get("clip"), + } + if uses_video_vae: + video_vae_value = { + "runtime": video_vae_value, + "graph_route": routes.get("video_vae"), + } + if reference_audio_contract is not None: + audio_vae_value = { + "runtime": audio_vae_value, + "graph_route": routes.get("reference_audio_vae"), + } + if driving_audio_contract is not None: + driving_audio_vae_value = { + "runtime": driving_audio_vae_value, + "graph_route": routes.get("audio_vae"), + } + global_contract = { + "sampling_contract_version": SAMPLING_CONTRACT_VERSION, + "conditioning_mode": conditioning_mode, + "model": model_value, + "clip": clip_value, + "sampler": sampler_value, + "sigmas": _tensor_exact(sigmas), + "width": int(width), "height": int(height), + "chunk_seconds": float(chunk_seconds), + "continuity": str(continuity), + "audio_continuity": bool(audio_continuity), + "base_seed": int(base_seed), + "strict_compatibility": bool(strict_compatibility), + "continuum_interop_api": 1, + "actual_prefix_steps": CONTINUUM_ACTUAL_PREFIX_STEPS, + } + if graph_authoritative: + global_contract["upstream_graph"] = dict(upstream_graph_contract) + if execution_semantics is not None: + global_contract["execution_semantics"] = dict(execution_semantics) + if uses_video_vae: + global_contract["video_vae"] = video_vae_value + if has_first: + global_contract["first_frame_hash"] = str(first_frame_hash) + if reference_contract is not None: + global_contract["reference"] = dict(reference_contract) + if has_first or has_last: + from .reference import HYBRID_PRESENTATION_VERSION + + picture_order: list[str] = [] + if has_first: + picture_order.append("first_frame") + if has_last: + picture_order.append("last_frame") + picture_order.extend( + f"reference_image_{index}" + for index in range(1, int(reference_contract.get("count", 0)) + 1) + ) + global_contract["hybrid_qwen_presentation"] = { + "version": HYBRID_PRESENTATION_VERSION, + "picture_order": picture_order, + } + if reference_audio_contract is not None: + global_contract["reference_audio"] = dict(reference_audio_contract) + global_contract["reference_audio_vae"] = audio_vae_value + if driving_audio_contract is not None: + global_contract["driving_audio"] = dict(driving_audio_contract) + global_contract["driving_audio_vae"] = driving_audio_vae_value if reference_video_contract is not None: global_contract["reference_video"] = dict(reference_video_contract) if guide_contract is not None: global_contract["guide"] = dict(guide_contract) - timeline_chunk_contracts = [] - if timeline_video_contract is not None: - timeline_value = dict(timeline_video_contract) - timeline_chunk_contracts = list(timeline_value.pop("chunk_slices", [])) - if len(timeline_chunk_contracts) != chunks: - raise RunStorageError( - "Timeline Video contract does not match the configured chunk count" - ) - global_contract["timeline_video"] = timeline_value + timeline_chunk_contracts = [] + if timeline_video_contract is not None: + timeline_value = dict(timeline_video_contract) + timeline_chunk_contracts = list(timeline_value.pop("chunk_slices", [])) + if len(timeline_chunk_contracts) != chunks: + raise RunStorageError( + "Timeline Video contract does not match the configured chunk count" + ) + global_contract["timeline_video"] = timeline_value contract = { "global": global_contract, "chunk_count": chunks, - "prompt_mode": str(prompt_plan["mode"]), - "prompt_hashes": prompt_hashes, - "reroll_from_chunk": boundary, - "last_frame_hash": str(last_frame_hash), + "prompt_mode": str(prompt_plan["mode"]), + "prompt_hashes": prompt_hashes, + "reroll_from_chunk": boundary, + "last_frame_hash": str(last_frame_hash), } lineage_sha256 = _nonce_lineage_hash( contract, @@ -957,131 +956,131 @@ def build_sampling_contract( requested_nonce=int(reroll_nonce), effective_nonce=int(reroll_nonce) if boundary > 0 else 0, ) - reasons = list(upstream_graph_reasons or []) if graph_authoritative else [] - if not model_safe: - reasons.append("MODEL wrapper/patch contract is not completely observable") - if not sampler_safe: - reasons.append("SAMPLER function/options are not completely observable") - if not clip_safe: - reasons.append("CLIP/Qwen encoder contract is not completely observable") - if not video_vae_safe: - reasons.append("Video VAE contract is not completely observable") - if not audio_vae_safe: - reasons.append("Reference Audio VAE contract is not completely observable") - if not driving_audio_vae_safe: - reasons.append("Driving Audio VAE contract is not completely observable") - graph_safe = bool(upstream_graph_safe) if graph_authoritative else True - return contract, model_safe and clip_safe and video_vae_safe and audio_vae_safe and driving_audio_vae_safe and sampler_safe and graph_safe, reasons - - -def revision_identity(contract: dict[str, Any]) -> tuple[str, str]: - full = _hash(contract) - return full[:16], full - - -def _pid_exists_windows(pid: int) -> bool: - """Probe a Windows PID without sending a console event or terminating it.""" - import ctypes - from ctypes import wintypes - - process_query_limited_information = 0x1000 - error_access_denied = 5 - kernel32 = ctypes.WinDLL("kernel32", use_last_error=True) - kernel32.OpenProcess.argtypes = ( - wintypes.DWORD, - wintypes.BOOL, - wintypes.DWORD, - ) - kernel32.OpenProcess.restype = wintypes.HANDLE - kernel32.CloseHandle.argtypes = (wintypes.HANDLE,) - kernel32.CloseHandle.restype = wintypes.BOOL - ctypes.set_last_error(0) - handle = kernel32.OpenProcess( - process_query_limited_information, - False, - int(pid), - ) - if handle: - kernel32.CloseHandle(handle) - return True - return ctypes.get_last_error() == error_access_denied - - -def _pid_exists(pid: int) -> bool: - if pid <= 0: - return False - if pid == os.getpid(): - return True - if os.name == "nt": - return _pid_exists_windows(pid) - try: - os.kill(pid, 0) - except ProcessLookupError: - return False - except PermissionError: - return True - except OSError: - return False - return True - - -class _RunLock: - def __init__(self, path: Path): - self.path = path - self.token = uuid.uuid4().hex - self.acquired = False - - def acquire(self) -> None: - self.path.parent.mkdir(parents=True, exist_ok=True) - payload = { - "pid": os.getpid(), "hostname": socket.gethostname(), - "started_utc": _now(), "token": self.token, - } - encoded = (_canonical(payload) + "\n").encode("utf-8") - for _ in range(2): - try: - descriptor = os.open(self.path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600) - except FileExistsError: - try: - existing = _read_json(self.path) - except Exception as exc: - raise RunStorageError(f"Run Storage lock exists and is unreadable: {self.path}") from exc - if str(existing.get("hostname", "")) == socket.gethostname() and not _pid_exists(int(existing.get("pid", -1))): - self.path.unlink() - continue - raise RunStorageError( - f"Run Name is locked by pid={existing.get('pid')} host={existing.get('hostname')}" - ) - else: - try: - os.write(descriptor, encoded) - os.fsync(descriptor) - finally: - os.close(descriptor) - self.acquired = True - return - raise RunStorageError("failed to recover stale Run Storage lock") - - def release(self) -> None: - if not self.acquired: - return - try: - existing = _read_json(self.path) - if existing.get("token") == self.token: - self.path.unlink() - finally: - self.acquired = False - - + reasons = list(upstream_graph_reasons or []) if graph_authoritative else [] + if not model_safe: + reasons.append("MODEL wrapper/patch contract is not completely observable") + if not sampler_safe: + reasons.append("SAMPLER function/options are not completely observable") + if not clip_safe: + reasons.append("CLIP/Qwen encoder contract is not completely observable") + if not video_vae_safe: + reasons.append("Video VAE contract is not completely observable") + if not audio_vae_safe: + reasons.append("Reference Audio VAE contract is not completely observable") + if not driving_audio_vae_safe: + reasons.append("Driving Audio VAE contract is not completely observable") + graph_safe = bool(upstream_graph_safe) if graph_authoritative else True + return contract, model_safe and clip_safe and video_vae_safe and audio_vae_safe and driving_audio_vae_safe and sampler_safe and graph_safe, reasons + + +def revision_identity(contract: dict[str, Any]) -> tuple[str, str]: + full = _hash(contract) + return full[:16], full + + +def _pid_exists_windows(pid: int) -> bool: + """Probe a Windows PID without sending a console event or terminating it.""" + import ctypes + from ctypes import wintypes + + process_query_limited_information = 0x1000 + error_access_denied = 5 + kernel32 = ctypes.WinDLL("kernel32", use_last_error=True) + kernel32.OpenProcess.argtypes = ( + wintypes.DWORD, + wintypes.BOOL, + wintypes.DWORD, + ) + kernel32.OpenProcess.restype = wintypes.HANDLE + kernel32.CloseHandle.argtypes = (wintypes.HANDLE,) + kernel32.CloseHandle.restype = wintypes.BOOL + ctypes.set_last_error(0) + handle = kernel32.OpenProcess( + process_query_limited_information, + False, + int(pid), + ) + if handle: + kernel32.CloseHandle(handle) + return True + return ctypes.get_last_error() == error_access_denied + + +def _pid_exists(pid: int) -> bool: + if pid <= 0: + return False + if pid == os.getpid(): + return True + if os.name == "nt": + return _pid_exists_windows(pid) + try: + os.kill(pid, 0) + except ProcessLookupError: + return False + except PermissionError: + return True + except OSError: + return False + return True + + +class _RunLock: + def __init__(self, path: Path): + self.path = path + self.token = uuid.uuid4().hex + self.acquired = False + + def acquire(self) -> None: + self.path.parent.mkdir(parents=True, exist_ok=True) + payload = { + "pid": os.getpid(), "hostname": socket.gethostname(), + "started_utc": _now(), "token": self.token, + } + encoded = (_canonical(payload) + "\n").encode("utf-8") + for _ in range(2): + try: + descriptor = os.open(self.path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600) + except FileExistsError: + try: + existing = _read_json(self.path) + except Exception as exc: + raise RunStorageError(f"Run Storage lock exists and is unreadable: {self.path}") from exc + if str(existing.get("hostname", "")) == socket.gethostname() and not _pid_exists(int(existing.get("pid", -1))): + self.path.unlink() + continue + raise RunStorageError( + f"Run Name is locked by pid={existing.get('pid')} host={existing.get('hostname')}" + ) + else: + try: + os.write(descriptor, encoded) + os.fsync(descriptor) + finally: + os.close(descriptor) + self.acquired = True + return + raise RunStorageError("failed to recover stale Run Storage lock") + + def release(self) -> None: + if not self.acquired: + return + try: + existing = _read_json(self.path) + if existing.get("token") == self.token: + self.path.unlink() + finally: + self.acquired = False + + def _entry_metadata(entry: dict[str, Any]) -> dict[str, Any]: - return { - "sequence_index": int(entry["sequence_index"]), - "clip_index": int(entry["clip_index"]), - "prompt_hash": str(entry["prompt_hash"]), - "seed": int(entry["seed"]), - "context_frames": int(entry["context_frames"]), - "motion_score": float(entry["motion_score"]), - "plan": dict(entry["plan"]), + return { + "sequence_index": int(entry["sequence_index"]), + "clip_index": int(entry["clip_index"]), + "prompt_hash": str(entry["prompt_hash"]), + "seed": int(entry["seed"]), + "context_frames": int(entry["context_frames"]), + "motion_score": float(entry["motion_score"]), + "plan": dict(entry["plan"]), } @@ -1150,25 +1149,25 @@ def _storage_revision_identity( class RunStorageController: - def __init__(self, run_name: str): - self.run_name = sanitize_run_name(run_name) - self.run_root = _output_root() / "h3_continuum" / "runs" / self.run_name - self.revisions_root = self.run_root / "revisions" - self.lock = _RunLock(self.run_root / ".lock") - self.context_token = None - self.contract: dict[str, Any] | None = None - self.contract_sha256 = "" - self.revision_id = "" - self.revision_root: Path | None = None - self.manifest: dict[str, Any] | None = None - self.prompts: list[str] = [] - self.reused_count = 0 - self.generated_count = 0 - self.disabled_reasons: list[str] = [] - self.notes: list[str] = [] - self.resume_safe = False - self.effective_reroll_nonce = 0 - self.nonce_decision = "inactive" + def __init__(self, run_name: str): + self.run_name = sanitize_run_name(run_name) + self.run_root = _output_root() / "h3_continuum" / "runs" / self.run_name + self.revisions_root = self.run_root / "revisions" + self.lock = _RunLock(self.run_root / ".lock") + self.context_token = None + self.contract: dict[str, Any] | None = None + self.contract_sha256 = "" + self.revision_id = "" + self.revision_root: Path | None = None + self.manifest: dict[str, Any] | None = None + self.prompts: list[str] = [] + self.reused_count = 0 + self.generated_count = 0 + self.disabled_reasons: list[str] = [] + self.notes: list[str] = [] + self.resume_safe = False + self.effective_reroll_nonce = 0 + self.nonce_decision = "inactive" self.prompt_graph: dict[str, Any] | None = None self.sampler_node_id: str | None = None self.review_generation_mode: str | None = None @@ -1186,7 +1185,13 @@ class RunStorageController: self.selected_take_revision: dict[str, Any] | None = None self.pending_branch_cut: dict[str, Any] | None = None self.storage_revision_id_override = "" - + # Lock-scoped metadata only. Never cache tensors or skip raw integrity checks. + self._manifest_snapshot = None + self._plan_import = None + self.io_metrics = {"manifest_scans": 0, "manifest_reads": 0, + "raw_loads": 0, "raw_bytes": 0, + "manifest_seconds": 0.0, "raw_seconds": 0.0} + def set_prompt_graph(self, prompt: Any, unique_id: Any) -> None: self.prompt_graph = prompt if isinstance(prompt, dict) else None self.sampler_node_id = None if unique_id is None else str(unique_id) @@ -1217,41 +1222,48 @@ class RunStorageController: raise RunStorageError( "Use This Take / Continue From Here requires a group and revision ID" ) - - def __enter__(self) -> "RunStorageController": - self.lock.acquire() - self.context_token = _ACTIVE.set(self) - return self - - def __exit__(self, exc_type, exc, traceback) -> None: - try: + + def __enter__(self) -> "RunStorageController": + self.lock.acquire() + self._manifest_snapshot = None + self.context_token = _ACTIVE.set(self) + return self + + def __exit__(self, exc_type, exc, traceback) -> None: + try: if exc is not None and self.manifest is not None: self.manifest.pop("review_unit", None) self.manifest.pop("review_pause_reason", None) self.manifest.update(status="interrupted", updated_utc=_now(), last_error=f"{type(exc).__name__}: {exc}"[:2048]) self._write_manifest() self._write_project() - finally: - if self.context_token is not None: - _ACTIVE.reset(self.context_token) - self.context_token = None - self.lock.release() - - def _manifest_path(self) -> Path: - if self.revision_root is None: - raise RunStorageError("Run Storage revision is not prepared") - return self.revision_root / "manifest.json" - - def _write_manifest(self) -> None: - if self.manifest is not None: - _write_json(self._manifest_path(), self.manifest) - + finally: + if self.context_token is not None: + _ACTIVE.reset(self.context_token) + self.context_token = None + self._manifest_snapshot = None + self._plan_import = None + self.lock.release() + + def _manifest_path(self) -> Path: + if self.revision_root is None: + raise RunStorageError("Run Storage revision is not prepared") + return self.revision_root / "manifest.json" + + def _write_manifest(self) -> None: + if self.manifest is not None: + _write_json(self._manifest_path(), self.manifest) + self._manifest_snapshot = None + def _read_manifests(self) -> dict[str, dict[str, Any]]: + if self.context_token is not None and self._manifest_snapshot is not None: + return self._manifest_snapshot + started = time.perf_counter() manifests: dict[str, dict[str, Any]] = {} - if not self.revisions_root.exists(): - return manifests + self.io_metrics["manifest_scans"] += 1 for path in sorted(self.revisions_root.glob("*/manifest.json")): try: + self.io_metrics["manifest_reads"] += 1 value = _read_json(path) _manifest_sampling_identity(value) revision_id = str(value.get("revision_id", "")) @@ -1260,6 +1272,9 @@ class RunStorageController: manifests[revision_id] = value except Exception as exc: self.notes.append(f"provenance manifest {path.parent.name} rejected: {exc}") + self.io_metrics["manifest_seconds"] += time.perf_counter() - started + if self.context_token is not None: + self._manifest_snapshot = manifests return manifests def _manifest_provenance_chain( @@ -1309,8 +1324,8 @@ class RunStorageController: group=group, variation_nonce=variation_nonce, created_utc=str( - source_manifest.get("updated_utc") - or source_manifest.get("created_utc") + source_manifest.get("created_utc") + or source_manifest.get("updated_utc") or "" ), storage_revision_id=source_id, @@ -1478,28 +1493,37 @@ class RunStorageController: "revisions": revisions, }, ) - - def _load_entry(self, record: dict[str, Any], prompt: str) -> dict[str, Any]: - source = str(record["storage_revision_id"]) - filename = str(record["filename"]) - if Path(filename).name != filename: - raise RunStorageError("stored chunk filename is invalid") - path = self.revisions_root / source / "chunks" / filename - if path.stat().st_size != int(record["file_size"]): - raise RunStorageError(f"stored chunk size mismatch: {filename}") - expected_sha256 = str(record.get("file_sha256", "")) - if not expected_sha256: - raise RunStorageError(f"stored chunk SHA-256 is missing: {filename}") - if _file_sha256(path) != expected_sha256: - raise RunStorageError(f"stored chunk SHA-256 mismatch: {filename}") - with safe_open(str(path), framework="pt", device="cpu") as handle: - if set(handle.keys()) != {"audio", "video"}: - raise RunStorageError(f"stored chunk tensors are invalid: {filename}") - video, audio = handle.get_tensor("video"), handle.get_tensor("audio") - entry = dict(record["entry"]) - entry.update(prompt=str(prompt), video=video, audio=audio, reused=False) - return validate_chunk_entry(entry) - + + def _load_entry(self, record: dict[str, Any], prompt: str) -> dict[str, Any]: + source = str(record["storage_revision_id"]) + filename = str(record["filename"]) + if Path(filename).name != filename or any(c in filename for c in "/\\") or filename in {"", ".", ".."}: + raise RunStorageError("stored chunk filename is invalid") + if source in {"", ".", ".."} or any(c in source for c in "/\\"): + raise RunStorageError("stored revision directory is invalid") + path = self.revisions_root / source / "chunks" / filename + if not path.resolve().is_relative_to(self.revisions_root.resolve()): + raise RunStorageError("stored chunk escapes the Run Storage directory") + started = time.perf_counter() + if path.stat().st_size != int(record["file_size"]): + raise RunStorageError(f"stored chunk size mismatch: {filename}") + expected_sha256 = str(record.get("file_sha256", "")) + if not expected_sha256: + raise RunStorageError(f"stored chunk SHA-256 is missing: {filename}") + if _file_sha256(path) != expected_sha256: + raise RunStorageError(f"stored chunk SHA-256 mismatch: {filename}") + self.io_metrics["raw_bytes"] += int(record["file_size"]) + self.io_metrics["raw_loads"] += 1 + with safe_open(str(path), framework="pt", device="cpu") as handle: + if set(handle.keys()) != {"audio", "video"}: + raise RunStorageError(f"stored chunk tensors are invalid: {filename}") + video, audio = handle.get_tensor("video"), handle.get_tensor("audio") + entry = dict(record["entry"]) + entry.update(prompt=str(prompt), video=video, audio=audio, reused=False) + result = validate_chunk_entry(entry) + self.io_metrics["raw_seconds"] += time.perf_counter() - started + return result + def _valid_prefix( self, manifest: dict[str, Any], @@ -1527,8 +1551,8 @@ class RunStorageController: ) if stored[position] != current and not compatible_absent_last_frame: break - if position >= len(records) or int(records[position].get("sequence_index", -1)) != position: - break + if position >= len(records) or int(records[position].get("sequence_index", -1)) != position: + break try: entry = self._load_entry(records[position], self.prompts[position]) except Exception as exc: @@ -1602,6 +1626,166 @@ class RunStorageController: entries.append(entry) return entries, records[:len(entries)] + def _compatible_plan_prefix( + self, manifest: dict[str, Any], current_contract: dict[str, Any], + *, stop_before: int = 0, + ) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: + """Certify a prefix for import, not for cross-lineage Take selection. + + Original provenance is validated first. Every reused physical group must + retain its topology and actual producing per-chunk contract. New plans + get their own raw copies below; no foreign lineage is spliced into a DAG. + """ + manifests = self._read_manifests() + source_contract = manifest.get("contract") or {} + _manifest_sampling_identity(manifest) + if _hash(source_contract.get("global")) != _hash(current_contract.get("global")): + return [], [] + chain = self._manifest_provenance_chain(manifest, manifests) + records = list(manifest.get("chunks") or []) + allowed = {g.start: g for g in physical_groups( + chunks=int(current_contract["chunk_count"]), + terminal_merge_enabled=_terminal_merge_enabled(current_contract), + )} + accepted = [] + requested_by_producer = {} + for revision in chain: + group = revision["group"] + expected = allowed.get(int(group["start"])) + if (expected is None or expected.as_metadata() != group + or (stop_before > 0 and expected.end >= stop_before)): + break + group_records = records[expected.start - 1:expected.end] + if len(group_records) != expected.end - expected.start + 1: + break + compatible = True + for position, record in zip(range(expected.start - 1, expected.end), group_records): + producer = manifests.get(str(record.get("storage_revision_id", ""))) + if producer is None: + compatible = False + break + producing = producer.get("contract") or {} + hashes = producing.get("chunk_contract_hashes") or [] + # Accepted earlier Takes can come from several nonce branches. + # Compare each producing contract against the new plan while + # preserving that producer's verified variation, not the latest + # branch's nonce for the entire ancestry. + producer_id = str(record["storage_revision_id"]) + if producer_id not in requested_by_producer: + requested_by_producer[producer_id] = _apply_reroll_branch_contract( + current_contract, + boundary=int(producing.get("reroll_from_chunk", 0)), + requested_nonce=int(producing.get("effective_reroll_nonce", 0)), + effective_nonce=int(producing.get("effective_reroll_nonce", 0)), + )["chunk_contract_hashes"] + requested_hashes = requested_by_producer[producer_id] + producer_records = producer.get("chunks") or [] + if (position >= len(hashes) or position >= len(requested_hashes) + or hashes[position] != requested_hashes[position] + or position >= len(producer_records) + or producer_records[position] != record): + compatible = False + break + if not compatible: + break + accepted.extend(group_records) + entries = [] + # Only now load the certified prefix. A corrupt group never becomes reusable. + for position, record in enumerate(accepted): + item = self._load_entry(record, self.prompts[position]) + if item["prompt_hash"] != current_contract["prompt_hashes"][position]: + raise RunStorageError("imported prefix prompt does not match its producing contract") + entries.append(item) + return entries, accepted + + def _find_plan_import( + self, contract: dict[str, Any], *, stop_before: int = 0, + ) -> dict[str, Any] | None: + """Find a verified plan prefix, stopping before explicit regeneration.""" + if stop_before == 1: + return None + manifests = self._read_manifests() + # A matching plan already owns its history. Do not reload an older plan + # merely because that older plan also supplies a compatible prefix. + if any((m.get("contract") or {}).get("nonce_lineage_sha256") + == contract.get("nonce_lineage_sha256") for m in manifests.values()): + return None + canonical_id = "" + try: + project = _read_json(self.run_root / "project.json") + canonical_id = str(project.get("canonical_storage_revision_id", "")) + selected = manifests.get(canonical_id) or {} + expected_chain = (selected.get("branch_provenance") or {}).get("active_chain") + if expected_chain is not None and project.get("canonical_chain") != expected_chain: + canonical_id = "" + except (OSError, ValueError, RunStorageError): + pass + ordered = sorted(manifests.values(), key=lambda m: ( + str(m.get("revision_id", "")) == canonical_id, + int((m.get("branch_provenance") or {}).get("canonical_sequence", 0)), + str(m.get("updated_utc", "")), str(m.get("revision_id", "")), + ), reverse=True) + for manifest in ordered: + source = manifest.get("contract") or {} + if (manifest.get("status") not in {"complete", "review_ready", "interrupted"} + or source.get("nonce_lineage_sha256") == contract.get("nonce_lineage_sha256") + or _hash(source.get("global")) != _hash(contract.get("global"))): + continue + # Preserve accepted variations when extending/editing a plan. Explicit + # regeneration still uses the existing nonce resolver, not this path. + boundary = int(source.get("reroll_from_chunk", 0)) + nonce = int(source.get("effective_reroll_nonce", 0)) + if boundary > int(contract["chunk_count"]): + boundary = nonce = 0 + requested = _apply_reroll_branch_contract( + contract, boundary=boundary, requested_nonce=nonce, effective_nonce=nonce, + ) + try: + entries, records = self._compatible_plan_prefix( + manifest, requested, stop_before=stop_before, + ) + except (RunStorageError, ValueError, OSError) as exc: + self.notes.append(f"plan prefix {manifest.get('revision_id', '')} rejected: {exc}") + continue + if not entries: + continue + if boundary > len(entries): + boundary = nonce = 0 + requested = _apply_reroll_branch_contract( + contract, boundary=0, requested_nonce=0, effective_nonce=0, + ) + groups = physical_groups(chunks=int(contract["chunk_count"]), + terminal_merge_enabled=_terminal_merge_enabled(contract)) + unit = next(g for g in groups if g.end == len(entries)) + return {"revision_id": str(manifest["revision_id"]), + "status": "complete" if len(entries) == int(contract["chunk_count"]) else "review_ready", + "validated_prefix_count": len(entries), "review_unit": unit.as_metadata(), + "branch_regenerate_from": boundary, "effective_reroll_nonce": nonce, + "manifest": manifest, "entries": entries, "records": records, + "contract": requested, "updated_utc": str(manifest.get("updated_utc", ""))} + return None + + def _adopt_plan_prefix(self, imported: dict[str, Any]) -> list[dict[str, Any]]: + """Copy verified tensors into the new plan; keep every old revision intact.""" + self.manifest["prefix_import"] = { + "version": 1, "source_revision_id": imported["revision_id"], + "source_contract_sha256": imported["manifest"]["contract_sha256"], + "records": [ + {"sequence_index": position, + "storage_revision_id": original["storage_revision_id"], + "filename": original["filename"], "file_sha256": original["file_sha256"]} + for position, original in enumerate(imported["records"]) + ], + } + self._write_manifest() + records = [] + for position, entry in enumerate(imported["entries"]): + self.commit_chunk(entry, position=position) + records.append(dict(self.manifest["chunks"][-1])) + self.generated_count = 0 # Copies are reused work, never new Sampling. + self.notes.append(f"Imported {len(records)} verified prefix chunks into the new plan; originals preserved") + return records + def _highest_lineage_nonce(self, lineage_sha256: str) -> int: highest = 0 for manifest in self._read_manifests().values(): @@ -1848,21 +2032,27 @@ class RunStorageController: if not self.revisions_root.exists(): return None compatible_lineage = str(contract.get("nonce_lineage_sha256", "")) - heads: list[dict[str, Any]] = [] mismatched_contracts: list[tuple[str, dict]] = [] - paths = sorted( - self.revisions_root.glob("*/manifest.json"), - key=lambda path: path.parent.name, - ) - for path in paths: - try: - manifest = _read_json(path) - except Exception as exc: - self.notes.append(f"review head {path.parent.name} rejected: {exc}") - continue + manifests = self._read_manifests() + canonical_id = "" + try: + project = _read_json(self.run_root / "project.json") + canonical_id = str(project.get("canonical_storage_revision_id", "")) + selected = manifests.get(canonical_id) or {} + expected_chain = (selected.get("branch_provenance") or {}).get("active_chain") + if expected_chain is not None and project.get("canonical_chain") != expected_chain: + canonical_id = "" + except (OSError, ValueError, RunStorageError): + pass + ordered = sorted(manifests.items(), key=lambda item: ( + item[0] == canonical_id, + int((item[1].get("contract") or {}).get("effective_reroll_nonce", 0)), + str(item[1].get("updated_utc", "")), item[0], + ), reverse=True) + for revision_id, manifest in ordered: stored_contract = manifest.get("contract") or {} if str(stored_contract.get("nonce_lineage_sha256", "")) != compatible_lineage: - mismatched_contracts.append((path.parent.name, stored_contract)) + mismatched_contracts.append((revision_id, stored_contract)) continue try: head = self._validated_review_head( @@ -1870,7 +2060,7 @@ class RunStorageController: current_contract=contract, ) except Exception as exc: - self.notes.append(f"review head {path.parent.name} rejected: {exc}") + self.notes.append(f"review head {revision_id} rejected: {exc}") continue if smart_regenerate_only and not ( head["status"] == REVISION_STATUS_REVIEW_READY @@ -1880,52 +2070,24 @@ class RunStorageController: ) ): continue - heads.append(head) - if not heads: - # Explain a missing head without changing which heads are reusable. - # Evaluate only after lookup fails; successful runs are unaffected. - candidates = [] - for revision_id, stored_contract in mismatched_contracts: - try: - delta = _review_contract_mismatches(stored_contract, contract) - candidates.append((len(delta), revision_id, delta)) - except Exception as exc: - self.notes.append( - f"review head {revision_id} diagnostic unavailable: {type(exc).__name__}" - ) - for _, revision_id, delta in sorted(candidates)[:3]: - detail = "; ".join(delta[:12]) or "lineage digest differs; inspect stored integrity" - if len(delta) > 12: - detail += f"; {len(delta) - 12} more differing sections" - self.notes.append(f"review head {revision_id} incompatible: {detail}") - return None - _, catalog, chains = self._provenance_catalog( - lineage_sha256=compatible_lineage, - ) - canonical_storage_revision_id, _ = self._canonical_project_selection( - catalog=catalog, - chains=chains, - ) - if canonical_storage_revision_id: - for head in heads: - if head["revision_id"] == canonical_storage_revision_id: - if smart_regenerate_only and not ( - head["status"] == REVISION_STATUS_REVIEW_READY - or ( - head["status"] == REVISION_STATUS_COMPLETE - and head["review_unit"] is not None - ) - ): - break - return head - return max( - heads, - key=lambda head: ( - int(head["effective_reroll_nonce"]), - str(head["updated_utc"]), - str(head["revision_id"]), - ), - ) + return head + # Explain a missing head without changing which heads are reusable. + # Evaluate only after lookup fails; successful runs are unaffected. + candidates = [] + for revision_id, stored_contract in mismatched_contracts: + try: + delta = _review_contract_mismatches(stored_contract, contract) + candidates.append((len(delta), revision_id, delta)) + except Exception as exc: + self.notes.append( + f"review head {revision_id} diagnostic unavailable: {type(exc).__name__}" + ) + for _, revision_id, delta in sorted(candidates)[:3]: + detail = "; ".join(delta[:12]) or "lineage digest differs; inspect stored integrity" + if len(delta) > 12: + detail += f"; {len(delta) - 12} more differing sections" + self.notes.append(f"review head {revision_id} incompatible: {detail}") + return None def _resolve_review_contract( self, @@ -1999,6 +2161,11 @@ class RunStorageController: contract, smart_regenerate_only=smart_only, ) + if head is None and not smart_only and resume_safe: + self._plan_import = self._find_plan_import( + contract, stop_before=self.review_manual_regenerate_from, + ) + head = self._plan_import self.review_head = head self.inherited_review_unit = ( None if head is None or head.get("review_unit") is None @@ -2063,102 +2230,166 @@ class RunStorageController: ) self.review_execution = execution return resolved, effective_nonce, decision - - def _resolve_effective_nonce( - self, contract: dict[str, Any], *, requested_nonce: int, resume_safe: bool, - ) -> tuple[int, str]: - boundary = int(contract["reroll_from_chunk"]) - requested = int(requested_nonce) - if boundary <= 0: - return 0, "inactive" - if requested >= 1: - return requested, "explicit" - lineage = str(contract["nonce_lineage_sha256"]) - request = str(contract["nonce_request_sha256"]) - highest = 0 - matching: dict[int, dict[str, Any]] = {} - if self.revisions_root.exists(): - for path in self.revisions_root.glob("*/manifest.json"): - try: - manifest = _read_json(path) - lifecycle = manifest.get("nonce_lifecycle") or (manifest.get("contract") or {}).get("nonce_lifecycle") or {} - if str(lifecycle.get("lineage_sha256", "")) != lineage: - continue - nonce = int(lifecycle.get("effective_nonce", 0)) - highest = max(highest, nonce) - if str(lifecycle.get("request_sha256", "")) == request: - current = matching.get(nonce) - if current is None or str(manifest.get("updated_utc", "")) >= str(current.get("updated_utc", "")): - matching[nonce] = manifest - except Exception: - continue - if resume_safe and matching: - latest_nonce = max(matching) - latest = matching[latest_nonce] - if latest_nonce == highest and str(latest.get("status", "")) != "complete": - return latest_nonce, "resume_interrupted" - return highest + 1, "new_revision" - - def prepare( - self, *, model: Any, model_fingerprint_value: str, clip: Any, - video_vae: Any, sampler: Any, - sigmas: torch.Tensor, prompt_plan: dict[str, Any], width: int, - height: int, chunk_seconds: float, continuity: str, - audio_continuity: bool, base_seed: int, reroll_from_chunk: int, - reroll_nonce: int, first_frame_hash: str, last_frame_hash: str, - identity_hash: str, strict_compatibility: bool, - existing_session: dict[str, Any] | None, - reference_contract: dict[str, Any] | None = None, - conditioning_mode: str | None = None, - reference_audio_contract: dict[str, Any] | None = None, - reference_audio_vae: Any = None, - driving_audio_contract: dict[str, Any] | None = None, - driving_audio_vae: Any = None, + + + def _reconcile_review_execution_with_reused_prefix(self, prefix_count: int) -> None: + """Make ordinary Review continuation follow the prefix actually reused. + + Run Storage candidate selection is the final authority for which saved + prefix survived integrity/contract validation. A stale or missed review + head must never make the Review controller expect Chunk 1 while the + sampler has already restored Chunk 1 and is about to generate Chunk 2. + Explicit regeneration and Take actions keep their resolved boundaries. + """ + + execution = self.review_execution + if ( + execution is None + or self.review_generation_mode != GENERATION_MODE_REVIEW + or self.review_action != REVIEW_ACTION_CONTINUE + or self.take_action != TAKE_ACTION_AUTOMATIC + or self.review_manual_regenerate_from + ): + return + contract = self.contract or {} + chunks = int(contract.get("chunk_count", 0)) + prefix = int(prefix_count) + if chunks <= 0 or prefix < 0 or prefix > chunks: + raise RunStorageError("reused review prefix is outside the configured chunk range") + status = ( + None + if prefix == 0 + else REVISION_STATUS_COMPLETE + if prefix == chunks + else REVISION_STATUS_REVIEW_READY + ) + terminal_merge_enabled = _terminal_merge_enabled(contract) + resolved = resolve_review_execution( + generation_mode=GENERATION_MODE_REVIEW, + review_action=REVIEW_ACTION_CONTINUE, + configured_chunks=chunks, + validated_prefix_count=prefix, + terminal_merge_enabled=terminal_merge_enabled, + terminal_pair_start=(chunks - 1 if terminal_merge_enabled else None), + manual_regenerate_from=0, + run_storage_mode=RUN_STORAGE_SAVE_AUTO_RESUME, + latest_review_unit=None, + latest_revision_status=status, + latest_effective_nonce=int(self.effective_reroll_nonce), + latest_branch_regenerate_from=int(contract.get("reroll_from_chunk", 0)), + ) + old_expected = ( + execution.next_review_unit_start, + execution.next_review_unit_end, + execution.next_review_physical_group, + ) + new_expected = ( + resolved.next_review_unit_start, + resolved.next_review_unit_end, + resolved.next_review_physical_group, + ) + if old_expected != new_expected or execution.projected_prefix_count != resolved.projected_prefix_count: + self.notes.append( + "Review continuation reconciled to validated saved prefix " + f"{prefix}/{chunks}: expected {old_expected} -> {new_expected}." + ) + self.review_execution = resolved + + def _resolve_effective_nonce( + self, contract: dict[str, Any], *, requested_nonce: int, resume_safe: bool, + ) -> tuple[int, str]: + boundary = int(contract["reroll_from_chunk"]) + requested = int(requested_nonce) + if boundary <= 0: + return 0, "inactive" + if requested >= 1: + return requested, "explicit" + lineage = str(contract["nonce_lineage_sha256"]) + request = str(contract["nonce_request_sha256"]) + highest = 0 + matching: dict[int, dict[str, Any]] = {} + if self.revisions_root.exists(): + for path in self.revisions_root.glob("*/manifest.json"): + try: + manifest = _read_json(path) + lifecycle = manifest.get("nonce_lifecycle") or (manifest.get("contract") or {}).get("nonce_lifecycle") or {} + if str(lifecycle.get("lineage_sha256", "")) != lineage: + continue + nonce = int(lifecycle.get("effective_nonce", 0)) + highest = max(highest, nonce) + if str(lifecycle.get("request_sha256", "")) == request: + current = matching.get(nonce) + if current is None or str(manifest.get("updated_utc", "")) >= str(current.get("updated_utc", "")): + matching[nonce] = manifest + except Exception: + continue + if resume_safe and matching: + latest_nonce = max(matching) + latest = matching[latest_nonce] + if latest_nonce == highest and str(latest.get("status", "")) != "complete": + return latest_nonce, "resume_interrupted" + return highest + 1, "new_revision" + + def prepare( + self, *, model: Any, model_fingerprint_value: str, clip: Any, + video_vae: Any, sampler: Any, + sigmas: torch.Tensor, prompt_plan: dict[str, Any], width: int, + height: int, chunk_seconds: float, continuity: str, + audio_continuity: bool, base_seed: int, reroll_from_chunk: int, + reroll_nonce: int, first_frame_hash: str, last_frame_hash: str, + identity_hash: str, strict_compatibility: bool, + existing_session: dict[str, Any] | None, + reference_contract: dict[str, Any] | None = None, + conditioning_mode: str | None = None, + reference_audio_contract: dict[str, Any] | None = None, + reference_audio_vae: Any = None, + driving_audio_contract: dict[str, Any] | None = None, + driving_audio_vae: Any = None, reference_video_contract: dict[str, Any] | None = None, timeline_video_contract: dict[str, Any] | None = None, guide_contract: dict[str, Any] | None = None, execution_semantics: dict[str, Any] | None = None, - ) -> dict[str, Any] | None: - if existing_session is not None: - raise RunStorageError("Run Storage cannot be combined with an explicit Session") - self.prompts = [str(value) for value in prompt_plan["prompts"]] - from .graph_contract import build_upstream_graph_contract - graph_contract, graph_safe, graph_reasons = build_upstream_graph_contract( - self.prompt_graph, - self.sampler_node_id, - require_video_vae=( + ) -> dict[str, Any] | None: + if existing_session is not None: + raise RunStorageError("Run Storage cannot be combined with an explicit Session") + self.prompts = [str(value) for value in prompt_plan["prompts"]] + from .graph_contract import build_upstream_graph_contract + graph_contract, graph_safe, graph_reasons = build_upstream_graph_contract( + self.prompt_graph, + self.sampler_node_id, + require_video_vae=( conditioning_mode_uses_video_vae(str(conditioning_mode)) or reference_video_contract is not None or timeline_video_contract is not None or guide_contract is not None - ), - require_reference_audio_vae=reference_audio_contract is not None, - require_audio_vae=driving_audio_contract is not None, - ) - contract, safe, reasons = build_sampling_contract( - model=model, model_fingerprint_value=model_fingerprint_value, - clip=clip, video_vae=video_vae, - sampler=sampler, sigmas=sigmas, prompt_plan=prompt_plan, - width=width, height=height, chunk_seconds=chunk_seconds, - continuity=continuity, audio_continuity=audio_continuity, - base_seed=base_seed, reroll_from_chunk=reroll_from_chunk, - reroll_nonce=reroll_nonce, first_frame_hash=first_frame_hash, - last_frame_hash=last_frame_hash, - strict_compatibility=strict_compatibility, - reference_contract=reference_contract, - conditioning_mode=conditioning_mode, - upstream_graph_contract=graph_contract, - upstream_graph_safe=graph_safe, - upstream_graph_reasons=graph_reasons, - reference_audio_contract=reference_audio_contract, - reference_audio_vae=reference_audio_vae, - driving_audio_contract=driving_audio_contract, - driving_audio_vae=driving_audio_vae, + ), + require_reference_audio_vae=reference_audio_contract is not None, + require_audio_vae=driving_audio_contract is not None, + ) + contract, safe, reasons = build_sampling_contract( + model=model, model_fingerprint_value=model_fingerprint_value, + clip=clip, video_vae=video_vae, + sampler=sampler, sigmas=sigmas, prompt_plan=prompt_plan, + width=width, height=height, chunk_seconds=chunk_seconds, + continuity=continuity, audio_continuity=audio_continuity, + base_seed=base_seed, reroll_from_chunk=reroll_from_chunk, + reroll_nonce=reroll_nonce, first_frame_hash=first_frame_hash, + last_frame_hash=last_frame_hash, + strict_compatibility=strict_compatibility, + reference_contract=reference_contract, + conditioning_mode=conditioning_mode, + upstream_graph_contract=graph_contract, + upstream_graph_safe=graph_safe, + upstream_graph_reasons=graph_reasons, + reference_audio_contract=reference_audio_contract, + reference_audio_vae=reference_audio_vae, + driving_audio_contract=driving_audio_contract, + driving_audio_vae=driving_audio_vae, reference_video_contract=reference_video_contract, timeline_video_contract=timeline_video_contract, guide_contract=guide_contract, execution_semantics=execution_semantics, - ) + ) self.contract = contract if self.review_generation_mode is not None or self.review_action is not None: contract, effective_nonce, nonce_decision = self._resolve_review_contract( @@ -2167,24 +2398,39 @@ class RunStorageController: resume_safe=safe, ) else: + if safe: + self._plan_import = self._find_plan_import( + contract, stop_before=int(reroll_from_chunk), + ) + inherited_import = self._plan_import is not None and int(reroll_from_chunk) == 0 + requested = (self._plan_import["effective_reroll_nonce"] + if inherited_import else int(reroll_nonce)) + if inherited_import: + contract = self._plan_import["contract"] effective_nonce, nonce_decision = self._resolve_effective_nonce( - contract, requested_nonce=int(reroll_nonce), resume_safe=safe + contract, requested_nonce=requested, resume_safe=safe, ) contract = _apply_nonce_contract( - contract, - requested_nonce=int(reroll_nonce), - effective_nonce=effective_nonce, + contract, requested_nonce=requested, effective_nonce=effective_nonce, ) - self.resume_safe = bool(safe) - self.effective_reroll_nonce = int(effective_nonce) - self.nonce_decision = nonce_decision - if not safe: - contract = dict(contract) - contract["reuse_policy"] = "disabled_unobservable_contract" - contract["execution_nonce"] = uuid.uuid4().hex - self.disabled_reasons = reasons + self.resume_safe = bool(safe) + self.effective_reroll_nonce = int(effective_nonce) + self.nonce_decision = nonce_decision + if not safe: + contract = dict(contract) + contract["reuse_policy"] = "disabled_unobservable_contract" + contract["execution_nonce"] = uuid.uuid4().hex + self.disabled_reasons = reasons self.contract = contract sampling_revision_id, self.contract_sha256 = revision_identity(contract) + # A selected, shorter canonical Take is not interchangeable with an old + # longer revision having the same sampling inputs. Continue in its own + # storage revision when the contract is unchanged; preserve old Takes. + head_manifest = (self.review_head or {}).get("manifest") + if (not self.storage_revision_id_override and self._plan_import is None + and isinstance(head_manifest, dict) + and head_manifest.get("contract_sha256") == self.contract_sha256): + self.storage_revision_id_override = str(head_manifest["revision_id"]) self.revision_id = self.storage_revision_id_override or _storage_revision_identity( contract_sha256=self.contract_sha256, take_action=TAKE_ACTION_AUTOMATIC, @@ -2192,33 +2438,41 @@ class RunStorageController: effective_nonce=int(effective_nonce), branch_boundary=int(contract.get("reroll_from_chunk", 0)), ) - - self.revision_root = self.revisions_root / self.revision_id - self.revision_root.mkdir(parents=True, exist_ok=True) - exact = None - if self._manifest_path().exists(): - try: - exact = _read_json(self._manifest_path()) - except Exception as exc: - self.notes.append(f"exact manifest rejected: {exc}") - if exact is not None and exact.get("contract_sha256") != self.contract_sha256: - raise RunStorageError(f"short revision id collision: {self.revision_id}") - + + self.revision_root = self.revisions_root / self.revision_id + self.revision_root.mkdir(parents=True, exist_ok=True) + exact = None + if self._manifest_path().exists(): + try: + exact = _read_json(self._manifest_path()) + except Exception as exc: + self.notes.append(f"exact manifest rejected: {exc}") + if exact is not None and exact.get("contract_sha256") != self.contract_sha256: + raise RunStorageError(f"short revision id collision: {self.revision_id}") + hashes = list(contract["chunk_contract_hashes"]) best_entries: list[dict[str, Any]] = [] best_records: list[dict[str, Any]] = [] - if self.selected_take_revision is not None: + if exact is not None: + self._plan_import = None + if self._plan_import is not None: + best_entries = list(self._plan_import["entries"]) + best_records = [] # Populated with new-plan-owned copies after manifest creation. + elif self.selected_take_revision is not None: best_entries = list(self.selected_take_revision["entries"]) best_records = list(self.selected_take_records) else: candidates = [exact] if exact is not None and safe else [] if safe and exact is None and self.revisions_root.exists(): - for path in self.revisions_root.glob("*/manifest.json"): - try: - candidates.append(_read_json(path)) - except Exception: - continue + if isinstance(head_manifest, dict): + candidates.append(head_manifest) + else: + candidates.extend(self._read_manifests().values()) + candidates.sort(key=lambda m: (len(m.get("chunks") or []), + int((m.get("branch_provenance") or {}).get("canonical_sequence", 0))), reverse=True) for candidate in candidates: + if len(candidate.get("chunks") or []) <= len(best_entries): + continue if int(candidate.get("run_storage_schema_version", -1)) not in RUN_STORAGE_READABLE_SCHEMA_VERSIONS: continue if ( @@ -2241,26 +2495,29 @@ class RunStorageController: entries, records = self._valid_prefix(candidate, hashes) if len(entries) > len(best_entries): best_entries, best_records = entries, records - - self.reused_count = len(best_entries) - now = _now() + + self._reconcile_review_execution_with_reused_prefix(len(best_entries)) + self.reused_count = len(best_entries) + now = _now() self.manifest = { - "run_storage_schema_version": RUN_STORAGE_SCHEMA_VERSION, - "sampling_contract_version": SAMPLING_CONTRACT_VERSION, + "run_storage_schema_version": RUN_STORAGE_SCHEMA_VERSION, + "sampling_contract_version": SAMPLING_CONTRACT_VERSION, "run_name": self.run_name, "revision_id": self.revision_id, "sampling_revision_id": sampling_revision_id, - "contract_sha256": self.contract_sha256, - "contract": contract, - "resume_safe": bool(safe), - "resume_disabled_reasons": list(reasons), - "nonce_lifecycle": dict(contract["nonce_lifecycle"]), - "status": "in_progress", - "created_utc": (exact or {}).get("created_utc", now), - "updated_utc": now, - "chunks": best_records, + "contract_sha256": self.contract_sha256, + "contract": contract, + "resume_safe": bool(safe), + "resume_disabled_reasons": list(reasons), + "nonce_lifecycle": dict(contract["nonce_lifecycle"]), + "status": "in_progress", + "created_utc": (exact or {}).get("created_utc", now), + "updated_utc": now, + "chunks": best_records, "report_summary": (exact or {}).get("report_summary", ""), } + if exact is not None and isinstance(exact.get("prefix_import"), dict): + self.manifest["prefix_import"] = dict(exact["prefix_import"]) if self.selected_take_chain: self.manifest["branch_provenance"] = { "version": BRANCH_PROVENANCE_VERSION, @@ -2281,7 +2538,10 @@ class RunStorageController: effective_reroll_nonce=int(effective_nonce), ) self._write_manifest() - self._write_project() + if self._plan_import is not None: + best_records = self._adopt_plan_prefix(self._plan_import) + self._plan_import = None + self._write_project() if not best_entries: return None session_settings = _resume_session_settings( @@ -2350,88 +2610,92 @@ class RunStorageController: ) def commit_chunk(self, entry: dict[str, Any], *, position: int) -> None: - if self.manifest is None or self.revision_root is None: - return - validated = validate_chunk_entry(entry) - if isinstance(position, bool) or not isinstance(position, int): - raise RunStorageError("Run Storage chunk position must be an integer") - expected = int((self.contract or {}).get("chunk_count", 0)) - if position < 0 or position >= expected: - raise RunStorageError( - f"Run Storage chunk position {position} is outside 0..{expected - 1}" - ) - existing_records = list(self.manifest.get("chunks") or []) - if len(existing_records) < position: - raise RunStorageError( - f"Run Storage cannot commit chunk {position + 1} before chunk {position}" - ) - chunks_root = self.revision_root / "chunks" - chunks_root.mkdir(parents=True, exist_ok=True) - filename = f"chunk_{position + 1:04d}.safetensors" - target = chunks_root / filename - temporary = chunks_root / f".{filename}.{uuid.uuid4().hex}.tmp" - tensors = { - "video": validated["video"].detach().to("cpu").contiguous(), - "audio": validated["audio"].detach().to("cpu").contiguous(), - } - try: - save_file(tensors, str(temporary), metadata={ - "h3_continuum_run_storage": str(RUN_STORAGE_SCHEMA_VERSION), - "revision_id": self.revision_id, - "chunk_number": str(position + 1), - }) - _fsync_file(temporary) - os.replace(temporary, target) - _fsync_dir(chunks_root) - finally: - if temporary.exists(): - temporary.unlink() - storage_entry = dict(validated) - storage_entry["sequence_index"] = position - record = { - "sequence_index": position, - "storage_revision_id": self.revision_id, - "filename": filename, - "file_size": target.stat().st_size, - "file_sha256": _file_sha256(target), - "entry": _entry_metadata(storage_entry), - } - records = existing_records[:position] - records.append(record) - self.manifest.update(chunks=records, updated_utc=_now(), status="in_progress") - self._write_manifest() - self.generated_count += 1 - - def summary(self, *, detailed: bool = False) -> str: - total = int((self.contract or {}).get("chunk_count", 0)) - resume = self.reused_count + 1 if self.reused_count < total else "complete" - policy = (" auto-resume disabled: " + "; ".join(self.disabled_reasons) + ".") if self.disabled_reasons else "" - note = (" " + " ".join(self.notes)) if self.notes else "" - basic = ( - f"Run Storage: {self.run_name} / revision {self.revision_id}; " - f"{self.reused_count} reused, {self.generated_count} generated, " - f"{total} total; resume={resume}; nonce={self.effective_reroll_nonce} " - f"({self.nonce_decision}).{policy}{note}" - ) - if not detailed or self.manifest is None: - return basic - records = list(self.manifest.get("chunks") or []) - lines = [basic, f"Run Storage path: {self.revision_root}"] - for record in records: - lines.append( - f"stored chunk {int(record['sequence_index']) + 1}: " - f"{record['storage_revision_id']}/chunks/{record['filename']} " - f"({int(record['file_size']) / (1024.0 ** 2):.1f} MiB)" - ) - try: - free_gib = shutil.disk_usage(self.run_root).free / (1024.0 ** 3) - lines.append(f"Run Storage free disk: {free_gib:.2f} GiB") - except OSError: - lines.append("Run Storage free disk: unknown") - first_invalid = self.reused_count + 1 if self.reused_count < total else "none" - lines.append(f"Run Storage first regenerated chunk: {first_invalid}") - return "\n".join(lines) - + if self.manifest is None or self.revision_root is None: + return + validated = validate_chunk_entry(entry) + if isinstance(position, bool) or not isinstance(position, int): + raise RunStorageError("Run Storage chunk position must be an integer") + expected = int((self.contract or {}).get("chunk_count", 0)) + if position < 0 or position >= expected: + raise RunStorageError( + f"Run Storage chunk position {position} is outside 0..{expected - 1}" + ) + existing_records = list(self.manifest.get("chunks") or []) + if len(existing_records) < position: + raise RunStorageError( + f"Run Storage cannot commit chunk {position + 1} before chunk {position}" + ) + chunks_root = self.revision_root / "chunks" + chunks_root.mkdir(parents=True, exist_ok=True) + filename = f"chunk_{position + 1:04d}.safetensors" + target = chunks_root / filename + temporary = chunks_root / f".{filename}.{uuid.uuid4().hex}.tmp" + tensors = { + "video": validated["video"].detach().to("cpu").contiguous(), + "audio": validated["audio"].detach().to("cpu").contiguous(), + } + try: + save_file(tensors, str(temporary), metadata={ + "h3_continuum_run_storage": str(RUN_STORAGE_SCHEMA_VERSION), + "revision_id": self.revision_id, + "chunk_number": str(position + 1), + }) + _fsync_file(temporary) + os.replace(temporary, target) + _fsync_dir(chunks_root) + finally: + if temporary.exists(): + temporary.unlink() + storage_entry = dict(validated) + storage_entry["sequence_index"] = position + record = { + "sequence_index": position, + "storage_revision_id": self.revision_id, + "filename": filename, + "file_size": target.stat().st_size, + "file_sha256": _file_sha256(target), + "entry": _entry_metadata(storage_entry), + } + records = existing_records[:position] + records.append(record) + self.manifest.update(chunks=records, updated_utc=_now(), status="in_progress") + self._write_manifest() + self.generated_count += 1 + + def summary(self, *, detailed: bool = False) -> str: + total = int((self.contract or {}).get("chunk_count", 0)) + resume = self.reused_count + 1 if self.reused_count < total else "complete" + policy = (" auto-resume disabled: " + "; ".join(self.disabled_reasons) + ".") if self.disabled_reasons else "" + shown_notes = self.notes if detailed else list(dict.fromkeys(self.notes))[:3] + note = (" " + " ".join(shown_notes)) if shown_notes else "" + if not detailed and len(self.notes) > len(shown_notes): + note += f" ({len(self.notes) - len(shown_notes)} additional diagnostics; enable Detailed Report.)" + basic = ( + f"Run Storage: {self.run_name} / revision {self.revision_id}; " + f"{self.reused_count} reused, {self.generated_count} generated, " + f"{total} total; resume={resume}; nonce={self.effective_reroll_nonce} " + f"({self.nonce_decision}).{policy}{note}" + ) + if not detailed or self.manifest is None: + return basic + records = list(self.manifest.get("chunks") or []) + lines = [basic, f"Run Storage path: {self.revision_root}", + "Run Storage I/O: " + _canonical(self.io_metrics)] + for record in records: + lines.append( + f"stored chunk {int(record['sequence_index']) + 1}: " + f"{record['storage_revision_id']}/chunks/{record['filename']} " + f"({int(record['file_size']) / (1024.0 ** 2):.1f} MiB)" + ) + try: + free_gib = shutil.disk_usage(self.run_root).free / (1024.0 ** 3) + lines.append(f"Run Storage free disk: {free_gib:.2f} GiB") + except OSError: + lines.append("Run Storage free disk: unknown") + first_invalid = self.reused_count + 1 if self.reused_count < total else "none" + lines.append(f"Run Storage first regenerated chunk: {first_invalid}") + return "\n".join(lines) + def finalize( self, *, @@ -2571,15 +2835,15 @@ class RunStorageController: self.manifest["branch_provenance"] = provenance self._write_manifest() self._write_project(set_canonical=True) - - -def get_active_run_storage() -> RunStorageController | None: - return _ACTIVE.get() - - -def run_storage_scope( - run_name: str, *, prompt: Any = None, unique_id: Any = None -) -> RunStorageController: - controller = RunStorageController(run_name) - controller.set_prompt_graph(prompt, unique_id) - return controller + + +def get_active_run_storage() -> RunStorageController | None: + return _ACTIVE.get() + + +def run_storage_scope( + run_name: str, *, prompt: Any = None, unique_id: Any = None +) -> RunStorageController: + controller = RunStorageController(run_name) + controller.set_prompt_graph(prompt, unique_id) + return controller diff --git a/tests/test_v38_completed_review_ui.py b/tests/test_v38_completed_review_ui.py index 1f651e2..5710d0d 100644 --- a/tests/test_v38_completed_review_ui.py +++ b/tests/test_v38_completed_review_ui.py @@ -187,7 +187,7 @@ async function load(n,p) {project=p;await loadTakeHistory(n);n.__h3ContinuumIntu prepareReviewQueueIntent(setup,inputs); assert.equal(inputs.review_action,"Continue / Next"); if(["complete","review_ready"].includes(oldStatus)){ - assert.equal(inputs.reroll_from_chunk,"Chunk 1","saved history starts a new review branch"); + assert.equal(inputs.reroll_from_chunk,"Auto","mode switch preserves compatible continuation"); assert.equal(inputs.reroll_nonce,0); assert.equal(inputs.take_group,0); assert.equal(inputs.take_revision_id,""); @@ -195,7 +195,7 @@ async function load(n,p) {project=p;await loadTakeHistory(n);n.__h3ContinuumIntu } await load(setup,old); assert(visible(setup,"Chunks"),"Queue alone does not mean generation completed"); - project=state("review_ready",{start:1,end:1,physical_group:1},"new-output"); + project=state("review_ready",{start:2,end:2,physical_group:2},"new-output"); setup.onExecuted(); await new Promise(resolve=>setImmediate(resolve)); assert(buttons.every(name=>visible(setup,name)),"new queued result opens ordinary review"); @@ -234,53 +234,79 @@ async function load(n,p) {project=p;await loadTakeHistory(n);n.__h3ContinuumIntu // Frontend 1.49 contract: widget.beforeQueued runs before serializeValue; // legacy beforeQueuePrompt is not part of the real queue path. const liveContract=makeNode();liveContract.id=312;app.graph._nodes=[liveContract]; + w(liveContract,"chunks").value=4; await load(liveContract,state("complete",{start:3,end:3,physical_group:3},"live-old-complete")); w(liveContract,"Run").callback("Generate Full Video"); w(liveContract,"Run").callback("Review Each Chunk"); for(const widget of liveContract.widgets)widget.beforeQueued?.({isPartialExecution:false}); const liveInputs=await serializedInputs(liveContract); - assert.equal(liveInputs.reroll_from_chunk,"Chunk 1"); + assert.equal(liveInputs.reroll_from_chunk,"Auto","mode switch must not inject Chunk 1"); assert.equal(liveInputs.reroll_nonce,0); assert.equal(liveInputs.take_group,0); assert.equal(liveInputs.take_revision_id,""); assert.equal(liveInputs.take_action,"Automatic"); assert.equal(liveInputs.review_action,"Continue / Next"); - assert.equal(w(liveContract,"reroll_from_chunk").value,"Auto","visible settings stay unchanged"); - project=state("review_ready",{start:1,end:1,physical_group:1},"live-fresh-chunk-1"); - emit("executed",{node:"312",prompt_id:"live-prompt"}); + project=state("review_ready",{start:4,end:4,physical_group:4},"live-fresh-chunk-4"); + // Sampler V3.8 does not need to emit a node-specific `executed` UI event. emit("execution_success",{prompt_id:"live-prompt"}); await new Promise(resolve=>setTimeout(resolve,20)); - assert(buttons.every(name=>visible(liveContract,name)),"real completion events open Chunk 1 review"); - assert.match(w(liveContract,"Review Ready").value,/Chunk 1/); - // Acceptance lifecycle: 3 x 5 seconds must stop at every review boundary. - const flow=makeNode();w(flow,"chunks").value=3;w(flow,"chunk_seconds").value=5; + assert(buttons.every(name=>visible(liveContract,name)),"terminal readback opens the new review"); + assert.match(w(liveContract,"Review Ready").value,/Chunk 4/); + // Acceptance lifecycle: extend a completed 3 x 5-second prefix to 5 x 5 seconds. + const flow=makeNode();w(flow,"chunks").value=5;w(flow,"chunk_seconds").value=5; await load(flow,state("complete",{start:3,end:3,physical_group:3},"old-complete-3x5")); w(flow,"Run").callback("Generate Full Video"); w(flow,"Run").callback("Review Each Chunk"); - const chunk1Inputs={reroll_from_chunk:"Auto",reroll_nonce:0}; - prepareReviewQueueIntent(flow,chunk1Inputs); - assert.equal(chunk1Inputs.reroll_from_chunk,"Chunk 1"); - project=state("review_ready",{start:1,end:1,physical_group:1},"fresh-chunk-1"); + const chunk4Inputs={reroll_from_chunk:"Auto",reroll_nonce:0, + take_group:9,take_revision_id:"stale",take_action:"Use This Take"}; + prepareReviewQueueIntent(flow,chunk4Inputs); + assert.equal(chunk4Inputs.reroll_from_chunk,"Auto","extension reuses the compatible prefix"); + assert.equal(chunk4Inputs.take_group,0); + assert.equal(chunk4Inputs.take_revision_id,""); + assert.equal(chunk4Inputs.take_action,"Automatic"); + project=state("review_ready",{start:4,end:4,physical_group:4},"fresh-chunk-4"); flow.onExecuted();await new Promise(resolve=>setImmediate(resolve)); - assert(buttons.every(name=>visible(flow,name)),"Chunk 1 opens the review screen"); - assert.match(w(flow,"Review Ready").value,/Chunk 1/); + assert(buttons.every(name=>visible(flow,name)),"Chunk 4 opens the review screen"); + assert.match(w(flow,"Review Ready").value,/Chunk 4/); w(flow,"Use it and continue").callback(); - const chunk2Inputs={reroll_from_chunk:"Auto",reroll_nonce:0}; - prepareReviewQueueIntent(flow,chunk2Inputs); - assert.equal(chunk2Inputs.reroll_from_chunk,"Auto","continuation does not restart Chunk 1"); - project=state("review_ready",{start:2,end:2,physical_group:2},"fresh-chunk-2"); + const chunk5Inputs={reroll_from_chunk:"Auto",reroll_nonce:0}; + prepareReviewQueueIntent(flow,chunk5Inputs); + assert.equal(chunk5Inputs.reroll_from_chunk,"Auto","continuation does not restart Chunk 1"); + project=state("complete",{start:5,end:5,physical_group:5},"fresh-chunk-5"); flow.onExecuted();await new Promise(resolve=>setImmediate(resolve)); - assert(buttons.every(name=>visible(flow,name)),"Chunk 2 opens the review screen"); - assert.match(w(flow,"Review Ready").value,/Chunk 2/); - w(flow,"Use it and continue").callback(); - const chunk3Inputs={reroll_from_chunk:"Auto",reroll_nonce:0}; - prepareReviewQueueIntent(flow,chunk3Inputs); - assert.equal(chunk3Inputs.reroll_from_chunk,"Auto"); - project=state("complete",{start:3,end:3,physical_group:3},"fresh-chunk-3"); - flow.onExecuted();await new Promise(resolve=>setImmediate(resolve)); - assert(visible(flow,"Try this chunk again"),"Chunk 3 completion remains reviewable"); + assert(visible(flow,"Try this chunk again"),"Chunk 5 completion remains reviewable"); assert(!visible(flow,"Use it and continue")&&!visible(flow,"Use it and finish the rest")); assert.match(w(flow,"Review Ready").value,/Saved sequence is complete/); + + // Full mode also keeps Auto so the backend can reuse Chunks 1-3 and generate 4-5. + const fullExtend=makeNode();w(fullExtend,"chunks").value=5; + await load(fullExtend,state("complete",{start:3,end:3,physical_group:3},"full-old-3")); + w(fullExtend,"Run").callback("Generate Full Video"); + const fullInputs={reroll_from_chunk:"Auto",reroll_nonce:0};prepareReviewQueueIntent(fullExtend,fullInputs); + assert.equal(fullInputs.generation_mode,"Full Run"); + assert.equal(fullInputs.reroll_from_chunk,"Auto"); + + // Storage Off cannot submit a stale explicit regeneration boundary. + const storageOff=makeNode(); + w(storageOff,"generation_mode").value="Full Run"; + w(storageOff,"run_storage").value="Off"; + w(storageOff,"reroll_from_chunk").value="Chunk 1"; + w(storageOff,"reroll_nonce").value=7; + for(const widget of storageOff.widgets)widget.beforeQueued?.({isPartialExecution:false}); + const offInputs=await serializedInputs(storageOff); + assert.equal(offInputs.reroll_from_chunk,"Auto"); + assert.equal(offInputs.reroll_nonce,0); + assert.equal(w(storageOff,"reroll_from_chunk").value,"Auto","visible stale boundary is normalized"); + + // An explicit Advanced regeneration remains explicit while storage is enabled. + const explicit=makeNode(); + w(explicit,"reroll_from_chunk").value="Chunk 1"; + w(explicit,"reroll_from_chunk").callback?.("Chunk 1"); + w(explicit,"Run").callback("Generate Full Video"); + w(explicit,"Run").callback("Review Each Chunk"); + for(const widget of explicit.widgets)widget.beforeQueued?.({isPartialExecution:false}); + const explicitInputs=await serializedInputs(explicit); + assert.equal(explicitInputs.reroll_from_chunk,"Chunk 1","manual Advanced regeneration is preserved"); // Hotfix: stale saved review cannot offer/submit Retry after settings edits. const edited=makeNode();w(edited,"chunks").value=4; const originalProject=state("review_ready",{start:2,end:2,physical_group:2},"edit-base"); diff --git a/tests/test_v38_review_ui.py b/tests/test_v38_review_ui.py index b6bb083..e8ce705 100644 --- a/tests/test_v38_review_ui.py +++ b/tests/test_v38_review_ui.py @@ -1096,7 +1096,7 @@ def test_n2c_history_refresh_hooks_and_multiline_surface_are_present(): source = PROJECT_ID_JS.read_text(encoding="utf-8") assert '"Render History / Takes"' in source assert '{ multiline: true }' in source - assert "void loadTakeHistory(this);" in source + assert "loadTakeHistory(this)" in source assert "attachTakeHistoryReload(node);" in source assert "node.__h3ContinuumTakeInitialLoad" in source assert 'const TAKE_TOGGLE_WIDGET = "Render History";' in source diff --git a/web/project_id.js b/web/project_id.js index 1aa2c80..1f848b9 100644 --- a/web/project_id.js +++ b/web/project_id.js @@ -1,25 +1,25 @@ import { app } from "../../scripts/app.js"; import { normalizeReferenceAudioLabels } from "./reference_audio_ui.js"; - -const PRODUCTION_NODE_CLASS = "H3ContinuumSamplerProduction"; -const TIMELINE_NODE_CLASS = "H3ContinuumSamplerTimelineVideo"; -const ASSEMBLE_SEAM_NODE_CLASS = "H3ContinuumAssembleSeamExperimental"; -const V34_NODE_CLASS = "H3ContinuumSamplerV34"; -const V34_ASSEMBLE_SEAM_NODE_CLASS = "H3ContinuumAssembleSeamV34"; + +const PRODUCTION_NODE_CLASS = "H3ContinuumSamplerProduction"; +const TIMELINE_NODE_CLASS = "H3ContinuumSamplerTimelineVideo"; +const ASSEMBLE_SEAM_NODE_CLASS = "H3ContinuumAssembleSeamExperimental"; +const V34_NODE_CLASS = "H3ContinuumSamplerV34"; +const V34_ASSEMBLE_SEAM_NODE_CLASS = "H3ContinuumAssembleSeamV34"; const V35_NODE_CLASS = "H3ContinuumSamplerV35"; const V36_NODE_CLASS = "H3ContinuumSamplerV36"; const V37_NODE_CLASS = "H3ContinuumSamplerV37"; const V38_NODE_CLASS = "H3ContinuumSamplerV38"; const V35_ASSEMBLE_SEAM_NODE_CLASS = "H3ContinuumAssembleSeamV35"; -const PROJECT_WIDGET = "project_id"; -const LEGACY_RUN_NAME_WIDGET = "run_name"; -const CHUNKS_WIDGET = "chunks"; -const REGENERATE_WIDGET = "reroll_from_chunk"; -const REROLL_NONCE_WIDGET = "reroll_nonce"; -const RUN_STORAGE_WIDGET = "run_storage"; -const REFERENCE_SIZE_WIDGET = "reference_size"; -const TIMELINE_SIZE_WIDGET = "timeline_video_size"; -const VIDEO_REFERENCE_SIZE_WIDGET = "video_reference_size"; +const PROJECT_WIDGET = "project_id"; +const LEGACY_RUN_NAME_WIDGET = "run_name"; +const CHUNKS_WIDGET = "chunks"; +const REGENERATE_WIDGET = "reroll_from_chunk"; +const REROLL_NONCE_WIDGET = "reroll_nonce"; +const RUN_STORAGE_WIDGET = "run_storage"; +const REFERENCE_SIZE_WIDGET = "reference_size"; +const TIMELINE_SIZE_WIDGET = "timeline_video_size"; +const VIDEO_REFERENCE_SIZE_WIDGET = "video_reference_size"; const PROMPT_OVERRIDES_INPUT = "prompt_overrides"; const RESOLUTION_PRESET_WIDGET = "preset"; const CUSTOM_MP_WIDGET = "custom_mp"; @@ -206,135 +206,135 @@ const V38_VIEW_PROPERTY = "H3 Continuum View"; const V38_VIEW_BASIC = "Basic"; const V38_VIEW_PRODUCTION = "Production"; const V38_VIEW_OPTIONS = [V38_VIEW_BASIC, V38_VIEW_PRODUCTION]; -const SETTINGS = { - detailedReport: "H3Continuum.DetailedReport", - developerDiagnostics: "H3Continuum.DeveloperDiagnostics", - samplingPreview: "H3Continuum.SamplingPreview", -}; - -function createProjectId() { - if (globalThis.crypto?.randomUUID) { - return globalThis.crypto.randomUUID(); - } - const bytes = new Uint8Array(16); - globalThis.crypto.getRandomValues(bytes); - bytes[6] = (bytes[6] & 0x0f) | 0x40; - bytes[8] = (bytes[8] & 0x3f) | 0x80; - const hex = Array.from(bytes, (value) => value.toString(16).padStart(2, "0")).join(""); - return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`; -} - -function findWidget(node, name) { - return node.widgets?.find((widget) => widget.name === name); -} - -function setWidgetVisible(widget, visible) { - if (!widget) { - return; - } - if (!widget.__h3ContinuumOriginal) { - widget.__h3ContinuumOriginal = { - type: widget.type, - computeSize: widget.computeSize, - hidden: widget.hidden, - optionsHidden: widget.options?.hidden, - }; - } - widget.options ||= {}; - if (visible) { - const original = widget.__h3ContinuumOriginal; - widget.type = original.type; - widget.computeSize = original.computeSize; - widget.hidden = original.hidden; - if (original.optionsHidden === undefined) { - delete widget.options.hidden; - } else { - widget.options.hidden = original.optionsHidden; - } - } else { - widget.hidden = true; - widget.type = "converted-widget"; - widget.options.hidden = true; - widget.computeSize = () => [0, -4]; - } -} - -function hidePersistentWidget(widget) { - setWidgetVisible(widget, false); -} - -function settingValue(id, fallback) { - try { - return app.ui?.settings?.getSettingValue?.(id) ?? fallback; - } catch { - return fallback; - } -} - -function applyRuntimeSettings(node) { - const detailed = Boolean(settingValue(SETTINGS.detailedReport, false)); - const debug = Boolean(settingValue(SETTINGS.developerDiagnostics, false)); - const preview = Boolean(settingValue(SETTINGS.samplingPreview, true)); - const diagnosticsWidget = findWidget(node, "diagnostics"); - const debugWidget = findWidget(node, "debug"); - const previewWidget = findWidget(node, "show_preview"); - const strictWidget = findWidget(node, "strict_compatibility"); - if (diagnosticsWidget) diagnosticsWidget.value = detailed ? "Detailed Report" : "Basic"; - if (debugWidget) debugWidget.value = debug; - if (previewWidget) previewWidget.value = preview; - if (strictWidget) strictWidget.value = false; -} - -function removeUnusedInput(node, name) { - const index = node.inputs?.findIndex((input) => input.name === name) ?? -1; - if (index < 0) { - return; - } - const input = node.inputs[index]; - if (input.link != null) { - app.graph?.removeLink(input.link); - } - node.removeInput(index); -} - -function regenerateOptions(chunks) { - const count = Math.max(1, Math.min(16, Number.parseInt(chunks, 10) || 1)); - return ["Auto", ...Array.from({ length: count }, (_, index) => `Chunk ${index + 1}`)]; -} - -function configureRegenerateFrom(node) { - const chunksWidget = findWidget(node, CHUNKS_WIDGET); - const regenerateWidget = findWidget(node, REGENERATE_WIDGET); - if (!chunksWidget || !regenerateWidget) { - return; - } - const refresh = () => { - const values = regenerateOptions(chunksWidget.value); - regenerateWidget.options ||= {}; - regenerateWidget.options.values = values; - const numeric = typeof regenerateWidget.value === "number" - ? regenerateWidget.value - : Number.parseInt(String(regenerateWidget.value).replace(/^Chunk\s+/, ""), 10); - if (regenerateWidget.value === "Auto" || numeric === 0) { - regenerateWidget.value = "Auto"; - } else if (Number.isInteger(numeric) && numeric >= 1 && numeric < values.length) { - regenerateWidget.value = `Chunk ${numeric}`; - } else { - regenerateWidget.value = "Auto"; - } - }; - if (!chunksWidget.__h3ContinuumRegenerateCallback) { - const previous = chunksWidget.callback; - chunksWidget.callback = function(value, ...args) { - const result = previous?.call(this, value, ...args); - refresh(); - return result; - }; - chunksWidget.__h3ContinuumRegenerateCallback = true; - } - refresh(); -} - +const SETTINGS = { + detailedReport: "H3Continuum.DetailedReport", + developerDiagnostics: "H3Continuum.DeveloperDiagnostics", + samplingPreview: "H3Continuum.SamplingPreview", +}; + +function createProjectId() { + if (globalThis.crypto?.randomUUID) { + return globalThis.crypto.randomUUID(); + } + const bytes = new Uint8Array(16); + globalThis.crypto.getRandomValues(bytes); + bytes[6] = (bytes[6] & 0x0f) | 0x40; + bytes[8] = (bytes[8] & 0x3f) | 0x80; + const hex = Array.from(bytes, (value) => value.toString(16).padStart(2, "0")).join(""); + return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`; +} + +function findWidget(node, name) { + return node.widgets?.find((widget) => widget.name === name); +} + +function setWidgetVisible(widget, visible) { + if (!widget) { + return; + } + if (!widget.__h3ContinuumOriginal) { + widget.__h3ContinuumOriginal = { + type: widget.type, + computeSize: widget.computeSize, + hidden: widget.hidden, + optionsHidden: widget.options?.hidden, + }; + } + widget.options ||= {}; + if (visible) { + const original = widget.__h3ContinuumOriginal; + widget.type = original.type; + widget.computeSize = original.computeSize; + widget.hidden = original.hidden; + if (original.optionsHidden === undefined) { + delete widget.options.hidden; + } else { + widget.options.hidden = original.optionsHidden; + } + } else { + widget.hidden = true; + widget.type = "converted-widget"; + widget.options.hidden = true; + widget.computeSize = () => [0, -4]; + } +} + +function hidePersistentWidget(widget) { + setWidgetVisible(widget, false); +} + +function settingValue(id, fallback) { + try { + return app.ui?.settings?.getSettingValue?.(id) ?? fallback; + } catch { + return fallback; + } +} + +function applyRuntimeSettings(node) { + const detailed = Boolean(settingValue(SETTINGS.detailedReport, false)); + const debug = Boolean(settingValue(SETTINGS.developerDiagnostics, false)); + const preview = Boolean(settingValue(SETTINGS.samplingPreview, true)); + const diagnosticsWidget = findWidget(node, "diagnostics"); + const debugWidget = findWidget(node, "debug"); + const previewWidget = findWidget(node, "show_preview"); + const strictWidget = findWidget(node, "strict_compatibility"); + if (diagnosticsWidget) diagnosticsWidget.value = detailed ? "Detailed Report" : "Basic"; + if (debugWidget) debugWidget.value = debug; + if (previewWidget) previewWidget.value = preview; + if (strictWidget) strictWidget.value = false; +} + +function removeUnusedInput(node, name) { + const index = node.inputs?.findIndex((input) => input.name === name) ?? -1; + if (index < 0) { + return; + } + const input = node.inputs[index]; + if (input.link != null) { + app.graph?.removeLink(input.link); + } + node.removeInput(index); +} + +function regenerateOptions(chunks) { + const count = Math.max(1, Math.min(16, Number.parseInt(chunks, 10) || 1)); + return ["Auto", ...Array.from({ length: count }, (_, index) => `Chunk ${index + 1}`)]; +} + +function configureRegenerateFrom(node) { + const chunksWidget = findWidget(node, CHUNKS_WIDGET); + const regenerateWidget = findWidget(node, REGENERATE_WIDGET); + if (!chunksWidget || !regenerateWidget) { + return; + } + const refresh = () => { + const values = regenerateOptions(chunksWidget.value); + regenerateWidget.options ||= {}; + regenerateWidget.options.values = values; + const numeric = typeof regenerateWidget.value === "number" + ? regenerateWidget.value + : Number.parseInt(String(regenerateWidget.value).replace(/^Chunk\s+/, ""), 10); + if (regenerateWidget.value === "Auto" || numeric === 0) { + regenerateWidget.value = "Auto"; + } else if (Number.isInteger(numeric) && numeric >= 1 && numeric < values.length) { + regenerateWidget.value = `Chunk ${numeric}`; + } else { + regenerateWidget.value = "Auto"; + } + }; + if (!chunksWidget.__h3ContinuumRegenerateCallback) { + const previous = chunksWidget.callback; + chunksWidget.callback = function(value, ...args) { + const result = previous?.call(this, value, ...args); + refresh(); + return result; + }; + chunksWidget.__h3ContinuumRegenerateCallback = true; + } + refresh(); +} + function linkedInput(node, names) { return node.inputs?.some((input) => names.includes(input.name) && input.link != null) ?? false; } @@ -367,17 +367,17 @@ function activeLinkedInput(node, names) { ); }); } - + function attachRefresh(widget, key, refresh) { - if (!widget || widget[key]) { - return; - } - const previous = widget.callback; - widget.callback = function(value, ...args) { - const result = previous?.call(this, value, ...args); - refresh(); - return result; - }; + if (!widget || widget[key]) { + return; + } + const previous = widget.callback; + widget.callback = function(value, ...args) { + const result = previous?.call(this, value, ...args); + refresh(); + return result; + }; widget[key] = true; } @@ -434,18 +434,17 @@ function installReviewModeSetupQueueContract(node) { const generationWidget = findWidget(node, GENERATION_MODE_WIDGET); if (!generationWidget) return; - // ComfyUI frontend 1.49 serializes API inputs through widget.serializeValue. - // Keep the visible/saved settings intact while making the first Queue after - // Full Run -> Review Each Chunk an explicit, non-destructive Chunk 1 branch. - const overrides = new Map([ + // ComfyUI frontend 1.49 calls widget.beforeQueued before serializeValue. + // Mode selection is presentation/setup only: it must never inject a hidden + // Chunk 1 restart. History selection is also cleared from a normal mode + // setup so Run Storage remains the authority for compatible prefix reuse. + const setupOverrides = new Map([ [REVIEW_ACTION_WIDGET, REVIEW_ACTION_CONTINUE], - [REGENERATE_WIDGET, "Chunk 1"], - [REROLL_NONCE_WIDGET, 0], [TAKE_GROUP_WIDGET, 0], [TAKE_REVISION_WIDGET, ""], [TAKE_ACTION_WIDGET, TAKE_ACTION_AUTOMATIC], ]); - for (const [name, value] of overrides) { + for (const [name, value] of setupOverrides) { const widget = findWidget(node, name); if (!widget || widget.__h3ContinuumModeSetupSerializeValue) continue; const previous = widget.serializeValue; @@ -458,14 +457,60 @@ function installReviewModeSetupQueueContract(node) { widget.__h3ContinuumModeSetupSerializeValue = true; } + const regenerateWidget = findWidget(node, REGENERATE_WIDGET); + if (regenerateWidget && !regenerateWidget.__h3ContinuumSafeSerializeValue) { + const previous = regenerateWidget.serializeValue; + regenerateWidget.serializeValue = function(...args) { + if (findWidget(node, RUN_STORAGE_WIDGET)?.value !== "Save + Auto Resume") { + return "Auto"; + } + if ( + reviewModeSetupActive(node) + && this.value === "Chunk 1" + && !node.__h3ContinuumManualRegenerateIntent + && !node.__h3ContinuumRestartSelected + ) { + return "Auto"; + } + return typeof previous === "function" + ? previous.apply(this, args) + : this.value; + }; + regenerateWidget.__h3ContinuumSafeSerializeValue = true; + } + const nonceWidget = findWidget(node, REROLL_NONCE_WIDGET); + if (nonceWidget && !nonceWidget.__h3ContinuumSafeSerializeValue) { + const previous = nonceWidget.serializeValue; + nonceWidget.serializeValue = function(...args) { + if (findWidget(node, RUN_STORAGE_WIDGET)?.value !== "Save + Auto Resume") { + return 0; + } + if ( + reviewModeSetupActive(node) + && regenerateWidget?.value === "Chunk 1" + && !node.__h3ContinuumManualRegenerateIntent + && !node.__h3ContinuumRestartSelected + ) { + return 0; + } + return typeof previous === "function" + ? previous.apply(this, args) + : this.value; + }; + nonceWidget.__h3ContinuumSafeSerializeValue = true; + } + const previousBeforeQueued = generationWidget.beforeQueued; generationWidget.beforeQueued = function(...args) { const result = previousBeforeQueued?.apply(this, args); + normalizeRunStorageState(node); if (reviewModeSetupActive(node)) { + normalizeUnownedRestart(node); + const revision = canonicalStorageRevision(node.__h3ContinuumTakeProject); node.__h3ContinuumModeSetupQueued = { setup: node.__h3ContinuumModeSetup, runName: takeRunName(node), - promptId: "", + baselineRevision: String(revision?.revision_id || ""), }; node.__h3ContinuumQueuedSettings = reviewSettingsSnapshot(node); node.__h3ContinuumQueuedSettingsRun = takeRunName(node); @@ -500,6 +545,39 @@ function setExistingWidgetValue(widget, value) { widget.callback?.(value); } +function setRegenerateProgrammatically(node, value) { + const widget = findWidget(node, REGENERATE_WIDGET); + if (!widget || widget.value === value) { + if (value === "Auto" || value === 0 || value == null) { + delete node.__h3ContinuumManualRegenerateIntent; + } + return; + } + node.__h3ContinuumProgrammaticRegenerate = true; + try { + setExistingWidgetValue(widget, value); + } finally { + delete node.__h3ContinuumProgrammaticRegenerate; + } + if (value === "Auto" || value === 0 || value == null) { + delete node.__h3ContinuumManualRegenerateIntent; + } +} + +function normalizeUnownedRestart(node) { + const widget = findWidget(node, REGENERATE_WIDGET); + if ( + widget?.value === "Chunk 1" + && !node.__h3ContinuumManualRegenerateIntent + && !node.__h3ContinuumRestartSelected + ) { + setRegenerateProgrammatically(node, "Auto"); + setExistingWidgetValue(findWidget(node, REROLL_NONCE_WIDGET), 0); + return true; + } + return false; +} + function facadeProductionWidgets(node) { return node.widgets?.filter((widget) => widget[FACADE_TRANSIENT_WIDGET]) || []; } @@ -1096,12 +1174,15 @@ function configureIntuitiveV38Ux(node) { onSet: (value, source) => { const reviewing = value === FACADE_GENERATE_REVIEW; if (reviewing && source.value !== GENERATION_MODE_REVIEW) { - // Selecting a mode is setup, not selecting a saved review. + // Selecting a mode is setup, not selecting a saved review and + // not a request to restart from Chunk 1. node.__h3ContinuumModeSetup = {}; delete node.__h3ContinuumModeSetupQueued; + normalizeUnownedRestart(node); } else if (!reviewing) { delete node.__h3ContinuumModeSetup; delete node.__h3ContinuumModeSetupQueued; + normalizeUnownedRestart(node); } setExistingWidgetValue( source, @@ -1134,6 +1215,8 @@ function configureIntuitiveV38Ux(node) { const enabled = value === FACADE_SAVE_ON; setExistingWidgetValue(source, enabled ? "Save + Auto Resume" : "Off"); if (!enabled) { + setRegenerateProgrammatically(node, "Auto"); + setExistingWidgetValue(findWidget(node, REROLL_NONCE_WIDGET), 0); setExistingWidgetValue( findWidget(node, GENERATION_MODE_WIDGET), GENERATION_MODE_FULL_RUN, @@ -1436,13 +1519,17 @@ function rememberReviewSettings(node, requestedSettings) { delete node.__h3ContinuumQueuedSettingsRun; } -function finishModeSetupAfterExecution(node, promptId = "") { +function finishModeSetupAfterExecution(node) { const queued = node.__h3ContinuumModeSetupQueued; + const revision = canonicalStorageRevision(node.__h3ContinuumTakeProject); + const revisionId = String(revision?.revision_id || ""); if ( !queued || queued.setup !== node.__h3ContinuumModeSetup || queued.runName !== takeRunName(node) - || (promptId && queued.promptId !== promptId) + || !revisionId + || revisionId === String(queued.baselineRevision || "") + || !["review_ready", "complete"].includes(revision?.status) ) { return false; } @@ -1453,26 +1540,6 @@ function finishModeSetupAfterExecution(node, promptId = "") { return true; } -function bindModeSetupPromptFromExecutedNode(event) { - const detail = event?.detail || event || {}; - const promptId = String(detail.prompt_id || ""); - const executedNodeId = String(detail.display_node || detail.node || ""); - if (!promptId || !executedNodeId) return; - for (const node of app.graph?._nodes || []) { - const queued = node.__h3ContinuumModeSetupQueued; - if ( - node.comfyClass !== V38_NODE_CLASS - || String(node.id) !== executedNodeId - || !queued - || queued.setup !== node.__h3ContinuumModeSetup - || queued.runName !== takeRunName(node) - ) { - continue; - } - queued.promptId = promptId; - } -} - function selectProductionRestart(node) { clearTakeSelection(node); setExistingWidgetValue(findWidget(node, REVIEW_ACTION_WIDGET), REVIEW_ACTION_CONTINUE); @@ -1943,15 +2010,16 @@ async function loadTakeHistory(node) { } function refreshV38TakeHistoryAfterExecution(event) { - const promptId = String(event?.detail?.prompt_id || ""); for (const node of app.graph?._nodes || []) { if (node.comfyClass !== V38_NODE_CLASS) continue; - if (event?.type === "execution_success" && promptId) { - finishModeSetupAfterExecution(node, promptId); - } if (event?.type !== "execution_success") delete node.__h3ContinuumQueuedSettings; + // Terminal events only trigger authoritative Run Storage readback. + // Keep the existing 250 ms retry and release setup only after readback + // has had a chance to publish a newer review_ready/complete revision. void loadTakeHistory(node); + setTimeout(() => finishModeSetupAfterExecution(node), 0); setTimeout(() => void loadTakeHistory(node), 250); + setTimeout(() => finishModeSetupAfterExecution(node), 500); } } @@ -2152,8 +2220,7 @@ function configureProductionReviewUx(node) { const previous = node.onExecuted; node.onExecuted = function(...args) { const result = previous?.apply(this, args); - finishModeSetupAfterExecution(this); - void loadTakeHistory(this); + void loadTakeHistory(this).then(() => finishModeSetupAfterExecution(this)); return result; }; node.__h3ContinuumTakeExecutedRefresh = true; @@ -2401,12 +2468,9 @@ function configureV38ViewProperty(node) { function normalizeRunStorageState(node, apiInputs = null) { const storageWidget = findWidget(node, RUN_STORAGE_WIDGET); const storageEnabled = storageWidget?.value === "Save + Auto Resume"; - if (storageEnabled) { - return true; - } - const regenerateWidget = findWidget(node, REGENERATE_WIDGET); + if (storageEnabled) return true; + setRegenerateProgrammatically(node, "Auto"); const nonceWidget = findWidget(node, REROLL_NONCE_WIDGET); - if (regenerateWidget) regenerateWidget.value = "Auto"; if (nonceWidget) nonceWidget.value = 0; if (apiInputs) { apiInputs[REGENERATE_WIDGET] = "Auto"; @@ -2420,11 +2484,29 @@ function configureConditionalWidgets(node) { const regenerateWidget = findWidget(node, REGENERATE_WIDGET); const nonceWidget = findWidget(node, REROLL_NONCE_WIDGET); const runNameWidget = findWidget(node, LEGACY_RUN_NAME_WIDGET); + if (regenerateWidget && !regenerateWidget.__h3ContinuumManualIntentCallback) { + const previous = regenerateWidget.callback; + regenerateWidget.callback = function(value, ...args) { + const result = previous?.call(this, value, ...args); + if (!node.__h3ContinuumProgrammaticRegenerate) { + if (value === "Auto" || value === 0 || value == null) { + delete node.__h3ContinuumManualRegenerateIntent; + } else { + node.__h3ContinuumManualRegenerateIntent = true; + } + } + return result; + }; + regenerateWidget.__h3ContinuumManualIntentCallback = true; + } const refresh = () => { const productionView = true; const storageEnabled = node.comfyClass === V38_NODE_CLASS ? storageWidget?.value === "Save + Auto Resume" : normalizeRunStorageState(node); + if (node.comfyClass === V38_NODE_CLASS && !storageEnabled) { + normalizeRunStorageState(node); + } const explicitRegeneration = storageEnabled && regenerateWidget?.value !== "Auto" && Number.parseInt(String(regenerateWidget?.value).replace(/^Chunk\s+/, ""), 10) > 0; @@ -2436,27 +2518,27 @@ function configureConditionalWidgets(node) { productionView && linkedInput(node, ["reference_image_1", "reference_image_2", "reference_image_3"]), ); - setWidgetVisible( - findWidget(node, TIMELINE_SIZE_WIDGET), - linkedInput(node, ["timeline_video"]), - ); + setWidgetVisible( + findWidget(node, TIMELINE_SIZE_WIDGET), + linkedInput(node, ["timeline_video"]), + ); setWidgetVisible( findWidget(node, VIDEO_REFERENCE_SIZE_WIDGET), productionView && linkedInput(node, ["reference_video_1"]), ); - node.setDirtyCanvas?.(true, true); - }; + node.setDirtyCanvas?.(true, true); + }; attachRefresh(storageWidget, "__h3ContinuumStorageCallback", refresh); attachRefresh(regenerateWidget, "__h3ContinuumRegenerateVisibilityCallback", refresh); - if (!node.__h3ContinuumConnectionCallback) { - const previous = node.onConnectionsChange; - node.onConnectionsChange = function(...args) { - const result = previous?.apply(this, args); - setTimeout(refresh, 0); - return result; - }; - node.__h3ContinuumConnectionCallback = true; - } + if (!node.__h3ContinuumConnectionCallback) { + const previous = node.onConnectionsChange; + node.onConnectionsChange = function(...args) { + const result = previous?.apply(this, args); + setTimeout(refresh, 0); + return result; + }; + node.__h3ContinuumConnectionCallback = true; + } refresh(); } @@ -2653,74 +2735,58 @@ function resetTakeActionAfterQueued(node) { } function prepareReviewQueueIntent(node, apiInputs) { - if (node.comfyClass !== V38_NODE_CLASS || !apiInputs) { - return false; - } + if (node.comfyClass !== V38_NODE_CLASS || !apiInputs) return false; const generationWidget = findWidget(node, GENERATION_MODE_WIDGET); const actionWidget = findWidget(node, REVIEW_ACTION_WIDGET); - if (!generationWidget || !actionWidget) { - return false; - } + if (!generationWidget || !actionWidget) return false; const generationMode = generationWidget.value; - const selectedAction = actionWidget.value; - const from = findWidget(node, REGENERATE_WIDGET)?.value; - const staleReview = node.__h3ContinuumReviewSettingsChanged?.() || false; const modeSetup = Boolean(node.__h3ContinuumModeSetup); - const savedStatus = canonicalStorageRevision(node.__h3ContinuumTakeProject)?.status; - const savedReview = ["review_ready", "complete"].includes(savedStatus); + const staleReview = node.__h3ContinuumReviewSettingsChanged?.() || false; + const storageEnabled = findWidget(node, RUN_STORAGE_WIDGET)?.value === "Save + Auto Resume"; + const hadFrom = Object.prototype.hasOwnProperty.call(apiInputs, REGENERATE_WIDGET); + const hadNonce = Object.prototype.hasOwnProperty.call(apiInputs, "reroll_nonce"); + let from = hadFrom ? apiInputs[REGENERATE_WIDGET] : findWidget(node, REGENERATE_WIDGET)?.value ?? "Auto"; + let nonce = hadNonce ? apiInputs.reroll_nonce : findWidget(node, "reroll_nonce")?.value ?? 0; + if (modeSetup && from === "Chunk 1" && !node.__h3ContinuumManualRegenerateIntent && !node.__h3ContinuumRestartSelected) { + from = "Auto"; nonce = 0; + setRegenerateProgrammatically(node, "Auto"); + setExistingWidgetValue(findWidget(node, "reroll_nonce"), 0); + } + if (!storageEnabled) { + from = "Auto"; nonce = 0; + setRegenerateProgrammatically(node, "Auto"); + setExistingWidgetValue(findWidget(node, "reroll_nonce"), 0); + } + if (hadFrom || modeSetup || !storageEnabled) apiInputs[REGENERATE_WIDGET] = from; + if (hadNonce || modeSetup || !storageEnabled) apiInputs.reroll_nonce = nonce; const manualRegenerate = from && from !== "Auto" && from !== 0; + const selectedAction = actionWidget.value; const submittedAction = generationMode === GENERATION_MODE_FULL_RUN || staleReview || manualRegenerate || modeSetup - ? REVIEW_ACTION_CONTINUE - : selectedAction; + ? REVIEW_ACTION_CONTINUE : selectedAction; + apiInputs[GENERATION_MODE_WIDGET] = generationMode; + apiInputs[REVIEW_ACTION_WIDGET] = submittedAction; if (staleReview || manualRegenerate || modeSetup) { actionWidget.value = REVIEW_ACTION_CONTINUE; delete node[REVIEW_UI_SELECTION]; } - apiInputs[GENERATION_MODE_WIDGET] = generationMode; - apiInputs[REVIEW_ACTION_WIDGET] = submittedAction; - let takeAction = findWidget(node, TAKE_ACTION_WIDGET)?.value || TAKE_ACTION_AUTOMATIC; - apiInputs[TAKE_GROUP_WIDGET] = Number(findWidget(node, TAKE_GROUP_WIDGET)?.value || 0); - apiInputs[TAKE_REVISION_WIDGET] = String(findWidget(node, TAKE_REVISION_WIDGET)?.value || ""); + const takeDefaults = modeSetup || staleReview; + const takeAction = takeDefaults ? TAKE_ACTION_AUTOMATIC : findWidget(node, TAKE_ACTION_WIDGET)?.value || TAKE_ACTION_AUTOMATIC; + apiInputs[TAKE_GROUP_WIDGET] = takeDefaults ? 0 : Number(findWidget(node, TAKE_GROUP_WIDGET)?.value || 0); + apiInputs[TAKE_REVISION_WIDGET] = takeDefaults ? "" : String(findWidget(node, TAKE_REVISION_WIDGET)?.value || ""); apiInputs[TAKE_ACTION_WIDGET] = takeAction; if (generationMode === GENERATION_MODE_REVIEW && modeSetup) { - // Saved results are history, not the first result of a newly selected - // Review Each Chunk run. Start a non-destructive branch at Chunk 1 in - // the queued payload; keep the visible settings unchanged. - if (savedReview) { - apiInputs[REGENERATE_WIDGET] = "Chunk 1"; - apiInputs[REROLL_NONCE_WIDGET] = 0; - apiInputs[TAKE_GROUP_WIDGET] = 0; - apiInputs[TAKE_REVISION_WIDGET] = ""; - apiInputs[TAKE_ACTION_WIDGET] = TAKE_ACTION_AUTOMATIC; - takeAction = TAKE_ACTION_AUTOMATIC; - } - node.__h3ContinuumModeSetupQueued = { - setup: node.__h3ContinuumModeSetup, - runName: takeRunName(node), - }; + const revision = canonicalStorageRevision(node.__h3ContinuumTakeProject); + node.__h3ContinuumModeSetupQueued = {setup: node.__h3ContinuumModeSetup, runName: takeRunName(node), baselineRevision: String(revision?.revision_id || "")}; } else { delete node.__h3ContinuumModeSetupQueued; } node.__h3ContinuumCaptureReviewSettings?.(); - if (node.__h3ContinuumRestartSelected && from === "Chunk 1") { - node.__h3ContinuumRestartQueued = true; - } else { - delete node.__h3ContinuumRestartSelected; - delete node.__h3ContinuumRestartQueued; - } - if ( - generationMode === GENERATION_MODE_REVIEW - && isOneShotReviewAction(submittedAction) - ) { - node[REVIEW_PENDING_ACTION] = submittedAction; - } else { - delete node[REVIEW_PENDING_ACTION]; - } - if (takeAction === TAKE_ACTION_USE || takeAction === TAKE_ACTION_CONTINUE) { - node[TAKE_PENDING_ACTION] = takeAction; - } else { - delete node[TAKE_PENDING_ACTION]; - } + if (node.__h3ContinuumRestartSelected && from === "Chunk 1") node.__h3ContinuumRestartQueued = true; + else { delete node.__h3ContinuumRestartSelected; delete node.__h3ContinuumRestartQueued; } + if (generationMode === GENERATION_MODE_REVIEW && isOneShotReviewAction(submittedAction)) node[REVIEW_PENDING_ACTION] = submittedAction; + else delete node[REVIEW_PENDING_ACTION]; + if (takeAction === TAKE_ACTION_USE || takeAction === TAKE_ACTION_CONTINUE) node[TAKE_PENDING_ACTION] = takeAction; + else delete node[TAKE_PENDING_ACTION]; return true; } @@ -2796,48 +2862,48 @@ function configureReviewControls(node) { } function configureAssembler(node) { - if ( - node.comfyClass !== ASSEMBLE_SEAM_NODE_CLASS - && node.comfyClass !== V34_ASSEMBLE_SEAM_NODE_CLASS - && node.comfyClass !== V35_ASSEMBLE_SEAM_NODE_CLASS - ) { - return false; - } - const exactDuration = findWidget(node, "exact_total_duration"); - if (exactDuration) exactDuration.value = true; - applyRuntimeSettings(node); - hidePersistentWidget(exactDuration); - hidePersistentWidget(findWidget(node, "diagnostics")); - node.setDirtyCanvas?.(true, true); - return true; -} - -function configureNode(node) { - const isProduction = node.comfyClass === PRODUCTION_NODE_CLASS; - const isTimeline = node.comfyClass === TIMELINE_NODE_CLASS; - const isV34 = node.comfyClass === V34_NODE_CLASS; + if ( + node.comfyClass !== ASSEMBLE_SEAM_NODE_CLASS + && node.comfyClass !== V34_ASSEMBLE_SEAM_NODE_CLASS + && node.comfyClass !== V35_ASSEMBLE_SEAM_NODE_CLASS + ) { + return false; + } + const exactDuration = findWidget(node, "exact_total_duration"); + if (exactDuration) exactDuration.value = true; + applyRuntimeSettings(node); + hidePersistentWidget(exactDuration); + hidePersistentWidget(findWidget(node, "diagnostics")); + node.setDirtyCanvas?.(true, true); + return true; +} + +function configureNode(node) { + const isProduction = node.comfyClass === PRODUCTION_NODE_CLASS; + const isTimeline = node.comfyClass === TIMELINE_NODE_CLASS; + const isV34 = node.comfyClass === V34_NODE_CLASS; const isV35 = node.comfyClass === V35_NODE_CLASS; const isV36 = node.comfyClass === V36_NODE_CLASS; const isV37 = node.comfyClass === V37_NODE_CLASS; const isV38 = node.comfyClass === V38_NODE_CLASS; if (!isProduction && !isTimeline && !isV34 && !isV35 && !isV36 && !isV37 && !isV38) { - configureAssembler(node); - return null; - } - const projectWidget = findWidget(node, PROJECT_WIDGET); + configureAssembler(node); + return null; + } + const projectWidget = findWidget(node, PROJECT_WIDGET); if (isProduction || isV34 || isV35 || isV36 || isV37 || isV38) { - if (projectWidget && !String(projectWidget.value || "").trim()) { - projectWidget.value = createProjectId(); - } + if (projectWidget && !String(projectWidget.value || "").trim()) { + projectWidget.value = createProjectId(); + } if (!isV38) removeUnusedInput(node, PROMPT_OVERRIDES_INPUT); - } + } applyRuntimeSettings(node); if (isV35 || isV36 || isV37 || isV38) { normalizeReferenceAudioLabels(node); } - hidePersistentWidget(findWidget(node, "diagnostics")); - hidePersistentWidget(findWidget(node, "strict_compatibility")); - hidePersistentWidget(findWidget(node, "debug")); + hidePersistentWidget(findWidget(node, "diagnostics")); + hidePersistentWidget(findWidget(node, "strict_compatibility")); + hidePersistentWidget(findWidget(node, "debug")); hidePersistentWidget(findWidget(node, "show_preview")); hidePersistentWidget(projectWidget); hidePersistentWidget(findWidget(node, TAKE_GROUP_WIDGET)); @@ -2853,24 +2919,20 @@ function configureNode(node) { installReviewModeSetupQueueContract(node); applyV38View(node); node.setDirtyCanvas?.(true, true); - return projectWidget; -} - -function configureNodeAfterSetup(node) { - configureNode(node); - const configureDeferred = () => configureNode(node); - setTimeout(configureDeferred, 0); - setTimeout(configureDeferred, 100); -} - -app.registerExtension({ + return projectWidget; +} + +function configureNodeAfterSetup(node) { + configureNode(node); + const configureDeferred = () => configureNode(node); + setTimeout(configureDeferred, 0); + setTimeout(configureDeferred, 100); +} + +app.registerExtension({ name: "H3Continuum.ProjectId", setup() { - app.api?.addEventListener?.( - "executed", - bindModeSetupPromptFromExecutedNode, - ); for (const eventName of [ "execution_success", "execution_error", @@ -2882,56 +2944,56 @@ app.registerExtension({ ); } const settings = app.ui?.settings; - settings?.addSetting?.({ - id: SETTINGS.samplingPreview, - name: "H3 Continuum: Sampling Preview", - type: "boolean", - defaultValue: true, - tooltip: "Show live sampling previews. Disable only to reduce preview overhead.", - onChange: () => refreshConfiguredNodes(), - }); - settings?.addSetting?.({ - id: SETTINGS.developerDiagnostics, - name: "H3 Continuum: Developer Diagnostics", - type: "boolean", - defaultValue: false, - tooltip: "Enable developer-only Continuum logging and assertions.", - onChange: () => refreshConfiguredNodes(), - }); - settings?.addSetting?.({ - id: SETTINGS.detailedReport, - name: "H3 Continuum: Detailed Report", - type: "boolean", - defaultValue: false, - tooltip: "Include detailed diagnostics in status and assembly reports.", - onChange: () => refreshConfiguredNodes(), - }); - }, - - nodeCreated(node) { - configureNodeAfterSetup(node); - }, - + settings?.addSetting?.({ + id: SETTINGS.samplingPreview, + name: "H3 Continuum: Sampling Preview", + type: "boolean", + defaultValue: true, + tooltip: "Show live sampling previews. Disable only to reduce preview overhead.", + onChange: () => refreshConfiguredNodes(), + }); + settings?.addSetting?.({ + id: SETTINGS.developerDiagnostics, + name: "H3 Continuum: Developer Diagnostics", + type: "boolean", + defaultValue: false, + tooltip: "Enable developer-only Continuum logging and assertions.", + onChange: () => refreshConfiguredNodes(), + }); + settings?.addSetting?.({ + id: SETTINGS.detailedReport, + name: "H3 Continuum: Detailed Report", + type: "boolean", + defaultValue: false, + tooltip: "Include detailed diagnostics in status and assembly reports.", + onChange: () => refreshConfiguredNodes(), + }); + }, + + nodeCreated(node) { + configureNodeAfterSetup(node); + }, + loadedGraphNode(node) { normalizeReviewActionOnLoad(node); configureNodeAfterSetup(node); - }, - - afterConfigureGraph() { - for (const node of app.graph?._nodes || []) { - configureNodeAfterSetup(node); - } - }, - - async beforeQueuePrompt(prompt) { - const seen = new Set(); - for (const node of app.graph?._nodes || []) { + }, + + afterConfigureGraph() { + for (const node of app.graph?._nodes || []) { + configureNodeAfterSetup(node); + } + }, + + async beforeQueuePrompt(prompt) { + const seen = new Set(); + for (const node of app.graph?._nodes || []) { const projectWidget = configureNode(node); const apiNode = prompt.output?.[String(node.id)]; if (apiNode?.inputs) { - if ( - node.comfyClass === PRODUCTION_NODE_CLASS - || node.comfyClass === TIMELINE_NODE_CLASS + if ( + node.comfyClass === PRODUCTION_NODE_CLASS + || node.comfyClass === TIMELINE_NODE_CLASS || node.comfyClass === V34_NODE_CLASS || node.comfyClass === V35_NODE_CLASS || node.comfyClass === V36_NODE_CLASS @@ -2949,40 +3011,40 @@ app.registerExtension({ } prepareReviewQueueIntent(node, apiNode.inputs); apiNode.inputs.diagnostics = settingValue(SETTINGS.detailedReport, false) - ? "Detailed Report" - : "Basic"; - apiNode.inputs.debug = Boolean(settingValue(SETTINGS.developerDiagnostics, false)); - apiNode.inputs.show_preview = Boolean(settingValue(SETTINGS.samplingPreview, true)); - apiNode.inputs.strict_compatibility = false; - } else if ( - node.comfyClass === ASSEMBLE_SEAM_NODE_CLASS - || node.comfyClass === V34_ASSEMBLE_SEAM_NODE_CLASS - || node.comfyClass === V35_ASSEMBLE_SEAM_NODE_CLASS - ) { - apiNode.inputs.diagnostics = settingValue(SETTINGS.detailedReport, false) - ? "Detailed Report" - : "Basic"; - apiNode.inputs.exact_total_duration = true; - } - } - if (!projectWidget) { - continue; - } - let projectId = String(projectWidget.value || "").trim(); - if (!projectId || seen.has(projectId)) { - projectId = createProjectId(); - projectWidget.value = projectId; - } - seen.add(projectId); - if (apiNode?.inputs) { - apiNode.inputs.project_id = projectId; - } - } - }, -}); - -function refreshConfiguredNodes() { - for (const node of app.graph?._nodes || []) { - configureNodeAfterSetup(node); - } -} + ? "Detailed Report" + : "Basic"; + apiNode.inputs.debug = Boolean(settingValue(SETTINGS.developerDiagnostics, false)); + apiNode.inputs.show_preview = Boolean(settingValue(SETTINGS.samplingPreview, true)); + apiNode.inputs.strict_compatibility = false; + } else if ( + node.comfyClass === ASSEMBLE_SEAM_NODE_CLASS + || node.comfyClass === V34_ASSEMBLE_SEAM_NODE_CLASS + || node.comfyClass === V35_ASSEMBLE_SEAM_NODE_CLASS + ) { + apiNode.inputs.diagnostics = settingValue(SETTINGS.detailedReport, false) + ? "Detailed Report" + : "Basic"; + apiNode.inputs.exact_total_duration = true; + } + } + if (!projectWidget) { + continue; + } + let projectId = String(projectWidget.value || "").trim(); + if (!projectId || seen.has(projectId)) { + projectId = createProjectId(); + projectWidget.value = projectId; + } + seen.add(projectId); + if (apiNode?.inputs) { + apiNode.inputs.project_id = projectId; + } + } + }, +}); + +function refreshConfiguredNodes() { + for (const node of app.graph?._nodes || []) { + configureNodeAfterSetup(node); + } +}