From 7a1163fc98149719c636a170aad6c99e2d68a291 Mon Sep 17 00:00:00 2001 From: James Russo Date: Sat, 21 Nov 2026 09:49:55 +0000 Subject: [PATCH] fix(cli): show control characters as text in more commands' printed lines (#8353) * fix(cli): show control characters as text in more commands' printed lines tts, remove-background, media-treatment, telemetry, docs, update, add, catalog, diff, doctor, clean, compare and grade-compare now pass quoted names, paths, queries and caught messages through terminalText or terminalLines at the line that prints them. JSON output is unchanged. Refs #8336. Co-Authored-By: Claude Fable 5.2 * fix(cli): remove-background --json reports a refused flag's value as given Co-Authored-By: Claude Fable 5.2 * fix(cli): docs answers a --json run with an unknown topic as given Co-Authored-By: Claude Fable 5.2 * fix(cli): telemetry, catalog and tts answer a --json run with the value as given With --json before the command name these commands print their lines for people, and the answer was built from those lines, so it carried the visible form of a control character instead of the value. - telemetry: an unknown subcommand and a preference that cannot be saved - catalog: a query with no searchable words and a registry that cannot be read - tts: a failed synthesis answers with the reason alone Co-Authored-By: Claude Fable 5.2 * fix(cli): explain the catalog gap report in words when the query cannot be printed as typed The hint printed a ready-to-paste feedback command with the query in it. A query with a line break or another control character was shown rewritten inside that command, so pasting it reported different text. Both hint branches now print the command only when it prints unchanged, and a plain sentence otherwise. The JSON report_gap value is unchanged. Co-Authored-By: Claude Fable 5.2 --------- Co-authored-by: Claude Fable 5.2 --- packages/cli/src/cli.lifecycle.test.ts | 158 ++++++++++++++---- packages/cli/src/commands/add.test.ts | 19 +++ packages/cli/src/commands/add.ts | 17 +- packages/cli/src/commands/catalog.test.ts | 56 +++++++ packages/cli/src/commands/catalog.ts | 43 +++-- packages/cli/src/commands/clean.test.ts | 47 +++++- packages/cli/src/commands/clean.ts | 5 +- packages/cli/src/commands/compare.ts | 7 +- packages/cli/src/commands/diff.test.ts | 46 +++++ packages/cli/src/commands/diff.ts | 24 +-- packages/cli/src/commands/docs.output.test.ts | 29 ++++ packages/cli/src/commands/docs.ts | 5 +- .../cli/src/commands/doctor.output.test.ts | 48 ++++++ packages/cli/src/commands/doctor.ts | 7 +- .../cli/src/commands/grade-compare.test.ts | 17 ++ packages/cli/src/commands/grade-compare.ts | 9 +- .../cli/src/commands/media-treatment.test.ts | 22 +++ packages/cli/src/commands/media-treatment.ts | 13 +- .../commands/remove-background.output.test.ts | 95 +++++++++++ .../cli/src/commands/remove-background.ts | 21 +-- packages/cli/src/commands/telemetry.test.ts | 40 +++++ packages/cli/src/commands/telemetry.ts | 18 +- packages/cli/src/commands/tts.output.test.ts | 68 ++++++++ packages/cli/src/commands/tts.ts | 13 +- packages/cli/src/commands/update.test.ts | 48 ++++++ packages/cli/src/commands/update.ts | 32 ++-- 26 files changed, 792 insertions(+), 115 deletions(-) create mode 100644 packages/cli/src/commands/docs.output.test.ts create mode 100644 packages/cli/src/commands/doctor.output.test.ts create mode 100644 packages/cli/src/commands/remove-background.output.test.ts create mode 100644 packages/cli/src/commands/tts.output.test.ts diff --git a/packages/cli/src/cli.lifecycle.test.ts b/packages/cli/src/cli.lifecycle.test.ts index 4046714992..b03a5e7147 100644 --- a/packages/cli/src/cli.lifecycle.test.ts +++ b/packages/cli/src/cli.lifecycle.test.ts @@ -522,36 +522,109 @@ describe("CLI lifecycle", () => { `no video-manifest.json at ${join(tmpdir(), "hf-no\u0007ne", "extracted")}`, 1, ], - ])("answers a --json run for %s with the value as given", async (_name, argv, given, exit) => { - const exitSpy = vi.spyOn(process, "exit").mockImplementation((() => undefined) as never); - const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {}); - let answered = ""; - const outSpy = vi.spyOn(process.stdout, "write").mockImplementation(((chunk: unknown) => { - answered += String(chunk); - return true; - }) as never); - try { - mockTelemetry(); - process.argv = ["node", "cli.ts", ...argv, "--json"]; - await import("./cli.js"); + [ + "a refused remove-background device", + ["remove-background", "in.mp4", "-o", "out.webm", "--device", "g\u0007pu"], + "Invalid --device 'g\u0007pu'.", + 2, + ], + [ + "a refused remove-background quality", + ["remove-background", "in.mp4", "-o", "out.webm", "--quality", "be\u0007st"], + "Invalid --quality 'be\u0007st'.", + 2, + ], + // `docs` has no --json flag of its own; --json before the command name still reaches it. + ["an unknown docs topic", ["--json", "docs", "to\u0007pic"], "Unknown topic: to\u0007pic", 2], + // The rows below put --json first too: the command then prints its lines for people. + [ + "an unknown telemetry subcommand", + ["--json", "telemetry", "fo\u0007o"], + "Unknown subcommand: fo\u0007o", + 2, + ], + [ + "a telemetry preference that cannot be saved", + ["--json", "telemetry", "disable"], + "Reason: EACCES /ho\u0007me", + 1, + () => + vi.doMock("./telemetry/config.js", async () => ({ + ...(await vi.importActual( + "./telemetry/config.js", + )), + readConfigFresh: () => ({}), + writeConfigWithResult: () => ({ ok: false, error: "EACCES /ho\u0007me" }), + })), + ], + [ + "a catalog query with no searchable words", + ["--json", "catalog", "--query", "!!\u0007"], + 'No searchable words in query "!!\u0007".', + 1, + () => mockCatalogRegistry(), + ], + [ + "a catalog whose registry cannot be read", + ["--json", "catalog"], + "The registry could not be read: no route to ho\u0007st", + 1, + () => mockCatalogRegistry("The registry could not be read: no route to ho\u0007st"), + ], + [ + "speech that cannot be generated", + ["--json", "tts", "hello", "--voice", "af_\u0007x"], + "no model at /mo\u0007dels", + 1, + () => + vi.doMock("./tts/synthesize.js", () => ({ + synthesize: async () => { + throw new Error("no model at /mo\u0007dels"); + }, + })), + ], + ] as [string, string[], string, number, (() => void)?][])( + "answers a --json run for %s with the value as given", + async (_name, argv, given, exit, mock) => { + const exitSpy = vi.spyOn(process, "exit").mockImplementation((() => undefined) as never); + const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {}); + let answered = ""; + const outSpy = vi.spyOn(process.stdout, "write").mockImplementation(((chunk: unknown) => { + answered += String(chunk); + return true; + }) as never); + // A spinner's lines go straight to the stream when nobody is watching. + let written = ""; + const errSpy = vi.spyOn(process.stderr, "write").mockImplementation(((chunk: unknown) => { + written += String(chunk); + return true; + }) as never); + try { + mockTelemetry(); + mock?.(); + process.argv = ["node", "cli.ts", ...argv, ...(argv[0] === "--json" ? [] : ["--json"])]; + await import("./cli.js"); - const said = errorSpy.mock.calls.map((call) => call.map(String).join(" ")).join("\n"); - expect(said).toContain(given.replace("\u0007", "\\x07")); - expect(said).not.toContain("\u0007"); - const body = JSON.parse(answered.trim().split("\n").at(-1) ?? "") as { - ok: boolean; - error: { message: string }; - }; - expect(body.ok).toBe(false); - expect(process.exitCode).toBe(exit); - expect(body.error.message).toContain(given); - expect(body.error.message).not.toContain("\\x07"); - } finally { - outSpy.mockRestore(); - errorSpy.mockRestore(); - exitSpy.mockRestore(); - } - }); + const said = + errorSpy.mock.calls.map((call) => call.map(String).join(" ")).join("\n") + written; + expect(said).toContain(given.replace("\u0007", "\\x07")); + expect(said).not.toContain("\u0007"); + const body = JSON.parse(answered.trim().split("\n").at(-1) ?? "") as { + ok: boolean; + error: { message: string }; + }; + expect(body.ok).toBe(false); + expect(process.exitCode).toBe(exit); + expect(body.error.message).toContain(given); + expect(body.error.message).not.toContain("\\x07"); + } finally { + errSpy.mockRestore(); + outSpy.mockRestore(); + errorSpy.mockRestore(); + exitSpy.mockRestore(); + } + }, + ); it("exits 1 and scores a failure when the pipe closes before the run delivered", async () => { const trackCommandResult = vi.fn(); @@ -624,6 +697,11 @@ describe("stale-skills notice under --json", () => { }); const MOCKED_MODULES = [ + "./telemetry/config.js", + "./tts/synthesize.js", + "./registry/remote.js", + "./registry/resolver.js", + "./registry/localModel.js", "./commands/init.js", "./telemetry/events.js", "./telemetry/index.js", @@ -657,6 +735,28 @@ async function runCli(args: string[]): Promise[]> { return sent; } +/** A one-item registry searched by words, or one that cannot be read for the given reason. */ +function mockCatalogRegistry(unreadable?: string): void { + vi.doMock("./registry/remote.js", async () => ({ + ...(await vi.importActual("./registry/remote.js")), + readRegistryManifest: async () => { + if (unreadable) throw new Error(unreadable); + return { items: [{ name: "fade", type: "hyperframes:block" }] }; + }, + })); + vi.doMock("./registry/resolver.js", () => ({ + loadAllItems: async () => [ + { name: "fade", type: "hyperframes:block", title: "Fade", description: "A fade", tags: [] }, + ], + })); + vi.doMock("./registry/localModel.js", async () => ({ + ...(await vi.importActual( + "./registry/localModel.js", + )), + localModelStatus: () => ({ status: "declined" }), + })); +} + function mockRenderCommand(run: () => void | Promise): void { vi.doMock("./commands/render.js", () => ({ default: { meta: { name: "render" }, args: {}, run }, diff --git a/packages/cli/src/commands/add.test.ts b/packages/cli/src/commands/add.test.ts index 98fba9b5d8..ff9e4c9c3f 100644 --- a/packages/cli/src/commands/add.test.ts +++ b/packages/cli/src/commands/add.test.ts @@ -633,6 +633,25 @@ describe("add command run() — several names", () => { expect(printed).toContain("is deprecated: gone\\x1b]52;c;cA==\\x07"); }); + // fails without the fix: a name the registry does not have is repeated as it was typed. + it("shows control characters in a skipped name as text", async () => { + const esc = String.fromCharCode(27); + const log = vi.spyOn(console, "log").mockImplementation(() => {}); + + await expect( + runWrapped(["my-block", `no-${esc}[2Jsuch\x07`, "--dir", dir, "--no-clipboard"]), + ).rejects.toMatchObject({ result: { exitCode: 1 } }); + + const printed = log.mock.calls + .map((call) => call.join(" ")) + .join("\n") + .replace(new RegExp(`${esc}\\[[0-9;]*m`, "g"), ""); + expect(printed).toContain("✓ my-block"); + expect(printed).toContain("✗ no-\\x1b[2Jsuch\\x07 (skipped: "); + expect(printed).not.toContain(esc); + expect(printed).not.toContain("\x07"); + }); + it("keeps the installs that worked when one name is unknown, and fails the call", async () => { const log = vi.spyOn(console, "log").mockImplementation(() => {}); diff --git a/packages/cli/src/commands/add.ts b/packages/cli/src/commands/add.ts index 9c977c14ef..c151211b39 100644 --- a/packages/cli/src/commands/add.ts +++ b/packages/cli/src/commands/add.ts @@ -208,12 +208,13 @@ async function installOne(name: string, context: InstallContext): Promise { }); }); +describe("catalog lines that repeat outside text", () => { + const ODD = `od${String.fromCharCode(27)}[2Jd\x07`; + const SHOWN = "od\\x1b[2Jd\\x07"; + + // fails without the fix: an item's name is printed as the registry sent it. + it("shows control characters in an item name as text", async () => { + state.registry = [block(`count-${ODD}`)]; + + const output = await runCatalog({}); + + expect(output).toContain(`count-${SHOWN}`); + expect(output).not.toContain("\x07"); + }); + + // fails without the fix: the query is repeated as it was typed. + it("shows control characters in a query that matched nothing as text", async () => { + state.ranking = []; + state.modelStatus = "declined"; + + const { err } = await runForExit({ query: `quantum ${ODD}` }); + + expect(err).toContain(`No items match query "quantum ${SHOWN}".`); + expect(err).not.toContain("\x07"); + }); + + // fails without the fix: the query is repeated as it was typed. + it("shows control characters in a query with no searchable words as text", async () => { + state.modelStatus = "declined"; + state.ranking = null; + + const { err } = await runForExit({ query: "実写\x07写真" }); + + expect(err).toContain('No searchable words in query "実写\\x07写真".'); + expect(err).not.toContain("\x07"); + }); +}); + describe("catalog --json meaning search", () => { it("reports the registry moves meaning search cannot see", async () => { // Published after the user's artifact was fetched: in the registry, absent @@ -684,6 +721,25 @@ describe("catalog meaning search, on a terminal", () => { expect(output).toContain("--tier words"); }); + // fails without the fix: the command was printed with the query rewritten, so pasting it reported other text. + it.each([ + ["some results", "count\nup"], + ["no result", "zzqx\nyyqx"], + ])( + "explains the gap report in words when the query cannot be shown as typed: %s", + async (_n, query) => { + state.modelStatus = "declined"; + state.ranking = null; + + const output = await runCatalog({ query }); + + expect(output).toContain( + "Run hyperframes feedback with your query as --search-miss, the move you needed as --wanted, and --tier words.", + ); + expect(output).not.toContain('--search-miss "'); + }, + ); + it("offers the gap report on the on-device tier too", async () => { const output = await runCatalog({ query: "make a number count up" }); diff --git a/packages/cli/src/commands/catalog.ts b/packages/cli/src/commands/catalog.ts index 8c50d4f302..2ae973178a 100644 --- a/packages/cli/src/commands/catalog.ts +++ b/packages/cli/src/commands/catalog.ts @@ -11,13 +11,20 @@ export const examples: Example[] = [ ]; import * as clack from "../ui/prompts.js"; -import { realpath, terminalText, type ItemType, type RegistryItem } from "@hyperframes/core"; +import { + realpath, + terminalLines, + terminalText, + type ItemType, + type RegistryItem, +} from "@hyperframes/core"; import { c } from "../ui/colors.js"; import { loadAllItems } from "../registry/resolver.js"; import { readRegistryManifest } from "../registry/remote.js"; import { loadProjectConfig, DEFAULT_PROJECT_CONFIG } from "../utils/projectConfig.js"; import { relative, resolve } from "node:path"; import { CliUsageError, finishCommand } from "../utils/commandResult.js"; +import { printFailureLine } from "../utils/jsonError.js"; import { isUnattended } from "../utils/attendedTerminal.js"; import { runAdd } from "./add.js"; import { hasNoSearchableTokens, searchByWords } from "../registry/localSearch.js"; @@ -66,7 +73,7 @@ async function prepareOnDeviceTier(opts: { const warnings: string[] = []; const warn = (message: string): void => { warnings.push(message); - console.error(message); + console.error(terminalLines(message)); }; const status = opts.status; @@ -233,7 +240,7 @@ export default defineCommand({ // Asked for the whole manifest on purpose: its item list defines coverage, // and its artifact revision is the one owner of vector freshness. const manifest = await readRegistryManifest(config.registry).catch((error: unknown) => { - console.error(terminalText(error instanceof Error ? error.message : String(error))); + printFailureLine((show) => show(error instanceof Error ? error.message : String(error))); return finishCommand(1); }); const entries = manifest.items; @@ -313,7 +320,7 @@ export default defineCommand({ : null; if (tierHint) { warnings.push(tierHint); - console.error(tierHint); + console.error(terminalLines(tierHint)); } // An empty result is exactly when the tier matters most: nothing found on // the weakest tier means something different from nothing found on the @@ -353,7 +360,9 @@ export default defineCommand({ args.tag ? `tag "${args.tag}"` : null, ].filter(Boolean); if (unsearchable) { - console.error(c.error(`No searchable words in query "${query}".`)); + printFailureLine((show) => + c.error(`No searchable words in query "${show(String(query))}".`), + ); console.error(""); console.error( c.warn( @@ -364,13 +373,13 @@ export default defineCommand({ ), ); } else { - console.log(`No items match ${criteria.join(" and ")}.`); + console.log(`No items match ${terminalText(criteria.join(" and "))}.`); // Zero results is the unambiguous case: no tier judgement to make and // nothing to install, so name the gap channel outright. if (query) { console.log(""); console.log(c.dim(" Nothing in the catalog does this? Report the gap:")); - console.log(c.dim(` ${searchMissCommand(query, tierToken(searched))}`)); + console.log(c.dim(` ${searchMissHint(query, tierToken(searched))}`)); } } } @@ -449,7 +458,7 @@ export default defineCommand({ // reads as the tool arguing with itself. if (warnings.length === 0) { const hint = localModelHint(json, effectiveStatus); - if (hint) console.error(hint); + if (hint) console.error(terminalLines(hint)); await offerLocalModel(matching.length, json, config.registry, artifactRevision); } } @@ -462,9 +471,7 @@ export default defineCommand({ // in. Every catalog gap reported to date came from the word tier. The // tier rides along in the command so a vocabulary miss stays // distinguishable from a meaning miss when the reports are read. - console.log( - c.dim(` None of these do it? ${searchMissCommand(query, tierToken(searched))}`), - ); + console.log(c.dim(` None of these do it? ${searchMissHint(query, tierToken(searched))}`)); } } @@ -495,7 +502,9 @@ export default defineCommand({ console.warn(c.warn(`Warning: ${terminalText(warning)}`)); } console.log(""); - console.log(`${c.success("✓")} Installed ${c.accent(result.name)} (${result.type})`); + console.log( + `${c.success("✓")} Installed ${c.accent(terminalText(result.name))} (${terminalText(result.type)})`, + ); const root = realpath(dir); for (const file of result.written) { console.log(` ${c.dim(terminalText(relative(root, file)))}`); @@ -519,7 +528,7 @@ export default defineCommand({ const type = item.type.replace("hyperframes:", ""); const tags = item.tags?.length ? c.dim(` [${terminalText(item.tags.join(", "))}]`) : ""; console.log( - `${c.cyan(item.name.padEnd(NAME_COL))}${type.padEnd(TYPE_COL)}${terminalText(item.description)}${tags}`, + `${c.cyan(terminalText(item.name).padEnd(NAME_COL))}${terminalText(type).padEnd(TYPE_COL)}${terminalText(item.description)}${tags}`, ); } @@ -657,7 +666,7 @@ async function applySearch< // not run is indistinguishable from one that ran badly. const warning = `on-device search did not run: ${error instanceof Error ? error.message : "unknown error"}`; warnings.push(warning); - console.error(warning); + console.error(terminalLines(warning)); } } @@ -714,6 +723,12 @@ export function searchMissCommand(query: string, tier: "on-device" | "words"): s ); } +function searchMissHint(query: string, tier: "on-device" | "words"): string { + const command = searchMissCommand(query, tier); + if (terminalText(command) === command) return command; + return `Run hyperframes feedback with your query as --search-miss, the move you needed as --wanted, and --tier ${tier}.`; +} + type LocalMode = "local-model" | "words"; /** diff --git a/packages/cli/src/commands/clean.test.ts b/packages/cli/src/commands/clean.test.ts index 5111a10f7b..7b35a94480 100644 --- a/packages/cli/src/commands/clean.test.ts +++ b/packages/cli/src/commands/clean.test.ts @@ -20,13 +20,13 @@ import { createOwnedRenderDir } from "@hyperframes/producer"; import { consumeCommandResult } from "../utils/commandResult.js"; import cleanCommand, { cleanLeftovers } from "./clean.js"; -const history = vi.hoisted(() => ({ unreadable: false })); +const history = vi.hoisted(() => ({ unreadable: false, message: "history unreadable" })); vi.mock("@hyperframes/studio-server", async (importOriginal) => { const actual = await importOriginal(); return { ...actual, listProjectHistories: (root: string) => { - if (history.unreadable) throw new Error("history unreadable"); + if (history.unreadable) throw new Error(history.message); return actual.listProjectHistories(root); }, }; @@ -193,6 +193,49 @@ describe("cleanLeftovers", () => { } }); + // fails without the fix: the reason is printed as it arrived. + it("shows control characters in a failure line as text", async () => { + const esc = String.fromCharCode(27); + history.unreadable = true; + history.message = `history od${esc}[2Jd\x07`; + const log = vi.spyOn(console, "log").mockImplementation(() => {}); + try { + await runCommand(cleanCommand, { rawArgs: [project, "--dry-run"] }); + const printed = log.mock.calls.map((call) => call.join(" ")).join("\n"); + expect(printed).toContain("history od\\x1b[2Jd\\x07"); + expect(printed.replace(new RegExp(`${esc}\\[[0-9;]*m`, "g"), "")).not.toContain(esc); + expect(printed).not.toContain("\x07"); + expect(consumeCommandResult().exitCode).toBe(1); + } finally { + history.unreadable = false; + history.message = "history unreadable"; + log.mockRestore(); + } + }); + + // fails without the fix: a leftover's path is printed as it is on disk. + it.skipIf(process.platform === "win32")( + "shows control characters in a listed path as text", + async () => { + const esc = String.fromCharCode(27); + const odd = join(scratch, `pr-${esc}[2Jd\x07`); + mkdirSync(odd); + writeFileSync(join(odd, "index.html"), '
'); + plant(odd, "snapshots"); + const log = vi.spyOn(console, "log").mockImplementation(() => {}); + try { + await runCommand(cleanCommand, { rawArgs: [odd, "--dry-run"] }); + const printed = log.mock.calls.map((call) => call.join(" ")).join("\n"); + expect(printed).toContain("pr-\\x1b[2Jd\\x07"); + expect(printed.replace(new RegExp(`${esc}\\[[0-9;]*m`, "g"), "")).not.toContain(esc); + expect(printed).not.toContain("\x07"); + } finally { + consumeCommandResult(); + log.mockRestore(); + } + }, + ); + it("lists snapshots as reclaimable and removes them only when asked", async () => { const snapshots = plant(project, "snapshots"); diff --git a/packages/cli/src/commands/clean.ts b/packages/cli/src/commands/clean.ts index 20d7fffd74..dfd89dcbcc 100644 --- a/packages/cli/src/commands/clean.ts +++ b/packages/cli/src/commands/clean.ts @@ -1,3 +1,4 @@ +import { terminalLines, terminalText } from "@hyperframes/core"; import { existsSync, readFileSync, realpathSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; import { isAbsolute, join, relative, resolve } from "node:path"; @@ -242,7 +243,7 @@ function printTable(rows: Leftover[]): void { const whatWidth = Math.max(...rows.map((row) => row.what.length)); for (const row of rows) { console.log( - ` ${row.what.padEnd(whatWidth)} ${formatBytes(row.bytes).padStart(9)} ${c.dim(row.path)}`, + ` ${row.what.padEnd(whatWidth)} ${formatBytes(row.bytes).padStart(9)} ${c.dim(terminalText(row.path))}`, ); } } @@ -304,6 +305,6 @@ export default defineCommand({ ); printTable(result.alsoReclaimable); } - for (const error of result.errors) console.log(c.warn(` ${error}`)); + for (const error of result.errors) console.log(c.warn(` ${terminalLines(error)}`)); }, }); diff --git a/packages/cli/src/commands/compare.ts b/packages/cli/src/commands/compare.ts index d0a4611344..e396176c1d 100644 --- a/packages/cli/src/commands/compare.ts +++ b/packages/cli/src/commands/compare.ts @@ -1,3 +1,4 @@ +import { terminalLines, terminalText } from "@hyperframes/core"; import { existsSync, mkdtempSync, realpathSync, renameSync, rmSync, statSync } from "node:fs"; import { makeOutputFolder } from "../utils/outputFolder.js"; import { tmpdir } from "node:os"; @@ -217,7 +218,7 @@ function stageHtmlVariant(variant: CompareVariantSpec): PreparedCompareVariant { `compare ${variant.displayPath}`, stageReferencedFiles(dirname(source), [source], stagedDir), ); - if (notice) console.warn(c.dim(notice)); + if (notice) console.warn(c.dim(terminalLines(notice))); const sourceName = basename(source); if (sourceName !== "index.html") { renameSync(join(stagedDir, sourceName), join(stagedDir, "index.html")); @@ -410,7 +411,9 @@ export default defineCommand({ if (parsed.json) { printJson(payload); } else { - console.log(`\n${c.success("◇")} Comparison sheet saved to ${payload.sheet}`); + console.log( + `\n${c.success("◇")} Comparison sheet saved to ${terminalText(payload.sheet)}`, + ); } } catch (err) { failCaught(err, jsonRequested, (m) => `\n${c.error("✗")} Compare failed: ${m}`, printJson); diff --git a/packages/cli/src/commands/diff.test.ts b/packages/cli/src/commands/diff.test.ts index 810886d21b..14984947e2 100644 --- a/packages/cli/src/commands/diff.test.ts +++ b/packages/cli/src/commands/diff.test.ts @@ -37,4 +37,50 @@ describe("diff command terminal output", () => { expect(text).not.toContain(control); } }); + + // fails without the fix: ids, notes, warnings and paths in the result are printed as they arrived. + it("prints a result with control characters as visible escapes", async () => { + const odd = "od\u001b[2Jd\u0007"; + const shown = "od\\x1b[2Jd\\x07"; + const { diffVideos } = await import("../measure/diff.js"); + vi.mocked(diffVideos).mockResolvedValueOnce({ + pass: true, + ssim: { mean: 1, p05: 1, cell_p05: 1, frames: 2 }, + window: [0, 1], + missing_content: { pass: true, share: 0, spans: [], texture: { share: 0, spans: [] } }, + worst: [], + duration: { reference: 1, yours: 1, pass: null, note: `note ${odd}` }, + frames: `frames ${odd}`, + segments: [{ id: `seg ${odd}`, pass: null, window: [0, 1], pixels: "kept", note: odd }], + drawn: [{ id: `box ${odd}`, pass: null, box: [0, 0, 1, 1], window: [0, 1] }], + layer: { selector: `#layer-${odd}`, benefit_median: 1, frames: [] }, + warnings: [`careful ${odd}\nsecond line`], + sheet: `/out/${odd}/sheet.png`, + sbs: `/out/${odd}/sbs.mp4`, + } as never); + const printed: string[] = []; + vi.spyOn(console, "log").mockImplementation((...args: unknown[]) => { + printed.push(args.map(String).join(" ")); + }); + vi.spyOn(process, "exit").mockImplementation(() => undefined as never); + const { default: diff } = await import("./diff.js"); + + await runCommand(diff, { rawArgs: ["original.mp4", "yours.mp4"] }); + + const text = printed.join("\n"); + for (const line of [ + `(note ${shown})`, + `every frame: frames ${shown}`, + `seg ${shown} 0–1 s kept: ${shown}`, + `box ${shown} 0,0,1,1`, + `layer #layer-${shown}:`, + `careful ${shown}\nsecond line`, + `sheet /out/${shown}/sheet.png`, + `side by side /out/${shown}/sbs.mp4`, + ]) { + expect(text).toContain(line); + } + expect(text).not.toContain("\u001b[2J"); + expect(text).not.toContain("\u0007"); + }); }); diff --git a/packages/cli/src/commands/diff.ts b/packages/cli/src/commands/diff.ts index b3824e9b41..9a93dd65f7 100644 --- a/packages/cli/src/commands/diff.ts +++ b/packages/cli/src/commands/diff.ts @@ -1,4 +1,4 @@ -import { terminalLines } from "@hyperframes/core"; +import { terminalLines, terminalText } from "@hyperframes/core"; import { basename, extname, join, resolve } from "node:path"; import { defineCommand } from "../utils/defineCommand.js"; import type { Example } from "./_examples.js"; @@ -104,11 +104,11 @@ function printHuman(r: DiffResult) { ); if (r.duration) console.log( - ` duration: original ${r.duration.reference} s, yours ${r.duration.yours} s${r.duration.pass === null ? ` (${r.duration.note})` : r.duration.pass ? "" : " (differ)"}`, + ` duration: original ${r.duration.reference} s, yours ${r.duration.yours} s${r.duration.pass === null ? ` (${terminalText(String(r.duration.note))})` : r.duration.pass ? "" : " (differ)"}`, ); if (r.sound) console.log( - ` sound: ${"offset_ms" in r.sound ? (r.sound.offset_ms === null ? (r.sound.note ?? "not aligned") : `${r.sound.offset_ms} ms off`) : `original ${r.sound.original ? "has" : "has no"} sound, yours ${r.sound.yours ? "has" : "has no"}`}${r.sound.pass ? "" : " (fails)"}`, + ` sound: ${"offset_ms" in r.sound ? (r.sound.offset_ms === null ? terminalText(r.sound.note ?? "not aligned") : `${r.sound.offset_ms} ms off`) : `original ${r.sound.original ? "has" : "has no"} sound, yours ${r.sound.yours ? "has" : "has no"}`}${r.sound.pass ? "" : " (fails)"}`, ); if (r.components) console.log( @@ -122,7 +122,7 @@ function printHuman(r: DiffResult) { ` person: framing ${mark(g.framing, r.person.failed.framing)}, text in the clip ${mark(g.text, r.person.failed.text)}, lips ${mark(g.sync, r.person.failed.sync)}; reported: motion ×${r.person.energy ?? "?"}, ${r.person.shots_at_cuts.at_cuts} of ${r.person.shots_at_cuts.total} clips start at a cut${r.person.shots_at_cuts.cuts_without_shot.length ? `, no new clip at ${r.person.shots_at_cuts.cuts_without_shot.join(", ")} s` : ""}`, ); } - console.log(` every frame: ${r.frames}`); + console.log(` every frame: ${terminalText(String(r.frames))}`); for (const s of r.segments ?? []) { const state = s.pass === null ? c.dim("—") : s.pass ? c.success("✓") : c.error("✗"); const detail = @@ -136,7 +136,7 @@ function printHuman(r: DiffResult) { (s.note ?? ""); const region = s.regenerated ? `; person in ${s.regenerated.roi.join(",")}` : ""; console.log( - ` ${state} ${s.id} ${s.window[0]}–${s.window[1]} s ${s.pixels}${s.regenerated ? " outside the region" : ""}: ${detail}${region}`, + ` ${state} ${terminalText(s.id)} ${s.window[0]}–${s.window[1]} s ${s.pixels}${s.regenerated ? " outside the region" : ""}: ${terminalText(detail)}${region}`, ); } for (const d of r.drawn ?? []) { @@ -146,12 +146,12 @@ function printHuman(r: DiffResult) { ? "no ink found in the box (crop it tight around the letters)" : `score ${d.score} / p05 ${d.p05}, off by ${d.offset!.join(",")} px${d.ink === undefined ? "" : `, ink ×${d.ink}`}`; console.log( - ` ${state} ${d.id} ${d.box.join(",")} ${d.window[0]}–${d.window[1]} s: ${detail}`, + ` ${state} ${terminalText(d.id)} ${d.box.join(",")} ${d.window[0]}–${d.window[1]} s: ${detail}`, ); } if (r.layer) console.log( - ` layer ${r.layer.selector}: benefit median ${r.layer.benefit_median ?? "—"} (1 matches the original, 0 is no better than without it)`, + ` layer ${terminalText(r.layer.selector)}: benefit median ${r.layer.benefit_median ?? "—"} (1 matches the original, 0 is no better than without it)`, ); for (const f of r.layer?.frames ?? []) { const state = @@ -166,11 +166,11 @@ function printHuman(r: DiffResult) { : f.benefit === null ? f.note : `benefit ${f.benefit}, ${f.instruction} (box ${f.bbox!.join(",")})`; - console.log(` ${state} ${f.t} s: ${detail}`); + console.log(` ${state} ${f.t} s: ${terminalText(String(detail))}`); } - for (const w of r.warnings) console.log(` ${c.warn("⚠")} ${w}`); - if (r.sheet) console.log(` sheet ${r.sheet}`); - if (r.sbs) console.log(` side by side ${r.sbs}`); + for (const w of r.warnings) console.log(` ${c.warn("⚠")} ${terminalLines(w)}`); + if (r.sheet) console.log(` sheet ${terminalText(r.sheet)}`); + if (r.sbs) console.log(` side by side ${terminalText(r.sbs)}`); } export default defineCommand({ @@ -281,7 +281,7 @@ export default defineCommand({ sbs: args.sbs === true, outDir: outDir(args.out, join("diff", stem)), timeoutMs: number(args.timeout, "--timeout"), - log: (message) => console.error(message), + log: (message) => console.error(terminalLines(message)), }); if (json) console.log(formatJson(withMeta({ ok: true, ...result }))); else printHuman(result); diff --git a/packages/cli/src/commands/docs.output.test.ts b/packages/cli/src/commands/docs.output.test.ts new file mode 100644 index 0000000000..337c2286db --- /dev/null +++ b/packages/cli/src/commands/docs.output.test.ts @@ -0,0 +1,29 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { consumeCommandResult } from "../utils/commandResult.js"; +import docsCommand from "./docs.js"; + +const ESC = String.fromCharCode(27); +const ODD = `od${ESC}[2Jd\x07`; +const SHOWN = "od\\x1b[2Jd\\x07"; + +afterEach(() => { + consumeCommandResult(); + vi.restoreAllMocks(); +}); + +describe("docs output for people", () => { + // fails without the fix: the topic is repeated as it was typed. + it("shows control characters in an unknown topic as text", async () => { + const said: string[] = []; + vi.spyOn(console, "error").mockImplementation((...args: unknown[]) => { + said.push(args.join(" ")); + }); + await expect( + Promise.resolve( + docsCommand.run?.({ args: { topic: ODD }, rawArgs: [], cmd: docsCommand } as never), + ), + ).rejects.toThrow(); + expect(said.join("\n")).toContain(`Unknown topic: ${SHOWN}`); + expect(said.join("\n")).not.toContain("\x07"); + }); +}); diff --git a/packages/cli/src/commands/docs.ts b/packages/cli/src/commands/docs.ts index ae66c23fce..3c2d5c05e8 100644 --- a/packages/cli/src/commands/docs.ts +++ b/packages/cli/src/commands/docs.ts @@ -1,4 +1,5 @@ import { failCommand, failUsage } from "../utils/commandResult.js"; +import { printFailureLine } from "../utils/jsonError.js"; import { defineCommand } from "../utils/defineCommand.js"; import type { Example } from "./_examples.js"; import { readFileSync, existsSync } from "node:fs"; @@ -134,7 +135,7 @@ export default defineCommand({ // Look up the topic const entry = TOPICS[topic]; if (entry === undefined) { - console.error(c.error(`Unknown topic: ${topic}`)); + printFailureLine((show) => c.error(`Unknown topic: ${show(topic)}`)); console.error(); console.error("Available topics:"); for (const name of Object.keys(TOPICS)) { @@ -145,7 +146,7 @@ export default defineCommand({ const filePath = join(docsDir(), entry.file); if (!existsSync(filePath)) { - console.error(c.error(`Doc file not found: ${filePath}`)); + printFailureLine((show) => c.error(`Doc file not found: ${show(filePath)}`)); failCommand(); } diff --git a/packages/cli/src/commands/doctor.output.test.ts b/packages/cli/src/commands/doctor.output.test.ts new file mode 100644 index 0000000000..fd69a7cd99 --- /dev/null +++ b/packages/cli/src/commands/doctor.output.test.ts @@ -0,0 +1,48 @@ +import { afterEach, 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"; + +vi.mock("../browser/preflight.js", async (importOriginal) => ({ + ...(await importOriginal()), + runEnvironmentChecks: async () => ({ + outcomes: [ + { + name: `Tool ${ODD}`, + ok: false, + level: "error", + detail: `not found at ${ODD}\nsecond line`, + hint: `install ${ODD}`, + }, + ], + }), +})); + +const { default: doctorCommand } = await import("./doctor.js"); + +afterEach(() => { + consumeCommandResult(); + vi.restoreAllMocks(); +}); + +describe("doctor output", () => { + // fails without the fix: a check's name, detail and hint are printed as the check returned them. + it("shows control characters in a check row as text", async () => { + const said: string[] = []; + vi.spyOn(console, "log").mockImplementation((...args: unknown[]) => { + said.push(args.join(" ")); + }); + vi.spyOn(console, "error").mockImplementation(() => {}); + await Promise.resolve( + doctorCommand.run?.({ args: { json: false }, rawArgs: [], cmd: doctorCommand } as never), + ).catch(() => undefined); + const text = said.join("\n").replace(new RegExp(`${ESC}\\[[0-9;]*m`, "g"), ""); + expect(text).toContain(`Tool ${SHOWN}`); + expect(text).toContain(`not found at ${SHOWN}\nsecond line`); + expect(text).toContain(`install ${SHOWN}`); + expect(text).not.toContain(ESC); + expect(text).not.toContain("\x07"); + }); +}); diff --git a/packages/cli/src/commands/doctor.ts b/packages/cli/src/commands/doctor.ts index feb687f953..9c301f0d7b 100644 --- a/packages/cli/src/commands/doctor.ts +++ b/packages/cli/src/commands/doctor.ts @@ -1,3 +1,4 @@ +import { terminalLines, terminalText } from "@hyperframes/core"; // fallow-ignore-file complexity import { defineCommand } from "../utils/defineCommand.js"; import { execFileSync, type ExecFileSyncOptions } from "node:child_process"; @@ -484,12 +485,12 @@ export default defineCommand({ for (const outcome of outcomes) { const icon = outcome.ok ? c.success("\u2713") : c.error("\u2717"); - const name = outcome.name.padEnd(16); + const name = terminalText(outcome.name).padEnd(16); console.log( - ` ${icon} ${c.bold(name)} ${outcome.ok ? c.dim(outcome.detail) : c.error(outcome.detail)}`, + ` ${icon} ${c.bold(name)} ${outcome.ok ? c.dim(terminalLines(outcome.detail)) : c.error(terminalLines(outcome.detail))}`, ); if (!outcome.ok && outcome.hint) { - console.log(` ${" ".repeat(19)}${c.accent(outcome.hint)}`); + console.log(` ${" ".repeat(19)}${c.accent(terminalLines(outcome.hint))}`); } } diff --git a/packages/cli/src/commands/grade-compare.test.ts b/packages/cli/src/commands/grade-compare.test.ts index 85c4a1b871..fc61a771fe 100644 --- a/packages/cli/src/commands/grade-compare.test.ts +++ b/packages/cli/src/commands/grade-compare.test.ts @@ -324,6 +324,23 @@ describe("warnInactiveGradingCells", () => { }); }); +describe("warnInactiveGradingCells output", () => { + // fails without the fix: the label is printed as the grades file had it. + it("shows control characters in a label as text", () => { + const esc = String.fromCharCode(27); + const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {}); + try { + warnInactiveGradingCells([{ label: `od${esc}[2Jd\x07`, grading: { lut: 12345 } }]); + expect(errorSpy).toHaveBeenCalledWith( + expect.stringContaining('Warning: grading for "od\\x1b[2Jd\\x07" is inactive/no-op'), + ); + expect(errorSpy).not.toHaveBeenCalledWith(expect.stringContaining("\x07")); + } finally { + vi.restoreAllMocks(); + } + }); +}); + describe("capCandidateCells", () => { it("truncates over-cap candidates and exposes truncation metadata for JSON output", () => { const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {}); diff --git a/packages/cli/src/commands/grade-compare.ts b/packages/cli/src/commands/grade-compare.ts index ddf06b014e..3364c59aae 100644 --- a/packages/cli/src/commands/grade-compare.ts +++ b/packages/cli/src/commands/grade-compare.ts @@ -17,6 +17,7 @@ import { normalizeHfColorGrading, parseCubeLut, serializeHfColorGrading, + terminalText, } from "@hyperframes/core"; import { gsapCdnDist } from "@hyperframes/core/gsap-cdn"; import { defineCommand } from "../utils/defineCommand.js"; @@ -148,7 +149,9 @@ export function warnInactiveGradingCells(cells: readonly GradeCompareCell[]): vo const normalized = normalizeHfColorGrading(cell.grading); if (!isHfColorGradingActive(normalized)) { console.error( - c.warn(`Warning: grading for "${cell.label}" is inactive/no-op — it will render ungraded`), + c.warn( + `Warning: grading for "${terminalText(cell.label)}" is inactive/no-op — it will render ungraded`, + ), ); } } @@ -654,7 +657,7 @@ export default defineCommand({ if (!parsed.json) { console.log( - `${c.accent("◆")} Rendering ${cells.length} grade candidates from ${c.accent(basename(parsed.framePath))}`, + `${c.accent("◆")} Rendering ${cells.length} grade candidates from ${c.accent(terminalText(basename(parsed.framePath)))}`, ); } @@ -688,7 +691,7 @@ export default defineCommand({ if (parsed.json) { printJson(buildGradeCompareSuccessPayload(sheet, prepared.cells.length, capResult)); } else { - console.log(`\n${c.success("◇")} Grade comparison saved to ${sheet}`); + console.log(`\n${c.success("◇")} Grade comparison saved to ${terminalText(sheet)}`); } } catch (err) { failCaught( diff --git a/packages/cli/src/commands/media-treatment.test.ts b/packages/cli/src/commands/media-treatment.test.ts index 11593f1fe8..209b95b9e3 100644 --- a/packages/cli/src/commands/media-treatment.test.ts +++ b/packages/cli/src/commands/media-treatment.test.ts @@ -697,6 +697,28 @@ describe("applyMediaTreatmentToHtml", () => { } }); + // fails without the fix: the selector is repeated as it was typed. + it("shows control characters in the selector of a preview as text", async () => { + const esc = String.fromCharCode(27); + const project = mkdtempSync(join(tmpdir(), "hf-media-odd-")); + const log = vi.spyOn(console, "log").mockImplementation(() => undefined); + writeFileSync(join(project, "index.html"), VIDEO); + const selector = `#hero:not([title="od${esc}[2Jd\x07"])`; + const grading = '{"preset":"warm-daylight","intensity":0.8}'; + try { + await runCommand(mediaTreatmentCommand, { + rawArgs: ["--project", project, "--selector", selector, "--grading", grading, "--dry-run"], + }); + const printed = log.mock.calls.map((call) => call.join(" ")).join("\n"); + expect(printed).toContain('#hero:not([title="od\\x1b[2Jd\\x07"])'); + expect(printed).not.toContain(`${esc}[2J`); + expect(printed).not.toContain("\x07"); + } finally { + log.mockRestore(); + rmSync(project, { recursive: true, force: true }); + } + }); + it("takes --grading from a file, and tells a quote-stripped value to use one", async () => { const project = mkdtempSync(join(tmpdir(), "hf-media-grading-file-")); writeFileSync(join(project, "index.html"), VIDEO); diff --git a/packages/cli/src/commands/media-treatment.ts b/packages/cli/src/commands/media-treatment.ts index 1c6d498165..42d833156d 100644 --- a/packages/cli/src/commands/media-treatment.ts +++ b/packages/cli/src/commands/media-treatment.ts @@ -10,6 +10,7 @@ import { normalizeHfColorGrading, serializeHfColorGrading, terminalLines, + terminalText, } from "@hyperframes/core"; import { COLOR_GRADING_SOURCE_TAGS, @@ -779,10 +780,10 @@ function printAnalysis(args: MediaTreatmentCommandArgs): void { console.log(JSON.stringify(withMeta(result), null, 2)); return; } - console.log(`${c.success("◇")} Analyzed ${c.accent(result.selector)}`); - for (const diagnosis of result.diagnosis) console.log(` ${diagnosis}`); - for (const warning of result.warnings) console.log(` ${c.warn(warning)}`); - console.log(` suggested patch: ${JSON.stringify(result.suggestedPatch)}`); + console.log(`${c.success("◇")} Analyzed ${c.accent(terminalText(result.selector))}`); + for (const diagnosis of result.diagnosis) console.log(` ${terminalLines(diagnosis)}`); + for (const warning of result.warnings) console.log(` ${c.warn(terminalLines(warning))}`); + console.log(` suggested patch: ${terminalText(JSON.stringify(result.suggestedPatch))}`); } async function printMutation(args: MediaTreatmentCommandArgs): Promise { @@ -797,7 +798,9 @@ async function printMutation(args: MediaTreatmentCommandArgs): Promise { result.targets.length > 1 ? ` (${changedCount} of ${result.targets.length} elements ${payload.dryRun ? "would change" : "changed"})` : ""; - console.log(`${c.success("◇")} ${verb} media treatment on ${c.accent(selector)}${count}`); + console.log( + `${c.success("◇")} ${verb} media treatment on ${c.accent(terminalText(selector))}${count}`, + ); } function printFailure(error: unknown, json: boolean): void { diff --git a/packages/cli/src/commands/remove-background.output.test.ts b/packages/cli/src/commands/remove-background.output.test.ts new file mode 100644 index 0000000000..d6e49edda3 --- /dev/null +++ b/packages/cli/src/commands/remove-background.output.test.ts @@ -0,0 +1,95 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { DEFAULT_QUALITY } from "../background-removal/pipeline.js"; +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[], removeBackground: vi.fn() })); + +vi.mock("../api/removeBackground.js", () => ({ + RemoveBackgroundError: class extends Error {}, + removeBackground: fake.removeBackground, +})); +vi.mock("../ui/prompts.js", () => { + const say = (message: string) => void fake.lines.push(message); + return { spinner: () => ({ start: say, stop: say, message: say }) }; +}); + +const { default: removeBackgroundCommand } = await import("./remove-background.js"); + +const printed = (): string => + fake.lines.join("\n").replace(new RegExp(`${ESC}\\[[0-9;]*m`, "g"), ""); + +const run = (args: Record = {}): Promise => + Promise.resolve( + removeBackgroundCommand.run?.({ + args: { + input: "in.mp4", + output: "out.webm", + device: "cpu", + quality: DEFAULT_QUALITY, + ...args, + }, + rawArgs: [], + cmd: removeBackgroundCommand, + } as never), + ); + +beforeEach(() => { + fake.lines.length = 0; + fake.removeBackground.mockReset(); + for (const method of ["log", "error"] as const) + vi.spyOn(console, method).mockImplementation((...args: unknown[]) => { + fake.lines.push(args.join(" ")); + }); +}); + +afterEach(() => { + consumeCommandResult(); + vi.restoreAllMocks(); +}); + +describe("remove-background output for people", () => { + // fails without the fix: the refused value is repeated as it was typed. + it.each([ + [{ device: ODD }, `Invalid --device '${SHOWN}'.`], + [{ quality: ODD }, `Invalid --quality '${SHOWN}'.`], + ])("shows control characters in a refused %o as text", async (args, line) => { + await expect(run(args)).rejects.toThrow(); + expect(printed()).toContain(line); + expect(printed()).not.toContain(ESC); + }); + + // fails without the fix: the progress text and the saved paths are printed as they arrived. + it("shows control characters in the lines of a finished run as text", async () => { + fake.removeBackground.mockImplementation( + async (opts: { onProgress: (event: { kind: "info"; message: string }) => void }) => { + opts.onProgress({ kind: "info", message: `loading ${ODD}` }); + return { + outputPath: `/out/${ODD}.webm`, + backgroundOutputPath: `/out/bg-${ODD}.webm`, + framesProcessed: 2, + durationSeconds: 1, + avgMsPerFrame: 5, + provider: "CPU", + format: "webm", + }; + }, + ); + await run(); + expect(printed()).toContain(`loading ${SHOWN}`); + expect(printed()).toContain(`→ /out/${SHOWN}.webm + /out/bg-${SHOWN}.webm`); + expect(printed()).not.toContain(ESC); + expect(printed()).not.toContain("\x07"); + }); + + // fails without the fix: the failure reason is printed as it was thrown. + it("shows control characters in a failure as text", async () => { + fake.removeBackground.mockRejectedValue(new Error(`no frames ${ODD}\nsecond line`)); + await expect(run()).rejects.toThrow(); + expect(printed()).toContain(`Background removal failed: no frames ${SHOWN}\nsecond line`); + expect(printed()).not.toContain(ESC); + }); +}); diff --git a/packages/cli/src/commands/remove-background.ts b/packages/cli/src/commands/remove-background.ts index a4903da9d2..de68ec0e14 100644 --- a/packages/cli/src/commands/remove-background.ts +++ b/packages/cli/src/commands/remove-background.ts @@ -1,3 +1,4 @@ +import { terminalLines, terminalText } from "@hyperframes/core"; import { failCommand, failUsage } from "../utils/commandResult.js"; import { defineCommand } from "../utils/defineCommand.js"; import { existsSync } from "node:fs"; @@ -15,7 +16,7 @@ import { import { DEFAULT_QUALITY, QUALITIES, isQuality } from "../background-removal/pipeline.js"; import type { Example } from "./_examples.js"; import { RemoveBackgroundError, removeBackground } from "../api/removeBackground.js"; -import { failureMessage, jsonFailure } from "../utils/jsonError.js"; +import { failureMessage, jsonFailure, printFailureLine } from "../utils/jsonError.js"; export const examples: Example[] = [ [ @@ -110,14 +111,14 @@ export default defineCommand({ failUsage(); } if (!isDevice(args.device)) { - console.error( - c.error(`Invalid --device '${String(args.device)}'. Use: ${DEVICES.join(", ")}.`), + printFailureLine((show) => + c.error(`Invalid --device '${show(String(args.device))}'. Use: ${DEVICES.join(", ")}.`), ); failUsage(); } if (!isQuality(args.quality)) { - console.error( - c.error(`Invalid --quality '${String(args.quality)}'. Use: ${QUALITIES.join(", ")}.`), + printFailureLine((show) => + c.error(`Invalid --quality '${show(String(args.quality))}'. Use: ${QUALITIES.join(", ")}.`), ); failUsage(); } @@ -134,7 +135,7 @@ export default defineCommand({ quality: args.quality, onProgress: (event) => { if (event.kind === "info") { - spin?.message(event.message); + spin?.message(terminalText(event.message)); } else if (event.kind === "metadata") { const dims = `${event.width}×${event.height}`; const frames = event.frameCount ? ` · ${event.frameCount} frames` : ""; @@ -168,8 +169,8 @@ export default defineCommand({ ? (result.framesProcessed / result.durationSeconds).toFixed(1) : "n/a"; const outputs = result.backgroundOutputPath - ? `${c.accent(result.outputPath)} + ${c.accent(result.backgroundOutputPath)}` - : c.accent(result.outputPath); + ? `${c.accent(terminalText(result.outputPath))} + ${c.accent(terminalText(result.backgroundOutputPath))}` + : c.accent(terminalText(result.outputPath)); spin?.stop( c.success( `Removed background from ${c.accent(String(result.framesProcessed))} frames in ${result.durationSeconds.toFixed(1)}s (${fpsThroughput} fps, ${c.accent(result.provider)}) → ${outputs}`, @@ -181,7 +182,7 @@ export default defineCommand({ if (args.json) { console.log(JSON.stringify(jsonFailure("runtime_error", message))); } else { - spin?.stop(c.error(`Background removal failed: ${message}`)); + spin?.stop(c.error(`Background removal failed: ${terminalLines(message)}`)); } failCommand(1, pipelineError(err)); } @@ -219,7 +220,7 @@ async function showInfo(json: boolean): Promise { console.log( ` ${c.dim("Weights cached:")} ${cached ? c.success("yes") : c.dim("no (will download on first run)")}`, ); - console.log(` ${c.dim("Cache path:")} ${modelPath()}`); + console.log(` ${c.dim("Cache path:")} ${terminalText(modelPath())}`); console.log(""); console.log(` ${c.dim("Available providers:")} ${providers.join(", ")}`); console.log(` ${c.dim("Auto-selected:")} ${c.accent(auto.label)}`); diff --git a/packages/cli/src/commands/telemetry.test.ts b/packages/cli/src/commands/telemetry.test.ts index a574786b11..d08fb7c4c3 100644 --- a/packages/cli/src/commands/telemetry.test.ts +++ b/packages/cli/src/commands/telemetry.test.ts @@ -182,3 +182,43 @@ describe("telemetry command", () => { expect(output).toContain("telemetry_disabled_build"); }); }); + +describe("telemetry lines for people", () => { + const ESC = String.fromCharCode(27); + const ODD = `od${ESC}[2Jd\x07`; + const SHOWN = "od\\x1b[2Jd\\x07"; + + afterEach(() => { + vi.doUnmock("../telemetry/config.js"); + vi.doUnmock("../utils/env.js"); + vi.restoreAllMocks(); + vi.resetModules(); + }); + + function capture(): string[] { + const said: string[] = []; + vi.spyOn(console, "error").mockImplementation((...args: unknown[]) => { + said.push(args.map(String).join(" ")); + }); + return said; + } + + // fails without the fix: the word is repeated as it was typed. + it("shows control characters in an unknown subcommand as text", async () => { + const { command } = await loadTelemetryCommand(); + const said = capture(); + await expect(runSubcommand(command, ODD)).rejects.toThrow(); + expect(said.join("\n")).toContain(SHOWN); + expect(said.join("\n")).not.toContain("\x07"); + }); + + // fails without the fix: the reason the file could not be written is printed as it arrived. + it("shows control characters in a failed save as text", async () => { + const { command, writeConfigWithResult } = await loadTelemetryCommand(); + writeConfigWithResult.mockReturnValue({ ok: false, error: `EACCES ${ODD}` } as never); + const said = capture(); + await expect(runSubcommand(command, "disable")).rejects.toThrow(); + expect(said.join("\n")).toContain(`EACCES ${SHOWN}`); + expect(said.join("\n")).not.toContain("\x07"); + }); +}); diff --git a/packages/cli/src/commands/telemetry.ts b/packages/cli/src/commands/telemetry.ts index 68394d62d5..89194a19c4 100644 --- a/packages/cli/src/commands/telemetry.ts +++ b/packages/cli/src/commands/telemetry.ts @@ -1,3 +1,4 @@ +import { terminalText } from "@hyperframes/core"; import { defineCommand } from "../utils/defineCommand.js"; import { writeConfigWithResult, @@ -8,6 +9,7 @@ import { import { effectiveTelemetryStatus, type TelemetryStatusSource } from "../telemetry/policy.js"; import { c } from "../ui/colors.js"; import { CliUsageError, failCommand, failUsage } from "../utils/commandResult.js"; +import { printFailureLine } from "../utils/jsonError.js"; import type { Example } from "./_examples.js"; export const examples: Example[] = [ @@ -35,9 +37,10 @@ function setTelemetryEnabled(enabled: boolean): void { config.telemetryEnabled = enabled; const result = writeConfigWithResult(config); if (!result.ok) { - console.error( - `\n ${c.error("\u2717")} Could not persist telemetry preference to ${c.accent(CONFIG_PATH)}\n` + - ` ${c.dim("Reason:")} ${result.error}\n`, + printFailureLine( + (show) => + `\n ${c.error("\u2717")} Could not persist telemetry preference to ${c.accent(show(CONFIG_PATH))}\n` + + ` ${c.dim("Reason:")} ${show(String(result.error))}\n`, ); failCommand(); } @@ -75,10 +78,10 @@ function runStatus(json: boolean): void { console.log(); console.log(` ${c.dim("Status:")} ${status}`); console.log(` ${c.dim("Source:")} ${effective.source}`); - console.log(` ${c.dim("Config:")} ${c.accent(CONFIG_PATH)}`); + console.log(` ${c.dim("Config:")} ${c.accent(terminalText(CONFIG_PATH))}`); // Machine-local safety state (no identity): survives a config wipe so a // tripped experiment circuit breaker stays tripped. Listed for transparency. - console.log(` ${c.dim("State:")} ${c.accent(STATE_PATH)}`); + console.log(` ${c.dim("State:")} ${c.accent(terminalText(STATE_PATH))}`); console.log(` ${c.dim("Tracked commands:")} ${c.bold(String(config.commandCount))}`); console.log(); console.log(` ${c.dim("Disable:")} ${c.accent("hyperframes telemetry disable")}`); @@ -140,8 +143,9 @@ ${c.dim("You can also set")} ${c.accent("HYPERFRAMES_NO_TELEMETRY=1")} ${c.dim(" case "status": return runStatus(args.json); default: - console.error( - `${c.error("Unknown subcommand:")} ${subcommand}\n\nRun ${c.accent("hyperframes telemetry --help")} for usage.`, + printFailureLine( + (show) => + `${c.error("Unknown subcommand:")} ${show(String(subcommand))}\n\nRun ${c.accent("hyperframes telemetry --help")} for usage.`, ); failUsage(); } diff --git a/packages/cli/src/commands/tts.output.test.ts b/packages/cli/src/commands/tts.output.test.ts new file mode 100644 index 0000000000..c381813794 --- /dev/null +++ b/packages/cli/src/commands/tts.output.test.ts @@ -0,0 +1,68 @@ +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[], synthesize: vi.fn() })); + +vi.mock("../tts/synthesize.js", () => ({ synthesize: fake.synthesize })); +vi.mock("../ui/prompts.js", () => { + const say = (message: string) => void fake.lines.push(message); + return { spinner: () => ({ start: say, stop: say, message: say }) }; +}); + +const { default: ttsCommand } = await import("./tts.js"); + +const printed = (): string => + fake.lines.join("\n").replace(new RegExp(`${ESC}\\[[0-9;]*m`, "g"), ""); + +const run = (): Promise => + Promise.resolve( + ttsCommand.run?.({ + args: { input: "Hello", voice: `af_${ODD}`, lang: "es" }, + rawArgs: [], + cmd: ttsCommand, + } as never), + ); + +beforeEach(() => { + fake.lines.length = 0; + fake.synthesize.mockReset(); + vi.spyOn(console, "log").mockImplementation((...args: unknown[]) => { + fake.lines.push(args.join(" ")); + }); +}); + +afterEach(() => { + consumeCommandResult(); + vi.restoreAllMocks(); +}); + +describe("tts output for people", () => { + // fails without the fix: the voice, the progress text and the saved path are printed as they arrived. + it("shows control characters in the lines of a finished run as text", async () => { + fake.synthesize.mockImplementation( + async (_text: string, _out: string, opts: { onProgress?: (msg: string) => void }) => { + opts.onProgress?.(`loading ${ODD}`); + return { durationSeconds: 1, langApplied: true, outputPath: `/out/${ODD}.wav` }; + }, + ); + await run(); + expect(printed()).toContain(`Note: voice "af_${SHOWN}" is`); + expect(printed()).toContain(`Generating speech with af_${SHOWN} (es)...`); + expect(printed()).toContain(`loading ${SHOWN}`); + expect(printed()).toContain(`of speech → /out/${SHOWN}.wav`); + expect(printed()).not.toContain(ESC); + expect(printed()).not.toContain("\x07"); + }); + + // fails without the fix: the failure reason is printed as it was thrown. + it("shows control characters in a failure as text", async () => { + fake.synthesize.mockRejectedValue(new Error(`no model ${ODD}\nsecond line`)); + await expect(run()).rejects.toThrow(); + expect(printed()).toContain(`Speech synthesis failed: no model ${SHOWN}\nsecond line`); + expect(printed()).not.toContain(ESC); + }); +}); diff --git a/packages/cli/src/commands/tts.ts b/packages/cli/src/commands/tts.ts index ccbdb77a08..33b6e6748c 100644 --- a/packages/cli/src/commands/tts.ts +++ b/packages/cli/src/commands/tts.ts @@ -1,3 +1,4 @@ +import { terminalLines, terminalText } from "@hyperframes/core"; import { failCommand, failUsage } from "../utils/commandResult.js"; import { isTextFile } from "../utils/textFile.js"; // fallow-ignore-file code-duplication @@ -145,7 +146,7 @@ export default defineCommand({ if (!args.json && args.lang != null && lang !== inferredLang) { console.log( c.dim( - ` Note: voice "${voice}" is ${inferredLang}, rendering with --lang ${lang} instead.`, + ` Note: voice "${terminalText(voice)}" is ${inferredLang}, rendering with --lang ${lang} instead.`, ), ); } @@ -153,14 +154,14 @@ export default defineCommand({ // ── Synthesize ──────────────────────────────────────────────────── const { synthesize } = await import("../tts/synthesize.js"); const spin = args.json ? null : clack.spinner(); - spin?.start(`Generating speech with ${c.accent(voice)} (${lang})...`); + spin?.start(`Generating speech with ${c.accent(terminalText(voice))} (${lang})...`); try { const result = await synthesize(text, output, { voice, speed, lang, - onProgress: spin ? (msg) => spin.message(msg) : undefined, + onProgress: spin ? (msg) => spin.message(terminalText(msg)) : undefined, }); if (args.json) { @@ -178,7 +179,7 @@ export default defineCommand({ } else { spin?.stop( c.success( - `Generated ${c.accent(result.durationSeconds.toFixed(1) + "s")} of speech → ${c.accent(result.outputPath)}`, + `Generated ${c.accent(result.durationSeconds.toFixed(1) + "s")} of speech → ${c.accent(terminalText(result.outputPath))}`, ), ); if (args.lang != null && !result.langApplied) { @@ -194,9 +195,9 @@ export default defineCommand({ if (args.json) { console.log(JSON.stringify(jsonFailure("runtime_error", message))); } else { - spin?.stop(c.error(`Speech synthesis failed: ${message}`)); + spin?.stop(c.error(`Speech synthesis failed: ${terminalLines(message)}`)); } - failCommand(); + failCommand(1, err); } }, }); diff --git a/packages/cli/src/commands/update.test.ts b/packages/cli/src/commands/update.test.ts index ac6a0bc195..fcb0118837 100644 --- a/packages/cli/src/commands/update.test.ts +++ b/packages/cli/src/commands/update.test.ts @@ -359,3 +359,51 @@ describe("hyperframes update (install)", () => { expect(json().updated).toEqual({ cli: { status: "current" }, skills: { status: "current" } }); }); }); + +describe("hyperframes update lines for people", () => { + const ESC = String.fromCharCode(27); + const ODD = `od${ESC}[2Jd\x07`; + const SHOWN = "od\\x1b[2Jd\\x07"; + const text = () => stdout.join("\n").replace(new RegExp(`${ESC}\\[[0-9;]*m`, "g"), ""); + + // fails without the fix: the install path and the skills folder are printed as they are on disk. + it("shows control characters in the install path and the skills folder as text", async () => { + const { checkSkills } = await import("../utils/skillsManifest.js"); + vi.mocked(checkSkills).mockResolvedValueOnce({ + ...OUTDATED_CHECK, + location: `/home/${ODD}/.claude/skills`, + } as never); + await runUpdate(`/usr/local/${ODD}/lib/node_modules/hyperframes/dist/cli.js`, { check: true }); + expect(text()).toContain(`/usr/local/${SHOWN}/lib/node_modules/hyperframes/dist/cli.js`); + expect(text()).toContain( + `2 outdated, 0 core missing at v0.9.5 · /home/${SHOWN}/.claude/skills`, + ); + expect(text()).not.toContain(ESC); + expect(text()).not.toContain("\x07"); + }); + + // fails without the fix: the reason the skills check failed is printed as it arrived. + it("shows control characters in a failed skills check as text", async () => { + const { checkSkills } = await import("../utils/skillsManifest.js"); + vi.mocked(checkSkills).mockRejectedValueOnce(new Error(`no list ${ODD}`)); + await runUpdate(ENTRIES.npm, { check: true }); + expect(text()).toContain(`Could not check: no list ${SHOWN}`); + expect(text()).not.toContain(ESC); + expect(text()).not.toContain("\x07"); + }); + + // fails without the fix: the reason the skills install failed is printed as it arrived. + it("shows control characters in a failed skills install as text", async () => { + state.registryLatest = "0.9.5"; + const { spawn } = await import("node:child_process"); + vi.mocked(spawn).mockImplementationOnce(() => { + const child = new EventEmitter(); + setImmediate(() => child.emit("error", new Error(`no install ${ODD}`))); + return child as never; + }); + expect(await runUpdate(ENTRIES.npm, { yes: true })).toBe(1); + expect(text()).toContain(`Skills update failed: no install ${SHOWN}`); + expect(text()).not.toContain(ESC); + expect(text()).not.toContain("\x07"); + }); +}); diff --git a/packages/cli/src/commands/update.ts b/packages/cli/src/commands/update.ts index dc7539e3cc..15ee837831 100644 --- a/packages/cli/src/commands/update.ts +++ b/packages/cli/src/commands/update.ts @@ -1,3 +1,4 @@ +import { terminalLines, terminalText } from "@hyperframes/core"; import { setCommandExitCode } from "../utils/commandResult.js"; import { defineCommand } from "../utils/defineCommand.js"; import type { Example } from "./_examples.js"; @@ -152,25 +153,30 @@ function printCheck(cli: CliReport, skills: SkillsReport): void { ? c.warn(`${cli.current} → ${cli.latest} available`) : c.success(`${cli.current} (${cli.checkedAt ? "latest" : "npm registry not reached"})`); console.log(` ${c.bold("CLI".padEnd(8))}${version}`); - console.log(` ${" ".repeat(8)}${c.dim(where)}`); + console.log(` ${" ".repeat(8)}${c.dim(terminalText(where))}`); if (cli.command) { - console.log(` ${" ".repeat(8)}${c.accent(`For the user: run ${cli.command}`)}`); + console.log(` ${" ".repeat(8)}${c.accent(`For the user: run ${terminalText(cli.command)}`)}`); } console.log(` ${c.bold("Skills".padEnd(8))}${skillsLine(skills)}`); if (skills.status === "checked" && skills.command) { - console.log(` ${" ".repeat(8)}${c.accent(`For the user: run ${skills.command}`)}`); + console.log( + ` ${" ".repeat(8)}${c.accent(`For the user: run ${terminalText(skills.command)}`)}`, + ); } console.log(); } function skillsLine(skills: SkillsReport): string { if (skills.status === "skipped") return c.dim(skills.reason); - if (skills.status === "error") return c.warn(`Could not check: ${skills.error}`); + if (skills.status === "error") return c.warn(`Could not check: ${terminalText(skills.error)}`); if (!skills.location) return c.warn("No HyperFrames skills installed"); const at = skills.ref ? ` at ${skills.ref}` : ""; - if (!skills.updateAvailable) return c.success(`Up to date${at} · ${skills.location}`); + if (!skills.updateAvailable) + return c.success(terminalText(`Up to date${at} · ${skills.location}`)); return c.warn( - `${skills.outdated} outdated, ${skills.missing} core missing${at} · ${skills.location}`, + terminalText( + `${skills.outdated} outdated, ${skills.missing} core missing${at} · ${skills.location}`, + ), ); } @@ -179,14 +185,16 @@ function cliOutcomeLine(cli: UpdateOutcome["cli"]): string { case "upgraded": return c.success(`CLI upgraded to v${cli.version}.`); case "unchanged": - return c.warn(`CLI stays at v${cli.version}: ${cli.reason}.`); + return c.warn(terminalText(`CLI stays at v${cli.version}: ${cli.reason}.`)); case "unverified": - return c.warn(`CLI: ran ${cli.command}, but ${cli.reason}.`); + return c.warn(terminalText(`CLI: ran ${cli.command}, but ${cli.reason}.`)); case "manual": - return c.warn(`CLI: run ${cli.command} (${cli.reason}).`); + return c.warn(terminalText(`CLI: run ${cli.command} (${cli.reason}).`)); case "failed": return c.error( - cli.reason ?? `CLI upgrade failed. From your home directory, run: ${cli.command}`, + terminalLines( + cli.reason ?? `CLI upgrade failed. From your home directory, run: ${cli.command}`, + ), ); default: return c.success("CLI is up to date."); @@ -201,14 +209,14 @@ function printOutcome(outcome: UpdateOutcome): void { console.log( c.success( n > 0 - ? `Updated ${n} skill(s): ${skills.result.installed.join(", ")}` + ? `Updated ${n} skill(s): ${terminalText(skills.result.installed.join(", "))}` : "Skills are up to date.", ), ); } else if (skills.status === "current") { console.log(c.success("Skills are up to date.")); } else if (skills.status === "failed") { - console.log(c.error(`Skills update failed: ${skills.error}`)); + console.log(c.error(`Skills update failed: ${terminalLines(skills.error)}`)); } else { console.log(c.dim(skills.reason)); }