diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e63a3829d8..984d51a2af 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -882,7 +882,7 @@ jobs: run: bun install --frozen-lockfile --ignore-scripts --linker=hoisted - run: bun run --filter '@hyperframes/{parsers,lint,studio-server}' build - run: bun run --cwd packages/core build - - run: bun run --cwd packages/cli test src/utils/npxCommand.test.ts src/commands/skills.test.ts + - run: bun run --cwd packages/cli test src/utils/npxCommand.test.ts src/commands/skills.test.ts src/utils/shellArg.test.ts env: HF_NPX_SHIM_E2E: "1" diff --git a/docs/packages/cli.mdx b/docs/packages/cli.mdx index 8007370d87..32c4800864 100644 --- a/docs/packages/cli.mdx +++ b/docs/packages/cli.mdx @@ -1172,7 +1172,10 @@ preview holds the project's edit history. So `open` first stops the project's `preview --background` server and says so. It leaves any other preview running, such as one started in a terminal, and prints the `preview --stop` command instead. With `--json`, the `preview` field reports `none`, `stopped` or -`left-running`. +`left-running`. A `left-running` preview carries its `stopCommand`. That is +`null` when the folder's name can't be printed safely for every Windows shell, +and `stopCommandFromProject` then holds the command to run from inside the +project folder. `catch-up` is the other half of that hand-off. Run it when the person is back from the desktop app, before you change anything: it lists what they asked and diff --git a/packages/cli/src/commands/init.ts b/packages/cli/src/commands/init.ts index ac088c0a5c..86f4f6cba2 100644 --- a/packages/cli/src/commands/init.ts +++ b/packages/cli/src/commands/init.ts @@ -1029,6 +1029,8 @@ export default defineCommand({ await keepSkillsCurrent(destDir); } + const shownName = shellArg(name); + const cdLine = shownName === null ? "go into the project folder" : `cd ${shownName}`; console.log(); console.log("Get started:"); console.log(); @@ -1045,7 +1047,7 @@ export default defineCommand({ console.log(); console.log(` ${c.accent("2.")} Open this project with your AI coding agent:`); console.log( - ` ${c.accent(`cd ${shellArg(name)}`)} then start ${c.accent("Claude Code")}, ${c.accent("Cursor")}, or your preferred agent`, + ` ${c.accent(cdLine)} then start ${c.accent("Claude Code")}, ${c.accent("Cursor")}, or your preferred agent`, ); console.log(); console.log(` ${c.accent("3.")} Try a starter prompt:`); @@ -1057,13 +1059,13 @@ export default defineCommand({ ); console.log(); console.log(` ${c.accent("4.")} Preview in the browser:`); - console.log(` ${c.accent(`cd ${shellArg(name)}`)} && ${c.accent("npm run dev")}`); + console.log(` ${c.accent(cdLine)} && ${c.accent("npm run dev")}`); console.log(); console.log(` ${c.accent("5.")} Check the composition:`); - console.log(` ${c.accent(`cd ${shellArg(name)}`)} && ${c.accent("npm run check")}`); + console.log(` ${c.accent(cdLine)} && ${c.accent("npm run check")}`); console.log(); console.log(` ${c.accent("6.")} Render to MP4 when ready:`); - console.log(` ${c.accent(`cd ${shellArg(name)}`)} && ${c.accent("npm run render")}`); + console.log(` ${c.accent(cdLine)} && ${c.accent("npm run render")}`); console.log(); console.log(` ${c.dim(`Full docs: ${cliSourced("https://hyperframes.heygen.com")}`)}`); return; diff --git a/packages/cli/src/commands/open.test.ts b/packages/cli/src/commands/open.test.ts index fc45cb7473..0733c8ace0 100644 --- a/packages/cli/src/commands/open.test.ts +++ b/packages/cli/src/commands/open.test.ts @@ -55,6 +55,22 @@ describe("endPreviewBeforeOpening", () => { ); }); + it("gives JSON no stop command when the folder name has no safe spelling", async () => { + const hostile = join(projectDir, "$(calc)&calc"); + const result = await endPreviewBeforeOpening(hostile, { + status: async () => ({ pid: 999, port: 3002, projectDir: hostile }), + stop: never, + appInstalled: () => true, + platform: "win32", + }); + + expect(result).toMatchObject({ + state: "left-running", + stopCommand: null, + stopCommandFromProject: "hyperframes preview --stop --port 3002", + }); + }); + it("keeps the preview when the app isn't installed, since nothing will open", async () => { const result = await endPreviewBeforeOpening(projectDir, { status: async () => background, diff --git a/packages/cli/src/commands/open.ts b/packages/cli/src/commands/open.ts index 4dfb3106c0..7e517ba6a3 100644 --- a/packages/cli/src/commands/open.ts +++ b/packages/cli/src/commands/open.ts @@ -29,20 +29,39 @@ const WHY_NOT: Record["reason"], s type PreviewBeforeOpen = | { state: "none" } | { state: "stopped"; port: number } - | { state: "left-running"; port: number; stopCommand: string; error?: string }; + | { + 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; stop?: (dir: string, startPort: number) => Promise; appInstalled?: () => boolean; + platform?: NodeJS.Platform; } = {}, ): Promise { const running = await status(dir, PREVIEW_SCAN_START_PORT); @@ -50,7 +69,7 @@ export async function endPreviewBeforeOpening( const leftRunning = (error?: string): PreviewBeforeOpen => ({ state: "left-running", port: running.port, - stopCommand: previewStopCommandFor(dir, running.port), + ...stopCommands(dir, running.port, platform), ...(error ? { error } : {}), }); const startedInBackground = Boolean(running.logPath); @@ -75,7 +94,8 @@ function printPreview(preview: PreviewBeforeOpen, opened: boolean): void { ? `${c.warn("◇")} Couldn't stop this project's preview (port ${preview.port}): ${preview.error}` : `${c.warn("◇")} A preview of this project is running (port ${preview.port}), and the app's edits wait until it stops.`, ); - console.log(` Stop it with: ${c.accent(preview.stopCommand)}`); + const stop = preview.stopCommand ?? `${preview.stopCommandFromProject} from the project folder`; + console.log(` Stop it with: ${c.accent(stop)}`); } function printResult(project: ProjectDir, result: DesktopOpenResult): void { diff --git a/packages/cli/src/commands/preview.test.ts b/packages/cli/src/commands/preview.test.ts index e6c960bfb4..104b459b4c 100644 --- a/packages/cli/src/commands/preview.test.ts +++ b/packages/cli/src/commands/preview.test.ts @@ -28,6 +28,7 @@ import { previewLaunchMode, previewLaunchModeError, previewPortError, + stopBackgroundCommand, publicPreviewPid, previewViteArgs, reportPreviewShutdown, @@ -854,3 +855,23 @@ describe("preview inside a host app's agent run", () => { expect(killOrphanedProcesses).not.toHaveBeenCalled(); }); }); + +describe("stopBackgroundCommand", () => { + it("spells the project folder so pasting the stop line runs nothing else", () => { + expect(stopBackgroundCommand("/work/my film", "darwin")).toBe( + 'hyperframes preview "/work/my film" --stop', + ); + expect(stopBackgroundCommand("/work/$(touch x)", "darwin")).toBe( + "hyperframes preview '/work/$(touch x)' --stop", + ); + expect(stopBackgroundCommand("C:\\Users\\Bob\\film", "win32")).toBe( + 'hyperframes preview "C:\\Users\\Bob\\film" --stop', + ); + expect(stopBackgroundCommand("C:\\work\\$(calc)", "win32")).toBe( + "hyperframes preview --stop from the project folder", + ); + expect(stopBackgroundCommand("C:\\work\\$(calc)&calc", "win32")).toBe( + "hyperframes preview --stop from the project folder", + ); + }); +}); diff --git a/packages/cli/src/commands/preview.ts b/packages/cli/src/commands/preview.ts index 8d65fbd40d..54b8857213 100644 --- a/packages/cli/src/commands/preview.ts +++ b/packages/cli/src/commands/preview.ts @@ -48,6 +48,7 @@ import { createRequire } from "node:module"; import * as clack from "../ui/prompts.js"; import { c } from "../ui/colors.js"; import { desktopHint, insideHostApp } from "../utils/desktopApp.js"; +import { shellArg } from "../utils/shellArg.js"; import { isDevMode } from "../utils/env.js"; import { normalizeErrorMessage as errorMessage } from "../utils/errorMessage.js"; import { buildNpxCommand } from "../utils/npxCommand.js"; @@ -572,7 +573,7 @@ export default defineCommand({ : `Running in the background. Log: ${background.logPath}`, "Changes reload automatically in the studio.", ], - footer: `Stop with: hyperframes preview ${JSON.stringify(dir)} --stop`, + footer: `Stop with: ${stopBackgroundCommand(dir)}`, }); } openStudioBrowser(url, projectName, { @@ -704,6 +705,16 @@ export function previewLaunchModeError(options: { return null; } +export function stopBackgroundCommand( + dir: string, + platform: NodeJS.Platform = process.platform, +): string { + const shown = shellArg(dir, platform); + return shown === null + ? "hyperframes preview --stop from the project folder" + : `hyperframes preview ${shown} --stop`; +} + export function previewPortError(port: string | undefined): string | null { try { parsePort(port ?? "3002"); diff --git a/packages/cli/src/utils/desktopApp.test.ts b/packages/cli/src/utils/desktopApp.test.ts index 33e7965ed9..591af14488 100644 --- a/packages/cli/src/utils/desktopApp.test.ts +++ b/packages/cli/src/utils/desktopApp.test.ts @@ -395,11 +395,26 @@ describe("openCommandFor", () => { "hyperframes open .", ); expect(openCommandFor(join(work, "films", "a"), work)).toBe( - `hyperframes open ${join("films", "a")}`, + process.platform === "win32" ? 'hyperframes open "films\\a"' : "hyperframes open films/a", ); expect(openCommandFor(join(work, "my film"), work)).toBe('hyperframes open "my film"'); }); + it("spells a Windows folder so PowerShell and Git Bash run no part of its name", () => { + const work = resolve("work"); + expect(openCommandFor(join(work, "$(calc)"), work, "win32")).toBe( + "hyperframes open from the project folder", + ); + expect(openCommandFor(join(work, "$(calc)&calc"), work, "win32")).toBe( + "hyperframes open from the project folder", + ); + }); + + it("has no Windows stop command for a folder with no safe spelling", () => { + const work = resolve("work"); + expect(previewStopCommandFor(join(work, "$(calc)&calc"), 3002, work, "win32")).toBeNull(); + }); + it("names the matching `preview --stop` the same way", () => { const work = resolve("work"); expect(previewStopCommandFor(work, 3002, work)).toBe( diff --git a/packages/cli/src/utils/desktopApp.ts b/packages/cli/src/utils/desktopApp.ts index b765518b5c..ea1b23414a 100644 --- a/packages/cli/src/utils/desktopApp.ts +++ b/packages/cli/src/utils/desktopApp.ts @@ -247,17 +247,28 @@ function leaveIntent(dir: string, cta?: string, doc?: "storyboard"): () => void }; } -function shownDir(dir: string, cwd: string): string { - return shellArg(relative(cwd, dir) || "."); +function shownDir(dir: string, cwd: string, platform: NodeJS.Platform): string | null { + return shellArg(relative(cwd, dir) || ".", platform); } /** The `hyperframes open` line for a project, relative to where the person is. */ -export function openCommandFor(dir: string, cwd = process.cwd()): string { - return `hyperframes open ${shownDir(dir, cwd)}`; +export function openCommandFor( + dir: string, + cwd = process.cwd(), + platform: NodeJS.Platform = process.platform, +): string { + const shown = shownDir(dir, cwd, platform); + return shown === null ? "hyperframes open from the project folder" : `hyperframes open ${shown}`; } -export function previewStopCommandFor(dir: string, port: number, cwd = process.cwd()): string { - return `hyperframes preview ${shownDir(dir, cwd)} --stop --port ${port}`; +export function previewStopCommandFor( + dir: string, + port: number, + cwd = process.cwd(), + platform: NodeJS.Platform = process.platform, +): string | null { + const shown = shownDir(dir, cwd, platform); + return shown === null ? null : `hyperframes preview ${shown} --stop --port ${port}`; } /** Spotlight's copies of an app with this bundle id; an updater's hidden leftover (`.X.app.installing-…`) is none. */ @@ -309,7 +320,7 @@ export function desktopHint( ): string | null { if (insideHostApp(env) || !someoneToTell(env, tty)) return null; if (ready && (installed ?? desktopInstalled({ platform, env }))) { - const open = openCommandFor(dir); + const open = openCommandFor(dir, process.cwd(), platform); const how = preview === "background" ? `${open} (this stops the background preview)` diff --git a/packages/cli/src/utils/shellArg.test.ts b/packages/cli/src/utils/shellArg.test.ts index ab407e85c0..6634dfece7 100644 --- a/packages/cli/src/utils/shellArg.test.ts +++ b/packages/cli/src/utils/shellArg.test.ts @@ -1,10 +1,43 @@ -import { execFileSync } from "node:child_process"; -import { mkdirSync, mkdtempSync, realpathSync, rmSync } from "node:fs"; +import { execFileSync, spawnSync } from "node:child_process"; +import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; -import { join } from "node:path"; +import { join, win32 } from "node:path"; import { afterAll, describe, expect, it } from "vitest"; import { shellArg } from "./shellArg.js"; +const WINDOWS_ROUND_TRIP = [ + "my-video", + "my first video", + "it's mine", + "o\u2019neil \u2018draft\u2019 it's", + "\u201Alow\u201B 'n\u2019 \u2018mixed'", + "Q&A (draft); 100% | ac ^", + "100% done", + "서울 여행", + "a,b", + "@scope", + "films\\my film", + "C:\\Users\\Bob\\film", + "C:\\work\\it's\\", +]; + +// `“ ” „` end a PowerShell double-quoted string; `$` and a backtick expand in PowerShell and Git Bash, +// `!` in interactive Git Bash, and `%NAME%` in cmd.exe. +const WINDOWS_UNPRINTABLE = [ + "$(calc)", + "a`b", + "o'neil $x", + "x\u201D;calc;\u201Dy", + "x\u2019;calc;\u2018 $y", + "$(calc)&calc", + "\u201Cquoted\u201D", + "a\nb", + "%USERPROFILE%", + "50% off, 20% more", + "Hello!", + "a!b", +]; + const NAMES = [ "my-video", "서울여행", @@ -34,10 +67,25 @@ describe("shellArg", () => { ]); }); - it("uses double quotes on Windows, where a backslash path needs none", () => { - expect(shellArg("films\\a", "win32")).toBe("films\\a"); + it("uses double quotes on Windows, for a backslash path too", () => { + expect(shellArg("films/a", "win32")).toBe("films/a"); + expect(shellArg("films\\a", "win32")).toBe('"films\\a"'); + expect(shellArg("C:\\Users\\Bob\\film", "win32")).toBe('"C:\\Users\\Bob\\film"'); + expect(shellArg("C:\\", "win32")).toBe('"C:\\\\"'); expect(shellArg("my first video", "win32")).toBe('"my first video"'); expect(shellArg("it's mine", "win32")).toBe(`"it's mine"`); + expect(shellArg("Q&A (draft); 100%", "win32")).toBe('"Q&A (draft); 100%"'); + expect(shellArg("서울 여행", "win32")).toBe('"서울 여행"'); + }); + + it("quotes a Windows name that PowerShell would read as an array or a splat", () => { + expect(shellArg("a,b", "win32")).toBe('"a,b"'); + expect(shellArg("@scope", "win32")).toBe('"@scope"'); + expect(shellArg("films/@scope", "win32")).toBe("films/@scope"); + }); + + it("prints nothing on Windows for a name no shell there reads literally", () => { + for (const name of WINDOWS_UNPRINTABLE) expect(shellArg(name, "win32"), name).toBeNull(); }); const root = mkdtempSync(join(tmpdir(), "hf-shell-arg-")); @@ -46,11 +94,61 @@ describe("shellArg", () => { it.skipIf(process.platform === "win32")("prints a cd that a POSIX shell runs as written", () => { for (const name of NAMES) { mkdirSync(join(root, name), { recursive: true }); - const pwd = execFileSync("/bin/sh", ["-c", `cd ${shellArg(name)} && pwd -P`], { + const pwd = execFileSync("/bin/sh", ["-c", `cd ${shellArg(name, "darwin")} && pwd -P`], { cwd: root, encoding: "utf8", }); expect(pwd.trim()).toBe(realpathSync(join(root, name))); } }); + + it.skipIf(process.platform === "win32")( + "prints a Windows word that Git Bash reads as written", + () => { + for (const name of WINDOWS_ROUND_TRIP) { + const shown = execFileSync("/bin/bash", ["-c", `printf %s ${shellArg(name, "win32")}`], { + encoding: "utf8", + }); + expect(shown, name).toBe(name); + } + }, + ); + + const argvScript = join(root, "argv.cjs"); + writeFileSync(argvScript, "process.stdout.write(JSON.stringify(process.argv.slice(2)));"); + const readArgv = (output: string): string[] => JSON.parse(output) as string[]; + + it.runIf(process.platform === "win32")( + "prints a Windows word that cmd.exe reads as written", + () => { + for (const name of WINDOWS_ROUND_TRIP) { + const line = `"${process.execPath}" "${argvScript}" ${shellArg(name, "win32")}`; + const run = spawnSync("cmd.exe", ["/d", "/s", "/c", `"${line}"`], { + encoding: "utf8", + windowsVerbatimArguments: true, + }); + expect(run.status, run.stderr).toBe(0); + expect(readArgv(run.stdout), name).toEqual([name]); + } + }, + ); + + it.runIf(process.platform === "win32")( + "prints a Windows word that PowerShell reads as written", + () => { + for (const name of WINDOWS_ROUND_TRIP) { + const line = `& '${process.execPath}' '${argvScript}' ${shellArg(name, "win32")}`; + const output = execFileSync( + "powershell.exe", + ["-NoProfile", "-EncodedCommand", Buffer.from(line, "utf16le").toString("base64")], + { encoding: "utf8" }, + ); + // Windows PowerShell hands a space-free word to a program unquoted, so a doubled trailing backslash stays doubled. + expect( + readArgv(output).map((arg) => win32.normalize(arg)), + name, + ).toEqual([win32.normalize(name)]); + } + }, + ); }); diff --git a/packages/cli/src/utils/shellArg.ts b/packages/cli/src/utils/shellArg.ts index 8020403742..62ed26745e 100644 --- a/packages/cli/src/utils/shellArg.ts +++ b/packages/cli/src/utils/shellArg.ts @@ -1,11 +1,24 @@ const PLAIN = /^[\p{L}\p{M}\p{N}_./@:+,=-]+$/u; -const PLAIN_WINDOWS_PATH = /^[\p{L}\p{M}\p{N}_./@:+,=\\-]+$/u; +const PLAIN_WINDOWS_WORD_WITHOUT_BACKSLASH_COMMA_OR_SPLAT = /^(?!@)[\p{L}\p{M}\p{N}_./@:+=-]+$/u; const SPECIAL_IN_DOUBLE_QUOTES = /["$`\\!]/; +const SPECIAL_IN_POWERSHELL_OR_BASH_DOUBLE_QUOTES = /["$`!\u201C-\u201E\p{Cc}]/u; +const CMD_VARIABLE = /%[^%]+%/; +const TRAILING_BACKSLASHES = /\\+$/; -/** `text` as one word of a command printed for the person to paste into their shell. */ -export function shellArg(text: string, platform: NodeJS.Platform = process.platform): string { - if (platform === "win32") return PLAIN_WINDOWS_PATH.test(text) ? text : `"${text}"`; +/** `text` as one word of a pasteable command; on Windows literal in PowerShell, cmd.exe and Git Bash alike, or null. */ +export function shellArg( + text: string, + platform: NodeJS.Platform = process.platform, +): string | null { + if (platform === "win32") return windowsShellArg(text); if (PLAIN.test(text)) return text; if (!SPECIAL_IN_DOUBLE_QUOTES.test(text)) return `"${text}"`; return `'${text.replaceAll("'", "'\\''")}'`; } + +function windowsShellArg(text: string): string | null { + if (PLAIN_WINDOWS_WORD_WITHOUT_BACKSLASH_COMMA_OR_SPLAT.test(text)) return text; + if (SPECIAL_IN_POWERSHELL_OR_BASH_DOUBLE_QUOTES.test(text) || CMD_VARIABLE.test(text)) + return null; + return `"${text.replace(TRAILING_BACKSLASHES, "$&$&")}"`; +}