fix(cli): show control characters in more command messages as text (#8344)

* fix(cli): show control characters in more command messages as text

beats, normalize-audio, lint, history, feedback and snapshot printed
failure text that can quote a file name or an attribute from the
project. Control characters in it now print as visible \xNN escapes,
the way the shared failure helper already prints them. JSON output is
unchanged.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* fix(cli): show control characters as text in the same commands' progress and result lines

Names, paths and ids that these commands print while they work and when
they finish now go through the same display helper as their failure lines.
JSON output is unchanged.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* fix(cli): the repro upload line moves to the reply-text change

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
James Russo
2026-11-21 06:06:43 +00:00
committed by GitHub
co-authored by Claude Fable 5.2
parent 4095b73689
commit 9937baee1e
10 changed files with 230 additions and 36 deletions
+31
View File
@@ -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"),
`<div data-composition-id="main"><audio id="music" src="be%1B[2Jd.wav"></audio></div>`,
);
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"),
`<div data-composition-id="main"><audio id="music" src="assets/so\u001b[2Jng.wav"></audio></div>`,
);
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");
});
+7 -7
View File
@@ -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<void> {
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.
+18
View File
@@ -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");
});
+3 -2
View File
@@ -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<string> {
@@ -333,7 +334,7 @@ function guarded<A>(run: (args: A) => Promise<void>) {
? `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));
}
};
}
+16
View File
@@ -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();
}
});
+2 -2
View File
@@ -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);
}
},
@@ -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"),
`<audio id="voice" src="vo\u001b[2Jice.wav" data-volume="1" data-duration="2"></audio>`,
);
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"),
`<audio id="vo\u001b[2Jice" src="voice.wav" data-volume="1" data-duration="2"></audio>`,
);
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 });
}
});
});
+9 -6
View File
@@ -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<LoudnessLimit, string> = {
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."),
);
}
@@ -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"),
`<div data-composition-id="main" data-width="320" data-height="180" data-duration="1"></div>`,
);
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"),
`<html><body><div data-composition-id="main" data-width="320" data-height="180" data-start="0" data-duration="2"><div class="clip" data-start="0" data-duration="2">Visible</div></div></body></html>`,
);
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 });
}
},
);
+21 -19
View File
@@ -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 <video>.currentTime writes, so
@@ -1566,7 +1566,7 @@ export async function captureSnapshots(
pairSheetFailure = describeSharpLoadFailure(err);
if (!pairSheetFailure) throw err;
console.error(
` ${c.warn("⚠")} Reference pair sheets skipped: ${pairSheetFailure}`,
` ${c.warn("⚠")} Reference pair sheets skipped: ${terminalText(pairSheetFailure)}`,
);
}
}
@@ -1706,8 +1706,8 @@ async function recordSnapshotArtifacts(
).catch(warnSnapshotsNotRecorded);
const record = records?.[0];
if (!record) return false;
log(` Revision: ${record.revision ?? "none"} (${record.attribution})`);
log(` State: ${join(projectDir, ".hyperframes", "video-state.json")}`);
log(` Revision: ${terminalText(`${record.revision ?? "none"} (${record.attribution})`)}`);
log(` State: ${terminalText(join(projectDir, ".hyperframes", "video-state.json"))}`);
return true;
}
@@ -1781,15 +1781,17 @@ function printReview(
const beats = review.plan.beats.map(
(beat) => `${formatSnapshotTimestamp(beat.time)} ${terminalText(beat.label)}`,
);
log(` Beat sheet (settled frame per scene): ${sheets.beats.join(", ") || "none"}`);
log(
` Beat sheet (settled frame per scene): ${terminalText(sheets.beats.join(", ")) || "none"}`,
);
log(` ${c.dim(beats.join(" · "))}`);
review.plan.seams.forEach((seam, index) => {
const sides = terminalText(`${seam.from ?? "start"} -> ${seam.to ?? "end"}`);
const strip = sheets.seams[index] ?? "not written";
const strip = terminalText(sheets.seams[index] ?? "not written");
log(` Seam ${index + 1} at ${formatSnapshotTimestamp(seam.time)} (${sides}): ${strip}`);
});
log(
` Phone sheet (beats at ${REVIEW_PHONE_WIDTH} px wide): ${sheets.phone.join(", ") || "none"}`,
` Phone sheet (beats at ${REVIEW_PHONE_WIDTH} px wide): ${terminalText(sheets.phone.join(", ")) || "none"}`,
);
for (const note of review.plan.notes) log(` ${c.dim(terminalText(note))}`);
}
@@ -1934,7 +1936,7 @@ export default defineCommand({
log(c.error(" Aborting snapshot because the default index.html entry is blank."));
if (candidate && posix.basename(candidate) === "index.html") {
const candidateDir = posix.dirname(candidate);
const target = `<project>/${candidateDir}`;
const target = terminalText(`<project>/${candidateDir}`);
log(
c.dim(
` Move or mount the authored file, or snapshot its directory directly: hyperframes snapshot ${target}. Only use the directory form when its assets are self-contained under that directory; otherwise mount it from the project root.`,
@@ -1943,7 +1945,7 @@ export default defineCommand({
} else if (candidate) {
log(
c.dim(
` Move or mount ${candidate} as a project index.html before snapshotting; snapshot accepts project directories, not individual HTML files.`,
` Move or mount ${terminalText(candidate)} as a project index.html before snapshotting; snapshot accepts project directories, not individual HTML files.`,
),
);
}
@@ -1962,7 +1964,7 @@ export default defineCommand({
const zoomScale = parseZoomScale(args["zoom-scale"]);
const against = args.against ? resolve(String(args.against)) : undefined;
if (against && !existsSync(against))
fail(`${c.error("✗")} --against video not found: ${against}`);
fail(`${c.error("✗")} --against video not found: ${terminalText(against)}`);
const label = reviewMode
? "review frames (beats, seams, phone)"
@@ -2016,19 +2018,19 @@ export default defineCommand({
const short = onDisk.missing.length > 0;
const mark = short ? c.error("✗") : c.success("◇");
const count = short ? `${paths.length} of ${captured.paths.length}` : String(paths.length);
log(`\n${mark} ${count} snapshots saved to ${snapshotDir}`);
log(`\n${mark} ${count} snapshots saved to ${terminalText(snapshotDir)}`);
for (const p of paths) {
log(` ${p}`);
log(` ${terminalText(p)}`);
}
if (short) {
const gone = onDisk.missing.map((path) => `\n missing: ${path}`).join("");
const gone = onDisk.missing.map((path) => `\n missing: ${terminalText(path)}`).join("");
fail(
`${c.error("✗")} Only ${paths.length} of ${captured.paths.length} snapshots are on disk in ${snapshotDir}.${gone}`,
`${c.error("✗")} Only ${paths.length} of ${captured.paths.length} snapshots are on disk in ${terminalText(snapshotDir)}.${gone}`,
);
}
if (captured.unreadVideoFrames > 0) {
fail(
`${c.error("✗")} ${captured.unreadVideoFrames} video frame(s) could not be read, so those videos are black or stale in the snapshots saved to ${snapshotDir}.`,
`${c.error("✗")} ${captured.unreadVideoFrames} video frame(s) could not be read, so those videos are black or stale in the snapshots saved to ${terminalText(snapshotDir)}.`,
);
}
if (against) {
@@ -2064,12 +2066,12 @@ export default defineCommand({
reportArtifacts("snapshot", "contact-sheet", contactSheets);
if (!captured.review) {
for (const sheet of contactSheets) {
log(` ${resolve(sheet)} (grid view for AI review)`);
log(` ${terminalText(resolve(sheet))} (grid view for AI review)`);
}
}
} catch (err) {
console.warn(
` ${c.warn("⚠")} Contact sheet skipped: ${describeSharpLoadFailure(err) ?? normalizeErrorMessage(err)}. Individual snapshot PNGs are still available.`,
` ${c.warn("⚠")} Contact sheet skipped: ${terminalText(describeSharpLoadFailure(err) ?? normalizeErrorMessage(err))}. Individual snapshot PNGs are still available.`,
);
}