Skip to content

HarnessRouter Community Edition: the self-hosted, Apache-2.0 edition of the unified interface for agent harnesses. Run Codex, Claude Code, Hermes, PI, DSH, and more through one API, with sessions, streaming, files, cancellation, and failure handling. Implements the Unified Harness Protocol (UHP), an open standard. Your keys, your infrastructure.

fix(media): a still's length was answered in five places, and the film believed the wrong one

richard-epsillacccb6393069e
diff --git a/gateway/app.py b/gateway/app.py
index 59e6f378..ca5cf2f8 100644
--- a/gateway/app.py
+++ b/gateway/app.py
@@ -7722,9 +7722,8 @@ def _uhp_message(e: HTTPException) -> str:
_MEDIA_SERVER = "media"
_MEDIA_SCENE_FILE = "scene.excalidraw"
-# How long a still is held when the cut does not say. Not a measurement — a still has no
-# length of its own — so it is a stated default rather than a number pretending to be one.
-STILL_HOLD_S = 3.0
+# How long a still is held when the cut does not say lives with the rest of that decision, in
+# media_plane.shot_window — a second copy here is how the total and the film came to disagree.
# Candidates stood down after a BILLABLE failure. Per-replica and in memory on purpose: it is a
# hint that saves money, not state anything depends on, and a replica that has not seen the
# failure simply pays for one more attempt rather than serving a stale verdict for half an hour.
@@ -9720,8 +9719,12 @@ async def _media_tool_call(name: str, args: dict, hid: str, sid: str, org: str,
rw, rh = media_plane.parse_size(res)
if w and h and rw and rh and abs(w / h - rw / rh) > 0.02:
warnings.append(f"Shot {i} is {w}x{h} and will be letterboxed into {res}.")
- shots.append({"elementId": eid, "inS": float(s.get("in_s") or 0.0),
- "outS": float(s.get("out_s") or m.get("seconds") or 0.0)})
+ # Normalised on the way IN, so what is stored is what will be filmed. Written
+ # raw, a still the agent placed without a duration was stored as outS 0 — in the
+ # cut, absent from the film, and nothing anywhere said why.
+ a, b, _ = media_plane.shot_window(
+ {"inS": s.get("in_s"), "outS": s.get("out_s")}, m)
+ shots.append({"elementId": eid, "inS": a, "outS": b})
audio = [{"elementId": str(a.get("element_id") or ""),
"startS": float(a.get("start_s") or 0.0),
"gainDb": float(a.get("gain_db") or 0.0)} for a in audio_in]
@@ -9789,13 +9792,10 @@ async def _media_export_start(hid: str, sid: str, org: str, entry_id: str,
raise media_plane.ExportRefused(
f"Shot {i} is still rendering. Every shot has to have landed before the film can "
f"be cut.")
- # A still carries no `seconds`, so its hold comes from the SHOT. Falling through to 0 is
- # what made an image in the cut fail the whole export.
- out_s = s.get("outS")
- if out_s is None:
- out_s = m.get("seconds") or (STILL_HOLD_S if m.get("kind") == "image" else 0.0)
- plan.append({"media_id": str(m["mediaId"]), "in_s": float(s.get("inS") or 0.0),
- "out_s": float(out_s or 0.0)})
+ # What window of the clip this shot shows — asked of the one function that answers it, so
+ # the film, the planned total and the preview cannot come to different conclusions.
+ in_s, out_s, still = media_plane.shot_window(s, m)
+ plan.append({"media_id": str(m["mediaId"]), "in_s": in_s, "out_s": out_s, "still": still})
total = media_plane.timeline_total(scene)
if total > float(cap.get("max_total_s") or 600):
raise media_plane.ExportRefused(
@@ -9836,7 +9836,8 @@ async def _media_export_run(job: dict, plan: list[dict], audio_plan: list[dict],
raise media_plane.ExportRefused(f"Shot {i + 1} is no longer readable.")
path = os.path.join(tmp, f"shot{i}.{meta.get('ext') or 'mp4'}")
pathlib.Path(path).write_bytes(data)
- shots.append({"path": path, "in_s": s["in_s"], "out_s": s["out_s"]})
+ shots.append({"path": path, "in_s": s["in_s"], "out_s": s["out_s"],
+ "still": s["still"]})
job["progress"] = f"{i + 1}/{len(plan)} shots"
await _media_job_save(job)
tracks = []
diff --git a/gateway/media_plane.py b/gateway/media_plane.py
index 059214cf..62ad4291 100644
--- a/gateway/media_plane.py
+++ b/gateway/media_plane.py
@@ -1533,11 +1533,11 @@ def assemble(shots: list[dict], audio: list[dict], *, fps: int, resolution: str,
end = float(shot.get("out_s") or dur or 0.0) or dur
end = min(end, dur) if dur else end
- # A STILL HAS NO DURATION OF ITS OWN, so the CUT decides how long it is shown. ffprobe
- # reports 0 seconds for a png, which used to make this refuse the whole film with "shot N
- # has no length" — the still was in the timeline, the export was impossible, and nothing
- # said the two facts were connected. `-loop 1 -t` is what turns one frame into a segment.
- still = dur <= 0 and not info.get("has_audio")
+ # A STILL HAS NO DURATION OF ITS OWN, so the CUT decides how long it is shown, and
+ # `-loop 1 -t` is what turns one frame into a segment. WHETHER a shot is a still is the
+ # caller's to state — see shot_window(). This asked ffprobe once, and a jpeg (which
+ # reports 0.04s) was clamped to a single frame while the identical png was held for 3s.
+ still = bool(shot.get("still")) or (dur <= 0 and not info.get("has_audio"))
if still:
hold = float(shot.get("out_s") or 0.0) - start
if hold <= 0:
@@ -1867,6 +1867,40 @@ def sanitize_scene(doc) -> dict:
return out
+# How long a still is held when the cut doesn't say. The kit has the same number in
+# src/lib/timeline.js — a preview that disagrees with the film is the bug this whole module
+# exists to prevent, so the two constants are one decision written twice, and neither moves alone.
+STILL_HOLD_S = 3.0
+
+
+def shot_window(shot: dict, media: dict) -> tuple[float, float, bool]:
+ """What part of a clip a shot shows: (in_s, out_s, is_still). THE answer to that question.
+
+ It used to be answered in five places that disagreed. A 13-second cut exported as a 10-second
+ film and every guard passed, because the planner said a still lasts STILL_HOLD_S, the total
+ said an unbounded still lasts 0s, and the assembler asked ffprobe — which reports no duration
+ for a png and 0.04s (one frame at 25fps) for a jpeg. Same picture, three answers, and the
+ jpeg was cut down to a single frame.
+
+ A STILL IS A STILL BECAUSE THE DOCUMENT SAYS IT IS AN IMAGE. Not because a file failed to
+ report a duration. It has no length of its own, so the cut decides; if the cut is silent it
+ is held for STILL_HOLD_S. A video is bounded by the length it was actually measured to be.
+ """
+ dur = float(media.get("seconds") or 0.0)
+ still = media.get("kind") == "image" or (dur <= 0 and media.get("kind") != "video")
+ in_s = max(0.0, float(shot.get("inS") or 0.0))
+ raw = shot.get("outS")
+ out_s = float(raw) if raw not in (None, "") else 0.0
+ if still:
+ # 0 gets here from writers that fell back to `seconds` a still does not have.
+ if out_s <= in_s:
+ out_s = in_s + STILL_HOLD_S
+ return in_s, out_s, True
+ if out_s <= 0 or out_s > dur:
+ out_s = dur
+ return min(in_s, out_s), out_s, False
+
+
def timeline_total(scene: dict, ready_only: bool = False) -> float:
"""Summed from the clips' REAL measured durations, never from the seconds someone asked for."""
by_id = {e.get("id"): e for e in scene.get("elements") or []}
@@ -1876,10 +1910,8 @@ def timeline_total(scene: dict, ready_only: bool = False) -> float:
m = media_of(el)
if ready_only and m.get("status") != "ready":
continue
- dur = float(m.get("seconds") or 0.0)
- a = float(shot.get("inS") or 0.0)
- b = float(shot.get("outS") or dur or 0.0) or dur
- total += max(0.0, min(b, dur or b) - a)
+ a, b, _ = shot_window(shot, m)
+ total += max(0.0, b - a)
return round(total, 3)
diff --git a/gateway/tests/test_media_mcp.py b/gateway/tests/test_media_mcp.py
index 08e7eccb..c37c916e 100644
--- a/gateway/tests/test_media_mcp.py
+++ b/gateway/tests/test_media_mcp.py
@@ -2155,6 +2155,69 @@ def test_export_fails_when_the_assembled_length_is_not_the_planned_length(monkey
assert "Nothing was delivered" in msg
+def _still(ext: str, size: str = "128x72") -> bytes:
+ """One real picture. The ENCODING is the point: ffprobe reports no duration for a png and
+ 0.04s — one frame at 25fps — for a jpeg, and the exporter used to believe it."""
+ with tempfile.TemporaryDirectory() as d:
+ out = os.path.join(d, f"s.{ext}")
+ subprocess.run(["ffmpeg", "-nostdin", "-y", "-f", "lavfi",
+ "-i", f"color=c=red:s={size}:d=1", "-frames:v", "1", out],
+ capture_output=True, check=True)
+ return Path(out).read_bytes()
+
+
+@needs_ffmpeg
[email protected]("ext,probed", [("png", 0.0), ("jpg", 0.04)])
+def test_a_still_is_held_for_its_full_window_whatever_the_file_says_it_is(monkeypatch, ext,
+ probed):
+ """A 3-second still is 3 seconds of film.
+
+ `probed` is not invented: the deployment's ffprobe read the png as having no duration and the
+ jpeg as 0.04s — one frame at 25fps — so the exporter held one for three seconds and clamped
+ the other to a single frame. A 13-second timeline came out as a 10-second film and no guard
+ objected, because the plan had asked the same wrong question. Which build of ffmpeg is
+ installed must not be able to change the length of a customer's film.
+ """
+ real = media_plane.probe_file
+ with tempfile.TemporaryDirectory() as d:
+ pic = os.path.join(d, f"s.{ext}")
+ Path(pic).write_bytes(_still(ext))
+ out = os.path.join(d, "out.mp4")
+ monkeypatch.setattr(media_plane, "probe_file",
+ lambda p: {**real(p), "seconds": probed} if p == pic else real(p))
+ got = media_plane.assemble(
+ [{"path": pic, "in_s": 0.0, "out_s": 3.0, "still": True}], [],
+ fps=24, resolution="320x180", out_path=out)
+ assert abs(float(got["seconds"]) - 3.0) < 0.25, got
+
+
+def test_shot_window_answers_for_a_still_the_same_way_however_the_shot_was_written():
+ """The three writers that fed the export each had their own idea of a still's length: one
+ wrote outS 0, one left it out, one measured the file. All three mean 'hold it'."""
+ img = {"kind": "image", "status": "ready", "mediaId": "m1"}
+ for shot in ({"inS": None, "outS": None}, {"inS": 0, "outS": 0}, {}):
+ a, b, still = media_plane.shot_window(shot, img)
+ assert (a, b, still) == (0.0, media_plane.STILL_HOLD_S, True), shot
+ # An explicit hold is obeyed, and a video is still bounded by what it was measured to be.
+ assert media_plane.shot_window({"inS": 1, "outS": 5}, img) == (1.0, 5.0, True)
+ vid = {"kind": "video", "status": "ready", "seconds": 6.0}
+ assert media_plane.shot_window({"inS": 0, "outS": 99}, vid) == (0.0, 6.0, False)
+ assert media_plane.shot_window({"inS": 2, "outS": None}, vid) == (2.0, 6.0, False)
+
+
+def test_the_planned_total_counts_a_still_that_nothing_gave_a_length():
+ """timeline_total is the number the app shows and the number the export promises. It read 0
+ for an unbounded still while the timeline drew 3 seconds of it."""
+ scene = {"elements": [{"id": "e1", "customData": {"media": {"kind": "image", "status":
+ "ready", "mediaId": "m1"}}},
+ {"id": "e2", "customData": {"media": {"kind": "video", "status":
+ "ready", "mediaId": "m2",
+ "seconds": 6.0}}}],
+ "timeline": {"shots": [{"elementId": "e1"},
+ {"elementId": "e2", "inS": 0, "outS": 2.0}]}}
+ assert media_plane.timeline_total(scene) == media_plane.STILL_HOLD_S + 2.0
+
+
@needs_ffmpeg
def test_export_refuses_while_a_shot_is_still_rendering(client, harness, session, provider):
tok = _cred(harness, session)