diff --git a/packages/cli/src/browser/manager.test.ts b/packages/cli/src/browser/manager.test.ts index 8a1f245e4a..bcc2ec8025 100644 --- a/packages/cli/src/browser/manager.test.ts +++ b/packages/cli/src/browser/manager.test.ts @@ -1137,6 +1137,27 @@ describe("findBrowser — cache resolution", () => { expect(warnSpy.mock.calls[0]?.[0]).toContain("Falling back to system Chrome"); }); + // fails without the fix: the error's code and message were printed as they arrived. + it("shows control characters in a cache read failure as text", async () => { + installFsMocks({ existing: new Set([HF_CACHE, SYSTEM_CHROME]) }); + installPuppeteerBrowsersMock({ + installedInHfCacheError: Object.assign(new Error("scandir '/c/od\u001b[2Jd\u0007'\nsecond"), { + code: "E\u001b]0;t\u0007", + }), + }); + const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {}); + + const { findBrowser, _resetSystemFallbackWarnForTests } = await import("./manager.js"); + _resetSystemFallbackWarnForTests(); + await findBrowser(); + + const said = warnSpy.mock.calls.map((call) => call.map(String).join(" ")).join("\n"); + expect(said).toContain("Browser cache read failed (E\\x1b]0;t\\x07)"); + expect(said).toContain("scandir '/c/od\\x1b[2Jd\\x07'"); + expect(said).not.toContain("\u001b"); + expect(said).not.toContain("\u0007"); + }); + it("falls back to the puppeteer-managed cache when hyperframes cache is empty", async () => { // Empty hyperframes cache, populated puppeteer cache — the regression // scenario from the hf#677 spike. diff --git a/packages/cli/src/browser/manager.ts b/packages/cli/src/browser/manager.ts index 1b46ccfbc0..b04c8ce844 100644 --- a/packages/cli/src/browser/manager.ts +++ b/packages/cli/src/browser/manager.ts @@ -1,5 +1,6 @@ // fallow-ignore-file code-duplication import { spawnSync } from "node:child_process"; +import { terminalLines, terminalText } from "@hyperframes/core"; import { randomUUID } from "node:crypto"; import { existsSync, @@ -323,7 +324,7 @@ async function findFromHyperframesCache(): Promise { const code = (err as NodeJS.ErrnoException | undefined)?.code; const suffix = code ? ` (${code})` : ""; console.warn( - `[hyperframes] Browser cache read failed${suffix}: ${normalizeErrorMessage(err)}. Falling back to system Chrome or a fresh download.`, + `[hyperframes] Browser cache read failed${terminalText(suffix)}: ${terminalLines(normalizeErrorMessage(err))}. Falling back to system Chrome or a fresh download.`, ); installed = []; } @@ -425,7 +426,7 @@ function warnSystemFallbackOnce(executablePath: string): void { if (isHeadlessShellBinary(executablePath)) return; _warnedSystemFallback = true; console.warn( - `[hyperframes] Using system Chrome at ${executablePath}; HeadlessExperimental.beginFrame is unavailable in regular Chrome builds, so the perf-optimized capture path falls back to screenshot mode. Install chrome-headless-shell for the optimized path:\n npx @puppeteer/browsers install chrome-headless-shell@${managedChromeVersion()}\n(Or set HYPERFRAMES_BROWSER_PATH to point at an existing chrome-headless-shell binary.)`, + `[hyperframes] Using system Chrome at ${terminalText(executablePath)}; HeadlessExperimental.beginFrame is unavailable in regular Chrome builds, so the perf-optimized capture path falls back to screenshot mode. Install chrome-headless-shell for the optimized path:\n npx @puppeteer/browsers install chrome-headless-shell@${managedChromeVersion()}\n(Or set HYPERFRAMES_BROWSER_PATH to point at an existing chrome-headless-shell binary.)`, ); } @@ -463,7 +464,7 @@ export async function findBrowser(): Promise { if (fromCache.result) return fromCache.result; if (fromCache.staleHyperframesCachePath) { console.warn( - `[browser] Cached binary missing, not the pinned build, or writable by another account at ${fromCache.staleHyperframesCachePath} — re-downloading...`, + `[browser] Cached binary missing, not the pinned build, or writable by another account at ${terminalText(fromCache.staleHyperframesCachePath)} — re-downloading...`, ); try { return await withInstallLock(() => downloadBrowser()); @@ -511,7 +512,7 @@ async function ensureLinuxArmBrowser(options?: EnsureBrowserOptions): Promise
downloadBrowser(options)); } @@ -738,7 +739,9 @@ export async function retryOnStall( return await run(); } catch (err) { if (!(err instanceof BrowserDownloadStalledError) || attempt >= attempts) throw err; - console.warn(`[hyperframes] ${err.message} Retrying (${attempt}/${attempts - 1}).`); + console.warn( + `[hyperframes] ${terminalLines(err.message)} Retrying (${attempt}/${attempts - 1}).`, + ); clear(); } } @@ -868,7 +871,7 @@ async function downloadBrowser(options?: EnsureBrowserOptions): Promise installWithCorruptArchiveRecovery(runInstall, clearStaging, (err) => console.warn( - `[hyperframes] Downloaded browser archive was corrupt (${normalizeErrorMessage(err)}); re-downloading.`, + `[hyperframes] Downloaded browser archive was corrupt (${terminalLines(normalizeErrorMessage(err))}); re-downloading.`, ), ), clearStaging, diff --git a/packages/cli/src/cli.lifecycle.test.ts b/packages/cli/src/cli.lifecycle.test.ts index d2bc6aed66..71b6e8443d 100644 --- a/packages/cli/src/cli.lifecycle.test.ts +++ b/packages/cli/src/cli.lifecycle.test.ts @@ -475,6 +475,39 @@ describe("CLI lifecycle", () => { } }); + // fails without the fix: the envelope's message was the line as people see it, escapes included. + it("answers a --json run for a missing file with the file's name as given", async () => { + 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); + const missing = join(tmpdir(), "hf-mis\u0007sing.wav"); + try { + mockTelemetry(); + process.argv = ["node", "cli.ts", "transcribe", missing, "--json"]; + await import("./cli.js"); + + const said = errorSpy.mock.calls.map((call) => call.map(String).join(" ")).join("\n"); + expect(said).toContain("hf-mis\\x07sing.wav"); + 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(1); + expect(body.error.message).toBe(`File not found: ${missing}`); + expect(body.error.message).not.toContain("\\x07"); + } finally { + 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(); const exitSpy = vi.spyOn(process, "exit").mockImplementation((() => undefined) as never); diff --git a/packages/cli/src/commands/browser.test.ts b/packages/cli/src/commands/browser.test.ts index fe246515d7..c375ec20ca 100644 --- a/packages/cli/src/commands/browser.test.ts +++ b/packages/cli/src/commands/browser.test.ts @@ -90,3 +90,49 @@ describe("browser ensure", () => { expect(spinners.filter((s) => s.running)).toEqual([]); }); }); + +describe("browser output for people", () => { + const ODD = "\u001b[2J\u0007"; + const SHOWN = "\\x1b[2J\\x07"; + + beforeEach(() => { + spinners.length = 0; + logError.mockReset(); + ensureBrowser.mockReset(); + findBrowser.mockReset(); + linuxArm = false; + }); + + // fails without the fix: the failure's own text is printed as it arrived. + it("shows control characters in an ensure failure as text", async () => { + vi.spyOn(console, "log").mockImplementation(() => {}); + ensureBrowser.mockRejectedValue(new Error(`no browser at /opt/ch${ODD}rome`)); + await expect(runEnsure(false)).rejects.toThrow("Command failed"); + expect(logError).toHaveBeenCalledWith(`no browser at /opt/ch${SHOWN}rome`); + }); + + // fails without the fix: the browser's path is printed as it is on disk. + it("shows control characters in the found browser's path as text", async () => { + const log = vi.spyOn(console, "log").mockImplementation(() => {}); + ensureBrowser.mockResolvedValue({ executablePath: `/opt/ch${ODD}rome`, source: "system" }); + await runEnsure(false); + const printed = log.mock.calls.flat().join("\n"); + expect(printed).toContain(`/opt/ch${SHOWN}rome`); + expect(printed).not.toContain(ODD); + }); + + // fails without the fix: the subcommand is printed as it was typed. + it("shows control characters in an unknown subcommand as text", async () => { + const error = vi.spyOn(console, "error").mockImplementation(() => {}); + await expect( + browserCommand.run!({ + args: { _: [], subcommand: `en${ODD}sure`, force: false }, + rawArgs: [], + cmd: browserCommand, + }), + ).rejects.toThrow(); + const printed = error.mock.calls.flat().join("\n"); + expect(printed).toContain(`en${SHOWN}sure`); + expect(printed).not.toContain(ODD); + }); +}); diff --git a/packages/cli/src/commands/browser.ts b/packages/cli/src/commands/browser.ts index fa6ceddcd4..4fb7cd4600 100644 --- a/packages/cli/src/commands/browser.ts +++ b/packages/cli/src/commands/browser.ts @@ -2,6 +2,7 @@ import { failCommand, failUsage } from "../utils/commandResult.js"; import { defineCommand } from "../utils/defineCommand.js"; import type { Example } from "./_examples.js"; import * as clack from "../ui/prompts.js"; +import { terminalLines, terminalText } from "@hyperframes/core"; import { c } from "../ui/colors.js"; export const examples: Example[] = [ @@ -22,17 +23,18 @@ import { } from "../browser/manager.js"; import { trackBrowserInstall } from "../telemetry/events.js"; import { normalizeErrorMessage } from "../utils/errorMessage.js"; +import { printFailureLine } from "../utils/jsonError.js"; function failSpinner(s: ReturnType, label: string, err: unknown): never { s.stop(c.error(label)); - clack.log.error(normalizeErrorMessage(err)); + clack.log.error(terminalLines(normalizeErrorMessage(err))); failCommand(1, err); } function printBrowser(browser: BrowserResult): void { console.log(); console.log(` ${c.dim("Source:")} ${c.bold(browser.source)}`); - console.log(` ${c.dim("Path:")} ${c.bold(browser.executablePath)}`); + console.log(` ${c.dim("Path:")} ${c.bold(terminalText(browser.executablePath))}`); console.log(); } @@ -65,7 +67,7 @@ async function runEnsure(options?: { force?: boolean }): Promise { } catch (err) { // The ARM64 auto-install failed: the browser is NOT ready, so this is a // real failure (exit 1), not a success. Report it and stop swallowing. - clack.log.error(err instanceof Error ? err.message : String(err)); + clack.log.error(terminalLines(err instanceof Error ? err.message : String(err))); clack.outro(c.warn("Manual setup required (see instructions above).")); failCommand(1, err); } @@ -113,7 +115,9 @@ async function runPath(): Promise { const ensured = await ensureBrowser(); process.stdout.write(ensured.executablePath + "\n"); } catch (err: unknown) { - console.error(err instanceof Error ? err.message : "Failed to find browser"); + printFailureLine((show) => + show(err instanceof Error ? err.message : "Failed to find browser"), + ); failCommand(1, err); } return; @@ -126,7 +130,7 @@ function runClear(): void { const removed = clearBrowser(); if (removed) { - clack.outro(c.success("Removed cached browser from ") + c.dim(CACHE_DIR)); + clack.outro(c.success("Removed cached browser from ") + c.dim(terminalText(CACHE_DIR))); } else { clack.outro(c.dim("No cached browser to remove.")); } @@ -179,8 +183,9 @@ ${c.bold("EXAMPLES:")} case "clear": return runClear(); default: - console.error( - `${c.error("Unknown subcommand:")} ${subcommand}\n\nRun ${c.accent("hyperframes browser --help")} for usage.`, + printFailureLine( + (show) => + `${c.error("Unknown subcommand:")} ${show(String(subcommand))}\n\nRun ${c.accent("hyperframes browser --help")} for usage.`, ); failUsage(); } diff --git a/packages/cli/src/commands/models.test.ts b/packages/cli/src/commands/models.test.ts index 221b755294..0415bafc98 100644 --- a/packages/cli/src/commands/models.test.ts +++ b/packages/cli/src/commands/models.test.ts @@ -208,3 +208,37 @@ describe("models list", () => { }); }); }); + +describe("models list for people", () => { + beforeEach(() => { + vi.clearAllMocks(); + consumeCommandResult(); + sherpa.sherpaUnsupportedReason.mockReturnValue(null); + sherpa.sherpaParakeetInstalled.mockReturnValue(true); + findParakeet.mockReturnValue(undefined); + }); + afterEach(() => vi.restoreAllMocks()); + + // fails without the fix: a model file's name is printed as it is on disk. + it("shows control characters in a model name as text", async () => { + const log = vi.spyOn(console, "log").mockImplementation(() => {}); + manager.listWhisperModels.mockReturnValue([ + { model: "sm\u001b[2J\u0007all", path: "/cache/whisper/models/ggml-odd.bin" }, + ]); + await runCommand(modelsCmd, { rawArgs: ["list"] }); + const printed = log.mock.calls.flat().join("\n"); + expect(printed).toContain("sm\\x1b[2J\\x07all"); + expect(printed).not.toContain("\u001b[2J"); + }); + + // fails without the fix: the words after `models` are printed as they were typed. + it("shows control characters in an unknown action as text", async () => { + const error = vi.spyOn(console, "error").mockImplementation(() => {}); + await expect( + modelsCmd.run!({ args: { action: "li\u001b[2J\u0007st", json: false } } as never), + ).rejects.toThrow(); + const printed = error.mock.calls.flat().join("\n"); + expect(printed).toContain("li\\x1b[2J\\x07st"); + expect(printed).not.toContain("\u001b[2J"); + }); +}); diff --git a/packages/cli/src/commands/models.ts b/packages/cli/src/commands/models.ts index 2510509c41..efe717260b 100644 --- a/packages/cli/src/commands/models.ts +++ b/packages/cli/src/commands/models.ts @@ -1,6 +1,7 @@ import { defineCommand } from "../utils/defineCommand.js"; import * as clack from "../ui/prompts.js"; import type { Example } from "./_examples.js"; +import { terminalLines, terminalText } from "@hyperframes/core"; import { c } from "../ui/colors.js"; import { formatBytes } from "../ui/format.js"; import { failCommand, failUsage, setCommandExitCode } from "../utils/commandResult.js"; @@ -17,7 +18,7 @@ export const examples: Example[] = [ function fail(message: string, json: boolean, usage = false): never { if (json) console.log(JSON.stringify(jsonFailure(usage ? "usage_error" : "runtime_error", message))); - else console.error(c.error(message)); + else console.error(c.error(terminalLines(message))); if (usage) failUsage(); failCommand(); } @@ -145,7 +146,7 @@ async function listModels(json: boolean): Promise { return; } for (const m of models) { - console.log(`${m.engine.padEnd(9)}${m.model.padEnd(22)}${describeState(m)}`); + console.log(`${m.engine.padEnd(9)}${terminalText(m.model).padEnd(22)}${describeState(m)}`); } } diff --git a/packages/cli/src/commands/templates.test.ts b/packages/cli/src/commands/templates.test.ts index 9cd1cbdcc5..513aaf7221 100644 --- a/packages/cli/src/commands/templates.test.ts +++ b/packages/cli/src/commands/templates.test.ts @@ -43,7 +43,12 @@ vi.mock("../telemetry/events.js", async (importOriginal) => ({ trackSkillCommandRan: (run: { skill: string; command: string }) => void commandRuns.push(run), })); -import { pullTemplate, PullRefused, tagStyleSamplingProject, TEMPLATES } from "./templates.js"; +import templatesCmd, { + pullTemplate, + PullRefused, + tagStyleSamplingProject, + TEMPLATES, +} from "./templates.js"; const LINK = "https://signed.test/bundle.tar.gz?sig=1"; let dir: string; @@ -447,3 +452,35 @@ describe("tagStyleSamplingProject", () => { expect(existsSync(join(pulled, "hyperframes.json"))).toBe(false); }); }); + +describe("templates pull output for people", () => { + const ODD = "\u001b[2J\u0007"; + const SHOWN = "\\x1b[2J\\x07"; + const pull = (slug: string, into: string) => + templatesCmd.run!({ args: { action: "pull", slug, dir: into }, rawArgs: [] } as never); + + // fails without the fix: the slug is printed as it was typed. + it("shows control characters in an unknown slug as text", async () => { + const error = vi.spyOn(console, "error").mockImplementation(() => {}); + await expect(pull(`sam${ODD}ple`, dir)).rejects.toThrow(); + const printed = error.mock.calls.flat().join("\n"); + expect(printed).toContain(`sam${SHOWN}ple`); + expect(printed).not.toContain(ODD); + }); + + // fails without the fix: the folder name is printed as it is on disk. + it.skipIf(process.platform === "win32")( + "shows control characters in the pulled folder's path as text", + async () => { + const log = vi.spyOn(console, "log").mockImplementation(() => {}); + const project = join(dir, `pro${ODD}ject`); + mkdirSync(project); + serve({}); + await pull("sample", project); + const printed = log.mock.calls.flat().join("\n"); + expect(printed).toContain(`pro${SHOWN}ject`); + expect(printed).not.toContain(ODD); + expect(existsSync(join(project, "templates", "sample", "SKILL.md"))).toBe(true); + }, + ); +}); diff --git a/packages/cli/src/commands/templates.ts b/packages/cli/src/commands/templates.ts index e1dd48d871..f8bcf94d39 100644 --- a/packages/cli/src/commands/templates.ts +++ b/packages/cli/src/commands/templates.ts @@ -22,8 +22,10 @@ import { processIsAlive } from "../utils/processTree.js"; import { basename, dirname, join, resolve } from "node:path"; import { resolveCloudAuthHeaders } from "../cloud/auth.js"; import { billingBaseUrl } from "../heygen/plan.js"; +import { terminalText } from "@hyperframes/core"; import { c } from "../ui/colors.js"; import { failCommand } from "../utils/commandResult.js"; +import { printFailureLine } from "../utils/jsonError.js"; import { fetchExplained, NetworkFailure } from "../utils/networkFailure.js"; import { defineCommand } from "../utils/defineCommand.js"; import { projectConfigPath, seedProjectAuthoringSkill } from "../utils/projectConfig.js"; @@ -278,7 +280,7 @@ export async function pullTemplate(slug: string, dir: string): Promise { if (aside) console.log( c.warn( - `${dest} did not match HeyGen's verified template, so it was moved to ${aside} and is no longer used.`, + `${terminalText(dest)} did not match HeyGen's verified template, so it was moved to ${terminalText(aside)} and is no longer used.`, ), ); trackSkillCommandRan({ skill: STYLE_SAMPLING, command: "templates pull" }); @@ -415,11 +417,11 @@ export default defineCommand({ try { const path = await pullTemplate(String(args.slug), args.dir ?? "."); tagStyleSamplingProject(args.dir ?? ".", path); - console.log(c.success(`✓ ${path}`)); + console.log(c.success(`✓ ${terminalText(path)}`)); } catch (error) { if (!(error instanceof PullRefused || error instanceof NetworkFailure)) throw error; - console.error(c.error(error.message)); - if (error instanceof NetworkFailure) console.error(c.dim(error.hint)); + printFailureLine((show) => c.error(show(error.message))); + if (error instanceof NetworkFailure) printFailureLine((show) => c.dim(show(error.hint))); failCommand(); } }, diff --git a/packages/cli/src/commands/transcribe.test.ts b/packages/cli/src/commands/transcribe.test.ts index 243be48991..af7624828f 100644 --- a/packages/cli/src/commands/transcribe.test.ts +++ b/packages/cli/src/commands/transcribe.test.ts @@ -25,6 +25,7 @@ import * as parakeet from "../whisper/parakeet.js"; import * as sherpa from "../whisper/sherpa.js"; import * as whisper from "../whisper/transcribe.js"; import { CliRuntimeError, consumeCommandResult } from "../utils/commandResult.js"; +import * as clack from "../ui/prompts.js"; import transcribeCmd from "./transcribe.js"; // Make the whisper core report "unavailable" so we exercise the soft-skip path. @@ -1130,3 +1131,102 @@ Render video. Built for agents. ); }); }); + +describe("transcribe output for people", () => { + const ODD = "\u001b[2J\u0007"; + const SHOWN = "\\x1b[2J\\x07"; + let dirs: string[] = []; + + beforeEach(() => { + dirs = []; + consumeCommandResult(); + replaceRunners(); + transcribeMock.mockReset(); + prepareWavMock.mockReset().mockImplementation((input: string) => input); + Object.assign(runners, { sherpa: false, mlx: false, whisper: true }); + vi.spyOn(console, "log").mockImplementation(() => {}); + vi.spyOn(console, "error").mockImplementation(() => {}); + }); + + afterEach(() => { + consumeCommandResult(); + for (const d of dirs) rmSync(d, { recursive: true, force: true }); + vi.restoreAllMocks(); + syncBuiltinESMExports(); + }); + + // fails without the fix: the input path is printed as it was typed. + it("shows control characters in a missing input's path as text", async () => { + const { dir } = dummyAudio(); + dirs.push(dir); + await expect( + transcribeCmd.run!({ args: { input: join(dir, `na${ODD}rration.wav`) } } as never), + ).rejects.toThrow(); + const printed = vi.mocked(console.error).mock.calls.flat().join("\n"); + expect(printed).toContain(`na${SHOWN}rration.wav`); + expect(printed).not.toContain(ODD); + }); + + // fails without the fix: the caption file's name is printed as it is on disk. + it.skipIf(process.platform === "win32")( + "shows control characters in the exported caption path as text", + async () => { + const { dir, input } = dummyAudio(); + dirs.push(dir); + transcribeMock.mockImplementation(async (_input, outputDir) => + fakeTranscript(outputDir, "whisper"), + ); + const output = join(dir, `ca${ODD}ps.vtt`); + await transcribeCmd.run!({ + args: { input, dir, engine: "whisper", to: "vtt", output }, + } as never); + const printed = vi.mocked(console.log).mock.calls.flat().join("\n"); + expect(printed).toContain(`ca${SHOWN}ps.vtt`); + expect(printed).not.toContain(ODD); + expect(existsSync(output)).toBe(true); + }, + ); + + // fails without the fix: the runner's own failure text is printed as it arrived. + it("shows control characters in a failed run's message as text", async () => { + const { dir, input } = dummyAudio(); + dirs.push(dir); + transcribeMock.mockRejectedValue(new Error(`model fi${ODD}le unreadable`)); + const written: string[] = []; + for (const stream of [process.stdout, process.stderr]) + vi.spyOn(stream, "write").mockImplementation((chunk) => { + written.push(String(chunk)); + return true; + }); + await expect( + transcribeCmd.run!({ + args: { input, dir, engine: "whisper", model: `sm${ODD}all` }, + } as never), + ).rejects.toThrow(); + const printed = written.join(""); + expect(printed).toContain(`sm${SHOWN}all`); + expect(printed).toContain(`model fi${SHOWN}le unreadable`); + expect(printed).not.toContain(ODD); + }); + + // fails without the fix: a runner's status line is handed to the spinner as it arrived. + it("shows control characters in a runner's status line as text", async () => { + const { dir, input } = dummyAudio(); + dirs.push(dir); + const model = `sm${ODD}all`; + transcribeMock.mockImplementation(async (_input, outputDir, options) => { + options.onProgress?.(`Downloading model ${model}...`); + return fakeTranscript(outputDir, "whisper"); + }); + const shown: string[] = []; + const spinner = clack.spinner(); + vi.spyOn(spinner, "message").mockImplementation((text) => { + shown.push(String(text)); + }); + vi.spyOn(spinner, "start").mockImplementation(() => {}); + vi.spyOn(spinner, "stop").mockImplementation(() => {}); + vi.spyOn(clack, "spinner").mockReturnValue(spinner); + await transcribeCmd.run!({ args: { input, dir, engine: "whisper", model } } as never); + expect(shown).toEqual([`Downloading model sm${SHOWN}all...`]); + }); +}); diff --git a/packages/cli/src/commands/transcribe.ts b/packages/cli/src/commands/transcribe.ts index ce061d034b..4b700667ba 100644 --- a/packages/cli/src/commands/transcribe.ts +++ b/packages/cli/src/commands/transcribe.ts @@ -3,6 +3,7 @@ import { failCommand, setCommandExitCode } from "../utils/commandResult.js"; import { defineCommand } from "../utils/defineCommand.js"; import type { Example } from "./_examples.js"; import * as clack from "../ui/prompts.js"; +import { terminalLines, terminalText } from "@hyperframes/core"; import { c } from "../ui/colors.js"; import { DEFAULT_MODEL } from "../whisper/manager.js"; import { trackTranscribeUnavailable } from "../telemetry/events.js"; @@ -14,7 +15,7 @@ import { type TranscribeEngineEvent, type TranscribeResult, } from "../api/transcribe.js"; -import { jsonFailure } from "../utils/jsonError.js"; +import { jsonFailure, printFailureLine } from "../utils/jsonError.js"; export const examples: Example[] = [ ["Transcribe an audio file", "hyperframes transcribe audio.mp3"], @@ -135,10 +136,10 @@ export default defineCommand({ timeoutMs: readTimeout(args.timeout)?.ms, captions: { format: args.to, outputPath: args.output, preserveCues: args["preserve-cues"] }, stopOnProcessSignals: true, - onStatus: json ? undefined : (message) => ui.spin?.message(message), + onStatus: json ? undefined : (message) => ui.spin?.message(terminalText(message)), onProgress: json ? createProgressWriter(process.stderr) : undefined, onEngine: (event) => { - if (event.notice && !json) console.error(c.dim(` Note: ${event.notice}`)); + if (event.notice && !json) console.error(c.dim(` Note: ${terminalLines(event.notice)}`)); ui.spin = showEngine(event, ui.spin, { json, model: args.model }); }, }); @@ -181,10 +182,14 @@ function showEngine( opts: { json: boolean; model?: string }, ): Spinner | null { // The requested model, as the spinner has always shown it; event.model is the one whisper runs. - const label = c.accent(event.runner === "whisper" ? (opts.model ?? DEFAULT_MODEL) : "Parakeet"); + const label = c.accent( + event.runner === "whisper" ? terminalText(opts.model ?? DEFAULT_MODEL) : "Parakeet", + ); if (event.fallbackReason !== undefined) { spin?.clear(); - console.error(c.warn(`${event.fallbackReason}. Using ${event.runner} for this run.`)); + console.error( + c.warn(`${terminalLines(event.fallbackReason)}. Using ${event.runner} for this run.`), + ); spin?.start(`Transcribing with ${label}...`); return spin; } @@ -203,7 +208,7 @@ function failWith(message: string, json: boolean): never { if (json) { console.log(JSON.stringify(jsonFailure("runtime_error", message))); } else { - console.error(c.error(message)); + console.error(c.error(terminalLines(message))); } failCommand(1, message); } @@ -216,7 +221,7 @@ function isRunFailure(err: TranscribeError): boolean { function reportSetupFailure(err: TranscribeError, json: boolean, timeoutFlag?: string): never { if (err.code === "input_not_found") { - console.error(c.error(err.message)); + printFailureLine((show) => c.error(show(err.message))); failCommand(1, err.message); } // An unreadable transcript file keeps failing the way it always has: with the parser's own error. @@ -239,14 +244,19 @@ function reportRunFailure( if (err.code === "whisper_unavailable") return reportWhisperUnavailable(err, spin, opts); if (err.code === "cancelled" || err.code === "caption_write_failed") { if (opts.json) console.log(JSON.stringify(jsonFailure("runtime_error", err.message))); - else spin?.stop(err.code === "cancelled" ? c.warn(err.message) : c.error(err.message)); + else + spin?.stop( + err.code === "cancelled" + ? c.warn(terminalLines(err.message)) + : c.error(terminalLines(err.message)), + ); setCommandExitCode(err.code === "cancelled" ? 130 : 1); return; } if (opts.json) { console.log(JSON.stringify(jsonFailure("runtime_error", err.message))); } else { - spin?.stop(c.error(`Transcription failed: ${err.message}`)); + spin?.stop(c.error(`Transcription failed: ${terminalLines(err.message)}`)); } failCommand(1, err.cause); } @@ -268,7 +278,7 @@ function reportWhisperUnavailable( ); } else { const orParakeet = install ? `\nOr transcribe with Parakeet after: ${install}` : ""; - spin?.stop(c.warn(`Captions skipped — ${err.message}${orParakeet}`)); + spin?.stop(c.warn(terminalLines(`Captions skipped — ${err.message}${orParakeet}`))); } // Optional callers (pipelines) treat a missing prerequisite as a clean // skip; explicit runs still surface non-zero. Set the status and return @@ -278,7 +288,7 @@ function reportWhisperUnavailable( function reportSidecar(to: CaptionFormat, wordCount: number, outPath: string): void { console.log( - `${c.success("◇")} Exported ${c.accent(String(wordCount))} words to ${c.accent(to.toUpperCase())} → ${c.accent(outPath)}`, + `${c.success("◇")} Exported ${c.accent(String(wordCount))} words to ${c.accent(to.toUpperCase())} → ${c.accent(terminalText(outPath))}`, ); } diff --git a/packages/cli/src/utils/jsonError.test.ts b/packages/cli/src/utils/jsonError.test.ts index 70037050b5..f0ffbed521 100644 --- a/packages/cli/src/utils/jsonError.test.ts +++ b/packages/cli/src/utils/jsonError.test.ts @@ -138,3 +138,29 @@ describe("failCaught", () => { ]); }); }); + +describe("printFailureLine", () => { + // fails without the fix: a --json run's error message was built from the line as people see it. + it("shows control characters as text and leaves the text as given for a --json envelope", async () => { + const saved = { + out: process.stdout.write, + err: process.stderr.write, + console: { ...console }, + }; + const shown: string[] = []; + console.error = (...args: unknown[]) => void shown.push(args.map(String).join(" ")); + try { + const { printFailureLine, watchOutput } = await import("./jsonError.js"); + const output = watchOutput(); + printFailureLine((show) => `File not found: ${show("mis\u0007sing.wav")}`); + expect(shown).toEqual(["File not found: mis\\x07sing.wav"]); + expect(output.stderrText()).toBe("File not found: mis\u0007sing.wav"); + console.error("later a\u0007b"); + expect(output.stderrText()).toContain("later a\u0007b"); + } finally { + process.stdout.write = saved.out; + process.stderr.write = saved.err; + Object.assign(console, saved.console); + } + }); +}); diff --git a/packages/cli/src/utils/jsonError.ts b/packages/cli/src/utils/jsonError.ts index 471af4625b..6b356d71e3 100644 --- a/packages/cli/src/utils/jsonError.ts +++ b/packages/cli/src/utils/jsonError.ts @@ -50,6 +50,16 @@ export function writeJsonFailure(body: CliErrorBody): void { */ let reported: { message: string; hint?: string } | undefined; let noticeDepth = 0; +let asGiven: string | undefined; + +export function printFailureLine(line: (show: (text: string) => string) => string): void { + asGiven = line((text) => text); + try { + console.error(line(terminalLines)); + } finally { + asGiven = undefined; + } +} /** The failure a command reported to the person (errorBox); the envelope's message when it has none. */ export function recordFailure(message: string, hint?: string): void { @@ -107,7 +117,7 @@ export function watchOutput(): { wroteStdout: () => boolean; stderrText: () => s for (const name of ["error", "warn"] as const) { const original = console[name].bind(console); console[name] = (...args: unknown[]) => { - keep(`${format(...args)}\n`); + keep(`${asGiven ?? format(...args)}\n`); inConsole = true; try { original(...args); diff --git a/packages/cli/src/utils/optionalPackages.test.ts b/packages/cli/src/utils/optionalPackages.test.ts index ec774590a4..a6665cefae 100644 --- a/packages/cli/src/utils/optionalPackages.test.ts +++ b/packages/cli/src/utils/optionalPackages.test.ts @@ -34,6 +34,7 @@ import { optionalPackageDir, requireSharpBesideCli, SHARP_VERSION, + sweepStaleStaging, type OptionalPackageDeps, } from "./optionalPackages.js"; @@ -737,6 +738,33 @@ describe("install", () => { }, ); + // fails without the fix: the folder's name was printed as it is on disk. + it.skipIf(process.platform === "win32")( + "shows control characters in a stale folder it could not remove as text", + () => { + const root = mkdtempSync(join(tmpdir(), "hf-stale-staging-")); + const parent = join(root, "od\u001b[2Jd\u0007"); + const dir = join(parent, "pkg"); + const deadPid = spawnSync(process.execPath, ["-e", ""]).pid; + const stale = `${dir}.tmp-${deadPid}-old`; + mkdirSync(join(stale, "inner"), { recursive: true }); + chmodSync(stale, 0o500); + const log = vi.spyOn(console, "error").mockImplementation(() => {}); + try { + sweepStaleStaging(dir); + const said = log.mock.calls.map((call) => call.map(String).join(" ")).join("\n"); + expect(said).toContain("could not remove stale install dir"); + expect(said).toContain("od\\x1b[2Jd\\x07"); + expect(said).not.toContain("\u001b"); + expect(said).not.toContain("\u0007"); + } finally { + log.mockRestore(); + chmodSync(stale, 0o700); + rmSync(root, { recursive: true, force: true }); + } + }, + ); + it("runs npm inside the staging dir, with no path on its command line", async () => { const { cache, dir } = setup(); const seen: { args: string[]; cwd: string }[] = []; diff --git a/packages/cli/src/utils/optionalPackages.ts b/packages/cli/src/utils/optionalPackages.ts index d1b67a320e..1a20b43d7f 100644 --- a/packages/cli/src/utils/optionalPackages.ts +++ b/packages/cli/src/utils/optionalPackages.ts @@ -1,4 +1,5 @@ import { spawn } from "node:child_process"; +import { terminalLines, terminalText } from "@hyperframes/core/terminal-text"; import { randomUUID } from "node:crypto"; import { existsSync, @@ -336,7 +337,9 @@ export function sweepStaleStaging(dir: string): void { rmSync(stale, { recursive: true, force: true }); } catch (err) { // Best effort: a locked stale dir must not block a viable install, but it stays visible. - console.error(`could not remove stale install dir ${stale}: ${(err as Error).message}`); + console.error( + `could not remove stale install dir ${terminalText(stale)}: ${terminalLines((err as Error).message)}`, + ); } } } @@ -387,5 +390,5 @@ const defaultDeps: OptionalPackageDeps = { loadBesideCli: (name) => (name === "sharp" ? null : loadBesideCli(name)), loadInstalled, install, - log: (line) => console.error(line), + log: (line) => console.error(terminalLines(line)), }; diff --git a/packages/cli/src/whisper/probe.process.test.ts b/packages/cli/src/whisper/probe.process.test.ts new file mode 100644 index 0000000000..086a0e0e5e --- /dev/null +++ b/packages/cli/src/whisper/probe.process.test.ts @@ -0,0 +1,41 @@ +import { spawnSync } from "node:child_process"; +import { chmodSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { expect, it } from "vitest"; + +const probed = new URL("./transcribe.ts", import.meta.url).href; +const script = `const { getMediaDurationSeconds } = await import(${JSON.stringify(probed)}); +process.stdout.write(String(getMediaDurationSeconds("clip.mp4")));`; + +// fails without the fix: the probe wrote straight to this process's stderr. +it.skipIf(process.platform === "win32")( + "shows control characters in what a failed probe said as text, across the whole stderr stream", + () => { + const dir = mkdtempSync(join(tmpdir(), "hf-probe-")); + const probe = join(dir, "ffprobe"); + writeFileSync( + probe, + "#!/bin/sh\nprintf 'clip: od\\033[2Jd\\007\\nsecond line\\n' >&2\nexit 1\n", + ); + chmodSync(probe, 0o755); + try { + const run = spawnSync( + process.execPath, + ["--import", "tsx", "--input-type=module", "-e", script], + { + env: { ...process.env, HYPERFRAMES_FFPROBE_PATH: probe }, + encoding: "utf-8", + timeout: 100_000, + }, + ); + expect(run.stdout).toBe("null"); + expect(run.stderr).toContain("clip: od\\x1b[2Jd\\x07\nsecond line"); + expect(run.stderr).not.toContain("\u001b"); + expect(run.stderr).not.toContain("\u0007"); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + }, + 120_000, +); diff --git a/packages/cli/src/whisper/sherpa.test.ts b/packages/cli/src/whisper/sherpa.test.ts index 8cf73dc219..1a12e55faf 100644 --- a/packages/cli/src/whisper/sherpa.test.ts +++ b/packages/cli/src/whisper/sherpa.test.ts @@ -320,6 +320,20 @@ module.exports = { expect(String(log.mock.calls[0]?.[0])).not.toContain("\n"); }); + // fails without the fix: the child's own words were printed with only whitespace collapsed. + it("shows control characters in the broken copy's error as text", async () => { + const { cache, cliUrl } = layout( + 'throw new Error("cannot open od\\u001b[2Jd\\u0007");', + decoder(), + ); + const log = vi.spyOn(console, "error").mockImplementation(() => {}); + await transcript(cache, cliUrl); + const said = String(log.mock.calls[0]?.[0]); + expect(said).toContain("cannot open od\\x1b[2Jd\\x07"); + expect(said).not.toContain("\u001b"); + expect(said).not.toContain("\u0007"); + }); + it("reports an accepted package with a missing entry and uses the healthy cache", async () => { const { cache, cliUrl, pinnedPath } = layout(LOADS, decoder()); rmSync(pinnedPath); diff --git a/packages/cli/src/whisper/sherpa.ts b/packages/cli/src/whisper/sherpa.ts index d6efab6467..4fa4b523bd 100644 --- a/packages/cli/src/whisper/sherpa.ts +++ b/packages/cli/src/whisper/sherpa.ts @@ -1,6 +1,7 @@ import { execFile, spawn, type ExecFileException } from "node:child_process"; import { randomUUID } from "node:crypto"; import { mkdirSync, renameSync, rmSync, statSync } from "node:fs"; +import { terminalText } from "@hyperframes/core"; import { ensurePrivateCacheDir, hyperframesCacheDir } from "@hyperframes/core/cache-dir"; import { dirname, join } from "node:path"; import { createInterface } from "node:readline"; @@ -207,7 +208,7 @@ async function selectRuntime( const error = await runtimeLoadError(path, timeoutMs, signal); if (error === null) return { status: "ready", path }; console.error( - `Parakeet runtime at ${path.replace(/\s+/g, " ")} did not load: ${error.replace(/\s+/g, " ")}`, + `Parakeet runtime at ${terminalText(path.replace(/\s+/g, " "))} did not load: ${terminalText(error.replace(/\s+/g, " "))}`, ); } return cachedRuntime(dir, timeoutMs, signal); diff --git a/packages/cli/src/whisper/transcribe.ts b/packages/cli/src/whisper/transcribe.ts index 8087da5281..ea90565415 100644 --- a/packages/cli/src/whisper/transcribe.ts +++ b/packages/cli/src/whisper/transcribe.ts @@ -12,6 +12,7 @@ import { statSync, unlinkSync, } from "node:fs"; +import { terminalLines } from "@hyperframes/core"; import { replaceFileAtomically } from "@hyperframes/core/atomic-file"; import { basename, join, extname } from "node:path"; import { homedir, tmpdir } from "node:os"; @@ -158,24 +159,34 @@ export function resolveAudioPreparationTimeoutMs(durationSeconds: number | null) ); } +function probeText(ffprobePath: string, args: string[]): string { + try { + return execFileSync(ffprobePath, args, { + encoding: "utf-8", + timeout: 10_000, + stdio: ["pipe", "pipe", "pipe"], + }); + } catch (err) { + const said = String((err as { stderr?: unknown }).stderr ?? "").trim(); + if (said) console.error(terminalLines(said)); + throw err; + } +} + export function getMediaDurationSeconds(filePath: string): number | null { try { const ffprobePath = findFFprobe(); if (!ffprobePath) return null; - const raw = execFileSync( - ffprobePath, - [ - "-v", - "error", - "-show_entries", - "format=duration", - "-of", - "default=noprint_wrappers=1:nokey=1", - "--", - filePath, - ], - { encoding: "utf-8", timeout: 10_000 }, - ); + const raw = probeText(ffprobePath, [ + "-v", + "error", + "-show_entries", + "format=duration", + "-of", + "default=noprint_wrappers=1:nokey=1", + "--", + filePath, + ]); const durationSeconds = Number.parseFloat(raw.trim()); return Number.isFinite(durationSeconds) && durationSeconds > 0 ? durationSeconds : null; } catch { @@ -408,11 +419,15 @@ function isWav16kMono(filePath: string): boolean { try { const ffprobePath = findFFprobe(); if (!ffprobePath) return false; - const raw = execFileSync( - ffprobePath, - ["-v", "quiet", "-print_format", "json", "-show_streams", "--", filePath], - { encoding: "utf-8", timeout: 10_000 }, - ); + const raw = probeText(ffprobePath, [ + "-v", + "quiet", + "-print_format", + "json", + "-show_streams", + "--", + filePath, + ]); const parsed: { streams?: AudioStream[] } = JSON.parse(raw); const audio = (parsed.streams ?? []).filter((s) => s.codec_type === "audio"); const index = decodableAudioStream(audio); diff --git a/packages/core/package-subpaths.json b/packages/core/package-subpaths.json index 2e01fd22b7..36a0f34904 100644 --- a/packages/core/package-subpaths.json +++ b/packages/core/package-subpaths.json @@ -116,6 +116,12 @@ "types": "./dist/missingPath.d.ts", "environments": ["bun", "node"] }, + "./terminal-text": { + "source": "./src/terminalText.ts", + "runtime": "./dist/terminalText.js", + "types": "./dist/terminalText.d.ts", + "environments": ["bun", "node"] + }, "./rename-retry": { "source": "./src/renameWithRetry.ts", "runtime": "./dist/renameWithRetry.js", diff --git a/packages/core/package.json b/packages/core/package.json index e679c7cd2e..0b1d3f3717 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -128,6 +128,12 @@ "import": "./src/missingPath.ts", "types": "./src/missingPath.ts" }, + "./terminal-text": { + "bun": "./src/terminalText.ts", + "node": "./dist/terminalText.js", + "import": "./src/terminalText.ts", + "types": "./src/terminalText.ts" + }, "./rename-retry": { "bun": "./src/renameWithRetry.ts", "node": "./dist/renameWithRetry.js", @@ -784,6 +790,10 @@ "import": "./dist/missingPath.js", "types": "./dist/missingPath.d.ts" }, + "./terminal-text": { + "import": "./dist/terminalText.js", + "types": "./dist/terminalText.d.ts" + }, "./rename-retry": { "import": "./dist/renameWithRetry.js", "types": "./dist/renameWithRetry.d.ts"