Skip to content

Write HTML. Render video. Built for agents.

14.0 KB
Raw Blame
// 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 { join } from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";

/**
 * These tests exercise the policy — when a background install should or
 * shouldn't be scheduled — without ever spawning a real child process. The
 * `launchDetachedInstall` path is mocked out via vi.mock on node:child_process.
 */

type ConfigShape = {
  pendingUpdate?: { version: string; command: string; startedAt: string };
  completedUpdate?: { version: string; ok: boolean; finishedAt: string; reported?: boolean };
  latestVersion?: string;
};

function setupMocks(opts: {
  installer: {
    kind: "npm" | "bun" | "pnpm" | "brew" | "skip";
    command: string | null;
  };
  devMode?: boolean;
  config?: ConfigShape;
  env?: Record<string, string | undefined>;
  writeFails?: boolean;
}): {
  writeSpy: ReturnType<typeof vi.fn>;
  spawnSpy: ReturnType<typeof vi.fn>;
  config: ConfigShape;
} {
  vi.resetModules();

  const config = { ...(opts.config ?? {}) };
  const writeSpy = vi.fn((next: ConfigShape) => {
    if (opts.writeFails) return false;
    Object.assign(config, next);
    // writeConfig is given a full replacement — mirror that by pruning keys
    // that disappeared.
    for (const k of Object.keys(config)) {
      if (!(k in next)) delete (config as Record<string, unknown>)[k];
    }
    return true;
  });

  vi.doMock("../telemetry/config.js", () => ({
    readConfig: () => ({ ...config }),
    writeConfig: writeSpy,
  }));
  vi.doMock("./env.js", () => ({ isDevMode: () => !!opts.devMode }));
  vi.doMock("./installerDetection.js", () => ({
    detectInstaller: () => ({
      kind: opts.installer.kind,
      installCommand: () => opts.installer.command,
      reason: "test",
    }),
    // scheduleBackgroundInstall now also derives the argv form; mirror the real
    // helper (null for skip, a {bin,args} pair otherwise).
    installInvocation: (kind: string, version: string) =>
      kind === "skip" ? null : { bin: kind, args: ["add", "-g", `hyperframes@${version}`] },
  }));

  const spawnSpy = vi.fn(() => ({
    pid: 42,
    unref: () => {},
  }));
  vi.doMock("node:child_process", () => ({ spawn: spawnSpy }));
  vi.doMock("node:fs", async () => {
    const actual = await vi.importActual<typeof import("node:fs")>("node:fs");
    return {
      ...actual,
      mkdirSync: () => {},
      openSync: () => 99,
      appendFileSync: () => {},
    };
  });

  // Clear any env knobs that would otherwise bypass the scheduling policy
  // 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["CI"];
  delete process.env["HYPERFRAMES_NO_AUTO_INSTALL"];
  delete process.env["HYPERFRAMES_NO_UPDATE_CHECK"];

  // Apply env overrides, remembering originals for afterEach cleanup.
  if (opts.env) {
    for (const [k, v] of Object.entries(opts.env)) {
      if (v === undefined) delete process.env[k];
      else process.env[k] = v;
    }
  }

  return { writeSpy, spawnSpy, config };
}

const ORIGINAL_ENV = { ...process.env };

describe("scheduleBackgroundInstall", () => {
  afterEach(() => {
    process.env = { ...ORIGINAL_ENV };
    vi.doUnmock("../telemetry/config.js");
    vi.doUnmock("./env.js");
    vi.doUnmock("./installerDetection.js");
    vi.doUnmock("node:child_process");
    vi.doUnmock("node:fs");
    vi.resetModules();
  });

  it("schedules an install when a newer minor/patch is available", async () => {
    const { spawnSpy, writeSpy, config } = setupMocks({
      installer: { kind: "npm", command: "npm install -g [email protected]" },
    });
    const { scheduleBackgroundInstall } = await import("./autoUpdate.js");

    const scheduled = scheduleBackgroundInstall("0.4.4", "0.4.3");

    expect(scheduled).toBe(true);
    expect(spawnSpy).toHaveBeenCalledOnce();
    expect(writeSpy).toHaveBeenCalled();
    expect(config.pendingUpdate?.version).toBe("0.4.4");
    expect(config.pendingUpdate?.command).toBe("npm install -g [email protected]");
  });

  it("launches nothing when the pending install cannot be recorded", async () => {
    const { spawnSpy } = setupMocks({
      installer: { kind: "npm", command: "npm install -g [email protected]" },
      writeFails: true,
    });
    const { scheduleBackgroundInstall } = await import("./autoUpdate.js");

    expect(scheduleBackgroundInstall("0.4.4", "0.4.3")).toBe(false);
    expect(spawnSpy).not.toHaveBeenCalled();
  });

  it("does NOT schedule across a major-version jump", async () => {
    const { spawnSpy } = setupMocks({
      installer: { kind: "npm", command: "npm install -g [email protected]" },
    });
    const { scheduleBackgroundInstall } = await import("./autoUpdate.js");

    expect(scheduleBackgroundInstall("1.0.0", "0.4.3")).toBe(false);
    expect(spawnSpy).not.toHaveBeenCalled();
  });

  it("skips in dev mode", async () => {
    const { spawnSpy } = setupMocks({
      installer: { kind: "npm", command: "npm install -g [email protected]" },
      devMode: true,
    });
    const { scheduleBackgroundInstall } = await import("./autoUpdate.js");

    expect(scheduleBackgroundInstall("0.4.4", "0.4.3")).toBe(false);
    expect(spawnSpy).not.toHaveBeenCalled();
  });

  it("skips when CI=1", async () => {
    const { spawnSpy } = setupMocks({
      installer: { kind: "npm", command: "npm install -g [email protected]" },
      env: { CI: "1" },
    });
    const { scheduleBackgroundInstall } = await import("./autoUpdate.js");

    expect(scheduleBackgroundInstall("0.4.4", "0.4.3")).toBe(false);
    expect(spawnSpy).not.toHaveBeenCalled();
  });

  it("skips when HYPERFRAMES_NO_AUTO_INSTALL=1", async () => {
    const { spawnSpy } = setupMocks({
      installer: { kind: "npm", command: "npm install -g [email protected]" },
      env: { HYPERFRAMES_NO_AUTO_INSTALL: "1" },
    });
    const { scheduleBackgroundInstall } = await import("./autoUpdate.js");

    expect(scheduleBackgroundInstall("0.4.4", "0.4.3")).toBe(false);
    expect(spawnSpy).not.toHaveBeenCalled();
  });

  it("skips when the installer kind is unknown", async () => {
    const { spawnSpy } = setupMocks({
      installer: { kind: "skip", command: null },
    });
    const { scheduleBackgroundInstall } = await import("./autoUpdate.js");

    expect(scheduleBackgroundInstall("0.4.4", "0.4.3")).toBe(false);
    expect(spawnSpy).not.toHaveBeenCalled();
  });

  it("skips when already up to date", async () => {
    const { spawnSpy } = setupMocks({
      installer: { kind: "npm", command: "npm install -g [email protected]" },
    });
    const { scheduleBackgroundInstall } = await import("./autoUpdate.js");

    expect(scheduleBackgroundInstall("0.4.3", "0.4.3")).toBe(false);
    expect(spawnSpy).not.toHaveBeenCalled();
  });

  it("does not re-launch while a fresh pending install exists for the same version", async () => {
    const { spawnSpy } = setupMocks({
      installer: { kind: "npm", command: "npm install -g [email protected]" },
      config: {
        pendingUpdate: {
          version: "0.4.4",
          command: "npm install -g [email protected]",
          startedAt: new Date().toISOString(),
        },
      },
    });
    const { scheduleBackgroundInstall } = await import("./autoUpdate.js");

    expect(scheduleBackgroundInstall("0.4.4", "0.4.3")).toBe(false);
    expect(spawnSpy).not.toHaveBeenCalled();
  });

  it("re-launches when a stale pending install is older than the timeout", async () => {
    const longAgo = new Date(Date.now() - 60 * 60 * 1000).toISOString(); // 1h ago
    const { spawnSpy } = setupMocks({
      installer: { kind: "npm", command: "npm install -g [email protected]" },
      config: {
        pendingUpdate: {
          version: "0.4.4",
          command: "npm install -g [email protected]",
          startedAt: longAgo,
        },
      },
    });
    const { scheduleBackgroundInstall } = await import("./autoUpdate.js");

    expect(scheduleBackgroundInstall("0.4.4", "0.4.3")).toBe(true);
    expect(spawnSpy).toHaveBeenCalledOnce();
  });

  it("skips when the previous run already completed this version successfully", async () => {
    const { spawnSpy } = setupMocks({
      installer: { kind: "npm", command: "npm install -g [email protected]" },
      config: {
        completedUpdate: {
          version: "0.4.4",
          ok: true,
          finishedAt: new Date().toISOString(),
        },
      },
    });
    const { scheduleBackgroundInstall } = await import("./autoUpdate.js");

    expect(scheduleBackgroundInstall("0.4.4", "0.4.3")).toBe(false);
    expect(spawnSpy).not.toHaveBeenCalled();
  });

  it("skips when the previous run already failed this version", async () => {
    const { spawnSpy } = setupMocks({
      installer: { kind: "npm", command: "npm install -g [email protected]" },
      config: {
        completedUpdate: {
          version: "0.4.4",
          ok: false,
          finishedAt: new Date().toISOString(),
        },
      },
    });
    const { scheduleBackgroundInstall } = await import("./autoUpdate.js");

    expect(scheduleBackgroundInstall("0.4.4", "0.4.3")).toBe(false);
    expect(spawnSpy).not.toHaveBeenCalled();
  });

  it("writes completed updates atomically in the detached child script", async () => {
    const { spawnSpy } = setupMocks({
      installer: { kind: "npm", command: "npm install -g [email protected]" },
    });
    const { scheduleBackgroundInstall } = await import("./autoUpdate.js");

    expect(scheduleBackgroundInstall("0.4.4", "0.4.3")).toBe(true);
    expect(spawnSpy).toHaveBeenCalledOnce();

    const spawnArgs = spawnSpy.mock.calls[0]?.[1];
    expect(Array.isArray(spawnArgs)).toBe(true);
    expect(spawnArgs?.[0]).toBe("-e");
    expect(spawnArgs?.[1]).toContain("renameSync");
    expect(spawnArgs?.[1]).toContain(".tmp");
  });

  it("surfaces failed installs once but still blocks retries for the same version", async () => {
    const { spawnSpy, config } = setupMocks({
      installer: { kind: "npm", command: "npm install -g [email protected]" },
      config: {
        completedUpdate: {
          version: "0.4.4",
          ok: false,
          finishedAt: new Date().toISOString(),
        },
      },
    });
    const { reportCompletedUpdate, scheduleBackgroundInstall } = await import("./autoUpdate.js");
    const stderrWrite = vi.spyOn(process.stderr, "write").mockReturnValue(true);
    const originalIsTTY = process.stderr.isTTY;
    Object.defineProperty(process.stderr, "isTTY", { value: true, configurable: true });

    try {
      reportCompletedUpdate();

      expect(stderrWrite).toHaveBeenCalledWith(
        expect.stringContaining("hyperframes auto-update to v0.4.4 failed"),
      );
      expect(config.completedUpdate).toMatchObject({
        version: "0.4.4",
        ok: false,
        reported: true,
      });

      stderrWrite.mockClear();
      reportCompletedUpdate();

      expect(stderrWrite).not.toHaveBeenCalled();
      expect(scheduleBackgroundInstall("0.4.4", "0.4.3")).toBe(false);
      expect(spawnSpy).not.toHaveBeenCalled();
    } finally {
      stderrWrite.mockRestore();
      Object.defineProperty(process.stderr, "isTTY", {
        value: originalIsTTY,
        configurable: true,
      });
    }
  });

  describe("the detached child's settings write", () => {
    const home = mkdtempSync(join(tmpdir(), "hf-auto-update-"));
    const dir = join(home, ".hyperframes");
    const cfg = join(dir, "config.json");

    beforeEach(() => mkdirSync(dir, { recursive: true }));
    afterEach(() => {
      rmSync(home, { recursive: true, force: true });
      vi.doUnmock("node:os");
    });

    /** The script the CLI would spawn, pointed at a throwaway home and an install that does nothing. */
    async function runChild(): Promise<void> {
      const { spawnSpy } = setupMocks({ installer: { kind: "npm", command: "npm i" } });
      vi.doMock("node:os", async () => ({
        ...(await vi.importActual<typeof import("node:os")>("node:os")),
        homedir: () => home,
      }));
      vi.doMock("./installerDetection.js", () => ({
        detectInstaller: () => ({ kind: "npm", installCommand: () => "npm i" }),
        installInvocation: () => ({ bin: process.execPath, args: ["-e", ""] }),
      }));
      const { scheduleBackgroundInstall } = await import("./autoUpdate.js");
      expect(scheduleBackgroundInstall("0.4.4", "0.4.3")).toBe(true);
      const args = spawnSpy.mock.calls[0]?.[1] as unknown as string[];
      expect(args[1]).toContain(JSON.stringify(cfg));
      execFileSync(process.execPath, args);
    }

    it("waits for another process's locked write, then keeps the no it saved", async () => {
      const script = `
        const fs = require("fs");
        const dir = process.argv[1];
        fs.writeFileSync(dir + "/config.json.lock", "", { flag: "wx" });
        process.stdout.write("locked\\n");
        setTimeout(() => {
          fs.writeFileSync(dir + "/other.tmp", JSON.stringify({ localEmbeddingEnabled: false }));
          fs.renameSync(dir + "/other.tmp", dir + "/config.json");
          fs.rmSync(dir + "/config.json.lock");
        }, 1000);`;
      const holder = spawn(process.execPath, ["-e", script, dir]);
      const exited = new Promise((done) => holder.on("exit", done));
      await new Promise((locked) => holder.stdout.once("data", locked));

      await runChild();
      await exited;

      const saved = JSON.parse(readFileSync(cfg, "utf-8"));
      expect([saved.localEmbeddingEnabled, saved.completedUpdate?.version]).toEqual([
        false,
        "0.4.4",
      ]);
    });

    it("leaves a settings file it cannot read untouched", async () => {
      writeFileSync(cfg, "{not json");

      await runChild();

      expect(readFileSync(cfg, "utf-8")).toBe("{not json");
    });

    it("starts a settings file when there is none", async () => {
      await runChild();

      expect(JSON.parse(readFileSync(cfg, "utf-8")).completedUpdate?.version).toBe("0.4.4");
    });
  });
});