diff --git a/docs/guides/authentication.mdx b/docs/guides/authentication.mdx index bc849912f9..52eb40614b 100644 --- a/docs/guides/authentication.mdx +++ b/docs/guides/authentication.mdx @@ -147,7 +147,7 @@ to a shared space with `--space`. | `HEYGEN_ACCESS_TOKEN` | OAuth token a host app injects; never refreshed or saved. | | `HEYGEN_API_BASE` | A host app's gateway for media workflows; never read from a project `.env`. | | `HEYGEN_API_URL` | API base URL for `hyperframes` CLI commands (default `https://api.heygen.com`). | -| `HYPERFRAMES_CONFIG_DIR` | HyperFrames credentials root (default `~/.hyperframes`). | +| `HYPERFRAMES_CONFIG_DIR` | HyperFrames settings root: credentials, telemetry and update settings, project links (default `~/.hyperframes`). | | `HYPERFRAMES_ENV` | `prod` (default) or `dev`; `dev` keeps credentials in a separate `dev/` directory under the root. Hosts and the OAuth client id come from `HEYGEN_API_URL`, `HYPERFRAMES_OAUTH_*` and `HYPERFRAMES_PUBLISHED_PROJECTS_API_URL`. | | `HYPERFRAMES_OAUTH_CLIENT_ID` | Override the public client ID for a controlled OAuth environment. | | `ELEVENLABS_API_KEY` | ElevenLabs TTS, used when no HeyGen credential is present. | diff --git a/docs/packages/cli.mdx b/docs/packages/cli.mdx index a56d50f1e0..212d0c4959 100644 --- a/docs/packages/cli.mdx +++ b/docs/packages/cli.mdx @@ -2516,7 +2516,7 @@ hyperframes auth logout --yes # no prompt | `HYPERFRAMES_API_KEY` | Alias for `HEYGEN_API_KEY`. | | `HEYGEN_ACCESS_TOKEN` | OAuth token from a host app; used first, never refreshed. | | `HEYGEN_API_URL` | API base URL (default `https://api.heygen.com`). | -| `HYPERFRAMES_CONFIG_DIR` | Credentials root (default `~/.hyperframes`). | +| `HYPERFRAMES_CONFIG_DIR` | Settings root: credentials, telemetry and update settings, project links (default `~/.hyperframes`). | | `HYPERFRAMES_ENV` | `prod` (default) or `dev`; `dev` uses a separate credential directory. Hosts and the OAuth client id come from `HEYGEN_API_URL` and `HYPERFRAMES_OAUTH_*`. | | `HYPERFRAMES_OAUTH_CLIENT_ID` | Override the selected public OAuth client. | diff --git a/packages/cli/src/auth/paths.test.ts b/packages/cli/src/auth/paths.test.ts index 785543c46f..875cc75bed 100644 --- a/packages/cli/src/auth/paths.test.ts +++ b/packages/cli/src/auth/paths.test.ts @@ -22,7 +22,7 @@ describe("auth/paths", () => { it("honors HYPERFRAMES_CONFIG_DIR override", () => { process.env["HYPERFRAMES_CONFIG_DIR"] = "/tmp/some-test-dir"; - expect(configDir()).toBe("/tmp/some-test-dir"); + expect(configDir()).toBe(join("/tmp/some-test-dir")); expect(credentialPath()).toBe(join("/tmp/some-test-dir", CREDENTIAL_FILENAME)); }); diff --git a/packages/cli/src/auth/paths.ts b/packages/cli/src/auth/paths.ts index c909b24650..7e0c972305 100644 --- a/packages/cli/src/auth/paths.ts +++ b/packages/cli/src/auth/paths.ts @@ -2,8 +2,8 @@ * HyperFrames credentials are isolated from the HeyGen CLI and between environments. */ -import { homedir } from "node:os"; import { join } from "node:path"; +import { hyperframesConfigDir } from "../utils/configDir.js"; import { oauthEnvironment } from "./config.js"; /** @@ -12,7 +12,7 @@ import { oauthEnvironment } from "./config.js"; export const CREDENTIAL_FILENAME = "credentials"; export function configDir(): string { - const root = process.env["HYPERFRAMES_CONFIG_DIR"] || join(homedir(), ".hyperframes"); + const root = hyperframesConfigDir(); return oauthEnvironment() === "dev" ? join(root, "dev") : root; } diff --git a/packages/cli/src/commands/cloudrun.ts b/packages/cli/src/commands/cloudrun.ts index ef585538d3..5bb54bef18 100644 --- a/packages/cli/src/commands/cloudrun.ts +++ b/packages/cli/src/commands/cloudrun.ts @@ -16,7 +16,6 @@ import { CliUsageError, failCommand, failUsage } from "../utils/commandResult.js import { spawnSync } from "node:child_process"; import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; -import { homedir } from "node:os"; import { join, resolve } from "node:path"; import { defineCommand } from "../utils/defineCommand.js"; import { type CanvasResolution } from "@hyperframes/core"; @@ -32,6 +31,7 @@ import { normalizeErrorMessage } from "../utils/errorMessage.js"; import { defaultCloudFps } from "../utils/compositionFps.js"; import { DISTRIBUTED_FPS, type DistributedFps, isDistributedFps } from "@hyperframes/core"; import { isMissingPackageError, missingPackageMessage } from "../utils/missingPackage.js"; +import { hyperframesConfigDir, seededConfigFile } from "../utils/configDir.js"; export const examples: Example[] = [ ["Deploy the Cloud Run render stack", "hyperframes cloudrun deploy --project my-gcp-project"], @@ -267,10 +267,10 @@ export default defineCommand({ // ── State helpers ───────────────────────────────────────────────────────── function stateDir(): string { - return join(homedir(), ".hyperframes"); + return hyperframesConfigDir(); } function statePath(): string { - return join(stateDir(), "cloudrun-state.json"); + return seededConfigFile("cloudrun-state.json"); } function writeState(state: StackState): void { mkdirSync(stateDir(), { recursive: true }); diff --git a/packages/cli/src/media-use/lib/telemetry.mjs b/packages/cli/src/media-use/lib/telemetry.mjs index 3bc278a6b8..ed74b77066 100644 --- a/packages/cli/src/media-use/lib/telemetry.mjs +++ b/packages/cli/src/media-use/lib/telemetry.mjs @@ -50,8 +50,13 @@ export function optedOut() { } // Read and write the shared config so media-use keeps one identity per install. +// Until the CLI seeds HYPERFRAMES_CONFIG_DIR's copy, ~/.hyperframes' own still holds the opt-out. function sharedConfigPath() { - return join(homedir(), ".hyperframes", "config.json"); + const home = join(homedir(), ".hyperframes", "config.json"); + const dir = process.env.HYPERFRAMES_CONFIG_DIR; + if (!dir) return home; + const file = join(dir, "config.json"); + return existsSync(file) || !existsSync(home) ? file : home; } function readSharedConfig() { diff --git a/packages/cli/src/media-use/lib/telemetry.test.mjs b/packages/cli/src/media-use/lib/telemetry.test.mjs index fc0b021bac..b3ebfafc99 100644 --- a/packages/cli/src/media-use/lib/telemetry.test.mjs +++ b/packages/cli/src/media-use/lib/telemetry.test.mjs @@ -79,6 +79,40 @@ test("optedOut honors telemetryEnabled: false from the shared config", () => { } }); +test("the shared config is read from HYPERFRAMES_CONFIG_DIR when it is set", () => { + const savedEnv = { ...process.env }; + const { root } = sandbox(); + try { + withoutTelemetryOptOut(); + const configDir = join(root, "config"); + mkdirSync(configDir, { recursive: true }); + writeFileSync(join(configDir, "config.json"), JSON.stringify({ telemetryEnabled: false })); + process.env.HYPERFRAMES_CONFIG_DIR = configDir; + assert.equal(optedOut(), true); + } finally { + restoreEnv(savedEnv); + rmSync(root, { recursive: true, force: true }); + } +}); + +test("an opt-out in ~/.hyperframes holds until HYPERFRAMES_CONFIG_DIR has its own config", () => { + const savedEnv = { ...process.env }; + const { root, home } = sandbox(); + try { + withoutTelemetryOptOut(); + mkdirSync(join(home, ".hyperframes"), { recursive: true }); + writeFileSync( + join(home, ".hyperframes", "config.json"), + JSON.stringify({ telemetryEnabled: false }), + ); + process.env.HYPERFRAMES_CONFIG_DIR = join(root, "moved"); + assert.equal(optedOut(), true); + } finally { + restoreEnv(savedEnv); + rmSync(root, { recursive: true, force: true }); + } +}); + test("track is a no-op (no network, resolves) when opted out", async () => { const savedEnv = { ...process.env }; const originalFetch = globalThis.fetch; diff --git a/packages/cli/src/telemetry/config.ts b/packages/cli/src/telemetry/config.ts index c6d69fb63d..6085c32213 100644 --- a/packages/cli/src/telemetry/config.ts +++ b/packages/cli/src/telemetry/config.ts @@ -7,26 +7,22 @@ import { normalizeErrorMessage } from "../utils/errorMessage.js"; import { telemetryRuntimeOverride } from "./policy.js"; import { isAttendedTerminal } from "../utils/attendedTerminal.js"; import { withFileLock } from "../media-use/lib/config-lock.mjs"; +import { hyperframesConfigDir, seededConfigFile } from "../utils/configDir.js"; // --------------------------------------------------------------------------- // Config directory: ~/.hyperframes/ // --------------------------------------------------------------------------- -const CONFIG_DIR = join(homedir(), ".hyperframes"); -const CONFIG_FILE = join(CONFIG_DIR, "config.json"); +const configDir = () => hyperframesConfigDir(); +const configFile = () => seededConfigFile("config.json"); // --------------------------------------------------------------------------- // Install-state file: ~/.hyperframes/install-state.json // // A separate FILE, but deliberately the same DIRECTORY as config.json, so -// `rm -rf ~/.hyperframes` really is a full reset. It previously lived in -// ~/.local/state/hyperframes/ specifically to survive that delete; review -// rejected that ("if someone is deleting their hyperframes config it should -// wipe all hyperframes state — I'm not sure we should try and persist state -// elsewhere to get around this"), and the measurement agreed: the churn this -// actually defends against is not users running `rm -rf`. +// `rm -rf ~/.hyperframes` really is a full reset. // -// The threat it does defend against is config.json itself. That file is hot +// What it defends against is config.json itself. That file is hot // and wide — ~20 fields rewritten on every command and every render — and // readConfig recovers from ANY parse/permission/IO failure by minting a fresh // identity. Splitting these two facts into their own file decouples them from @@ -37,7 +33,7 @@ const CONFIG_FILE = join(CONFIG_DIR, "config.json"); // no counters, nothing emitted that links the old install to the new one: // // 1. `markerAt` — "a hyperframes install existed on this machine". Now that -// it shares CONFIG_DIR, `predecessorFound` measures the churn we care +// it shares configDir(), `predecessorFound` measures the churn we care // about (config.json lost, install-state survived => corruption/re-mint) // rather than deliberate directory deletion, which takes both. // 2. `deParallelRouterTrialFired` — the DE parallel-router circuit @@ -45,18 +41,18 @@ const CONFIG_FILE = join(CONFIG_DIR, "config.json"); // install into an experimental path that already FAILED on this machine. // 3. `bucketSeed` — the canary bucketing unit, so a re-mint does not // reshuffle cohorts mid-rollout. Never transmitted; only the resulting -// true/false assignments are. Sharing CONFIG_DIR is what keeps it from +// true/false assignments are. Sharing configDir() is what keeps it from // being a persistent identifier that outlives the user's reset. // // Removal path: delete ~/.hyperframes (or just this file). `hyperframes // telemetry status` prints its exact location. // --------------------------------------------------------------------------- -const STATE_FILE = join(CONFIG_DIR, "install-state.json"); +const stateFile = () => seededConfigFile("install-state.json"); // Pre-move location. Read once, migrated, then deleted — an install that // wrote state under the old scheme keeps its tripped breaker instead of -// silently re-enrolling, and no file is left behind outside CONFIG_DIR. +// silently re-enrolling, and no file is left behind outside configDir(). const LEGACY_STATE_FILE = join(homedir(), ".local", "state", "hyperframes", "install-state.json"); interface InstallState { @@ -231,7 +227,7 @@ function isInstallState(value: InstallState | InstallStateMiss): value is Instal * re-read harmlessly next time. */ function readInstallState(): InstallState | InstallStateMiss { - const current = parseInstallState(STATE_FILE); + const current = parseInstallState(stateFile()); if (isInstallState(current)) { removeLegacyStateFile(); return current; @@ -281,10 +277,10 @@ export function __resetInstallStateSyncForTests(): void { * since a corrupted state file silently reads as absent. */ function writeInstallState(next: InstallState): void { - mkdirSync(CONFIG_DIR, { recursive: true, mode: 0o700 }); - const tmpFile = `${STATE_FILE}.${process.pid}.tmp`; + mkdirSync(configDir(), { recursive: true, mode: 0o700 }); + const tmpFile = `${stateFile()}.${process.pid}.tmp`; writeFileSync(tmpFile, JSON.stringify(next, null, 2) + "\n", { mode: 0o600 }); - renameSync(tmpFile, STATE_FILE); + renameSync(tmpFile, stateFile()); } /** @@ -344,7 +340,7 @@ function syncInstallState(config: HyperframesConfig): boolean { // the freshly minted seed lived in config.json alone, and the NEXT // config-only re-mint rolled a third seed instead of inheriting the second. // One existsSync on a path we are about to write anyway. - if (stateMarkerSynced && !existsSync(STATE_FILE)) { + if (stateMarkerSynced && !existsSync(stateFile())) { stateMarkerSynced = false; stateFiredSynced = false; } @@ -799,10 +795,10 @@ function materializeConfig(parsed: Partial): HyperframesConfi export function readConfig(): HyperframesConfig { if (cachedConfig) return { ...cachedConfig }; - if (!existsSync(CONFIG_FILE)) return mintAndCacheConfig(); + if (!existsSync(configFile())) return mintAndCacheConfig(); try { - const raw = readFileSync(CONFIG_FILE, "utf-8"); + const raw = readFileSync(configFile(), "utf-8"); const parsed = JSON.parse(raw) as Partial; const config = materializeConfig(parsed); @@ -958,7 +954,7 @@ function consentFrom(value: unknown): boolean | undefined { function localModelConsentOnDisk(): boolean | undefined { try { - return consentFrom(JSON.parse(readFileSync(CONFIG_FILE, "utf-8")).localEmbeddingEnabled); + return consentFrom(JSON.parse(readFileSync(configFile(), "utf-8")).localEmbeddingEnabled); } catch (error) { // A settings file that exists but cannot be read may hold a no; only a missing one was never asked. return (error as NodeJS.ErrnoException).code === "ENOENT" ? undefined : false; @@ -970,8 +966,8 @@ let holdingConfigLock = false; /** One process at a time between reading config.json and replacing it; re-entrant within this one. */ function withConfigLock(task: () => T): T { if (holdingConfigLock) return task(); - mkdirSync(CONFIG_DIR, { recursive: true, mode: 0o700 }); - return withFileLock(`${CONFIG_FILE}.lock`, fs, () => { + mkdirSync(configDir(), { recursive: true, mode: 0o700 }); + return withFileLock(`${configFile()}.lock`, fs, () => { holdingConfigLock = true; try { return task(); @@ -983,10 +979,10 @@ function withConfigLock(task: () => T): T { function persistConfig(config: HyperframesConfig): ConfigWriteResult { try { - mkdirSync(CONFIG_DIR, { recursive: true, mode: 0o700 }); - const tmpFile = `${CONFIG_FILE}.${process.pid}.tmp`; + mkdirSync(configDir(), { recursive: true, mode: 0o700 }); + const tmpFile = `${configFile()}.${process.pid}.tmp`; writeFileSync(tmpFile, JSON.stringify(config, null, 2) + "\n", { mode: 0o600 }); - renameSync(tmpFile, CONFIG_FILE); + renameSync(tmpFile, configFile()); cachedConfig = { ...config }; // Mirror into the install-state file (marker + tripped breaker) so no // breaker write site has to remember to do it. A failed mirror does NOT @@ -1013,7 +1009,7 @@ export function incrementCommandCount(): number { } /** Expose the config directory path for the telemetry command output */ -export const CONFIG_PATH = CONFIG_FILE; +export const CONFIG_PATH = configFile(); /** Expose the install-state path for the telemetry command output. */ -export const STATE_PATH = STATE_FILE; +export const STATE_PATH = stateFile(); diff --git a/packages/cli/src/utils/autoUpdate.invocation.test.ts b/packages/cli/src/utils/autoUpdate.invocation.test.ts index 2c3e508cbf..ee70659110 100644 --- a/packages/cli/src/utils/autoUpdate.invocation.test.ts +++ b/packages/cli/src/utils/autoUpdate.invocation.test.ts @@ -43,6 +43,10 @@ async function patchAvailableAt(entry: string) { VERSION: "0.8.231", })); vi.doMock("./env.js", () => ({ isDevMode: () => false })); + vi.doMock("./runningCli.js", async (importOriginal) => ({ + ...(await importOriginal()), + registeredAsRunning: () => true, + })); vi.doMock("./attendedTerminal.js", async (importOriginal) => ({ ...(await importOriginal()), isUnattended: () => false, diff --git a/packages/cli/src/utils/autoUpdate.test.ts b/packages/cli/src/utils/autoUpdate.test.ts index 3204f99f40..1354fb23cf 100644 --- a/packages/cli/src/utils/autoUpdate.test.ts +++ b/packages/cli/src/utils/autoUpdate.test.ts @@ -27,6 +27,7 @@ function setupMocks(opts: { env?: Record; writeFails?: boolean; unattended?: boolean; + registered?: boolean; }): { writeSpy: ReturnType; spawnSpy: ReturnType; @@ -51,6 +52,10 @@ function setupMocks(opts: { writeConfig: writeSpy, })); vi.doMock("./env.js", () => ({ isDevMode: () => !!opts.devMode })); + vi.doMock("./runningCli.js", async (importOriginal) => ({ + ...(await importOriginal()), + registeredAsRunning: () => opts.registered ?? true, + })); vi.doMock("./attendedTerminal.js", async (importOriginal) => ({ ...(await importOriginal()), isUnattended: () => opts.unattended ?? false, @@ -108,6 +113,7 @@ describe("scheduleBackgroundInstall", () => { process.env = { ...ORIGINAL_ENV }; vi.doUnmock("../telemetry/config.js"); vi.doUnmock("./env.js"); + vi.doUnmock("./runningCli.js"); vi.doUnmock("./installerDetection.js"); vi.doUnmock("node:child_process"); vi.doUnmock("node:fs"); @@ -129,6 +135,18 @@ describe("scheduleBackgroundInstall", () => { expect(config.pendingUpdate?.command).toBe("npm install -g hyperframes@0.4.4"); }); + 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" }, + registered: false, + }); + 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("launches nothing when the pending install cannot be recorded", async () => { const { spawnSpy } = setupMocks({ installer: { kind: "npm", command: "npm install -g hyperframes@0.4.4" }, diff --git a/packages/cli/src/utils/autoUpdate.ts b/packages/cli/src/utils/autoUpdate.ts index c030b69ca2..f0448249f7 100644 --- a/packages/cli/src/utils/autoUpdate.ts +++ b/packages/cli/src/utils/autoUpdate.ts @@ -25,22 +25,21 @@ import { spawn } from "node:child_process"; import { appendFileSync, mkdirSync, openSync } from "node:fs"; -import { homedir } from "node:os"; -import { join } from "node:path"; import { compareVersions } from "compare-versions"; import { withFileLock } from "../media-use/lib/config-lock.mjs"; import { readConfig, writeConfig } from "../telemetry/config.js"; import { isUnattended } from "./attendedTerminal.js"; import { updateCheckDisabled } from "./updateCheck.js"; -import { RUNNING_DIR, RUNNING_STALE_MS } from "./runningCli.js"; +import { RUNNING_STALE_MS, registeredAsRunning, runningDir } from "./runningCli.js"; import { detectInstaller, installInvocation, type InstallInvocation, } from "./installerDetection.js"; +import { hyperframesConfigDir, seededConfigFile } from "./configDir.js"; -const CONFIG_DIR = join(homedir(), ".hyperframes"); -const LOG_FILE = join(CONFIG_DIR, "auto-update.log"); +const configDir = () => hyperframesConfigDir(); +const logFile = () => hyperframesConfigDir("auto-update.log"); /** An install that hasn't finished after this many ms is considered stuck. */ const PENDING_TIMEOUT_MS = 10 * 60 * 1000; /** A waiting installer gives up after this long; the next run schedules it again. */ @@ -66,8 +65,8 @@ function breakingLine(version: string): string | null { */ function log(line: string): void { try { - mkdirSync(CONFIG_DIR, { recursive: true, mode: 0o700 }); - appendFileSync(LOG_FILE, `${new Date().toISOString()} ${line}\n`, { mode: 0o600 }); + mkdirSync(configDir(), { recursive: true, mode: 0o700 }); + appendFileSync(logFile(), `${new Date().toISOString()} ${line}\n`, { mode: 0o600 }); } catch { /* best-effort */ } @@ -207,21 +206,21 @@ function launchDetachedInstall( displayCommand: string, version: string, ): void { - mkdirSync(CONFIG_DIR, { recursive: true, mode: 0o700 }); - const configFile = join(CONFIG_DIR, "config.json"); + mkdirSync(configDir(), { recursive: true, mode: 0o700 }); + const configFile = seededConfigFile("config.json"); const nodeScript = installerScript({ configFile, version, bin: invocation.bin, args: invocation.args, - runningDir: RUNNING_DIR, + runningDir: runningDir(), pollMs: INSTALL_POLL_MS, maxWaitMs: INSTALL_MAX_WAIT_MS, staleMs: RUNNING_STALE_MS, }); - const out = openSync(LOG_FILE, "a", 0o600); + const out = openSync(logFile(), "a", 0o600); const child = spawn(process.execPath, ["-e", nodeScript], { detached: true, stdio: ["ignore", out, out], @@ -277,6 +276,12 @@ function backgroundInstaller( export function scheduleBackgroundInstall(latestVersion: string, currentVersion: string): boolean { if (isAutoInstallDisabled()) return false; if (!isSilentUpgrade(latestVersion, currentVersion)) return false; + if (!registeredAsRunning()) { + log( + `[skip] ${latestVersion}: this CLI is not on record as running, so an install could replace it mid-run`, + ); + return false; + } const installer = backgroundInstaller(latestVersion); if (!installer) return false; diff --git a/packages/cli/src/utils/configDir.test.ts b/packages/cli/src/utils/configDir.test.ts new file mode 100644 index 0000000000..ff0053eefc --- /dev/null +++ b/packages/cli/src/utils/configDir.test.ts @@ -0,0 +1,42 @@ +import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterEach, expect, it, vi } from "vitest"; +import { credentialPath } from "../auth/paths.js"; +import { readConfig, readConfigFresh, writeConfig } from "../telemetry/config.js"; +import { hyperframesConfigDir } from "./configDir.js"; +import { writeProjectLink } from "./projectLink.js"; +import { runningDir } from "./runningCli.js"; + +let dir = ""; +afterEach(() => { + vi.unstubAllEnvs(); + rmSync(dir, { recursive: true, force: true }); +}); + +it("keeps every config file under HYPERFRAMES_CONFIG_DIR when it is set", () => { + dir = mkdtempSync(join(tmpdir(), "hf-config-")); + vi.stubEnv("HYPERFRAMES_CONFIG_DIR", dir); + expect(hyperframesConfigDir("x")).toBe(join(dir, "x")); + expect(runningDir()).toBe(join(dir, "running")); + expect(credentialPath().startsWith(dir)).toBe(true); + expect(writeConfig(readConfig())).toBe(true); + expect(existsSync(join(dir, "config.json"))).toBe(true); + writeProjectLink(join(dir, "project"), { projectId: "p", url: "https://example.test/p" }); + expect(existsSync(join(dir, "projects.json"))).toBe(true); +}); + +it("starts a new settings folder from ~/.hyperframes, so an opt-out and the install id move with it", () => { + dir = mkdtempSync(join(tmpdir(), "hf-config-")); + const home = join(dir, "home"); + mkdirSync(join(home, ".hyperframes"), { recursive: true }); + const old = { telemetryEnabled: false, anonymousId: "kept-id" }; + writeFileSync(join(home, ".hyperframes", "config.json"), JSON.stringify(old)); + vi.stubEnv("HOME", home); + vi.stubEnv("USERPROFILE", home); + vi.stubEnv("HYPERFRAMES_CONFIG_DIR", join(dir, "moved")); + const config = readConfigFresh(); + expect(config.telemetryEnabled).toBe(false); + expect(config.anonymousId).toBe("kept-id"); + expect(existsSync(join(dir, "moved", "config.json"))).toBe(true); +}); diff --git a/packages/cli/src/utils/configDir.ts b/packages/cli/src/utils/configDir.ts new file mode 100644 index 0000000000..5f6cc1e620 --- /dev/null +++ b/packages/cli/src/utils/configDir.ts @@ -0,0 +1,23 @@ +import { constants, copyFileSync, existsSync, mkdirSync } from "node:fs"; +import { homedir } from "node:os"; +import { dirname, join } from "node:path"; + +const homeConfigDir = () => join(homedir(), ".hyperframes"); + +export function hyperframesConfigDir(...parts: string[]): string { + return join(process.env["HYPERFRAMES_CONFIG_DIR"] || homeConfigDir(), ...parts); +} + +/** A settings file under HYPERFRAMES_CONFIG_DIR starts as a copy of ~/.hyperframes' one, so an opt-out moves too. */ +export function seededConfigFile(name: string): string { + const file = hyperframesConfigDir(name); + const home = join(homeConfigDir(), name); + if (file === home || existsSync(file) || !existsSync(home)) return file; + try { + mkdirSync(dirname(file), { recursive: true, mode: 0o700 }); + copyFileSync(home, file, constants.COPYFILE_EXCL); + } catch { + // expected: an unreadable home folder, or another CLI seeded it first; the caller reads what is there + } + return file; +} diff --git a/packages/cli/src/utils/projectLink.ts b/packages/cli/src/utils/projectLink.ts index 33cc60ba0b..3afc6cdc5b 100644 --- a/packages/cli/src/utils/projectLink.ts +++ b/packages/cli/src/utils/projectLink.ts @@ -1,7 +1,7 @@ import { randomUUID } from "node:crypto"; import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; -import { homedir } from "node:os"; import { join, resolve } from "node:path"; +import { hyperframesConfigDir, seededConfigFile } from "./configDir.js"; interface ProjectLink { projectId: string; @@ -10,8 +10,8 @@ interface ProjectLink { type ProjectLinks = Record; -const CONFIG_DIR = join(homedir(), ".hyperframes"); -const PROJECTS_FILE = join(CONFIG_DIR, "projects.json"); +const configDir = () => hyperframesConfigDir(); +const projectsFile = () => seededConfigFile("projects.json"); /** Read + parse a JSON object file, or null if it's missing, unreadable, or not an object. */ function readJsonRecord(path: string): Record | null { @@ -34,7 +34,7 @@ function isProjectLink(value: unknown): value is ProjectLink { } function readProjectLinks(): ProjectLinks { - const record = readJsonRecord(PROJECTS_FILE); + const record = readJsonRecord(projectsFile()); if (!record) return {}; const links: ProjectLinks = {}; for (const [path, value] of Object.entries(record)) { @@ -47,8 +47,8 @@ function readProjectLinks(): ProjectLinks { function writeProjectLinks(links: ProjectLinks): void { try { - mkdirSync(CONFIG_DIR, { recursive: true, mode: 0o700 }); - writeFileSync(PROJECTS_FILE, `${JSON.stringify(links, null, 2)}\n`, { mode: 0o600 }); + mkdirSync(configDir(), { recursive: true, mode: 0o700 }); + writeFileSync(projectsFile(), `${JSON.stringify(links, null, 2)}\n`, { mode: 0o600 }); } catch { // Project links must never prevent local CLI commands from running. } diff --git a/packages/cli/src/utils/runningCli.test.ts b/packages/cli/src/utils/runningCli.test.ts index 166946f48d..658d5bcca2 100644 --- a/packages/cli/src/utils/runningCli.test.ts +++ b/packages/cli/src/utils/runningCli.test.ts @@ -12,7 +12,7 @@ import { import { tmpdir } from "node:os"; import { join } from "node:path"; import { afterEach, expect, it } from "vitest"; -import { RUNNING_STALE_MS, registerRunningCli } from "./runningCli.js"; +import { RUNNING_STALE_MS, registerRunningCli, registeredAsRunning } from "./runningCli.js"; let dir = ""; afterEach(() => rmSync(dir, { recursive: true, force: true })); @@ -81,3 +81,11 @@ it("removes the files of processes that are gone or stopped beating, and keeps l process.off("exit", listener); } }); + +it("says when this process cannot be put on record, and never throws", () => { + dir = mkdtempSync(join(tmpdir(), "hf-running-")); + const notAFolder = join(dir, "file"); + writeFileSync(notAFolder, ""); + expect(registerRunningCli(join(notAFolder, "running"))).toBe(false); + expect(registeredAsRunning()).toBe(false); +}); diff --git a/packages/cli/src/utils/runningCli.ts b/packages/cli/src/utils/runningCli.ts index 3f875a7992..ea0f743aac 100644 --- a/packages/cli/src/utils/runningCli.ts +++ b/packages/cli/src/utils/runningCli.ts @@ -1,9 +1,9 @@ import { mkdirSync, readdirSync, statSync, unlinkSync, writeFileSync } from "node:fs"; -import { homedir } from "node:os"; import { join } from "node:path"; +import { hyperframesConfigDir } from "./configDir.js"; /** One empty file per live CLI process, named by pid; the background installer waits until none is alive. */ -export const RUNNING_DIR = join(homedir(), ".hyperframes", "running"); +export const runningDir = () => hyperframesConfigDir("running"); const RUNNING_HEARTBEAT_MS = 30_000; export const RUNNING_STALE_MS = 10 * 60_000; @@ -39,11 +39,16 @@ function pruneExitedClis(dir: string, own: string): void { } } -/** Mark this process as running until it exits. Never throws: a failed write only lets an update land sooner. */ +let registered = false; + +/** Whether this process is on record as running, so an installer would wait for it to exit. */ +export const registeredAsRunning = (): boolean => registered; + +/** Mark this process as running until it exits. Never throws: false when the record cannot be written. */ export function registerRunningCli( - dir: string = RUNNING_DIR, + dir: string = runningDir(), heartbeatMs: number = RUNNING_HEARTBEAT_MS, -): void { +): boolean { try { mkdirSync(dir, { recursive: true, mode: 0o700 }); const file = join(dir, String(process.pid)); @@ -66,7 +71,9 @@ export function registerRunningCli( /* already gone */ } }); + registered = true; } catch { - /* best-effort */ + registered = false; } + return registered; } diff --git a/skills-manifest.json b/skills-manifest.json index fd7994e353..3fde349bbd 100644 --- a/skills-manifest.json +++ b/skills-manifest.json @@ -18,7 +18,7 @@ "files": 13 }, "media-use": { - "hash": "40fbd6271fb7be28", + "hash": "f3e4cc75041371b3", "files": 118 }, "remotion-to-hyperframes": { diff --git a/skills/media-use/scripts/lib/telemetry.mjs b/skills/media-use/scripts/lib/telemetry.mjs index 3bc278a6b8..ed74b77066 100644 --- a/skills/media-use/scripts/lib/telemetry.mjs +++ b/skills/media-use/scripts/lib/telemetry.mjs @@ -50,8 +50,13 @@ export function optedOut() { } // Read and write the shared config so media-use keeps one identity per install. +// Until the CLI seeds HYPERFRAMES_CONFIG_DIR's copy, ~/.hyperframes' own still holds the opt-out. function sharedConfigPath() { - return join(homedir(), ".hyperframes", "config.json"); + const home = join(homedir(), ".hyperframes", "config.json"); + const dir = process.env.HYPERFRAMES_CONFIG_DIR; + if (!dir) return home; + const file = join(dir, "config.json"); + return existsSync(file) || !existsSync(home) ? file : home; } function readSharedConfig() { diff --git a/skills/media-use/scripts/lib/telemetry.test.mjs b/skills/media-use/scripts/lib/telemetry.test.mjs index 4a0c541ee1..d2d39f9849 100644 --- a/skills/media-use/scripts/lib/telemetry.test.mjs +++ b/skills/media-use/scripts/lib/telemetry.test.mjs @@ -11,6 +11,7 @@ import { optedOut } from "./telemetry.mjs"; const ENV_KEYS = [ "HOME", "USERPROFILE", + "HYPERFRAMES_CONFIG_DIR", "HYPERFRAMES_NO_TELEMETRY", "DO_NOT_TRACK", "CI", @@ -71,3 +72,27 @@ test("optedOut still honors the env opt-outs", () => { delete process.env.DO_NOT_TRACK; } }); + +test("optedOut reads the shared config from HYPERFRAMES_CONFIG_DIR when it is set", () => { + writeConfig(null); + const configDir = join(home, "elsewhere"); + mkdirSync(configDir, { recursive: true }); + writeFileSync(join(configDir, "config.json"), JSON.stringify({ telemetryEnabled: false })); + process.env.HYPERFRAMES_CONFIG_DIR = configDir; + try { + assert.equal(optedOut(), true); + } finally { + delete process.env.HYPERFRAMES_CONFIG_DIR; + } +}); + +test("an opt-out in ~/.hyperframes holds until HYPERFRAMES_CONFIG_DIR has its own config", () => { + writeConfig(JSON.stringify({ telemetryEnabled: false })); + process.env.HYPERFRAMES_CONFIG_DIR = join(home, "moved"); + try { + assert.equal(optedOut(), true); + } finally { + delete process.env.HYPERFRAMES_CONFIG_DIR; + writeConfig(null); + } +});