Skip to content

Commit bd0dc8c

Browse files
feat(studio,cli): add an Edit with Framey button and hyperframes open for HyperFrames Studio (#4951)
* feat(studio,cli): add an Edit with Framey button and `hyperframes open` for HyperFrames Studio Point people from the CLI and the Studio preview to HyperFrames Studio, the desktop app. - Studio header: an "Edit with Framey" button with Framey, the app's cursor mascot (the eye follows the pointer, a wiggle on hover, honours reduced motion). Until the app opens handed-over projects (HANDOFF_READY), a press shows a "Meet Framey" card with the download. The button shows only where the preview server answers GET /api/open-in-desktop on macOS, so the desktop app's own embedded Studio never shows it. - `hyperframes open [dir]`: hands the project folder to the app with `open -b` (released app, then Canary) and points to the download when neither is installed. When run by Claude Code or Codex it leaves .hyperframes/agent-handoff.json (CLAUDE_CODE_SESSION_ID / CODEX_THREAD_ID) so the app's first chat can pick up that conversation. - render and preview print one line about the app: the download until HANDOFF_READY, then `hyperframes open` when the app is installed. Nothing for a draft render, a batch row, or a run inside the app (HYPERFRAMES_DESKTOP_PROJECT). * fix(studio,cli): gate `hyperframes open` too, guard the open-in-desktop POST, keep one gate Review of #4951 at 58934a3. - One gate: HANDOFF_READY lives only in the CLI. `GET /api/open-in-desktop` now says `handoff`, and Studio's button reads it, so the gate cannot be half-flipped. - While gated nothing opens and nothing is written: `openInDesktop` returns `handoff-unavailable` (so `hyperframes open` prints the download line and the POST route answers with it), and no `.hyperframes/agent-handoff.json` can sit waiting for a later release. - The POST answers only Studio's own same-origin request (loopback Host, matching Origin, Sec-Fetch-Site same-origin); a cross-site or rebound-host POST gets 403. Routes moved to server/desktopRoutes.ts with their own tests. - `hyperframes open`: exits 1 when nothing opened, answers in JSON under --json for a bad directory, and tells a missing app from one macOS could not open (`open-failed`). A project that cannot be written still opens, with nothing handed over. - Tests drive the live path through `ready`, are path-portable for Windows, and cover the draft and batch-row hint skips (`wantsDesktopHint`, `batchRowRenderOptions`). - The load smoke mocks the route. * fix(studio): the edit-with-framey button asks its route through studioApiFetch
1 parent 6037d22 commit bd0dc8c

20 files changed

Lines changed: 911 additions & 13 deletions

‎packages/cli/src/cli.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,7 @@ const commandLoaders = {
129129
preview: () =>
130130
assertStudioWorkspaceBuilt().then(() => import("./commands/preview.js").then((m) => m.default)),
131131
publish: () => import("./commands/publish.js").then((m) => m.default),
132+
open: () => import("./commands/open.js").then((m) => m.default),
132133
render: () => import("./commands/render.js").then((m) => m.default),
133134
lint: () => import("./commands/lint.js").then((m) => m.default),
134135
check: () => import("./commands/check.js").then((m) => m.default),

‎packages/cli/src/commands/open.ts‎

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
import { defineCommand } from "citty";
2+
import type { Example } from "./_examples.js";
3+
import { c } from "../ui/colors.js";
4+
import { setCommandExitCode } from "../utils/commandResult.js";
5+
import { DOWNLOAD_HINT, openInDesktop, type DesktopOpenResult } from "../utils/desktopApp.js";
6+
import { resolveProject, resolveProjectOrThrow, type ProjectDir } from "../utils/project.js";
7+
8+
export const examples: Example[] = [
9+
["Open this project in HyperFrames Studio", "hyperframes open"],
10+
["Open another project", "hyperframes open ./my-video"],
11+
["For agents", "hyperframes open --json"],
12+
];
13+
14+
const WHY_NOT: Record<Extract<DesktopOpenResult, { opened: false }>["reason"], string | null> = {
15+
"handoff-unavailable": null,
16+
"unsupported-platform": "Opening a project from the CLI works on macOS only.",
17+
"not-installed": "HyperFrames Studio isn't installed on this Mac.",
18+
"open-failed": "macOS couldn't open HyperFrames Studio.",
19+
};
20+
21+
function printResult(project: ProjectDir, result: DesktopOpenResult): void {
22+
if (result.opened) {
23+
console.log(`${c.success("◇")} Opening ${c.accent(project.name)} in HyperFrames Studio`);
24+
if (result.handedOver) {
25+
const agent = result.handedOver.engine === "claude" ? "Claude Code" : "Codex";
26+
console.log(` ${c.dim(`Its chat picks up this ${agent} conversation.`)}`);
27+
}
28+
return;
29+
}
30+
const why = WHY_NOT[result.reason];
31+
if (!why) return console.log(`${c.warn("◇")} ${DOWNLOAD_HINT}`);
32+
console.log(`${c.warn("◇")} ${why}`);
33+
console.log(` Download it: ${c.accent(result.downloadUrl)}`);
34+
}
35+
36+
/** Under --json a bad directory answers in JSON too, not with the human error box. */
37+
function projectForJson(dir: string | undefined): ProjectDir | null {
38+
try {
39+
return resolveProjectOrThrow(dir);
40+
} catch (error) {
41+
const message = error instanceof Error ? error.message : String(error);
42+
console.log(JSON.stringify({ ok: false, error: { code: "invalid-project", message } }));
43+
setCommandExitCode(1);
44+
return null;
45+
}
46+
}
47+
48+
export default defineCommand({
49+
meta: { name: "open", description: "Open a project in HyperFrames Studio, the desktop app" },
50+
args: {
51+
dir: {
52+
type: "positional",
53+
description: "Project directory (default: current)",
54+
required: false,
55+
},
56+
json: { type: "boolean", description: "Output as JSON", default: false },
57+
},
58+
run({ args }) {
59+
const project = args.json ? projectForJson(args.dir) : resolveProject(args.dir);
60+
if (!project) return;
61+
const result = openInDesktop(project.dir);
62+
if (!result.opened) setCommandExitCode(1);
63+
if (args.json) console.log(JSON.stringify({ project: project.dir, ...result }, null, 2));
64+
else printResult(project, result);
65+
},
66+
});

‎packages/cli/src/commands/preview.ts‎

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ import { fileURLToPath } from "node:url";
3939
import { createRequire } from "node:module";
4040
import * as clack from "@clack/prompts";
4141
import { c } from "../ui/colors.js";
42+
import { desktopHint } from "../utils/desktopApp.js";
4243
import { isDevMode } from "../utils/env.js";
4344
import { normalizeErrorMessage as errorMessage } from "../utils/errorMessage.js";
4445
import { buildNpxCommand } from "../utils/npxCommand.js";
@@ -365,7 +366,7 @@ export default defineCommand({
365366
);
366367
return;
367368
}
368-
printStudioSummary(project.name, previewBaseUrl(status.port), {
369+
printStudioSummary(project.name, previewBaseUrl(status.port), project.dir, {
369370
details: [`Background preview running (PID ${status.pid}).`, `Log: ${status.logPath}`],
370371
});
371372
return;
@@ -539,7 +540,7 @@ export default defineCommand({
539540
);
540541
} else {
541542
clack.intro(c.bold("hyperframes preview"));
542-
printStudioSummary(projectName, url, {
543+
printStudioSummary(projectName, url, dir, {
543544
details: [
544545
background.type === "reused"
545546
? "Reusing the background server already running for this project."
@@ -1282,13 +1283,16 @@ function openStudioBrowser(url: string, projectName: string, options?: BrowserLa
12821283
function printStudioSummary(
12831284
projectName: string,
12841285
serverUrl: string,
1286+
projectDir: string,
12851287
opts: { details?: string[]; footer?: string } = {},
12861288
): void {
12871289
const urls = studioSummaryUrls(projectName, serverUrl);
12881290
console.log();
12891291
console.log(` ${c.dim("Project")} ${c.accent(projectName)}`);
12901292
console.log(` ${c.dim("Studio")} ${c.accent(urls.studioUrl)}`);
12911293
console.log(` ${c.dim("Server")} ${c.accent(urls.serverUrl)}`);
1294+
const hint = desktopHint(projectDir);
1295+
if (hint) console.log(` ${c.dim("Desktop")} ${hint}`);
12921296
console.log();
12931297
for (const detail of opts.details ?? []) {
12941298
console.log(` ${c.dim(detail)}`);
@@ -1395,7 +1399,7 @@ function attachStudioReadyHandler(
13951399
);
13961400
} else {
13971401
spinner.stop(c.success("Studio running"));
1398-
printStudioSummary(projectName, url, {
1402+
printStudioSummary(projectName, url, projectDir, {
13991403
footer: "Press Ctrl+C to stop",
14001404
});
14011405
}
@@ -1629,7 +1633,7 @@ async function runEmbeddedMode(
16291633
);
16301634
} else {
16311635
s.stop(c.success("Already running"));
1632-
printStudioSummary(pName, url, {
1636+
printStudioSummary(pName, url, dir, {
16331637
details: ["Reusing existing server. Use --force-new to start a fresh instance."],
16341638
});
16351639
}
@@ -1647,7 +1651,7 @@ async function runEmbeddedMode(
16471651
console.log(` ${c.warn(`Port ${startPort} is in use, using ${result.port} instead`)}`);
16481652
console.log();
16491653
}
1650-
printStudioSummary(pName, url, {
1654+
printStudioSummary(pName, url, dir, {
16511655
details: [
16521656
"Edit with your AI agent — it has HyperFrames skills installed.",
16531657
"Changes reload automatically in the studio.",

‎packages/cli/src/commands/render.ts‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,7 @@ import { resolve, dirname, join, basename } from "node:path";
6262
import { execFileSync, spawn } from "node:child_process";
6363
import { loadProducer } from "../utils/producer.js";
6464
import { c } from "../ui/colors.js";
65+
import { desktopHint } from "../utils/desktopApp.js";
6566
import {
6667
formatBytes,
6768
formatRenderSummaryDetail,
@@ -524,6 +525,8 @@ export interface RenderOptions {
524525
throwOnError?: boolean;
525526
/** Skip the interactive feedback prompt after a successful render. */
526527
skipFeedback?: boolean;
528+
/** False for a batch row: one line about the desktop app per batch is noise, not a pointer. */
529+
desktopHint?: boolean;
527530
/**
528531
* OPT IN to managing the DE parallel-router circuit breaker
529532
* (`applyDeParallelRouterCircuitBreaker`) for this render. Default OFF —
@@ -886,6 +889,8 @@ async function renderDocker(
886889
runPostRenderStep("printRenderComplete", () =>
887890
printRenderComplete({
888891
outputPath,
892+
projectDir,
893+
desktopHint: wantsDesktopHint(options),
889894
elapsedMs: elapsed,
890895
quiet: options.quiet,
891896
format: options.format,
@@ -1138,6 +1143,8 @@ async function executeLocalRender(
11381143
runPostRenderStep("printRenderComplete", () =>
11391144
printRenderComplete({
11401145
outputPath,
1146+
projectDir,
1147+
desktopHint: wantsDesktopHint(options),
11411148
elapsedMs: elapsed,
11421149
quiet: options.quiet,
11431150
format: options.format,
@@ -1898,8 +1905,16 @@ function readOutputFootprint(outputPath: string): { fileSize: string; isDirector
18981905
}
18991906
}
19001907

1908+
/** A delivered render points to the desktop app; a draft or a batch row does not. */
1909+
export function wantsDesktopHint(options: Pick<RenderOptions, "desktopHint" | "quality">): boolean {
1910+
return options.desktopHint !== false && options.quality !== "draft";
1911+
}
1912+
19011913
function printRenderComplete(input: {
19021914
outputPath: string;
1915+
projectDir: string;
1916+
/** Print the desktop-app line: a delivered render, never a draft or a batch row. */
1917+
desktopHint: boolean;
19031918
elapsedMs: number;
19041919
quiet: boolean;
19051920
format: RenderFormat;
@@ -1920,6 +1935,8 @@ function printRenderComplete(input: {
19201935
console.log(c.success("\u25C7") + " " + c.accent(outputPath));
19211936
console.log(" " + c.bold(fileSize) + c.dim(" \u00B7 " + detail));
19221937
if (perf) printRenderPipeline(perf, input.requestedGpuMode);
1938+
const hint = input.desktopHint ? desktopHint(input.projectDir) : null;
1939+
if (hint) console.log(" " + c.dim(hint));
19231940
}
19241941

19251942
function printRenderPipeline(

‎packages/cli/src/commands/render/execute.test.ts‎

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,8 @@ import { tmpdir } from "node:os";
33
import { join } from "node:path";
44
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
55
import { createRenderPlan } from "./plan.js";
6-
import { renderOptionsFromPlan } from "./execute.js";
6+
import { batchRowRenderOptions, renderOptionsFromPlan } from "./execute.js";
7+
import { wantsDesktopHint } from "../render.js";
78

89
describe("renderOptionsFromPlan", () => {
910
let projectDir: string;
@@ -40,3 +41,19 @@ describe("renderOptionsFromPlan", () => {
4041
expect(on.variables).toEqual({ title: "x" });
4142
});
4243
});
44+
45+
describe("the desktop-app line after a render", () => {
46+
it("comes after a delivered render, never after a draft or a batch row", () => {
47+
expect(wantsDesktopHint({ quality: "high" })).toBe(true);
48+
expect(wantsDesktopHint({ quality: "draft" })).toBe(false);
49+
expect(wantsDesktopHint({ quality: "high", desktopHint: false })).toBe(false);
50+
const projectDir = mkdtempSync(join(tmpdir(), "hf-render-batch-"));
51+
try {
52+
writeFileSync(join(projectDir, "index.html"), '<main data-composition-id="main"></main>');
53+
const row = batchRowRenderOptions(createRenderPlan({ dir: projectDir }), undefined);
54+
expect(wantsDesktopHint(row)).toBe(false);
55+
} finally {
56+
rmSync(projectDir, { recursive: true, force: true });
57+
}
58+
});
59+
});

‎packages/cli/src/commands/render/execute.ts‎

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -320,16 +320,12 @@ async function runResolutionPreflight(
320320
failCommand();
321321
}
322322

323-
async function executeBatchRender(
323+
export function batchRowRenderOptions(
324324
plan: RenderPlan,
325325
browserPath: string | undefined,
326-
batchModule: typeof import("../batchRender.js"),
327-
preparedBatch: import("../batchRender.js").PreparedBatchRender,
328-
dependencies: RenderExecutionDependencies,
329-
cancellation?: RenderCancellationScope,
330-
): Promise<void> {
326+
): RenderOptions {
331327
const batchQuiet = plan.quiet || plan.batchJson;
332-
const renderOptionsBase: RenderOptions = {
328+
return {
333329
fps: plan.fps,
334330
quality: plan.quality,
335331
authoringSkill: plan.authoringSkill,
@@ -365,8 +361,21 @@ async function executeBatchRender(
365361
exitAfterComplete: false,
366362
throwOnError: true,
367363
skipFeedback: true,
364+
desktopHint: false,
368365
manageDeParallelRouterBreaker: plan.batchConcurrency <= 1,
369366
};
367+
}
368+
369+
async function executeBatchRender(
370+
plan: RenderPlan,
371+
browserPath: string | undefined,
372+
batchModule: typeof import("../batchRender.js"),
373+
preparedBatch: import("../batchRender.js").PreparedBatchRender,
374+
dependencies: RenderExecutionDependencies,
375+
cancellation?: RenderCancellationScope,
376+
): Promise<void> {
377+
const batchQuiet = plan.quiet || plan.batchJson;
378+
const renderOptionsBase = batchRowRenderOptions(plan, browserPath);
370379
const manifest = await batchModule.runBatchRender({
371380
prepared: preparedBatch,
372381
concurrency: plan.batchConcurrency,

‎packages/cli/src/help.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ const GROUPS: Group[] = [
2727
["present", "Open a slideshow deck in presenter mode (with audience sync)"],
2828
["publish", "Upload a project to a stable URL (private by default)"],
2929
["render", "Render a composition to MP4 or WebM"],
30+
["open", "Open a project in HyperFrames Studio, the desktop app"],
3031
],
3132
},
3233
{
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
import { Hono } from "hono";
2+
import { describe, expect, it, vi } from "vitest";
3+
import type { DesktopOpenResult } from "../utils/desktopApp.js";
4+
import { mountDesktopRoutes, sameOriginPost } from "./desktopRoutes.js";
5+
6+
const STUDIO = {
7+
host: "localhost:3002",
8+
origin: "http://localhost:3002",
9+
"sec-fetch-site": "same-origin",
10+
};
11+
const OPENED: DesktopOpenResult = {
12+
opened: true,
13+
bundleId: "dev.hyperframes.desktop",
14+
handedOver: null,
15+
};
16+
17+
function server(ready: boolean) {
18+
const app = new Hono();
19+
const open = vi.fn((_dir: string): DesktopOpenResult => OPENED);
20+
mountDesktopRoutes(app, "/films/a", { ready, open });
21+
const post = (headers: Record<string, string>) =>
22+
app.request("/api/open-in-desktop", { method: "POST", headers });
23+
return { app, open, post };
24+
}
25+
26+
describe("open-in-desktop routes", () => {
27+
it("tells Studio whether to show the button and whether the app can take the project", async () => {
28+
const body = await (await server(false).app.request("/api/open-in-desktop")).json();
29+
expect(body).toEqual({ available: process.platform === "darwin", handoff: false });
30+
});
31+
32+
it("refuses a POST from another site, or through a rebound host name", async () => {
33+
const { open, post } = server(true);
34+
const crossSite = { ...STUDIO, origin: "https://evil.example", "sec-fetch-site": "cross-site" };
35+
expect((await post(crossSite)).status).toBe(403);
36+
expect(
37+
(await post({ ...STUDIO, host: "evil.example:3002", origin: "http://evil.example:3002" }))
38+
.status,
39+
).toBe(403);
40+
expect(open).not.toHaveBeenCalled();
41+
});
42+
43+
it("while gated, answers Studio's own POST with the download and opens nothing", async () => {
44+
const { open, post } = server(false);
45+
const res = await post(STUDIO);
46+
expect(await res.json()).toMatchObject({ opened: false, reason: "handoff-unavailable" });
47+
expect(open).not.toHaveBeenCalled();
48+
});
49+
50+
it("once live, opens this server's project for Studio's own POST", async () => {
51+
const { open, post } = server(true);
52+
expect(await (await post(STUDIO)).json()).toEqual(OPENED);
53+
expect(open).toHaveBeenCalledWith("/films/a");
54+
});
55+
});
56+
57+
describe("sameOriginPost", () => {
58+
it("lets a local process without browser headers through, never a foreign origin", () => {
59+
expect(sameOriginPost({ host: "127.0.0.1:3002" })).toBe(true);
60+
expect(sameOriginPost({ host: "localhost:3002", origin: "http://localhost:3003" })).toBe(false);
61+
expect(sameOriginPost({ host: "localhost:3002", fetchSite: "same-site" })).toBe(false);
62+
expect(sameOriginPost({})).toBe(false);
63+
});
64+
});
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
import type { Hono } from "hono";
2+
import { DESKTOP_DOWNLOAD_URL, HANDOFF_READY, openInDesktop } from "../utils/desktopApp.js";
3+
import { identityAllowed } from "./telemetryIdentity.js";
4+
5+
/** A bodiless POST is a simple request, so any page can send one to localhost: it has to come from this Studio. */
6+
export function sameOriginPost(headers: {
7+
host?: string;
8+
origin?: string;
9+
fetchSite?: string;
10+
}): boolean {
11+
const { host, origin, fetchSite } = headers;
12+
if (!host || !identityAllowed(host)) return false;
13+
if (fetchSite && fetchSite !== "same-origin") return false;
14+
return origin === undefined || origin === `http://${host}`;
15+
}
16+
17+
/** Studio's Edit with Framey: the GET says whether to show it (macOS) and whether the app can take the project. */
18+
export function mountDesktopRoutes(
19+
app: Hono,
20+
projectDir: string,
21+
{ ready = HANDOFF_READY, open = openInDesktop } = {},
22+
): void {
23+
app.get("/api/open-in-desktop", (c) =>
24+
c.json({ available: process.platform === "darwin", handoff: ready }),
25+
);
26+
app.post("/api/open-in-desktop", (c) => {
27+
const allowed = sameOriginPost({
28+
host: c.req.header("host"),
29+
origin: c.req.header("origin"),
30+
fetchSite: c.req.header("sec-fetch-site"),
31+
});
32+
if (!allowed) return c.json({ error: "forbidden" }, 403);
33+
if (!ready)
34+
return c.json({
35+
opened: false,
36+
reason: "handoff-unavailable",
37+
downloadUrl: DESKTOP_DOWNLOAD_URL,
38+
});
39+
return c.json(open(projectDir));
40+
});
41+
}

0 commit comments

Comments
 (0)