Write HTML. Render video. Built for agents.
JavaScript aiai-agentsanimationclaude-codeffmpegframeworkgsaphtmlhtml-to-videomcpmotion-graphicspuppeteerrenderingtypescriptvideo-editor
fix(cli): Studio's catalog install records the item and honours paths, as add does (#4573)
Miguel Ángel4984a268f760
diff --git a/docs/packages/cli.mdx b/docs/packages/cli.mdxindex c271fea412..8b41b45e5d 100644--- a/docs/packages/cli.mdx+++ b/docs/packages/cli.mdx@@ -1207,8 +1207,8 @@ npx hyperframes telemetry statusTelemetry collects command names, render performance, render checkpoint anderror names, aggregate browser diagnostic counts, browser initializationduration and tween count, aggregate video-extraction workload counts (extracted-frames, VFR preflights), example choices, the names of registry items `add`-installs, and system info — including a coarse+frames, VFR preflights), example choices, the names of registry items `add` or+Studio installs and which of the two installed them, and system info — including a coarseenvironment fingerprint: OS, kernel string, CPU and memory shape, sandboxruntime such as gVisor or Docker, and the _name_ of a coding agent driving theCLI when one is detected (`claude_code`, `codex`, `cursor`). That name isdiff --git a/packages/cli/src/commands/add.test.ts b/packages/cli/src/commands/add.test.tsindex e84ad4f4ac..8618bd2985 100644--- a/packages/cli/src/commands/add.test.ts+++ b/packages/cli/src/commands/add.test.ts@@ -442,11 +442,13 @@ describe("runAdd (integration, mocked registry)", () => {item: "base-component",itemType: "hyperframes:component",requested: false,+ source: "cli",});expect(trackRegistryItemAdded).toHaveBeenCalledWith({item: "dep-block",itemType: "hyperframes:block",requested: true,+ source: "cli",});} finally {rmSync(dir, { recursive: true, force: true });diff --git a/packages/cli/src/commands/add.ts b/packages/cli/src/commands/add.tsindex 51f5ced62b..b4c1cad4b2 100644--- a/packages/cli/src/commands/add.ts+++ b/packages/cli/src/commands/add.ts@@ -96,7 +96,7 @@ function variableValuesAttribute(values: Record<string, unknown> | null): string* recorded manifest target must name the same file, or a render would look for* a block at a path the composition never mounts and report it as dropped.*/-function primaryInstalledTarget(item: RegistryItem): string {+export function primaryInstalledTarget(item: RegistryItem): string {const primary =item.files.find((f) => f.type === "hyperframes:snippet") ??item.files.find((f) => f.type === "hyperframes:composition") ??@@ -179,6 +179,7 @@ export interface RunAddArgs {force?: boolean;/** Current CLI version used for registry metadata compatibility checks. */cliVersion?: string;+ source?: "cli" | "studio";}export interface RunAddResult {@@ -312,6 +313,13 @@ export function describeInstallFailure(err: unknown, registry?: string): string}export async function runAdd(opts: RunAddArgs): Promise<RunAddResult> {+ return (await addToProject(opts)).result;+}++/** The one install path for a catalog item, shared by `add` and Studio; `item` is the requested item as installed. */+export async function addToProject(+ opts: RunAddArgs,+): Promise<{ result: RunAddResult; item: RegistryItem }> {const projectDir = resolve(opts.projectDir);// 1. Load (or write default) project config.@@ -374,6 +382,7 @@ export async function runAdd(opts: RunAddArgs): Promise<RunAddResult> {item: planItem.name,itemType: planItem.type,requested: planItem.name === item.name,+ source: opts.source ?? "cli",});}@@ -406,7 +415,7 @@ export async function runAdd(opts: RunAddArgs): Promise<RunAddResult> {warnings.push(`--vars ignored (not declared by ${item.name}): ${variablesUnknown.join(", ")}`);}- return {+ const result: RunAddResult = {ok: true,name: item.name,type: item.type,@@ -419,6 +428,7 @@ export async function runAdd(opts: RunAddArgs): Promise<RunAddResult> {variablesApplied,warnings,};+ return { result, item: itemForInstall };}// ── Command ─────────────────────────────────────────────────────────────────diff --git a/packages/cli/src/registry/installer.ts b/packages/cli/src/registry/installer.tsindex b1f5304d90..2d3a69a4e7 100644--- a/packages/cli/src/registry/installer.ts+++ b/packages/cli/src/registry/installer.ts@@ -86,6 +86,24 @@ function writeInstallRecord(destDir: string, record: InstallRecord): void {publishRegistryFile(destDir, INSTALL_RECORD, `${JSON.stringify(sorted, null, 2)}\n`);}+/** Re-record files an install wrote and its caller then rewrote, so they still read as unedited. */+export function recordRewrittenInstall(destDir: string, written: string[]): void {+ if (written.length === 0) return;+ const root = registryRoot(destDir);+ const record = readInstallRecord(root);+ const rewritten = new Set(written);+ for (const target of Object.keys(record)) {+ let path: string;+ try {+ path = registryTargetPath(root, target);+ } catch {+ continue; // a key that no longer resolves, or that the installer would refuse+ }+ if (rewritten.has(path)) record[target] = digest(readFileSync(path));+ }+ writeInstallRecord(root, record);+}+/*** Has the project changed this file since we installed it?*diff --git a/packages/cli/src/server/studioServer.registryInstall.test.ts b/packages/cli/src/server/studioServer.registryInstall.test.tsnew file mode 100644index 0000000000..6e65c1c890--- /dev/null+++ b/packages/cli/src/server/studioServer.registryInstall.test.ts@@ -0,0 +1,201 @@+import { afterEach, describe, expect, it, vi } from "vitest";+import {+ existsSync,+ mkdirSync,+ mkdtempSync,+ readFileSync,+ rmSync,+ symlinkSync,+ writeFileSync,+} from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { trackRegistryItemAdded } from "../telemetry/events.js";+import { createStudioServer, type StudioServer } from "./studioServer.js";++vi.mock("../telemetry/events.js", () => ({ trackRegistryItemAdded: vi.fn() }));++const SCHEMA = "https://hyperframes.heygen.com/schema/registry-item.json";+// Names no other test uses: the registry cache is shared by every test in a run.+const block = (name: string, dependencies?: string[]) => ({+ $schema: SCHEMA,+ name,+ type: "hyperframes:block",+ title: name,+ description: "Block for tests",+ dimensions: { width: 1080, height: 1350 },+ duration: 6,+ ...(dependencies ? { registryDependencies: dependencies } : {}),+ files: [+ { path: `${name}.html`, target: `compositions/${name}.html`, type: "hyperframes:composition" },+ ],+});+const ITEMS = [+ block("studio-drop-block"),+ block("studio-drop-other"),+ block("studio-drop-parent", ["studio-drop-part"]),+ {+ $schema: SCHEMA,+ name: "studio-drop-part",+ type: "hyperframes:component",+ title: "part",+ description: "Component for tests",+ files: [+ {+ path: "studio-drop-part.html",+ target: "compositions/components/studio-drop-part.html",+ type: "hyperframes:snippet",+ },+ ],+ },+];++const dirs: string[] = [];+let server: StudioServer | undefined;++afterEach(() => {+ server?.watcher.close();+ server = undefined;+ vi.unstubAllGlobals();+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });+});++/** A project behind a symlink whose hyperframes.json points at a stubbed registry; `fetched` logs every URL. */+function projectWithRegistry(): {+ link: string;+ real: string;+ registry: string;+ fetched: string[];+} {+ const fetched: string[] = [];+ const registry = `https://test.invalid/${crypto.randomUUID()}`;+ vi.stubGlobal(+ "fetch",+ vi.fn(async (input: string | URL) => {+ const url = String(input);+ fetched.push(url);+ // Only the project's own registry answers, so nothing is cached for the public registry.+ if (!url.startsWith(registry)) return new Response("not found", { status: 404 });+ if (url.endsWith("/registry.json")) {+ const items = ITEMS.map(({ name, type }) => ({ name, type }));+ const $schema = "https://hyperframes.heygen.com/schema/registry.json";+ return new Response(+ JSON.stringify({ $schema, name: "t", homepage: "https://example.com", items }),+ );+ }+ const item = ITEMS.find((candidate) => url.includes(`/${candidate.name}/`));+ if (item && url.endsWith("/registry-item.json")) return new Response(JSON.stringify(item));+ if (item && url.endsWith(".html")) {+ return new Response(+ `<meta name="viewport" content="width=1080, height=1350"><div data-composition-id="${item.name}"></div>`,+ );+ }+ return new Response("not found", { status: 404 });+ }),+ );+ const root = mkdtempSync(join(tmpdir(), "hf-studio-install-"));+ dirs.push(root);+ const real = join(root, "real");+ mkdirSync(real);+ const link = join(root, "link");+ symlinkSync(real, link, "junction");+ writeFileSync(join(real, "index.html"), '<div data-width="1920" data-height="1080"></div>');+ writeFileSync(+ join(real, "hyperframes.json"),+ JSON.stringify({ registry, paths: { blocks: "scenes" } }),+ );+ server = createStudioServer({ projectDir: link });+ return { link, real, registry, fetched };+}++function installer(link: string) {+ return (blockName: string) =>+ server!.adapter.installRegistryBlock!({+ project: { dir: link, id: "p", title: "p" },+ blockName,+ } as never);+}++describe("Studio catalog install", () => {+ it("installs through add: honours the project's block folder and records the item", async () => {+ const { link, real } = projectWithRegistry();++ const result = await installer(link)("studio-drop-block");++ expect(result.written).toEqual(["scenes/studio-drop-block.html"]);+ expect(result.block.name).toBe("studio-drop-block");+ expect(trackRegistryItemAdded).toHaveBeenCalledWith(+ expect.objectContaining({ item: "studio-drop-block", source: "studio" }),+ );+ expect(existsSync(join(real, "compositions/studio-drop-block.html"))).toBe(false);+ const config = JSON.parse(readFileSync(join(real, "hyperframes.json"), "utf-8"));+ expect(config.registryItems).toEqual([+ {+ name: "studio-drop-block",+ type: "hyperframes:block",+ target: "scenes/studio-drop-block.html",+ },+ ]);+ });++ it("lists the catalog from the registry install uses", async () => {+ const { registry, fetched } = projectWithRegistry();++ const items = await server!.adapter.listRegistryCatalog!();++ expect(items.map((item) => item.name).sort()).toEqual(ITEMS.map((item) => item.name).sort());+ expect(fetched.length).toBeGreaterThan(0);+ expect(fetched.every((url) => url.startsWith(registry))).toBe(true);+ });++ it("installs a block sized unlike the project twice, and leaves a real edit alone", async () => {+ const { link, real } = projectWithRegistry();+ const install = installer(link);+ const file = join(real, "scenes/studio-drop-block.html");++ await install("studio-drop-block");+ expect(readFileSync(file, "utf-8")).toContain('content="width=1920, height=1080"');+ expect((await install("studio-drop-block")).written).toEqual(["scenes/studio-drop-block.html"]);++ writeFileSync(file, "my own edit");+ expect((await install("studio-drop-block")).written).toEqual([]);+ expect(readFileSync(file, "utf-8")).toBe("my own edit");+ });++ it("keeps an edit to one block when another block is installed", async () => {+ const { link, real } = projectWithRegistry();+ const install = installer(link);+ const file = join(real, "scenes/studio-drop-block.html");++ await install("studio-drop-block");+ writeFileSync(file, "my own edit");+ await install("studio-drop-other");+ await install("studio-drop-block");++ expect(readFileSync(file, "utf-8")).toBe("my own edit");+ });++ it("names the block's own file, as recorded, when its folder is a symlink inside the project", async () => {+ const { link, real } = projectWithRegistry();+ mkdirSync(join(real, "shared-scenes"));+ symlinkSync(join(real, "shared-scenes"), join(real, "scenes"), "junction");+ const install = installer(link);++ await install("studio-drop-block");+ expect(readFileSync(join(real, "scenes/studio-drop-block.html"), "utf-8")).toContain(+ "width=1920",+ );+ expect((await install("studio-drop-block")).written).toEqual(["scenes/studio-drop-block.html"]);+ });++ it("names the requested block's file first, before its dependencies'", async () => {+ const { link } = projectWithRegistry();++ const { written } = await installer(link)("studio-drop-parent");++ expect(written).toEqual([+ "scenes/studio-drop-parent.html",+ "compositions/components/studio-drop-part.html",+ ]);+ });+});diff --git a/packages/cli/src/server/studioServer.ts b/packages/cli/src/server/studioServer.tsindex 7d534efbaa..35b4fa8d52 100644--- a/packages/cli/src/server/studioServer.ts+++ b/packages/cli/src/server/studioServer.ts@@ -7,10 +7,10 @@import { Hono, type Context } from "hono";import { streamSSE } from "hono/streaming";-import { existsSync, readFileSync, writeFileSync, unlinkSync } from "node:fs";+import { existsSync, readFileSync, realpathSync, writeFileSync, unlinkSync } from "node:fs";import { createHash } from "node:crypto";import { fileURLToPath } from "node:url";-import { resolve, join, basename } from "node:path";+import { resolve, join, basename, relative, sep } from "node:path";import { readBundleFile } from "./readBundleFile.js";import {createProjectWatcher,@@ -755,40 +755,45 @@ export function createStudioServer(options: StudioServerOptions): StudioServer {async listRegistryCatalog() {const { listRegistryItems, loadAllItems } = await import("../registry/resolver.js");- const entries = await listRegistryItems();+ const { loadProjectConfig } = await import("../utils/projectConfig.js");+ // The same registry `add` installs from, so the panel lists what can be installed.+ const registry = { baseUrl: loadProjectConfig(projectDir).registry };+ const entries = await listRegistryItems(undefined, registry);const blockAndComponentEntries = entries.filter((e) => e.type === "hyperframes:block" || e.type === "hyperframes:component",);- return loadAllItems(blockAndComponentEntries);+ return loadAllItems(blockAndComponentEntries, registry);},async installRegistryBlock(opts) {- const { resolveItemWithDependencies } = await import("../registry/resolver.js");- const { installItem } = await import("../registry/installer.js");- const { gateRegistryItemsCompatibility } = await import("../registry/compatibility.js");- // Resolve transitive registryDependencies and install them first so a- // block that depends on other registry items installs completely.- const items = await resolveItemWithDependencies(opts.blockName);- // Compatibility-gate the whole set before writing anything (same gate as- // `hyperframes add`), so an incompatible block or dep aborts cleanly.- const warnings = gateRegistryItemsCompatibility(items);- for (const warning of warnings) {+ const { addToProject, primaryInstalledTarget } = await import("../commands/add.js");+ const { recordRewrittenInstall } = await import("../registry/installer.js");+ const { registryTargetPath } = await import("../registry/publication.js");+ const { result, item } = await addToProject({+ name: opts.blockName,+ projectDir: opts.project.dir,+ skipClipboard: true,+ source: "studio",+ });+ for (const warning of result.warnings) {process.stderr.write(`hyperframes:registry ${warning}\n`);}- const written: string[] = [];- for (const dep of items) {- const result = await installItem(dep, { destDir: opts.project.dir });- written.push(...result.written);- }- const item = items[items.length - 1]!;+ const written = result.written;rewriteWrittenToHostViewport(opts.project.dir, written);-- const relativePaths = written.map((abs) => {- const rel = abs.startsWith(opts.project.dir) ? abs.slice(opts.project.dir.length + 1) : abs;- return rel;- });- return { written: relativePaths, block: item };+ recordRewrittenInstall(opts.project.dir, written);++ // The item's own file first, as add recorded it, since Studio mounts the first .html it gets.+ const root = realpathSync(opts.project.dir);+ const primary = primaryInstalledTarget(item);+ const primaryPath = registryTargetPath(root, primary);+ const others = written+ .filter((abs) => abs !== primaryPath)+ .map((abs) => relative(root, abs).split(sep).join("/"));+ return {+ written: written.includes(primaryPath) ? [primary, ...others] : others,+ block: item,+ };},};diff --git a/packages/cli/src/telemetry/events.ts b/packages/cli/src/telemetry/events.tsindex 75407f1eca..192a93d7c9 100644--- a/packages/cli/src/telemetry/events.ts+++ b/packages/cli/src/telemetry/events.ts@@ -793,11 +793,13 @@ export function trackRegistryItemAdded(props: {item: string;itemType: string;requested: boolean;+ source: "cli" | "studio";}): void {trackEvent("registry_item_added", {item: props.item,item_type: props.itemType,requested: props.requested,+ source: props.source,});}