Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions docs/packages/cli.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -2409,6 +2409,10 @@ prompting, `--yes, -y` upgrades a detected global install (otherwise it prints
the right `npx` command; an unattended run without `--yes` or `--check` exits 2),
and `--project [dir]` rewrites
`hyperframes@<version>` script pins in a project's `package.json`.
Foreground and background CLI updates run the global package manager from your home directory.
Run global CLI updates directly from your shell. An npm, pnpm, or Bun package script can pass project settings to its children, so the CLI skips self-installation in that context.
On POSIX systems, the home directory must belong to the effective user and allow writes only by its owner. If `sudo` retains a different user's home, the update reports the ownership mismatch. A skipped background install reports its reason on stderr.

`--check --json` returns:

```json
Expand Down
8 changes: 7 additions & 1 deletion packages/cli/src/commands/update.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
// only spawn, the config file, the manifest fetch/disk and the registry are stubbed.

import { homeCliCommand } from "../utils/homeCliCommand.js";
import { homedir } from "node:os";
import { EventEmitter } from "node:events";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";

Expand Down Expand Up @@ -131,6 +132,7 @@ beforeEach(() => {
}),
);
for (const name of [
"npm_lifecycle_event",
"HYPERFRAMES_PLUGIN_VERSION",
"HYPERFRAMES_SKIP_SKILLS",
"HYPERFRAMES_AGENT",
Expand Down Expand Up @@ -261,7 +263,11 @@ describe("hyperframes update (install)", () => {
expect(installs()).toHaveLength(1);
expect(installs()[0]).toMatchObject({ command: bin, args });
// The child's stdout goes to stderr: a --json stdout stays one parseable object.
expect(installs()[0]!.opts).toMatchObject({ shell: false, stdio: ["inherit", 2, 2] });
expect(installs()[0]!.opts).toMatchObject({
cwd: homedir(),
shell: false,
stdio: ["inherit", 2, 2],
});
expect(skillsAdds()).toHaveLength(1);
expect(skillsAdds()[0]!.args).toContain("https://github.com/heygen-com/hyperframes#v0.9.8");
expect(json().updated).toMatchObject({
Expand Down
4 changes: 3 additions & 1 deletion packages/cli/src/commands/update.ts
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,9 @@ function cliOutcomeLine(cli: UpdateOutcome["cli"]): string {
case "manual":
return c.warn(`CLI: run ${cli.command} (${cli.reason}).`);
case "failed":
return c.error(`CLI upgrade failed. Run: ${cli.command}`);
return c.error(
cli.reason ?? `CLI upgrade failed. From your home directory, run: ${cli.command}`,
);
default:
return c.success("CLI is up to date.");
}
Expand Down
43 changes: 42 additions & 1 deletion packages/cli/src/commands/upgrade.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { homedir } from "node:os";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";

/**
* Pins the security-relevant contract of the `--yes` install path: the detected
Expand All @@ -8,8 +9,11 @@ import { afterEach, describe, expect, it, vi } from "vitest";
* in installerDetection.test.ts; this locks how it's executed.
*/
describe("runDetectedInstall", () => {
beforeEach(() => vi.stubEnv("npm_lifecycle_event", ""));
afterEach(() => {
vi.unstubAllEnvs();
vi.doUnmock("node:child_process");
vi.doUnmock("node:os");
vi.resetModules();
});

Expand All @@ -27,11 +31,48 @@ describe("runDetectedInstall", () => {

expect(execSpy).toHaveBeenCalledTimes(1);
expect(execSpy).toHaveBeenCalledWith("bun", ["add", "-g", "hyperframes@1.2.3"], {
cwd: homedir(),
stdio: "inherit",
shell: false,
});
});

it.each([
["", /home directory/],
["preview", /outside the package script/],
] as const)(
"reports why both foreground installs were skipped (package event %j)",
async (event, reason) => {
vi.stubEnv("npm_lifecycle_event", event);
const execSpy = vi.fn();
vi.doMock("node:child_process", () => ({ execFileSync: execSpy }));
vi.doMock("node:os", async (importOriginal) => ({
...(await importOriginal<typeof import("node:os")>()),
homedir: () => ".",
}));

const { runDetectedInstall, upgradeRunningCli } = await import("./upgrade.js");
const { consumeCommandResult } = await import("../utils/commandResult.js");
const argv = process.argv;
try {
process.argv = [process.execPath, "/usr/local/lib/node_modules/hyperframes/dist/cli.js"];
expect(upgradeRunningCli("1.2.3")).toMatchObject({
status: "failed",
reason: expect.stringMatching(reason),
});
runDetectedInstall(
{ bin: "npm", args: ["install", "-g", "hyperframes@1.2.3"] },
"npm install -g hyperframes@1.2.3",
"1.2.3",
);
expect(consumeCommandResult().exitCode).toBe(1);
expect(execSpy).not.toHaveBeenCalled();
} finally {
process.argv = argv;
}
},
);

it("sets a non-zero exit code when the install fails, without throwing", async () => {
const execSpy = vi.fn(() => {
throw new Error("install boom");
Expand Down
29 changes: 23 additions & 6 deletions packages/cli/src/commands/upgrade.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { homeCliCommand } from "../utils/homeCliCommand.js";
import { globalInstallLocation, homeCliCommand } from "../utils/homeCliCommand.js";
import { setCommandExitCode } from "../utils/commandResult.js";
import { defineCommand } from "../utils/defineCommand.js";
import type { Example } from "./_examples.js";
Expand Down Expand Up @@ -170,17 +170,19 @@ export type CliUpgradeOutcome =
| { status: "unchanged"; version: string; command: string; reason: string }
| { status: "unverified"; command: string; reason: string }
| { status: "manual"; command: string; reason: string }
| { status: "failed"; command: string };
| { status: "failed"; command: string; reason?: string };

/** The version Homebrew's linked `hyperframes` reports, or null when it cannot be read. */
function brewInstalledVersion(): string | null {
function brewInstalledVersion(cwd: string): string | null {
try {
const prefix = execFileSync("brew", ["--prefix", "hyperframes"], {
cwd,
encoding: "utf8",
stdio: ["ignore", "pipe", "ignore"],
shell: false,
}).trim();
const version = execFileSync(join(prefix, "bin", "hyperframes"), ["--version"], {
cwd,
encoding: "utf8",
stdio: ["ignore", "pipe", "ignore"],
shell: false,
Expand All @@ -200,16 +202,21 @@ export function upgradeRunningCli(latest: string): CliUpgradeOutcome {
if (!isSafeVersion(latest)) return { status: "failed", command: NPX_LATEST };
const plan = upgradePlan(latest);
if ("manual" in plan) return { status: "manual", command: plan.manual, reason: plan.reason };
const location = globalInstallLocation();
if ("reason" in location)
return { status: "failed", command: plan.displayCmd, reason: location.reason };
const { cwd } = location;
try {
execFileSync(plan.invocation.bin, plan.invocation.args, {
cwd,
stdio: ["inherit", 2, 2],
shell: false,
});
} catch {
return { status: "failed", command: plan.displayCmd };
}
// `brew upgrade` installs whatever the formula pins, which can lag npm, and exits 0 on a no-op.
const installed = plan.pinsVersion ? latest : brewInstalledVersion();
const installed = plan.pinsVersion ? latest : brewInstalledVersion(cwd);
const command = plan.displayCmd;
if (installed === null) {
return { status: "unverified", command, reason: "the installed version could not be read" };
Expand Down Expand Up @@ -327,16 +334,26 @@ export function runDetectedInstall(
displayCmd: string,
version: string,
): void {
const location = globalInstallLocation();
if ("reason" in location) {
clack.outro(c.dim(location.reason));
setCommandExitCode(1);
return;
}
console.log();
console.log(` ${c.dim("Running:")} ${c.accent(displayCmd)}`);
console.log();
try {
// shell:false — version is provably safe per isSafeVersion above; keep the
// no-shell call so future edits can't regress the injection surface.
execFileSync(invocation.bin, invocation.args, { stdio: "inherit", shell: false });
execFileSync(invocation.bin, invocation.args, {
cwd: location.cwd,
stdio: "inherit",
shell: false,
});
clack.outro(c.success(`Upgraded to v${version}`));
} catch {
clack.outro(c.dim("Install failed. Try running manually:"));
clack.outro(c.dim("Install failed. Retry from your home directory:"));
console.log(` ${c.accent(displayCmd)}`);
setCommandExitCode(1);
}
Expand Down
28 changes: 25 additions & 3 deletions packages/cli/src/utils/autoUpdate.installer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
mkdirSync,
mkdtempSync,
readFileSync,
realpathSync,
rmSync,
utimesSync,
writeFileSync,
Expand All @@ -29,10 +30,17 @@ function setup(staleMs = 60_000) {
mkdirSync(runningDir);
const marker = join(dir, "installed");
const script = installerScript({
cwd: dir,
configFile: join(dir, "config.json"),
version: "9.9.9",
bin: process.execPath,
args: ["-e", `require("node:fs").writeFileSync(${JSON.stringify(marker)}, "")`],
args: [
"-e",
`const fs = require("node:fs");
fs.writeFileSync(${JSON.stringify(marker)}, JSON.stringify({
cwd: process.cwd(), localConfig: fs.existsSync("bunfig.toml")
}));`,
],
runningDir,
pollMs: 50,
maxWaitMs: 60_000,
Expand All @@ -41,8 +49,8 @@ function setup(staleMs = 60_000) {
return { dir, runningDir, marker, script };
}

function start(args: string[]): ChildProcess {
const child = spawn(process.execPath, args, { stdio: "ignore" });
function start(args: string[], cwd?: string): ChildProcess {
const child = spawn(process.execPath, args, { cwd, stdio: "ignore" });
children.push(child);
return child;
}
Expand Down Expand Up @@ -74,6 +82,20 @@ function registerCli(runningDir: string): ChildProcess {
return cli;
}

it("runs the manager in the selected home even when the installer starts in a project", async () => {
const { dir, marker, script } = setup();
const project = join(dir, "project");
mkdirSync(project);
writeFileSync(join(project, "bunfig.toml"), "[install]\nexact = true\n");

await exited(start(["-e", script], project));

expect(JSON.parse(readFileSync(marker, "utf8"))).toEqual({
cwd: realpathSync(dir),
localConfig: false,
});
});

it("never replaces package files while a CLI process is running, then installs once it exits", async () => {
const { dir, runningDir, marker, script } = setup();
const cli = registerCli(runningDir);
Expand Down
7 changes: 6 additions & 1 deletion packages/cli/src/utils/autoUpdate.invocation.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,12 @@ async function patchAvailableAt(entry: string) {
}));

process.argv = [process.argv[0] ?? "node", entry];
for (const name of ["CI", "HYPERFRAMES_NO_AUTO_INSTALL", "HYPERFRAMES_NO_UPDATE_CHECK"]) {
for (const name of [
"CI",
"npm_lifecycle_event",
"HYPERFRAMES_NO_AUTO_INSTALL",
"HYPERFRAMES_NO_UPDATE_CHECK",
]) {
delete process.env[name];
}
Object.defineProperty(process.stderr, "isTTY", { value: true, configurable: true });
Expand Down
91 changes: 88 additions & 3 deletions packages/cli/src/utils/autoUpdate.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
// fallow-ignore-file code-duplication
import { execFileSync, spawn } from "node:child_process";
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { EventEmitter } from "node:events";
import { homedir, tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";

Expand Down Expand Up @@ -91,6 +92,7 @@ function setupMocks(opts: {
// before the test runs. Critical for CI, where GitHub Actions always sets
// CI=true and would cause every scheduling assertion to fail false-negative.
// Tests that specifically want one of these set pass it via opts.env.
delete process.env["npm_lifecycle_event"];
delete process.env["CI"];
delete process.env["HYPERFRAMES_NO_AUTO_INSTALL"];
delete process.env["HYPERFRAMES_NO_UPDATE_CHECK"];
Expand All @@ -117,6 +119,7 @@ describe("scheduleBackgroundInstall", () => {
vi.doUnmock("./installerDetection.js");
vi.doUnmock("node:child_process");
vi.doUnmock("node:fs");
vi.doUnmock("node:os");
vi.resetModules();
});

Expand All @@ -129,12 +132,94 @@ describe("scheduleBackgroundInstall", () => {
const scheduled = scheduleBackgroundInstall("0.4.4", "0.4.3");

expect(scheduled).toBe(true);
expect(spawnSpy).toHaveBeenCalledOnce();
expect(spawnSpy).toHaveBeenCalledWith(
process.execPath,
expect.any(Array),
expect.objectContaining({ cwd: homedir(), detached: true }),
);
expect(writeSpy).toHaveBeenCalled();
expect(config.pendingUpdate?.version).toBe("0.4.4");
expect(config.pendingUpdate?.command).toBe("npm install -g hyperframes@0.4.4");
});

it.each(["missing", "relative", "file"] as const)(
"skips an install with a %s home directory",
async (kind) => {
const { spawnSpy, writeSpy } = setupMocks({
installer: { kind: "bun", command: "bun add -g hyperframes@0.4.4" },
});
const homes = { missing: join(homedir(), "absent"), relative: ".", file: process.execPath };
vi.doMock("node:os", async (importOriginal) => ({
...(await importOriginal<typeof import("node:os")>()),
homedir: () => homes[kind],
}));
const { scheduleBackgroundInstall } = await import("./autoUpdate.js");
expect(scheduleBackgroundInstall("0.4.4", "0.4.3")).toBe(false);
expect(spawnSpy).not.toHaveBeenCalled();
expect(writeSpy).not.toHaveBeenCalled();
},
);

it.skipIf(!process.geteuid).each([
["other-owner", "belongs to a different user"],
["group-writable", "allows writes by the group or other users"],
] as const)(
"explains a rejected %s home on stderr without writing in it",
async (kind, message) => {
const home = mkdtempSync(join(tmpdir(), "hf-update-home-"));
try {
const { spawnSpy, writeSpy } = setupMocks({
installer: { kind: "npm", command: "npm install -g hyperframes@0.4.4" },
});
if (kind === "other-owner") {
vi.spyOn(process, "geteuid").mockReturnValue(process.geteuid!() + 1);
} else {
chmodSync(home, 0o775);
}
vi.doMock("node:os", async (importOriginal) => ({
...(await importOriginal<typeof import("node:os")>()),
homedir: () => home,
}));
const stderr = vi.spyOn(process.stderr, "write").mockReturnValue(true);
const fs = await import("node:fs");
const logWrite = vi.spyOn(fs, "appendFileSync");
const { scheduleBackgroundInstall } = await import("./autoUpdate.js");
expect(scheduleBackgroundInstall("0.4.4", "0.4.3")).toBe(false);
expect(stderr).toHaveBeenCalledWith(expect.stringContaining(message));
expect(spawnSpy).not.toHaveBeenCalled();
expect(writeSpy).not.toHaveBeenCalled();
expect(logWrite).not.toHaveBeenCalled();
} finally {
vi.restoreAllMocks();
rmSync(home, { recursive: true, force: true });
}
},
);

it("leaves no pending install when launched by a package script", async () => {
const { spawnSpy, writeSpy } = setupMocks({
installer: { kind: "bun", command: "bun add -g hyperframes@0.4.4" },
env: { npm_lifecycle_event: "preview", npm_config_color: "always" },
});
const { scheduleBackgroundInstall } = await import("./autoUpdate.js");
expect(scheduleBackgroundInstall("0.4.4", "0.4.3")).toBe(false);
expect(spawnSpy).not.toHaveBeenCalled();
expect(writeSpy).not.toHaveBeenCalled();
});

it("clears the pending update if the installer cannot enter its working directory", async () => {
const { spawnSpy, config } = setupMocks({
installer: { kind: "npm", command: "npm install -g hyperframes@0.4.4" },
});
const child = new EventEmitter();
spawnSpy.mockReturnValueOnce(child);
const { scheduleBackgroundInstall } = await import("./autoUpdate.js");

expect(scheduleBackgroundInstall("0.4.4", "0.4.3")).toBe(false);
child.emit("error", new Error("ENOENT"));
expect(config.pendingUpdate).toBeUndefined();
});

it("schedules nothing from a CLI that could not put itself on record as running", async () => {
const { spawnSpy, writeSpy } = setupMocks({
installer: { kind: "npm", command: "npm install -g hyperframes@0.4.4" },
Expand Down
Loading
Loading