fix(media-use): provider error lines print control characters as escapes (#8249)

* fix(media-use): provider error lines print control characters as escapes

The local video, local image, Codex image, local voice and HeyGen providers
print a helper tool's output or an error message when a step fails. Those
lines now go through terminalText, as the sound effect provider already does,
so escape and bell bytes from a prompt or a helper's output show as visible
\xNN escapes instead of reaching the terminal. Printable text, return values
and thrown errors are unchanged.

* fix(media-use): keep line breaks in escaped provider error lines

A helper's multi-line error output printed as one long line, because every
line break showed as a visible escape. A new terminalLines helper keeps each
line break (a CRLF pair counts as one) and escapes every other control
character, a lone carriage return included. Provider lines that can carry
multi-line helper output now use it.
This commit is contained in:
Michael Wang
2026-11-19 18:52:27 +00:00
committed by GitHub
parent 6bd0b5d870
commit 77134c9273
18 changed files with 212 additions and 9 deletions
@@ -3,6 +3,7 @@ import { copyFileSync, existsSync, readdirSync, statSync } from "node:fs";
import { homedir } from "node:os";
import { dirname, join } from "node:path";
import { discardPrivateOutput, privateOutputPath } from "./private-output.mjs";
import { terminalLines } from "./terminal-text.mjs";
// Image generation via the OpenAI Codex CLI's built-in image tool (gpt-image-2)
// on the user's ChatGPT subscription: the codex CLI owns auth, media-use holds
@@ -144,7 +145,9 @@ function generateIn(outPath, intent, flag) {
);
} catch (err) {
console.error(
`media-use: \`codex exec\` image generation failed: ${err.stderr?.toString().trim().slice(-200) || err.message}`,
terminalLines(
`media-use: \`codex exec\` image generation failed: ${err.stderr?.toString().trim().slice(-200) || err.message}`,
),
);
return null;
}
@@ -15,6 +15,7 @@ import { codexImageGenerate, imageGenFlag } from "./codex-provider.mjs";
// A stand-in `codex` on PATH: `features list` offers the image tool; `exec` records its
// arguments, renders nothing, and plants a file where an attacker could (EVIL_PATH).
// With CODEX_FAIL set, `exec` fails with a terminal control sequence on stderr.
function fakeCodex(t) {
const root = mkdtempSync(join(tmpdir(), "fake-codex-"));
const bin = join(root, "bin");
@@ -26,6 +27,7 @@ function fakeCodex(t) {
'case "$1" in',
' features) echo "image_generation stable true" ;;',
' exec) printf "%s\\n" "$@" > "$CODEX_LOG"; cat > /dev/null;',
' [ -n "$CODEX_FAIL" ] && { printf "refused \\033]0;title\\007 a red cube\\r\\nsecond \\rline\\n" >&2; exit 1; }',
' [ -n "$EVIL_PATH" ] && printf EVIL > "$EVIL_PATH" ;;',
"esac",
"",
@@ -115,3 +117,21 @@ test("no image feature at all is unavailable, not a silent default", () => {
test("substring lookalikes do not count as the feature row", () => {
assert.equal(imageGenFlag("image_generation_v2 stable true"), null);
});
test(
"a failed codex exec prints its output line by line with control characters escaped",
posixOnly,
async (t) => {
fakeCodex(t);
process.env.CODEX_FAIL = "1";
t.after(() => delete process.env.CODEX_FAIL);
const errors = [];
t.mock.method(console, "error", (message) => errors.push(message));
assert.equal(await codexImageGenerate("a red cube"), null);
assert.deepEqual(errors, [
"media-use: `codex exec` image generation failed: refused \\x1b]0;title\\x07 a red cube\nsecond \\x0dline",
]);
},
);
@@ -1,5 +1,6 @@
import { execFileSync } from "node:child_process";
import { track } from "./telemetry.mjs";
import { terminalLines } from "./terminal-text.mjs";
// v0.3.0 is the first CLI that can use an OAuth session; v0.1.x/0.2.x reject it
// ("heygen-cli can't use OAuth yet"), and OAuth is what the free-usage path
@@ -129,7 +130,7 @@ export function reportHeygenFailure(err, context, trackEvent = track) {
if (ACTIONABLE_MESSAGES.has(message)) {
console.error(message);
} else {
console.error(`media-use: \`${context}\` failed: ${message}`);
console.error(terminalLines(`media-use: \`${context}\` failed: ${message}`));
}
try {
const tracked = Promise.resolve(
@@ -313,3 +313,17 @@ test("only a music miss names the heygen CLI and the host app's own tool", () =>
test("a CLI that rejects --headers without printing a version is outdated", () => {
assert.equal(classifyHeygenErrorCode({ stderr: "Error: unknown flag: --headers" }), "outdated");
});
test("a heygen CLI failure message keeps its lines and prints control characters as escapes", () => {
const stderrCalls = captureFailureReport(
{ stderr: Buffer.from("Error: voice \x1b]0;title\x07 not usable\r\nretry \rlater\n") },
"heygen voice list",
() => {},
);
assert.deepEqual(stderrCalls, [
[
"media-use: `heygen voice list` failed: Error: voice \\x1b]0;title\\x07 not usable\nretry \\x0dlater",
],
]);
});
@@ -1,5 +1,6 @@
import { execFileSync } from "node:child_process";
import { HEYGEN_CLIENT_SOURCE_ARGV, reportHeygenFailure } from "./heygen-cli.mjs";
import { terminalLines } from "./terminal-text.mjs";
export function heygenSearch(subcommand, query, { type, limit = 5, minScore, onEmpty } = {}) {
// execFileSync with an argv array (no shell), so query/type/etc. are passed as
@@ -36,7 +37,9 @@ export function heygenSearch(subcommand, query, { type, limit = 5, minScore, onE
}
if (parsed?.error) {
const e = parsed.error;
console.error(`media-use: \`heygen ${subcommand}\` error: ${e.message ?? JSON.stringify(e)}`);
console.error(
terminalLines(`media-use: \`heygen ${subcommand}\` error: ${e.message ?? JSON.stringify(e)}`),
);
return null;
}
@@ -47,3 +47,31 @@ test("keeps CLI and REST media-use client source headers in lockstep", () => {
assert.equal(HEYGEN_CLIENT_SOURCE_ARGV[1], `${key}: ${value}`);
});
test("a heygen error message prints control characters as visible escapes", (t) => {
const dir = mkdtempSync(join(tmpdir(), "media-use-heygen-search-"));
const heygenPath = join(dir, "heygen");
const previousPath = process.env.PATH;
writeFileSync(
heygenPath,
`#!/bin/sh
printf '%s\\n' '{"error":{"message":"no match for \\u001b]0;title\\u0007\\r\\nocean"}}'
`,
);
chmodSync(heygenPath, 0o755);
process.env.PATH = `${dir}:${previousPath ?? ""}`;
const errors = [];
t.mock.method(console, "error", (message) => errors.push(message));
try {
assert.equal(heygenSearch("audio sounds list", "ocean", { limit: 1 }), null);
} finally {
if (previousPath === undefined) delete process.env.PATH;
else process.env.PATH = previousPath;
rmSync(dir, { recursive: true, force: true });
}
assert.deepEqual(errors, [
"media-use: `heygen audio sounds list` error: no match for \\x1b]0;title\\x07\nocean",
]);
});
@@ -11,6 +11,7 @@ import {
reportHeygenFailure,
runHeygenJson,
} from "./heygen-cli.mjs";
import { terminalText } from "./terminal-text.mjs";
export const AVATAR_VIDEO_SIGNIN_MESSAGE = `media-use: avatar video is free for new API users — sign in: ${HEYGEN_AUTH_COMMAND}`;
@@ -123,7 +124,7 @@ export async function heygenVideoGenerate(intent, ctx) {
// Preserve the download failure if temporary-directory cleanup fails.
}
}
console.error(`media-use: heygen video download failed: ${err.message}`);
console.error(terminalText(`media-use: heygen video download failed: ${err.message}`));
return null;
}
@@ -433,3 +433,26 @@ test("removes private download staging on failure while returning null", async (
rmSync(root, { recursive: true, force: true });
}
});
test("a download failure prints its message with control characters escaped", async (t) => {
t.mock.method(globalThis, "fetch", async () => {
throw new Error("download failed \x1b]0;title\x07 here");
});
const errors = [];
t.mock.method(console, "error", (message) => errors.push(message));
await withFakeHeygen(
{ response: JSON.stringify({ data: { video_url: "https://example.invalid/video.mp4" } }) },
async () => {
const generate = await freshGenerate();
assert.equal(await generate("Failure", { avatarId: "a", voiceId: "v" }), null);
},
);
assert.ok(
errors.includes(
"media-use: heygen video download failed: download failed \\x1b]0;title\\x07 here",
),
errors.join("\n"),
);
});
@@ -4,6 +4,7 @@ import { homedir } from "node:os";
import { describeDownload, probeSpecs } from "./specs.mjs";
import { buildArgv, selectModel, selectModelLadder } from "./local-models.mjs";
import { discardPrivateOutput, privateOutputPath } from "./private-output.mjs";
import { terminalLines } from "./terminal-text.mjs";
export async function ltxVideoGenerate(
intent,
@@ -72,7 +73,9 @@ export async function ltxVideoGenerate(
} catch (err) {
discardPartial(outPath);
console.error(
`media-use: local video gen (${model.id}) failed: ${err.stderr?.toString().trim().slice(-200) || err.message}`,
terminalLines(
`media-use: local video gen (${model.id}) failed: ${err.stderr?.toString().trim().slice(-200) || err.message}`,
),
);
continue;
}
@@ -331,3 +331,31 @@ test("an unremovable partial does not mask the generate failure", async (t) => {
// cleanup is best-effort: a partial we cannot delete must not become the error
assert.equal(result, null);
});
test("a failed generate prints the runner's output with control characters escaped", async (t) => {
const errors = [];
t.mock.method(console, "error", (message) => errors.push(message));
let calls = 0;
const fakeExec = () => {
calls += 1;
if (calls === 2) {
const error = new Error("generation failed");
error.stderr = "bad prompt \x1b]0;title\x07\r\nstorm \rclouds";
throw error;
}
};
const result = await ltxVideoGenerate(
"storm clouds",
{ specs: fittingSpecs },
fakeExec,
() => true,
);
assert.equal(result, null);
assert.equal(errors.length, 1);
assert.match(
errors[0],
/^media-use: local video gen \(\S+\) failed: bad prompt \\x1b\]0;title\\x07\nstorm \\x0dclouds$/,
);
});
@@ -3,6 +3,7 @@ import { existsSync, unlinkSync } from "node:fs";
import { describeDownload, probeSpecs } from "./specs.mjs";
import { buildArgv, selectModelLadder } from "./local-models.mjs";
import { discardPrivateOutput, privateOutputPath } from "./private-output.mjs";
import { terminalLines } from "./terminal-text.mjs";
// Local image generation via mflux (FLUX-on-MLX), the Mac-native runner.
// Spec-gated: selectModelLadder("imagegen", specs) returns every FLUX-class
@@ -87,7 +88,7 @@ export async function mfluxImageGenerate(
}
if (!snap) {
discardPartial(outPath);
console.error(`media-use: local image gen (${model.id}): ${why}`);
console.error(terminalLines(`media-use: local image gen (${model.id}): ${why}`));
continue;
}
vars.model_path = snap;
@@ -104,7 +105,9 @@ export async function mfluxImageGenerate(
} catch (err) {
discardPartial(outPath);
console.error(
`media-use: local image gen (${model.id}) failed: ${err.stderr?.toString().trim().slice(-200) || err.message}`,
terminalLines(
`media-use: local image gen (${model.id}) failed: ${err.stderr?.toString().trim().slice(-200) || err.message}`,
),
);
continue;
}
@@ -172,3 +172,41 @@ test("a successful generation is never discarded", async () => {
assert.ok(result);
assert.deepEqual(unlinked, [], "the returned artifact must survive");
});
test("helper output in a failure line prints control characters as visible escapes", async (t) => {
const errors = [];
t.mock.method(console, "error", (message) => errors.push(message));
const exec = (...call) => {
const [bin, argv] = call;
if (bin === "which") return "";
if (bin === "hf") {
if (argv[1].includes("FLUX.2-klein")) {
const err = new Error("exit 1");
err.stderr = "repo \x1b]0;title\x07\nnot found";
throw err;
}
return `${SNAPSHOT}\n`;
}
const err = new Error("exit 1");
err.stderr = "bad prompt \x1b[2J\x07\r\na red \rbicycle";
throw err;
};
const result = await mfluxImageGenerate(
"a red bicycle",
{ specs: bothTiersSpecs },
exec,
() => true,
);
assert.equal(result, null);
assert.equal(errors.length, 2);
assert.match(
errors[0],
/^media-use: local image gen \(\S+\): hf download failed: repo \\x1b\]0;title\\x07\nnot found$/,
);
assert.match(
errors[1],
/^media-use: local image gen \(\S+\) failed: bad prompt \\x1b\[2J\\x07\na red \\x0dbicycle$/,
);
});
@@ -1 +1,2 @@
export function terminalText(value: unknown): string;
export function terminalLines(value: unknown): string;
@@ -10,3 +10,12 @@ export function terminalText(value) {
}
return shown;
}
// Multi-line output keeps its line breaks, with a "\r\n" pair printed as one break. Every other
// control character, a lone "\r" included, still prints as an escape.
export function terminalLines(value) {
return String(value)
.split(/\r?\n/)
.map((line) => terminalText(line))
.join("\n");
}
@@ -2,6 +2,7 @@ import { execFileSync } from "node:child_process";
import { existsSync, statSync } from "node:fs";
import { ffprobeBinary } from "./ff-binaries.mjs";
import { discardPrivateOutput, privateOutputPath } from "./private-output.mjs";
import { terminalLines } from "./terminal-text.mjs";
import { resolveSpawnCommand } from "../../audio/scripts/lib/tts.mjs";
// Local voiceover via the packaged Kokoro-82M TTS (the `hyperframes tts` CLI),
@@ -82,7 +83,7 @@ export async function localTtsGenerate(
const hint = /not installed|pip install kokoro/i.test(out)
? "install for free on-device voice: pip install kokoro-onnx soundfile (or set HYPERFRAMES_PYTHON to a venv that has it)"
: out.slice(-200) || err.message;
console.error(`media-use: local voice not enabled (kokoro). ${hint}`);
console.error(terminalLines(`media-use: local voice not enabled (kokoro). ${hint}`));
discardPrivateOutput(outPath);
return null;
}
@@ -57,3 +57,21 @@ test("without an absolute CLI entry: falls through to the next provider (null),
}
}
});
test("a failed tts run prints its output line by line with control characters escaped", async (t) => {
const errors = [];
t.mock.method(console, "error", (message) => errors.push(String(message)));
const fakeExec = () => {
const err = new Error("Command failed");
err.stdout = "";
err.stderr = "bad text \x1b]0;title\x07\r\nline two \rhello";
throw err;
};
const env = { ...envWithNpxCli, HYPERFRAMES_CLI_ENTRY: "/opt/hf/dist/cli.js" };
assert.equal(await localTtsGenerate("hello", {}, "darwin", fakeExec, env, pathExists), null);
assert.deepEqual(errors, [
"media-use: local voice not enabled (kokoro). bad text \\x1b]0;title\\x07\nline two \\x0dhello",
]);
});