From f01d1f32b093b41adf4233fa1b4ff3a8ff5886cb Mon Sep 17 00:00:00 2001 From: James Russo Date: Sat, 21 Nov 2026 18:03:26 +0000 Subject: [PATCH] fix(core): show text direction marks and typed text as visible text in printed lines (#8384) * fix(core): show text direction marks as visible text in printed lines The unknown-command line and its suggestion follow the same rule. Co-Authored-By: Claude Fable 5.2 * test(cli): move the unknown-command text test to a file of its own Co-Authored-By: Claude Fable 5.2 * test(cli): write the direction mark in the test as an escape Co-Authored-By: Claude Fable 5.2 * test(cli): run the unknown command text test with the default test group Co-Authored-By: Claude Fable 5.2 * fix(cli): keep the suggestion under an unknown command on one line Co-Authored-By: Claude Fable 5.2 * fix(cli): show typed and project text as visible text in every line cli.ts prints Co-Authored-By: Claude Fable 5.2 * fix(cli): show typed text as visible text in the missing-value and extra-argument lines The two argument checks that print their own line now show control characters and line breaks in the repeated word as visible text. JSON output keeps the message as built. A usage error from the argument parser prints on one line like the CLI's own. Co-Authored-By: Claude Fable 5.2 --------- Co-authored-by: Claude Fable 5.2 --- docs/packages/cli.mdx | 14 ++- packages/cli/src/cli.ts | 20 ++-- .../cli/src/cli.unknownCommandText.test.ts | 97 +++++++++++++++++++ .../cli/src/utils/reject-extra-positionals.ts | 12 ++- .../cli/src/utils/reject-unknown-flags.ts | 3 +- packages/core/src/terminalText.test.ts | 11 +++ packages/core/src/terminalText.ts | 7 +- 7 files changed, 148 insertions(+), 16 deletions(-) create mode 100644 packages/cli/src/cli.unknownCommandText.test.ts diff --git a/docs/packages/cli.mdx b/docs/packages/cli.mdx index 0921316d1b..586e5d6bad 100644 --- a/docs/packages/cli.mdx +++ b/docs/packages/cli.mdx @@ -53,7 +53,19 @@ the `timeline` edit commands use `--dir`. about files left out) print control characters in a repeated value as visible text such as `\x1b` and `\x07`, and keep the value on its line, with a line break shown as `\x0a`. [`capture`](#capture) does the same for its warnings and failure -reason. `--json` output is not changed by this. +reason. 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 +marks U+200E, U+200F and U+061C, and the zero-width characters (U+200B to U+200D +and U+FEFF) are printed as they are: they reorder and hide nothing, and ordinary +Arabic, Hebrew, Persian and emoji text needs them. These lines follow all of +these rules for text you typed or a project supplied, and no others are changed +here: the `Unknown command:` line and the suggestion under it, the +`Unknown flag:` line, the `Missing value for --` line, the +`Unexpected extra argument` line, the `.env:` notices at start-up, and the line +the `measure ` shortcut prints. Other lines a command prints are as they +were. +`--json` output is not changed by this. **`--json` for agents and scripts.** Most commands accept it, before or after the command name: `hyperframes --json info` is the same run as diff --git a/packages/cli/src/cli.ts b/packages/cli/src/cli.ts index 6b86e3a9f5..774e364ee6 100644 --- a/packages/cli/src/cli.ts +++ b/packages/cli/src/cli.ts @@ -74,8 +74,9 @@ if (rootVersionRequested) { const { loadProjectDotEnv, yieldReceivedProviderKeys } = await import("./utils/dotEnv.js"); const captureEnv = argv[commandWordIndex(argv)] === "capture"; if (!captureEnv || process.env.HYPERFRAMES_NO_CAPTURE_DOTENV !== "1") { - loadProjectDotEnv(process.cwd(), process.env, (line) => console.error(line)); - await yieldReceivedProviderKeys((line) => console.error(line)); + const say = (line: string) => console.error(terminalText(line)); + loadProjectDotEnv(process.cwd(), process.env, say); + await yieldReceivedProviderKeys(say); } // ── Lazy imports ──────────────────────────────────────────────────────────── @@ -134,7 +135,7 @@ async function assertStudioWorkspaceBuilt(): Promise { await import("./utils/workspaceBuildCheck.js"); const problems = checkStudioWorkspaceBuild(repoRoot); if (problems.length === 0) return; - console.error(formatWorkspaceBuildProblems(problems)); + console.error(terminalLines(formatWorkspaceBuildProblems(problems))); throw new CliRuntimeError("Studio workspace build check failed", { exitCode: 1, presented: true, @@ -220,7 +221,7 @@ if (argv[commandWordIndex(argv)] === "measure") { if (rewritten !== argv) { const file = rewritten[rewritten.indexOf("probe") + 1]; console.error( - `No measure op named: running 'probe ${JSON.stringify(file)}'. Ops: ${MEASURE_OPS.join(", ")}.`, + `No measure op named: running 'probe ${terminalText(JSON.stringify(file))}'. Ops: ${MEASURE_OPS.join(", ")}.`, ); process.argv = [...process.argv.slice(0, 2), ...rewritten]; argv = process.argv.slice(2); @@ -609,8 +610,8 @@ async function unknownCommandError(requested: ResolvedCommandUsage): Promise { const usage = error instanceof CliUsageError && !error.result.presented; if (usage && !error.hint) await showRequestedUsage(console.error); if (!typed || !error.result.presented) { - console.error(terminalLines(error instanceof Error ? error.message : String(error))); + const message = error instanceof Error ? error.message : String(error); + const oneLine = error instanceof CliUsageError || isCittyUsageError(error); + const shown = oneLine ? terminalText : terminalLines; + console.error(shown(message)); } - if (usage && error.hint) console.error(error.hint); + if (usage && error.hint) console.error(terminalText(error.hint)); } } finally { const pending = consumeCommandResult(); diff --git a/packages/cli/src/cli.unknownCommandText.test.ts b/packages/cli/src/cli.unknownCommandText.test.ts new file mode 100644 index 0000000000..ad88237f36 --- /dev/null +++ b/packages/cli/src/cli.unknownCommandText.test.ts @@ -0,0 +1,97 @@ +import { spawn } from "node:child_process"; +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { afterAll, expect, it } from "vitest"; + +const cliEntry = join(dirname(fileURLToPath(import.meta.url)), "cli.ts"); +const home = mkdtempSync(join(tmpdir(), "hf-unknown-command-")); +afterAll(() => rmSync(home, { recursive: true, force: true })); + +interface Run { + code: number | null; + stdout: string; + stderr: string; +} + +function runCli(args: string[], cwd = home): Promise { + return new Promise((resolve, reject) => { + const child = spawn("bun", ["run", cliEntry, ...args], { + cwd, + stdio: ["ignore", "pipe", "pipe"], + timeout: 30_000, + env: { PATH: process.env.PATH, HOME: home, USERPROFILE: home, CI: "1" }, + }); + let stdout = ""; + let stderr = ""; + child.stdout.on("data", (chunk: Buffer) => (stdout += chunk.toString())); + child.stderr.on("data", (chunk: Buffer) => (stderr += chunk.toString())); + child.on("error", reject); + child.on("close", (code) => resolve({ code, stdout, stderr })); + }); +} + +it("shows control characters in an unknown command word as visible text", async () => { + const [word, file, json, lines] = await Promise.all([ + runCli(["ren\u001b[2Jdr\u202e"]), + runCli(["cloud", "a\u001b[2Jb.html"]), + runCli(["cloud", "a\u001b[2Jb.html", "--json"]), + runCli(["cloud", "a\nError: b.html"]), + ]); + expect(word.stderr).toContain("Unknown command: ren\\x1b[2Jdr\\u202e\n"); + expect(file.stderr).toContain("'a\\x1b[2Jb.html' "); + for (const run of [word, file]) { + expect(run.code).toBe(2); + expect(run.stderr).not.toContain("\u001b"); + expect(run.stderr).not.toContain("\u202e"); + } + expect(JSON.parse(json.stdout).error.hint).not.toContain("\\x1b"); + expect(lines.stderr).toContain("Unknown command: a\\x0aError: b.html\n"); + expect(lines.stderr).toContain("'a\\x0aError: b.html' "); + expect(lines.stderr.split("\n").filter((line) => line.startsWith("Error:"))).toEqual([]); +}, 60_000); + +const startsALine = (run: Run, text: string) => + run.stderr.split("\n").filter((line) => line.startsWith(text)); + +it("keeps a usage failure that repeats a typed flag on one line", async () => { + const run = await runCli(["info", "--x\nError: y"]); + expect(run.stderr).toContain("--x\\x0aError: y"); + expect(startsALine(run, "Error:")).toEqual([]); +}, 60_000); + +it("shows control characters in a project .env key name as visible text", async () => { + const project = mkdtempSync(join(home, "env-")); + writeFileSync(join(project, ".env"), "KEY\u001b[2J\u202e=1\n"); + const run = await runCli(["info"], project); + expect(run.stderr).toContain(".env: ignoring KEY\\x1b[2J\\u202e "); + expect(run.stderr).not.toContain("\u001b"); + expect(run.stderr).not.toContain("\u202e"); +}, 60_000); + +it("shows direction marks in the file name the measure shortcut repeats", async () => { + const folder = mkdtempSync(join(home, "measure-")); + writeFileSync(join(folder, "clip\u202e\u0085.mp4"), ""); + const run = await runCli(["measure", "clip\u202e\u0085.mp4"], folder); + expect(run.stderr).toContain("running 'probe \"clip\\u202e\\x85.mp4\"'"); + expect(run.stderr).not.toContain("\u202e"); +}, 60_000); + +it("keeps a flag value that looks like the next option on one line", async () => { + const run = await runCli(["catalog", "--query", "--json=a\u001b[2Jb\nError: c"]); + expect(run.stderr).toContain('Missing value for --query: value "--json=a\\x1b[2Jb\\x0aError: c"'); + expect(run.stderr).not.toContain("\u001b[2J"); + expect(startsALine(run, "Error:")).toEqual([]); +}, 60_000); + +it("shows control characters in an extra argument as visible text", async () => { + const [text, json] = await Promise.all([ + runCli(["info", ".", "x\u001b[2Jy\nError: z"]), + runCli(["info", ".", "x\u001b[2Jy", "--json"]), + ]); + expect(text.stderr).toContain("hyperframes info: x\\x1b[2Jy\\x0aError: z\nUsage: "); + expect(text.stderr).not.toContain("\u001b"); + expect(startsALine(text, "Error:")).toEqual([]); + expect(JSON.parse(json.stdout).error.message).toContain("x\u001b[2Jy"); +}, 60_000); diff --git a/packages/cli/src/utils/reject-extra-positionals.ts b/packages/cli/src/utils/reject-extra-positionals.ts index ab465e505a..c25108daa8 100644 --- a/packages/cli/src/utils/reject-extra-positionals.ts +++ b/packages/cli/src/utils/reject-extra-positionals.ts @@ -1,5 +1,6 @@ import { existsSync } from "node:fs"; import type { ArgsDef, CommandDef } from "citty"; +import { terminalText } from "@hyperframes/core/terminal-text"; import { CliUsageError } from "./commandResult.js"; import { isTextFile } from "./textFile.js"; import { jsonFailure } from "./jsonError.js"; @@ -87,12 +88,13 @@ export function resolveExtraPositionals( const plural = extra.length === 1 ? "" : "s"; const spaced = spacedPath(process.argv.slice(2)); - const message = - `Unexpected extra argument${plural} for hyperframes ${path}: ${extra.join(", ")}\n` + - (spaced ? `'${spaced}' is one path with spaces: quote it.\n` : "") + + const message = (show: (text: string) => string) => + `Unexpected extra argument${plural} for hyperframes ${path}: ${extra.map(show).join(", ")}\n` + + (spaced ? `'${show(spaced)}' is one path with spaces: quote it.\n` : "") + `Usage: ${usageLine(path, args)}`; - if (wantsJson(parsed?.json)) console.log(JSON.stringify(jsonFailure("usage_error", message))); - else console.error(message); + if (wantsJson(parsed?.json)) + console.log(JSON.stringify(jsonFailure("usage_error", message(String)))); + else console.error(message(terminalText)); // Telemetry reads the thrown message: the command path and a count, never the arguments. throw new CliUsageError( `${extra.length} unexpected extra argument${plural} for hyperframes ${path}`, diff --git a/packages/cli/src/utils/reject-unknown-flags.ts b/packages/cli/src/utils/reject-unknown-flags.ts index 7b98fd0717..5fbdfadb25 100644 --- a/packages/cli/src/utils/reject-unknown-flags.ts +++ b/packages/cli/src/utils/reject-unknown-flags.ts @@ -1,4 +1,5 @@ import type { ArgDef, ArgsDef, CommandDef } from "citty"; +import { terminalText } from "@hyperframes/core/terminal-text"; import { CliUsageError } from "./commandResult.js"; import { c } from "../ui/colors.js"; import { closestMatch } from "./didYouMean.js"; @@ -177,7 +178,7 @@ export function swallowedFlagUsageError(flagName: string, next: string): CliUsag function throwSwallowedFlagError(flagName: string, next: string): never { const hint = `pass one: --${flagName} or --${flagName}=`; const message = swallowedValueMessage(flagName, next, hint); - console.error(c.error(message)); + console.error(c.error(terminalText(message))); throw new CliUsageError(message, { presented: true }); } diff --git a/packages/core/src/terminalText.test.ts b/packages/core/src/terminalText.test.ts index 565ae4e777..4bcbb2bac0 100644 --- a/packages/core/src/terminalText.test.ts +++ b/packages/core/src/terminalText.test.ts @@ -11,6 +11,17 @@ describe("terminalText", () => { "a\\x1b[31mb\\x07c\\x0ad\\x7fe\\x9bf\\x85", ); }); + + it("writes text direction marks out as visible escapes and keeps right-to-left letters", () => { + expect( + terminalText("clip\u202egpj.exe\u202c \u2066a\u2069 \u202a\u202b\u202d\u2067\u2068"), + ).toBe("clip\\u202egpj.exe\\u202c \\u2066a\\u2069 \\u202a\\u202b\\u202d\\u2067\\u2068"); + expect(terminalText("שלום \u200f مرحبا")).toBe("שלום \u200f مرحبا"); + }); + + it("writes the line and paragraph separators out as visible escapes", () => { + expect(terminalText("a\u2028b\u2029c\u200d\u061c")).toBe("a\\u2028b\\u2029c\u200d\u061c"); + }); }); describe("terminalLines", () => { diff --git a/packages/core/src/terminalText.ts b/packages/core/src/terminalText.ts index 7aedc29eee..e51c8477bd 100644 --- a/packages/core/src/terminalText.ts +++ b/packages/core/src/terminalText.ts @@ -1,11 +1,16 @@ const isControlCode = (code: number) => (code < 0x20 && code !== 0x09) || (code >= 0x7f && code <= 0x9f); +const reordersOrBreaksTextOnScreen = (code: number) => + (code >= 0x2028 && code <= 0x202e) || (code >= 0x2066 && code <= 0x2069); + export function terminalText(text: string): string { let shown = ""; for (const ch of text) { const code = ch.charCodeAt(0); - shown += isControlCode(code) ? `\\x${code.toString(16).padStart(2, "0")}` : ch; + if (isControlCode(code)) shown += `\\x${code.toString(16).padStart(2, "0")}`; + else if (reordersOrBreaksTextOnScreen(code)) shown += `\\u${code.toString(16)}`; + else shown += ch; } return shown; }