Skip to content

Commit afec3f1

Browse files
committed
fix(cli): make telemetry opt-out durable
1 parent c691869 commit afec3f1

5 files changed

Lines changed: 202 additions & 20 deletions

File tree

‎packages/cli/src/cli.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -233,6 +233,8 @@ if (!isHelp && command !== "telemetry" && command !== "events" && command !== "u
233233

234234
// `events` skips the update check too — a skill-usage beacon must not add
235235
// network latency or trigger a background self-upgrade on the calling skill.
236+
// `telemetry` skips it because update metadata must never race the command
237+
// that changes the user's telemetry preference.
236238
// `skills` is excluded from the SKILLS nudge for the same reason `upgrade` is
237239
// excluded from the self-update notice: a command that is itself actively
238240
// checking/reconciling skills (`skills check`, `skills update`) must not also
@@ -244,6 +246,7 @@ if (
244246
!hasJsonFlag &&
245247
command !== "upgrade" &&
246248
command !== "events" &&
249+
command !== "telemetry" &&
247250
command !== "skills"
248251
) {
249252
// Report any completed auto-install from the previous run first, before
Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
import { afterEach, describe, expect, it, vi } from "vitest";
2+
3+
const baseConfig = {
4+
telemetryEnabled: true,
5+
anonymousId: "test-install",
6+
telemetryNoticeShown: true,
7+
commandCount: 7,
8+
renderSuccessCount: 0,
9+
lastFeedbackPromptAt: 0,
10+
};
11+
12+
async function loadTelemetryCommand(options?: {
13+
writeSucceeds?: boolean;
14+
configEnabled?: boolean;
15+
}) {
16+
const config = {
17+
...baseConfig,
18+
telemetryEnabled: options?.configEnabled ?? true,
19+
};
20+
const writeConfig = vi.fn(() => options?.writeSucceeds ?? true);
21+
vi.resetModules();
22+
vi.doMock("../telemetry/config.js", () => ({
23+
CONFIG_PATH: "/test/.hyperframes/config.json",
24+
readConfig: () => {
25+
throw new Error("telemetry commands must bypass stale cached config");
26+
},
27+
readConfigFresh: () => ({ ...config }),
28+
writeConfig,
29+
}));
30+
const module = await import("./telemetry.js");
31+
return { command: module.default, writeConfig };
32+
}
33+
34+
async function runSubcommand(
35+
command: Awaited<ReturnType<typeof loadTelemetryCommand>>["command"],
36+
subcommand: string,
37+
): Promise<void> {
38+
await command.run?.({
39+
args: { subcommand },
40+
rawArgs: [subcommand],
41+
cmd: command,
42+
} as never);
43+
}
44+
45+
describe("telemetry command", () => {
46+
afterEach(() => {
47+
vi.doUnmock("../telemetry/config.js");
48+
vi.restoreAllMocks();
49+
vi.resetModules();
50+
delete process.env["HYPERFRAMES_NO_TELEMETRY"];
51+
delete process.env["DO_NOT_TRACK"];
52+
});
53+
54+
it("persists disable from a fresh config snapshot", async () => {
55+
const { command, writeConfig } = await loadTelemetryCommand();
56+
vi.spyOn(console, "log").mockImplementation(() => undefined);
57+
58+
await runSubcommand(command, "disable");
59+
60+
expect(writeConfig).toHaveBeenCalledWith(expect.objectContaining({ telemetryEnabled: false }));
61+
});
62+
63+
it("fails instead of claiming success when the preference cannot be persisted", async () => {
64+
const { command } = await loadTelemetryCommand({ writeSucceeds: false });
65+
const stdout = vi.spyOn(console, "log").mockImplementation(() => undefined);
66+
const stderr = vi.spyOn(console, "error").mockImplementation(() => undefined);
67+
68+
await expect(runSubcommand(command, "disable")).rejects.toMatchObject({
69+
name: "CliRuntimeError",
70+
});
71+
72+
expect(stderr).toHaveBeenCalledWith(expect.stringContaining("Could not persist"));
73+
expect(stdout).not.toHaveBeenCalledWith(expect.stringContaining("Telemetry disabled"));
74+
});
75+
76+
it("reports the effective env-var opt-out instead of the stored preference", async () => {
77+
process.env["HYPERFRAMES_NO_TELEMETRY"] = "1";
78+
const { command } = await loadTelemetryCommand({ configEnabled: true });
79+
const lines: string[] = [];
80+
vi.spyOn(console, "log").mockImplementation((...args: unknown[]) => {
81+
lines.push(args.map(String).join(" "));
82+
});
83+
84+
await runSubcommand(command, "status");
85+
86+
const output = lines.join("\n");
87+
expect(output).toContain("disabled");
88+
expect(output).toContain("HYPERFRAMES_NO_TELEMETRY");
89+
expect(output).toContain("Tracked commands:");
90+
});
91+
92+
it("reports DO_NOT_TRACK as the effective opt-out source", async () => {
93+
process.env["DO_NOT_TRACK"] = "1";
94+
const { command } = await loadTelemetryCommand({ configEnabled: true });
95+
const lines: string[] = [];
96+
vi.spyOn(console, "log").mockImplementation((...args: unknown[]) => {
97+
lines.push(args.map(String).join(" "));
98+
});
99+
100+
await runSubcommand(command, "status");
101+
102+
expect(lines.join("\n")).toContain("DO_NOT_TRACK");
103+
});
104+
});

‎packages/cli/src/commands/telemetry.ts‎

Lines changed: 34 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -8,29 +8,47 @@ export const examples: Example[] = [
88
["Disable telemetry", "hyperframes telemetry disable"],
99
["Enable telemetry", "hyperframes telemetry enable"],
1010
];
11-
import { readConfig, writeConfig, CONFIG_PATH } from "../telemetry/config.js";
11+
import { readConfigFresh, writeConfig, CONFIG_PATH } from "../telemetry/config.js";
1212

13-
function runEnable(): void {
14-
const config = readConfig();
15-
config.telemetryEnabled = true;
16-
writeConfig(config);
17-
console.log(`\n ${c.success("\u2713")} Telemetry ${c.success("enabled")}\n`);
13+
type TelemetryStatus = {
14+
enabled: boolean;
15+
source: "config" | "HYPERFRAMES_NO_TELEMETRY" | "DO_NOT_TRACK";
16+
};
17+
18+
function effectiveTelemetryStatus(configEnabled: boolean): TelemetryStatus {
19+
if (process.env["HYPERFRAMES_NO_TELEMETRY"] === "1") {
20+
return { enabled: false, source: "HYPERFRAMES_NO_TELEMETRY" };
21+
}
22+
if (process.env["DO_NOT_TRACK"] === "1") {
23+
return { enabled: false, source: "DO_NOT_TRACK" };
24+
}
25+
return { enabled: configEnabled, source: "config" };
1826
}
1927

20-
function runDisable(): void {
21-
const config = readConfig();
22-
config.telemetryEnabled = false;
23-
writeConfig(config);
24-
console.log(`\n ${c.success("\u2713")} Telemetry ${c.bold("disabled")}\n`);
28+
function setTelemetryEnabled(enabled: boolean): void {
29+
// Bypass the module cache so this privacy preference starts from the latest
30+
// on-disk state rather than a snapshot held by another config consumer.
31+
const config = readConfigFresh();
32+
config.telemetryEnabled = enabled;
33+
if (!writeConfig(config)) {
34+
console.error(
35+
`\n ${c.error("\u2717")} Could not persist telemetry preference to ${c.accent(CONFIG_PATH)}\n`,
36+
);
37+
failCommand();
38+
}
39+
const label = enabled ? c.success("enabled") : c.bold("disabled");
40+
console.log(`\n ${c.success("\u2713")} Telemetry ${label}\n`);
2541
}
2642

2743
function runStatus(): void {
28-
const config = readConfig();
29-
const status = config.telemetryEnabled ? c.success("enabled") : c.dim("disabled");
44+
const config = readConfigFresh();
45+
const effective = effectiveTelemetryStatus(config.telemetryEnabled);
46+
const status = effective.enabled ? c.success("enabled") : c.dim("disabled");
3047
console.log();
3148
console.log(` ${c.dim("Status:")} ${status}`);
49+
console.log(` ${c.dim("Source:")} ${effective.source}`);
3250
console.log(` ${c.dim("Config:")} ${c.accent(CONFIG_PATH)}`);
33-
console.log(` ${c.dim("Commands:")} ${c.bold(String(config.commandCount))}`);
51+
console.log(` ${c.dim("Tracked commands:")} ${c.bold(String(config.commandCount))}`);
3452
console.log();
3553
console.log(` ${c.dim("Disable:")} ${c.accent("hyperframes telemetry disable")}`);
3654
console.log(` ${c.dim("Env var:")} ${c.accent("HYPERFRAMES_NO_TELEMETRY=1")}`);
@@ -78,9 +96,9 @@ ${c.dim("You can also set")} ${c.accent("HYPERFRAMES_NO_TELEMETRY=1")} ${c.dim("
7896

7997
switch (subcommand) {
8098
case "enable":
81-
return runEnable();
99+
return setTelemetryEnabled(true);
82100
case "disable":
83-
return runDisable();
101+
return setTelemetryEnabled(false);
84102
case "status":
85103
return runStatus();
86104
default:

‎packages/cli/src/utils/updateCheck.test.ts‎

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,7 @@ async function checkWith(registryVersion: unknown): Promise<{
130130
const writes: Array<Record<string, unknown>> = [];
131131
vi.doMock("../telemetry/config.js", () => ({
132132
readConfig: () => ({}),
133+
readConfigFresh: () => ({}),
133134
writeConfig: (c: Record<string, unknown>) => writes.push({ ...c }),
134135
}));
135136
const origFetch = globalThis.fetch;
@@ -150,6 +151,49 @@ async function checkWith(registryVersion: unknown): Promise<{
150151
}
151152
}
152153

154+
async function checkAcrossConcurrentConfigWrite(): Promise<Record<string, unknown>> {
155+
vi.resetModules();
156+
const initial = {
157+
telemetryEnabled: true,
158+
anonymousId: "test-install",
159+
telemetryNoticeShown: true,
160+
commandCount: 0,
161+
renderSuccessCount: 0,
162+
lastFeedbackPromptAt: 0,
163+
};
164+
let persisted: Record<string, unknown> = { ...initial };
165+
vi.doMock("../telemetry/config.js", () => ({
166+
readConfig: () => ({ ...initial }),
167+
readConfigFresh: () => ({ ...persisted }),
168+
writeConfig: (config: Record<string, unknown>) => {
169+
persisted = { ...config };
170+
return true;
171+
},
172+
}));
173+
const origFetch = globalThis.fetch;
174+
let releaseResponse: (() => void) | undefined;
175+
const responseReady = new Promise<void>((resolve) => {
176+
releaseResponse = resolve;
177+
});
178+
globalThis.fetch = (async () => {
179+
await responseReady;
180+
return {
181+
ok: true,
182+
json: async () => ({ version: "9.9.9" }),
183+
};
184+
}) as unknown as typeof fetch;
185+
try {
186+
const mod = await import("./updateCheck.js");
187+
const check = mod.checkForUpdate(true);
188+
persisted = { ...persisted, telemetryEnabled: false };
189+
releaseResponse?.();
190+
await check;
191+
return persisted;
192+
} finally {
193+
globalThis.fetch = origFetch;
194+
}
195+
}
196+
153197
/**
154198
* U5: validate/inspect/layout are deprecated in favor of `check`. withMeta's
155199
* optional `{ deprecated: true }` is the single place that adds `_meta.deprecated`
@@ -236,4 +280,12 @@ describe("checkForUpdate — registry boundary guard", () => {
236280
expect(typeof latest).toBe("string");
237281
expect(wroteVersion).toBeUndefined();
238282
});
283+
284+
it("merges update metadata into a fresh snapshot without re-enabling telemetry", async () => {
285+
const persisted = await checkAcrossConcurrentConfigWrite();
286+
expect(persisted).toMatchObject({
287+
telemetryEnabled: false,
288+
latestVersion: "9.9.9",
289+
});
290+
});
239291
});

‎packages/cli/src/utils/updateCheck.ts‎

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { existsSync, readFileSync } from "node:fs";
22
import { join } from "node:path";
33
import { compareVersions } from "compare-versions";
4-
import { readConfig, writeConfig } from "../telemetry/config.js";
4+
import { readConfig, readConfigFresh, writeConfig } from "../telemetry/config.js";
55
import { VERSION } from "../version.js";
66
import { isDevMode } from "./env.js";
77
import { detectInstaller } from "./installerDetection.js";
@@ -88,9 +88,14 @@ export async function checkForUpdate(force?: boolean): Promise<UpdateCheckResult
8888
}
8989
const latest = data.version;
9090

91-
config.lastUpdateCheck = new Date().toISOString();
92-
config.latestVersion = latest;
93-
writeConfig(config);
91+
// The registry request can take seconds. Merge its two metadata fields
92+
// into a fresh snapshot rather than writing the object captured before
93+
// the network call: the stale object previously reverted a concurrent
94+
// `telemetry disable` back to the default `true`.
95+
const freshConfig = readConfigFresh();
96+
freshConfig.lastUpdateCheck = new Date().toISOString();
97+
freshConfig.latestVersion = latest;
98+
writeConfig(freshConfig);
9499

95100
return { current: VERSION, latest, updateAvailable: isNewerSemver(latest, VERSION) };
96101
} catch {

0 commit comments

Comments
 (0)