diff --git a/packages/cli/src/commands/auth/refresh.test.ts b/packages/cli/src/commands/auth/refresh.test.ts new file mode 100644 index 0000000000..3fc26c8ebd --- /dev/null +++ b/packages/cli/src/commands/auth/refresh.test.ts @@ -0,0 +1,47 @@ +import { afterEach, expect, it, vi } from "vitest"; +import { AuthError } from "../../auth/errors.js"; + +const refresh = vi.hoisted(() => ({ error: null as Error | null })); + +vi.mock("../../auth/index.js", async (importOriginal) => ({ + ...(await importOriginal()), + assertOAuthConfiguredOrExit: () => undefined, + readStore: async () => ({ + source: "file", + credentials: { oauth: { refresh_token: "stored" } }, + }), + refreshTokens: async () => { + if (refresh.error) throw refresh.error; + }, +})); + +import refreshCommand from "./refresh.js"; + +afterEach(() => { + refresh.error = null; + vi.restoreAllMocks(); +}); + +// fails without the fix: the refusal and its hint reached the terminal with their control characters live. +it("prints a refused refresh's control characters as visible escapes", async () => { + const esc = String.fromCharCode(27); + refresh.error = new AuthError( + "REFRESH_FAILED", + `Refresh refused${esc}[2J`, + `Run auth login${esc}]0;t${String.fromCharCode(7)}`, + ); + const lines: string[] = []; + vi.spyOn(console, "error").mockImplementation((...parts: unknown[]) => { + lines.push(parts.map(String).join(" ")); + }); + + await expect(refreshCommand.run?.({ args: {}, rawArgs: [] } as never)).rejects.toMatchObject({ + name: "CliRuntimeError", + }); + + const printed = lines.join("\n"); + expect(printed).toContain("Refresh refused\\x1b[2J"); + expect(printed).toContain("Run auth login\\x1b]0;t\\x07"); + expect(printed).not.toContain(`${esc}[2J`); + expect(printed).not.toContain(`${esc}]`); +}); diff --git a/packages/cli/src/commands/auth/refresh.ts b/packages/cli/src/commands/auth/refresh.ts index a196ed5762..eb696064b2 100644 --- a/packages/cli/src/commands/auth/refresh.ts +++ b/packages/cli/src/commands/auth/refresh.ts @@ -8,6 +8,7 @@ import { failCommand } from "../../utils/commandResult.js"; * job. Status's 401-retry path already does this automatically. */ +import { terminalLines } from "@hyperframes/core"; import { defineCommand } from "../../utils/defineCommand.js"; import { assertOAuthConfiguredOrExit, @@ -39,8 +40,8 @@ export default defineCommand({ console.log(c.success("✓ Refreshed OAuth access token.")); } catch (err) { if (isAuthError(err) && err.code === "REFRESH_FAILED") { - console.error(c.error(err.message)); - if (err.hint) console.error(c.dim(err.hint)); + console.error(c.error(terminalLines(err.message))); + if (err.hint) console.error(c.dim(terminalLines(err.hint))); failCommand(); } throw err; diff --git a/packages/cli/src/commands/auth/status-user.test.ts b/packages/cli/src/commands/auth/status-user.test.ts index cd1265aca3..70ed0a1249 100644 --- a/packages/cli/src/commands/auth/status-user.test.ts +++ b/packages/cli/src/commands/auth/status-user.test.ts @@ -1,3 +1,4 @@ +import { mkdir } from "node:fs/promises"; import { join } from "node:path"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { writeStore } from "../../auth/store.js"; @@ -12,8 +13,14 @@ import { consumeCommandResult } from "../../utils/commandResult.js"; // - user: the live identity returned on success const probeState = vi.hoisted( () => - ({ apiReject: false, offline: false, user: { email: "live@example.com" } }) as { + ({ + apiReject: false, + apiDetail: "service unavailable", + offline: false, + user: { email: "live@example.com" }, + }) as { apiReject: boolean; + apiDetail: string; offline: boolean; user: Record; }, @@ -35,7 +42,7 @@ vi.mock("../../auth/index.js", async (orig) => { } if (probeState.apiReject) { const { ErrApi } = await import("../../auth/errors.js"); - throw ErrApi(503, "service unavailable"); + throw ErrApi(503, probeState.apiDetail); } return probeState.user; } @@ -50,6 +57,7 @@ describe("auth status — persisted user block surface", () => { beforeEach(async () => { envFixture = await setupTempAuthEnv("hf-status-99-"); probeState.apiReject = false; + probeState.apiDetail = "service unavailable"; probeState.offline = false; probeState.user = { email: "live@example.com" }; stdout = []; @@ -237,4 +245,110 @@ describe("auth status — persisted user block surface", () => { expect(await runStatus(false)).toBe(1); expect(stdout.join("\n")).toContain("cached@example.com"); }); + + describe("rows printed for people", () => { + const ESC = String.fromCharCode(27); + const ODD = `od${ESC}[2Jd\x07`; + const SHOWN = "od\\x1b[2Jd\\x07"; + const expectNoRawCodes = (text: string): void => { + expect(text.replace(new RegExp(`${ESC}\\[[0-9;]*m`, "g"), "")).not.toContain(ESC); + expect(text).not.toContain("\x07"); + }; + + // fails without the fix: the account and billing values are printed as they arrived. + it("shows control characters in the account and billing rows as text", async () => { + probeState.user = { + email: `${ODD}@example.com`, + billing_type: `type ${ODD}`, + wallet: { remaining_balance: 5, currency: `cur ${ODD}` }, + subscription: { + plan: `plan ${ODD}`, + credits: { premium_credits: { remaining: 3, resets_at: `${ODD}-01` } }, + }, + usage_based: { spending_current_usd: 1, spending_cap_usd: `cap ${ODD}` }, + }; + await writeStore({ api_key: "hg_x" }); + expect(await runStatus(false)).toBe(0); + const text = stdout.join("\n"); + for (const row of [ + `Account: ${SHOWN}@example.com`, + `Billing: type ${SHOWN}`, + `5 cur ${SHOWN}`, + `plan ${SHOWN}`, + `3 (resets ${SHOWN}`, + `$1 / $cap ${SHOWN}`, + ]) + expect(text).toContain(row); + expectNoRawCodes(text); + }); + + // fails without the fix: the scope and the plan name are printed as they arrived. + it("shows control characters in the scope and plan rows as text", async () => { + vi.stubGlobal( + "fetch", + async () => + new Response( + JSON.stringify({ + data: { + subscription: { plan_name: `pro ${ODD}`, status: "active" }, + usage: { remaining_units: 7 }, + }, + }), + ), + ); + await persistFreshOAuth({ access_token: "at", refresh_token: "rt", scope: `openid ${ODD}` }); + expect(await runStatus(false)).toBe(0); + const text = stdout.join("\n"); + expect(text).toContain(`openid ${SHOWN}`); + expect(text).toContain(`pro ${SHOWN} plan, 7 credits`); + expectNoRawCodes(text); + }); + + // fails without the fix: the failure reason and the cached name are printed as they arrived. + it("shows control characters in a failed check and the cached account as text", async () => { + await writeStore({ api_key: "hg_x", user: { email: `${ODD}@example.com` } }); + probeState.apiReject = true; + probeState.apiDetail = `down ${ODD}`; + expect(await runStatus(false)).toBe(1); + const text = stdout.join("\n"); + expect(text).toContain(`HeyGen API error (503): down ${SHOWN}`); + expect(text).toContain(`${SHOWN}@example.com`); + expectNoRawCodes(text); + }); + + // fails without the fix: the folder name is printed as it is on disk. + it.skipIf(process.platform === "win32")( + "shows control characters in the credential file's path as text", + async () => { + const odd = join(envFixture.dir, `cfg ${ODD}`); + process.env["HYPERFRAMES_CONFIG_DIR"] = odd; + await writeStore({ api_key: "hg_x" }); + expect(await runStatus(false)).toBe(0); + expect(stdout.join("\n")).toContain(`cfg ${SHOWN}`); + expectNoRawCodes(stdout.join("\n")); + }, + ); + + // fails without the fix: the unreadable file's path is printed as it is on disk. + it.skipIf(process.platform === "win32")( + "shows control characters in an unreadable credential file's message as text", + async () => { + const odd = join(envFixture.dir, `cfg ${ODD}`); + process.env["HYPERFRAMES_CONFIG_DIR"] = odd; + await mkdir(join(odd, "credentials"), { recursive: true }); + const stderr: string[] = []; + vi.spyOn(console, "error").mockImplementation((...args: unknown[]) => { + stderr.push(args.join(" ")); + }); + const cmd = (await import("./status.js")).default; + await expect( + (cmd.run as (ctx: { args: Record }) => Promise)({ + args: { json: false }, + }), + ).rejects.toThrow(); + expect(stderr.join("\n")).toContain(`cfg ${SHOWN}`); + expectNoRawCodes(stderr.join("\n")); + }, + ); + }); }); diff --git a/packages/cli/src/commands/auth/status.ts b/packages/cli/src/commands/auth/status.ts index bc45bbdbb9..675af8db1f 100644 --- a/packages/cli/src/commands/auth/status.ts +++ b/packages/cli/src/commands/auth/status.ts @@ -1,3 +1,4 @@ +import { terminalLines, terminalText } from "@hyperframes/core"; import { failCommand, setCommandExitCode } from "../../utils/commandResult.js"; /** * `hyperframes auth status` — print the active credential's source, @@ -165,8 +166,8 @@ function handleResolveError(err: unknown, asJson: boolean): never { JSON.stringify({ configured: false, ...jsonFailure("auth_error", err.message, err.hint) }), ); } else { - console.error(c.error(err.message)); - if (err.hint) console.error(c.dim(err.hint)); + console.error(c.error(terminalLines(err.message))); + if (err.hint) console.error(c.dim(terminalLines(err.hint))); } failCommand(1, new AuthStatusUnavailable(err.code)); } @@ -297,11 +298,11 @@ function collectStatusRows(s: VerifiedStatus): [string, string][] { ]; if (s.credential.type === "oauth") rows.push(...oauthRows(s.credential)); if (s.apiError) { - rows.push([c.error("API check failed:"), s.apiError]); + rows.push([c.error("API check failed:"), terminalLines(s.apiError)]); // Fall back to the persisted identity so the user still sees who // they're logged in as when the live probe is unreachable. const cached = s.persistedUser && userDisplayName(s.persistedUser); - if (cached) rows.push(["Account:", `${cached} ${c.dim("(cached)")}`]); + if (cached) rows.push(["Account:", `${terminalText(cached)} ${c.dim("(cached)")}`]); return rows; } if (s.user) rows.push(...identityRows(s.user, billingProduct(s.credential), !!s.plan)); @@ -311,10 +312,10 @@ function collectStatusRows(s: VerifiedStatus): [string, string][] { rows.push([ "HyperFrames:", plan.plan === "none" - ? `Free · Upgrade to Pro: ${s.planUrl}${tag}` - : `${plan.plan} plan, ${plan.credits.toLocaleString("en-US")} credits${tag}`, + ? `Free · Upgrade to Pro: ${terminalText(String(s.planUrl))}${tag}` + : `${terminalText(plan.plan)} plan, ${plan.credits.toLocaleString("en-US")} credits${tag}`, ]); - if (plan.plan !== "none" && s.planUrl) rows.push([MANAGE_LABEL, s.planUrl]); + if (plan.plan !== "none" && s.planUrl) rows.push([MANAGE_LABEL, terminalText(s.planUrl)]); } return rows; } @@ -328,7 +329,7 @@ function oauthRows(credential: Extract): const refresh = credential.refreshable ? c.dim(" · refreshable") : ""; rows.push(["Expires:", `${credential.expires_at.toISOString()} ${tag}${refresh}`]); } - if (credential.scope) rows.push(["Scope: ", credential.scope]); + if (credential.scope) rows.push(["Scope: ", terminalText(credential.scope)]); return rows; } @@ -339,7 +340,7 @@ function identityRows( hasPlan = false, ): [string, string][] { const identity = user.email ?? user.username ?? "(unknown user)"; - const rows: [string, string][] = [["Account:", identity]]; + const rows: [string, string][] = [["Account:", terminalText(identity)]]; if (product === "hyperframes") return [ ...rows, @@ -366,14 +367,15 @@ const SOURCE_LABELS = { }; function describeSource(source: ResolvedCredential["source"]): string { - if (source === "file_legacy") return `file (${credentialPath()} — legacy plaintext)`; - if (source === "file_json") return `file (${credentialPath()})`; + if (source === "file_legacy") + return `file (${terminalText(credentialPath())} — legacy plaintext)`; + if (source === "file_json") return `file (${terminalText(credentialPath())})`; return SOURCE_LABELS[source]; } function billingRows(user: UserInfo): [string, string][] { const rows: [string, string][] = []; - if (user.billing_type) rows.push(["Billing:", user.billing_type]); + if (user.billing_type) rows.push(["Billing:", terminalText(user.billing_type)]); pushWalletRow(rows, user); pushSubscriptionRows(rows, user); pushUsageRow(rows, user); @@ -385,12 +387,12 @@ function pushWalletRow(rows: [string, string][], user: UserInfo): void { const balance = user.wallet?.remaining_balance; if (balance === undefined) return; const currency = user.wallet?.currency ? ` ${user.wallet.currency}` : ""; - rows.push(["Wallet: ", `${balance}${currency}`]); + rows.push(["Wallet: ", terminalText(`${balance}${currency}`)]); } // fallow-ignore-next-line complexity function pushSubscriptionRows(rows: [string, string][], user: UserInfo): void { - if (user.subscription?.plan) rows.push(["Plan: ", user.subscription.plan]); + if (user.subscription?.plan) rows.push(["Plan: ", terminalText(user.subscription.plan)]); pushCreditRow(rows, "Premium credits:", user.subscription?.credits?.premium_credits); pushCreditRow(rows, "Add-on credits: ", user.subscription?.credits?.add_on_credits); } @@ -403,7 +405,7 @@ function pushCreditRow( ): void { if (!credit || credit.remaining === undefined) return; const resets = credit.resets_at ? ` (resets ${credit.resets_at.slice(0, 10)})` : ""; - rows.push([label, `${credit.remaining}${resets}`]); + rows.push([label, terminalText(`${credit.remaining}${resets}`)]); } // fallow-ignore-next-line complexity @@ -412,5 +414,5 @@ function pushUsageRow(rows: [string, string][], user: UserInfo): void { if (current === undefined) return; const cap = user.usage_based?.spending_cap_usd; const capPart = cap !== undefined ? ` / $${cap}` : ""; - rows.push(["Usage: ", `$${current}${capPart}`]); + rows.push(["Usage: ", terminalText(`$${current}${capPart}`)]); } diff --git a/packages/cli/src/commands/billing.test.ts b/packages/cli/src/commands/billing.test.ts index ad9c67955a..db6d6b0536 100644 --- a/packages/cli/src/commands/billing.test.ts +++ b/packages/cli/src/commands/billing.test.ts @@ -194,6 +194,14 @@ describe("billing with no action", () => { expect(opened).toEqual([]); }); + // fails without the fix: the plan name reached the terminal with its control characters live. + it("shows a plan name's control characters as visible escapes", async () => { + const esc = String.fromCharCode(27); + const out = await printed([], { plan: `pro${esc}[2J`, credits: 500 }); + expect(out).toContain("HyperFrames: pro\\x1b[2J"); + expect(out).not.toContain(esc); + }); + it("shows Free with no manage line", async () => { const out = await printed([], { plan: "none", credits: 0 }); expect(out).toContain("HyperFrames: Free"); @@ -245,6 +253,21 @@ describe("billing numeric flags", () => { }); describe("billing without a terminal", () => { + // fails without the fix: the checkout link reached the terminal with its control characters live. + it("prints a checkout link's control characters as visible escapes", async () => { + const esc = String.fromCharCode(27); + held.checkout = Promise.resolve(`https://checkout.example.test/c${esc}[2J`); + const log = vi.spyOn(console, "log").mockImplementation(() => undefined); + vi.useFakeTimers(); + const done = runCommand(billing, { rawArgs: ["subscribe"] }); + await vi.advanceTimersByTimeAsync(2000); + await done; + vi.useRealTimers(); + const printed = log.mock.calls.flat().join("\n"); + expect(printed).toContain("Checkout link: https://checkout.example.test/c\\x1b[2J"); + expect(printed).not.toContain(esc); + }); + it("prints Stripe's checkout link instead of waiting for Enter, and opens only the pricing page", async () => { const log = vi.spyOn(console, "log").mockImplementation(() => undefined); vi.useFakeTimers(); @@ -371,6 +394,25 @@ describe("billing outcomes", () => { expect(events.timeout).toEqual([]); }); + // fails without the fix: the checkout failure reached the terminal with its control characters live. + it("prints a checkout failure's control characters as visible escapes", async () => { + const { CheckoutError } = await import("../heygen/plan.js"); + const esc = String.fromCharCode(27); + terminal.checkoutError = new CheckoutError("checkout_rejected", `No${esc}[2J checkout`); + never.paid = false; + vi.spyOn(console, "log").mockImplementation(() => undefined); + const error = vi.spyOn(console, "error").mockImplementation(() => undefined); + vi.useFakeTimers(); + const done = runCommand(billing, { rawArgs: ["subscribe", "--timeout", "4"] }); + const settled = expect(done).rejects.toThrow(); + await vi.advanceTimersByTimeAsync(6000); + await settled; + vi.useRealTimers(); + const printed = error.mock.calls.map((call) => call.join(" ")).join("\n"); + expect(printed).toContain("No\\x1b[2J checkout"); + expect(printed).not.toContain(`${esc}[2J`); + }); + it("stops at once when credits are not on sale, since the credits page cannot sell them either", async () => { const { CheckoutError } = await import("../heygen/plan.js"); terminal.checkoutError = new CheckoutError("checkout_unavailable", "Credits are not on sale"); diff --git a/packages/cli/src/commands/billing.ts b/packages/cli/src/commands/billing.ts index fb8b03cf17..9fc30f6961 100644 --- a/packages/cli/src/commands/billing.ts +++ b/packages/cli/src/commands/billing.ts @@ -1,4 +1,5 @@ import { createInterface } from "node:readline/promises"; +import { terminalLines, terminalText } from "@hyperframes/core"; import { openBrowser } from "../auth/browser.js"; import { addonBlocks, @@ -66,7 +67,7 @@ async function openCheckout( const { atEnter, needed, ...from } = source; if (isUnattended()) { const link = await createCheckout(kind, offer, missing, { ...from, stop: signal }); - if (!signal.aborted) console.log(`Checkout link: ${c.accent(link)}`); + if (!signal.aborted) console.log(`Checkout link: ${c.accent(terminalText(link))}`); return; } const rl = createInterface({ input: process.stdin, output: process.stdout }); @@ -83,7 +84,7 @@ async function openCheckout( return; } const line = priceLine(kind, offer, fresh.missing, needed); - if (line && line !== priceLine(kind, offer, missing, needed)) console.log(line); + if (line && line !== priceLine(kind, offer, missing, needed)) console.log(terminalText(line)); const link = await createCheckout(kind, offer, fresh.missing, { ...from, stop: signal }); if (!signal.aborted) await openBrowser(link); } @@ -101,7 +102,7 @@ async function offerCheckout( const shortBy = (p: Plan) => (needed ? needed - p.credits : undefined); const missing = shortBy(before); const line = priceLine(kind, offer, missing, needed); - if (line) console.log(line); + if (line) console.log(terminalText(line)); const atEnter: AtEnter = async () => { const now = await readPlan(signal); if (done(now)) return { covered: true }; @@ -124,7 +125,7 @@ async function readPlanBefore(stop: AbortSignal): Promise { } function reportCheckoutFailure(error: unknown): CheckoutError | null { - console.error(c.error(error instanceof Error ? error.message : String(error))); + console.error(c.error(terminalLines(error instanceof Error ? error.message : String(error)))); if (!(error instanceof CheckoutError)) return null; trackBillingCheckoutFailed({ reason: error.reason }); return error; @@ -132,10 +133,10 @@ function reportCheckoutFailure(error: unknown): CheckoutError | null { async function showPlan(open: boolean): Promise { const plan = await readPlan(); - console.log(`HyperFrames: ${plan ? describe(plan) : "plan unavailable"}`); + console.log(`HyperFrames: ${plan ? terminalText(describe(plan)) : "plan unavailable"}`); if (plan?.plan === "none" && !open) return; const url = await pageUrl("manage"); - console.log(`${MANAGE_LABEL} ${c.accent(url)}`); + console.log(`${MANAGE_LABEL} ${c.accent(terminalText(url))}`); if (open && !isUnattended()) await openBrowser(url); } @@ -192,7 +193,7 @@ export default defineCommand({ ? !!p && p.plan !== "none" : !!p && p.plan !== "none" && p.credits >= (needed ?? (before?.credits ?? 0) + 1); if (done(before) && (action === "subscribe" || needed)) { - console.log(c.success(`✓ Already covered: ${describe(before)}.`)); + console.log(c.success(`✓ Already covered: ${terminalText(describe(before))}.`)); return; } const url = await pageUrl(action === "subscribe" ? "plans" : "credits", { @@ -202,7 +203,9 @@ export default defineCommand({ rs: args.session, skill, }); - console.log(`${action === "subscribe" ? "Plans" : "Credits"} page: ${c.accent(url)}`); + console.log( + `${action === "subscribe" ? "Plans" : "Credits"} page: ${c.accent(terminalText(url))}`, + ); await openBrowser(url); const giveUp = new AbortController(); const waiting = (async () => { @@ -233,7 +236,7 @@ export default defineCommand({ console.log("Waiting for the person to finish ..."); const now = await waiting; if (now) { - console.log(c.success(`✓ Done: ${describe(now)}. Carry on.`)); + console.log(c.success(`✓ Done: ${terminalText(describe(now))}. Carry on.`)); return; } console.error( diff --git a/packages/cli/src/commands/feedback.reproFailure.test.ts b/packages/cli/src/commands/feedback.reproFailure.test.ts new file mode 100644 index 0000000000..8f9b1386e2 --- /dev/null +++ b/packages/cli/src/commands/feedback.reproFailure.test.ts @@ -0,0 +1,68 @@ +import { mkdirSync, mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { expect, it, vi } from "vitest"; + +vi.mock("../telemetry/client.js", () => ({ shouldTrack: () => true, flush: async () => {} })); +vi.mock("../telemetry/events.js", () => ({ + trackCatalogSearchMiss: vi.fn(), + trackFeedbackComment: vi.fn(), + trackRenderFeedback: vi.fn(), +})); +vi.mock("../telemetry/feedback.js", () => ({ getDoctorSummary: async () => "os=test" })); +vi.mock("../telemetry/config.js", () => ({ readConfig: () => ({ anonymousId: "a" }) })); +vi.mock("../telemetry/uploadLeftOut.js", () => ({ trackUploadLeftOut: vi.fn() })); +vi.mock("../utils/submitFeedback.js", () => ({ + submitFeedback: async () => {}, + submitCatalogSearchMiss: async () => {}, +})); +vi.mock("open", () => ({ default: async () => {} })); +vi.mock("../utils/publishProject.js", () => ({ + createPublishArchive: () => ({}), + publishProjectArchive: async () => { + throw new Error("Upload refused: scenes/a\u001b[2Jb.html\nTry again later"); + }, +})); + +// fails without the fix: the publish failure reached the terminal with its control characters live. +it("prints a publish failure's control characters as visible escapes", async () => { + const dir = mkdtempSync(join(tmpdir(), "hf-feedback-repro-")); + const log = vi.spyOn(console, "log").mockImplementation(() => {}); + const error = vi.spyOn(console, "error").mockImplementation(() => {}); + try { + const { default: feedback } = await import("./feedback.js"); + await feedback.run?.({ args: { rating: "8", "file-issue": true, yes: true, dir } } as never); + expect(error.mock.calls.map((call) => call.join(" "))).toEqual([ + " Upload refused: scenes/a\\x1b[2Jb.html\nTry again later", + ]); + } finally { + log.mockRestore(); + error.mockRestore(); + rmSync(dir, { recursive: true, force: true }); + } +}); + +// fails without the fix: the project folder name reached the terminal with its control characters live. +it.skipIf(process.platform === "win32")( + "prints the project folder's control characters as visible escapes before publishing", + async () => { + const root = mkdtempSync(join(tmpdir(), "hf-feedback-consent-")); + const dir = join(root, "pro\u001b[2Jject"); + mkdirSync(dir); + const lines: string[] = []; + const log = vi.spyOn(console, "log").mockImplementation((...parts: unknown[]) => { + lines.push(parts.map(String).join(" ")); + }); + const error = vi.spyOn(console, "error").mockImplementation(() => {}); + try { + const { default: feedback } = await import("./feedback.js"); + await feedback.run?.({ args: { rating: "8", "file-issue": true, yes: true, dir } } as never); + expect(lines.join("\n")).toContain("pro\\x1b[2Jject will be uploaded to a public URL."); + expect(lines.join("\n")).not.toContain("pro\u001b[2Jject"); + } finally { + log.mockRestore(); + error.mockRestore(); + rmSync(root, { recursive: true, force: true }); + } + }, +); diff --git a/packages/cli/src/commands/feedback.ts b/packages/cli/src/commands/feedback.ts index 90aab00cb6..1890057d49 100644 --- a/packages/cli/src/commands/feedback.ts +++ b/packages/cli/src/commands/feedback.ts @@ -1,6 +1,7 @@ import { failUsage } from "../utils/commandResult.js"; import { randomUUID } from "node:crypto"; import { resolve } from "node:path"; +import { terminalLines, terminalText } from "@hyperframes/core"; import { defineCommand } from "../utils/defineCommand.js"; import * as clack from "../ui/prompts.js"; import open from "open"; @@ -91,7 +92,7 @@ function printIssueConsent(dir: string): void { console.log( ` ${c.bold("Filing an issue will publish this project publicly and open a GitHub issue draft.")}`, ); - console.log(` ${c.dim(`Project at ${dir} will be uploaded to a public URL.`)}`); + console.log(` ${c.dim(`Project at ${terminalText(dir)} will be uploaded to a public URL.`)}`); console.log( ` ${c.dim("The issue draft will contain that public link plus your feedback; you review and submit it.")}`, ); @@ -160,16 +161,16 @@ async function publishRepro( trackUploadLeftOut("feedback", references); if (outsideFiles.length > 0) { spinner.stop("Repro prepared"); - clack.log.info(outsideFilesNotice(outsideFiles)); + clack.log.info(terminalLines(outsideFilesNotice(outsideFiles))); spinner.start("Publishing minimal repro..."); } const published = await publishProjectArchive(dir, { archive }); spinner.stop(c.success("Repro published")); - for (const warning of leftOut) clack.log.warn(c.warn(warning)); + for (const warning of leftOut) clack.log.warn(c.warn(terminalLines(warning))); return published.url; } catch (err: unknown) { spinner.stop(c.error("Publish failed")); - console.error(` ${(err as Error).message}`); + console.error(` ${terminalLines((err as Error).message)}`); console.log(` ${c.dim("Filing the issue without a repro link.")}`); return undefined; } @@ -183,7 +184,7 @@ async function publishRepro( */ function printFeedbackLintWarnings(input: FeedbackLintInput): void { for (const warning of lintFeedbackComment(input)) { - console.log(c.warn(`⚠ ${warning.message}`)); + console.log(c.warn(`⚠ ${terminalLines(warning.message)}`)); } } @@ -197,7 +198,7 @@ async function openAndPrintIssue(url: string): Promise { } console.log(); console.log(` ${c.dim("Review and submit the pre-filled issue (it is not auto-submitted):")}`); - console.log(` ${c.accent(url)}`); + console.log(` ${c.accent(terminalText(url))}`); console.log(); } diff --git a/packages/cli/src/commands/publish.test.ts b/packages/cli/src/commands/publish.test.ts index 2fca0ad861..52514d1eba 100644 --- a/packages/cli/src/commands/publish.test.ts +++ b/packages/cli/src/commands/publish.test.ts @@ -5,6 +5,7 @@ import { tmpdir } from "node:os"; const publishState = vi.hoisted(() => ({ publish: vi.fn(), + credentialError: null as Error | null, noticeRelease: null as string | null, confirm: vi.fn(), })); @@ -22,6 +23,16 @@ vi.mock("../utils/attendedTerminal.js", async (importOriginal) => ({ vi.mock("../utils/publishProject.js", async (importOriginal) => ({ ...(await importOriginal()), publishProjectArchive: publishState.publish, + resolvePublishCredential: async ( + ...args: Parameters + ) => { + if (publishState.credentialError) throw publishState.credentialError; + return ( + await vi.importActual( + "../utils/publishProject.js", + ) + ).resolvePublishCredential(...args); + }, })); vi.mock("../share/publishTransition.js", async (importOriginal) => { @@ -309,6 +320,62 @@ describe("publish visibility messaging", () => { } }); + // fails without the fix: the stored link of an earlier publish reached the terminal with its control characters live. + it("prints an earlier publish's link with control characters as visible escapes", async () => { + const esc = String.fromCharCode(27); + const project = mkdtempSync(join(tmpdir(), "hf-publish-prior-link-")); + const config = mkdtempSync(join(tmpdir(), "hf-publish-prior-link-config-")); + vi.stubEnv("HYPERFRAMES_CONFIG_DIR", config); + vi.stubEnv("HEYGEN_API_KEY", ""); + vi.stubEnv("HYPERFRAMES_API_KEY", ""); + writeFileSync(join(project, "index.html"), VISIBLE_INDEX); + writeProjectLink(project, { + projectId: "earlier", + url: `https://hyperframes.dev/p/e${esc}[2J`, + }); + await writeStore({ oauth: { access_token: "fixture-token" } }, join(config, "credentials")); + mockPublished({ + projectId: "earlier", + url: "https://hyperframes.dev/p/earlier", + updated: true, + }); + try { + const printed = await captureLog(() => + publishCommand.run?.({ args: { dir: project, yes: true, proxy: false } } as never), + ); + expect(printed).toContain("Previously published at https://hyperframes.dev/p/e\\x1b[2J"); + expect(printed).not.toContain(`e${esc}[2J`); + } finally { + vi.unstubAllEnvs(); + rmSync(project, { recursive: true, force: true }); + rmSync(config, { recursive: true, force: true }); + } + }); + + // fails without the fix: the sign-in failure reached the terminal with its control characters live. + it("prints a sign-in failure with control characters as visible escapes", async () => { + const esc = String.fromCharCode(27); + const project = mkdtempSync(join(tmpdir(), "hf-publish-sign-in-failure-")); + writeFileSync(join(project, "index.html"), VISIBLE_INDEX); + publishState.credentialError = new Error(`Sign-in refused${esc}[2J\nRun auth login`); + const lines: string[] = []; + const error = vi.spyOn(console, "error").mockImplementation((...parts: unknown[]) => { + lines.push(parts.map(String).join(" ")); + }); + try { + await captureLog(() => + publishCommand.run?.({ args: { dir: project, yes: true, proxy: false } } as never), + ); + expect(consumeCommandResult().exitCode).toBe(1); + expect(lines.join("\n")).toContain(" Sign-in refused\\x1b[2J\nRun auth login"); + expect(lines.join("\n")).not.toContain(esc); + } finally { + publishState.credentialError = null; + error.mockRestore(); + rmSync(project, { recursive: true, force: true }); + } + }); + it("prints a publish failure with control characters as visible escapes", async () => { const esc = String.fromCharCode(27); const project = mkdtempSync(join(tmpdir(), "hf-publish-failure-")); diff --git a/packages/cli/src/commands/publish.ts b/packages/cli/src/commands/publish.ts index ea7860a7c3..eff83d23c3 100644 --- a/packages/cli/src/commands/publish.ts +++ b/packages/cli/src/commands/publish.ts @@ -166,7 +166,7 @@ export default defineCommand({ credential = await resolvePublishCredential(); } catch (err: unknown) { console.error(); - console.error(` ${(err as Error).message}`); + console.error(` ${terminalLines((err as Error).message)}`); console.error(); setCommandExitCode(1); return; @@ -225,7 +225,7 @@ export default defineCommand({ args.public === true ? "" : " and keeps its current visibility, which may be public"; const created = args.public === true ? "public" : "private"; console.log( - ` ${c.bold(`If you can access project ${existingTarget}, this updates it in place${keeps}. Otherwise it creates a new ${created} project.`)}`, + ` ${c.bold(`If you can access project ${terminalText(existingTarget)}, this updates it in place${keeps}. Otherwise it creates a new ${created} project.`)}`, ); } console.log(); @@ -247,7 +247,7 @@ export default defineCommand({ // user knows a re-publish updates that same link (when logged in). if (priorLink?.url) { console.log(); - console.log(` ${c.dim(`Previously published at ${priorLink.url}`)}`); + console.log(` ${c.dim(`Previously published at ${terminalText(priorLink.url)}`)}`); } clack.intro(c.bold("hyperframes publish")); @@ -297,7 +297,7 @@ export default defineCommand({ const archive = zipPublishFileMap(fileMap); if (outsideFiles.length > 0) { publishSpinner.stop("Project prepared"); - clack.log.info(outsideFilesNotice(outsideFiles)); + clack.log.info(terminalLines(outsideFilesNotice(outsideFiles))); publishSpinner.start("Uploading project..."); } else { publishSpinner.message("Uploading project..."); @@ -371,7 +371,7 @@ export default defineCommand({ const file = writeTeamProject(dir, { projectId: published.projectId, spaceId }); console.log(); console.log( - ` ${c.dim(`Wrote ${relative(dir, file) || file} — commit it so your team publishes to this link.`)}`, + ` ${c.dim(`Wrote ${terminalText(relative(dir, file) || file)} — commit it so your team publishes to this link.`)}`, ); } catch { // Convenience file only; never shadow a successful publish with a local write failure. @@ -381,7 +381,9 @@ export default defineCommand({ } else { const claimUrl = new URL(published.url); claimUrl.searchParams.set("claim_token", published.claimToken); - console.log(` ${c.dim("Claim URL")} ${c.accent(cliSourced(claimUrl.toString()))}`); + console.log( + ` ${c.dim("Claim URL")} ${c.accent(terminalText(cliSourced(claimUrl.toString())))}`, + ); console.log(` ${c.dim("Access")} ${c.accent("Sign in required to claim")}`); console.log(); console.log( diff --git a/packages/cli/src/commands/share.test.ts b/packages/cli/src/commands/share.test.ts index 4319b21f90..74cdbfb675 100644 --- a/packages/cli/src/commands/share.test.ts +++ b/packages/cli/src/commands/share.test.ts @@ -119,6 +119,33 @@ it("deduplicates progress and terminates each message before the friendly error" expect(friendly).toHaveBeenCalledWith("Sharing blocked."); }); +// fails without the fix: the failure line reached the terminal with its control characters live. +it("prints a failure's control characters as visible escapes", async () => { + const esc = String.fromCharCode(27); + const friendly = vi.spyOn(console, "error").mockImplementation(() => {}); + vi.spyOn(console, "log").mockImplementation(() => {}); + mocks.run.mockRejectedValue(new Error(`Sharing blocked${esc}[2J.\nTry again`)); + await runCommand(command, { rawArgs: ["--private", "-y"] }); + expect(friendly).toHaveBeenLastCalledWith("Sharing blocked\\x1b[2J.\nTry again"); +}); + +// fails without the fix: a failed export's reason reached the terminal with its control characters live. +it("prints a failed export's control characters as visible escapes", async () => { + const esc = String.fromCharCode(27); + const friendly = vi.spyOn(console, "error").mockImplementation(() => {}); + mocks.run.mockResolvedValue({ + state: "failed", + ready: false, + url: null, + previousUrl: null, + manageUrl: "https://hyperframes.dev/shares", + source: { at: "not_checked" }, + version: { failure: `Export stopped${esc}]0;t${String.fromCharCode(7)}` }, + }); + await runCommand(command, { rawArgs: ["--status"] }); + expect(friendly).toHaveBeenLastCalledWith("Export stopped\\x1b]0;t\\x07"); +}); + it.each(["owner@example.com", "another@example.com"])( "keeps the owner error code stable for %s", async (owner) => { @@ -317,3 +344,42 @@ describe("a received folder whose record names an existing review", () => { ); }); }); + +// fails without the fix: the finished share's link reached the terminal with its control characters live. +it("prints a ready share's link with control characters as visible escapes", async () => { + const esc = String.fromCharCode(27); + const log = vi.spyOn(console, "log").mockImplementation(() => {}); + mocks.run.mockResolvedValue({ + state: "shared", + ready: true, + url: `https://hyperframes.dev/review/a${esc}[2J`, + previousUrl: null, + manageUrl: "https://hyperframes.dev/shares", + source: { at: "not_checked" }, + version: {}, + }); + await runCommand(command, { rawArgs: ["--status"] }); + expect(log).toHaveBeenLastCalledWith( + "Shared video ready: https://hyperframes.dev/review/a\\x1b[2J", + ); +}); + +// fails without the fix: the earlier version's link reached the terminal with its control characters live. +it("prints the earlier version's link with control characters as visible escapes", async () => { + const esc = String.fromCharCode(27); + vi.spyOn(console, "error").mockImplementation(() => {}); + const log = vi.spyOn(console, "log").mockImplementation(() => {}); + mocks.run.mockResolvedValue({ + state: "failed", + ready: false, + url: null, + previousUrl: `https://hyperframes.dev/review/b${esc}[2J`, + manageUrl: "https://hyperframes.dev/shares", + source: { at: "not_checked" }, + version: { failure: "Export stopped" }, + }); + await runCommand(command, { rawArgs: ["--status"] }); + expect(log).toHaveBeenLastCalledWith( + "Previous shared version: https://hyperframes.dev/review/b\\x1b[2J", + ); +}); diff --git a/packages/cli/src/commands/share.ts b/packages/cli/src/commands/share.ts index fba948f221..b989b3862f 100644 --- a/packages/cli/src/commands/share.ts +++ b/packages/cli/src/commands/share.ts @@ -4,7 +4,7 @@ import { CliUsageError, setCommandExitCode } from "../utils/commandResult.js"; import { isUnattended } from "../utils/attendedTerminal.js"; import * as prompts from "../ui/prompts.js"; import { c } from "../ui/colors.js"; -import { terminalText } from "@hyperframes/core"; +import { terminalLines, terminalText } from "@hyperframes/core"; import { receivedRecordStatus } from "../utils/privateProjectFile.js"; import { changesNamedReview, @@ -78,7 +78,7 @@ export default defineCommand({ let lastProgress = ""; const service: ShareService = createShareService(project.dir, (value) => { if (!value || args.json) return; - const message = `Sharing: ${value.step}${value.slow ? " (still processing)" : ""}`; + const message = `Sharing: ${terminalText(value.step)}${value.slow ? " (still processing)" : ""}`; if (message !== lastProgress) process.stderr.write(`${message}\n`); lastProgress = message; }); @@ -92,7 +92,7 @@ export default defineCommand({ console.log( JSON.stringify({ ...jsonFailure(failure.code, failure.message), error: failure }), ); - else console.error(failure.message); + else console.error(terminalLines(failure.message)); setCommandExitCode(error instanceof CliUsageError ? 2 : 1); } }, @@ -277,13 +277,13 @@ async function presentSuccessfulResult(result: ShareState, input: ShareAction, j if (json) console.log(JSON.stringify({ ok: true, ...result })); else if (result.activity) console.log( - `Sharing: ${result.activity.step.replaceAll("_", " ")}. Run hyperframes share --status to check progress.`, + `Sharing: ${terminalText(result.activity.step.replaceAll("_", " "))}. Run hyperframes share --status to check progress.`, ); else if (result.upToDate) console.log("Already up to date."); else if (input.action === "manage") { - console.log(result.manageUrl); + console.log(terminalText(result.manageUrl)); if (!isUnattended()) await (await import("open")).default(result.manageUrl); - } else if (result.ready) console.log(`Shared video ready: ${result.url}`); + } else if (result.ready) console.log(`Shared video ready: ${terminalText(String(result.url))}`); else if (result.state === "not_shared") console.log("This project has not been shared yet."); else if (result.state === "link_off") console.log("This share's link is off. Run hyperframes share --manage to turn it on."); @@ -295,8 +295,9 @@ function presentFailure(result: ShareState, json: boolean) { if (json) console.log(JSON.stringify({ ...result, ...jsonFailure("share_export_failed", message) })); else { - console.error(message); - if (result.previousUrl) console.log(`Previous shared version: ${result.previousUrl}`); + console.error(terminalLines(message)); + if (result.previousUrl) + console.log(`Previous shared version: ${terminalText(result.previousUrl)}`); } setCommandExitCode(1); }