Skip to content

Commit 693c385

Browse files
fix(cli): commands exit right away even when the network or DNS is broken (#4604)
* fix(cli): commands exit without waiting on update checks or telemetry The update and skills checks run in a detached child that refreshes the caches for the next run; the parent only reads the caches. finalizeCli no longer awaits the telemetry flush: the exit handler flushSync() delivers what is queued. The events beacon, feedback and figma error paths stop awaiting flush() too. * fix(cli): retry a failed background check at most once an hour Before starting the background worker, the CLI stamps a per-check attempt time and skips a check it attempted within the hour, so a dead network no longer starts a worker on every command. The stale-pin notice writes onto a fresh read, detached spawns set windowsHide, and a test ties the worker path to its build entry. * fix(cli): a failed-check stamp dated in the future no longer silences update checks
1 parent 09ab947 commit 693c385

27 files changed

Lines changed: 678 additions & 144 deletions

‎.fallowrc.jsonc‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,8 @@
4646
"packages/producer/src/services/healthWorkerThread.ts",
4747
// Render-setup worker, spawned by path from cancellableProcess.ts.
4848
"packages/cli/src/renderSetupWorker.ts",
49+
// Update/skills cache refresh, spawned detached by path from backgroundChecks.ts.
50+
"packages/cli/src/backgroundChecksWorker.ts",
4951
// Parakeet decode worker, spawned by path from whisper/sherpa.ts.
5052
"packages/cli/src/whisper/sherpaWorker.ts",
5153
// Test fixture worker, spawned by path via the pools' workerEntryPath

‎docs/packages/cli.mdx‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -59,8 +59,9 @@ from any command's output, without a second call:
5959
}
6060
```
6161

62-
The version numbers come from a cache refreshed at most once a day. `--json`
63-
never makes a network request of its own. Deprecated commands add
62+
The version numbers come from a cache refreshed at most once a day, in a
63+
background process, and never under CI or `HYPERFRAMES_NO_UPDATE_CHECK=1`.
64+
`--json` never makes a network request of its own. Deprecated commands add
6465
`_meta.deprecated: true`.
6566

6667
**Flags, not prompts.** A missing required flag fails immediately with a usage
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
import { expect, it, vi } from "vitest";
2+
3+
const checks = vi.hoisted(() => ({
4+
checkForUpdate: vi.fn(async () => ({})),
5+
refreshSkillsCache: vi.fn(async () => {
6+
throw new Error("offline");
7+
}),
8+
}));
9+
vi.mock("./utils/updateCheck.js", () => ({ checkForUpdate: checks.checkForUpdate }));
10+
vi.mock("./utils/skillsUpdateCheck.js", () => ({ refreshSkillsCache: checks.refreshSkillsCache }));
11+
12+
it("runs each check it was handed, and one failing does not stop the other", async () => {
13+
process.argv = [process.execPath, "backgroundChecksWorker.js", "skills", "update"];
14+
15+
await import("./backgroundChecksWorker.js");
16+
17+
expect(checks.refreshSkillsCache).toHaveBeenCalledTimes(1);
18+
expect(checks.checkForUpdate).toHaveBeenCalledTimes(1);
19+
});
20+
21+
it("skips a check the parent did not find due", async () => {
22+
vi.resetModules();
23+
checks.checkForUpdate.mockClear();
24+
process.argv = [process.execPath, "backgroundChecksWorker.js", "skills"];
25+
26+
await import("./backgroundChecksWorker.js");
27+
28+
expect(checks.checkForUpdate).not.toHaveBeenCalled();
29+
});
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
import { checkForUpdate } from "./utils/updateCheck.js";
2+
import { refreshSkillsCache } from "./utils/skillsUpdateCheck.js";
3+
4+
// Detached child of launchBackgroundChecks: refreshes the caches the next run's notices read.
5+
const due = process.argv.slice(2);
6+
await Promise.allSettled([
7+
due.includes("update") && checkForUpdate(),
8+
due.includes("skills") && refreshSkillsCache(),
9+
]);

‎packages/cli/src/cli.lifecycle.test.ts‎

Lines changed: 43 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -10,15 +10,12 @@ const originalExitCode = process.exitCode;
1010
afterEach(() => {
1111
process.argv = [...originalArgv];
1212
process.exitCode = originalExitCode;
13-
vi.doUnmock("./commands/init.js");
14-
vi.doUnmock("./telemetry/events.js");
15-
vi.doUnmock("./telemetry/index.js");
16-
vi.doUnmock("./telemetry/client.js");
13+
for (const path of MOCKED_MODULES) vi.doUnmock(path);
1714
vi.resetModules();
1815
});
1916

2017
describe("CLI lifecycle", () => {
21-
it("queues a command failure before finalizing telemetry", async () => {
18+
it("queues a command failure before exit, without waiting on a network flush", async () => {
2219
let resolveEvents!: (events: {
2320
trackCommandFailure: (command: string, error: unknown) => void;
2421
}) => void;
@@ -41,10 +38,9 @@ describe("CLI lifecycle", () => {
4138
},
4239
}));
4340
vi.doMock("./telemetry/index.js", () => ({
44-
flush: async () => {
45-
order.push("flush");
46-
},
47-
flushSync: vi.fn(),
41+
// Never settles: a finalize that awaited it would hang this test.
42+
flush: () => new Promise<void>(() => {}),
43+
flushSync: () => order.push("flushSync"),
4844
incrementCommandCount: vi.fn(),
4945
showTelemetryNotice: vi.fn(),
5046
shouldTrack: () => false,
@@ -69,8 +65,9 @@ describe("CLI lifecycle", () => {
6965
},
7066
});
7167
await execution;
68+
process.emit("exit", 0);
7269

73-
expect(order).toEqual(["cli_error", "flush"]);
70+
expect(order).toEqual(["cli_error", "flushSync"]);
7471
});
7572

7673
describe("reports each failure once, by its real error", () => {
@@ -297,8 +294,44 @@ describe("CLI lifecycle", () => {
297294
exitSpy.mockRestore();
298295
}
299296
});
297+
298+
it("starts the background checks in a child and reads only the caches itself", async () => {
299+
const launchBackgroundChecks = vi.fn();
300+
const checkForUpdate = vi.fn();
301+
mockInitCommand(vi.fn());
302+
mockTelemetry();
303+
vi.doMock("./utils/autoUpdate.js", () => ({
304+
reportCompletedUpdate: vi.fn(),
305+
scheduleBackgroundInstall: vi.fn(),
306+
}));
307+
vi.doMock("./utils/updateCheck.js", () => ({
308+
cachedUpdateCheck: () => ({ current: "1.0.0", latest: "1.0.0", updateAvailable: false }),
309+
checkForUpdate,
310+
printUpdateNotice: vi.fn(),
311+
printStalePinNotice: vi.fn(),
312+
}));
313+
vi.doMock("./utils/skillsUpdateCheck.js", () => ({ printSkillsUpdateNotice: vi.fn() }));
314+
vi.doMock("./utils/backgroundChecks.js", () => ({ launchBackgroundChecks }));
315+
316+
process.argv = ["node", "cli.ts", "init"];
317+
await import("./cli.js");
318+
319+
await vi.waitFor(() => expect(launchBackgroundChecks).toHaveBeenCalledTimes(1));
320+
expect(checkForUpdate).not.toHaveBeenCalled();
321+
});
300322
});
301323

324+
const MOCKED_MODULES = [
325+
"./commands/init.js",
326+
"./telemetry/events.js",
327+
"./telemetry/index.js",
328+
"./telemetry/client.js",
329+
"./utils/autoUpdate.js",
330+
"./utils/updateCheck.js",
331+
"./utils/skillsUpdateCheck.js",
332+
"./utils/backgroundChecks.js",
333+
];
334+
302335
/** Runs the CLI with the real failure reporting and returns the cli_error events it sent. */
303336
async function runCli(args: string[]): Promise<Record<string, unknown>[]> {
304337
const sent: Record<string, unknown>[] = [];

‎packages/cli/src/cli.ts‎

Lines changed: 10 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -215,7 +215,6 @@ const hasJsonFlag = process.argv.includes("--json");
215215
// Captured references — populated when the lazy imports resolve.
216216
// Used in exit handlers where dynamic import() is unsafe (beforeExit loops,
217217
// exit handler is synchronous-only).
218-
let _flush: (() => Promise<void>) | undefined;
219218
let _flushSync: (() => void) | undefined;
220219
let _trackCliError:
221220
| ((props: {
@@ -245,7 +244,6 @@ let telemetryReady: Promise<void> = Promise.resolve();
245244
// printed into a skill's captured output).
246245
if (!isHelp && command !== "telemetry" && command !== "events" && command !== "unknown") {
247246
telemetryReady = import("./telemetry/index.js").then((mod) => {
248-
_flush = mod.flush;
249247
_flushSync = mod.flushSync;
250248
_trackCliError = mod.trackCliError;
251249
_trackCommandResult = mod.trackCommandResult;
@@ -281,19 +279,20 @@ if (
281279
import("./utils/updateCheck.js").then(async (mod) => {
282280
_printUpdateNotice = mod.printUpdateNotice;
283281
_printStalePinNotice = mod.printStalePinNotice;
284-
const result = await mod.checkForUpdate().catch(() => null);
285-
if (result?.updateAvailable) {
282+
const result = mod.cachedUpdateCheck();
283+
if (result.updateAvailable) {
286284
const auto = await import("./utils/autoUpdate.js").catch(() => null);
287285
auto?.scheduleBackgroundInstall(result.latest, result.current);
288286
}
289287
});
290288

291-
// Skills freshness nudge — same gating as the CLI self-update notice. The
292-
// check is cached (24h) and best-effort: it never blocks or fails the command.
293-
import("./utils/skillsUpdateCheck.js").then(async (mod) => {
289+
// Skills freshness nudge — same gating as the CLI self-update notice.
290+
import("./utils/skillsUpdateCheck.js").then((mod) => {
294291
_printSkillsUpdateNotice = mod.printSkillsUpdateNotice;
295-
await mod.checkSkillsForUpdate().catch(() => null);
296292
});
293+
294+
// The notices read the caches; a detached child refreshes them for the next run.
295+
import("./utils/backgroundChecks.js").then((mod) => mod.launchBackgroundChecks()).catch(() => {});
297296
}
298297

299298
const commandStart = Date.now();
@@ -323,7 +322,7 @@ async function finalizeCli(result: CommandResult): Promise<void> {
323322
durationMs: Date.now() - commandStart,
324323
runId,
325324
});
326-
await _flush?.().catch(() => {});
325+
// No network wait: the exit handler's flushSync() delivers what is still queued.
327326
if (!hasJsonFlag) {
328327
_printUpdateNotice?.();
329328
_printStalePinNotice?.();
@@ -362,12 +361,8 @@ process.on(
362361
runId,
363362
});
364363
}
365-
// Unconditional — `finalized` only means finalizeCli STARTED its awaited
366-
// flush(). A process.exit() racing that flush (the EPIPE path under agent
367-
// pipes) kills the in-flight request, and gating this fallback behind
368-
// `finalized` silently dropped the still-queued events — the 0.7.65
369-
// render_complete regression. flushSync() is safe to over-call: an empty
370-
// queue is a no-op, and event uuids make re-sends idempotent.
364+
// Unconditional: this is the exit-time delivery for every command (gating it on `finalized`
365+
// was the 0.7.65 render_complete loss). Empty queue is a no-op; uuids make re-sends idempotent.
371366
_flushSync?.();
372367
},
373368
);
Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { describe, expect, it, vi } from "vitest";
22

3+
const order: string[] = [];
34
const telemetry = vi.hoisted(() => ({
45
trackEvent: vi.fn(),
56
flush: vi.fn(async () => {}),
@@ -8,10 +9,12 @@ const telemetry = vi.hoisted(() => ({
89
vi.mock("../telemetry/client.js", () => telemetry);
910

1011
describe("events", () => {
11-
it("hands anything flush() left queued to the detached sender", async () => {
12+
it("queues the event, then hands it to the detached sender without waiting on the network", async () => {
13+
telemetry.trackEvent.mockImplementation(() => order.push("track"));
14+
telemetry.flushSync.mockImplementation(() => order.push("flushSync"));
1215
const { default: events } = await import("./events.js");
1316
await events.run?.({ args: { skill: "hyperframes", event: "skill_invoked" } } as never);
14-
expect(telemetry.trackEvent).toHaveBeenCalled();
15-
expect(telemetry.flushSync).toHaveBeenCalled();
17+
expect(order).toEqual(["track", "flushSync"]);
18+
expect(telemetry.flush).not.toHaveBeenCalled();
1619
});
1720
});

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

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { defineCommand } from "citty";
2-
import { trackEvent, flush, flushSync } from "../telemetry/client.js";
2+
import { trackEvent, flushSync } from "../telemetry/client.js";
33
import { SKILL_SLUG } from "../telemetry/skill.js";
44

55
// Skill-usage telemetry endpoint. A skill reports its own invocation/outcome —
@@ -14,7 +14,7 @@ import { SKILL_SLUG } from "../telemetry/skill.js";
1414
//
1515
// Telemetry must NEVER break the calling skill: every arg is optional (a missing
1616
// or malformed value is a silent no-op, not a non-zero exit), the body is
17-
// guarded, and flush() carries its own hard timeout. This command always exits 0.
17+
// guarded, and the send runs in a detached child. This command always exits 0.
1818

1919
const ALLOWED_EVENTS = ["skill_invoked", "skill_completed"];
2020
const ALLOWED_OUTCOMES = ["success", "error", "abort"];
@@ -53,7 +53,6 @@ export default defineCommand({
5353
props["outcome"] = args.outcome;
5454
}
5555
trackEvent(event, props);
56-
await flush();
5756
flushSync();
5857
} catch {
5958
// swallow — telemetry must never surface a non-zero exit to the caller
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
import { expect, it, vi } from "vitest";
2+
3+
const mocks = vi.hoisted(() => ({
4+
// Never settles: waiting on it would hang the command.
5+
flush: vi.fn(() => new Promise<void>(() => {})),
6+
submitFeedback: vi.fn(async () => {}),
7+
submitCatalogSearchMiss: vi.fn(async () => {}),
8+
}));
9+
vi.mock("../telemetry/client.js", () => ({ shouldTrack: () => true, flush: mocks.flush }));
10+
vi.mock("../telemetry/events.js", () => ({
11+
trackCatalogSearchMiss: vi.fn(),
12+
trackRenderFeedback: vi.fn(),
13+
}));
14+
vi.mock("../telemetry/feedback.js", () => ({ getDoctorSummary: async () => "" }));
15+
vi.mock("../telemetry/config.js", () => ({ readConfig: () => ({ anonymousId: "a" }) }));
16+
vi.mock("../utils/submitFeedback.js", () => ({
17+
submitFeedback: mocks.submitFeedback,
18+
submitCatalogSearchMiss: mocks.submitCatalogSearchMiss,
19+
}));
20+
21+
it.each([
22+
["a rating", { rating: "8" }, mocks.submitFeedback],
23+
["a catalog search miss", { "search-miss": "typewriter" }, mocks.submitCatalogSearchMiss],
24+
])("sends %s without waiting on the telemetry upload", async (_, args, submit) => {
25+
vi.spyOn(console, "log").mockImplementation(() => {});
26+
const { default: feedback } = await import("./feedback.js");
27+
await feedback.run?.({ args } as never);
28+
expect(submit).toHaveBeenCalled();
29+
});

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

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import * as clack from "@clack/prompts";
66
import open from "open";
77
import type { Example } from "./_examples.js";
88
import { trackCatalogSearchMiss, trackRenderFeedback } from "../telemetry/events.js";
9-
import { shouldTrack, flush } from "../telemetry/client.js";
9+
import { shouldTrack } from "../telemetry/client.js";
1010
import { getDoctorSummary } from "../telemetry/feedback.js";
1111
import { readConfig, type RecentRenderRecord } from "../telemetry/config.js";
1212
import { publishProjectArchive } from "../utils/publishProject.js";
@@ -208,7 +208,6 @@ export default defineCommand({
208208
const wanted = normalizeComment(args.wanted);
209209
const tier = normalizeComment(args.tier);
210210
trackCatalogSearchMiss({ query: searchMiss, wanted, tier });
211-
await flush();
212211
// Ack before the forward, which is best-effort and bounded, so the
213212
// reporter is never left waiting on it.
214213
console.log(c.dim("Logged the gap. Thanks — that is how the catalog grows."));
@@ -259,7 +258,6 @@ export default defineCommand({
259258
recentRenderIds: config.recentRenders?.map((r) => r.id),
260259
});
261260

262-
await flush();
263261
// Ack first so the user isn't kept waiting on the best-effort forward (which
264262
// is bounded to a few seconds and never surfaces an error either way).
265263
console.log(c.dim("Thanks for the feedback!"));

0 commit comments

Comments
 (0)