diff --git a/docs/packages/cli.mdx b/docs/packages/cli.mdx index 9303c6b799..8204f192c0 100644 --- a/docs/packages/cli.mdx +++ b/docs/packages/cli.mdx @@ -61,6 +61,14 @@ of `play` and `present`, and the notices about telemetry settings, project history, the received-files record, the media scan before a preview, the desktop app project file, render priority, a file approval that could not be saved and `HF_TOOL_CONTEXT` events. +So do these lines when they repeat a name, a path or a value read from a file: +the result, refusal and diff lines of the `timeline` edit commands, the scope +notes of `check`, the clips named on the person line of `diff`, the process id in +`preview --list`, the count in `telemetry status`, the auto-update and +out-of-date skills notices, the path in the FFmpeg install hint, the +`data-fps` warning of a cloud render, the font summary of `capture`, the notice +that a key comes from a folder's `.env`, and the plain progress lines of a run +with no terminal attached. The same lines show the Unicode marks that switch text direction (U+202A to U+202E and U+2066 to U+2069) and the line and paragraph separators (U+2028 and U+2029) as visible text such as `\u202e`. Right-to-left letters, the diff --git a/packages/cli/src/auth/resolver.test.ts b/packages/cli/src/auth/resolver.test.ts index f3ecca33b9..b5a5cf31d7 100644 --- a/packages/cli/src/auth/resolver.test.ts +++ b/packages/cli/src/auth/resolver.test.ts @@ -203,6 +203,26 @@ describe("auth/resolver", () => { }, ); + // fails without the fix: the folder's path was printed as it is on disk + // Windows refuses control characters in folder names. + it.skipIf(process.platform === "win32")( + "shows control characters in the folder of a project .env key as text", + async () => { + const stderr = vi.spyOn(process.stderr, "write").mockImplementation(() => true); + try { + const project = await fs.mkdtemp(join(dir, "project\u0007-")); + await fs.writeFile(join(project, ".env"), "HEYGEN_API_KEY=odd-folder-key\n"); + loadProjectDotEnv(project, process.env, () => {}); + await resolveCredential(); + const printed = stderr.mock.calls.map(([line]) => String(line)).join(""); + expect(printed).toContain(`.env (${join(project, ".env").replace("\u0007", "\\x07")}):`); + expect(printed).not.toContain("\u0007"); + } finally { + stderr.mockRestore(); + } + }, + ); + describe.each(PROJECT_KINDS)("a project .env key from %s", (_, record) => { it.each([ ["expired without a refresh token", { access_token: "stale", expires_at: "2020-01-01Z" }], diff --git a/packages/cli/src/auth/resolver.ts b/packages/cli/src/auth/resolver.ts index 494aa0b181..00b7c7f580 100644 --- a/packages/cli/src/auth/resolver.ts +++ b/packages/cli/src/auth/resolver.ts @@ -11,6 +11,7 @@ * Neither a saved API key nor a project `.env` key replaces an expired login (60s skew). */ +import { terminalText } from "@hyperframes/core/terminal-text"; import { isHeaderSafe, readStore } from "./store.js"; import { ErrInvalidStore, ErrLoginExpired, ErrNotConfigured, isAuthError } from "./errors.js"; import { assertOAuthIdentity } from "./config.js"; @@ -118,7 +119,7 @@ function noteProjectKey(credential: ResolvedCredential): ResolvedCredential { if (dir !== undefined && !projectKeyNoted) { projectKeyNoted = true; process.stderr.write( - `[hyperframes] Using ${name} from this folder's .env (${join(dir, ".env")}): uploads and renders go to that key's HeyGen account.\n`, + `[hyperframes] Using ${name} from this folder's .env (${terminalText(join(dir, ".env"))}): uploads and renders go to that key's HeyGen account.\n`, ); } return credential; diff --git a/packages/cli/src/browser/ffmpeg.output.test.ts b/packages/cli/src/browser/ffmpeg.output.test.ts new file mode 100644 index 0000000000..746ee3f2fa --- /dev/null +++ b/packages/cli/src/browser/ffmpeg.output.test.ts @@ -0,0 +1,25 @@ +import { afterEach, expect, it, vi } from "vitest"; + +const skipped = vi.hoisted(() => ({ path: undefined as string | undefined })); +vi.mock("@hyperframes/parsers/ff-binaries", () => ({ + findFfBinary: () => undefined, + getSkippedX86Binary: () => skipped.path, +})); +vi.mock("@hyperframes/engine", () => ({ getCachedGpuEncoder: vi.fn() })); + +const { getFFmpegInstallHint } = await import("./ffmpeg.js"); + +afterEach(() => { + skipped.path = undefined; + vi.restoreAllMocks(); +}); + +// fails without the fix: the path of the binary that was passed over was printed as found +it("shows control characters in an ignored binary's path as text", () => { + skipped.path = "/opt/tools\u0007/ffmpeg"; + + const hint = getFFmpegInstallHint(); + + expect(hint).toContain("(ignored /opt/tools\\x07/ffmpeg: x86_64 only"); + expect(hint).not.toContain("\u0007"); +}); diff --git a/packages/cli/src/browser/ffmpeg.ts b/packages/cli/src/browser/ffmpeg.ts index 088fc48a81..f40eada3ac 100644 --- a/packages/cli/src/browser/ffmpeg.ts +++ b/packages/cli/src/browser/ffmpeg.ts @@ -1,3 +1,4 @@ +import { terminalText } from "@hyperframes/core/terminal-text"; import { getCachedGpuEncoder } from "@hyperframes/engine"; import { findFfBinary, getSkippedX86Binary } from "@hyperframes/parsers/ff-binaries"; import { detectLinuxDistro, ffmpegInstallCommand } from "./linuxDeps.js"; @@ -106,7 +107,9 @@ export function getFFmpegInstallHint(): string { .filter((name) => !findFfBinary(name, { configuredMustExist: true })) .map(getSkippedX86Binary) .filter((path) => path !== undefined); - const note = ignored.map((path) => ` (ignored ${path}: x86_64 only, it cannot run on this Mac)`); + const note = ignored.map( + (path) => ` (ignored ${terminalText(path)}: x86_64 only, it cannot run on this Mac)`, + ); return installHint() + note.join(""); } diff --git a/packages/cli/src/capture/captureCompositionFrame.browserFallback.test.ts b/packages/cli/src/capture/captureCompositionFrame.browserFallback.test.ts index f2f93673c7..ce76dc1744 100644 --- a/packages/cli/src/capture/captureCompositionFrame.browserFallback.test.ts +++ b/packages/cli/src/capture/captureCompositionFrame.browserFallback.test.ts @@ -178,6 +178,31 @@ describe("openSettledCompositionPage Windows bundled-browser recovery", () => { expect(session.browser).toBe(fallback.browser); }); + // fails without the fix: the system Chrome's path and the caller's wording for the not-ready warning were printed as given + it("shows control characters in the retry path and the not-render-ready warning as text", async () => { + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + mocks.findSystemBrowser.mockReturnValue({ + executablePath: "C:\\Tools\u0007\\chrome.exe", + source: "system", + }); + const fallback = fakeBrowser(); + fallback.page.waitForFunction.mockRejectedValue(new Error("not ready")); + mocks.launch.mockRejectedValueOnce(launchCrash()).mockResolvedValueOnce(fallback.browser); + try { + await openSettledCompositionPage(HTML, "http://127.0.0.1:3000", { + ...OPTIONS, + renderReadyWarningSuffix: 'comparison variant "b\u0007" may be inaccurate', + }); + + const printed = warn.mock.calls.map((call) => call.join(" ")).join("\n"); + expect(printed).toContain("system Chrome at C:\\Tools\\x07\\chrome.exe."); + expect(printed).toContain('1000ms — comparison variant "b\\x07" may be inaccurate'); + expect(printed).not.toContain("\u0007"); + } finally { + warn.mockRestore(); + } + }); + it("adds STATUS_STACK_BUFFER_OVERRUN and browser-path guidance when no system Chrome exists", async () => { mocks.findSystemBrowser.mockReturnValue(undefined); mocks.launch.mockRejectedValueOnce(launchCrash()); diff --git a/packages/cli/src/capture/captureCompositionFrame.ts b/packages/cli/src/capture/captureCompositionFrame.ts index 8c26e8e389..38b46f7d55 100644 --- a/packages/cli/src/capture/captureCompositionFrame.ts +++ b/packages/cli/src/capture/captureCompositionFrame.ts @@ -256,7 +256,7 @@ async function waitForCompositionSettle( if (!runtimeReady) { console.warn( - `\n ${c.warn("⚠")} Runtime did not become render-ready within ${options.renderReadyTimeoutMs}ms — ${options.renderReadyWarningSuffix}`, + `\n ${c.warn("⚠")} Runtime did not become render-ready within ${options.renderReadyTimeoutMs}ms — ${terminalText(options.renderReadyWarningSuffix)}`, ); } @@ -419,7 +419,7 @@ async function launchCompositionBrowser( } console.warn( - `[hyperframes] Managed chrome-headless-shell crashed at launch; retrying once with system Chrome at ${systemBrowser.executablePath}.`, + `[hyperframes] Managed chrome-headless-shell crashed at launch; retrying once with system Chrome at ${terminalText(systemBrowser.executablePath)}.`, ); try { chromeBrowser = await launch(systemBrowser.executablePath); diff --git a/packages/cli/src/capture/postExtractionPhase.test.ts b/packages/cli/src/capture/postExtractionPhase.test.ts index 454ebe1dac..24f2de6984 100644 --- a/packages/cli/src/capture/postExtractionPhase.test.ts +++ b/packages/cli/src/capture/postExtractionPhase.test.ts @@ -1,12 +1,28 @@ import { mkdirSync, mkdtempSync, readdirSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { describe, expect, it, onTestFinished } from "vitest"; +import { afterEach, describe, expect, it, onTestFinished, vi } from "vitest"; import { noDrops } from "./assetDownloader.js"; import { createPartialCaptureState } from "./partialCapture.js"; import { runPostExtraction } from "./postExtractionPhase.js"; import { createCaptureDownloadBudget } from "./readBoundedResponse.js"; +// Only a test that sets `fonts.read` replaces the font reading; the others get the real one. +const fonts = vi.hoisted(() => ({ read: undefined as (() => unknown) | undefined })); +vi.mock("./fontMetadataExtractor.js", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + extractFontMetadata: (...args: Parameters) => + fonts.read ? (fonts.read() as never) : actual.extractFontMetadata(...args), + }; +}); + +afterEach(() => { + fonts.read = undefined; + vi.restoreAllMocks(); +}); + const PLANTED_SVG = ``; describe("runPostExtraction", () => { @@ -55,4 +71,67 @@ describe("runPostExtraction", () => { ]); }, ); + + async function runWithFonts(read: () => unknown): Promise { + const root = mkdtempSync(join(tmpdir(), "hyperframes-post-extraction-")); + onTestFinished(() => rmSync(root, { recursive: true, force: true })); + const outputDir = join(root, "capture"); + for (const dir of ["extracted", "screenshots", "assets"]) { + mkdirSync(join(outputDir, dir), { recursive: true }); + } + const state = createPartialCaptureState({ url: "https://example.com", outputDir }); + fonts.read = read; + await runPostExtraction({ + state, + outputDir, + warnings: [], + progress: () => {}, + remainingMs: () => 60_000, + phase: () => {}, + animationCatalog: undefined, + catalogedAssets: [], + visibleTextContent: "", + faviconLinks: [], + tokens: state.tokens, + extracted: state.extracted, + skipAssets: true, + skipVision: true, + downloadByteBudget: createCaptureDownloadBudget(), + assets: [], + dropped: noDrops(), + fontDrops: noDrops(), + canWrite: () => true, + }); + } + + const printed = (spy: { mock: { calls: unknown[][] } }): string => + spy.mock.calls.map((call) => call.map(String).join(" ")).join("\n"); + + // fails without the fix: a family name read from a font file was printed as stored in the file + it("shows control characters in a font family name as text", async () => { + const error = vi.spyOn(console, "error").mockImplementation(() => {}); + + await runWithFonts(() => ({ + files: [], + families: [{ family: "Inter\u0007", variable: true, fileCount: 2 }], + unidentified: [], + })); + + expect(printed(error)).toContain("Font metadata extracted: Inter\\x07 (variable) × 2"); + expect(printed(error)).not.toContain("\u0007"); + }); + + // fails without the fix: the reason the fonts could not be read was printed as it arrived + it("shows control characters in a font reading failure as text", async () => { + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + + await runWithFonts(() => { + throw new Error("bad name table in a\u0007.woff2\nsecond line"); + }); + + expect(printed(warn)).toContain( + "Font metadata extraction failed (non-fatal): bad name table in a\\x07.woff2\nsecond line", + ); + expect(printed(warn)).not.toContain("\u0007"); + }); }); diff --git a/packages/cli/src/capture/postExtractionPhase.ts b/packages/cli/src/capture/postExtractionPhase.ts index d2102831ea..d5d72162e0 100644 --- a/packages/cli/src/capture/postExtractionPhase.ts +++ b/packages/cli/src/capture/postExtractionPhase.ts @@ -1,3 +1,4 @@ +import { terminalLines, terminalText } from "@hyperframes/core/terminal-text"; import { existsSync } from "node:fs"; import { ensureCaptureDirSync, writeCaptureFileSync } from "./captureFile.js"; import { CaptureDirRefusedError } from "./captureErrors.js"; @@ -135,7 +136,9 @@ export async function runPostExtraction(input: PostExtractionInput): Promise 0) { const summary = fontsManifest.families - .map((f) => `${f.family}${f.variable ? " (variable)" : ""} × ${f.fileCount}`) + .map( + (f) => `${terminalText(f.family)}${f.variable ? " (variable)" : ""} × ${f.fileCount}`, + ) .join(", "); // stderr (via diag): `capture --json` writes its envelope to stdout, so // these progress/advisory lines must not land there. @@ -147,7 +150,10 @@ export async function runPostExtraction(input: PostExtractionInput): Promise { consumeCommandResult(); }); + // fails without the fix: a scope note was printed as it arrived + it("shows control characters in a scope note as text", async () => { + const { report } = await runScenario(fakeDriver()); + const log = vi.spyOn(console, "log").mockImplementation(() => undefined); + await runCommand( + createCheckCommand({ + resolveProject: () => PROJECT, + runPipeline: async () => ({ + ...report, + scope: { hiddenFindings: 0, notes: ["Scoped to #hero\u0007\nsecond line"] }, + }), + prepareMedia: vi.fn(), + withMeta: (value) => value, + }), + { rawArgs: [] }, + ); + const human = log.mock.calls.map((call) => call.join(" ")).join("\n"); + + expect(human).toContain("Scoped to #hero\\x07\nsecond line"); + expect(human).not.toContain("\u0007"); + consumeCommandResult(); + }); + // fails without the fix: the revision read from the project's history reached stdout raw it("prints the saved report's revision with control characters as visible escapes", async () => { // Built rather than written: a literal control character in the source is a lint error. diff --git a/packages/cli/src/commands/check.ts b/packages/cli/src/commands/check.ts index 101caf5bfa..a8987c6ec6 100644 --- a/packages/cli/src/commands/check.ts +++ b/packages/cli/src/commands/check.ts @@ -795,7 +795,7 @@ function printHumanReport(report: CheckReport): void { console.log( `Scope: ${report.scope.range ? report.scope.range.join("–") + "s" : "full timeline"}; ${report.scope.hiddenFindings} findings hidden by component filter. Counts/status include hidden findings.`, ); - for (const note of report.scope.notes) console.log(note); + for (const note of report.scope.notes) console.log(terminalLines(note)); } printSection("Lint", report.lint); if (report.browserSkipped) { diff --git a/packages/cli/src/commands/diff.test.ts b/packages/cli/src/commands/diff.test.ts index 14984947e2..83ddf98d36 100644 --- a/packages/cli/src/commands/diff.test.ts +++ b/packages/cli/src/commands/diff.test.ts @@ -83,4 +83,44 @@ describe("diff command terminal output", () => { expect(text).not.toContain("\u001b[2J"); expect(text).not.toContain("\u0007"); }); + + // fails without the fix: the ids of the clips a person check fails in were printed as they arrived. + it("shows control characters in the clips a person check fails in as text", async () => { + const { diffVideos } = await import("../measure/diff.js"); + vi.mocked(diffVideos).mockResolvedValueOnce({ + pass: false, + 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: [], + person: { + gates: { framing: false, text: false, sync: false }, + failed: { + framing: ["shot\u0007-a", "shot-b"], + text: ["title\u0007"], + sync: ["lips\u0007"], + }, + energy: 1, + shots_at_cuts: { at_cuts: 1, total: 1, cuts_without_shot: [] }, + }, + frames: "2", + warnings: [], + } 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"] }).catch((error: unknown) => { + if (!(error instanceof CliRuntimeError)) throw error; + }); + + const text = printed.join("\n"); + expect(text).toContain( + "person: framing fails in shot\\x07-a, shot-b, text in the clip fails in title\\x07, lips fails in lips\\x07;", + ); + expect(text).not.toContain("\u0007"); + }); }); diff --git a/packages/cli/src/commands/diff.ts b/packages/cli/src/commands/diff.ts index 9a93dd65f7..0eb5791f11 100644 --- a/packages/cli/src/commands/diff.ts +++ b/packages/cli/src/commands/diff.ts @@ -117,7 +117,7 @@ function printHuman(r: DiffResult) { if (r.person) { const g = r.person.gates; const mark = (v: boolean | null, failed: string[]) => - v === null ? "unmeasured" : v ? "ok" : `fails in ${failed.join(", ")}`; + v === null ? "unmeasured" : v ? "ok" : `fails in ${terminalText(failed.join(", "))}`; console.log( ` 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` : ""}`, ); diff --git a/packages/cli/src/commands/preview.test.ts b/packages/cli/src/commands/preview.test.ts index b4ca459331..619e2a0213 100644 --- a/packages/cli/src/commands/preview.test.ts +++ b/packages/cli/src/commands/preview.test.ts @@ -963,6 +963,29 @@ describe.skipIf(process.platform === "win32")( expect(human).toContain(shown); }); + // fails without the fix: the process id another server reported was printed as it arrived + it("shows control characters in a listed server's process id as text", async () => { + const log = vi.spyOn(console, "log").mockImplementation(() => {}); + await handlePreviewList(3002, false, { + scan: async () => + [ + { + port: 32601, + host: "127.0.0.1", + projectName: "film", + projectDir: "/work/film", + version: "1.0.0", + pid: "4242\u0007", + }, + ] as never, + listManaged: async () => [], + }); + const human = log.mock.calls.map((call) => call.join(" ")).join("\n"); + + expect(human).toContain("(PID 4242\\x07)"); + expect(human).not.toContain("\u0007"); + }); + it("prints it as visible escapes in --list and keeps it in --list --json", async () => { const dir = projectNamedWithControls(); const log = vi.spyOn(console, "log").mockImplementation(() => {}); diff --git a/packages/cli/src/commands/preview.ts b/packages/cli/src/commands/preview.ts index 1b9ec3b78f..32f61d4e5b 100644 --- a/packages/cli/src/commands/preview.ts +++ b/packages/cli/src/commands/preview.ts @@ -811,7 +811,7 @@ export async function handlePreviewList( } console.log(`\n ${c.bold("Active preview servers:")}\n`); for (const server of servers) { - const pid = server.pid ? c.dim(` (PID ${server.pid})`) : ""; + const pid = server.pid ? c.dim(` (PID ${terminalText(String(server.pid))})`) : ""; console.log( ` ${c.accent(`Port ${server.port}`)} ${terminalText(server.projectName)} ${c.dim(terminalText(server.projectDir))}${pid}`, ); diff --git a/packages/cli/src/commands/telemetry.test.ts b/packages/cli/src/commands/telemetry.test.ts index d08fb7c4c3..6b5e06f5ea 100644 --- a/packages/cli/src/commands/telemetry.test.ts +++ b/packages/cli/src/commands/telemetry.test.ts @@ -14,10 +14,12 @@ async function loadTelemetryCommand(options?: { configEnabled?: boolean; devMode?: boolean; apiKey?: string; + commandCount?: unknown; }) { const config = { ...baseConfig, telemetryEnabled: options?.configEnabled ?? true, + ...(options?.commandCount === undefined ? {} : { commandCount: options.commandCount }), }; const writeConfigWithResult = vi.fn(() => options?.writeSucceeds === false @@ -221,4 +223,12 @@ describe("telemetry lines for people", () => { expect(said.join("\n")).toContain(`EACCES ${SHOWN}`); expect(said.join("\n")).not.toContain("\x07"); }); + + // fails without the fix: a count that is not a number in the settings file was printed as stored. + it("shows control characters in the tracked command count as text", async () => { + const { command } = await loadTelemetryCommand({ commandCount: "12\u0007" }); + const output = await runWithCapturedOutput(command, "status"); + expect(output).toContain("12\\x07"); + expect(output).not.toContain("\u0007"); + }); }); diff --git a/packages/cli/src/commands/telemetry.ts b/packages/cli/src/commands/telemetry.ts index 89194a19c4..884cd79db3 100644 --- a/packages/cli/src/commands/telemetry.ts +++ b/packages/cli/src/commands/telemetry.ts @@ -82,7 +82,9 @@ function runStatus(json: boolean): void { // 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(terminalText(STATE_PATH))}`); - console.log(` ${c.dim("Tracked commands:")} ${c.bold(String(config.commandCount))}`); + console.log( + ` ${c.dim("Tracked commands:")} ${c.bold(terminalText(String(config.commandCount)))}`, + ); console.log(); console.log(` ${c.dim("Disable:")} ${c.accent("hyperframes telemetry disable")}`); console.log( diff --git a/packages/cli/src/timeline/a2Commands.ids.test.ts b/packages/cli/src/timeline/a2Commands.ids.test.ts index 4afa0aaa86..527ca460a8 100644 --- a/packages/cli/src/timeline/a2Commands.ids.test.ts +++ b/packages/cli/src/timeline/a2Commands.ids.test.ts @@ -3,7 +3,8 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import { afterEach, describe, expect, it, vi } from "vitest"; import { consumeCommandResult } from "../utils/commandResult.js"; -import { readEditPlan, runIds } from "./a2Commands.js"; +import { fileContentVersion } from "@hyperframes/studio-server"; +import { readEditPlan, runIds, runUndo } from "./a2Commands.js"; const hooks = vi.hoisted(() => ({ minting: undefined as (() => void) | undefined })); vi.mock("@hyperframes/parsers/hf-ids", async (importOriginal) => { @@ -61,3 +62,30 @@ describe("timeline apply plan file", () => { expect(readEditPlan(file)).toEqual({ ok: true, edits: [{ op: "trim" }] }); }); }); + +describe("timeline undo", () => { + // fails without the fix: the file named in the receipt was printed as it is on disk + // Windows refuses control characters in file names. + it.skipIf(process.platform === "win32")( + "shows control characters in the undone file's name as text", + async () => { + const dir = mkdtempSync(join(tmpdir(), "hf-timeline-undo-")); + dirs.push(dir); + const file = "sc\u0007ene.html"; + writeFileSync(join(dir, file), "
after
"); + writeFileSync(join(dir, "backup.html"), "
before
"); + const receipt = { + file, + version: fileContentVersion("
after
"), + backupPath: "backup.html", + }; + const log = vi.spyOn(console, "log").mockImplementation(() => {}); + + await runUndo({ dir, receipt: JSON.stringify(receipt) }); + + expect(readFileSync(join(dir, file), "utf-8")).toBe("
before
"); + expect(log.mock.calls.map((call) => call.join(" "))).toEqual(["undid sc\\x07ene.html"]); + consumeCommandResult(); + }, + ); +}); diff --git a/packages/cli/src/timeline/a2Commands.ts b/packages/cli/src/timeline/a2Commands.ts index 1a6884e8e0..410e7c921b 100644 --- a/packages/cli/src/timeline/a2Commands.ts +++ b/packages/cli/src/timeline/a2Commands.ts @@ -1,3 +1,4 @@ +import { terminalText } from "@hyperframes/core/terminal-text"; import { applyFileMutations, fileContentVersion, @@ -385,6 +386,6 @@ export async function runUndo(args: Record): Promise { console.log( undo.batch ? `undid ${receipts.length} file${receipts.length === 1 ? "" : "s"}` - : `undid ${undo.receipts[0]!.file}`, + : `undid ${terminalText(undo.receipts[0]!.file)}`, ); } diff --git a/packages/cli/src/timeline/a2MutationCommand.output.test.ts b/packages/cli/src/timeline/a2MutationCommand.output.test.ts new file mode 100644 index 0000000000..3614de5041 --- /dev/null +++ b/packages/cli/src/timeline/a2MutationCommand.output.test.ts @@ -0,0 +1,79 @@ +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterEach, expect, it, vi } from "vitest"; +import { consumeCommandResult } from "../utils/commandResult.js"; +import { runMutation } from "./a2MutationCommand.js"; + +// Only a test that sets `receipts.version` changes what the write reports; the write itself is real. +const receipts = vi.hoisted(() => ({ version: undefined as string | undefined })); +vi.mock("@hyperframes/studio-server", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + applyFileMutations: (...args: Parameters) => + actual + .applyFileMutations(...args) + .map((receipt) => ({ ...receipt, version: receipts.version ?? receipt.version })), + }; +}); + +const dirs: string[] = []; +afterEach(() => { + receipts.version = undefined; + consumeCommandResult(); + vi.restoreAllMocks(); + for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); +}); + +/** A one-clip project; `clip` is the clip's attributes. */ +function project(clip: string): string { + const dir = mkdtempSync(join(tmpdir(), "hf-timeline-output-")); + dirs.push(dir); + writeFileSync( + join(dir, "index.html"), + `
\n
\n
`, + ); + return dir; +} + +const printed = (spy: { mock: { calls: unknown[][] } }): string => + spy.mock.calls.map((call) => call.map(String).join(" ")).join("\n"); + +// fails without the fix: the clip's id from the file and the receipt's version were printed as they arrived +it("shows control characters in a moved clip's name and its receipt as text", async () => { + const dir = project('id="cl\u0007ip"'); + receipts.version = "v1\u0007"; + const log = vi.spyOn(console, "log").mockImplementation(() => {}); + + await runMutation("move", { dir, ref: "#cl\u0007ip", time: "4" }); + + expect(printed(log)).toBe("move #cl\\x07ip: 1-3s -> 4-6s\nreceipt: v1\\x07"); +}); + +// fails without the fix: the changed lines of the file were printed as they are in the file +it("shows control characters in a planned change's diff as text", async () => { + const dir = project('id="clip" title="a\u0007b"'); + const log = vi.spyOn(console, "log").mockImplementation(() => {}); + + await runMutation("move", { dir, ref: "#clip", time: "4", plan: true }); + + const diff = printed(log).split("\ndiff:\n")[1]; + expect(diff).toContain('title="a\\x07b"'); + expect(diff).toContain("\n"); + expect(diff).not.toContain("\u0007"); +}); + +// fails without the fix: each changed line of a file with Windows line endings ended in a visible \x0d +it("leaves a Windows line ending out of a planned change's diff and still shows one inside a line", async () => { + const dir = project('id="clip" title="a\rb"'); + const file = join(dir, "index.html"); + writeFileSync(file, readFileSync(file, "utf8").replaceAll("\n", "\r\n")); + const log = vi.spyOn(console, "log").mockImplementation(() => {}); + + await runMutation("move", { dir, ref: "#clip", time: "4", plan: true }); + + const lines = printed(log).split("\ndiff:\n")[1]!.split("\n"); + expect(lines.filter((line) => line.includes('title="a\\x0db"'))).toHaveLength(2); + expect(lines.filter((line) => line.endsWith("\\x0d") || line.includes("\r"))).toEqual([]); +}); diff --git a/packages/cli/src/timeline/a2MutationCommand.ts b/packages/cli/src/timeline/a2MutationCommand.ts index c95f5e5b46..84c0ec6e5e 100644 --- a/packages/cli/src/timeline/a2MutationCommand.ts +++ b/packages/cli/src/timeline/a2MutationCommand.ts @@ -1,3 +1,4 @@ +import { terminalLines, terminalText } from "@hyperframes/core/terminal-text"; import { applyFileMutations, fileContentVersion } from "@hyperframes/studio-server"; import type { AppliedFileMutation } from "@hyperframes/studio-server"; import { readFileSync } from "node:fs"; @@ -198,7 +199,7 @@ async function applyAndPrint(args: { return; } console.log( - `${args.verb} ${args.row.ref}: ${args.row.start}-${args.row.end}s -> ${args.nextStart}-${args.nextStart + args.nextDuration}s\nreceipt: ${receipt?.version ?? "unchanged"}`, + `${args.verb} ${terminalText(args.row.ref)}: ${args.row.start}-${args.row.end}s -> ${args.nextStart}-${args.nextStart + args.nextDuration}s\nreceipt: ${terminalText(receipt?.version ?? "unchanged")}`, ); } @@ -231,7 +232,7 @@ async function printPlan( if (json) console.log(JSON.stringify(withMeta(result), null, 2)); else console.log( - `${formatTimeline(timeline)}\n\nplanned:\n${formatTimeline(plannedTimeline)}\n\ndiff:\n${diff(before, after)}`, + `${formatTimeline(timeline)}\n\nplanned:\n${formatTimeline(plannedTimeline)}\n\ndiff:\n${terminalLines(diff(before, after).replace(/\r$/gm, ""))}`, ); } diff --git a/packages/cli/src/timeline/a2Shared.output.test.ts b/packages/cli/src/timeline/a2Shared.output.test.ts new file mode 100644 index 0000000000..78652fa931 --- /dev/null +++ b/packages/cli/src/timeline/a2Shared.output.test.ts @@ -0,0 +1,22 @@ +import { afterEach, expect, it, vi } from "vitest"; +import { consumeCommandResult } from "../utils/commandResult.js"; +import { refusal } from "./a2Shared.js"; + +afterEach(() => { + consumeCommandResult(); + vi.restoreAllMocks(); +}); + +// fails without the fix: the reason and the fix were printed as they arrived +it.each([ + ["reason", "#clip\u0007 was not found", "choose an existing clip", "#clip\\x07 was not found; "], + ["fix", "no stable id", "add an id in scene\u0007.html", "; add an id in scene\\x07.html."], +])("shows control characters in a refusal's %s as text", (_, reason, fix, shown) => { + const error = vi.spyOn(console, "error").mockImplementation(() => {}); + + refusal(reason, fix, false); + + const printed = error.mock.calls.map((call) => call.join(" ")).join("\n"); + expect(printed).toContain(shown); + expect(printed).not.toContain("\u0007"); +}); diff --git a/packages/cli/src/timeline/a2Shared.ts b/packages/cli/src/timeline/a2Shared.ts index 35b754ed7e..d40a82615c 100644 --- a/packages/cli/src/timeline/a2Shared.ts +++ b/packages/cli/src/timeline/a2Shared.ts @@ -1,3 +1,4 @@ +import { terminalLines } from "@hyperframes/core/terminal-text"; import { duplicateElementInHtml, patchElementInHtml, @@ -55,7 +56,7 @@ export function refusal(reason: string, fix: string, json: boolean): void { setCommandExitCode(2); if (json) console.log(JSON.stringify({ ...jsonFailure("refused", reason, fix), reason, fix }, null, 2)); - else console.error(`${reason}; ${fix}.`); + else console.error(`${terminalLines(reason)}; ${terminalLines(fix)}.`); } export const isFileChanged = (error: unknown): error is Error => diff --git a/packages/cli/src/ui/prompts.test.ts b/packages/cli/src/ui/prompts.test.ts index 9141e440a5..68b69a7d43 100644 --- a/packages/cli/src/ui/prompts.test.ts +++ b/packages/cli/src/ui/prompts.test.ts @@ -60,6 +60,22 @@ describe("prompt wrapper", () => { } }); + // fails without the fix: a bell in the message reached stderr as it was given + it("an unattended spinner shows control characters in its message as text", () => { + const write = vi.spyOn(process.stderr, "write").mockImplementation(() => true); + try { + const spin = prompts.spinner(); + spin.start("Transcoding clip\u0007.mov"); + spin.stop("Done\u0007\nnext line"); + expect(write.mock.calls).toEqual([ + ["Transcoding clip\\x07.mov\n"], + ["Done\\x07\nnext line\n"], + ]); + } finally { + write.mockRestore(); + } + }); + it("an attended spinner is clack's", () => { state.unattended = false; expect(prompts.spinner()).toEqual({ fromClack: true }); diff --git a/packages/cli/src/ui/prompts.ts b/packages/cli/src/ui/prompts.ts index 9f94ac9dd6..fc43411630 100644 --- a/packages/cli/src/ui/prompts.ts +++ b/packages/cli/src/ui/prompts.ts @@ -1,3 +1,4 @@ +import { terminalLines } from "@hyperframes/core/terminal-text"; import * as clack from "@clack/prompts"; import type { ConfirmOptions, @@ -54,7 +55,7 @@ export function password(opts: PasswordOptions): Promise { function lineSpinner(): SpinnerResult { const say = (message?: string) => { - if (message) process.stderr.write(`${stripVTControlCharacters(message)}\n`); + if (message) process.stderr.write(`${terminalLines(stripVTControlCharacters(message))}\n`); }; return { start: say, diff --git a/packages/cli/src/utils/autoUpdate.test.ts b/packages/cli/src/utils/autoUpdate.test.ts index 57d7fbc725..e0c93ffdff 100644 --- a/packages/cli/src/utils/autoUpdate.test.ts +++ b/packages/cli/src/utils/autoUpdate.test.ts @@ -482,6 +482,40 @@ describe("scheduleBackgroundInstall", () => { } }); + // fails without the fix: the version stored in the settings file was printed as stored + it.each([ + [true, "auto-updated to v0.4.4\\x07\n"], + [false, "auto-update to v0.4.4\\x07 failed"], + ])( + "shows control characters in a finished update's version as text (ok=%s)", + async (ok, shown) => { + setupMocks({ + installer: { kind: "npm", command: "npm install -g hyperframes@0.4.4" }, + config: { + completedUpdate: { version: "0.4.4\u0007", ok, finishedAt: new Date().toISOString() }, + }, + }); + const { reportCompletedUpdate } = await import("./autoUpdate.js"); + const stderrWrite = vi.spyOn(process.stderr, "write").mockReturnValue(true); + const originalIsTTY = process.stderr.isTTY; + Object.defineProperty(process.stderr, "isTTY", { value: true, configurable: true }); + + try { + reportCompletedUpdate(); + + const printed = stderrWrite.mock.calls.map(([text]) => String(text)).join(""); + expect(printed).toContain(shown); + expect(printed).not.toContain("\u0007"); + } finally { + stderrWrite.mockRestore(); + Object.defineProperty(process.stderr, "isTTY", { + value: originalIsTTY, + configurable: true, + }); + } + }, + ); + describe("the detached child's settings write", () => { const home = mkdtempSync(join(tmpdir(), "hf-auto-update-")); const dir = join(home, ".hyperframes"); diff --git a/packages/cli/src/utils/autoUpdate.ts b/packages/cli/src/utils/autoUpdate.ts index 4272d27f76..97d2b9cdb2 100644 --- a/packages/cli/src/utils/autoUpdate.ts +++ b/packages/cli/src/utils/autoUpdate.ts @@ -23,6 +23,7 @@ * postmortem; the user's terminal stays clean. */ +import { terminalText } from "@hyperframes/core/terminal-text"; import { spawn } from "node:child_process"; import { appendFileSync, mkdirSync, openSync } from "node:fs"; import { resolve } from "node:path"; @@ -366,12 +367,14 @@ export function reportCompletedUpdate(): void { if (!process.stderr.isTTY) return; if (done.ok) { - process.stderr.write(` hyperframes auto-updated to v${done.version}\n\n`); + process.stderr.write( + ` hyperframes auto-updated to v${terminalText(String(done.version))}\n\n`, + ); } else if (!done.reported) { // Failed installs are surfaced once too — the user should know why the // auto-update didn't take. process.stderr.write( - ` hyperframes auto-update to v${done.version} failed. Run \`hyperframes upgrade\` to retry.\n\n`, + ` hyperframes auto-update to v${terminalText(String(done.version))} failed. Run \`hyperframes upgrade\` to retry.\n\n`, ); } } diff --git a/packages/cli/src/utils/compositionFps.test.ts b/packages/cli/src/utils/compositionFps.test.ts index 167cc00e69..d9c7dd2ea8 100644 --- a/packages/cli/src/utils/compositionFps.test.ts +++ b/packages/cli/src/utils/compositionFps.test.ts @@ -114,6 +114,15 @@ describe("defaultCloudFps", () => { expect(String(warn.mock.calls[0]?.[0])).toContain(`data-fps="${fps}"`); }); + // fails without the fix: the declared value was printed as written in the file + it("shows control characters in an unsupported data-fps as text", () => { + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + expect(defaultCloudFps(root("48\u0007"))).toBe(30); + const printed = String(warn.mock.calls[0]?.[0]); + expect(printed).toContain('data-fps="48\\x07"'); + expect(printed).not.toContain("\u0007"); + }); + it("reads mixed-case HTML attributes before validating the cloud fps", () => { const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); const dir = makeProject( diff --git a/packages/cli/src/utils/compositionFps.ts b/packages/cli/src/utils/compositionFps.ts index 1df7d199f3..978485e803 100644 --- a/packages/cli/src/utils/compositionFps.ts +++ b/packages/cli/src/utils/compositionFps.ts @@ -1,3 +1,4 @@ +import { terminalText } from "@hyperframes/core/terminal-text"; import { readFileSync } from "node:fs"; import { join } from "node:path"; import { DISTRIBUTED_FPS, type DistributedFps, isDistributedFps } from "@hyperframes/core"; @@ -63,7 +64,7 @@ export function defaultCloudFps(projectDir: string): DistributedFps { if (isDistributedFps(n)) return n; console.warn( c.warn( - `The composition declares data-fps="${raw}", which cloud renders do not support ` + + `The composition declares data-fps="${terminalText(raw)}", which cloud renders do not support ` + `(${DISTRIBUTED_FPS.join(", ")}). Rendering at ${DEFAULT_CLOUD_FPS} fps; pass --fps to choose.`, ), ); diff --git a/packages/cli/src/utils/desktopApp.test.ts b/packages/cli/src/utils/desktopApp.test.ts index 6f8a3f4a40..37894ecab4 100644 --- a/packages/cli/src/utils/desktopApp.test.ts +++ b/packages/cli/src/utils/desktopApp.test.ts @@ -435,6 +435,51 @@ describe("agent hand-off", () => { expect(existsSync(handoff())).toBe(false); }); + // fails without the fix: the path of the record that could not be written was printed as it is on disk + // Windows refuses control characters in folder names, and has no read-only folders to make. + it.skipIf(process.platform === "win32")( + "shows control characters in the hand-off record's path as text", + () => { + const home = mkdtempSync(join(tmpdir(), "hf-home\u0007-")); + vi.stubEnv("HOME", home); + vi.stubEnv("HYPERFRAMES_CACHE_DIR", ""); + chmodSync(home, 0o555); + dir = mkdtempSync(join(tmpdir(), "hf-handoff-")); + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + try { + openInDesktop(dir, { ...LIVE, open: () => true, env: { CODEX_THREAD_ID: "x-1" } }); + + const printed = warn.mock.calls.map((call) => call.join(" ")).join("\n"); + expect(printed).toContain(`hand-off in ${home.replace("\u0007", "\\x07")}`); + expect(printed).not.toContain("\u0007"); + } finally { + warn.mockRestore(); + chmodSync(home, 0o755); + rmSync(home, { recursive: true, force: true }); + } + }, + ); + + // fails without the fix: the folder that could not be marked as a project was printed as it is on disk + it.skipIf(process.platform === "win32")( + "shows control characters in a folder it could not mark as a project as text", + () => { + dir = mkdtempSync(join(tmpdir(), "hf-bare\u0007-")); + writeFileSync(join(dir, "index.html"), ""); + chmodSync(dir, 0o555); + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + try { + openInDesktop(dir, { ...LIVE, open: () => true }); + + const printed = warn.mock.calls.map((call) => call.join(" ")).join("\n"); + expect(printed).toContain(`hyperframes.json to ${dir.replace("\u0007", "\\x07")}, so`); + expect(printed).not.toContain("\u0007"); + } finally { + warn.mockRestore(); + } + }, + ); + it.skipIf(process.platform === "win32")( "still opens a project it cannot write to, with nothing handed over", () => { diff --git a/packages/cli/src/utils/desktopApp.ts b/packages/cli/src/utils/desktopApp.ts index 5278b1c06b..ced1138587 100644 --- a/packages/cli/src/utils/desktopApp.ts +++ b/packages/cli/src/utils/desktopApp.ts @@ -161,7 +161,7 @@ function leaveHandoff(dir: string, session: AgentSession | null): AgentSession | if (!session || !writeRecord(dir, "agent-handoff.json", JSON.stringify(session))) return null; if (!noteHandoff(dir)) console.warn( - `◇ Couldn't note the hand-off in ${seenPath(dir)}, so \`catch-up\` won't see it.`, + `◇ Couldn't note the hand-off in ${terminalText(seenPath(dir))}, so \`catch-up\` won't see it.`, ); addCatchUpNote(dir); return session; @@ -173,7 +173,7 @@ function markBareIndexAsProject(dir: string): void { createProjectConfig(dir); } catch (error) { console.warn( - `◇ Couldn't add hyperframes.json to ${dir}, so the app may not open it: ${terminalText(String(error))}`, + `◇ Couldn't add hyperframes.json to ${terminalText(dir)}, so the app may not open it: ${terminalText(String(error))}`, ); } } diff --git a/packages/cli/src/utils/skillsUpdateCheck.test.ts b/packages/cli/src/utils/skillsUpdateCheck.test.ts index 5f507769eb..af38c1122e 100644 --- a/packages/cli/src/utils/skillsUpdateCheck.test.ts +++ b/packages/cli/src/utils/skillsUpdateCheck.test.ts @@ -224,6 +224,13 @@ describe("skillsUpdateCheck", () => { expect(await noticeTextFor({ skillsOutdatedCount: 2, skillsMissingCount: 1 })).toBeNull(); }); + // fails without the fix: a count that is not a number in the settings file was printed as stored + it("shows control characters in the stale-skills count as text", async () => { + const text = await noticeTextFor({ skillsOutdatedCount: 0, skillsMissingCount: "2\u0007" }); + expect(text).toContain("02\\x07 HyperFrames skills out of date or missing"); + expect(text).not.toContain("\u0007"); + }); + it("prints the stale-skills notice without a TTY, so an agent hears it", async () => { gate.noTty = true; const text = await noticeTextFor({ skillsOutdatedCount: 2, skillsMissingCount: 1 }); diff --git a/packages/cli/src/utils/skillsUpdateCheck.ts b/packages/cli/src/utils/skillsUpdateCheck.ts index bc2d2c962b..5105e15b31 100644 --- a/packages/cli/src/utils/skillsUpdateCheck.ts +++ b/packages/cli/src/utils/skillsUpdateCheck.ts @@ -6,6 +6,7 @@ // check on their own, but they DO run render/lint/validate — so we piggyback // the reminder on the commands they already run. +import { terminalText } from "@hyperframes/core/terminal-text"; import { resolve } from "node:path"; import { readConfig, readConfigFresh, writeConfig } from "../telemetry/config.js"; import { isUnattended } from "./attendedTerminal.js"; @@ -133,7 +134,7 @@ function skillsNoticeText(meta: SkillsUpdateMeta): string | null { const total = meta.outdated + meta.missing; if (total < 1) return null; const noun = total === 1 ? "skill" : "skills"; - return `\n ${total} HyperFrames ${noun} out of date or missing.\n For the user: npx hyperframes skills update refreshes them.\n\n`; + return `\n ${terminalText(String(total))} HyperFrames ${noun} out of date or missing.\n For the user: npx hyperframes skills update refreshes them.\n\n`; } /**