Skip to content

fix (desktop): first pass auth flash fix - #1047

Merged
AviPeltz merged 5 commits into
mainfrom
AviPeltz/auth-fix
Feb 4, 2026
Merged

AviPeltz merged 5 commits into
mainfrom
AviPeltz/auth-fix

Conversation

@AviPeltz

@AviPeltz AviPeltz commented Jan 29, 2026 •

Copy link
Copy Markdown
Collaborator

Description

Related Issues

Type of Change

  • Bug fix
  • New feature
  • Documentation
  • Refactor
  • Other (please describe):

Testing

Screenshots (if applicable)

Additional Notes

Summary by CodeRabbit

  • New Features

    • Offline detection and an "Offline" indicator in the top bar.
    • Offline UI with a Retry action when a local token exists but no network.
    • Non-blocking background session validation; UI renders promptly while validation runs.
    • Temporary full-screen loading when a local token is present and session validation is pending.
  • Bug Fixes

    • Authentication works offline when a stored token is still valid.
    • Session validation failures no longer block rendering; improved sign-in navigation when no local token.

@coderabbitai

coderabbitai Bot commented Jan 29, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

On mount, AuthProvider checks a stored token's expiry and, if valid, sets it in memory and starts a non-blocking background session refetch. The authenticated layout uses session pending, local-token presence, and online status to choose between spinner, sign-in redirect, or an offline retry UI.

Changes

Cohort / File(s) Summary
Auth Provider Token Hydration
apps/desktop/src/renderer/providers/AuthProvider/AuthProvider.tsx
Adds local expiry check before setting a stored token in memory; when valid, sets token and invokes a non-blocking refetchSession. Keeps token-change subscription and public API unchanged.
Authenticated Layout & Offline UX
apps/desktop/src/renderer/routes/_authenticated/layout.tsx
Adds useOnlineStatus, derives hasLocalToken/isOnline, and introduces early-return flows: full-screen Spinner when session pending + local token, navigate to /sign-in when pending without local token, and render an offline retry UI (Wi‑Fi icon + Retry) when offline with a local token.
Online Status Hook
apps/desktop/src/renderer/hooks/useOnlineStatus.ts
New hook exposing isOnline via navigator.onLine, subscribing to online/offline window events and cleaning up on unmount.
TopBar Offline Indicator
apps/desktop/src/renderer/routes/_authenticated/_dashboard/components/TopBar/TopBar.tsx
Adds useOnlineStatus and a small offline badge (Wi‑Fi icon + "Offline") to the top bar while preserving existing controls and behavior.

Sequence Diagram(s)

sequenceDiagram
  participant Renderer as Renderer (UI)
  participant AuthProv as AuthProvider
  participant Storage as LocalStorage
  participant API as Auth API

  Renderer->>AuthProv: mount
  AuthProv->>Storage: read storedToken
  alt storedToken exists && not expired
    AuthProv->>AuthProv: set token in memory
    AuthProv->>API: refetchSession() (async, non-blocking)
    API-->>AuthProv: session data / error
    AuthProv-->>Renderer: session state updated
  else no token or expired
    AuthProv-->>Renderer: no token (render sign-in path)
  end
  Renderer->>Renderer: layout checks isPending, hasLocalToken, isOnline
  alt isPending && hasLocalToken
    Renderer-->>Renderer: render full-screen Spinner
  else isPending && !hasLocalToken
    Renderer-->>Renderer: navigate to /sign-in
  else !signedIn && hasLocalToken && !isOnline
    Renderer-->>Renderer: render offline retry UI (Retry -> triggers refetch)
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested reviewers

  • CharlieHelps
  • saddlepaddle

Poem

🐇 I nibble tokens in the dark and light,
I check their age by soft moonlight,
If fresh, I hum a background tune,
If old, I point toward sign‑in soon.
Hop—tap Retry when the wifi's out tonight.

🚥 Pre-merge checks | ✅ 1 | ❌ 2
❌ Failed checks (2 warnings)
Check name Status Explanation Resolution
Description check ⚠️ Warning The PR description is largely a template with only the 'Type of Change' section completed; critical details like implementation summary, related issues, and testing steps are missing or empty. Fill in the Description section with how the auth flash is addressed (offline-aware token handling, UI blocking prevention), link any related GitHub issues, and document testing steps for the offline UX changes.
Docstring Coverage ⚠️ Warning Docstring coverage is 25.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (1 passed)
Check name Status Explanation
Title check ✅ Passed The title 'fix (desktop): first pass auth flash fix' directly addresses the main change—reducing auth UI flash by implementing offline-aware token handling and validation.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch AviPeltz/auth-fix

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@AviPeltz
AviPeltz marked this pull request as ready for review January 29, 2026 18:53
@AviPeltz
AviPeltz requested a review from saddlepaddle January 29, 2026 18:58

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Fix all issues with AI agents
In `@apps/desktop/src/renderer/providers/AuthProvider/AuthProvider.tsx`:
- Around line 32-43: The code currently treats storedToken.expiresAt by
comparing new Date(storedToken.expiresAt) < new Date(), which accepts invalid
dates and lets exact-expiry tokens through; update the guard around
storedToken.expiresAt in the AuthProvider logic to first parse and validate the
timestamp (e.g., Date.parse or new Date(...) and check isNaN) and then use a <=
comparison against now to treat exact-expiry as expired; if the parsed date is
invalid or <= now, do NOT call setAuthToken(storedToken.token) or
refetchSession(), otherwise proceed to setAuthToken and kick off
refetchSession() as before.

Comment on lines +32 to +43
// If token exists and isn't expired locally, set it and validate in background
if (storedToken?.token && storedToken?.expiresAt) {
setAuthToken(storedToken.token);
refetchSession();
const isExpired = new Date(storedToken.expiresAt) < new Date();

if (!isExpired) {
setAuthToken(storedToken.token);
// Validate session in background - don't block UI on network
refetchSession().catch((err) => {
console.warn("[auth] Background session validation failed:", err);
});
}
// If expired, don't set token - user will be redirected to sign-in

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Guard against invalid or boundary expiresAt values.

new Date(expiresAt) < new Date() treats invalid timestamps as “not expired” and lets exact-expiry tokens through. Prefer isNaN guard and <= to avoid accepting malformed/just-expired tokens.

💡 Suggested fix
-		const isExpired = new Date(storedToken.expiresAt) < new Date();
+		const expiresAtMs = new Date(storedToken.expiresAt).getTime();
+		const nowMs = Date.now();
+		const isExpired = Number.isNaN(expiresAtMs) || expiresAtMs <= nowMs;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// If token exists and isn't expired locally, set it and validate in background
if (storedToken?.token && storedToken?.expiresAt) {
setAuthToken(storedToken.token);
refetchSession();
const isExpired = new Date(storedToken.expiresAt) < new Date();
if (!isExpired) {
setAuthToken(storedToken.token);
// Validate session in background - don't block UI on network
refetchSession().catch((err) => {
console.warn("[auth] Background session validation failed:", err);
});
}
// If expired, don't set token - user will be redirected to sign-in
// If token exists and isn't expired locally, set it and validate in background
if (storedToken?.token && storedToken?.expiresAt) {
const expiresAtMs = new Date(storedToken.expiresAt).getTime();
const nowMs = Date.now();
const isExpired = Number.isNaN(expiresAtMs) || expiresAtMs <= nowMs;
if (!isExpired) {
setAuthToken(storedToken.token);
// Validate session in background - don't block UI on network
refetchSession().catch((err) => {
console.warn("[auth] Background session validation failed:", err);
});
}
// If expired, don't set token - user will be redirected to sign-in
🤖 Prompt for AI Agents
In `@apps/desktop/src/renderer/providers/AuthProvider/AuthProvider.tsx` around
lines 32 - 43, The code currently treats storedToken.expiresAt by comparing new
Date(storedToken.expiresAt) < new Date(), which accepts invalid dates and lets
exact-expiry tokens through; update the guard around storedToken.expiresAt in
the AuthProvider logic to first parse and validate the timestamp (e.g.,
Date.parse or new Date(...) and check isNaN) and then use a <= comparison
against now to treat exact-expiry as expired; if the parsed date is invalid or
<= now, do NOT call setAuthToken(storedToken.token) or refetchSession(),
otherwise proceed to setAuthToken and kick off refetchSession() as before.

- Remove verbose comments and console.warn from AuthProvider
- Add offline screen when disconnected with valid token
- Add offline indicator badge in TopBar
- Extract useOnlineStatus hook for shared use
# Conflicts:
#	apps/desktop/src/renderer/routes/_authenticated/layout.tsx
@AviPeltz
AviPeltz merged commit 28fb8b3 into main Feb 4, 2026
5 checks passed
@github-actions

github-actions Bot commented Feb 4, 2026

Copy link
Copy Markdown
Contributor

🧹 Preview Cleanup Complete

The following preview resources have been cleaned up:

  • ⚠️ Neon database branch
  • ⚠️ Electric Fly.io app

Thank you for your contribution! 🎉

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants