From bd1f75ce033b5182a5fdb704a21c07effa3e08b4 Mon Sep 17 00:00:00 2001 From: QQ Date: Sat, 14 Nov 2026 14:16:21 +0800 Subject: [PATCH] Import apps/android/src/screens/setup-screens.tsx --- apps/android/src/screens/setup-screens.tsx | 1888 ++++++++++++++++++++ 1 file changed, 1888 insertions(+) create mode 100644 apps/android/src/screens/setup-screens.tsx diff --git a/apps/android/src/screens/setup-screens.tsx b/apps/android/src/screens/setup-screens.tsx new file mode 100644 index 0000000..9b51cac --- /dev/null +++ b/apps/android/src/screens/setup-screens.tsx @@ -0,0 +1,1888 @@ +import { useEffect, useRef, useState } from 'react' +import { connectionLogEntries, connectionLogText, subscribeConnectionLog } from '../services/connection-log' +import { exportConnectionLog } from '../services/export-connection-log' +import { useBrowseMemory, browsePreference } from '../services/browse-memory' +import * as Application from 'expo-application' +import * as Clipboard from 'expo-clipboard' +import { File, Paths } from 'expo-file-system' +import { getContentUriAsync } from 'expo-file-system/legacy' +import * as IntentLauncher from 'expo-intent-launcher' +import { ActivityIndicator, Alert, Animated, Easing, Image, KeyboardAvoidingView, Linking, Modal, PixelRatio, Platform, Pressable, ScrollView, StyleSheet, Text, TextInput, View } from 'react-native' +import { Toggle } from '../ui/toggle' +import { AlertTriangle, BatteryCharging, Bell, BellRing, Bot, Cable, Check, ChevronRight, Copy, Download, ExternalLink, Fingerprint, FolderPen, Globe, Hash, History, Info, KeyRound, Languages, Laptop, Layers, ListCollapse, LockKeyhole, LogOut, Mail, MoreVertical, Network, PanelTop, QrCode as QrCodeIcon, RotateCcw, Route, Server, Settings, ShieldAlert, ShieldCheck, SlidersHorizontal, Smartphone, Terminal, Type, UserRound, X, type LucideIcon } from 'lucide-react-native' +import { useAppStore } from '../state/store' +import { useBotTeamStore } from '../state/bot-store' +import { DsBotSettingsModal } from './bot/ds-bot-settings-screen' +import type { QrLoginStart } from '../state/store-state' +import { SOURCE_CODE_URL } from '../lib/links' +import { foregroundService } from '../services/foreground-service' +import type { OAuthProviderInfo } from '../services/api' +import { BlurHeaderFrame, Button, Field, GroupCard, GroupRow, IconButton, KeyValue, Screen, SectionTitle, TopBar } from '../ui/components' +import { useSafeAreaInsets } from 'react-native-safe-area-context' +import { transportPreferenceOptions } from '../types' +import type { DefaultPermissionPreset, LoginMethod } from '../types' +import { QrCode } from '../ui/qr-code' +import Svg, { Path, Polygon } from 'react-native-svg' +import { FISH_LOGO_PATH, FISH_LOGO_VIEWBOX } from '../ui/fish-logo' +import { GithubIcon, GoogleIcon, ZhihuIcon } from '../ui/brand-icons' +import { darkColors, floatingShadow, lightColors, radius, spacing, type } from '../ui/theme' +import { useTheme, type ThemeColors } from '../ui/theme-context' +import { useResponsiveLayout } from '../ui/responsive' +import { useThemedStyles } from '../ui/use-themed-styles' +import { easingCurve, resolveMotion } from '../ui/motion' +import { useReduceMotion } from '../ui/use-reduce-motion' +import { SheetModal } from '../ui/sheet' +import { strings as zhCN, type LanguagePreference } from '../locales/i18n' +import type { ActivityDockMode, ThemePreference, TypographyDensity } from '../ui/theme' + +/** Default DSH Remote Server; a build can override it via EXPO_PUBLIC_DSH_REMOTE_SERVER. */ +const defaultServerUrl = 'https://dsh.r2049.cn' +const updateUrl = 'https://github.com/liguobao/ds-harness-remote/releases/latest' +const releaseApiUrl = 'https://api.github.com/repos/liguobao/ds-harness-remote/releases/latest' +const developerUrl = 'https://www.zhihu.com/people/codelover' +const twitterUrl = 'https://x.com/liguobao2077' + +type SetupLoginMethod = LoginMethod + +function qrProviderFor(method: SetupLoginMethod): string | undefined { + if (method === 'oauth') return 'zhihu' + if (method === 'github-oauth') return 'github' + if (method === 'google-oauth') return 'google' + return undefined +} + +function loginMethodLabel(method?: LoginMethod): string { + if (method === 'oauth') return zhCN.setup.oauth + if (method === 'github-oauth') return zhCN.setup.githubOAuth + if (method === 'google-oauth') return 'Google' + if (method === 'password') return zhCN.setup.passwordMethod + return zhCN.common.unknown +} + +export function ServerSetupScreen({ onComplete, onBack, onMore, serverExpanded, setServerExpanded }: { onComplete: () => void; onBack?: () => void; onMore: () => void; serverExpanded: boolean; setServerExpanded: (expanded: boolean) => void }) { + const config = useAppStore(state => state.config) + const busy = useAppStore(state => state.busyAction === 'server') + const language = useAppStore(state => state.language) + const oauthBusy = useAppStore(state => state.busyAction === 'oauth') + const pendingOAuthLoginMethod = useAppStore(state => state.pendingOAuthLoginMethod) + const oauthFlowBusy = oauthBusy || pendingOAuthLoginMethod !== undefined + const selectServer = useAppStore(state => state.selectServer) + const configure = useAppStore(state => state.configureServer) + const startOAuth = useAppStore(state => state.startOAuth) + const startGithubOAuth = useAppStore(state => state.startGithubOAuth) + const startGoogleOAuth = useAppStore(state => state.startGoogleOAuth) + const listLoginProviders = useAppStore(state => state.listLoginProviders) + const listQrProviders = useAppStore(state => state.listQrProviders) + const startQrLogin = useAppStore(state => state.startQrLogin) + const pollQrLogin = useAppStore(state => state.pollQrLogin) + const completeQrLogin = useAppStore(state => state.completeQrLogin) + const [serverUrl, setServerUrl] = useState(config?.baseUrl ?? process.env.EXPO_PUBLIC_DSH_REMOTE_SERVER ?? defaultServerUrl) + const [serverDraft, setServerDraft] = useState(serverUrl) + const [serverError, setServerError] = useState() + const serverDirty = serverDraft.trim() !== serverUrl + const [email, setEmail] = useState('') + const [password, setPassword] = useState('') + const [showPassword, setShowPassword] = useState(false) + const preferredLoginMethod: SetupLoginMethod = language.startsWith('zh-') ? 'oauth' : 'google-oauth' + const [loginMethod, setLoginMethod] = useState(preferredLoginMethod) + const [showQr, setShowQr] = useState(false) + const [loginProviders, setLoginProviders] = useState([]) + const [providersPhase, setProvidersPhase] = useState<'loading' | 'ready' | 'failed'>('loading') + const [providerReload, setProviderReload] = useState(0) + const availableMethods: SetupLoginMethod[] = ([preferredLoginMethod, 'oauth', 'github-oauth', 'google-oauth'] as const) + .filter((method, index, methods) => methods.indexOf(method) === index) + .filter(method => loginProviders.some(provider => provider.id === qrProviderFor(method))) + availableMethods.push('password') + const supportsQrAny = loginProviders.some(provider => provider.qrStartUrl !== undefined && availableMethods.some(method => qrProviderFor(method) === provider.id)) + + const [qrLogin, setQrLogin] = useState() + const [qrPhase, setQrPhase] = useState<'idle' | 'loading' | 'waiting' | 'expired' | 'unsupported' | 'failed'>('idle') + const qrRun = useRef(0) + const lastServerUrl = useRef(serverUrl) + // Keep navigation out of the polling effect dependencies: completing QR + // sign-in updates the store (and re-renders the app), which must not cancel + // the in-flight registration and re-poll an already-consumed one-time token. + const onCompleteRef = useRef(onComplete) + onCompleteRef.current = onComplete + const qrCompleted = useRef(false) + const mounted = useRef(true) + useEffect(() => { + mounted.current = true + return () => { mounted.current = false } + }, []) + const { width, height, sheetMaxHeight } = useResponsiveLayout() + // Give tablets a larger code while keeping the same login tabs on all screens. + const largeScreen = Math.min(width, height) >= 600 + const { colors } = useTheme() + const styles = useThemedStyles(createStyles) + + useEffect(() => { + let cancelled = false + qrRun.current += 1 + setQrLogin(undefined) + setShowQr(false) + setLoginProviders([]) + setProvidersPhase('loading') + void listLoginProviders(serverUrl).then(result => { + if (cancelled) return + if (result === undefined) { + qrRun.current += 1 + setProvidersPhase('failed') + setLoginMethod('password') + setShowPassword(false) + setShowQr(false) + setQrLogin(undefined) + setQrPhase('idle') + return + } + setLoginProviders(result.providers) + setProvidersPhase('ready') + const nextMethod = ([preferredLoginMethod, 'oauth', 'github-oauth', 'google-oauth'] as const) + .find(method => result.providers.some(provider => provider.id === qrProviderFor(method))) ?? 'password' + setLoginMethod(nextMethod) + setShowPassword(nextMethod === 'password') + setShowQr(false) + }).catch(() => { + if (cancelled) return + qrRun.current += 1 + setProvidersPhase('failed') + setLoginMethod('password') + setShowPassword(false) + setShowQr(false) + setQrLogin(undefined) + setQrPhase('idle') + }) + return () => { cancelled = true } + }, [serverUrl, providerReload, listLoginProviders, preferredLoginMethod, largeScreen]) + + const closeServerEditor = () => { + if (busy) return + setServerDraft(serverUrl) + setServerError(undefined) + setServerExpanded(false) + } + + const saveServer = async () => { + setServerError(undefined) + const saved = await selectServer(serverDraft) + if (saved === undefined) { + setServerError(useAppStore.getState().error ?? zhCN.tools.failed) + return + } + setServerUrl(saved) + setServerDraft(saved) + setProviderReload(value => value + 1) + setPassword('') + setServerExpanded(false) + } + + const submit = async () => { + if (serverDirty) return + if (await configure(serverUrl, email, password)) onComplete() + } + + const signInWithZhihu = async () => { + if (serverDirty) return + const url = await startOAuth(serverUrl) + if (url === undefined) return + if (Platform.OS === 'android') { + try { + // Zhihu's hybrid route takes zh_url; an unknown route only opens its home screen. + // Keep the server OAuth entry and nested return_to intact. + await IntentLauncher.startActivityAsync('android.intent.action.VIEW', { + data: `zhihu://hybrid?zh_url=${encodeURIComponent(url)}`, + packageName: 'com.zhihu.android', + }) + return + } catch { + // Zhihu may be missing or unable to handle this link; use the browser. + } + } + await Linking.openURL(url) + } + + const signInWithGithub = async () => { + if (serverDirty) return + const url = await startGithubOAuth(serverUrl) + if (url !== undefined) await Linking.openURL(url) + } + + const signInWithGoogle = async () => { + if (serverDirty) return + const url = await startGoogleOAuth(serverUrl) + if (url !== undefined) await Linking.openURL(url) + } + + const canSubmit = email.trim().length > 0 && password.length > 0 + + const startQrFor = async (provider: OAuthProviderInfo, run: number) => { + qrCompleted.current = false + setQrPhase('loading') + setQrLogin(undefined) + const started = await startQrLogin(serverUrl, provider.id) + if (run !== qrRun.current) return + if (started === undefined) { + setQrPhase('failed') + return + } + setQrLogin(started) + setQrPhase('waiting') + } + + const refreshQr = async (method = loginMethod) => { + if (serverDirty) return + const run = ++qrRun.current + qrCompleted.current = false + setQrPhase('loading') + setQrLogin(undefined) + const result = await listQrProviders(serverUrl) + if (run !== qrRun.current) return + if (result === undefined) { + setQrPhase('failed') + return + } + const preferred = result.providers.find(provider => provider.id === qrProviderFor(method)) + if (preferred === undefined) { + setQrPhase('unsupported') + return + } + await startQrFor(preferred, run) + } + + // Changing the Server invalidates every provider and QR session on screen. + useEffect(() => { + if (lastServerUrl.current === serverUrl) return + lastServerUrl.current = serverUrl + qrRun.current += 1 + qrCompleted.current = false + setShowQr(false) + setQrLogin(undefined) + setQrPhase('idle') + }, [serverUrl]) + + // Poll only the selected provider while its QR panel is visible. + useEffect(() => { + if (serverDirty || !showQr || qrLogin === undefined || qrLogin.provider.id !== qrProviderFor(loginMethod) || qrCompleted.current) return + let cancelled = false + let timer: ReturnType | undefined + let failures = 0 + const poll = async () => { + if (cancelled || qrCompleted.current) return + const result = await pollQrLogin(qrLogin.baseUrl, qrLogin.session.qrId) + if (cancelled || qrCompleted.current) return + if (result === undefined) { + failures += 1 + if (failures >= 5) { + setQrPhase('failed') + return + } + timer = setTimeout(() => void poll(), 3000) + return + } + failures = 0 + if (result.status === 'expired') { + setQrPhase('expired') + return + } + if (result.status === 'complete') { + // The one-time token can only be claimed once. From here on the app + // must not poll again while device registration is in flight; the + // registration also re-renders the app, so navigation is read from a + // ref instead of being an effect dependency. + qrCompleted.current = true + const method = loginMethod + if (method === 'password') return + const ok = await completeQrLogin(qrLogin.baseUrl, result.token, method) + if (ok) { + // Finish navigation even if this render's tab was switched while the + // registration was in flight; the account is already signed in. + if (mounted.current) onCompleteRef.current() + } else { + qrCompleted.current = false + if (mounted.current && !cancelled) setQrPhase('failed') + } + return + } + timer = setTimeout(() => void poll(), 2000) + } + timer = setTimeout(() => void poll(), 1200) + return () => { + cancelled = true + if (timer !== undefined) clearTimeout(timer) + } + }, [completeQrLogin, loginMethod, pollQrLogin, qrLogin, showQr, serverDirty]) + + const chooseLoginMethod = (method: SetupLoginMethod) => { + if (method === loginMethod) return + qrRun.current += 1 + setLoginMethod(method) + setQrLogin(undefined) + setQrPhase('idle') + if (method === 'password') { + setShowQr(false) + setShowPassword(true) + } + else if (showQr) void refreshQr(method) + } + + const qrMethods = availableMethods.filter(method => loginProviders.some(provider => provider.id === qrProviderFor(method) && provider.qrStartUrl !== undefined)) + const oauthMethods = availableMethods.filter(method => method !== 'password') + + const signInWithProvider = (method: SetupLoginMethod) => { + if (showQr) { + qrRun.current += 1 + setShowQr(false) + setQrLogin(undefined) + setQrPhase('idle') + } + setLoginMethod(method) + setShowPassword(false) + if (method === 'oauth') void signInWithZhihu() + else if (method === 'github-oauth') void signInWithGithub() + else if (method === 'google-oauth') void signInWithGoogle() + } + + const closeQr = () => { + qrRun.current += 1 + setShowQr(false) + setQrLogin(undefined) + setQrPhase('idle') + } + + const openQr = () => { + const method = qrMethods.includes(loginMethod) ? loginMethod : qrMethods[0] + if (method === undefined) return + setLoginMethod(method) + setShowPassword(false) + setShowQr(true) + void refreshQr(method) + } + + // Third-party sign-in is the primary path; email is a collapsed fallback + // (the Server has no email sign-up). QR is offered on large screens only. + const qrVisible = largeScreen && showQr + const emailVisible = showPassword || (providersPhase === 'ready' && oauthMethods.length === 0) + const controlsDisabled = busy || oauthBusy || serverDirty + + const providerIcon = (method: SetupLoginMethod, size = 22) => method === 'oauth' + ? + : method === 'github-oauth' + ? + : + + const providerLabel = (method: SetupLoginMethod) => method === 'oauth' + ? zhCN.setup.zhihu + : method === 'github-oauth' ? zhCN.setup.github : zhCN.setup.google + + const providerShortName = (method: SetupLoginMethod) => method === 'oauth' + ? zhCN.setup.oauth + : method === 'github-oauth' ? zhCN.setup.githubOAuth : 'Google' + + const qrContent = !qrVisible ? null : ( + + {zhCN.setup.qrScanTitle} + {qrMethods.length > 1 && ( + + {qrMethods.map(method => ( + chooseLoginMethod(method)} + style={[styles.qrSegment, loginMethod === method && styles.segmentButtonActive]} + > + {providerIcon(method, 16)} + {providerShortName(method)} + + ))} + + )} + + {qrPhase === 'waiting' && qrLogin !== undefined + ? + : qrPhase === 'loading' || qrPhase === 'idle' + ? + : {qrPhase === 'unsupported' ? zhCN.setup.qrUnsupported : qrPhase === 'expired' ? zhCN.setup.qrExpired : zhCN.setup.qrFailed}} + + {zhCN.setup.qrScanHint} + + + {zhCN.common.back} + + void refreshQr()} + style={styles.textLink} + > + {zhCN.setup.qrRefresh} + + + + ) + + const emailContent = ( + + + { if (canSubmit) void submit() }} + placeholder={zhCN.setup.passwordPlaceholder} + placeholderTextColor={colors.muted} + accessibilityLabel={zhCN.setup.password} + /> + void submit()} + style={({ pressed }) => [styles.emailSubmit, canSubmit && styles.emailSubmitReady, pressed && styles.providerButtonPressed]} + > + {busy + ? + : {zhCN.setup.title}} + + {zhCN.setup.passwordHint} + + ) + + const whaleWidth = largeScreen ? 168 : 128 + + return ( + + } />}> + setProviderReload(value => value + 1)}> + + + + + + DSH REMOTE + + {zhCN.setup.lead} + + + + {providersPhase === 'loading' + ? + : qrVisible + ? qrContent + : <> + {providersPhase === 'ready' && oauthMethods.map(method => { + const preparing = oauthBusy && loginMethod === method + return ( + signInWithProvider(method)} + style={({ pressed }) => [styles.providerButton, pressed && styles.providerButtonPressed, controlsDisabled && !preparing && styles.providerButtonDisabled]} + > + + {preparing ? : providerIcon(method)} + + {providerLabel(method)} + + ) + })} + {providersPhase === 'ready' && oauthMethods.length > 0 && ( + {zhCN.setup.oauthHint} + )} + {providersPhase === 'failed' && ( +