Skip to content

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

fix(mobile): keep the composer above the iOS keyboard (#1186) (#1188)

Hairy28097c376e10
diff --git a/packages/dsh-tauri-mobile-ui/src/client/register/keyboard.test.ts b/packages/dsh-tauri-mobile-ui/src/client/register/keyboard.test.ts
index 5429df10..11e81445 100644
--- a/packages/dsh-tauri-mobile-ui/src/client/register/keyboard.test.ts
+++ b/packages/dsh-tauri-mobile-ui/src/client/register/keyboard.test.ts
@@ -11,8 +11,14 @@ vi.mock('dsh-tauri/client', () => ({
let controller: ReturnType<typeof createLifecycleController>
let editor: HTMLElement
+let viewport: FakeViewport
const labels: Record<string, string> = { 'input.send': '发送消息', 'input.send.queue': '排队发送', 'input.send.steer': '插话发送' }
+class FakeViewport extends EventTarget {
+ height = window.innerHeight
+ scale = 1
+}
+
function touch(type: string, x: number, y: number, target: Element = document.querySelector('[data-conversation-scroll]')!) {
const event = new Event(type, { bubbles: true, cancelable: true })
Object.defineProperty(event, 'touches', { value: [{ identifier: 1, clientX: x, clientY: y }] })
@@ -25,6 +31,8 @@ beforeEach(() => {
document.body.innerHTML = '<div data-conversation-scroll><p>Message</p><div data-composer-seat><textarea></textarea><button aria-label="发送消息"><svg></svg></button></div></div><input id="setting">'
editor = document.querySelector('textarea')!
editor.focus()
+ viewport = new FakeViewport()
+ Object.defineProperty(window, 'visualViewport', { configurable: true, value: viewport })
controller = createLifecycleController()
const register = registerMobileKeyboard as unknown as (controller: unknown, ctx: unknown) => void
register(controller, { locale: { bind: () => (key: string) => labels[key] ?? key } })
@@ -32,6 +40,8 @@ beforeEach(() => {
afterEach(() => {
controller.dispose()
+ Reflect.deleteProperty(window, 'visualViewport')
+ document.documentElement.removeAttribute('style')
document.body.innerHTML = ''
vi.restoreAllMocks()
})
@@ -96,3 +106,38 @@ describe('mobile composer keyboard dismissal', () => {
expect(document.activeElement).toBe(editor)
})
})
+
+describe('mobile keyboard viewport fit', () => {
+ const reserved = () => document.documentElement.style.getPropertyValue('--dsh-mobile-viewport-height')
+
+ it('reserves the visible height while a text field is focused and releases it afterwards', () => {
+ viewport.height = 420
+ viewport.dispatchEvent(new Event('resize'))
+ expect(reserved()).toBe('420px')
+ viewport.height = window.innerHeight
+ editor.blur()
+ viewport.dispatchEvent(new Event('resize'))
+ expect(reserved()).toBe('')
+ })
+
+ it('ignores a shrunken viewport without a focused text field', () => {
+ editor.blur()
+ viewport.height = 420
+ viewport.dispatchEvent(new Event('resize'))
+ expect(reserved()).toBe('')
+ })
+
+ it('follows the keyboard height the iOS app reports', () => {
+ const report = (height: number) => window.dispatchEvent(new CustomEvent('dsh-mobile-keyboard', { detail: { height } }))
+ report(300)
+ expect(reserved()).toBe(`${window.innerHeight - 300}px`)
+ report(0)
+ expect(reserved()).toBe('')
+ })
+
+ it('drops the reservation when the plugin unloads', () => {
+ window.dispatchEvent(new CustomEvent('dsh-mobile-keyboard', { detail: { height: 300 } }))
+ controller.dispose()
+ expect(reserved()).toBe('')
+ })
+})
diff --git a/packages/dsh-tauri-mobile-ui/src/client/register/keyboard.ts b/packages/dsh-tauri-mobile-ui/src/client/register/keyboard.ts
index 59fa9eb0..4953733c 100644
--- a/packages/dsh-tauri-mobile-ui/src/client/register/keyboard.ts
+++ b/packages/dsh-tauri-mobile-ui/src/client/register/keyboard.ts
@@ -3,19 +3,57 @@ import { defineRegister, detectMobileDevice } from 'dsh-tauri/client'
const COMPOSER = '[data-composer-seat], [data-slot="conversation.composer.bar"]'
const SCROLL = '[data-conversation-scroll], [data-slot="conversation.view"]'
+const EDITABLE = 'textarea, input, [contenteditable="true"]'
+const VIEWPORT_HEIGHT = '--dsh-mobile-viewport-height'
+const NATIVE_KEYBOARD = 'dsh-mobile-keyboard'
export const registerMobileKeyboard = defineRegister<ClientContext>((controller, ctx) => {
const t = ctx.locale.bind('conversation')
+ const viewport = window.visualViewport
let touch: { id: number, x: number, y: number } | undefined
+ let nativeHeight = 0
function dismissKeyboard() {
const editor = document.activeElement
if (detectMobileDevice() && editor instanceof HTMLElement && editor.closest(COMPOSER)
- && editor.matches('textarea, input, [contenteditable="true"]')) {
+ && editor.matches(EDITABLE)) {
editor.blur()
}
}
+ function shrinkHeight() {
+ if (nativeHeight > 0)
+ return Math.max(0, window.innerHeight - nativeHeight)
+ const editor = document.activeElement
+ if (!(editor instanceof HTMLElement) || !editor.matches(EDITABLE) || !viewport || Math.abs(viewport.scale - 1) > 0.01)
+ return 0
+ return window.innerHeight - viewport.height >= 1 ? Math.floor(viewport.height) : 0
+ }
+
+ // keep:effect The keyboard overlays the WebView instead of shrinking it, so the page itself has to reserve the covered height or the composer stays behind it.
+ function fitKeyboard() {
+ const height = shrinkHeight()
+ const style = document.documentElement.style
+ if (height > 0)
+ style.setProperty(VIEWPORT_HEIGHT, `${height}px`)
+ else
+ style.removeProperty(VIEWPORT_HEIGHT)
+ }
+
+ function onNativeKeyboard(event: Event) {
+ const detail = (event as CustomEvent<{ height?: number }>).detail
+ nativeHeight = Math.max(0, Math.round(detail?.height ?? 0))
+ fitKeyboard()
+ }
+
+ window.addEventListener(NATIVE_KEYBOARD, onNativeKeyboard)
+ viewport?.addEventListener('resize', fitKeyboard)
+ controller.add(() => {
+ window.removeEventListener(NATIVE_KEYBOARD, onNativeKeyboard)
+ viewport?.removeEventListener('resize', fitKeyboard)
+ document.documentElement.style.removeProperty(VIEWPORT_HEIGHT)
+ })
+
controller.listen('click', (event) => {
if (!(event.target instanceof Element))
return
diff --git a/packages/dsh-tauri-mobile-ui/src/client/styles/mobile.cssr.test.ts b/packages/dsh-tauri-mobile-ui/src/client/styles/mobile.cssr.test.ts
index 075c8719..24db0e89 100644
--- a/packages/dsh-tauri-mobile-ui/src/client/styles/mobile.cssr.test.ts
+++ b/packages/dsh-tauri-mobile-ui/src/client/styles/mobile.cssr.test.ts
@@ -250,4 +250,15 @@ describe('mobile conversation layout', () => {
})
expect(declarations).toEqual([['padding-bottom', '0', true]])
})
+
+ it('pins the page to the keyboard-free height reported by the shell, outside the mobile layout', () => {
+ const values: unknown[] = []
+ root.walkRules(':root', (rule) => {
+ expect(rule.parent?.type).toBe('root')
+ rule.walkDecls((decl) => {
+ values.push([decl.prop, decl.value, decl.important])
+ })
+ })
+ expect(values).toEqual([['height', 'var(--dsh-mobile-viewport-height, 100%)', undefined]])
+ })
})
diff --git a/packages/dsh-tauri-mobile-ui/src/client/styles/mobile.cssr.ts b/packages/dsh-tauri-mobile-ui/src/client/styles/mobile.cssr.ts
index aae97562..deb4b1e9 100644
--- a/packages/dsh-tauri-mobile-ui/src/client/styles/mobile.cssr.ts
+++ b/packages/dsh-tauri-mobile-ui/src/client/styles/mobile.cssr.ts
@@ -3,7 +3,13 @@ import { MOBILE_MEDIA_QUERIES } from 'dsh-tauri/client'
const { c } = cssr
-export default c(`@media ${MOBILE_MEDIA_QUERIES.join(' and ')}`, [
+// keep: The keyboard does not resize the layout viewport on iOS, so the page height is pinned to the
+// height reported while a text field is focused; iPad landscape uses the desktop layout, hence no media query.
+const keyboardFit = c(':root', {
+ height: 'var(--dsh-mobile-viewport-height, 100%)',
+})
+
+export default c([c(`@media ${MOBILE_MEDIA_QUERIES.join(' and ')}`, [
c('html[data-dsh-mobile-sidebar], html[data-dsh-mobile-sidebar] body', {
overflow: 'hidden',
}),
@@ -254,4 +260,4 @@ export default c(`@media ${MOBILE_MEDIA_QUERIES.join(' and ')}`, [
transition: 'none !important',
}),
]),
-])
+]), keyboardFit])
diff --git a/src-native/ui/webview.test.tsx b/src-native/ui/webview.test.tsx
index 06e311b7..5369467e 100644
--- a/src-native/ui/webview.test.tsx
+++ b/src-native/ui/webview.test.tsx
@@ -11,6 +11,8 @@ const native = vi.hoisted(() => ({
platform: { OS: 'android' },
appListeners: new Set<() => void>(),
backListeners: new Set<() => boolean>(),
+ keyboardListeners: new Map<string, (payload: { endCoordinates: { screenY: number } }) => void>(),
+ windowMetrics: { width: 1180, height: 820 },
navigation: { isFocused: vi.fn<() => boolean>() },
randomUUID: vi.fn<() => string>(),
openURL: vi.fn<(url: string) => Promise<void>>(),
@@ -46,6 +48,17 @@ vi.mock('react-native', () => ({
} }
},
},
+ Dimensions: {
+ get: () => ({ ...native.windowMetrics }),
+ },
+ Keyboard: {
+ addListener: (event: string, listener: (payload: { endCoordinates: { screenY: number } }) => void) => {
+ native.keyboardListeners.set(event, listener)
+ return { remove: () => {
+ native.keyboardListeners.delete(event)
+ } }
+ },
+ },
}))
vi.mock('uniwind', () => ({ Uniwind: { setTheme: native.setTheme } }))
// 文案与 store 现在都经过 i18n;node 环境无法真正加载 expo-localization(缺 __DEV__),设备区域固定为 zh-CN。
@@ -290,6 +303,7 @@ beforeEach(async () => {
native.platform.OS = 'android'
native.appListeners.clear()
native.backListeners.clear()
+ native.keyboardListeners.clear()
native.navigation.isFocused.mockReturnValue(true)
let sequence = 0
native.randomUUID.mockImplementation(() => `webview-uuid-${++sequence}`)
@@ -316,6 +330,7 @@ afterEach(async () => {
await vi.advanceTimersByTimeAsync(0)
expect(native.appListeners.size).toBe(0)
expect(native.backListeners.size).toBe(0)
+ expect(native.keyboardListeners.size).toBe(0)
expect(vi.getTimerCount()).toBe(0)
vi.restoreAllMocks()
vi.resetAllMocks()
@@ -413,6 +428,7 @@ describe('rendered Bridge WebView document lifecycle', () => {
await mount()
const edges = platform === 'ios' ? ['top'] : ['top', 'bottom']
expect(root().find(node => String(node.type) === 'SafeAreaView').props.edges).toEqual(edges)
+ expect(native.keyboardListeners.size).toBe(platform === 'ios' ? 1 : 0)
const page = createPage()
const style = page.styles.get('dsh-bridge-tap-highlight')
expect(style?.textContent).toContain('--dsh-mobile-safe-area-inset-top: 0px;')
@@ -434,6 +450,21 @@ describe('rendered Bridge WebView document lifecycle', () => {
expect(Reflect.get(page.window, '__dshBridgeReceive')).toBe(receive)
})
+ it('reports the ios keyboard height into the loaded page and clears it when the keyboard hides', async () => {
+ native.platform.OS = 'ios'
+ await mount()
+ const view = await viewRef()
+ view.injectJavaScript.mockClear()
+
+ native.keyboardListeners.get('keyboardWillChangeFrame')!({ endCoordinates: { screenY: native.windowMetrics.height - 301 } })
+ native.keyboardListeners.get('keyboardWillChangeFrame')!({ endCoordinates: { screenY: native.windowMetrics.height } })
+
+ expect(view.injectJavaScript.mock.calls.map(([script]) => script)).toEqual([
+ expect.stringContaining('"detail":{"height":301}'),
+ expect.stringContaining('"detail":{"height":0}'),
+ ])
+ })
+
it('never records Android native finish followed by network error as a successful connection', async () => {
await mount()
const view = await viewRef()
diff --git a/src-native/ui/webview.tsx b/src-native/ui/webview.tsx
index 39e6c0f9..ab83fe44 100644
--- a/src-native/ui/webview.tsx
+++ b/src-native/ui/webview.tsx
@@ -10,7 +10,7 @@ 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, Linking, Modal, Platform, Pressable, Text, View } from 'react-native'
+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'
@@ -24,7 +24,7 @@ import { requestNotificationAccess, sendNativeNotification } from '@/hooks/use-n
import { connection } from '@/store/modules/connection'
import { connectAddress, refreshHealth } from '@/store/modules/connection/runtime'
import { buildConnectUrl, isTrustedOrigin } from '@/utils/bridge-protocol'
-import { createNotificationShim, nativeMessageScript, parseNativeMessage } from '@/utils/webview-bridge'
+import { createNotificationShim, keyboardHeightScript, nativeMessageScript, parseNativeMessage } from '@/utils/webview-bridge'
export function BridgeWebView({ address, generation }: { address: BridgeAddress, generation: number }) {
const ref = useRef<WebView>(null)
@@ -55,6 +55,16 @@ export function BridgeWebView({ address, generation }: { address: BridgeAddress,
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)
diff --git a/src-native/utils/webview-bridge.test.ts b/src-native/utils/webview-bridge.test.ts
index f89a07ef..959059f9 100644
--- a/src-native/utils/webview-bridge.test.ts
+++ b/src-native/utils/webview-bridge.test.ts
@@ -1,7 +1,7 @@
/// <reference types="node" />
import { createContext as createVmContext, runInContext } from 'node:vm'
import { afterEach, describe, expect, it, vi } from 'vitest'
-import { createNotificationShim, nativeMessageScript, parseNativeMessage } from './webview-bridge'
+import { createNotificationShim, keyboardHeightScript, nativeMessageScript, parseNativeMessage } from './webview-bridge'
const origin = 'https://harness.test:3080'
const nonce = 'bridge-nonce'
@@ -139,7 +139,7 @@ function createBrowser(options: { locationOrigin?: string, topFrame?: boolean, h
}
const location = { origin: options.locationOrigin ?? origin }
const fetch = vi.fn<typeof globalThis.fetch>().mockResolvedValue(new Response(null, { status: 404 }))
- const context = createVmContext({ window, document, location, fetch, MutationObserver: BrowserMutationObserver, Event, MessageEvent: BrowserMessageEvent, Date, setTimeout, clearTimeout })
+ const context = createVmContext({ window, document, location, fetch, MutationObserver: BrowserMutationObserver, Event, CustomEvent, MessageEvent: BrowserMessageEvent, Date, setTimeout, clearTimeout })
function run(script: string): unknown {
return runInContext(script, context, { timeout: 1000 })
}
@@ -1165,3 +1165,36 @@ describe('nativeMessageScript origin guard', () => {
expect(receive).toHaveBeenCalledExactlyOnceWith({ type: 'dsh://visibility-state', hidden: true, nonce: 'bridge-nonce' })
})
})
+
+describe('keyboardHeightScript', () => {
+ function keyboardEvents() {
+ const browser = createBrowser()
+ const seen: CustomEvent<{ height: number }>[] = []
+ browser.window.addEventListener('dsh-mobile-keyboard', event => void seen.push(event as CustomEvent<{ height: number }>))
+ return { browser, seen }
+ }
+
+ it('reports the rounded keyboard height to the trusted page', () => {
+ const { browser, seen } = keyboardEvents()
+
+ expect(browser.run(keyboardHeightScript(origin, 400.7))).toBe(true)
+ expect(seen.map(event => event.detail)).toEqual([{ height: 401 }])
+ })
+
+ it('clamps a dismissed keyboard to zero', () => {
+ const { browser, seen } = keyboardEvents()
+
+ browser.run(keyboardHeightScript(origin, -1))
+
+ expect(seen.map(event => event.detail)).toEqual([{ height: 0 }])
+ })
+
+ it.each([{ locationOrigin: 'https://evil.test:3080' }, { topFrame: false }])('ignores untrusted documents or subframes %j', (options) => {
+ const browser = createBrowser(options)
+ const seen: Event[] = []
+ browser.window.addEventListener('dsh-mobile-keyboard', event => void seen.push(event))
+
+ expect(browser.run(keyboardHeightScript(origin, 400))).toBe(true)
+ expect(seen).toHaveLength(0)
+ })
+})
diff --git a/src-native/utils/webview-bridge.ts b/src-native/utils/webview-bridge.ts
index 262db426..84e67e26 100644
--- a/src-native/utils/webview-bridge.ts
+++ b/src-native/utils/webview-bridge.ts
@@ -398,3 +398,8 @@ export function createNotificationShim(origin: string, nonce: string, nativeSafe
export function nativeMessageScript(origin: string, nonce: string, payload: Record<string, unknown>): string {
return `if (window.top === window && location.origin === ${JSON.stringify(origin)} && window.__dshBridgeNonce === ${JSON.stringify(nonce)}) { window.__dshBridgeReceive && window.__dshBridgeReceive(${JSON.stringify({ ...payload, nonce })}); } true;`
}
+
+export function keyboardHeightScript(origin: string, height: number): string {
+ const detail = { detail: { height: Math.max(0, Math.round(height)) } }
+ return `if (window.top === window && location.origin === ${JSON.stringify(origin)}) window.dispatchEvent(new CustomEvent('dsh-mobile-keyboard', ${JSON.stringify(detail)})); true;`
+}
diff --git a/test/e2e/plugins/mobile-document-scroll.e2e.ts b/test/e2e/plugins/mobile-document-scroll.e2e.ts
index bd6975c4..0d4eabfc 100644
--- a/test/e2e/plugins/mobile-document-scroll.e2e.ts
+++ b/test/e2e/plugins/mobile-document-scroll.e2e.ts
@@ -91,6 +91,36 @@ it('releases document scrolling when mobile sidebar ownership ends', async () =>
}
})
+it('pins the page to the keyboard height reported while composing in the desktop layout', async () => {
+ const page = await browser.newPage({ hasTouch: true, viewport: { width: 1180, height: 820 } })
+ try {
+ await page.setContent(`<!doctype html><html><head>
+ <meta name="viewport" content="width=device-width, initial-scale=1">
+ <style>html,body,#root{height:100%;margin:0}
+ #root{display:flex;flex-direction:column}
+ [data-conversation-scroll]{flex:1;min-height:0;overflow:auto}
+ article{height:2400px}
+ [data-composer-seat]{flex-shrink:0;height:120px}</style></head><body>
+ <div id="root">
+ <div data-conversation-scroll><article>Messages</article></div>
+ <div data-composer-seat><textarea aria-label="Draft"></textarea></div>
+ </div>
+ </body></html>`)
+ await page.addStyleTag({ content: mobileStyle.render() })
+ const seat = page.locator('[data-composer-seat]')
+ const seatBottom = () => seat.evaluate(element => Math.round(element.getBoundingClientRect().bottom))
+ expect(await seatBottom(), '无键盘时输入区贴在视口底部').toBe(820)
+ await page.evaluate(() => document.documentElement.style.setProperty('--dsh-mobile-viewport-height', '520px'))
+ expect(await page.evaluate(() => Math.round(document.documentElement.getBoundingClientRect().height)), 'iPad 横屏的桌面布局也须按键盘高度收缩').toBe(520)
+ expect(await seatBottom(), '键盘弹出后输入区须守在键盘上沿').toBe(520)
+ await page.evaluate(() => document.documentElement.style.removeProperty('--dsh-mobile-viewport-height'))
+ expect(await seatBottom(), '键盘收起后输入区须回到视口底部').toBe(820)
+ }
+ finally {
+ await page.close()
+ }
+})
+
it('leaves document scrolling unchanged for desktop pointer media', async () => {
const page = await browser.newPage({ viewport: { width: 1400, height: 900 } })
try {