From a44cb9ac3ed19baff5413dbe0ff43c88f7bfc7dc Mon Sep 17 00:00:00 2001 From: Kelvin Amoaba <97001695+AmoabaKelvin@users.noreply.github.com> Date: Mon, 9 Nov 2026 02:14:05 +0000 Subject: [PATCH] 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> --- .../MobileWebShellBridge.kt | 3 + .../MobileWebShellDocument.kt | 10 +- .../MobileWebShellLoadState.kt | 1 + .../MobileWebShellSparePool.kt | 169 ++++++++++++++++++ .../orcamobilewebshell/MobileWebShellView.kt | 30 ++-- .../OrcaMobileWebShellModule.kt | 58 ++++++ .../ios/MobileWebShellBridge.swift | 3 + .../ios/MobileWebShellDocument.swift | 22 ++- .../ios/MobileWebShellLoadState.swift | 2 +- .../ios/MobileWebShellSparePool.swift | 150 ++++++++++++++++ .../ios/MobileWebShellView.swift | 22 ++- .../ios/OrcaMobileWebShellModule.swift | 41 +++++ .../src/spare-document.ts | 27 +++ mobile/src/home/MobileHomeScreen.tsx | 2 + mobile/src/home/use-home-spare-page.ts | 48 +++++ .../bridge/bridge-client-inbound-frames.ts | 4 + .../bridge/bridge-envelope.ts | 2 + .../bridge/bridge-rpc-client.ts | 2 + .../generation-host-directories.ts | 27 +++ .../mobile-web-shell/generation-store.test.ts | 18 ++ .../src/mobile-web-shell/generation-store.ts | 37 ++-- .../src/mobile-web-shell/home-spare-page.ts | 91 ++++++++++ ...e-web-shell-failed-update-fallback.test.ts | 1 + .../mobile-web-shell-runtime.ts | 12 +- .../mobile-web-shell-session-effects.test.ts | 1 + .../mobile-web-shell-session-effects.ts | 7 +- .../page-frames-without-host.ts | 40 +++++ .../process-generation-store.ts | 6 +- .../src/mobile-web-shell/shell-session-id.ts | 9 + .../use-mobile-web-shell-bridge.test.ts | 31 +++- .../use-mobile-web-shell-bridge.ts | 35 ++-- .../use-mobile-web-shell-session.test.ts | 18 +- .../src/test-support/spare-document-node.ts | 4 + mobile/vitest.config.ts | 6 + 34 files changed, 865 insertions(+), 74 deletions(-) create mode 100644 mobile/modules/orca-mobile-web-shell/android/src/main/java/expo/modules/orcamobilewebshell/MobileWebShellSparePool.kt create mode 100644 mobile/modules/orca-mobile-web-shell/ios/MobileWebShellSparePool.swift create mode 100644 mobile/modules/orca-mobile-web-shell/src/spare-document.ts create mode 100644 mobile/src/home/use-home-spare-page.ts create mode 100644 mobile/src/mobile-web-shell/generation-host-directories.ts create mode 100644 mobile/src/mobile-web-shell/home-spare-page.ts create mode 100644 mobile/src/mobile-web-shell/page-frames-without-host.ts create mode 100644 mobile/src/mobile-web-shell/shell-session-id.ts create mode 100644 mobile/src/test-support/spare-document-node.ts diff --git a/mobile/modules/orca-mobile-web-shell/android/src/main/java/expo/modules/orcamobilewebshell/MobileWebShellBridge.kt b/mobile/modules/orca-mobile-web-shell/android/src/main/java/expo/modules/orcamobilewebshell/MobileWebShellBridge.kt index d3df9fffb59..045cce54908 100644 --- a/mobile/modules/orca-mobile-web-shell/android/src/main/java/expo/modules/orcamobilewebshell/MobileWebShellBridge.kt +++ b/mobile/modules/orca-mobile-web-shell/android/src/main/java/expo/modules/orcamobilewebshell/MobileWebShellBridge.kt @@ -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 diff --git a/mobile/modules/orca-mobile-web-shell/android/src/main/java/expo/modules/orcamobilewebshell/MobileWebShellDocument.kt b/mobile/modules/orca-mobile-web-shell/android/src/main/java/expo/modules/orcamobilewebshell/MobileWebShellDocument.kt index 8292fb9ca2c..af1aff6a343 100644 --- a/mobile/modules/orca-mobile-web-shell/android/src/main/java/expo/modules/orcamobilewebshell/MobileWebShellDocument.kt +++ b/mobile/modules/orca-mobile-web-shell/android/src/main/java/expo/modules/orcamobilewebshell/MobileWebShellDocument.kt @@ -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) 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() diff --git a/mobile/modules/orca-mobile-web-shell/android/src/main/java/expo/modules/orcamobilewebshell/MobileWebShellLoadState.kt b/mobile/modules/orca-mobile-web-shell/android/src/main/java/expo/modules/orcamobilewebshell/MobileWebShellLoadState.kt index 493e50b9b5b..93737f6dd66 100644 --- a/mobile/modules/orca-mobile-web-shell/android/src/main/java/expo/modules/orcamobilewebshell/MobileWebShellLoadState.kt +++ b/mobile/modules/orca-mobile-web-shell/android/src/main/java/expo/modules/orcamobilewebshell/MobileWebShellLoadState.kt @@ -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? = null diff --git a/mobile/modules/orca-mobile-web-shell/android/src/main/java/expo/modules/orcamobilewebshell/MobileWebShellSparePool.kt b/mobile/modules/orca-mobile-web-shell/android/src/main/java/expo/modules/orcamobilewebshell/MobileWebShellSparePool.kt new file mode 100644 index 00000000000..791dbba21cf --- /dev/null +++ b/mobile/modules/orca-mobile-web-shell/android/src/main/java/expo/modules/orcamobilewebshell/MobileWebShellSparePool.kt @@ -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>() + private var ready: String? = null + + init { + document.sink = this + } + + override fun documentLoadState(payload: Map) { + 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 = + 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 diff --git a/mobile/modules/orca-mobile-web-shell/android/src/main/java/expo/modules/orcamobilewebshell/MobileWebShellView.kt b/mobile/modules/orca-mobile-web-shell/android/src/main/java/expo/modules/orcamobilewebshell/MobileWebShellView.kt index 6e86c878f4e..506c6e03202 100644 --- a/mobile/modules/orca-mobile-web-shell/android/src/main/java/expo/modules/orcamobilewebshell/MobileWebShellView.kt +++ b/mobile/modules/orca-mobile-web-shell/android/src/main/java/expo/modules/orcamobilewebshell/MobileWebShellView.kt @@ -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) = onLoadState(payload) diff --git a/mobile/modules/orca-mobile-web-shell/android/src/main/java/expo/modules/orcamobilewebshell/OrcaMobileWebShellModule.kt b/mobile/modules/orca-mobile-web-shell/android/src/main/java/expo/modules/orcamobilewebshell/OrcaMobileWebShellModule.kt index c3d036b0416..81e5a16133a 100644 --- a/mobile/modules/orca-mobile-web-shell/android/src/main/java/expo/modules/orcamobilewebshell/OrcaMobileWebShellModule.kt +++ b/mobile/modules/orca-mobile-web-shell/android/src/main/java/expo/modules/orcamobilewebshell/OrcaMobileWebShellModule.kt @@ -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() diff --git a/mobile/modules/orca-mobile-web-shell/ios/MobileWebShellBridge.swift b/mobile/modules/orca-mobile-web-shell/ios/MobileWebShellBridge.swift index 6a8fb35df39..f3d6ebb5cb4 100644 --- a/mobile/modules/orca-mobile-web-shell/ios/MobileWebShellBridge.swift +++ b/mobile/modules/orca-mobile-web-shell/ios/MobileWebShellBridge.swift @@ -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 diff --git a/mobile/modules/orca-mobile-web-shell/ios/MobileWebShellDocument.swift b/mobile/modules/orca-mobile-web-shell/ios/MobileWebShellDocument.swift index b23b2efaf75..ae372997bf4 100644 --- a/mobile/modules/orca-mobile-web-shell/ios/MobileWebShellDocument.swift +++ b/mobile/modules/orca-mobile-web-shell/ios/MobileWebShellDocument.swift @@ -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 } diff --git a/mobile/modules/orca-mobile-web-shell/ios/MobileWebShellLoadState.swift b/mobile/modules/orca-mobile-web-shell/ios/MobileWebShellLoadState.swift index 5fb8544ef73..b3e1fef7005 100644 --- a/mobile/modules/orca-mobile-web-shell/ios/MobileWebShellLoadState.swift +++ b/mobile/modules/orca-mobile-web-shell/ios/MobileWebShellLoadState.swift @@ -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. diff --git a/mobile/modules/orca-mobile-web-shell/ios/MobileWebShellSparePool.swift b/mobile/modules/orca-mobile-web-shell/ios/MobileWebShellSparePool.swift new file mode 100644 index 00000000000..92e9ff89ffc --- /dev/null +++ b/mobile/modules/orca-mobile-web-shell/ios/MobileWebShellSparePool.swift @@ -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.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) + } +} diff --git a/mobile/modules/orca-mobile-web-shell/ios/MobileWebShellView.swift b/mobile/modules/orca-mobile-web-shell/ios/MobileWebShellView.swift index 86c45218151..91aa028d7fa 100644 --- a/mobile/modules/orca-mobile-web-shell/ios/MobileWebShellView.swift +++ b/mobile/modules/orca-mobile-web-shell/ios/MobileWebShellView.swift @@ -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) } diff --git a/mobile/modules/orca-mobile-web-shell/ios/OrcaMobileWebShellModule.swift b/mobile/modules/orca-mobile-web-shell/ios/OrcaMobileWebShellModule.swift index 0f3bcaa5ca7..ed5e81770d1 100644 --- a/mobile/modules/orca-mobile-web-shell/ios/OrcaMobileWebShellModule.swift +++ b/mobile/modules/orca-mobile-web-shell/ios/OrcaMobileWebShellModule.swift @@ -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. diff --git a/mobile/modules/orca-mobile-web-shell/src/spare-document.ts b/mobile/modules/orca-mobile-web-shell/src/spare-document.ts new file mode 100644 index 00000000000..ca9ba5c1f85 --- /dev/null +++ b/mobile/modules/orca-mobile-web-shell/src/spare-document.ts @@ -0,0 +1,27 @@ +import { requireOptionalNativeModule } from 'expo-modules-core' + +type SpareDocumentModule = { + prepareSpareDocument?: (directory: string, sessionId: string) => Promise + claimSpareDocument?: (directory: string) => Promise + discardSpareDocument?: () => Promise +} + +// A binary built before the spare existed has the module without these functions. +const spareModule = (): SpareDocumentModule | null => + requireOptionalNativeModule('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 { + 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 { + return (await spareModule()?.claimSpareDocument?.(directory)) ?? null +} + +export async function discardSpareDocument(): Promise { + await spareModule()?.discardSpareDocument?.() +} diff --git a/mobile/src/home/MobileHomeScreen.tsx b/mobile/src/home/MobileHomeScreen.tsx index fadfbfcd5aa..11c0274f3a1 100644 --- a/mobile/src/home/MobileHomeScreen.tsx +++ b/mobile/src/home/MobileHomeScreen.tsx @@ -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() diff --git a/mobile/src/home/use-home-spare-page.ts b/mobile/src/home/use-home-spare-page.ts new file mode 100644 index 00000000000..58aa55953c6 --- /dev/null +++ b/mobile/src/home/use-home-spare-page.ts @@ -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]) + ) +} diff --git a/mobile/src/mobile-web-shell/bridge/bridge-client-inbound-frames.ts b/mobile/src/mobile-web-shell/bridge/bridge-client-inbound-frames.ts index f36beea592f..57c5300af27 100644 --- a/mobile/src/mobile-web-shell/bridge/bridge-client-inbound-frames.ts +++ b/mobile/src/mobile-web-shell/bridge/bridge-client-inbound-frames.ts @@ -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 diff --git a/mobile/src/mobile-web-shell/bridge/bridge-envelope.ts b/mobile/src/mobile-web-shell/bridge/bridge-envelope.ts index 2cef127bfe6..31458b9f69d 100644 --- a/mobile/src/mobile-web-shell/bridge/bridge-envelope.ts +++ b/mobile/src/mobile-web-shell/bridge/bridge-envelope.ts @@ -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, 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 11cc2190538..e9a62282aa2 100644 --- a/mobile/src/mobile-web-shell/bridge/bridge-rpc-client.ts +++ b/mobile/src/mobile-web-shell/bridge/bridge-rpc-client.ts @@ -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) }) diff --git a/mobile/src/mobile-web-shell/generation-host-directories.ts b/mobile/src/mobile-web-shell/generation-host-directories.ts new file mode 100644 index 00000000000..fa56421bd66 --- /dev/null +++ b/mobile/src/mobile-web-shell/generation-host-directories.ts @@ -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 { + 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 { + 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 +} diff --git a/mobile/src/mobile-web-shell/generation-store.test.ts b/mobile/src/mobile-web-shell/generation-store.test.ts index 257aeb9f58f..4d381f688ba 100644 --- a/mobile/src/mobile-web-shell/generation-store.test.ts +++ b/mobile/src/mobile-web-shell/generation-store.test.ts @@ -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]) + }) }) diff --git a/mobile/src/mobile-web-shell/generation-store.ts b/mobile/src/mobile-web-shell/generation-store.ts index 73d2d0bcf91..67da4168d49 100644 --- a/mobile/src/mobile-web-shell/generation-store.ts +++ b/mobile/src/mobile-web-shell/generation-store.ts @@ -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 }): 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 { - 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 { - 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 { activeMemo.delete(hostKey) deferred.drop(hostKey) + await options.beforeHostFilesDeleted?.(hostKey) await fs.delete(hostRoot(hostKey)) } async function enforceHostLimit(order: readonly string[]): Promise { - 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 { 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 diff --git a/mobile/src/mobile-web-shell/home-spare-page.ts b/mobile/src/mobile-web-shell/home-spare-page.ts new file mode 100644 index 00000000000..1456e5909b1 --- /dev/null +++ b/mobile/src/mobile-web-shell/home-spare-page.ts @@ -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 | 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 { + 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 { + 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 { + parkedDirectory = null + return discardSpareDocument().catch(() => undefined) +} 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 1d7d38cdab3..d4c7b198524 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 @@ -165,6 +165,7 @@ async function mountRoute(fileSystem: FakeGenerationFileSystem): Promise createGenerationStore({ fileSystem }), mintSessionId: () => 'session-id', + claimSpareSessionId: async () => null, now: () => 0, setForegroundTimer: () => () => {} } diff --git a/mobile/src/mobile-web-shell/mobile-web-shell-runtime.ts b/mobile/src/mobile-web-shell/mobile-web-shell-runtime.ts index e9aff1ac061..44e53bfd614 100644 --- a/mobile/src/mobile-web-shell/mobile-web-shell-runtime.ts +++ b/mobile/src/mobile-web-shell/mobile-web-shell-runtime.ts @@ -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 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 } 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 5af588e13bc..b023ae70955 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 @@ -103,6 +103,7 @@ describe('a download that reuses the cached generation', () => { runtime: { createStore: () => store, mintSessionId: () => 's', + claimSpareSessionId: async () => null, now: () => 0, setForegroundTimer: () => () => {} }, 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 05605735d45..c5995d21023 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 @@ -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() }) diff --git a/mobile/src/mobile-web-shell/page-frames-without-host.ts b/mobile/src/mobile-web-shell/page-frames-without-host.ts new file mode 100644 index 00000000000..86e6c55ce88 --- /dev/null +++ b/mobile/src/mobile-web-shell/page-frames-without-host.ts @@ -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) + } + } + } +} diff --git a/mobile/src/mobile-web-shell/process-generation-store.ts b/mobile/src/mobile-web-shell/process-generation-store.ts index 205abf1145c..1087603b3e0 100644 --- a/mobile/src/mobile-web-shell/process-generation-store.ts +++ b/mobile/src/mobile-web-shell/process-generation-store.ts @@ -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 } diff --git a/mobile/src/mobile-web-shell/shell-session-id.ts b/mobile/src/mobile-web-shell/shell-session-id.ts new file mode 100644 index 00000000000..3b28baf87e4 --- /dev/null +++ b/mobile/src/mobile-web-shell/shell-session-id.ts @@ -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)) +} 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 d18449d42b9..95ce881b9e4 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 @@ -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 { 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' }) + ]) + }) +}) 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 04bfaa84363..07a5f2cba67 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 @@ -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(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. 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 65f65113c20..c5b70b1822f 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 @@ -264,7 +264,8 @@ afterEach(async () => { async function mount( store: GenerationStore, - setForegroundTimer?: MobileWebShellRuntime['setForegroundTimer'] + setForegroundTimer?: MobileWebShellRuntime['setForegroundTimer'], + claimSpareSessionId: MobileWebShellRuntime['claimSpareSessionId'] = async () => null ): Promise { 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 } diff --git a/mobile/src/test-support/spare-document-node.ts b/mobile/src/test-support/spare-document-node.ts new file mode 100644 index 00000000000..13723e207eb --- /dev/null +++ b/mobile/src/test-support/spare-document-node.ts @@ -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 => Promise.resolve(false) +export const claimSpareDocument = (): Promise => Promise.resolve(null) +export const discardSpareDocument = (): Promise => Promise.resolve() diff --git a/mobile/vitest.config.ts b/mobile/vitest.config.ts index e9861769f75..53fb31a4987 100644 --- a/mobile/vitest.config.ts +++ b/mobile/vitest.config.ts @@ -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(