Files
hyperframes/packages/cli/src/commands/open.ts
T
Michael Wang 3e788fb15a fix(cli): show control characters in printed names as visible escapes (#8008)
* fix(cli): project folder names print control characters as visible escapes

check, info, compositions, benchmark, play, present and preview printed the
project folder name, and in places the project path, straight to the
terminal. A folder name can hold escape bytes on Linux and macOS, so a
received project could move the cursor, rewrite earlier lines, set the
window title or write the clipboard. Those lines now go through
terminalText(), as validate, snapshot, layout and lint already do. This
covers the preview summary, --status, --stop, --list and --kill-all lines,
and the check report path. The CLI's own colours stay, and --json output is
unchanged.

The play page also HTML-escapes the name in its title and footer, as the
present page does.

* fix(cli): preview --selection and --context print Studio text as visible escapes

The human output of preview --selection and --context printed the selected
element's label, source file, target and thumbnail URL, and the preview
server's project name, straight to the terminal. These come from the
composition or from whichever preview server answers, so control characters
in them could move the cursor, rewrite earlier lines, set the window title
or write the clipboard. They now go through terminalText(), as do the
failure messages these commands print. The CLI's own colours stay, and
--json output is unchanged.

* fix(cli): cloud get, list and delete print server fields as visible escapes

The human output of cloud get printed render fields from the server, such
as the failure message, title, composition and URLs, straight to the
terminal. A failure message can quote text from the rendered project, so
control characters in it could move the cursor, rewrite earlier lines, set
the window title or write the clipboard. cloud get, cloud list (rows and
the next-page token) and cloud delete now pass those fields through
terminalText(). The CLI's own colours stay, and --json output is unchanged.

* fix(inspector): the live inspection stamp gives the page only the generation id

prepareLiveInspection wrote the project's absolute path into the preview
page as window.__hfLiveInspection.project. Nothing in the page reads it, but
any composition script on that page could, which told it the account name
and folder layout. The page now gets only the generation id; the project
path stays with the host that prepared the page.

* fix(skills): locate.mjs keeps its grid font in a private per-run folder

locate.mjs drew its grid labels with a font at the fixed shared path
/tmp/locate-font.ttf. It used whatever file was already there and copied a
system font onto that path otherwise, following any link in its place. On a
machine shared with other accounts, someone else could plant that file
first, so the grid showed wrong numbers, a file appeared where they chose,
or every run failed.

The font is now copied into a folder made with mkdtemp (mode 0700) for each
run and removed when the run ends, so no file another account can create is
read or written. The skills manifest hash is regenerated.

* fix: escape the check report path and lint warnings, and harden locate.mjs font cleanup

check's report path notice and its not-recorded warning, and preview's
"Lint did not finish" warning, now print control characters as visible
escapes, like the other lines that carry the project path.

locate.mjs escapes the font path for ffmpeg's filter syntax, so a temp
folder with ':', ',', quotes or brackets in its name still works, and it
removes its font folder when the run is stopped by SIGINT or SIGTERM before
re-raising the signal.

play and present share one HTML escape helper.

* refactor(cli): keep the shared HTML escape helper within the comment budget

* fix: one HTML escape helper for the CLI, and locate.mjs escapes its font path in one pass

The sign-in callback page uses the shared escapeHtml helper, which now also
escapes single quotes.

locate.mjs escapes the font path for ffmpeg's option list and filtergraph
in a single replacement with the same result as before, and removes its
font folder on SIGHUP as well as SIGINT and SIGTERM.

* fix(cli): escape render output paths and cloud upload names

A finished render printed its output path and the desktop app hint raw.
The default output path sits under the project folder and is named after
it, so the folder name reached the terminal on every render. Batch renders
printed row output paths and the manifest path raw, and cloud render
printed the archive name in its upload progress lines and walked file
names in its left-out warnings raw. These lines now go through
terminalText() or terminalLines(). --json output is unchanged.
2026-11-18 09:30:01 +00:00

164 lines
6.1 KiB
TypeScript

import { defineCommand } from "../utils/defineCommand.js";
import type { Example } from "./_examples.js";
import { c } from "../ui/colors.js";
import { terminalLines, terminalText } from "@hyperframes/core";
import { setCommandExitCode } from "../utils/commandResult.js";
import {
desktopInstalled,
downloadHint,
openInDesktop,
previewStopCommandFor,
type DesktopOpenResult,
} from "../utils/desktopApp.js";
import { resolveProject, resolveProjectOrThrow, type ProjectDir } from "../utils/project.js";
import { readBackgroundPreviewStatus, stopBackgroundPreview } from "./previewLifecycle.js";
export const examples: Example[] = [
["Open this project in the HyperFrames desktop app", "hyperframes ."],
["Open another project", "hyperframes ./my-video"],
["Same, naming the command (needed for a folder named like a command)", "hyperframes open ."],
["For agents", "hyperframes open --json"],
];
const WHY_NOT: Record<Extract<DesktopOpenResult, { opened: false }>["reason"], string | null> = {
"handoff-unavailable": null,
"unsupported-platform": "Opening a project from the CLI works on macOS, Windows and Linux only.",
"not-installed": "The HyperFrames desktop app isn't installed on this computer.",
"open-failed": "The HyperFrames desktop app couldn't be started.",
};
type PreviewBeforeOpen =
| { state: "none" }
| { state: "stopped"; port: number }
| {
state: "left-running";
port: number;
stopCommand: string | null;
stopCommandFromProject?: string;
error?: string;
};
const PREVIEW_SCAN_START_PORT = 3002;
function stopCommands(
dir: string,
port: number,
platform: NodeJS.Platform,
): { stopCommand: string | null; stopCommandFromProject?: string } {
const stopCommand = previewStopCommandFor(dir, port, process.cwd(), platform);
return stopCommand === null
? { stopCommand, stopCommandFromProject: `hyperframes preview --stop --port ${port}` }
: { stopCommand };
}
export async function endPreviewBeforeOpening(
dir: string,
{
status = readBackgroundPreviewStatus,
stop = stopBackgroundPreview,
appInstalled = () => desktopInstalled(),
platform = process.platform,
}: {
status?: (dir: string, startPort: number) => ReturnType<typeof readBackgroundPreviewStatus>;
stop?: (dir: string, startPort: number) => Promise<boolean>;
appInstalled?: () => boolean;
platform?: NodeJS.Platform;
} = {},
): Promise<PreviewBeforeOpen> {
const running = await status(dir, PREVIEW_SCAN_START_PORT);
if (!running) return { state: "none" };
const leftRunning = (error?: string): PreviewBeforeOpen => ({
state: "left-running",
port: running.port,
...stopCommands(dir, running.port, platform),
...(error ? { error } : {}),
});
const startedInBackground = Boolean(running.logPath);
if (!startedInBackground || !appInstalled()) return leftRunning();
try {
return (await stop(dir, running.port))
? { state: "stopped", port: running.port }
: { state: "none" };
} catch (error) {
return leftRunning(error instanceof Error ? error.message : String(error));
}
}
function printPreview(preview: PreviewBeforeOpen, opened: boolean): void {
if (preview.state === "stopped")
return console.log(
`${c.success("◇")} Stopped this project's background preview (port ${preview.port}) so the app can edit it.`,
);
if (preview.state !== "left-running" || !opened) return;
console.log(
preview.error
? `${c.warn("◇")} Couldn't stop this project's preview (port ${preview.port}): ${terminalLines(preview.error)}`
: `${c.warn("◇")} A preview of this project is running (port ${preview.port}), and the app's edits wait until it stops.`,
);
const stop = preview.stopCommand ?? `${preview.stopCommandFromProject} from the project folder`;
console.log(` Stop it with: ${c.accent(terminalText(stop))}`);
}
function printResult(project: ProjectDir, result: DesktopOpenResult): void {
if (result.opened) {
console.log(
`${c.success("◇")} Opening ${c.accent(terminalText(project.name))} in ${result.app}`,
);
if (result.handedOver) {
const agent = { claude: "Claude Code", codex: "Codex", grok: "Grok" }[
result.handedOver.engine
];
console.log(` ${c.dim(`Its chat picks up this ${agent} conversation.`)}`);
console.log(
` ${c.dim(`When the person is back here, run ${c.accent("npx hyperframes catch-up")} to see what they did in the app.`)}`,
);
}
return;
}
const why = WHY_NOT[result.reason];
if (!why) return console.log(`${c.warn("◇")} ${downloadHint(result.downloadUrl)}`);
console.log(`${c.warn("◇")} ${why}`);
console.log(` Download it: ${c.accent(result.downloadUrl)}`);
}
/** Under --json a bad directory answers in JSON too, not with the human error box. */
function projectForJson(dir: string | undefined): ProjectDir | null {
try {
return resolveProjectOrThrow(dir);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
console.log(JSON.stringify({ ok: false, error: { code: "invalid-project", message } }));
setCommandExitCode(1);
return null;
}
}
export default defineCommand({
meta: { name: "open", description: "Open a project in the HyperFrames desktop app" },
args: {
dir: {
type: "positional",
description: "Project directory (default: current)",
required: false,
},
json: { type: "boolean", description: "Output as JSON", default: false },
},
async run({ args }) {
const project = args.json ? projectForJson(args.dir) : resolveProject(args.dir);
if (!project) return;
const preview = await endPreviewBeforeOpening(project.dir);
const result = openInDesktop(project.dir);
if (!result.opened) setCommandExitCode(1);
const catchUp =
result.opened && result.handedOver ? { catchUp: "npx hyperframes catch-up" } : {};
if (args.json)
console.log(
JSON.stringify({ project: project.dir, ...result, ...catchUp, preview }, null, 2),
);
else {
printPreview(preview, result.opened);
printResult(project, result);
}
},
});