fix(producer): probe sub-composition media defaults (#7550)

* fix(producer): probe sub-composition media defaults

Sub-composition defaults declared on <html> disappear from the DOM
during inlining. The browser-probe gate then misses data-var-src
bindings, causing renders to use the authored placeholder source.

Pass the inliner's variablesByComp table through CompiledComposition
and consult the nearest composition scope when checking media bindings.

Give anonymous mounts distinct runtime scopes and reserve IDs as
nested mounts are processed, preserving each instance's variable values.

Add regression coverage for declared defaults, repeated mounts,
nested scopes, and named/anonymous mount collisions.

Fixes #7505

* fix(core): keep anonymous hosts unnamed, key their variables by the authored id

The previous commit made an anonymous mount claim its sub-composition's id on
the host element, which changed the DOM contract the runtime mount path and
the `missing-host-comp-id` regression golden pin: the compile paths put the
host's start/duration on the composition while the mount path kept them on an
unnamed timed element, so the producer parity test and the regression shard
failed on the first CI run.

Restore the contract: an anonymous host carries no composition id and its
flattened wrapper keeps the authored one. For #7505 that wrapper is already
the scope the probe gate (and `variableScope.ts`) resolves through, so the
inliner now keys an anonymous mount's merged defaults by the authored id
instead of skipping them. A named mount of the same file shares that scope;
its explicit instance values win regardless of inlining order, which the
replacement unit test pins in both orders. The id-reservation machinery for
claimed ids goes with the claim.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
Ice cola
2026-11-16 18:58:41 +00:00
committed by GitHub
co-authored by Claude Fable 5.1
parent af873924db
commit 95e4e7f880
7 changed files with 169 additions and 14 deletions
@@ -264,6 +264,7 @@ describe("inlineSubCompositions – #ID selector scoping divergence", () => {
flattenInnerRoot,
});
expect(host.hasAttribute("data-composition-id")).toBe(false);
const wrapper = host.querySelector("[data-hf-inner-root]");
expect(wrapper?.getAttribute("data-composition-id")).toBe("scoped-text");
@@ -574,6 +575,50 @@ describe("inlineSubCompositions – variable defaults on a template sub-comp roo
});
expect(result.variablesByComp["card"]).toMatchObject({ headline: "Overridden" });
});
it("keys an anonymous host's values by the sub-composition's own id, which its wrapper and scripts use", () => {
const { document } = parseHTML(`<!DOCTYPE html><html><body>
<div data-composition-id="main">
<div data-composition-src="card.html" data-start="0" data-duration="4" data-track-index="0"></div>
</div></body></html>`);
const host = document.querySelector('[data-composition-src="card.html"]')!;
const result = inlineSubCompositions(document, [host], {
resolveHtml: () => SUB_COMP_WITH_VAR,
parseHtml: (h) => parseHTML(h).document,
readVariableDefaults: readDeclaredDefaults,
parseHostVariables: parseHostVariableValues,
});
expect(result.variablesByComp["card"]).toMatchObject({ headline: "Hi there" });
// The host stays anonymous; the preserved wrapper is what carries the id.
expect(host.hasAttribute("data-composition-id")).toBe(false);
expect(host.querySelector('[data-composition-id="card"]')).not.toBeNull();
});
it.each([
["named first", ["named", "anonymous"]],
["anonymous first", ["anonymous", "named"]],
] as const)(
"keeps a named mount's values when an anonymous mount of the same file shares its scope (%s)",
(_order, order) => {
// Both mounts resolve through `[data-composition-id="card"]`: the named
// host carries it, the anonymous wrapper keeps it. The explicit instance
// values on the named host must win whichever mount is inlined first.
const { document } = parseHTML(`<!DOCTYPE html><html><body>
<div data-composition-id="main">
<div id="named" data-composition-id="card" data-composition-src="card.html" data-variable-values='{"headline":"Custom"}' data-start="0" data-duration="4" data-track-index="0"></div>
<div id="anonymous" data-composition-src="card.html" data-start="0" data-duration="4" data-track-index="1"></div>
</div></body></html>`);
const hosts = order.map((id) => document.querySelector(`#${id}`)!);
const result = inlineSubCompositions(document, hosts, {
resolveHtml: () => SUB_COMP_WITH_VAR,
parseHtml: (h) => parseHTML(h).document,
readVariableDefaults: readDeclaredDefaults,
parseHostVariables: parseHostVariableValues,
});
expect(result.variablesByComp).toEqual({ card: { headline: "Custom" } });
expect(document.querySelector("#anonymous")!.hasAttribute("data-composition-id")).toBe(false);
},
);
});
describe("inlineSubCompositions – recursive host discovery", () => {
@@ -434,6 +434,7 @@ export function inlineSubCompositions(
const scopeCssToComposition = createCompositionCssScoper();
const sceneHosts = new Map<string, Element>();
const queue = hosts.map((element) => ({
element,
ancestry: [] as string[],
@@ -526,14 +527,26 @@ export function inlineSubCompositions(
// document element (full-document sub-comps) AND the inner composition root
// (template/fragment sub-comps store their schema on the root div, not a
// synthetic <html>), then let per-instance host values override.
if (readVariableDefaults && parseHostVariables && runtimeCompId) {
//
// An anonymous host has no runtime id of its own. Its wrapper keeps the
// authored composition id (restored below), so that id is the scope its
// bound media and scripts resolve variables through (runtime/variableScope.ts)
// and the key the producer's probe gate reads — a full-document sub-comp's
// `<html data-composition-variables>` is dropped by inlining, so the table
// is the only place its declared defaults survive to compile time (#7505).
// A named mount of the same file shares that scope and its explicit
// instance values win, so an anonymous mount only fills the entry while
// nothing holds it; a named mount processed later still overwrites it.
const variablesCompId = runtimeCompId || scopeCompId;
if (readVariableDefaults && parseHostVariables && variablesCompId) {
const mergedVariables: Record<string, unknown> = {};
for (const carrier of plan.variableDefaultCarriers) {
Object.assign(mergedVariables, readVariableDefaults(carrier));
}
Object.assign(mergedVariables, parseHostVariables(hostEl));
if (Object.keys(mergedVariables).length > 0) {
variablesByComp[runtimeCompId] = mergedVariables;
const holdsEntry = !runtimeCompId && Object.hasOwn(variablesByComp, variablesCompId);
if (Object.keys(mergedVariables).length > 0 && !holdsEntry) {
variablesByComp[variablesCompId] = mergedVariables;
}
// Compile time is the only place this defect is visible on the sub-comp
// path: the instance value is baked into `__hfVariablesByComp` right
@@ -541,8 +554,8 @@ export function inlineSubCompositions(
// runtime's identical guard never runs. Same helper, so the message and
// the per-process dedupe set are shared with the runtime path and the
// author sees one warning either way.
warnUnknownEnumValues(compDoc.documentElement, mergedVariables, runtimeCompId);
warnUnknownEnumValues(innerRoot, mergedVariables, runtimeCompId);
warnUnknownEnumValues(compDoc.documentElement, mergedVariables, variablesCompId);
warnUnknownEnumValues(innerRoot, mergedVariables, variablesCompId);
}
// `<head>` <link>/<script src> are hoisted into the ROOT document, so they
@@ -488,7 +488,9 @@ async function mountCompositionContent(params: {
// `querySelector('[data-composition-id="..."]')`.
const scriptScopeCompositionId = plan.scriptCompositionId;
// No fallback to the authored id: an anonymous host has no runtime id, and
// the compiler emits no runtime scope selector and no variable table for one.
// the compiler emits no runtime scope selector for one. (Its declared
// defaults are keyed by the authored id its restored wrapper carries — see
// inlineSubCompositions — which is also the scope variableScope.ts resolves.)
const runtimeScopeCompositionId = params.runtimeCompositionId || null;
const authoredRootId = plan.authoredRootId;
const runtimeScopeSelector = runtimeScopeCompositionId
@@ -158,6 +158,7 @@ export interface CompiledComposition {
gradedCanvas: boolean;
masterFxChain?: string;
unresolvedCompositions: UnresolvedElement[];
variablesByComp: Record<string, Record<string, unknown>>;
/** Assets that resolve outside projectDir. Keys are the path used in HTML, values are absolute filesystem paths. */
externalAssets: Map<string, string>;
width: number;
@@ -1120,7 +1121,7 @@ function inlineSubCompositions(
projectDir: string,
variableOverrides: Record<string, unknown>,
assetRoot: string | undefined,
): string {
): { html: string; variablesByComp: Record<string, Record<string, unknown>> } {
const { document } = parseHTML(html);
const head = document.querySelector("head");
const body = document.querySelector("body");
@@ -1136,7 +1137,7 @@ function inlineSubCompositions(
{},
variableOverrides,
);
return emitted ? document.toString() : html;
return { html: emitted ? document.toString() : html, variablesByComp: {} };
}
// Assign per-instance runtime composition ids before each host is inlined,
@@ -1297,7 +1298,7 @@ function inlineSubCompositions(
// anything downstream keys media on an id. See core's mediaRenderIds.ts.
assignMediaRenderIds(document as unknown as Document);
return document.toString();
return { html: document.toString(), variablesByComp: result.variablesByComp };
}
/**
@@ -2262,7 +2263,7 @@ export async function compileForRender(
// Inline sub-compositions into the main HTML so the runtime takes the same
// synchronous code path as the bundled preview (no async fetch of
// data-composition-src). This mirrors what htmlBundler.ts does for preview.
const inlinedHtml = inlineSubCompositions(
const { html: inlinedHtml, variablesByComp } = inlineSubCompositions(
fullHtml,
subCompositions,
projectDir,
@@ -2500,6 +2501,7 @@ export async function compileForRender(
gradedCanvas,
...(masterFxChain ? { masterFxChain } : {}),
unresolvedCompositions,
variablesByComp,
externalAssets,
width,
height,
@@ -40,6 +40,22 @@ describe("compileForRender variable-bound media", () => {
join(projectDir, "index.html"),
`<!doctype html><html><body><main data-composition-id="root" data-start="0" data-duration="60" data-width="16" data-height="16"><div data-composition-id="clip" data-composition-src="compositions/clip.html" data-start="0" data-duration="60" data-width="16" data-height="16" data-variable-values='{"src":"assets/clip.mp4"}'></div></main></body></html>`,
);
// A full-document sub-composition declares the default on its own <html>,
// which inlining drops; only __hfVariablesByComp still carries it.
writeFileSync(
join(projectDir, "compositions", "card.html"),
`<!doctype html><html data-composition-variables='[{"id":"src","type":"string","default":"assets/clip.mp4"}]'><body><div data-composition-id="card" data-width="16" data-height="16"><video id="v" muted src="../assets/placeholder.mp4" data-var-src="src" data-start="0" data-duration="60" data-track-index="0"></video></div></body></html>`,
);
writeFileSync(
join(projectDir, "index-declared-default.html"),
`<!doctype html><html><body><main data-composition-id="root" data-start="0" data-duration="60" data-width="16" data-height="16"><div data-composition-id="card" data-composition-src="compositions/card.html" data-start="0" data-duration="60" data-width="16" data-height="16"></div></main></body></html>`,
);
// Same mount with no authored data-composition-id: the flattened inner
// root keeps the sub-composition's own id, which keys its table entry.
writeFileSync(
join(projectDir, "index-anonymous-host.html"),
`<!doctype html><html><body><main data-composition-id="root" data-start="0" data-duration="60" data-width="16" data-height="16"><div data-composition-src="compositions/card.html" data-start="0" data-duration="60" data-width="16" data-height="16"></div></main></body></html>`,
);
});
afterAll(() => rmSync(projectDir, { recursive: true, force: true }));
@@ -51,7 +67,27 @@ describe("compileForRender variable-bound media", () => {
// Compile reads the authored 3 s placeholder; only the browser knows the mount binds the 13 s clip.
expect(compiled.videos.map((video) => video.src)).toEqual(["assets/placeholder.mp4"]);
expect(hasVariableBoundMedia(compiled.html, undefined)).toBe(true);
expect(hasVariableBoundMedia(compiled.html, undefined, compiled.variablesByComp)).toBe(true);
});
it("probes a clip bound to its sub-composition's own declared default", async () => {
const entry = join(projectDir, "index-declared-default.html");
const options = { allowSystemFontCapture: false };
const compiled = await compileForRender(projectDir, entry, projectDir, options);
expect(compiled.videos.map((video) => video.src)).toEqual(["assets/placeholder.mp4"]);
expect(compiled.variablesByComp).toEqual({ card: { src: "assets/clip.mp4" } });
expect(hasVariableBoundMedia(compiled.html, undefined, compiled.variablesByComp)).toBe(true);
});
it("probes an anonymous mount whose default lives in the sub-composition's table entry", async () => {
const entry = join(projectDir, "index-anonymous-host.html");
const options = { allowSystemFontCapture: false };
const compiled = await compileForRender(projectDir, entry, projectDir, options);
expect(compiled.videos.map((video) => video.src)).toEqual(["assets/placeholder.mp4"]);
expect(compiled.variablesByComp).toEqual({ card: { src: "assets/clip.mp4" } });
expect(hasVariableBoundMedia(compiled.html, undefined, compiled.variablesByComp)).toBe(true);
});
it("reads the length and the one sound lane from the clip a variable binds", async () => {
@@ -402,6 +402,47 @@ describe("hasVariableBoundMedia", () => {
expect(hasVariableBoundMedia(`${declared}${video}</body></html>`, undefined)).toBe(true);
});
it("requires a browser probe when an inlined sub-composition declared the default", () => {
// Inlining drops a full-document sub-composition's <html data-composition-variables> and the
// inner root's data-composition-id; the compiled table, keyed by the host, keeps the merged value.
const mount =
`<div data-composition-id="card" data-composition-file="compositions/card.html">` +
`<div data-hf-inner-root="true"><video id="v" src="placeholder.mp4" data-var-src="src"></video></div>` +
`</div>`;
const html = `<html><body>${mount}</body></html>`;
expect(hasVariableBoundMedia(html, undefined, { card: { src: "clip.mp4" } })).toBe(true);
expect(hasVariableBoundMedia(html, undefined, { card: { other: "clip.mp4" } })).toBe(false);
expect(hasVariableBoundMedia(html, undefined, {})).toBe(false);
});
it("matches a repeated mount through the host's runtime composition id", () => {
const mount =
`<div data-composition-id="card__hf2" data-hf-original-composition-id="card">` +
`<div data-hf-inner-root="true"><video id="v" src="placeholder.mp4" data-var-src="src"></video></div>` +
`</div>`;
expect(
hasVariableBoundMedia(`<html><body>${mount}</body></html>`, undefined, {
card__hf1: { src: "a.mp4" },
card__hf2: { src: "b.mp4" },
}),
).toBe(true);
});
it("lets the nearest scope's table entry answer alone, like the runtime", () => {
const nested =
`<div data-composition-id="outer"><div data-composition-id="inner">` +
`<video id="v" src="placeholder.mp4" data-var-src="src"></video></div></div>`;
const html = `<html><body>${nested}</body></html>`;
expect(
hasVariableBoundMedia(html, undefined, { outer: { src: "a.mp4" }, inner: { title: "x" } }),
).toBe(false);
expect(hasVariableBoundMedia(html, undefined, { outer: { src: "a.mp4" } })).toBe(false);
expect(hasVariableBoundMedia(html, undefined, { inner: { src: "b.mp4" } })).toBe(true);
});
});
describe("runProbeStage — forceScreenshot threading", () => {
@@ -186,12 +186,23 @@ export function hasAutoStartVideos(html: string): boolean {
return document.querySelector("video[data-hf-auto-start]") !== null;
}
type VariablesByComp = Record<string, Record<string, unknown>>;
function scopedVariablesFor(element: Element, variablesByComp: VariablesByComp) {
const scope = element.closest("[data-composition-id]");
const compId = scope?.getAttribute("data-composition-id")?.trim() ?? "";
return compId && Object.hasOwn(variablesByComp, compId) ? variablesByComp[compId] : undefined;
}
function variableHasValue(
element: Element,
variableId: string,
variables: Record<string, unknown> | undefined,
variablesByComp: VariablesByComp,
): boolean {
if (variables && Object.hasOwn(variables, variableId)) return true;
const scoped = scopedVariablesFor(element, variablesByComp);
if (scoped) return Object.hasOwn(scoped, variableId);
for (let scope = element.parentElement; scope; scope = scope.parentElement) {
if (Object.hasOwn(parseHostVariableValues(scope), variableId)) return true;
if (Object.hasOwn(readDeclaredDefaults(scope), variableId)) return true;
@@ -201,11 +212,12 @@ function variableHasValue(
/**
* Variable-bound sources are resolved by the browser runtime, not the static compiler. Probe them whenever the
* element's variable has a value (the render's, its mount's `data-variable-values`, a declared default).
* element's variable has a value (the render's, its scope's compiled table entry, its mount's, a declared default).
*/
export function hasVariableBoundMedia(
html: string,
variables: Record<string, unknown> | undefined,
variablesByComp: VariablesByComp = {},
): boolean {
const { document } = parseHTML(html);
return Array.from(
@@ -214,7 +226,7 @@ export function hasVariableBoundMedia(
),
).some((element) => {
const variableId = element.getAttribute("data-var-src")?.trim();
return Boolean(variableId && variableHasValue(element, variableId, variables));
return Boolean(variableId && variableHasValue(element, variableId, variables, variablesByComp));
});
}
@@ -408,7 +420,11 @@ export async function runProbeStage(input: ProbeStageInput): Promise<ProbeStageR
compiled.html,
composition.audios.length,
);
const hasVariableMedia = hasVariableBoundMedia(compiled.html, job.config.variables);
const hasVariableMedia = hasVariableBoundMedia(
compiled.html,
job.config.variables,
compiled.variablesByComp,
);
const hasInsertedMedia = hasRuntimeMediaChanges(compiled.html);
const needsBrowser =
cfg.videoLayerPassthrough ||