// desktop/src/components/settings/ChatGPTOfficialLogin.tsx import { useEffect, useState } from 'react' import { open as shellOpen } from '@tauri-apps/plugin-shell' import { Copy, LogIn, LogOut } from 'lucide-react' import { useHahaOpenAIOAuthStore } from '../../stores/hahaOpenAIOAuthStore' import { useTranslation } from '../../i18n' import { copyTextToClipboard } from '../chat/clipboard' export function ChatGPTOfficialLogin() { const t = useTranslation() const [manualAuthorizeUrl, setManualAuthorizeUrl] = useState(null) const { status, isLoading, error, fetchStatus, login, logout, startPolling, stopPolling, } = useHahaOpenAIOAuthStore() useEffect(() => { void fetchStatus() return () => stopPolling() }, [fetchStatus, stopPolling]) useEffect(() => { if (status?.loggedIn) { setManualAuthorizeUrl(null) } }, [status?.loggedIn]) const handleLogin = async () => { setManualAuthorizeUrl(null) try { const { authorizeUrl } = await login() setManualAuthorizeUrl(authorizeUrl) try { await shellOpen(authorizeUrl) setManualAuthorizeUrl(null) startPolling() } catch (err) { console.error('[ChatGPTOfficialLogin] shellOpen failed:', err) useHahaOpenAIOAuthStore.setState({ error: t('settings.chatgptOfficialLogin.openBrowserFailed'), }) } } catch { // store.login() errors are already captured into store.error } } const handleCopyAuthorizeUrl = async () => { if (!manualAuthorizeUrl) return const copied = await copyTextToClipboard(manualAuthorizeUrl) if (copied) { setManualAuthorizeUrl(null) useHahaOpenAIOAuthStore.setState({ error: null }) startPolling() return } useHahaOpenAIOAuthStore.setState({ error: t('settings.chatgptOfficialLogin.copyLinkFailed'), }) } const manualAuthorizeButton = manualAuthorizeUrl ? ( ) : null if (status === null) { if (error) { return (
{t('settings.chatgptOfficialLogin.errorPrefix')}{error}
{manualAuthorizeButton}
) } return (
{t('common.loading')}
) } if (status.loggedIn) { const accountLabel = status.email || status.accountId || t('settings.chatgptOfficialLogin.accountUnknown') return (
{t('settings.chatgptOfficialLogin.loggedInPrefix')} {accountLabel}
) } return (
{t('settings.chatgptOfficialLogin.intro')}
{error && (
{t('settings.chatgptOfficialLogin.errorPrefix')}{error}
)} {manualAuthorizeButton}
) }