Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(desktop): stop the auth retry loop with a refusal and backoff (#88137)

Brandone8ab3b2b1942
diff --git a/products/desktop/packages/core/src/auth/auth.test.ts b/products/desktop/packages/core/src/auth/auth.test.ts
index 0100376bba57..3f0894860318 100644
--- a/products/desktop/packages/core/src/auth/auth.test.ts
+++ b/products/desktop/packages/core/src/auth/auth.test.ts
@@ -1,6 +1,6 @@
import type { RootLogger } from "@posthog/di/logger";
import type { IPowerManager } from "@posthog/platform/power-manager";
-import { OAUTH_SCOPE_VERSION } from "@posthog/shared";
+import { NotAuthenticatedError, OAUTH_SCOPE_VERSION } from "@posthog/shared";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { AuthService } from "./auth";
import type {
@@ -1189,6 +1189,129 @@ describe("AuthService", () => {
expect(sessionPort.getCurrent()).toBeNull();
});
+ it("never re-presents a refresh token the server rejected", async () => {
+ seedStoredSession();
+ oauthFlow.refreshToken.mockResolvedValue({
+ success: false,
+ error: "Token revoked",
+ errorCode: "auth_error",
+ });
+
+ await service.initialize();
+ expect(oauthFlow.refreshToken).toHaveBeenCalledTimes(1);
+
+ // Storage still holds the dead token, so this must fail without a request.
+ seedStoredSession();
+ await expect(service.getValidAccessToken()).rejects.toThrow(
+ NotAuthenticatedError,
+ );
+ expect(oauthFlow.refreshToken).toHaveBeenCalledTimes(1);
+ });
+
+ it("pauses rather than retires a token after an unclassified failure", async () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date("2026-08-24T00:00:00.000Z"));
+ try {
+ seedStoredSession();
+ oauthFlow.refreshToken.mockResolvedValue({
+ success: false,
+ error: "Something weird",
+ errorCode: "unknown_error",
+ });
+
+ await service.initialize();
+ expect(oauthFlow.refreshToken).toHaveBeenCalledTimes(1);
+
+ await expect(service.getValidAccessToken()).rejects.toThrow(/paused/i);
+ expect(oauthFlow.refreshToken).toHaveBeenCalledTimes(1);
+
+ // Held just under the cooldown, so the constant itself is pinned.
+ vi.setSystemTime(new Date("2026-08-24T00:00:14.900Z"));
+ await expect(service.getValidAccessToken()).rejects.toThrow(/paused/i);
+ expect(oauthFlow.refreshToken).toHaveBeenCalledTimes(1);
+
+ // And the pause lifts on its own, unlike a server rejection.
+ vi.setSystemTime(new Date("2026-08-24T00:00:15.100Z"));
+ await expect(service.getValidAccessToken()).rejects.toThrow();
+ expect(oauthFlow.refreshToken).toHaveBeenCalledTimes(2);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("releases the refusal when a new grant bumps the session generation", async () => {
+ seedStoredSession();
+ oauthFlow.refreshToken.mockResolvedValue({
+ success: false,
+ error: "Token revoked",
+ errorCode: "auth_error",
+ });
+ await service.initialize();
+ expect(oauthFlow.refreshToken).toHaveBeenCalledTimes(1);
+
+ oauthFlow.startFlow.mockResolvedValue(
+ mockTokenResponse({
+ accessToken: "fresh-access-token",
+ refreshToken: "stored-refresh-token",
+ }),
+ );
+ stubAuthFetch();
+ await service.login("us");
+
+ // Same token as the refused one, so only the generation bump can release
+ // it. Otherwise signing back in leaves the user locked out.
+ seedStoredSession();
+ oauthFlow.refreshToken.mockResolvedValue(
+ mockTokenResponse({
+ accessToken: "rotated-access-token",
+ refreshToken: "rotated-refresh-token",
+ }),
+ );
+ await service.refreshAccessToken();
+ expect(oauthFlow.refreshToken).toHaveBeenCalledTimes(2);
+ });
+
+ it("pauses only the token that failed", async () => {
+ seedStoredSession();
+ oauthFlow.refreshToken.mockResolvedValue({
+ success: false,
+ error: "Something weird",
+ errorCode: "unknown_error",
+ });
+ await service.initialize();
+ expect(oauthFlow.refreshToken).toHaveBeenCalledTimes(1);
+
+ // A different token is a different credential; the pause must not widen.
+ seedStoredSession({ refreshToken: "another-refresh-token" });
+ await expect(service.getValidAccessToken()).rejects.toThrow();
+ expect(oauthFlow.refreshToken).toHaveBeenCalledTimes(2);
+ });
+
+ it("pauses the token when retries are exhausted", async () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date("2026-08-24T00:00:00.000Z"));
+ try {
+ seedStoredSession();
+ oauthFlow.refreshToken.mockResolvedValue({
+ success: false,
+ error: "Boom",
+ errorCode: "server_error",
+ });
+
+ const restoring = service.initialize();
+ await vi.advanceTimersByTimeAsync(10_000);
+ await restoring;
+ const spent = oauthFlow.refreshToken.mock.calls.length;
+ expect(spent).toBeGreaterThan(1);
+
+ // This exhausts the retry budget rather than failing on the first attempt.
+ await expect(service.getValidAccessToken()).rejects.toThrow();
+ expect(oauthFlow.refreshToken).toHaveBeenCalledTimes(spent);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
it("keeps restoring after a non-retryable unknown_error", async () => {
seedStoredSession();
oauthFlow.refreshToken.mockResolvedValue({
@@ -1250,6 +1373,39 @@ describe("AuthService", () => {
}
});
+ it("raises a not-authenticated error on the rejection itself", async () => {
+ vi.useFakeTimers();
+ try {
+ oauthFlow.startFlow.mockResolvedValue(
+ mockTokenResponse({
+ accessToken: "current-access-token",
+ refreshToken: "current-refresh-token",
+ }),
+ );
+ stubAuthFetch();
+
+ await service.initialize();
+ await service.login("us");
+
+ oauthFlow.refreshToken.mockReset();
+ oauthFlow.refreshToken.mockResolvedValue({
+ success: false,
+ error: "Token revoked",
+ errorCode: "auth_error",
+ });
+
+ await vi.advanceTimersByTimeAsync(3_599_500);
+
+ // Raised by the rejection that tears the session down, so callers
+ // that stop on a dead session see it here, not one trigger later.
+ await expect(service.getValidAccessToken()).rejects.toBeInstanceOf(
+ NotAuthenticatedError,
+ );
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
it("does not use the current access token when refresh token auth fails", async () => {
vi.useFakeTimers();
try {
diff --git a/products/desktop/packages/core/src/auth/auth.ts b/products/desktop/packages/core/src/auth/auth.ts
index 27c80acbb560..90e02e5a9d33 100644
--- a/products/desktop/packages/core/src/auth/auth.ts
+++ b/products/desktop/packages/core/src/auth/auth.ts
@@ -42,6 +42,11 @@ import {
type ValidAccessTokenOutput,
} from "./schemas";
+// A refresh failure that is not a rejection is no evidence the token is dead, so
+// pause rather than retire. Sized inside TOKEN_EXPIRY_SKEW_MS so a fast failure
+// still retries on a live token. Retry exhaustion can already outrun the skew on
+// its own, so the sizing buys nothing there.
+const FAILED_REFRESH_COOLDOWN_MS = 15_000;
const TOKEN_EXPIRY_SKEW_MS = 60_000;
const AUTH_FETCH_TIMEOUT_MS = 30_000;
const AUTH_BOOTSTRAP_DEADLINE_MS = 20_000;
@@ -96,6 +101,13 @@ export class AuthService extends TypedEventEmitter<AuthServiceEvents> {
private refreshPromise: Promise<InMemorySession> | null = null;
private impersonationExpiryTimer: ReturnType<typeof setTimeout> | null = null;
private sessionGeneration = 0;
+ // A refresh already refused, keyed to the session generation so every teardown
+ // invalidates it. `until: null` is a proven-dead token, a timestamp is a pause.
+ private refusedRefresh: {
+ token: string;
+ generation: number;
+ until: number | null;
+ } | null = null;
// Serializes session-state commits so overlapping selections can't
// interleave across async encryption (see commitSessionState).
private commitChain: Promise<void> = Promise.resolve();
@@ -499,6 +511,7 @@ export class AuthService extends TypedEventEmitter<AuthServiceEvents> {
this.authSession.clearCurrent();
this.clearImpersonationExpiryTimer();
this.session = null;
+ this.refusedRefresh = null;
this.setAnonymousState({ cloudRegion, currentProjectId });
return this.getState();
}
@@ -700,6 +713,15 @@ export class AuthService extends TypedEventEmitter<AuthServiceEvents> {
return storedSession;
}
+ private pauseRefresh(token: string, errorCode: string | undefined): void {
+ this.refusedRefresh = {
+ token,
+ generation: this.sessionGeneration,
+ until: Date.now() + FAILED_REFRESH_COOLDOWN_MS,
+ };
+ this.logger.warn("Refresh failed, pausing this token", { errorCode });
+ }
+
private async refreshSession(
input: StoredSessionInput,
): Promise<InMemorySession> {
@@ -707,6 +729,22 @@ export class AuthService extends TypedEventEmitter<AuthServiceEvents> {
throw new Error("Offline");
}
+ const refused = this.refusedRefresh;
+ if (
+ refused &&
+ refused.token === input.refreshToken &&
+ refused.generation === this.sessionGeneration
+ ) {
+ if (refused.until === null) {
+ throw new NotAuthenticatedError(
+ "Your session has expired. Sign in again to continue.",
+ );
+ }
+ if (Date.now() < refused.until) {
+ throw new Error("Token refresh paused after an unclassified failure");
+ }
+ }
+
let lastError = "Token refresh failed";
for (
@@ -737,7 +775,15 @@ export class AuthService extends TypedEventEmitter<AuthServiceEvents> {
cloudRegion: input.cloudRegion,
currentProjectId: input.selectedProjectId,
});
- throw new Error(lastError);
+ // Last, so a throwing teardown leaves no refusal over a live-looking session.
+ this.refusedRefresh = {
+ token: input.refreshToken,
+ generation: this.sessionGeneration,
+ until: null,
+ };
+ // The session is already anonymous, so callers that stop on a dead
+ // session must see that class here rather than a trigger later.
+ throw new NotAuthenticatedError(lastError);
}
const isRetryable =
@@ -745,6 +791,9 @@ export class AuthService extends TypedEventEmitter<AuthServiceEvents> {
result.errorCode === "server_error";
if (!isRetryable) {
+ // This arm keeps the session and the stored token, so only the pause
+ // stops the caller re-presenting it on the next trigger.
+ this.pauseRefresh(input.refreshToken, result.errorCode);
throw new Error(lastError);
}
@@ -758,6 +807,10 @@ export class AuthService extends TypedEventEmitter<AuthServiceEvents> {
await sleepWithBackoff(attempt, AuthService.REFRESH_BACKOFF);
}
+ // A 5xx endpoint or a captive portal exhausts the budget here, not in the arm
+ // above; unpaused, each later trigger spends the whole budget again.
+ this.pauseRefresh(input.refreshToken, "retries_exhausted");
+
throw new Error(lastError);
}
private async createSessionFromTokenResponse(
@@ -1372,6 +1425,7 @@ export class AuthService extends TypedEventEmitter<AuthServiceEvents> {
this.sessionGeneration += 1;
this.clearImpersonationExpiryTimer();
this.session = null;
+ this.refusedRefresh = null;
this.setAnonymousState({
cloudRegion: session.cloudRegion,
currentProjectId: session.currentProjectId,
diff --git a/products/desktop/packages/core/src/usage/usage-monitor.test.ts b/products/desktop/packages/core/src/usage/usage-monitor.test.ts
index 3f91589e94d5..da8a0cd56ac8 100644
--- a/products/desktop/packages/core/src/usage/usage-monitor.test.ts
+++ b/products/desktop/packages/core/src/usage/usage-monitor.test.ts
@@ -1,3 +1,4 @@
+import { NotAuthenticatedError } from "@posthog/shared";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { AuthService } from "../auth/auth";
import type { UsageHost } from "./identifiers";
@@ -44,28 +45,45 @@ function makeThresholdStore(): ThresholdSlice {
};
}
+interface ScopedLog {
+ debug: ReturnType<typeof vi.fn>;
+ info: ReturnType<typeof vi.fn>;
+ warn: ReturnType<typeof vi.fn>;
+ error: ReturnType<typeof vi.fn>;
+}
+
+let lastScopedLog: ScopedLog;
+
function makeLogger() {
const log = { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() };
+ lastScopedLog = log;
return { ...log, scope: () => log };
}
type GatewaySlice = Pick<UsageHost, "fetchUsage">;
-let emitAuthState: (currentOrgId: string | null) => void = () => {};
+type AuthStatus = "anonymous" | "authenticated" | "restoring";
+interface EmittedAuthState {
+ currentOrgId: string | null;
+ status: AuthStatus;
+}
+
+let emitAuthState: (currentOrgId: string | null, status?: AuthStatus) => void =
+ () => {};
function makeAuthService(): AuthService {
- const listeners = new Set<(state: { currentOrgId: string | null }) => void>();
- emitAuthState = (currentOrgId) => {
+ const listeners = new Set<(state: EmittedAuthState) => void>();
+ let currentStatus: AuthStatus = "authenticated";
+ emitAuthState = (currentOrgId, status = "authenticated") => {
+ currentStatus = status;
for (const listener of [...listeners]) {
- listener({ currentOrgId });
+ listener({ currentOrgId, status });
}
};
return {
- getState: () => ({ currentOrgId: "org-1" }),
- on: (
- _event: string,
- listener: (state: { currentOrgId: string | null }) => void,
- ) => listeners.add(listener),
+ getState: () => ({ currentOrgId: "org-1", status: currentStatus }),
+ on: (_event: string, listener: (state: EmittedAuthState) => void) =>
+ listeners.add(listener),
} as unknown as AuthService;
}
@@ -130,6 +148,7 @@ describe("UsageMonitorService", () => {
afterEach(() => {
service?.stop();
vi.useRealTimers();
+ vi.restoreAllMocks();
});
it("emits at 75% but not again on the next poll for the same anchor", async () => {
@@ -229,6 +248,187 @@ describe("UsageMonitorService", () => {
expect(events[0]?.userIsActive).toBe(true);
});
+ it("backs off after a failure instead of refetching on the next trigger", async () => {
+ const fetchUsage = vi.fn().mockRejectedValue(new Error("HTTP 401"));
+ const gateway = { fetchUsage } as unknown as GatewaySlice;
+ service = makeService(gateway, makeActivityMonitor());
+
+ await service.fetchOnce();
+ await service.fetchOnce();
+ expect(fetchUsage).toHaveBeenCalledTimes(1);
+
+ // The first window is the 5s base, jittered down to at most 5s.
+ vi.advanceTimersByTime(5_001);
+ await service.fetchOnce();
+ expect(fetchUsage).toHaveBeenCalledTimes(2);
+ });
+
+ it("keeps backing off when a mid-failure refresh emits a state change", async () => {
+ const fetchUsage = vi.fn().mockRejectedValue(new Error("HTTP 401"));
+ const gateway = { fetchUsage } as unknown as GatewaySlice;
+ service = makeService(gateway, makeActivityMonitor());
+
+ await service.fetchOnce();
+ // The 401 retry refreshes the token from inside the failing fetch.
+ // Releasing the window on that emission pins it at its floor.
+ emitAuthState("org-1", "authenticated");
+ await service.fetchOnce();
+ expect(fetchUsage).toHaveBeenCalledTimes(1);
+ });
+
+ it("grows the backoff window and caps it at the backstop interval", async () => {
+ vi.spyOn(Math, "random").mockReturnValue(0);
+ const fetchUsage = vi.fn().mockRejectedValue(new Error("HTTP 500"));
+ const gateway = { fetchUsage } as unknown as GatewaySlice;
+ service = makeService(gateway, makeActivityMonitor());
+
+ // Jitter pinned at its low end, so windows are 2.5s, 5s, 10s, ... 15m.
+ await service.fetchOnce();
+ vi.advanceTimersByTime(2_500);
+ await service.fetchOnce();
+ expect(fetchUsage).toHaveBeenCalledTimes(2);
+
+ // A flat, non-doubling backoff would release here.
+ vi.advanceTimersByTime(2_500);
+ await service.fetchOnce();
+ expect(fetchUsage).toHaveBeenCalledTimes(2);
+ vi.advanceTimersByTime(2_500);
+ await service.fetchOnce();
+ expect(fetchUsage).toHaveBeenCalledTimes(3);
+
+ for (let i = 0; i < 12; i++) {
+ vi.advanceTimersByTime(15 * 60_000);
+ await service.fetchOnce();
+ }
+ const capped = fetchUsage.mock.calls.length;
+ vi.advanceTimersByTime(15 * 60_000 - 1);
+ await service.fetchOnce();
+ expect(fetchUsage).toHaveBeenCalledTimes(capped);
+ vi.advanceTimersByTime(1);
+ await service.fetchOnce();
+ expect(fetchUsage).toHaveBeenCalledTimes(capped + 1);
+ });
+
+ it("stops polling entirely after a terminal auth failure", async () => {
+ const fetchUsage = vi.fn().mockRejectedValue(new NotAuthenticatedError());
+ const gateway = { fetchUsage } as unknown as GatewaySlice;
+ service = makeService(gateway, makeActivityMonitor());
+ emitAuthState("org-1", "anonymous");
+
+ await service.fetchOnce();
+ // No window expiry releases this one, and a signed-out session must not.
+ vi.advanceTimersByTime(6 * 60 * 60_000);
+ await service.fetchOnce();
+ expect(fetchUsage).toHaveBeenCalledTimes(1);
+
+ emitAuthState("org-1", "authenticated");
+ await service.fetchOnce();
+ expect(fetchUsage).toHaveBeenCalledTimes(2);
+ });
+
+ it("recovers polling when the user signs back into the same organization", async () => {
+ const fetchUsage = vi.fn().mockRejectedValue(new NotAuthenticatedError());
+ const gateway = { fetchUsage } as unknown as GatewaySlice;
+ service = makeService(gateway, makeActivityMonitor());
+ emitAuthState("org-1", "anonymous");
+
+ await service.fetchOnce();
+ expect(fetchUsage).toHaveBeenCalledTimes(1);
+
+ // A teardown publishes the anonymous org before any new sign-in, so
+ // returning to the same org is still a transition the listener acts on.
+ emitAuthState(null, "anonymous");
+ fetchUsage.mockResolvedValue(makeUsage());
+ emitAuthState("org-1", "authenticated");
+ await vi.advanceTimersByTimeAsync(10_000);
+
+ expect(fetchUsage).toHaveBeenCalledTimes(2);
+ });
+
+ it("resets the window after a success", async () => {
+ vi.spyOn(Math, "random").mockReturnValue(0);
+ const fetchUsage = vi
+ .fn()
+ .mockRejectedValueOnce(new Error("HTTP 500"))
+ .mockRejectedValueOnce(new Error("HTTP 500"))
+ .mockResolvedValueOnce(makeUsage({ burstPercent: 10 }))
+ .mockRejectedValue(new Error("HTTP 500"));
+ const gateway = { fetchUsage } as unknown as GatewaySlice;
+ service = makeService(gateway, makeActivityMonitor());
+
+ await service.fetchOnce();
+ vi.advanceTimersByTime(2_500);
+ await service.fetchOnce();
+ vi.advanceTimersByTime(5_000);
+ await service.fetchOnce();
+ expect(fetchUsage).toHaveBeenCalledTimes(3);
+
+ // The next failure starts from the base, not the escalated window.
+ await service.fetchOnce();
+ vi.advanceTimersByTime(2_500);
+ await service.fetchOnce();
+ expect(fetchUsage).toHaveBeenCalledTimes(5);
+ });
+
+ it("lets an org switch refetch through an open backoff window", async () => {
+ vi.spyOn(Math, "random").mockReturnValue(0);
+ const fetchUsage = vi.fn().mockRejectedValue(new Error("HTTP 500"));
+ const gateway = { fetchUsage } as unknown as GatewaySlice;
+ service = makeService(gateway, makeActivityMonitor());
+
+ // Three failures put the window at 10s, wider than the coalesce delay the
+ // switch's refetch waits out, so the window is still open when it fires.
+ await service.fetchOnce();
+ vi.advanceTimersByTime(2_500);
+ await service.fetchOnce();
+ vi.advanceTimersByTime(5_000);
+ await service.fetchOnce();
+ expect(fetchUsage).toHaveBeenCalledTimes(3);
+
+ // The switch drops the snapshot, so its refetch must not be swallowed.
+ emitAuthState("org-2");
+ await vi.advanceTimersByTimeAsync(5_001);
+ expect(fetchUsage).toHaveBeenCalledTimes(4);
+ });
+
+ it("lets a forced refresh skip the timed window", async () => {
+ const fetchUsage = vi.fn().mockRejectedValue(new Error("HTTP 500"));
+ const gateway = { fetchUsage } as unknown as GatewaySlice;
+ service = makeService(gateway, makeActivityMonitor());
+
+ await service.fetchOnce();
+ await service.fetchOnce();
+ expect(fetchUsage).toHaveBeenCalledTimes(1);
+
+ await service.refreshNow();
+ expect(fetchUsage).toHaveBeenCalledTimes(2);
+ });
+
+ it("does not let a forced refresh bypass the terminal stop", async () => {
+ const fetchUsage = vi.fn().mockRejectedValue(new NotAuthenticatedError());
+ const gateway = { fetchUsage } as unknown as GatewaySlice;
+ service = makeService(gateway, makeActivityMonitor());
+ emitAuthState("org-1", "anonymous");
+
+ await service.fetchOnce();
+ // A forced fetch with no session cannot succeed.
+ await service.refreshNow();
+ expect(fetchUsage).toHaveBeenCalledTimes(1);
+ });
+
+ it("warns when it enters the terminal stop", async () => {
+ const fetchUsage = vi.fn().mockRejectedValue(new NotAuthenticatedError());
+ const gateway = { fetchUsage } as unknown as GatewaySlice;
+ service = makeService(gateway, makeActivityMonitor());
+
+ await service.fetchOnce();
+
+ expect(lastScopedLog.warn).toHaveBeenCalledWith(
+ expect.stringContaining("re-auth"),
+ { reason: "reauth_required" },
+ );
+ });
+
it("silently skips polls when the gateway throws", async () => {
const events: unknown[] = [];
const gateway = {
diff --git a/products/desktop/packages/core/src/usage/usage-monitor.ts b/products/desktop/packages/core/src/usage/usage-monitor.ts
index af783d96b69b..2229631187ee 100644
--- a/products/desktop/packages/core/src/usage/usage-monitor.ts
+++ b/products/desktop/packages/core/src/usage/usage-monitor.ts
@@ -1,5 +1,5 @@
import { ROOT_LOGGER, type RootLogger } from "@posthog/di/logger";
-import { TypedEventEmitter } from "@posthog/shared";
+import { isNotAuthenticatedError, TypedEventEmitter } from "@posthog/shared";
import { inject, injectable, postConstruct, preDestroy } from "inversify";
import type { AuthService } from "../auth/auth";
import { AUTH_SERVICE } from "../auth/auth.module";
@@ -18,6 +18,9 @@ const COALESCE_INTERVAL_MS = 5_000;
// Catches reset-window rollovers and out-of-band plan changes while the app
// sits idle and no LlmActivity events fire.
const BACKSTOP_INTERVAL_MS = 30 * 60_000;
+// Bounds a persistent failure to one request per window, not one per trigger.
+const FAILURE_BACKOFF_BASE_MS = COALESCE_INTERVAL_MS;
+const FAILURE_BACKOFF_MAX_MS = BACKSTOP_INTERVAL_MS;
type BucketName = "burst" | "sustained";
@@ -27,6 +30,10 @@ export class UsageMonitorService extends TypedEventEmitter<UsageMonitorEvents> {
private coalesceTimeoutId: ReturnType<typeof setTimeout> | null = null;
private lastFetchStartedAt = 0;
private isFetching = false;
+ private consecutiveFailures = 0;
+ private nextAllowedFetchAt = 0;
+ // A dead session is fixed by a new sign-in, never by polling.
+ private reauthRequired = false;
private thresholdsSeen: Record<string, string>;
private latestUsage: UsageOutput | null = null;
@@ -38,7 +45,7 @@ export class UsageMonitorService extends TypedEventEmitter<UsageMonitorEvents> {
@inject(ROOT_LOGGER)
logger: RootLogger,
@inject(AUTH_SERVICE)
- authService: AuthService,
+ private readonly authService: AuthService,
) {
super();
this.log = logger.scope("usage-monitor");
@@ -50,6 +57,9 @@ export class UsageMonitorService extends TypedEventEmitter<UsageMonitorEvents> {
if (state.currentOrgId === orgId) return;
orgId = state.currentOrgId;
this.latestUsage = null;
+ // The snapshot was just dropped, so let the refetch through any open
+ // window. This clears the terminal stop too, which the gate re-derives.
+ this.resetBackoff();
if (state.currentOrgId !== null) this.requestRefresh();
});
}
@@ -60,8 +70,9 @@ export class UsageMonitorService extends TypedEventEmitter<UsageMonitorEvents> {
return this.latestUsage;
}
+ // Skips the failure backoff. The terminal stop still applies.
async refreshNow(): Promise<UsageOutput | null> {
- return this.fetchOnce();
+ return this.fetchOnce({ force: true });
}
// Coalesces N parallel agents finishing turns into at most two fetches
@@ -100,8 +111,20 @@ export class UsageMonitorService extends TypedEventEmitter<UsageMonitorEvents> {
}
}
- async fetchOnce(): Promise<UsageOutput | null> {
+ async fetchOnce({
+ force = false,
+ }: {
+ force?: boolean;
+ } = {}): Promise<UsageOutput | null> {
if (this.isFetching) return null;
+ // Re-derived, not trusted: the error can arrive after the last authenticated
+ // emission, and auth raises the same class for a merely superseded refresh.
+ if (this.reauthRequired) {
+ if (this.authService.getState().status !== "authenticated") return null;
+ this.reauthRequired = false;
+ }
+ // force skips the timed window, never the terminal stop.
+ if (!force && Date.now() < this.nextAllowedFetchAt) return null;
this.isFetching = true;
this.lastFetchStartedAt = Date.now();
if (this.coalesceTimeoutId) {
@@ -113,11 +136,14 @@ export class UsageMonitorService extends TypedEventEmitter<UsageMonitorEvents> {
try {
usage = await this.host.fetchUsage();
} catch (err) {
+ this.recordFailure(err);
this.log.debug("Usage fetch skipped", {
error: err instanceof Error ? err.message : String(err),
+ consecutiveFailures: this.consecutiveFailures,
});
}
if (usage) {
+ this.resetBackoff();
const changed = !isSameUsage(this.latestUsage, usage);
this.latestUsage = usage;
if (changed) {
@@ -131,6 +157,29 @@ export class UsageMonitorService extends TypedEventEmitter<UsageMonitorEvents> {
}
}
+ private recordFailure(err: unknown): void {
+ if (isNotAuthenticatedError(err)) {
+ this.reauthRequired = true;
+ this.log.warn("Usage polling stopped, session needs re-auth", {
+ reason: "reauth_required",
+ });
+ return;
+ }
+ this.consecutiveFailures += 1;
+ const delay = Math.min(
+ FAILURE_BACKOFF_BASE_MS * 2 ** (this.consecutiveFailures - 1),
+ FAILURE_BACKOFF_MAX_MS,
+ );
+ // Jitter so N agents that failed together don't retry in lockstep.
+ this.nextAllowedFetchAt = Date.now() + delay * (0.5 + Math.random() / 2);
+ }
+
+ private resetBackoff(): void {
+ this.consecutiveFailures = 0;
+ this.nextAllowedFetchAt = 0;
+ this.reauthRequired = false;
+ }
+
private scheduleBackstop(): void {
this.backstopTimeoutId = setTimeout(async () => {
this.backstopTimeoutId = null;