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 <noreply@anthropic.com>

* test(cli): move the unknown-command text test to a file of its own

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* test(cli): write the direction mark in the test as an escape

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* test(cli): run the unknown command text test with the default test group

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* fix(cli): keep the suggestion under an unknown command on one line

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* fix(cli): show typed and project text as visible text in every line cli.ts prints

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

* 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 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
James Russo
2026-11-21 18:03:26 +00:00
committed by GitHub
co-authored by Claude Fable 5.2
parent 63e700de1e
commit f01d1f32b0
7 changed files with 148 additions and 16 deletions
+13 -1
View File
@@ -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 --<flag>` line, the
`Unexpected extra argument` line, the `.env:` notices at start-up, and the line
the `measure <file>` 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
+12 -8
View File
@@ -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<void> {
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<Cli
const subCommands = typeof declared === "function" ? await declared() : await declared;
const names = Object.keys(subCommands ?? {});
const hint = unknownCommandHint(word, requested.path, names);
console.error(`Unknown command: ${word}`);
if (hint) console.error(hint);
console.error(`Unknown command: ${terminalText(word)}`);
if (hint) console.error(terminalText(hint));
console.error(`Run '${group} --help' to list every command.`);
return new CliUsageError(`Unknown command: ${word}`, {
presented: true,
@@ -709,9 +710,12 @@ async function executeCli(): Promise<void> {
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();
@@ -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<Run> {
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);
@@ -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}`,
@@ -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} <value> or --${flagName}=<value>`;
const message = swallowedValueMessage(flagName, next, hint);
console.error(c.error(message));
console.error(c.error(terminalText(message)));
throw new CliUsageError(message, { presented: true });
}
+11
View File
@@ -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", () => {
+6 -1
View File
@@ -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;
}