🙌 OpenHands: AI-Driven Development
Update to login if session times out and return to previous conversation (#8587)
chuckbutkus3280f450acdb
diff --git a/frontend/src/components/features/waitlist/auth-modal.tsx b/frontend/src/components/features/waitlist/auth-modal.tsxindex 3fbafea011..20cf60f3d1 100644--- a/frontend/src/components/features/waitlist/auth-modal.tsx+++ b/frontend/src/components/features/waitlist/auth-modal.tsx@@ -9,6 +9,7 @@ import GitHubLogo from "#/assets/branding/github-logo.svg?react";import GitLabLogo from "#/assets/branding/gitlab-logo.svg?react";import { useAuthUrl } from "#/hooks/use-auth-url";import { GetConfigResponse } from "#/api/open-hands.types";+import { LoginMethod, setLoginMethod } from "#/utils/local-storage";interface AuthModalProps {githubAuthUrl: string | null;@@ -25,6 +26,10 @@ export function AuthModal({ githubAuthUrl, appMode }: AuthModalProps) {const handleGitHubAuth = () => {if (githubAuthUrl) {+ // Store the login method in local storage (only in SAAS mode)+ if (appMode === "saas") {+ setLoginMethod(LoginMethod.GITHUB);+ }// Always start the OIDC flow, let the backend handle TOS checkwindow.location.href = githubAuthUrl;}@@ -32,6 +37,10 @@ export function AuthModal({ githubAuthUrl, appMode }: AuthModalProps) {const handleGitLabAuth = () => {if (gitlabAuthUrl) {+ // Store the login method in local storage (only in SAAS mode)+ if (appMode === "saas") {+ setLoginMethod(LoginMethod.GITLAB);+ }// Always start the OIDC flow, let the backend handle TOS checkwindow.location.href = gitlabAuthUrl;}diff --git a/frontend/src/components/features/waitlist/reauth-modal.tsx b/frontend/src/components/features/waitlist/reauth-modal.tsxnew file mode 100644index 0000000000..33e2ee219b--- /dev/null+++ b/frontend/src/components/features/waitlist/reauth-modal.tsx@@ -0,0 +1,23 @@+import React from "react";+import { useTranslation } from "react-i18next";+import { ModalBackdrop } from "#/components/shared/modals/modal-backdrop";+import { ModalBody } from "#/components/shared/modals/modal-body";+import { I18nKey } from "#/i18n/declaration";+import AllHandsLogo from "#/assets/branding/all-hands-logo.svg?react";++export function ReauthModal() {+ const { t } = useTranslation();++ return (+ <ModalBackdrop>+ <ModalBody className="border border-tertiary">+ <AllHandsLogo width={68} height={46} />+ <div className="flex flex-col gap-2 w-full items-center text-center">+ <h1 className="text-2xl font-bold">+ {t(I18nKey.AUTH$LOGGING_BACK_IN)}+ </h1>+ </div>+ </ModalBody>+ </ModalBackdrop>+ );+}diff --git a/frontend/src/hooks/mutation/use-logout.ts b/frontend/src/hooks/mutation/use-logout.tsindex c574778a71..caf3feb993 100644--- a/frontend/src/hooks/mutation/use-logout.ts+++ b/frontend/src/hooks/mutation/use-logout.ts@@ -3,6 +3,7 @@ import { useNavigate } from "react-router";import posthog from "posthog-js";import OpenHands from "#/api/open-hands";import { useConfig } from "../query/use-config";+import { clearLoginData } from "#/utils/local-storage";export const useLogout = () => {const queryClient = useQueryClient();@@ -17,8 +18,16 @@ export const useLogout = () => {queryClient.removeQueries({ queryKey: ["user"] });queryClient.removeQueries({ queryKey: ["secrets"] });+ // Clear login method and last page from local storage+ if (config?.APP_MODE === "saas") {+ clearLoginData();+ }+posthog.reset();await navigate("/");++ // Refresh the page after all logout logic is completed+ window.location.reload();},});};diff --git a/frontend/src/hooks/use-auto-login.ts b/frontend/src/hooks/use-auto-login.tsnew file mode 100644index 0000000000..18602cf6e2--- /dev/null+++ b/frontend/src/hooks/use-auto-login.ts@@ -0,0 +1,100 @@+import { useEffect } from "react";+import { useNavigate } from "react-router";+import { useConfig } from "./query/use-config";+import { useIsAuthed } from "./query/use-is-authed";+import {+ getLoginMethod,+ getLastPage,+ LoginMethod,+} from "#/utils/local-storage";+import { useAuthUrl } from "./use-auth-url";++/**+ * Hook to automatically log in the user if they have a login method stored in local storage+ * Only works in SAAS mode and when the user is not already logged in+ */+export const useAutoLogin = () => {+ const navigate = useNavigate();+ const { data: config, isLoading: isConfigLoading } = useConfig();+ const { data: isAuthed, isLoading: isAuthLoading } = useIsAuthed();++ // Get the stored login method+ const loginMethod = getLoginMethod();++ // Get the auth URLs for both providers+ const githubAuthUrl = useAuthUrl({+ appMode: config?.APP_MODE || null,+ identityProvider: "github",+ });++ const gitlabAuthUrl = useAuthUrl({+ appMode: config?.APP_MODE || null,+ identityProvider: "gitlab",+ });++ useEffect(() => {+ // Only auto-login in SAAS mode+ if (config?.APP_MODE !== "saas") {+ return;+ }++ // Wait for auth and config to load+ if (isConfigLoading || isAuthLoading) {+ return;+ }++ // Don't auto-login if already authenticated+ if (isAuthed) {+ return;+ }++ // Don't auto-login if no login method is stored+ if (!loginMethod) {+ return;+ }++ // Get the appropriate auth URL based on the stored login method+ const authUrl =+ loginMethod === LoginMethod.GITHUB ? githubAuthUrl : gitlabAuthUrl;++ // If we have an auth URL, redirect to it+ if (authUrl) {+ // After successful login, the user will be redirected back and can navigate to the last page+ window.location.href = authUrl;+ }+ }, [+ config?.APP_MODE,+ isAuthed,+ isConfigLoading,+ isAuthLoading,+ loginMethod,+ githubAuthUrl,+ gitlabAuthUrl,+ ]);++ // Handle navigation to last page after login+ useEffect(() => {+ // Only navigate in SAAS mode+ if (config?.APP_MODE !== "saas") {+ return;+ }++ // Wait for auth to load+ if (isAuthLoading) {+ return;+ }++ // Only navigate if authenticated+ if (!isAuthed) {+ return;+ }++ // Get the last page from local storage+ const lastPage = getLastPage();++ // Navigate to the last page if it exists+ if (lastPage) {+ navigate(lastPage);+ }+ }, [config?.APP_MODE, isAuthed, isAuthLoading, navigate]);+};diff --git a/frontend/src/hooks/use-track-last-page.ts b/frontend/src/hooks/use-track-last-page.tsnew file mode 100644index 0000000000..5398c6e3b1--- /dev/null+++ b/frontend/src/hooks/use-track-last-page.ts@@ -0,0 +1,33 @@+import { useEffect } from "react";+import { useLocation } from "react-router";+import { useConfig } from "./query/use-config";+import { setLastPage, shouldExcludePath } from "#/utils/local-storage";+import { useIsAuthed } from "./query/use-is-authed";++/**+ * Hook to track the last visited page in local storage+ * Only tracks pages in SAAS mode and excludes certain paths+ */+export const useTrackLastPage = () => {+ const location = useLocation();+ const { data: config } = useConfig();+ const { data: isAuthed, isLoading: isAuthLoading } = useIsAuthed();++ useEffect(() => {+ // Only track pages in SAAS mode when authenticated+ if (config?.APP_MODE !== "saas" || !isAuthed || isAuthLoading) {+ return;+ }++ const { pathname } = location;++ // Don't track excluded paths+ if (shouldExcludePath(pathname)) {+ // leave code block for now as we may decide not to track certain pages.+ // return;+ }++ // Store the current path as the last visited page+ setLastPage(pathname);+ }, [location, config?.APP_MODE]);+};diff --git a/frontend/src/i18n/declaration.ts b/frontend/src/i18n/declaration.tsindex 031cb1ec01..ef7e403d82 100644--- a/frontend/src/i18n/declaration.ts+++ b/frontend/src/i18n/declaration.ts@@ -1,5 +1,6 @@// this file generate by script, don't modify it manually!!!export enum I18nKey {+ AUTH$LOGGING_BACK_IN = "AUTH$LOGGING_BACK_IN",SECURITY$LOW_RISK = "SECURITY$LOW_RISK",SECURITY$MEDIUM_RISK = "SECURITY$MEDIUM_RISK",SECURITY$HIGH_RISK = "SECURITY$HIGH_RISK",@@ -12,7 +13,6 @@ export enum I18nKey {OBSERVATION$MCP_NO_OUTPUT = "OBSERVATION$MCP_NO_OUTPUT",OBSERVATION$ERROR_PREFIX = "OBSERVATION$ERROR_PREFIX",TASK$ADDRESSING_TASK = "TASK$ADDRESSING_TASK",- CHAT_INTERFACE$AGENT_ERROR_MESSAGE = "CHAT_INTERFACE$AGENT_ERROR_MESSAGE",SECRETS$SECRET_VALUE_REQUIRED = "SECRETS$SECRET_VALUE_REQUIRED",SECRETS$ADD_SECRET = "SECRETS$ADD_SECRET",SECRETS$EDIT_SECRET = "SECRETS$EDIT_SECRET",@@ -292,6 +292,7 @@ export enum I18nKey {CHAT_INTERFACE$AGENT_STOPPED_MESSAGE = "CHAT_INTERFACE$AGENT_STOPPED_MESSAGE",CHAT_INTERFACE$AGENT_FINISHED_MESSAGE = "CHAT_INTERFACE$AGENT_FINISHED_MESSAGE",CHAT_INTERFACE$AGENT_REJECTED_MESSAGE = "CHAT_INTERFACE$AGENT_REJECTED_MESSAGE",+ CHAT_INTERFACE$AGENT_ERROR_MESSAGE = "CHAT_INTERFACE$AGENT_ERROR_MESSAGE",CHAT_INTERFACE$AGENT_AWAITING_USER_CONFIRMATION_MESSAGE = "CHAT_INTERFACE$AGENT_AWAITING_USER_CONFIRMATION_MESSAGE",CHAT_INTERFACE$AGENT_ACTION_USER_CONFIRMED_MESSAGE = "CHAT_INTERFACE$AGENT_ACTION_USER_CONFIRMED_MESSAGE",CHAT_INTERFACE$AGENT_ACTION_USER_REJECTED_MESSAGE = "CHAT_INTERFACE$AGENT_ACTION_USER_REJECTED_MESSAGE",diff --git a/frontend/src/i18n/translation.json b/frontend/src/i18n/translation.jsonindex 1882fbe6bc..6efd38b8ab 100644--- a/frontend/src/i18n/translation.json+++ b/frontend/src/i18n/translation.json@@ -1,4 +1,20 @@{+ "AUTH$LOGGING_BACK_IN": {+ "en": "Logging back into OpenHands...",+ "ja": "OpenHandsに再ログインしています...",+ "zh-CN": "正在重新登录OpenHands...",+ "zh-TW": "正在重新登錄OpenHands...",+ "ko-KR": "OpenHands에 다시 로그인 중...",+ "no": "Logger inn igjen på OpenHands...",+ "it": "Accesso nuovamente a OpenHands...",+ "pt": "Entrando novamente no OpenHands...",+ "es": "Iniciando sesión de nuevo en OpenHands...",+ "ar": "جاري إعادة تسجيل الدخول إلى OpenHands...",+ "fr": "Reconnexion à OpenHands...",+ "tr": "OpenHands'e yeniden giriş yapılıyor...",+ "de": "Erneute Anmeldung bei OpenHands...",+ "uk": "Повторний вхід до OpenHands..."+ },"SECURITY$LOW_RISK": {"en": "Low Risk","ja": "低リスク",diff --git a/frontend/src/routes/root-layout.tsx b/frontend/src/routes/root-layout.tsxindex 37c087839e..76d06de2ef 100644--- a/frontend/src/routes/root-layout.tsx+++ b/frontend/src/routes/root-layout.tsx@@ -14,6 +14,7 @@ import { useIsAuthed } from "#/hooks/query/use-is-authed";import { useConfig } from "#/hooks/query/use-config";import { Sidebar } from "#/components/features/sidebar/sidebar";import { AuthModal } from "#/components/features/waitlist/auth-modal";+import { ReauthModal } from "#/components/features/waitlist/reauth-modal";import { AnalyticsConsentFormModal } from "#/components/features/analytics/analytics-consent-form-modal";import { useSettings } from "#/hooks/query/use-settings";import { useMigrateUserConsent } from "#/hooks/use-migrate-user-consent";@@ -21,6 +22,9 @@ import { useBalance } from "#/hooks/query/use-balance";import { SetupPaymentModal } from "#/components/features/payment/setup-payment-modal";import { displaySuccessToast } from "#/utils/custom-toast-handlers";import { useIsOnTosPage } from "#/hooks/use-is-on-tos-page";+import { useTrackLastPage } from "#/hooks/use-track-last-page";+import { useAutoLogin } from "#/hooks/use-auto-login";+import { LOCAL_STORAGE_KEYS } from "#/utils/local-storage";export function ErrorBoundary() {const error = useRouteError();@@ -82,6 +86,12 @@ export default function MainApp() {const [consentFormIsOpen, setConsentFormIsOpen] = React.useState(false);+ // Track the last visited page+ useTrackLastPage();++ // Auto-login if login method is stored in local storage+ useAutoLogin();+React.useEffect(() => {// Don't change language when on TOS pageif (!isOnTosPage && settings?.LANGUAGE) {@@ -125,12 +135,30 @@ export default function MainApp() {}}, [error?.status, pathname, isOnTosPage]);+ // Check if login method exists in local storage+ const loginMethodExists = React.useMemo(() => {+ // Only check localStorage if we're in a browser environment+ if (typeof window !== "undefined" && window.localStorage) {+ return localStorage.getItem(LOCAL_STORAGE_KEYS.LOGIN_METHOD) !== null;+ }+ return false;+ }, []);+const renderAuthModal =!isAuthed &&!isAuthError &&!isFetchingAuth &&!isOnTosPage &&- config.data?.APP_MODE === "saas";+ config.data?.APP_MODE === "saas" &&+ !loginMethodExists; // Don't show auth modal if login method exists in local storage++ const renderReAuthModal =+ !isAuthed &&+ !isAuthError &&+ !isFetchingAuth &&+ !isOnTosPage &&+ config.data?.APP_MODE === "saas" &&+ loginMethodExists;return (<div@@ -152,6 +180,7 @@ export default function MainApp() {appMode={config.data?.APP_MODE}/>)}+ {renderReAuthModal && <ReauthModal />}{config.data?.APP_MODE === "oss" && consentFormIsOpen && (<AnalyticsConsentFormModalonClose={() => {diff --git a/frontend/src/utils/local-storage.ts b/frontend/src/utils/local-storage.tsnew file mode 100644index 0000000000..cfe0757cb8--- /dev/null+++ b/frontend/src/utils/local-storage.ts@@ -0,0 +1,59 @@+// Local storage keys+export const LOCAL_STORAGE_KEYS = {+ LOGIN_METHOD: "openhands_login_method",+ LAST_PAGE: "openhands_last_page",+};++// Login methods+export enum LoginMethod {+ GITHUB = "github",+ GITLAB = "gitlab",+}++/**+ * Set the login method in local storage+ * @param method The login method (github or gitlab)+ */+export const setLoginMethod = (method: LoginMethod): void => {+ localStorage.setItem(LOCAL_STORAGE_KEYS.LOGIN_METHOD, method);+};++/**+ * Get the login method from local storage+ * @returns The login method or null if not set+ */+export const getLoginMethod = (): LoginMethod | null => {+ const method = localStorage.getItem(LOCAL_STORAGE_KEYS.LOGIN_METHOD);+ return method as LoginMethod | null;+};++/**+ * Set the last visited page in local storage+ * @param path The path of the last visited page+ */+export const setLastPage = (path: string): void => {+ localStorage.setItem(LOCAL_STORAGE_KEYS.LAST_PAGE, path);+};++/**+ * Get the last visited page from local storage+ * @returns The last visited page or null if not set+ */+export const getLastPage = (): string | null =>+ localStorage.getItem(LOCAL_STORAGE_KEYS.LAST_PAGE);++/**+ * Clear login method and last page from local storage+ */+export const clearLoginData = (): void => {+ localStorage.removeItem(LOCAL_STORAGE_KEYS.LOGIN_METHOD);+ localStorage.removeItem(LOCAL_STORAGE_KEYS.LAST_PAGE);+};++/**+ * Check if the given path should be excluded from being saved as the last page+ * @param path The path to check+ * @returns True if the path should be excluded, false otherwise+ */+export const shouldExcludePath = (path: string): boolean =>+ path.startsWith("/settings");