Skip to content

Write HTML. Render video. Built for agents.

fix(cli): a failed command sends one error report, naming its real cause (#4586)

Miguel Ángel627e9476af1c
diff --git a/packages/cli/src/cli.lifecycle.test.ts b/packages/cli/src/cli.lifecycle.test.ts
index 9f4469f780..08621f993b 100644
--- a/packages/cli/src/cli.lifecycle.test.ts
+++ b/packages/cli/src/cli.lifecycle.test.ts
@@ -1,3 +1,6 @@
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
import { afterEach, describe, expect, it, vi } from "vitest";
import { mockTelemetry } from "./cliDispatchTestUtils.js";
@@ -10,6 +13,7 @@ afterEach(() => {
vi.doUnmock("./commands/init.js");
vi.doUnmock("./telemetry/events.js");
vi.doUnmock("./telemetry/index.js");
+ vi.doUnmock("./telemetry/client.js");
vi.resetModules();
});
@@ -69,6 +73,66 @@ describe("CLI lifecycle", () => {
expect(order).toEqual(["cli_error", "flush"]);
});
+ describe("reports each failure once, by its real error", () => {
+ const dirs: string[] = [];
+ afterEach(() => {
+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });
+ });
+ const outsideProject = () => {
+ const dir = mkdtempSync(join(tmpdir(), "hf-cli-once-"));
+ dirs.push(dir);
+ return dir;
+ };
+
+ it("when the failure reaches the top-level handler", async () => {
+ const dir = outsideProject();
+ mockInitCommand(async () => {
+ const { resolveProject } = await import("./utils/project.js");
+ resolveProject(dir);
+ });
+ const sent = await runCli(["init", "--json"]);
+
+ expect(sent).toEqual([expect.objectContaining({ error_name: "InvalidProjectError" })]);
+ });
+
+ it("when the command catches the failure itself", async () => {
+ const sent = await runCli(["lint", outsideProject(), "--json"]);
+
+ expect(sent).toEqual([
+ expect.objectContaining({ error_name: "InvalidProjectError", command: "lint" }),
+ ]);
+ });
+
+ it("when the command rethrows the failure as its own", async () => {
+ const sent = await runCli([
+ "normalize-audio",
+ outsideProject(),
+ "--reference",
+ "a",
+ "--target",
+ "b",
+ "--json",
+ ]);
+
+ expect(sent).toEqual([expect.objectContaining({ error_name: "InvalidProjectError" })]);
+ });
+
+ it("when a figma command reports its error code", async () => {
+ mockInitCommand(async () => {
+ const { withFigmaErrors } = await import("./commands/figma/cliError.js");
+ const { FigmaClientError } = await import("@hyperframes/core/figma");
+ await withFigmaErrors("figma:asset", async () => {
+ throw new FigmaClientError("NO_TOKEN", "No Figma token");
+ });
+ });
+ const sent = await runCli(["init", "--json"]);
+
+ expect(sent).toEqual([
+ expect.objectContaining({ error_name: "NO_TOKEN", command: "figma:asset" }),
+ ]);
+ });
+ });
+
it("hands queued events to flushSync even after finalizeCli has run", async () => {
const flushSync = vi.fn();
const trackCommandResult = vi.fn();
@@ -235,7 +299,30 @@ describe("CLI lifecycle", () => {
});
});
-function mockInitCommand(run: () => void): void {
+/** Runs the CLI with the real failure reporting and returns the cli_error events it sent. */
+async function runCli(args: string[]): Promise<Record<string, unknown>[]> {
+ const sent: Record<string, unknown>[] = [];
+ mockTelemetry();
+ vi.doUnmock("./telemetry/events.js");
+ vi.doMock("./telemetry/client.js", async () => ({
+ ...(await vi.importActual<typeof import("./telemetry/client.js")>("./telemetry/client.js")),
+ trackEvent: (event: string, props: Record<string, unknown>) => {
+ if (event === "cli_error") sent.push(props);
+ },
+ }));
+ const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
+ const logSpy = vi.spyOn(console, "log").mockImplementation(() => {});
+ try {
+ process.argv = ["node", "cli.ts", ...args];
+ await import("./cli.js");
+ } finally {
+ errorSpy.mockRestore();
+ logSpy.mockRestore();
+ }
+ return sent;
+}
+
+function mockInitCommand(run: () => void | Promise<void>): void {
vi.doMock("./commands/init.js", () => ({
default: {
meta: { name: "init" },
diff --git a/packages/cli/src/commands/browser.ts b/packages/cli/src/commands/browser.ts
index 041e16c5aa..77915b3da3 100644
--- a/packages/cli/src/commands/browser.ts
+++ b/packages/cli/src/commands/browser.ts
@@ -19,7 +19,7 @@ import {
CACHE_DIR,
isLinuxArm,
} from "../browser/manager.js";
-import { trackBrowserInstall, trackCommandFailure } from "../telemetry/events.js";
+import { trackBrowserInstall } from "../telemetry/events.js";
async function runEnsure(options?: { force?: boolean }): Promise<void> {
clack.intro(c.bold("hyperframes browser ensure"));
@@ -54,10 +54,9 @@ async function runEnsure(options?: { force?: boolean }): Promise<void> {
} 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.
- trackCommandFailure("browser", err);
clack.log.error(err instanceof Error ? err.message : String(err));
clack.outro(c.warn("Manual setup required (see instructions above)."));
- failCommand();
+ failCommand(1, err);
}
return;
}
@@ -135,9 +134,8 @@ async function runPath(): Promise<void> {
const ensured = await ensureBrowser();
process.stdout.write(ensured.executablePath + "\n");
} catch (err: unknown) {
- trackCommandFailure("browser", err);
console.error(err instanceof Error ? err.message : "Failed to find browser");
- failCommand();
+ failCommand(1, err);
}
return;
}
@@ -202,11 +200,10 @@ ${c.bold("EXAMPLES:")}
case "clear":
return runClear();
default:
- trackCommandFailure("browser", `Unknown subcommand: ${subcommand}`);
console.error(
`${c.error("Unknown subcommand:")} ${subcommand}\n\nRun ${c.accent("hyperframes browser --help")} for usage.`,
);
- failCommand();
+ failCommand(1, `Unknown subcommand: ${subcommand}`);
}
},
});
diff --git a/packages/cli/src/commands/figma/cliError.ts b/packages/cli/src/commands/figma/cliError.ts
index c323f68476..0534b76034 100644
--- a/packages/cli/src/commands/figma/cliError.ts
+++ b/packages/cli/src/commands/figma/cliError.ts
@@ -6,10 +6,8 @@ import { failCommand } from "../../utils/commandResult.js";
* the CLI's standard errorBox, not a stack trace. Non-Error throws still
* surface raw.
*
- * Because this exits the process itself, it must ALSO report the failure
- * inline (the top-level trackCommandFailures wrapper never sees it) — the
- * typed error name (FigmaClientError code) is the whole first-run funnel:
- * NO_TOKEN → later success is onboarding conversion.
+ * It reports inline to name the typed code (FigmaClientError code) — the whole
+ * first-run funnel: NO_TOKEN → later success is onboarding conversion.
*/
import { FigmaClientError } from "@hyperframes/core/figma";
@@ -21,24 +19,20 @@ export async function withFigmaErrors(command: string, fn: () => Promise<void>):
} catch (err) {
if (err instanceof Error) {
try {
- const telemetry = await import("../../telemetry/index.js");
+ const { trackCommandFailure } = await import("../../telemetry/events.js");
// Surface the typed code (NO_TOKEN, BAD_TOKEN, RATE_LIMITED, …) as the
// error name — `FigmaClientError` alone says nothing in a dashboard.
- telemetry.trackCliError({
- error_name: err instanceof FigmaClientError ? err.code : err.name,
- error_message: err.message,
- stack_trace: err.stack,
+ trackCommandFailure(
command,
- kind: "command_error",
- endpoint: err instanceof FigmaClientError ? err.endpoint : undefined,
- });
- await telemetry.flush();
+ err,
+ err instanceof FigmaClientError ? { error_name: err.code, endpoint: err.endpoint } : {},
+ );
} catch {
// Telemetry must never mask the real command failure.
}
const [title = "figma command failed", ...rest] = err.message.split("\n");
errorBox(title, rest.length > 0 ? rest.join("\n") : undefined);
- failCommand();
+ failCommand(1, err);
}
throw err;
}
diff --git a/packages/cli/src/commands/media-treatment.ts b/packages/cli/src/commands/media-treatment.ts
index ad983cc9d7..38d78871a0 100644
--- a/packages/cli/src/commands/media-treatment.ts
+++ b/packages/cli/src/commands/media-treatment.ts
@@ -681,7 +681,7 @@ function printFailure(error: unknown, json: boolean): void {
const message = normalizeErrorMessage(error);
if (json) console.log(JSON.stringify(withMeta({ ok: false, error: message })));
else console.error(`${c.error("✗")} ${message}`);
- failCommand();
+ failCommand(1, error);
}
export const mediaTreatmentCommand = defineCommand({
diff --git a/packages/cli/src/commands/normalize-audio.ts b/packages/cli/src/commands/normalize-audio.ts
index 4585691aa7..e85528ca6f 100644
--- a/packages/cli/src/commands/normalize-audio.ts
+++ b/packages/cli/src/commands/normalize-audio.ts
@@ -405,10 +405,10 @@ async function measureAudio(
* failures — this command exists to be driven by an agent, and an agent doing
* `JSON.parse(stdout)` on a bare error line just throws.
*/
-function fail(message: string, json: boolean): never {
+function fail(message: string, json: boolean, cause?: unknown): never {
if (json) console.log(JSON.stringify({ ok: false, error: message }, null, 2));
else console.error(c.error(message));
- failCommand();
+ failCommand(1, cause);
}
function byId(tags: readonly AudioTag[], rawId: string, role: string): AudioTag {
@@ -595,7 +595,7 @@ export default defineCommand({
}
printHumanResult(result);
} catch (error) {
- fail(error instanceof Error ? error.message : String(error), Boolean(args.json));
+ fail(error instanceof Error ? error.message : String(error), Boolean(args.json), error);
}
},
});
diff --git a/packages/cli/src/commands/remove-background.ts b/packages/cli/src/commands/remove-background.ts
index 3ce4dacee6..65a627ace3 100644
--- a/packages/cli/src/commands/remove-background.ts
+++ b/packages/cli/src/commands/remove-background.ts
@@ -6,7 +6,6 @@ import * as clack from "@clack/prompts";
import { c } from "../ui/colors.js";
import { isDevice, DEVICES } from "../background-removal/manager.js";
import { DEFAULT_QUALITY, QUALITIES, isQuality } from "../background-removal/pipeline.js";
-import { trackCommandFailure } from "../telemetry/events.js";
import type { Example } from "./_examples.js";
export const examples: Example[] = [
@@ -177,15 +176,12 @@ export default defineCommand({
}
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
- // Self-exits, so the cli.ts dispatch wrapper never sees it — report the
- // reason inline (e.g. a missing native module) before exiting.
- trackCommandFailure("remove-background", err);
if (args.json) {
console.log(JSON.stringify({ ok: false, error: message }));
} else {
spin?.stop(c.error(`Background removal failed: ${message}`));
}
- failCommand();
+ failCommand(1, err);
}
},
});
diff --git a/packages/cli/src/commands/transcribe.test.ts b/packages/cli/src/commands/transcribe.test.ts
index 5c4bd521d5..329d62339d 100644
--- a/packages/cli/src/commands/transcribe.test.ts
+++ b/packages/cli/src/commands/transcribe.test.ts
@@ -10,10 +10,8 @@ const transcribeMock = vi.fn();
vi.mock("../whisper/transcribe.js", () => ({ transcribe: transcribeMock }));
const trackTranscribeUnavailable = vi.fn();
-const trackCommandFailure = vi.fn();
vi.mock("../telemetry/events.js", () => ({
trackTranscribeUnavailable: (...a: unknown[]) => trackTranscribeUnavailable(...a),
- trackCommandFailure: (...a: unknown[]) => trackCommandFailure(...a),
}));
import transcribeCmd from "./transcribe.js";
@@ -32,7 +30,6 @@ describe("transcribe command", () => {
consumeCommandResult();
transcribeMock.mockReset();
trackTranscribeUnavailable.mockReset();
- trackCommandFailure.mockReset();
transcribeMock.mockRejectedValue(
new WhisperUnavailableError("whisper-cpp not found. Install: brew install whisper-cpp"),
);
@@ -60,7 +57,6 @@ describe("transcribe command", () => {
expect(transcribeMock).toHaveBeenCalled();
expect(consumeCommandResult().exitCode).toBe(1);
expect(trackTranscribeUnavailable).toHaveBeenCalledWith({ optional: false });
- expect(trackCommandFailure).not.toHaveBeenCalled();
});
it("--optional skips cleanly with exit 0", async () => {
@@ -76,7 +72,6 @@ describe("transcribe command", () => {
expect(transcribeMock).toHaveBeenCalled();
expect(consumeCommandResult().exitCode).toBe(0);
expect(trackTranscribeUnavailable).toHaveBeenCalledWith({ optional: true });
- expect(trackCommandFailure).not.toHaveBeenCalled();
});
it("imports an SRT and exports an SRT sidecar from transcript.json", async () => {
diff --git a/packages/cli/src/commands/transcribe.ts b/packages/cli/src/commands/transcribe.ts
index 501bde54bd..eca73b1b1b 100644
--- a/packages/cli/src/commands/transcribe.ts
+++ b/packages/cli/src/commands/transcribe.ts
@@ -32,7 +32,7 @@ import { DEFAULT_MODEL, isWhisperUnavailable } from "../whisper/manager.js";
// entering the sync-import graph. Below this floor the whisper spawn has no
// realistic chance of completing even on the fastest hardware for the shortest clip.
const CLI_TIMEOUT_MIN_MS = 5000;
-import { trackCommandFailure, trackTranscribeUnavailable } from "../telemetry/events.js";
+import { trackTranscribeUnavailable } from "../telemetry/events.js";
export default defineCommand({
meta: {
@@ -109,9 +109,8 @@ export default defineCommand({
const inputPath = resolve(args.input);
if (!existsSync(inputPath)) {
const message = `File not found: ${args.input}`;
- trackCommandFailure("transcribe", message);
console.error(c.error(message));
- failCommand();
+ failCommand(1, message);
}
// Default to the directory containing the input file so transcript.json
@@ -176,13 +175,12 @@ function parseTimeoutMs(raw: string | undefined, json: boolean): number | undefi
}
function failWith(message: string, json: boolean): never {
- trackCommandFailure("transcribe", message);
if (json) {
console.log(JSON.stringify({ ok: false, error: message }));
} else {
console.error(c.error(message));
}
- failCommand();
+ failCommand(1, message);
}
function parseExportFormat(
@@ -383,12 +381,11 @@ async function transcribeAudio(
return;
}
- trackCommandFailure("transcribe", err);
if (opts.json) {
console.log(JSON.stringify({ ok: false, error: message }));
} else {
spin?.stop(c.error(`Transcription failed: ${message}`));
}
- failCommand();
+ failCommand(1, err);
}
}
diff --git a/packages/cli/src/telemetry/events.test.ts b/packages/cli/src/telemetry/events.test.ts
index 37ff307162..ff33f82f69 100644
--- a/packages/cli/src/telemetry/events.test.ts
+++ b/packages/cli/src/telemetry/events.test.ts
@@ -1,4 +1,5 @@
import { describe, expect, it, vi, beforeEach } from "vitest";
+import { CliRuntimeError } from "../utils/commandResult.js";
const trackEvent = vi.fn();
const flush = vi.fn(() => Promise.resolve());
@@ -1150,6 +1151,39 @@ describe("trackCommandFailure", () => {
);
});
+ it("reports the same error once, however many places report it", () => {
+ const err = new Error("not a project");
+ trackCommandFailure("info", err);
+ trackCommandFailure("info", err);
+
+ expect(trackEvent).toHaveBeenCalledTimes(1);
+ });
+
+ it("reports the failure a CliRuntimeError carries, through every wrapper, once", () => {
+ const cause = new Error("not a project");
+ const inner = new CliRuntimeError("Command failed", { exitCode: 1, cause });
+ trackCommandFailure("figma:asset", inner);
+ trackCommandFailure("figma", new CliRuntimeError("x", { exitCode: 1, cause: inner }));
+
+ expect(trackEvent).toHaveBeenCalledTimes(1);
+ expect(trackEvent).toHaveBeenCalledWith(
+ "cli_error",
+ expect.objectContaining({ error_message: "not a project" }),
+ );
+ });
+
+ it("takes a caller's error name and endpoint", () => {
+ trackCommandFailure("figma:asset", new Error("No token"), {
+ error_name: "NO_TOKEN",
+ endpoint: "images",
+ });
+
+ expect(trackEvent).toHaveBeenCalledWith(
+ "cli_error",
+ expect.objectContaining({ error_name: "NO_TOKEN", endpoint: "images" }),
+ );
+ });
+
it("coerces a non-Error reason (e.g. a string) into the message", () => {
trackCommandFailure("transcribe", "No words found in transcript.");
diff --git a/packages/cli/src/telemetry/events.ts b/packages/cli/src/telemetry/events.ts
index 192a93d7c9..d8c42e6ec0 100644
--- a/packages/cli/src/telemetry/events.ts
+++ b/packages/cli/src/telemetry/events.ts
@@ -6,6 +6,7 @@ import type { CatalogUsage } from "../utils/catalogUsage.js";
import { flush, shouldTrack, trackEvent } from "./client.js";
import { readConfig } from "./config.js";
import { getPowerState } from "./system.js";
+import { CliRuntimeError } from "../utils/commandResult.js";
// Power state is volatile (a laptop docks/undocks mid-session), so it is
// sampled per render event rather than cached with SystemMeta. Attached to
@@ -924,18 +925,30 @@ export function trackFigmaImport(props: {
});
}
-// Report why a command failed before it exits non-zero. cli_command_result
-// records the failure but not the reason; this fills that gap via cli_error so
-// command failures are diagnosable. Enqueues synchronously — the process `exit`
-// handler flushes it. Drop this into any command's failure path.
-export function trackCommandFailure(command: string, err: unknown): void {
- const error = err instanceof Error ? err : new Error(String(err));
+const reportedFailures = new WeakSet<object>();
+
+// Report why a command failed: cli_command_result records the failure, not the reason. Every
+// command-failure report goes through here. Enqueues synchronously; the `exit` handler flushes it.
+export function trackCommandFailure(
+ command: string,
+ err: unknown,
+ overrides: { error_name?: string; endpoint?: string } = {},
+): void {
+ // A CliRuntimeError wraps the failure it presented; report that failure, and only once.
+ let failure = err;
+ while (failure instanceof CliRuntimeError && failure.cause !== undefined) failure = failure.cause;
+ if (typeof failure === "object" && failure !== null) {
+ if (reportedFailures.has(failure)) return;
+ reportedFailures.add(failure);
+ }
+ const error = failure instanceof Error ? failure : new Error(String(failure));
trackCliError({
- error_name: error.name,
+ error_name: overrides.error_name ?? error.name,
error_message: error.message,
stack_trace: error.stack,
command,
kind: "command_error",
+ endpoint: overrides.endpoint,
});
}
diff --git a/packages/cli/src/utils/command-failure-tracking.ts b/packages/cli/src/utils/command-failure-tracking.ts
index f613399d2c..1f545a40dd 100644
--- a/packages/cli/src/utils/command-failure-tracking.ts
+++ b/packages/cli/src/utils/command-failure-tracking.ts
@@ -8,7 +8,7 @@ type AnyCommandDef = CommandDef<any>;
/**
* Wrap a lazy command loader so leaf commands and nested subcommands share the
* unknown-flag guard. Errors propagate unchanged to the executable boundary,
- * which is the sole command-failure telemetry reporter.
+ * which reports them.
*/
export function trackCommandFailures(
load: () => Promise<AnyCommandDef>,
diff --git a/packages/cli/src/utils/commandResult.ts b/packages/cli/src/utils/commandResult.ts
index 8aa8ca47d9..e281de656f 100644
--- a/packages/cli/src/utils/commandResult.ts
+++ b/packages/cli/src/utils/commandResult.ts
@@ -34,9 +34,9 @@ export class CliRuntimeError extends Error {
constructor(
message = "Command failed",
- options: { exitCode?: number; presented?: boolean } = {},
+ options: { exitCode?: number; presented?: boolean; cause?: unknown } = {},
) {
- super(message);
+ super(message, options.cause === undefined ? undefined : { cause: options.cause });
this.name = "CliRuntimeError";
this.result = {
exitCode: options.exitCode ?? 1,
@@ -57,8 +57,8 @@ export class CliResultSignal extends Error {
}
}
-export function failCommand(exitCode = 1): never {
- throw new CliRuntimeError("Command failed", { exitCode, presented: true });
+export function failCommand(exitCode = 1, cause?: unknown): never {
+ throw new CliRuntimeError("Command failed", { exitCode, presented: true, cause });
}
export function failUsage(exitCode = 1): never {
diff --git a/packages/cli/src/utils/project.ts b/packages/cli/src/utils/project.ts
index 63d56462e0..aed50c92e5 100644
--- a/packages/cli/src/utils/project.ts
+++ b/packages/cli/src/utils/project.ts
@@ -67,13 +67,10 @@ export function resolveProject(
return resolveProjectOrThrow(dirArg, options);
} catch (err) {
if (err instanceof InvalidProjectError) {
- // Self-exit (not a throw) so the cli.ts wrapper never sees it — report
- // inline. argv[2] is the running command (info / inspect / render / ...).
- // This is the dominant failure for read-only commands like `info` run
- // outside a project; the redaction in trackCliError strips the dir path.
+ // Reported here: several commands catch this failure and never reach the executable boundary.
trackCommandFailure(process.argv[2] ?? "unknown", err);
errorBox(err.title, err.hint, err.suggestion);
- failCommand();
+ failCommand(1, err);
}
throw err;
}