Skip to content

DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.

15.3 KB
Raw Blame
import type { Edge } from 'react-native-safe-area-context'
import type { ShouldStartLoadRequest, WebViewMessageEvent } from 'react-native-webview/lib/WebViewTypes'
import type { NotificationFocus } from '@/store/modules/connection'
import type { BridgeAddress } from '@/utils/bridge-protocol'
import { useWhenever } from '@reause/core'
import { randomUUID } from 'expo-crypto'
import { useNavigation } from 'expo-router'
import { Button } from 'heroui-native/button'
import { useThemeColor } from 'heroui-native/hooks'
import { useEffect, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { If, Then } from 'react-if-lite'
import { BackHandler, Dimensions, Keyboard, Linking, Modal, Platform, Pressable, Text, View } from 'react-native'
import { ArrowLeft, Hand } from 'react-native-lucide'
import { SafeAreaView } from 'react-native-safe-area-context'
import { WebView } from 'react-native-webview'
import { Uniwind } from 'uniwind'
import { useStore } from 'valtio-define'
import { BreathingLight } from '@/components/breathing-light'
import { Logo, Wordmark } from '@/components/icons'
import { ACCESS_LOGIN_PATH, ACCESS_TEAM_DOMAIN_SUFFIX, SESSION_FORGET_TIMEOUT_MS, WEBVIEW_LOAD_TIMEOUT_MS } from '@/config/constants'
import { useAppState } from '@/hooks/use-app-state'
import { requestNotificationAccess, sendNativeNotification } from '@/hooks/use-notifications'
import { connection } from '@/store/modules/connection'
import { connectAddress, refreshHealth } from '@/store/modules/connection/runtime'
import { buildConnectUrl, isTrustedOrigin } from '@/utils/bridge-protocol'
import { createNotificationShim, keyboardHeightScript, nativeMessageScript, parseNativeMessage } from '@/utils/webview-bridge'

export function BridgeWebView({ address, generation }: { address: BridgeAddress, generation: number }) {
  const ref = useRef<WebView>(null)
  const { t } = useTranslation()
  const [nonce] = useState(randomUUID)
  const [source] = useState(() => ({
    uri: !address.token && !connection.tokens[address.id] && !connection.history.some(entry => entry.id === address.id)
      ? new URL('/?pair=1', address.id).toString()
      : buildConnectUrl(address),
  }))
  const mainUrlRef = useRef(source.uri)
  const canGoBackRef = useRef(false)
  const focusRequestRef = useRef<{ requestId: string, focus: NotificationFocus } | null>(null)
  const documentReadyRef = useRef(false)
  const redirectableRef = useRef(true)
  const authenticatingRef = useRef(false)
  const accessHistoryRef = useRef(false)
  const clearedHistoryRef = useRef(false)
  const [documentReady, setDocumentReady] = useState(false)
  const [authenticating, setAuthenticating] = useState(false)
  const [loadingTimedOut, setLoadingTimedOut] = useState(false)
  const [documentGeneration, setDocumentGeneration] = useState(0)
  const state = useStore(connection)
  const navigation = useNavigation()
  const appState = useAppState()
  const background = useThemeColor('background')
  const edges: Edge[] = ['top']
  if (Platform.OS !== 'ios')
    edges.push('bottom')
  const shim = createNotificationShim(address.id, nonce, edges)
  // keep:effect The WebView keeps its frame under the iOS keyboard, so the page has to reserve the covered height itself; the keyboard top comes from the frame event so docked, resized and floating keyboards all report their real overlap.
  useEffect(() => {
    if (Platform.OS !== 'ios')
      return
    const subscription = Keyboard.addListener('keyboardWillChangeFrame', (event) => {
      const covered = Dimensions.get('window').height - event.endCoordinates.screenY
      ref.current?.injectJavaScript(keyboardHeightScript(address.id, covered))
    })
    return () => subscription.remove()
  }, [address.id])
  // keep:effect Mirror native visibility into the authenticated loaded document.
  useEffect(() => {
    if (!documentReady || state.loadError)
      return
    ref.current?.injectJavaScript(nativeMessageScript(address.id, nonce, {
      type: 'dsh://visibility-state',
      hidden: appState !== 'active',
    }))
  }, [address.id, appState, documentReady, nonce, state.loadError])
  // keep:whenever Request native notification access as soon as a verified document reaches the foreground.
  useWhenever(documentReady && !state.loadError && appState === 'active', () => void requestNotificationAccess())
  // keep:effect Keep notification focus pending until the loaded page acknowledges selection.
  useEffect(() => {
    const focus = state.pendingFocus
    if (!documentReady || state.loadError || focus?.origin !== address.id || appState !== 'active')
      return
    const requestId = randomUUID()
    const webView = ref.current
    focusRequestRef.current = { requestId, focus }
    webView?.injectJavaScript(nativeMessageScript(address.id, nonce, {
      type: 'dsh://focus-session',
      requestId,
      sessionId: focus.sessionId,
      title: focus.title,
      tag: focus.tag,
    }))
    connection.setDrawerOpen(false)
    return () => {
      webView?.injectJavaScript(nativeMessageScript(address.id, nonce, { type: 'dsh://cancel-focus', requestId }))
      if (focusRequestRef.current?.requestId === requestId)
        focusRequestRef.current = null
    }
  }, [address.id, appState, documentReady, nonce, state.loadError, state.pendingFocus, state.focusGeneration])
  // keep:effect Offer recovery for a slow document without rejecting its later authenticated readiness.
  useEffect(() => {
    if (documentReady || state.loadError || authenticating)
      return
    const timeout = setTimeout(setLoadingTimedOut, WEBVIEW_LOAD_TIMEOUT_MS, true)
    return () => clearTimeout(timeout)
  }, [authenticating, documentGeneration, documentReady, state.loadError])
  // keep:effect Bound cookie clearing to this WebView's lifetime before removing its connection.
  useEffect(() => {
    if (state.forgettingOrigin !== address.id)
      return
    ref.current?.injectJavaScript(nativeMessageScript(address.id, nonce, { type: 'dsh://forget-session' }))
    const timeout = setTimeout(() => {
      if (generation === connection.viewGeneration && connection.forgettingOrigin === address.id)
        connection.remove(address.id)
    }, SESSION_FORGET_TIMEOUT_MS)
    return () => clearTimeout(timeout)
  }, [address.id, generation, nonce, state.forgettingOrigin])
  // keep:effect Route Android back to WebView history without consuming an open drawer's back event.
  useEffect(() => {
    const subscription = BackHandler.addEventListener('hardwareBackPress', () => {
      if (!navigation.isFocused() || connection.drawerOpen || !canGoBackRef.current)
        return false
      ref.current?.goBack()
      return true
    })
    return () => subscription.remove()
  }, [navigation])
  async function openExternal(raw: string) {
    try {
      const url = new URL(raw)
      if ((url.protocol === 'http:' || url.protocol === 'https:') && !url.username && !url.password)
        await Linking.openURL(url.toString())
    }
    catch {
      connection.setNotice(t('connection.connectionFailed'))
    }
  }
  function authenticate(active: boolean) {
    authenticatingRef.current = active
    setAuthenticating(active)
    if (!active)
      return
    accessHistoryRef.current = true
    setLoadingTimedOut(false)
  }
  function allowNavigation(request: ShouldStartLoadRequest): boolean {
    if (request.isTopFrame === false)
      return true
    if (isTrustedOrigin(request.url, address.id)) {
      mainUrlRef.current = request.url
      redirectableRef.current = true
      authenticate(false)
      return true
    }
    if (request.url === 'about:blank')
      return true
    const redirected = redirectableRef.current
    redirectableRef.current = false
    const url = URL.canParse(request.url) ? new URL(request.url) : null
    // Why: only our own document's server redirect may open Cloudflare Access login in-app; tapped links still leave for the system browser.
    if (url?.protocol === 'https:' && !url.username && !url.password
      && (authenticatingRef.current || (redirected && url.hostname.endsWith(ACCESS_TEAM_DOMAIN_SUFFIX) && url.pathname.startsWith(ACCESS_LOGIN_PATH)))) {
      authenticate(true)
      return true
    }
    void openExternal(request.url)
    return false
  }
  function handleMessage({ nativeEvent }: WebViewMessageEvent) {
    const message = parseNativeMessage(nativeEvent.data, nativeEvent.url, address.id, nonce)
    if (!message || generation !== connection.viewGeneration)
      return
    if (message.type === 'dsh://session-forgotten') {
      if (connection.forgettingOrigin === address.id)
        connection.remove(address.id)
      return
    }
    if (connection.forgettingOrigin === address.id)
      return
    if (message.type === 'dsh://bridge-ready') {
      if (connection.loadError)
        return
      documentReadyRef.current = true
      setDocumentReady(true)
      setLoadingTimedOut(false)
      connection.markLoaded(generation)
      return
    }
    if (!documentReadyRef.current || connection.loadError)
      return
    if (message.type === 'dsh://device-session') {
      connection.rememberDeviceSession(address.id, message.token, generation)
      return
    }
    if (message.type === 'dsh://theme-state') {
      Uniwind.setTheme(message.theme)
      return
    }
    if (message.type === 'dsh://focus-result') {
      const request = focusRequestRef.current
      const pending = connection.pendingFocus
      if (!request || request.requestId !== message.requestId || !pending
        || pending.origin !== request.focus.origin || pending.sessionId !== request.focus.sessionId
        || pending.tag !== request.focus.tag || pending.title !== request.focus.title) {
        return
      }
      connection.queueFocus(null)
      if (!message.handled)
        connection.setNotice(t('connection.focusFailed'))
      return
    }
    void sendNativeNotification(message, address.id)
  }
  function loadingStarted(url: string, loading: boolean) {
    if (generation !== connection.viewGeneration || !isTrustedOrigin(url, address.id))
      return
    mainUrlRef.current = url
    authenticate(false)
    if (!loading)
      return
    focusRequestRef.current = null
    documentReadyRef.current = false
    setDocumentReady(false)
    setLoadingTimedOut(false)
    setDocumentGeneration(value => value + 1)
  }
  function loaded(url: string) {
    if (!isTrustedOrigin(url, address.id))
      return
    redirectableRef.current = false
    ref.current?.injectJavaScript(shim)
    if (!accessHistoryRef.current)
      return
    // Why: Android Back must not re-enter Access/IdP pages outside the login; this finish event's canGoBack predates the clear.
    accessHistoryRef.current = false
    clearedHistoryRef.current = true
    ref.current?.clearHistory?.()
  }
  function openDrawer() {
    connection.dismissHint()
    connection.setDrawerOpen(true)
    void refreshHealth()
  }
  return (
    <SafeAreaView style={{ flex: 1, backgroundColor: background }} edges={edges}>
      <View className="flex-1">
        <WebView
          ref={ref}
          source={source}
          style={{ flex: 1, backgroundColor: background }}
          injectedJavaScriptBeforeContentLoaded={shim}
          injectedJavaScript={shim}
          injectedJavaScriptForMainFrameOnly
          injectedJavaScriptBeforeContentLoadedForMainFrameOnly
          javaScriptEnabled
          domStorageEnabled
          sharedCookiesEnabled
          thirdPartyCookiesEnabled={false}
          allowFileAccess={false}
          allowFileAccessFromFileURLs={false}
          allowUniversalAccessFromFileURLs={false}
          mixedContentMode="never"
          originWhitelist={['*']}
          onShouldStartLoadWithRequest={allowNavigation}
          onMessage={handleMessage}
          onLoadStart={event => loadingStarted(event.nativeEvent.url, event.nativeEvent.loading)}
          onLoad={event => loaded(event.nativeEvent.url)}
          onError={() => connection.markLoadFailed(generation, t('connection.connectionFailed'))}
          onHttpError={({ nativeEvent }) => {
            if (nativeEvent.statusCode >= 400 && nativeEvent.statusCode !== 401 && nativeEvent.url === mainUrlRef.current)
              connection.markLoadFailed(generation, t('connection.connectionFailed'))
          }}
          onNavigationStateChange={(navigation) => {
            canGoBackRef.current = navigation.canGoBack && !clearedHistoryRef.current
            clearedHistoryRef.current = false
            if (isTrustedOrigin(navigation.url, address.id))
              mainUrlRef.current = navigation.url
          }}
          onOpenWindow={({ nativeEvent }) => { void openExternal(nativeEvent.targetUrl) }}
          onRenderProcessGone={() => connection.markLoadFailed(generation, t('connection.connectionFailed'))}
          onContentProcessDidTerminate={() => connection.markLoadFailed(generation, t('connection.connectionFailed'))}
        />
        <If cond={state.notice && !state.drawerOpen}>
          <Then>
            <Pressable
              className="absolute left-3 right-3 top-3 rounded-xl border border-border bg-surface px-4 py-3"
              accessibilityRole="button"
              accessibilityLabel={state.notice ?? t('connection.connectionInfo')}
              onPress={openDrawer}
            >
              <Text className="text-sm leading-6 text-warning" accessibilityLiveRegion="polite">{state.notice}</Text>
            </Pressable>
          </Then>
        </If>
        <If cond={state.loading && !loadingTimedOut && !authenticating}>
          <Then>
            <View className="absolute inset-0 items-center justify-center gap-7 bg-background px-8">
              <View className="items-center gap-3">
                <Logo />
                <Wordmark />
              </View>
              <BreathingLight />
              <Text className="text-sm text-muted" accessibilityLiveRegion="polite">{t('connection.loading')}</Text>
            </View>
          </Then>
        </If>
        <If cond={state.loadError || (loadingTimedOut && !documentReady)}>
          <Then>
            <View className="absolute inset-0 items-center justify-center gap-5 bg-background px-8">
              <Text className="text-center text-base leading-7 text-foreground" accessibilityLiveRegion="polite">{state.loadError ?? t('connection.loadingSlow')}</Text>
              <Button onPress={() => connectAddress(address)}>{t('connection.reconnect')}</Button>
              <Button variant="ghost" onPress={openDrawer}>{t('connection.connectionInfo')}</Button>
            </View>
          </Then>
        </If>
        <If cond={documentReady && state.swipeHintVisible && !state.drawerOpen}>
          <Then>
            <Modal
              transparent
              visible
              statusBarTranslucent
              navigationBarTranslucent
              onRequestClose={() => connection.dismissHint()}
            >
              <Pressable
                className="flex-1 items-center justify-center gap-5 bg-black/60"
                accessibilityRole="button"
                accessibilityLabel={t('connection.swipeAccessibility')}
                onPress={() => connection.dismissHint()}
              >
                <View className="flex-row items-center gap-3">
                  <ArrowLeft size={34} color="#ffffff" />
                  <Hand size={52} color="#ffffff" strokeWidth={1.5} />
                </View>
                <Text className="text-base font-medium text-white">{t('connection.swipeHint')}</Text>
              </Pressable>
            </Modal>
          </Then>
        </If>
      </View>
    </SafeAreaView>
  )
}