diff --git a/packages/cli/src/commands/beats.test.ts b/packages/cli/src/commands/beats.test.ts index 1ad9504548..cc6237fa74 100644 --- a/packages/cli/src/commands/beats.test.ts +++ b/packages/cli/src/commands/beats.test.ts @@ -346,3 +346,34 @@ describe.skipIf(!canDecode)("beats source discovery", () => { expectMusicFile("bed.wav"); }); }); + +// fails without the fix: the track name from index.html reached the terminal with its control characters live. +describe.skipIf(!canDecode || process.platform === "win32")("beats on an oddly named track", () => { + it("prints the track's control characters as visible escapes while it works", async () => { + const dir = project("odd-track", 120); + writeFileSync(join(dir, "be\u001b[2Jd.wav"), readFileSync(join(dir, "assets", "song.wav"))); + writeFileSync( + join(dir, "index.html"), + `
`, + ); + const { exitCode, out } = await runBeats(dir, false); + expect(exitCode).toBe(0); + expect(out).toContain("Analyzing be\\x1b[2Jd.wav…"); + expect(out).toContain("beats/be\\x1b[2Jd.wav.json"); + expect(out).not.toContain("be\u001b[2Jd"); + }); +}); + +// fails without the fix: the music src from index.html reached the terminal with its control characters live. +it("prints a missing track's control characters as visible escapes", async () => { + const dir = join(root, "odd-src"); + mkdirSync(dir, { recursive: true }); + writeFileSync( + join(dir, "index.html"), + `
`, + ); + const { exitCode, out } = await runBeats(dir, false); + expect(exitCode).not.toBe(0); + expect(out).toContain("Audio file not found: assets/so\\x1b[2Jng.wav"); + expect(out).not.toContain("so\u001b[2Jng"); +}); diff --git a/packages/cli/src/commands/beats.ts b/packages/cli/src/commands/beats.ts index 50f6d2b96c..0831b0d7ac 100644 --- a/packages/cli/src/commands/beats.ts +++ b/packages/cli/src/commands/beats.ts @@ -12,7 +12,7 @@ import { } from "@hyperframes/core/beats"; import { parseHTMLContent } from "@hyperframes/core/compiler"; import { walkCompositionDescendants } from "@hyperframes/parsers"; -import { isSafePath, resolveWithinProject } from "@hyperframes/core"; +import { isSafePath, resolveWithinProject, terminalLines, terminalText } from "@hyperframes/core"; import type { Example } from "./_examples.js"; import { resolveProject, type ProjectDir } from "../utils/project.js"; import type { AudioSignal } from "@hyperframes/core/audio-analysis"; @@ -26,7 +26,7 @@ export const examples: Example[] = [ ]; function fail(message: string): never { - console.error(c.error(message)); + console.error(c.error(terminalLines(message))); failCommand(); } @@ -92,7 +92,7 @@ function report(file: string, result: MusicBeatAnalysis, json: boolean): void { } console.log( c.success( - `✓ Wrote ${result.beatTimes.length} beats → ${file} (bpm ${result.bpm ?? "?"}, ${result.bpmConfidence})`, + `✓ Wrote ${result.beatTimes.length} beats → ${terminalText(file)} (bpm ${result.bpm ?? "?"}, ${result.bpmConfidence})`, ), ); } @@ -101,7 +101,7 @@ function answerNoBeats(rel: string, json: boolean): void { if (json) { console.log(JSON.stringify({ ok: true, track: rel, file: null, count: 0, bpm: null }, null, 2)); } else { - console.log(c.dim(`No beats in ${rel}; nothing written.`)); + console.log(c.dim(`No beats in ${terminalText(rel)}; nothing written.`)); } } @@ -124,12 +124,12 @@ async function analyzeFile(audioPath: string, json: boolean): Promise { return; } if (result.beatTimes.length === 0) { - console.log(c.dim(`No beats in ${audioPath}.`)); + console.log(c.dim(`No beats in ${terminalText(audioPath)}.`)); return; } console.log( c.success( - `✓ ${result.beatTimes.length} beats in ${audioPath} (bpm ${result.bpm ?? "?"}, ${result.bpmConfidence})`, + `✓ ${result.beatTimes.length} beats in ${terminalText(audioPath)} (bpm ${result.bpm ?? "?"}, ${result.bpmConfidence})`, ), ); } @@ -161,7 +161,7 @@ export default defineCommand({ const target = resolveMusicTarget(project); if (!target) return answerNoTrack(Boolean(args.json)); const { rel, audioPath } = target; - if (!args.json) console.log(c.dim(`Analyzing ${rel}…`)); + if (!args.json) console.log(c.dim(`Analyzing ${terminalText(rel)}…`)); const result = await analyzeMusicFromSignal(await decode(audioPath)); // The Studio ignores a 0-beat file (treats it as a stale seed), so don't write one. diff --git a/packages/cli/src/commands/history.test.ts b/packages/cli/src/commands/history.test.ts index e12e087668..f5d8e11e3b 100644 --- a/packages/cli/src/commands/history.test.ts +++ b/packages/cli/src/commands/history.test.ts @@ -902,3 +902,21 @@ describe.skipIf(process.platform === "win32" || process.getuid?.() === 0)( }); }, ); + +// fails without the fix: a refusal reached the terminal with its control characters live. +it("prints a refusal's control characters as visible escapes", async () => { + const { hf } = project(); + const refused = await hf("--since", "20\u001b[2J26"); + expect([refused.code, refused.err]).toEqual([2, 'No entry "20\\x1b[2J26" in this history']); +}); + +// fails without the fix: a changed file's text reached the terminal with its control characters live. +it("prints a diff's control characters as visible escapes", async () => { + const { hf, turn } = project(); + await hf("begin", "--who", "claude", "--label", "Start"); + await hf("end"); + const entry = await turn("claude", "Retitle", "index.html", "A\u001b[2J2"); + const diff = (await hf("show", entry.id, "--diff")).out; + expect(diff).toContain("+A\\x1b[2J2"); + expect(diff).not.toContain("\u001b"); +}); diff --git a/packages/cli/src/commands/history.ts b/packages/cli/src/commands/history.ts index aecc626a6b..87d240f24d 100644 --- a/packages/cli/src/commands/history.ts +++ b/packages/cli/src/commands/history.ts @@ -1,4 +1,5 @@ import { type ArgsDef } from "citty"; +import { terminalLines } from "@hyperframes/core"; import { defineCommand } from "../utils/defineCommand.js"; import { HISTORY_START, @@ -191,7 +192,7 @@ const changeOf = (file: HistoryEntry["files"][number]) => file.before === null ? "added" : file.after === null ? "deleted" : "modified"; function print(json: boolean, data: object, text: string): void { - console.log(json ? JSON.stringify(withMeta(data), null, 2) : text); + console.log(json ? JSON.stringify(withMeta(data), null, 2) : terminalLines(text)); } async function textDiff(reader: Reader, entry: HistoryEntry): Promise { @@ -333,7 +334,7 @@ function guarded(run: (args: A) => Promise) { ? `This project is open in another app (pid ${error.pid}), which keeps its history: undo, restore or pin there.` : (error as Error).message; if ((args as { json?: boolean }).json) print(true, jsonFailure("refused", message), message); - else console.error(message); + else console.error(terminalLines(message)); } }; } diff --git a/packages/cli/src/commands/lint.test.ts b/packages/cli/src/commands/lint.test.ts index 0c4ed99ce9..d389b5b6ea 100644 --- a/packages/cli/src/commands/lint.test.ts +++ b/packages/cli/src/commands/lint.test.ts @@ -181,3 +181,19 @@ describe("lint and compositions the project never mounts", () => { ]); }); }); + +// fails without the fix: the failure line reached the terminal with its control characters live. +it("prints a failure's control characters as visible escapes", async () => { + consumeCommandResult(); + lintProjectMock.mockRejectedValue(new Error("Cannot read scenes/a\u001b[2Jb.html\nline two")); + const error = vi.spyOn(console, "error").mockImplementation(() => {}); + try { + await run({ json: false, verbose: false }); + expect(error.mock.calls.map((call) => call.join(" "))).toEqual([ + "Cannot read scenes/a\\x1b[2Jb.html\nline two", + ]); + } finally { + error.mockRestore(); + consumeCommandResult(); + } +}); diff --git a/packages/cli/src/commands/lint.ts b/packages/cli/src/commands/lint.ts index d7f4cf8af7..219ef02028 100644 --- a/packages/cli/src/commands/lint.ts +++ b/packages/cli/src/commands/lint.ts @@ -1,4 +1,4 @@ -import { terminalText } from "@hyperframes/core"; +import { terminalLines, terminalText } from "@hyperframes/core"; import { setCommandExitCode } from "../utils/commandResult.js"; import { defineCommand } from "../utils/defineCommand.js"; import type { Example } from "./_examples.js"; @@ -137,7 +137,7 @@ export default defineCommand({ setCommandExitCode(1); return; } - console.error(message); + console.error(terminalLines(message)); setCommandExitCode(1); } }, diff --git a/packages/cli/src/commands/normalize-audio.command.test.ts b/packages/cli/src/commands/normalize-audio.command.test.ts index 8501940ee0..8aba8f9fe8 100644 --- a/packages/cli/src/commands/normalize-audio.command.test.ts +++ b/packages/cli/src/commands/normalize-audio.command.test.ts @@ -346,3 +346,51 @@ describe("reference normalize-audio command", () => { } }); }); + +// fails without the fix: the audio src from index.html reached the terminal with its control characters live. +describe("normalize-audio on a clip whose file is missing", () => { + it("prints the src's control characters as visible escapes", async () => { + const dir = mkdtempSync(join(tmpdir(), "hf-normalize-command-test-")); + const error = vi.spyOn(console, "error").mockImplementation(() => {}); + try { + writeFileSync( + join(dir, "index.html"), + ``, + ); + await expect( + runCommand(normalizeAudioCommand, { rawArgs: [dir, "--target", "voice"] }), + ).rejects.toBeInstanceOf(CliRuntimeError); + const printed = error.mock.calls.map((call) => call.join(" ")).join("\n"); + expect(printed).toContain("Audio #voice file was not found: vo\\x1b[2Jice.wav"); + expect(printed).not.toContain("vo\u001b[2Jice"); + } finally { + error.mockRestore(); + rmSync(dir, { recursive: true, force: true }); + } + }); +}); + +// fails without the fix: the clip id from index.html reached the terminal with its control characters live. +describe("normalize-audio on a clip whose id holds control characters", () => { + it("prints the id's control characters as visible escapes", async () => { + const dir = mkdtempSync(join(tmpdir(), "hf-normalize-command-test-")); + const log = vi.spyOn(console, "log").mockImplementation(() => {}); + try { + writeFileSync( + join(dir, "index.html"), + ``, + ); + writeFileSync(join(dir, "voice.wav"), "audio bytes"); + measureAudio.mockResolvedValue({ integratedLufs: -20, truePeakDbfs: -12.3 }); + await runCommand(normalizeAudioCommand, { rawArgs: [dir, "--target", "vo\u001b[2Jice"] }); + const printed = log.mock.calls.map((call) => String(call[0])).join("\n"); + expect(printed).toContain("#vo\\x1b[2Jice"); + expect(printed).toContain("Set #vo\\x1b[2Jice data-volume"); + expect(printed).not.toContain("vo\u001b[2Jice"); + } finally { + log.mockRestore(); + measureAudio.mockReset(); + rmSync(dir, { recursive: true, force: true }); + } + }); +}); diff --git a/packages/cli/src/commands/normalize-audio.ts b/packages/cli/src/commands/normalize-audio.ts index 73e437b78f..6ebfe84441 100644 --- a/packages/cli/src/commands/normalize-audio.ts +++ b/packages/cli/src/commands/normalize-audio.ts @@ -1,4 +1,5 @@ import { existsSync, readFileSync } from "node:fs"; +import { terminalLines, terminalText } from "@hyperframes/core"; import { replaceFileAtomically } from "@hyperframes/core/atomic-file"; import { relative, resolve } from "node:path"; import { @@ -42,7 +43,7 @@ function fail(message: string, json: boolean, cause?: unknown): never { console.log( JSON.stringify(jsonFailure(usage ? cause.code : "runtime_error", message), null, 2), ); - } else console.error(c.error(message)); + } else console.error(c.error(terminalLines(message))); if (usage) failUsage(); failCommand(1, cause); } @@ -221,8 +222,8 @@ const LIMIT_TEXT: Record = { function printMeasuredLine(result: NormalizeAudioResult): void { if (result.mode === "reference") { console.log( - `${c.bold(`#${result.referenceId}`)} ${result.referenceLufs.toFixed(1)} LUFS → ` + - `${c.bold(`#${result.targetId}`)} ${result.targetLufs.toFixed(1)} LUFS`, + `${c.bold(`#${terminalText(result.referenceId)}`)} ${result.referenceLufs.toFixed(1)} LUFS → ` + + `${c.bold(`#${terminalText(result.targetId)}`)} ${result.targetLufs.toFixed(1)} LUFS`, ); if (result.limitedBy) { console.log( @@ -235,7 +236,7 @@ function printMeasuredLine(result: NormalizeAudioResult): void { } const limit = result.limitedBy ? ` (${LIMIT_TEXT[result.limitedBy]})` : ""; console.log( - `${c.bold(`#${result.targetId}`)} ${result.sourceLufs.toFixed(1)} LUFS → ` + + `${c.bold(`#${terminalText(result.targetId)}`)} ${result.sourceLufs.toFixed(1)} LUFS → ` + `${result.reachedLufs.toFixed(1)} LUFS, target ${result.targetLufs.toFixed(1)}${limit}`, ); } @@ -255,12 +256,14 @@ function printHumanResult(result: NormalizeAudioResult): void { } console.log( - `Set #${result.targetId} data-volume ${result.previousVolume.toFixed(3)} → ${result.volume.toFixed(6)} ` + + `Set #${terminalText(result.targetId)} data-volume ${result.previousVolume.toFixed(3)} → ${result.volume.toFixed(6)} ` + `(${result.changeDb >= 0 ? "+" : ""}${result.changeDb.toFixed(1)} dB).`, ); console.log( result.wrote - ? c.success(`Updated ${relative(process.cwd(), result.filePath) || "index.html"}.`) + ? c.success( + `Updated ${terminalText(relative(process.cwd(), result.filePath) || "index.html")}.`, + ) : c.dim("Dry run only. Pass --write to persist this gain."), ); } diff --git a/packages/cli/src/commands/snapshot.test.ts b/packages/cli/src/commands/snapshot.test.ts index 5accb0ecb8..eb2709a58e 100644 --- a/packages/cli/src/commands/snapshot.test.ts +++ b/packages/cli/src/commands/snapshot.test.ts @@ -1589,3 +1589,78 @@ describe("renderNotReadyError", () => { expect(error.message).toContain("not render-ready after 5000ms"); }); }); + +// fails without the fix: the --against path reached the terminal with its control characters live. +it("prints a missing --against path's control characters as visible escapes", async () => { + const project = mkdtempSync(join(tmpdir(), "hf-snapshot-against-")); + writeFileSync( + join(project, "index.html"), + `
`, + ); + const lines: string[] = []; + const log = vi.spyOn(console, "log").mockImplementation((...parts: unknown[]) => { + lines.push(parts.map(String).join(" ")); + }); + try { + await expect( + snapshotCommand.run?.({ + args: { dir: project, against: join(project, "re\u001b[2Jf.mp4") }, + } as never), + ).rejects.toMatchObject({ name: "CliRuntimeError" }); + expect(lines.join("\n")).toContain("re\\x1b[2Jf.mp4"); + expect(lines.join("\n")).not.toContain("re\u001b[2Jf"); + } finally { + log.mockRestore(); + rmSync(project, { recursive: true, force: true }); + } +}); + +// fails without the fix: the folder and file names of saved snapshots reached the terminal with their control characters live. +it.skipIf(process.platform === "win32")( + "prints saved snapshot paths' control characters as visible escapes", + async () => { + const project = mkdtempSync(join(tmpdir(), "hf-snapshot-saved-")); + writeFileSync( + join(project, "index.html"), + `
Visible
`, + ); + const png = Buffer.from( + "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==", + "base64", + ); + snapshotState.openSettledPage.mockResolvedValueOnce({ + browser: { close: vi.fn(async () => undefined) }, + page: { + evaluate: vi + .fn() + .mockResolvedValueOnce({ loaded: [], errored: [], unused: [] }) + .mockResolvedValueOnce(2) + .mockResolvedValueOnce(true) + .mockResolvedValueOnce([]) + .mockResolvedValue(true), + screenshot: vi.fn(async () => png), + }, + renderReadyTimedOut: false, + }); + snapshotState.seek.mockResolvedValue(undefined); + snapshotState.settle.mockResolvedValue({ pending: [], failed: [] }); + const lines: string[] = []; + const log = vi.spyOn(console, "log").mockImplementation((...parts: unknown[]) => { + lines.push(parts.map(String).join(" ")); + }); + const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined); + try { + await snapshotCommand.run?.({ + args: { dir: project, at: "1", end: false, output: join(project, "o\u001b[2Jut") }, + } as never); + const printed = lines.join("\n"); + expect(printed).toContain("snapshots saved to"); + expect(printed).toContain("o\\x1b[2Jut"); + expect(printed).not.toContain("o\u001b[2Jut"); + } finally { + log.mockRestore(); + warn.mockRestore(); + rmSync(project, { recursive: true, force: true }); + } + }, +); diff --git a/packages/cli/src/commands/snapshot.ts b/packages/cli/src/commands/snapshot.ts index a5d7f785c0..5063b3c887 100644 --- a/packages/cli/src/commands/snapshot.ts +++ b/packages/cli/src/commands/snapshot.ts @@ -1169,11 +1169,11 @@ export async function captureSnapshots( }); if (range) log( - ` Sampling ${positions.length} frames within ${range[0]}–${range[1]}s${opts.composition ? ` (composition ${opts.composition})` : ""}`, + ` Sampling ${positions.length} frames within ${range[0]}–${range[1]}s${opts.composition ? ` (composition ${terminalText(opts.composition)})` : ""}`, ); if (review) log( - ` Review: ${review.beats.length} beat(s) and ${review.seams.length} seam(s) within ${review.window[0]}–${review.window[1]}s${opts.composition ? ` (composition ${opts.composition})` : ""}`, + ` Review: ${review.beats.length} beat(s) and ${review.seams.length} seam(s) within ${review.window[0]}–${review.window[1]}s${opts.composition ? ` (composition ${terminalText(opts.composition)})` : ""}`, ); if (appendedTail) { log( @@ -1195,7 +1195,7 @@ export async function captureSnapshots( ); if (!opts.keep) replaced.push(...clearEarlierStills(snapshotDir)); if (replaced.length > 0) { - log(` ${c.warn("⚠")} ${clearedNote(replaced.length, snapshotDir)}`); + log(` ${c.warn("⚠")} ${terminalText(clearedNote(replaced.length, snapshotDir))}`); } // Chrome-headless ignores programmatic