perf(mobile): prewarm one page while Home is shown so opening a page skips the WebView start (#40018)

* perf(mobile): answer a page's ready that arrived before its bridge host

A page's ready can reach the shell before the screen has built its bridge
host (the host waits on the client and the host profile read). It used to
be dropped, so init waited for the page's next retry, up to 2 s later.
Keep the latest ready per session and answer it once the host exists.

* perf(mobile): keep one prewarmed page document while Home is shown

While native Home is on screen, boot one page document for the most
recently connected host with a cached build, parked invisibly in the
window. Opening a page from that build adopts it instead of building a
WebView, which removes the WebView start and script parse from the tap.

The spare is dropped when Home is left without a claim (2 s grace), on
background, memory pressure, its own failure and before the cache deletes
its files. It is never kept beside a shown page, and only phones with
more than 3 GiB of RAM (4 GB phones) get one. A parked page is told to
stop asking for init; the adopting view answers the ready it sent.

Builds on Jinwoo's spare pool and replay work in #32203 and #32204.

Co-authored-by: Jinwoo-H <73622457+Jinwoo-H@users.noreply.github.com>

* fix(mobile): unregister the shell's memory callbacks from the context that registered them

---------

Co-authored-by: Jinwoo-H <73622457+Jinwoo-H@users.noreply.github.com>
This commit is contained in:
Kelvin Amoaba
2026-11-09 02:14:05 +00:00
committed by GitHub
co-authored by Jinwoo-H
parent 49a2163e07
commit a44cb9ac3e
34 changed files with 865 additions and 74 deletions
@@ -3,6 +3,9 @@ package expo.modules.orcamobilewebshell
/** Shared page/native bridge contract; framework-free for off-device checks. */
internal const val MOBILE_WEB_SHELL_BRIDGE_OBJECT = "orcaBridge"
/** Tells a page booted ahead of its screen to stop asking for init; the screen that adopts it answers. */
internal const val MOBILE_WEB_SHELL_PARKED_FRAME = """{"v":1,"type":"parked"}"""
/** Enforce the shared UTF-8 JSON byte ceiling natively, before parsing. */
internal const val MOBILE_WEB_SHELL_BRIDGE_MAX_MESSAGE_BYTES = 640 * 1024
@@ -33,7 +33,7 @@ private class MobileWebShellServed(
val originHost: String
)
/** Where a document's reports go: the view showing it. */
/** Where a document's reports go: the view showing it, or the spare pool while it is parked. */
internal interface MobileWebShellDocumentSink {
fun documentLoadState(payload: Map<String, Any>)
fun documentBridgeMessage(json: String)
@@ -58,6 +58,9 @@ internal class MobileWebShellDocument(private val context: Context) {
@Volatile var webView: WebView? = createWebView()
private set
/** Still showable: not torn down, and no terminal load failure or renderer loss. */
val isUsable: Boolean get() = webView != null && !loadState.isTerminal
/** Apply unordered props together; identical triples do not retry. Recovery requires a remount. */
fun apply(generationDirectory: String, sessionId: String, bridgeEnabled: Boolean) {
val next = MobileWebShellAppliedProps(generationDirectory, sessionId, bridgeEnabled)
@@ -169,6 +172,11 @@ internal class MobileWebShellDocument(private val context: Context) {
proxy.postMessage(json)
}
/** A frame from the shell itself, to the frame that spoke. */
fun postHostFrame(json: String) {
replyProxy?.postMessage(json)
}
/** The view's attach and detach: off-window, the page reads hidden, as a buried WKWebView does on iOS. */
fun resume() {
webView?.onResume()
@@ -26,6 +26,7 @@ internal data class MobileWebShellLoadEmission(
/** Failure is terminal and duplicate reports are dropped: late error-document/rule-list callbacks must never restore ready. Cross-thread readers require volatile state. */
internal class MobileWebShellLoadStateMachine {
private var terminal = false
val isTerminal: Boolean get() = terminal
private var last: MobileWebShellLoadEmission? = null
private var rendererLoss: Pair<Boolean, Boolean>? = null
@@ -0,0 +1,169 @@
package expo.modules.orcamobilewebshell
import android.app.Activity
import android.app.ActivityManager
import android.content.Context
import android.os.Handler
import android.os.Looper
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import java.util.Collections
import java.util.WeakHashMap
/** More than 3 GiB can only come from a phone with 4 GB or more; those report about 3.5 to 3.9 GiB. */
private const val MINIMUM_TOTAL_MEMORY_BYTES = 3L shl 30
/** A claim is adopted on the claiming screen's first commit; this only bounds a screen that never mounts. */
private const val CLAIM_EXPIRY_MS = 10_000L
/** Holds a parked WebView under the app's content: invisible, untouchable and out of accessibility. */
private class MobileWebShellParking(context: Context) : FrameLayout(context) {
init {
alpha = 0f
isFocusable = false
descendantFocusability = ViewGroup.FOCUS_BLOCK_DESCENDANTS
importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS
}
override fun dispatchTouchEvent(event: MotionEvent): Boolean = false
}
/**
* A booted document waiting for a screen. It keeps what the page reported, and the page's ready, for
* the view that adopts it: a parked page stops asking for init, so its ready is answered from here.
*/
internal class MobileWebShellSpare(
activity: Activity,
val directory: String,
val sessionId: String
) : MobileWebShellDocumentSink {
val document = MobileWebShellDocument(activity)
val parking: ViewGroup = MobileWebShellParking(activity)
private val loadStates = mutableListOf<Map<String, Any>>()
private var ready: String? = null
init {
document.sink = this
}
override fun documentLoadState(payload: Map<String, Any>) {
loadStates += payload
if (payload["state"] == "failed") MobileWebShellSparePool.discard(this)
}
/** Before init a page only sends ready, from its first document or one it reloaded. */
override fun documentBridgeMessage(json: String) {
ready = json
document.postHostFrame(MOBILE_WEB_SHELL_PARKED_FRAME)
}
// A parked page has no screen to have been tapped on.
override fun documentExternalNavigation(url: String) = Unit
/** The adopting view sees what a fresh document would have reported, ready last. */
fun handOver(sink: MobileWebShellDocumentSink) {
document.sink = sink
loadStates.forEach(sink::documentLoadState)
ready?.let(sink::documentBridgeMessage)
}
fun destroy() {
document.destroyWebView()
(parking.parent as? ViewGroup)?.removeView(parking)
}
}
/**
* At most one document booted ahead of its screen, only while no page document is shown. Main thread only.
* Parked attached under the content, not detached: a detached WebView took 0.3–1.9 s to paint after 30 s, vs 0.2 s.
*/
internal object MobileWebShellSparePool {
private val main = Handler(Looper.getMainLooper())
private var parked: MobileWebShellSpare? = null
private var claimed: MobileWebShellSpare? = null
private val shown: MutableSet<MobileWebShellDocument> =
Collections.newSetFromMap(WeakHashMap())
/** Whether a spare for [directory] is parked after the call; never on a small phone or beside a page. */
fun prepare(activity: Activity, directory: String, sessionId: String): Boolean {
if (!inForeground() || cannotAffordSpare(activity) || shown.any { it.webView != null }) return false
val current = parked
if (current != null && current.directory == directory && current.document.isUsable) return true
val decor = activity.window?.decorView as? ViewGroup ?: return false
// A claim no view adopted was abandoned; it must not outlive the spare that replaces it.
discardAll()
val spare = MobileWebShellSpare(activity, directory, sessionId)
val webView = spare.document.webView ?: return false
spare.parking.addView(webView, FrameLayout.LayoutParams(MATCH, MATCH))
decor.addView(spare.parking, 0, FrameLayout.LayoutParams(MATCH, MATCH))
parked = spare
spare.document.apply(directory, sessionId, bridgeEnabled = true)
// A load that failed at once has already discarded it.
return parked === spare
}
/** The parked spare's session id for a screen opening [directory], handed out once. */
fun claim(directory: String): String? {
val spare = parked ?: return null
if (spare.directory != directory || !spare.document.isUsable) return null
parked = null
claimed = spare
main.postDelayed({ if (claimed === spare) discard(spare) }, CLAIM_EXPIRY_MS)
return spare.sessionId
}
/** The claimed spare when [sessionId] names it, else a fresh document, which leaves no room for a spare. */
fun document(
context: Context,
sessionId: String,
sink: MobileWebShellDocumentSink
): MobileWebShellDocument {
val spare = claimed
val document = if (spare != null && spare.sessionId == sessionId && spare.document.isUsable) {
claimed = null
spare.document.webView?.let { spare.parking.removeView(it) }
(spare.parking.parent as? ViewGroup)?.removeView(spare.parking)
spare.handOver(sink)
spare.document
} else {
discardAll()
MobileWebShellDocument(context).also { it.sink = sink }
}
shown += document
return document
}
/** Memory pressure, the app leaving the foreground, files going away, or Home without a claim. */
fun discardAll() {
listOfNotNull(parked, claimed).forEach(MobileWebShellSpare::destroy)
parked = null
claimed = null
}
fun discard(spare: MobileWebShellSpare) {
when {
parked === spare -> parked = null
claimed === spare -> claimed = null
else -> return
}
spare.destroy()
}
/** React Native keeps its activity after it stops, so ask the process's own importance. */
private fun inForeground(): Boolean {
val state = ActivityManager.RunningAppProcessInfo()
ActivityManager.getMyMemoryState(state)
return state.importance <= ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND
}
private fun cannotAffordSpare(activity: Activity): Boolean {
val manager = activity.getSystemService(ActivityManager::class.java) ?: return true
val memory = ActivityManager.MemoryInfo().also(manager::getMemoryInfo)
// Android 14 stopped sending RUNNING_LOW trims to foreground apps, so check pressure before booting.
return manager.isLowRamDevice || memory.totalMem <= MINIMUM_TOTAL_MEMORY_BYTES || memory.lowMemory
}
}
private const val MATCH = ViewGroup.LayoutParams.MATCH_PARENT
@@ -19,14 +19,8 @@ internal class OrcaMobileWebShellView(
private var generationDirectory = ""
private var sessionId = ""
private var bridgeEnabled = false
private val document = MobileWebShellDocument(context)
init {
document.sink = this
addView(document.webView, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT))
// Why: Chromium reports an unpaused, never-attached WebView as visible, and a screen pushed under another never attaches.
document.pause()
}
/** Taken on the first prop commit, not in init: the session id says whether a spare was booted for it. */
private var document: MobileWebShellDocument? = null
fun setGenerationDirectory(value: String) {
generationDirectory = value
@@ -41,27 +35,37 @@ internal class OrcaMobileWebShellView(
}
fun propsDidUpdate() {
document.apply(generationDirectory, sessionId, bridgeEnabled)
val current = document ?: hostDocument().also { document = it }
current.apply(generationDirectory, sessionId, bridgeEnabled)
}
private fun hostDocument(): MobileWebShellDocument {
val document = MobileWebShellSparePool.document(context, sessionId, this)
addView(document.webView, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT))
// Why: Chromium reports an unpaused, never-attached WebView as visible, and a screen pushed under another never attaches.
if (!isAttachedToWindow) document.pause()
return document
}
fun postBridgeMessage(json: String) {
document.postBridgeMessage(json)
val current = document ?: throw MobileWebShellBridgeUnavailableException()
current.postBridgeMessage(json)
}
override fun onAttachedToWindow() {
super.onAttachedToWindow()
document.resume()
document?.resume()
}
// Stay paused whenever off-window so the page reads hidden, as a buried WKWebView does on iOS.
override fun onDetachedFromWindow() {
document.pause()
document?.pause()
super.onDetachedFromWindow()
}
/** Expo calls this once React Native is done with the view. */
fun destroyWebView() {
document.destroyWebView()
document?.destroyWebView()
}
override fun documentLoadState(payload: Map<String, Any>) = onLoadState(payload)
@@ -1,17 +1,75 @@
package expo.modules.orcamobilewebshell
import android.content.ActivityNotFoundException
import android.content.ComponentCallbacks2
import android.content.Context
import android.content.Intent
import android.content.res.Configuration
import android.net.Uri
import android.os.Handler
import android.os.Looper
import expo.modules.kotlin.exception.CodedException
import expo.modules.kotlin.exception.Exceptions
import expo.modules.kotlin.functions.Queues
import expo.modules.kotlin.modules.Module
import expo.modules.kotlin.modules.ModuleDefinition
class OrcaMobileWebShellModule : Module() {
private val main = Handler(Looper.getMainLooper())
// Kept so teardown unregisters from the same context after React has let go of it.
private var callbacksContext: Context? = null
// A spare is the first thing to give back: nothing is shown by it. UI_HIDDEN, above RUNNING_LOW, is
// the app leaving the foreground; an activity pause is not, since a notification tap or deep link
// pauses it on the way to the screen that would claim the spare.
private val memoryCallbacks = object : ComponentCallbacks2 {
override fun onTrimMemory(level: Int) {
if (level >= ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW) discardSpare()
}
override fun onConfigurationChanged(newConfig: Configuration) = Unit
@Deprecated("Deprecated in Java")
override fun onLowMemory() = discardSpare()
}
// Callbacks and OnDestroy can run off the main thread, and the pool's WebViews must not.
private fun discardSpare() {
main.post { MobileWebShellSparePool.discardAll() }
}
override fun definition() = ModuleDefinition {
Name("OrcaMobileWebShell")
OnCreate {
callbacksContext = appContext.reactContext?.applicationContext?.also {
it.registerComponentCallbacks(memoryCallbacks)
}
}
OnDestroy {
callbacksContext?.unregisterComponentCallbacks(memoryCallbacks)
callbacksContext = null
discardSpare()
}
OnActivityDestroys {
discardSpare()
}
AsyncFunction("prepareSpareDocument") { directory: String, sessionId: String ->
val activity = appContext.currentActivity ?: return@AsyncFunction false
MobileWebShellSparePool.prepare(activity, directory, sessionId)
}.runOnQueue(Queues.MAIN)
AsyncFunction("claimSpareDocument") { directory: String ->
MobileWebShellSparePool.claim(directory)
}.runOnQueue(Queues.MAIN)
AsyncFunction("discardSpareDocument") {
MobileWebShellSparePool.discardAll()
}.runOnQueue(Queues.MAIN)
// Takes a FileProvider content:// URI; the grant lets the chosen viewer read Orca's cache file.
AsyncFunction("presentPdf") { uri: String ->
val activity = appContext.currentActivity ?: throw Exceptions.MissingActivity()
@@ -5,6 +5,9 @@ enum MobileWebShellBridge {
/// Use the same injected global/handler name on Android and iOS.
static let handlerName = "orcaBridge"
/// Tells a page booted ahead of its screen to stop asking for init; the screen that adopts it answers.
static let parkedFrame = #"{"v":1,"type":"parked"}"#
/// Enforce the shared UTF-8 JSON byte ceiling natively, before parsing.
static let maxMessageByteCount = 640 * 1024
@@ -184,7 +184,7 @@ internal final class MobileWebShellBridgeMessageTooLargeException: GenericExcept
}
}
/// Where a document's reports go: the view showing it.
/// Where a document's reports go: the view showing it, or the spare pool while it is parked.
protocol MobileWebShellDocumentSink: AnyObject {
func documentLoadState(_ payload: [String: Any])
func documentBridgeMessage(_ json: String)
@@ -206,6 +206,7 @@ final class MobileWebShellDocument: NSObject, WKNavigationDelegate, WKUIDelegate
private var pendingDocumentUrl: URL?
private var isolationReady = false
private var isolationFailed = false
private var destroyed = false
private let loadState = MobileWebShellLoadStateMachine()
private var keyboardPreparationPending = false
private var windowObservers: [NSObjectProtocol] = []
@@ -254,6 +255,19 @@ final class MobileWebShellDocument: NSObject, WKNavigationDelegate, WKUIDelegate
}
}
/// Still showable: not torn down, and no terminal load failure or content-process loss.
var isUsable: Bool { !destroyed && !loadState.isTerminal }
/// The spare pool's teardown; the content process goes with the last reference.
func destroy() {
destroyed = true
sink = nil
clearBridgeTarget()
pendingDocumentUrl = nil
webView.stopLoading()
webView.removeFromSuperview()
}
/// Apply unordered props together; identical triples do not retry (remount required).
/// Include bridgeEnabled: document-start scripts require a reload to change.
func apply(generationDirectory: String, sessionId: String, bridgeEnabled: Bool) {
@@ -394,6 +408,12 @@ final class MobileWebShellDocument: NSObject, WKNavigationDelegate, WKUIDelegate
}
}
/// A frame from the shell itself, to the frame that spoke; nothing waits on its delivery.
func postHostFrame(_ json: String) {
guard let frame = bridgeTarget.frame else { return }
webView.callAsyncJavaScript(bridgeDeliver, arguments: ["m": json], in: frame, in: .page) { _ in }
}
private func installNetworkBlock(into controller: WKUserContentController) {
NetworkBlockRuleList.load { [weak self] ruleList in
guard let self else { return }
@@ -28,7 +28,7 @@ struct MobileWebShellLoadEmission: Equatable {
/// Failure is terminal and duplicate reports are dropped: late error-document/rule-list callbacks must never restore ready.
final class MobileWebShellLoadStateMachine {
private var isTerminal = false
private(set) var isTerminal = false
private var last: MobileWebShellLoadEmission?
/// Accept messages only after the current props’ document commits; the replaced same-origin document can still speak before then.
@@ -0,0 +1,150 @@
import UIKit
import WebKit
/// More than 3 GiB can only come from a phone with 4 GB or more; those report about 3.5 to 3.9 GiB.
private let minimumPhysicalMemory: UInt64 = 3 << 30
/// A claim is adopted on the claiming screen's first commit; this only bounds a screen that never mounts.
private let claimExpirySeconds: TimeInterval = 10
/// A booted document waiting for a screen. It keeps what the page reported, and the page's ready, for
/// the view that adopts it: a parked page stops asking for init, so its ready is answered from here.
final class MobileWebShellSpare: MobileWebShellDocumentSink {
let document = MobileWebShellDocument()
let directory: String
let sessionId: String
private var loadStates: [[String: Any]] = []
private var ready: String?
init(directory: String, sessionId: String) {
self.directory = directory
self.sessionId = sessionId
document.sink = self
}
func documentLoadState(_ payload: [String: Any]) {
loadStates.append(payload)
if payload["state"] as? String == "failed" {
MobileWebShellSparePool.shared.discard(self)
}
}
/// Before init a page only sends ready, from its first document or one it reloaded.
func documentBridgeMessage(_ json: String) {
ready = json
document.postHostFrame(MobileWebShellBridge.parkedFrame)
}
/// A parked page has no screen to have been tapped on.
func documentExternalNavigation(_ url: String) {}
/// The adopting view sees what a fresh document would have reported, ready last.
func handOver(to sink: MobileWebShellDocumentSink) {
document.sink = sink
loadStates.forEach(sink.documentLoadState)
if let ready {
sink.documentBridgeMessage(ready)
}
}
}
/// At most one document booted ahead of its screen, only while no page document is shown. Main thread only.
/// Parked in the key window at alpha 0: WebKit suspends an off-window view (0.5–1.3 s to paint after 30 s, vs 0.1 s).
final class MobileWebShellSparePool {
static let shared = MobileWebShellSparePool()
private var parked: MobileWebShellSpare?
private var claimed: MobileWebShellSpare?
private let shown = NSHashTable<MobileWebShellDocument>.weakObjects()
/// Whether a spare for `directory` is parked after the call; never on a small phone, inactive app or shown page.
func prepare(directory: String, sessionId: String) -> Bool {
guard
ProcessInfo.processInfo.physicalMemory > minimumPhysicalMemory,
UIApplication.shared.applicationState == .active,
shown.allObjects.isEmpty,
let window = keyWindow()
else { return false }
if let parked, parked.directory == directory, parked.document.isUsable {
return true
}
// A claim no view adopted was abandoned; it must not outlive the spare that replaces it.
discardAll()
let spare = MobileWebShellSpare(directory: directory, sessionId: sessionId)
let webView = spare.document.webView
webView.alpha = 0
webView.isUserInteractionEnabled = false
webView.accessibilityElementsHidden = true
webView.frame = window.bounds
webView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
window.insertSubview(webView, at: 0)
parked = spare
spare.document.apply(generationDirectory: directory, sessionId: sessionId, bridgeEnabled: true)
// A load that failed at once has already discarded it.
return parked === spare
}
/// The parked spare's session id for a screen opening `directory`, handed out once.
func claim(directory: String) -> String? {
guard let spare = parked, spare.directory == directory, spare.document.isUsable else {
return nil
}
parked = nil
claimed = spare
DispatchQueue.main.asyncAfter(deadline: .now() + claimExpirySeconds) { [weak self, weak spare] in
if let self, let spare, self.claimed === spare {
self.discard(spare)
}
}
return spare.sessionId
}
/// The claimed spare when `sessionId` names it, else a fresh document, which leaves no room for a spare.
func document(for sessionId: String, sink: MobileWebShellDocumentSink) -> MobileWebShellDocument {
let document: MobileWebShellDocument
if let spare = claimed, spare.sessionId == sessionId, spare.document.isUsable {
claimed = nil
document = spare.document
let webView = document.webView
webView.removeFromSuperview()
webView.alpha = 1
webView.isUserInteractionEnabled = true
webView.accessibilityElementsHidden = false
webView.autoresizingMask = []
spare.handOver(to: sink)
} else {
discardAll()
document = MobileWebShellDocument()
document.sink = sink
}
shown.add(document)
return document
}
/// Memory pressure, the app leaving the foreground, files going away, or Home without a claim.
func discardAll() {
for spare in [parked, claimed].compactMap({ $0 }) {
spare.document.destroy()
}
parked = nil
claimed = nil
}
fileprivate func discard(_ spare: MobileWebShellSpare) {
if parked === spare {
parked = nil
} else if claimed === spare {
claimed = nil
} else {
return
}
spare.document.destroy()
}
private func keyWindow() -> UIWindow? {
UIApplication.shared.connectedScenes
.compactMap { $0 as? UIWindowScene }
.flatMap(\.windows)
.first(where: \.isKeyWindow)
}
}
@@ -11,19 +11,27 @@ final class OrcaMobileWebShellView: ExpoView, MobileWebShellDocumentSink,
// The page's own Back: the stack's swipe is off while the page claims Back, and a strip overlay would eat taps.
private let backEdgePan = UIPanGestureRecognizer()
private let document = MobileWebShellDocument()
/// Taken on the first prop commit, not in init: the session id says whether a spare was booted for it.
private var document: MobileWebShellDocument?
private var generationDirectory = ""
private var sessionId = ""
private var bridgeEnabled = false
override func didMoveToWindow() {
super.didMoveToWindow()
document.loadWhenIsolated()
document?.loadWhenIsolated()
}
required init(appContext: AppContext? = nil) {
super.init(appContext: appContext)
document.sink = self
backEdgePan.isEnabled = false
backEdgePan.addTarget(self, action: #selector(handleBackEdgePan(_:)))
backEdgePan.delegate = self
addGestureRecognizer(backEdgePan)
}
private func hostDocument() -> MobileWebShellDocument {
let document = MobileWebShellSparePool.shared.document(for: sessionId, sink: self)
let webView = document.webView
webView.translatesAutoresizingMaskIntoConstraints = false
addSubview(webView)
@@ -33,11 +41,8 @@ final class OrcaMobileWebShellView: ExpoView, MobileWebShellDocumentSink,
webView.leadingAnchor.constraint(equalTo: leadingAnchor),
webView.trailingAnchor.constraint(equalTo: trailingAnchor)
])
backEdgePan.isEnabled = false
backEdgePan.addTarget(self, action: #selector(handleBackEdgePan(_:)))
backEdgePan.delegate = self
addGestureRecognizer(backEdgePan)
webView.scrollView.panGestureRecognizer.require(toFail: backEdgePan)
return document
}
func setBackEdgeSwipe(_ value: Bool) {
@@ -78,6 +83,8 @@ final class OrcaMobileWebShellView: ExpoView, MobileWebShellDocumentSink,
}
func propsDidUpdate() {
let document = self.document ?? hostDocument()
self.document = document
document.apply(
generationDirectory: generationDirectory,
sessionId: sessionId,
@@ -86,6 +93,7 @@ final class OrcaMobileWebShellView: ExpoView, MobileWebShellDocumentSink,
}
func postBridgeMessage(_ json: String, promise: Promise) throws {
guard let document else { throw MobileWebShellBridgeUnavailableException() }
try document.postBridgeMessage(json, promise: promise)
}
@@ -1,12 +1,53 @@
import ExpoModulesCore
import QuickLook
import UIKit
public class OrcaMobileWebShellModule: Module {
private var pdfPreview: MobileWebShellPdfPreview?
private var memoryWarningObserver: NSObjectProtocol?
public func definition() -> ModuleDefinition {
Name("OrcaMobileWebShell")
// A spare is the first thing to give back: nothing is shown by it.
OnCreate {
memoryWarningObserver = NotificationCenter.default.addObserver(
forName: UIApplication.didReceiveMemoryWarningNotification,
object: nil,
queue: .main
) { _ in
MobileWebShellSparePool.shared.discardAll()
}
}
OnDestroy {
if let memoryWarningObserver {
NotificationCenter.default.removeObserver(memoryWarningObserver)
}
DispatchQueue.main.async {
MobileWebShellSparePool.shared.discardAll()
}
}
// Home boots the next one after its next foreground idle.
OnAppEntersBackground {
DispatchQueue.main.async {
MobileWebShellSparePool.shared.discardAll()
}
}
AsyncFunction("prepareSpareDocument") { (directory: String, sessionId: String) -> Bool in
MobileWebShellSparePool.shared.prepare(directory: directory, sessionId: sessionId)
}.runOnQueue(.main)
AsyncFunction("claimSpareDocument") { (directory: String) -> String? in
MobileWebShellSparePool.shared.claim(directory: directory)
}.runOnQueue(.main)
AsyncFunction("discardSpareDocument") {
MobileWebShellSparePool.shared.discardAll()
}.runOnQueue(.main)
// Home calls this once it has a paired host, so a user with nothing to open pays nothing.
Function("warmUp") {
// A second's delay keeps the warm-up off the launch's first frames.
@@ -0,0 +1,27 @@
import { requireOptionalNativeModule } from 'expo-modules-core'
type SpareDocumentModule = {
prepareSpareDocument?: (directory: string, sessionId: string) => Promise<boolean>
claimSpareDocument?: (directory: string) => Promise<string | null>
discardSpareDocument?: () => Promise<void>
}
// A binary built before the spare existed has the module without these functions.
const spareModule = (): SpareDocumentModule | null =>
requireOptionalNativeModule<SpareDocumentModule>('OrcaMobileWebShell')
// Boot a page from `directory` under `sessionId` and park it, invisible, until a screen claims it.
// False when native declined: a phone under 4 GB, the app not active, or a page document shown.
export async function prepareSpareDocument(directory: string, sessionId: string): Promise<boolean> {
return (await spareModule()?.prepareSpareDocument?.(directory, sessionId)) ?? false
}
// The parked spare's session id when it was booted from `directory`, handed out once. The view
// mounted under that id adopts the booted page.
export async function claimSpareDocument(directory: string): Promise<string | null> {
return (await spareModule()?.claimSpareDocument?.(directory)) ?? null
}
export async function discardSpareDocument(): Promise<void> {
await spareModule()?.discardSpareDocument?.()
}
+2
View File
@@ -29,6 +29,7 @@ import { useOpenMobileHostEdit } from '../host-screen/use-open-mobile-host-edit'
import { mobileConnectionPathLabel } from '../transport/connection/mobile-connection-path-label'
import { newWorkspaceOverlayHref } from '../new-workspace/new-workspace-overlay-route'
import { useMobileHomeData } from './use-mobile-home-data'
import { useHomeSparePage } from './use-home-spare-page'
import { HOME_TABS, type HomeTabId } from './tabs/home-tabs'
import { MobileHomeAgentsTab } from './tabs/MobileHomeAgentsTab'
import { MobileHomeAutomationsTab } from './tabs/MobileHomeAutomationsTab'
@@ -45,6 +46,7 @@ export function MobileHomeScreen() {
const t = useMobileTranslation()
useMobileColorScheme()
const data = useMobileHomeData()
useHomeSparePage(data.hostCatalogLoaded ? data.sortedHosts.map((host) => host.id) : [])
const insets = useSafeAreaInsets()
const openMobileHostEdit = useOpenMobileHostEdit()
const openMobileTasks = useOpenMobileTasks()
+48
View File
@@ -0,0 +1,48 @@
import { useFocusEffect } from 'expo-router'
import { useCallback } from 'react'
import { AppState } from 'react-native'
import { setForegroundTimer } from '../mobile-web-shell/foreground-timer'
import {
enterHomeSparePage,
leaveHomeSparePage,
prepareHomeSparePage
} from '../mobile-web-shell/home-spare-page'
import { processGenerationStore } from '../mobile-web-shell/process-generation-store'
// Past Home's first paint and its first reads, so the boot never competes with them.
const HOME_SPARE_IDLE_MS = 1000
const HOST_ID_SEPARATOR = '\n'
// While Home is shown, keep one page booted for the most recently connected host with a cached build.
// Native drops it when the app leaves the foreground, so every return to it arms again.
export function useHomeSparePage(hostIds: readonly string[]): void {
const hosts = hostIds.join(HOST_ID_SEPARATOR)
useFocusEffect(
useCallback(() => {
if (hosts === '') {
return undefined
}
enterHomeSparePage()
let cancelTimer = (): void => undefined
const arm = (): void => {
cancelTimer()
cancelTimer = setForegroundTimer(
() => void prepareHomeSparePage(processGenerationStore(), hosts.split(HOST_ID_SEPARATOR)),
HOME_SPARE_IDLE_MS
)
}
arm()
const subscription = AppState.addEventListener('change', (state) => {
if (state === 'active') {
arm()
}
})
return () => {
subscription.remove()
cancelTimer()
leaveHomeSparePage()
}
}, [hosts])
)
}
@@ -20,6 +20,7 @@ export type BridgeInboundFramePort = {
acceptState: (connection: BridgeConnectionSnapshot) => void
acceptConnectionPath: (connection: BridgeConnectionSnapshot) => void
acceptBack: () => void
acceptParked: () => void
acceptTerminalKey: (key: BridgeTerminalKeyId, inputOwner?: string) => void
}
@@ -66,6 +67,9 @@ export function createBridgeInboundFrameReader(
case 'back':
port.acceptBack()
return
case 'parked':
port.acceptParked()
return
case 'terminalKey':
port.acceptTerminalKey(message.key, message.inputOwner)
return
@@ -236,6 +236,8 @@ const BridgeHostMessageSchema = z.union([
}),
// Back names no destination; only the native stack knows what screen lies beneath.
z.object({ v: versionSchema, type: z.literal(BRIDGE_BACK_FRAME) }),
// Native booted this page ahead of its screen and keeps its ready for the screen that adopts it.
z.object({ v: versionSchema, type: z.literal('parked') }),
// One press on the shell's key rail. Sent only to a page granted the rail, which knows the frame.
z.object({
v: versionSchema,
@@ -198,6 +198,8 @@ export function createBridgeRpcClient(options: BridgeRpcClientOptions): BridgeRp
acceptState: (connection) => acceptState(cache.apply(connection)),
acceptConnectionPath: (connection) => acceptState(cache.applyPath(connection)),
acceptBack: back.press,
// Only a page booted before its screen, with no init yet, is parked; the shell answers its ready on adoption.
acceptParked: handshake.stop,
acceptTerminalKey: (key, inputOwner) => terminalKeys.accept(key, inputOwner)
})
@@ -0,0 +1,27 @@
import { joinUri } from './generation-cache-uri'
import type { GenerationDirectoryEntry, GenerationFileSystem } from './generation-store-file-system'
import { isHostCacheKey } from './host-cache-key'
export const GENERATIONS_DIRECTORY_NAME = 'generations'
// One directory per host under the cache root; anything else there is not the store's.
export async function listGenerationHostDirectories(
fs: GenerationFileSystem
): Promise<readonly GenerationDirectoryEntry[]> {
const entries = await fs.list(fs.rootUri)
return entries.filter((entry) => entry.isDirectory && isHostCacheKey(entry.name))
}
// Count/evict only hosts with generations; evicting staged-only hosts would delete a tree awaiting commit. Sweeps still visit them.
export async function listActivatedGenerationHosts(
fs: GenerationFileSystem
): Promise<readonly string[]> {
const activated: string[] = []
for (const host of await listGenerationHostDirectories(fs)) {
const generations = await fs.list(joinUri(fs.rootUri, host.name, GENERATIONS_DIRECTORY_NAME))
if (generations.some((entry) => entry.isDirectory)) {
activated.push(host.name)
}
}
return activated
}
@@ -544,4 +544,22 @@ describe('an update staged behind a live page', () => {
expect((await relaunched.readActiveGeneration(HOST))?.buildId).toBe(SECOND_BUILD)
expect(await fs.fileExists(`${ROOT}/${HOST}/generations/${SECOND_BUILD}/index.html`)).toBe(true)
})
it('lets a reader of a host’s build go before a commit or a removal deletes it', async () => {
const fs = createFakeFileSystem()
const onDisk: boolean[] = []
let reading = BUILD
const store = createGenerationStore({
fileSystem: fs,
beforeHostFilesDeleted: async (hostKey) => {
onDisk.push(await fs.fileExists(`${ROOT}/${hostKey}/generations/${reading}/manifest.json`))
}
})
await activate(store, HOST)
onDisk.length = 0
await activate(store, HOST, buildResult(SECOND))
reading = SECOND_BUILD
await store.deleteHostCache(HOST)
expect(onDisk).toEqual([true, true])
})
})
+15 -22
View File
@@ -10,7 +10,12 @@ import { MANIFEST_FILE_NAME } from './generation-asset-path'
import { parseGenerationManifest, readWaitingStage } from './generation-manifest-read'
import { reusableAssetsOf, reusableAssetsOfHosts } from './generation-reuse'
import { stagingAssetsOf } from './generation-staging-assets'
import type { GenerationDirectoryEntry, GenerationFileSystem } from './generation-store-file-system'
import type { GenerationFileSystem } from './generation-store-file-system'
import {
GENERATIONS_DIRECTORY_NAME,
listActivatedGenerationHosts,
listGenerationHostDirectories
} from './generation-host-directories'
import { isHostCacheKey } from './host-cache-key'
import type { MobileWebShellUpdateFailure } from './mobile-web-shell-update-failure'
import {
@@ -19,7 +24,6 @@ import {
recordUpdateFailureIn
} from './mobile-web-shell-update-failure-log'
const GENERATIONS_DIRECTORY_NAME = 'generations'
const STAGING_DIRECTORY_NAME = 'tmp'
export const MAX_CACHED_HOSTS = 6
@@ -66,6 +70,8 @@ export type GenerationStore = {
export function createGenerationStore(options: {
fileSystem: GenerationFileSystem
// Runs before a host's built files are deleted, so nothing still reading them outlives them.
beforeHostFilesDeleted?: (hostKey: string) => Promise<void>
}): GenerationStore {
const fs = options.fileSystem
const hostOrder = createGenerationHostOrder(fs)
@@ -87,31 +93,15 @@ export function createGenerationStore(options: {
const stagingRoot = (hostKey: string): string =>
joinUri(hostRoot(hostKey), STAGING_DIRECTORY_NAME)
async function listHostDirectories(): Promise<readonly GenerationDirectoryEntry[]> {
const entries = await fs.list(fs.rootUri)
return entries.filter((entry) => entry.isDirectory && isHostCacheKey(entry.name))
}
// Count/evict only hosts with generations; evicting staged-only hosts would delete a tree awaiting commit. Sweeps still visit them.
async function listActivatedHosts(): Promise<readonly string[]> {
const activated: string[] = []
for (const host of await listHostDirectories()) {
const generations = await fs.list(joinUri(fs.rootUri, host.name, GENERATIONS_DIRECTORY_NAME))
if (generations.some((entry) => entry.isDirectory)) {
activated.push(host.name)
}
}
return activated
}
async function dropHostTree(hostKey: string): Promise<void> {
activeMemo.delete(hostKey)
deferred.drop(hostKey)
await options.beforeHostFilesDeleted?.(hostKey)
await fs.delete(hostRoot(hostKey))
}
async function enforceHostLimit(order: readonly string[]): Promise<void> {
const hosts = await listActivatedHosts()
const hosts = await listActivatedGenerationHosts(fs)
// Unlisted hosts sort first after index loss; keep the just-activated host last so it survives eviction.
const evicted = new Set(
[...hosts]
@@ -238,6 +228,7 @@ export function createGenerationStore(options: {
if (!(await fs.fileExists(joinUri(staged.directory, MANIFEST_FILE_NAME)))) {
throw new Error(`staged generation ${staged.buildId} is no longer on disk`)
}
await options.beforeHostFilesDeleted?.(staged.hostKey)
// Delete old generations before rename: a crash then leaves no activation, whereas renaming first can leave two with no way to choose.
for (const entry of entries) {
await fs.delete(joinUri(generations, entry.name))
@@ -276,7 +267,9 @@ export function createGenerationStore(options: {
async function openReusable(hostKey: string): Promise<MobileWebBundleReusableAssets> {
const hosts = [
hostKey,
...(await listHostDirectories()).map((host) => host.name).filter((key) => key !== hostKey)
...(await listGenerationHostDirectories(fs))
.map((host) => host.name)
.filter((key) => key !== hostKey)
]
// Reuse discovery must not clean up another shell's active or staged files.
const reusable = await reusableAssetsOfHosts(fs, hosts, (key) => readActive(key, false))
@@ -290,7 +283,7 @@ export function createGenerationStore(options: {
return
}
// Interrupted downloads may belong to a host this launch never opens, so visit every host's tmp tree.
for (const host of await listHostDirectories()) {
for (const host of await listGenerationHostDirectories(fs)) {
// Unreadable (undefined) is not corrupt: leave that tree for a later launch rather than fail every read.
const waiting = await readWaitingStage(fs, host.name, stagingRoot(host.name)).catch(
() => undefined
@@ -0,0 +1,91 @@
import {
claimSpareDocument,
discardSpareDocument,
prepareSpareDocument
} from '../../modules/orca-mobile-web-shell/src/spare-document'
import type { GenerationStore } from './generation-store'
import { generationDirectoryPath } from './generation-store-file-system'
import { deriveHostCacheKey } from './host-cache-key'
import { mintShellSessionId } from './shell-session-id'
// A Home entry claims the spare about 0.2 s after the tap on a simulator; a native screen keeps it no longer.
const HOME_SPARE_CLAIM_GRACE_MS = 2000
// What JS last asked native to park, until a claim or a drop. Native may since have dropped it on
// its own (background, memory); this only saves the claim's native round trip when nothing can match.
let parkedDirectory: string | null = null
let dropTimer: ReturnType<typeof setTimeout> | null = null
// A prepare still reading the store when Home goes must not park a spare after the drop ran.
let homeShown = false
function cancelDrop(): void {
if (dropTimer !== null) {
clearTimeout(dropTimer)
dropTimer = null
}
}
// Boot one page from the first of `hostIds` (most recently connected first) that has a cached build.
export async function prepareHomeSparePage(
store: GenerationStore,
hostIds: readonly string[]
): Promise<void> {
try {
for (const hostId of hostIds) {
const hostKey = deriveHostCacheKey(hostId)
const active = await store.readActiveGeneration(hostKey)
if (active === null) {
continue
}
if (!homeShown) {
return
}
const directory = generationDirectoryPath(active.directory)
const prepared = await prepareSpareDocument(directory, mintShellSessionId())
if (prepared && !homeShown) {
await dropHomeSparePage()
} else if (prepared) {
parkedDirectory = directory
}
return
}
} catch {
// A spare only saves time; the next entry boots its own page without one.
}
}
// The spare's session id when Home booted it from `directory`; the view mounted with it adopts that page.
export async function claimHomeSparePage(directory: string): Promise<string | null> {
if (parkedDirectory !== directory) {
return null
}
parkedDirectory = null
cancelDrop()
try {
return await claimSpareDocument(directory)
} catch {
return null
}
}
// Home is shown; a spare still inside the grace after leaving it stays.
export function enterHomeSparePage(): void {
homeShown = true
cancelDrop()
}
// Home lost focus: a page opening from it claims the spare within the grace, anything else drops it.
export function leaveHomeSparePage(): void {
homeShown = false
cancelDrop()
dropTimer = setTimeout(() => {
dropTimer = null
void dropHomeSparePage()
}, HOME_SPARE_CLAIM_GRACE_MS)
}
// Also runs before any host's built files go: that is rare, and a spare must not outlive its files.
export function dropHomeSparePage(): Promise<void> {
parkedDirectory = null
return discardSpareDocument().catch(() => undefined)
}
@@ -165,6 +165,7 @@ async function mountRoute(fileSystem: FakeGenerationFileSystem): Promise<Mounted
runtime: {
createStore: () => createGenerationStore({ fileSystem }),
mintSessionId: () => 'session-id',
claimSpareSessionId: async () => null,
now: () => 0,
setForegroundTimer: () => () => {}
}
@@ -1,12 +1,9 @@
import * as ExpoCrypto from 'expo-crypto'
import { encodeBase64Url } from '../transport/encryption/mobile-session-id-encoding'
import { BRIDGE_READY_RETRY_MAX_MS } from './bridge/bridge-client-init-handshake'
import type { GenerationStore } from './generation-store'
import { processGenerationStore } from './process-generation-store'
import { setForegroundTimer } from './foreground-timer'
// Use 32 random base64url bytes: each mount/remount needs a fresh id for the view’s private origin.
const SESSION_ID_BYTES = 32
import { claimHomeSparePage } from './home-spare-page'
import { mintShellSessionId } from './shell-session-id'
// Allow five ready-backoff ceilings before treating a loaded document as silent; startup import failures may prevent every ready attempt.
export const PAGE_READY_DEADLINE_MS = BRIDGE_READY_RETRY_MAX_MS * 5
@@ -17,6 +14,8 @@ export const DOCUMENT_LOAD_DEADLINE_MS = 20_000
export type MobileWebShellRuntime = {
createStore(): GenerationStore
mintSessionId(): string
// The session id of a page Home booted from this directory, so the view adopts it instead of a new one.
claimSpareSessionId(directory: string): Promise<string | null>
now(): number
// Count only foreground time and return cancellation; tests replace this seam instead of waiting on wall time.
setForegroundTimer(run: () => void, delayMs: number): () => void
@@ -25,7 +24,8 @@ export type MobileWebShellRuntime = {
export function createMobileWebShellRuntime(): MobileWebShellRuntime {
return {
createStore: processGenerationStore,
mintSessionId: () => encodeBase64Url(ExpoCrypto.getRandomBytes(SESSION_ID_BYTES)),
mintSessionId: mintShellSessionId,
claimSpareSessionId: claimHomeSparePage,
now: Date.now,
setForegroundTimer
}
@@ -103,6 +103,7 @@ describe('a download that reuses the cached generation', () => {
runtime: {
createStore: () => store,
mintSessionId: () => 's',
claimSpareSessionId: async () => null,
now: () => 0,
setForegroundTimer: () => () => {}
},
@@ -264,17 +264,20 @@ export async function runShellEffect(
context.manifest.current = null
await (effect.kind === 'download' ? download : stageUpdate)({ ...context, opened })
return
case 'open-generation':
case 'open-generation': {
// A remount mints its own id below; only a first open adopts a page Home booted.
const spare = await runtime.claimSpareSessionId(effect.directory)
send({
type: 'activated',
flow,
generationDirectory: effect.directory,
sessionId: runtime.mintSessionId(),
sessionId: spare ?? runtime.mintSessionId(),
buildId: effect.buildId,
totalBytes: effect.totalBytes,
elapsedMs: runtime.now() - context.startedAt
})
return
}
case 'remount': {
const remount = (): void =>
send({ type: 'remounted', flow, sessionId: runtime.mintSessionId() })
@@ -0,0 +1,40 @@
import { readBridgeClientMessage } from './bridge/bridge-envelope'
import { frameWithoutHostLine } from './shell-bridge-log-lines'
import { recordShellLifecycleLine } from './shell-lifecycle-line-recorder'
export type FrameWithoutHostFacts = { hostId: string; clientReady: boolean; snapshotReady: boolean }
export type PageFramesWithoutHost = {
/** A frame no host serves yet; `facts` is null when a retired session's host is still mounted. */
receive: (sessionId: string, json: string, facts: FrameWithoutHostFacts | null) => void
/** Hands the page's latest ready for this session to the host just built for it, once. */
replayReady: (sessionId: string, host: { receive: (json: string) => void }) => void
}
// Keep the ready instead of dropping it, so init does not wait on the page's 50 ms to 2 s backoff.
export function createPageFramesWithoutHost(): PageFramesWithoutHost {
let loggedSessionId: string | null = null
let ready: { sessionId: string; json: string } | null = null
return {
receive: (sessionId, json, facts) => {
if (facts !== null && loggedSessionId !== sessionId) {
loggedSessionId = sessionId
recordShellLifecycleLine(facts.hostId, frameWithoutHostLine(facts))
}
const read = readBridgeClientMessage(json)
if (read.ok && read.message.type === 'ready') {
ready = { sessionId, json }
} else if (read.ok && read.message.type === 'close') {
// The document that asked is gone, so its ready must not be answered.
ready = null
}
},
replayReady: (sessionId, host) => {
const kept = ready
ready = null
if (kept?.sessionId === sessionId) {
host.receive(kept.json)
}
}
}
}
@@ -1,11 +1,15 @@
import { createGenerationStore, type GenerationStore } from './generation-store'
import { createExpoGenerationFileSystem } from './generation-store-file-system'
import { dropHomeSparePage } from './home-spare-page'
let processStore: GenerationStore | null = null
// Share one store queue across native callers so host removal cannot interleave with generation/index/failure-log writes.
export function processGenerationStore(): GenerationStore {
processStore ??= createGenerationStore({ fileSystem: createExpoGenerationFileSystem() })
processStore ??= createGenerationStore({
fileSystem: createExpoGenerationFileSystem(),
beforeHostFilesDeleted: dropHomeSparePage
})
return processStore
}
@@ -0,0 +1,9 @@
import * as ExpoCrypto from 'expo-crypto'
import { encodeBase64Url } from '../transport/encryption/mobile-session-id-encoding'
// Use 32 random base64url bytes: each mount/remount needs a fresh id for the view’s private origin.
const SESSION_ID_BYTES = 32
export function mintShellSessionId(): string {
return encodeBase64Url(ExpoCrypto.getRandomBytes(SESSION_ID_BYTES))
}
@@ -14,6 +14,7 @@ import {
import type { BridgeErrorCapture } from './bridge/bridge-error-capture'
import type { MobileWebShellSessionState } from './mobile-web-shell-session-contract'
import type { FakeRpcClient } from './bridge-host-test-fakes'
import type { PageHostSnapshot } from './use-page-host-snapshot'
const doubles = vi.hoisted((): { client: FakeRpcClient | null } => ({ client: null }))
@@ -82,6 +83,7 @@ function FakeShellView(props: {
function Harness(props: {
session: MobileWebShellSessionState
sessionEstablished?: boolean
snapshot?: PageHostSnapshot | null
posted: PostedFrame[]
probe: Probe
faults: BridgeErrorCapture[]
@@ -121,7 +123,7 @@ function Harness(props: {
props.probe.backPops += 1
return 'popped'
},
snapshot: SNAPSHOT,
snapshot: props.snapshot === undefined ? SNAPSHOT : props.snapshot,
readStorage: () => ({ storage: STORAGE, storageOversize: [] }),
onStorageWrite: (key, value) => props.probe.storageWrites.push({ key, value }),
// Use fresh callbacks each render; rebuilding for them would settle pending requests.
@@ -198,7 +200,8 @@ afterEach(async () => {
async function mount(
session: MobileWebShellSessionState,
sessionEstablished?: boolean
sessionEstablished?: boolean,
snapshot?: PageHostSnapshot | null
): Promise<Mounted> {
const posted: PostedFrame[] = []
const probe: Probe = {
@@ -219,6 +222,7 @@ async function mount(
createElement(Harness, {
session: next,
...(sessionEstablished === undefined ? {} : { sessionEstablished }),
...(snapshot === undefined ? {} : { snapshot }),
posted,
probe,
faults,
@@ -312,3 +316,26 @@ describe('a session that handshook before this host existed', () => {
expect(fakeClient().requests).toEqual([])
})
})
describe('a ready the page sent before its host existed', () => {
it('is answered with one init as soon as the host snapshot arrives', async () => {
const mounted = await mount(readyState('session-one'), undefined, null)
await mounted.deliver(clientFrame({ type: 'ready' }))
expect(mounted.posted).toEqual([])
await act(async () => {
mounted.tree.update(
createElement(Harness, {
session: readyState('session-one'),
snapshot: SNAPSHOT,
posted: mounted.posted,
probe: mounted.probe,
faults: mounted.faults,
readies: mounted.readies
})
)
})
expect(mounted.frames('session-one')).toEqual([
expect.objectContaining({ type: 'init', sessionId: 'session-one', buildId: 'build-a' })
])
})
})
@@ -5,14 +5,14 @@ import type {
BridgeTerminalKeyRail
} from './bridge/bridge-terminal-key'
import type { BridgePageGeometry } from './bridge/bridge-page-geometry'
import { useCallback, useEffect, useLayoutEffect, useRef } from 'react'
import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react'
import type {
MobileWebShellBridgeMessagePayload,
OrcaMobileWebShellViewHandle
} from '../../modules/orca-mobile-web-shell/src'
import { useHostClient } from '../transport/connection/host-client-hooks'
import { createBridgeDiagnosticReporter } from './bridge-diagnostic-log'
import { bridgeDiagnosticLine, frameWithoutHostLine } from './shell-bridge-log-lines'
import { bridgeDiagnosticLine } from './shell-bridge-log-lines'
import { recordShellLifecycleLine } from './shell-lifecycle-line-recorder'
import type { BridgeColorScheme, BridgeInitRoute, BridgeUiLocale } from './bridge/bridge-envelope'
import type { BridgeClearableRouteParam } from './bridge/bridge-route-update'
@@ -27,6 +27,7 @@ import type { BridgeErrorCapture } from './bridge/bridge-error-capture'
import type { MobileWebShellSessionState } from './mobile-web-shell-session-contract'
import type { PageHostSnapshot } from './use-page-host-snapshot'
import type { PageStorageForInit } from './page-storage-keys'
import { createPageFramesWithoutHost } from './page-frames-without-host'
class BridgeViewGoneError extends Error {
constructor() {
@@ -135,7 +136,7 @@ export function useMobileWebShellBridge(args: MobileWebShellBridgeArgs): MobileW
// Read identity lazily without rebuilding a live host just to refresh a string.
const clientIdRef = useRef(clientId)
const clientRef = useRef(client)
const droppedFrameLoggedRef = useRef<string | null>(null)
const [framesWithoutHost] = useState(createPageFramesWithoutHost)
// Update refs on every commit before host construction; native frames may arrive before passive effects.
useLayoutEffect(() => {
argsRef.current = args
@@ -207,13 +208,14 @@ export function useMobileWebShellBridge(args: MobileWebShellBridgeArgs): MobileW
hostRef.current = { sessionId, host }
// Reset host-owned drop totals on rebuild so a new lower count cannot look like frames being recovered.
latest.onBinaryFramesDropped(0)
framesWithoutHost.replayReady(sessionId, host)
return () => {
// Capture Back before disposal so the next host for this document inherits it.
establishedBackRef.current = { sessionId, back: host.readSessionBack() }
hostRef.current = null
host.dispose()
}
}, [buildId, client, sessionId, snapshot])
}, [buildId, client, framesWithoutHost, sessionId, snapshot])
useEffect(() => {
const mounted = hostRef.current
@@ -246,25 +248,24 @@ export function useMobileWebShellBridge(args: MobileWebShellBridgeArgs): MobileW
(event: MobileWebShellBridgeMessageEvent) => {
const mounted = hostRef.current
if (mounted === null || mounted.sessionId !== sessionId) {
if (
mounted === null &&
sessionId !== null &&
droppedFrameLoggedRef.current !== sessionId
) {
droppedFrameLoggedRef.current = sessionId
recordShellLifecycleLine(
argsRef.current.hostId,
frameWithoutHostLine({
clientReady: clientRef.current !== null,
snapshotReady: argsRef.current.snapshot !== null
})
if (sessionId !== null) {
framesWithoutHost.receive(
sessionId,
event.nativeEvent.json,
mounted === null
? {
hostId: argsRef.current.hostId,
clientReady: clientRef.current !== null,
snapshotReady: argsRef.current.snapshot !== null
}
: null
)
}
return
}
mounted.host.receive(event.nativeEvent.json)
},
[sessionId]
[framesWithoutHost, sessionId]
),
// Fenced on the session the same way inbound frames are: a host left over from a session this
// render has moved past must not be handed this one's route.
@@ -264,7 +264,8 @@ afterEach(async () => {
async function mount(
store: GenerationStore,
setForegroundTimer?: MobileWebShellRuntime['setForegroundTimer']
setForegroundTimer?: MobileWebShellRuntime['setForegroundTimer'],
claimSpareSessionId: MobileWebShellRuntime['claimSpareSessionId'] = async () => null
): Promise<Mounted> {
const timers = createTimerSeam()
// Mint distinct ids so a remount's replacement view can be told from the one it retires.
@@ -297,6 +298,7 @@ async function mount(
runtime: {
createStore: () => store,
mintSessionId: () => `session-${++minted}`,
claimSpareSessionId,
now: () => 0,
setForegroundTimer: setForegroundTimer ?? timers.setTimer
}
@@ -374,6 +376,19 @@ describe('the wait for the page to speak', () => {
expect(mounted.states().at(-1)?.kind).toBe('ready')
})
it('opens a page Home booted under its session id, and remounts under a fresh one', async () => {
const fake = createFakeStore()
const mounted = await mount(fake.store, undefined, async () => 'home-spare')
fake.settleCacheRead(activeGeneration())
await flush()
expect(mounted.states().at(-1)).toMatchObject({ kind: 'ready', sessionId: 'home-spare' })
await act(async () => {
mounted.shellFailed('document-load-failed')
})
await flush()
expect(mounted.states().at(-1)).toMatchObject({ kind: 'ready', sessionId: 'session-1' })
})
it('stays ready when the page speaks after document load and the timers fire', async () => {
const mounted = await ready()
await act(async () => {
@@ -401,6 +416,7 @@ describe('the wait for the page to speak', () => {
runtime: {
createStore: () => fake.store,
mintSessionId: () => 'session-id',
claimSpareSessionId: async () => null,
now: () => 0,
setForegroundTimer: createTimerSeam().setTimer
}
@@ -0,0 +1,4 @@
// Alias the native spare pool for Vitest: no spare is ever parked, so every entry boots its own page.
export const prepareSpareDocument = (): Promise<boolean> => Promise.resolve(false)
export const claimSpareDocument = (): Promise<string | null> => Promise.resolve(null)
export const discardSpareDocument = (): Promise<void> => Promise.resolve()
+6
View File
@@ -22,6 +22,12 @@ export default defineConfig({
new URL('./src/test-support/expo-crypto-node.ts', import.meta.url)
)
},
{
find: /^.*\/orca-mobile-web-shell\/src\/spare-document$/,
replacement: fileURLToPath(
new URL('./src/test-support/spare-document-node.ts', import.meta.url)
)
},
{
find: 'expo-haptics',
replacement: fileURLToPath(