diff --git a/packages/cli/src/commands/init.output.test.ts b/packages/cli/src/commands/init.output.test.ts new file mode 100644 index 0000000000..bee4b8337b --- /dev/null +++ b/packages/cli/src/commands/init.output.test.ts @@ -0,0 +1,237 @@ +import { copyFileSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { consumeCommandResult } from "../utils/commandResult.js"; + +const ESC = String.fromCharCode(27); +const ODD = `od${ESC}[2Jd\x07`; +const SHOWN = "od\\x1b[2Jd\\x07"; + +const fake = vi.hoisted(() => ({ + lines: [] as string[], + attended: false, + json: false, + confirmAnswer: false, + templates: [] as Array>, + fetchRemoteTemplate: vi.fn(), + updateSkills: vi.fn(), +})); + +vi.mock("../utils/attendedTerminal.js", async (importOriginal) => ({ + ...(await importOriginal()), + isUnattended: () => !fake.attended, +})); +vi.mock("../utils/jsonError.js", async (importOriginal) => ({ + ...(await importOriginal()), + isJsonRun: () => fake.json, +})); +vi.mock("@clack/prompts", () => { + const say = (message: string) => void fake.lines.push(message); + return { + intro: () => undefined, + cancel: () => undefined, + isCancel: () => false, + note: (body: string, title: string) => void fake.lines.push(title, body), + confirm: async (opts: { message: string }) => { + fake.lines.push(opts.message); + return fake.confirmAnswer; + }, + select: async (opts: { options: Array<{ label: string; hint?: string }> }) => { + for (const option of opts.options) fake.lines.push(`${option.label} ${option.hint}`); + return "blank"; + }, + spinner: () => (fake.lines.push("(spinner)"), { start: say, stop: say, message: say }), + log: { info: say, warn: say, error: say }, + }; +}); +vi.mock("../ui/banner.js", () => ({ printBanner: () => undefined })); +vi.mock("../telemetry/events.js", () => ({ trackInitTemplate: () => undefined })); +vi.mock("../templates/remote.js", () => ({ fetchRemoteTemplate: fake.fetchRemoteTemplate })); +vi.mock("../templates/generators.js", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + resolveTemplateList: async () => [...actual.BUNDLED_TEMPLATES, ...fake.templates], + }; +}); +vi.mock("./skills.js", () => ({ updateSkills: fake.updateSkills })); +vi.mock("./preview.js", () => ({ default: { meta: { name: "preview" }, run: () => undefined } })); + +const { default: initCommand } = await import("./init.js"); + +let work: string; + +const printed = (): string => + fake.lines.join("\n").replace(new RegExp(`${ESC}\\[[0-9;]*m`, "g"), ""); + +function expectNoControlCharacters(): void { + expect(printed()).not.toContain(ESC); + expect(printed()).not.toContain("\x07"); +} + +function run(args: Record): Promise { + return Promise.resolve( + initCommand.run?.({ + args: { "skip-skills": true, ...args }, + rawArgs: [], + cmd: initCommand, + } as never), + ); +} + +function oddFile(name: string): string { + const path = join(work, name); + writeFileSync(path, ""); + return path; +} + +beforeEach(() => { + fake.lines.length = 0; + fake.attended = false; + fake.json = false; + fake.confirmAnswer = false; + fake.templates = []; + fake.fetchRemoteTemplate.mockReset().mockRejectedValue(new Error(`gone ${ODD}\nsecond line`)); + fake.updateSkills.mockReset().mockRejectedValue(new Error(`no skills ${ODD}`)); + work = mkdtempSync(join(tmpdir(), "hf-init-output-")); + for (const method of ["log", "error", "warn"] as const) + vi.spyOn(console, method).mockImplementation((...args: unknown[]) => { + fake.lines.push(args.join(" ")); + }); +}); + +afterEach(() => { + consumeCommandResult(); + vi.restoreAllMocks(); + rmSync(work, { recursive: true, force: true }); +}); + +describe("init output without prompts", () => { + // fails without the fix: the example command repeats the old flag's value and the name as they were typed. + it.each([ + [{ template: `tpl-${ODD}` }, "npx hyperframes init --example "], + [{ "video-legacy": `clip-${ODD}` }, "npx hyperframes init --video "], + ])("leaves values that cannot be typed back out of the example for %o", async (args, line) => { + await expect(run({ name: join(work, `n-${ODD}`), ...args })).rejects.toThrow(); + expect(printed()).toContain(line); + expectNoControlCharacters(); + }); + + // fails without the fix: the refused value and the name are repeated as they were typed. + it.each([ + [{ resolution: `res-${ODD}` }, `Invalid --resolution: "res-${SHOWN}".`], + [{ video: `clip-${ODD}.mp4` }, `Video file not found: clip-${SHOWN}.mp4`], + [{ audio: `song-${ODD}.mp3` }, `Audio file not found: song-${SHOWN}.mp3`], + ])("shows control characters in a refused %o as text", async (args, line) => { + await expect(run({ name: join(work, `n-${ODD}`), ...args })).rejects.toThrow(); + expect(printed()).toContain(line.replace("init n-", `init ${join(work, "n-")}`)); + expectNoControlCharacters(); + }); + + // fails without the fix: the example name and the reason are printed as they arrived. + it("shows control characters in a failed example download as text", async () => { + await expect(run({ name: join(work, "film"), example: `ex-${ODD}` })).rejects.toThrow(); + expect(printed()).toContain( + `Failed to scaffold example "ex-${SHOWN}": gone ${SHOWN}\nsecond line`, + ); + expectNoControlCharacters(); + }); + + // Windows refuses control characters in file and folder names. + describe.skipIf(process.platform === "win32")("with odd names on disk", () => { + // fails without the fix: the folder name is repeated as it was typed. + it("shows control characters in a folder that is not empty as text", async () => { + const name = join(work, `full-${ODD}`); + mkdirSync(name); + writeFileSync(join(name, "notes.txt"), ""); + await expect(run({ name })).rejects.toThrow(); + expect(printed()).toContain( + `Directory already exists and is not empty: ${work}/full-${SHOWN}`, + ); + expectNoControlCharacters(); + }); + + // fails without the fix: the audio name, the new folder, its files and the next step are printed as they are on disk. + it("shows control characters in the lines of a finished project as text", async () => { + const name = join(work, `film-${ODD}`); + await run({ + name, + audio: oddFile(`song-${ODD}.mp3`), + "skip-transcribe": true, + "skip-skills": false, + }); + expect(printed()).toContain(`Audio: song-${SHOWN}.mp3`); + expect(printed()).toContain(`Created ${work}/film-${SHOWN}/`); + expect(printed()).toContain(`\n song-${SHOWN}.mp3`); + expect(printed()).toContain(`AI coding skills install skipped: no skills ${SHOWN}`); + expect(printed()).toContain(`film-${SHOWN}`); + expect(printed()).toContain("npm run dev"); + expectNoControlCharacters(); + }); + }); +}); + +describe("init output with prompts", () => { + beforeEach(() => { + fake.attended = true; + }); + + // fails without the fix: the path is repeated as it was typed. + it.each([ + [{ video: `clip-${ODD}.mp4` }, `File not found: clip-${SHOWN}.mp4`], + [{ audio: `song-${ODD}.mp3` }, `File not found: song-${SHOWN}.mp3`], + ])("shows control characters in a missing %o as text", async (args, line) => { + await expect(run({ name: join(work, "film"), ...args })).rejects.toThrow(); + expect(printed()).toContain(line); + expectNoControlCharacters(); + }); + + // fails without the fix: a run that asked for JSON went to the questions, and a spinner drew the video's status on stdout. + it.each([undefined, "gone"])("asks and spins nothing in a JSON run: %s", async (example) => { + fake.json = true; + const video = join(work, "clip.mov"); + copyFileSync(new URL("./__fixtures__/mpeg4.mp4", import.meta.url), video); + await run({ name: join(work, "f"), video, example, "skip-transcribe": true }).catch(String); + expect(printed()).toContain("Transcoded to clip.mp4\n"); + expect(printed()).toContain(example ? 'Failed to scaffold example "gone"' : "Get started:"); + expect(printed()).not.toContain("(spinner)"); + }); + + // fails without the fix: the example name and the reason are printed as they arrived. + it("shows control characters in a failed example download as text", async () => { + await expect(run({ name: join(work, "film"), example: `ex-${ODD}` })).rejects.toThrow(); + expect(printed()).toContain(`Downloading example ex-${SHOWN}...`); + expect(printed()).toContain(`gone ${SHOWN}\nsecond line`); + expectNoControlCharacters(); + }); + + // fails without the fix: each example's title and description are shown as they arrived. + it("shows control characters in the example list as text", async () => { + fake.templates = [{ id: "far", label: `Far ${ODD}`, hint: `about ${ODD}`, source: "remote" }]; + await run({ name: join(work, "film") }); + expect(printed()).toContain(`Far ${SHOWN} about ${SHOWN} (download)`); + expectNoControlCharacters(); + }); + + describe.skipIf(process.platform === "win32")("with odd names on disk", () => { + // fails without the fix: the folder name is put into the question as it was typed. + it("shows control characters in the overwrite question as text", async () => { + const name = join(work, `full-${ODD}`); + mkdirSync(name); + writeFileSync(join(name, "notes.txt"), ""); + await expect(run({ name })).rejects.toThrow(); + expect(printed()).toContain(`Directory ${work}/full-${SHOWN} already exists`); + expectNoControlCharacters(); + }); + + // fails without the fix: the audio name, the new folder and its files are shown as they are on disk. + it("shows control characters in the lines of a finished project as text", async () => { + await run({ name: join(work, `film-${ODD}`), audio: oddFile(`song-${ODD}.mp3`) }); + expect(printed()).toContain(`Audio copied to song-${SHOWN}.mp3`); + expect(printed()).toContain(`Created ${work}/film-${SHOWN}/`); + expect(printed()).toContain(`song-${SHOWN}.mp3\n`); + expectNoControlCharacters(); + }); + }); +}); diff --git a/packages/cli/src/commands/init.test.ts b/packages/cli/src/commands/init.test.ts index 2a8e60c906..3e6bca3e0d 100644 --- a/packages/cli/src/commands/init.test.ts +++ b/packages/cli/src/commands/init.test.ts @@ -383,6 +383,7 @@ describe("hyperframes init flag rename", () => { try { const res = runInit([target, "--non-interactive", "--skip-transcribe", "--audio", audio]); expect(res.status).toBe(0); + expect(res.stdout.startsWith("Audio: track.wav\nCreated ")).toBe(true); const html = readFileSync(join(target, "index.html"), "utf-8"); expect(html).toMatch(/]*src="track\.wav"/); expect(html).not.toMatch(/ { } }); + // fails without the fix: the next steps printed `cd` with a path that is not the folder's. + it.skipIf(process.platform === "win32")( + "prints the next steps as bare commands for a folder whose name cannot be typed back", + () => { + const dir = mkdtempSync(join(tmpdir(), "hf-init-test-")); + const target = join(dir, "my\nfilm"); + try { + const res = runInit([target, "--example", "blank", "--non-interactive", "--skip-skills"]); + expect(res.status).toBe(0); + expect(existsSync(join(target, "index.html"))).toBe(true); + expect(res.stdout).toContain("Get started, from the project folder:\n"); + for (const step of ["dev", "check", "render"]) + expect(res.stdout).toContain(`\n npm run ${step}\n`); + expect(res.stdout).not.toMatch(/\bcd |&&/); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }, + ); + + it("prints next steps a shell runs as written for a name with a space", () => { + const dir = mkdtempSync(join(tmpdir(), "hf-init-test-")); + const target = join(dir, "my film"); + try { + const res = runInit([target, "--example", "blank", "--non-interactive", "--skip-skills"]); + expect(res.status).toBe(0); + expect(res.stdout).toContain(`cd "${target}" && npm run dev`); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }); + + // fails without the fix: the example command carried the values as shown, which is not what was typed. + it.each([ + ["--template", "--example "], + ["-V", "--video "], + ])( + "%s prints an example with placeholders for values that cannot be typed back", + (flag, shown) => { + const bell = String.fromCharCode(7); + const res = runInit([ + `pro${bell}j`, + flag, + `bl${bell}ank`, + "--non-interactive", + "--skip-skills", + ]); + expect(res.status).toBe(2); + expect(res.stderr).toContain(`npx hyperframes init ${shown}`); + expect(res.stderr).not.toContain(bell); + expect(res.stderr).not.toContain("\\x07"); + }, + ); + + // One row per init failure line that names something the caller typed. + // fails without the fix: the answer's message was the line as people see it, escapes included. + describe("with --json first, a failure answers with the value as given", () => { + type Row = { + name: string; + args: string[]; + before?: (dir: string) => void; + after?: (dir: string) => void; + shown?: string; + given?: string; + exit: number; + stderr?: string; + stdout?: string; + // Windows refuses control characters in folder names; root ignores folder permissions. + skip?: boolean; + }; + const posixOnly = process.platform === "win32"; + const rows: Row[] = [ + { + name: "the renamed --template flag", + args: ["proj", "--template", "bl\u0007a\nnk "], + shown: "--example ", + given: "(given: --template bl\u0007a\nnk )", + exit: 2, + stderr: + "The --template flag was renamed to --example. Example:\n npx hyperframes init proj --example \n", + }, + { + name: "the renamed -V flag", + args: ["proj", "-V", "cl\u0007i\np.mp4 "], + shown: "--video ", + given: "(given: -V cl\u0007i\np.mp4 )", + exit: 2, + stderr: + "The -V short flag no longer maps to --video. Use --video (or -v). Example:\n npx hyperframes init proj --video \n", + }, + { + name: "a refused --resolution", + args: ["proj", "--resolution", "b\u0007a\nd "], + shown: 'Invalid --resolution: "b\\x07a\nd "', + given: 'Invalid --resolution: "b\u0007a\nd "', + exit: 2, + }, + { + name: "a folder that is not empty", + args: ["fu\u0007l\nl "], + before: (dir) => { + mkdirSync(join(dir, "fu\u0007l\nl ")); + writeFileSync(join(dir, "fu\u0007l\nl ", "notes.txt"), ""); + }, + shown: "fu\\x07l\nl ", + given: "fu\u0007l\nl ", + exit: 1, + skip: posixOnly, + }, + { + name: "a missing --video", + args: ["proj", "--video", "cl\u0007i\np.mp4 "], + shown: "Video file not found: cl\\x07i\np.mp4 ", + given: "Video file not found: cl\u0007i\np.mp4 ", + exit: 1, + }, + { + name: "a missing --audio", + args: ["proj", "--audio", "so\u0007n\ng.mp3 "], + shown: "Audio file not found: so\\x07n\ng.mp3 ", + given: "Audio file not found: so\u0007n\ng.mp3 ", + exit: 1, + }, + { + name: "an example that cannot be written", + args: ["lo\u0007cked", "--audio", "lo\u0007cked/a.wav", "--skip-transcribe"], + before: (dir) => { + mkdirSync(join(dir, "lo\u0007cked")); + writeFileSync(join(dir, "lo\u0007cked", "a.wav"), ""); + chmodSync(join(dir, "lo\u0007cked"), 0o555); + }, + after: (dir) => chmodSync(join(dir, "lo\u0007cked"), 0o755), + shown: 'Failed to scaffold example "from-file": ', + given: "lo\u0007cked", + exit: 1, + skip: posixOnly || process.getuid?.() === 0, + }, + { + name: "a folder that cannot be made, in the words of the error itself", + args: ["fi\nle /sub"], + before: (dir) => writeFileSync(join(dir, "fi\nle "), ""), + given: "fi\nle /sub'", + exit: 1, + skip: posixOnly, + }, + { + name: "a finished project, whose status line still comes first", + args: ["done", "--audio", "a.wav", "--skip-transcribe"], + before: (dir) => writeFileSync(join(dir, "a.wav"), ""), + stdout: "Audio: a.wav\nCreated done/\n", + exit: 0, + }, + { + name: "the renamed --template flag with values the shell would split", + args: ["my film", "--template", "two words"], + given: "The --template flag was renamed to --example (given: --template two words)", + exit: 2, + stderr: + 'The --template flag was renamed to --example. Example:\n npx hyperframes init "my film" --example "two words"\n', + }, + { + name: "the renamed -V flag with a value in two words", + args: ["proj", "-V", "two words.mp4"], + given: + "The -V short flag no longer maps to --video; use --video or -v (given: -V two words.mp4)", + exit: 2, + stderr: + 'The -V short flag no longer maps to --video. Use --video (or -v). Example:\n npx hyperframes init proj --video "two words.mp4"\n', + }, + ]; + + it.each(rows.filter((row) => !row.skip))("$name", (row) => { + const dir = mkdtempSync(join(tmpdir(), "hf-init-test-")); + row.before?.(dir); + try { + const res = spawnSync( + "bun", + ["run", cliEntry, "--json", "init", ...row.args, "--non-interactive"], + { + cwd: dir, + encoding: "utf-8", + timeout: 30_000, + env: { ...process.env, HYPERFRAMES_SKIP_SKILLS: "1" }, + }, + ); + expect(res.status).toBe(row.exit); + if (row.stdout !== undefined) return expect(res.stdout.startsWith(row.stdout)).toBe(true); + expect(res.stderr).toContain(row.shown ?? ""); + expect(res.stderr).not.toContain("\u0007"); + if (row.stderr !== undefined) expect(res.stderr).toBe(row.stderr); + const body = JSON.parse(res.stdout.trim()) as { ok: boolean; error: { message: string } }; + expect(body.ok).toBe(false); + expect(body.error.message).toContain(row.given ?? ""); + expect(body.error.message).not.toContain("\\x07"); + } finally { + row.after?.(dir); + rmSync(dir, { recursive: true, force: true }); + } + }); + + // A failure line added with a bare console.error would skip the helper the rows above rely on. + it("leaves console.error in init to the lines that name nothing the caller typed", () => { + const bare = [...initSource.matchAll(/console\.error\(([\s\S]*?)\);\n/g)].map((m) => m[1]); + expect(bare).toEqual([ + "c.error(tooLong)", + 'c.error("Cannot use --video and --audio together")', + 'c.dim("Use --example blank for offline use.")', + ]); + }); + }); + + it("refuses --json after the command name, before any value is read", () => { + const res = runInit(["proj", "--resolution", "bad", "--non-interactive", "--json"]); + expect(res.status).toBe(2); + const body = JSON.parse(res.stdout.trim()) as { ok: boolean; error: { code: string } }; + expect(body).toMatchObject({ ok: false, error: { code: "json_unsupported" } }); + }); + it("--template prints a rename hint and exits 2", () => { const dir = mkdtempSync(join(tmpdir(), "hf-init-test-")); const target = join(dir, "proj"); @@ -571,7 +790,7 @@ describe("hyperframes init flag rename", () => { const res = runInit([target, "--template", "blank", "--non-interactive", "--skip-skills"]); expect(res.status).toBe(2); expect(res.stderr).toContain("--template flag was renamed to --example"); - expect(res.stderr).toContain(`--example "blank"`); + expect(res.stderr).toContain("--example blank"); expect(existsSync(target)).toBe(false); } finally { rmSync(dir, { recursive: true, force: true }); diff --git a/packages/cli/src/commands/init.ts b/packages/cli/src/commands/init.ts index eb614e6375..eb4e1246c9 100644 --- a/packages/cli/src/commands/init.ts +++ b/packages/cli/src/commands/init.ts @@ -4,6 +4,7 @@ // own task. // fallow-ignore-file complexity import { failCommand, finishCommand, failUsage } from "../utils/commandResult.js"; +import { isJsonRun, printFailureLine, releaseStatus, status } from "../utils/jsonError.js"; import { writeNewFileSync } from "../utils/writeNewFile.js"; import { runCommand } from "citty"; import { defineCommand } from "../utils/defineCommand.js"; @@ -54,6 +55,8 @@ import { VERSION } from "../version.js"; import { CANVAS_DIMENSIONS, normalizeResolutionFlag, + terminalLines, + terminalText, type CanvasResolution, } from "@hyperframes/core"; import { @@ -505,7 +508,7 @@ async function handleVideoFile( if (interactive) { clack.log.warn(msg); } else { - console.log(c.warn(msg)); + status(c.warn(msg)); } } @@ -513,10 +516,14 @@ async function handleVideoFile( if (probed && !keepOriginal && !isWebCompatible(probed.videoCodec)) { if (interactive) { clack.log.warn( - c.warn(`Video codec "${probed.videoCodec}" is not supported by web browsers.`), + c.warn( + `Video codec "${terminalText(probed.videoCodec)}" is not supported by web browsers.`, + ), ); } else { - console.log(c.warn(`Video codec "${probed.videoCodec}" is not supported by browsers.`)); + status( + c.warn(`Video codec "${terminalText(probed.videoCodec)}" is not supported by browsers.`), + ); } if (hasFFmpeg()) { @@ -548,11 +555,11 @@ async function handleVideoFile( if (shouldTranscode) { const mp4Name = freeTranscodeName(destDir, localVideoName); const mp4Path = resolve(destDir, mp4Name); - const spin = clack.spinner(); + const spin = interactive ? clack.spinner() : { start: status, stop: status }; spin.start("Transcoding to H.264 MP4..."); const ok = await transcodeToMp4(videoPath, mp4Path); if (ok) { - spin.stop(c.success(`Transcoded to ${mp4Name}`)); + spin.stop(c.success(`Transcoded to ${terminalText(mp4Name)}`)); localVideoName = mp4Name; } else { spin.stop(c.warn("Transcode failed — copying original file")); @@ -566,8 +573,8 @@ async function handleVideoFile( clack.log.warn(c.dim("ffmpeg not installed — cannot transcode.")); clack.log.info(c.accent(`Install: ${getFFmpegInstallHint()}`)); } else { - console.log(c.warn("ffmpeg not installed — cannot transcode. Copying original.")); - console.log(c.dim("Install: ") + c.accent(getFFmpegInstallHint())); + status(c.warn("ffmpeg not installed — cannot transcode. Copying original.")); + status(c.dim("Install: ") + c.accent(getFFmpegInstallHint())); } copyIntoProjectUnlessAlreadyThere(videoPath, resolve(destDir, localVideoName)); } @@ -757,7 +764,9 @@ async function keepSkillsCurrent(destDir: string): Promise { } } catch (err) { console.log( - c.dim(`AI coding skills install skipped: ${err instanceof Error ? err.message : err}`), + c.dim( + `AI coding skills install skipped: ${terminalLines(err instanceof Error ? err.message : String(err))}`, + ), ); } } @@ -855,20 +864,24 @@ export default defineCommand({ }, async run({ args }) { if (args.template !== undefined) { - // Quote the value in case it looks flag-like — keeps the suggested - // command copy-pasteable. - console.error( - c.error( - `The --template flag was renamed to --example. Example:\n npx hyperframes init ${args.name ?? "my-video"} --example "${args.template}"`, - ), + const template = args.template; + printFailureLine( + () => + c.error( + `The --template flag was renamed to --example. Example:\n npx hyperframes init ${shellArg(args.name ?? "my-video") ?? ""} --example ${shellArg(template) ?? ""}`, + ), + `The --template flag was renamed to --example (given: --template ${template})`, ); failUsage(); } if (args["video-legacy"] !== undefined) { - console.error( - c.error( - `The -V short flag no longer maps to --video. Use --video (or -v). Example:\n npx hyperframes init ${args.name ?? "my-video"} --video "${args["video-legacy"]}"`, - ), + const legacy = args["video-legacy"]; + printFailureLine( + () => + c.error( + `The -V short flag no longer maps to --video. Use --video (or -v). Example:\n npx hyperframes init ${shellArg(args.name ?? "my-video") ?? ""} --video ${shellArg(legacy) ?? ""}`, + ), + `The -V short flag no longer maps to --video; use --video or -v (given: -V ${legacy})`, ); failUsage(); } @@ -886,15 +899,15 @@ export default defineCommand({ modelFlag ?? DEFAULT_MODEL, languageFlag, ); - const interactive = !nonInteractive && !isUnattended(); + const interactive = !nonInteractive && !isUnattended() && !isJsonRun(); let resolutionPreset: CanvasResolution | undefined; if (args.resolution !== undefined) { resolutionPreset = normalizeResolutionFlag(args.resolution); if (!resolutionPreset) { - console.error( + printFailureLine((show) => c.error( - `Invalid --resolution: "${args.resolution}". ` + + `Invalid --resolution: "${show(String(args.resolution))}". ` + `Use one of: landscape, portrait, landscape-4k, portrait-4k, square, square-4k, ` + `landscape-1440p, portrait-1440p, square-1440p ` + `(or aliases 1080p, 4k, uhd, 1440p, qhd, 1080p-square, square-1080p, 4k-square, 1440p-portrait, 1440p-square).`, @@ -919,7 +932,9 @@ export default defineCommand({ } if (holdsFilesBesideProjectConfigOrSources(destDir, [videoFlag, audioFlag])) { - console.error(c.error(`Directory already exists and is not empty: ${name}`)); + printFailureLine((show) => + c.error(`Directory already exists and is not empty: ${show(name)}`), + ); failCommand(); } @@ -933,12 +948,12 @@ export default defineCommand({ // already validates in this order. const videoPath = videoFlag ? resolve(videoFlag) : undefined; if (videoPath && !existsSync(videoPath)) { - console.error(c.error(`Video file not found: ${videoFlag}`)); + printFailureLine((show) => c.error(`Video file not found: ${show(String(videoFlag))}`)); failCommand(); } const audioPath = audioFlag ? resolve(audioFlag) : undefined; if (audioPath && !existsSync(audioPath)) { - console.error(c.error(`Audio file not found: ${audioFlag}`)); + printFailureLine((show) => c.error(`Audio file not found: ${show(String(audioFlag))}`)); failCommand(); } @@ -958,7 +973,7 @@ export default defineCommand({ videoHasAudio = result.meta.hasAudio; videoDuration = result.meta.durationSeconds; videoSize = result.meta; - console.log( + status( `Video: ${result.meta.width}x${result.meta.height}, ${result.meta.durationSeconds.toFixed(1)}s`, ); } @@ -969,7 +984,7 @@ export default defineCommand({ copyIntoProjectUnlessAlreadyThere(audioPath, resolve(destDir, basename(audioPath))); const { getMediaDurationSeconds } = await import("../whisper/transcribe.js"); videoDuration = getMediaDurationSeconds(audioPath) ?? undefined; - console.log(`Audio: ${basename(audioPath)}`); + status(`Audio: ${terminalText(basename(audioPath))}`); } // Transcribe @@ -978,18 +993,18 @@ export default defineCommand({ const { ensureWhisper, ensureModel } = await import("../whisper/manager.js"); await ensureWhisper(); await ensureModel(initialTranscriptionModel); - console.log("Transcribing..."); + status("Transcribing..."); const { transcribe: runTranscribe } = await import("../whisper/transcribe.js"); const result = await runTranscribe(sourceFilePath, destDir, { model: modelFlag, language: languageFlag, }); - console.log( - `Transcribed: ${result.wordCount} words (${result.durationSeconds.toFixed(1)}s)`, - ); + status(`Transcribed: ${result.wordCount} words (${result.durationSeconds.toFixed(1)}s)`); if (!videoDuration) videoDuration = result.durationSeconds; } catch (err) { - console.log(`Transcription skipped: ${err instanceof Error ? err.message : err}`); + status( + `Transcription skipped: ${terminalLines(err instanceof Error ? err.message : String(err))}`, + ); } } @@ -1010,19 +1025,23 @@ export default defineCommand({ args.skill, ); } catch (err) { - console.error( - c.error( - `Failed to scaffold example "${templateId}": ${err instanceof Error ? err.message : err}`, - ), + printFailureLine( + (show) => + c.error( + `Failed to scaffold example "${show(templateId)}": ${show(err instanceof Error ? err.message : String(err))}`, + ), + undefined, + "Use --example blank for offline use.", ); console.error(c.dim("Use --example blank for offline use.")); failCommand(); } await finishScaffold(destDir, templateId, tailwind); + releaseStatus(); - console.log(c.success(`Created ${c.accent(name + "/")}`)); + console.log(c.success(`Created ${c.accent(terminalText(name) + "/")}`)); for (const f of readdirSync(destDir).filter((f) => !f.startsWith("."))) { - console.log(` ${c.accent(f)}`); + console.log(` ${c.accent(terminalText(f))}`); } if (!skipSkills) { @@ -1030,9 +1049,12 @@ export default defineCommand({ } const shownName = shellArg(name); - const cdLine = shownName === null ? "go into the project folder" : `cd ${shownName}`; + const inFolder = (command: string) => + shownName === null + ? c.accent(command) + : `${c.accent(`cd ${shownName}`)} && ${c.accent(command)}`; console.log(); - console.log("Get started:"); + console.log(shownName === null ? "Get started, from the project folder:" : "Get started:"); console.log(); if (skipSkills) { console.log( @@ -1047,7 +1069,7 @@ export default defineCommand({ console.log(); console.log(` ${c.accent("2.")} Open this project with your AI coding agent:`); console.log( - ` ${c.accent(cdLine)} then start ${c.accent("Claude Code")}, ${c.accent("Cursor")}, or your preferred agent`, + ` ${shownName === null ? "From the project folder, start" : `${c.accent(`cd ${shownName}`)} then start`} ${c.accent("Claude Code")}, ${c.accent("Cursor")}, or your preferred agent`, ); console.log(); console.log(` ${c.accent("3.")} Try a starter prompt:`); @@ -1059,13 +1081,13 @@ export default defineCommand({ ); console.log(); console.log(` ${c.accent("4.")} Preview in the browser:`); - console.log(` ${c.accent(cdLine)} && ${c.accent("npm run dev")}`); + console.log(` ${inFolder("npm run dev")}`); console.log(); console.log(` ${c.accent("5.")} Check the composition:`); - console.log(` ${c.accent(cdLine)} && ${c.accent("npm run check")}`); + console.log(` ${inFolder("npm run check")}`); console.log(); console.log(` ${c.accent("6.")} Render to MP4 when ready:`); - console.log(` ${c.accent(cdLine)} && ${c.accent("npm run render")}`); + console.log(` ${inFolder("npm run render")}`); console.log(); console.log(` ${c.dim(`Full docs: ${cliSourced("https://hyperframes.heygen.com")}`)}`); return; @@ -1106,7 +1128,7 @@ export default defineCommand({ if (holdsFilesBesideProjectConfigOrSources(destDir, [videoFlag, audioFlag])) { const overwrite = await clack.confirm({ - message: `Directory ${c.accent(name)} already exists and is not empty. Overwrite?`, + message: `Directory ${c.accent(terminalText(name))} already exists and is not empty. Overwrite?`, initialValue: false, }); if (clack.isCancel(overwrite) || !overwrite) { @@ -1125,7 +1147,7 @@ export default defineCommand({ if (videoFlag) { const videoPath = resolve(videoFlag); if (!existsSync(videoPath)) { - clack.log.error(`File not found: ${videoFlag}`); + clack.log.error(`File not found: ${terminalText(videoFlag)}`); clack.cancel("Setup cancelled."); failCommand(); } @@ -1139,7 +1161,7 @@ export default defineCommand({ } else if (audioFlag) { const audioPath = resolve(audioFlag); if (!existsSync(audioPath)) { - clack.log.error(`File not found: ${audioFlag}`); + clack.log.error(`File not found: ${terminalText(audioFlag)}`); clack.cancel("Setup cancelled."); failCommand(); } @@ -1148,7 +1170,7 @@ export default defineCommand({ copyIntoProjectUnlessAlreadyThere(audioPath, resolve(destDir, basename(audioPath))); const { getMediaDurationSeconds } = await import("../whisper/transcribe.js"); videoDuration = getMediaDurationSeconds(audioPath) ?? undefined; - clack.log.info(`Audio copied to ${c.accent(basename(audioPath))}`); + clack.log.info(`Audio copied to ${c.accent(terminalText(basename(audioPath)))}`); } // 2b. Transcribe if we have a source file with audio (via flags) @@ -1173,10 +1195,10 @@ export default defineCommand({ try { const { ensureWhisper, ensureModel } = await import("../whisper/manager.js"); await ensureWhisper({ - onProgress: (msg) => spin.message(msg), + onProgress: (msg) => spin.message(terminalText(msg)), }); await ensureModel(initialTranscriptionModel, { - onProgress: (msg) => spin.message(msg), + onProgress: (msg) => spin.message(terminalText(msg)), }); spin.message("Transcribing audio..."); @@ -1184,7 +1206,7 @@ export default defineCommand({ const transcribeResult = await runTranscribe(sourceFilePath, destDir, { model: modelFlag, language: languageFlag, - onProgress: (msg) => spin.message(msg), + onProgress: (msg) => spin.message(terminalText(msg)), }); spin.stop( c.success( @@ -1192,7 +1214,11 @@ export default defineCommand({ ), ); } catch (err) { - spin.stop(c.dim(`Transcription skipped: ${err instanceof Error ? err.message : err}`)); + spin.stop( + c.dim( + `Transcription skipped: ${terminalLines(err instanceof Error ? err.message : String(err))}`, + ), + ); } } } @@ -1210,8 +1236,8 @@ export default defineCommand({ message: "Pick an example", options: allTemplates.map((t: TemplateOption) => ({ value: t.id, - label: t.label, - hint: t.source === "remote" ? `${t.hint} (download)` : t.hint, + label: terminalText(t.label), + hint: terminalText(t.source === "remote" ? `${t.hint} (download)` : t.hint), })), initialValue: defaultTemplate, }); @@ -1226,7 +1252,7 @@ export default defineCommand({ const spin = clack.spinner(); const isBundled = BUNDLED_TEMPLATES.some((t) => t.id === templateId); if (!isBundled) { - spin.start(`Downloading example ${c.accent(templateId)}...`); + spin.start(`Downloading example ${c.accent(terminalText(templateId))}...`); } try { const media: InitMediaOptions = { @@ -1244,14 +1270,14 @@ export default defineCommand({ args.skill, ); if (!isBundled) { - spin.stop(c.success(`Downloaded ${templateId}`)); + spin.stop(c.success(`Downloaded ${terminalText(templateId)}`)); } } catch (err) { if (!isBundled) { spin.stop(c.error("Download failed")); } clack.log.error( - `${err instanceof Error ? err.message : err}\n${c.dim("Use --example blank for offline use.")}`, + `${terminalLines(err instanceof Error ? err.message : String(err))}\n${c.dim("Use --example blank for offline use.")}`, ); failCommand(); } @@ -1259,7 +1285,10 @@ export default defineCommand({ await finishScaffold(destDir, templateId, tailwind); const files = readdirSync(destDir); - clack.note(files.map((f) => c.accent(f)).join("\n"), c.success(`Created ${name}/`)); + clack.note( + files.map((f) => c.accent(terminalText(f))).join("\n"), + c.success(`Created ${terminalText(name)}/`), + ); // Install the core set if it is missing; installed skills are left alone. // --skip-skills (or HYPERFRAMES_SKIP_SKILLS=1) leaves skills alone. diff --git a/packages/cli/src/commands/render.test.ts b/packages/cli/src/commands/render.test.ts index 171b7a70a8..0ece708611 100644 --- a/packages/cli/src/commands/render.test.ts +++ b/packages/cli/src/commands/render.test.ts @@ -17,6 +17,7 @@ const producerState = vi.hoisted(() => ({ _job: Record, _abortSignal?: AbortSignal, _assertRenderActive?: () => void, + _onProgress?: (job: { progress: number }, message: string) => void, ): Promise => undefined, })); @@ -146,10 +147,10 @@ vi.mock("../utils/producer.js", () => ({ job: Record, _projectDir: string, _outputPath: string, - _onProgress: unknown, + onProgress: ((job: { progress: number }, message: string) => void) | undefined, abortSignal?: AbortSignal, assertRenderActive?: () => void, - ) => producerState.executeImpl(job, abortSignal, assertRenderActive), + ) => producerState.executeImpl(job, abortSignal, assertRenderActive, onProgress), ), })), })); @@ -322,6 +323,85 @@ describe("renderLocal browser GPU config", () => { expect(renderLintContinuationHint(true)).not.toContain("Use --strict to block"); }); + // fails without the fix: a failure reported as progress was written as it arrived, over several lines. + it("writes a progress update whose text has line breaks as one line", async () => { + const written: string[] = []; + const isTTY = process.stdout.isTTY; + Object.defineProperty(process.stdout, "isTTY", { value: false, configurable: true }); + const out = vi.spyOn(process.stdout, "write").mockImplementation(((chunk: unknown) => { + written.push(String(chunk)); + return true; + }) as never); + vi.spyOn(console, "log").mockImplementation(() => {}); + vi.spyOn(console, "warn").mockImplementation(() => {}); + producerState.executeImpl = async (_job, _signal, _active, onProgress) => { + onProgress?.({ progress: 40 }, "Failed: encoder said\nno such filter\r\nexit 1"); + }; + try { + await renderLocal(PROJECT_DIR, "/tmp/out.mp4", { + fps: { num: 30, den: 1 }, + quality: "standard", + format: "mp4", + gpu: false, + browserGpuMode: "software", + hdrMode: "auto", + quiet: false, + throwOnError: true, + }); + } finally { + out.mockRestore(); + Object.defineProperty(process.stdout, "isTTY", { value: isTTY, configurable: true }); + } + const update = written.find((chunk) => chunk.includes("Failed: encoder said")); + expect(update).toContain("Failed: encoder said\\x0ano such filter\\x0d\\x0aexit 1"); + expect(update?.trimEnd()).not.toMatch(/[\r\n]/); + }); + + // fails without the fix: the check's detail and hint, the probe failure and the job's warning are printed as they arrived. + it("shows control characters in a preflight warning, a probe failure and a job warning as text", async () => { + const esc = String.fromCharCode(27); + const odd = `od${esc}[2Jd${String.fromCharCode(7)}`; + const shown = "od\\x1b[2Jd\\x07"; + const warned: string[] = []; + vi.spyOn(console, "warn").mockImplementation((...args: unknown[]) => { + warned.push(args.join(" ")); + }); + vi.spyOn(console, "log").mockImplementation(() => {}); + const outcomes = preflightState.result.outcomes as Array>; + outcomes.push({ + name: "Disk", + ok: true, + level: "warn", + detail: `low ${odd}`, + hint: `free ${odd}`, + }); + ffmpegEncoderState.error = new Error(`probe ${odd}`); + producerState.executeImpl = async (job) => { + job.outcome = "completed_with_warnings"; + job.warnings = [{ code: "late_media", message: `late ${odd}\nsecond line` }]; + }; + try { + await renderLocal(PROJECT_DIR, "/tmp/out.mp4", { + fps: { num: 30, den: 1 }, + quality: "standard", + format: "mp4", + gpu: false, + browserGpuMode: "software", + hdrMode: "auto", + quiet: false, + throwOnError: true, + }); + } finally { + outcomes.pop(); + } + const said = warned.join("\n").replace(new RegExp(`${esc}\\[[0-9;]*m`, "g"), ""); + expect(said).toContain(`Disk: low ${shown}`); + expect(said).toContain(`free ${shown}`); + expect(said).toContain(`Unable to probe H.264 encoder capabilities: probe ${shown}`); + expect(said).toContain(`[late_media] late ${shown}\nsecond line`); + expect(said).not.toContain(esc); + }); + it("points non-strict renders to --strict for lint errors", () => { expect(renderLintContinuationHint(false)).toContain("Use --strict to block errors"); }); diff --git a/packages/cli/src/commands/render.ts b/packages/cli/src/commands/render.ts index a7805813eb..23f0c127f1 100644 --- a/packages/cli/src/commands/render.ts +++ b/packages/cli/src/commands/render.ts @@ -166,6 +166,7 @@ import { checkOutputResolutionCompatibility, suggestMatchingPreset, fpsToNumber, + terminalLines, terminalText, type CanvasResolution, type OutputResolutionIssueKind, @@ -785,7 +786,7 @@ function ensureDockerImage(version: string, platform: string, quiet: boolean): s return tag; } - if (!quiet) console.log(c.dim(` Building Docker image: ${tag} (${platform})...`)); + if (!quiet) console.log(c.dim(` Building Docker image: ${tag} (${terminalText(platform)})...`)); const dockerfilePath = resolveDockerfilePath(); @@ -878,7 +879,9 @@ function resolveDockerHostPlatform(options: RenderOptions): string { async function registerRenderOutputOrWarn(projectDir: string, outputPath: string): Promise { await registerRenderOutput(projectDir, outputPath).catch((error: unknown) => - console.warn(`Render output was not registered: ${normalizeErrorMessage(error)}`), + console.warn( + `Render output was not registered: ${terminalLines(normalizeErrorMessage(error))}`, + ), ); } @@ -1121,8 +1124,8 @@ async function executeLocalRender( if (!options.quiet) { for (const outcome of preflight.outcomes) { if (outcome.level === "warn") { - console.warn(c.warn(` ${outcome.name}: ${outcome.detail}`)); - if (outcome.hint) console.warn(c.dim(` ${outcome.hint}`)); + console.warn(c.warn(` ${outcome.name}: ${terminalLines(String(outcome.detail))}`)); + if (outcome.hint) console.warn(c.dim(` ${terminalLines(outcome.hint)}`)); } } } @@ -1167,7 +1170,9 @@ async function executeLocalRender( // authoritative FFmpeg error instead of failing here with a bare stack. if (!options.quiet) { const detail = error instanceof Error ? error.message : String(error); - console.warn(c.warn(` Unable to probe H.264 encoder capabilities: ${detail}`)); + console.warn( + c.warn(` Unable to probe H.264 encoder capabilities: ${terminalLines(detail)}`), + ); } } if (encoderMode === "gpu" && isHls) { @@ -1346,7 +1351,7 @@ async function executeLocalRender( const cpuUsage = cpu.stop(); if (job.outcome === "completed_with_warnings") { for (const warning of job.warnings) { - console.warn(c.warn(` [${warning.code}] ${warning.message}`)); + console.warn(c.warn(` [${warning.code}] ${terminalLines(warning.message)}`)); } } const audioLowered = audioLoweredWarning(job.audioLoweredDb); diff --git a/packages/cli/src/commands/render/present.test.ts b/packages/cli/src/commands/render/present.test.ts index 4018beafd4..2953063cd9 100644 --- a/packages/cli/src/commands/render/present.test.ts +++ b/packages/cli/src/commands/render/present.test.ts @@ -43,6 +43,23 @@ describe("presentRenderPlan", () => { expect(await settingsLine(args)).toContain(`30fps · ${label} · 2 workers`); }); + // fails without the fix: the bitrate and the refused --skill value are repeated as they were typed. + it("prints a bitrate and a refused skill name with control characters as visible escapes", async () => { + const esc = String.fromCharCode(27); + const odd = `od${esc}[2Jd${String.fromCharCode(7)}`; + const refused: string[] = []; + vi.spyOn(process.stderr, "write").mockImplementation((chunk: unknown) => { + refused.push(String(chunk)); + return true; + }); + + const line = await settingsLine({ "video-bitrate": `10M${odd}`, skill: `Bad ${odd}` }); + + expect(line).toContain("looks (10Mod\\x1b[2Jd\\x07)"); + expect(refused.join("")).toContain('ignoring --skill="Bad od\\x1b[2Jd\\x07"'); + expect(printed.join("\n") + refused.join("")).not.toContain(odd); + }); + // Windows refuses control characters in folder names. it.skipIf(process.platform === "win32")( "prints a folder name with control characters as visible escapes", diff --git a/packages/cli/src/commands/render/present.ts b/packages/cli/src/commands/render/present.ts index 471c191c31..59ff44d700 100644 --- a/packages/cli/src/commands/render/present.ts +++ b/packages/cli/src/commands/render/present.ts @@ -16,7 +16,7 @@ export async function presentRenderPlan(plan: RenderPlan): Promise { async function presentRenderWarnings(plan: RenderPlan): Promise { if (plan.invalidAuthoringSkill) { process.stderr.write( - `hyperframes: ignoring --skill="${plan.invalidAuthoringSkill}" — not a valid slug ` + + `hyperframes: ignoring --skill="${terminalText(plan.invalidAuthoringSkill)}" — not a valid slug ` + "(lowercase letters/digits/hyphens, max 64); this render will be unattributed.\n", ); } @@ -53,7 +53,7 @@ function presentRenderSummary(plan: RenderPlan): void { function qualityLabel(plan: Pick): string { if (plan.crf !== undefined) return `${plan.qualityPreset} (CRF ${plan.crf})`; - if (plan.videoBitrate) return `${plan.qualityPreset} (${plan.videoBitrate})`; + if (plan.videoBitrate) return `${plan.qualityPreset} (${terminalText(plan.videoBitrate)})`; return plan.qualityPreset; } diff --git a/packages/cli/src/commands/render/renderSlot.test.ts b/packages/cli/src/commands/render/renderSlot.test.ts new file mode 100644 index 0000000000..63870bde09 --- /dev/null +++ b/packages/cli/src/commands/render/renderSlot.test.ts @@ -0,0 +1,41 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import type { RenderLockOptions } from "../../utils/renderLock.js"; +import type { RenderPlan } from "./plan.js"; + +const ESC = String.fromCharCode(27); +const ODD = `od${ESC}[2Jd\x07`; +const SHOWN = "od\\x1b[2Jd\\x07"; + +vi.mock("../../utils/renderLock.js", async (importOriginal) => ({ + ...(await importOriginal()), + acquireRenderLock: async (options: RenderLockOptions) => { + options.onWait?.( + { pid: 7, project: `/films/${ODD}`, startedAt: Date.now() } as never, + `/locks/${ODD}/render.lock`, + ); + return () => {}; + }, +})); + +const { acquireRenderSlot } = await import("./renderSlot.js"); + +afterEach(() => { + vi.restoreAllMocks(); +}); + +describe("waiting for the render slot", () => { + // fails without the fix: the other render's project and the lock's path are printed as they were read. + it("shows control characters in the holder and the lock path as text", async () => { + const said: string[] = []; + vi.spyOn(console, "error").mockImplementation((...args: unknown[]) => { + said.push(args.join(" ")); + }); + const plan = { project: { dir: "/films/mine" }, waitForRenderSlot: true } as RenderPlan; + await acquireRenderSlot(plan); + const line = said.join("\n").replace(new RegExp(`${ESC}\\[[0-9;]*m`, "g"), ""); + expect(line).toContain(`pid 7, project /films/${SHOWN}, running 0s`); + expect(line).toContain(`Lock: /locks/${SHOWN}/render.lock`); + expect(line).not.toContain(ESC); + expect(line).not.toContain("\x07"); + }); +}); diff --git a/packages/cli/src/commands/render/renderSlot.ts b/packages/cli/src/commands/render/renderSlot.ts index cce7bb3110..f8922cbdf8 100644 --- a/packages/cli/src/commands/render/renderSlot.ts +++ b/packages/cli/src/commands/render/renderSlot.ts @@ -1,3 +1,4 @@ +import { terminalText } from "@hyperframes/core"; import { c } from "../../ui/colors.js"; import { errorBox } from "../../ui/format.js"; import { failCommand } from "../../utils/commandResult.js"; @@ -28,9 +29,9 @@ export async function acquireRenderSlot( onWait: (holder, path) => console.error( c.warn( - ` Waiting for another render to finish (${describeRenderLockHolder(holder, Date.now())}). ` + + ` Waiting for another render to finish (${terminalText(describeRenderLockHolder(holder, Date.now()))}). ` + "Renders run one at a time per user account; pass --no-wait to stop instead.", - ) + c.dim(`\n Lock: ${path}`), + ) + c.dim(`\n Lock: ${terminalText(path)}`), ), ...lock, }); diff --git a/packages/cli/src/commands/skills.output.test.ts b/packages/cli/src/commands/skills.output.test.ts new file mode 100644 index 0000000000..e2c6b6a569 --- /dev/null +++ b/packages/cli/src/commands/skills.output.test.ts @@ -0,0 +1,172 @@ +import { EventEmitter } from "node:events"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { consumeCommandResult } from "../utils/commandResult.js"; + +const ESC = String.fromCharCode(27); +const ODD = `od${ESC}[2Jd\x07`; +const SHOWN = "od\\x1b[2Jd\\x07"; + +const fake = vi.hoisted(() => ({ + lines: [] as string[], + missingTool: "" as "" | "git" | "npx", + copyHint: "", + checkSkills: vi.fn(), + presentSkills: vi.fn(), + foreignSkillNames: vi.fn(), +})); + +vi.mock("node:child_process", () => ({ + execFile: vi.fn(), + execFileSync: vi.fn((command: string, args: ReadonlyArray) => { + const tool = command === "git" ? "git" : "npx"; + if (fake.missingTool === tool && args.includes("--version")) throw new Error("ENOENT"); + return Buffer.from("11.0.0"); + }), + spawn: vi.fn(() => { + const child = new EventEmitter(); + setImmediate(() => child.emit("close", 0, null)); + return child; + }), +})); +vi.mock("@clack/prompts", () => ({ + log: { + error: (message: string) => fake.lines.push(message), + warn: (message: string) => fake.lines.push(message), + }, +})); +vi.mock("../telemetry/events.js", () => ({ trackSkillsInstallSkipped: vi.fn() })); +vi.mock("../utils/appleStubs.js", () => ({ runsWithoutInstallPrompt: () => true })); +vi.mock("../utils/projectCopyHint.js", () => ({ projectCopyHint: () => fake.copyHint })); +vi.mock("../utils/skillsManifest.js", async (importOriginal) => ({ + ...(await importOriginal()), + checkSkills: fake.checkSkills, + presentSkills: fake.presentSkills, + foreignSkillNames: fake.foreignSkillNames, + hyperframesSkillNames: () => [], +})); +vi.mock("../utils/skillsMirror.js", () => ({ + mirrorGlobalSkills: () => ({ source: null, mirrored: [], skipped: [] }), +})); +vi.mock("../utils/skillsUpdateCheck.js", () => ({ invalidateSkillsCache: vi.fn() })); + +const { default: skillsCommand, updateSkills } = await import("./skills.js"); + +const printed = (): string => + fake.lines.join("\n").replace(new RegExp(`${ESC}\\[[0-9;]*m`, "g"), ""); + +function expectNoControlCharacters(): void { + expect(printed()).not.toContain(ESC); + expect(printed()).not.toContain("\x07"); +} + +function check(skills: Array<{ name: string; status: string }>): Record { + return { + location: `/skills/${ODD}`, + agent: `agent-${ODD}`, + scope: "global", + updateAvailable: true, + summary: { current: 0, outdated: 1, missing: 1, coreMissing: 0, removed: 0 }, + skills, + lockMissing: false, + }; +} + +const ODD_MANIFEST = [ + { name: "hyperframes", status: "outdated" }, + { name: `late-${ODD}`, status: "outdated" }, + { name: `more-${ODD}`, status: "missing" }, +]; + +function runSub(name: "check" | "update", positionals: string[] = []): Promise { + const subs = skillsCommand.subCommands as unknown as Record; + return Promise.resolve( + subs[name]!.run?.({ args: { _: positionals }, rawArgs: positionals, cmd: subs[name] } as never), + ); +} + +const runBare = (): Promise => + Promise.resolve(skillsCommand.run?.({ args: {}, rawArgs: [], cmd: skillsCommand } as never)); + +beforeEach(() => { + fake.lines.length = 0; + fake.missingTool = ""; + fake.copyHint = ""; + fake.checkSkills.mockReset().mockResolvedValue(check(ODD_MANIFEST)); + fake.presentSkills.mockReset().mockImplementation((names: readonly string[]) => [...names]); + fake.foreignSkillNames.mockReset().mockReturnValue([]); + for (const method of ["log", "error", "warn"] as const) + vi.spyOn(console, method).mockImplementation((...args: unknown[]) => { + fake.lines.push(args.join(" ")); + }); +}); + +afterEach(() => { + consumeCommandResult(); + vi.restoreAllMocks(); +}); + +describe("skills output for people", () => { + // fails without the fix: the folder, the agent and each listed name are printed as they arrived. + it("check shows control characters in the location and the listed names as text", async () => { + await runSub("check"); + expect(printed()).toContain(`/skills/${SHOWN} (agent-${SHOWN})`); + expect(printed()).toContain(`↑ late-${SHOWN}`); + expect(printed()).toContain(`◦ more-${SHOWN}`); + expectNoControlCharacters(); + }); + + // fails without the fix: the names the list held are repeated as they arrived. + it("update shows control characters in a skipped name and the installed list as text", async () => { + await runSub("update"); + expect(printed()).toContain(`Skipping unexpected skill name(s): late-${SHOWN}`); + expect(printed()).toContain(`Installed/updated 2 skill(s): hyperframes, late-${SHOWN}`); + expectNoControlCharacters(); + }); + + // fails without the fix: the failure line repeats the names the list held. + it("update shows control characters in a failure as text", async () => { + await runSub("update", ["nope"]); + expect(printed()).toContain(`Update failed: Unknown skill(s): nope. Available: `); + expect(printed()).toContain(`late-${SHOWN}`); + expect(consumeCommandResult().exitCode).toBe(1); + expectNoControlCharacters(); + }); + + // fails without the fix: the names still absent are repeated as they arrived. + it("a bare run shows control characters in the names still missing as text", async () => { + fake.presentSkills.mockReturnValue([]); + await runBare(); + expect(printed()).toContain(`Skill(s) still missing after install: hyperframes, late-${SHOWN}`); + expectNoControlCharacters(); + }); + + // fails without the fix: the asked-for name and the list's names are repeated as they arrived. + it("shows control characters in an unknown name as text", async () => { + await updateSkills({ requested: [`ask-${ODD}`] }); + expect(printed()).toContain(`Unknown skill(s): ask-${SHOWN}. Available: `); + expectNoControlCharacters(); + }); + + // fails without the fix: the other publisher's name and the names to install are repeated as they arrived. + it("shows control characters in the lines of a run that cannot reach the list as text", async () => { + fake.checkSkills.mockRejectedValue(new Error("offline")); + fake.foreignSkillNames.mockReturnValue([`theirs-${ODD}`]); + fake.presentSkills.mockReturnValue([]); + await updateSkills({ requested: [`theirs-${ODD}`, `mine-${ODD}`] }); + expect(printed()).toContain(`Skill(s) owned by another publisher: theirs-${SHOWN}.`); + expect(printed()).toContain(`attempting a blind install of: mine-${SHOWN}`); + expectNoControlCharacters(); + }); + + // fails without the fix: the path of the unused copy is printed as it is on disk. + it.each([ + ["git", "Skipping AI coding skills: git not available."], + ["npx", "npx not found. Install Node.js and retry."], + ] as const)("shows control characters in the unused %s copy as text", async (tool, line) => { + fake.missingTool = tool; + fake.copyHint = ` A copy at ./${ODD}/${tool} was not used.`; + await runBare(); + expect(printed()).toContain(`${line} A copy at ./${SHOWN}/${tool} was not used.`); + expectNoControlCharacters(); + }); +}); diff --git a/packages/cli/src/commands/skills.ts b/packages/cli/src/commands/skills.ts index c9f365bbe1..788f2f2468 100644 --- a/packages/cli/src/commands/skills.ts +++ b/packages/cli/src/commands/skills.ts @@ -1,5 +1,6 @@ import { runsWithoutInstallPrompt } from "../utils/appleStubs.js"; import { setCommandExitCode, CliResultSignal } from "../utils/commandResult.js"; +import { terminalLines, terminalText } from "@hyperframes/core"; import { defineCommand } from "../utils/defineCommand.js"; import { execFileSync, spawn } from "node:child_process"; import { homedir, tmpdir } from "node:os"; @@ -217,7 +218,7 @@ const SKILLS_TOOLING: ReadonlyArray<{ reason: "npx_missing", report: () => clack.log.error( - c.error(`npx not found. Install Node.js and retry.${projectCopyHint("npx")}`), + c.error(terminalText(`npx not found. Install Node.js and retry.${projectCopyHint("npx")}`)), ), }, { @@ -228,7 +229,11 @@ const SKILLS_TOOLING: ReadonlyArray<{ // Skip cleanly rather than letting the upstream clone dump a noisy // multi-line `spawn git ENOENT` / "Installation failed" abort. report: () => - console.log(c.dim(`Skipping AI coding skills: git not available.${projectCopyHint("git")}`)), + console.log( + c.dim( + terminalText(`Skipping AI coding skills: git not available.${projectCopyHint("git")}`), + ), + ), }, ]; @@ -254,7 +259,9 @@ function sanitizeSelection(selection: SkillSelection): SkillSelection | null { if (selection === "*") return selection; const rejected = selection.filter((n) => !PLAIN_SKILL_NAME.test(n)); if (rejected.length) { - clack.log.warn(c.warn(`Skipping unexpected skill name(s): ${rejected.join(", ")}`)); + clack.log.warn( + c.warn(terminalText(`Skipping unexpected skill name(s): ${rejected.join(", ")}`)), + ); } const safe = selection.filter((n) => PLAIN_SKILL_NAME.test(n)); return safe.length > 0 ? safe : null; @@ -414,7 +421,7 @@ export async function updateSkills( `Unknown skill(s): ${unknown.join(", ")}. ` + `Available: ${[...manifestNames].sort().join(", ")}`; if (strict) throw new Error(message); - clack.log.warn(c.warn(message)); + clack.log.warn(c.warn(terminalText(message))); } const targets = manifestSkills.filter( @@ -467,7 +474,7 @@ function verifyInstalled(names: readonly string[], opts: { strict: boolean; cwd? if (absent.length === 0) return; const message = `Skill(s) still missing after install: ${absent.join(", ")}`; if (opts.strict) throw new Error(message); - clack.log.warn(c.warn(message)); + clack.log.warn(c.warn(terminalText(message))); } /** @@ -506,7 +513,7 @@ async function updateSkillsOffline( if (unknown.length > 0) { const message = `Skill(s) owned by another publisher: ${unknown.join(", ")}. Leaving them unchanged.`; if (opts.strict) throw new Error(message); - clack.log.warn(c.warn(message)); + clack.log.warn(c.warn(terminalText(message))); } const targets = [...new Set([...requested, ...FALLBACK_CORE_SKILLS])].filter( (name) => !foreign.has(name), @@ -518,7 +525,7 @@ async function updateSkillsOffline( c.dim( absent.length === 0 ? "Skills freshness check unavailable (offline?) — installed skills found, continuing without a refresh." - : `Skills freshness check unavailable (offline?) — attempting a blind install of: ${absent.join(", ")}`, + : `Skills freshness check unavailable (offline?) — attempting a blind install of: ${terminalText(absent.join(", "))}`, ), ); @@ -553,7 +560,7 @@ function printSkillSection( if (!items.length) return; console.log(); console.log(` ${color(title)}`); - for (const s of items) console.log(` ${color(`${mark} ${s.name}`)}`); + for (const s of items) console.log(` ${color(`${mark} ${terminalText(s.name)}`)}`); } function renderCheck(result: SkillsCheckResult): void { @@ -569,7 +576,9 @@ function renderCheck(result: SkillsCheckResult): void { return; } - console.log(` ${c.bold("Location")} ${c.dim(result.location)} ${c.dim(`(${result.agent})`)}`); + console.log( + ` ${c.bold("Location")} ${c.dim(terminalText(result.location))} ${c.dim(`(${terminalText(String(result.agent))})`)}`, + ); console.log(); const onDemandMissing = summary.missing - summary.coreMissing; @@ -702,7 +711,7 @@ function reportUpdate( if (result.installed.length > 0) { console.log( c.success( - `Installed/updated ${result.installed.length} skill(s): ${result.installed.join(", ")}`, + `Installed/updated ${result.installed.length} skill(s): ${terminalText(result.installed.join(", "))}`, ), ); } else if (result.presenceOnly) { @@ -715,7 +724,7 @@ function reportUpdate( // The named skills are the caller's actual question ("is my skill ready?") // — answer it explicitly, whatever the install had to do. const ready = requested.filter((name) => !result.retired.includes(name)); - if (ready.length) console.log(c.success(`◇ Ready: ${ready.join(", ")}`)); + if (ready.length) console.log(c.success(`◇ Ready: ${terminalText(ready.join(", "))}`)); } /** @@ -730,7 +739,7 @@ function reportUpdateFailure(message: string, json: boolean): void { ); return; } - clack.log.error(c.error(message)); + clack.log.error(c.error(terminalLines(message))); } const updateCommand = defineCommand({ diff --git a/packages/cli/src/ui/progress.test.ts b/packages/cli/src/ui/progress.test.ts index 220efac25d..7b2869c007 100644 --- a/packages/cli/src/ui/progress.test.ts +++ b/packages/cli/src/ui/progress.test.ts @@ -32,6 +32,23 @@ describe("renderProgress", () => { }); }); +describe("renderProgress with a stage that is not one line", () => { + // fails without the fix: the stage was written as given, so one update took several lines. + it.each([false, true])("keeps the update on one line (TTY: %s)", (isTTY) => { + let output = ""; + Object.defineProperty(process.stdout, "isTTY", { value: isTTY, configurable: true }); + process.stdout.write = ((chunk: string | Uint8Array) => { + output += String(chunk); + return true; + }) as typeof process.stdout.write; + + renderProgress(42, `Failed: a\nb${String.fromCharCode(27)}[2Kc`); + + expect(output).toContain("Failed: a\\x0ab\\x1b[2Kc"); + expect(output.replace(/^\r/, "").trimEnd()).not.toMatch(/[\r\n]/); + }); +}); + describe("renderMachineProgress", () => { const capture = (isTTY: boolean) => { let output = ""; diff --git a/packages/cli/src/ui/progress.ts b/packages/cli/src/ui/progress.ts index 9a2791f5c2..86ecb3e493 100644 --- a/packages/cli/src/ui/progress.ts +++ b/packages/cli/src/ui/progress.ts @@ -1,3 +1,4 @@ +import { terminalText } from "@hyperframes/core"; import { c } from "./colors.js"; import type { RenderJob } from "@hyperframes/producer"; @@ -9,7 +10,7 @@ export function renderProgress(percent: number, stage: string, row?: number): vo const empty = width - filled; const bar = c.progress("\u2588".repeat(filled)) + c.dim("\u2591".repeat(empty)); - const line = ` ${bar} ${c.bold(String(Math.round(percent)) + "%")} ${c.dim(stage)}`; + const line = ` ${bar} ${c.bold(String(Math.round(percent)) + "%")} ${c.dim(terminalText(stage))}`; if (row !== undefined && stdout.isTTY) { stdout.write(`\x1b[${row};1H\x1b[2K${line}`); diff --git a/packages/cli/src/utils/jsonError.test.ts b/packages/cli/src/utils/jsonError.test.ts index f0ffbed521..36e6a3790f 100644 --- a/packages/cli/src/utils/jsonError.test.ts +++ b/packages/cli/src/utils/jsonError.test.ts @@ -152,11 +152,13 @@ describe("printFailureLine", () => { try { const { printFailureLine, watchOutput } = await import("./jsonError.js"); const output = watchOutput(); - printFailureLine((show) => `File not found: ${show("mis\u0007sing.wav")}`); - expect(shown).toEqual(["File not found: mis\\x07sing.wav"]); - expect(output.stderrText()).toBe("File not found: mis\u0007sing.wav"); - console.error("later a\u0007b"); - expect(output.stderrText()).toContain("later a\u0007b"); + printFailureLine((show) => `File not found: ${show("mis\u0007s\ning.wav ")}`); + expect(shown).toEqual(["File not found: mis\\x07s\ning.wav "]); + expect(output.stderrText()).toBe("File not found: mis\\x07s ing.wav"); + const failed = new CliRuntimeError("Command failed", { presented: true }); + expect(jsonErrorBody(failed, runtime, output.stderrText()).message).toBe( + "File not found: mis\u0007s\ning.wav ", + ); } finally { process.stdout.write = saved.out; process.stderr.write = saved.err; diff --git a/packages/cli/src/utils/jsonError.ts b/packages/cli/src/utils/jsonError.ts index 6b356d71e3..916e00f333 100644 --- a/packages/cli/src/utils/jsonError.ts +++ b/packages/cli/src/utils/jsonError.ts @@ -48,17 +48,33 @@ export function writeJsonFailure(body: CliErrorBody): void { * run that printed nothing can still answer with an envelope that says why. Bun's console * writes past process.stdout.write, so the console methods are watched too. */ -let reported: { message: string; hint?: string } | undefined; +let reported: { message: string; hint?: string; exact?: boolean } | undefined; let noticeDepth = 0; -let asGiven: string | undefined; +let jsonRun = false; +const heldStatus: string[] = []; -export function printFailureLine(line: (show: (text: string) => string) => string): void { - asGiven = line((text) => text); - try { - console.error(line(terminalLines)); - } finally { - asGiven = undefined; - } +export function printFailureLine( + line: (show: (text: string) => string) => string, + answer?: string, + hint?: string, +): void { + console.error(line(terminalLines)); + const given: string[] = []; + const shape = tidy(line((text) => `\uE000${given.push(text) - 1}\uE001`)); + const message = shape.replace(/\uE000(\d+)\uE001/g, (_, at) => given[Number(at)] ?? ""); + const earlier = reported?.exact ? `${reported.message} ` : ""; + reported = { message: earlier + (answer ?? message), hint, exact: true }; +} + +export const isJsonRun = (): boolean => jsonRun; + +export function status(text: string): void { + if (jsonRun) heldStatus.push(text); + else console.log(text); +} + +export function releaseStatus(): void { + for (const text of heldStatus.splice(0)) console.log(text); } /** The failure a command reported to the person (errorBox); the envelope's message when it has none. */ @@ -90,6 +106,7 @@ export function failureMessage(error: unknown): string { } export function watchOutput(): { wroteStdout: () => boolean; stderrText: () => string } { + jsonRun = true; let wrote = false; let stderr = ""; let inConsole = false; @@ -117,7 +134,7 @@ export function watchOutput(): { wroteStdout: () => boolean; stderrText: () => s for (const name of ["error", "warn"] as const) { const original = console[name].bind(console); console[name] = (...args: unknown[]) => { - keep(`${asGiven ?? format(...args)}\n`); + keep(`${format(...args)}\n`); inConsole = true; try { original(...args); @@ -128,16 +145,18 @@ export function watchOutput(): { wroteStdout: () => boolean; stderrText: () => s } return { wroteStdout: () => wrote, - stderrText: () => - stripVTControlCharacters(stderr) - .split("\n") - .map((line) => line.replace(/^[\s✗│◇◆]+/u, "").trim()) - .filter(Boolean) - .join(" ") - .slice(-1000), + stderrText: () => tidy(stderr).slice(-1000), }; } +function tidy(text: string): string { + return stripVTControlCharacters(text) + .split("\n") + .map((line) => line.replace(/^[\s✗│◇◆]+/u, "").trim()) + .filter(Boolean) + .join(" "); +} + function withHint(body: CliErrorBody, hint: string | undefined): CliErrorBody { return hint ? { ...body, hint: stripVTControlCharacters(hint) } : body; } @@ -171,6 +190,12 @@ export function jsonErrorBody( return { code, message: failureMessage(error.cause) }; } if (reported) - return withHint({ code, message: stripVTControlCharacters(reported.message) }, reported.hint); + return withHint( + { + code, + message: reported.exact ? reported.message : stripVTControlCharacters(reported.message), + }, + reported.hint, + ); return { code, message: stderrText || "Command failed" }; } diff --git a/packages/cli/src/utils/render-success-state.test.ts b/packages/cli/src/utils/render-success-state.test.ts index db645ddea6..a20938ab58 100644 --- a/packages/cli/src/utils/render-success-state.test.ts +++ b/packages/cli/src/utils/render-success-state.test.ts @@ -109,6 +109,22 @@ describe("runPostRenderStep", () => { expect(process.exitCode).toBe(0); }); + // fails without the fix: the step's failure message is handed to the printer as it was thrown. + it("reports a failure message with control characters as visible escapes", () => { + const sink = vi.fn(); + const esc = String.fromCharCode(27); + runPostRenderStep( + "record", + () => { + throw new Error(`no such file /out/od${esc}[2Jd${String.fromCharCode(7)}.mp4\nsecond line`); + }, + sink, + ); + expect(sink.mock.calls[0]?.[0]).toContain( + "(render already succeeded): no such file /out/od\\x1b[2Jd\\x07.mp4\nsecond line", + ); + }); + it("stringifies a non-Error throw value", () => { const sink = vi.fn(); runPostRenderStep( diff --git a/packages/cli/src/utils/render-success-state.ts b/packages/cli/src/utils/render-success-state.ts index 1e0bce5ec5..cd97b7d6d8 100644 --- a/packages/cli/src/utils/render-success-state.ts +++ b/packages/cli/src/utils/render-success-state.ts @@ -22,6 +22,7 @@ * still exited 1 after the terminal "artifact validated" checkpoint. */ +import { terminalLines } from "@hyperframes/core"; import { sanitizeSuccessfulExitCode } from "./commandResult.js"; let renderSucceeded = false; @@ -100,7 +101,9 @@ export async function runPostRenderStepAsync( function reportPostRenderStepFailure(label: string, err: unknown, sink: PostRenderErrorSink): void { const message = err instanceof Error ? err.message : String(err); - sink(` [hyperframes] Post-render step '${label}' failed (render already succeeded): ${message}`); + sink( + ` [hyperframes] Post-render step '${label}' failed (render already succeeded): ${terminalLines(message)}`, + ); // The failing step (or something it triggered) may have set a non-zero // exitCode. The render succeeded, so ask the root CLI owner to clear it. if (isRenderSucceeded()) sanitizeSuccessfulExitCode(); diff --git a/packages/cli/src/utils/shellArg.test.ts b/packages/cli/src/utils/shellArg.test.ts index 6634dfece7..f479a13cd2 100644 --- a/packages/cli/src/utils/shellArg.test.ts +++ b/packages/cli/src/utils/shellArg.test.ts @@ -84,6 +84,20 @@ describe("shellArg", () => { expect(shellArg("films/@scope", "win32")).toBe("films/@scope"); }); + // fails without the fix: the word was printed with the character inside its quotes. + it.each(["darwin", "linux", "win32"] as const)( + "prints nothing on %s for a name with a character a terminal does not show", + (platform) => { + for (const name of [ + "a\nb", + "a\tb", + `a${String.fromCharCode(7)}b`, + `a${String.fromCharCode(27)}[2Jb`, + ]) + expect(shellArg(name, platform), JSON.stringify(name)).toBeNull(); + }, + ); + 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(); }); diff --git a/packages/cli/src/utils/shellArg.ts b/packages/cli/src/utils/shellArg.ts index 62ed26745e..364fe27762 100644 --- a/packages/cli/src/utils/shellArg.ts +++ b/packages/cli/src/utils/shellArg.ts @@ -1,3 +1,5 @@ +import { terminalText } from "@hyperframes/core"; + const PLAIN = /^[\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 = /["$`\\!]/; @@ -5,11 +7,12 @@ 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 pasteable command; on Windows literal in PowerShell, cmd.exe and Git Bash alike, or null. */ +/** `text` as one word of a pasteable command, or null when no word a terminal shows would be typed back as `text`; on Windows literal in PowerShell, cmd.exe and Git Bash alike. */ export function shellArg( text: string, platform: NodeJS.Platform = process.platform, ): string | null { + if (/\p{Cc}/u.test(text) || terminalText(text) !== text) return null; if (platform === "win32") return windowsShellArg(text); if (PLAIN.test(text)) return text; if (!SPECIAL_IN_DOUBLE_QUOTES.test(text)) return `"${text}"`;