@@ -31,6 +31,7 @@ import { compareVersions } from "compare-versions";
3131import { withFileLock } from "../media-use/lib/config-lock.mjs" ;
3232import { readConfig , writeConfig } from "../telemetry/config.js" ;
3333import { updateCheckDisabled } from "./updateCheck.js" ;
34+ import { RUNNING_DIR , RUNNING_STALE_MS } from "./runningCli.js" ;
3435import {
3536 detectInstaller ,
3637 installInvocation ,
@@ -41,6 +42,9 @@ const CONFIG_DIR = join(homedir(), ".hyperframes");
4142const LOG_FILE = join ( CONFIG_DIR , "auto-update.log" ) ;
4243/** An install that hasn't finished after this many ms is considered stuck. */
4344const PENDING_TIMEOUT_MS = 10 * 60 * 1000 ;
45+ /** A waiting installer gives up after this long; the next run schedules it again. */
46+ const INSTALL_MAX_WAIT_MS = 60 * 60 * 1000 ;
47+ const INSTALL_POLL_MS = 2_000 ;
4448
4549function isAutoInstallDisabled ( ) : boolean {
4650 return updateCheckDisabled ( ) || process . env [ "HYPERFRAMES_NO_AUTO_INSTALL" ] === "1" ;
@@ -65,6 +69,125 @@ function log(line: string): void {
6569 }
6670}
6771
72+ export interface InstallerScriptOptions {
73+ configFile : string ;
74+ version : string ;
75+ bin : string ;
76+ args : readonly string [ ] ;
77+ runningDir : string ;
78+ pollMs : number ;
79+ maxWaitMs : number ;
80+ /** A pid or install-lock file not touched for this long belongs to a dead process. */
81+ staleMs : number ;
82+ }
83+
84+ /** The detached installer, run via `node -e`: waits until no CLI in `runningDir` is alive, then
85+ * installs with execFile (no shell) and records completedUpdate under the settings lock. */
86+ export function installerScript ( o : InstallerScriptOptions ) : string {
87+ return `
88+ const { execFile } = require("node:child_process");
89+ const fs = require("node:fs");
90+ const { join } = require("node:path");
91+ const { readFileSync, renameSync, writeFileSync } = fs;
92+ const CFG = ${ JSON . stringify ( o . configFile ) } ;
93+ const TMP = \`\${CFG}.tmp\`;
94+ const INSTALL_LOCK = \`\${CFG}.install-lock\`;
95+ const RUNNING = ${ JSON . stringify ( o . runningDir ) } ;
96+ const VERSION = ${ JSON . stringify ( o . version ) } ;
97+ const BIN = ${ JSON . stringify ( o . bin ) } ;
98+ const ARGS = ${ JSON . stringify ( o . args ) } ;
99+ const withFileLock = ${ withFileLock . toString ( ) } ;
100+ const withLock = (task) => { try { withFileLock(\`\${CFG}.lock\`, fs, task); } catch (e) {} };
101+ const alive = (pid) => { try { process.kill(pid, 0); return true; } catch (e) { return e.code === "EPERM"; } };
102+ // Stale = no heartbeat for staleMs on this process's own clock, which stops while the machine sleeps.
103+ const seen = new Map();
104+ const mono = () => Number(process.hrtime.bigint() / 1000000n);
105+ const observe = (file) => {
106+ let mtime;
107+ try { mtime = fs.statSync(file).mtimeMs; } catch (e) { return "stale"; }
108+ const prev = seen.get(file);
109+ if (prev && prev.mtime === mtime) return mono() - prev.at >= ${ o . staleMs } ? "stale" : "quiet";
110+ seen.set(file, { mtime, at: mono() });
111+ return prev ? "beating" : "quiet";
112+ };
113+ const touch = (file) => { try { const now = new Date(); fs.utimesSync(file, now, now); } catch (e) {} };
114+ const running = () => {
115+ let names = [];
116+ try { names = fs.readdirSync(RUNNING); } catch (e) {}
117+ return names.filter((name) => {
118+ const pid = Number(name);
119+ const file = join(RUNNING, name);
120+ if (Number.isInteger(pid) && pid > 0 && alive(pid) && observe(file) !== "stale") return true;
121+ try { fs.unlinkSync(file); } catch (e) {}
122+ return false;
123+ });
124+ };
125+ let lockBeat;
126+ const ownsLock = () => { try { return Number(readFileSync(INSTALL_LOCK, "utf-8")) === process.pid; } catch (e) { return false; } };
127+ // Under the settings lock, so two installers launched together cannot both take it over.
128+ const tryLock = () => {
129+ let result = "stuck";
130+ withLock(() => {
131+ let owner = NaN;
132+ try { owner = Number(readFileSync(INSTALL_LOCK, "utf-8")); } catch (e) {}
133+ const state = Number.isInteger(owner) && owner > 0 && alive(owner) ? observe(INSTALL_LOCK) : "stale";
134+ if (state !== "stale") { result = state; return; }
135+ writeFileSync(INSTALL_LOCK, String(process.pid));
136+ result = "taken";
137+ });
138+ return result;
139+ };
140+ const releaseInstallLock = () => {
141+ clearInterval(lockBeat);
142+ if (ownsLock()) { try { fs.unlinkSync(INSTALL_LOCK); } catch (e) {} }
143+ };
144+ const install = () => execFile(BIN, ARGS, { windowsHide: true, maxBuffer: 4 * 1024 * 1024 }, (err, _stdout, stderr) => {
145+ withLock(() => {
146+ let cfg = {};
147+ try { cfg = JSON.parse(readFileSync(CFG, "utf-8")); } catch (e) { if (e.code !== "ENOENT") return; }
148+ cfg.completedUpdate = {
149+ version: VERSION,
150+ ok: !err,
151+ finishedAt: new Date().toISOString(),
152+ ...(err ? { error: String(stderr || err.message || "install failed").slice(-400) } : {}),
153+ };
154+ delete cfg.pendingUpdate;
155+ try {
156+ writeFileSync(TMP, JSON.stringify(cfg, null, 2) + "\\n", { mode: 0o600 });
157+ renameSync(TMP, CFG);
158+ } catch (e) {}
159+ });
160+ releaseInstallLock();
161+ });
162+ const started = Date.now();
163+ let lastPoll = Date.now();
164+ const waitThenInstall = () => {
165+ if (!ownsLock()) return releaseInstallLock();
166+ // A long gap between polls means the machine slept: watch every file afresh.
167+ if (Date.now() - lastPoll > ${ o . pollMs } * 5) seen.clear();
168+ lastPoll = Date.now();
169+ if (running().length === 0) return install();
170+ if (Date.now() - started > ${ o . maxWaitMs } ) {
171+ console.log(\`[wait] gave up on \${VERSION}: a hyperframes process is still running\`);
172+ return releaseInstallLock();
173+ }
174+ setTimeout(waitThenInstall, ${ o . pollMs } );
175+ };
176+ const acquire = () => {
177+ const result = tryLock();
178+ if (result === "taken") {
179+ lockBeat = setInterval(() => ownsLock() && touch(INSTALL_LOCK), ${ o . pollMs } );
180+ return waitThenInstall();
181+ }
182+ if (result === "quiet") return setTimeout(acquire, ${ o . pollMs } );
183+ console.log(result === "beating"
184+ ? \`[wait] another installer is already waiting; leaving \${VERSION} to it\`
185+ : \`[wait] settings lock busy; \${VERSION} left for the next run\`);
186+ };
187+ acquire();
188+ ` ;
189+ }
190+
68191/**
69192 * Spawn a detached child to run the install command. Stdout/stderr land in
70193 * the log file; the child is `unref()`d so the parent exits immediately
@@ -83,41 +206,16 @@ function launchDetachedInstall(
83206 mkdirSync ( CONFIG_DIR , { recursive : true , mode : 0o700 } ) ;
84207 const configFile = join ( CONFIG_DIR , "config.json" ) ;
85208
86- // The child script:
87- // 1. Runs the install via execFile (bin + argv, NO shell) so a version
88- // string can never be re-interpreted as shell syntax — structural
89- // symmetry with the interactive `runDetectedInstall` path.
90- // 2. Under the shared settings lock (withFileLock, embedded as source), rewrites the config with
91- // completedUpdate and clears pendingUpdate; skips on lock timeout or an unreadable file.
92- // We run it through `node -e` so we don't need to ship a separate file. Bin
93- // and args are embedded as JSON literals (data, not code).
94- const nodeScript = `
95- const { execFile } = require("node:child_process");
96- const fs = require("node:fs");
97- const { readFileSync, renameSync, writeFileSync } = fs;
98- const CFG = ${ JSON . stringify ( configFile ) } ;
99- const TMP = \`\${CFG}.tmp\`;
100- const VERSION = ${ JSON . stringify ( version ) } ;
101- const BIN = ${ JSON . stringify ( invocation . bin ) } ;
102- const ARGS = ${ JSON . stringify ( invocation . args ) } ;
103- const withFileLock = ${ withFileLock . toString ( ) } ;
104- const withLock = (task) => { try { withFileLock(\`\${CFG}.lock\`, fs, task); } catch (e) {} };
105- execFile(BIN, ARGS, { windowsHide: true, maxBuffer: 4 * 1024 * 1024 }, (err, _stdout, stderr) => withLock(() => {
106- let cfg = {};
107- try { cfg = JSON.parse(readFileSync(CFG, "utf-8")); } catch (e) { if (e.code !== "ENOENT") return; }
108- cfg.completedUpdate = {
109- version: VERSION,
110- ok: !err,
111- finishedAt: new Date().toISOString(),
112- ...(err ? { error: String(stderr || err.message || "install failed").slice(-400) } : {}),
113- };
114- delete cfg.pendingUpdate;
115- try {
116- writeFileSync(TMP, JSON.stringify(cfg, null, 2) + "\\n", { mode: 0o600 });
117- renameSync(TMP, CFG);
118- } catch (e) {}
119- }));
120- ` ;
209+ const nodeScript = installerScript ( {
210+ configFile,
211+ version,
212+ bin : invocation . bin ,
213+ args : invocation . args ,
214+ runningDir : RUNNING_DIR ,
215+ pollMs : INSTALL_POLL_MS ,
216+ maxWaitMs : INSTALL_MAX_WAIT_MS ,
217+ staleMs : RUNNING_STALE_MS ,
218+ } ) ;
121219
122220 const out = openSync ( LOG_FILE , "a" , 0o600 ) ;
123221 const child = spawn ( process . execPath , [ "-e" , nodeScript ] , {
@@ -130,12 +228,7 @@ function launchDetachedInstall(
130228 log ( `[launch] pid=${ child . pid ?? "?" } cmd=${ displayCommand } version=${ version } ` ) ;
131229}
132230
133- /**
134- * If a new version is available and policy allows, kick off a detached
135- * installer. Returns whether an install was spawned (for tests).
136- */
137- export function scheduleBackgroundInstall ( latestVersion : string , currentVersion : string ) : boolean {
138- if ( isAutoInstallDisabled ( ) ) return false ;
231+ function isSilentUpgrade ( latestVersion : string , currentVersion : string ) : boolean {
139232 if ( ! latestVersion || ! currentVersion ) return false ;
140233
141234 let cmp : number ;
@@ -155,6 +248,16 @@ export function scheduleBackgroundInstall(latestVersion: string, currentVersion:
155248 log ( `[skip] major-bump ${ currentVersion } -> ${ latestVersion } ` ) ;
156249 return false ;
157250 }
251+ return true ;
252+ }
253+
254+ /**
255+ * If a new version is available and policy allows, kick off a detached
256+ * installer. Returns whether an install was spawned (for tests).
257+ */
258+ export function scheduleBackgroundInstall ( latestVersion : string , currentVersion : string ) : boolean {
259+ if ( isAutoInstallDisabled ( ) ) return false ;
260+ if ( ! isSilentUpgrade ( latestVersion , currentVersion ) ) return false ;
158261
159262 const installer = detectInstaller ( ) ;
160263 if ( installer . kind === "skip" ) {
0 commit comments