Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions apps/desktop/src/main/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import {
PLATFORM,
PROTOCOL_SCHEME,
} from "shared/constants";
import { flushAnalytics } from "./lib/analytics";
import { initAppState } from "./lib/app-state";
import { requestAppleEventsAccess } from "./lib/apple-events-permission";
import { isUpdateReadyToInstall, setupAutoUpdater } from "./lib/auto-updater";
Expand All @@ -46,6 +47,7 @@ import {
} from "./lib/persistence/persistence";
import { ensureProjectIconsDir, getProjectIconPath } from "./lib/project-icons";
import { runQuitCleanup } from "./lib/quit-sequence";
import { startResourceDigest, stopResourceDigest } from "./lib/resource-digest";
import { initSentry } from "./lib/sentry";
import {
prewarmTerminalRuntime,
Expand Down Expand Up @@ -244,6 +246,7 @@ app.on("before-quit", async (event) => {
}

isQuitting = true;
stopResourceDigest();
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
await runQuitCleanup({
isDev,
forceFullCleanup,
Expand All @@ -253,6 +256,7 @@ app.on("before-quit", async (event) => {
disposeTerminalHostClient,
shutdownPersistence: shutdownTanstackDbPersistence,
disposeTray,
flushAnalytics,
forceExit: (code) => app.exit(code),
});
});
Expand Down Expand Up @@ -503,6 +507,7 @@ if (!gotTheLock) {

await makeAppSetup(() => MainWindow());
setupAutoUpdater();
startResourceDigest();
initTray();

const coldStartUrl = findDeepLinkInArgv(process.argv);
Expand Down
20 changes: 20 additions & 0 deletions apps/desktop/src/main/lib/analytics/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,26 @@ export function setUserId(id: string | null): void {
userId = id;
}

/**
* Drain captures onto the wire before process exit. `flushAt: 1` starts the
* HTTP send at capture time, but `app.exit()` right after a quit-time capture
* kills the request mid-flight; awaiting this (time-bounded) closes that race.
* The client is unusable afterwards, so only call it from the quit path.
*/
export async function flushAnalytics(timeoutMs = 2_000): Promise<void> {
if (!posthog) return;
try {
await Promise.race([
posthog.shutdown(timeoutMs),
new Promise<void>((resolve) => {
setTimeout(resolve, timeoutMs).unref?.();
}),
]);
} catch {
// Losing a final telemetry event must never block quit.
}
}

export function track(
event: string,
properties?: Record<string, unknown>,
Expand Down
32 changes: 32 additions & 0 deletions apps/desktop/src/main/lib/quit-sequence.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,38 @@ describe("runQuitCleanup", () => {
expect(h.forceExit).toHaveBeenCalledWith(0);
});

test("waits for the analytics drain before force-exiting", async () => {
let resolveDrain: () => void = () => {};
const drain = new Promise<void>((resolve) => {
resolveDrain = resolve;
});
const h = createHarness({ flushAnalytics: () => drain });

let finished = false;
const run = runQuitCleanup(h.deps).then(() => {
finished = true;
});
await Promise.resolve();
expect(finished).toBe(false);
expect(h.forceExit).not.toHaveBeenCalled();

resolveDrain();
await run;
expect(h.forceExit).toHaveBeenCalledWith(0);
});

test("force-exits even if the analytics drain rejects", async () => {
const h = createHarness({
flushAnalytics: async () => {
throw new Error("network down");
},
});

await runQuitCleanup(h.deps);

expect(h.forceExit).toHaveBeenCalledWith(0);
});

test("force-exits even if cleanup throws", async () => {
const h = createHarness({
stopHostServices: () => {
Expand Down
8 changes: 8 additions & 0 deletions apps/desktop/src/main/lib/quit-sequence.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ export interface QuitCleanupDeps {
disposeTerminalHostClient: () => void;
shutdownPersistence: () => void;
disposeTray: () => void;
/** Time-bounded analytics drain so quit-time captures reach the wire. */
flushAnalytics?: () => Promise<void>;
forceExit: (code: number) => void;
scheduleTimer?: (callback: () => void, delayMs: number) => void;
logError?: (message: string, error: unknown) => void;
Expand All @@ -36,12 +38,17 @@ export async function runQuitCleanup(deps: QuitCleanupDeps): Promise<void> {
shutdownPersistence,
disposeTray,
forceExit,
flushAnalytics,
scheduleTimer = (callback, delayMs) => {
setTimeout(callback, delayMs);
},
logError = (message, error) => console.error(message, error),
} = deps;

// Start draining quit-time analytics captures while cleanup runs; awaited
// (already time-bounded by the implementation) before the forced exit.
const analyticsDrain = flushAnalytics?.().catch(() => {});

try {
stopHostServices();
if (isDev || forceFullCleanup) {
Expand All @@ -67,5 +74,6 @@ export async function runQuitCleanup(deps: QuitCleanupDeps): Promise<void> {
return;
}

await analyticsDrain;
forceExit(0);
}
20 changes: 20 additions & 0 deletions apps/desktop/src/main/lib/resource-digest/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
export {
ALERT_COOLDOWN_MS,
ALERT_KINDS,
type AlertKind,
DIGEST_SCALAR_KEYS,
IDLE_SKIP_THRESHOLD_SECONDS,
isResourceDigestEnabled,
MIN_SAMPLES_TO_FLUSH_ON_QUIT,
RESOURCE_ALERT_EVENT,
RESOURCE_DIGEST_EVENT,
type ResourceDigestDeps,
type ResourceSample,
recordWindowUnresponsive,
SAMPLE_INTERVAL_MS,
SAMPLE_JITTER_MS,
SAMPLE_KEYS,
type SampleKey,
startResourceDigest,
stopResourceDigest,
} from "./resource-digest";
Loading
Loading