From 93a4892f59348d722595c337cbe5c3ec840077df Mon Sep 17 00:00:00 2001 From: Jinwoo-H Date: Fri, 25 Sep 2026 22:10:50 -0400 Subject: [PATCH 01/22] fix(mobile): the page's tab and dock taps keep the keyboard up react-native-web ignores `keyboardShouldPersistTaps`, and a Pressable there is a focusable element: on Pixel_API_37 a tap on a session tab or a dock key moved focus from the live input on mousedown and the IME closed. Natively a Pressable never takes focus and the two ScrollViews persist taps ('handled' for the tabs, 'always' for the accessory bar). The page's sibling gives both bars the same rule: while a text field holds focus, a mousedown on something pressable (or, for 'always', anywhere in the bar) does not move it. Natively the ref is undefined. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb --- .../src/platform/keyboard-persisting-taps.ts | 6 ++ .../keyboard-persisting-taps.web.test.ts | 76 +++++++++++++++++++ .../platform/keyboard-persisting-taps.web.ts | 50 ++++++++++++ .../src/session/MobileSessionCommandDock.tsx | 4 +- mobile/src/session/MobileSessionHeader.tsx | 4 +- .../mobile-session-route-parity.test.ts | 9 ++- 6 files changed, 144 insertions(+), 5 deletions(-) create mode 100644 mobile/src/platform/keyboard-persisting-taps.ts create mode 100644 mobile/src/platform/keyboard-persisting-taps.web.test.ts create mode 100644 mobile/src/platform/keyboard-persisting-taps.web.ts diff --git a/mobile/src/platform/keyboard-persisting-taps.ts b/mobile/src/platform/keyboard-persisting-taps.ts new file mode 100644 index 000000000000..77185a5f2b33 --- /dev/null +++ b/mobile/src/platform/keyboard-persisting-taps.ts @@ -0,0 +1,6 @@ +export type KeyboardPersistingTaps = 'always' | 'handled' + +/** Natively a Pressable never takes focus; the ScrollView's `keyboardShouldPersistTaps` is the rule. */ +export function useKeyboardPersistingTaps(_mode: KeyboardPersistingTaps): undefined { + return undefined +} diff --git a/mobile/src/platform/keyboard-persisting-taps.web.test.ts b/mobile/src/platform/keyboard-persisting-taps.web.test.ts new file mode 100644 index 000000000000..e02f71f93f53 --- /dev/null +++ b/mobile/src/platform/keyboard-persisting-taps.web.test.ts @@ -0,0 +1,76 @@ +// @vitest-environment happy-dom +/** + * The page's form of `keyboardShouldPersistTaps`, which react-native-web ignores. + * + * Measured on Pixel_API_37: a tap on a dock key or a session tab moves focus from the live input + * to the Pressable (tabindex 0) on mousedown, and the IME closes. Natively a Pressable never takes + * focus, so the same taps keep the keyboard up. + */ +import { afterEach, describe, expect, it } from 'vitest' +import { keepTextFocusThroughTaps } from './keyboard-persisting-taps.web' + +function plant() { + const container = document.createElement('div') + const button = document.createElement('div') + button.tabIndex = 0 + const label = document.createElement('span') + button.appendChild(label) + const gap = document.createElement('span') + const field = document.createElement('input') + container.append(button, gap, field) + const liveInput = document.createElement('input') + document.body.append(container, liveInput) + return { container, label, gap, field, liveInput } +} + +/** Whether a mousedown on `target` was kept from moving focus. */ +function pressKeepsFocus(target: Element): boolean { + const event = new MouseEvent('mousedown', { bubbles: true, cancelable: true }) + target.dispatchEvent(event) + return event.defaultPrevented +} + +afterEach(() => { + document.body.innerHTML = '' +}) + +describe('keepTextFocusThroughTaps', () => { + it("keeps a text field's focus through a tap on a pressable, in both modes", () => { + for (const mode of ['always', 'handled'] as const) { + const { container, label, liveInput } = plant() + const release = keepTextFocusThroughTaps(container, mode) + liveInput.focus() + expect(pressKeepsFocus(label), mode).toBe(true) + release() + document.body.innerHTML = '' + } + }) + + it('lets a tap on nothing pressable dismiss only when taps are handled', () => { + const always = plant() + keepTextFocusThroughTaps(always.container, 'always') + always.liveInput.focus() + expect(pressKeepsFocus(always.gap)).toBe(true) + document.body.innerHTML = '' + + const handled = plant() + keepTextFocusThroughTaps(handled.container, 'handled') + handled.liveInput.focus() + expect(pressKeepsFocus(handled.gap)).toBe(false) + }) + + it('leaves focus alone when no text field holds it, or when the tap is on a text field', () => { + const { container, label, field, liveInput } = plant() + keepTextFocusThroughTaps(container, 'always') + expect(pressKeepsFocus(label)).toBe(false) + liveInput.focus() + expect(pressKeepsFocus(field)).toBe(false) + }) + + it('stops when released', () => { + const { container, label, liveInput } = plant() + keepTextFocusThroughTaps(container, 'always')() + liveInput.focus() + expect(pressKeepsFocus(label)).toBe(false) + }) +}) diff --git a/mobile/src/platform/keyboard-persisting-taps.web.ts b/mobile/src/platform/keyboard-persisting-taps.web.ts new file mode 100644 index 000000000000..af3330d568b9 --- /dev/null +++ b/mobile/src/platform/keyboard-persisting-taps.web.ts @@ -0,0 +1,50 @@ +import { useCallback, useRef } from 'react' +import type { KeyboardPersistingTaps } from './keyboard-persisting-taps' + +export type { KeyboardPersistingTaps } from './keyboard-persisting-taps' + +function isTextField(element: Element | null): boolean { + if (!(element instanceof HTMLElement)) { + return false + } + return ( + element instanceof HTMLInputElement || + element instanceof HTMLTextAreaElement || + element.isContentEditable + ) +} + +/** + * `keyboardShouldPersistTaps` for the page: react-native-web ignores it, and a Pressable there is a + * focusable element that takes focus on mousedown, which blurs the text field and closes the IME. + * `handled` keeps focus only for a tap on something pressable; `always` for any tap. + */ +export function keepTextFocusThroughTaps( + container: HTMLElement, + mode: KeyboardPersistingTaps +): () => void { + const onMouseDown = (event: MouseEvent) => { + const target = event.target instanceof Element ? event.target : null + if (!isTextField(document.activeElement) || !target || isTextField(target)) { + return + } + if (mode === 'handled' && !target.closest('[tabindex]:not([tabindex="-1"])')) { + return + } + event.preventDefault() + } + container.addEventListener('mousedown', onMouseDown, true) + return () => container.removeEventListener('mousedown', onMouseDown, true) +} + +/** A ref for the View that holds the taps; on the page that View is its DOM element. */ +export function useKeyboardPersistingTaps(mode: KeyboardPersistingTaps) { + const releaseRef = useRef<(() => void) | null>(null) + return useCallback( + (node: unknown) => { + releaseRef.current?.() + releaseRef.current = node instanceof HTMLElement ? keepTextFocusThroughTaps(node, mode) : null + }, + [mode] + ) +} diff --git a/mobile/src/session/MobileSessionCommandDock.tsx b/mobile/src/session/MobileSessionCommandDock.tsx index ed12bb6e51a1..3ee0ece152a1 100644 --- a/mobile/src/session/MobileSessionCommandDock.tsx +++ b/mobile/src/session/MobileSessionCommandDock.tsx @@ -19,6 +19,7 @@ import { MobileTerminalInputActions } from './MobileTerminalInputActions' import { isTerminalPhoneDisplayMode } from './mobile-session-route-helpers' import { colors } from '../theme/mobile-theme' import { styles } from './mobile-session-styles' +import { useKeyboardPersistingTaps } from '../platform/keyboard-persisting-taps' import type { MobileSessionController } from './use-mobile-session-controller' export function MobileSessionCommandDock({ controller }: { controller: MobileSessionController }) { @@ -65,6 +66,7 @@ export function MobileSessionCommandDock({ controller }: { controller: MobileSes activeBrowserTab, keyboardLift } = controller + const accessoryBarKeepsKeyboard = useKeyboardPersistingTaps('always') return ( !activeMarkdownTab && !activeFileTab && @@ -77,7 +79,7 @@ export function MobileSessionCommandDock({ controller }: { controller: MobileSes ]} > {/* Accessory keys */} - + {/* Why: fixed keyboard escape hatch; outside ScrollView + shortcut path so it can't scroll away or be hidden (#5106). */} {keyboardLift > 0 && ( @@ -119,7 +121,7 @@ export function MobileSessionHeader({ controller }: { controller: MobileSessionC {visibleTabs.length > 0 && ( - + {/* Why: tab taps must register on first press with the keyboard open instead of being eaten by dismissal (#5106). */} 533, and the host-JSX hash: the tab bar and the accessory bar take a ref that gives the +// page `keyboardShouldPersistTaps` ('handled', 'always'), which react-native-web ignores. Natively +// the ref is undefined. const HEAD_RUNTIME_STRING_SHA256 = - '1be5398cdbdf96b6f7738b63a0e19f536496844140a947939a7f71824b08fe50' + '110e263e0c43e5200c35a30f67769d4545e39019c7936d03e22a920e90e5d62d' // Moved by both of the dock's fields: their refs, and the live one's submit handler, are the seam's now. -const HEAD_HOST_JSX_SHA256 = 'ca4c8b46af86a05cb671de91c22111c9e4aaeefd4a04c7b8b09976ca01a31c9b' +const HEAD_HOST_JSX_SHA256 = '3a1c72c513a000b677ae7ba09e58db1b5ccc99345e41addcf075f111f455b841' const HEAD_LEAF_JSX_SHA256 = 'c7e1a4b90197697f1eaa640c38da63281b4f7b84fb036ae2152f00c2f7d7cb77' const HEAD_STYLE_REFERENCE_SHA256 = '295a3501c2c6d7bea7c8bbf38b3f3534f01344cd7e1b91bb8e07c040821d596a' @@ -611,7 +614,7 @@ describe('mobile session route extraction parity', () => { it('preserves runtime strings, styles, and the expanded JSX tree', () => { const strings = readRuntimeStrings() - expect(strings).toHaveLength(531) + expect(strings).toHaveLength(533) expect(hash(strings)).toBe(HEAD_RUNTIME_STRING_SHA256) const jsx = readJsxFacts(readDefinitions()) expect(jsx.host).toHaveLength(124) From b5023bf94b9d5da41c978333c4dec45c21925dc5 Mon Sep 17 00:00:00 2001 From: Jinwoo-H Date: Fri, 25 Sep 2026 22:16:18 -0400 Subject: [PATCH 02/22] chore(mobile): register the page's keyboard-persisting-taps override Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb --- mobile/web-entry/web-overrides.json | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/mobile/web-entry/web-overrides.json b/mobile/web-entry/web-overrides.json index 50a31ed61cbe..1dfeb4ed9dee 100644 --- a/mobile/web-entry/web-overrides.json +++ b/mobile/web-entry/web-overrides.json @@ -69,6 +69,10 @@ "file": "src/platform/keyboard-occlusion.web.ts", "reason": "react-native-web's Keyboard is a stub: addListener returns a subscription that never fires and isVisible() is always false, so a screen waiting for keyboardDidShow inside the page waits forever and the software keyboard covers whatever sits at the bottom of the document \u2014 the source-control commit bar, and the review note composer whose KeyboardAvoidingView is driven by those same events. The browser publishes the geometry a different way: the layout viewport keeps its size and visualViewport shrinks, so the occluded strip is innerHeight minus the visual viewport's height and offsetTop, tracked on its resize and scroll. A document with no visualViewport answers 0 rather than guessing." }, + { + "file": "src/platform/keyboard-persisting-taps.web.ts", + "reason": "react-native-web ignores keyboardShouldPersistTaps, and its Pressable is a focusable element that takes focus on mousedown. On Pixel_API_37 a tap on a session tab or a dock key moved focus off the live input and the IME closed, while natively a Pressable never takes focus and those two ScrollViews persist taps. This sibling gives the tab bar ('handled') and the accessory bar ('always') the same rule by keeping a focused text field's focus through the mousedown; the native module returns no ref." + }, { "file": "src/platform/clipboard.web.ts", "reason": "expo-clipboard resolves to navigator.clipboard on the web, which needs a secure context; the iOS shell serves the page from the custom scheme orca-mobile-web:/// while Android serves https, so that path would work on one platform and silently not on the other. This one asks the shell through the native.clipboard.write and native.clipboard.read verbs, where the pasteboard is the device's, and rejects when the route was not granted one so the caller's own catch puts that on screen. An image is the same pasteboard reached a different way: native.clipboard.read admits only text, and a 24 MiB base64 image cannot cross an 8 MiB reply cap, so readImage runs native.media.pick with source 'clipboard', reads the staged bytes back a chunk at a time and gives the handle back. contents answers per grant without probing, because the shell serves no 'is there text' verb and reading to find out would raise iOS's paste-consent prompt on every mount." From 5e561e61bf2a32f2dc757b5d44d1de27792cc194 Mon Sep 17 00:00:00 2001 From: Jinwoo-H Date: Fri, 25 Sep 2026 22:45:28 -0400 Subject: [PATCH 03/22] fix(mobile): the session hears a row-pitch change in the keyboard metrics Carried from 2eab7633013 and 62113b7ac30 with the `rowPitch` metric they need (from f7d78405c7d, without its page-only lift). The document reports the drawn row pitch, cell height times fit scale, and reports again when a fit commits a new scale. The metrics handler compared four fields and dropped an update that moved only the pitch, so desktop display mode kept the phone's 15 px pitch; it now compares every field. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb --- .../mobile-session-route-parity.test.ts | 3 +- .../use-mobile-session-accessory-selection.ts | 15 ++---- mobile/src/terminal/document/fit-scale.ts | 13 ++---- .../document/keyboard-avoidance-metrics.ts | 5 +- .../terminal/document/viewport-transform.ts | 9 ++++ ...erminal-keyboard-avoidance-webview.test.ts | 32 ++++++++++++- .../terminal-webview-contract.test.ts | 46 ++++++++++++++++++- .../src/terminal/terminal-webview-contract.ts | 28 ++++++++--- 8 files changed, 123 insertions(+), 28 deletions(-) diff --git a/mobile/src/session/mobile-session-route-parity.test.ts b/mobile/src/session/mobile-session-route-parity.test.ts index d52f950d5ec3..163189ece28e 100644 --- a/mobile/src/session/mobile-session-route-parity.test.ts +++ b/mobile/src/session/mobile-session-route-parity.test.ts @@ -115,7 +115,8 @@ const HEAD_CALLBACK_IDENTITY_SHA256 = // the other's body. The hook and string counts are C7.2's and stand. // Refreshed once more for the two dictation failure handlers, which now both call // `reportDictationFailure` instead of each choosing between the setup sheet and a toast. -const HEAD_CALLBACK_BODY_SHA256 = '2ccbfb5ee57e7dfeb07dafaee6fa592b95862b3bc898a5ac2995e7c69913bfc4' +// Moved when the metrics handler compared every field, the row pitch included. +const HEAD_CALLBACK_BODY_SHA256 = '65f5c1274967cecef39660430169dcfde81b362e8aa5878833b9f20bc8e43a6a' // Refreshed for the startup effect: both `worktree.activate` sends became `worktreeActivate`, and // the sleeping-agent check reads that operation's verdict instead of the reply envelope. Refreshed // again when the reporter took the reply and interpreted it itself, retiring the hand-built diff --git a/mobile/src/session/use-mobile-session-accessory-selection.ts b/mobile/src/session/use-mobile-session-accessory-selection.ts index 7e3cfcfa76cd..a9795d82b1fc 100644 --- a/mobile/src/session/use-mobile-session-accessory-selection.ts +++ b/mobile/src/session/use-mobile-session-accessory-selection.ts @@ -8,9 +8,10 @@ import { triggerError, triggerEdgeBump } from '../platform/haptics' -import type { - TerminalKeyboardAvoidanceMetrics, - TerminalModes +import { + sameTerminalKeyboardAvoidanceMetrics, + type TerminalKeyboardAvoidanceMetrics, + type TerminalModes } from '../terminal/terminal-webview-contract' import type { createTerminalLiveAccessoryInput } from '../terminal/terminal-live-accessory-input' import { clearTerminalLiveInputFocusTimer } from '../terminal/terminal-live-input' @@ -165,13 +166,7 @@ export function useMobileSessionAccessorySelection(scope: MobileSessionTerminalI (handle: string, metrics: TerminalKeyboardAvoidanceMetrics) => { setTerminalKeyboardMetrics((prev) => { const current = prev.get(handle) - if ( - current && - current.cursorY === metrics.cursorY && - current.contentBottomRow === metrics.contentBottomRow && - current.rows === metrics.rows && - current.altScreen === metrics.altScreen - ) { + if (current && sameTerminalKeyboardAvoidanceMetrics(current, metrics)) { return prev } return new Map(prev).set(handle, metrics) diff --git a/mobile/src/terminal/document/fit-scale.ts b/mobile/src/terminal/document/fit-scale.ts index 20aa1c1ee49e..77cbc1a64ec0 100644 --- a/mobile/src/terminal/document/fit-scale.ts +++ b/mobile/src/terminal/document/fit-scale.ts @@ -3,24 +3,19 @@ import { computeFitScale, flog, getCellWidth, + getMeasuredCellHeight, getTotalScale, updateTransform } from './viewport-transform' import type { TerminalDocumentScope } from './document-scope' import { scheduleDocumentFrame } from './document-frame-registry' +import { emitKeyboardAvoidanceMetrics } from './keyboard-avoidance-metrics' /** The narrowest grid a fit or a text-scale change will fit to. */ export const MIN_FIT_COLS = 20 export function getCellHeight(scope: TerminalDocumentScope) { - if (!scope.term || !scope.term._core) { - return 15 - } - const core = scope.term._core - if (core._renderService && core._renderService.dimensions) { - return core._renderService.dimensions.css.cell.height || 15 - } - return 15 + return getMeasuredCellHeight(scope) || 15 } // Why: clamp pan so the terminal content always covers the viewport @@ -170,6 +165,8 @@ export function commitFitScale( }) } repositionOverlay(scope) + // The host's lift reads the drawn row pitch, which a new scale changes with no new output. + emitKeyboardAvoidanceMetrics(scope) } /** diff --git a/mobile/src/terminal/document/keyboard-avoidance-metrics.ts b/mobile/src/terminal/document/keyboard-avoidance-metrics.ts index 516dfdb1b2a6..a0f28d801c16 100644 --- a/mobile/src/terminal/document/keyboard-avoidance-metrics.ts +++ b/mobile/src/terminal/document/keyboard-avoidance-metrics.ts @@ -1,3 +1,4 @@ +import { getMeasuredCellHeight, getTotalScale } from './viewport-transform' import { notify } from './host-notify' import type { TerminalDocumentCell, @@ -70,6 +71,8 @@ export function emitKeyboardAvoidanceMetrics(scope: TerminalDocumentScope) { cursorY: scope.term.buffer && scope.term.buffer.active ? scope.term.buffer.active.cursorY : 0, contentBottomRow: alt ? 0 : computeContentBottomRow(scope), rows: scope.term.rows || 0, - altScreen: alt + altScreen: alt, + // As drawn: desktop display mode scales the desktop's rows down to the phone's width. + rowPitch: getMeasuredCellHeight(scope) * getTotalScale(scope) }) } diff --git a/mobile/src/terminal/document/viewport-transform.ts b/mobile/src/terminal/document/viewport-transform.ts index 4f60fc9eca1a..284b2a3d12ae 100644 --- a/mobile/src/terminal/document/viewport-transform.ts +++ b/mobile/src/terminal/document/viewport-transform.ts @@ -19,6 +19,15 @@ export function flog(scope: TerminalDocumentScope, tag: string, payload: Record< } catch {} } +/** 0 until the renderer has measured a cell. */ +export function getMeasuredCellHeight(scope: TerminalDocumentScope) { + const core = scope.term?._core + if (core && core._renderService && core._renderService.dimensions) { + return core._renderService.dimensions.css.cell.height || 0 + } + return 0 +} + export function getCellWidth(scope: TerminalDocumentScope) { if (!scope.term || !scope.term._core) { return 0 diff --git a/mobile/src/terminal/terminal-keyboard-avoidance-webview.test.ts b/mobile/src/terminal/terminal-keyboard-avoidance-webview.test.ts index f47395be0490..9291f6fbe6ce 100644 --- a/mobile/src/terminal/terminal-keyboard-avoidance-webview.test.ts +++ b/mobile/src/terminal/terminal-keyboard-avoidance-webview.test.ts @@ -1,3 +1,4 @@ +import { readFileSync } from 'node:fs' import { Terminal } from '@xterm/xterm' import { describe, expect, it, vi } from 'vitest' import { createTerminalDocumentScope } from './document/document-scope' @@ -13,11 +14,12 @@ import { parseTerminalKeyboardAvoidanceMetrics } from './terminal-webview-contra * it is handed, so a case builds one with its own terminal double and reads the notifications back * out of the seam it passed in. */ -function runMetricsOver(term: unknown): Record[] { +function runMetricsOver(term: unknown, fitScale = 1): Record[] { const notifications: Record[] = [] const scope = createTerminalDocumentScope({ postToHost: (message) => notifications.push(message) }) + scope.currentScale = fitScale // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: each case's double implements the buffer members the scan reads, which is what the assertions check. scope.term = term as typeof scope.term emitKeyboardAvoidanceMetrics(scope) @@ -214,4 +216,32 @@ describe('terminal keyboard-avoidance WebView metrics', () => { expect(emitAt, `${module} emits before it resizes`).toBeGreaterThan(geometryAt) } }) + + it('reports the row pitch as drawn, fit scale included, and none before a cell is measured', () => { + // Desktop display mode keeps the desktop's rows and the fit shrinks the grid by width. + const buffer = { cursorY: 0, viewportY: 0, type: 'normal', getLine: () => undefined } + const measuredTerm = { + buffer: { active: buffer }, + cols: 10, + rows: 47, + _core: { _renderService: { dimensions: { css: { cell: { width: 8, height: 15 } } } } } + } + const phone = runMetricsOver(measuredTerm)[0] + const desktop = runMetricsOver(measuredTerm, 0.5)[0] + const unmeasured = runMetricsOver({ buffer: { active: buffer }, cols: 10, rows: 47 })[0] + expect({ + phone: phone?.rowPitch, + desktop: desktop?.rowPitch, + unmeasured: unmeasured?.rowPitch + }).toEqual({ phone: 15, desktop: 7.5, unmeasured: 0 }) + }) + + it('reports again when a fit commits a new scale', () => { + const fit = readFileSync(new URL('./document/fit-scale.ts', import.meta.url), 'utf8') + const commit = fit.slice(fit.indexOf('export function commitFitScale(')) + const body = commit.slice(0, commit.indexOf('\n}\n')) + expect(body.indexOf('emitKeyboardAvoidanceMetrics(scope)')).toBeGreaterThan( + body.indexOf('scope.currentScale = 1') + ) + }) }) diff --git a/mobile/src/terminal/terminal-webview-contract.test.ts b/mobile/src/terminal/terminal-webview-contract.test.ts index 0a3527111e3e..aca7f9533d83 100644 --- a/mobile/src/terminal/terminal-webview-contract.test.ts +++ b/mobile/src/terminal/terminal-webview-contract.test.ts @@ -1,6 +1,10 @@ import { describe, expect, it } from 'vitest' -import { parseTerminalKeyboardAvoidanceMetrics } from './terminal-webview-contract' +import { + parseTerminalKeyboardAvoidanceMetrics, + sameTerminalKeyboardAvoidanceMetrics, + type TerminalKeyboardAvoidanceMetrics +} from './terminal-webview-contract' describe('parseTerminalKeyboardAvoidanceMetrics', () => { it('parses a full payload', () => { @@ -49,4 +53,44 @@ describe('parseTerminalKeyboardAvoidanceMetrics', () => { }) ).toEqual({ cursorY: 0, contentBottomRow: 0, rows: 0, altScreen: false }) }) + + it('carries the drawn row pitch when the document reports one, and omits it otherwise', () => { + expect(parseTerminalKeyboardAvoidanceMetrics({ cursorY: 46, rows: 47, rowPitch: 7.5 })).toEqual( + { cursorY: 46, contentBottomRow: 46, rows: 47, altScreen: false, rowPitch: 7.5 } + ) + for (const rowPitch of [undefined, 0, -3, Number.NaN, Number.POSITIVE_INFINITY, '15']) { + expect( + 'rowPitch' in parseTerminalKeyboardAvoidanceMetrics({ cursorY: 1, rows: 4, rowPitch }) + ).toBe(false) + } + }) +}) + +describe('sameTerminalKeyboardAvoidanceMetrics', () => { + const metrics: Required = { + cursorY: 38, + contentBottomRow: 38, + rows: 40, + altScreen: false, + rowPitch: 15 + } + // One variant per field, each differing from `metrics` in that field alone. + const variants: [keyof typeof metrics, TerminalKeyboardAvoidanceMetrics][] = [ + ['cursorY', { ...metrics, cursorY: 39 }], + ['contentBottomRow', { ...metrics, contentBottomRow: 39 }], + ['rows', { ...metrics, rows: 41 }], + ['altScreen', { ...metrics, altScreen: true }], + // Desktop display mode, measured on the page: same rows, the fit scale moved to 0.46. + ['rowPitch', { ...metrics, rowPitch: 6.96 }] + ] + + it('tells apart metrics that differ in any one field', () => { + expect(sameTerminalKeyboardAvoidanceMetrics(metrics, { ...metrics })).toBe(true) + expect(variants.map(([key]) => key).sort()).toEqual(Object.keys(metrics).sort()) + for (const [key, variant] of variants) { + expect(sameTerminalKeyboardAvoidanceMetrics(metrics, variant), key).toBe(false) + } + const { rowPitch: _rowPitch, ...older } = metrics + expect(sameTerminalKeyboardAvoidanceMetrics(metrics, older)).toBe(false) + }) }) diff --git a/mobile/src/terminal/terminal-webview-contract.ts b/mobile/src/terminal/terminal-webview-contract.ts index 45b9a38c05a5..e20821926289 100644 --- a/mobile/src/terminal/terminal-webview-contract.ts +++ b/mobile/src/terminal/terminal-webview-contract.ts @@ -18,6 +18,23 @@ export type TerminalKeyboardAvoidanceMetrics = { contentBottomRow: number rows: number altScreen: boolean + // CSS px between drawn rows, fit scale included; absent from older documents and before the + // renderer has measured. + rowPitch?: number +} + +/** Every field: a fit-scale change moves only the row pitch, and the lift must hear it. */ +export function sameTerminalKeyboardAvoidanceMetrics( + a: TerminalKeyboardAvoidanceMetrics, + b: TerminalKeyboardAvoidanceMetrics +): boolean { + return ( + a.cursorY === b.cursorY && + a.contentBottomRow === b.contentBottomRow && + a.rows === b.rows && + a.altScreen === b.altScreen && + a.rowPitch === b.rowPitch + ) } export function parseTerminalKeyboardAvoidanceMetrics( @@ -30,12 +47,11 @@ export function parseTerminalKeyboardAvoidanceMetrics( msg.contentBottomRow === undefined ? cursorY : Math.min(toNonNegativeInteger(msg.contentBottomRow), maxRow) - return { - cursorY, - contentBottomRow, - rows, - altScreen: msg.altScreen === true - } + const metrics = { cursorY, contentBottomRow, rows, altScreen: msg.altScreen === true } + const rowPitch = msg.rowPitch + return typeof rowPitch === 'number' && Number.isFinite(rowPitch) && rowPitch > 0 + ? { ...metrics, rowPitch } + : metrics } function toNonNegativeInteger(value: unknown): number { From c7b9e9e485d45cfb1319df8a795974548af10335 Mon Sep 17 00:00:00 2001 From: Jinwoo-H Date: Fri, 25 Sep 2026 22:45:54 -0400 Subject: [PATCH 04/22] fix(mobile): native desktop display mode lifts only what the keyboard hides of the grid Carried from 097f5d8d33f, native rule only. Desktop display mode draws 40 rows about 270 dp tall, and a lift by the covered strip (312 on Pixel_API_37) moved the whole grid under the header. The lift is now also capped by the hidden strip of the drawn grid. A sweep shows it equals base's arithmetic whenever the drawn grid fills the frame, which phone mode always does. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb --- .../terminal-keyboard-avoidance-lift.test.ts | 90 +++++++++++++++++++ .../terminal-keyboard-avoidance-lift.ts | 32 ++++++- 2 files changed, 118 insertions(+), 4 deletions(-) diff --git a/mobile/src/terminal/terminal-keyboard-avoidance-lift.test.ts b/mobile/src/terminal/terminal-keyboard-avoidance-lift.test.ts index 4c11320db2e3..5dcd32f9e1e3 100644 --- a/mobile/src/terminal/terminal-keyboard-avoidance-lift.test.ts +++ b/mobile/src/terminal/terminal-keyboard-avoidance-lift.test.ts @@ -103,6 +103,13 @@ describe('computeActiveTerminalKeyboardLift', () => { terminalFrameHeight: FRAME_HEIGHT }) expect(lift).toBeLessThanOrEqual(KEYBOARD_LIFT) + // With the drawn row pitch too, and a grid drawn taller than the frame it is lifted in. + const taller = computeActiveTerminalKeyboardLift({ + keyboardLift: KEYBOARD_LIFT, + metrics: metrics({ rows: 60, rowPitch: 18, cursorY: 59, contentBottomRow: 59 }), + terminalFrameHeight: FRAME_HEIGHT + }) + expect(taller).toBe(KEYBOARD_LIFT) }) it('uses the platform-adjusted lift proportionally on iOS and Android', () => { @@ -119,4 +126,87 @@ describe('computeActiveTerminalKeyboardLift', () => { }) expect({ android, ios }).toEqual({ android: 220, ios: 186 }) }) + + /** Base's arithmetic, kept here as the oracle a covered frame must match to the pixel. */ + function baseLift(keyboardLift: number, m: TerminalKeyboardAvoidanceMetrics, frame: number) { + if (keyboardLift <= 0) { + return 0 + } + if (m.rows <= 0 || frame <= 0 || m.altScreen) { + return keyboardLift + } + const rowHeight = frame / m.rows + const anchorBottom = (Math.max(m.cursorY, m.contentBottomRow) + 1) * rowHeight + return Math.min(keyboardLift, Math.max(0, anchorBottom + rowHeight - (frame - keyboardLift))) + } + + describe('a keyboard that covers the frame', () => { + const lift = (keyboardLift: number, m: TerminalKeyboardAvoidanceMetrics, frame = 713.7) => + computeActiveTerminalKeyboardLift({ + keyboardLift, + metrics: m, + terminalFrameHeight: frame + }) + + it('keeps base in phone mode, where the fit fills the frame to within a row', () => { + // Pixel_API_37: 47 rows of 15 px in a 713.7 px frame under a 312 px keyboard. + const phone = metrics({ rows: 47, rowPitch: 15, cursorY: 46, contentBottomRow: 46 }) + expect(lift(312, phone)).toBe(312) + expect(lift(312, phone)).toBe(baseLift(312, phone, 713.7)) + }) + + it('lifts a desktop-mode grid only by what the keyboard hides of it', () => { + // Pixel_API_37, measured blank: 40 desktop rows drawn 270 px tall, lifted 312 under the header. + const drawn270 = metrics({ rows: 40, rowPitch: 6.75, cursorY: 39, contentBottomRow: 39 }) + expect(lift(312, drawn270)).toBe(0) + expect(lift(312, { ...drawn270, altScreen: true })).toBe(0) + // 425 px drawn, the dock at 401.7: the caret row's bottom lands on the dock. + const drawn425 = metrics({ rows: 50, rowPitch: 8.5, cursorY: 49, contentBottomRow: 49 }) + expect(lift(312, drawn425)).toBeCloseTo(23.3, 5) + expect(lift(312, { ...drawn425, altScreen: true })).toBeCloseTo(23.3, 5) + }) + + it('lifts nothing for a keyboard that is open and covers nothing', () => { + expect(lift(0, metrics({ rows: 50, rowPitch: 17, cursorY: 49, contentBottomRow: 49 }))).toBe( + 0 + ) + }) + + it('stays under the strip while stale rows outlast a rotation or a text-size change', () => { + const rotated = metrics({ rows: 47, rowPitch: 15, cursorY: 46, contentBottomRow: 46 }) + expect(lift(150, rotated, 300)).toBe(150) + const resized = metrics({ rows: 47, rowPitch: 18, cursorY: 46, contentBottomRow: 46 }) + expect(lift(312, resized)).toBe(312) + }) + + it('matches base wherever the drawn grid fills the frame, and never lifts past it elsewhere', () => { + let matched = 0 + let drawnShort = 0 + for (const rows of [8, 26, 47, 50, 80]) { + for (const rowPitch of [undefined, 5.1, 8.5, 15, 18, 25]) { + for (const frame of [300, 401.7, 710.33, 713.7]) { + for (const keyboard of [0.5, 150, 312, 336]) { + for (const anchor of [0, Math.floor(rows / 2), rows - 1]) { + const m = metrics({ rows, rowPitch, cursorY: anchor, contentBottomRow: anchor }) + const got = lift(keyboard, m, frame) + const drawn = rowPitch === undefined ? frame : rows * rowPitch + // The fit floors rows, so a grid that fills the frame leaves less than a row. + if (drawn >= frame - (rowPitch ?? 0)) { + expect(got).toBe(baseLift(keyboard, m, frame)) + matched++ + continue + } + expect(got).toBeLessThanOrEqual(keyboard) + expect(got).toBeLessThanOrEqual(Math.max(0, drawn - (frame - keyboard)) + 1e-9) + drawnShort++ + } + } + } + } + } + // Presence: both halves of the sweep ran. + expect(matched).toBeGreaterThan(500) + expect(drawnShort).toBeGreaterThan(500) + }) + }) }) diff --git a/mobile/src/terminal/terminal-keyboard-avoidance-lift.ts b/mobile/src/terminal/terminal-keyboard-avoidance-lift.ts index 6ada640430d9..003b42b50c40 100644 --- a/mobile/src/terminal/terminal-keyboard-avoidance-lift.ts +++ b/mobile/src/terminal/terminal-keyboard-avoidance-lift.ts @@ -1,11 +1,16 @@ import type { TerminalKeyboardAvoidanceMetrics } from './terminal-webview-contract' type ActiveTerminalKeyboardLiftParams = { + // What the keyboard covers of the frame. keyboardLift: number metrics: TerminalKeyboardAvoidanceMetrics | undefined terminalFrameHeight: number } +/** + * How far to lift the active pane so its anchor row clears the keyboard. Never more than the strip + * the keyboard covers, nor more than it hides of the grid as drawn. + */ export function computeActiveTerminalKeyboardLift( params: ActiveTerminalKeyboardLiftParams ): number { @@ -16,14 +21,33 @@ export function computeActiveTerminalKeyboardLift( if (!metrics || metrics.rows <= 0 || terminalFrameHeight <= 0) { return keyboardLift } + const dockTop = terminalFrameHeight - keyboardLift + const pitch = metrics.rowPitch + // Desktop display mode draws the desktop's rows scaled down, well short of the frame; lifting + // by the strip there moved the whole grid under the header. The fit floors rows, so a gap under + // one row is a grid that fills the frame, and keeps the arithmetic below. + if (pitch && metrics.rows * pitch < terminalFrameHeight - pitch) { + const drawnHidden = metrics.rows * pitch - dockTop + if (drawnHidden <= 0) { + return 0 + } + const hidden = Math.min(keyboardLift, drawnHidden) + return metrics.altScreen ? hidden : Math.min(hidden, anchorOverflow(metrics, pitch, dockTop)) + } if (metrics.altScreen) { return keyboardLift } const rowHeight = terminalFrameHeight / metrics.rows + return Math.min(keyboardLift, anchorOverflow(metrics, rowHeight, dockTop)) +} + +/** How far the anchor row, plus one row of margin, reaches below `visibleBottom`. */ +function anchorOverflow( + metrics: TerminalKeyboardAvoidanceMetrics, + rowHeight: number, + visibleBottom: number +): number { // Main-buffer TUI footer rows can sit below the caret. const anchorRow = Math.max(metrics.cursorY, metrics.contentBottomRow) - const anchorBottom = (anchorRow + 1) * rowHeight - const dockTop = terminalFrameHeight - keyboardLift - const margin = rowHeight - return Math.min(keyboardLift, Math.max(0, anchorBottom + margin - dockTop)) + return Math.max(0, (anchorRow + 1) * rowHeight + rowHeight - visibleBottom) } From ec7ba2ea248026fc4c80d4a3a0193759c59d015f Mon Sep 17 00:00:00 2001 From: Jinwoo-H Date: Fri, 25 Sep 2026 22:49:58 -0400 Subject: [PATCH 05/22] feat(mobile): the keyboard covers the page like a native screen, and the shell says its height The shell shortened the WebView above the IME (`MobileWebShellScreen.tsx`, `paddingBottom: keyboardInset`), so nothing covered the page and the session's keyboard logic read a height of 0. For a page that declares `keyboard-inset` in `ready.accepts`, the shell now keeps the view full size and publishes `init.keyboardInset`, the keyboard's own height as native screens read it, on every keyboard event (a height change while open included), over the route-update `init` the safe-area insets take. The bottom inset stays the window's, as natively. A page without the declaration (served by an older desktop) keeps the shortened view: it cannot see a keyboard over it. An older shell sends no field and the page reads 0. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb --- .../mobile-web-shell/MobileWebShellScreen.tsx | 39 +++-- .../mobile-web-shell/bridge-host-contract.ts | 3 + .../src/mobile-web-shell/bridge-host-route.ts | 17 ++ mobile/src/mobile-web-shell/bridge-host.ts | 9 +- .../bridge/bridge-client-init-handshake.ts | 13 +- .../bridge/bridge-client-session.ts | 4 + .../bridge/bridge-client-shell-session.ts | 18 ++- .../bridge/bridge-envelope.ts | 3 + .../bridge/bridge-init-frame.ts | 5 + .../bridge/bridge-keyboard-inset.test.ts | 97 ++++++++++++ .../bridge/bridge-keyboard-inset.ts | 15 ++ .../bridge-port-pair-test-harness.test.ts | 1 + .../bridge/bridge-port-pair-test-harness.ts | 2 + .../bridge/bridge-rpc-client-frames.test.ts | 9 +- .../bridge/bridge-rpc-client.ts | 3 + ...web-shell-keyboard-overlay-screen.test.tsx | 148 ++++++++++++++++++ .../mobile-web-shell-keyboard-state.test.ts | 33 ++++ .../mobile-web-shell-screen-test-harness.tsx | 4 + .../mobile-web-shell-screen-test-mocks.tsx | 3 +- .../mobile-web-shell-session-contract.ts | 3 + .../mobile-web-shell-session.ts | 1 + .../mobile-web-shell/page-document-state.ts | 14 +- .../page-safe-area-insets.test.ts | 16 +- .../mobile-web-shell/page-safe-area-insets.ts | 12 +- .../use-mobile-web-shell-bridge.test.ts | 1 + .../use-mobile-web-shell-bridge.ts | 14 ++ .../use-mobile-web-shell-session.ts | 10 +- 27 files changed, 457 insertions(+), 40 deletions(-) create mode 100644 mobile/src/mobile-web-shell/bridge/bridge-keyboard-inset.test.ts create mode 100644 mobile/src/mobile-web-shell/bridge/bridge-keyboard-inset.ts create mode 100644 mobile/src/mobile-web-shell/mobile-web-shell-keyboard-overlay-screen.test.tsx create mode 100644 mobile/src/mobile-web-shell/mobile-web-shell-keyboard-state.test.ts diff --git a/mobile/src/mobile-web-shell/MobileWebShellScreen.tsx b/mobile/src/mobile-web-shell/MobileWebShellScreen.tsx index 83d6d1724998..331512863e9f 100644 --- a/mobile/src/mobile-web-shell/MobileWebShellScreen.tsx +++ b/mobile/src/mobile-web-shell/MobileWebShellScreen.tsx @@ -178,16 +178,6 @@ export function MobileWebShellScreen({ runtime }: MobileWebShellScreenProps) { const insets = useSafeAreaInsets() - // The page cannot see the IME for itself: edge-to-edge makes the manifest's `adjustResize` inert, - // so the window never shrinks and `visualViewport` inside the WebView reads full height with the - // keyboard up — the session route lays its live input row out under the keys. The shell owns the - // window, so it takes the strip off the view and the page lays out in what is left. - const keyboardHeight = useKeyboardOcclusion() - const keyboardInset = softwareKeyboardWindowInset({ - keyboardHeight, - bottomInset: insets.bottom, - platform: Platform.OS - }) const router = useRouter() const navigation = useNavigation() const popShellStack = useShellStackPop() @@ -208,16 +198,28 @@ export function MobileWebShellScreen({ pageReady, pageFrame, backClaimed, - pageOwnsSafeArea + pageOwnsSafeArea, + pageReadsKeyboardInset } = useMobileWebShellSession({ hostId, routePathname: route.pathname, runtime }) // Which mount the notice was dismissed on, not whether it was: a later refusal opens its own // generation under a new session id, so it is not silenced by a tap on the one before it. const [noticeDismissedFor, setNoticeDismissedFor] = useState(null) const noticeShown = updateNotice !== null && state.kind === 'ready' && noticeDismissedFor !== state.sessionId + // The page cannot see the IME for itself: edge-to-edge makes `adjustResize` inert and the view's + // IME insets are zeroed, so `visualViewport` never shrinks. A page that reads the height from + // `init` is covered by the keyboard like a native screen; an older one gets a view ended above it. + const keyboardHeight = useKeyboardOcclusion() + const viewShortenedBy = pageReadsKeyboardInset + ? 0 + : softwareKeyboardWindowInset({ + keyboardHeight, + bottomInset: insets.bottom, + platform: Platform.OS + }) const pageInsets = pageSafeAreaInsets({ insets, - keyboardInset, + viewShortenedBy, topCovered: noticeShown }) const { snapshot, unreadable, readStorage, refreshStorage, writeStorage } = usePageHostSnapshot( @@ -242,6 +244,7 @@ export function MobileWebShellScreen({ hostId, route, safeAreaInsets: pageInsets, + keyboardInset: keyboardHeight, pageRoutes, pageRouteGrants, routeGrants, @@ -323,6 +326,11 @@ export function MobileWebShellScreen({ }, [publishRoute, route]) usePublishedSafeAreaInsets(bridge.publishSafeAreaInsets, pageInsets) + // Every keyboard event, a height change while open included, so the page never holds a stale one. + const publishKeyboardInset = bridge.publishKeyboardInset + useEffect(() => { + publishKeyboardInset(keyboardHeight) + }, [publishKeyboardInset, keyboardHeight]) // The navigation object rather than the router: what this takes away is this screen's own place // on the stack, which is a screen option, and the router has no member that says it. @@ -373,11 +381,10 @@ export function MobileWebShellScreen({ style={[ styles.shellRoot, // Edge-to-edge like a native screen, for a page that pads for the bars itself; an older page - // keeps the strips. The keyboard strip stays off either way, since the page cannot see it, - // and the banner takes the status bar strip when it shows. + // keeps the strips. The banner takes the status bar strip when it shows. pageOwnsSafeArea - ? { paddingTop: noticeShown ? insets.top : 0, paddingBottom: keyboardInset } - : { paddingTop: insets.top, paddingBottom: Math.max(insets.bottom, keyboardInset) } + ? { paddingTop: noticeShown ? insets.top : 0, paddingBottom: viewShortenedBy } + : { paddingTop: insets.top, paddingBottom: Math.max(insets.bottom, viewShortenedBy) } ]} testID="mobile-web-shell-ready" > diff --git a/mobile/src/mobile-web-shell/bridge-host-contract.ts b/mobile/src/mobile-web-shell/bridge-host-contract.ts index f360fdc0d964..9253fad99a0d 100644 --- a/mobile/src/mobile-web-shell/bridge-host-contract.ts +++ b/mobile/src/mobile-web-shell/bridge-host-contract.ts @@ -133,6 +133,9 @@ export type BridgeHostOptions = { /** How much of the WebView sits under a system bar when it is drawn edge-to-edge. Zeros when * absent; moved later with `publishSafeAreaInsets`. */ safeAreaInsets?: BridgeSafeAreaInsets + /** How much of the WebView the software keyboard covers. 0 when absent; moved later with + * `publishKeyboardInset`. */ + keyboardInset?: number /** * This device's identity to that host, as the native screens already send it, swapped in for the * page's placeholder on the way out. Read at forward time rather than captured: the host outlives diff --git a/mobile/src/mobile-web-shell/bridge-host-route.ts b/mobile/src/mobile-web-shell/bridge-host-route.ts index 055932a5ffeb..1b6144d88d73 100644 --- a/mobile/src/mobile-web-shell/bridge-host-route.ts +++ b/mobile/src/mobile-web-shell/bridge-host-route.ts @@ -10,6 +10,7 @@ import { ZERO_SAFE_AREA_INSETS, type BridgeSafeAreaInsets } from './bridge/bridge-safe-area-insets' +import { BRIDGE_KEYBOARD_INSET_ACCEPT } from './bridge/bridge-keyboard-inset' /** The screen one host is serving, which is the one field of `init` that moves under a live page. */ export type BridgeHostRoute = { @@ -40,6 +41,10 @@ export type BridgeHostRoute = { * lane as a pane update: held either way, so the next `ready` carries them. */ readonly publishSafeAreaInsets: (next: BridgeSafeAreaInsets, deliverable: boolean) => void + /** The keyboard height the next `init` carries. */ + readonly keyboardInset: () => number + /** Moves the held keyboard height on the same lane as the insets, to a page that reads it. */ + readonly publishKeyboardInset: (next: number, deliverable: boolean) => void } /** @@ -65,11 +70,13 @@ export function createBridgeHostRoute(args: { sendInit: () => void onRefused: (issue: string) => void safeAreaInsets?: BridgeSafeAreaInsets + keyboardInset?: number }): BridgeHostRoute { const parsed = BridgeInitRouteSchema.safeParse(args.opened) let route = parsed.success && !args.refused ? parsed.data : null let accepts: readonly string[] = [] let insets = args.safeAreaInsets ?? ZERO_SAFE_AREA_INSETS + let keyboard = args.keyboardInset ?? 0 return { current: () => route, openIssue: () => (parsed.success ? 'unknown' : (parsed.error.issues[0]?.message ?? 'unknown')), @@ -97,6 +104,16 @@ export function createBridgeHostRoute(args: { if (deliverable && accepts.includes(BRIDGE_SAFE_AREA_ACCEPT)) { args.sendInit() } + }, + keyboardInset: () => keyboard, + publishKeyboardInset: (next, deliverable) => { + if (keyboard === next) { + return + } + keyboard = next + if (deliverable && accepts.includes(BRIDGE_KEYBOARD_INSET_ACCEPT)) { + args.sendInit() + } } } } diff --git a/mobile/src/mobile-web-shell/bridge-host.ts b/mobile/src/mobile-web-shell/bridge-host.ts index 28e25c2e452a..a34ad4c1bd4f 100644 --- a/mobile/src/mobile-web-shell/bridge-host.ts +++ b/mobile/src/mobile-web-shell/bridge-host.ts @@ -42,6 +42,8 @@ export type BridgeHost = { publishRoute: (next: BridgeInitRoute) => void /** Hands this session moved safe-area insets over the same re-sent `init` a route update takes. */ publishSafeAreaInsets: (next: BridgeSafeAreaInsets) => void + /** Hands this session a moved keyboard height over the same re-sent `init`. */ + publishKeyboardInset: (next: number) => void /** * Hands the page one Back press. False when this document never said it takes one, which is * every page older than the frame; the caller then leaves the key to the navigator. @@ -87,7 +89,8 @@ export function createBridgeHost(options: BridgeHostOptions): BridgeHost { sendInit() }, onRefused: (issue) => options.onDiagnostic?.({ kind: 'route-update-refused', issue }), - ...(options.safeAreaInsets === undefined ? {} : { safeAreaInsets: options.safeAreaInsets }) + ...(options.safeAreaInsets === undefined ? {} : { safeAreaInsets: options.safeAreaInsets }), + ...(options.keyboardInset === undefined ? {} : { keyboardInset: options.keyboardInset }) }) let closed = false // One document's turn at the bridge. `close` ends it and the next `ready` begins the next one; @@ -163,6 +166,7 @@ export function createBridgeHost(options: BridgeHostOptions): BridgeHost { connection: snapshot(), route, safeAreaInsets: routes.safeAreaInsets(), + keyboardInset: routes.keyboardInset(), pageRoutes, ...(parsedRouteGrants?.success === true ? { pageRouteGrants: parsedRouteGrants.data } @@ -337,6 +341,9 @@ export function createBridgeHost(options: BridgeHostOptions): BridgeHost { publishSafeAreaInsets: (next) => { routes.publishSafeAreaInsets(next, deliverable()) }, + publishKeyboardInset: (next) => { + routes.publishKeyboardInset(next, deliverable()) + }, sendBack: back.send, readSessionBack: back.read, dispose diff --git a/mobile/src/mobile-web-shell/bridge/bridge-client-init-handshake.ts b/mobile/src/mobile-web-shell/bridge/bridge-client-init-handshake.ts index 609016f033e4..7f7ee6e8d6dc 100644 --- a/mobile/src/mobile-web-shell/bridge/bridge-client-init-handshake.ts +++ b/mobile/src/mobile-web-shell/bridge/bridge-client-init-handshake.ts @@ -3,6 +3,7 @@ import { BRIDGE_BACK_FRAME } from './bridge-page-back' import { BRIDGE_PAGE_PAINTED } from './bridge-page-painted' import { BRIDGE_ROUTE_UPDATE_ACCEPT } from './bridge-route-update' import { BRIDGE_SAFE_AREA_ACCEPT } from './bridge-safe-area-insets' +import { BRIDGE_KEYBOARD_INSET_ACCEPT } from './bridge-keyboard-inset' /** The page asks again until the shell answers; a session has no other way to start. */ export const BRIDGE_READY_RETRY_MIN_MS = 50 @@ -56,14 +57,20 @@ export function createBridgeInitHandshake(ask: () => void): BridgeInitHandshake /** * What the page says on every ask, because the shell reads it off whichever `ready` it answers. * `accepts` is what this page build can be sent: a second `init` for the session it holds, the - * Back frame, and insets it pads for itself. `reports` runs the other way: what a shell may wait - * for this page to post, and the shell holds a frame over the view until it arrives. + * Back frame, insets it pads for itself, and the keyboard height it lifts by. `reports` runs the + * other way: what a shell may wait for this page to post, and the shell holds a frame over the view + * until it arrives. */ export function createPageReadyFrame(): Extract { return { v: BRIDGE_PROTOCOL_VERSION, type: 'ready', - accepts: [BRIDGE_ROUTE_UPDATE_ACCEPT, BRIDGE_BACK_FRAME, BRIDGE_SAFE_AREA_ACCEPT], + accepts: [ + BRIDGE_ROUTE_UPDATE_ACCEPT, + BRIDGE_BACK_FRAME, + BRIDGE_SAFE_AREA_ACCEPT, + BRIDGE_KEYBOARD_INSET_ACCEPT + ], reports: [BRIDGE_PAGE_PAINTED] } } diff --git a/mobile/src/mobile-web-shell/bridge/bridge-client-session.ts b/mobile/src/mobile-web-shell/bridge/bridge-client-session.ts index 02d8a5348297..a4ec43d48ace 100644 --- a/mobile/src/mobile-web-shell/bridge/bridge-client-session.ts +++ b/mobile/src/mobile-web-shell/bridge/bridge-client-session.ts @@ -27,6 +27,9 @@ export type BridgeShellSession = { /** How much of the WebView sits under a system bar. Zeros for a shell that reserves the bars * outside the view, which is every shell before the field. */ safeAreaInsets: BridgeSafeAreaInsets + /** How much of the WebView the software keyboard covers. 0 for a shell that shortens the view + * above it instead, which is every shell before the field. */ + keyboardInset: number /** Null for a shell too old to name it; the page's own `loadHosts()` then answers with nothing. */ host: BridgeInitHost | null /** The allowlisted keys as the app held them when this page opened. */ @@ -61,6 +64,7 @@ export function readShellSession( pageRoutes: message.pageRoutes ?? [], pageRouteGrants: message.pageRouteGrants ?? null, safeAreaInsets: message.safeAreaInsets ?? ZERO_SAFE_AREA_INSETS, + keyboardInset: message.keyboardInset ?? 0, host: message.host ?? null, storage: message.storage ?? {}, storageOversize: message.storageOversize ?? [], diff --git a/mobile/src/mobile-web-shell/bridge/bridge-client-shell-session.ts b/mobile/src/mobile-web-shell/bridge/bridge-client-shell-session.ts index db5614119e86..03181a4e03fd 100644 --- a/mobile/src/mobile-web-shell/bridge/bridge-client-shell-session.ts +++ b/mobile/src/mobile-web-shell/bridge/bridge-client-shell-session.ts @@ -31,6 +31,8 @@ export type BridgeClientShellSession = { onRouteUpdate: (listener: (route: BridgeInitRoute | null) => void) => () => void /** Fires when an `init` moved the safe-area insets the page holds, including a replacement's. */ onSafeAreaInsetsUpdate: (listener: (insets: BridgeSafeAreaInsets) => void) => () => void + /** Fires when an `init` moved the keyboard height the page holds, including a replacement's. */ + onKeyboardInsetUpdate: (listener: (height: number) => void) => () => void /** Drops the session and every listener waiting on one, which `close` is the only caller of. */ close: () => void } @@ -45,6 +47,7 @@ export function createBridgeClientShellSession(args: { const readyListeners = new Set<() => void>() const routeUpdateListeners = new Set<(route: BridgeInitRoute | null) => void>() const insetsListeners = new Set<(insets: BridgeSafeAreaInsets) => void>() + const keyboardListeners = new Set<(height: number) => void>() return { current: () => session, @@ -62,10 +65,12 @@ export function createBridgeClientShellSession(args: { // The held object when the values match, so a reader keyed on identity does not re-render // for a re-asked `ready`. const safeAreaInsets = held === null || movedInsets ? sent : held.safeAreaInsets + const keyboardInset = message.keyboardInset ?? 0 + const movedKeyboard = held !== null && held.keyboardInset !== keyboardInset session = update === null ? { ...readShellSession(message), safeAreaInsets } - : { ...update, route: message.route ?? null, safeAreaInsets } + : { ...update, route: message.route ?? null, safeAreaInsets, keyboardInset } // Re-primed either way, because a second `init` is also how the page recovers a cache it has // refused a `state` frame into: the shell rebuilt under it publishes a generation the page's // own is newer than, and this frame is what puts the two back in step. A pane update carries @@ -80,6 +85,11 @@ export function createBridgeClientShellSession(args: { listener(safeAreaInsets) } } + if (movedKeyboard) { + for (const listener of keyboardListeners) { + listener(keyboardInset) + } + } // Only a route that moved is an update. The shell answers every `ready` with the route it // holds, and the page re-asks after a refused `state` frame, so publishing each of those // would hand the pane hook the route it is already on. @@ -114,6 +124,12 @@ export function createBridgeClientShellSession(args: { insetsListeners.delete(listener) } }, + onKeyboardInsetUpdate: (listener) => { + keyboardListeners.add(listener) + return () => { + keyboardListeners.delete(listener) + } + }, close: () => { session = null readyListeners.clear() diff --git a/mobile/src/mobile-web-shell/bridge/bridge-envelope.ts b/mobile/src/mobile-web-shell/bridge/bridge-envelope.ts index ae8729f96ce5..17ea2330fe22 100644 --- a/mobile/src/mobile-web-shell/bridge/bridge-envelope.ts +++ b/mobile/src/mobile-web-shell/bridge/bridge-envelope.ts @@ -7,6 +7,7 @@ import { BridgeErrorCaptureSchema } from './bridge-error-capture' import { BridgeInitRouteSchema, type BridgeInitRoute } from './bridge-init-route' import { BridgePageRouteGrantsSchema } from './bridge-page-route-grants' import { BridgeSafeAreaInsetsSchema } from './bridge-safe-area-insets' +import { BridgeKeyboardInsetSchema } from './bridge-keyboard-inset' import { BridgeNotifySchema } from './bridge-notify-envelope' import { BRIDGE_BACK_FRAME } from './bridge-page-back' import { BRIDGE_ID_PATTERN, idSchema, methodSchema, versionSchema } from './bridge-frame-fields' @@ -307,6 +308,8 @@ const BridgeHostMessageSchema = z.union([ route: BridgeInitRouteSchema.optional(), /** How much of the WebView is under a system bar; absent reads as zeros. */ safeAreaInsets: BridgeSafeAreaInsetsSchema.optional(), + /** How much of the WebView the software keyboard covers; absent reads as 0. */ + keyboardInset: BridgeKeyboardInsetSchema.optional(), host: BridgeInitHostSchema.optional(), storage: BridgeInitStorageSchema.optional(), /** diff --git a/mobile/src/mobile-web-shell/bridge/bridge-init-frame.ts b/mobile/src/mobile-web-shell/bridge/bridge-init-frame.ts index 582ed79548c1..a350a5124374 100644 --- a/mobile/src/mobile-web-shell/bridge/bridge-init-frame.ts +++ b/mobile/src/mobile-web-shell/bridge/bridge-init-frame.ts @@ -57,6 +57,8 @@ export function createBridgeInitFrame(args: { pageRoutes: readonly string[] /** How much of the WebView sits under a system bar, for a page that pads for them itself. */ safeAreaInsets?: BridgeSafeAreaInsets + /** How much of the WebView the software keyboard covers. */ + keyboardInset?: number /** What each of those patterns declared, so the page can tell a hop it may keep from one it * must hand back. Omitted by a shell that has none, which leaves the page on its old rule. */ pageRouteGrants?: readonly { pathname: string; grants: readonly string[] }[] @@ -94,6 +96,9 @@ export function createBridgeInitFrame(args: { sameSafeAreaInsets(args.safeAreaInsets, ZERO_SAFE_AREA_INSETS) ? {} : { safeAreaInsets: { ...args.safeAreaInsets } }), + ...(args.keyboardInset === undefined || args.keyboardInset === 0 + ? {} + : { keyboardInset: args.keyboardInset }), pageRoutes: [...args.pageRoutes], // Omitted when empty for the reason `storageOversize` is: a shell that declares nothing and // one that declares an empty list are the same answer to the page's check. diff --git a/mobile/src/mobile-web-shell/bridge/bridge-keyboard-inset.test.ts b/mobile/src/mobile-web-shell/bridge/bridge-keyboard-inset.test.ts new file mode 100644 index 000000000000..8105e21ebd6e --- /dev/null +++ b/mobile/src/mobile-web-shell/bridge/bridge-keyboard-inset.test.ts @@ -0,0 +1,97 @@ +import { describe, expect, it } from 'vitest' +import { createFakeBridgePortPair } from './bridge-port-pair-test-harness' +import { readBridgeHostMessage } from './bridge-envelope' +import { createBridgeInitFrame } from './bridge-init-frame' +import { readShellSession } from './bridge-client-session' +import { BRIDGE_KEYBOARD_INSET_ACCEPT } from './bridge-keyboard-inset' +import { createPageReadyFrame } from './bridge-client-init-handshake' + +function initFrame(keyboardInset?: number) { + return createBridgeInitFrame({ + sessionId: 'session-a', + buildId: 'build-a', + connection: { + state: 'connected', + reconnectAttempt: 0, + lastConnectedAt: null, + lastInboundAt: null, + generation: null + }, + route: { pathname: '/h/host-a' }, + pageRoutes: ['/h/[hostId]'], + granted: [], + host: { id: 'host-a', name: 'Host A', endpoint: 'ws://host-a', lastConnected: 0 }, + storage: {}, + ...(keyboardInset === undefined ? {} : { keyboardInset }) + }) +} + +function readInit(json: string) { + const read = readBridgeHostMessage(json) + if (!read.ok || read.message.type !== 'init') { + throw new Error( + `not an init the page would read: ${read.ok ? read.message.type : read.refusal}` + ) + } + return read.message +} + +describe('keyboardInset on init', () => { + it('reads an init without the field as 0, which is every shell before it', () => { + const init = readInit(JSON.stringify(initFrame())) + expect('keyboardInset' in init).toBe(false) + expect(readShellSession(init).keyboardInset).toBe(0) + }) + + it('passes the keyboard height through to the session the page holds', () => { + expect(readShellSession(readInit(JSON.stringify(initFrame(312)))).keyboardInset).toBe(312) + }) + + it('omits 0, since absent and closed are the same answer', () => { + expect('keyboardInset' in initFrame(0)).toBe(false) + }) + + it('refuses an init whose keyboard no device produces', () => { + for (const bad of [-1, 1e9, Number.NaN, '312']) { + const frame = { ...initFrame(), keyboardInset: bad } + expect(readBridgeHostMessage(JSON.stringify(frame)).ok, String(bad)).toBe(false) + } + }) + + it('is declared by this page build, so the shell overlays it rather than shortening it', () => { + expect(createPageReadyFrame().accepts).toContain(BRIDGE_KEYBOARD_INSET_ACCEPT) + }) +}) + +describe('a keyboard that moves under a live page', () => { + it('re-sends init on show, height change and hide, and the page reads each in place', async () => { + const pair = createFakeBridgePortPair() + await pair.flush() + const session = pair.client.getShellSession() + expect(session?.keyboardInset).toBe(0) + const seen: number[] = [] + pair.client.onKeyboardInsetUpdate((height) => seen.push(height)) + + // Pixel_API_37: the IME opens at 312, the suggestion strip grows it by 34, then it closes. + for (const height of [312, 346, 0]) { + pair.host.publishKeyboardInset(height) + await pair.flush() + expect(pair.client.getShellSession()?.keyboardInset).toBe(height) + } + expect(seen).toEqual([312, 346, 0]) + // Same session: a keyboard update is not a replacement. + expect(pair.client.getShellSession()?.sessionId).toBe(session?.sessionId) + expect(pair.client.getShellSession()?.route).toEqual(session?.route) + }) + + it('sends nothing for a height that did not move', async () => { + const pair = createFakeBridgePortPair({ keyboardInset: 312 }) + await pair.flush() + const inits = () => pair.readToPage().filter((frame) => frame.type === 'init').length + const before = inits() + pair.host.publishKeyboardInset(312) + await pair.flush() + expect(inits()).toBe(before) + expect(pair.client.getShellSession()?.keyboardInset).toBe(312) + }) +}) diff --git a/mobile/src/mobile-web-shell/bridge/bridge-keyboard-inset.ts b/mobile/src/mobile-web-shell/bridge/bridge-keyboard-inset.ts new file mode 100644 index 000000000000..f7b5af8a9317 --- /dev/null +++ b/mobile/src/mobile-web-shell/bridge/bridge-keyboard-inset.ts @@ -0,0 +1,15 @@ +import { z } from 'zod' +import { BRIDGE_MAX_SAFE_AREA_INSET } from './bridge-safe-area-insets' + +/** + * How much of the bottom of the page's WebView the software keyboard covers, in the page's px; 0 + * while it is closed. The shell overlays the IME on the view like a native screen, and the page + * cannot measure it: the view's IME insets are zeroed, so `visualViewport` never shrinks. + */ +export const BridgeKeyboardInsetSchema = z.number().finite().min(0).max(BRIDGE_MAX_SAFE_AREA_INSET) + +/** + * What a page puts in `ready.accepts` to say it reads the keyboard from `init`. The shell overlays + * the keyboard only on such a page; an older one cannot see it, so the shell shortens its view. + */ +export const BRIDGE_KEYBOARD_INSET_ACCEPT = 'keyboard-inset' diff --git a/mobile/src/mobile-web-shell/bridge/bridge-port-pair-test-harness.test.ts b/mobile/src/mobile-web-shell/bridge/bridge-port-pair-test-harness.test.ts index 705360361db1..23eaff973669 100644 --- a/mobile/src/mobile-web-shell/bridge/bridge-port-pair-test-harness.test.ts +++ b/mobile/src/mobile-web-shell/bridge/bridge-port-pair-test-harness.test.ts @@ -43,6 +43,7 @@ describe('the bridge port pair', () => { pageRoutes: expect.any(Array), pageRouteGrants: null, safeAreaInsets: { top: 0, right: 0, bottom: 0, left: 0 }, + keyboardInset: 0, host: expect.objectContaining({ id: expect.any(String) }), storage: expect.any(Object), storageOversize: [], diff --git a/mobile/src/mobile-web-shell/bridge/bridge-port-pair-test-harness.ts b/mobile/src/mobile-web-shell/bridge/bridge-port-pair-test-harness.ts index bf9b611a540d..d187f8cfd155 100644 --- a/mobile/src/mobile-web-shell/bridge/bridge-port-pair-test-harness.ts +++ b/mobile/src/mobile-web-shell/bridge/bridge-port-pair-test-harness.ts @@ -105,6 +105,7 @@ export type BridgePortPairOptions = { /** Replaces the verb handler, for the arms where the shell refuses rather than answers. */ serveNativeVerb?: (verb: BridgeNativeVerb, params: unknown) => Promise safeAreaInsets?: BridgeSafeAreaInsets + keyboardInset?: number } type Lane = { @@ -229,6 +230,7 @@ export function createBridgePortPair( sessionId: options.sessionId ?? 'session-a', route: options.route ?? { pathname: '/h/host-a' }, ...(options.safeAreaInsets === undefined ? {} : { safeAreaInsets: options.safeAreaInsets }), + ...(options.keyboardInset === undefined ? {} : { keyboardInset: options.keyboardInset }), readClientIdentity: () => options.clientIdentity === undefined ? PORT_PAIR_CLIENT_IDENTITY : options.clientIdentity, pageRoutes: options.pageRoutes ?? ['/h/[hostId]'], diff --git a/mobile/src/mobile-web-shell/bridge/bridge-rpc-client-frames.test.ts b/mobile/src/mobile-web-shell/bridge/bridge-rpc-client-frames.test.ts index 55cff6ace69f..fcec59a53342 100644 --- a/mobile/src/mobile-web-shell/bridge/bridge-rpc-client-frames.test.ts +++ b/mobile/src/mobile-web-shell/bridge/bridge-rpc-client-frames.test.ts @@ -16,6 +16,7 @@ import { BRIDGE_BACK_FRAME } from './bridge-page-back' import { BRIDGE_PAGE_PAINTED } from './bridge-page-painted' import { BRIDGE_ROUTE_UPDATE_ACCEPT } from './bridge-route-update' import { BRIDGE_SAFE_AREA_ACCEPT } from './bridge-safe-area-insets' +import { BRIDGE_KEYBOARD_INSET_ACCEPT } from './bridge-keyboard-inset' import { BRIDGE_READY_RETRY_MAX_MS, BRIDGE_READY_RETRY_MIN_MS @@ -49,7 +50,12 @@ describe('bridge client handshake', () => { { v: BRIDGE_PROTOCOL_VERSION, type: 'ready', - accepts: [BRIDGE_ROUTE_UPDATE_ACCEPT, BRIDGE_BACK_FRAME, BRIDGE_SAFE_AREA_ACCEPT], + accepts: [ + BRIDGE_ROUTE_UPDATE_ACCEPT, + BRIDGE_BACK_FRAME, + BRIDGE_SAFE_AREA_ACCEPT, + BRIDGE_KEYBOARD_INSET_ACCEPT + ], reports: [BRIDGE_PAGE_PAINTED] } ]) @@ -141,6 +147,7 @@ describe('bridge client handshake', () => { pageRouteGrants: null, // And no insets, which is the shell that reserves the bar strips outside the view. safeAreaInsets: { top: 0, right: 0, bottom: 0, left: 0 }, + keyboardInset: 0, // And no host and no stored keys, which is what `host-store.web.ts` then answers with. host: null, storage: {}, diff --git a/mobile/src/mobile-web-shell/bridge/bridge-rpc-client.ts b/mobile/src/mobile-web-shell/bridge/bridge-rpc-client.ts index 452bcceb57c3..113f381dd2ae 100644 --- a/mobile/src/mobile-web-shell/bridge/bridge-rpc-client.ts +++ b/mobile/src/mobile-web-shell/bridge/bridge-rpc-client.ts @@ -77,6 +77,8 @@ export type BridgeRpcClient = RpcClient & { onRouteUpdate: (listener: (route: BridgeInitRoute | null) => void) => () => void /** Fires when an `init` moved the safe-area insets; the value itself is on `getShellSession`. */ onSafeAreaInsetsUpdate: (listener: (insets: BridgeSafeAreaInsets) => void) => () => void + /** Fires when an `init` moved the keyboard height; the value itself is on `getShellSession`. */ + onKeyboardInsetUpdate: (listener: (height: number) => void) => () => void getShellSession: () => BridgeShellSession | null /** * Asks the shell to open a screen this page does not render. False when the shell granted no @@ -465,6 +467,7 @@ export function createBridgeRpcClient(options: BridgeRpcClientOptions): BridgeRp onReady: shellSession.onReady, onRouteUpdate: shellSession.onRouteUpdate, onSafeAreaInsetsUpdate: shellSession.onSafeAreaInsetsUpdate, + onKeyboardInsetUpdate: shellSession.onKeyboardInsetUpdate, getShellSession: shellSession.current, clearRouteParam: (param, value) => shellSession.current()?.accepts.includes(BRIDGE_ROUTE_PARAM_CLEAR) === true && diff --git a/mobile/src/mobile-web-shell/mobile-web-shell-keyboard-overlay-screen.test.tsx b/mobile/src/mobile-web-shell/mobile-web-shell-keyboard-overlay-screen.test.tsx new file mode 100644 index 000000000000..68ae95d5e95e --- /dev/null +++ b/mobile/src/mobile-web-shell/mobile-web-shell-keyboard-overlay-screen.test.tsx @@ -0,0 +1,148 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +const harness = await vi.hoisted(async () => await import('./mobile-web-shell-screen-test-harness')) +const dependencies = vi.hoisted(() => harness.createScreenDependencies()) + +const { screenModuleMocks } = await vi.hoisted( + async () => await import('./mobile-web-shell-screen-test-mocks') +) +const mocks = vi.hoisted(() => screenModuleMocks(dependencies)) +vi.mock('react-native', mocks['react-native']) +vi.mock('expo-clipboard', mocks['expo-clipboard']) +vi.mock('expo-haptics', mocks['expo-haptics']) +vi.mock('expo-document-picker', mocks['expo-document-picker']) +vi.mock('@orca/expo-two-way-audio', mocks['@orca/expo-two-way-audio']) +vi.mock('expo-keep-awake', mocks['expo-keep-awake']) +vi.mock('expo-image-picker', mocks['expo-image-picker']) +vi.mock('expo-file-system', mocks['expo-file-system']) +vi.mock('lucide-react-native', mocks['lucide-react-native']) +vi.mock('react-native-safe-area-context', mocks['react-native-safe-area-context']) +vi.mock('expo-router', mocks['expo-router']) +vi.mock('../../modules/orca-mobile-web-shell/src', mocks['../../modules/orca-mobile-web-shell/src']) +vi.mock('../transport/client-context', mocks['../transport/client-context']) +vi.mock('./use-page-host-snapshot', mocks['./use-page-host-snapshot']) +vi.mock('./use-mobile-web-shell-session', mocks['./use-mobile-web-shell-session']) + +import { act } from 'react-test-renderer' +import { clientFrame, createFakeRpcClient } from './bridge-host-test-fakes' +import { + byName, + readyState, + renderScreen as mountScreen +} from './mobile-web-shell-screen-test-harness' +import { readBridgeHostMessage } from './bridge/bridge-envelope' +import { BRIDGE_KEYBOARD_INSET_ACCEPT } from './bridge/bridge-keyboard-inset' +import { BRIDGE_ROUTE_UPDATE_ACCEPT } from './bridge/bridge-route-update' +import { BRIDGE_SAFE_AREA_ACCEPT } from './bridge/bridge-safe-area-insets' +import { MobileWebShellScreen } from './MobileWebShellScreen' +import type { MobileWebShellSessionState } from './mobile-web-shell-session-contract' +import type { ReactTestRenderer } from 'react-test-renderer' + +const renderScreen = (state: MobileWebShellSessionState): Promise => + mountScreen(MobileWebShellScreen, dependencies, state) + +afterEach(harness.unmountRenderedScreens) + +beforeEach(() => { + harness.resetScreenDependencies(dependencies) +}) + +const WINDOW = { top: 44, right: 0, bottom: 8, left: 0 } + +/** + * A page that reads the keyboard from `init` is covered by it like a native screen: the view keeps + * its size, and the page is told the height on every keyboard event. + */ +describe('a page the keyboard covers', () => { + async function openPage(sessionId: string) { + dependencies.client = createFakeRpcClient() + dependencies.pageOwnsSafeArea = true + dependencies.pageReadsKeyboardInset = true + const tree = await renderScreen(readyState(sessionId)) + await act(async () => { + byName(tree, 'ShellViewProbe')[0]?.props.onBridgeMessage({ + nativeEvent: { + json: clientFrame({ + type: 'ready', + accepts: [ + BRIDGE_ROUTE_UPDATE_ACCEPT, + BRIDGE_SAFE_AREA_ACCEPT, + BRIDGE_KEYBOARD_INSET_ACCEPT + ] + }) + } + }) + }) + const root = () => tree.root.find((node) => node.props.testID === 'mobile-web-shell-ready') + const inits = () => + dependencies.posted.flatMap((json) => { + const read = readBridgeHostMessage(json) + return read.ok && read.message.type === 'init' + ? [{ keyboard: read.message.keyboardInset ?? 0, insets: read.message.safeAreaInsets }] + : [] + }) + const keyboard = async (height: number) => { + await act(async () => { + const ios = dependencies.platform === 'ios' + const name = + height > 0 + ? ios + ? 'keyboardWillShow' + : 'keyboardDidShow' + : ios + ? 'keyboardWillHide' + : 'keyboardDidHide' + dependencies.keyboardListeners.get(name)?.({ endCoordinates: { height } }) + }) + } + return { root, inits, keyboard } + } + + for (const platform of ['ios', 'android'] as const) { + it(`never shortens the view, and publishes show, a height change and hide (${platform})`, async () => { + dependencies.platform = platform + const page = await openPage(`session-overlay-${platform}`) + // Pixel_API_37: 312 up, 346 with the suggestion strip, then closed. The inset tracks each, so + // a keyboard that changes height while open leaves no gap above it. + for (const height of [312, 346, 0]) { + await page.keyboard(height) + expect(page.root().props.style[1]).toEqual({ paddingTop: 0, paddingBottom: 0 }) + } + // The keyboard's own height, as native screens read it; the bottom inset stays the window's. + expect(page.inits()).toEqual([ + { keyboard: 0, insets: WINDOW }, + { keyboard: 312, insets: WINDOW }, + { keyboard: 346, insets: WINDOW }, + { keyboard: 0, insets: WINDOW } + ]) + }) + } + + it('still shortens the view for an older page that cannot read the keyboard', async () => { + dependencies.platform = 'android' + dependencies.client = createFakeRpcClient() + dependencies.pageOwnsSafeArea = true + const tree = await renderScreen(readyState('session-older-keyboard')) + await act(async () => { + byName(tree, 'ShellViewProbe')[0]?.props.onBridgeMessage({ + nativeEvent: { + json: clientFrame({ + type: 'ready', + accepts: [BRIDGE_ROUTE_UPDATE_ACCEPT, BRIDGE_SAFE_AREA_ACCEPT] + }) + } + }) + }) + await act(async () => { + dependencies.keyboardListeners.get('keyboardDidShow')?.({ endCoordinates: { height: 336 } }) + }) + const root = tree.root.find((node) => node.props.testID === 'mobile-web-shell-ready') + expect(root.props.style[1]).toEqual({ paddingTop: 0, paddingBottom: 344 }) + // The first `init` and the insets move; the keyboard itself sends nothing to this page. + const inits = dependencies.posted.filter((json) => { + const read = readBridgeHostMessage(json) + return read.ok && read.message.type === 'init' + }) + expect(inits).toHaveLength(2) + }) +}) diff --git a/mobile/src/mobile-web-shell/mobile-web-shell-keyboard-state.test.ts b/mobile/src/mobile-web-shell/mobile-web-shell-keyboard-state.test.ts new file mode 100644 index 000000000000..2336ec77c73c --- /dev/null +++ b/mobile/src/mobile-web-shell/mobile-web-shell-keyboard-state.test.ts @@ -0,0 +1,33 @@ +import { describe, expect, it } from 'vitest' +import { readySession, run } from './mobile-web-shell-session-test-fixtures' +import { BRIDGE_KEYBOARD_INSET_ACCEPT } from './bridge/bridge-keyboard-inset' +import { shellPageReadsKeyboardInset } from './page-document-state' + +/** Whether the shell may let the keyboard cover the view, which only the document on screen can say. */ +describe('the page declaring it reads the keyboard from init', () => { + const reads = () => + run(readySession().session, { + type: 'page-ready', + reports: [], + accepts: [BRIDGE_KEYBOARD_INSET_ACCEPT] + }) + + it('is read off the ready that declared it', () => { + expect(shellPageReadsKeyboardInset(reads().session)).toBe(true) + }) + + it('is false for a page that did not declare it, which is every page before the name', () => { + const older = run(readySession().session, { type: 'page-ready', reports: [], accepts: [] }) + expect(shellPageReadsKeyboardInset(older.session)).toBe(false) + }) + + it('is dropped when a replacement document starts, so the next one has to say it again', () => { + const started = run(reads().session, { type: 'document-started' }) + expect(shellPageReadsKeyboardInset(started.session)).toBe(false) + }) + + it('is not read once the generation is off screen', () => { + const failed = run(reads().session, { type: 'shell-failed', reason: 'document-load-failed' }) + expect(shellPageReadsKeyboardInset(failed.session)).toBe(false) + }) +}) diff --git a/mobile/src/mobile-web-shell/mobile-web-shell-screen-test-harness.tsx b/mobile/src/mobile-web-shell/mobile-web-shell-screen-test-harness.tsx index 64135cef2485..05b51a6a6645 100644 --- a/mobile/src/mobile-web-shell/mobile-web-shell-screen-test-harness.tsx +++ b/mobile/src/mobile-web-shell/mobile-web-shell-screen-test-harness.tsx @@ -57,6 +57,8 @@ export type ScreenDependencies = { backClaimed: boolean /** Whether the session says the page pads for the system bars itself. */ pageOwnsSafeArea: boolean + /** Whether the session says the page reads the keyboard from `init`. */ + pageReadsKeyboardInset: boolean /** What `Platform.OS` answers, which picks the keyboard events and the IME strip. */ platform: 'ios' | 'android' reportPageBackClaim: Mock @@ -115,6 +117,7 @@ export function createScreenDependencies(): ScreenDependencies { setScreenOptions: vi.fn(), backClaimed: false, pageOwnsSafeArea: false, + pageReadsKeyboardInset: false, platform: 'ios', reportPageBackClaim: vi.fn(), sendBackDelivers: true, @@ -155,6 +158,7 @@ export function resetScreenDependencies(dependencies: ScreenDependencies): void dependencies.reportPageBackClaim.mockReset() dependencies.backClaimed = false dependencies.pageOwnsSafeArea = false + dependencies.pageReadsKeyboardInset = false dependencies.platform = 'ios' dependencies.sendBackDelivers = true dependencies.backSends = 0 diff --git a/mobile/src/mobile-web-shell/mobile-web-shell-screen-test-mocks.tsx b/mobile/src/mobile-web-shell/mobile-web-shell-screen-test-mocks.tsx index c622c77f11d5..39564c3ba83e 100644 --- a/mobile/src/mobile-web-shell/mobile-web-shell-screen-test-mocks.tsx +++ b/mobile/src/mobile-web-shell/mobile-web-shell-screen-test-mocks.tsx @@ -181,7 +181,8 @@ export function screenModuleMocks(dependencies: ScreenDependencies) { pageReady: dependencies.pageReady, pageFrame: dependencies.pageFrame, backClaimed: dependencies.backClaimed, - pageOwnsSafeArea: dependencies.pageOwnsSafeArea + pageOwnsSafeArea: dependencies.pageOwnsSafeArea, + pageReadsKeyboardInset: dependencies.pageReadsKeyboardInset }) }) } diff --git a/mobile/src/mobile-web-shell/mobile-web-shell-session-contract.ts b/mobile/src/mobile-web-shell/mobile-web-shell-session-contract.ts index 98f0df8a9007..ab62620914b7 100644 --- a/mobile/src/mobile-web-shell/mobile-web-shell-session-contract.ts +++ b/mobile/src/mobile-web-shell/mobile-web-shell-session-contract.ts @@ -267,6 +267,9 @@ export type MobileWebShellSession = { /** Whether this document pads for the system bars itself, so the view may go edge-to-edge. * Cleared with `pageReady`, and false for every page built before the declaration existed. */ readonly pageOwnsSafeArea: boolean + /** Whether this document reads the keyboard height from `init`, so the keyboard may cover the + * view. Cleared with `pageReady`, and false for every page built before the declaration. */ + readonly pageReadsKeyboardInset: boolean /** The gates the current step was taken on; null until the first one arrives. */ readonly gates: MobileWebShellGates | null readonly cached: CachedGeneration | null diff --git a/mobile/src/mobile-web-shell/mobile-web-shell-session.ts b/mobile/src/mobile-web-shell/mobile-web-shell-session.ts index 5a0a25b7db68..c325d300557e 100644 --- a/mobile/src/mobile-web-shell/mobile-web-shell-session.ts +++ b/mobile/src/mobile-web-shell/mobile-web-shell-session.ts @@ -43,6 +43,7 @@ export function createMobileWebShellSession(routePathname: string): MobileWebShe pagePainted: false, pageBackClaimed: false, pageOwnsSafeArea: false, + pageReadsKeyboardInset: false, gates: null, cached: null, updateNotice: null, diff --git a/mobile/src/mobile-web-shell/page-document-state.ts b/mobile/src/mobile-web-shell/page-document-state.ts index 935f201d346f..c25b4552bfd6 100644 --- a/mobile/src/mobile-web-shell/page-document-state.ts +++ b/mobile/src/mobile-web-shell/page-document-state.ts @@ -1,5 +1,6 @@ import { BRIDGE_PAGE_PAINTED } from './bridge/bridge-page-painted' import { BRIDGE_SAFE_AREA_ACCEPT } from './bridge/bridge-safe-area-insets' +import { BRIDGE_KEYBOARD_INSET_ACCEPT } from './bridge/bridge-keyboard-inset' import type { MobileWebShellSession, MobileWebShellSessionEvent @@ -11,7 +12,8 @@ export const CLEAR_PAGE_DOCUMENT_STATE = { pageReportsPaint: false, pagePainted: false, pageBackClaimed: false, - pageOwnsSafeArea: false + pageOwnsSafeArea: false, + pageReadsKeyboardInset: false } as const /** The three things a document reports about itself, as the reducer receives them. */ @@ -42,7 +44,8 @@ export function pageDocumentStatePatch( pageReady: true, pageReportsPaint: event.reports.includes(BRIDGE_PAGE_PAINTED), pageBackClaimed: false, - pageOwnsSafeArea: event.accepts.includes(BRIDGE_SAFE_AREA_ACCEPT) + pageOwnsSafeArea: event.accepts.includes(BRIDGE_SAFE_AREA_ACCEPT), + pageReadsKeyboardInset: event.accepts.includes(BRIDGE_KEYBOARD_INSET_ACCEPT) } } // Kept off a page that never said it would report: acting on an unasked-for frame would make @@ -57,3 +60,10 @@ export function shellPageOwnsSafeArea( ): boolean { return session.state.kind === 'ready' && session.pageOwnsSafeArea } + +/** Whether the shell may let the keyboard cover the view, gated on `ready` the same way. */ +export function shellPageReadsKeyboardInset( + session: Pick +): boolean { + return session.state.kind === 'ready' && session.pageReadsKeyboardInset +} diff --git a/mobile/src/mobile-web-shell/page-safe-area-insets.test.ts b/mobile/src/mobile-web-shell/page-safe-area-insets.test.ts index 76877567b31c..8b0cf1758b7f 100644 --- a/mobile/src/mobile-web-shell/page-safe-area-insets.test.ts +++ b/mobile/src/mobile-web-shell/page-safe-area-insets.test.ts @@ -5,20 +5,22 @@ const WINDOW = { top: 52, right: 12, bottom: 24, left: 12 } describe('the insets the page pads for', () => { it('is the window insets while nothing of the shell stands over the view', () => { - expect(pageSafeAreaInsets({ insets: WINDOW, keyboardInset: 0, topCovered: false })).toEqual( + expect(pageSafeAreaInsets({ insets: WINDOW, viewShortenedBy: 0, topCovered: false })).toEqual( WINDOW ) }) - it('has no bottom while the keyboard ends the view above the gesture bar', () => { - expect(pageSafeAreaInsets({ insets: WINDOW, keyboardInset: 360, topCovered: false })).toEqual({ - ...WINDOW, - bottom: 0 - }) + it("has no bottom while the shell ends an older page's view above the gesture bar", () => { + expect(pageSafeAreaInsets({ insets: WINDOW, viewShortenedBy: 360, topCovered: false })).toEqual( + { + ...WINDOW, + bottom: 0 + } + ) }) it('has no top while the shell banner takes the status bar strip', () => { - expect(pageSafeAreaInsets({ insets: WINDOW, keyboardInset: 0, topCovered: true })).toEqual({ + expect(pageSafeAreaInsets({ insets: WINDOW, viewShortenedBy: 0, topCovered: true })).toEqual({ ...WINDOW, top: 0 }) diff --git a/mobile/src/mobile-web-shell/page-safe-area-insets.ts b/mobile/src/mobile-web-shell/page-safe-area-insets.ts index 3b9666baca95..f4ef399beb0a 100644 --- a/mobile/src/mobile-web-shell/page-safe-area-insets.ts +++ b/mobile/src/mobile-web-shell/page-safe-area-insets.ts @@ -4,25 +4,25 @@ import type { BridgeSafeAreaInsets } from './bridge/bridge-safe-area-insets' /** * The part of an edge-to-edge WebView that sits under a system bar, which is what the page pads for. * - * Not the window's insets as they are: with the keyboard up the shell already ends the view at the - * keyboard's top, so nothing of the page is under the gesture bar, and a banner the shell draws above - * the view takes the status bar strip itself. + * The window's insets, as a native screen reads them with the keyboard covering it, except where + * the shell stands over the view: an older page's view it ends at the keyboard's top has nothing + * under the gesture bar, and a banner above the view takes the status bar strip itself. */ export function pageSafeAreaInsets(input: { insets: BridgeSafeAreaInsets - keyboardInset: number + viewShortenedBy: number topCovered: boolean }): BridgeSafeAreaInsets { const { insets } = input return { top: input.topCovered ? 0 : insets.top, right: insets.right, - bottom: input.keyboardInset > 0 ? 0 : insets.bottom, + bottom: input.viewShortenedBy > 0 ? 0 : insets.bottom, left: insets.left } } -/** Hands moved insets to the page over the re-sent `init` a pane move takes: the keyboard, a +/** Hands moved insets to the page over the re-sent `init` a pane move takes: a shortened view, a * rotation, or the shell's banner. Keyed on the four numbers, so a render moves nothing. */ export function usePublishedSafeAreaInsets( publish: (insets: BridgeSafeAreaInsets) => void, diff --git a/mobile/src/mobile-web-shell/use-mobile-web-shell-bridge.test.ts b/mobile/src/mobile-web-shell/use-mobile-web-shell-bridge.test.ts index 82ed511a2234..062a57154683 100644 --- a/mobile/src/mobile-web-shell/use-mobile-web-shell-bridge.test.ts +++ b/mobile/src/mobile-web-shell/use-mobile-web-shell-bridge.test.ts @@ -151,6 +151,7 @@ function Harness(props: { // Built inline on every render, as a caller writes it: the host is not rebuilt for it. route: { pathname: '/h/host-1' }, safeAreaInsets: { top: 0, right: 0, bottom: 0, left: 0 }, + keyboardInset: 0, pageRoutes: ['/h/[hostId]'], pageRouteGrants: [{ pathname: '/h/[hostId]', grants: ['navigate', 'storage'] }], routeGrants: [ diff --git a/mobile/src/mobile-web-shell/use-mobile-web-shell-bridge.ts b/mobile/src/mobile-web-shell/use-mobile-web-shell-bridge.ts index 2489e1ef564c..1be777cfea7c 100644 --- a/mobile/src/mobile-web-shell/use-mobile-web-shell-bridge.ts +++ b/mobile/src/mobile-web-shell/use-mobile-web-shell-bridge.ts @@ -62,6 +62,8 @@ export type MobileWebShellBridgeView = { readonly publishRoute: (route: BridgeInitRoute) => void /** Hands the mounted host moved safe-area insets; dropped with no host, as a route is. */ readonly publishSafeAreaInsets: (insets: BridgeSafeAreaInsets) => void + /** Hands the mounted host a moved keyboard height; dropped with no host, as the insets are. */ + readonly publishKeyboardInset: (height: number) => void /** * Hands the mounted host one Back press. False when there is no host, or when the document it * serves never said it takes one — the caller then leaves the key to the navigator. @@ -86,6 +88,8 @@ export type MobileWebShellBridgeArgs = { route: BridgeInitRoute /** What the first `init` of a new host carries; later moves go through `publishSafeAreaInsets`. */ safeAreaInsets: BridgeSafeAreaInsets + /** What the first `init` of a new host carries; later moves go through `publishKeyboardInset`. */ + keyboardInset: number /** The route patterns the page keeps for itself; everything else comes back as `navigate`. */ pageRoutes: readonly string[] pageRouteGrants: readonly { pathname: string; grants: readonly string[] }[] @@ -195,6 +199,7 @@ export function useMobileWebShellBridge(args: MobileWebShellBridgeArgs): MobileW sessionId, route: latest.route, safeAreaInsets: latest.safeAreaInsets, + keyboardInset: latest.keyboardInset, pageRoutes: latest.pageRoutes, pageRouteGrants: latest.pageRouteGrants, routeGrants: latest.routeGrants, @@ -283,6 +288,15 @@ export function useMobileWebShellBridge(args: MobileWebShellBridgeArgs): MobileW }, [buildId, client, sessionId, snapshot] ), + publishKeyboardInset: useCallback( + (height: number) => { + const mounted = hostRef.current + if (mounted !== null && mounted.sessionId === sessionId) { + mounted.host.publishKeyboardInset(height) + } + }, + [buildId, client, sessionId, snapshot] + ), // Fenced on the session the way inbound frames are, and answering false rather than throwing // when there is no host: the caller is a hardware key handler, and a press it cannot forward // is one the navigator has to be left to answer. diff --git a/mobile/src/mobile-web-shell/use-mobile-web-shell-session.ts b/mobile/src/mobile-web-shell/use-mobile-web-shell-session.ts index da22cd69a2e2..11751ec01aa5 100644 --- a/mobile/src/mobile-web-shell/use-mobile-web-shell-session.ts +++ b/mobile/src/mobile-web-shell/use-mobile-web-shell-session.ts @@ -24,7 +24,7 @@ import type { MobileWebShellUpdateNotice, PageReadyDeclaration } from './mobile-web-shell-session-contract' -import { shellPageOwnsSafeArea } from './page-document-state' +import { shellPageOwnsSafeArea, shellPageReadsKeyboardInset } from './page-document-state' export type MobileWebShellSessionView = { readonly state: MobileWebShellSessionState @@ -65,6 +65,7 @@ export type MobileWebShellSessionView = { /** Whether the document on screen pads for the system bars itself. Projected for the same * reason as `backClaimed`. */ readonly pageOwnsSafeArea: boolean + readonly pageReadsKeyboardInset: boolean } /** @@ -98,6 +99,9 @@ export function useMobileWebShellSession(args: { const [pageOwnsSafeArea, setPageOwnsSafeArea] = useState(() => shellPageOwnsSafeArea(sessionRef.current) ) + const [pageReadsKeyboardInset, setPageReadsKeyboardInset] = useState(() => + shellPageReadsKeyboardInset(sessionRef.current) + ) const hostKey = useMemo(() => deriveHostCacheKey(hostId), [hostId]) const startedAtRef = useRef(runtime.now()) // Bumped by anything that invalidates work in flight; every dispatch out of an effect checks it. @@ -122,6 +126,7 @@ export function useMobileWebShellSession(args: { setPageFrame(shellPageFrame(stepped.session)) setBackClaimed(shellPageBackClaimed(stepped.session)) setPageOwnsSafeArea(shellPageOwnsSafeArea(stepped.session)) + setPageReadsKeyboardInset(shellPageReadsKeyboardInset(stepped.session)) for (const effect of stepped.effects) { // Every effect of a step belongs to the flow that step produced, and its result carries that // number back, so a flow the session has since restarted reports into nothing. @@ -315,6 +320,7 @@ export function useMobileWebShellSession(args: { reportPagePainted, reportPageBackClaim, backClaimed, - pageOwnsSafeArea + pageOwnsSafeArea, + pageReadsKeyboardInset } } From b3b9f33e05067575f9b1226bb841adb43e1b19cc Mon Sep 17 00:00:00 2001 From: Jinwoo-H Date: Fri, 25 Sep 2026 22:54:15 -0400 Subject: [PATCH 06/22] feat(mobile): the page reads the keyboard the shell says covers it `keyboard-occlusion.web.ts` answers from the shell's published `keyboardInset` inside the shell (the entry publishes the bridge client as the source) and from `visualViewport` outside it; `visible` is `height > 0`. Inside the shell the WebView's IME insets are zeroed, so the visual viewport never moves and the shell is the only thing that knows the height. With a real height on the page the session's native keyboard logic runs unchanged: the lift, the refit deferral, the dock and the dismiss key. `useShortenedWindow` is deleted, since the window no longer shortens. `useKeyboardAvoidingPadding` is deleted too. Its one caller, the note composer, sits in a bottom drawer that already lifts by the same seam, so on the page it moved the composer twice; natively it was 0. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb --- .../components/MobileDiffReviewDrawers.tsx | 10 +- ...d-bottom-drawer-page-keyboard.web.test.tsx | 36 ++++- .../src/components/mounted-bottom-drawer.tsx | 3 +- .../keyboard-geometry-owner-census.test.ts | 4 +- .../src/platform/keyboard-occlusion.test.tsx | 20 --- mobile/src/platform/keyboard-occlusion.ts | 14 -- .../platform/keyboard-occlusion.web.test.tsx | 153 ++++++++++-------- mobile/src/platform/keyboard-occlusion.web.ts | 98 +++++------ mobile/web-entry/index.tsx | 7 + 9 files changed, 171 insertions(+), 174 deletions(-) diff --git a/mobile/src/components/MobileDiffReviewDrawers.tsx b/mobile/src/components/MobileDiffReviewDrawers.tsx index 9f979761fe87..1ff763fc9b82 100644 --- a/mobile/src/components/MobileDiffReviewDrawers.tsx +++ b/mobile/src/components/MobileDiffReviewDrawers.tsx @@ -2,7 +2,6 @@ import { useMemo } from 'react' import { KeyboardAvoidingView, Platform, Pressable, Text, TextInput, View } from 'react-native' import { Check, Copy, FileText, Plus, Send, Trash2, X } from 'lucide-react-native' import type { DiffComment } from '../../../src/shared/diff-comment-types' -import { useKeyboardAvoidingPadding } from '../platform/keyboard-occlusion' import { colors } from '../theme/mobile-theme' import type { ActionSheetAction } from './ActionSheetModal' import { ActionSheetModal } from './ActionSheetModal' @@ -163,16 +162,9 @@ function sendSheetMessage( function NoteComposerDrawer({ controller }: Props) { const composer = controller.composer - // Zero on a phone, where `KeyboardAvoidingView` above already moved this; the page's own - // keyboard measurement where it cannot, because that view is driven by events RN Web never - // sends. Padding rather than a second avoiding view: the drawer owns the position. - const keyboardPadding = useKeyboardAvoidingPadding() return ( - 0 ? { paddingBottom: keyboardPadding } : undefined} - > + diff --git a/mobile/src/components/mounted-bottom-drawer-page-keyboard.web.test.tsx b/mobile/src/components/mounted-bottom-drawer-page-keyboard.web.test.tsx index a741f5c864da..8cb7734ed5aa 100644 --- a/mobile/src/components/mounted-bottom-drawer-page-keyboard.web.test.tsx +++ b/mobile/src/components/mounted-bottom-drawer-page-keyboard.web.test.tsx @@ -69,6 +69,7 @@ vi.mock('react-native-reanimated', () => ({ })) import { MountedBottomDrawer } from './mounted-bottom-drawer' +import { publishShellKeyboardSource } from '../platform/keyboard-occlusion.web' const RESTING_HEIGHT = 900 const IME_HEIGHT = 300 @@ -106,7 +107,40 @@ describe('a fill-mode sheet on the page', () => { act(() => renderer.unmount()) }) - it('does not lift over a keyboard the shell already shortened the WebView for', () => { + it('sits on the keyboard the shell says covers the page, as it does natively', () => { + let height = 0 + const listeners = new Set<(next: number) => void>() + publishShellKeyboardSource({ + read: () => height, + subscribe: (listener) => { + listeners.add(listener) + return () => listeners.delete(listener) + } + }) + try { + setWindowHeight(RESTING_HEIGHT) + const renderer = renderFillSheet() + act(() => { + height = IME_HEIGHT + listeners.forEach((listener) => listener(IME_HEIGHT)) + }) + expect(sheetStyle(renderer)).toMatchObject({ + marginBottom: IME_HEIGHT, + height: RESTING_HEIGHT - IME_HEIGHT - 24 - 16 + }) + act(() => { + height = 0 + listeners.forEach((listener) => listener(0)) + }) + expect(sheetStyle(renderer).marginBottom).toBe(0) + act(() => renderer.unmount()) + expect(listeners.size).toBe(0) + } finally { + publishShellKeyboardSource(null) + } + }) + + it('does not lift over a keyboard an older shell shortened the WebView for', () => { setWindowHeight(RESTING_HEIGHT) const renderer = renderFillSheet() act(() => setWindowHeight(RESTING_HEIGHT - IME_HEIGHT)) diff --git a/mobile/src/components/mounted-bottom-drawer.tsx b/mobile/src/components/mounted-bottom-drawer.tsx index ea85c3208610..40f737fc45d6 100644 --- a/mobile/src/components/mounted-bottom-drawer.tsx +++ b/mobile/src/components/mounted-bottom-drawer.tsx @@ -131,8 +131,7 @@ export function MountedBottomDrawer({ // Why: KeyboardAvoidingView and useAnimatedKeyboard are both unreliable // inside Modal (iOS ignores KAV; Android needs adjustNothing for // useAnimatedKeyboard). The keyboard seam's events work on both platforms - // and give the exact height; inside the shell's page none fire, because - // the shell shortens the WebView above the IME. + // and give the exact height; inside the shell's page they are the shell's. useEffect(() => { // Pinned-under sheets stay visible for size but must not ride the keyboard — // only the top interactive sheet owns inset/lift. diff --git a/mobile/src/platform/keyboard-geometry-owner-census.test.ts b/mobile/src/platform/keyboard-geometry-owner-census.test.ts index 25c90d0d1eeb..b3bee07b5f49 100644 --- a/mobile/src/platform/keyboard-geometry-owner-census.test.ts +++ b/mobile/src/platform/keyboard-geometry-owner-census.test.ts @@ -15,8 +15,8 @@ const MOBILE_DIR = fileURLToPath(new URL('../../', import.meta.url)) const SRC_DIR = fileURLToPath(new URL('../', import.meta.url)) const SEAM = 'src/platform/keyboard-occlusion.ts' -/** A one-shot "open after the keyboard hides" with a timer fallback; it subscribes only while the - * seam reports a keyboard, which on the page is never, so there it cannot wait forever. */ +/** A one-shot "open after the keyboard hides" with a timer fallback; on the page, where the event + * never fires, the timer is what opens the sheet, so it cannot wait forever. */ const TAB_SHEET_AFTER_HIDE = 'src/session/use-mobile-session-terminal-send-actions.ts' const asksKeyboard = (line: string): boolean => diff --git a/mobile/src/platform/keyboard-occlusion.test.tsx b/mobile/src/platform/keyboard-occlusion.test.tsx index 526da87f12dd..c388c775de2d 100644 --- a/mobile/src/platform/keyboard-occlusion.test.tsx +++ b/mobile/src/platform/keyboard-occlusion.test.tsx @@ -47,14 +47,12 @@ vi.mock('react-native', () => ({ import { currentSoftKeyboardHeight, subscribeSoftKeyboard, - useKeyboardAvoidingPadding, useKeyboardOcclusion, useSoftKeyboard, type SoftKeyboardState } from './keyboard-occlusion' let lift = 0 -let padding = 0 let keyboardState: SoftKeyboardState = { height: 0, visible: false } function Harness(): null { @@ -62,12 +60,6 @@ function Harness(): null { return null } -/** Separate, so the padding case measures the padding hook's own subscriptions and nothing else. */ -function PaddingHarness(): null { - padding = useKeyboardAvoidingPadding() - return null -} - function StateHarness(): null { keyboardState = useSoftKeyboard() return null @@ -94,7 +86,6 @@ describe('the keyboard the phone reports', () => { keyboard.addListenerCalls = 0 keyboard.metrics = undefined lift = 0 - padding = 0 keyboardState = { height: 0, visible: false } }) @@ -137,17 +128,6 @@ describe('the keyboard the phone reports', () => { expect(keyboard.removed.sort()).toEqual(['keyboardWillHide', 'keyboardWillShow']) }) - it('asks a phone for no composer padding, because KeyboardAvoidingView already moved it', async () => { - // Rendered, not called: a hook read outside a component measures whatever the module does at - // the top of its body and nothing its effects do, which is where a subscription would live. - // And it subscribes to nothing doing it, so a composer that calls this renders as often as it - // does today — which is what makes adding the call to a shared component safe. - await mountComponent(PaddingHarness) - expect(padding).toBe(0) - expect(keyboard.addListenerCalls).toBe(0) - expect(keyboard.listeners.size).toBe(0) - }) - it('answers both facts from one subscription, so a screen wanting each pays for one', async () => { // The session screen reads the height to lift its dock and the flag to hold off the terminal // refit. Two hooks would mean two listener pairs and two renders per keyboard event. diff --git a/mobile/src/platform/keyboard-occlusion.ts b/mobile/src/platform/keyboard-occlusion.ts index 6b0fc0deb2b5..60ec14f015af 100644 --- a/mobile/src/platform/keyboard-occlusion.ts +++ b/mobile/src/platform/keyboard-occlusion.ts @@ -68,17 +68,3 @@ export function currentSoftKeyboardHeight(): number { export function useKeyboardOcclusion(): number { return useSoftKeyboard().height } - -/** - * The bottom padding a composer needs to clear the keyboard, which natively is none. - * - * `KeyboardAvoidingView` already moves the composer on a phone, so adding padding there would move - * it twice. It is inert on the web for the same reason the `Keyboard` stub is — it is driven by - * those events — so there the padding is the whole of the avoidance. - * - * A second name rather than a `Platform.OS` branch at the call site: this one subscribes to nothing - * on a phone, so a composer that asks for it renders exactly as many times as it does today. - */ -export function useKeyboardAvoidingPadding(): number { - return 0 -} diff --git a/mobile/src/platform/keyboard-occlusion.web.test.tsx b/mobile/src/platform/keyboard-occlusion.web.test.tsx index 11e96afff8fa..fdba98e028fe 100644 --- a/mobile/src/platform/keyboard-occlusion.web.test.tsx +++ b/mobile/src/platform/keyboard-occlusion.web.test.tsx @@ -5,9 +5,9 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest' import { currentSoftKeyboardHeight, subscribeSoftKeyboard, - useKeyboardAvoidingPadding, useKeyboardOcclusion, useSoftKeyboard, + publishShellKeyboardSource, type SoftKeyboardState } from './keyboard-occlusion.web' @@ -62,11 +62,9 @@ class FakeVisualViewport extends EventTarget { const LAYOUT_HEIGHT = 800 let viewport: FakeVisualViewport | null = null let lift = 0 -let padding = 0 function Harness(): null { lift = useKeyboardOcclusion() - padding = useKeyboardAvoidingPadding() return null } @@ -83,7 +81,6 @@ async function mount(): Promise> { beforeEach(() => { lift = 0 - padding = 0 viewport = new FakeVisualViewport(LAYOUT_HEIGHT) Object.defineProperty(window, 'innerHeight', { value: LAYOUT_HEIGHT, configurable: true }) Object.defineProperty(window, 'visualViewport', { value: viewport, configurable: true }) @@ -189,15 +186,9 @@ describe('the keyboard the browser reports', () => { expect(lift).toBe(0) }) - it('is the whole of the avoidance here, where KeyboardAvoidingView is inert', async () => { - await mount() - await act(async () => viewport?.resizeTo(464)) - expect(padding).toBe(336) - }) - it('removes both listeners on unmount', async () => { const tree = await mount() - expect(viewport?.counts).toEqual({ resize: 2, scroll: 2 }) + expect(viewport?.counts).toEqual({ resize: 1, scroll: 1 }) await act(async () => tree.unmount()) expect(viewport?.counts).toEqual({ resize: 0, scroll: 0 }) }) @@ -262,7 +253,6 @@ describe('the keyboard as events, for a sheet', () => { }) }) -const LAYOUT_WIDTH = 400 let keyboardState: SoftKeyboardState = { height: 0, visible: false } function StateHarness(): null { @@ -270,16 +260,6 @@ function StateHarness(): null { return null } -function resizeWindow(width: number, height: number): void { - Object.defineProperty(window, 'innerWidth', { value: width, configurable: true }) - Object.defineProperty(window, 'innerHeight', { value: height, configurable: true }) - window.dispatchEvent(new Event('resize')) -} - -/** Tracked so a case that resizes the window is not also re-rendering an earlier case's harness, - * which shares this file's one `keyboardState`. */ -const mountedStateHarnesses: ReturnType[] = [] - async function mountState(): Promise> { let tree: ReturnType | null = null await act(async () => { @@ -288,65 +268,102 @@ async function mountState(): Promise> { if (tree === null) { throw new Error('the harness did not mount') } - mountedStateHarnesses.push(tree) return tree } -/** - * The shell shortens the WebView to sit above the IME, so by the time the page measures itself - * nothing is covered and `visualViewport` reads full height. The resize is what is left. - */ -describe('the keyboard the page cannot see, because the shell already moved it', () => { - beforeEach(() => { - act(() => { - for (const tree of mountedStateHarnesses.splice(0)) { - tree.unmount() +/** The shell's side of the bridge, as the entry publishes it: the height `init` last carried. */ +function createShellKeyboard(initial = 0) { + let height = initial + const listeners = new Set<(height: number) => void>() + return { + source: { + read: () => height, + subscribe: (listener: (height: number) => void) => { + listeners.add(listener) + return () => { + listeners.delete(listener) + } } - }) - keyboardState = { height: 0, visible: false } - Object.defineProperty(window, 'innerWidth', { value: LAYOUT_WIDTH, configurable: true }) - Object.defineProperty(window, 'innerHeight', { value: LAYOUT_HEIGHT, configurable: true }) - }) + }, + move: (next: number) => { + height = next + for (const listener of listeners) { + listener(next) + } + }, + listenerCount: () => listeners.size + } +} - it('reads no keyboard while the window keeps the height it mounted at', async () => { - await mountState() +describe('the state a native screen reads, from the browser outside the shell', () => { + it('is open exactly while something is covered', async () => { + const tree = await mountState() expect(keyboardState).toEqual({ height: 0, visible: false }) + await act(async () => viewport?.resizeTo(464)) + expect(keyboardState).toEqual({ height: 336, visible: true }) + await act(async () => viewport?.resizeTo(LAYOUT_HEIGHT)) + expect(keyboardState).toEqual({ height: 0, visible: false }) + await act(async () => tree.unmount()) }) +}) - it('calls the window shortened at an unchanged width the keyboard, and covers nothing by it', async () => { - await mountState() - await act(async () => resizeWindow(LAYOUT_WIDTH, LAYOUT_HEIGHT - 336)) - expect(keyboardState).toEqual({ height: 0, visible: true }) - }) - - it('drops the flag when the window gets its height back', async () => { - await mountState() - await act(async () => resizeWindow(LAYOUT_WIDTH, LAYOUT_HEIGHT - 336)) - await act(async () => resizeWindow(LAYOUT_WIDTH, LAYOUT_HEIGHT)) - expect(keyboardState.visible).toBe(false) - }) - - it('reads a rotation as a new window rather than a keyboard, because the width moved too', async () => { - await mountState() - await act(async () => resizeWindow(LAYOUT_HEIGHT, LAYOUT_WIDTH)) - expect(keyboardState.visible).toBe(false) - // And the shorter window is now the one the next keyboard is measured against. - await act(async () => resizeWindow(LAYOUT_HEIGHT, LAYOUT_WIDTH - 200)) - expect(keyboardState.visible).toBe(true) +/** + * Inside the shell the keyboard covers the page as it covers a native screen, but the page cannot + * measure it: the WebView's IME insets are zeroed, so `visualViewport` never moves. The shell says + * the height over the bridge, and every reader here answers from that. + */ +describe('the keyboard the shell says covers the page', () => { + afterEach(() => { + publishShellKeyboardSource(null) }) - it('takes a window that grew as the new resting height, not as a keyboard closing twice', async () => { - await mountState() - await act(async () => resizeWindow(LAYOUT_WIDTH, LAYOUT_HEIGHT + 60)) - expect(keyboardState.visible).toBe(false) - await act(async () => resizeWindow(LAYOUT_WIDTH, LAYOUT_HEIGHT)) - expect(keyboardState.visible).toBe(true) + it('answers the height the shell sent, and ignores the visual viewport', async () => { + const shell = createShellKeyboard() + publishShellKeyboardSource(shell.source) + const tree = await mountState() + const lifted = await mount() + // Pixel_API_37: the IME opens at 312 and the suggestion strip grows it to 346. + for (const height of [312, 346]) { + await act(async () => shell.move(height)) + expect(keyboardState).toEqual({ height, visible: true }) + expect(lift).toBe(height) + } + await act(async () => viewport?.resizeTo(464)) + expect(keyboardState.height).toBe(346) + await act(async () => shell.move(0)) + expect(keyboardState).toEqual({ height: 0, visible: false }) + expect(lift).toBe(0) + await act(async () => { + tree.unmount() + lifted.unmount() + }) + expect(shell.listenerCount()).toBe(0) }) - it('stops listening on unmount', async () => { + it('reads a keyboard already up at mount, which the shell sent in the first init', async () => { + publishShellKeyboardSource(createShellKeyboard(312).source) + expect(currentSoftKeyboardHeight()).toBe(312) const tree = await mountState() + expect(keyboardState).toEqual({ height: 312, visible: true }) await act(async () => tree.unmount()) - await act(async () => resizeWindow(LAYOUT_WIDTH, LAYOUT_HEIGHT - 336)) - expect(keyboardState.visible).toBe(false) + }) + + it('hands a sheet each height as a show and the close as one hide', () => { + const shell = createShellKeyboard() + publishShellKeyboardSource(shell.source) + const calls: string[] = [] + const unsubscribe = subscribeSoftKeyboard( + (height, duration) => calls.push(`show ${height} ${duration}`), + (duration) => calls.push(`hide ${duration}`) + ) + viewport?.resizeTo(464) + shell.move(312) + shell.move(346) + shell.move(0) + shell.move(0) + expect(calls).toEqual(['show 312 0', 'show 346 0', 'hide 0']) + unsubscribe() + expect(shell.listenerCount()).toBe(0) + expect(viewport?.counts).toEqual({ resize: 0, scroll: 0 }) }) }) diff --git a/mobile/src/platform/keyboard-occlusion.web.ts b/mobile/src/platform/keyboard-occlusion.web.ts index 05500f369ee0..c157f24cb4cd 100644 --- a/mobile/src/platform/keyboard-occlusion.web.ts +++ b/mobile/src/platform/keyboard-occlusion.web.ts @@ -1,7 +1,24 @@ import { useEffect, useState } from 'react' +/** The height the shell last said over the bridge, and a way to hear it move. */ +export type ShellKeyboardSource = { + read: () => number + subscribe: (listener: (height: number) => void) => () => void +} + +let shellKeyboard: ShellKeyboardSource | null = null + +/** + * Called once by the page entry. Inside the shell the keyboard covers the page as it covers a + * native screen, but the WebView's IME insets are zeroed, so `visualViewport` never moves: the + * shell is the only thing that knows the height, and every reader below answers from it. + */ +export function publishShellKeyboardSource(source: ShellKeyboardSource | null): void { + shellKeyboard = source +} + /** - * Web sibling: the keyboard's height as the browser reports it, which is not as an event. + * Outside the shell: the keyboard's height as the browser reports it, which is not as an event. * * react-native-web's `Keyboard` is a stub whose `addListener` returns a subscription that never * fires, so every screen waiting for `keyboardDidShow` inside the shell's page waits forever and @@ -48,21 +65,15 @@ function visualViewport(): VisualViewport | undefined { } /** - * The strip as events, with duration 0: the browser has already moved the viewport by the time it - * says so. Inside the shell nothing fires, because the shell shortens the WebView above the IME and - * the strip stays 0; in a plain mobile browser the keyboard overlays the page and this is the lift. + * The strip as events, with duration 0: the shell and the browser have both moved the keyboard by + * the time they say so. */ export function subscribeSoftKeyboard( onShow: (height: number, duration: number) => void, onHide: (duration: number) => void ): () => void { - const viewport = visualViewport() - if (viewport === undefined) { - return () => {} - } - let open = occlusion(viewport) > 0 - const read = (): void => { - const height = occlusion(viewport) + let open = currentSoftKeyboardHeight() > 0 + const read = (height: number): void => { if (height > 0) { open = true onShow(height, 0) @@ -71,17 +82,28 @@ export function subscribeSoftKeyboard( onHide(0) } } - viewport.addEventListener('resize', read) - viewport.addEventListener('scroll', read) + if (shellKeyboard !== null) { + return shellKeyboard.subscribe(read) + } + const viewport = visualViewport() + if (viewport === undefined) { + return () => {} + } + const measure = (): void => read(occlusion(viewport)) + viewport.addEventListener('resize', measure) + viewport.addEventListener('scroll', measure) return () => { - viewport.removeEventListener('resize', read) - viewport.removeEventListener('scroll', read) + viewport.removeEventListener('resize', measure) + viewport.removeEventListener('scroll', measure) } } /** A keyboard already up when a composer opens gets no event at all. */ export function currentSoftKeyboardHeight(): number { + if (shellKeyboard !== null) { + return shellKeyboard.read() + } const viewport = visualViewport() return viewport === undefined ? 0 : occlusion(viewport) } @@ -100,50 +122,10 @@ export function useKeyboardOcclusion(): number { return keyboardLift } -/** - * On the web the padding is the whole of the avoidance: `KeyboardAvoidingView` is driven by the - * `Keyboard` events this file exists because the page never receives. - */ -export function useKeyboardAvoidingPadding(): number { - return useKeyboardOcclusion() -} - -/** The sibling's shape; the two facts it answers together are measured separately here. */ +/** The sibling's shape. Open is a covered strip here: neither source reports a keyboard of 0. */ export type SoftKeyboardState = { readonly height: number; readonly visible: boolean } -/** - * Whether a keyboard is open, which here is not what it covers: the shell shortens the WebView to - * sit above the IME, so nothing covers the page and the occlusion above reads 0, correctly. The - * resize is what is left of the keyboard — inside the shell's WebView the shell's own bottom - * padding is the one thing that changes this window's height without changing its width too. - */ -function useShortenedWindow(): boolean { - const [shortened, setShortened] = useState(false) - - useEffect(() => { - // The tallest height seen at this width is the resting one; a width change is a rotation or a - // fold, which starts the comparison again. A page that mounts with the keyboard already up - // reads false until it closes once, which costs one terminal refit and no correctness. - let width = window.innerWidth - let tallest = window.innerHeight - const read = (): void => { - if (window.innerWidth !== width) { - width = window.innerWidth - tallest = window.innerHeight - } else if (window.innerHeight > tallest) { - tallest = window.innerHeight - } - setShortened(window.innerHeight < tallest) - } - read() - window.addEventListener('resize', read) - - return () => window.removeEventListener('resize', read) - }, []) - - return shortened -} - export function useSoftKeyboard(): SoftKeyboardState { - return { height: useKeyboardOcclusion(), visible: useShortenedWindow() } + const height = useKeyboardOcclusion() + return { height, visible: height > 0 } } diff --git a/mobile/web-entry/index.tsx b/mobile/web-entry/index.tsx index 2c346e0dbf2c..4690bb48abf6 100644 --- a/mobile/web-entry/index.tsx +++ b/mobile/web-entry/index.tsx @@ -20,6 +20,7 @@ import { PageFaultBoundary } from '../src/mobile-web-shell/bridge/page-fault-bou import { publishPageHostProfile } from '../src/mobile-web-shell/bridge/page-host-profile' import { publishExternalLinkOpener } from '../src/platform/external-link.web' import { publishHapticsNotifier } from '../src/platform/haptics.web' +import { publishShellKeyboardSource } from '../src/platform/keyboard-occlusion.web' // Named with its extension: this entry is the web build's and the provider it needs is the web // sibling's, which takes the page's client. The screens below still import `./client-context` // and reach the same module, because the builder resolves both specifiers to the same file. @@ -111,6 +112,12 @@ bootstrapShellPage({ // The same shape again, and for the same reason: every haptic on this page is played from a // plain function inside a row's press handler, which no provider wraps. publishHapticsNotifier((kind) => client.notifyHaptics(kind)) + // The shell's keyboard height, read by plain functions as well as hooks; 0 from a shell too old + // to send one, which shortens the view instead. + publishShellKeyboardSource({ + read: () => client.getShellSession()?.keyboardInset ?? 0, + subscribe: client.onKeyboardInsetUpdate + }) // Scoped to the host `init` named: with none, no key is writable, which is the right answer // for a shell too old to say whose list this is. publishPageStorage( From 007accc6a84e6a021335dee0e7f81221bb63e1be Mon Sep 17 00:00:00 2001 From: Jinwoo-H Date: Fri, 25 Sep 2026 23:23:53 -0400 Subject: [PATCH 07/22] fix(mobile): an older page is never handed the keyboard height The host held the height for every page and put it in any `init` it re-sent, so an older page that re-asked `ready` with the keyboard up was handed a field it never declared. The held value now reaches `init` only for a page whose `ready.accepts` names `keyboard-inset`. The legacy resize branch names the condition for deleting it. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb --- .../mobile-web-shell/MobileWebShellScreen.tsx | 2 ++ .../src/mobile-web-shell/bridge-host-route.ts | 4 +-- ...web-shell-keyboard-overlay-screen.test.tsx | 32 +++++++++++-------- 3 files changed, 23 insertions(+), 15 deletions(-) diff --git a/mobile/src/mobile-web-shell/MobileWebShellScreen.tsx b/mobile/src/mobile-web-shell/MobileWebShellScreen.tsx index 331512863e9f..080008a3a860 100644 --- a/mobile/src/mobile-web-shell/MobileWebShellScreen.tsx +++ b/mobile/src/mobile-web-shell/MobileWebShellScreen.tsx @@ -210,6 +210,8 @@ export function MobileWebShellScreen({ // IME insets are zeroed, so `visualViewport` never shrinks. A page that reads the height from // `init` is covered by the keyboard like a native screen; an older one gets a view ended above it. const keyboardHeight = useKeyboardOcclusion() + // Legacy: only a page without the `keyboard-inset` accept is shortened; delete this branch (and + // `softwareKeyboardWindowInset`) once every served page declares it. const viewShortenedBy = pageReadsKeyboardInset ? 0 : softwareKeyboardWindowInset({ diff --git a/mobile/src/mobile-web-shell/bridge-host-route.ts b/mobile/src/mobile-web-shell/bridge-host-route.ts index 1b6144d88d73..4467681aff91 100644 --- a/mobile/src/mobile-web-shell/bridge-host-route.ts +++ b/mobile/src/mobile-web-shell/bridge-host-route.ts @@ -41,7 +41,7 @@ export type BridgeHostRoute = { * lane as a pane update: held either way, so the next `ready` carries them. */ readonly publishSafeAreaInsets: (next: BridgeSafeAreaInsets, deliverable: boolean) => void - /** The keyboard height the next `init` carries. */ + /** The keyboard height the next `init` carries; 0 to a page that did not declare it reads one. */ readonly keyboardInset: () => number /** Moves the held keyboard height on the same lane as the insets, to a page that reads it. */ readonly publishKeyboardInset: (next: number, deliverable: boolean) => void @@ -105,7 +105,7 @@ export function createBridgeHostRoute(args: { args.sendInit() } }, - keyboardInset: () => keyboard, + keyboardInset: () => (accepts.includes(BRIDGE_KEYBOARD_INSET_ACCEPT) ? keyboard : 0), publishKeyboardInset: (next, deliverable) => { if (keyboard === next) { return diff --git a/mobile/src/mobile-web-shell/mobile-web-shell-keyboard-overlay-screen.test.tsx b/mobile/src/mobile-web-shell/mobile-web-shell-keyboard-overlay-screen.test.tsx index 68ae95d5e95e..c71e4e5db332 100644 --- a/mobile/src/mobile-web-shell/mobile-web-shell-keyboard-overlay-screen.test.tsx +++ b/mobile/src/mobile-web-shell/mobile-web-shell-keyboard-overlay-screen.test.tsx @@ -123,26 +123,32 @@ describe('a page the keyboard covers', () => { dependencies.client = createFakeRpcClient() dependencies.pageOwnsSafeArea = true const tree = await renderScreen(readyState('session-older-keyboard')) - await act(async () => { - byName(tree, 'ShellViewProbe')[0]?.props.onBridgeMessage({ - nativeEvent: { - json: clientFrame({ - type: 'ready', - accepts: [BRIDGE_ROUTE_UPDATE_ACCEPT, BRIDGE_SAFE_AREA_ACCEPT] - }) - } + const ready = async () => { + await act(async () => { + byName(tree, 'ShellViewProbe')[0]?.props.onBridgeMessage({ + nativeEvent: { + json: clientFrame({ + type: 'ready', + accepts: [BRIDGE_ROUTE_UPDATE_ACCEPT, BRIDGE_SAFE_AREA_ACCEPT] + }) + } + }) }) - }) + } + await ready() await act(async () => { dependencies.keyboardListeners.get('keyboardDidShow')?.({ endCoordinates: { height: 336 } }) }) const root = tree.root.find((node) => node.props.testID === 'mobile-web-shell-ready') expect(root.props.style[1]).toEqual({ paddingTop: 0, paddingBottom: 344 }) - // The first `init` and the insets move; the keyboard itself sends nothing to this page. - const inits = dependencies.posted.filter((json) => { + // The page re-asks, as one does after a refused frame: the answer still carries no keyboard. + await ready() + const inits = dependencies.posted.flatMap((json) => { const read = readBridgeHostMessage(json) - return read.ok && read.message.type === 'init' + return read.ok && read.message.type === 'init' ? [read.message] : [] }) - expect(inits).toHaveLength(2) + // The first `init`, the insets move and the re-ask; the keyboard itself sends nothing here. + expect(inits).toHaveLength(3) + expect(inits.filter((init) => 'keyboardInset' in init)).toEqual([]) }) }) From 0a09a7b9af6a5fffb4648e65b982e124fd975558 Mon Sep 17 00:00:00 2001 From: Jinwoo-H Date: Fri, 25 Sep 2026 23:23:53 -0400 Subject: [PATCH 08/22] Revert "fix(mobile): native desktop display mode lifts only what the keyboard hides of the grid" This reverts commit c7b9e9e485d45cfb1319df8a795974548af10335. --- .../terminal-keyboard-avoidance-lift.test.ts | 90 ------------------- .../terminal-keyboard-avoidance-lift.ts | 32 +------ 2 files changed, 4 insertions(+), 118 deletions(-) diff --git a/mobile/src/terminal/terminal-keyboard-avoidance-lift.test.ts b/mobile/src/terminal/terminal-keyboard-avoidance-lift.test.ts index 5dcd32f9e1e3..4c11320db2e3 100644 --- a/mobile/src/terminal/terminal-keyboard-avoidance-lift.test.ts +++ b/mobile/src/terminal/terminal-keyboard-avoidance-lift.test.ts @@ -103,13 +103,6 @@ describe('computeActiveTerminalKeyboardLift', () => { terminalFrameHeight: FRAME_HEIGHT }) expect(lift).toBeLessThanOrEqual(KEYBOARD_LIFT) - // With the drawn row pitch too, and a grid drawn taller than the frame it is lifted in. - const taller = computeActiveTerminalKeyboardLift({ - keyboardLift: KEYBOARD_LIFT, - metrics: metrics({ rows: 60, rowPitch: 18, cursorY: 59, contentBottomRow: 59 }), - terminalFrameHeight: FRAME_HEIGHT - }) - expect(taller).toBe(KEYBOARD_LIFT) }) it('uses the platform-adjusted lift proportionally on iOS and Android', () => { @@ -126,87 +119,4 @@ describe('computeActiveTerminalKeyboardLift', () => { }) expect({ android, ios }).toEqual({ android: 220, ios: 186 }) }) - - /** Base's arithmetic, kept here as the oracle a covered frame must match to the pixel. */ - function baseLift(keyboardLift: number, m: TerminalKeyboardAvoidanceMetrics, frame: number) { - if (keyboardLift <= 0) { - return 0 - } - if (m.rows <= 0 || frame <= 0 || m.altScreen) { - return keyboardLift - } - const rowHeight = frame / m.rows - const anchorBottom = (Math.max(m.cursorY, m.contentBottomRow) + 1) * rowHeight - return Math.min(keyboardLift, Math.max(0, anchorBottom + rowHeight - (frame - keyboardLift))) - } - - describe('a keyboard that covers the frame', () => { - const lift = (keyboardLift: number, m: TerminalKeyboardAvoidanceMetrics, frame = 713.7) => - computeActiveTerminalKeyboardLift({ - keyboardLift, - metrics: m, - terminalFrameHeight: frame - }) - - it('keeps base in phone mode, where the fit fills the frame to within a row', () => { - // Pixel_API_37: 47 rows of 15 px in a 713.7 px frame under a 312 px keyboard. - const phone = metrics({ rows: 47, rowPitch: 15, cursorY: 46, contentBottomRow: 46 }) - expect(lift(312, phone)).toBe(312) - expect(lift(312, phone)).toBe(baseLift(312, phone, 713.7)) - }) - - it('lifts a desktop-mode grid only by what the keyboard hides of it', () => { - // Pixel_API_37, measured blank: 40 desktop rows drawn 270 px tall, lifted 312 under the header. - const drawn270 = metrics({ rows: 40, rowPitch: 6.75, cursorY: 39, contentBottomRow: 39 }) - expect(lift(312, drawn270)).toBe(0) - expect(lift(312, { ...drawn270, altScreen: true })).toBe(0) - // 425 px drawn, the dock at 401.7: the caret row's bottom lands on the dock. - const drawn425 = metrics({ rows: 50, rowPitch: 8.5, cursorY: 49, contentBottomRow: 49 }) - expect(lift(312, drawn425)).toBeCloseTo(23.3, 5) - expect(lift(312, { ...drawn425, altScreen: true })).toBeCloseTo(23.3, 5) - }) - - it('lifts nothing for a keyboard that is open and covers nothing', () => { - expect(lift(0, metrics({ rows: 50, rowPitch: 17, cursorY: 49, contentBottomRow: 49 }))).toBe( - 0 - ) - }) - - it('stays under the strip while stale rows outlast a rotation or a text-size change', () => { - const rotated = metrics({ rows: 47, rowPitch: 15, cursorY: 46, contentBottomRow: 46 }) - expect(lift(150, rotated, 300)).toBe(150) - const resized = metrics({ rows: 47, rowPitch: 18, cursorY: 46, contentBottomRow: 46 }) - expect(lift(312, resized)).toBe(312) - }) - - it('matches base wherever the drawn grid fills the frame, and never lifts past it elsewhere', () => { - let matched = 0 - let drawnShort = 0 - for (const rows of [8, 26, 47, 50, 80]) { - for (const rowPitch of [undefined, 5.1, 8.5, 15, 18, 25]) { - for (const frame of [300, 401.7, 710.33, 713.7]) { - for (const keyboard of [0.5, 150, 312, 336]) { - for (const anchor of [0, Math.floor(rows / 2), rows - 1]) { - const m = metrics({ rows, rowPitch, cursorY: anchor, contentBottomRow: anchor }) - const got = lift(keyboard, m, frame) - const drawn = rowPitch === undefined ? frame : rows * rowPitch - // The fit floors rows, so a grid that fills the frame leaves less than a row. - if (drawn >= frame - (rowPitch ?? 0)) { - expect(got).toBe(baseLift(keyboard, m, frame)) - matched++ - continue - } - expect(got).toBeLessThanOrEqual(keyboard) - expect(got).toBeLessThanOrEqual(Math.max(0, drawn - (frame - keyboard)) + 1e-9) - drawnShort++ - } - } - } - } - } - // Presence: both halves of the sweep ran. - expect(matched).toBeGreaterThan(500) - expect(drawnShort).toBeGreaterThan(500) - }) - }) }) diff --git a/mobile/src/terminal/terminal-keyboard-avoidance-lift.ts b/mobile/src/terminal/terminal-keyboard-avoidance-lift.ts index 003b42b50c40..6ada640430d9 100644 --- a/mobile/src/terminal/terminal-keyboard-avoidance-lift.ts +++ b/mobile/src/terminal/terminal-keyboard-avoidance-lift.ts @@ -1,16 +1,11 @@ import type { TerminalKeyboardAvoidanceMetrics } from './terminal-webview-contract' type ActiveTerminalKeyboardLiftParams = { - // What the keyboard covers of the frame. keyboardLift: number metrics: TerminalKeyboardAvoidanceMetrics | undefined terminalFrameHeight: number } -/** - * How far to lift the active pane so its anchor row clears the keyboard. Never more than the strip - * the keyboard covers, nor more than it hides of the grid as drawn. - */ export function computeActiveTerminalKeyboardLift( params: ActiveTerminalKeyboardLiftParams ): number { @@ -21,33 +16,14 @@ export function computeActiveTerminalKeyboardLift( if (!metrics || metrics.rows <= 0 || terminalFrameHeight <= 0) { return keyboardLift } - const dockTop = terminalFrameHeight - keyboardLift - const pitch = metrics.rowPitch - // Desktop display mode draws the desktop's rows scaled down, well short of the frame; lifting - // by the strip there moved the whole grid under the header. The fit floors rows, so a gap under - // one row is a grid that fills the frame, and keeps the arithmetic below. - if (pitch && metrics.rows * pitch < terminalFrameHeight - pitch) { - const drawnHidden = metrics.rows * pitch - dockTop - if (drawnHidden <= 0) { - return 0 - } - const hidden = Math.min(keyboardLift, drawnHidden) - return metrics.altScreen ? hidden : Math.min(hidden, anchorOverflow(metrics, pitch, dockTop)) - } if (metrics.altScreen) { return keyboardLift } const rowHeight = terminalFrameHeight / metrics.rows - return Math.min(keyboardLift, anchorOverflow(metrics, rowHeight, dockTop)) -} - -/** How far the anchor row, plus one row of margin, reaches below `visibleBottom`. */ -function anchorOverflow( - metrics: TerminalKeyboardAvoidanceMetrics, - rowHeight: number, - visibleBottom: number -): number { // Main-buffer TUI footer rows can sit below the caret. const anchorRow = Math.max(metrics.cursorY, metrics.contentBottomRow) - return Math.max(0, (anchorRow + 1) * rowHeight + rowHeight - visibleBottom) + const anchorBottom = (anchorRow + 1) * rowHeight + const dockTop = terminalFrameHeight - keyboardLift + const margin = rowHeight + return Math.min(keyboardLift, Math.max(0, anchorBottom + margin - dockTop)) } From 85e65ca915db78df77612cbbb6c3486a76f945ae Mon Sep 17 00:00:00 2001 From: Jinwoo-H Date: Fri, 25 Sep 2026 23:23:53 -0400 Subject: [PATCH 09/22] Revert "fix(mobile): the session hears a row-pitch change in the keyboard metrics" This reverts commit 5e561e61bf2a32f2dc757b5d44d1de27792cc194. --- .../mobile-session-route-parity.test.ts | 3 +- .../use-mobile-session-accessory-selection.ts | 15 ++++-- mobile/src/terminal/document/fit-scale.ts | 13 ++++-- .../document/keyboard-avoidance-metrics.ts | 5 +- .../terminal/document/viewport-transform.ts | 9 ---- ...erminal-keyboard-avoidance-webview.test.ts | 32 +------------ .../terminal-webview-contract.test.ts | 46 +------------------ .../src/terminal/terminal-webview-contract.ts | 28 +++-------- 8 files changed, 28 insertions(+), 123 deletions(-) diff --git a/mobile/src/session/mobile-session-route-parity.test.ts b/mobile/src/session/mobile-session-route-parity.test.ts index 163189ece28e..d52f950d5ec3 100644 --- a/mobile/src/session/mobile-session-route-parity.test.ts +++ b/mobile/src/session/mobile-session-route-parity.test.ts @@ -115,8 +115,7 @@ const HEAD_CALLBACK_IDENTITY_SHA256 = // the other's body. The hook and string counts are C7.2's and stand. // Refreshed once more for the two dictation failure handlers, which now both call // `reportDictationFailure` instead of each choosing between the setup sheet and a toast. -// Moved when the metrics handler compared every field, the row pitch included. -const HEAD_CALLBACK_BODY_SHA256 = '65f5c1274967cecef39660430169dcfde81b362e8aa5878833b9f20bc8e43a6a' +const HEAD_CALLBACK_BODY_SHA256 = '2ccbfb5ee57e7dfeb07dafaee6fa592b95862b3bc898a5ac2995e7c69913bfc4' // Refreshed for the startup effect: both `worktree.activate` sends became `worktreeActivate`, and // the sleeping-agent check reads that operation's verdict instead of the reply envelope. Refreshed // again when the reporter took the reply and interpreted it itself, retiring the hand-built diff --git a/mobile/src/session/use-mobile-session-accessory-selection.ts b/mobile/src/session/use-mobile-session-accessory-selection.ts index a9795d82b1fc..7e3cfcfa76cd 100644 --- a/mobile/src/session/use-mobile-session-accessory-selection.ts +++ b/mobile/src/session/use-mobile-session-accessory-selection.ts @@ -8,10 +8,9 @@ import { triggerError, triggerEdgeBump } from '../platform/haptics' -import { - sameTerminalKeyboardAvoidanceMetrics, - type TerminalKeyboardAvoidanceMetrics, - type TerminalModes +import type { + TerminalKeyboardAvoidanceMetrics, + TerminalModes } from '../terminal/terminal-webview-contract' import type { createTerminalLiveAccessoryInput } from '../terminal/terminal-live-accessory-input' import { clearTerminalLiveInputFocusTimer } from '../terminal/terminal-live-input' @@ -166,7 +165,13 @@ export function useMobileSessionAccessorySelection(scope: MobileSessionTerminalI (handle: string, metrics: TerminalKeyboardAvoidanceMetrics) => { setTerminalKeyboardMetrics((prev) => { const current = prev.get(handle) - if (current && sameTerminalKeyboardAvoidanceMetrics(current, metrics)) { + if ( + current && + current.cursorY === metrics.cursorY && + current.contentBottomRow === metrics.contentBottomRow && + current.rows === metrics.rows && + current.altScreen === metrics.altScreen + ) { return prev } return new Map(prev).set(handle, metrics) diff --git a/mobile/src/terminal/document/fit-scale.ts b/mobile/src/terminal/document/fit-scale.ts index 77cbc1a64ec0..20aa1c1ee49e 100644 --- a/mobile/src/terminal/document/fit-scale.ts +++ b/mobile/src/terminal/document/fit-scale.ts @@ -3,19 +3,24 @@ import { computeFitScale, flog, getCellWidth, - getMeasuredCellHeight, getTotalScale, updateTransform } from './viewport-transform' import type { TerminalDocumentScope } from './document-scope' import { scheduleDocumentFrame } from './document-frame-registry' -import { emitKeyboardAvoidanceMetrics } from './keyboard-avoidance-metrics' /** The narrowest grid a fit or a text-scale change will fit to. */ export const MIN_FIT_COLS = 20 export function getCellHeight(scope: TerminalDocumentScope) { - return getMeasuredCellHeight(scope) || 15 + if (!scope.term || !scope.term._core) { + return 15 + } + const core = scope.term._core + if (core._renderService && core._renderService.dimensions) { + return core._renderService.dimensions.css.cell.height || 15 + } + return 15 } // Why: clamp pan so the terminal content always covers the viewport @@ -165,8 +170,6 @@ export function commitFitScale( }) } repositionOverlay(scope) - // The host's lift reads the drawn row pitch, which a new scale changes with no new output. - emitKeyboardAvoidanceMetrics(scope) } /** diff --git a/mobile/src/terminal/document/keyboard-avoidance-metrics.ts b/mobile/src/terminal/document/keyboard-avoidance-metrics.ts index a0f28d801c16..516dfdb1b2a6 100644 --- a/mobile/src/terminal/document/keyboard-avoidance-metrics.ts +++ b/mobile/src/terminal/document/keyboard-avoidance-metrics.ts @@ -1,4 +1,3 @@ -import { getMeasuredCellHeight, getTotalScale } from './viewport-transform' import { notify } from './host-notify' import type { TerminalDocumentCell, @@ -71,8 +70,6 @@ export function emitKeyboardAvoidanceMetrics(scope: TerminalDocumentScope) { cursorY: scope.term.buffer && scope.term.buffer.active ? scope.term.buffer.active.cursorY : 0, contentBottomRow: alt ? 0 : computeContentBottomRow(scope), rows: scope.term.rows || 0, - altScreen: alt, - // As drawn: desktop display mode scales the desktop's rows down to the phone's width. - rowPitch: getMeasuredCellHeight(scope) * getTotalScale(scope) + altScreen: alt }) } diff --git a/mobile/src/terminal/document/viewport-transform.ts b/mobile/src/terminal/document/viewport-transform.ts index 284b2a3d12ae..4f60fc9eca1a 100644 --- a/mobile/src/terminal/document/viewport-transform.ts +++ b/mobile/src/terminal/document/viewport-transform.ts @@ -19,15 +19,6 @@ export function flog(scope: TerminalDocumentScope, tag: string, payload: Record< } catch {} } -/** 0 until the renderer has measured a cell. */ -export function getMeasuredCellHeight(scope: TerminalDocumentScope) { - const core = scope.term?._core - if (core && core._renderService && core._renderService.dimensions) { - return core._renderService.dimensions.css.cell.height || 0 - } - return 0 -} - export function getCellWidth(scope: TerminalDocumentScope) { if (!scope.term || !scope.term._core) { return 0 diff --git a/mobile/src/terminal/terminal-keyboard-avoidance-webview.test.ts b/mobile/src/terminal/terminal-keyboard-avoidance-webview.test.ts index 9291f6fbe6ce..f47395be0490 100644 --- a/mobile/src/terminal/terminal-keyboard-avoidance-webview.test.ts +++ b/mobile/src/terminal/terminal-keyboard-avoidance-webview.test.ts @@ -1,4 +1,3 @@ -import { readFileSync } from 'node:fs' import { Terminal } from '@xterm/xterm' import { describe, expect, it, vi } from 'vitest' import { createTerminalDocumentScope } from './document/document-scope' @@ -14,12 +13,11 @@ import { parseTerminalKeyboardAvoidanceMetrics } from './terminal-webview-contra * it is handed, so a case builds one with its own terminal double and reads the notifications back * out of the seam it passed in. */ -function runMetricsOver(term: unknown, fitScale = 1): Record[] { +function runMetricsOver(term: unknown): Record[] { const notifications: Record[] = [] const scope = createTerminalDocumentScope({ postToHost: (message) => notifications.push(message) }) - scope.currentScale = fitScale // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: each case's double implements the buffer members the scan reads, which is what the assertions check. scope.term = term as typeof scope.term emitKeyboardAvoidanceMetrics(scope) @@ -216,32 +214,4 @@ describe('terminal keyboard-avoidance WebView metrics', () => { expect(emitAt, `${module} emits before it resizes`).toBeGreaterThan(geometryAt) } }) - - it('reports the row pitch as drawn, fit scale included, and none before a cell is measured', () => { - // Desktop display mode keeps the desktop's rows and the fit shrinks the grid by width. - const buffer = { cursorY: 0, viewportY: 0, type: 'normal', getLine: () => undefined } - const measuredTerm = { - buffer: { active: buffer }, - cols: 10, - rows: 47, - _core: { _renderService: { dimensions: { css: { cell: { width: 8, height: 15 } } } } } - } - const phone = runMetricsOver(measuredTerm)[0] - const desktop = runMetricsOver(measuredTerm, 0.5)[0] - const unmeasured = runMetricsOver({ buffer: { active: buffer }, cols: 10, rows: 47 })[0] - expect({ - phone: phone?.rowPitch, - desktop: desktop?.rowPitch, - unmeasured: unmeasured?.rowPitch - }).toEqual({ phone: 15, desktop: 7.5, unmeasured: 0 }) - }) - - it('reports again when a fit commits a new scale', () => { - const fit = readFileSync(new URL('./document/fit-scale.ts', import.meta.url), 'utf8') - const commit = fit.slice(fit.indexOf('export function commitFitScale(')) - const body = commit.slice(0, commit.indexOf('\n}\n')) - expect(body.indexOf('emitKeyboardAvoidanceMetrics(scope)')).toBeGreaterThan( - body.indexOf('scope.currentScale = 1') - ) - }) }) diff --git a/mobile/src/terminal/terminal-webview-contract.test.ts b/mobile/src/terminal/terminal-webview-contract.test.ts index aca7f9533d83..0a3527111e3e 100644 --- a/mobile/src/terminal/terminal-webview-contract.test.ts +++ b/mobile/src/terminal/terminal-webview-contract.test.ts @@ -1,10 +1,6 @@ import { describe, expect, it } from 'vitest' -import { - parseTerminalKeyboardAvoidanceMetrics, - sameTerminalKeyboardAvoidanceMetrics, - type TerminalKeyboardAvoidanceMetrics -} from './terminal-webview-contract' +import { parseTerminalKeyboardAvoidanceMetrics } from './terminal-webview-contract' describe('parseTerminalKeyboardAvoidanceMetrics', () => { it('parses a full payload', () => { @@ -53,44 +49,4 @@ describe('parseTerminalKeyboardAvoidanceMetrics', () => { }) ).toEqual({ cursorY: 0, contentBottomRow: 0, rows: 0, altScreen: false }) }) - - it('carries the drawn row pitch when the document reports one, and omits it otherwise', () => { - expect(parseTerminalKeyboardAvoidanceMetrics({ cursorY: 46, rows: 47, rowPitch: 7.5 })).toEqual( - { cursorY: 46, contentBottomRow: 46, rows: 47, altScreen: false, rowPitch: 7.5 } - ) - for (const rowPitch of [undefined, 0, -3, Number.NaN, Number.POSITIVE_INFINITY, '15']) { - expect( - 'rowPitch' in parseTerminalKeyboardAvoidanceMetrics({ cursorY: 1, rows: 4, rowPitch }) - ).toBe(false) - } - }) -}) - -describe('sameTerminalKeyboardAvoidanceMetrics', () => { - const metrics: Required = { - cursorY: 38, - contentBottomRow: 38, - rows: 40, - altScreen: false, - rowPitch: 15 - } - // One variant per field, each differing from `metrics` in that field alone. - const variants: [keyof typeof metrics, TerminalKeyboardAvoidanceMetrics][] = [ - ['cursorY', { ...metrics, cursorY: 39 }], - ['contentBottomRow', { ...metrics, contentBottomRow: 39 }], - ['rows', { ...metrics, rows: 41 }], - ['altScreen', { ...metrics, altScreen: true }], - // Desktop display mode, measured on the page: same rows, the fit scale moved to 0.46. - ['rowPitch', { ...metrics, rowPitch: 6.96 }] - ] - - it('tells apart metrics that differ in any one field', () => { - expect(sameTerminalKeyboardAvoidanceMetrics(metrics, { ...metrics })).toBe(true) - expect(variants.map(([key]) => key).sort()).toEqual(Object.keys(metrics).sort()) - for (const [key, variant] of variants) { - expect(sameTerminalKeyboardAvoidanceMetrics(metrics, variant), key).toBe(false) - } - const { rowPitch: _rowPitch, ...older } = metrics - expect(sameTerminalKeyboardAvoidanceMetrics(metrics, older)).toBe(false) - }) }) diff --git a/mobile/src/terminal/terminal-webview-contract.ts b/mobile/src/terminal/terminal-webview-contract.ts index e20821926289..45b9a38c05a5 100644 --- a/mobile/src/terminal/terminal-webview-contract.ts +++ b/mobile/src/terminal/terminal-webview-contract.ts @@ -18,23 +18,6 @@ export type TerminalKeyboardAvoidanceMetrics = { contentBottomRow: number rows: number altScreen: boolean - // CSS px between drawn rows, fit scale included; absent from older documents and before the - // renderer has measured. - rowPitch?: number -} - -/** Every field: a fit-scale change moves only the row pitch, and the lift must hear it. */ -export function sameTerminalKeyboardAvoidanceMetrics( - a: TerminalKeyboardAvoidanceMetrics, - b: TerminalKeyboardAvoidanceMetrics -): boolean { - return ( - a.cursorY === b.cursorY && - a.contentBottomRow === b.contentBottomRow && - a.rows === b.rows && - a.altScreen === b.altScreen && - a.rowPitch === b.rowPitch - ) } export function parseTerminalKeyboardAvoidanceMetrics( @@ -47,11 +30,12 @@ export function parseTerminalKeyboardAvoidanceMetrics( msg.contentBottomRow === undefined ? cursorY : Math.min(toNonNegativeInteger(msg.contentBottomRow), maxRow) - const metrics = { cursorY, contentBottomRow, rows, altScreen: msg.altScreen === true } - const rowPitch = msg.rowPitch - return typeof rowPitch === 'number' && Number.isFinite(rowPitch) && rowPitch > 0 - ? { ...metrics, rowPitch } - : metrics + return { + cursorY, + contentBottomRow, + rows, + altScreen: msg.altScreen === true + } } function toNonNegativeInteger(value: unknown): number { From 4bf6c20ca920fbc0a5f041f3eca63b7f98b04b82 Mon Sep 17 00:00:00 2001 From: Jinwoo-H Date: Sat, 26 Sep 2026 00:07:25 -0400 Subject: [PATCH 10/22] fix(mobile): a tap keeps the keyboard only for a pressable inside its own bar In `handled` mode the check took `closest('[tabindex]')`, which can match a focusable ancestor above the container, so every tap in the bar would have kept focus. The pressable must now be inside the container. Also renames a web seam test title that still described the shortened WebView. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb --- mobile/src/platform/keyboard-occlusion.web.test.tsx | 2 +- .../src/platform/keyboard-persisting-taps.web.test.ts | 11 +++++++++++ mobile/src/platform/keyboard-persisting-taps.web.ts | 8 +++++++- 3 files changed, 19 insertions(+), 2 deletions(-) diff --git a/mobile/src/platform/keyboard-occlusion.web.test.tsx b/mobile/src/platform/keyboard-occlusion.web.test.tsx index fdba98e028fe..b6bae0e85476 100644 --- a/mobile/src/platform/keyboard-occlusion.web.test.tsx +++ b/mobile/src/platform/keyboard-occlusion.web.test.tsx @@ -228,7 +228,7 @@ describe('the keyboard as events, for a sheet', () => { expect(lift).toBe(0) }) - it('stays silent when nothing is covered, which is the shell shortening the WebView', () => { + it('stays silent while the visual viewport covers nothing', () => { const calls: string[] = [] const unsubscribe = subscribeSoftKeyboard( () => calls.push('show'), diff --git a/mobile/src/platform/keyboard-persisting-taps.web.test.ts b/mobile/src/platform/keyboard-persisting-taps.web.test.ts index e02f71f93f53..9bea438b4050 100644 --- a/mobile/src/platform/keyboard-persisting-taps.web.test.ts +++ b/mobile/src/platform/keyboard-persisting-taps.web.test.ts @@ -67,6 +67,17 @@ describe('keepTextFocusThroughTaps', () => { expect(pressKeepsFocus(field)).toBe(false) }) + it('does not count a focusable ancestor above the container as a pressable in the bar', () => { + const outer = document.createElement('div') + outer.tabIndex = 0 + const { container, gap, liveInput } = plant() + outer.append(container) + document.body.prepend(outer) + keepTextFocusThroughTaps(container, 'handled') + liveInput.focus() + expect(pressKeepsFocus(gap)).toBe(false) + }) + it('stops when released', () => { const { container, label, liveInput } = plant() keepTextFocusThroughTaps(container, 'always')() diff --git a/mobile/src/platform/keyboard-persisting-taps.web.ts b/mobile/src/platform/keyboard-persisting-taps.web.ts index af3330d568b9..ae05cf0355f5 100644 --- a/mobile/src/platform/keyboard-persisting-taps.web.ts +++ b/mobile/src/platform/keyboard-persisting-taps.web.ts @@ -14,6 +14,12 @@ function isTextField(element: Element | null): boolean { ) } +/** A focusable element between the tap and the container; an ancestor above it is not in the bar. */ +function isPressableInside(container: HTMLElement, target: Element): boolean { + const pressable = target.closest('[tabindex]:not([tabindex="-1"])') + return pressable !== null && pressable !== container && container.contains(pressable) +} + /** * `keyboardShouldPersistTaps` for the page: react-native-web ignores it, and a Pressable there is a * focusable element that takes focus on mousedown, which blurs the text field and closes the IME. @@ -28,7 +34,7 @@ export function keepTextFocusThroughTaps( if (!isTextField(document.activeElement) || !target || isTextField(target)) { return } - if (mode === 'handled' && !target.closest('[tabindex]:not([tabindex="-1"])')) { + if (mode === 'handled' && !isPressableInside(container, target)) { return } event.preventDefault() From b179bf730bb0c855ea43196444a3ffce9d15e840 Mon Sep 17 00:00:00 2001 From: Jinwoo-H Date: Sat, 26 Sep 2026 00:36:57 -0400 Subject: [PATCH 11/22] fix(mobile): the iOS page's keyboard carries no form accessory bar iPhone 17 simulator: WKWebView's form accessory bar (up, down, done) rode on the keyboard, and the keyboard event the shell publishes counted it, so the page's dock lifted 379 pt against native's 277 and stood 52 pt above the bar. The shell's iOS view moves the WebView's content view onto a subclass whose `inputAccessoryView` is nil, as react-native-webview's `hideKeyboardAccessoryView` does. The WebView neither resized nor scrolled for the keyboard before or after: the header held its place. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb --- .../ios/MobileWebShellKeyboardAccessory.swift | 34 +++++++++++++++++++ .../ios/MobileWebShellView.swift | 1 + .../shell-view-keyboard-accessory.test.ts | 22 ++++++++++++ 3 files changed, 57 insertions(+) create mode 100644 mobile/modules/orca-mobile-web-shell/ios/MobileWebShellKeyboardAccessory.swift create mode 100644 mobile/src/mobile-web-shell/shell-view-keyboard-accessory.test.ts diff --git a/mobile/modules/orca-mobile-web-shell/ios/MobileWebShellKeyboardAccessory.swift b/mobile/modules/orca-mobile-web-shell/ios/MobileWebShellKeyboardAccessory.swift new file mode 100644 index 000000000000..07b5e9620f7c --- /dev/null +++ b/mobile/modules/orca-mobile-web-shell/ios/MobileWebShellKeyboardAccessory.swift @@ -0,0 +1,34 @@ +import ObjectiveC +import UIKit +import WebKit + +/// Removes WKWebView's form accessory bar (up, down, done). Native screens have none, and the +/// keyboard event the shell publishes counts it, so the page lifted by the bar as well. WebKit +/// exposes no switch, so the content view is moved onto a subclass whose `inputAccessoryView` is +/// nil, the same technique react-native-webview's `hideKeyboardAccessoryView` uses. +func hideKeyboardAccessoryBar(of webView: WKWebView) { + guard + let content = webView.scrollView.subviews.first(where: { + String(describing: type(of: $0)).hasPrefix("WKContent") + }) + else { + return + } + let base: AnyClass = type(of: content) + let name = "\(NSStringFromClass(base))_OrcaNoAccessory" + let subclass: AnyClass + if let existing = NSClassFromString(name) { + subclass = existing + } else { + guard let created = objc_allocateClassPair(base, name, 0) else { + return + } + let noAccessory: @convention(block) (AnyObject) -> UIView? = { _ in nil } + let selector = #selector(getter: UIResponder.inputAccessoryView) + let typeEncoding = method_getTypeEncoding(class_getInstanceMethod(UIResponder.self, selector)!) + class_addMethod(created, selector, imp_implementationWithBlock(noAccessory), typeEncoding) + objc_registerClassPair(created) + subclass = created + } + object_setClass(content, subclass) +} diff --git a/mobile/modules/orca-mobile-web-shell/ios/MobileWebShellView.swift b/mobile/modules/orca-mobile-web-shell/ios/MobileWebShellView.swift index 0a2122f8183a..7fd75fc7f840 100644 --- a/mobile/modules/orca-mobile-web-shell/ios/MobileWebShellView.swift +++ b/mobile/modules/orca-mobile-web-shell/ios/MobileWebShellView.swift @@ -221,6 +221,7 @@ final class OrcaMobileWebShellView: ExpoView, WKNavigationDelegate, WKUIDelegate webView.backgroundColor = .clear webView.scrollView.backgroundColor = .clear webView.scrollView.contentInsetAdjustmentBehavior = .never + hideKeyboardAccessoryBar(of: webView) webView.translatesAutoresizingMaskIntoConstraints = false addSubview(webView) NSLayoutConstraint.activate([ diff --git a/mobile/src/mobile-web-shell/shell-view-keyboard-accessory.test.ts b/mobile/src/mobile-web-shell/shell-view-keyboard-accessory.test.ts new file mode 100644 index 000000000000..5785feeec465 --- /dev/null +++ b/mobile/src/mobile-web-shell/shell-view-keyboard-accessory.test.ts @@ -0,0 +1,22 @@ +import { describe, expect, it } from 'vitest' +import { readFileSync } from 'node:fs' +import { join } from 'node:path' + +/** + * The iOS shell's keyboard, read off the Swift view: a property of a live WKWebView, so what is + * checkable here is that the view installs the fix, and the simulator proof measures its effect. + * + * iPhone 17 simulator, measured: WKWebView's form accessory bar (up, down, done) rides on the + * keyboard, and the keyboard event's height counts it, so the page's dock lifted 379 pt against + * native's 277 and stood 52 pt above the bar. + */ +const SHELL = join(import.meta.dirname, '..', '..', 'modules', 'orca-mobile-web-shell', 'ios') + +describe("the iOS WebView's keyboard", () => { + it('carries no form accessory bar, so the keyboard is the height a native screen reads', () => { + const view = readFileSync(join(SHELL, 'MobileWebShellView.swift'), 'utf8') + expect(view).toContain('hideKeyboardAccessoryBar(of: webView)') + const accessory = readFileSync(join(SHELL, 'MobileWebShellKeyboardAccessory.swift'), 'utf8') + expect(accessory).toContain('inputAccessoryView') + }) +}) From 2a3d46a16e80932249dd20cc3ff543ef07a535e2 Mon Sep 17 00:00:00 2001 From: Jinwoo-H Date: Sat, 26 Sep 2026 00:36:57 -0400 Subject: [PATCH 12/22] fix(mobile): the shell hands the page the keyboard's height above the bottom inset The session's lift subtracts the home-indicator inset only when `Platform.OS === 'ios'` (`use-mobile-session-presentation.ts:80`), and the page runs as `web`, so on iOS the page lifted 34 pt more than native. `keyboardInset` is now the height above the bottom safe-area inset on both platforms: Android's own convention, which the page's non-iOS code already reads. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb --- .../src/mobile-web-shell/MobileWebShellScreen.tsx | 12 +++++++++--- .../src/mobile-web-shell/bridge-host-contract.ts | 2 +- .../bridge/bridge-client-session.ts | 2 +- .../mobile-web-shell/bridge/bridge-envelope.ts | 2 +- .../mobile-web-shell/bridge/bridge-init-frame.ts | 2 +- .../bridge/bridge-keyboard-inset.ts | 6 +++--- ...ile-web-shell-keyboard-overlay-screen.test.tsx | 9 ++++++--- .../src/mobile-web-shell/page-keyboard-inset.ts | 15 +++++++++++++++ 8 files changed, 37 insertions(+), 13 deletions(-) create mode 100644 mobile/src/mobile-web-shell/page-keyboard-inset.ts diff --git a/mobile/src/mobile-web-shell/MobileWebShellScreen.tsx b/mobile/src/mobile-web-shell/MobileWebShellScreen.tsx index 080008a3a860..834dc9dbbe1f 100644 --- a/mobile/src/mobile-web-shell/MobileWebShellScreen.tsx +++ b/mobile/src/mobile-web-shell/MobileWebShellScreen.tsx @@ -42,6 +42,7 @@ import { useMobileWebShellSession } from './use-mobile-web-shell-session' import { usePageHostSnapshot } from './use-page-host-snapshot' import { SHELL_OPENING_LABEL, ShellPageCover, ShellWaitingFrame } from './ShellWaitingFrame' import { pageSafeAreaInsets, usePublishedSafeAreaInsets } from './page-safe-area-insets' +import { pageKeyboardInset } from './page-keyboard-inset' function failureMessage(reason: MobileWebShellFailureCause): string { switch (reason) { @@ -219,6 +220,11 @@ export function MobileWebShellScreen({ bottomInset: insets.bottom, platform: Platform.OS }) + const keyboardInset = pageKeyboardInset({ + keyboardHeight, + bottomInset: insets.bottom, + platform: Platform.OS + }) const pageInsets = pageSafeAreaInsets({ insets, viewShortenedBy, @@ -246,7 +252,7 @@ export function MobileWebShellScreen({ hostId, route, safeAreaInsets: pageInsets, - keyboardInset: keyboardHeight, + keyboardInset, pageRoutes, pageRouteGrants, routeGrants, @@ -331,8 +337,8 @@ export function MobileWebShellScreen({ // Every keyboard event, a height change while open included, so the page never holds a stale one. const publishKeyboardInset = bridge.publishKeyboardInset useEffect(() => { - publishKeyboardInset(keyboardHeight) - }, [publishKeyboardInset, keyboardHeight]) + publishKeyboardInset(keyboardInset) + }, [publishKeyboardInset, keyboardInset]) // The navigation object rather than the router: what this takes away is this screen's own place // on the stack, which is a screen option, and the router has no member that says it. diff --git a/mobile/src/mobile-web-shell/bridge-host-contract.ts b/mobile/src/mobile-web-shell/bridge-host-contract.ts index 9253fad99a0d..c94c1e8f200f 100644 --- a/mobile/src/mobile-web-shell/bridge-host-contract.ts +++ b/mobile/src/mobile-web-shell/bridge-host-contract.ts @@ -133,7 +133,7 @@ export type BridgeHostOptions = { /** How much of the WebView sits under a system bar when it is drawn edge-to-edge. Zeros when * absent; moved later with `publishSafeAreaInsets`. */ safeAreaInsets?: BridgeSafeAreaInsets - /** How much of the WebView the software keyboard covers. 0 when absent; moved later with + /** The keyboard height above the bottom safe-area inset. 0 when absent; moved later with * `publishKeyboardInset`. */ keyboardInset?: number /** diff --git a/mobile/src/mobile-web-shell/bridge/bridge-client-session.ts b/mobile/src/mobile-web-shell/bridge/bridge-client-session.ts index a4ec43d48ace..38a8a00fce9b 100644 --- a/mobile/src/mobile-web-shell/bridge/bridge-client-session.ts +++ b/mobile/src/mobile-web-shell/bridge/bridge-client-session.ts @@ -27,7 +27,7 @@ export type BridgeShellSession = { /** How much of the WebView sits under a system bar. Zeros for a shell that reserves the bars * outside the view, which is every shell before the field. */ safeAreaInsets: BridgeSafeAreaInsets - /** How much of the WebView the software keyboard covers. 0 for a shell that shortens the view + /** The keyboard height above the bottom safe-area inset. 0 for a shell that shortens the view * above it instead, which is every shell before the field. */ keyboardInset: number /** Null for a shell too old to name it; the page's own `loadHosts()` then answers with nothing. */ diff --git a/mobile/src/mobile-web-shell/bridge/bridge-envelope.ts b/mobile/src/mobile-web-shell/bridge/bridge-envelope.ts index 17ea2330fe22..28044966d361 100644 --- a/mobile/src/mobile-web-shell/bridge/bridge-envelope.ts +++ b/mobile/src/mobile-web-shell/bridge/bridge-envelope.ts @@ -308,7 +308,7 @@ const BridgeHostMessageSchema = z.union([ route: BridgeInitRouteSchema.optional(), /** How much of the WebView is under a system bar; absent reads as zeros. */ safeAreaInsets: BridgeSafeAreaInsetsSchema.optional(), - /** How much of the WebView the software keyboard covers; absent reads as 0. */ + /** The keyboard height above the bottom safe-area inset; absent reads as 0. */ keyboardInset: BridgeKeyboardInsetSchema.optional(), host: BridgeInitHostSchema.optional(), storage: BridgeInitStorageSchema.optional(), diff --git a/mobile/src/mobile-web-shell/bridge/bridge-init-frame.ts b/mobile/src/mobile-web-shell/bridge/bridge-init-frame.ts index a350a5124374..3ea4d1a906d3 100644 --- a/mobile/src/mobile-web-shell/bridge/bridge-init-frame.ts +++ b/mobile/src/mobile-web-shell/bridge/bridge-init-frame.ts @@ -57,7 +57,7 @@ export function createBridgeInitFrame(args: { pageRoutes: readonly string[] /** How much of the WebView sits under a system bar, for a page that pads for them itself. */ safeAreaInsets?: BridgeSafeAreaInsets - /** How much of the WebView the software keyboard covers. */ + /** The keyboard height above the bottom safe-area inset. */ keyboardInset?: number /** What each of those patterns declared, so the page can tell a hop it may keep from one it * must hand back. Omitted by a shell that has none, which leaves the page on its old rule. */ diff --git a/mobile/src/mobile-web-shell/bridge/bridge-keyboard-inset.ts b/mobile/src/mobile-web-shell/bridge/bridge-keyboard-inset.ts index f7b5af8a9317..a447eb6840ec 100644 --- a/mobile/src/mobile-web-shell/bridge/bridge-keyboard-inset.ts +++ b/mobile/src/mobile-web-shell/bridge/bridge-keyboard-inset.ts @@ -2,9 +2,9 @@ import { z } from 'zod' import { BRIDGE_MAX_SAFE_AREA_INSET } from './bridge-safe-area-insets' /** - * How much of the bottom of the page's WebView the software keyboard covers, in the page's px; 0 - * while it is closed. The shell overlays the IME on the view like a native screen, and the page - * cannot measure it: the view's IME insets are zeroed, so `visualViewport` never shrinks. + * The software keyboard's height above the bottom safe-area inset, in the page's px (Android's own + * convention); 0 while it is closed. The shell overlays the IME on the view like a native screen, + * and the page cannot measure it: the view's IME insets are zeroed, so `visualViewport` never moves. */ export const BridgeKeyboardInsetSchema = z.number().finite().min(0).max(BRIDGE_MAX_SAFE_AREA_INSET) diff --git a/mobile/src/mobile-web-shell/mobile-web-shell-keyboard-overlay-screen.test.tsx b/mobile/src/mobile-web-shell/mobile-web-shell-keyboard-overlay-screen.test.tsx index c71e4e5db332..5c422cfe5a59 100644 --- a/mobile/src/mobile-web-shell/mobile-web-shell-keyboard-overlay-screen.test.tsx +++ b/mobile/src/mobile-web-shell/mobile-web-shell-keyboard-overlay-screen.test.tsx @@ -108,11 +108,14 @@ describe('a page the keyboard covers', () => { await page.keyboard(height) expect(page.root().props.style[1]).toEqual({ paddingTop: 0, paddingBottom: 0 }) } - // The keyboard's own height, as native screens read it; the bottom inset stays the window's. + // The height above the bottom inset, which is Android's own and what the page's non-iOS lift + // reads; iOS measures from the window's bottom, so the home-indicator strip comes off there. + // The bottom inset itself stays the window's. + const above = platform === 'ios' ? WINDOW.bottom : 0 expect(page.inits()).toEqual([ { keyboard: 0, insets: WINDOW }, - { keyboard: 312, insets: WINDOW }, - { keyboard: 346, insets: WINDOW }, + { keyboard: 312 - above, insets: WINDOW }, + { keyboard: 346 - above, insets: WINDOW }, { keyboard: 0, insets: WINDOW } ]) }) diff --git a/mobile/src/mobile-web-shell/page-keyboard-inset.ts b/mobile/src/mobile-web-shell/page-keyboard-inset.ts new file mode 100644 index 000000000000..a37b5ab00f7d --- /dev/null +++ b/mobile/src/mobile-web-shell/page-keyboard-inset.ts @@ -0,0 +1,15 @@ +/** + * The keyboard height the page is handed: its height above the bottom safe-area inset, which is + * what Android reports and what the page's non-iOS code reads. iOS measures from the window's + * bottom, home indicator included, and the page runs as `web`, so the strip comes off here. + */ +export function pageKeyboardInset(input: { + keyboardHeight: number + bottomInset: number + platform: 'ios' | 'android' | 'windows' | 'macos' | 'web' +}): number { + const keyboardHeight = Math.max(0, input.keyboardHeight) + return input.platform === 'ios' + ? Math.max(0, keyboardHeight - Math.max(0, input.bottomInset)) + : keyboardHeight +} From 15204c8475a47216a85425e8c0af99325ecf3d55 Mon Sep 17 00:00:00 2001 From: Jinwoo-H Date: Sat, 26 Sep 2026 00:48:24 -0400 Subject: [PATCH 13/22] refactor(mobile): the shell's keyboard geometry is one function beside the page's inset Moves the published height and the legacy strip out of the screen, which had reached the 400-line cap, into `shellKeyboardGeometry`. The legacy branch keeps its deletion condition. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb --- .../mobile-web-shell/MobileWebShellScreen.tsx | 20 +++++-------------- .../mobile-web-shell/page-keyboard-inset.ts | 18 +++++++++++++++++ 2 files changed, 23 insertions(+), 15 deletions(-) diff --git a/mobile/src/mobile-web-shell/MobileWebShellScreen.tsx b/mobile/src/mobile-web-shell/MobileWebShellScreen.tsx index 834dc9dbbe1f..b26e1ca9496f 100644 --- a/mobile/src/mobile-web-shell/MobileWebShellScreen.tsx +++ b/mobile/src/mobile-web-shell/MobileWebShellScreen.tsx @@ -34,7 +34,6 @@ import { playPageHaptic } from './page-haptics' import { useMobileWebShellBridge } from './use-mobile-web-shell-bridge' import type { MobileWebShellRuntime } from './mobile-web-shell-runtime' import { useKeyboardOcclusion } from '../platform/keyboard-occlusion' -import { softwareKeyboardWindowInset } from '../platform/software-keyboard-window-inset' import { useNativeDeviceVerbs } from '../platform/use-native-device-verbs' import { useShellPageBack } from './use-shell-page-back' import { useShellStackPop } from './use-shell-stack-pop' @@ -42,7 +41,7 @@ import { useMobileWebShellSession } from './use-mobile-web-shell-session' import { usePageHostSnapshot } from './use-page-host-snapshot' import { SHELL_OPENING_LABEL, ShellPageCover, ShellWaitingFrame } from './ShellWaitingFrame' import { pageSafeAreaInsets, usePublishedSafeAreaInsets } from './page-safe-area-insets' -import { pageKeyboardInset } from './page-keyboard-inset' +import { shellKeyboardGeometry } from './page-keyboard-inset' function failureMessage(reason: MobileWebShellFailureCause): string { switch (reason) { @@ -210,20 +209,11 @@ export function MobileWebShellScreen({ // The page cannot see the IME for itself: edge-to-edge makes `adjustResize` inert and the view's // IME insets are zeroed, so `visualViewport` never shrinks. A page that reads the height from // `init` is covered by the keyboard like a native screen; an older one gets a view ended above it. - const keyboardHeight = useKeyboardOcclusion() - // Legacy: only a page without the `keyboard-inset` accept is shortened; delete this branch (and - // `softwareKeyboardWindowInset`) once every served page declares it. - const viewShortenedBy = pageReadsKeyboardInset - ? 0 - : softwareKeyboardWindowInset({ - keyboardHeight, - bottomInset: insets.bottom, - platform: Platform.OS - }) - const keyboardInset = pageKeyboardInset({ - keyboardHeight, + const { keyboardInset, viewShortenedBy } = shellKeyboardGeometry({ + keyboardHeight: useKeyboardOcclusion(), bottomInset: insets.bottom, - platform: Platform.OS + platform: Platform.OS, + pageReadsKeyboardInset }) const pageInsets = pageSafeAreaInsets({ insets, diff --git a/mobile/src/mobile-web-shell/page-keyboard-inset.ts b/mobile/src/mobile-web-shell/page-keyboard-inset.ts index a37b5ab00f7d..ef79bc388044 100644 --- a/mobile/src/mobile-web-shell/page-keyboard-inset.ts +++ b/mobile/src/mobile-web-shell/page-keyboard-inset.ts @@ -1,3 +1,5 @@ +import { softwareKeyboardWindowInset } from '../platform/software-keyboard-window-inset' + /** * The keyboard height the page is handed: its height above the bottom safe-area inset, which is * what Android reports and what the page's non-iOS code reads. iOS measures from the window's @@ -13,3 +15,19 @@ export function pageKeyboardInset(input: { ? Math.max(0, keyboardHeight - Math.max(0, input.bottomInset)) : keyboardHeight } + +/** What the shell does with one keyboard reading: the height it hands the page, and the strip it + * takes off the view, which is none for a page that reads the height. */ +export function shellKeyboardGeometry(input: { + keyboardHeight: number + bottomInset: number + platform: 'ios' | 'android' | 'windows' | 'macos' | 'web' + pageReadsKeyboardInset: boolean +}): { keyboardInset: number; viewShortenedBy: number } { + return { + keyboardInset: pageKeyboardInset(input), + // Legacy: only a page without the `keyboard-inset` accept is shortened; delete this branch (and + // `softwareKeyboardWindowInset`) once every served page declares it. + viewShortenedBy: input.pageReadsKeyboardInset ? 0 : softwareKeyboardWindowInset(input) + } +} From 333a0bb932bfb9d3d73a5c2784497bb1b8a6dc2f Mon Sep 17 00:00:00 2001 From: Jinwoo-H Date: Sat, 26 Sep 2026 01:02:30 -0400 Subject: [PATCH 14/22] fix(mobile): the shell hands the page the keyboard height native screens read again Subtracting the home indicator from the published height fixed the terminal on an iPhone page and moved two views that read the raw height natively: the source-control commit bar and fill-mode sheets, which dock to the true keyboard top. The field is the raw per-OS height again; the page's arithmetic reads the shell's OS in the next commit, so each consumer computes what native does. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb --- .../mobile-web-shell/bridge-host-contract.ts | 2 +- .../bridge/bridge-client-session.ts | 4 ++-- .../bridge/bridge-envelope.ts | 2 +- .../bridge/bridge-init-frame.ts | 2 +- .../bridge/bridge-keyboard-inset.ts | 6 ++--- ...web-shell-keyboard-overlay-screen.test.tsx | 11 ++++----- .../mobile-web-shell/page-keyboard-inset.ts | 23 ++++--------------- 7 files changed, 17 insertions(+), 33 deletions(-) diff --git a/mobile/src/mobile-web-shell/bridge-host-contract.ts b/mobile/src/mobile-web-shell/bridge-host-contract.ts index c94c1e8f200f..26b6819d376e 100644 --- a/mobile/src/mobile-web-shell/bridge-host-contract.ts +++ b/mobile/src/mobile-web-shell/bridge-host-contract.ts @@ -133,7 +133,7 @@ export type BridgeHostOptions = { /** How much of the WebView sits under a system bar when it is drawn edge-to-edge. Zeros when * absent; moved later with `publishSafeAreaInsets`. */ safeAreaInsets?: BridgeSafeAreaInsets - /** The keyboard height above the bottom safe-area inset. 0 when absent; moved later with + /** The keyboard height native screens read on the shell's OS. 0 when absent; moved later with * `publishKeyboardInset`. */ keyboardInset?: number /** diff --git a/mobile/src/mobile-web-shell/bridge/bridge-client-session.ts b/mobile/src/mobile-web-shell/bridge/bridge-client-session.ts index 38a8a00fce9b..ff989d8c0793 100644 --- a/mobile/src/mobile-web-shell/bridge/bridge-client-session.ts +++ b/mobile/src/mobile-web-shell/bridge/bridge-client-session.ts @@ -27,8 +27,8 @@ export type BridgeShellSession = { /** How much of the WebView sits under a system bar. Zeros for a shell that reserves the bars * outside the view, which is every shell before the field. */ safeAreaInsets: BridgeSafeAreaInsets - /** The keyboard height above the bottom safe-area inset. 0 for a shell that shortens the view - * above it instead, which is every shell before the field. */ + /** The keyboard height native screens read on the shell's OS. 0 for a shell that shortens the + * view above it instead, which is every shell before the field. */ keyboardInset: number /** Null for a shell too old to name it; the page's own `loadHosts()` then answers with nothing. */ host: BridgeInitHost | null diff --git a/mobile/src/mobile-web-shell/bridge/bridge-envelope.ts b/mobile/src/mobile-web-shell/bridge/bridge-envelope.ts index 28044966d361..b85925012d67 100644 --- a/mobile/src/mobile-web-shell/bridge/bridge-envelope.ts +++ b/mobile/src/mobile-web-shell/bridge/bridge-envelope.ts @@ -308,7 +308,7 @@ const BridgeHostMessageSchema = z.union([ route: BridgeInitRouteSchema.optional(), /** How much of the WebView is under a system bar; absent reads as zeros. */ safeAreaInsets: BridgeSafeAreaInsetsSchema.optional(), - /** The keyboard height above the bottom safe-area inset; absent reads as 0. */ + /** The keyboard height native screens read on the shell's OS; absent reads as 0. */ keyboardInset: BridgeKeyboardInsetSchema.optional(), host: BridgeInitHostSchema.optional(), storage: BridgeInitStorageSchema.optional(), diff --git a/mobile/src/mobile-web-shell/bridge/bridge-init-frame.ts b/mobile/src/mobile-web-shell/bridge/bridge-init-frame.ts index 3ea4d1a906d3..c838c5b3b356 100644 --- a/mobile/src/mobile-web-shell/bridge/bridge-init-frame.ts +++ b/mobile/src/mobile-web-shell/bridge/bridge-init-frame.ts @@ -57,7 +57,7 @@ export function createBridgeInitFrame(args: { pageRoutes: readonly string[] /** How much of the WebView sits under a system bar, for a page that pads for them itself. */ safeAreaInsets?: BridgeSafeAreaInsets - /** The keyboard height above the bottom safe-area inset. */ + /** The keyboard height native screens read on the shell's OS. */ keyboardInset?: number /** What each of those patterns declared, so the page can tell a hop it may keep from one it * must hand back. Omitted by a shell that has none, which leaves the page on its old rule. */ diff --git a/mobile/src/mobile-web-shell/bridge/bridge-keyboard-inset.ts b/mobile/src/mobile-web-shell/bridge/bridge-keyboard-inset.ts index a447eb6840ec..0299a74f637a 100644 --- a/mobile/src/mobile-web-shell/bridge/bridge-keyboard-inset.ts +++ b/mobile/src/mobile-web-shell/bridge/bridge-keyboard-inset.ts @@ -2,9 +2,9 @@ import { z } from 'zod' import { BRIDGE_MAX_SAFE_AREA_INSET } from './bridge-safe-area-insets' /** - * The software keyboard's height above the bottom safe-area inset, in the page's px (Android's own - * convention); 0 while it is closed. The shell overlays the IME on the view like a native screen, - * and the page cannot measure it: the view's IME insets are zeroed, so `visualViewport` never moves. + * The software keyboard's height as native screens read it on the shell's OS (iOS from the + * window's bottom, Android above the bars), in the page's px; 0 while it is closed. The shell + * overlays the IME on the view like a native screen, and the page cannot measure it. */ export const BridgeKeyboardInsetSchema = z.number().finite().min(0).max(BRIDGE_MAX_SAFE_AREA_INSET) diff --git a/mobile/src/mobile-web-shell/mobile-web-shell-keyboard-overlay-screen.test.tsx b/mobile/src/mobile-web-shell/mobile-web-shell-keyboard-overlay-screen.test.tsx index 5c422cfe5a59..19acb4a681db 100644 --- a/mobile/src/mobile-web-shell/mobile-web-shell-keyboard-overlay-screen.test.tsx +++ b/mobile/src/mobile-web-shell/mobile-web-shell-keyboard-overlay-screen.test.tsx @@ -108,14 +108,13 @@ describe('a page the keyboard covers', () => { await page.keyboard(height) expect(page.root().props.style[1]).toEqual({ paddingTop: 0, paddingBottom: 0 }) } - // The height above the bottom inset, which is Android's own and what the page's non-iOS lift - // reads; iOS measures from the window's bottom, so the home-indicator strip comes off there. - // The bottom inset itself stays the window's. - const above = platform === 'ios' ? WINDOW.bottom : 0 + // The keyboard's own height as native screens read it on this OS, home indicator included on + // iOS; the page's arithmetic branches on the shell's OS, as native does. The bottom inset + // stays the window's. expect(page.inits()).toEqual([ { keyboard: 0, insets: WINDOW }, - { keyboard: 312 - above, insets: WINDOW }, - { keyboard: 346 - above, insets: WINDOW }, + { keyboard: 312, insets: WINDOW }, + { keyboard: 346, insets: WINDOW }, { keyboard: 0, insets: WINDOW } ]) }) diff --git a/mobile/src/mobile-web-shell/page-keyboard-inset.ts b/mobile/src/mobile-web-shell/page-keyboard-inset.ts index ef79bc388044..0b86ecb75dab 100644 --- a/mobile/src/mobile-web-shell/page-keyboard-inset.ts +++ b/mobile/src/mobile-web-shell/page-keyboard-inset.ts @@ -1,23 +1,8 @@ import { softwareKeyboardWindowInset } from '../platform/software-keyboard-window-inset' -/** - * The keyboard height the page is handed: its height above the bottom safe-area inset, which is - * what Android reports and what the page's non-iOS code reads. iOS measures from the window's - * bottom, home indicator included, and the page runs as `web`, so the strip comes off here. - */ -export function pageKeyboardInset(input: { - keyboardHeight: number - bottomInset: number - platform: 'ios' | 'android' | 'windows' | 'macos' | 'web' -}): number { - const keyboardHeight = Math.max(0, input.keyboardHeight) - return input.platform === 'ios' - ? Math.max(0, keyboardHeight - Math.max(0, input.bottomInset)) - : keyboardHeight -} - -/** What the shell does with one keyboard reading: the height it hands the page, and the strip it - * takes off the view, which is none for a page that reads the height. */ +/** What the shell does with one keyboard reading: the height it hands the page, which is the one + * native screens read on this OS, and the strip it takes off the view, none for a page that + * reads the height. */ export function shellKeyboardGeometry(input: { keyboardHeight: number bottomInset: number @@ -25,7 +10,7 @@ export function shellKeyboardGeometry(input: { pageReadsKeyboardInset: boolean }): { keyboardInset: number; viewShortenedBy: number } { return { - keyboardInset: pageKeyboardInset(input), + keyboardInset: Math.max(0, input.keyboardHeight), // Legacy: only a page without the `keyboard-inset` accept is shortened; delete this branch (and // `softwareKeyboardWindowInset`) once every served page declares it. viewShortenedBy: input.pageReadsKeyboardInset ? 0 : softwareKeyboardWindowInset(input) From 16c9228f5dea7fa64e4501a0993fe649c46b5aa1 Mon Sep 17 00:00:00 2001 From: Jinwoo-H Date: Sat, 26 Sep 2026 01:02:30 -0400 Subject: [PATCH 15/22] fix(mobile): keyboard and inset arithmetic branches on the host OS, not Platform.OS The page runs as `web`, so every `Platform.OS === 'ios'` in keyboard arithmetic took the Android branch on an iPhone page (`use-mobile-session-presentation.ts` lifted 34 pt past native). A platform seam answers the host OS: `Platform.OS` natively, the phone's OS from the WebView's user agent on the page (iPadOS by its touch points). The seven keyboard and inset reads move to it, and a census fails on a `Platform.OS` read within two lines of keyboard or inset arithmetic. Also corrects the accessory test's measured numbers (376 vs 274 pt). Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb --- mobile/app/h/[hostId]/edit.tsx | 3 +- .../components/MobileDiffReviewDrawers.tsx | 5 +- .../src/components/mounted-bottom-drawer.tsx | 13 +---- .../mobile-web-shell/MobileWebShellScreen.tsx | 13 +---- .../shell-view-keyboard-accessory.test.ts | 4 +- mobile/src/platform/host-os.ts | 8 +++ mobile/src/platform/host-os.web.test.ts | 31 +++++++++++ mobile/src/platform/host-os.web.ts | 19 +++++++ .../keyboard-geometry-host-os-census.test.ts | 55 +++++++++++++++++++ mobile/src/platform/keyboard-occlusion.ts | 7 ++- .../use-mobile-session-presentation.ts | 4 +- mobile/web-entry/web-overrides.json | 4 ++ 12 files changed, 136 insertions(+), 30 deletions(-) create mode 100644 mobile/src/platform/host-os.ts create mode 100644 mobile/src/platform/host-os.web.test.ts create mode 100644 mobile/src/platform/host-os.web.ts create mode 100644 mobile/src/platform/keyboard-geometry-host-os-census.test.ts diff --git a/mobile/app/h/[hostId]/edit.tsx b/mobile/app/h/[hostId]/edit.tsx index af15f28ad200..c1016af4cc0b 100644 --- a/mobile/app/h/[hostId]/edit.tsx +++ b/mobile/app/h/[hostId]/edit.tsx @@ -19,6 +19,7 @@ import { displayHostEndpoint } from '../../../src/transport/host-endpoint' import { resolveHostEndpointEdit } from '../../../src/transport/host-endpoint-edit' import { useForceReconnect, usePrimeHosts } from '../../../src/transport/client-context' import type { HostProfile } from '../../../src/transport/types' +import { hostOs } from '../../../src/platform/host-os' export default function EditHostScreen() { const router = useRouter() @@ -181,7 +182,7 @@ export default function EditHostScreen() { ) : ( @@ -164,7 +165,7 @@ function NoteComposerDrawer({ controller }: Props) { const composer = controller.composer return ( - + diff --git a/mobile/src/components/mounted-bottom-drawer.tsx b/mobile/src/components/mounted-bottom-drawer.tsx index 40f737fc45d6..18427409f929 100644 --- a/mobile/src/components/mounted-bottom-drawer.tsx +++ b/mobile/src/components/mounted-bottom-drawer.tsx @@ -1,13 +1,5 @@ import { type ReactNode, useCallback, useEffect, useRef, useState } from 'react' -import { - View, - Pressable, - useWindowDimensions, - ScrollView, - Keyboard, - Modal, - Platform -} from 'react-native' +import { View, Pressable, useWindowDimensions, ScrollView, Keyboard, Modal } from 'react-native' import { useSafeAreaInsets } from 'react-native-safe-area-context' import { Gesture, GestureDetector, GestureHandlerRootView } from 'react-native-gesture-handler' import Animated, { @@ -29,6 +21,7 @@ import { useInsideBottomDrawerModalHost } from './bottom-drawer-modal-host' import { useResponsiveLayout } from '../layout/responsive-layout' import { useBackClaim } from '../navigation/use-back-claim' import { currentSoftKeyboardHeight, subscribeSoftKeyboard } from '../platform/keyboard-occlusion' +import { hostOs } from '../platform/host-os' const DISMISS_THRESHOLD = 80 const SPRING_CONFIG = { damping: 28, stiffness: 400 } @@ -146,7 +139,7 @@ export function MountedBottomDrawer({ keyboardHeight, bottomInset: insets.bottom, fillAvailable, - platform: Platform.OS + platform: hostOs() }) setKeyboardInset(inset) if (duration > 0) { diff --git a/mobile/src/mobile-web-shell/MobileWebShellScreen.tsx b/mobile/src/mobile-web-shell/MobileWebShellScreen.tsx index b26e1ca9496f..d3a2a5e15c58 100644 --- a/mobile/src/mobile-web-shell/MobileWebShellScreen.tsx +++ b/mobile/src/mobile-web-shell/MobileWebShellScreen.tsx @@ -1,13 +1,5 @@ import { useEffect, useState, type ReactNode } from 'react' -import { - ActivityIndicator, - Linking, - Platform, - Pressable, - StyleSheet, - Text, - View -} from 'react-native' +import { ActivityIndicator, Linking, Pressable, StyleSheet, Text, View } from 'react-native' import { useNavigation, useRouter } from 'expo-router' import { useSafeAreaInsets } from 'react-native-safe-area-context' import { @@ -42,6 +34,7 @@ import { usePageHostSnapshot } from './use-page-host-snapshot' import { SHELL_OPENING_LABEL, ShellPageCover, ShellWaitingFrame } from './ShellWaitingFrame' import { pageSafeAreaInsets, usePublishedSafeAreaInsets } from './page-safe-area-insets' import { shellKeyboardGeometry } from './page-keyboard-inset' +import { hostOs } from '../platform/host-os' function failureMessage(reason: MobileWebShellFailureCause): string { switch (reason) { @@ -212,7 +205,7 @@ export function MobileWebShellScreen({ const { keyboardInset, viewShortenedBy } = shellKeyboardGeometry({ keyboardHeight: useKeyboardOcclusion(), bottomInset: insets.bottom, - platform: Platform.OS, + platform: hostOs(), pageReadsKeyboardInset }) const pageInsets = pageSafeAreaInsets({ diff --git a/mobile/src/mobile-web-shell/shell-view-keyboard-accessory.test.ts b/mobile/src/mobile-web-shell/shell-view-keyboard-accessory.test.ts index 5785feeec465..d199166c6aa8 100644 --- a/mobile/src/mobile-web-shell/shell-view-keyboard-accessory.test.ts +++ b/mobile/src/mobile-web-shell/shell-view-keyboard-accessory.test.ts @@ -7,8 +7,8 @@ import { join } from 'node:path' * checkable here is that the view installs the fix, and the simulator proof measures its effect. * * iPhone 17 simulator, measured: WKWebView's form accessory bar (up, down, done) rides on the - * keyboard, and the keyboard event's height counts it, so the page's dock lifted 379 pt against - * native's 277 and stood 52 pt above the bar. + * keyboard, and the keyboard event's height counts it, so the page's terminal lifted 376 pt against + * native's 274 and its dock stood 52 pt above the bar. */ const SHELL = join(import.meta.dirname, '..', '..', 'modules', 'orca-mobile-web-shell', 'ios') diff --git a/mobile/src/platform/host-os.ts b/mobile/src/platform/host-os.ts new file mode 100644 index 000000000000..da58fbe0d1ec --- /dev/null +++ b/mobile/src/platform/host-os.ts @@ -0,0 +1,8 @@ +import { Platform } from 'react-native' + +/** The OS a screen's keyboard and inset arithmetic is for. Natively, the one it runs on. */ +export type HostOs = 'ios' | 'android' | 'windows' | 'macos' | 'web' + +export function hostOs(): HostOs { + return Platform.OS +} diff --git a/mobile/src/platform/host-os.web.test.ts b/mobile/src/platform/host-os.web.test.ts new file mode 100644 index 000000000000..82eac2bf5602 --- /dev/null +++ b/mobile/src/platform/host-os.web.test.ts @@ -0,0 +1,31 @@ +// @vitest-environment happy-dom +import { afterEach, describe, expect, it } from 'vitest' +import { hostOs } from './host-os.web' + +function agent(userAgent: string, platform = '', maxTouchPoints = 0) { + Object.defineProperty(navigator, 'userAgent', { value: userAgent, configurable: true }) + Object.defineProperty(navigator, 'platform', { value: platform, configurable: true }) + Object.defineProperty(navigator, 'maxTouchPoints', { value: maxTouchPoints, configurable: true }) +} + +afterEach(() => agent('')) + +describe("the page's host OS", () => { + it('reads the phone off the WebView user agent', () => { + agent( + 'Mozilla/5.0 (iPhone; CPU iPhone OS 26_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148' + ) + expect(hostOs()).toBe('ios') + agent( + 'Mozilla/5.0 (Linux; Android 17; sdk_gphone64_arm64 Build/CP1A; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/144.0 Mobile Safari/537.36' + ) + expect(hostOs()).toBe('android') + }) + + it('takes an iPad, which reports a Mac, by its touch points', () => { + agent('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15', 'MacIntel', 5) + expect(hostOs()).toBe('ios') + agent('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15', 'MacIntel', 0) + expect(hostOs()).toBe('web') + }) +}) diff --git a/mobile/src/platform/host-os.web.ts b/mobile/src/platform/host-os.web.ts new file mode 100644 index 000000000000..755cf3a2ace1 --- /dev/null +++ b/mobile/src/platform/host-os.web.ts @@ -0,0 +1,19 @@ +import type { HostOs } from './host-os' + +export type { HostOs } from './host-os' + +/** + * Web sibling: `Platform.OS` is `web` inside the shell's page, but the keyboard it lifts over is the + * phone's, whose height the shell reports in that OS's own terms. So the page answers the phone's + * OS from the WebView's user agent. iPadOS reports a Mac, which only its touch points give away. + */ +export function hostOs(): HostOs { + const agent = globalThis.navigator?.userAgent ?? '' + if (/iP(ad|hone|od)/.test(agent)) { + return 'ios' + } + if (globalThis.navigator?.platform === 'MacIntel' && globalThis.navigator.maxTouchPoints > 1) { + return 'ios' + } + return agent.includes('Android') ? 'android' : 'web' +} diff --git a/mobile/src/platform/keyboard-geometry-host-os-census.test.ts b/mobile/src/platform/keyboard-geometry-host-os-census.test.ts new file mode 100644 index 000000000000..077dad192de2 --- /dev/null +++ b/mobile/src/platform/keyboard-geometry-host-os-census.test.ts @@ -0,0 +1,55 @@ +/** + * Keyboard and inset arithmetic branches on the host OS, never on `Platform.OS`. + * + * The page runs as `web` while the keyboard it lifts over is the phone's, reported in that OS's own + * terms (iOS counts the home indicator). A `Platform.OS === 'ios'` there takes the Android branch on + * an iPhone page: measured on the iPhone 17 simulator, the terminal lifted 34 pt past native. + */ +import { readFileSync } from 'node:fs' +import { relative } from 'node:path' +import { fileURLToPath } from 'node:url' +import { describe, expect, it } from 'vitest' +import { censusSourceFiles } from '../test-support/census-source-files' + +const MOBILE_DIR = fileURLToPath(new URL('../../', import.meta.url)) +const GEOMETRY = + /keyboardHeight|keyboardLift|keyboardInset|bottomInset|insets\.bottom|KeyboardAvoidingView|keyboard(Will|Did)(Show|Hide)/ + +/** Lines reading `Platform.OS` within two lines of keyboard or inset arithmetic. */ +export function platformReadsInGeometry(source: string): number[] { + const lines = source.split('\n') + return lines.flatMap((line, index) => + line.includes('Platform.OS') && + lines.slice(Math.max(0, index - 2), index + 3).some((near) => GEOMETRY.test(near)) + ? [index + 1] + : [] + ) +} + +function files(): string[] { + return ['src', 'app'].flatMap((dir) => + censusSourceFiles(fileURLToPath(new URL(`../../${dir}/`, import.meta.url))).filter( + (file) => /\.tsx?$/.test(file) && !/\.test\.tsx?$/.test(file) && !file.endsWith('host-os.ts') + ) + ) +} + +describe('keyboard and inset arithmetic', () => { + it('finds the reads it is looking for', () => { + expect( + platformReadsInGeometry("const lift = Platform.OS === 'ios' ? keyboardHeight - 1 : 0") + ).toEqual([1]) + expect( + platformReadsInGeometry("keyboardType={Platform.OS === 'ios' ? 'url' : 'default'}") + ).toEqual([]) + }) + + it('reads the host OS, never Platform.OS', () => { + const offenders = files().flatMap((file) => + platformReadsInGeometry(readFileSync(file, 'utf8')).map( + (line) => `${relative(MOBILE_DIR, file)}:${line}` + ) + ) + expect(offenders).toEqual([]) + }) +}) diff --git a/mobile/src/platform/keyboard-occlusion.ts b/mobile/src/platform/keyboard-occlusion.ts index 60ec14f015af..aa952871d984 100644 --- a/mobile/src/platform/keyboard-occlusion.ts +++ b/mobile/src/platform/keyboard-occlusion.ts @@ -1,5 +1,6 @@ import { useEffect, useState } from 'react' -import { Keyboard, Platform } from 'react-native' +import { Keyboard } from 'react-native' +import { hostOs } from './host-os' /** How much of the bottom of the layout viewport it covers, and whether it is open at all. */ export type SoftKeyboardState = { readonly height: number; readonly visible: boolean } @@ -44,8 +45,8 @@ export function subscribeSoftKeyboard( onShow: (height: number, duration: number) => void, onHide: (duration: number) => void ): () => void { - const showEvent = Platform.OS === 'ios' ? 'keyboardWillShow' : 'keyboardDidShow' - const hideEvent = Platform.OS === 'ios' ? 'keyboardWillHide' : 'keyboardDidHide' + const showEvent = hostOs() === 'ios' ? 'keyboardWillShow' : 'keyboardDidShow' + const hideEvent = hostOs() === 'ios' ? 'keyboardWillHide' : 'keyboardDidHide' const show = Keyboard.addListener(showEvent, (event) => onShow(event.endCoordinates.height, event.duration) ) diff --git a/mobile/src/session/use-mobile-session-presentation.ts b/mobile/src/session/use-mobile-session-presentation.ts index 2bea9158db08..221d26594e6a 100644 --- a/mobile/src/session/use-mobile-session-presentation.ts +++ b/mobile/src/session/use-mobile-session-presentation.ts @@ -1,9 +1,9 @@ -import { Platform } from 'react-native' import { classifyConnection, verdictDisplayLabel } from '../transport/connection-health' import { computeActiveTerminalKeyboardLift } from '../terminal/terminal-keyboard-avoidance-lift' import { useInitialSessionTerminalAutoCreate } from './use-initial-session-terminal-autocreate' import { MOBILE_SESSION_STATUS_LABELS } from './mobile-session-route-helpers' import type { MobileSessionBulkCloseModel } from './use-mobile-session-bulk-close' +import { hostOs } from '../platform/host-os' export function useMobileSessionPresentation(scope: MobileSessionBulkCloseModel) { const { @@ -77,7 +77,7 @@ export function useMobileSessionPresentation(scope: MobileSessionBulkCloseModel) // Why: iOS keyboard height includes the home-indicator inset; Android IME height does not. const keyboardLift = keyboardHeight > 0 - ? Platform.OS === 'ios' + ? hostOs() === 'ios' ? Math.max(0, keyboardHeight - insets.bottom) : keyboardHeight : 0 diff --git a/mobile/web-entry/web-overrides.json b/mobile/web-entry/web-overrides.json index 1dfeb4ed9dee..aa296ebc606d 100644 --- a/mobile/web-entry/web-overrides.json +++ b/mobile/web-entry/web-overrides.json @@ -29,6 +29,10 @@ "file": "src/transport/host-device-token-store.web.ts", "reason": "expo-secure-store resolves to {} on web, and the bridge carries the RPC, so the page holds no device token." }, + { + "file": "src/platform/host-os.web.ts", + "reason": "Platform.OS is web inside the shell's page, but the keyboard the page lifts over is the phone's, reported in that OS's own terms: iOS counts the home indicator. Keyboard and inset arithmetic branches on the host OS, so this answers the phone's OS from the WebView's user agent, and the page computes what the native screen computes." + }, { "file": "app/_layout.web.tsx", "reason": "The page's route tree starts at app/h, so without a root layout expo-router mounts DefaultNavigator, an all-edges SafeAreaView that would pad every screen a second time. The native root owns pairing and push and cannot reach the page. This one adds no padding and feeds the insets the shell sent in init to react-native-safe-area-context, whose web provider reads env(safe-area-inset-*) as 0 in both WebViews." From b8f792c68761d7f7497260e6786363d400827b58 Mon Sep 17 00:00:00 2001 From: Jinwoo-H Date: Sat, 26 Sep 2026 01:23:10 -0400 Subject: [PATCH 16/22] fix(mobile): the iOS WebView no longer scrolls the page to reveal a focused field WKWebView scrolled the document on keyboard frame changes on top of the page's own lift (commit bar 384 pt above the keyboard, shot ios-43). The shell removes the web view's keyboard observers; the page lifts from the height the shell sends. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb --- .../ios/MobileWebShellKeyboardAccessory.swift | 16 ++++++++++++++++ .../ios/MobileWebShellView.swift | 1 + .../shell-view-keyboard-accessory.test.ts | 9 +++++++++ 3 files changed, 26 insertions(+) diff --git a/mobile/modules/orca-mobile-web-shell/ios/MobileWebShellKeyboardAccessory.swift b/mobile/modules/orca-mobile-web-shell/ios/MobileWebShellKeyboardAccessory.swift index 07b5e9620f7c..43de70947b0a 100644 --- a/mobile/modules/orca-mobile-web-shell/ios/MobileWebShellKeyboardAccessory.swift +++ b/mobile/modules/orca-mobile-web-shell/ios/MobileWebShellKeyboardAccessory.swift @@ -32,3 +32,19 @@ func hideKeyboardAccessoryBar(of webView: WKWebView) { } object_setClass(content, subclass) } + +/// Stops WKWebView reacting to the keyboard itself. It listens for the keyboard's frame and scrolls +/// the document to reveal the focused field, on top of the lift the page already applies from the +/// height the shell sends, so the page moved twice. The shell's own listeners are unaffected. +func ignoreKeyboardNotifications(in webView: WKWebView) { + for name in [ + UIResponder.keyboardWillShowNotification, + UIResponder.keyboardDidShowNotification, + UIResponder.keyboardWillHideNotification, + UIResponder.keyboardDidHideNotification, + UIResponder.keyboardWillChangeFrameNotification, + UIResponder.keyboardDidChangeFrameNotification + ] { + NotificationCenter.default.removeObserver(webView, name: name, object: nil) + } +} diff --git a/mobile/modules/orca-mobile-web-shell/ios/MobileWebShellView.swift b/mobile/modules/orca-mobile-web-shell/ios/MobileWebShellView.swift index 7fd75fc7f840..abf9e7a70ede 100644 --- a/mobile/modules/orca-mobile-web-shell/ios/MobileWebShellView.swift +++ b/mobile/modules/orca-mobile-web-shell/ios/MobileWebShellView.swift @@ -222,6 +222,7 @@ final class OrcaMobileWebShellView: ExpoView, WKNavigationDelegate, WKUIDelegate webView.scrollView.backgroundColor = .clear webView.scrollView.contentInsetAdjustmentBehavior = .never hideKeyboardAccessoryBar(of: webView) + ignoreKeyboardNotifications(in: webView) webView.translatesAutoresizingMaskIntoConstraints = false addSubview(webView) NSLayoutConstraint.activate([ diff --git a/mobile/src/mobile-web-shell/shell-view-keyboard-accessory.test.ts b/mobile/src/mobile-web-shell/shell-view-keyboard-accessory.test.ts index d199166c6aa8..56e542fd40a0 100644 --- a/mobile/src/mobile-web-shell/shell-view-keyboard-accessory.test.ts +++ b/mobile/src/mobile-web-shell/shell-view-keyboard-accessory.test.ts @@ -19,4 +19,13 @@ describe("the iOS WebView's keyboard", () => { const accessory = readFileSync(join(SHELL, 'MobileWebShellKeyboardAccessory.swift'), 'utf8') expect(accessory).toContain('inputAccessoryView') }) + + it('does not scroll the page to reveal a focused field, which the page lifts itself', () => { + // iPhone 17 simulator: focusing the page's commit message scrolled the whole document up, the + // header off screen and the bar 384 pt above the keyboard (shot ios-43). + const view = readFileSync(join(SHELL, 'MobileWebShellView.swift'), 'utf8') + expect(view).toContain('ignoreKeyboardNotifications(in: webView)') + const accessory = readFileSync(join(SHELL, 'MobileWebShellKeyboardAccessory.swift'), 'utf8') + expect(accessory).toContain('keyboardWillChangeFrameNotification') + }) }) From 521fd7f89512ecb9b04e407f43ec71a7fdcd38c9 Mon Sep 17 00:00:00 2001 From: Jinwoo-H Date: Sat, 26 Sep 2026 01:57:03 -0400 Subject: [PATCH 17/22] fix(mobile): the live input's keyboard reopen and the dock's keyboard props read the host OS On the Android page Platform.OS is web, so the reopen flag was false: after Back closed the IME the input stayed focused and a later focus() did nothing. The census now flags any Platform.OS read in a file that reads the keyboard, imports a keyboard/inset module or is named for one, beside the proximity rule. The host-OS test covers an iPad user agent. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb --- mobile/src/platform/host-os.web.test.ts | 7 ++++++ .../keyboard-geometry-host-os-census.test.ts | 22 +++++++++++++++---- .../src/session/MobileSessionCommandDock.tsx | 9 ++++---- .../mobile-session-route-parity.test.ts | 11 +++++----- .../use-mobile-session-terminal-runtime.ts | 5 +++-- ...erminal-live-input-keyboard-reopen.test.ts | 17 ++++++++++++++ .../terminal-live-input-keyboard-reopen.ts | 6 +++++ 7 files changed, 62 insertions(+), 15 deletions(-) create mode 100644 mobile/src/terminal/terminal-live-input-keyboard-reopen.test.ts create mode 100644 mobile/src/terminal/terminal-live-input-keyboard-reopen.ts diff --git a/mobile/src/platform/host-os.web.test.ts b/mobile/src/platform/host-os.web.test.ts index 82eac2bf5602..fcc3d446f36b 100644 --- a/mobile/src/platform/host-os.web.test.ts +++ b/mobile/src/platform/host-os.web.test.ts @@ -22,6 +22,13 @@ describe("the page's host OS", () => { expect(hostOs()).toBe('android') }) + it('reads an iPad that still names itself in the user agent', () => { + agent( + 'Mozilla/5.0 (iPad; CPU OS 18_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148' + ) + expect(hostOs()).toBe('ios') + }) + it('takes an iPad, which reports a Mac, by its touch points', () => { agent('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15', 'MacIntel', 5) expect(hostOs()).toBe('ios') diff --git a/mobile/src/platform/keyboard-geometry-host-os-census.test.ts b/mobile/src/platform/keyboard-geometry-host-os-census.test.ts index 077dad192de2..81b7259395dc 100644 --- a/mobile/src/platform/keyboard-geometry-host-os-census.test.ts +++ b/mobile/src/platform/keyboard-geometry-host-os-census.test.ts @@ -15,12 +15,26 @@ const MOBILE_DIR = fileURLToPath(new URL('../../', import.meta.url)) const GEOMETRY = /keyboardHeight|keyboardLift|keyboardInset|bottomInset|insets\.bottom|KeyboardAvoidingView|keyboard(Will|Did)(Show|Hide)/ -/** Lines reading `Platform.OS` within two lines of keyboard or inset arithmetic. */ -export function platformReadsInGeometry(source: string): number[] { +const KEYBOARD_READ = + /keyboardHeight|keyboardLift|keyboardInset|useKeyboardOcclusion|useSoftKeyboard/ +const KEYBOARD_IMPORT = /from '[^']*(keyboard|inset)[^']*'/i +const KEYBOARD_FILE = /(keyboard|inset|drawer|lift)[^/]*$/i +const COMMENT = /^\s*(\/\/|\*|\/\*)/ + +/** + * `Platform.OS` reads near keyboard or inset arithmetic, or anywhere in a file that reads the keyboard, + * imports a keyboard/inset module or is named for one: a live-input reopen flag four lines from its + * keyboard height escaped the proximity rule alone. Comments are not reads. + */ +export function platformReadsInGeometry(source: string, file = ''): number[] { const lines = source.split('\n') + const wholeFile = + KEYBOARD_READ.test(source) || KEYBOARD_IMPORT.test(source) || KEYBOARD_FILE.test(file) return lines.flatMap((line, index) => line.includes('Platform.OS') && - lines.slice(Math.max(0, index - 2), index + 3).some((near) => GEOMETRY.test(near)) + !COMMENT.test(line) && + (wholeFile || + lines.slice(Math.max(0, index - 2), index + 3).some((near) => GEOMETRY.test(near))) ? [index + 1] : [] ) @@ -46,7 +60,7 @@ describe('keyboard and inset arithmetic', () => { it('reads the host OS, never Platform.OS', () => { const offenders = files().flatMap((file) => - platformReadsInGeometry(readFileSync(file, 'utf8')).map( + platformReadsInGeometry(readFileSync(file, 'utf8'), file).map( (line) => `${relative(MOBILE_DIR, file)}:${line}` ) ) diff --git a/mobile/src/session/MobileSessionCommandDock.tsx b/mobile/src/session/MobileSessionCommandDock.tsx index 3ee0ece152a1..87b46246572f 100644 --- a/mobile/src/session/MobileSessionCommandDock.tsx +++ b/mobile/src/session/MobileSessionCommandDock.tsx @@ -1,4 +1,5 @@ -import { View, Text, ScrollView, TextInput, Pressable, Platform } from 'react-native' +import { View, Text, ScrollView, TextInput, Pressable } from 'react-native' +import { hostOs } from '../platform/host-os' import { ArrowUp, ChevronDown, @@ -305,7 +306,7 @@ export function MobileSessionCommandDock({ controller }: { controller: MobileSes smartInsertDelete={false} // Why: iOS textContentType overrides autoComplete and can narrow the keyboard; keep IME switching available. autoComplete="off" - keyboardType={getTerminalLiveInputKeyboardType(Platform.OS)} + keyboardType={getTerminalLiveInputKeyboardType(hostOs())} returnKeyType="default" blurOnSubmit={false} editable={canSend} @@ -318,7 +319,7 @@ export function MobileSessionCommandDock({ controller }: { controller: MobileSes ref={bindCommandField} // Why: Android caches IME inputType at mount, so toggling autocomplete must remount there; iOS updates in place. key={ - Platform.OS === 'android' + hostOs() === 'android' ? autocompleteEnabled ? 'cmd-input-ac-on' : 'cmd-input-ac-off' @@ -336,7 +337,7 @@ export function MobileSessionCommandDock({ controller }: { controller: MobileSes smartInsertDelete={false} // Why: not autofill content, but keyboard must stay default so non-Latin IMEs remain selectable. autoComplete="off" - keyboardType={getTerminalCommandKeyboardType(Platform.OS, autocompleteEnabled)} + keyboardType={getTerminalCommandKeyboardType(hostOs(), autocompleteEnabled)} returnKeyType="send" blurOnSubmit={false} // Why: composing is local — an outage must not lock the field or discard typed text (#6713). diff --git a/mobile/src/session/mobile-session-route-parity.test.ts b/mobile/src/session/mobile-session-route-parity.test.ts index d52f950d5ec3..193fa04c0320 100644 --- a/mobile/src/session/mobile-session-route-parity.test.ts +++ b/mobile/src/session/mobile-session-route-parity.test.ts @@ -173,11 +173,12 @@ const HEAD_TIMER_CLEANUP_SHA256 = 'c73f1d1c2cc89642f3d727d6f3b6b81860a9d6f342345 // frame reported either way, and its window is its frame, so both measure paths agree there. // 531 -> 533, and the host-JSX hash: the tab bar and the accessory bar take a ref that gives the // page `keyboardShouldPersistTaps` ('handled', 'always'), which react-native-web ignores. Natively -// the ref is undefined. +// the ref is undefined. 533 -> 532: the live input's reopen flag reads the host OS, not an 'android' literal. const HEAD_RUNTIME_STRING_SHA256 = - '110e263e0c43e5200c35a30f67769d4545e39019c7936d03e22a920e90e5d62d' -// Moved by both of the dock's fields: their refs, and the live one's submit handler, are the seam's now. -const HEAD_HOST_JSX_SHA256 = '3a1c72c513a000b677ae7ba09e58db1b5ccc99345e41addcf075f111f455b841' + 'e70e112260bdbbc620a6b9b39da2824d33b7c4921b51bc601a3ad3ca2fe194ba' +// Moved by both of the dock's fields: their refs, and the live one's submit handler, are the seam's now; +// their keyboard type and remount key read the host OS. +const HEAD_HOST_JSX_SHA256 = '06163ee4cb4aa7ef84250e9c1873a4f0beab91a0d21212d28e586e133789961b' const HEAD_LEAF_JSX_SHA256 = 'c7e1a4b90197697f1eaa640c38da63281b4f7b84fb036ae2152f00c2f7d7cb77' const HEAD_STYLE_REFERENCE_SHA256 = '295a3501c2c6d7bea7c8bbf38b3f3534f01344cd7e1b91bb8e07c040821d596a' @@ -614,7 +615,7 @@ describe('mobile session route extraction parity', () => { it('preserves runtime strings, styles, and the expanded JSX tree', () => { const strings = readRuntimeStrings() - expect(strings).toHaveLength(533) + expect(strings).toHaveLength(532) expect(hash(strings)).toBe(HEAD_RUNTIME_STRING_SHA256) const jsx = readJsxFacts(readDefinitions()) expect(jsx.host).toHaveLength(124) diff --git a/mobile/src/session/use-mobile-session-terminal-runtime.ts b/mobile/src/session/use-mobile-session-terminal-runtime.ts index 5e4196e15007..1e24ec01be02 100644 --- a/mobile/src/session/use-mobile-session-terminal-runtime.ts +++ b/mobile/src/session/use-mobile-session-terminal-runtime.ts @@ -1,10 +1,11 @@ import { useState, useRef, useCallback } from 'react' -import { Platform, type Keyboard, type TextInput } from 'react-native' +import type { Keyboard, TextInput } from 'react-native' import { useFocusEffect } from 'expo-router' import type { RpcClient } from '../transport/rpc-client' import type { ConnectionState } from '../transport/types' import type { TerminalModes, TerminalWebViewHandle } from '../terminal/terminal-webview-contract' import { useTerminalLiveInputFocus } from '../terminal/use-terminal-live-input-focus' +import { reopensFocusedInputWhenKeyboardHidden } from '../terminal/terminal-live-input-keyboard-reopen' import type { TerminalLiveInputSender } from '../terminal/terminal-live-input-sender' import { useTerminalLiveInputCommit } from '../terminal/use-terminal-live-input-commit' import { resolveMobileTerminalInputGate } from '../terminal/terminal-input-connection-gate' @@ -144,7 +145,7 @@ export function useMobileSessionTerminalRuntime(scope: MobileSessionScreenStateM lifecycleIdentity: client, lifecycleKey: JSON.stringify([hostId, worktreeId, connState]), liveInputEnabled, - reopenFocusedInputWhenKeyboardHidden: Platform.OS === 'android', + reopenFocusedInputWhenKeyboardHidden: reopensFocusedInputWhenKeyboardHidden(), timerRef: liveInputFocusTimerRef }) useFocusEffect( diff --git a/mobile/src/terminal/terminal-live-input-keyboard-reopen.test.ts b/mobile/src/terminal/terminal-live-input-keyboard-reopen.test.ts new file mode 100644 index 000000000000..c70880c1642d --- /dev/null +++ b/mobile/src/terminal/terminal-live-input-keyboard-reopen.test.ts @@ -0,0 +1,17 @@ +import { describe, expect, it, vi } from 'vitest' + +const host = vi.hoisted(() => ({ os: 'android' })) +vi.mock('react-native', () => ({ Platform: { OS: 'web' } })) +vi.mock('../platform/host-os', () => ({ hostOs: () => host.os })) + +const { reopensFocusedInputWhenKeyboardHidden } = + await import('./terminal-live-input-keyboard-reopen') + +describe('reopening a focused live input whose keyboard is hidden', () => { + it("follows the phone's OS on the page, which runs as web", () => { + host.os = 'android' + expect(reopensFocusedInputWhenKeyboardHidden()).toBe(true) + host.os = 'ios' + expect(reopensFocusedInputWhenKeyboardHidden()).toBe(false) + }) +}) diff --git a/mobile/src/terminal/terminal-live-input-keyboard-reopen.ts b/mobile/src/terminal/terminal-live-input-keyboard-reopen.ts new file mode 100644 index 000000000000..4fc6cf57e1ac --- /dev/null +++ b/mobile/src/terminal/terminal-live-input-keyboard-reopen.ts @@ -0,0 +1,6 @@ +import { hostOs } from '../platform/host-os' + +/** Android keeps a hidden TextInput focused after Back closes the IME, so focus must blur first. */ +export function reopensFocusedInputWhenKeyboardHidden(): boolean { + return hostOs() === 'android' +} From 13bba064f57c6aebc3fba5f148465ac46148b094 Mon Sep 17 00:00:00 2001 From: Jinwoo-H Date: Sun, 27 Sep 2026 18:41:14 -0400 Subject: [PATCH 18/22] refactor(mobile): the shell never resizes the WebView for the keyboard No served page lacks the keyboard height, so the negotiation and the shortened view for one go: the keyboard-inset accept, pageReadsKeyboardInset, viewShortenedBy, softwareKeyboardWindowInset and shellKeyboardGeometry. The shell publishes the height and the keyboard covers the view. A census in the shell names the retired symbols and flags any view sized from the keyboard. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb --- ...d-bottom-drawer-page-keyboard.web.test.tsx | 12 ----- .../MobileWebShellScreen.test.tsx | 10 ++-- .../mobile-web-shell/MobileWebShellScreen.tsx | 26 +++------- .../src/mobile-web-shell/bridge-host-route.ts | 9 ++-- .../bridge/bridge-client-init-handshake.ts | 13 ++--- .../bridge/bridge-client-session.ts | 3 +- .../bridge/bridge-keyboard-inset.test.ts | 6 --- .../bridge/bridge-keyboard-inset.ts | 6 --- .../bridge/bridge-rpc-client-frames.test.ts | 8 +-- ...web-shell-keyboard-overlay-screen.test.tsx | 48 ++--------------- .../mobile-web-shell-keyboard-state.test.ts | 33 ------------ ...mobile-web-shell-safe-area-screen.test.tsx | 51 ++++--------------- .../mobile-web-shell-screen-test-harness.tsx | 6 +-- .../mobile-web-shell-screen-test-mocks.tsx | 3 +- .../mobile-web-shell-session-contract.ts | 3 -- .../mobile-web-shell-session.ts | 1 - .../mobile-web-shell/page-document-state.ts | 14 +---- .../mobile-web-shell/page-keyboard-inset.ts | 18 ------- .../page-safe-area-insets.test.ts | 18 +------ .../mobile-web-shell/page-safe-area-insets.ts | 10 ++-- .../shell-keyboard-covers-view-census.test.ts | 48 +++++++++++++++++ .../use-mobile-web-shell-session.ts | 10 +--- .../software-keyboard-window-inset.test.ts | 39 -------------- .../software-keyboard-window-inset.ts | 17 ------- ...use-mobile-session-keyboard-state.test.tsx | 8 +-- .../terminal/terminal-viewport-refit.test.ts | 4 +- mobile/web-entry/index.tsx | 3 +- 27 files changed, 103 insertions(+), 324 deletions(-) delete mode 100644 mobile/src/mobile-web-shell/mobile-web-shell-keyboard-state.test.ts delete mode 100644 mobile/src/mobile-web-shell/page-keyboard-inset.ts create mode 100644 mobile/src/mobile-web-shell/shell-keyboard-covers-view-census.test.ts delete mode 100644 mobile/src/platform/software-keyboard-window-inset.test.ts delete mode 100644 mobile/src/platform/software-keyboard-window-inset.ts diff --git a/mobile/src/components/mounted-bottom-drawer-page-keyboard.web.test.tsx b/mobile/src/components/mounted-bottom-drawer-page-keyboard.web.test.tsx index 8cb7734ed5aa..d7d0c67a0cbb 100644 --- a/mobile/src/components/mounted-bottom-drawer-page-keyboard.web.test.tsx +++ b/mobile/src/components/mounted-bottom-drawer-page-keyboard.web.test.tsx @@ -139,16 +139,4 @@ describe('a fill-mode sheet on the page', () => { publishShellKeyboardSource(null) } }) - - it('does not lift over a keyboard an older shell shortened the WebView for', () => { - setWindowHeight(RESTING_HEIGHT) - const renderer = renderFillSheet() - act(() => setWindowHeight(RESTING_HEIGHT - IME_HEIGHT)) - // The shortened window is the whole avoidance: the sheet's height follows it and nothing lifts. - expect(sheetStyle(renderer)).toMatchObject({ - marginBottom: 0, - height: RESTING_HEIGHT - IME_HEIGHT - 24 - 16 - }) - act(() => renderer.unmount()) - }) }) diff --git a/mobile/src/mobile-web-shell/MobileWebShellScreen.test.tsx b/mobile/src/mobile-web-shell/MobileWebShellScreen.test.tsx index b41c67a2d710..57caf340c4e9 100644 --- a/mobile/src/mobile-web-shell/MobileWebShellScreen.test.tsx +++ b/mobile/src/mobile-web-shell/MobileWebShellScreen.test.tsx @@ -673,7 +673,7 @@ describe('what one case mutates does not reach the next', () => { await act(async () => { dependencies.keyboardListeners.get('keyboardWillShow')?.({ endCoordinates: { height: 336 } }) }) - expect(root.props.style[1]).toEqual({ paddingTop: 44, paddingBottom: 336 }) + expect(root.props.style[1]).toEqual({ paddingTop: 44, paddingBottom: 8 }) await act(async () => { dependencies.keyboardListeners.get('keyboardWillHide')?.({ endCoordinates: { height: 0 } }) @@ -718,17 +718,17 @@ describe('the frame under a page that has not painted', () => { expect(tree.root.findAll((node) => node.props.testID === 'mobile-web-shell-cover')).toEqual([]) }) - it('covers the same box the view gets, which is what the keyboard strip shortens', async () => { + it('covers the same box the view gets, which the keyboard does not shorten', async () => { // Both are children of the padded root: the view is `flex: 1` and the cover is an absolute - // fill, so Yoga lays each of them out against the same content box. The keyboard takes its - // strip off that box, so it takes it off both, and the cover cannot leave a gap the view fills. + // fill, so Yoga lays each of them out against the same content box, and the cover cannot leave + // a gap the view fills. The keyboard covers that box rather than taking a strip off it. dependencies.pageFrame = 'unpainted' const tree = await renderScreen(readyState('session-keyboard-cover')) const root = tree.root.find((node) => node.props.testID === 'mobile-web-shell-ready') await act(async () => { dependencies.keyboardListeners.get('keyboardWillShow')?.({ endCoordinates: { height: 336 } }) }) - expect(root.props.style[1]).toEqual({ paddingTop: 44, paddingBottom: 336 }) + expect(root.props.style[1]).toEqual({ paddingTop: 44, paddingBottom: 8 }) const cover = tree.root.find((node) => node.props.testID === 'mobile-web-shell-cover') expect(cover.props.style[0]).toMatchObject({ position: 'absolute', diff --git a/mobile/src/mobile-web-shell/MobileWebShellScreen.tsx b/mobile/src/mobile-web-shell/MobileWebShellScreen.tsx index d3a2a5e15c58..9ec9744ed1f4 100644 --- a/mobile/src/mobile-web-shell/MobileWebShellScreen.tsx +++ b/mobile/src/mobile-web-shell/MobileWebShellScreen.tsx @@ -33,8 +33,6 @@ import { useMobileWebShellSession } from './use-mobile-web-shell-session' import { usePageHostSnapshot } from './use-page-host-snapshot' import { SHELL_OPENING_LABEL, ShellPageCover, ShellWaitingFrame } from './ShellWaitingFrame' import { pageSafeAreaInsets, usePublishedSafeAreaInsets } from './page-safe-area-insets' -import { shellKeyboardGeometry } from './page-keyboard-inset' -import { hostOs } from '../platform/host-os' function failureMessage(reason: MobileWebShellFailureCause): string { switch (reason) { @@ -191,8 +189,7 @@ export function MobileWebShellScreen({ pageReady, pageFrame, backClaimed, - pageOwnsSafeArea, - pageReadsKeyboardInset + pageOwnsSafeArea } = useMobileWebShellSession({ hostId, routePathname: route.pathname, runtime }) // Which mount the notice was dismissed on, not whether it was: a later refusal opens its own // generation under a new session id, so it is not silenced by a tap on the one before it. @@ -200,19 +197,10 @@ export function MobileWebShellScreen({ const noticeShown = updateNotice !== null && state.kind === 'ready' && noticeDismissedFor !== state.sessionId // The page cannot see the IME for itself: edge-to-edge makes `adjustResize` inert and the view's - // IME insets are zeroed, so `visualViewport` never shrinks. A page that reads the height from - // `init` is covered by the keyboard like a native screen; an older one gets a view ended above it. - const { keyboardInset, viewShortenedBy } = shellKeyboardGeometry({ - keyboardHeight: useKeyboardOcclusion(), - bottomInset: insets.bottom, - platform: hostOs(), - pageReadsKeyboardInset - }) - const pageInsets = pageSafeAreaInsets({ - insets, - viewShortenedBy, - topCovered: noticeShown - }) + // IME insets are zeroed, so `visualViewport` never shrinks. The keyboard covers the view like a + // native screen, and the page lifts by the height native screens read. + const keyboardInset = Math.max(0, useKeyboardOcclusion()) + const pageInsets = pageSafeAreaInsets({ insets, topCovered: noticeShown }) const { snapshot, unreadable, readStorage, refreshStorage, writeStorage } = usePageHostSnapshot( hostId, route.pathname @@ -374,8 +362,8 @@ export function MobileWebShellScreen({ // Edge-to-edge like a native screen, for a page that pads for the bars itself; an older page // keeps the strips. The banner takes the status bar strip when it shows. pageOwnsSafeArea - ? { paddingTop: noticeShown ? insets.top : 0, paddingBottom: viewShortenedBy } - : { paddingTop: insets.top, paddingBottom: Math.max(insets.bottom, viewShortenedBy) } + ? { paddingTop: noticeShown ? insets.top : 0 } + : { paddingTop: insets.top, paddingBottom: insets.bottom } ]} testID="mobile-web-shell-ready" > diff --git a/mobile/src/mobile-web-shell/bridge-host-route.ts b/mobile/src/mobile-web-shell/bridge-host-route.ts index 4467681aff91..c61a042b03bd 100644 --- a/mobile/src/mobile-web-shell/bridge-host-route.ts +++ b/mobile/src/mobile-web-shell/bridge-host-route.ts @@ -10,7 +10,6 @@ import { ZERO_SAFE_AREA_INSETS, type BridgeSafeAreaInsets } from './bridge/bridge-safe-area-insets' -import { BRIDGE_KEYBOARD_INSET_ACCEPT } from './bridge/bridge-keyboard-inset' /** The screen one host is serving, which is the one field of `init` that moves under a live page. */ export type BridgeHostRoute = { @@ -41,9 +40,9 @@ export type BridgeHostRoute = { * lane as a pane update: held either way, so the next `ready` carries them. */ readonly publishSafeAreaInsets: (next: BridgeSafeAreaInsets, deliverable: boolean) => void - /** The keyboard height the next `init` carries; 0 to a page that did not declare it reads one. */ + /** The keyboard height the next `init` carries. */ readonly keyboardInset: () => number - /** Moves the held keyboard height on the same lane as the insets, to a page that reads it. */ + /** Moves the held keyboard height on the same lane as the insets. */ readonly publishKeyboardInset: (next: number, deliverable: boolean) => void } @@ -105,13 +104,13 @@ export function createBridgeHostRoute(args: { args.sendInit() } }, - keyboardInset: () => (accepts.includes(BRIDGE_KEYBOARD_INSET_ACCEPT) ? keyboard : 0), + keyboardInset: () => keyboard, publishKeyboardInset: (next, deliverable) => { if (keyboard === next) { return } keyboard = next - if (deliverable && accepts.includes(BRIDGE_KEYBOARD_INSET_ACCEPT)) { + if (deliverable) { args.sendInit() } } diff --git a/mobile/src/mobile-web-shell/bridge/bridge-client-init-handshake.ts b/mobile/src/mobile-web-shell/bridge/bridge-client-init-handshake.ts index 7f7ee6e8d6dc..609016f033e4 100644 --- a/mobile/src/mobile-web-shell/bridge/bridge-client-init-handshake.ts +++ b/mobile/src/mobile-web-shell/bridge/bridge-client-init-handshake.ts @@ -3,7 +3,6 @@ import { BRIDGE_BACK_FRAME } from './bridge-page-back' import { BRIDGE_PAGE_PAINTED } from './bridge-page-painted' import { BRIDGE_ROUTE_UPDATE_ACCEPT } from './bridge-route-update' import { BRIDGE_SAFE_AREA_ACCEPT } from './bridge-safe-area-insets' -import { BRIDGE_KEYBOARD_INSET_ACCEPT } from './bridge-keyboard-inset' /** The page asks again until the shell answers; a session has no other way to start. */ export const BRIDGE_READY_RETRY_MIN_MS = 50 @@ -57,20 +56,14 @@ export function createBridgeInitHandshake(ask: () => void): BridgeInitHandshake /** * What the page says on every ask, because the shell reads it off whichever `ready` it answers. * `accepts` is what this page build can be sent: a second `init` for the session it holds, the - * Back frame, insets it pads for itself, and the keyboard height it lifts by. `reports` runs the - * other way: what a shell may wait for this page to post, and the shell holds a frame over the view - * until it arrives. + * Back frame, and insets it pads for itself. `reports` runs the other way: what a shell may wait + * for this page to post, and the shell holds a frame over the view until it arrives. */ export function createPageReadyFrame(): Extract { return { v: BRIDGE_PROTOCOL_VERSION, type: 'ready', - accepts: [ - BRIDGE_ROUTE_UPDATE_ACCEPT, - BRIDGE_BACK_FRAME, - BRIDGE_SAFE_AREA_ACCEPT, - BRIDGE_KEYBOARD_INSET_ACCEPT - ], + accepts: [BRIDGE_ROUTE_UPDATE_ACCEPT, BRIDGE_BACK_FRAME, BRIDGE_SAFE_AREA_ACCEPT], reports: [BRIDGE_PAGE_PAINTED] } } diff --git a/mobile/src/mobile-web-shell/bridge/bridge-client-session.ts b/mobile/src/mobile-web-shell/bridge/bridge-client-session.ts index ff989d8c0793..a8571918b897 100644 --- a/mobile/src/mobile-web-shell/bridge/bridge-client-session.ts +++ b/mobile/src/mobile-web-shell/bridge/bridge-client-session.ts @@ -27,8 +27,7 @@ export type BridgeShellSession = { /** How much of the WebView sits under a system bar. Zeros for a shell that reserves the bars * outside the view, which is every shell before the field. */ safeAreaInsets: BridgeSafeAreaInsets - /** The keyboard height native screens read on the shell's OS. 0 for a shell that shortens the - * view above it instead, which is every shell before the field. */ + /** The keyboard height native screens read on the shell's OS; 0 while it is closed. */ keyboardInset: number /** Null for a shell too old to name it; the page's own `loadHosts()` then answers with nothing. */ host: BridgeInitHost | null diff --git a/mobile/src/mobile-web-shell/bridge/bridge-keyboard-inset.test.ts b/mobile/src/mobile-web-shell/bridge/bridge-keyboard-inset.test.ts index 8105e21ebd6e..9cdf24ae99b2 100644 --- a/mobile/src/mobile-web-shell/bridge/bridge-keyboard-inset.test.ts +++ b/mobile/src/mobile-web-shell/bridge/bridge-keyboard-inset.test.ts @@ -3,8 +3,6 @@ import { createFakeBridgePortPair } from './bridge-port-pair-test-harness' import { readBridgeHostMessage } from './bridge-envelope' import { createBridgeInitFrame } from './bridge-init-frame' import { readShellSession } from './bridge-client-session' -import { BRIDGE_KEYBOARD_INSET_ACCEPT } from './bridge-keyboard-inset' -import { createPageReadyFrame } from './bridge-client-init-handshake' function initFrame(keyboardInset?: number) { return createBridgeInitFrame({ @@ -57,10 +55,6 @@ describe('keyboardInset on init', () => { expect(readBridgeHostMessage(JSON.stringify(frame)).ok, String(bad)).toBe(false) } }) - - it('is declared by this page build, so the shell overlays it rather than shortening it', () => { - expect(createPageReadyFrame().accepts).toContain(BRIDGE_KEYBOARD_INSET_ACCEPT) - }) }) describe('a keyboard that moves under a live page', () => { diff --git a/mobile/src/mobile-web-shell/bridge/bridge-keyboard-inset.ts b/mobile/src/mobile-web-shell/bridge/bridge-keyboard-inset.ts index 0299a74f637a..c11a642e8c24 100644 --- a/mobile/src/mobile-web-shell/bridge/bridge-keyboard-inset.ts +++ b/mobile/src/mobile-web-shell/bridge/bridge-keyboard-inset.ts @@ -7,9 +7,3 @@ import { BRIDGE_MAX_SAFE_AREA_INSET } from './bridge-safe-area-insets' * overlays the IME on the view like a native screen, and the page cannot measure it. */ export const BridgeKeyboardInsetSchema = z.number().finite().min(0).max(BRIDGE_MAX_SAFE_AREA_INSET) - -/** - * What a page puts in `ready.accepts` to say it reads the keyboard from `init`. The shell overlays - * the keyboard only on such a page; an older one cannot see it, so the shell shortens its view. - */ -export const BRIDGE_KEYBOARD_INSET_ACCEPT = 'keyboard-inset' diff --git a/mobile/src/mobile-web-shell/bridge/bridge-rpc-client-frames.test.ts b/mobile/src/mobile-web-shell/bridge/bridge-rpc-client-frames.test.ts index fcec59a53342..12886c1e27f1 100644 --- a/mobile/src/mobile-web-shell/bridge/bridge-rpc-client-frames.test.ts +++ b/mobile/src/mobile-web-shell/bridge/bridge-rpc-client-frames.test.ts @@ -16,7 +16,6 @@ import { BRIDGE_BACK_FRAME } from './bridge-page-back' import { BRIDGE_PAGE_PAINTED } from './bridge-page-painted' import { BRIDGE_ROUTE_UPDATE_ACCEPT } from './bridge-route-update' import { BRIDGE_SAFE_AREA_ACCEPT } from './bridge-safe-area-insets' -import { BRIDGE_KEYBOARD_INSET_ACCEPT } from './bridge-keyboard-inset' import { BRIDGE_READY_RETRY_MAX_MS, BRIDGE_READY_RETRY_MIN_MS @@ -50,12 +49,7 @@ describe('bridge client handshake', () => { { v: BRIDGE_PROTOCOL_VERSION, type: 'ready', - accepts: [ - BRIDGE_ROUTE_UPDATE_ACCEPT, - BRIDGE_BACK_FRAME, - BRIDGE_SAFE_AREA_ACCEPT, - BRIDGE_KEYBOARD_INSET_ACCEPT - ], + accepts: [BRIDGE_ROUTE_UPDATE_ACCEPT, BRIDGE_BACK_FRAME, BRIDGE_SAFE_AREA_ACCEPT], reports: [BRIDGE_PAGE_PAINTED] } ]) diff --git a/mobile/src/mobile-web-shell/mobile-web-shell-keyboard-overlay-screen.test.tsx b/mobile/src/mobile-web-shell/mobile-web-shell-keyboard-overlay-screen.test.tsx index 19acb4a681db..32ff38f30d49 100644 --- a/mobile/src/mobile-web-shell/mobile-web-shell-keyboard-overlay-screen.test.tsx +++ b/mobile/src/mobile-web-shell/mobile-web-shell-keyboard-overlay-screen.test.tsx @@ -31,7 +31,6 @@ import { renderScreen as mountScreen } from './mobile-web-shell-screen-test-harness' import { readBridgeHostMessage } from './bridge/bridge-envelope' -import { BRIDGE_KEYBOARD_INSET_ACCEPT } from './bridge/bridge-keyboard-inset' import { BRIDGE_ROUTE_UPDATE_ACCEPT } from './bridge/bridge-route-update' import { BRIDGE_SAFE_AREA_ACCEPT } from './bridge/bridge-safe-area-insets' import { MobileWebShellScreen } from './MobileWebShellScreen' @@ -50,25 +49,20 @@ beforeEach(() => { const WINDOW = { top: 44, right: 0, bottom: 8, left: 0 } /** - * A page that reads the keyboard from `init` is covered by it like a native screen: the view keeps - * its size, and the page is told the height on every keyboard event. + * The page is covered by the keyboard like a native screen: the view keeps its size, and the page + * is told the height on every keyboard event. */ describe('a page the keyboard covers', () => { async function openPage(sessionId: string) { dependencies.client = createFakeRpcClient() dependencies.pageOwnsSafeArea = true - dependencies.pageReadsKeyboardInset = true const tree = await renderScreen(readyState(sessionId)) await act(async () => { byName(tree, 'ShellViewProbe')[0]?.props.onBridgeMessage({ nativeEvent: { json: clientFrame({ type: 'ready', - accepts: [ - BRIDGE_ROUTE_UPDATE_ACCEPT, - BRIDGE_SAFE_AREA_ACCEPT, - BRIDGE_KEYBOARD_INSET_ACCEPT - ] + accepts: [BRIDGE_ROUTE_UPDATE_ACCEPT, BRIDGE_SAFE_AREA_ACCEPT] }) } }) @@ -106,7 +100,7 @@ describe('a page the keyboard covers', () => { // a keyboard that changes height while open leaves no gap above it. for (const height of [312, 346, 0]) { await page.keyboard(height) - expect(page.root().props.style[1]).toEqual({ paddingTop: 0, paddingBottom: 0 }) + expect(page.root().props.style[1]).toEqual({ paddingTop: 0 }) } // The keyboard's own height as native screens read it on this OS, home indicator included on // iOS; the page's arithmetic branches on the shell's OS, as native does. The bottom inset @@ -119,38 +113,4 @@ describe('a page the keyboard covers', () => { ]) }) } - - it('still shortens the view for an older page that cannot read the keyboard', async () => { - dependencies.platform = 'android' - dependencies.client = createFakeRpcClient() - dependencies.pageOwnsSafeArea = true - const tree = await renderScreen(readyState('session-older-keyboard')) - const ready = async () => { - await act(async () => { - byName(tree, 'ShellViewProbe')[0]?.props.onBridgeMessage({ - nativeEvent: { - json: clientFrame({ - type: 'ready', - accepts: [BRIDGE_ROUTE_UPDATE_ACCEPT, BRIDGE_SAFE_AREA_ACCEPT] - }) - } - }) - }) - } - await ready() - await act(async () => { - dependencies.keyboardListeners.get('keyboardDidShow')?.({ endCoordinates: { height: 336 } }) - }) - const root = tree.root.find((node) => node.props.testID === 'mobile-web-shell-ready') - expect(root.props.style[1]).toEqual({ paddingTop: 0, paddingBottom: 344 }) - // The page re-asks, as one does after a refused frame: the answer still carries no keyboard. - await ready() - const inits = dependencies.posted.flatMap((json) => { - const read = readBridgeHostMessage(json) - return read.ok && read.message.type === 'init' ? [read.message] : [] - }) - // The first `init`, the insets move and the re-ask; the keyboard itself sends nothing here. - expect(inits).toHaveLength(3) - expect(inits.filter((init) => 'keyboardInset' in init)).toEqual([]) - }) }) diff --git a/mobile/src/mobile-web-shell/mobile-web-shell-keyboard-state.test.ts b/mobile/src/mobile-web-shell/mobile-web-shell-keyboard-state.test.ts deleted file mode 100644 index 2336ec77c73c..000000000000 --- a/mobile/src/mobile-web-shell/mobile-web-shell-keyboard-state.test.ts +++ /dev/null @@ -1,33 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { readySession, run } from './mobile-web-shell-session-test-fixtures' -import { BRIDGE_KEYBOARD_INSET_ACCEPT } from './bridge/bridge-keyboard-inset' -import { shellPageReadsKeyboardInset } from './page-document-state' - -/** Whether the shell may let the keyboard cover the view, which only the document on screen can say. */ -describe('the page declaring it reads the keyboard from init', () => { - const reads = () => - run(readySession().session, { - type: 'page-ready', - reports: [], - accepts: [BRIDGE_KEYBOARD_INSET_ACCEPT] - }) - - it('is read off the ready that declared it', () => { - expect(shellPageReadsKeyboardInset(reads().session)).toBe(true) - }) - - it('is false for a page that did not declare it, which is every page before the name', () => { - const older = run(readySession().session, { type: 'page-ready', reports: [], accepts: [] }) - expect(shellPageReadsKeyboardInset(older.session)).toBe(false) - }) - - it('is dropped when a replacement document starts, so the next one has to say it again', () => { - const started = run(reads().session, { type: 'document-started' }) - expect(shellPageReadsKeyboardInset(started.session)).toBe(false) - }) - - it('is not read once the generation is off screen', () => { - const failed = run(reads().session, { type: 'shell-failed', reason: 'document-load-failed' }) - expect(shellPageReadsKeyboardInset(failed.session)).toBe(false) - }) -}) diff --git a/mobile/src/mobile-web-shell/mobile-web-shell-safe-area-screen.test.tsx b/mobile/src/mobile-web-shell/mobile-web-shell-safe-area-screen.test.tsx index e8fcf93aad76..f502691a8622 100644 --- a/mobile/src/mobile-web-shell/mobile-web-shell-safe-area-screen.test.tsx +++ b/mobile/src/mobile-web-shell/mobile-web-shell-safe-area-screen.test.tsx @@ -65,21 +65,7 @@ describe('a page that owns its safe area', () => { const read = readBridgeHostMessage(json) return read.ok && read.message.type === 'init' ? [read.message.safeAreaInsets ?? null] : [] }) - const keyboard = async (height: number) => { - await act(async () => { - const ios = dependencies.platform === 'ios' - const name = - height > 0 - ? ios - ? 'keyboardWillShow' - : 'keyboardDidShow' - : ios - ? 'keyboardWillHide' - : 'keyboardDidHide' - dependencies.keyboardListeners.get(name)?.({ endCoordinates: { height } }) - }) - } - return { tree, root, initInsets, keyboard } + return { tree, root, initInsets } } const ownedPage = (sessionId: string) => { dependencies.pageOwnsSafeArea = true @@ -89,48 +75,33 @@ describe('a page that owns its safe area', () => { it('draws the view edge-to-edge and hands the page the insets it now sits under', async () => { const page = await ownedPage('session-owned') - expect(page.root().props.style[1]).toEqual({ paddingTop: 0, paddingBottom: 0 }) + expect(page.root().props.style[1]).toEqual({ paddingTop: 0 }) expect(page.initInsets()).toEqual([WINDOW]) }) - it('re-sends init with no bottom inset while the keyboard ends the view', async () => { - const page = await ownedPage('session-owned-keyboard') - await page.keyboard(336) - // The view ends at the keyboard's top, so nothing of it is under the gesture bar. - expect(page.root().props.style[1]).toEqual({ paddingTop: 0, paddingBottom: 336 }) - await page.keyboard(0) - expect(page.root().props.style[1]).toEqual({ paddingTop: 0, paddingBottom: 0 }) - expect(page.initInsets()).toEqual([WINDOW, { ...WINDOW, bottom: 0 }, WINDOW]) - }) - - it('does the same on Android, where the IME strip is measured above the gesture bar', async () => { - dependencies.platform = 'android' - const page = await ownedPage('session-owned-android') - await page.keyboard(336) - expect(page.root().props.style[1]).toEqual({ paddingTop: 0, paddingBottom: 344 }) - await page.keyboard(0) - expect(page.root().props.style[1]).toEqual({ paddingTop: 0, paddingBottom: 0 }) - expect(page.initInsets()).toEqual([WINDOW, { ...WINDOW, bottom: 0 }, WINDOW]) - }) - it('gives the status bar strip to the update banner while it shows', async () => { dependencies.updateNotice = 'update-failed' const page = await ownedPage('session-owned-banner') - expect(page.root().props.style[1]).toEqual({ paddingTop: 44, paddingBottom: 0 }) + expect(page.root().props.style[1]).toEqual({ paddingTop: 44 }) expect(page.initInsets()).toEqual([{ ...WINDOW, top: 0 }]) await act(async () => { byName(page.tree, 'Pressable') .find((node) => node.props.accessibilityLabel === 'Dismiss notice') ?.props.onPress() }) - expect(page.root().props.style[1]).toEqual({ paddingTop: 0, paddingBottom: 0 }) + expect(page.root().props.style[1]).toEqual({ paddingTop: 0 }) expect(page.initInsets()).toEqual([{ ...WINDOW, top: 0 }, WINDOW]) }) it('sends no second init to an older page that takes route updates but not insets', async () => { + dependencies.updateNotice = 'update-failed' const page = await openPage('session-older', [BRIDGE_ROUTE_UPDATE_ACCEPT]) - await page.keyboard(336) - await page.keyboard(0) + // Dismissing the banner moves the top inset, which this page does not read. + await act(async () => { + byName(page.tree, 'Pressable') + .find((node) => node.props.accessibilityLabel === 'Dismiss notice') + ?.props.onPress() + }) expect(page.root().props.style[1]).toEqual({ paddingTop: 44, paddingBottom: 8 }) expect(page.initInsets()).toHaveLength(1) }) diff --git a/mobile/src/mobile-web-shell/mobile-web-shell-screen-test-harness.tsx b/mobile/src/mobile-web-shell/mobile-web-shell-screen-test-harness.tsx index 05b51a6a6645..5769acc6f291 100644 --- a/mobile/src/mobile-web-shell/mobile-web-shell-screen-test-harness.tsx +++ b/mobile/src/mobile-web-shell/mobile-web-shell-screen-test-harness.tsx @@ -57,9 +57,7 @@ export type ScreenDependencies = { backClaimed: boolean /** Whether the session says the page pads for the system bars itself. */ pageOwnsSafeArea: boolean - /** Whether the session says the page reads the keyboard from `init`. */ - pageReadsKeyboardInset: boolean - /** What `Platform.OS` answers, which picks the keyboard events and the IME strip. */ + /** What `Platform.OS` answers, which picks the keyboard events. */ platform: 'ios' | 'android' reportPageBackClaim: Mock /** Whether the mounted host would take a press, which is a page that declared it takes one. */ @@ -117,7 +115,6 @@ export function createScreenDependencies(): ScreenDependencies { setScreenOptions: vi.fn(), backClaimed: false, pageOwnsSafeArea: false, - pageReadsKeyboardInset: false, platform: 'ios', reportPageBackClaim: vi.fn(), sendBackDelivers: true, @@ -158,7 +155,6 @@ export function resetScreenDependencies(dependencies: ScreenDependencies): void dependencies.reportPageBackClaim.mockReset() dependencies.backClaimed = false dependencies.pageOwnsSafeArea = false - dependencies.pageReadsKeyboardInset = false dependencies.platform = 'ios' dependencies.sendBackDelivers = true dependencies.backSends = 0 diff --git a/mobile/src/mobile-web-shell/mobile-web-shell-screen-test-mocks.tsx b/mobile/src/mobile-web-shell/mobile-web-shell-screen-test-mocks.tsx index 39564c3ba83e..c622c77f11d5 100644 --- a/mobile/src/mobile-web-shell/mobile-web-shell-screen-test-mocks.tsx +++ b/mobile/src/mobile-web-shell/mobile-web-shell-screen-test-mocks.tsx @@ -181,8 +181,7 @@ export function screenModuleMocks(dependencies: ScreenDependencies) { pageReady: dependencies.pageReady, pageFrame: dependencies.pageFrame, backClaimed: dependencies.backClaimed, - pageOwnsSafeArea: dependencies.pageOwnsSafeArea, - pageReadsKeyboardInset: dependencies.pageReadsKeyboardInset + pageOwnsSafeArea: dependencies.pageOwnsSafeArea }) }) } diff --git a/mobile/src/mobile-web-shell/mobile-web-shell-session-contract.ts b/mobile/src/mobile-web-shell/mobile-web-shell-session-contract.ts index ab62620914b7..98f0df8a9007 100644 --- a/mobile/src/mobile-web-shell/mobile-web-shell-session-contract.ts +++ b/mobile/src/mobile-web-shell/mobile-web-shell-session-contract.ts @@ -267,9 +267,6 @@ export type MobileWebShellSession = { /** Whether this document pads for the system bars itself, so the view may go edge-to-edge. * Cleared with `pageReady`, and false for every page built before the declaration existed. */ readonly pageOwnsSafeArea: boolean - /** Whether this document reads the keyboard height from `init`, so the keyboard may cover the - * view. Cleared with `pageReady`, and false for every page built before the declaration. */ - readonly pageReadsKeyboardInset: boolean /** The gates the current step was taken on; null until the first one arrives. */ readonly gates: MobileWebShellGates | null readonly cached: CachedGeneration | null diff --git a/mobile/src/mobile-web-shell/mobile-web-shell-session.ts b/mobile/src/mobile-web-shell/mobile-web-shell-session.ts index c325d300557e..5a0a25b7db68 100644 --- a/mobile/src/mobile-web-shell/mobile-web-shell-session.ts +++ b/mobile/src/mobile-web-shell/mobile-web-shell-session.ts @@ -43,7 +43,6 @@ export function createMobileWebShellSession(routePathname: string): MobileWebShe pagePainted: false, pageBackClaimed: false, pageOwnsSafeArea: false, - pageReadsKeyboardInset: false, gates: null, cached: null, updateNotice: null, diff --git a/mobile/src/mobile-web-shell/page-document-state.ts b/mobile/src/mobile-web-shell/page-document-state.ts index c25b4552bfd6..935f201d346f 100644 --- a/mobile/src/mobile-web-shell/page-document-state.ts +++ b/mobile/src/mobile-web-shell/page-document-state.ts @@ -1,6 +1,5 @@ import { BRIDGE_PAGE_PAINTED } from './bridge/bridge-page-painted' import { BRIDGE_SAFE_AREA_ACCEPT } from './bridge/bridge-safe-area-insets' -import { BRIDGE_KEYBOARD_INSET_ACCEPT } from './bridge/bridge-keyboard-inset' import type { MobileWebShellSession, MobileWebShellSessionEvent @@ -12,8 +11,7 @@ export const CLEAR_PAGE_DOCUMENT_STATE = { pageReportsPaint: false, pagePainted: false, pageBackClaimed: false, - pageOwnsSafeArea: false, - pageReadsKeyboardInset: false + pageOwnsSafeArea: false } as const /** The three things a document reports about itself, as the reducer receives them. */ @@ -44,8 +42,7 @@ export function pageDocumentStatePatch( pageReady: true, pageReportsPaint: event.reports.includes(BRIDGE_PAGE_PAINTED), pageBackClaimed: false, - pageOwnsSafeArea: event.accepts.includes(BRIDGE_SAFE_AREA_ACCEPT), - pageReadsKeyboardInset: event.accepts.includes(BRIDGE_KEYBOARD_INSET_ACCEPT) + pageOwnsSafeArea: event.accepts.includes(BRIDGE_SAFE_AREA_ACCEPT) } } // Kept off a page that never said it would report: acting on an unasked-for frame would make @@ -60,10 +57,3 @@ export function shellPageOwnsSafeArea( ): boolean { return session.state.kind === 'ready' && session.pageOwnsSafeArea } - -/** Whether the shell may let the keyboard cover the view, gated on `ready` the same way. */ -export function shellPageReadsKeyboardInset( - session: Pick -): boolean { - return session.state.kind === 'ready' && session.pageReadsKeyboardInset -} diff --git a/mobile/src/mobile-web-shell/page-keyboard-inset.ts b/mobile/src/mobile-web-shell/page-keyboard-inset.ts deleted file mode 100644 index 0b86ecb75dab..000000000000 --- a/mobile/src/mobile-web-shell/page-keyboard-inset.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { softwareKeyboardWindowInset } from '../platform/software-keyboard-window-inset' - -/** What the shell does with one keyboard reading: the height it hands the page, which is the one - * native screens read on this OS, and the strip it takes off the view, none for a page that - * reads the height. */ -export function shellKeyboardGeometry(input: { - keyboardHeight: number - bottomInset: number - platform: 'ios' | 'android' | 'windows' | 'macos' | 'web' - pageReadsKeyboardInset: boolean -}): { keyboardInset: number; viewShortenedBy: number } { - return { - keyboardInset: Math.max(0, input.keyboardHeight), - // Legacy: only a page without the `keyboard-inset` accept is shortened; delete this branch (and - // `softwareKeyboardWindowInset`) once every served page declares it. - viewShortenedBy: input.pageReadsKeyboardInset ? 0 : softwareKeyboardWindowInset(input) - } -} diff --git a/mobile/src/mobile-web-shell/page-safe-area-insets.test.ts b/mobile/src/mobile-web-shell/page-safe-area-insets.test.ts index 8b0cf1758b7f..e0bd1305405b 100644 --- a/mobile/src/mobile-web-shell/page-safe-area-insets.test.ts +++ b/mobile/src/mobile-web-shell/page-safe-area-insets.test.ts @@ -5,24 +5,10 @@ const WINDOW = { top: 52, right: 12, bottom: 24, left: 12 } describe('the insets the page pads for', () => { it('is the window insets while nothing of the shell stands over the view', () => { - expect(pageSafeAreaInsets({ insets: WINDOW, viewShortenedBy: 0, topCovered: false })).toEqual( - WINDOW - ) - }) - - it("has no bottom while the shell ends an older page's view above the gesture bar", () => { - expect(pageSafeAreaInsets({ insets: WINDOW, viewShortenedBy: 360, topCovered: false })).toEqual( - { - ...WINDOW, - bottom: 0 - } - ) + expect(pageSafeAreaInsets({ insets: WINDOW, topCovered: false })).toEqual(WINDOW) }) it('has no top while the shell banner takes the status bar strip', () => { - expect(pageSafeAreaInsets({ insets: WINDOW, viewShortenedBy: 0, topCovered: true })).toEqual({ - ...WINDOW, - top: 0 - }) + expect(pageSafeAreaInsets({ insets: WINDOW, topCovered: true })).toEqual({ ...WINDOW, top: 0 }) }) }) diff --git a/mobile/src/mobile-web-shell/page-safe-area-insets.ts b/mobile/src/mobile-web-shell/page-safe-area-insets.ts index f4ef399beb0a..71da590370b1 100644 --- a/mobile/src/mobile-web-shell/page-safe-area-insets.ts +++ b/mobile/src/mobile-web-shell/page-safe-area-insets.ts @@ -5,25 +5,23 @@ import type { BridgeSafeAreaInsets } from './bridge/bridge-safe-area-insets' * The part of an edge-to-edge WebView that sits under a system bar, which is what the page pads for. * * The window's insets, as a native screen reads them with the keyboard covering it, except where - * the shell stands over the view: an older page's view it ends at the keyboard's top has nothing - * under the gesture bar, and a banner above the view takes the status bar strip itself. + * the shell's banner stands above the view and takes the status bar strip itself. */ export function pageSafeAreaInsets(input: { insets: BridgeSafeAreaInsets - viewShortenedBy: number topCovered: boolean }): BridgeSafeAreaInsets { const { insets } = input return { top: input.topCovered ? 0 : insets.top, right: insets.right, - bottom: input.viewShortenedBy > 0 ? 0 : insets.bottom, + bottom: insets.bottom, left: insets.left } } -/** Hands moved insets to the page over the re-sent `init` a pane move takes: a shortened view, a - * rotation, or the shell's banner. Keyed on the four numbers, so a render moves nothing. */ +/** Hands moved insets to the page over the re-sent `init` a pane move takes: a rotation or the + * shell's banner. Keyed on the four numbers, so a render moves nothing. */ export function usePublishedSafeAreaInsets( publish: (insets: BridgeSafeAreaInsets) => void, insets: BridgeSafeAreaInsets diff --git a/mobile/src/mobile-web-shell/shell-keyboard-covers-view-census.test.ts b/mobile/src/mobile-web-shell/shell-keyboard-covers-view-census.test.ts new file mode 100644 index 000000000000..386d4f9be8ce --- /dev/null +++ b/mobile/src/mobile-web-shell/shell-keyboard-covers-view-census.test.ts @@ -0,0 +1,48 @@ +/** + * The shell never resizes the WebView for the keyboard: the keyboard covers the view like a native + * screen and the page lifts by the height `init` carries. The symbols of the retired path (a view + * shortened for pages that could not read the height) are named so a reintroduction goes red. + */ +import { readFileSync } from 'node:fs' +import { relative } from 'node:path' +import { fileURLToPath } from 'node:url' +import { describe, expect, it } from 'vitest' +import { censusSourceFiles } from '../test-support/census-source-files' + +const SHELL_DIR = fileURLToPath(new URL('./', import.meta.url)) +const RETIRED = + /softwareKeyboardWindowInset|viewShortenedBy|pageReadsKeyboardInset|shellPageReadsKeyboardInset|shellKeyboardGeometry|BRIDGE_KEYBOARD_INSET_ACCEPT|'keyboard-inset'/ +const KEYBOARD_SIZES_VIEW = /\b(padding|margin)?(Bottom|bottom|height|Height)\s*:[^,}\n]*keyboard/i + +/** Lines that bring back the retired path or size a view from the keyboard. */ +export function keyboardResizesView(source: string): number[] { + return source + .split('\n') + .flatMap((line, index) => + RETIRED.test(line) || KEYBOARD_SIZES_VIEW.test(line) ? [index + 1] : [] + ) +} + +describe('the shell and the keyboard', () => { + it('finds the lines it is looking for', () => { + expect(keyboardResizesView('style={{ paddingBottom: keyboardInset }}')).toEqual([1]) + expect(keyboardResizesView(' height: windowHeight - keyboardHeight,')).toEqual([1]) + expect(keyboardResizesView("accepts.includes('keyboard-inset')")).toEqual([1]) + expect(keyboardResizesView('const { viewShortenedBy } = geometry')).toEqual([1]) + expect(keyboardResizesView('{ paddingTop: insets.top, paddingBottom: insets.bottom }')).toEqual( + [] + ) + expect(keyboardResizesView('publishKeyboardInset(keyboardInset)')).toEqual([]) + }) + + it('never sizes the view from the keyboard', () => { + const offenders = censusSourceFiles(SHELL_DIR) + .filter((file) => /\.tsx?$/.test(file) && !/\.test\.tsx?$/.test(file)) + .flatMap((file) => + keyboardResizesView(readFileSync(file, 'utf8')).map( + (line) => `${relative(SHELL_DIR, file)}:${line}` + ) + ) + expect(offenders).toEqual([]) + }) +}) diff --git a/mobile/src/mobile-web-shell/use-mobile-web-shell-session.ts b/mobile/src/mobile-web-shell/use-mobile-web-shell-session.ts index 11751ec01aa5..da22cd69a2e2 100644 --- a/mobile/src/mobile-web-shell/use-mobile-web-shell-session.ts +++ b/mobile/src/mobile-web-shell/use-mobile-web-shell-session.ts @@ -24,7 +24,7 @@ import type { MobileWebShellUpdateNotice, PageReadyDeclaration } from './mobile-web-shell-session-contract' -import { shellPageOwnsSafeArea, shellPageReadsKeyboardInset } from './page-document-state' +import { shellPageOwnsSafeArea } from './page-document-state' export type MobileWebShellSessionView = { readonly state: MobileWebShellSessionState @@ -65,7 +65,6 @@ export type MobileWebShellSessionView = { /** Whether the document on screen pads for the system bars itself. Projected for the same * reason as `backClaimed`. */ readonly pageOwnsSafeArea: boolean - readonly pageReadsKeyboardInset: boolean } /** @@ -99,9 +98,6 @@ export function useMobileWebShellSession(args: { const [pageOwnsSafeArea, setPageOwnsSafeArea] = useState(() => shellPageOwnsSafeArea(sessionRef.current) ) - const [pageReadsKeyboardInset, setPageReadsKeyboardInset] = useState(() => - shellPageReadsKeyboardInset(sessionRef.current) - ) const hostKey = useMemo(() => deriveHostCacheKey(hostId), [hostId]) const startedAtRef = useRef(runtime.now()) // Bumped by anything that invalidates work in flight; every dispatch out of an effect checks it. @@ -126,7 +122,6 @@ export function useMobileWebShellSession(args: { setPageFrame(shellPageFrame(stepped.session)) setBackClaimed(shellPageBackClaimed(stepped.session)) setPageOwnsSafeArea(shellPageOwnsSafeArea(stepped.session)) - setPageReadsKeyboardInset(shellPageReadsKeyboardInset(stepped.session)) for (const effect of stepped.effects) { // Every effect of a step belongs to the flow that step produced, and its result carries that // number back, so a flow the session has since restarted reports into nothing. @@ -320,7 +315,6 @@ export function useMobileWebShellSession(args: { reportPagePainted, reportPageBackClaim, backClaimed, - pageOwnsSafeArea, - pageReadsKeyboardInset + pageOwnsSafeArea } } diff --git a/mobile/src/platform/software-keyboard-window-inset.test.ts b/mobile/src/platform/software-keyboard-window-inset.test.ts deleted file mode 100644 index b458993d0eaa..000000000000 --- a/mobile/src/platform/software-keyboard-window-inset.test.ts +++ /dev/null @@ -1,39 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { softwareKeyboardWindowInset } from './software-keyboard-window-inset' - -describe('the strip of the window the software keyboard takes', () => { - it('is nothing while the keyboard is closed', () => { - expect( - softwareKeyboardWindowInset({ keyboardHeight: 0, bottomInset: 48, platform: 'android' }) - ).toBe(0) - }) - - it('is the iOS frame height as reported, which already spans the home indicator', () => { - expect( - softwareKeyboardWindowInset({ keyboardHeight: 336, bottomInset: 34, platform: 'ios' }) - ).toBe(336) - }) - - it('adds the navigation bar back on Android, whose IME height stops above it', () => { - // The session dock is the proof this split is real: it pads itself by the inset and then - // translates by the raw height, which lands on the keys only if Android's excludes the bar. - expect( - softwareKeyboardWindowInset({ keyboardHeight: 336, bottomInset: 48, platform: 'android' }) - ).toBe(384) - }) - - it('takes the page host as a phone, since it is one: the shell runs no web build', () => { - expect( - softwareKeyboardWindowInset({ keyboardHeight: 300, bottomInset: 20, platform: 'web' }) - ).toBe(320) - }) - - it('never reports a negative strip, whatever the event and the inset say', () => { - expect( - softwareKeyboardWindowInset({ keyboardHeight: -10, bottomInset: 48, platform: 'android' }) - ).toBe(0) - expect( - softwareKeyboardWindowInset({ keyboardHeight: 336, bottomInset: -48, platform: 'android' }) - ).toBe(336) - }) -}) diff --git a/mobile/src/platform/software-keyboard-window-inset.ts b/mobile/src/platform/software-keyboard-window-inset.ts deleted file mode 100644 index 0c15bba7c2a4..000000000000 --- a/mobile/src/platform/software-keyboard-window-inset.ts +++ /dev/null @@ -1,17 +0,0 @@ -/** - * The strip at the bottom of the window the software keyboard takes, for a view that owns the - * window and has to shorten itself out of the way. The two platforms measure the IME from - * different edges: iOS's frame height starts at the bottom of the window and already spans the - * home indicator, Android's starts above the system bars, so only Android adds the bar back. - */ -export function softwareKeyboardWindowInset(input: { - keyboardHeight: number - bottomInset: number - platform: 'ios' | 'android' | 'windows' | 'macos' | 'web' -}): number { - const keyboardHeight = Math.max(0, input.keyboardHeight) - if (keyboardHeight === 0) { - return 0 - } - return input.platform === 'ios' ? keyboardHeight : keyboardHeight + Math.max(0, input.bottomInset) -} diff --git a/mobile/src/session/use-mobile-session-keyboard-state.test.tsx b/mobile/src/session/use-mobile-session-keyboard-state.test.tsx index e1f12b7414d0..19681ea779a2 100644 --- a/mobile/src/session/use-mobile-session-keyboard-state.test.tsx +++ b/mobile/src/session/use-mobile-session-keyboard-state.test.tsx @@ -121,10 +121,10 @@ describe('what the session screen hears about the keyboard', () => { expect(harness.notifyKeyboardVisibility).toHaveBeenLastCalledWith(false) }) - it('holds the refit off on the page, where the keyboard is open and covers nothing', async () => { - // Inside the shell the WebView is already shortened, so the seam reports no occlusion: the - // dock needs no lift. Refitting on that height change would reflow the desktop PTY on every - // keyboard open, which is the reflow the visibility flag exists to defer. + it('holds the refit off for a keyboard that is open and covers nothing', async () => { + // A floating keyboard reports no occlusion, so the dock needs no lift. Refitting on that height + // change would reflow the desktop PTY on every keyboard open, which is the reflow the + // visibility flag exists to defer. const tree = await mount() harness.keyboard = { height: 0, visible: true } await rerender(tree) diff --git a/mobile/src/terminal/terminal-viewport-refit.test.ts b/mobile/src/terminal/terminal-viewport-refit.test.ts index 7a54c70c8683..1c61a53076fd 100644 --- a/mobile/src/terminal/terminal-viewport-refit.test.ts +++ b/mobile/src/terminal/terminal-viewport-refit.test.ts @@ -153,8 +153,8 @@ describe('terminal viewport refit', () => { expect(sessionSource).toContain('textScale: terminalTextScale') expect(sessionSource).toContain('connState,') expect(sessionSource).toContain('notifyTerminalFrameHeight(nextHeight)') - // One seam for both facts: on the page they come apart, because the shell shortens the WebView - // and the keyboard covers nothing the screen has to lift for. + // One seam for both facts: they come apart for a floating keyboard, which is open yet covers + // nothing the screen has to lift for. expect(sessionSource).toContain('const softKeyboard = useSoftKeyboard()') expect(sessionSource).toContain('notifyKeyboardVisibility(softKeyboard.visible)') expect(sessionSource).toContain('setKeyboardHeight(softKeyboard.height)') diff --git a/mobile/web-entry/index.tsx b/mobile/web-entry/index.tsx index 4690bb48abf6..57936f042529 100644 --- a/mobile/web-entry/index.tsx +++ b/mobile/web-entry/index.tsx @@ -112,8 +112,7 @@ bootstrapShellPage({ // The same shape again, and for the same reason: every haptic on this page is played from a // plain function inside a row's press handler, which no provider wraps. publishHapticsNotifier((kind) => client.notifyHaptics(kind)) - // The shell's keyboard height, read by plain functions as well as hooks; 0 from a shell too old - // to send one, which shortens the view instead. + // The shell's keyboard height, read by plain functions as well as hooks; 0 while it is closed. publishShellKeyboardSource({ read: () => client.getShellSession()?.keyboardInset ?? 0, subscribe: client.onKeyboardInsetUpdate From 43e355b269b93d126621a5c59728846e6283847a Mon Sep 17 00:00:00 2001 From: Jinwoo-H Date: Sun, 27 Sep 2026 18:43:05 -0400 Subject: [PATCH 19/22] test(mobile): the shell keyboard census reads its directory from import.meta Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb --- .../mobile-web-shell/shell-keyboard-covers-view-census.test.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/mobile/src/mobile-web-shell/shell-keyboard-covers-view-census.test.ts b/mobile/src/mobile-web-shell/shell-keyboard-covers-view-census.test.ts index 386d4f9be8ce..6cbeceac5d19 100644 --- a/mobile/src/mobile-web-shell/shell-keyboard-covers-view-census.test.ts +++ b/mobile/src/mobile-web-shell/shell-keyboard-covers-view-census.test.ts @@ -5,11 +5,10 @@ */ import { readFileSync } from 'node:fs' import { relative } from 'node:path' -import { fileURLToPath } from 'node:url' import { describe, expect, it } from 'vitest' import { censusSourceFiles } from '../test-support/census-source-files' -const SHELL_DIR = fileURLToPath(new URL('./', import.meta.url)) +const SHELL_DIR = import.meta.dirname const RETIRED = /softwareKeyboardWindowInset|viewShortenedBy|pageReadsKeyboardInset|shellPageReadsKeyboardInset|shellKeyboardGeometry|BRIDGE_KEYBOARD_INSET_ACCEPT|'keyboard-inset'/ const KEYBOARD_SIZES_VIEW = /\b(padding|margin)?(Bottom|bottom|height|Height)\s*:[^,}\n]*keyboard/i From 6ab349e143b370abae6e9dc9568c01e2e2935656 Mon Sep 17 00:00:00 2001 From: Jinwoo-H Date: Sun, 27 Sep 2026 19:19:51 -0400 Subject: [PATCH 20/22] feat(mobile): the shell requires a page at least as new as itself The manifest carries an optional pageVersion (MOBILE_WEB_PAGE_VERSION, written by the desktop bundle writer); the compat gate walls a page below MOBILE_WEB_PAGE_VERSION_FLOOR with the desktop-side bundle-incompatible verdict, reading an absent field as 0. The wall and the update failure record need no new case. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb --- config/scripts/mobile-web-bundle-manifest.mjs | 14 +++++-- .../mobile-web-bundle-manifest.test.mjs | 35 ++++++++++++++++- .../components/ProtocolBlockScreen.test.ts | 13 +++++++ ...e-web-shell-failed-update-fallback.test.ts | 1 + ...-web-shell-offline-grant-staleness.test.ts | 1 + .../mobile-web-shell-session-effects.test.ts | 23 ++++++++++- .../mobile-web-shell-session-effects.ts | 5 ++- .../mobile-web-shell-session-test-fixtures.ts | 5 ++- .../mobile-web-shell-session.test.ts | 19 ++++++++++ .../use-mobile-web-shell-session.test.ts | 1 + .../mobile-web-bundle-compat.test.ts | 38 +++++++++++++++++++ .../src/transport/mobile-web-bundle-compat.ts | 24 ++++++++++++ .../mobile-web-bundle-reply-schemas.test.ts | 11 ++++++ .../mobile-web-bundle-reply-schemas.ts | 1 + .../mobile-web-page-version-floor.test.ts | 9 +++++ .../manifest-contract.test.ts | 19 ++++++++++ .../mobile-web-bundle/manifest-contract.ts | 8 ++++ 17 files changed, 219 insertions(+), 8 deletions(-) create mode 100644 mobile/src/transport/mobile-web-page-version-floor.test.ts diff --git a/config/scripts/mobile-web-bundle-manifest.mjs b/config/scripts/mobile-web-bundle-manifest.mjs index b7efce25ca0e..2e9888f69c79 100644 --- a/config/scripts/mobile-web-bundle-manifest.mjs +++ b/config/scripts/mobile-web-bundle-manifest.mjs @@ -68,12 +68,10 @@ export function hashedAsset(bytes, extension) { } } -function readIntegerConstant(source, name) { +function readIntegerConstant(source, name, file = 'src/shared/protocol-version.ts') { const match = new RegExp(`export const ${name} = (\\d+)`).exec(source) if (!match) { - throw new Error( - `[mobile-web-bundle-manifest] ${name} not found in src/shared/protocol-version.ts` - ) + throw new Error(`[mobile-web-bundle-manifest] ${name} not found in ${file}`) } return Number.parseInt(match[1], 10) } @@ -94,6 +92,13 @@ export async function readProtocolWindow() { } } +/** The page's build number, parsed for the same reason the protocol window is. */ +export async function readPageVersion() { + const file = join('src', 'shared', 'mobile-web-bundle', 'manifest-contract.ts') + const source = await readFile(join(projectDir, file), 'utf8') + return readIntegerConstant(source, 'MOBILE_WEB_PAGE_VERSION', file) +} + export async function readDesktopVersion() { const packageJson = JSON.parse(await readFile(join(projectDir, 'package.json'), 'utf8')) if (typeof packageJson.version !== 'string' || packageJson.version.length === 0) { @@ -124,6 +129,7 @@ export async function writeMobileWebBundleTree({ desktopVersion, minCompatibleRuntimeProtocolVersion: protocolWindow.minCompatibleRuntimeProtocolVersion, runtimeProtocolVersion: protocolWindow.runtimeProtocolVersion, + pageVersion: await readPageVersion(), entrypoint: MOBILE_WEB_BUNDLE_ENTRYPOINT, totalBytes: assets.reduce((total, asset) => total + asset.byteLength, 0), assets, diff --git a/config/scripts/mobile-web-bundle-manifest.test.mjs b/config/scripts/mobile-web-bundle-manifest.test.mjs index 3c4d35fd8a7f..81c447878a8a 100644 --- a/config/scripts/mobile-web-bundle-manifest.test.mjs +++ b/config/scripts/mobile-web-bundle-manifest.test.mjs @@ -1,10 +1,16 @@ +import { mkdtemp, readFile, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' import { describe, expect, it } from 'vitest' import { computeMobileWebBundleBuildId, contentTypeForExtension, hashedAsset, - serializeMobileWebBundleAssets + serializeMobileWebBundleAssets, + sha256Hex, + writeMobileWebBundleTree } from './mobile-web-bundle-manifest.mjs' +import { MobileWebBundleManifestSchema } from '../../src/shared/mobile-web-bundle/manifest-contract.js' describe('computeMobileWebBundleBuildId', () => { const assets = [ @@ -55,3 +61,30 @@ describe('hashedAsset', () => { expect(() => hashedAsset(Buffer.from('body'), 'wasm')).toThrow(/no content type registered/) }) }) + +describe('writeMobileWebBundleTree', () => { + it('stamps the page version the contract names, which the shell floors on', async () => { + const outDir = await mkdtemp(join(tmpdir(), 'mobile-web-bundle-manifest-')) + try { + const bytes = Buffer.from('\n', 'utf8') + const entry = { + path: 'index.html', + bytes, + sha256: sha256Hex(bytes), + byteLength: bytes.byteLength, + contentType: contentTypeForExtension('html') + } + await writeMobileWebBundleTree({ + outDir, + written: [entry], + desktopVersion: '1.0.0', + protocolWindow: { runtimeProtocolVersion: 3, minCompatibleRuntimeProtocolVersion: 3 } + }) + const manifest = JSON.parse(await readFile(join(outDir, 'manifest.json'), 'utf8')) + expect(Number.isInteger(manifest.pageVersion)).toBe(true) + expect(MobileWebBundleManifestSchema.parse(manifest).pageVersion).toBe(manifest.pageVersion) + } finally { + await rm(outDir, { recursive: true, force: true }) + } + }) +}) diff --git a/mobile/src/components/ProtocolBlockScreen.test.ts b/mobile/src/components/ProtocolBlockScreen.test.ts index a69b52566e3d..c0dd920293d1 100644 --- a/mobile/src/components/ProtocolBlockScreen.test.ts +++ b/mobile/src/components/ProtocolBlockScreen.test.ts @@ -151,6 +151,19 @@ describe('ProtocolBlockScreen', () => { expect(primaryActionUrl()).toBe(RELEASES_URL) }) + it('sends a desktop whose page is older than this shell to the desktop update', () => { + const output = render({ + kind: 'blocked', + reason: 'bundle-incompatible', + side: 'desktop', + pageVersion: 0, + requiredPageVersion: 1 + }) + expect(output).toContain('Update Orca on your computer') + expect(output).toContain('This paired desktop app is too old for your current Orca Mobile app') + expect(primaryActionUrl()).toBe(RELEASES_URL) + }) + it('routes an Android bundle wall to GitHub Releases, not a store that has no listing', () => { nativeTestState.platform.OS = 'android' const output = render({ diff --git a/mobile/src/mobile-web-shell/mobile-web-shell-failed-update-fallback.test.ts b/mobile/src/mobile-web-shell/mobile-web-shell-failed-update-fallback.test.ts index 7814b33c73fe..3ae35fc7a6e5 100644 --- a/mobile/src/mobile-web-shell/mobile-web-shell-failed-update-fallback.test.ts +++ b/mobile/src/mobile-web-shell/mobile-web-shell-failed-update-fallback.test.ts @@ -122,6 +122,7 @@ function manifestOf( buildId: computeMobileWebBundleId(assets), minCompatibleRuntimeProtocolVersion: 2, runtimeProtocolVersion, + pageVersion: 1, entrypoint: 'index.html', totalBytes: TOTAL_BYTES, assets, diff --git a/mobile/src/mobile-web-shell/mobile-web-shell-offline-grant-staleness.test.ts b/mobile/src/mobile-web-shell/mobile-web-shell-offline-grant-staleness.test.ts index c39c55604645..1fb8acee474f 100644 --- a/mobile/src/mobile-web-shell/mobile-web-shell-offline-grant-staleness.test.ts +++ b/mobile/src/mobile-web-shell/mobile-web-shell-offline-grant-staleness.test.ts @@ -110,6 +110,7 @@ function manifestGranting( buildId: BUILD_ID, minCompatibleRuntimeProtocolVersion: 2, runtimeProtocolVersion: 5, + pageVersion: 1, entrypoint: 'index.html', totalBytes: TOTAL_BYTES, assets: ASSETS, diff --git a/mobile/src/mobile-web-shell/mobile-web-shell-session-effects.test.ts b/mobile/src/mobile-web-shell/mobile-web-shell-session-effects.test.ts index 24f3e9a01b8d..5777cb8173f2 100644 --- a/mobile/src/mobile-web-shell/mobile-web-shell-session-effects.test.ts +++ b/mobile/src/mobile-web-shell/mobile-web-shell-session-effects.test.ts @@ -20,7 +20,7 @@ import { MobileWebBundleFetchError } from '../transport/mobile-web-bundle-fetch- import { markRpcDeliveryUnknown } from '../transport/rpc-delivery-ambiguity' import type { RpcClient } from '../transport/rpc-client' import type { GenerationStore } from './generation-store' -import { download, readManifest } from './mobile-web-shell-session-effects' +import { download, openCache, readManifest } from './mobile-web-shell-session-effects' // The mocked operations never touch the client; they only need one to exist. const CLIENT: RpcClient = { @@ -128,6 +128,27 @@ describe('the manifest read', () => { }) }) +describe('the page version the floor reads', () => { + it('is carried from the host manifest to the reducer', async () => { + doubles.manifest = () => Promise.resolve({ manifest: { ...MANIFEST, pageVersion: 4 } }) + const { events, send } = collect() + await readManifest(CLIENT, 3, send) + expect(events).toMatchObject([{ type: 'manifest-read', manifest: { pageVersion: 4 } }]) + }) + + it('is carried from the cached manifest to the generation judged against the host', async () => { + const store: GenerationStore = { + ...storeThat(null), + readActiveGeneration: async () => ({ + buildId: MANIFEST.buildId, + directory: 'd', + manifest: { ...MANIFEST, pageVersion: 4, routes: [] } + }) + } + expect((await openCache(store, 'k'))?.compat.pageVersion).toBe(4) + }) +}) + describe('the download', () => { beforeEach(() => { doubles.fetch = () => diff --git a/mobile/src/mobile-web-shell/mobile-web-shell-session-effects.ts b/mobile/src/mobile-web-shell/mobile-web-shell-session-effects.ts index 989f56bb99bf..56f3ab554d03 100644 --- a/mobile/src/mobile-web-shell/mobile-web-shell-session-effects.ts +++ b/mobile/src/mobile-web-shell/mobile-web-shell-session-effects.ts @@ -40,7 +40,9 @@ export async function openCache( compat: { schemaVersion: active.manifest.schemaVersion, runtimeProtocolVersion: active.manifest.runtimeProtocolVersion, - minCompatibleRuntimeProtocolVersion: active.manifest.minCompatibleRuntimeProtocolVersion + minCompatibleRuntimeProtocolVersion: + active.manifest.minCompatibleRuntimeProtocolVersion, + pageVersion: active.manifest.pageVersion } } } catch { @@ -78,6 +80,7 @@ export async function readManifest( schemaVersion: manifest.schemaVersion, runtimeProtocolVersion: manifest.runtimeProtocolVersion, minCompatibleRuntimeProtocolVersion: manifest.minCompatibleRuntimeProtocolVersion, + pageVersion: manifest.pageVersion, totalBytes: manifest.totalBytes, totalAssets: manifest.assets.length, routes: manifest.routes, diff --git a/mobile/src/mobile-web-shell/mobile-web-shell-session-test-fixtures.ts b/mobile/src/mobile-web-shell/mobile-web-shell-session-test-fixtures.ts index 2151597353e1..17fb655dba62 100644 --- a/mobile/src/mobile-web-shell/mobile-web-shell-session-test-fixtures.ts +++ b/mobile/src/mobile-web-shell/mobile-web-shell-session-test-fixtures.ts @@ -41,6 +41,7 @@ export const MANIFEST_WIRE: MobileWebBundleManifestRead = { buildId: 'b'.repeat(64), minCompatibleRuntimeProtocolVersion: 2, runtimeProtocolVersion: 5, + pageVersion: 1, entrypoint: 'index.html', totalBytes: 4096, assets: [ @@ -86,6 +87,7 @@ export function manifestFacts(wire: MobileWebBundleManifestRead): MobileWebShell schemaVersion: wire.schemaVersion, runtimeProtocolVersion: wire.runtimeProtocolVersion, minCompatibleRuntimeProtocolVersion: wire.minCompatibleRuntimeProtocolVersion, + pageVersion: wire.pageVersion, totalBytes: wire.totalBytes, totalAssets: wire.assets.length, routes: wire.routes, @@ -103,7 +105,8 @@ export const CACHED: CachedGeneration = { compat: { schemaVersion: MANIFEST.schemaVersion, runtimeProtocolVersion: MANIFEST.runtimeProtocolVersion, - minCompatibleRuntimeProtocolVersion: MANIFEST.minCompatibleRuntimeProtocolVersion + minCompatibleRuntimeProtocolVersion: MANIFEST.minCompatibleRuntimeProtocolVersion, + pageVersion: MANIFEST.pageVersion } } diff --git a/mobile/src/mobile-web-shell/mobile-web-shell-session.test.ts b/mobile/src/mobile-web-shell/mobile-web-shell-session.test.ts index 1cf6c0914b07..f88a51e8da79 100644 --- a/mobile/src/mobile-web-shell/mobile-web-shell-session.test.ts +++ b/mobile/src/mobile-web-shell/mobile-web-shell-session.test.ts @@ -221,6 +221,25 @@ describe('the connected flow', () => { }) }) + it('walls a listed route whose page is older than this shell, as a desktop to update', () => { + for (const manifest of [ + { ...MANIFEST, pageVersion: 0 }, + { ...MANIFEST, pageVersion: undefined } + ]) { + const step = run(afterCacheRead(null).session, { type: 'manifest-read', manifest }) + expect(step.session.state).toEqual({ + kind: 'wall', + verdict: { + kind: 'blocked', + reason: 'bundle-incompatible', + side: 'desktop', + pageVersion: 0, + requiredPageVersion: 1 + } + }) + } + }) + it('tells the page which routes it may keep, so it hands the rest back', () => { const step = run(afterCacheRead(null).session, { type: 'manifest-read', manifest: MANIFEST }) expect(step.session.pageRoutes).toEqual(['/h/[hostId]']) diff --git a/mobile/src/mobile-web-shell/use-mobile-web-shell-session.test.ts b/mobile/src/mobile-web-shell/use-mobile-web-shell-session.test.ts index 0787874b441f..469b97571b16 100644 --- a/mobile/src/mobile-web-shell/use-mobile-web-shell-session.test.ts +++ b/mobile/src/mobile-web-shell/use-mobile-web-shell-session.test.ts @@ -41,6 +41,7 @@ const doubles = vi.hoisted((): Doubles => { buildId: 'b'.repeat(64), minCompatibleRuntimeProtocolVersion: 2, runtimeProtocolVersion: 5, + pageVersion: 1, entrypoint: 'index.html', totalBytes: 2048, assets: [ diff --git a/mobile/src/transport/mobile-web-bundle-compat.test.ts b/mobile/src/transport/mobile-web-bundle-compat.test.ts index 639d41ef7db1..4fea3dab1767 100644 --- a/mobile/src/transport/mobile-web-bundle-compat.test.ts +++ b/mobile/src/transport/mobile-web-bundle-compat.test.ts @@ -25,6 +25,7 @@ function manifest( schemaVersion: 1, runtimeProtocolVersion: 3, minCompatibleRuntimeProtocolVersion: 2, + pageVersion: 1, ...overrides } } @@ -189,3 +190,40 @@ describe('evaluateMobileWebBundleCompat', () => { expect(SUPPORTED_MOBILE_WEB_BUNDLE_SCHEMA_VERSIONS).toContain(MOBILE_WEB_BUNDLE_SCHEMA_VERSION) }) }) + +/** The shell requires a page at least as new as itself; an older desktop is walled, never served. */ +describe('the page floor', () => { + const tooOld = (pageVersion: number) => ({ + kind: 'blocked', + reason: 'bundle-incompatible', + side: 'desktop', + pageVersion, + requiredPageVersion: 1 + }) + + it('walls a desktop whose page is older than this shell, as a desktop to update', () => { + expect(evaluate({ manifest: manifest({ pageVersion: 0 }) })).toEqual(tooOld(0)) + }) + + it('reads a manifest with no page version as older than the floor', () => { + const { schemaVersion, runtimeProtocolVersion, minCompatibleRuntimeProtocolVersion } = + manifest() + const unversioned = { + schemaVersion, + runtimeProtocolVersion, + minCompatibleRuntimeProtocolVersion + } + expect(evaluate({ manifest: unversioned })).toEqual(tooOld(0)) + }) + + it('opens a page at the floor and one above it', () => { + expect(evaluate({ manifest: manifest({ pageVersion: 1 }) })).toEqual({ + kind: 'ok', + manifestChecked: true + }) + expect(evaluate({ manifest: manifest({ pageVersion: 7 }) })).toEqual({ + kind: 'ok', + manifestChecked: true + }) + }) +}) diff --git a/mobile/src/transport/mobile-web-bundle-compat.ts b/mobile/src/transport/mobile-web-bundle-compat.ts index b331540df669..d039816be14b 100644 --- a/mobile/src/transport/mobile-web-bundle-compat.ts +++ b/mobile/src/transport/mobile-web-bundle-compat.ts @@ -1,6 +1,10 @@ import { MOBILE_WEB_BUNDLE_CAPABILITY } from '../../../src/shared/mobile-web-bundle/mobile-web-bundle-capability' import type { HostStatusReply } from './host-status-reply-schema' +/** The oldest page this shell serves: the `MOBILE_WEB_PAGE_VERSION` of the page built beside it. An + * older desktop is walled rather than served, so the shell keeps no path for an older page. */ +export const MOBILE_WEB_PAGE_VERSION_FLOOR = 1 + /** The manifest schemas this app shell can mount. Widening it is a shell release, so the list is * stated here rather than read off the contract's current version: the contract names the schema * the desktop writes, which is exactly the number this shell may not recognise. */ @@ -24,6 +28,8 @@ export type MobileWebBundleCompatManifest = { schemaVersion: number runtimeProtocolVersion: number minCompatibleRuntimeProtocolVersion: number + /** Absent from a desktop older than the field, which reads as 0: below every floor. */ + pageVersion?: number } export type MobileWebBundleCompatVerdict = @@ -42,6 +48,14 @@ export type MobileWebBundleCompatVerdict = hostProtocolVersion: number requiredHostProtocolVersion: number } + /** The host serves a page older than this shell's floor. */ + | { + kind: 'blocked' + reason: 'bundle-incompatible' + side: 'desktop' + pageVersion: number + requiredPageVersion: number + } /** The bundle is older than the host expects; the caller refetches. */ | { kind: 'blocked' @@ -90,6 +104,16 @@ export function evaluateMobileWebBundleCompat(input: { schemaVersion: manifest.schemaVersion } } + const pageVersion = manifest.pageVersion ?? 0 + if (pageVersion < MOBILE_WEB_PAGE_VERSION_FLOOR) { + return { + kind: 'blocked', + reason: 'bundle-incompatible', + side: 'desktop', + pageVersion, + requiredPageVersion: MOBILE_WEB_PAGE_VERSION_FLOOR + } + } const hostProtocolVersion = input.hostStatus.protocolVersion ?? 0 if (hostProtocolVersion < manifest.minCompatibleRuntimeProtocolVersion) { return { diff --git a/mobile/src/transport/mobile-web-bundle-reply-schemas.test.ts b/mobile/src/transport/mobile-web-bundle-reply-schemas.test.ts index ca00eca79515..57f5618763ab 100644 --- a/mobile/src/transport/mobile-web-bundle-reply-schemas.test.ts +++ b/mobile/src/transport/mobile-web-bundle-reply-schemas.test.ts @@ -55,6 +55,7 @@ function manifestReply(overrides: Record = {}) { desktopVersion: '1.4.200', minCompatibleRuntimeProtocolVersion: 2, runtimeProtocolVersion: 2, + pageVersion: 1, entrypoint: 'index.html', totalBytes: 12, assets: [asset()], @@ -234,6 +235,16 @@ describe('mobile web bundle manifest reply reader', () => { expect(verdict).toEqual({ kind: 'ok', manifestChecked: true }) }) + it('reads the page version the floor compares, and one a desktop older than it never wrote', () => { + expect(MobileWebBundleManifestReplySchema.parse(manifestReply()).manifest.pageVersion).toBe(1) + expect(readManifest(manifestReply({ pageVersion: undefined })).compatible).toBe(true) + for (const pageVersion of [-1, 1.5, 'one', null]) { + expect(readManifest(manifestReply({ pageVersion })).compatible, String(pageVersion)).toBe( + false + ) + } + }) + it('refuses a manifest with no protocol window, which only a host without the capability sends', () => { expect(readManifest(manifestReply({ runtimeProtocolVersion: undefined })).compatible).toBe( false diff --git a/mobile/src/transport/mobile-web-bundle-reply-schemas.ts b/mobile/src/transport/mobile-web-bundle-reply-schemas.ts index ea68e7dbd142..be9b7bf40add 100644 --- a/mobile/src/transport/mobile-web-bundle-reply-schemas.ts +++ b/mobile/src/transport/mobile-web-bundle-reply-schemas.ts @@ -72,6 +72,7 @@ export const MobileWebBundleManifestReadSchema = z buildId: z.string().regex(SHA256_PATTERN), minCompatibleRuntimeProtocolVersion: z.number().int().nonnegative(), runtimeProtocolVersion: z.number().int().nonnegative(), + pageVersion: z.number().int().nonnegative().optional(), entrypoint: MobileWebBundleAssetPathSchema, totalBytes: z.number().int().nonnegative().max(MOBILE_WEB_BUNDLE_MAX_TOTAL_BYTES), assets: z.array(assetSchema).min(1).max(MOBILE_WEB_BUNDLE_MAX_ASSETS), diff --git a/mobile/src/transport/mobile-web-page-version-floor.test.ts b/mobile/src/transport/mobile-web-page-version-floor.test.ts new file mode 100644 index 000000000000..284e136e7cc8 --- /dev/null +++ b/mobile/src/transport/mobile-web-page-version-floor.test.ts @@ -0,0 +1,9 @@ +import { describe, expect, it } from 'vitest' +import { MOBILE_WEB_PAGE_VERSION } from '../../../src/shared/mobile-web-bundle/manifest-contract' +import { MOBILE_WEB_PAGE_VERSION_FLOOR } from './mobile-web-bundle-compat' + +describe("the shell's page floor", () => { + it('never requires a page newer than the one built beside this shell', () => { + expect(MOBILE_WEB_PAGE_VERSION_FLOOR).toBeLessThanOrEqual(MOBILE_WEB_PAGE_VERSION) + }) +}) diff --git a/src/shared/mobile-web-bundle/manifest-contract.test.ts b/src/shared/mobile-web-bundle/manifest-contract.test.ts index c072b9de63be..089fb9c91491 100644 --- a/src/shared/mobile-web-bundle/manifest-contract.test.ts +++ b/src/shared/mobile-web-bundle/manifest-contract.test.ts @@ -11,6 +11,7 @@ import { MOBILE_WEB_BUNDLE_MAX_ROUTES, MOBILE_WEB_BUNDLE_MAX_TOTAL_BYTES, MOBILE_WEB_BUNDLE_SCHEMA_VERSION, + MOBILE_WEB_PAGE_VERSION, type MobileWebBundleAsset } from './manifest-contract' @@ -104,6 +105,24 @@ describe('MobileWebBundleManifestSchema', () => { }) }) +describe('the page version a manifest carries', () => { + it('takes a count, which is what a shell floors on', () => { + expect( + MobileWebBundleManifestSchema.safeParse(manifestOf([ENTRY], { pageVersion: 1 })).success + ).toBe(true) + for (const bad of [-1, 1.5, '1']) { + expect( + MobileWebBundleManifestSchema.safeParse(manifestOf([ENTRY], { pageVersion: bad })).success, + String(bad) + ).toBe(false) + } + }) + + it('is at least 1, so a manifest without one reads as older than every page that has one', () => { + expect(MOBILE_WEB_PAGE_VERSION).toBeGreaterThanOrEqual(1) + }) +}) + describe('the page routes a manifest declares', () => { function withRoutes(routes: unknown): boolean { return MobileWebBundleManifestSchema.safeParse(manifestOf([ENTRY], { routes })).success diff --git a/src/shared/mobile-web-bundle/manifest-contract.ts b/src/shared/mobile-web-bundle/manifest-contract.ts index 644c0dc1e095..e12443cb7a23 100644 --- a/src/shared/mobile-web-bundle/manifest-contract.ts +++ b/src/shared/mobile-web-bundle/manifest-contract.ts @@ -4,6 +4,12 @@ import { sha256 } from '../sha256' /** A reader that sees another value must reject rather than guess at the shape. */ export const MOBILE_WEB_BUNDLE_SCHEMA_VERSION = 1 as const +/** + * The page's build number, written into every manifest. A shell requires a page at least as new as + * its own floor and walls an older desktop; bump this when a shell stops handling an older page. + */ +export const MOBILE_WEB_PAGE_VERSION = 1 + /** The only stable-named asset, and the only one that references the content-addressed names. */ export const MOBILE_WEB_BUNDLE_ENTRYPOINT = 'index.html' @@ -259,6 +265,8 @@ export const MobileWebBundleManifestSchema = z desktopVersion: z.string().min(1).max(MAX_DESKTOP_VERSION_LENGTH), minCompatibleRuntimeProtocolVersion: z.number().int().nonnegative(), runtimeProtocolVersion: z.number().int().nonnegative(), + /** `MOBILE_WEB_PAGE_VERSION` at build time; absent from a desktop older than the field. */ + pageVersion: z.number().int().nonnegative().optional(), entrypoint: z.literal(MOBILE_WEB_BUNDLE_ENTRYPOINT), totalBytes: z.number().int().nonnegative().max(MOBILE_WEB_BUNDLE_MAX_TOTAL_BYTES), assets: z.array(MobileWebBundleAssetSchema).min(1).max(MOBILE_WEB_BUNDLE_MAX_ASSETS), From 0b9f34d50f1559a0a496228a7747d8a371419637 Mon Sep 17 00:00:00 2001 From: Jinwoo-H Date: Sun, 27 Sep 2026 19:38:36 -0400 Subject: [PATCH 21/22] refactor(mobile): the shell negotiates nothing with a page above its floor No page below the floor is served and no older shell exists, so every accepts fallback is unreachable: ready.accepts, ready.reports and init.accepts go, with BRIDGE_ROUTE_UPDATE_ACCEPT, BRIDGE_SAFE_AREA_ACCEPT, BRIDGE_PAGE_CLIENT_IDENTITY_ACCEPT, BRIDGE_SHELL_ACCEPTS, BRIDGE_MAX_PAGE_ACCEPT(S|_CHARS), pageReportsPaint, pageOwnsSafeArea and PageReadyDeclaration. The shell sends route, Back, safe-area and keyboard updates unconditionally and draws the view edge-to-edge; the page always claims its identity and posts paint and Back claims. The census, renamed shell-older-page-paths-census, names every retired symbol and field. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb --- .../mobile-web-app-drawer-render.test.mjs | 3 - .../scripts/mobile-web-app-render-harness.mjs | 15 +--- config/scripts/mobile-web-app-render.test.mjs | 13 +-- ...ile-web-app-session-terminal-init.test.mjs | 2 - .../MobileWebShellScreen.test.tsx | 49 ++-------- .../mobile-web-shell/MobileWebShellScreen.tsx | 17 ++-- .../mobile-web-shell/bridge-host-back.test.ts | 42 ++++----- .../src/mobile-web-shell/bridge-host-back.ts | 25 ++---- .../mobile-web-shell/bridge-host-contract.ts | 9 +- .../mobile-web-shell/bridge-host-init.test.ts | 15 +--- .../bridge-host-notifications.test.ts | 25 +----- .../src/mobile-web-shell/bridge-host-route.ts | 25 ++---- .../bridge-host-test-harness.ts | 6 +- mobile/src/mobile-web-shell/bridge-host.ts | 16 ++-- .../bridge/bridge-back-round-trip.test.ts | 76 +++------------- .../mobile-web-shell/bridge/bridge-caps.ts | 9 -- .../bridge/bridge-client-init-handshake.ts | 19 +--- .../bridge/bridge-client-notifications.ts | 21 +---- .../bridge/bridge-client-session.ts | 11 +-- .../bridge/bridge-envelope.test.ts | 10 +-- .../bridge/bridge-envelope.ts | 51 +---------- .../bridge/bridge-init-frame.ts | 23 ----- .../bridge/bridge-notify-grants.ts | 5 +- .../bridge/bridge-page-back.ts | 12 +-- .../bridge-page-client-identity.test.ts | 8 -- .../bridge/bridge-page-client-identity.ts | 3 - .../bridge/bridge-page-painted.ts | 6 +- .../bridge-port-pair-test-harness.test.ts | 12 +-- .../bridge/bridge-port-pair-test-harness.ts | 6 +- .../bridge/bridge-route-update.test.ts | 32 +------ .../bridge/bridge-route-update.ts | 25 ++---- .../bridge/bridge-rpc-client-frames.test.ts | 20 +---- .../bridge/bridge-rpc-client.ts | 13 +-- .../bridge/bridge-safe-area-insets.ts | 7 -- ...age-first-paint-through-the-bridge.test.ts | 50 +---------- .../mobile-web-shell-back-claim-state.test.ts | 4 +- ...web-shell-keyboard-overlay-screen.test.tsx | 10 +-- ...mobile-web-shell-safe-area-screen.test.tsx | 35 +++----- .../mobile-web-shell-safe-area-state.test.ts | 34 ------- .../mobile-web-shell-screen-test-harness.tsx | 4 - .../mobile-web-shell-screen-test-mocks.tsx | 3 +- .../mobile-web-shell-session-contract.ts | 20 +---- .../mobile-web-shell-session.test.ts | 85 ++++-------------- .../mobile-web-shell-session.ts | 2 - .../mobile-web-shell/page-document-state.ts | 31 ++----- .../shell-keyboard-covers-view-census.test.ts | 47 ---------- .../shell-older-page-paths-census.test.ts | 89 +++++++++++++++++++ .../mobile-web-shell/shell-page-frame.test.ts | 45 ++-------- .../src/mobile-web-shell/shell-page-frame.ts | 13 +-- .../use-mobile-web-shell-bridge.test.ts | 40 ++------- .../use-mobile-web-shell-bridge.ts | 14 ++- .../use-mobile-web-shell-session.test.ts | 6 +- .../use-mobile-web-shell-session.ts | 30 ++----- .../mobile-web-shell/use-shell-page-back.ts | 2 +- .../src/transport/client-context.web.test.tsx | 27 +----- mobile/src/transport/client-context.web.tsx | 18 +--- .../force-reconnect-page-seam.test.tsx | 3 +- 57 files changed, 280 insertions(+), 963 deletions(-) delete mode 100644 mobile/src/mobile-web-shell/mobile-web-shell-safe-area-state.test.ts delete mode 100644 mobile/src/mobile-web-shell/shell-keyboard-covers-view-census.test.ts create mode 100644 mobile/src/mobile-web-shell/shell-older-page-paths-census.test.ts diff --git a/config/scripts/mobile-web-app-drawer-render.test.mjs b/config/scripts/mobile-web-app-drawer-render.test.mjs index 051072815a48..22d3b14a1d5d 100644 --- a/config/scripts/mobile-web-app-drawer-render.test.mjs +++ b/config/scripts/mobile-web-app-drawer-render.test.mjs @@ -302,9 +302,6 @@ describeDrawer('the device Back key reaching a sheet on the page', () => { host: SHELL_HOST, storage: {}, faultGrant, - // What a shell that knows the lane offers, and the frame it would send. Without the first - // the page posts no claim at all, which is the older-shell arm the unit suites pin. - accepts: [backNames.claim], backFrame: backNames.frame }) await page.goto(`${origin}/`, { waitUntil: 'load' }) diff --git a/config/scripts/mobile-web-app-render-harness.mjs b/config/scripts/mobile-web-app-render-harness.mjs index b7a43815a1e7..f07e0c130a1a 100644 --- a/config/scripts/mobile-web-app-render-harness.mjs +++ b/config/scripts/mobile-web-app-render-harness.mjs @@ -164,9 +164,9 @@ export async function readBrowserFrameQuality() { } /** - * The page's client-identity placeholder and the `init.accepts` name that unlocks it, read from - * the module that declares both. A rig carrying its own copy would go on passing after the real - * pair moved, which is the whole reason every other constant here is read rather than retyped. + * The page's client-identity placeholder, read from the module that declares it. A rig carrying its + * own copy would go on passing after the real one moved, which is the whole reason every other + * constant here is read rather than retyped. */ export async function readBridgePageClientIdentity() { const source = await readFile( @@ -180,10 +180,7 @@ export async function readBridgePageClientIdentity() { } return match[1] } - return { - placeholder: read('BRIDGE_PAGE_CLIENT_ID'), - accept: read('BRIDGE_PAGE_CLIENT_IDENTITY_ACCEPT') - } + return { placeholder: read('BRIDGE_PAGE_CLIENT_ID') } } /** The grant the shell offers every page, read from the same source for the same reason. */ @@ -264,7 +261,6 @@ export function installShellDouble({ grants, pageRoutes = null, pageRouteGrants = null, - accepts = null, backFrame = null, replies, streams = [], @@ -323,9 +319,6 @@ export function installShellDouble({ // Omitted when the caller names none, which is the older-shell case the page falls back // on: an absent field is not an empty one, and the page reads the difference. ...(pageRouteGrants === null ? {} : { pageRouteGrants }), - // Omitted when a check names none, which is the shell that performs no swap and the - // state every other rig in this directory runs in. - ...(accepts === null ? {} : { accepts }), // Omitted for a shell too old to name one, which is the case the page has a panel for. ...(route === null ? {} : { route }), ...(host === null ? {} : { host }), diff --git a/config/scripts/mobile-web-app-render.test.mjs b/config/scripts/mobile-web-app-render.test.mjs index 1cd797d26007..84d3164c7cb3 100644 --- a/config/scripts/mobile-web-app-render.test.mjs +++ b/config/scripts/mobile-web-app-render.test.mjs @@ -135,8 +135,7 @@ async function openPage({ shellHost = SHELL_HOST, shellStorage = {}, shellGrants, - shellPageRoutes = null, - shellAccepts = null + shellPageRoutes = null } = {}) { const page = await browser.newPage({ viewport: { width: 390, height: 844 } }) if (shellRoute !== undefined) { @@ -151,8 +150,7 @@ async function openPage({ storage: shellStorage, faultGrant, grants: shellGrants ?? [faultGrant], - pageRoutes: shellPageRoutes, - accepts: shellAccepts + pageRoutes: shellPageRoutes }) } const errors = [] @@ -587,11 +585,7 @@ describeRender('the Route A page in a real browser', () => { }) ) try { - // The one case that advertises the report, because it is the only one asserting on it. - const opened = await openPage({ - shellRoute: { pathname: HOST_ROUTE }, - shellAccepts: [paintName] - }) + const opened = await openPage({ shellRoute: { pathname: HOST_ROUTE } }) await opened.page.goto(`${origin}/`, { waitUntil: 'load' }) await opened.page.waitForFunction( () => document.documentElement.dataset.orcaWebEntry === 'mounted', @@ -639,7 +633,6 @@ describeRender('the Route A page in a real browser', () => { const route = `${HOST_ROUTE}/pr/render-check-tree` const opened = await openPage({ shellRoute: { pathname: route }, - shellAccepts: [paintName], shellPageRoutes: [HOST_ROUTE_PATTERN, '/h/[hostId]/pr/[worktreeId]'] }) await opened.page.goto(`${origin}/`, { waitUntil: 'load' }) diff --git a/config/scripts/mobile-web-app-session-terminal-init.test.mjs b/config/scripts/mobile-web-app-session-terminal-init.test.mjs index 199c0f15f799..60f1d9050de4 100644 --- a/config/scripts/mobile-web-app-session-terminal-init.test.mjs +++ b/config/scripts/mobile-web-app-session-terminal-init.test.mjs @@ -148,8 +148,6 @@ async function openSessionWithTerminalTab() { faultGrant, grants: [faultGrant, ...sessionGrants()], pageRoutes: PAGE_ROUTE_PATTERNS, - // The page claims an identity only against a shell that says it swaps one in. - accepts: [pageClientIdentity.accept], streams: ['session.tabs.subscribe', 'terminal.subscribe'], replies: { 'worktree.show': { worktree: { id: WORKTREE, name: WORKTREE, path: `/tmp/${WORKTREE}` } }, diff --git a/mobile/src/mobile-web-shell/MobileWebShellScreen.test.tsx b/mobile/src/mobile-web-shell/MobileWebShellScreen.test.tsx index 57caf340c4e9..bc9c4f18da6a 100644 --- a/mobile/src/mobile-web-shell/MobileWebShellScreen.test.tsx +++ b/mobile/src/mobile-web-shell/MobileWebShellScreen.test.tsx @@ -46,7 +46,6 @@ import { BRIDGE_NAVIGATE_BACK_NOTIFY, readBridgeHostMessage } from './bridge/bridge-envelope' -import { BRIDGE_ROUTE_UPDATE_ACCEPT } from './bridge/bridge-route-update' import { MobileWebShellScreen } from './MobileWebShellScreen' import type { MobileWebShellSessionState } from './mobile-web-shell-session-contract' import type { ReactTestInstance, ReactTestRenderer } from 'react-test-renderer' @@ -227,7 +226,7 @@ describe('the hybrid shell screen', () => { tree: ReactTestRenderer initRoutes: () => (Record | undefined)[] move: (next: Record) => Promise - ready: (accepts?: readonly string[]) => Promise + ready: () => Promise }> { const element = (next: Record) => createElement(MobileWebShellScreen, { @@ -259,10 +258,10 @@ describe('the hybrid shell screen', () => { tree.update(element(next)) }) }, - ready: async (accepts = [BRIDGE_ROUTE_UPDATE_ACCEPT]) => { + ready: async () => { await act(async () => { byName(tree, 'ShellViewProbe')[0]?.props.onBridgeMessage({ - nativeEvent: { json: clientFrame({ type: 'ready', accepts }) } + nativeEvent: { json: clientFrame({ type: 'ready' }) } }) }) } @@ -302,18 +301,6 @@ describe('the hybrid shell screen', () => { warned.mockRestore() }) - it('sends no second init to a page that never said it takes one', async () => { - dependencies.client = createFakeRpcClient() - const page = await renderForRoute({ paneKey: '' }) - // A page built before route updates existed declares nothing, and reads a second `init` as a - // replacement: the route still moves, so its next `ready` is answered with the new one. - await page.ready([]) - await page.move({ paneKey: 'pane-1' }) - expect(page.initRoutes()).toEqual([{ paneKey: '' }]) - await page.ready([]) - expect(page.initRoutes()).toEqual([{ paneKey: '' }, { paneKey: 'pane-1' }]) - }) - it('ends that wait on the page asking for a session', async () => { dependencies.client = createFakeRpcClient() const tree = await renderScreen(readyState('session-one')) @@ -434,7 +421,7 @@ describe('the hybrid shell screen', () => { const tree = await renderScreen(readyState('session-one')) await act(async () => { byName(tree, 'ShellViewProbe')[0].props.onBridgeMessage({ - nativeEvent: { json: clientFrame({ type: 'ready', accepts: [BRIDGE_BACK_FRAME] }) } + nativeEvent: { json: clientFrame({ type: 'ready' }) } }) byName(tree, 'ShellViewProbe')[0].props.onBridgeMessage({ nativeEvent: { @@ -661,25 +648,6 @@ describe('what one case mutates does not reach the next', () => { client: null }) }) - - it('keeps both bar strips off the view for a page that does not pad for them', async () => { - // A page served from an older desktop has no reader for the insets, so the shell reserves - // the strips itself. Edge-to-edge makes the manifest's `adjustResize` inert, so the keyboard - // strip comes off the view too: the page's `visualViewport` reads full height with the IME up. - const tree = await renderScreen(readyState('session-keyboard')) - const root = tree.root.find((node) => node.props.testID === 'mobile-web-shell-ready') - expect(root.props.style[1]).toEqual({ paddingTop: 44, paddingBottom: 8 }) - - await act(async () => { - dependencies.keyboardListeners.get('keyboardWillShow')?.({ endCoordinates: { height: 336 } }) - }) - expect(root.props.style[1]).toEqual({ paddingTop: 44, paddingBottom: 8 }) - - await act(async () => { - dependencies.keyboardListeners.get('keyboardWillHide')?.({ endCoordinates: { height: 0 } }) - }) - expect(root.props.style[1]).toEqual({ paddingTop: 44, paddingBottom: 8 }) - }) }) /** @@ -728,7 +696,7 @@ describe('the frame under a page that has not painted', () => { await act(async () => { dependencies.keyboardListeners.get('keyboardWillShow')?.({ endCoordinates: { height: 336 } }) }) - expect(root.props.style[1]).toEqual({ paddingTop: 44, paddingBottom: 8 }) + expect(root.props.style[1]).toEqual({ paddingTop: 0 }) const cover = tree.root.find((node) => node.props.testID === 'mobile-web-shell-cover') expect(cover.props.style[0]).toMatchObject({ position: 'absolute', @@ -750,13 +718,10 @@ describe('the frame under a page that has not painted', () => { const probe = byName(tree, 'ShellViewProbe')[0] await act(async () => { probe.props.onBridgeMessage({ - nativeEvent: { json: clientFrame({ type: 'ready', reports: [BRIDGE_PAGE_PAINTED] }) } + nativeEvent: { json: clientFrame({ type: 'ready' }) } }) }) - expect(dependencies.reportPageReady).toHaveBeenCalledWith({ - reports: [BRIDGE_PAGE_PAINTED], - accepts: [] - }) + expect(dependencies.reportPageReady).toHaveBeenCalledTimes(1) await act(async () => { probe.props.onBridgeMessage({ nativeEvent: { json: clientFrame({ type: 'notify', name: BRIDGE_PAGE_PAINTED }) } diff --git a/mobile/src/mobile-web-shell/MobileWebShellScreen.tsx b/mobile/src/mobile-web-shell/MobileWebShellScreen.tsx index 9ec9744ed1f4..88cedd9fd6de 100644 --- a/mobile/src/mobile-web-shell/MobileWebShellScreen.tsx +++ b/mobile/src/mobile-web-shell/MobileWebShellScreen.tsx @@ -188,8 +188,7 @@ export function MobileWebShellScreen({ reportPageBackClaim, pageReady, pageFrame, - backClaimed, - pageOwnsSafeArea + backClaimed } = useMobileWebShellSession({ hostId, routePathname: route.pathname, runtime }) // Which mount the notice was dismissed on, not whether it was: a later refusal opens its own // generation under a new session id, so it is not silenced by a tap on the one before it. @@ -246,12 +245,12 @@ export function MobileWebShellScreen({ // the map as they are made. This re-seats that map on the store afterwards, for the key whose // write never persisted, and it runs on every ask because a document that reloads inside this // mount asks again. - onPageReady: (ready) => { - reportPageReady(ready) + onPageReady: () => { + reportPageReady() void refreshStorage() }, // The one thing that says the page is something to look at. The cover below stays up until it - // lands, for a page that declared it would send one. + // lands. onPagePainted: reportPagePainted, // While this is true the key below belongs to the page, not to the stack this screen sits on. onPageBackClaim: reportPageBackClaim, @@ -359,11 +358,9 @@ export function MobileWebShellScreen({ diff --git a/mobile/src/mobile-web-shell/bridge-host-back.test.ts b/mobile/src/mobile-web-shell/bridge-host-back.test.ts index 7010e85ea8b8..d368c74d524e 100644 --- a/mobile/src/mobile-web-shell/bridge-host-back.test.ts +++ b/mobile/src/mobile-web-shell/bridge-host-back.test.ts @@ -3,8 +3,8 @@ import { clientFrame } from './bridge-host-test-fakes' import { harness } from './bridge-host-test-harness' import { BRIDGE_BACK_CLAIM_NOTIFY, BRIDGE_BACK_FRAME } from './bridge/bridge-page-back' -function ready(accepts?: readonly string[]): string { - return clientFrame(accepts === undefined ? { type: 'ready' } : { type: 'ready', accepts }) +function ready(): string { + return clientFrame({ type: 'ready' }) } function claim(claimed: boolean): string { @@ -21,7 +21,7 @@ function claim(claimed: boolean): string { describe('the claim a host holds on the device Back key', () => { it('carries the page taking the key and letting it go, and says neither twice', () => { const bridge = harness() - bridge.host.receive(ready([BRIDGE_BACK_FRAME])) + bridge.host.receive(ready()) bridge.host.receive(claim(true)) bridge.host.receive(claim(true)) bridge.host.receive(claim(false)) @@ -30,15 +30,15 @@ describe('the claim a host holds on the device Back key', () => { it('drops it on the next document saying ready, which is the one that has to claim again', () => { const bridge = harness() - bridge.host.receive(ready([BRIDGE_BACK_FRAME])) + bridge.host.receive(ready()) bridge.host.receive(claim(true)) - bridge.host.receive(ready([BRIDGE_BACK_FRAME])) + bridge.host.receive(ready()) expect(bridge.backClaims).toEqual([true, false]) }) it('drops it when the page closes, which is the document saying it is going', () => { const bridge = harness() - bridge.host.receive(ready([BRIDGE_BACK_FRAME])) + bridge.host.receive(ready()) bridge.host.receive(claim(true)) bridge.host.receive(clientFrame({ type: 'close' })) expect(bridge.backClaims).toEqual([true, false]) @@ -53,7 +53,7 @@ describe('the claim a host holds on the device Back key', () => { */ it('reports nothing when the host itself ends: the claim belongs to the session', () => { const bridge = harness() - bridge.host.receive(ready([BRIDGE_BACK_FRAME])) + bridge.host.receive(ready()) bridge.host.receive(claim(true)) bridge.host.dispose() expect(bridge.backClaims).toEqual([true]) @@ -61,35 +61,35 @@ describe('the claim a host holds on the device Back key', () => { it('hands what the session established to the host that takes over from it', () => { const bridge = harness() - bridge.host.receive(ready([BRIDGE_BACK_FRAME])) + bridge.host.receive(ready()) bridge.host.receive(claim(true)) bridge.host.dispose() - expect(bridge.host.readSessionBack()).toEqual({ accepts: [BRIDGE_BACK_FRAME], claimed: true }) + expect(bridge.host.readSessionBack()).toEqual({ claimed: true }) }) it('takes that seed without announcing a claim the screen never heard go', () => { const rebuilt = harness({ - sessionBack: { accepts: [BRIDGE_BACK_FRAME], claimed: true }, + sessionBack: { claimed: true }, sessionEstablished: true }) expect(rebuilt.backClaims).toEqual([]) - // And it delivers on it: the page said it takes a press, over a session that is still open. + // And it delivers on it, over a session that is still open. expect(rebuilt.host.sendBack()).toBe(true) expect(rebuilt.last()).toEqual({ v: 1, type: BRIDGE_BACK_FRAME }) }) it('lets the next document reset a carried claim, so the seed is not a latch', () => { const rebuilt = harness({ - sessionBack: { accepts: [BRIDGE_BACK_FRAME], claimed: true }, + sessionBack: { claimed: true }, sessionEstablished: true }) - rebuilt.host.receive(ready([BRIDGE_BACK_FRAME])) + rebuilt.host.receive(ready()) expect(rebuilt.backClaims).toEqual([false]) }) it('says nothing on a document that never claimed, so a drop is always a real one', () => { const bridge = harness() - bridge.host.receive(ready([BRIDGE_BACK_FRAME])) + bridge.host.receive(ready()) bridge.host.receive(clientFrame({ type: 'close' })) bridge.host.dispose() expect(bridge.backClaims).toEqual([]) @@ -110,7 +110,7 @@ describe('the claim a host holds on the device Back key', () => { describe('handing one press to the page', () => { it('posts a back frame to a page that said it takes one', () => { const bridge = harness() - bridge.host.receive(ready([BRIDGE_BACK_FRAME])) + bridge.host.receive(ready()) expect(bridge.host.sendBack()).toBe(true) expect(bridge.last()).toEqual({ v: 1, type: BRIDGE_BACK_FRAME }) }) @@ -120,24 +120,16 @@ describe('handing one press to the page', () => { * one as `unrecognised-message` and drops the whole thing, so the shell must not send it. False * is what leaves the press to the navigator, which is what Back did before this lane. */ - it('sends nothing to a page that never declared it, and says so to the caller', () => { - const bridge = harness() - bridge.host.receive(ready()) - const before = bridge.posted.length - expect(bridge.host.sendBack()).toBe(false) - expect(bridge.posted).toHaveLength(before) - }) - it('sends nothing between documents, when the view belongs to no page', () => { const bridge = harness() - bridge.host.receive(ready([BRIDGE_BACK_FRAME])) + bridge.host.receive(ready()) bridge.host.receive(clientFrame({ type: 'close' })) expect(bridge.host.sendBack()).toBe(false) }) it('sends nothing once the host is disposed', () => { const bridge = harness() - bridge.host.receive(ready([BRIDGE_BACK_FRAME])) + bridge.host.receive(ready()) bridge.host.dispose() expect(bridge.host.sendBack()).toBe(false) }) diff --git a/mobile/src/mobile-web-shell/bridge-host-back.ts b/mobile/src/mobile-web-shell/bridge-host-back.ts index b9cbe108e553..a835be0e3549 100644 --- a/mobile/src/mobile-web-shell/bridge-host-back.ts +++ b/mobile/src/mobile-web-shell/bridge-host-back.ts @@ -2,8 +2,7 @@ import { BRIDGE_PROTOCOL_VERSION, type BridgeHostMessage } from './bridge/bridge import { BRIDGE_BACK_FRAME } from './bridge/bridge-page-back' /** - * What one session has established about the device Back key: what its page declared it takes, and - * whether it is holding the key right now. + * What one session has established about the device Back key: whether its page is holding it. * * Carried across a host rebuild rather than relearned, the way `sessionEstablished` already is. A * client swapped under a live page is not a new document — the WebView stays mounted and the page @@ -11,8 +10,6 @@ import { BRIDGE_BACK_FRAME } from './bridge/bridge-page-back' * under an open sheet. */ export type BridgeSessionBack = { - /** What the page's last `ready` said it takes. Empty for a page too old to name the frame. */ - readonly accepts: readonly string[] readonly claimed: boolean } @@ -29,14 +26,12 @@ export type BridgeSessionBack = { * whoever builds the replacement, and reports nothing, because the claim belongs to the session. */ export type BridgeHostBack = { - /** A document has spoken: it takes what it named, and claims nothing until it says otherwise. */ - readonly readReady: (accepts: readonly string[]) => void + /** A document has spoken: it claims nothing until it says otherwise. */ + readonly readReady: () => void /** The page holding Back, or letting it go. */ readonly readClaim: (claimed: boolean) => void - /** - * Posts one press. False when this page never said it takes one — every page older than the - * frame — and the caller then leaves Back to the navigator, which is what it did before this. - */ + /** Posts one press. False when no document can take it, and the caller leaves Back to the + * navigator. */ readonly send: () => boolean /** The document is gone; whatever it claimed goes with it. */ readonly drop: () => void @@ -53,7 +48,6 @@ export function createBridgeHostBack(args: { * a host opening a session of its own, which has established nothing yet. */ established?: BridgeSessionBack }): BridgeHostBack { - let accepts: readonly string[] = args.established?.accepts ?? [] // Seeded without a report: the screen never heard this claim go, because it did not. let claimed = args.established?.claimed ?? false @@ -66,10 +60,7 @@ export function createBridgeHostBack(args: { } return { - readReady: (next) => { - accepts = next - drop() - }, + readReady: drop, readClaim: (next) => { if (next === claimed) { return @@ -78,13 +69,13 @@ export function createBridgeHostBack(args: { args.onClaim(next) }, send: () => { - if (!accepts.includes(BRIDGE_BACK_FRAME) || !args.deliverable()) { + if (!args.deliverable()) { return false } args.send({ v: BRIDGE_PROTOCOL_VERSION, type: BRIDGE_BACK_FRAME }) return true }, drop, - read: () => ({ accepts, claimed }) + read: () => ({ claimed }) } } diff --git a/mobile/src/mobile-web-shell/bridge-host-contract.ts b/mobile/src/mobile-web-shell/bridge-host-contract.ts index 26b6819d376e..a9f9dfcb10b2 100644 --- a/mobile/src/mobile-web-shell/bridge-host-contract.ts +++ b/mobile/src/mobile-web-shell/bridge-host-contract.ts @@ -5,7 +5,6 @@ import type { BridgeRefusal } from './bridge/bridge-caps' import type { BridgeInitHost, BridgeInitRoute } from './bridge/bridge-envelope' import type { BridgeClearableRouteParam } from './bridge/bridge-route-update' import type { BridgeSafeAreaInsets } from './bridge/bridge-safe-area-insets' -import type { PageReadyDeclaration } from './mobile-web-shell-session-contract' import type { BridgeHapticsKind } from './bridge/bridge-haptics-notify' import type { BridgeErrorCapture } from './bridge/bridge-error-capture' import type { BridgeNativeVerb } from './bridge/bridge-native-verbs' @@ -205,12 +204,8 @@ export type BridgeHostOptions = { * the same reason as the fault: the shell bounds the wait for it, and a host built without this * would leave a document that never spoke looking exactly like one still starting up. */ - onPageReady: (ready: PageReadyDeclaration) => void - /** - * The page has a frame on screen. Only pages whose `ready` listed `BRIDGE_PAGE_PAINTED` post it, - * which is why `onPageReady` carries that list: a caller covering the view until this arrives - * has to know whether it is coming, and a page served from an older desktop never sends one. - */ + onPageReady: () => void + /** The page has a frame on screen, which a caller covering the view until then waits for. */ onPagePainted: () => void /** * The page is holding the device Back key, or has let it go. Required, because the shell only diff --git a/mobile/src/mobile-web-shell/bridge-host-init.test.ts b/mobile/src/mobile-web-shell/bridge-host-init.test.ts index 6e2f86788f2d..0b0b52687fc1 100644 --- a/mobile/src/mobile-web-shell/bridge-host-init.test.ts +++ b/mobile/src/mobile-web-shell/bridge-host-init.test.ts @@ -7,10 +7,6 @@ import { BRIDGE_MAX_SUBSCRIPTIONS } from './bridge/bridge-caps' import { BRIDGE_FAULT_GRANT } from './bridge/bridge-envelope' -import { BRIDGE_PAGE_CLIENT_IDENTITY_ACCEPT } from './bridge/bridge-page-client-identity' -import { BRIDGE_BACK_CLAIM_NOTIFY } from './bridge/bridge-page-back' -import { BRIDGE_PAGE_PAINTED } from './bridge/bridge-page-painted' -import { BRIDGE_ROUTE_PARAM_CLEAR } from './bridge/bridge-route-update' import { routeViewOf } from './page-route-policy' describe('init and state', () => { @@ -29,13 +25,6 @@ describe('init and state', () => { type: 'init', sessionId: 'session-a', buildId: 'build-a', - // What this shell takes from the page, which is the page's own check before it posts one. - accepts: [ - BRIDGE_ROUTE_PARAM_CLEAR, - BRIDGE_PAGE_CLIENT_IDENTITY_ACCEPT, - BRIDGE_PAGE_PAINTED, - BRIDGE_BACK_CLAIM_NOTIFY - ], connection: { state: 'reconnecting', reconnectAttempt: 3, @@ -265,7 +254,7 @@ describe('init and state', () => { route: { pathname: '/h/host-a/session/wt-1' }, post: () => (view.gone ? Promise.reject(new Error('the view is gone')) : Promise.resolve()) }) - // A page that declares nothing is never sent a second `init`, so the tap can only be held. + // The second `init` the tap sends is refused with the view, so only the held route is left. bridge.host.receive(clientFrame({ type: 'ready' })) bridge.host.publishRoute({ pathname: '/h/host-a/session/wt-1', @@ -274,7 +263,7 @@ describe('init and state', () => { for (let turn = 0; turn < 4; turn += 1) { await Promise.resolve() } - expect(bridge.posted).toHaveLength(1) + expect(bridge.posted).toHaveLength(2) // The next document over the same host: a reload, or the view coming back. view.gone = false bridge.host.receive(clientFrame({ type: 'ready' })) diff --git a/mobile/src/mobile-web-shell/bridge-host-notifications.test.ts b/mobile/src/mobile-web-shell/bridge-host-notifications.test.ts index dc9436074e83..1e7b7904a101 100644 --- a/mobile/src/mobile-web-shell/bridge-host-notifications.test.ts +++ b/mobile/src/mobile-web-shell/bridge-host-notifications.test.ts @@ -6,8 +6,6 @@ import { BRIDGE_FAULT_GRANT, BRIDGE_NAVIGATE_BACK_NOTIFY } from './bridge/bridge-envelope' -import { BRIDGE_PAGE_CLIENT_IDENTITY_ACCEPT } from './bridge/bridge-page-client-identity' -import { BRIDGE_BACK_CLAIM_NOTIFY } from './bridge/bridge-page-back' import { BRIDGE_PAGE_PAINTED } from './bridge/bridge-page-painted' import { BRIDGE_ROUTE_PARAM_CLEAR } from './bridge/bridge-route-update' import { @@ -462,20 +460,6 @@ describe('the page erasing a one-shot route param', () => { expect(bridge.routeParamClears()).toEqual([]) expect(bridge.diagnostics).toEqual([{ kind: 'refused', refusal: 'unrecognised-message' }]) }) - - it('tells the page it takes a clear, so a page built for an older shell does not post one', () => { - const bridge = harness({ route: { pathname: '/h/host-a/session/wt-1' } }) - bridge.host.receive(clientFrame({ type: 'ready' })) - const init = bridge.last() - // Written out rather than compared against `BRIDGE_SHELL_ACCEPTS`: a list that pins itself - // pins nothing, and this is the frame an older page reads to decide what it may post. - expect(init.type === 'init' && init.accepts).toEqual([ - BRIDGE_ROUTE_PARAM_CLEAR, - BRIDGE_PAGE_CLIENT_IDENTITY_ACCEPT, - BRIDGE_PAGE_PAINTED, - BRIDGE_BACK_CLAIM_NOTIFY - ]) - }) }) /** @@ -485,20 +469,13 @@ describe('the page erasing a one-shot route param', () => { describe('the page reporting its first frame', () => { it('hands the report to the session and asks the client for nothing', () => { const bridge = harness() - bridge.host.receive(clientFrame({ type: 'ready', reports: [BRIDGE_PAGE_PAINTED] })) + bridge.host.receive(clientFrame({ type: 'ready' })) bridge.host.receive(clientFrame({ type: 'notify', name: BRIDGE_PAGE_PAINTED })) expect(bridge.pagePaintCount()).toBe(1) expect(bridge.client.requests).toHaveLength(0) expect(bridge.client.foregroundCalls).toHaveLength(0) }) - it('forwards what each ready declared, including a name this shell does not implement', () => { - const bridge = harness() - bridge.host.receive(clientFrame({ type: 'ready', reports: [BRIDGE_PAGE_PAINTED, 'weather'] })) - bridge.host.receive(clientFrame({ type: 'ready' })) - expect(bridge.pageReports()).toEqual([[BRIDGE_PAGE_PAINTED, 'weather'], []]) - }) - it('refuses a report from a document nothing has answered', () => { const bridge = harness() bridge.host.receive(clientFrame({ type: 'notify', name: BRIDGE_PAGE_PAINTED })) diff --git a/mobile/src/mobile-web-shell/bridge-host-route.ts b/mobile/src/mobile-web-shell/bridge-host-route.ts index c61a042b03bd..1306ea276a29 100644 --- a/mobile/src/mobile-web-shell/bridge-host-route.ts +++ b/mobile/src/mobile-web-shell/bridge-host-route.ts @@ -1,11 +1,6 @@ -import { - BridgeInitRouteSchema, - type BridgeClientMessage, - type BridgeInitRoute -} from './bridge/bridge-envelope' +import { BridgeInitRouteSchema, type BridgeInitRoute } from './bridge/bridge-envelope' import { readBridgeRouteUpdate } from './bridge/bridge-route-update' import { - BRIDGE_SAFE_AREA_ACCEPT, sameSafeAreaInsets, ZERO_SAFE_AREA_INSETS, type BridgeSafeAreaInsets @@ -17,13 +12,10 @@ export type BridgeHostRoute = { readonly current: () => BridgeInitRoute | null /** Why the opened route was refused, for the line the host prints at construction. */ readonly openIssue: () => string - /** What the page's latest `ready` said it can be sent. Reset by each document's `ready`. */ - readonly readReady: (message: Extract) => void /** * Hands the page a rewritten param for the screen it is already on, and sends one `init` when * that moved the route. The held route moves either way, so a page that reloads inside this - * mount is given the newest one on its next `ready` even when it is too old to be sent one in - * flight. + * mount is given the newest one on its next `ready`. * * Answers nothing, and nothing here learns anything from a post (ruling 34). It cannot: a frame * the page received and then failed to handle is caught by the page and reported there, so what @@ -36,8 +28,8 @@ export type BridgeHostRoute = { /** The insets the next `init` carries. */ readonly safeAreaInsets: () => BridgeSafeAreaInsets /** - * Moves the held insets, and sends one `init` when they moved and the page reads them. The same - * lane as a pane update: held either way, so the next `ready` carries them. + * Moves the held insets, and sends one `init` when they moved. The same lane as a pane update: + * held either way, so the next `ready` carries them. */ readonly publishSafeAreaInsets: (next: BridgeSafeAreaInsets, deliverable: boolean) => void /** The keyboard height the next `init` carries. */ @@ -73,17 +65,13 @@ export function createBridgeHostRoute(args: { }): BridgeHostRoute { const parsed = BridgeInitRouteSchema.safeParse(args.opened) let route = parsed.success && !args.refused ? parsed.data : null - let accepts: readonly string[] = [] let insets = args.safeAreaInsets ?? ZERO_SAFE_AREA_INSETS let keyboard = args.keyboardInset ?? 0 return { current: () => route, openIssue: () => (parsed.success ? 'unknown' : (parsed.error.issues[0]?.message ?? 'unknown')), - readReady: (message) => { - accepts = message.accepts ?? [] - }, publish: (next, deliverable) => { - const update = readBridgeRouteUpdate({ held: route, next, accepts, deliverable }) + const update = readBridgeRouteUpdate({ held: route, next, deliverable }) if (update.kind === 'refuse') { args.onRefused(update.issue) return @@ -99,8 +87,7 @@ export function createBridgeHostRoute(args: { return } insets = next - // Only to a page that reads them: a re-init to one that does not is a wasted frame per move. - if (deliverable && accepts.includes(BRIDGE_SAFE_AREA_ACCEPT)) { + if (deliverable) { args.sendInit() } }, diff --git a/mobile/src/mobile-web-shell/bridge-host-test-harness.ts b/mobile/src/mobile-web-shell/bridge-host-test-harness.ts index 835698e24ac7..5c3d602a4ed5 100644 --- a/mobile/src/mobile-web-shell/bridge-host-test-harness.ts +++ b/mobile/src/mobile-web-shell/bridge-host-test-harness.ts @@ -50,7 +50,6 @@ export type Harness = { /** Every claim the host reported, in order, including the false it sends when a document ends. */ backClaims: boolean[] /** What each answered `ready` declared it reports, in order. */ - pageReports: () => readonly (readonly string[])[] /** One entry per `ready` answered, saying whether its `init` reached the page. Filled as each * post settles, so a case reads it after awaiting the turn the post resolves on. */ /** Every clear the page asked for, in order. */ @@ -120,7 +119,6 @@ export function harness( let pageReadies = 0 let pagePaints = 0 /** What each answered `ready` declared it reports, in order. */ - const pageReports: (readonly string[])[] = [] /** One entry per `ready` answered, saying whether an `init` actually went out for it. */ const routeParamClears: { param: string; value: string }[] = [] const routeRefusals: string[] = [] @@ -146,9 +144,8 @@ export function harness( readStorage: options.readStorage ?? (() => ({ storage: options.storage ?? {}, storageOversize: [] })), onStorageWrite: (key, value) => storageWrites.push({ key, value }), - onPageReady: ({ reports }) => { + onPageReady: () => { pageReadies += 1 - pageReports.push(reports) }, onPageBackClaim: (claimed) => backClaims.push(claimed), onPagePainted: () => { @@ -212,7 +209,6 @@ export function harness( pageReadyCount: () => pageReadies, pagePaintCount: () => pagePaints, backClaims, - pageReports: () => pageReports, routeParamClears: () => routeParamClears, routeRefusals, pageFaults, diff --git a/mobile/src/mobile-web-shell/bridge-host.ts b/mobile/src/mobile-web-shell/bridge-host.ts index a34ad4c1bd4f..9431b4500db0 100644 --- a/mobile/src/mobile-web-shell/bridge-host.ts +++ b/mobile/src/mobile-web-shell/bridge-host.ts @@ -13,7 +13,7 @@ import { type BridgeInitRoute } from './bridge/bridge-envelope' import { BridgePageRouteGrantsSchema } from './bridge/bridge-page-route-grants' -import { BRIDGE_SHELL_ACCEPTS, createBridgeInitFrame } from './bridge/bridge-init-frame' +import { createBridgeInitFrame } from './bridge/bridge-init-frame' import { splitBridgeReply } from './bridge/bridge-reply-chunking' import { createBridgeHostFrames } from './bridge-host-frames' import { createBridgeHostBack, type BridgeSessionBack } from './bridge-host-back' @@ -31,9 +31,8 @@ export type BridgeHost = { * Hands this session a rewritten route: same screen, different params (ruling 33.1). * * The held route moves either way, so a page that reloads inside this mount is told the newest - * one; the frame goes out only to a page that declared `BRIDGE_ROUTE_UPDATE_ACCEPT`, because a - * page too old to name it reads a second `init` as a replacement. A different pathname is a - * different screen and is refused here — that is a remount, which is what the shell already does. + * one. A different pathname is a different screen and is refused here — that is a remount, + * which is what the shell already does. * * Answers nothing, and nothing is tracked (ruling 34): a frame the view refused is repaired by * the next `init`, and the request it carried is spent by the page, which erases the param it @@ -172,7 +171,6 @@ export function createBridgeHost(options: BridgeHostOptions): BridgeHost { ? { pageRouteGrants: parsedRouteGrants.data } : {}), granted, - accepts: BRIDGE_SHELL_ACCEPTS, host, ...options.readStorage() }) @@ -253,16 +251,12 @@ export function createBridgeHost(options: BridgeHostOptions): BridgeHost { // re-asked `ready` from the document already being served is answered the same way. if (message.type === 'ready') { serving = true - routes.readReady(message) - back.readReady(message.accepts ?? []) + back.readReady() // Every time it is asked, not once: the page re-asks on a backoff, and each ask is answered // with the route the shell holds now. That is the whole repair path for a frame that never // arrived (ruling 34) — nothing here waits on one, and nothing retries one. sendInit() - // Forwarded verbatim, including a name this shell has never implemented: what each report - // means is the caller's, and this host's job is that the list belongs to the document that - // just spoke rather than to the one before it. - options.onPageReady({ reports: message.reports ?? [], accepts: message.accepts ?? [] }) + options.onPageReady() return } if (!serving) { diff --git a/mobile/src/mobile-web-shell/bridge/bridge-back-round-trip.test.ts b/mobile/src/mobile-web-shell/bridge/bridge-back-round-trip.test.ts index 1ceb977eb71a..a4940d4d9d8b 100644 --- a/mobile/src/mobile-web-shell/bridge/bridge-back-round-trip.test.ts +++ b/mobile/src/mobile-web-shell/bridge/bridge-back-round-trip.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it, vi } from 'vitest' import { BRIDGE_PROTOCOL_VERSION } from './bridge-envelope' -import { BRIDGE_BACK_CLAIM_NOTIFY, BRIDGE_BACK_FRAME } from './bridge-page-back' +import { BRIDGE_BACK_CLAIM_NOTIFY } from './bridge-page-back' import { createFakeBridgePortPair, type BridgePortPair } from './bridge-port-pair-test-harness' import type { FakeRpcClient } from '../bridge-host-test-fakes' @@ -58,9 +58,7 @@ describe('a Back press crossing from the shell to the page', () => { release() await pair.flush() // The shell still sends one, standing in for a claim that went stale in flight. - pair.host.receive( - JSON.stringify({ v: BRIDGE_PROTOCOL_VERSION, type: 'ready', accepts: [BRIDGE_BACK_FRAME] }) - ) + pair.host.receive(JSON.stringify({ v: BRIDGE_PROTOCOL_VERSION, type: 'ready' })) await pair.flush() expect(pair.host.sendBack()).toBe(true) await pair.flush() @@ -83,18 +81,14 @@ describe('a Back press crossing from the shell to the page', () => { expect(pair.backClaims).toEqual([true]) // The page re-asks, which is what a stale `state` frame makes it do; the host drops the claim // answering it, and the page's re-assert is what puts the two back in step. - pair.host.receive( - JSON.stringify({ v: BRIDGE_PROTOCOL_VERSION, type: 'ready', accepts: [BRIDGE_BACK_FRAME] }) - ) + pair.host.receive(JSON.stringify({ v: BRIDGE_PROTOCOL_VERSION, type: 'ready' })) await pair.flush() expect(pair.backClaims).toEqual([true, false, true]) }) it('says nothing again when this document is holding nothing', async () => { const pair = await opened() - pair.host.receive( - JSON.stringify({ v: BRIDGE_PROTOCOL_VERSION, type: 'ready', accepts: [BRIDGE_BACK_FRAME] }) - ) + pair.host.receive(JSON.stringify({ v: BRIDGE_PROTOCOL_VERSION, type: 'ready' })) await pair.flush() expect(notifies(pair)).toEqual([]) expect(pair.backClaims).toEqual([]) @@ -111,66 +105,22 @@ describe('a Back press crossing from the shell to the page', () => { }) }) -/** - * Both halves of the mixed-version matrix. The page bundle is served by a desktop that updates - * independently of the installed shell, so one side older than the other is the normal state and - * each direction has to degrade to exactly what Back did before this lane: the navigator pops. - */ -describe('a shell and a page built either side of the Back lane', () => { - it('old shell, new page: the page never posts a claim it was not offered', async () => { - // The `init.accepts` this shell sends, with the claim taken back out of it on the wire — which - // is exactly the frame a shell built before the name would have posted. - const pair = createFakeBridgePortPair({ - rewriteToPage: (json) => { - const frame: Record = JSON.parse(json) - const accepts = frame.accepts - if (frame.type !== 'init' || !Array.isArray(accepts)) { - return json - } - return JSON.stringify({ - ...frame, - accepts: accepts.filter((name) => name !== BRIDGE_BACK_CLAIM_NOTIFY) - }) - } - }) - await pair.flush() - pair.client.claimBack(() => true) - await pair.flush() - expect(notifies(pair)).toEqual([]) - expect(pair.backClaims).toEqual([]) - // And the re-assert is held to the same declaration: a second `init` from a shell that never - // named the claim is still one the page says nothing back to. - pair.host.receive(JSON.stringify({ v: BRIDGE_PROTOCOL_VERSION, type: 'ready' })) - await pair.flush() - expect(notifies(pair)).toEqual([]) - }) - - it('new shell, old page: the shell never sends a press the page would refuse', async () => { +describe('the Back lane with no negotiation', () => { + it('hands a press to any page it serves, whose ready declares nothing', async () => { const pair = await opened() - // The same document reloaded as a build that declares nothing, which is what a released page is. pair.host.receive(JSON.stringify({ v: BRIDGE_PROTOCOL_VERSION, type: 'ready' })) await pair.flush() const before = pair.toPage.length - expect(pair.host.sendBack()).toBe(false) + expect(pair.host.sendBack()).toBe(true) await pair.flush() - expect(pair.toPage).toHaveLength(before) + expect(pair.toPage.length).toBe(before + 1) }) - /** Why that gate has to exist: an older page's reader takes the whole frame down rather than - * ignoring a type it has never heard of. */ - it('a page too old to read the frame refuses it whole', async () => { - const pair = createFakeBridgePortPair({ - rewriteToPage: (json) => - JSON.parse(json).type === BRIDGE_BACK_FRAME ? '{"v":1,"type":"b4ck"}' : json - }) - await pair.flush() - pair.host.receive( - JSON.stringify({ v: BRIDGE_PROTOCOL_VERSION, type: 'ready', accepts: [BRIDGE_BACK_FRAME] }) - ) - await pair.flush() - expect(pair.host.sendBack()).toBe(true) + it('posts the claim to the shell with nothing offered in init', async () => { + const pair = await opened() + pair.client.claimBack(() => true) await pair.flush() - expect(pair.diagnostics).toContainEqual({ kind: 'refused', refusal: 'unrecognised-message' }) - expect(pair.backPops).toEqual([]) + expect(notifies(pair)).toEqual([BRIDGE_BACK_CLAIM_NOTIFY]) + expect(pair.backClaims).toEqual([true]) }) }) diff --git a/mobile/src/mobile-web-shell/bridge/bridge-caps.ts b/mobile/src/mobile-web-shell/bridge/bridge-caps.ts index de7056a9b70a..4e625884b840 100644 --- a/mobile/src/mobile-web-shell/bridge/bridge-caps.ts +++ b/mobile/src/mobile-web-shell/bridge/bridge-caps.ts @@ -138,15 +138,6 @@ export function isBridgeExternalLinkUrl(url: string): boolean { } export const BRIDGE_MAX_PAGE_ROUTES = 64 -/** - * What a page may say it can be sent, bounded the way every other list on the envelope is. - * - * A frame bound and not a vocabulary: the shell acts on the names it knows and ignores the rest, - * which is what lets a newer page declare one an older shell has never heard of. - */ -export const BRIDGE_MAX_PAGE_ACCEPTS = 16 -export const BRIDGE_MAX_PAGE_ACCEPT_CHARS = 64 - /** A host id, its name and its endpoint. Bounded because the page renders all three. */ export const BRIDGE_MAX_HOST_FIELD_CHARS = 1024 diff --git a/mobile/src/mobile-web-shell/bridge/bridge-client-init-handshake.ts b/mobile/src/mobile-web-shell/bridge/bridge-client-init-handshake.ts index 609016f033e4..24060668e24b 100644 --- a/mobile/src/mobile-web-shell/bridge/bridge-client-init-handshake.ts +++ b/mobile/src/mobile-web-shell/bridge/bridge-client-init-handshake.ts @@ -1,8 +1,4 @@ import { BRIDGE_PROTOCOL_VERSION, type BridgeClientMessage } from './bridge-envelope' -import { BRIDGE_BACK_FRAME } from './bridge-page-back' -import { BRIDGE_PAGE_PAINTED } from './bridge-page-painted' -import { BRIDGE_ROUTE_UPDATE_ACCEPT } from './bridge-route-update' -import { BRIDGE_SAFE_AREA_ACCEPT } from './bridge-safe-area-insets' /** The page asks again until the shell answers; a session has no other way to start. */ export const BRIDGE_READY_RETRY_MIN_MS = 50 @@ -53,17 +49,8 @@ export function createBridgeInitHandshake(ask: () => void): BridgeInitHandshake } } -/** - * What the page says on every ask, because the shell reads it off whichever `ready` it answers. - * `accepts` is what this page build can be sent: a second `init` for the session it holds, the - * Back frame, and insets it pads for itself. `reports` runs the other way: what a shell may wait - * for this page to post, and the shell holds a frame over the view until it arrives. - */ +/** What the page says on every ask. It declares nothing: the shell serves no page older than its + * floor, so every page it talks to takes everything the shell sends. */ export function createPageReadyFrame(): Extract { - return { - v: BRIDGE_PROTOCOL_VERSION, - type: 'ready', - accepts: [BRIDGE_ROUTE_UPDATE_ACCEPT, BRIDGE_BACK_FRAME, BRIDGE_SAFE_AREA_ACCEPT], - reports: [BRIDGE_PAGE_PAINTED] - } + return { v: BRIDGE_PROTOCOL_VERSION, type: 'ready' } } diff --git a/mobile/src/mobile-web-shell/bridge/bridge-client-notifications.ts b/mobile/src/mobile-web-shell/bridge/bridge-client-notifications.ts index b900a0957254..993782d8818e 100644 --- a/mobile/src/mobile-web-shell/bridge/bridge-client-notifications.ts +++ b/mobile/src/mobile-web-shell/bridge/bridge-client-notifications.ts @@ -43,8 +43,6 @@ export type BridgeClientNotificationDeps = { isClosed: () => boolean /** What `init.grants.native` named. A grant the shell did not give is a frame it would refuse. */ hasGrant: (name: string) => boolean - /** What `init.accepts` named. The other half of the same read: a capability rather than a grant. */ - shellAccepts: (name: string) => boolean } export type BridgeClientNotifications = { @@ -140,25 +138,12 @@ export function createBridgeClientNotifications( error: captureBridgeError(error) }) }, - // Gated on the shell saying it takes one, not on a grant: `notify` is a closed union, so an - // older shell answers an unknown name with an error frame per mount. Answering nothing, because - // a page that has painted has nothing else to do about a shell that will not hear it. + // Not on a grant: every session takes it, and a page that has painted has nothing else to do. notifyPagePainted: () => { - if (deps.shellAccepts(BRIDGE_PAGE_PAINTED)) { - post({ v: BRIDGE_PROTOCOL_VERSION, type: 'notify', name: BRIDGE_PAGE_PAINTED }) - } + post({ v: BRIDGE_PROTOCOL_VERSION, type: 'notify', name: BRIDGE_PAGE_PAINTED }) }, - // Gated the same way, for the same reason, and answering nothing: a shell that will not hear - // the claim keeps the key, which is what every shell did before this frame existed. notifyBackClaim: (claimed) => { - if (deps.shellAccepts(BRIDGE_BACK_CLAIM_NOTIFY)) { - post({ - v: BRIDGE_PROTOCOL_VERSION, - type: 'notify', - name: BRIDGE_BACK_CLAIM_NOTIFY, - claimed - }) - } + post({ v: BRIDGE_PROTOCOL_VERSION, type: 'notify', name: BRIDGE_BACK_CLAIM_NOTIFY, claimed }) } } } diff --git a/mobile/src/mobile-web-shell/bridge/bridge-client-session.ts b/mobile/src/mobile-web-shell/bridge/bridge-client-session.ts index a8571918b897..09085cb2ec6f 100644 --- a/mobile/src/mobile-web-shell/bridge/bridge-client-session.ts +++ b/mobile/src/mobile-web-shell/bridge/bridge-client-session.ts @@ -36,14 +36,6 @@ export type BridgeShellSession = { /** The allowlisted keys `storage` could not carry because the app's value is over the page's cap * (ruling 33.6). Empty for a shell too old to name them, which is what it was before. */ storageOversize: readonly string[] - /** - * What this shell takes from the page beyond the frames every shell has taken (ruling 34). - * - * Empty for a shell that named none, which is every shell before this field: a page that posts - * one of these to one of those has the whole frame refused as `unrecognised-message`, so the - * check is the page's and it is made from here. - */ - accepts: readonly string[] } /** @@ -66,7 +58,6 @@ export function readShellSession( keyboardInset: message.keyboardInset ?? 0, host: message.host ?? null, storage: message.storage ?? {}, - storageOversize: message.storageOversize ?? [], - accepts: message.accepts ?? [] + storageOversize: message.storageOversize ?? [] } } diff --git a/mobile/src/mobile-web-shell/bridge/bridge-envelope.test.ts b/mobile/src/mobile-web-shell/bridge/bridge-envelope.test.ts index 056dcf7bb180..4542949ac326 100644 --- a/mobile/src/mobile-web-shell/bridge/bridge-envelope.test.ts +++ b/mobile/src/mobile-web-shell/bridge/bridge-envelope.test.ts @@ -34,7 +34,7 @@ import { type BridgeHostMessage, type BridgeReplyPayload } from './bridge-envelope' -import { BRIDGE_BACK_CLAIM_NOTIFY, BRIDGE_BACK_FRAME } from './bridge-page-back' +import { BRIDGE_BACK_CLAIM_NOTIFY } from './bridge-page-back' import { BRIDGE_PAGE_PAINTED } from './bridge-page-painted' const ID = 'AAAAAAAAAAAAAAAAAAAAAA' @@ -89,20 +89,12 @@ function client(fields: Record): Record { describe('client messages', () => { const accepted = [ ['ready', { type: 'ready' }], - ['ready naming what it reports', { type: 'ready', reports: [BRIDGE_PAGE_PAINTED] }], - // A shell with no row for the name reads a report it will never wait on, which is what an - // additive field has to look like in the older direction. - [ - 'ready naming a report this shell does not implement', - { type: 'ready', reports: ['weather'] } - ], ['a page painted notify', { type: 'notify', name: BRIDGE_PAGE_PAINTED }], ['a back claim', { type: 'notify', name: BRIDGE_BACK_CLAIM_NOTIFY, claimed: true }], [ 'a back claim being let go', { type: 'notify', name: BRIDGE_BACK_CLAIM_NOTIFY, claimed: false } ], - ['ready naming what it takes', { type: 'ready', accepts: [BRIDGE_BACK_FRAME] }], ['request without params', { type: 'request', id: ID, method: 'status.get' }], ['request with params', { type: 'request', id: ID, method: 'status.get', params: { a: 1 } }], [ diff --git a/mobile/src/mobile-web-shell/bridge/bridge-envelope.ts b/mobile/src/mobile-web-shell/bridge/bridge-envelope.ts index b85925012d67..d24f1ab599c9 100644 --- a/mobile/src/mobile-web-shell/bridge/bridge-envelope.ts +++ b/mobile/src/mobile-web-shell/bridge/bridge-envelope.ts @@ -27,8 +27,6 @@ import { PAGE_STORAGE_MAX_VALUE_CHARS } from '../page-storage-keys' import { - BRIDGE_MAX_PAGE_ACCEPT_CHARS, - BRIDGE_MAX_PAGE_ACCEPTS, BRIDGE_MAX_PAGE_ROUTES, BRIDGE_MAX_REPLY_PARTS, BRIDGE_MAX_ROUTE_PATHNAME_CHARS, @@ -171,37 +169,7 @@ const replyPartSchema = z.object({ const BridgeClientMessageSchema = z.discriminatedUnion('type', [ z.object({ v: versionSchema, - type: z.literal('ready'), - /** - * What this page can be sent beyond its first `init`; the names and why live in - * `bridge-route-update.ts`, which is the only one there is. - * - * Optional, and safe in both directions without a version bump: a page that sends none is - * never sent a second `init`, and a shell that reads none never sends one. An unknown name is - * accepted by the schema and ignored by the shell, which is what a newer page declaring a - * capability this shell has never implemented has to look like. - */ - accepts: z - .array(z.string().min(1).max(BRIDGE_MAX_PAGE_ACCEPT_CHARS)) - .max(BRIDGE_MAX_PAGE_ACCEPTS) - .optional(), - /** - * What this page will post that the shell may have to wait for, which today is - * `BRIDGE_PAGE_PAINTED` and nothing else. - * - * `accepts` runs the other way and cannot stand in for this: it says what may be sent *to* the - * page. A shell waiting on a frame has to know the page will send one, because the generation - * is served by a desktop that updates independently of the installed shell — an undeclared - * wait would hide a working page built before the frame existed. - * - * Optional and additive in both directions, on the same bounds as `accepts`: a page that - * declares none is waited for by nothing, and an unknown name is a report this shell does not - * act on. - */ - reports: z - .array(z.string().min(1).max(BRIDGE_MAX_PAGE_ACCEPT_CHARS)) - .max(BRIDGE_MAX_PAGE_ACCEPTS) - .optional() + type: z.literal('ready') }), z.object({ v: versionSchema, @@ -283,8 +251,7 @@ const BridgeHostMessageSchema = z.union([ connection: BridgeConnectionSnapshotSchema }), // One Back press, and nothing else: the shell pops what it pushed, so a frame naming where to go - // back to would be naming a screen the page cannot see. Sent only to a page whose `ready` listed - // `BRIDGE_BACK_FRAME`, because an older page's reader refuses the whole frame. + // back to would be naming a screen the page cannot see. z.object({ v: versionSchema, type: z.literal(BRIDGE_BACK_FRAME) }), z.object({ v: versionSchema, @@ -346,19 +313,7 @@ const BridgeHostMessageSchema = z.union([ * behaviour, an older page ignores it. The grant grammar is the manifest's own, so a name the * bundle could not have declared cannot arrive here either. */ - pageRouteGrants: BridgePageRouteGrantsSchema.optional(), - /** - * What this shell accepts from the page beyond the frames every shell has always taken, which - * today is `BRIDGE_ROUTE_PARAM_CLEAR` and nothing else. - * - * The mirror of `ready.accepts`, and optional for the same reason: a shell that sends none is - * never posted a clear, and a page that reads none never posts one. An unknown name is a - * capability this page has never heard of and is ignored. - */ - accepts: z - .array(z.string().min(1).max(BRIDGE_MAX_PAGE_ACCEPT_CHARS)) - .max(BRIDGE_MAX_PAGE_ACCEPTS) - .optional() + pageRouteGrants: BridgePageRouteGrantsSchema.optional() }) ]) diff --git a/mobile/src/mobile-web-shell/bridge/bridge-init-frame.ts b/mobile/src/mobile-web-shell/bridge/bridge-init-frame.ts index c838c5b3b356..c31244c23ac6 100644 --- a/mobile/src/mobile-web-shell/bridge/bridge-init-frame.ts +++ b/mobile/src/mobile-web-shell/bridge/bridge-init-frame.ts @@ -8,10 +8,6 @@ import { type BridgeInitHost, type BridgeInitRoute } from './bridge-envelope' -import { BRIDGE_PAGE_CLIENT_IDENTITY_ACCEPT } from './bridge-page-client-identity' -import { BRIDGE_BACK_CLAIM_NOTIFY } from './bridge-page-back' -import { BRIDGE_PAGE_PAINTED } from './bridge-page-painted' -import { BRIDGE_ROUTE_PARAM_CLEAR } from './bridge-route-update' import { sameSafeAreaInsets, ZERO_SAFE_AREA_INSETS, @@ -34,18 +30,6 @@ export const BRIDGE_NATIVE_GRANTS: readonly string[] = [ ...MOBILE_WEB_SHELL_GRANTS ] -/** - * What this shell accepts from a page beyond the frames every shell has always taken. Additive - * names on an optional list, so no version moves: a page that knows none posts none, one told - * nothing claims no identity, and one told nothing reports no paint. - */ -export const BRIDGE_SHELL_ACCEPTS: readonly string[] = [ - BRIDGE_ROUTE_PARAM_CLEAR, - BRIDGE_PAGE_CLIENT_IDENTITY_ACCEPT, - BRIDGE_PAGE_PAINTED, - BRIDGE_BACK_CLAIM_NOTIFY -] - /** The one frame that starts a session, built in one place so its caps and its grants agree. */ export function createBridgeInitFrame(args: { sessionId: string @@ -64,8 +48,6 @@ export function createBridgeInitFrame(args: { pageRouteGrants?: readonly { pathname: string; grants: readonly string[] }[] /** What this session may do: the protocol's own grant plus what its route declared. */ granted: readonly string[] - /** What this shell takes from the page beyond the frames every shell has taken (ruling 34). */ - accepts?: readonly string[] /** The host the page is showing, minus the credential the bridge already carries for it. */ host: BridgeInitHost /** The allowlisted keys as the app holds them right now. */ @@ -100,11 +82,6 @@ export function createBridgeInitFrame(args: { ? {} : { keyboardInset: args.keyboardInset }), pageRoutes: [...args.pageRoutes], - // Omitted when empty for the reason `storageOversize` is: a shell that declares nothing and - // one that declares an empty list are the same answer to the page's check. - ...(args.accepts === undefined || args.accepts.length === 0 - ? {} - : { accepts: [...args.accepts] }), // Copied entry by entry for the reason the grants are: nothing the shell keeps may be // reachable through a frame it hands out. ...(args.pageRouteGrants === undefined diff --git a/mobile/src/mobile-web-shell/bridge/bridge-notify-grants.ts b/mobile/src/mobile-web-shell/bridge/bridge-notify-grants.ts index d363be3f5fd4..04683d787399 100644 --- a/mobile/src/mobile-web-shell/bridge/bridge-notify-grants.ts +++ b/mobile/src/mobile-web-shell/bridge/bridge-notify-grants.ts @@ -37,11 +37,10 @@ const BRIDGE_NOTIFY_GRANTS: Readonly> = // The protocol's own as well: it spends a request this shell handed the page, on a param closed // to the one the shell hands over, so there is nothing here for a grant to gate. [BRIDGE_ROUTE_PARAM_CLEAR]: null, - // The page reporting on its own document. Nothing here reaches the host or the device, and the - // shell acts on it only for a page that declared it in `ready.reports`. + // The page reporting on its own document. Nothing here reaches the host or the device. [BRIDGE_PAGE_PAINTED]: null, // The page reporting on its own document as well. A claim is not a capability: the shell decides - // whether to hand the key over, and it acts on this only for a page that declared it takes one. + // whether to hand the key over. [BRIDGE_BACK_CLAIM_NOTIFY]: null, navigate: 'navigate', [BRIDGE_NAVIGATE_BACK_NOTIFY]: 'navigate', diff --git a/mobile/src/mobile-web-shell/bridge/bridge-page-back.ts b/mobile/src/mobile-web-shell/bridge/bridge-page-back.ts index 87d08d46d6f6..e7c151f63e45 100644 --- a/mobile/src/mobile-web-shell/bridge/bridge-page-back.ts +++ b/mobile/src/mobile-web-shell/bridge/bridge-page-back.ts @@ -1,12 +1,8 @@ -/** - * The device Back key, in the two places it is named: the page's claim on it, and the frame that - * hands one press over. Negotiated both ways, because each is a closed list on the other side — a - * claim to a shell that never advertised it is an error frame per mount on every shell installed, - * and a `back` to a page that never asked for one is a frame its reader drops. - */ +/** The device Back key, in the two places it is named: the page's claim on it, and the frame that + * hands one press over. */ -/** Page to shell, on `init.accepts`: this document is holding Back, or has let it go. */ +/** Page to shell, a notify: this document is holding Back, or has let it go. */ export const BRIDGE_BACK_CLAIM_NOTIFY = 'back-claim' -/** Shell to page, on `ready.accepts`: one Back press, handed to whoever claimed it. */ +/** Shell to page, a frame: one Back press, handed to whoever claimed it. */ export const BRIDGE_BACK_FRAME = 'back' diff --git a/mobile/src/mobile-web-shell/bridge/bridge-page-client-identity.test.ts b/mobile/src/mobile-web-shell/bridge/bridge-page-client-identity.test.ts index bda9737f02f0..b65a8faeee23 100644 --- a/mobile/src/mobile-web-shell/bridge/bridge-page-client-identity.test.ts +++ b/mobile/src/mobile-web-shell/bridge/bridge-page-client-identity.test.ts @@ -1,7 +1,6 @@ import { describe, expect, it } from 'vitest' import { BRIDGE_PAGE_CLIENT_ID, - BRIDGE_PAGE_CLIENT_IDENTITY_ACCEPT, BridgePageClientIdentityUnavailableError, substituteBridgePageClientIdentity } from './bridge-page-client-identity' @@ -39,7 +38,6 @@ describe('the placeholder a page claims', () => { // The composer's send journal refuses a retained operation whose caller changed, and it has no // expiry. A per-document identity would turn "send it again" into a permanent refusal. expect(BRIDGE_PAGE_CLIENT_ID).toBe('orca-page-client') - expect(BRIDGE_PAGE_CLIENT_IDENTITY_ACCEPT).toBe('page-client-identity') }) it('becomes the device identity in both fields a page carries one in', () => { @@ -184,12 +182,6 @@ describe('the shell substitutes on both doors to the client', () => { } }) }) - - it('tells the page it performs the swap, on a list an older page ignores', () => { - const bridge = harness({ ready: true }) - const init = bridge.frames().find((message) => message.type === 'init') - expect(init?.accepts).toContain(BRIDGE_PAGE_CLIENT_IDENTITY_ACCEPT) - }) }) describe('what the page hears when the shell has no identity', () => { diff --git a/mobile/src/mobile-web-shell/bridge/bridge-page-client-identity.ts b/mobile/src/mobile-web-shell/bridge/bridge-page-client-identity.ts index a23a8b4c319e..44277fa0d244 100644 --- a/mobile/src/mobile-web-shell/bridge/bridge-page-client-identity.ts +++ b/mobile/src/mobile-web-shell/bridge/bridge-page-client-identity.ts @@ -8,9 +8,6 @@ /** What a page puts in `client.id`. Fixed, so a resent message fingerprints the same caller. */ export const BRIDGE_PAGE_CLIENT_ID = 'orca-page-client' -/** `init.accepts` name for a shell that swaps. A page told nothing claims no identity at all. */ -export const BRIDGE_PAGE_CLIENT_IDENTITY_ACCEPT = 'page-client-identity' - /** The two fields a page carries an identity in. `mobileClient` is native chat's spelling. */ const IDENTITY_FIELDS = ['client', 'mobileClient'] as const diff --git a/mobile/src/mobile-web-shell/bridge/bridge-page-painted.ts b/mobile/src/mobile-web-shell/bridge/bridge-page-painted.ts index effa3c07a054..41266b01fe01 100644 --- a/mobile/src/mobile-web-shell/bridge/bridge-page-painted.ts +++ b/mobile/src/mobile-web-shell/bridge/bridge-page-painted.ts @@ -1,6 +1,2 @@ -/** - * The page's first frame, in all three places it is named: `ready.reports`, the notify, and - * `init.accepts`. Negotiated both ways, because the notify union is closed — a report to a shell - * that never advertised it is an error frame per mount on every shell already installed. - */ +/** The notify a page posts when its first frame is on screen; the shell covers the view until it. */ export const BRIDGE_PAGE_PAINTED = 'painted' diff --git a/mobile/src/mobile-web-shell/bridge/bridge-port-pair-test-harness.test.ts b/mobile/src/mobile-web-shell/bridge/bridge-port-pair-test-harness.test.ts index 23eaff973669..ac532410aa03 100644 --- a/mobile/src/mobile-web-shell/bridge/bridge-port-pair-test-harness.test.ts +++ b/mobile/src/mobile-web-shell/bridge/bridge-port-pair-test-harness.test.ts @@ -2,10 +2,6 @@ import { describe, expect, it } from 'vitest' import type { RpcClient } from '../../transport/rpc-client' import type { RpcResponse } from '../../transport/types' import { createBridgePortPair, createFakeBridgePortPair } from './bridge-port-pair-test-harness' -import { BRIDGE_PAGE_CLIENT_IDENTITY_ACCEPT } from './bridge-page-client-identity' -import { BRIDGE_BACK_CLAIM_NOTIFY } from './bridge-page-back' -import { BRIDGE_PAGE_PAINTED } from './bridge-page-painted' -import { BRIDGE_ROUTE_PARAM_CLEAR } from './bridge-route-update' /** Every member of the contract, none of them a fake anything: the pair must carry a plain client. */ function plainShellClient(record: string[]): RpcClient { @@ -46,13 +42,7 @@ describe('the bridge port pair', () => { keyboardInset: 0, host: expect.objectContaining({ id: expect.any(String) }), storage: expect.any(Object), - storageOversize: [], - accepts: [ - BRIDGE_ROUTE_PARAM_CLEAR, - BRIDGE_PAGE_CLIENT_IDENTITY_ACCEPT, - BRIDGE_PAGE_PAINTED, - BRIDGE_BACK_CLAIM_NOTIFY - ] + storageOversize: [] }) }) diff --git a/mobile/src/mobile-web-shell/bridge/bridge-port-pair-test-harness.ts b/mobile/src/mobile-web-shell/bridge/bridge-port-pair-test-harness.ts index d187f8cfd155..1b329207d539 100644 --- a/mobile/src/mobile-web-shell/bridge/bridge-port-pair-test-harness.ts +++ b/mobile/src/mobile-web-shell/bridge/bridge-port-pair-test-harness.ts @@ -60,7 +60,6 @@ export type BridgePortPair = { /** Every claim on the device Back key the host reported, in order. */ readonly backClaims: boolean[] /** What each answered `ready` declared it reports, in order. */ - readonly pageReports: () => readonly (readonly string[])[] /** Every clear the page asked the shell for, in order. */ readonly routeParamClears: () => readonly { param: string; value: string }[] /** Why the host refused to open a session at all, if it did. */ @@ -211,7 +210,6 @@ export function createBridgePortPair( let pageReadies = 0 let pagePaints = 0 /** What each answered `ready` declared it reports, in order. */ - const pageReports: (readonly string[])[] = [] const routeParamClears: { param: string; value: string }[] = [] const routeRefusals: string[] = [] let receiveOnPage: ((json: string) => void) | null = null @@ -256,9 +254,8 @@ export function createBridgePortPair( }), onStorageWrite: (key, value) => storageWrites.push({ key, value }), onPageFault: (error) => pageFaults.push(error), - onPageReady: ({ reports }) => { + onPageReady: () => { pageReadies += 1 - pageReports.push(reports) }, onPagePainted: () => { pagePaints += 1 @@ -301,7 +298,6 @@ export function createBridgePortPair( pageReadyCount: () => pageReadies, pagePaintCount: () => pagePaints, backClaims, - pageReports: () => pageReports, routeParamClears: () => routeParamClears, routeRefusals, async flush(): Promise { diff --git a/mobile/src/mobile-web-shell/bridge/bridge-route-update.test.ts b/mobile/src/mobile-web-shell/bridge/bridge-route-update.test.ts index aaef95a00ffc..ff3b1c0b3bb1 100644 --- a/mobile/src/mobile-web-shell/bridge/bridge-route-update.test.ts +++ b/mobile/src/mobile-web-shell/bridge/bridge-route-update.test.ts @@ -1,7 +1,6 @@ import { describe, expect, it } from 'vitest' import { createFakeBridgePortPair } from './bridge-port-pair-test-harness' import type { BridgeInitRoute } from './bridge-envelope' -import { BRIDGE_ROUTE_UPDATE_ACCEPT } from './bridge-route-update' const SESSION = '/h/host-a/session/wt-1' @@ -79,17 +78,13 @@ describe('a route update over a re-sent init', () => { it('publishes nothing for a re-asked ready that carries the route the page holds', async () => { const pair = await openedOnTheSession() const seen = recordRouteUpdates(pair) - pair.host.receive( - JSON.stringify({ v: 1, type: 'ready', accepts: [BRIDGE_ROUTE_UPDATE_ACCEPT] }) - ) + pair.host.receive(JSON.stringify({ v: 1, type: 'ready' })) await pair.flush() expect(seen).toEqual([]) // And the same ask after a real update still leaves exactly the one delivery behind it. pair.host.publishRoute(sessionRoute('pane-1')) await pair.flush() - pair.host.receive( - JSON.stringify({ v: 1, type: 'ready', accepts: [BRIDGE_ROUTE_UPDATE_ACCEPT] }) - ) + pair.host.receive(JSON.stringify({ v: 1, type: 'ready' })) await pair.flush() expect(seen).toEqual(['pane-1']) }) @@ -114,32 +109,13 @@ describe('a route update over a re-sent init', () => { expect(pair.client.getShellSession()?.storage).toBe(before) }) - /** - * Wire compatibility, the half a schema cannot state: an older page never declares `accepts`, so - * the shell must not post it a second `init`. That page would read one as a replacement and - * settle every request it held; the tap it degrades to losing is what it loses today. - */ - it('sends no second init to a page that never declared it accepts one', async () => { + it('sends the second init to a page whose ready declares nothing', async () => { const pair = await openedOnTheSession() - expect(pair.readToShell().find((frame) => frame.type === 'ready')?.accepts).toContain( - BRIDGE_ROUTE_UPDATE_ACCEPT - ) - // This page, then the same document reloaded as a build that declares nothing -- which is what - // a released page is. The host reads `accepts` off whichever `ready` it last answered. pair.host.receive(JSON.stringify({ v: 1, type: 'ready' })) await pair.flush() const framesBefore = pair.toPage.length pair.host.publishRoute(sessionRoute('pane-1')) await pair.flush() - expect(pair.toPage.length).toBe(framesBefore) - // And the contrast, so the case fails when the gate stops gating rather than when it starts. - pair.host.receive( - JSON.stringify({ v: 1, type: 'ready', accepts: [BRIDGE_ROUTE_UPDATE_ACCEPT] }) - ) - await pair.flush() - const framesAfterReady = pair.toPage.length - pair.host.publishRoute(sessionRoute('pane-2')) - await pair.flush() - expect(pair.toPage.length).toBe(framesAfterReady + 1) + expect(pair.toPage.length).toBe(framesBefore + 1) }) }) diff --git a/mobile/src/mobile-web-shell/bridge/bridge-route-update.ts b/mobile/src/mobile-web-shell/bridge/bridge-route-update.ts index 93e42564424b..1f5d3c00e5ae 100644 --- a/mobile/src/mobile-web-shell/bridge/bridge-route-update.ts +++ b/mobile/src/mobile-web-shell/bridge/bridge-route-update.ts @@ -2,23 +2,15 @@ import { BridgeInitRouteSchema, type BridgeInitRoute } from './bridge-init-route import { shellScreenRouteKey } from '../shell-screen-route' /** - * The one thing a page can say it accepts, which is a second `init` for the session it already has. - * * A notification tap for another pane of the session on screen rewrites one route param of a page * that is already mounted, and the shell has no push lane to deliver it on: `notify` runs * page-to-shell only, and a shell-to-page frame kind would need a capability of its own * (`bridge-audio-verbs.ts` refused one for raw PCM). `init` already carries `route`, is already - * re-sent on every `ready` and is already re-read, so the pane request rides it. - * - * Declared by the page rather than assumed by the shell, in both directions. A page too old to - * name it reads a second `init` as a replacement and settles every request it holds, so a shell - * that sent one unasked would break it; a shell too old to re-send one leaves a newer page exactly - * where it is today. Both degrade to the repeat tap doing nothing, which is what it does now. + * re-sent on every `ready` and is already re-read, so the pane request rides a second `init`. */ -export const BRIDGE_ROUTE_UPDATE_ACCEPT = 'route-update' /** - * The one thing a shell can say it accepts, which is a page erasing a one-shot route param. + * The notify a page posts to erase a one-shot route param. * * The reader erases (ruling 34). A notification tap writes `paneKey` onto the native route, the * shell re-sends `init` for as long as it holds one, and the page — having applied the pane — asks @@ -28,10 +20,6 @@ export const BRIDGE_ROUTE_UPDATE_ACCEPT = 'route-update' * Every one of those is followed by a fresh document's `ready`, answered with the route the shell * holds then. A clear naming a pane the tap has already moved past is refused by the comparison * rather than by a sequence number. - * - * Declared in `init` rather than assumed, in the direction `ready.accepts` runs the other way. No - * shipped shell serves a page, so nothing needs negotiating today; the declaration is here so the - * page's check exists from the first version that can post one. */ export const BRIDGE_ROUTE_PARAM_CLEAR = 'route-param-clear' @@ -67,8 +55,8 @@ export function bridgeRouteMoved( * What a host does with a rewritten route: hold it for the next `init`, send one now, or refuse. * * `hold` and `send` both move what the host will publish, because a page that reloads inside this - * mount must be handed the newest route on its next `ready` even when it is too old to be sent one - * in flight. Only `send` is a frame, and only a frame lets the caller clear the param it delivered. + * mount must be handed the newest route on its next `ready`. Only `send` is a frame, and only a + * frame lets the caller clear the param it delivered. */ export type BridgeRouteUpdate = | { readonly kind: 'send'; readonly route: BridgeInitRoute } @@ -86,8 +74,6 @@ export type BridgeRouteUpdate = export function readBridgeRouteUpdate(args: { held: BridgeInitRoute | null next: BridgeInitRoute - /** What the page's last `ready` declared. Empty for every page built before this existed. */ - accepts: readonly string[] /** Whether this host has a served document that has already had an `init`. */ deliverable: boolean }): BridgeRouteUpdate { @@ -100,6 +86,5 @@ export function readBridgeRouteUpdate(args: { return { kind: 'refuse', issue: 'not-this-screen' } } const moved = bridgeRouteMoved(held, parsed.data) - const sendable = moved && args.deliverable && args.accepts.includes(BRIDGE_ROUTE_UPDATE_ACCEPT) - return { kind: sendable ? 'send' : 'hold', route: parsed.data } + return { kind: moved && args.deliverable ? 'send' : 'hold', route: parsed.data } } diff --git a/mobile/src/mobile-web-shell/bridge/bridge-rpc-client-frames.test.ts b/mobile/src/mobile-web-shell/bridge/bridge-rpc-client-frames.test.ts index 12886c1e27f1..f651e23b080d 100644 --- a/mobile/src/mobile-web-shell/bridge/bridge-rpc-client-frames.test.ts +++ b/mobile/src/mobile-web-shell/bridge/bridge-rpc-client-frames.test.ts @@ -12,10 +12,6 @@ import { BRIDGE_ACK_INTERVAL_FRAMES } from './bridge-client-subscriptions' import { BRIDGE_PROTOCOL_VERSION, type BridgeHostMessage } from './bridge-envelope' -import { BRIDGE_BACK_FRAME } from './bridge-page-back' -import { BRIDGE_PAGE_PAINTED } from './bridge-page-painted' -import { BRIDGE_ROUTE_UPDATE_ACCEPT } from './bridge-route-update' -import { BRIDGE_SAFE_AREA_ACCEPT } from './bridge-safe-area-insets' import { BRIDGE_READY_RETRY_MAX_MS, BRIDGE_READY_RETRY_MIN_MS @@ -43,16 +39,9 @@ afterEach(() => { }) describe('bridge client handshake', () => { - it('asks for a session as soon as it exists, naming what it can be sent and what it reports', () => { + it('asks for a session as soon as it exists, declaring nothing', () => { const page = createPageClient() - expect(page.frames()).toEqual([ - { - v: BRIDGE_PROTOCOL_VERSION, - type: 'ready', - accepts: [BRIDGE_ROUTE_UPDATE_ACCEPT, BRIDGE_BACK_FRAME, BRIDGE_SAFE_AREA_ACCEPT], - reports: [BRIDGE_PAGE_PAINTED] - } - ]) + expect(page.frames()).toEqual([{ v: BRIDGE_PROTOCOL_VERSION, type: 'ready' }]) }) it('keeps asking on a widening backoff until init answers', () => { @@ -145,10 +134,7 @@ describe('bridge client handshake', () => { // And no host and no stored keys, which is what `host-store.web.ts` then answers with. host: null, storage: {}, - storageOversize: [], - // And one that takes nothing from the page beyond the frames every shell has taken, which - // is what stops the page posting an erase it would refuse whole (ruling 34). - accepts: [] + storageOversize: [] }) }) diff --git a/mobile/src/mobile-web-shell/bridge/bridge-rpc-client.ts b/mobile/src/mobile-web-shell/bridge/bridge-rpc-client.ts index 113f381dd2ae..687d26637f71 100644 --- a/mobile/src/mobile-web-shell/bridge/bridge-rpc-client.ts +++ b/mobile/src/mobile-web-shell/bridge/bridge-rpc-client.ts @@ -110,7 +110,6 @@ export type BridgeRpcClient = RpcClient & { /** * Tells the shell this document has a frame on screen, which is the only thing that does: the * shell sees a document commit and a page say `ready`, and neither of those is a painted tree. - * Declared in `ready.reports`, so a shell waiting for it is one this page will answer. */ notifyPagePainted: () => void /** @@ -143,9 +142,8 @@ export type BridgeRpcClient = RpcClient & { * (ruling 34). The reader erases: the shell tracks no delivery, so a request stays on the route * and keeps arriving until the page that applied it says so. * - * False when this shell never declared it takes one, which is every shell older than the field. - * Nothing is owed the caller either way — a clear that did not leave is repaired by the request - * arriving again, which is the same path a lost frame takes. + * False when the frame could not leave. Nothing is owed the caller — a clear that did not leave + * is repaired by the request arriving again, which is the same path a lost frame takes. */ clearRouteParam: (param: BridgeClearableRouteParam, value: string) => boolean } @@ -294,8 +292,7 @@ export function createBridgeRpcClient(options: BridgeRpcClientOptions): BridgeRp subscriptions, report, // Declared here rather than beside the others: the re-assert has to run after the session has - // taken this frame, so the claim's own gate reads this `init`'s `accepts` and a shell that - // never named it still hears nothing. + // taken this frame. acceptInit: (message) => { handshake.stop() shellSession.accept(message) @@ -414,8 +411,7 @@ export function createBridgeRpcClient(options: BridgeRpcClientOptions): BridgeRp send: posted, requireSession, isClosed: () => closed, - hasGrant: (name) => shellSession.current()?.grants.native.includes(name) === true, - shellAccepts: (name) => shellSession.current()?.accepts.includes(name) === true + hasGrant: (name) => shellSession.current()?.grants.native.includes(name) === true }) const unsubscribeFromMessages = options.onMessage(receive) @@ -470,7 +466,6 @@ export function createBridgeRpcClient(options: BridgeRpcClientOptions): BridgeRp onKeyboardInsetUpdate: shellSession.onKeyboardInsetUpdate, getShellSession: shellSession.current, clearRouteParam: (param, value) => - shellSession.current()?.accepts.includes(BRIDGE_ROUTE_PARAM_CLEAR) === true && posted({ v: BRIDGE_PROTOCOL_VERSION, type: 'notify', diff --git a/mobile/src/mobile-web-shell/bridge/bridge-safe-area-insets.ts b/mobile/src/mobile-web-shell/bridge/bridge-safe-area-insets.ts index ada32878371d..67d42c774c4c 100644 --- a/mobile/src/mobile-web-shell/bridge/bridge-safe-area-insets.ts +++ b/mobile/src/mobile-web-shell/bridge/bridge-safe-area-insets.ts @@ -41,10 +41,3 @@ export function sameSafeAreaInsets( left.left === right.left ) } - -/** - * What a page puts in `ready.accepts` to say it pads for the system bars itself. The shell draws - * the WebView edge-to-edge only for such a page: an older page has no reader for the insets and - * would lay its header under the status bar, so it keeps the strips the shell reserves. - */ -export const BRIDGE_SAFE_AREA_ACCEPT = 'safe-area-insets' diff --git a/mobile/src/mobile-web-shell/bridge/page-first-paint-through-the-bridge.test.ts b/mobile/src/mobile-web-shell/bridge/page-first-paint-through-the-bridge.test.ts index 86d5189db5e1..c4962ebe16c6 100644 --- a/mobile/src/mobile-web-shell/bridge/page-first-paint-through-the-bridge.test.ts +++ b/mobile/src/mobile-web-shell/bridge/page-first-paint-through-the-bridge.test.ts @@ -1,37 +1,18 @@ /** - * The paint report end to end, and the three pairings it has to survive: a shell that never - * advertised it, a page that never declared it, and two halves that did both. - * - * Driven through the real port pair rather than a mocked host, because what is worth proving is - * that each half reads the other's word off a real frame rather than assuming it. + * The paint report end to end, driven through the real port pair rather than a mocked host, because + * what is worth proving is that the page's post reaches the shell's cover over a real frame. */ import { describe, expect, it } from 'vitest' import { readFileSync } from 'node:fs' import { join } from 'node:path' import { createFakeRpcClient } from '../bridge-host-test-fakes' import { createFakeBridgePortPair } from './bridge-port-pair-test-harness' -import { BRIDGE_PAGE_PAINTED } from './bridge-page-painted' import { createRouteScreenPaintReporter } from './page-first-paint' -/** One `init` frame with one name taken out of `accepts`, which is what an older shell sends. */ -function stripAccept(json: string, name: string): string { - const frame: unknown = JSON.parse(json) - if (typeof frame !== 'object' || frame === null || !('type' in frame)) { - return json - } - const record: Record = { ...frame } - if (record.type !== 'init' || !Array.isArray(record.accepts)) { - return json - } - record.accepts = record.accepts.filter((entry) => entry !== name) - return JSON.stringify(record) -} - describe('the page telling the shell it has a frame', () => { - it('new shell, new page: declares on ready and posts after the first paint', async () => { + it('posts after the first paint, and not before', async () => { const pair = createFakeBridgePortPair({ rpc: createFakeRpcClient() }) await pair.flush() - expect(pair.pageReports()).toEqual([[BRIDGE_PAGE_PAINTED]]) expect(pair.pagePaintCount()).toBe(0) // The two frames the entry waits out, drained by hand so "after the paint" is a step. @@ -52,31 +33,6 @@ describe('the page telling the shell it has a frame', () => { expect(pair.pagePaintCount()).toBe(1) }) - it('old shell, new page: posts nothing, so no shell is left refusing a frame', async () => { - // Stands for every shell installed before this change: `notify` is a closed union there, so an - // unasked-for report is an error frame per mount rather than a dropped one. - const pair = createFakeBridgePortPair({ - rpc: createFakeRpcClient(), - rewriteToPage: (json) => stripAccept(json, BRIDGE_PAGE_PAINTED) - }) - await pair.flush() - expect(pair.client.getShellSession()?.accepts).not.toContain(BRIDGE_PAGE_PAINTED) - const framesToShell = pair.toShell.length - pair.client.notifyPagePainted() - await pair.flush() - expect(pair.toShell).toHaveLength(framesToShell) - expect(pair.pagePaintCount()).toBe(0) - expect(pair.hostDiagnostics).not.toContainEqual( - expect.objectContaining({ refusal: 'unrecognised-message' }) - ) - }) - - it('advertises the report in init, which is what the page reads before posting one', async () => { - const pair = createFakeBridgePortPair({ rpc: createFakeRpcClient() }) - await pair.flush() - expect(pair.client.getShellSession()?.accepts).toContain(BRIDGE_PAGE_PAINTED) - }) - it('is reported by the page entry, from the effect that runs after the tree commits', () => { // The one call site, pinned: every test above drives the client directly, so a deleted line in // the entry would leave a shell covering a page that has painted and will never say so. diff --git a/mobile/src/mobile-web-shell/mobile-web-shell-back-claim-state.test.ts b/mobile/src/mobile-web-shell/mobile-web-shell-back-claim-state.test.ts index 29c0d802860a..b75cd2b54477 100644 --- a/mobile/src/mobile-web-shell/mobile-web-shell-back-claim-state.test.ts +++ b/mobile/src/mobile-web-shell/mobile-web-shell-back-claim-state.test.ts @@ -13,7 +13,7 @@ describe('the page claiming the device Back key', () => { function claimed(): MobileWebShellStep { return run( readySession().session, - { type: 'page-ready', reports: [], accepts: [] }, + { type: 'page-ready' }, { type: 'page-back-claim', claimed: true } ) } @@ -38,7 +38,7 @@ describe('the page claiming the device Back key', () => { }) it('drops it when the document asks for a session again, so the page has to claim again', () => { - const reasked = run(claimed().session, { type: 'page-ready', reports: [], accepts: [] }) + const reasked = run(claimed().session, { type: 'page-ready' }) expect(shellPageBackClaimed(reasked.session)).toBe(false) }) diff --git a/mobile/src/mobile-web-shell/mobile-web-shell-keyboard-overlay-screen.test.tsx b/mobile/src/mobile-web-shell/mobile-web-shell-keyboard-overlay-screen.test.tsx index 32ff38f30d49..bc0c93968c97 100644 --- a/mobile/src/mobile-web-shell/mobile-web-shell-keyboard-overlay-screen.test.tsx +++ b/mobile/src/mobile-web-shell/mobile-web-shell-keyboard-overlay-screen.test.tsx @@ -31,8 +31,6 @@ import { renderScreen as mountScreen } from './mobile-web-shell-screen-test-harness' import { readBridgeHostMessage } from './bridge/bridge-envelope' -import { BRIDGE_ROUTE_UPDATE_ACCEPT } from './bridge/bridge-route-update' -import { BRIDGE_SAFE_AREA_ACCEPT } from './bridge/bridge-safe-area-insets' import { MobileWebShellScreen } from './MobileWebShellScreen' import type { MobileWebShellSessionState } from './mobile-web-shell-session-contract' import type { ReactTestRenderer } from 'react-test-renderer' @@ -55,16 +53,10 @@ const WINDOW = { top: 44, right: 0, bottom: 8, left: 0 } describe('a page the keyboard covers', () => { async function openPage(sessionId: string) { dependencies.client = createFakeRpcClient() - dependencies.pageOwnsSafeArea = true const tree = await renderScreen(readyState(sessionId)) await act(async () => { byName(tree, 'ShellViewProbe')[0]?.props.onBridgeMessage({ - nativeEvent: { - json: clientFrame({ - type: 'ready', - accepts: [BRIDGE_ROUTE_UPDATE_ACCEPT, BRIDGE_SAFE_AREA_ACCEPT] - }) - } + nativeEvent: { json: clientFrame({ type: 'ready' }) } }) }) const root = () => tree.root.find((node) => node.props.testID === 'mobile-web-shell-ready') diff --git a/mobile/src/mobile-web-shell/mobile-web-shell-safe-area-screen.test.tsx b/mobile/src/mobile-web-shell/mobile-web-shell-safe-area-screen.test.tsx index f502691a8622..446f57b5062c 100644 --- a/mobile/src/mobile-web-shell/mobile-web-shell-safe-area-screen.test.tsx +++ b/mobile/src/mobile-web-shell/mobile-web-shell-safe-area-screen.test.tsx @@ -31,8 +31,6 @@ import { renderScreen as mountScreen } from './mobile-web-shell-screen-test-harness' import { readBridgeHostMessage } from './bridge/bridge-envelope' -import { BRIDGE_ROUTE_UPDATE_ACCEPT } from './bridge/bridge-route-update' -import { BRIDGE_SAFE_AREA_ACCEPT } from './bridge/bridge-safe-area-insets' import { MobileWebShellScreen } from './MobileWebShellScreen' import type { MobileWebShellSessionState } from './mobile-web-shell-session-contract' import type { ReactTestRenderer } from 'react-test-renderer' @@ -47,16 +45,16 @@ beforeEach(() => { }) /** - * A page that pads for the system bars itself gets the whole window, like a native screen: it + * Every page pads for the system bars itself and gets the whole window, like a native screen: it * paints under both bars and its SafeAreaViews pad by the insets `init` carries. */ describe('a page that owns its safe area', () => { - async function openPage(sessionId: string, accepts: readonly string[]) { + async function openPage(sessionId: string) { dependencies.client = createFakeRpcClient() const tree = await renderScreen(readyState(sessionId)) await act(async () => { byName(tree, 'ShellViewProbe')[0]?.props.onBridgeMessage({ - nativeEvent: { json: clientFrame({ type: 'ready', accepts }) } + nativeEvent: { json: clientFrame({ type: 'ready' }) } }) }) const root = () => tree.root.find((node) => node.props.testID === 'mobile-web-shell-ready') @@ -67,10 +65,8 @@ describe('a page that owns its safe area', () => { }) return { tree, root, initInsets } } - const ownedPage = (sessionId: string) => { - dependencies.pageOwnsSafeArea = true - return openPage(sessionId, [BRIDGE_ROUTE_UPDATE_ACCEPT, BRIDGE_SAFE_AREA_ACCEPT]) - } + // A `ready` that declares nothing: every page the shell serves reads the insets. + const ownedPage = openPage const WINDOW = { top: 44, right: 0, bottom: 8, left: 0 } it('draws the view edge-to-edge and hands the page the insets it now sits under', async () => { @@ -84,25 +80,14 @@ describe('a page that owns its safe area', () => { const page = await ownedPage('session-owned-banner') expect(page.root().props.style[1]).toEqual({ paddingTop: 44 }) expect(page.initInsets()).toEqual([{ ...WINDOW, top: 0 }]) + const dismiss = byName(page.tree, 'Pressable').find( + (node) => node.props.accessibilityLabel === 'Dismiss notice' + ) + expect(dismiss).toBeDefined() await act(async () => { - byName(page.tree, 'Pressable') - .find((node) => node.props.accessibilityLabel === 'Dismiss notice') - ?.props.onPress() + dismiss?.props.onPress() }) expect(page.root().props.style[1]).toEqual({ paddingTop: 0 }) expect(page.initInsets()).toEqual([{ ...WINDOW, top: 0 }, WINDOW]) }) - - it('sends no second init to an older page that takes route updates but not insets', async () => { - dependencies.updateNotice = 'update-failed' - const page = await openPage('session-older', [BRIDGE_ROUTE_UPDATE_ACCEPT]) - // Dismissing the banner moves the top inset, which this page does not read. - await act(async () => { - byName(page.tree, 'Pressable') - .find((node) => node.props.accessibilityLabel === 'Dismiss notice') - ?.props.onPress() - }) - expect(page.root().props.style[1]).toEqual({ paddingTop: 44, paddingBottom: 8 }) - expect(page.initInsets()).toHaveLength(1) - }) }) diff --git a/mobile/src/mobile-web-shell/mobile-web-shell-safe-area-state.test.ts b/mobile/src/mobile-web-shell/mobile-web-shell-safe-area-state.test.ts deleted file mode 100644 index 0ea58b85b0be..000000000000 --- a/mobile/src/mobile-web-shell/mobile-web-shell-safe-area-state.test.ts +++ /dev/null @@ -1,34 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { readySession, run } from './mobile-web-shell-session-test-fixtures' -import { BRIDGE_SAFE_AREA_ACCEPT } from './bridge/bridge-safe-area-insets' -import { shellPageOwnsSafeArea } from './page-document-state' - -/** Whether the shell may draw the view edge-to-edge, which only the document on screen can say. */ -describe('the page declaring it pads for the system bars', () => { - const owned = () => - run(readySession().session, { - type: 'page-ready', - reports: [], - accepts: [BRIDGE_SAFE_AREA_ACCEPT] - }) - - it('is read off the ready that declared it', () => { - expect(shellPageOwnsSafeArea(owned().session)).toBe(true) - }) - - it('is false for a page that did not declare it, which is every page before the name', () => { - const older = run(readySession().session, { type: 'page-ready', reports: [], accepts: [] }) - expect(shellPageOwnsSafeArea(older.session)).toBe(false) - }) - - it('is dropped when a replacement document starts, so the next one has to say it again', () => { - expect(shellPageOwnsSafeArea(run(owned().session, { type: 'document-started' }).session)).toBe( - false - ) - }) - - it('is not read once the generation is off screen', () => { - const failed = run(owned().session, { type: 'shell-failed', reason: 'document-load-failed' }) - expect(shellPageOwnsSafeArea(failed.session)).toBe(false) - }) -}) diff --git a/mobile/src/mobile-web-shell/mobile-web-shell-screen-test-harness.tsx b/mobile/src/mobile-web-shell/mobile-web-shell-screen-test-harness.tsx index 5769acc6f291..2abeff8fd96e 100644 --- a/mobile/src/mobile-web-shell/mobile-web-shell-screen-test-harness.tsx +++ b/mobile/src/mobile-web-shell/mobile-web-shell-screen-test-harness.tsx @@ -55,8 +55,6 @@ export type ScreenDependencies = { setScreenOptions: Mock /** Whether the session says the page is holding the device Back key. */ backClaimed: boolean - /** Whether the session says the page pads for the system bars itself. */ - pageOwnsSafeArea: boolean /** What `Platform.OS` answers, which picks the keyboard events. */ platform: 'ios' | 'android' reportPageBackClaim: Mock @@ -114,7 +112,6 @@ export function createScreenDependencies(): ScreenDependencies { backHandlers: new Map(), setScreenOptions: vi.fn(), backClaimed: false, - pageOwnsSafeArea: false, platform: 'ios', reportPageBackClaim: vi.fn(), sendBackDelivers: true, @@ -154,7 +151,6 @@ export function resetScreenDependencies(dependencies: ScreenDependencies): void dependencies.setScreenOptions.mockReset() dependencies.reportPageBackClaim.mockReset() dependencies.backClaimed = false - dependencies.pageOwnsSafeArea = false dependencies.platform = 'ios' dependencies.sendBackDelivers = true dependencies.backSends = 0 diff --git a/mobile/src/mobile-web-shell/mobile-web-shell-screen-test-mocks.tsx b/mobile/src/mobile-web-shell/mobile-web-shell-screen-test-mocks.tsx index c622c77f11d5..1976c3d700f7 100644 --- a/mobile/src/mobile-web-shell/mobile-web-shell-screen-test-mocks.tsx +++ b/mobile/src/mobile-web-shell/mobile-web-shell-screen-test-mocks.tsx @@ -180,8 +180,7 @@ export function screenModuleMocks(dependencies: ScreenDependencies) { reportPageBackClaim: dependencies.reportPageBackClaim, pageReady: dependencies.pageReady, pageFrame: dependencies.pageFrame, - backClaimed: dependencies.backClaimed, - pageOwnsSafeArea: dependencies.pageOwnsSafeArea + backClaimed: dependencies.backClaimed }) }) } diff --git a/mobile/src/mobile-web-shell/mobile-web-shell-session-contract.ts b/mobile/src/mobile-web-shell/mobile-web-shell-session-contract.ts index 98f0df8a9007..bfc8c5f385e9 100644 --- a/mobile/src/mobile-web-shell/mobile-web-shell-session-contract.ts +++ b/mobile/src/mobile-web-shell/mobile-web-shell-session-contract.ts @@ -11,11 +11,6 @@ import type { MobileWebShellUpdateFailureFacts } from './mobile-web-shell-update-failure' -/** What one `ready` declared: what the page will report, and what it can be sent. */ -export type PageReadyDeclaration = { - readonly reports: readonly string[] - readonly accepts: readonly string[] -} /** * Whether the host can be asked anything right now. * @@ -218,12 +213,9 @@ export type MobileWebShellSessionEvent = /** The native view finished a document. Unstamped, like the view's failure and for the same * reason: the view exists only under the generation on screen. */ | { readonly type: 'document-loaded' } - /** - * The page said `ready` over the bridge, which is the only proof its code ran at all, carrying - * what that `ready` declared it reports and accepts. - */ - | ({ readonly type: 'page-ready' } & PageReadyDeclaration) - /** The page has a frame on screen. Only a page that declared it ever sends one. */ + /** The page said `ready` over the bridge, which is the only proof its code ran at all. */ + | { readonly type: 'page-ready' } + /** The page has a frame on screen. */ | { readonly type: 'page-painted' } /** The page is holding the device Back key, or has let it go. The host sends false on its own * for every way a document ends, so this never has to be inferred from silence. */ @@ -251,9 +243,6 @@ export type MobileWebShellSession = { /** Whether the document on screen has spoken over the bridge. Cleared by every new document, * because each one has to prove itself: the last one's word says nothing about this one. */ readonly pageReady: boolean - /** Whether this document said it would report its first paint. Cleared with `pageReady`, and - * false for every page built before the report existed. */ - readonly pageReportsPaint: boolean /** Whether this document has reported a frame on screen. Cleared with `pageReady`. */ readonly pagePainted: boolean /** @@ -264,9 +253,6 @@ export type MobileWebShellSession = { * with it, which is a key that does nothing at all. */ readonly pageBackClaimed: boolean - /** Whether this document pads for the system bars itself, so the view may go edge-to-edge. - * Cleared with `pageReady`, and false for every page built before the declaration existed. */ - readonly pageOwnsSafeArea: boolean /** The gates the current step was taken on; null until the first one arrives. */ readonly gates: MobileWebShellGates | null readonly cached: CachedGeneration | null diff --git a/mobile/src/mobile-web-shell/mobile-web-shell-session.test.ts b/mobile/src/mobile-web-shell/mobile-web-shell-session.test.ts index f88a51e8da79..a0cf5fd07742 100644 --- a/mobile/src/mobile-web-shell/mobile-web-shell-session.test.ts +++ b/mobile/src/mobile-web-shell/mobile-web-shell-session.test.ts @@ -14,7 +14,6 @@ import { LINK_LOST, withoutRecord } from './mobile-web-shell-session-test-fixtures' -import { BRIDGE_PAGE_PAINTED } from './bridge/bridge-page-painted' import { shellPageFrame } from './shell-page-frame' describe('the gates decide whether a step is taken at all', () => { @@ -709,11 +708,7 @@ describe('the page has to speak for the document that loaded', () => { }) it('arms nothing when the page spoke first, because there is nothing left to wait for', () => { - const step = run( - readySession().session, - { type: 'page-ready', reports: [], accepts: [] }, - { type: 'document-loaded' } - ) + const step = run(readySession().session, { type: 'page-ready' }, { type: 'document-loaded' }) expect(step.effects).toEqual([]) expect(step.session.pageReady).toBe(true) }) @@ -737,7 +732,7 @@ describe('the page has to speak for the document that loaded', () => { const step = run( readySession().session, { type: 'document-loaded' }, - { type: 'page-ready', reports: [], accepts: [] }, + { type: 'page-ready' }, { type: 'page-ready-deadline' } ) expect(step.effects).toEqual([]) @@ -756,7 +751,7 @@ describe('the page has to speak for the document that loaded', () => { }) it('makes the second document prove itself, rather than riding the first one word', () => { - const spoken = run(readySession().session, { type: 'page-ready', reports: [], accepts: [] }) + const spoken = run(readySession().session, { type: 'page-ready' }) const remounted = run(spoken.session, { type: 'remounted', sessionId: 'session-two' }) expect(remounted.session.pageReady).toBe(false) expect(run(remounted.session, { type: 'document-loaded' }).effects).toEqual([ @@ -765,11 +760,7 @@ describe('the page has to speak for the document that loaded', () => { }) it('leaves a remounted document its own wait when the first one expires late', () => { - const first = run( - readySession().session, - { type: 'document-loaded' }, - { type: 'page-ready', reports: [], accepts: [] } - ) + const first = run(readySession().session, { type: 'document-loaded' }, { type: 'page-ready' }) const armed = first.session.flow const second = run( first.session, @@ -785,7 +776,7 @@ describe('the page has to speak for the document that loaded', () => { }) it('makes a freshly activated generation prove itself too', () => { - const spoken = run(readySession().session, { type: 'page-ready', reports: [], accepts: [] }) + const spoken = run(readySession().session, { type: 'page-ready' }) const reactivated = run(spoken.session, { type: 'activated', generationDirectory: CACHED.directory, @@ -803,13 +794,8 @@ describe('the page has to speak for the document that loaded', () => { * thing that says the view is worth showing is the page saying so. */ describe('the page reporting a frame on screen', () => { - it('records what the ready declared and keeps the frame covered until the report', () => { - const spoken = run(readySession().session, { - type: 'page-ready', - reports: [BRIDGE_PAGE_PAINTED], - accepts: [] - }) - expect(spoken.session.pageReportsPaint).toBe(true) + it('keeps the frame covered past ready until the report', () => { + const spoken = run(readySession().session, { type: 'page-ready' }) expect(spoken.session.pagePainted).toBe(false) expect(shellPageFrame(spoken.session)).toBe('unpainted') const painted = run(spoken.session, { type: 'page-painted' }) @@ -817,42 +803,15 @@ describe('the page reporting a frame on screen', () => { expect(shellPageFrame(painted.session)).toBe('painted') }) - it('new shell, old page: ignores an undeclared report and uncovers on ready', () => { - const spoken = run(readySession().session, { type: 'page-ready', reports: [], accepts: [] }) - const step = run(spoken.session, { type: 'page-painted' }) - expect(step.session.pagePainted).toBe(false) - // Uncovered anyway: `ready` is the newest word a page built before the report can say. - expect(shellPageFrame(step.session)).toBe('painted') - }) - - it('re-reads the declaration on every ask, because a reload asks again', () => { - const declared = run(readySession().session, { - type: 'page-ready', - reports: [BRIDGE_PAGE_PAINTED], - accepts: [] - }) - const reloaded = run(declared.session, { type: 'page-ready', reports: [], accepts: [] }) - expect(reloaded.session.pageReportsPaint).toBe(false) - }) - it('makes a remounted document report its own frame', () => { - const painted = run( - readySession().session, - { type: 'page-ready', reports: [BRIDGE_PAGE_PAINTED], accepts: [] }, - { type: 'page-painted' } - ) + const painted = run(readySession().session, { type: 'page-ready' }, { type: 'page-painted' }) const remounted = run(painted.session, { type: 'remounted', sessionId: 'session-two' }) expect(remounted.session.pagePainted).toBe(false) - expect(remounted.session.pageReportsPaint).toBe(false) expect(shellPageFrame(remounted.session)).toBe('unpainted') }) it('makes a freshly activated generation report its own frame', () => { - const painted = run( - readySession().session, - { type: 'page-ready', reports: [BRIDGE_PAGE_PAINTED], accepts: [] }, - { type: 'page-painted' } - ) + const painted = run(readySession().session, { type: 'page-ready' }, { type: 'page-painted' }) const reactivated = run(painted.session, { type: 'activated', generationDirectory: CACHED.directory, @@ -862,24 +821,15 @@ describe('the page reporting a frame on screen', () => { elapsedMs: 9 }) expect(reactivated.session.pagePainted).toBe(false) - expect(reactivated.session.pageReportsPaint).toBe(false) }) it('makes the document that replaced a painted one inside this mount report its own frame', () => { - const painted = run( - readySession().session, - { type: 'page-ready', reports: [BRIDGE_PAGE_PAINTED], accepts: [] }, - { type: 'page-painted' } - ) + const painted = run(readySession().session, { type: 'page-ready' }, { type: 'page-painted' }) expect(shellPageFrame(painted.session)).toBe('painted') // No new session and no new generation: the view reloaded under the one already on screen. const restarted = run(painted.session, { type: 'document-started' }) expect(restarted.session.pagePainted).toBe(false) - const reasked = run(restarted.session, { - type: 'page-ready', - reports: [BRIDGE_PAGE_PAINTED], - accepts: [] - }) + const reasked = run(restarted.session, { type: 'page-ready' }) expect(shellPageFrame(reasked.session)).toBe('unpainted') expect(shellPageFrame(run(reasked.session, { type: 'page-painted' }).session)).toBe('painted') }) @@ -888,11 +838,7 @@ describe('the page reporting a frame on screen', () => { const loaded = run(readySession().session, { type: 'document-loaded' }) expect(loaded.effects).toEqual([{ kind: 'await-page-ready' }]) const armed = loaded.session.flow - const spoken = run(loaded.session, { - type: 'page-ready', - reports: [BRIDGE_PAGE_PAINTED], - accepts: [] - }) + const spoken = run(loaded.session, { type: 'page-ready' }) const restarted = run(spoken.session, { type: 'document-started' }) // The replacement is still loading and has said nothing, which is exactly what the retired // document's deadline reads as a document that never loaded. @@ -907,9 +853,9 @@ describe('the page reporting a frame on screen', () => { it('keeps the frame of a document that repeats its own handshake', () => { const painted = run( readySession().session, - { type: 'page-ready', reports: [BRIDGE_PAGE_PAINTED], accepts: [] }, + { type: 'page-ready' }, { type: 'page-painted' }, - { type: 'page-ready', reports: [BRIDGE_PAGE_PAINTED], accepts: [] } + { type: 'page-ready' } ) // The document never restarted, so its frame is still the one on screen. expect(painted.session.pagePainted).toBe(true) @@ -919,8 +865,9 @@ describe('the page reporting a frame on screen', () => { it('records nothing from a page whose generation is no longer on screen', () => { const failed = run(readySession().session, { type: 'shell-failed', - reason: 'render-process-gone' + reason: 'document-load-failed' }) + expect(failed.session.state.kind).not.toBe('ready') expect(run(failed.session, { type: 'page-painted' }).session.pagePainted).toBe(false) }) }) diff --git a/mobile/src/mobile-web-shell/mobile-web-shell-session.ts b/mobile/src/mobile-web-shell/mobile-web-shell-session.ts index 5a0a25b7db68..595e1d92dfdf 100644 --- a/mobile/src/mobile-web-shell/mobile-web-shell-session.ts +++ b/mobile/src/mobile-web-shell/mobile-web-shell-session.ts @@ -39,10 +39,8 @@ export function createMobileWebShellSession(routePathname: string): MobileWebShe retriedOnce: false, remountedOnce: false, pageReady: false, - pageReportsPaint: false, pagePainted: false, pageBackClaimed: false, - pageOwnsSafeArea: false, gates: null, cached: null, updateNotice: null, diff --git a/mobile/src/mobile-web-shell/page-document-state.ts b/mobile/src/mobile-web-shell/page-document-state.ts index 935f201d346f..e2405f24591d 100644 --- a/mobile/src/mobile-web-shell/page-document-state.ts +++ b/mobile/src/mobile-web-shell/page-document-state.ts @@ -1,5 +1,3 @@ -import { BRIDGE_PAGE_PAINTED } from './bridge/bridge-page-painted' -import { BRIDGE_SAFE_AREA_ACCEPT } from './bridge/bridge-safe-area-insets' import type { MobileWebShellSession, MobileWebShellSessionEvent @@ -8,10 +6,8 @@ import type { /** Everything one document told the shell about itself, which the next one has to say again. */ export const CLEAR_PAGE_DOCUMENT_STATE = { pageReady: false, - pageReportsPaint: false, pagePainted: false, - pageBackClaimed: false, - pageOwnsSafeArea: false + pageBackClaimed: false } as const /** The three things a document reports about itself, as the reducer receives them. */ @@ -25,7 +21,7 @@ export type PageDocumentEvent = Extract< * view exists only under the generation on screen. */ export function pageDocumentStatePatch( - session: Pick, + session: Pick, event: PageDocumentEvent ): Partial { if (session.state.kind !== 'ready') { @@ -35,25 +31,8 @@ export function pageDocumentStatePatch( return { pageBackClaimed: event.claimed } } if (event.type === 'page-ready') { - // Re-read on every ask rather than latched: a document that reloads inside this mount asks - // again, and it is the newest ask that says whether a paint report is coming. The key goes with - // it: the host drops the claim on the same `ready`, so a page that still holds one re-claims. - return { - pageReady: true, - pageReportsPaint: event.reports.includes(BRIDGE_PAGE_PAINTED), - pageBackClaimed: false, - pageOwnsSafeArea: event.accepts.includes(BRIDGE_SAFE_AREA_ACCEPT) - } + // The host drops the claim on the same `ready`, so a page that still holds one re-claims. + return { pageReady: true, pageBackClaimed: false } } - // Kept off a page that never said it would report: acting on an unasked-for frame would make - // the wait depend on a name arriving instead of on a claim the page made. - return session.pageReportsPaint ? { pagePainted: true } : {} -} - -/** Whether the shell may draw the view edge-to-edge: gated on `ready` like the Back claim, so a - * declaration never outlives the document on screen. */ -export function shellPageOwnsSafeArea( - session: Pick -): boolean { - return session.state.kind === 'ready' && session.pageOwnsSafeArea + return { pagePainted: true } } diff --git a/mobile/src/mobile-web-shell/shell-keyboard-covers-view-census.test.ts b/mobile/src/mobile-web-shell/shell-keyboard-covers-view-census.test.ts deleted file mode 100644 index 6cbeceac5d19..000000000000 --- a/mobile/src/mobile-web-shell/shell-keyboard-covers-view-census.test.ts +++ /dev/null @@ -1,47 +0,0 @@ -/** - * The shell never resizes the WebView for the keyboard: the keyboard covers the view like a native - * screen and the page lifts by the height `init` carries. The symbols of the retired path (a view - * shortened for pages that could not read the height) are named so a reintroduction goes red. - */ -import { readFileSync } from 'node:fs' -import { relative } from 'node:path' -import { describe, expect, it } from 'vitest' -import { censusSourceFiles } from '../test-support/census-source-files' - -const SHELL_DIR = import.meta.dirname -const RETIRED = - /softwareKeyboardWindowInset|viewShortenedBy|pageReadsKeyboardInset|shellPageReadsKeyboardInset|shellKeyboardGeometry|BRIDGE_KEYBOARD_INSET_ACCEPT|'keyboard-inset'/ -const KEYBOARD_SIZES_VIEW = /\b(padding|margin)?(Bottom|bottom|height|Height)\s*:[^,}\n]*keyboard/i - -/** Lines that bring back the retired path or size a view from the keyboard. */ -export function keyboardResizesView(source: string): number[] { - return source - .split('\n') - .flatMap((line, index) => - RETIRED.test(line) || KEYBOARD_SIZES_VIEW.test(line) ? [index + 1] : [] - ) -} - -describe('the shell and the keyboard', () => { - it('finds the lines it is looking for', () => { - expect(keyboardResizesView('style={{ paddingBottom: keyboardInset }}')).toEqual([1]) - expect(keyboardResizesView(' height: windowHeight - keyboardHeight,')).toEqual([1]) - expect(keyboardResizesView("accepts.includes('keyboard-inset')")).toEqual([1]) - expect(keyboardResizesView('const { viewShortenedBy } = geometry')).toEqual([1]) - expect(keyboardResizesView('{ paddingTop: insets.top, paddingBottom: insets.bottom }')).toEqual( - [] - ) - expect(keyboardResizesView('publishKeyboardInset(keyboardInset)')).toEqual([]) - }) - - it('never sizes the view from the keyboard', () => { - const offenders = censusSourceFiles(SHELL_DIR) - .filter((file) => /\.tsx?$/.test(file) && !/\.test\.tsx?$/.test(file)) - .flatMap((file) => - keyboardResizesView(readFileSync(file, 'utf8')).map( - (line) => `${relative(SHELL_DIR, file)}:${line}` - ) - ) - expect(offenders).toEqual([]) - }) -}) diff --git a/mobile/src/mobile-web-shell/shell-older-page-paths-census.test.ts b/mobile/src/mobile-web-shell/shell-older-page-paths-census.test.ts new file mode 100644 index 000000000000..a1d40ccf49a1 --- /dev/null +++ b/mobile/src/mobile-web-shell/shell-older-page-paths-census.test.ts @@ -0,0 +1,89 @@ +/** + * The shell serves no page older than its floor (`MOBILE_WEB_PAGE_VERSION_FLOOR`), so it keeps no + * path for one: no negotiated `accepts`/`reports`, and no WebView resized for the keyboard. The + * retired names are listed so a reintroduction goes red. + */ +import { readFileSync } from 'node:fs' +import { join, relative } from 'node:path' +import { describe, expect, it } from 'vitest' +import { censusSourceFiles } from '../test-support/census-source-files' + +const MOBILE_DIR = join(import.meta.dirname, '..', '..') +const SHELL_DIR = import.meta.dirname +const RETIRED = new RegExp( + [ + 'softwareKeyboardWindowInset', + 'viewShortenedBy', + 'pageReadsKeyboardInset', + 'shellPageReadsKeyboardInset', + 'shellKeyboardGeometry', + 'BRIDGE_KEYBOARD_INSET_ACCEPT', + 'BRIDGE_ROUTE_UPDATE_ACCEPT', + 'BRIDGE_SAFE_AREA_ACCEPT', + 'BRIDGE_PAGE_CLIENT_IDENTITY_ACCEPT', + 'BRIDGE_SHELL_ACCEPTS', + 'BRIDGE_MAX_PAGE_ACCEPTS', + 'pageReportsPaint', + 'pageOwnsSafeArea', + 'shellPageOwnsSafeArea', + 'shellAccepts', + 'PageReadyDeclaration', + "'keyboard-inset'", + "'route-update'", + "'safe-area-insets'", + "'page-client-identity'" + ].join('|') +) +/** The negotiated fields themselves, in code: a `ready` or `init` declaring what it takes or reports. */ +const NEGOTIATED_FIELD = /\.(accepts|reports)\b|\b(accepts|reports)\??:/ +const COMMENT = /^\s*(\/\/|\*|\/\*)/ +const KEYBOARD_SIZES_VIEW = /\b(padding|margin)?(Bottom|bottom|height|Height)\s*:[^,}\n]*keyboard/i + +/** Lines that bring back a path for an older page, or size the view from the keyboard. */ +export function olderPagePaths(source: string, inShell: boolean): number[] { + return source + .split('\n') + .flatMap((line, index) => + RETIRED.test(line) || + (inShell && + ((NEGOTIATED_FIELD.test(line) && !COMMENT.test(line)) || KEYBOARD_SIZES_VIEW.test(line))) + ? [index + 1] + : [] + ) +} + +function sources(dir: string): string[] { + return censusSourceFiles(dir).filter( + (file) => /\.tsx?$/.test(file) && !/\.test\.tsx?$/.test(file) + ) +} + +describe('the shell and a page older than its floor', () => { + it('finds the lines it is looking for', () => { + expect(olderPagePaths('style={{ paddingBottom: keyboardInset }}', true)).toEqual([1]) + expect(olderPagePaths("accepts.includes('keyboard-inset')", false)).toEqual([1]) + expect(olderPagePaths('if (accepts.includes(BRIDGE_SAFE_AREA_ACCEPT)) {', false)).toEqual([1]) + expect(olderPagePaths(' accepts: z.array(z.string()).optional(),', true)).toEqual([1]) + expect(olderPagePaths('return message.reports ?? []', true)).toEqual([1]) + expect(olderPagePaths('session.pageOwnsSafeArea', false)).toEqual([1]) + expect( + olderPagePaths('{ paddingTop: insets.top, paddingBottom: insets.bottom }', true) + ).toEqual([]) + expect(olderPagePaths('publishKeyboardInset(keyboardInset)', true)).toEqual([]) + // The field rule is the shell's code: elsewhere, and in prose, `accepts` is an ordinary word. + expect(olderPagePaths('gate.accepts(byteCount)', false)).toEqual([]) + expect(olderPagePaths(' // the answer is what the caller reports: a page', true)).toEqual([]) + }) + + it('keeps no path for one anywhere in the app or the page entry', () => { + const offenders = [ + ...sources(join(MOBILE_DIR, 'src')), + ...sources(join(MOBILE_DIR, 'web-entry')) + ].flatMap((file) => + olderPagePaths(readFileSync(file, 'utf8'), file.startsWith(SHELL_DIR)).map( + (line) => `${relative(MOBILE_DIR, file)}:${line}` + ) + ) + expect(offenders).toEqual([]) + }) +}) diff --git a/mobile/src/mobile-web-shell/shell-page-frame.test.ts b/mobile/src/mobile-web-shell/shell-page-frame.test.ts index 243f5763d771..8c4d7b5b6d87 100644 --- a/mobile/src/mobile-web-shell/shell-page-frame.test.ts +++ b/mobile/src/mobile-web-shell/shell-page-frame.test.ts @@ -1,5 +1,4 @@ import { describe, expect, it } from 'vitest' -import { BRIDGE_PAGE_PAINTED } from './bridge/bridge-page-painted' import type { MobileWebShellSessionState } from './mobile-web-shell-session-contract' import { shellPageFrame } from './shell-page-frame' @@ -12,18 +11,8 @@ const READY: MobileWebShellSessionState = { elapsedMs: 1 } -function frame(patch: { - state?: MobileWebShellSessionState - pageReady?: boolean - pageReportsPaint?: boolean - pagePainted?: boolean -}) { - return shellPageFrame({ - state: patch.state ?? READY, - pageReady: patch.pageReady ?? false, - pageReportsPaint: patch.pageReportsPaint ?? false, - pagePainted: patch.pagePainted ?? false - }) +function frame(patch: { state?: MobileWebShellSessionState; pagePainted?: boolean }) { + return shellPageFrame({ state: patch.state ?? READY, pagePainted: patch.pagePainted ?? false }) } describe('how long the shell keeps its own frame up', () => { @@ -38,33 +27,13 @@ describe('how long the shell keeps its own frame up', () => { } }) - it('covers a mounted view that has said nothing, which is the whole of the page boot', () => { + it('covers a mounted view until the page reports a frame, handshake or not', () => { + // `ready` is posted before the tree is built, so the view is mounted, empty and showing the + // surface behind it for every frame between the two. expect(frame({})).toBe('unpainted') }) - it('keeps covering a page that has handshaken and not yet painted', () => { - // The gap this exists for: `ready` is posted before the tree is built, so the view is mounted, - // empty and showing the surface behind it for every frame between the two. - expect(frame({ pageReady: true, pageReportsPaint: true })).toBe('unpainted') - }) - - it('new shell, new page: uncovers on the page reporting a frame', () => { - expect(frame({ pageReady: true, pageReportsPaint: true, pagePainted: true })).toBe('painted') - }) - - it('new shell, old page: uncovers on ready, the newest word that page will ever say', () => { - // A generation served by a desktop built before the report exists. Waiting on a frame it - // cannot send would hide a working workspace for the life of the document. - expect(frame({ pageReady: true, pageReportsPaint: false })).toBe('painted') - }) - - it('reads the declaration off the list the page sent, not off the shell', () => { - // The name is what the page puts in `ready.reports`, so the frame follows that list and not a - // flag the shell set: a list without it is a page whose newest word is `ready`. - const declared = [BRIDGE_PAGE_PAINTED].includes(BRIDGE_PAGE_PAINTED) - expect(frame({ pageReady: true, pageReportsPaint: declared })).toBe('unpainted') - expect( - frame({ pageReady: true, pageReportsPaint: ['other'].includes(BRIDGE_PAGE_PAINTED) }) - ).toBe('painted') + it('uncovers on the page reporting a frame', () => { + expect(frame({ pagePainted: true })).toBe('painted') }) }) diff --git a/mobile/src/mobile-web-shell/shell-page-frame.ts b/mobile/src/mobile-web-shell/shell-page-frame.ts index 02d870a0f489..45094d9d0a0b 100644 --- a/mobile/src/mobile-web-shell/shell-page-frame.ts +++ b/mobile/src/mobile-web-shell/shell-page-frame.ts @@ -7,19 +7,12 @@ import type { MobileWebShellSession } from './mobile-web-shell-session-contract' */ export type ShellPageFrame = 'pending' | 'unpainted' | 'painted' -/** - * Bounded by the page's declaration, never by a timer. A page that declared none is one served by - * a desktop older than the report, and `ready` is the newest thing it will ever say: waiting on a - * word it cannot speak would hide a working workspace for the life of the document. - */ +/** Up until the page reports a frame of its own; every page the shell serves reports one. */ export function shellPageFrame( - session: Pick + session: Pick ): ShellPageFrame { if (session.state.kind !== 'ready') { return 'pending' } - if (session.pagePainted) { - return 'painted' - } - return session.pageReportsPaint || !session.pageReady ? 'unpainted' : 'painted' + return session.pagePainted ? 'painted' : 'unpainted' } diff --git a/mobile/src/mobile-web-shell/use-mobile-web-shell-bridge.test.ts b/mobile/src/mobile-web-shell/use-mobile-web-shell-bridge.test.ts index 062a57154683..67bc07fba2c5 100644 --- a/mobile/src/mobile-web-shell/use-mobile-web-shell-bridge.test.ts +++ b/mobile/src/mobile-web-shell/use-mobile-web-shell-bridge.test.ts @@ -339,7 +339,7 @@ describe('the bridge channel', () => { it("hands the page's first paint to the caller that owns the cover over the view", async () => { const mounted = await mount(readyState('session-one')) - await mounted.deliver(clientFrame({ type: 'ready', reports: [BRIDGE_PAGE_PAINTED] })) + await mounted.deliver(clientFrame({ type: 'ready' })) expect(mounted.probe.paints).toBe(0) await mounted.deliver(clientFrame({ type: 'notify', name: BRIDGE_PAGE_PAINTED })) expect(mounted.probe.paints).toBe(1) @@ -658,13 +658,13 @@ describe('client changes', () => { * * A client swapped under a live page is not a new document: the WebView stays mounted, the * session id does not move, and the page neither handshakes again nor hears that anything - * happened. What it declared and what it is holding therefore belong to the session, the way + * happened. What it is holding therefore belongs to the session, the way * `sessionEstablished` already does — a rebuilt host that started over would answer every press * with "I cannot deliver this" and pop the screen out from under an open sheet. */ it('keeps delivering Back to an open sheet after the host is rebuilt under it', async () => { const mounted = await mount(readyState('session-one')) - await mounted.deliver(clientFrame({ type: 'ready', accepts: [BRIDGE_BACK_FRAME] })) + await mounted.deliver(clientFrame({ type: 'ready' })) await mounted.deliver( clientFrame({ type: 'notify', name: BRIDGE_BACK_CLAIM_NOTIFY, claimed: true }) ) @@ -682,47 +682,17 @@ describe('client changes', () => { expect(mounted.frames('session-one').slice(before)).toEqual([{ v: 1, type: BRIDGE_BACK_FRAME }]) }) - /** The other half of the same seed: a page that never said it takes a press is still one the - * rebuilt host will not send to. An empty declaration is a declaration. */ - it('sends nothing after a rebuild to a page that never declared the frame', async () => { - const mounted = await mount(readyState('session-one')) - await mounted.deliver(clientFrame({ type: 'ready' })) - doubles.client = createFakeRpcClient() - await mounted.update(readyState('session-one')) - const before = mounted.frames('session-one').length - expect(mounted.probe.view?.sendBack()).toBe(false) - expect(mounted.frames('session-one')).toHaveLength(before) - }) - - /** The seed is the session's, not the hook's. A different session id is a different document, - * which has declared nothing and is holding nothing until it says so itself. */ - it('carries nothing into a host built for a different session', async () => { - // Both mounts stand for an established session, so the rebuilt host's own pre-handshake gate - // is already open and the declaration is the only thing left that can refuse the press. - const mounted = await mount(readyState('session-one'), true) - await mounted.deliver(clientFrame({ type: 'ready', accepts: [BRIDGE_BACK_FRAME] })) - await mounted.deliver( - clientFrame({ type: 'notify', name: BRIDGE_BACK_CLAIM_NOTIFY, claimed: true }) - ) - // The control: the same rebuild inside the session does keep delivering. - doubles.client = createFakeRpcClient() - await mounted.update(readyState('session-one')) - expect(mounted.probe.view?.sendBack()).toBe(true) - await mounted.update(readyState('session-two')) - expect(mounted.probe.view?.sendBack()).toBe(false) - }) - /** A new document inside the same session still starts over: its own `ready` is what the host * reads, and the seed is not a latch. */ it('drops the carried claim when the next document says ready', async () => { const mounted = await mount(readyState('session-one')) - await mounted.deliver(clientFrame({ type: 'ready', accepts: [BRIDGE_BACK_FRAME] })) + await mounted.deliver(clientFrame({ type: 'ready' })) await mounted.deliver( clientFrame({ type: 'notify', name: BRIDGE_BACK_CLAIM_NOTIFY, claimed: true }) ) doubles.client = createFakeRpcClient() await mounted.update(readyState('session-one')) - await mounted.deliver(clientFrame({ type: 'ready', accepts: [BRIDGE_BACK_FRAME] })) + await mounted.deliver(clientFrame({ type: 'ready' })) expect(mounted.probe.backClaims).toEqual([true, false]) }) diff --git a/mobile/src/mobile-web-shell/use-mobile-web-shell-bridge.ts b/mobile/src/mobile-web-shell/use-mobile-web-shell-bridge.ts index 1be777cfea7c..3a55096ac32b 100644 --- a/mobile/src/mobile-web-shell/use-mobile-web-shell-bridge.ts +++ b/mobile/src/mobile-web-shell/use-mobile-web-shell-bridge.ts @@ -14,10 +14,7 @@ import type { BridgeSessionBack } from './bridge-host-back' import type { BridgeNavigateBackOutcome } from './bridge-host-contract' import type { BridgeNativeVerb } from './bridge/bridge-native-verbs' import type { BridgeErrorCapture } from './bridge/bridge-error-capture' -import type { - MobileWebShellSessionState, - PageReadyDeclaration -} from './mobile-web-shell-session-contract' +import type { MobileWebShellSessionState } from './mobile-web-shell-session-contract' import type { PageHostSnapshot } from './use-page-host-snapshot' import type { PageStorageForInit } from './page-storage-keys' @@ -117,10 +114,9 @@ export type MobileWebShellBridgeArgs = { onStorageWrite: (key: string, value: string | null) => void /** The page could not render the generation on screen. Reported, never recovered from here. */ onPageFault: (error: BridgeErrorCapture) => void - /** The page asked for a session, and what it declared it reports. Reported so the screen can - * stop waiting for it, and so it knows whether a paint report is coming. */ - onPageReady: (ready: PageReadyDeclaration) => void - /** The page has a frame on screen, from a page that said it would report one. */ + /** The page asked for a session. Reported so the screen can stop waiting for it. */ + onPageReady: () => void + /** The page has a frame on screen. */ onPagePainted: () => void /** The page is holding the device Back key, or has let it go. False arrives on its own for * every way a document ends, so no claim outlives the page that made it. */ @@ -227,7 +223,7 @@ export function useMobileWebShellBridge(args: MobileWebShellBridgeArgs): MobileW onRouteParamClear: (param, value) => argsRef.current.onRouteParamClear(param, value), onRouteRefused: (issue) => argsRef.current.onRouteRefused(issue), onBinaryFramesDropped: (total) => argsRef.current.onBinaryFramesDropped(total), - onPageReady: (ready) => argsRef.current.onPageReady(ready), + onPageReady: () => argsRef.current.onPageReady(), onPagePainted: () => argsRef.current.onPagePainted(), onPageBackClaim: (claimed) => argsRef.current.onPageBackClaim(claimed) }) diff --git a/mobile/src/mobile-web-shell/use-mobile-web-shell-session.test.ts b/mobile/src/mobile-web-shell/use-mobile-web-shell-session.test.ts index 469b97571b16..f9ab64437887 100644 --- a/mobile/src/mobile-web-shell/use-mobile-web-shell-session.test.ts +++ b/mobile/src/mobile-web-shell/use-mobile-web-shell-session.test.ts @@ -211,7 +211,7 @@ type Mounted = { /** Whether the page had spoken, as every render of the hook reported it. */ handshakes: () => readonly boolean[] documentLoaded: () => void - pageReady: (reports?: readonly string[]) => void + pageReady: () => void timers: ReturnType } @@ -220,7 +220,7 @@ async function mount(store: GenerationStore): Promise { const handle: { retry: () => void documentLoaded: () => void - pageReady: (ready: { reports: readonly string[]; accepts: readonly string[] }) => void + pageReady: () => void states: MobileWebShellSessionState[] handshakes: boolean[] } = { @@ -263,7 +263,7 @@ async function mount(store: GenerationStore): Promise { states: () => handle.states, handshakes: () => handle.handshakes, documentLoaded: () => handle.documentLoaded(), - pageReady: (reports: readonly string[] = []) => handle.pageReady({ reports, accepts: [] }), + pageReady: () => handle.pageReady(), timers } } diff --git a/mobile/src/mobile-web-shell/use-mobile-web-shell-session.ts b/mobile/src/mobile-web-shell/use-mobile-web-shell-session.ts index da22cd69a2e2..57eea752065e 100644 --- a/mobile/src/mobile-web-shell/use-mobile-web-shell-session.ts +++ b/mobile/src/mobile-web-shell/use-mobile-web-shell-session.ts @@ -21,10 +21,8 @@ import type { MobileWebShellSessionEffect, MobileWebShellSessionEvent, MobileWebShellSessionState, - MobileWebShellUpdateNotice, - PageReadyDeclaration + MobileWebShellUpdateNotice } from './mobile-web-shell-session-contract' -import { shellPageOwnsSafeArea } from './page-document-state' export type MobileWebShellSessionView = { readonly state: MobileWebShellSessionState @@ -42,10 +40,9 @@ export type MobileWebShellSessionView = { readonly reportDocumentStarted: () => void /** The native view finished a document; starts the wait for the page's first word. */ readonly reportDocumentLoaded: () => void - /** The page spoke over the bridge; ends that wait, whichever of the two arrived first. Carries - * what that `ready` declared it reports, which is what says whether a paint is coming. */ - readonly reportPageReady: (ready: PageReadyDeclaration) => void - /** The page has a frame on screen. Ignored for a page that never said it would report one. */ + /** The page spoke over the bridge; ends that wait, whichever of the two arrived first. */ + readonly reportPageReady: () => void + /** The page has a frame on screen. */ readonly reportPagePainted: () => void /** The page took the device Back key, or let it go. */ readonly reportPageBackClaim: (claimed: boolean) => void @@ -62,9 +59,6 @@ export type MobileWebShellSessionView = { /** Whether the shell should take Back off the navigator. Projected for the same reason as * `pageReady`: a claim moves nothing else, so no other value would re-render to carry it. */ readonly backClaimed: boolean - /** Whether the document on screen pads for the system bars itself. Projected for the same - * reason as `backClaimed`. */ - readonly pageOwnsSafeArea: boolean } /** @@ -95,9 +89,6 @@ export function useMobileWebShellSession(args: { const [pageReady, setPageReady] = useState(sessionRef.current.pageReady) const [pageFrame, setPageFrame] = useState(() => shellPageFrame(sessionRef.current)) const [backClaimed, setBackClaimed] = useState(() => shellPageBackClaimed(sessionRef.current)) - const [pageOwnsSafeArea, setPageOwnsSafeArea] = useState(() => - shellPageOwnsSafeArea(sessionRef.current) - ) const hostKey = useMemo(() => deriveHostCacheKey(hostId), [hostId]) const startedAtRef = useRef(runtime.now()) // Bumped by anything that invalidates work in flight; every dispatch out of an effect checks it. @@ -121,7 +112,6 @@ export function useMobileWebShellSession(args: { setPageReady(stepped.session.pageReady) setPageFrame(shellPageFrame(stepped.session)) setBackClaimed(shellPageBackClaimed(stepped.session)) - setPageOwnsSafeArea(shellPageOwnsSafeArea(stepped.session)) for (const effect of stepped.effects) { // Every effect of a step belongs to the flow that step produced, and its result carries that // number back, so a flow the session has since restarted reports into nothing. @@ -281,12 +271,9 @@ export function useMobileWebShellSession(args: { dispatch(epochRef.current, { type: 'document-loaded' }) }, [dispatch]) - const reportPageReady = useCallback( - (ready: PageReadyDeclaration) => { - dispatch(epochRef.current, { type: 'page-ready', ...ready }) - }, - [dispatch] - ) + const reportPageReady = useCallback(() => { + dispatch(epochRef.current, { type: 'page-ready' }) + }, [dispatch]) const reportPagePainted = useCallback(() => { dispatch(epochRef.current, { type: 'page-painted' }) @@ -314,7 +301,6 @@ export function useMobileWebShellSession(args: { reportPageReady, reportPagePainted, reportPageBackClaim, - backClaimed, - pageOwnsSafeArea + backClaimed } } diff --git a/mobile/src/mobile-web-shell/use-shell-page-back.ts b/mobile/src/mobile-web-shell/use-shell-page-back.ts index dd1ac0ac7b1c..ecf8f145f208 100644 --- a/mobile/src/mobile-web-shell/use-shell-page-back.ts +++ b/mobile/src/mobile-web-shell/use-shell-page-back.ts @@ -9,7 +9,7 @@ import { BackHandler, Platform } from 'react-native' * and posted; iOS has none, so what is taken away is the stack's swipe-back gesture — a swipe while * a sheet is open would leave the screen with the sheet still on it. * - * Nothing is registered without a live claim, so a page too old to make one, a shell whose page has + * Nothing is registered without a live claim, so a page holding nothing, a shell whose page has * faulted, and a session between documents all keep today's behaviour: the navigator pops. */ export function useShellPageBack(args: { diff --git a/mobile/src/transport/client-context.web.test.tsx b/mobile/src/transport/client-context.web.test.tsx index c322d07ab7ed..1efc5771dd97 100644 --- a/mobile/src/transport/client-context.web.test.tsx +++ b/mobile/src/transport/client-context.web.test.tsx @@ -2,10 +2,7 @@ import type { ReactElement } from 'react' import { act, create } from 'react-test-renderer' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { BRIDGE_PROTOCOL_VERSION } from '../mobile-web-shell/bridge/bridge-envelope' -import { - BRIDGE_PAGE_CLIENT_ID, - BRIDGE_PAGE_CLIENT_IDENTITY_ACCEPT -} from '../mobile-web-shell/bridge/bridge-page-client-identity' +import { BRIDGE_PAGE_CLIENT_ID } from '../mobile-web-shell/bridge/bridge-page-client-identity' import { createShellPageClient } from '../mobile-web-shell/bridge/page-bootstrap' import type { BridgeRpcClient } from '../mobile-web-shell/bridge/bridge-rpc-client' import type { RpcClientContextValue } from './rpc-client-context-contract' @@ -35,8 +32,7 @@ const INIT = { lastInboundAt: 1800, generation: 5 }, - grants: { rpc: { maxPendingRequests: 64, maxSubscriptions: 32 }, native: [] }, - accepts: [BRIDGE_PAGE_CLIENT_IDENTITY_ACCEPT] + grants: { rpc: { maxPendingRequests: 64, maxSubscriptions: 32 }, native: [] } } /** What the page mounted, and what it holds — the two things the provider decides. */ @@ -172,25 +168,6 @@ describe('the page provider', () => { expect(first).toBe(BRIDGE_PAGE_CLIENT_ID) }) - it('claims nothing at all when the shell never said it performs the swap', () => { - const channel = installChannel() - const client = createShellPageClient() - if (client === null) { - throw new Error('no channel installed') - } - // An `init` that landed, naming no swap — not a client with no session at all, which would - // answer null for a reason that has nothing to do with the capability. - channel.deliver({ ...INIT, accepts: [] }) - act(() => { - create(render(client)) - }) - expect(readContext().getState('host-a')).toBe('connected') - - // An older shell forwards what the page sent, so a placeholder would reach the host and be - // refused as a spoof. Nothing claimed is the honest answer, and it is what shipped before. - expect(readContext().getClientId('host-a')).toBe(null) - }) - it('carries a state change from the shell to the screens watching it', () => { const channel = installChannel() const client = createReadyClient(channel.deliver) diff --git a/mobile/src/transport/client-context.web.tsx b/mobile/src/transport/client-context.web.tsx index 463aff873b21..a1606ba98534 100644 --- a/mobile/src/transport/client-context.web.tsx +++ b/mobile/src/transport/client-context.web.tsx @@ -3,10 +3,7 @@ // side of the bridge already did, and this provider only carries what it holds across the boundary. import { createContext, useContext, useMemo, useRef, type ReactNode } from 'react' import type { BridgeRpcClient } from '../mobile-web-shell/bridge/bridge-rpc-client' -import { - BRIDGE_PAGE_CLIENT_ID, - BRIDGE_PAGE_CLIENT_IDENTITY_ACCEPT -} from '../mobile-web-shell/bridge/bridge-page-client-identity' +import { BRIDGE_PAGE_CLIENT_ID } from '../mobile-web-shell/bridge/bridge-page-client-identity' import type { ConnectionState, HostProfile } from './types' import type { RpcClientContextValue } from './rpc-client-context-contract' @@ -61,17 +58,8 @@ export function RpcClientProvider({ getState: () => client.getState(), // Nothing mounts before `init`, so the page's state is never the unknown this answers null for. getKnownState: () => client.getState(), - /** - * A placeholder the shell swaps for this device's real identity, never the credential itself. - * - * Only when the shell said it performs the swap; a shell that did not leaves this null, which - * is no terminal and no live input, because the session route refuses to subscribe or send - * without one — but a placeholder the host read itself would be refused as a spoof. - */ - getClientId: () => - client.getShellSession()?.accepts.includes(BRIDGE_PAGE_CLIENT_IDENTITY_ACCEPT) === true - ? BRIDGE_PAGE_CLIENT_ID - : null, + /** A placeholder the shell swaps for this device's real identity, never the credential. */ + getClientId: () => BRIDGE_PAGE_CLIENT_ID, getReconnectAttempt: () => client.getReconnectAttempt(), getLastConnectedAt: () => client.getLastConnectedAt(), // The page reaches its host through the shell bridge, which rides whatever path the RN diff --git a/mobile/src/transport/force-reconnect-page-seam.test.tsx b/mobile/src/transport/force-reconnect-page-seam.test.tsx index 8aa8aee556e8..38d07b0d44b3 100644 --- a/mobile/src/transport/force-reconnect-page-seam.test.tsx +++ b/mobile/src/transport/force-reconnect-page-seam.test.tsx @@ -27,8 +27,7 @@ const INIT = { lastInboundAt: 1800, generation: 5 }, - grants: { rpc: { maxPendingRequests: 64, maxSubscriptions: 32 }, native: [] }, - accepts: [] + grants: { rpc: { maxPendingRequests: 64, maxSubscriptions: 32 }, native: [] } } afterEach(() => { From 34a8fdd524b79e212946c639dfbd1a35ec286aa0 Mon Sep 17 00:00:00 2001 From: Jinwoo-H Date: Sun, 27 Sep 2026 19:45:15 -0400 Subject: [PATCH 22/22] test(mobile): read Back notifies past the paint report every page now posts Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb --- .../mobile-web-app-agent-history-render.test.mjs | 11 ++++++++--- .../mobile-web-shell/MobileWebShellScreen.test.tsx | 2 +- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/config/scripts/mobile-web-app-agent-history-render.test.mjs b/config/scripts/mobile-web-app-agent-history-render.test.mjs index 08ce37ea6c97..b1c69a880623 100644 --- a/config/scripts/mobile-web-app-agent-history-render.test.mjs +++ b/config/scripts/mobile-web-app-agent-history-render.test.mjs @@ -9,6 +9,7 @@ import { createBundleServer, installShellDouble, readBridgeFaultGrant, + readBridgePagePainted, readBridgeProtocolVersion, readShellCsp } from './mobile-web-app-render-harness.mjs' @@ -110,6 +111,7 @@ let routeChunks = {} let cspHeader = null let bridgeVersion = null let faultGrant = null +let paintName = null beforeAll(async () => { if (!bundles) { @@ -118,6 +120,7 @@ beforeAll(async () => { cspHeader = await readShellCsp() bridgeVersion = await readBridgeProtocolVersion() faultGrant = await readBridgeFaultGrant() + paintName = await readBridgePagePainted() scratch = await mkdtemp(join(tmpdir(), 'orca-mobile-web-app-agent-history-')) const built = await buildMobileWebAppBundle({ outDir: join(scratch, 'bundle') }) routeChunks = built.routeChunks @@ -227,9 +230,11 @@ async function openRoute(route, awaitText, options = {}) { return opened } -/** Every grant-gated notify the page posted, whole and in order, as the shell received them. */ -function readNotifies(page) { - return page.evaluate(() => globalThis.__orcaRenderCheckNotifies ?? []) +/** Every grant-gated notify the page posted, whole and in order, as the shell received them. The + * paint report is not one: every page posts it once its route screen has a frame. */ +async function readNotifies(page) { + const notifies = await page.evaluate(() => globalThis.__orcaRenderCheckNotifies ?? []) + return notifies.filter((frame) => frame.name !== paintName) } describeRender('the agent-history route in a real browser', () => { diff --git a/mobile/src/mobile-web-shell/MobileWebShellScreen.test.tsx b/mobile/src/mobile-web-shell/MobileWebShellScreen.test.tsx index bc9c4f18da6a..a93f503bd63a 100644 --- a/mobile/src/mobile-web-shell/MobileWebShellScreen.test.tsx +++ b/mobile/src/mobile-web-shell/MobileWebShellScreen.test.tsx @@ -39,7 +39,7 @@ import { textOf, updateScreen as reRenderScreen } from './mobile-web-shell-screen-test-harness' -import { BRIDGE_BACK_CLAIM_NOTIFY, BRIDGE_BACK_FRAME } from './bridge/bridge-page-back' +import { BRIDGE_BACK_CLAIM_NOTIFY } from './bridge/bridge-page-back' import { BRIDGE_PAGE_PAINTED } from './bridge/bridge-page-painted' import { BRIDGE_FAULT_GRANT,