Import apps/android/App.tsx

This commit is contained in:
QQ 2026-11-17 08:24:34 +08:00
parent 7ceb6929eb
commit c78b7ec54f
1 changed files with 309 additions and 138 deletions

View File

@ -1,7 +1,7 @@
import { hydrateBrowseMemory, useBrowseMemory, browseKey, browsePreference, browseScope, saveHostMode } from './src/services/browse-memory'
import { startBrowseTracking } from './src/services/browse-tracking'
import { useEffect, useRef, useState } from 'react'
import { AppState, BackHandler, Linking, StyleSheet, Text, View } from 'react-native'
import { useEffect, useRef, useState, type ReactNode } from 'react'
import { Animated, AppState, BackHandler, Easing, Keyboard, Linking, StyleSheet, Text, View } from 'react-native'
import NetInfo from '@react-native-community/netinfo'
import { useLocales } from 'expo-localization'
import * as SplashScreen from 'expo-splash-screen'
@ -13,17 +13,31 @@ import { HostSwitcherSheet } from './src/screens/host-switcher-sheet'
import { RemoteHostsScreen } from './src/screens/remote-hosts-screen'
import { AboutScreen, DiagnosticsScreen, HomeActionsMenu, ServerSetupScreen, SettingsScreen, useStartupUpdateCheck } from './src/screens/setup-screens'
import { stopConnectionRecovery, useAppStore } from './src/state/store'
import { useBotTeamStore } from './src/state/bot-store'
import { ForegroundConnectionRecovery } from './src/services/connection-recovery'
import { resolveStartupAutoConnect } from './src/lib/auto-connect'
import {
isRouteActiveScreen,
isSheetConnectionRoute,
resolveTopLevelHardwareBack,
shouldHideSplashScreen,
shouldSuppressAutoSessionSelect,
type AppRoute,
} from './src/lib/navigation'
import {
networkRouteForNativeType,
shouldReconnectForNetworkRoute,
type NetworkRoute,
} from './src/lib/network-route'
import { Button, ErrorBanner } from './src/ui/components'
import { NavigationFocusProvider } from './src/ui/mention-popover'
import { easingCurve, motionTokens } from './src/ui/motion'
import { dismissClosingSheets } from './src/ui/sheet'
import { spacing, type } from './src/ui/theme'
import { ThemeProvider, useTheme, type ThemeColors } from './src/ui/theme-context'
import { MermaidRendererHost } from './src/ui/mermaid/mermaid-renderer'
import { AlertHost } from './src/ui/alert'
import { useReduceMotion } from './src/ui/use-reduce-motion'
import { useThemedStyles } from './src/ui/use-themed-styles'
import { strings as zhCN } from './src/locales/i18n'
import { sessionBackendFromId } from './src/lib/session-backend'
@ -31,15 +45,7 @@ import { sessionBackendFromId } from './src/lib/session-backend'
// is the only startup view; the app then enters the login or chat route.
void SplashScreen.preventAutoHideAsync().catch(() => undefined)
type Route =
| { name: 'server' }
| { name: 'remote-hosts' }
| { name: 'device'; deviceId: string }
| { name: 'connecting'; deviceId: string; sheet?: boolean; focusWorkspaceKey?: string; sessionId?: string }
| { name: 'chat'; botConversationId?: string; externalOpenRevision?: number }
| { name: 'settings' }
| { name: 'diagnostics' }
| { name: 'about' }
type Route = AppRoute
export default function App() {
const locales = useLocales()
@ -56,6 +62,7 @@ export default function App() {
<SafeAreaProvider>
<AppShell />
<MermaidRendererHost />
<AlertHost />
</SafeAreaProvider>
</ThemeProvider>
)
@ -90,6 +97,7 @@ function AppNavigator() {
const config = useAppStore(state => state.config)
const devices = useAppStore(state => state.devices)
const selectedDevice = useAppStore(state => state.selectedDevice)
const connectionPhase = useAppStore(state => state.connection.phase)
const hostScope = browseScope({ config, selectedDevice })
const botMode = useBrowseMemory(state => state.hostModes[hostScope] === 'bot')
const autoConnectHost = useBrowseMemory(state => state.autoConnectHost)
@ -101,6 +109,9 @@ function AppNavigator() {
const setOffline = useAppStore(state => state.setOffline)
const clearError = useAppStore(state => state.clearError)
const [routes, setRoutes] = useState<Route[]>([{ name: 'server' }])
const [initialRouteChosen, setInitialRouteChosen] = useState(false)
const [resolvingKnownSession, setResolvingKnownSession] = useState(false)
const [signingOut, setSigningOut] = useState(false)
const [homeMenuOpen, setHomeMenuOpen] = useState(false)
const [hostSwitcherOpen, setHostSwitcherOpen] = useState(false)
const [serverEditorOpen, setServerEditorOpen] = useState(false)
@ -116,15 +127,30 @@ function AppNavigator() {
useStartupUpdateCheck(bootPhase === 'ready')
useEffect(() => {
if (bootPhase === 'error' || (bootPhase === 'ready' && browseReady)) {
if (shouldHideSplashScreen({ bootPhase, browseReady, initialRouteChosen })) {
void SplashScreen.hideAsync().catch(() => undefined)
}
}, [bootPhase, browseReady])
}, [bootPhase, browseReady, initialRouteChosen])
const push = (next: Route) => setRoutes(current => [...current, next])
const replace = (next: Route) => setRoutes(current => [...current.slice(0, -1), next])
const pop = () => setRoutes(current => current.length > 1 ? current.slice(0, -1) : current)
const reset = (next: Route) => setRoutes([next])
const push = (next: Route) => {
Keyboard.dismiss()
dismissClosingSheets()
setRoutes(current => [...current, next])
}
const replace = (next: Route) => {
Keyboard.dismiss()
dismissClosingSheets()
setRoutes(current => [...current.slice(0, -1), next])
}
const pop = () => {
Keyboard.dismiss()
setRoutes(current => current.length > 1 ? current.slice(0, -1) : current)
}
const reset = (next: Route) => {
Keyboard.dismiss()
dismissClosingSheets()
setRoutes([next])
}
const selectOfflineTrustedDevice = (device: (typeof devices)[number], preferredSessionId?: string) => {
const state = useAppStore.getState()
@ -187,23 +213,36 @@ function AppNavigator() {
const externalOpenRevision = useRef(0)
const openKnownSession = async (id: string) => {
const revision = ++externalOpenRevision.current
const backend = sessionBackendFromId(id)
const expectedScope = browseScope(useAppStore.getState())
const isCurrent = () => revision === externalOpenRevision.current
&& browseScope(useAppStore.getState()) === expectedScope
&& useAppStore.getState().connection.phase === 'connected'
await useAppStore.getState().refreshWorkspaces(backend)
if (!isCurrent()) return
const state = useAppStore.getState(), target = state.sessions.find(item => item.sessionId === id)
if (target === undefined) {goHomeChat(); useAppStore.setState({error: zhCN.comfort.conversationMissing}); return}
const ok = await openSession(target)
if (!isCurrent()) return
if (ok && useAppStore.getState().selectedSession?.sessionId === id) {
saveHostMode(expectedScope, 'agent')
setHostSwitcherOpen(false)
reset({ name: 'chat', externalOpenRevision: revision })
} else if (routeRef.current.name === 'connecting') {
goHomeChat()
setResolvingKnownSession(true)
try {
const backend = sessionBackendFromId(id)
const expectedScope = browseScope(useAppStore.getState())
const isCurrent = () => revision === externalOpenRevision.current
&& browseScope(useAppStore.getState()) === expectedScope
&& useAppStore.getState().connection.phase === 'connected'
await useAppStore.getState().refreshWorkspaces(backend)
if (!isCurrent()) return
const state = useAppStore.getState(), target = state.sessions.find(item => item.sessionId === id)
if (target === undefined) {
setHostSwitcherOpen(false)
goHomeChat()
useAppStore.setState({ error: zhCN.comfort.conversationMissing })
return
}
const ok = await openSession(target)
if (!isCurrent()) return
if (ok && useAppStore.getState().selectedSession?.sessionId === id) {
saveHostMode(expectedScope, 'agent')
setHostSwitcherOpen(false)
reset({ name: 'chat', externalOpenRevision: revision })
} else if (routeRef.current.name === 'connecting') {
setHostSwitcherOpen(false)
goHomeChat()
}
} finally {
if (revision === externalOpenRevision.current) {
setResolvingKnownSession(false)
}
}
}
useEffect(() => {
@ -314,10 +353,12 @@ function AppNavigator() {
didChooseInitialRoute.current = true
if (config === undefined || reauthRequired) {
reset({ name: 'server' })
setInitialRouteChosen(true)
return
}
// Resolve sign-in first; the optional resume preference runs after this route.
reset({ name: 'chat' })
setInitialRouteChosen(true)
}, [bootPhase, config, reauthRequired])
// Session expired while already navigating — send the user to sign-in.
@ -331,33 +372,54 @@ function AppNavigator() {
if (route.name !== 'chat' && hostSwitcherOpen) {
setHostSwitcherOpen(false)
}
}, [route.name, hostSwitcherOpen])
if (route.name !== 'server' && homeMenuOpen) {
setHomeMenuOpen(false)
}
}, [route.name, hostSwitcherOpen, homeMenuOpen])
const backFromRemoteHosts = () => {
if (routes.length > 1) pop()
else reset({ name: 'chat' })
}
const homeMenuVisible = homeMenuOpen && route.name === 'server'
const backStateRef = useRef({
signingOut,
hostSwitcherOpen,
homeMenuOpen: homeMenuVisible,
route,
routesLength: routes.length,
})
backStateRef.current = {
signingOut,
hostSwitcherOpen,
homeMenuOpen: homeMenuVisible,
route,
routesLength: routes.length,
}
useEffect(() => {
const subscription = BackHandler.addEventListener('hardwareBackPress', () => {
if (hostSwitcherOpen) {
setHostSwitcherOpen(false)
return true
const state = backStateRef.current
const outcome = resolveTopLevelHardwareBack(state)
switch (outcome.action) {
case 'consume':
return true
case 'close-host-switcher':
setHostSwitcherOpen(false)
return true
case 'close-home-menu':
setHomeMenuOpen(false)
return true
case 'delegate':
return false
case 'pop':
pop()
return true
}
if (homeMenuOpen) {
setHomeMenuOpen(false)
return true
}
// ConnectionScreen owns hardware back (and may swallow it while connecting).
if (route.name === 'connecting') return false
if (routes.length <= 1) {
return false
}
pop()
return true
})
return () => subscription.remove()
}, [hostSwitcherOpen, homeMenuOpen, route.name, routes])
}, [])
useEffect(() => {
const recovery = new ForegroundConnectionRecovery(
@ -411,99 +473,153 @@ function AppNavigator() {
backgrounded.current = false
// Keep healthy carriers, but verify an encrypted round trip before
// trusting a socket that merely remained locally "open" while asleep.
void useAppStore.getState().resumeConnection()
void useAppStore.getState().resumeConnection().then(() => {
if (useAppStore.getState().connection.phase === 'connected' && useBotTeamStore.getState().state !== undefined) {
void useBotTeamStore.getState().refreshLive({ forceFull: true })
}
})
})
return () => subscription.remove()
}, [reconnect])
if (bootPhase === 'error') return <BootError onRetry={() => void bootstrap()} message={error} />
if (bootPhase === 'loading' || !browseReady) return null
const deviceForRoute = route.name === 'device' || route.name === 'connecting'
? devices.find(device => device.deviceId === route.deviceId)
?? (selectedDevice?.deviceId === route.deviceId ? selectedDevice : undefined)
const resolveDeviceForRoute = (target: Route) => target.name === 'device' || target.name === 'connecting'
? devices.find(device => device.deviceId === target.deviceId)
?? (selectedDevice?.deviceId === target.deviceId ? selectedDevice : undefined)
: undefined
const startupConnection = route.name === 'connecting' && route.sheet === true
const homeMenuVisible = homeMenuOpen && route.name === 'server'
const deviceForRoute = resolveDeviceForRoute(route)
const startupConnection = isSheetConnectionRoute(route)
useEffect(() => {
if (bootPhase === 'ready' && startupConnection && deviceForRoute === undefined) {
pop()
}
}, [bootPhase, startupConnection, deviceForRoute])
if (bootPhase === 'error') return <BootError onRetry={() => void bootstrap()} message={error} />
if (bootPhase === 'loading' || !browseReady || !initialRouteChosen) return null
const overlayVisible = hostSwitcherOpen || homeMenuVisible || (startupConnection && deviceForRoute !== undefined)
const suppressAutoSelect = shouldSuppressAutoSessionSelect({
botMode,
routeName: route.name,
connectionPhase,
resolvingKnownSession: resolvingKnownSession || pendingConversation !== undefined,
})
const renderRouteScreen = (entry: Route, index: number) => {
const active = isRouteActiveScreen(routes, index, overlayVisible)
switch (entry.name) {
case 'server':
return (
<ServerSetupScreen
serverExpanded={serverEditorOpen}
setServerExpanded={setServerEditorOpen}
onMore={openHomeMenu}
onBack={routes.length > 1 ? pop : undefined}
onComplete={() => {
autoRestored.current = false
reset({ name: 'chat' })
}}
/>
)
case 'remote-hosts':
return (
<RemoteHostsScreen
onBack={backFromRemoteHosts}
onSelectDevice={openDevice}
onOpenDeviceDetail={device => push({ name: 'device', deviceId: device.deviceId })}
onSignedOut={() => reset({ name: 'server' })}
autoConnectHost={autoConnectHost}
onToggleAutoConnectHost={value => browsePreference({ autoConnectHost: value })}
/>
)
case 'connecting': {
const entryDevice = resolveDeviceForRoute(entry)
if (entryDevice === undefined) return <MissingRoute onBack={() => reset({ name: 'chat' })} />
return (
<ConnectionScreen
device={entryDevice}
onBack={() => {
if (routes.length > 1) pop()
else reset({ name: 'chat' })
}}
onConnected={() => {
if (entry.sessionId !== undefined) void openKnownSession(entry.sessionId)
else if (entry.focusWorkspaceKey === undefined) goHomeChat()
else void openShortcutSession(entry.focusWorkspaceKey)
}}
/>
)
}
case 'device': {
const entryDevice = resolveDeviceForRoute(entry)
if (entryDevice === undefined) return <MissingRoute onBack={() => reset({ name: 'chat' })} />
return (
<DeviceDetailScreen
device={entryDevice}
onBack={pop}
onConnect={() => replace({ name: 'connecting', deviceId: entryDevice.deviceId })}
onWorkspaces={goHomeChat}
/>
)
}
case 'chat':
return (
<ChatScreen
active={active}
suppressAutoSelect={suppressAutoSelect}
botMode={botMode}
externalOpenRevision={entry.externalOpenRevision}
botConversationId={entry.botConversationId}
onBotModeChange={next => {
saveHostMode(hostScope, next ? 'bot' : 'agent')
setRoutes(current => current.map(item => item.name === 'chat' ? { ...item, botConversationId: undefined } : item))
}}
onSelectBot={botConversationId => setRoutes(current => current.map(item => item.name === 'chat' ? { ...item, botConversationId } : item))}
onBack={pop}
onOpenHostSwitcher={() => setHostSwitcherOpen(true)}
onOpenSettings={() => push({ name: 'settings' })}
onOpenAbout={() => push({ name: 'about' })}
onOpenDeviceInfo={() => {
if (selectedDevice !== undefined) push({ name: 'device', deviceId: selectedDevice.deviceId })
else setHostSwitcherOpen(true)
}}
/>
)
case 'settings':
return (
<SettingsScreen
active={active}
onBack={pop}
onSigningOutChange={setSigningOut}
onReset={() => reset({ name: 'server' })}
onOpenDiagnostics={() => push({ name: 'diagnostics' })}
onOpenAbout={() => push({ name: 'about' })}
/>
)
case 'diagnostics':
return <DiagnosticsScreen onBack={pop} />
case 'about':
return <AboutScreen onBack={pop} />
}
}
return (
<View style={styles.flex}>
{route.name === 'server' && (
<ServerSetupScreen
serverExpanded={serverEditorOpen}
setServerExpanded={setServerEditorOpen}
onMore={openHomeMenu}
onBack={routes.length > 1 ? pop : undefined}
onComplete={() => {
autoRestored.current = false
reset({ name: 'chat' })
}}
/>
)}
{route.name === 'remote-hosts' && (
<RemoteHostsScreen
onBack={backFromRemoteHosts}
onSelectDevice={openDevice}
onOpenDeviceDetail={device => push({ name: 'device', deviceId: device.deviceId })}
onSignedOut={() => reset({ name: 'server' })}
autoConnectHost={autoConnectHost}
onToggleAutoConnectHost={value => browsePreference({ autoConnectHost: value })}
/>
)}
{route.name === 'connecting' && !startupConnection && deviceForRoute !== undefined && (
<ConnectionScreen
device={deviceForRoute}
onBack={() => {
if (routes.length > 1) pop()
else reset({ name: 'chat' })
}}
onConnected={() => {
if (route.sessionId !== undefined) void openKnownSession(route.sessionId)
else if (route.focusWorkspaceKey === undefined) goHomeChat()
else void openShortcutSession(route.focusWorkspaceKey)
}}
/>
)}
{route.name === 'connecting' && deviceForRoute === undefined && <MissingRoute onBack={() => reset({ name: 'chat' })} />}
{route.name === 'device' && deviceForRoute !== undefined && (
<DeviceDetailScreen
device={deviceForRoute}
onBack={pop}
onConnect={() => replace({ name: 'connecting', deviceId: deviceForRoute.deviceId })}
onWorkspaces={goHomeChat}
/>
)}
{route.name === 'device' && deviceForRoute === undefined && <MissingRoute onBack={() => reset({ name: 'chat' })} />}
{(route.name === 'chat' || startupConnection) && (
<ChatScreen
botMode={botMode}
externalOpenRevision={route.name === 'chat' ? route.externalOpenRevision : undefined}
botConversationId={route.name === 'chat' ? route.botConversationId : undefined}
onBotModeChange={next => {
saveHostMode(hostScope, next ? 'bot' : 'agent')
setRoutes(current => current.map((entry, index) => index === current.length - 1 && entry.name === 'chat' ? { ...entry, botConversationId: undefined } : entry))
}}
onSelectBot={botConversationId => setRoutes(current => current.map((entry, index) => index === current.length - 1 && entry.name === 'chat' ? { ...entry, botConversationId } : entry))}
onBack={pop}
onOpenHostSwitcher={() => setHostSwitcherOpen(true)}
onOpenSettings={() => push({ name: 'settings' })}
onOpenAbout={() => push({ name: 'about' })}
onOpenDeviceInfo={() => {
if (selectedDevice !== undefined) push({ name: 'device', deviceId: selectedDevice.deviceId })
else setHostSwitcherOpen(true)
}}
/>
)}
{route.name === 'settings' && (
<SettingsScreen
onBack={pop}
onReset={() => reset({ name: 'server' })}
onOpenDiagnostics={() => push({ name: 'diagnostics' })}
onOpenAbout={() => push({ name: 'about' })}
/>
)}
{route.name === 'diagnostics' && <DiagnosticsScreen onBack={pop} />}
{route.name === 'about' && <AboutScreen onBack={pop} />}
{routes.map((entry, index) => {
if (isSheetConnectionRoute(entry)) return null
const active = isRouteActiveScreen(routes, index, overlayVisible)
return (
<RouteLayer
key={`${entry.name}:${index}`}
index={index}
animateEnter={index > 0}
active={active}
>
{renderRouteScreen(entry, index)}
</RouteLayer>
)
})}
{error !== undefined && route.name !== 'connecting' && route.name !== 'diagnostics' && (
<View pointerEvents="box-none" style={[styles.globalError, { top: insets.top }]}>
<ErrorBanner message={error} onDismiss={clearError} />
@ -517,9 +633,12 @@ function AppNavigator() {
if (startupConnection) pop()
}}
onConnected={() => {
if (route.name === 'connecting' && route.sessionId !== undefined) {
void openKnownSession(route.sessionId)
return
}
setHostSwitcherOpen(false)
if (route.name === 'connecting' && route.sessionId !== undefined) void openKnownSession(route.sessionId)
else goHomeChat()
goHomeChat()
}}
onSelectDevice={device => {
setHostSwitcherOpen(false)
@ -550,6 +669,58 @@ function AppNavigator() {
)
}
function RouteLayer({
index,
animateEnter,
active,
children,
}: {
index: number
animateEnter: boolean
active: boolean
children: ReactNode
}) {
const { colors } = useTheme()
const reduceMotion = useReduceMotion()
const progress = useRef(new Animated.Value(animateEnter ? 0 : 1)).current
useEffect(() => {
if (!animateEnter) return
progress.setValue(0)
const animation = Animated.timing(progress, {
toValue: 1,
duration: reduceMotion ? motionTokens.duration.reduced : 220,
easing: Easing.bezier(...easingCurve('expand')),
useNativeDriver: true,
})
animation.start()
return () => animation.stop()
}, [animateEnter, progress, reduceMotion])
const translateX = animateEnter && !reduceMotion
? progress.interpolate({ inputRange: [0, 1], outputRange: [24, 0] })
: 0
return (
<Animated.View
pointerEvents={active ? 'auto' : 'none'}
accessibilityElementsHidden={!active}
importantForAccessibility={active ? 'auto' : 'no-hide-descendants'}
style={[
StyleSheet.absoluteFill,
{
backgroundColor: colors.background,
zIndex: index + 1,
elevation: (index + 1) * 16,
transform: [{ translateX }],
},
]}
>
<NavigationFocusProvider value={active}>{children}</NavigationFocusProvider>
</Animated.View>
)
}
function LoadingScreen() {
return null
}
@ -584,7 +755,7 @@ function createStyles(colors: ThemeColors) {
return StyleSheet.create({
safeArea: { flex: 1, backgroundColor: colors.background },
flex: { flex: 1 },
globalError: { position: 'absolute', left: 0, right: 0, zIndex: 10 },
globalError: { position: 'absolute', left: 0, right: 0, zIndex: 1000, elevation: 1000 },
center: { flex: 1, alignItems: 'center', justifyContent: 'center', paddingHorizontal: spacing.xl, backgroundColor: colors.background },
loadingTitle: { ...type.title, color: colors.ink, textAlign: 'center' },
loadingBody: { ...type.body, color: colors.muted, textAlign: 'center', marginTop: spacing.xs },