Skip to content

Write HTML. Render video. Built for agents.

fix(cli): commands exit right away even when the network or DNS is broken (#4604)

Miguel Ángel693c38550888
diff --git a/.fallowrc.jsonc b/.fallowrc.jsonc
index a98fe708dd..ebf4ffe3b1 100644
--- a/.fallowrc.jsonc
+++ b/.fallowrc.jsonc
@@ -46,6 +46,8 @@
"packages/producer/src/services/healthWorkerThread.ts",
// Render-setup worker, spawned by path from cancellableProcess.ts.
"packages/cli/src/renderSetupWorker.ts",
+ // Update/skills cache refresh, spawned detached by path from backgroundChecks.ts.
+ "packages/cli/src/backgroundChecksWorker.ts",
// Parakeet decode worker, spawned by path from whisper/sherpa.ts.
"packages/cli/src/whisper/sherpaWorker.ts",
// Test fixture worker, spawned by path via the pools' workerEntryPath
diff --git a/docs/packages/cli.mdx b/docs/packages/cli.mdx
index db81489abe..e93c42c675 100644
--- a/docs/packages/cli.mdx
+++ b/docs/packages/cli.mdx
@@ -59,8 +59,9 @@ from any command's output, without a second call:
}
```
-The version numbers come from a cache refreshed at most once a day. `--json`
-never makes a network request of its own. Deprecated commands add
+The version numbers come from a cache refreshed at most once a day, in a
+background process, and never under CI or `HYPERFRAMES_NO_UPDATE_CHECK=1`.
+`--json` never makes a network request of its own. Deprecated commands add
`_meta.deprecated: true`.
**Flags, not prompts.** A missing required flag fails immediately with a usage
diff --git a/packages/cli/src/backgroundChecksWorker.test.ts b/packages/cli/src/backgroundChecksWorker.test.ts
new file mode 100644
index 0000000000..18e6410279
--- /dev/null
+++ b/packages/cli/src/backgroundChecksWorker.test.ts
@@ -0,0 +1,29 @@
+import { expect, it, vi } from "vitest";
+
+const checks = vi.hoisted(() => ({
+ checkForUpdate: vi.fn(async () => ({})),
+ refreshSkillsCache: vi.fn(async () => {
+ throw new Error("offline");
+ }),
+}));
+vi.mock("./utils/updateCheck.js", () => ({ checkForUpdate: checks.checkForUpdate }));
+vi.mock("./utils/skillsUpdateCheck.js", () => ({ refreshSkillsCache: checks.refreshSkillsCache }));
+
+it("runs each check it was handed, and one failing does not stop the other", async () => {
+ process.argv = [process.execPath, "backgroundChecksWorker.js", "skills", "update"];
+
+ await import("./backgroundChecksWorker.js");
+
+ expect(checks.refreshSkillsCache).toHaveBeenCalledTimes(1);
+ expect(checks.checkForUpdate).toHaveBeenCalledTimes(1);
+});
+
+it("skips a check the parent did not find due", async () => {
+ vi.resetModules();
+ checks.checkForUpdate.mockClear();
+ process.argv = [process.execPath, "backgroundChecksWorker.js", "skills"];
+
+ await import("./backgroundChecksWorker.js");
+
+ expect(checks.checkForUpdate).not.toHaveBeenCalled();
+});
diff --git a/packages/cli/src/backgroundChecksWorker.ts b/packages/cli/src/backgroundChecksWorker.ts
new file mode 100644
index 0000000000..0b0f287bbc
--- /dev/null
+++ b/packages/cli/src/backgroundChecksWorker.ts
@@ -0,0 +1,9 @@
+import { checkForUpdate } from "./utils/updateCheck.js";
+import { refreshSkillsCache } from "./utils/skillsUpdateCheck.js";
+
+// Detached child of launchBackgroundChecks: refreshes the caches the next run's notices read.
+const due = process.argv.slice(2);
+await Promise.allSettled([
+ due.includes("update") && checkForUpdate(),
+ due.includes("skills") && refreshSkillsCache(),
+]);
diff --git a/packages/cli/src/cli.lifecycle.test.ts b/packages/cli/src/cli.lifecycle.test.ts
index 08621f993b..e52e537300 100644
--- a/packages/cli/src/cli.lifecycle.test.ts
+++ b/packages/cli/src/cli.lifecycle.test.ts
@@ -10,15 +10,12 @@ const originalExitCode = process.exitCode;
afterEach(() => {
process.argv = [...originalArgv];
process.exitCode = originalExitCode;
- vi.doUnmock("./commands/init.js");
- vi.doUnmock("./telemetry/events.js");
- vi.doUnmock("./telemetry/index.js");
- vi.doUnmock("./telemetry/client.js");
+ for (const path of MOCKED_MODULES) vi.doUnmock(path);
vi.resetModules();
});
describe("CLI lifecycle", () => {
- it("queues a command failure before finalizing telemetry", async () => {
+ it("queues a command failure before exit, without waiting on a network flush", async () => {
let resolveEvents!: (events: {
trackCommandFailure: (command: string, error: unknown) => void;
}) => void;
@@ -41,10 +38,9 @@ describe("CLI lifecycle", () => {
},
}));
vi.doMock("./telemetry/index.js", () => ({
- flush: async () => {
- order.push("flush");
- },
- flushSync: vi.fn(),
+ // Never settles: a finalize that awaited it would hang this test.
+ flush: () => new Promise<void>(() => {}),
+ flushSync: () => order.push("flushSync"),
incrementCommandCount: vi.fn(),
showTelemetryNotice: vi.fn(),
shouldTrack: () => false,
@@ -69,8 +65,9 @@ describe("CLI lifecycle", () => {
},
});
await execution;
+ process.emit("exit", 0);
- expect(order).toEqual(["cli_error", "flush"]);
+ expect(order).toEqual(["cli_error", "flushSync"]);
});
describe("reports each failure once, by its real error", () => {
@@ -297,8 +294,44 @@ describe("CLI lifecycle", () => {
exitSpy.mockRestore();
}
});
+
+ it("starts the background checks in a child and reads only the caches itself", async () => {
+ const launchBackgroundChecks = vi.fn();
+ const checkForUpdate = vi.fn();
+ mockInitCommand(vi.fn());
+ mockTelemetry();
+ vi.doMock("./utils/autoUpdate.js", () => ({
+ reportCompletedUpdate: vi.fn(),
+ scheduleBackgroundInstall: vi.fn(),
+ }));
+ vi.doMock("./utils/updateCheck.js", () => ({
+ cachedUpdateCheck: () => ({ current: "1.0.0", latest: "1.0.0", updateAvailable: false }),
+ checkForUpdate,
+ printUpdateNotice: vi.fn(),
+ printStalePinNotice: vi.fn(),
+ }));
+ vi.doMock("./utils/skillsUpdateCheck.js", () => ({ printSkillsUpdateNotice: vi.fn() }));
+ vi.doMock("./utils/backgroundChecks.js", () => ({ launchBackgroundChecks }));
+
+ process.argv = ["node", "cli.ts", "init"];
+ await import("./cli.js");
+
+ await vi.waitFor(() => expect(launchBackgroundChecks).toHaveBeenCalledTimes(1));
+ expect(checkForUpdate).not.toHaveBeenCalled();
+ });
});
+const MOCKED_MODULES = [
+ "./commands/init.js",
+ "./telemetry/events.js",
+ "./telemetry/index.js",
+ "./telemetry/client.js",
+ "./utils/autoUpdate.js",
+ "./utils/updateCheck.js",
+ "./utils/skillsUpdateCheck.js",
+ "./utils/backgroundChecks.js",
+];
+
/** Runs the CLI with the real failure reporting and returns the cli_error events it sent. */
async function runCli(args: string[]): Promise<Record<string, unknown>[]> {
const sent: Record<string, unknown>[] = [];
diff --git a/packages/cli/src/cli.ts b/packages/cli/src/cli.ts
index c9e3f62bc4..0635ec1366 100644
--- a/packages/cli/src/cli.ts
+++ b/packages/cli/src/cli.ts
@@ -215,7 +215,6 @@ const hasJsonFlag = process.argv.includes("--json");
// Captured references — populated when the lazy imports resolve.
// Used in exit handlers where dynamic import() is unsafe (beforeExit loops,
// exit handler is synchronous-only).
-let _flush: (() => Promise<void>) | undefined;
let _flushSync: (() => void) | undefined;
let _trackCliError:
| ((props: {
@@ -245,7 +244,6 @@ let telemetryReady: Promise<void> = Promise.resolve();
// printed into a skill's captured output).
if (!isHelp && command !== "telemetry" && command !== "events" && command !== "unknown") {
telemetryReady = import("./telemetry/index.js").then((mod) => {
- _flush = mod.flush;
_flushSync = mod.flushSync;
_trackCliError = mod.trackCliError;
_trackCommandResult = mod.trackCommandResult;
@@ -281,19 +279,20 @@ if (
import("./utils/updateCheck.js").then(async (mod) => {
_printUpdateNotice = mod.printUpdateNotice;
_printStalePinNotice = mod.printStalePinNotice;
- const result = await mod.checkForUpdate().catch(() => null);
- if (result?.updateAvailable) {
+ const result = mod.cachedUpdateCheck();
+ if (result.updateAvailable) {
const auto = await import("./utils/autoUpdate.js").catch(() => null);
auto?.scheduleBackgroundInstall(result.latest, result.current);
}
});
- // Skills freshness nudge — same gating as the CLI self-update notice. The
- // check is cached (24h) and best-effort: it never blocks or fails the command.
- import("./utils/skillsUpdateCheck.js").then(async (mod) => {
+ // Skills freshness nudge — same gating as the CLI self-update notice.
+ import("./utils/skillsUpdateCheck.js").then((mod) => {
_printSkillsUpdateNotice = mod.printSkillsUpdateNotice;
- await mod.checkSkillsForUpdate().catch(() => null);
});
+
+ // The notices read the caches; a detached child refreshes them for the next run.
+ import("./utils/backgroundChecks.js").then((mod) => mod.launchBackgroundChecks()).catch(() => {});
}
const commandStart = Date.now();
@@ -323,7 +322,7 @@ async function finalizeCli(result: CommandResult): Promise<void> {
durationMs: Date.now() - commandStart,
runId,
});
- await _flush?.().catch(() => {});
+ // No network wait: the exit handler's flushSync() delivers what is still queued.
if (!hasJsonFlag) {
_printUpdateNotice?.();
_printStalePinNotice?.();
@@ -362,12 +361,8 @@ process.on(
runId,
});
}
- // Unconditional — `finalized` only means finalizeCli STARTED its awaited
- // flush(). A process.exit() racing that flush (the EPIPE path under agent
- // pipes) kills the in-flight request, and gating this fallback behind
- // `finalized` silently dropped the still-queued events — the 0.7.65
- // render_complete regression. flushSync() is safe to over-call: an empty
- // queue is a no-op, and event uuids make re-sends idempotent.
+ // Unconditional: this is the exit-time delivery for every command (gating it on `finalized`
+ // was the 0.7.65 render_complete loss). Empty queue is a no-op; uuids make re-sends idempotent.
_flushSync?.();
},
);
diff --git a/packages/cli/src/commands/events.test.ts b/packages/cli/src/commands/events.test.ts
index 0524fb2870..6890a50187 100644
--- a/packages/cli/src/commands/events.test.ts
+++ b/packages/cli/src/commands/events.test.ts
@@ -1,5 +1,6 @@
import { describe, expect, it, vi } from "vitest";
+const order: string[] = [];
const telemetry = vi.hoisted(() => ({
trackEvent: vi.fn(),
flush: vi.fn(async () => {}),
@@ -8,10 +9,12 @@ const telemetry = vi.hoisted(() => ({
vi.mock("../telemetry/client.js", () => telemetry);
describe("events", () => {
- it("hands anything flush() left queued to the detached sender", async () => {
+ it("queues the event, then hands it to the detached sender without waiting on the network", async () => {
+ telemetry.trackEvent.mockImplementation(() => order.push("track"));
+ telemetry.flushSync.mockImplementation(() => order.push("flushSync"));
const { default: events } = await import("./events.js");
await events.run?.({ args: { skill: "hyperframes", event: "skill_invoked" } } as never);
- expect(telemetry.trackEvent).toHaveBeenCalled();
- expect(telemetry.flushSync).toHaveBeenCalled();
+ expect(order).toEqual(["track", "flushSync"]);
+ expect(telemetry.flush).not.toHaveBeenCalled();
});
});
diff --git a/packages/cli/src/commands/events.ts b/packages/cli/src/commands/events.ts
index 70ac850270..97b3f4701e 100644
--- a/packages/cli/src/commands/events.ts
+++ b/packages/cli/src/commands/events.ts
@@ -1,5 +1,5 @@
import { defineCommand } from "citty";
-import { trackEvent, flush, flushSync } from "../telemetry/client.js";
+import { trackEvent, flushSync } from "../telemetry/client.js";
import { SKILL_SLUG } from "../telemetry/skill.js";
// Skill-usage telemetry endpoint. A skill reports its own invocation/outcome —
@@ -14,7 +14,7 @@ import { SKILL_SLUG } from "../telemetry/skill.js";
//
// Telemetry must NEVER break the calling skill: every arg is optional (a missing
// or malformed value is a silent no-op, not a non-zero exit), the body is
-// guarded, and flush() carries its own hard timeout. This command always exits 0.
+// guarded, and the send runs in a detached child. This command always exits 0.
const ALLOWED_EVENTS = ["skill_invoked", "skill_completed"];
const ALLOWED_OUTCOMES = ["success", "error", "abort"];
@@ -53,7 +53,6 @@ export default defineCommand({
props["outcome"] = args.outcome;
}
trackEvent(event, props);
- await flush();
flushSync();
} catch {
// swallow — telemetry must never surface a non-zero exit to the caller
diff --git a/packages/cli/src/commands/feedback.test.ts b/packages/cli/src/commands/feedback.test.ts
new file mode 100644
index 0000000000..4502f1a617
--- /dev/null
+++ b/packages/cli/src/commands/feedback.test.ts
@@ -0,0 +1,29 @@
+import { expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ // Never settles: waiting on it would hang the command.
+ flush: vi.fn(() => new Promise<void>(() => {})),
+ submitFeedback: vi.fn(async () => {}),
+ submitCatalogSearchMiss: vi.fn(async () => {}),
+}));
+vi.mock("../telemetry/client.js", () => ({ shouldTrack: () => true, flush: mocks.flush }));
+vi.mock("../telemetry/events.js", () => ({
+ trackCatalogSearchMiss: vi.fn(),
+ trackRenderFeedback: vi.fn(),
+}));
+vi.mock("../telemetry/feedback.js", () => ({ getDoctorSummary: async () => "" }));
+vi.mock("../telemetry/config.js", () => ({ readConfig: () => ({ anonymousId: "a" }) }));
+vi.mock("../utils/submitFeedback.js", () => ({
+ submitFeedback: mocks.submitFeedback,
+ submitCatalogSearchMiss: mocks.submitCatalogSearchMiss,
+}));
+
+it.each([
+ ["a rating", { rating: "8" }, mocks.submitFeedback],
+ ["a catalog search miss", { "search-miss": "typewriter" }, mocks.submitCatalogSearchMiss],
+])("sends %s without waiting on the telemetry upload", async (_, args, submit) => {
+ vi.spyOn(console, "log").mockImplementation(() => {});
+ const { default: feedback } = await import("./feedback.js");
+ await feedback.run?.({ args } as never);
+ expect(submit).toHaveBeenCalled();
+});
diff --git a/packages/cli/src/commands/feedback.ts b/packages/cli/src/commands/feedback.ts
index 760265572e..99533ab5de 100644
--- a/packages/cli/src/commands/feedback.ts
+++ b/packages/cli/src/commands/feedback.ts
@@ -6,7 +6,7 @@ import * as clack from "@clack/prompts";
import open from "open";
import type { Example } from "./_examples.js";
import { trackCatalogSearchMiss, trackRenderFeedback } from "../telemetry/events.js";
-import { shouldTrack, flush } from "../telemetry/client.js";
+import { shouldTrack } from "../telemetry/client.js";
import { getDoctorSummary } from "../telemetry/feedback.js";
import { readConfig, type RecentRenderRecord } from "../telemetry/config.js";
import { publishProjectArchive } from "../utils/publishProject.js";
@@ -208,7 +208,6 @@ export default defineCommand({
const wanted = normalizeComment(args.wanted);
const tier = normalizeComment(args.tier);
trackCatalogSearchMiss({ query: searchMiss, wanted, tier });
- await flush();
// Ack before the forward, which is best-effort and bounded, so the
// reporter is never left waiting on it.
console.log(c.dim("Logged the gap. Thanks — that is how the catalog grows."));
@@ -259,7 +258,6 @@ export default defineCommand({
recentRenderIds: config.recentRenders?.map((r) => r.id),
});
- await flush();
// Ack first so the user isn't kept waiting on the best-effort forward (which
// is bounded to a few seconds and never surfaces an error either way).
console.log(c.dim("Thanks for the feedback!"));
diff --git a/packages/cli/src/telemetry/client.test.ts b/packages/cli/src/telemetry/client.test.ts
index 564a71c957..bd947ecdfb 100644
--- a/packages/cli/src/telemetry/client.test.ts
+++ b/packages/cli/src/telemetry/client.test.ts
@@ -26,8 +26,13 @@ vi.mock("../utils/env.js", () => ({
isDevMode: () => false,
}));
-const dns = vi.hoisted(() => ({ answers: true }));
-vi.mock("../utils/hostAnswers.js", () => ({ hostAnswers: async () => dns.answers }));
+const dns = vi.hoisted(() => ({ answers: true, probes: 0 }));
+vi.mock("../utils/hostAnswers.js", () => ({
+ hostAnswers: async () => {
+ dns.probes++;
+ return dns.answers;
+ },
+}));
// Canary enrolment is registry-driven and will change as rollouts ramp; stub
// it so this asserts the WIRING (does every event carry the cohort?) rather
@@ -77,6 +82,7 @@ describe("telemetry queue delivery", () => {
);
await flush();
vi.unstubAllGlobals();
+ dns.probes = 0;
});
it("delivers harness context alongside a recognized agent without leaking marker values", async () => {
@@ -171,14 +177,50 @@ describe("telemetry queue delivery", () => {
expect(gated).toHaveBeenCalledTimes(1);
});
- it("leaves the batch to the exit-time send when the flush ahead of it failed", async () => {
+ it.each([
+ ["the send failed", () => {}, 1],
+ ["DNS did not answer", () => (dns.answers = false), 0],
+ ])("leaves the batch to the exit-time send when, ahead of it, %s", async (_, arrange, sends) => {
const fetchMock = vi.fn(() => Promise.reject(new Error("offline")));
vi.stubGlobal("fetch", fetchMock);
trackEvent("render_complete", { quality: "draft" });
- await Promise.all([flush(), flush()]);
+ arrange();
+ try {
+ await Promise.all([flush(), flush()]);
+ } finally {
+ dns.answers = true;
+ }
+ // One attempt, whichever way it failed.
+ expect(dns.probes).toBe(1);
+ expect(fetchMock).toHaveBeenCalledTimes(sends);
+ // Still queued: the next send carries it.
+ const succeeding = vi.fn(() => Promise.resolve(new Response("")));
+ vi.stubGlobal("fetch", succeeding);
+ await flush();
+ expect(sentBatch(succeeding).map((e) => e.event)).toEqual(["render_complete"]);
+ });
+
+ it("still sends from a flush queued behind one that had nothing to send", async () => {
+ const fetchMock = vi.fn(() => Promise.resolve(new Response("")));
+ vi.stubGlobal("fetch", fetchMock);
+ const empty = flush();
+ trackEvent("render_complete", { quality: "draft" });
+ await Promise.all([empty, flush()]);
expect(fetchMock).toHaveBeenCalledTimes(1);
});
+ it("cancels the reply it never reads, so a stalled body cannot hold the process", async () => {
+ const cancel = vi.fn();
+ const body = new ReadableStream({ cancel });
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(() => Promise.resolve(new Response(body))),
+ );
+ trackEvent("render_complete", { quality: "draft" });
+ await flush();
+ expect(cancel).toHaveBeenCalled();
+ });
+
it("still sends from a flush queued behind one that threw", async () => {
const fetchMock = vi.fn(() => Promise.resolve(new Response("")));
vi.stubGlobal("fetch", fetchMock);
@@ -222,13 +264,13 @@ describe("telemetry queue delivery", () => {
const [execPath, args, opts] = spawnMock.mock.calls[0] as unknown as [
string,
string[],
- { detached: boolean },
+ Record<string, unknown>,
];
expect(execPath).toBe(process.execPath);
expect(args[0]).toBe("-e");
expect(args[1]).toContain("render_complete");
expect(args[1]).toMatch(/[0-9a-f-]{36}/); // event uuid rides along
- expect(opts.detached).toBe(true);
+ expect(opts).toMatchObject({ detached: true, windowsHide: true });
// Queue handed to the child — nothing left for a regular flush.
const fetchMock = vi.fn(() => Promise.resolve(new Response("")));
diff --git a/packages/cli/src/telemetry/config.test.ts b/packages/cli/src/telemetry/config.test.ts
index 8510d5cbad..622fd0dc4b 100644
--- a/packages/cli/src/telemetry/config.test.ts
+++ b/packages/cli/src/telemetry/config.test.ts
@@ -113,6 +113,17 @@ describe("config.ts — readConfig / readConfigFresh / writeConfig (real module,
expect(reread.deParallelRouterTrialRenderCount).toBe(5);
});
+ it("keeps the background checks' attempt stamps across a fresh read", () => {
+ const config = readConfig();
+ config.lastUpdateAttemptAt = "2026-09-27T10:00:00.000Z";
+ config.lastSkillsAttemptAt = "2026-09-27T11:00:00.000Z";
+ writeConfig(config);
+ expect(readConfigFresh()).toMatchObject({
+ lastUpdateAttemptAt: "2026-09-27T10:00:00.000Z",
+ lastSkillsAttemptAt: "2026-09-27T11:00:00.000Z",
+ });
+ });
+
it('treats a non-boolean deParallelRouterTrialFired (e.g. the JSON string "false") as unset, not truthy', () => {
const base = readConfig();
fsState.files.set(
diff --git a/packages/cli/src/telemetry/config.ts b/packages/cli/src/telemetry/config.ts
index eb900d130c..5c6683a93d 100644
--- a/packages/cli/src/telemetry/config.ts
+++ b/packages/cli/src/telemetry/config.ts
@@ -409,6 +409,8 @@ export interface HyperframesConfig {
latestVersion?: string;
/** Throttle for the non-TTY stale-project-pin notice (ms epoch). */
lastStalePinNoticeAt?: number;
+ lastUpdateAttemptAt?: string;
+ lastSkillsAttemptAt?: string;
/**
* Auto-update marker. Set when a background install is spawned so a
* subsequent run can skip re-triggering it. Cleared once
@@ -650,6 +652,8 @@ function passthroughFields(parsed: Partial<HyperframesConfig>): Partial<Hyperfra
lastUpdateCheck: parsed.lastUpdateCheck,
latestVersion: parsed.latestVersion,
lastStalePinNoticeAt: parsed.lastStalePinNoticeAt,
+ lastUpdateAttemptAt: parsed.lastUpdateAttemptAt,
+ lastSkillsAttemptAt: parsed.lastSkillsAttemptAt,
pendingUpdate: parsed.pendingUpdate,
completedUpdate: parsed.completedUpdate,
lastSkillsCheck: parsed.lastSkillsCheck,
diff --git a/packages/cli/src/telemetry/transport.ts b/packages/cli/src/telemetry/transport.ts
index 126a28ed06..a7f9c335ee 100644
--- a/packages/cli/src/telemetry/transport.ts
+++ b/packages/cli/src/telemetry/transport.ts
@@ -99,9 +99,8 @@ let inFlight: Promise<boolean> | undefined;
/**
* Flush all queued events to PostHog via async HTTP POST.
- * Call sites: the `beforeExit` hook in cli.ts (normal exit), eager sends right
- * after high-value events (trackRenderComplete / trackRenderError), and the
- * `events` beacon command, which awaits delivery before its process exits.
+ * Call sites: eager sends right after high-value events (trackRenderComplete /
+ * trackRenderError), which also serve long-lived preview processes.
*
* Events are only removed from the queue once the request has completed.
* The old drain-first version silently lost the whole batch whenever the
@@ -138,12 +137,14 @@ async function sendQueued(): Promise<boolean> {
const timeout = setTimeout(() => controller.abort(), FLUSH_TIMEOUT_MS);
try {
- await fetch(`${POSTHOG_HOST}/batch/`, {
+ const res = await fetch(`${POSTHOG_HOST}/batch/`, {
method: "POST",
headers: { "Content-Type": "application/json", Connection: "close" },
body: payload,
signal: controller.signal,
});
+ // Nothing reads the reply; drop it so a stalled body cannot hold the socket open.
+ await res.body?.cancel();
// Delivered — forget exactly what was sent (events queued while the
// request was in flight stay for the next flush).
const sent = new Set(snapshot);
@@ -175,7 +176,7 @@ export function flushSync(): void {
"-e",
`fetch(${JSON.stringify(`${POSTHOG_HOST}/batch/`)},{method:"POST",headers:{"Content-Type":"application/json"},body:${JSON.stringify(payload)},signal:AbortSignal.timeout(${FLUSH_TIMEOUT_MS})}).catch(()=>{})`,
],
- { detached: true, stdio: "ignore" },
+ { detached: true, stdio: "ignore", windowsHide: true },
);
// Let the parent exit without waiting for the child
child.unref();
diff --git a/packages/cli/src/utils/backgroundChecks.test.ts b/packages/cli/src/utils/backgroundChecks.test.ts
new file mode 100644
index 0000000000..cc88c48155
--- /dev/null
+++ b/packages/cli/src/utils/backgroundChecks.test.ts
@@ -0,0 +1,129 @@
+import { existsSync, readFileSync } from "node:fs";
+import { basename } from "node:path";
+import { fileURLToPath } from "node:url";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const env = vi.hoisted(() => ({ dev: false }));
+vi.mock("./env.js", () => ({ isDevMode: () => env.dev }));
+const disk = vi.hoisted(() => ({ config: {} as Record<string, unknown> }));
+vi.mock("../telemetry/config.js", () => ({
+ readConfig: () => ({ ...disk.config }),
+ readConfigFresh: () => ({ ...disk.config }),
+ writeConfig: (next: Record<string, unknown>) => {
+ disk.config = { ...next };
+ return true;
+ },
+}));
+const child = vi.hoisted(() => ({ on: vi.fn(), unref: vi.fn() }));
+const spawn = vi.hoisted(() => vi.fn(() => child));
+vi.mock("node:child_process", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("node:child_process")>()),
+ spawn,
+}));
+
+const { launchBackgroundChecks } = await import("./backgroundChecks.js");
+
+/** The checks handed to the child, or null when none was spawned. */
+function spawnedChecks(): string[] | null {
+ const call = spawn.mock.calls[0] as unknown as [string, string[]] | undefined;
+ return call ? call[1].slice(1) : null;
+}
+
+/** tsup entry name -> source file, as the package build declares them. */
+function buildEntries(): Map<string, string> {
+ const config = readFileSync(new URL("../../tsup.config.ts", import.meta.url), "utf8");
+ const block = config.slice(config.indexOf("entry: {"));
+ const entries = block.slice(0, block.indexOf("},"));
+ return new Map([...entries.matchAll(/"?([\w/]+)"?: "([^"]+)"/g)].map((m) => [m[1]!, m[2]!]));
+}
+
+describe("launchBackgroundChecks", () => {
+ let origTTY: boolean | undefined;
+ beforeEach(() => {
+ spawn.mockClear();
+ disk.config = {};
+ env.dev = false;
+ for (const name of ["CI", "HYPERFRAMES_NO_UPDATE_CHECK", "HYPERFRAMES_SKIP_SKILLS"]) {
+ vi.stubEnv(name, "");
+ }
+ origTTY = process.stderr.isTTY;
+ Object.defineProperty(process.stderr, "isTTY", { value: true, configurable: true });
+ });
+ afterEach(() => {
+ vi.useRealTimers();
+ vi.unstubAllEnvs();
+ Object.defineProperty(process.stderr, "isTTY", { value: origTTY, configurable: true });
+ });
+
+ it("runs both stale checks in one detached child the parent does not wait for", () => {
+ launchBackgroundChecks();
+ expect(spawn).toHaveBeenCalledTimes(1);
+ const [execPath, , opts] = spawn.mock.calls[0] as unknown as [
+ string,
+ string[],
+ Record<string, unknown>,
+ ];
+ expect(execPath).toBe(process.execPath);
+ expect(spawnedChecks()).toEqual(["update", "skills"]);
+ expect(opts).toMatchObject({ detached: true, stdio: "ignore", windowsHide: true });
+ expect(child.unref).toHaveBeenCalled();
+ expect(child.on).toHaveBeenCalledWith("error", expect.any(Function));
+ });
+
+ it("spawns the file the package build emits", () => {
+ launchBackgroundChecks();
+ const worker = (spawn.mock.calls[0] as unknown as [string, string[]])[1][0]!;
+ const source = buildEntries().get(basename(worker, ".js"));
+ expect(source, `${basename(worker)} is not a tsup entry`).toBeDefined();
+ expect(existsSync(fileURLToPath(new URL(`../../${source}`, import.meta.url)))).toBe(true);
+ });
+
+ it("retries a check that did not refresh its cache at most once an hour", () => {
+ vi.useFakeTimers({ toFake: ["Date"] });
+ launchBackgroundChecks();
+ expect(spawnedChecks()).toEqual(["update", "skills"]);
+
+ // The child failed (offline): no cache written. The next command within the hour starts nothing.
+ spawn.mockClear();
+ vi.advanceTimersByTime(59 * 60 * 1000);
+ launchBackgroundChecks();
+ expect(spawn).not.toHaveBeenCalled();
+
+ vi.advanceTimersByTime(2 * 60 * 1000);
+ launchBackgroundChecks();
+ expect(spawnedChecks()).toEqual(["update", "skills"]);
+ });
+
+ it("ignores an attempt stamp dated in the future, as after a clock correction", () => {
+ const later = new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString();
+ disk.config = { lastUpdateAttemptAt: later, lastSkillsAttemptAt: later };
+ launchBackgroundChecks();
+ expect(spawnedChecks()).toEqual(["update", "skills"]);
+ });
+
+ it("does not start a second skills check while one started this hour", () => {
+ disk.config = { lastUpdateCheck: new Date().toISOString(), latestVersion: "1.0.0" };
+ launchBackgroundChecks();
+ expect(spawnedChecks()).toEqual(["skills"]);
+ spawn.mockClear();
+ launchBackgroundChecks();
+ expect(spawn).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ ["dev mode", () => (env.dev = true), null],
+ ["CI=1", () => vi.stubEnv("CI", "1"), null],
+ ["CI=true", () => vi.stubEnv("CI", "true"), null],
+ ["HYPERFRAMES_NO_UPDATE_CHECK=1", () => vi.stubEnv("HYPERFRAMES_NO_UPDATE_CHECK", "1"), null],
+ ["HYPERFRAMES_SKIP_SKILLS=1", () => vi.stubEnv("HYPERFRAMES_SKIP_SKILLS", "1"), ["update"]],
+ [
+ "no terminal",
+ () => Object.defineProperty(process.stderr, "isTTY", { value: false, configurable: true }),
+ ["update"],
+ ],
+ ])("with %s, hands the child only what the parent used to check", (_, arrange, checks) => {
+ arrange();
+ launchBackgroundChecks();
+ expect(spawnedChecks()).toEqual(checks);
+ });
+});
diff --git a/packages/cli/src/utils/backgroundChecks.ts b/packages/cli/src/utils/backgroundChecks.ts
new file mode 100644
index 0000000000..5b984bf47c
--- /dev/null
+++ b/packages/cli/src/utils/backgroundChecks.ts
@@ -0,0 +1,44 @@
+import { spawn } from "node:child_process";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+import { readConfig, readConfigFresh, writeConfig } from "../telemetry/config.js";
+import { skillsCheckDue } from "./skillsUpdateCheck.js";
+import { updateCheckDue } from "./updateCheck.js";
+
+/** A check that did not refresh its cache (offline, DNS down) is retried at most this often. */
+const FAILED_CHECK_RETRY_MS = 60 * 60 * 1000;
+
+function attemptedRecently(stamp: string | undefined, now: number): boolean {
+ const age = stamp === undefined ? NaN : now - new Date(stamp).getTime();
+ return age >= 0 && age < FAILED_CHECK_RETRY_MS;
+}
+
+/** Refresh the due update and skills caches in a detached child, so this process never waits on it. */
+export function launchBackgroundChecks(): void {
+ const now = Date.now();
+ const config = readConfig();
+ const due: string[] = [];
+ if (updateCheckDue() && !attemptedRecently(config.lastUpdateAttemptAt, now)) due.push("update");
+ if (skillsCheckDue() && !attemptedRecently(config.lastSkillsAttemptAt, now)) due.push("skills");
+ if (due.length === 0) return;
+
+ const stamped = readConfigFresh();
+ const at = new Date(now).toISOString();
+ if (due.includes("update")) stamped.lastUpdateAttemptAt = at;
+ if (due.includes("skills")) stamped.lastSkillsAttemptAt = at;
+ writeConfig(stamped);
+
+ // Next to the bundled cli.js; from source (dev mode) no check is ever due.
+ const worker = join(dirname(fileURLToPath(import.meta.url)), "backgroundChecksWorker.js");
+ try {
+ const child = spawn(process.execPath, [worker, ...due], {
+ detached: true,
+ stdio: "ignore",
+ windowsHide: true,
+ });
+ child.on("error", () => {});
+ child.unref();
+ } catch {
+ // Best-effort: the next run tries again.
+ }
+}
diff --git a/packages/cli/src/utils/hostAnswers.test.ts b/packages/cli/src/utils/hostAnswers.test.ts
new file mode 100644
index 0000000000..6fc3558a92
--- /dev/null
+++ b/packages/cli/src/utils/hostAnswers.test.ts
@@ -0,0 +1,81 @@
+import { createSocket, type Socket } from "node:dgram";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+// Point every Resolver hostAnswers creates at a local UDP server this test controls.
+const dnsServer = vi.hoisted(() => ({ address: "" }));
+vi.mock("node:dns", async (importOriginal) => {
+ const real = await importOriginal<typeof import("node:dns")>();
+ class Resolver extends real.promises.Resolver {
+ constructor(options?: ConstructorParameters<typeof real.promises.Resolver>[0]) {
+ super(options);
+ this.setServers([dnsServer.address]);
+ }
+ }
+ return { ...real, promises: { ...real.promises, Resolver } };
+});
+
+let socket: Socket | undefined;
+
+/** A DNS server: "silent" never replies, "answer" answers A with 127.0.0.1, "no-aaaa" answers A and drops AAAA. */
+async function startServer(mode: "silent" | "answer" | "no-aaaa"): Promise<void> {
+ socket = createSocket("udp4");
+ socket.on("message", (msg, peer) => {
+ if (mode === "silent") return;
+ let end = 12;
+ while (msg[end] !== 0) end += (msg[end] ?? 0) + 1;
+ end += 5;
+ const isA = msg.readUInt16BE(end - 4) === 1;
+ if (mode === "no-aaaa" && !isA) return;
+ const header = Buffer.alloc(12);
+ msg.copy(header, 0, 0, 2);
+ header.writeUInt16BE(0x8180, 2);
+ header.writeUInt16BE(1, 4);
+ header.writeUInt16BE(isA ? 1 : 0, 6);
+ const record = Buffer.from([0xc0, 0x0c, 0, 1, 0, 1, 0, 0, 0, 60, 0, 4, 127, 0, 0, 1]);
+ socket?.send(
+ Buffer.concat([header, msg.subarray(12, end), ...(isA ? [record] : [])]),
+ peer.port,
+ peer.address,
+ );
+ });
+ await new Promise<void>((resolve) => socket?.bind(0, "127.0.0.1", resolve));
+ dnsServer.address = `127.0.0.1:${socket.address().port}`;
+}
+
+describe("hostAnswers", () => {
+ afterEach(() => {
+ socket?.close();
+ socket = undefined;
+ });
+
+ it("says no, within its short timeout, when DNS never replies", async () => {
+ await startServer("silent");
+ const { hostAnswers } = await import("./hostAnswers.js");
+ const started = Date.now();
+ expect(await hostAnswers("registry.npmjs.org")).toBe(false);
+ expect(Date.now() - started).toBeLessThan(3500);
+ });
+
+ it("says yes when DNS answers", async () => {
+ await startServer("answer");
+ const { hostAnswers } = await import("./hostAnswers.js");
+ expect(await hostAnswers("registry.npmjs.org")).toBe(true);
+ });
+ it("says yes without asking DNS when fetch goes through an env proxy", async () => {
+ await startServer("silent");
+ vi.stubEnv("HTTPS_PROXY", "http://127.0.0.1:9");
+ vi.stubEnv("NODE_USE_ENV_PROXY", "1");
+ try {
+ const { hostAnswers } = await import("./hostAnswers.js");
+ expect(await hostAnswers("registry.npmjs.org")).toBe(true);
+ } finally {
+ vi.unstubAllEnvs();
+ }
+ });
+
+ it("says no when A answers but AAAA never does, since the system lookup waits for both", async () => {
+ await startServer("no-aaaa");
+ const { hostAnswers } = await import("./hostAnswers.js");
+ expect(await hostAnswers("registry.npmjs.org")).toBe(false);
+ });
+});
diff --git a/packages/cli/src/utils/hostAnswers.ts b/packages/cli/src/utils/hostAnswers.ts
index 4698c1dac3..fd5262d9b0 100644
--- a/packages/cli/src/utils/hostAnswers.ts
+++ b/packages/cli/src/utils/hostAnswers.ts
@@ -2,19 +2,25 @@ import { promises as dns } from "node:dns";
const PROBE_TIMEOUT_MS = 1000;
+function fetchGoesThroughEnvProxy(): boolean {
+ if (!(process.env["HTTPS_PROXY"] ?? process.env["https_proxy"])?.trim()) return false;
+ const flags = [...process.execArgv, ...(process.env["NODE_OPTIONS"]?.split(/\s+/u) ?? [])];
+ return process.env["NODE_USE_ENV_PROXY"] === "1" || flags.includes("--use-env-proxy");
+}
+
/**
* Whether DNS answers for `host` via c-ares, one short try per nameserver. The system lookup
* `fetch` makes cannot be aborted and holds even `process.exit`, so background requests ask this first.
*/
export async function hostAnswers(host: string): Promise<boolean> {
+ if (fetchGoesThroughEnvProxy()) return true;
try {
const resolver = new dns.Resolver({ timeout: PROBE_TIMEOUT_MS, tries: 1 });
- try {
- await Promise.any([resolver.resolve4(host), resolver.resolve6(host)]);
- return true;
- } finally {
- resolver.cancel();
- }
+ const results = await Promise.allSettled([resolver.resolve4(host), resolver.resolve6(host)]);
+ const anyFamilyTimedOut = results.some(
+ (r) => r.status === "rejected" && (r.reason as NodeJS.ErrnoException).code === "ETIMEOUT",
+ );
+ return !anyFamilyTimedOut && results.some((r) => r.status === "fulfilled");
} catch {
return false;
}
diff --git a/packages/cli/src/utils/skillsManifest.test.ts b/packages/cli/src/utils/skillsManifest.test.ts
index 7828a953b9..71e4cea5c4 100644
--- a/packages/cli/src/utils/skillsManifest.test.ts
+++ b/packages/cli/src/utils/skillsManifest.test.ts
@@ -10,6 +10,7 @@ import {
statSync,
writeFileSync,
} from "node:fs";
+import { execFile } from "node:child_process";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
@@ -777,6 +778,13 @@ describe("checkSkills canonical bypass of the in-repo manifest shortcut", () =>
const res = await checkSkills({ cwd: project, home, canonical: true });
expect(res.skills.map((s) => s.name)).not.toContain("retired-skill");
expect(res.skills.map((s) => s.name)).toContain("kept");
+ // The background check runs this with no console; git must not open one on Windows.
+ expect(vi.mocked(execFile)).toHaveBeenCalledWith(
+ "git",
+ expect.arrayContaining(["ls-remote"]),
+ expect.objectContaining({ windowsHide: true }),
+ expect.any(Function),
+ );
});
it("canonical:true still honors an explicit local `source` override", async () => {
diff --git a/packages/cli/src/utils/skillsManifest.ts b/packages/cli/src/utils/skillsManifest.ts
index aaa19efceb..77b2dbfb7d 100644
--- a/packages/cli/src/utils/skillsManifest.ts
+++ b/packages/cli/src/utils/skillsManifest.ts
@@ -664,7 +664,11 @@ async function remoteHeadSha(repoSlug: string): Promise<string | null> {
const { stdout } = await execFileAsync(
"git",
["ls-remote", `https://github.com/${repoSlug}.git`, "refs/heads/main"],
- { timeout: FETCH_TIMEOUT_MS, env: { ...process.env, GIT_TERMINAL_PROMPT: "0" } },
+ {
+ timeout: FETCH_TIMEOUT_MS,
+ env: { ...process.env, GIT_TERMINAL_PROMPT: "0" },
+ windowsHide: true,
+ },
);
const sha = stdout.split(/\s+/)[0]?.trim() ?? "";
return /^[0-9a-f]{40}$/.test(sha) ? sha : null;
diff --git a/packages/cli/src/utils/skillsUpdateCheck.test.ts b/packages/cli/src/utils/skillsUpdateCheck.test.ts
index 43163529b8..d496476d28 100644
--- a/packages/cli/src/utils/skillsUpdateCheck.test.ts
+++ b/packages/cli/src/utils/skillsUpdateCheck.test.ts
@@ -8,9 +8,11 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
type FakeConfig = Record<string, unknown>;
let config: FakeConfig;
+// What a process-cached readConfig() returns; null means it matches disk.
+let cachedRead: FakeConfig | null = null;
vi.mock("../telemetry/config.js", () => ({
- readConfig: () => ({ ...config }),
+ readConfig: () => ({ ...(cachedRead ?? config) }),
readConfigFresh: () => ({ ...config }),
writeConfig: (next: FakeConfig) => {
config = { ...next };
@@ -32,6 +34,7 @@ describe("skillsUpdateCheck", () => {
beforeEach(() => {
vi.resetModules();
config = {};
+ cachedRead = null;
mockCheckSkills.mockReset();
gate.suppressed = false;
gate.answers = true;
@@ -45,14 +48,34 @@ describe("skillsUpdateCheck", () => {
it.each([
["HYPERFRAMES_SKIP_SKILLS is set", () => vi.stubEnv("HYPERFRAMES_SKIP_SKILLS", "1")],
["the run shows no notices", () => (gate.suppressed = true)],
- ["DNS does not answer", () => (gate.answers = false)],
- ])("does not check skills when %s", async (_, arrange) => {
+ ])("no background check is due when %s", async (_, arrange) => {
+ const { skillsCheckDue } = await import("./skillsUpdateCheck.js");
+ expect(skillsCheckDue()).toBe(true);
arrange();
- const { checkSkillsForUpdate } = await import("./skillsUpdateCheck.js");
- await checkSkillsForUpdate(true);
+ expect(skillsCheckDue()).toBe(false);
+ });
+
+ it("does not check skills when DNS does not answer", async () => {
+ gate.answers = false;
+ const { refreshSkillsCache } = await import("./skillsUpdateCheck.js");
+ await refreshSkillsCache();
expect(mockCheckSkills).not.toHaveBeenCalled();
});
+ it("writes onto a fresh read, keeping what another process wrote meanwhile", async () => {
+ config = { commandCount: 1 };
+ cachedRead = { ...config };
+ config = { commandCount: 2 };
+ mockCheckSkills.mockResolvedValue({
+ location: "/home/user/.claude/skills",
+ updateAvailable: false,
+ summary: { current: 1, outdated: 0, missing: 0, coreMissing: 0, removed: 0 },
+ });
+ const { refreshSkillsCache } = await import("./skillsUpdateCheck.js");
+ await refreshSkillsCache();
+ expect(config).toMatchObject({ commandCount: 2, skillsOutdatedCount: 0 });
+ });
+
it("refreshSkillsCache persists the removed count alongside outdated/missing", async () => {
mockCheckSkills.mockResolvedValue({
location: "/home/user/.claude/skills",
@@ -60,11 +83,15 @@ describe("skillsUpdateCheck", () => {
summary: { current: 1, outdated: 2, missing: 3, coreMissing: 1, removed: 3 },
});
- const { checkSkillsForUpdate } = await import("./skillsUpdateCheck.js");
- const meta = await checkSkillsForUpdate(true);
+ const { refreshSkillsCache } = await import("./skillsUpdateCheck.js");
+ await refreshSkillsCache();
- expect(meta).toEqual({ updateAvailable: true, outdated: 2, missing: 1, removed: 3 });
- expect(config["skillsRemovedCount"]).toBe(3);
+ expect(config).toMatchObject({
+ skillsUpdateAvailable: true,
+ skillsOutdatedCount: 2,
+ skillsMissingCount: 1,
+ skillsRemovedCount: 3,
+ });
// Must resolve against the canonical upstream manifest, not a possibly
// stale in-repo skills-manifest.json, so this nudge agrees with what
// `updateSkills` would actually reconcile.
@@ -78,8 +105,8 @@ describe("skillsUpdateCheck", () => {
summary: { current: 0, outdated: 0, missing: 0, coreMissing: 0, removed: 0 },
});
- const { checkSkillsForUpdate } = await import("./skillsUpdateCheck.js");
- await checkSkillsForUpdate(true);
+ const { refreshSkillsCache } = await import("./skillsUpdateCheck.js");
+ await refreshSkillsCache();
expect(config["skillsRemovedCount"]).toBeUndefined();
});
@@ -150,12 +177,9 @@ describe("skillsUpdateCheck", () => {
it("a fresh cache short-circuits the background check with the stale verdict (the bug's precondition)", async () => {
config = { ...PRE_INSTALL_CACHE };
- const { checkSkillsForUpdate } = await import("./skillsUpdateCheck.js");
-
- const meta = await checkSkillsForUpdate();
+ const { skillsCheckDue } = await import("./skillsUpdateCheck.js");
- expect(mockCheckSkills).not.toHaveBeenCalled();
- expect(meta).toEqual({ updateAvailable: true, outdated: 12, missing: 8, removed: 0 });
+ expect(skillsCheckDue()).toBe(false);
});
it("drops the cached verdict so the next background check re-runs for real", async () => {
@@ -166,7 +190,7 @@ describe("skillsUpdateCheck", () => {
summary: { current: 20, outdated: 0, missing: 0, coreMissing: 0, removed: 0 },
});
- const { checkSkillsForUpdate, invalidateSkillsCache } =
+ const { skillsCheckDue, refreshSkillsCache, invalidateSkillsCache } =
await import("./skillsUpdateCheck.js");
invalidateSkillsCache();
@@ -177,22 +201,22 @@ describe("skillsUpdateCheck", () => {
expect(config["skillsMissingCount"]).toBeUndefined();
expect(config["skillsRemovedCount"]).toBeUndefined();
- const meta = await checkSkillsForUpdate();
+ expect(skillsCheckDue()).toBe(true);
+ await refreshSkillsCache();
expect(mockCheckSkills).toHaveBeenCalledWith({ canonical: true });
- expect(meta).toEqual({ updateAvailable: false, outdated: 0, missing: 0, removed: 0 });
+ expect(config).toMatchObject({ skillsUpdateAvailable: false, skillsOutdatedCount: 0 });
});
it("counts are cleared, not just the timestamp — an offline machine goes quiet instead of resurrecting stale counts", async () => {
config = { ...PRE_INSTALL_CACHE };
mockCheckSkills.mockRejectedValue(new Error("offline"));
- const { checkSkillsForUpdate, invalidateSkillsCache, printSkillsUpdateNotice } =
+ const { refreshSkillsCache, invalidateSkillsCache, printSkillsUpdateNotice } =
await import("./skillsUpdateCheck.js");
invalidateSkillsCache();
- // Refresh fails (offline) → falls back to cached meta, which is now empty.
- const meta = await checkSkillsForUpdate();
- expect(meta).toEqual({ updateAvailable: false, outdated: 0, missing: 0, removed: 0 });
+ // Refresh fails (offline) and leaves the now-empty cache alone.
+ await expect(refreshSkillsCache()).rejects.toThrow("offline");
const writeSpy = vi.spyOn(process.stderr, "write").mockImplementation(() => true);
printSkillsUpdateNotice();
diff --git a/packages/cli/src/utils/skillsUpdateCheck.ts b/packages/cli/src/utils/skillsUpdateCheck.ts
index b60b5051c2..d4cdf0d82d 100644
--- a/packages/cli/src/utils/skillsUpdateCheck.ts
+++ b/packages/cli/src/utils/skillsUpdateCheck.ts
@@ -13,7 +13,7 @@ import { updateNoticesSuppressed } from "./updateCheck.js";
const CHECK_INTERVAL_MS = 24 * 60 * 60 * 1000; // 24 hours
-export interface SkillsUpdateMeta {
+interface SkillsUpdateMeta {
updateAvailable: boolean;
outdated: number;
missing: number;
@@ -37,15 +37,17 @@ function cacheFresh(lastSkillsCheck: string | undefined, now: number): boolean {
return now - new Date(lastSkillsCheck).getTime() < CHECK_INTERVAL_MS;
}
-/** Run the real check and persist the result to the cache. */
-async function refreshSkillsCache(): Promise<SkillsUpdateMeta> {
+/** Run the real check and persist the result to the cache. Skipped when DNS does not answer. */
+export async function refreshSkillsCache(): Promise<void> {
+ if (!(await hostAnswers("github.com"))) return;
// `canonical: true` so this nudge's counts agree with `updateSkills`'s
// source of truth — otherwise a stale in-repo skills-manifest.json (e.g.
// inside a hyperframes checkout) can produce a false-positive count here.
const result = await checkSkills({ canonical: true });
// Only record a meaningful check when skills were actually found.
if (result.location) {
- const config = readConfig();
+ // Fresh read: this runs in a background child, beside the command's own config writes.
+ const config = readConfigFresh();
config.lastSkillsCheck = new Date().toISOString();
config.skillsUpdateAvailable = result.updateAvailable;
config.skillsOutdatedCount = result.summary.outdated;
@@ -59,12 +61,6 @@ async function refreshSkillsCache(): Promise<SkillsUpdateMeta> {
config.skillsRemovedCount = result.summary.removed;
writeConfig(config);
}
- return {
- updateAvailable: result.updateAvailable,
- outdated: result.summary.outdated,
- missing: result.summary.coreMissing,
- removed: result.summary.removed,
- };
}
/**
@@ -101,24 +97,10 @@ export function invalidateSkillsCache(): void {
}
}
-/**
- * Refresh the skills freshness cache if it is older than 24h, only in runs that show the nudge. Best-effort:
- * any failure (offline, no manifest published yet, no skills installed) leaves
- * the cache untouched and reports "no update".
- *
- * @param force - skip the cache and check now
- */
-export async function checkSkillsForUpdate(force?: boolean): Promise<SkillsUpdateMeta> {
- if (process.env["HYPERFRAMES_SKIP_SKILLS"] === "1" || updateNoticesSuppressed()) {
- return getSkillsUpdateMeta();
- }
- if (!force && cacheFresh(readConfig().lastSkillsCheck, Date.now())) return getSkillsUpdateMeta();
- try {
- if (!(await hostAnswers("github.com"))) return getSkillsUpdateMeta();
- return await refreshSkillsCache();
- } catch {
- return getSkillsUpdateMeta();
- }
+/** Whether a background skills check is due: this run shows notices and the 24 h cache is stale. */
+export function skillsCheckDue(): boolean {
+ if (process.env["HYPERFRAMES_SKIP_SKILLS"] === "1" || updateNoticesSuppressed()) return false;
+ return !cacheFresh(readConfig().lastSkillsCheck, Date.now());
}
/** The stale-skills nudge text, or null when nothing is outdated, missing, or removed. */
diff --git a/packages/cli/src/utils/updateCheck.stalepin.test.ts b/packages/cli/src/utils/updateCheck.stalepin.test.ts
index 297c833e6a..fe8f67ce78 100644
--- a/packages/cli/src/utils/updateCheck.stalepin.test.ts
+++ b/packages/cli/src/utils/updateCheck.stalepin.test.ts
@@ -17,8 +17,11 @@ vi.mock("../version.js", () => ({
// isDevMode() is true under vitest (module path ends in .ts), which would
// suppress the notice unconditionally — mock ./env.js like updateCheck.test.ts does.
vi.mock("./env.js", () => ({ isDevMode: () => false }));
+// What a process-cached readConfig() returns; null means it matches disk.
+let cachedRead: Record<string, unknown> | null = null;
vi.mock("../telemetry/config.js", () => ({
- readConfig: () => ({ ...store }),
+ readConfig: () => ({ ...(cachedRead ?? store) }),
+ readConfigFresh: () => ({ ...store }),
writeConfig: (c: Record<string, unknown>) => {
store = { ...c };
return true;
@@ -33,6 +36,7 @@ describe("printStalePinNotice", () => {
const origWrite = process.stderr.write.bind(process.stderr);
beforeEach(() => {
store = { latestVersion: "0.7.55" };
+ cachedRead = null;
runningVersion = "0.7.55";
writes = [];
dir = mkdtempSync(join(tmpdir(), "hf-pin-"));
@@ -48,6 +52,18 @@ describe("printStalePinNotice", () => {
rmSync(dir, { recursive: true, force: true });
});
+ it("keeps what the background check wrote after this process read the settings", () => {
+ writeFileSync(
+ join(dir, "package.json"),
+ JSON.stringify({ scripts: { render: "npx --yes [email protected] render" } }),
+ );
+ cachedRead = { ...store };
+ store = { ...store, lastUpdateCheck: "2026-09-27T00:00:00.000Z" };
+ printStalePinNotice(dir);
+ expect(store).toMatchObject({ lastUpdateCheck: "2026-09-27T00:00:00.000Z" });
+ expect(store["lastStalePinNoticeAt"]).toEqual(expect.any(Number));
+ });
+
it("warns once when the project pins an older version", () => {
writeFileSync(
join(dir, "package.json"),
diff --git a/packages/cli/src/utils/updateCheck.test.ts b/packages/cli/src/utils/updateCheck.test.ts
index 33c0a8e932..0df1dd9e36 100644
--- a/packages/cli/src/utils/updateCheck.test.ts
+++ b/packages/cli/src/utils/updateCheck.test.ts
@@ -337,6 +337,28 @@ describe("checkForUpdate — registry boundary guard", () => {
expect(wroteVersion).toBeUndefined();
});
+ it("leaves no timer behind when the registry request fails fast", async () => {
+ vi.resetModules();
+ vi.doMock("../telemetry/config.js", () => ({
+ readConfig: () => ({}),
+ readConfigFresh: () => ({}),
+ writeConfig: () => {},
+ }));
+ const origFetch = globalThis.fetch;
+ globalThis.fetch = (async () => {
+ throw new TypeError("fetch failed");
+ }) as unknown as typeof fetch;
+ vi.useFakeTimers();
+ try {
+ const mod = await import("./updateCheck.js");
+ await mod.checkForUpdate(true);
+ expect(vi.getTimerCount()).toBe(0);
+ } finally {
+ vi.useRealTimers();
+ globalThis.fetch = origFetch;
+ }
+ });
+
it("merges update metadata into a fresh snapshot without re-enabling telemetry", async () => {
const persisted = await checkAcrossConcurrentConfigWrite();
expect(persisted).toMatchObject({
@@ -345,3 +367,58 @@ describe("checkForUpdate — registry boundary guard", () => {
});
});
});
+
+describe("updateCheckDue / cachedUpdateCheck — what the parent reads without fetching", () => {
+ afterEach(() => {
+ vi.doUnmock("../telemetry/config.js");
+ vi.doUnmock("./env.js");
+ vi.resetModules();
+ vi.unstubAllEnvs();
+ });
+
+ async function load(config: Record<string, unknown>) {
+ vi.resetModules();
+ vi.stubEnv("CI", "");
+ vi.stubEnv("HYPERFRAMES_NO_UPDATE_CHECK", "");
+ vi.doMock("./env.js", () => ({ isDevMode: () => false }));
+ vi.doMock("../telemetry/config.js", () => ({
+ readConfig: () => ({ ...config }),
+ readConfigFresh: () => ({ ...config }),
+ writeConfig: () => {},
+ }));
+ return import("./updateCheck.js");
+ }
+
+ const hoursAgo = (h: number) => new Date(Date.now() - h * 3_600_000).toISOString();
+
+ it.each([
+ ["no cache", {}, true],
+ ["a cache from an hour ago", { lastUpdateCheck: hoursAgo(1), latestVersion: "9.9.9" }, false],
+ ["a cache from 25 hours ago", { lastUpdateCheck: hoursAgo(25), latestVersion: "9.9.9" }, true],
+ ["an unreadable timestamp", { lastUpdateCheck: "garbage", latestVersion: "9.9.9" }, true],
+ [
+ "an unsafe cached version",
+ { lastUpdateCheck: hoursAgo(1), latestVersion: "1.2.3; rm" },
+ true,
+ ],
+ ])("with %s, a check is due: %s", async (_, config, due) => {
+ const mod = await load(config);
+ expect(mod.updateCheckDue()).toBe(due);
+ });
+
+ it("is never due under CI", async () => {
+ const mod = await load({});
+ vi.stubEnv("CI", "1");
+ expect(mod.updateCheckDue()).toBe(false);
+ });
+
+ it("reports a cached newer version, and never surfaces an unsafe one", async () => {
+ expect((await load({ latestVersion: "999.0.0" })).cachedUpdateCheck()).toMatchObject({
+ latest: "999.0.0",
+ updateAvailable: true,
+ });
+ const poisoned = (await load({ latestVersion: "999.0.0; rm -rf /" })).cachedUpdateCheck();
+ expect(poisoned.updateAvailable).toBe(false);
+ expect(poisoned.latest).not.toContain(";");
+ });
+});
diff --git a/packages/cli/src/utils/updateCheck.ts b/packages/cli/src/utils/updateCheck.ts
index c87d35bb51..9bd418096b 100644
--- a/packages/cli/src/utils/updateCheck.ts
+++ b/packages/cli/src/utils/updateCheck.ts
@@ -46,26 +46,7 @@ export interface UpdateMeta {
*/
export async function checkForUpdate(force?: boolean): Promise<UpdateCheckResult> {
const config = readConfig();
- if (!force && updateCheckDisabled()) return fallbackResult(config.latestVersion);
- const now = Date.now();
-
- // Also guard the cache read: a cache written before this boundary guard
- // existed could hold an unsafe latestVersion — re-validate before trusting it.
- if (
- !force &&
- config.lastUpdateCheck &&
- config.latestVersion &&
- isSafeVersion(config.latestVersion)
- ) {
- const lastCheck = new Date(config.lastUpdateCheck).getTime();
- if (now - lastCheck < CHECK_INTERVAL_MS) {
- return {
- current: VERSION,
- latest: config.latestVersion,
- updateAvailable: isNewerSemver(config.latestVersion, VERSION),
- };
- }
- }
+ if (!force && !updateCheckDue(config)) return fallbackResult(config.latestVersion);
try {
if (!force && !(await hostAnswers(new URL(NPM_REGISTRY_URL).hostname))) {
@@ -73,15 +54,17 @@ export async function checkForUpdate(force?: boolean): Promise<UpdateCheckResult
}
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
- const res = await fetch(NPM_REGISTRY_URL, {
- signal: controller.signal,
- headers: { Connection: "close" },
- });
- clearTimeout(timeout);
-
- if (!res.ok) return fallbackResult(config.latestVersion);
-
- const data = (await res.json()) as { version?: unknown };
+ let data: { version?: unknown };
+ try {
+ const res = await fetch(NPM_REGISTRY_URL, {
+ signal: controller.signal,
+ headers: { Connection: "close" },
+ });
+ if (!res.ok) return fallbackResult(config.latestVersion);
+ data = (await res.json()) as { version?: unknown };
+ } finally {
+ clearTimeout(timeout);
+ }
// Registry boundary guard: only a strict-semver STRING is trusted. This
// value is cached and later flows into an install command that the
// background auto-updater executes, so a poisoned or non-string
@@ -108,6 +91,20 @@ export async function checkForUpdate(force?: boolean): Promise<UpdateCheckResult
}
}
+/** Whether the background check should ask the registry: not opted out, and no fresh safe cache. */
+export function updateCheckDue(config = readConfig()): boolean {
+ if (updateCheckDisabled()) return false;
+ if (!config.lastUpdateCheck || !config.latestVersion || !isSafeVersion(config.latestVersion)) {
+ return true;
+ }
+ const fresh = Date.now() - new Date(config.lastUpdateCheck).getTime() < CHECK_INTERVAL_MS;
+ return !fresh;
+}
+
+export function cachedUpdateCheck(): UpdateCheckResult {
+ return fallbackResult(readConfig().latestVersion);
+}
+
function fallbackResult(cachedLatest?: string): UpdateCheckResult {
// Only surface a cached version we can prove is safe — a pre-existing
// poisoned cache must not leak through the fallback path either.
@@ -211,9 +208,7 @@ const STALE_PIN_THROTTLE_MS = 24 * 60 * 60 * 1000;
* is skipped for --json, so a JSON stdout stays clean regardless.
*/
export function printStalePinNotice(cwd: string = process.cwd()): void {
- if (isDevMode()) return;
- if (process.env["CI"] === "true" || process.env["CI"] === "1") return;
- if (process.env["HYPERFRAMES_NO_UPDATE_CHECK"] === "1") return;
+ if (updateCheckDisabled()) return;
let scripts: Record<string, string> = {};
try {
@@ -245,9 +240,9 @@ export function printStalePinNotice(cwd: string = process.cwd()): void {
});
if (stale.length === 0) return;
- const config = readConfig();
- const last = config.lastStalePinNoticeAt ?? 0;
+ const last = readConfig().lastStalePinNoticeAt ?? 0;
if (Date.now() - last < STALE_PIN_THROTTLE_MS) return;
+ const config = readConfigFresh();
config.lastStalePinNoticeAt = Date.now();
writeConfig(config);
diff --git a/packages/cli/tsup.config.ts b/packages/cli/tsup.config.ts
index 4e82ab1ddd..e1175ee906 100644
--- a/packages/cli/tsup.config.ts
+++ b/packages/cli/tsup.config.ts
@@ -16,6 +16,7 @@ export default defineConfig({
fontLocalizeCli: "src/fontLocalizeCli.ts",
runtimeVersion: "src/runtimeVersion.ts",
renderSetupWorker: "src/renderSetupWorker.ts",
+ backgroundChecksWorker: "src/backgroundChecksWorker.ts",
sherpaWorker: "src/whisper/sherpaWorker.ts",
shaderTransitionWorker: "../producer/src/services/shaderTransitionWorker.ts",
"registry/localSemantic": "src/registry/localSemantic.ts",
diff --git a/scripts/ci/cli-telemetry-e2e.mjs b/scripts/ci/cli-telemetry-e2e.mjs
index f8acb53cee..821bb5265c 100644
--- a/scripts/ci/cli-telemetry-e2e.mjs
+++ b/scripts/ci/cli-telemetry-e2e.mjs
@@ -14,10 +14,9 @@
* a local registry (the origin is a first-class project setting,
* `hyperframes.json#registry`) supplies an item with a `registryDependencies`
* edge, which no shipped catalog item declares today; and `globalThis.fetch`
- * is wrapped so the batch is captured instead of sent. Faking a 200 is what
- * keeps this off production analytics — `flush()` only leaves events queued
- * when the request fails, and only a non-empty queue makes the exit handler
- * spawn the detached `flushSync` child that would bypass the hook.
+ * is wrapped so the batch is captured instead of sent. The exit handler's
+ * detached `flushSync` child would bypass that wrapper, so the hook runs the
+ * child's script in-process instead; nothing reaches production analytics.
*
* Usage: node scripts/ci/cli-telemetry-e2e.mjs [path/to/dist/cli.js]
*/
@@ -135,6 +134,18 @@ globalThis.fetch = async function (input, init) {
}
return realFetch(input, init);
};
+// The exit-time flushSync() child would send past the wrapper above: run its script here instead.
+// It runs inside the exit handler, so the wrapper must record before its first await.
+const childProcess = require("node:child_process");
+const realSpawn = childProcess.spawn;
+childProcess.spawn = function (command, args, options) {
+ if (Array.isArray(args) && args[0] === "-e" && String(args[1]).includes("posthog")) {
+ (0, eval)(args[1]);
+ return { unref() {}, on() { return this; } };
+ }
+ return realSpawn.call(this, command, args, options);
+};
+require("node:module").syncBuiltinESMExports();
`,
);