← DemosAI WorkspaceMulti-session agent chatView source ↗
HyperKit Agent Workspace3 sessions
Fix flaky auth token refresh
Connected

Users are getting logged out randomly. I suspect the token refresh — it fails once and never retries. Can you dig in?

I traced it. scheduleRefresh computes the delay from expiresAt - Date.now() once, at login. If the first refresh request fails (flaky network), no retry is ever scheduled — the session silently dies at expiry.

Here is the fix with exponential backoff:

async function refreshLoop(session: Session) {
  let attempt = 0;
  while (!session.closed) {
    const delay = attempt === 0
      ? session.expiresAt - Date.now() - SKEW_MS
      : Math.min(2 ** attempt * 1_000, 30_000);
    await sleep(delay);
    try {
      await session.refresh();
      attempt = 0; // healthy again
    } catch {
      attempt += 1; // retry with backoff
    }
  }
}

The loop owns the schedule, so a failed attempt backs off and retries instead of giving up.

That matches what we see in Sentry. Apply it and add a regression test for the failure path.

Patch applied to src/auth/refresh.ts. Now writing the regression test — simulating a failed first refresh and asserting the retry fires within the backoff window