Skip to content

An open-source, faster Devin alternative

TypeScript

web: keep the dashboard session alive and redirect to login when it lapses (#813)

devin-ai-integration[bot]b8efb28f069a
diff --git a/web/src/api/client.ts b/web/src/api/client.ts
index e505a560..149843cf 100644
--- a/web/src/api/client.ts
+++ b/web/src/api/client.ts
@@ -211,6 +211,19 @@ export async function logout(): Promise<void> {
window.location.replace(dest)
}
+// Rotate the session cookie so an open tab keeps a sliding expiry instead of
+// hitting the fixed TTL mid-page. Best-effort: not every backend serves the
+// route, and a failure here just means the next 401 sends the user through
+// the normal login round-trip.
+export async function refreshSession(): Promise<void> {
+ if (import.meta.env.VITE_PREVIEW === '1') return
+ try {
+ await fetch('/auth/refresh', { method: 'POST', credentials: 'include' })
+ } catch {
+ // ignore
+ }
+}
+
// API functions
export const getMe = () => apiFetch('/me', {}, S.MeResponseSchema)
diff --git a/web/src/hooks/auth-provider.tsx b/web/src/hooks/auth-provider.tsx
index fb7223c2..12f97ef0 100644
--- a/web/src/hooks/auth-provider.tsx
+++ b/web/src/hooks/auth-provider.tsx
@@ -1,8 +1,21 @@
import { useCallback, useEffect, type ReactNode } from 'react'
import { useQuery, useQueryClient } from '@tanstack/react-query'
import posthog from 'posthog-js'
-import { getMe, switchOrg as switchOrgApi } from '../api/client'
-import { AuthContext } from './useAuth'
+import { getMe, refreshSession, switchOrg as switchOrgApi } from '../api/client'
+import { ApiError } from '../api/errors'
+import { AuthContext, ME_QUERY_KEY } from './useAuth'
+
+// Session cookies carry a fixed 8h expiry. Re-mint one whenever the user
+// comes back to the tab (and on load), throttled so a flurry of focus events
+// doesn't hammer the edge. Module-level so it survives provider remounts.
+const SESSION_REFRESH_MIN_INTERVAL_MS = 15 * 60_000
+let lastSessionRefreshAt = 0
+function refreshSessionThrottled() {
+ const now = Date.now()
+ if (now - lastSessionRefreshAt < SESSION_REFRESH_MIN_INTERVAL_MS) return
+ lastSessionRefreshAt = now
+ void refreshSession()
+}
export function AuthProvider({ children }: { children: ReactNode }) {
const queryClient = useQueryClient()
@@ -10,13 +23,32 @@ export function AuthProvider({ children }: { children: ReactNode }) {
// /me is server state, so React Query owns it. A 401 throws (see apiFetch)
// and lands as an error with no data — ProtectedRoute redirects to login.
const query = useQuery({
- queryKey: ['me'],
+ queryKey: ME_QUERY_KEY,
queryFn: getMe,
retry: false,
staleTime: 60_000,
})
const { refetch } = query
- const user = query.data ?? null
+ // A 401 on a background refetch keeps the previous data around; the session
+ // is gone regardless, so treat it as signed out rather than trusting the
+ // stale user.
+ const unauthorized =
+ query.error instanceof ApiError && query.error.status === 401
+ const user = unauthorized ? null : (query.data ?? null)
+
+ useEffect(() => {
+ if (!user) return
+ refreshSessionThrottled()
+ const onVisible = () => {
+ if (document.visibilityState === 'visible') refreshSessionThrottled()
+ }
+ document.addEventListener('visibilitychange', onVisible)
+ window.addEventListener('focus', onVisible)
+ return () => {
+ document.removeEventListener('visibilitychange', onVisible)
+ window.removeEventListener('focus', onVisible)
+ }
+ }, [user])
// Identify the analytics user once /me resolves (external-system sync).
useEffect(() => {
@@ -44,7 +76,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {
// A 401 is an expected unauthenticated state, not a surfaced error.
const error =
- query.error && !/unauthorized/i.test(query.error.message)
+ query.error && !unauthorized && !/unauthorized/i.test(query.error.message)
? query.error.message
: null
diff --git a/web/src/hooks/useAuth.ts b/web/src/hooks/useAuth.ts
index a2fda8a4..a7d542a4 100644
--- a/web/src/hooks/useAuth.ts
+++ b/web/src/hooks/useAuth.ts
@@ -1,6 +1,8 @@
import { createContext, useContext } from 'react'
import type { OrgInfo } from '../api/client'
+export const ME_QUERY_KEY = ['me'] as const
+
export interface AuthUser {
id: string
email: string
diff --git a/web/src/main.tsx b/web/src/main.tsx
index dd6455b4..d2977b6d 100644
--- a/web/src/main.tsx
+++ b/web/src/main.tsx
@@ -1,6 +1,10 @@
import React from 'react'
import ReactDOM from 'react-dom/client'
-import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
+import {
+ QueryCache,
+ QueryClient,
+ QueryClientProvider,
+} from '@tanstack/react-query'
import { BrowserRouter } from 'react-router-dom'
import posthog from 'posthog-js'
import { PostHogProvider } from '@posthog/react'
@@ -11,9 +15,26 @@ import {
DefaultErrorFallback,
} from './components/error-boundary'
import { reloadForStaleChunk } from './lib/chunk-reload'
+import { ME_QUERY_KEY } from './hooks/useAuth'
+import { ApiError } from './api/errors'
import './index.css'
+// When the dashboard session expires (laptop sleep, cookie TTL), the polling
+// queries are the first to see the 401 — ['me'] keeps serving its cached user,
+// so ProtectedRoute never redirects and screens render "not found" instead.
+// Drop the cached user on any 401 so the auth gate re-checks and sends the
+// user to login. Skipped when no user is cached: ['me'] itself failing with
+// 401 is the normal signed-out state and must not loop.
+const queryCache = new QueryCache({
+ onError: (error) => {
+ if (!(error instanceof ApiError) || error.status !== 401) return
+ if (queryClient.getQueryData(ME_QUERY_KEY) === undefined) return
+ void queryClient.resetQueries({ queryKey: ME_QUERY_KEY, exact: true })
+ },
+})
+
const queryClient = new QueryClient({
+ queryCache,
defaultOptions: {
queries: {
retry: 1,
diff --git a/web/src/pages/Settings.tsx b/web/src/pages/Settings.tsx
index 28f8eeac..98e7b1c1 100644
--- a/web/src/pages/Settings.tsx
+++ b/web/src/pages/Settings.tsx
@@ -2,7 +2,7 @@ import { useState, type ReactNode } from 'react'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { notifyError } from '@/lib/errors'
import { useTransientFlag } from '@/lib/use-transient-flag'
-import { useAuth } from '@/hooks/useAuth'
+import { ME_QUERY_KEY, useAuth } from '@/hooks/useAuth'
import { organizationPlanLabel } from '@/lib/plan-label'
import {
deleteCustomDomain,
@@ -127,7 +127,7 @@ export default function Settings() {
const navigationMutation = useMutation({
mutationFn: (updates: NavigationPreferenceUpdate) =>
updateNavigationPreferences(updates),
- onSuccess: (updated) => queryClient.setQueryData(['me'], updated),
+ onSuccess: (updated) => queryClient.setQueryData(ME_QUERY_KEY, updated),
onError: (e) => notifyError("Couldn't save navigation settings.", e),
})