fix(cli): show control characters in failure messages as text (#8336)

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

A failure message can quote text from the project, such as a file name or a
data-composition-src value. `compare`, `grade-compare` and `add` printed that
message to the terminal as it was, so a control character in the quoted text
reached the terminal instead of being shown.

- failCaught now prints the message with control characters written out
  (\x1b, \x07, ...), the same way errorBox does. The --json envelope is
  unchanged.
- The composition size limit messages write the file label the same way, so
  every caller and the render server's logs get readable text.

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

* refactor(cli): carry the reason in the helper's name instead of a comment

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 02:04:59 +00:00
committed by GitHub
co-authored by Claude Fable 5.2
parent 80d968a94c
commit 183bc10807
5 changed files with 165 additions and 7 deletions
+40
View File
@@ -258,3 +258,43 @@ describe("prepareCompareVariantProjects", () => {
}
});
});
// Windows file names cannot hold control characters, so the project below cannot exist there.
describe.skipIf(process.platform === "win32")("compare failure output", () => {
it("prints a refused project's file name with its control characters as text", async () => {
const scene = "scene\x1b[2J\x07.html";
const mount = `<div data-composition-id="scene" data-composition-src="${scene}" data-start="0" data-duration="2"></div>`;
const variants = ["a", "b"].map((name) => {
const dir = join(tempDir(), name);
mkdirSync(dir);
writeFileSync(
join(dir, "index.html"),
`<!doctype html><html><body><div data-composition-id="main" data-width="320" data-height="180" data-start="0" data-duration="2">${mount.repeat(10_001)}</div><script>window.__timelines = {};</script></body></html>`,
);
writeFileSync(
join(dir, scene),
`<template><div data-composition-id="scene" data-width="320" data-height="180"><h1>x</h1></div></template>`,
);
return dir;
});
const written: string[] = [];
const error = vi.spyOn(console, "error").mockImplementation((text: string) => {
written.push(text);
});
const log = vi.spyOn(console, "log").mockImplementation(() => {});
try {
const { default: compare } = await import("./compare.js");
await expect(
compare.run?.({ args: { _: variants, json: false }, rawArgs: [], cmd: compare } as never),
).rejects.toThrow("Command failed");
} finally {
error.mockRestore();
log.mockRestore();
for (const dir of variants) rmSync(join(dir, ".."), { recursive: true, force: true });
}
expect(written.join("\n")).toContain('ending at "scene\\x1b[2J\\x07.html"');
// The formatter's own colour codes are the only escape bytes left.
// eslint-disable-next-line no-control-regex
expect(written.join("\n").replace(/\x1b\[\d+m/g, "")).not.toMatch(/[\x00-\x08\x0b-\x1f\x7f]/);
}, 60_000);
});
+57 -2
View File
@@ -1,6 +1,12 @@
import { describe, expect, it } from "vitest";
import { describe, expect, it, vi } from "vitest";
import { CliRuntimeError, CliUsageError } from "./commandResult.js";
import { failureMessage, jsonErrorBody, jsonFailure, recordFailure } from "./jsonError.js";
import {
failCaught,
failureMessage,
jsonErrorBody,
jsonFailure,
recordFailure,
} from "./jsonError.js";
const runtime = { exitCode: 1, kind: "runtime_error" } as const;
@@ -83,3 +89,52 @@ describe("jsonErrorBody", () => {
});
});
});
describe("failCaught", () => {
const controls = "\x1b[2J\x1b]0;title\x07 \u009b31m \x7f \r";
const shown = "\\x1b[2J\\x1b]0;title\\x07 \\x9b31m \\x7f \\x0d";
const caught = (run: () => never): unknown => {
try {
run();
} catch (error) {
return error;
}
};
it("prints control characters in the message as text and keeps the formatter's own colour", () => {
const written: string[] = [];
const spy = vi.spyOn(console, "error").mockImplementation((text: string) => {
written.push(text);
});
try {
const error = caught(() =>
failCaught(
new Error(`Composition file "${controls}" is too large\nsecond line`),
false,
(message) => `\x1b[31m✗\x1b[39m Compare failed: ${message}`,
),
);
expect(error).toBeInstanceOf(CliRuntimeError);
} finally {
spy.mockRestore();
}
expect(written).toEqual([
`\x1b[31m✗\x1b[39m Compare failed: Composition file "${shown}" is too large\nsecond line`,
]);
});
it("leaves the --json envelope's message as the error wrote it", () => {
const printed: object[] = [];
caught(() =>
failCaught(
new Error(`file "${controls}"`),
true,
(m) => m,
(payload) => printed.push(payload),
),
);
expect(printed).toEqual([
{ ok: false, error: { code: "runtime_error", message: `file "${controls}"` } },
]);
});
});
+2 -1
View File
@@ -1,4 +1,5 @@
import { format, stripVTControlCharacters } from "node:util";
import { terminalLines } from "@hyperframes/core";
import {
CliRuntimeError,
CliUsageError,
@@ -33,7 +34,7 @@ export function failCaught(
const message = failureMessage(error);
const usage = error instanceof CliUsageError;
if (json) print(jsonFailure(usage ? error.code : "runtime_error", message));
else console.error(line(message));
else console.error(line(terminalLines(message)));
if (usage) failUsage();
failCommand();
}
@@ -0,0 +1,59 @@
// @vitest-environment node
import { mkdtempSync, rmSync, truncateSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterAll, describe, expect, it } from "vitest";
import {
assertCompositionFileSize,
CompositionExpansionBudget,
MAX_COMPOSITION_HTML_BYTES,
MAX_EXPANDED_COMPOSITION_BYTES,
MAX_EXPANDED_ELEMENTS,
} from "./compositionSizeLimit";
const dir = mkdtempSync(join(tmpdir(), "hf-size-limit-"));
afterAll(() => rmSync(dir, { recursive: true, force: true }));
const label = "scene\x1b[2J\x07\u009b\x7f.html";
const shown = '"scene\\x1b[2J\\x07\\x9b\\x7f.html"';
const messageOf = (run: () => void): string => {
try {
run();
} catch (error) {
return error instanceof Error ? error.message : String(error);
}
return "";
};
describe("composition size limit messages", () => {
it.each([
[
"one file over the file limit",
() => {
const path = join(dir, "big.html");
writeFileSync(path, "");
truncateSync(path, MAX_COMPOSITION_HTML_BYTES + 1);
assertCompositionFileSize(path, label);
},
],
[
"mounts over the byte limit",
() => new CompositionExpansionBudget().charge(label, MAX_EXPANDED_COMPOSITION_BYTES + 1),
],
[
"mounts over the element limit",
() => new CompositionExpansionBudget().chargeElements(label, MAX_EXPANDED_ELEMENTS + 1),
],
[
"generated text over the byte limit",
() =>
new CompositionExpansionBudget().chargeGenerated(label, MAX_EXPANDED_COMPOSITION_BYTES + 1),
],
])("show control characters in the file label as text: %s", (_name, run) => {
const message = messageOf(run);
expect(message).toContain(shown);
// eslint-disable-next-line no-control-regex
expect(message).not.toMatch(/[\x00-\x08\x0a-\x1f\x7f-\x9f]/);
});
});
@@ -1,4 +1,5 @@
import { statSync } from "node:fs";
import { terminalText } from "../terminalText";
/**
* The largest entry or sub-composition HTML file a render compiles. Compiling and probing a page
@@ -11,6 +12,8 @@ const COMPOSITION_TOO_LARGE = "COMPOSITION_TOO_LARGE" as const;
const megabytes = (bytes: number) => `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
const quotedForTerminalAndLogs = (file: string) => `"${terminalText(file)}"`;
/**
* What one render may inline across every sub-composition mount. Each file is checked on its own
* above, but a few small files that mount each other many times assemble a page far larger.
@@ -48,7 +51,7 @@ export function isCompositionTooLargeError(error: unknown): error is Error {
const fileTooLarge = (file: string, bytes: number) =>
new CompositionTooLargeError(
`Composition file "${file}" is ${megabytes(bytes)}, over the ` +
`Composition file ${quotedForTerminalAndLogs(file)} is ${megabytes(bytes)}, over the ` +
`${megabytes(MAX_COMPOSITION_HTML_BYTES)} limit for one composition HTML file. ` +
"Keep large data such as images, fonts and JSON in separate asset files and reference " +
"them by path instead of inlining them.",
@@ -81,7 +84,7 @@ function generatedTooLarge(file: string, bytes: number): string {
);
}
return (
`Scripts, styles and rebased asset paths generated for compositions, ending at "${file}", add up to ` +
`Scripts, styles and rebased asset paths generated for compositions, ending at ${quotedForTerminalAndLogs(file)}, add up to ` +
`${megabytes(bytes)}. One render generates at most ` +
`${megabytes(MAX_EXPANDED_COMPOSITION_BYTES)} for its mounts. Merge small inline scripts ` +
"and style rules, keep data-composition-id values short, or mount scenes fewer times."
@@ -101,7 +104,7 @@ export class CompositionExpansionBudget {
throw new CompositionTooLargeError(
(file === ENTRY_PAGE
? `The entry page holds ${this.elements} elements. `
: `Sub-composition mounts, ending at "${file}", add up to ${this.elements} elements. `) +
: `Sub-composition mounts, ending at ${quotedForTerminalAndLogs(file)}, add up to ${this.elements} elements. `) +
`One render inlines at most ${MAX_EXPANDED_ELEMENTS} elements. Mount large or repeated scenes fewer times.`,
{
bytes: this.bytes,
@@ -141,7 +144,7 @@ export class CompositionExpansionBudget {
return;
}
throw new CompositionTooLargeError(
`Sub-composition mounts, ending at "${file}", add up to ${megabytes(this.bytes)} ` +
`Sub-composition mounts, ending at ${quotedForTerminalAndLogs(file)}, add up to ${megabytes(this.bytes)} ` +
`across ${this.mounts} mounts. One render inlines at most ` +
`${megabytes(MAX_EXPANDED_COMPOSITION_BYTES)} of composition HTML in at most ` +
`${MAX_COMPOSITION_MOUNTS} mounts. Mount large or repeated scenes fewer times.`,