Skip to content

Write HTML. Render video. Built for agents.

feat(studio): host apps can open the ask-agent flow from a picked element (#4075)

Miguel Ángele174b1715b6e
diff --git a/packages/studio/src/components/AskAgentModal.tsx b/packages/studio/src/components/AskAgentModal.tsx
index 9df38006cf..613496d92d 100644
--- a/packages/studio/src/components/AskAgentModal.tsx
+++ b/packages/studio/src/components/AskAgentModal.tsx
@@ -25,19 +25,21 @@ function getAgentModalPositionStyle(
return { left, top, transform: "translateX(-50%)" };
}
+export interface AskAgentModalProps {
+ selectionLabel: string;
+ contextPreview?: string;
+ anchorPoint?: AgentModalAnchorPoint | null;
+ onSubmit: (instruction: string) => void;
+ onClose: () => void;
+}
+
export function AskAgentModal({
selectionLabel,
contextPreview,
anchorPoint = null,
onSubmit,
onClose,
-}: {
- selectionLabel: string;
- contextPreview?: string;
- anchorPoint?: AgentModalAnchorPoint | null;
- onSubmit: (instruction: string) => void;
- onClose: () => void;
-}) {
+}: AskAgentModalProps) {
const [value, setValue] = useState("");
const inputRef = useRef<HTMLTextAreaElement>(null);
const containerRef = useRef<HTMLDivElement>(null);
diff --git a/packages/studio/src/components/editor/domEditing.ts b/packages/studio/src/components/editor/domEditing.ts
index 7934c87078..6c67ca4d94 100644
--- a/packages/studio/src/components/editor/domEditing.ts
+++ b/packages/studio/src/components/editor/domEditing.ts
@@ -45,4 +45,10 @@ export {
} from "./domEditingLayers";
// Agent prompt
-export { buildElementAgentPrompt } from "./domEditingAgentPrompt";
+export {
+ buildElementAgentPrompt,
+ buildAgentContextPreview,
+ buildPickerAgentPrompt,
+ buildPickerAgentContextPreview,
+} from "./domEditingAgentPrompt";
+export type { AgentPromptElementInfo } from "./domEditingAgentPrompt";
diff --git a/packages/studio/src/components/editor/domEditingAgentPrompt.test.ts b/packages/studio/src/components/editor/domEditingAgentPrompt.test.ts
new file mode 100644
index 0000000000..235fe6c90e
--- /dev/null
+++ b/packages/studio/src/components/editor/domEditingAgentPrompt.test.ts
@@ -0,0 +1,199 @@
+// @vitest-environment happy-dom
+
+import { describe, expect, it } from "vitest";
+import type { HyperframePickerElementInfo } from "@hyperframes/core";
+import {
+ buildAgentContextPreview,
+ buildElementAgentPrompt,
+ buildPickerAgentContextPreview,
+ buildPickerAgentPrompt,
+} from "./domEditingAgentPrompt";
+import type { DomEditSelection } from "./domEditingTypes";
+
+function makeSelection(overrides: Partial<DomEditSelection> = {}): DomEditSelection {
+ return {
+ element: document.createElement("div"),
+ label: "Headline",
+ tagName: "div",
+ sourceFile: "hero.html",
+ compositionPath: "hero.html",
+ isCompositionHost: false,
+ isInsideLockedComposition: false,
+ id: "headline-1",
+ selector: "#headline-1",
+ selectorIndex: 0,
+ boundingBox: { x: 10, y: 20, width: 300, height: 40 },
+ textContent: "Hello world",
+ dataAttributes: {},
+ inlineStyles: {},
+ computedStyles: {},
+ textFields: [],
+ capabilities: {
+ canSelect: true,
+ canEditStyles: true,
+ canCrop: false,
+ canMove: true,
+ canResize: true,
+ canApplyManualOffset: false,
+ canApplyManualSize: false,
+ canApplyManualRotation: false,
+ },
+ ...overrides,
+ };
+}
+
+const PICKER_SELECTION: HyperframePickerElementInfo = {
+ id: "headline-1",
+ tagName: "div",
+ selector: "#headline-1",
+ label: "Headline",
+ boundingBox: { x: 10, y: 20, width: 300, height: 40 },
+ textContent: "Hello world",
+ src: null,
+ dataAttributes: {},
+};
+
+describe("buildElementAgentPrompt", () => {
+ it("produces the documented v1 schema", () => {
+ const prompt = buildElementAgentPrompt({
+ selection: makeSelection(),
+ currentTime: 1.5,
+ userInstruction: "Make this bigger",
+ });
+ expect(prompt).toBe(
+ [
+ "## HyperFrames element edit request v1",
+ "Schema version: 1",
+ "",
+ "Make this bigger",
+ "",
+ "Composition: hero.html",
+ "Playback time: 00:01",
+ "Source file: hero.html",
+ "DOM id: headline-1",
+ "Selector: #headline-1",
+ "Selector index: 0",
+ "Tag: <div>",
+ "Bounds: x=10, y=20, width=300, height=40",
+ "Text: Hello world",
+ "",
+ "Guardrails:",
+ "- Make a targeted change to this element only.",
+ "- Preserve the rest of the composition and its timing.",
+ "- Do not modify other elements' data-* attributes or positioning.",
+ "- Prefer existing inline styles or existing CSS rules for this element over adding unrelated selectors.",
+ ].join("\n"),
+ );
+ });
+
+ it("includes text fields, inline styles, computed styles and a target snippet when present", () => {
+ const prompt = buildElementAgentPrompt({
+ selection: makeSelection({
+ inlineStyles: { color: "red" },
+ computedStyles: { "font-size": "16px" },
+ textFields: [
+ {
+ key: "title",
+ label: "Title",
+ value: "Hello",
+ tagName: "h1",
+ attributes: [],
+ inlineStyles: {},
+ computedStyles: {},
+ source: "self",
+ },
+ ],
+ }),
+ currentTime: 0,
+ tagSnippet: "<div id='headline-1'>Hello world</div>",
+ selectionContext: "Nested inside the hero card",
+ });
+ expect(prompt).toContain("Selection context:\nNested inside the hero card");
+ expect(prompt).toContain('Text fields:\n- key=title; tag=<h1>; source=self; text="Hello"');
+ expect(prompt).toContain("Inline styles:\ncolor: red");
+ expect(prompt).toContain("Computed styles (browser-resolved):\nfont-size: 16px");
+ expect(prompt).toContain("Target HTML:\n<div id='headline-1'>Hello world</div>");
+ });
+});
+
+describe("buildAgentContextPreview", () => {
+ it("summarizes composition, source, selector, tag and text", () => {
+ expect(buildAgentContextPreview(makeSelection(), "hero.html")).toBe(
+ [
+ "Composition: hero.html",
+ "Source: hero.html",
+ "Selector: #headline-1 Tag: <div>",
+ "Text: Hello world",
+ ].join("\n"),
+ );
+ });
+});
+
+describe("buildPickerAgentPrompt", () => {
+ it("produces a plain comment prompt when nothing is selected", () => {
+ const prompt = buildPickerAgentPrompt({ selection: null, userInstruction: "Add a border" });
+ expect(prompt).toBe(
+ ["## HyperFrames element edit request v1", "Schema version: 1", "", "Add a border"].join(
+ "\n",
+ ),
+ );
+ });
+
+ it("produces identical shared-field text to buildElementAgentPrompt for equivalent input", () => {
+ const domPrompt = buildElementAgentPrompt({
+ selection: makeSelection({ compositionPath: "", sourceFile: "" }),
+ currentTime: 0,
+ });
+ const pickerPrompt = buildPickerAgentPrompt({ selection: PICKER_SELECTION });
+
+ const sharedFields = [
+ "DOM id: headline-1",
+ "Selector: #headline-1",
+ "Tag: <div>",
+ "Bounds: x=10, y=20, width=300, height=40",
+ "Text: Hello world",
+ ];
+ for (const line of sharedFields) {
+ expect(domPrompt).toContain(line);
+ expect(pickerPrompt).toContain(line);
+ }
+ // Both end on the identical guardrails block, byte for byte.
+ const guardrails = [
+ "Guardrails:",
+ "- Make a targeted change to this element only.",
+ "- Preserve the rest of the composition and its timing.",
+ "- Do not modify other elements' data-* attributes or positioning.",
+ "- Prefer existing inline styles or existing CSS rules for this element over adding unrelated selectors.",
+ ].join("\n");
+ expect(domPrompt.endsWith(guardrails)).toBe(true);
+ expect(pickerPrompt.endsWith(guardrails)).toBe(true);
+ });
+
+ it("surfaces the picker's label and media src — a host app has no DOM to read them from otherwise", () => {
+ const prompt = buildPickerAgentPrompt({
+ selection: { ...PICKER_SELECTION, tagName: "img", src: "assets/hero.png" },
+ });
+ expect(prompt).toContain("Label: Headline");
+ expect(prompt).toContain("Source (media): assets/hero.png");
+ });
+
+ it("omits the label and source lines when the picker didn't report them", () => {
+ const prompt = buildPickerAgentPrompt({
+ selection: { ...PICKER_SELECTION, label: "", src: null },
+ });
+ expect(prompt).not.toContain("Label:");
+ expect(prompt).not.toContain("Source (media):");
+ });
+});
+
+describe("buildPickerAgentContextPreview", () => {
+ it("returns an empty string when nothing is selected", () => {
+ expect(buildPickerAgentContextPreview(null)).toBe("");
+ });
+
+ it("matches buildAgentContextPreview's selector/tag/text line format", () => {
+ expect(buildPickerAgentContextPreview(PICKER_SELECTION)).toBe(
+ ["Selector: #headline-1 Tag: <div>", "Text: Hello world"].join("\n"),
+ );
+ });
+});
diff --git a/packages/studio/src/components/editor/domEditingAgentPrompt.ts b/packages/studio/src/components/editor/domEditingAgentPrompt.ts
index 2be7155c1c..1a4704c2f6 100644
--- a/packages/studio/src/components/editor/domEditingAgentPrompt.ts
+++ b/packages/studio/src/components/editor/domEditingAgentPrompt.ts
@@ -1,10 +1,40 @@
/**
* Agent prompt builder for HyperFrames element edit requests.
*/
+import type { HyperframePickerElementInfo } from "@hyperframes/core";
import { formatTime } from "../../player/lib/time";
import type { DomEditSelection, DomEditTextField } from "./domEditingTypes";
-function formatBoundingBox(bounds: DomEditSelection["boundingBox"]): string {
+/**
+ * The subset of an element selection shared by the Studio DOM editor (`DomEditSelection`) and the
+ * runtime picker (`HyperframePickerElementInfo`); a field absent from a caller's type is simply omitted.
+ */
+export interface AgentPromptElementInfo {
+ id: string | null;
+ selector?: string | null;
+ /** Disambiguates duplicate selectors in `DomEditSelection`. The picker
+ * payload has no such concept (one picked node, not a candidate list), so
+ * a picker-built prompt always prints index 0 — expected, not a gap. */
+ selectorIndex?: number;
+ tagName: string;
+ label?: string;
+ boundingBox: { x: number; y: number; width: number; height: number };
+ textContent: string | null;
+ src?: string | null;
+ textFields?: DomEditTextField[];
+ inlineStyles?: Record<string, string>;
+ computedStyles?: Record<string, string>;
+}
+
+const GUARDRAIL_LINES = [
+ "Guardrails:",
+ "- Make a targeted change to this element only.",
+ "- Preserve the rest of the composition and its timing.",
+ "- Do not modify other elements' data-* attributes or positioning.",
+ "- Prefer existing inline styles or existing CSS rules for this element over adding unrelated selectors.",
+];
+
+function formatBoundingBox(bounds: AgentPromptElementInfo["boundingBox"]): string {
return `x=${Math.round(bounds.x)}, y=${Math.round(bounds.y)}, width=${Math.round(bounds.width)}, height=${Math.round(bounds.height)}`;
}
@@ -24,6 +54,41 @@ function formatTextFields(fields: DomEditTextField[]): string {
.join("\n");
}
+function formatSelectorTagLine(info: Pick<AgentPromptElementInfo, "selector" | "tagName">): string {
+ return `Selector: ${info.selector ?? "(none)"} Tag: <${info.tagName}>`;
+}
+
+function formatTextLine(textContent: string | null): string {
+ return textContent ? `Text: ${textContent}` : "";
+}
+
+/** Core identity fields, plus the text line when the element has text content. */
+function buildElementInfoLines(info: AgentPromptElementInfo): string[] {
+ const lines = [
+ `DOM id: ${info.id ?? "(none)"}`,
+ `Selector: ${info.selector ?? "(none)"}`,
+ `Selector index: ${info.selectorIndex ?? 0}`,
+ `Tag: <${info.tagName}>`,
+ ];
+ if (info.label) lines.push(`Label: ${info.label}`);
+ lines.push(`Bounds: ${formatBoundingBox(info.boundingBox)}`);
+ if (info.src) lines.push(`Source (media): ${info.src}`);
+ if (info.textContent) lines.push(`Text: ${info.textContent}`);
+ return lines;
+}
+
+/** Text fields, inline styles, computed styles — present when the caller supplies them. */
+function buildElementDetailLines(info: AgentPromptElementInfo): string[] {
+ const lines: string[] = [];
+ const textFieldsBlock = info.textFields ? formatTextFields(info.textFields) : "";
+ if (textFieldsBlock) lines.push("", "Text fields:", textFieldsBlock);
+ const inlineStyleBlock = info.inlineStyles ? formatStyleBlock(info.inlineStyles) : "";
+ if (inlineStyleBlock) lines.push("", "Inline styles:", inlineStyleBlock);
+ const computedStyleBlock = info.computedStyles ? formatStyleBlock(info.computedStyles) : "";
+ if (computedStyleBlock) lines.push("", "Computed styles (browser-resolved):", computedStyleBlock);
+ return lines;
+}
+
export function buildElementAgentPrompt({
selection,
currentTime,
@@ -40,6 +105,18 @@ export function buildElementAgentPrompt({
sourceFilePath?: string;
}): string {
const displayedSourceFile = sourceFilePath?.trim() || selection.sourceFile;
+ const info: AgentPromptElementInfo = {
+ id: selection.id ?? null,
+ selector: selection.selector,
+ selectorIndex: selection.selectorIndex,
+ tagName: selection.tagName,
+ boundingBox: selection.boundingBox,
+ textContent: selection.textContent,
+ textFields: selection.textFields,
+ inlineStyles: selection.inlineStyles,
+ computedStyles: selection.computedStyles,
+ };
+
const lines = [
"## HyperFrames element edit request v1",
"Schema version: 1",
@@ -49,53 +126,31 @@ export function buildElementAgentPrompt({
`Composition: ${selection.compositionPath}`,
`Playback time: ${formatTime(currentTime)}`,
`Source file: ${displayedSourceFile}`,
- `DOM id: ${selection.id ?? "(none)"}`,
- `Selector: ${selection.selector ?? "(none)"}`,
- `Selector index: ${selection.selectorIndex ?? 0}`,
- `Tag: <${selection.tagName}>`,
- `Bounds: ${formatBoundingBox(selection.boundingBox)}`,
+ ...buildElementInfoLines(info),
];
- if (selection.textContent) {
- lines.push(`Text: ${selection.textContent}`);
- }
-
const trimmedSelectionContext = selectionContext?.trim();
if (trimmedSelectionContext) {
lines.push("", "Selection context:", trimmedSelectionContext);
}
- const textFieldsBlock = formatTextFields(selection.textFields);
- if (textFieldsBlock) {
- lines.push("", "Text fields:", textFieldsBlock);
- }
-
- const inlineStyleBlock = formatStyleBlock(selection.inlineStyles);
- if (inlineStyleBlock) {
- lines.push("", "Inline styles:", inlineStyleBlock);
- }
-
- const computedStyleBlock = formatStyleBlock(selection.computedStyles);
- if (computedStyleBlock) {
- lines.push("", "Computed styles (browser-resolved):", computedStyleBlock);
- }
+ lines.push(...buildElementDetailLines(info));
if (tagSnippet) {
lines.push("", "Target HTML:", tagSnippet);
}
- lines.push(
- "",
- "Guardrails:",
- "- Make a targeted change to this element only.",
- "- Preserve the rest of the composition and its timing.",
- "- Do not modify other elements' data-* attributes or positioning.",
- "- Prefer existing inline styles or existing CSS rules for this element over adding unrelated selectors.",
- );
+ lines.push("", ...GUARDRAIL_LINES);
return lines.join("\n");
}
+function buildSelectorAndTextLines(
+ info: Pick<AgentPromptElementInfo, "selector" | "tagName" | "textContent">,
+): string[] {
+ return [formatSelectorTagLine(info), formatTextLine(info.textContent)];
+}
+
export function buildAgentContextPreview(
selection: DomEditSelection,
activeCompPath: string | null,
@@ -103,9 +158,56 @@ export function buildAgentContextPreview(
return [
`Composition: ${selection.compositionPath}`,
`Source: ${selection.sourceFile || activeCompPath || "index.html"}`,
- `Selector: ${selection.selector ?? "(none)"} Tag: <${selection.tagName}>`,
- selection.textContent ? `Text: ${selection.textContent}` : "",
+ ...buildSelectorAndTextLines(selection),
]
.filter(Boolean)
.join("\n");
}
+
+/**
+ * Same convention as `buildElementAgentPrompt`, for a host app embedding only the player: built from
+ * the runtime picker's own payload, not `DomEditSelection`. Null selection yields a bare prompt, no guardrails.
+ */
+export function buildPickerAgentPrompt({
+ selection,
+ userInstruction,
+}: {
+ selection: HyperframePickerElementInfo | null;
+ userInstruction?: string;
+}): string {
+ const lines = [
+ "## HyperFrames element edit request v1",
+ "Schema version: 1",
+ "",
+ userInstruction?.trim() || "Edit this selected HyperFrames element.",
+ ];
+
+ if (!selection) return lines.join("\n");
+
+ const info: AgentPromptElementInfo = {
+ id: selection.id,
+ selector: selection.selector,
+ tagName: selection.tagName,
+ label: selection.label,
+ boundingBox: selection.boundingBox,
+ textContent: selection.textContent,
+ src: selection.src,
+ };
+
+ lines.push(
+ "",
+ ...buildElementInfoLines(info),
+ ...buildElementDetailLines(info),
+ "",
+ ...GUARDRAIL_LINES,
+ );
+
+ return lines.join("\n");
+}
+
+export function buildPickerAgentContextPreview(
+ selection: HyperframePickerElementInfo | null,
+): string {
+ if (!selection) return "";
+ return buildSelectorAndTextLines(selection).filter(Boolean).join("\n");
+}
diff --git a/packages/studio/src/index.ts b/packages/studio/src/index.ts
index 1da7407a66..d5f5d8dc0c 100644
--- a/packages/studio/src/index.ts
+++ b/packages/studio/src/index.ts
@@ -27,6 +27,16 @@ export { FileTree } from "./components/editor/FileTree";
// App
export { StudioApp } from "./App";
+// Ask-agent flow
+export { AskAgentModal } from "./components/AskAgentModal";
+export type { AskAgentModalProps } from "./components/AskAgentModal";
+export type { AgentModalAnchorPoint } from "./utils/studioHelpers";
+export {
+ buildPickerAgentPrompt,
+ buildPickerAgentContextPreview,
+} from "./components/editor/domEditingAgentPrompt";
+export type { AgentPromptElementInfo } from "./components/editor/domEditingAgentPrompt";
+
// Hooks
export { useElementPicker } from "./hooks/useElementPicker";
export type { PickedElement } from "./hooks/useElementPicker";