Multi-Agent Collaboration for Team and Friends
TypeScript agent-automationagent-orchestrationagent-workflowai-agentsai-collaborationai-memoryai-workforceautonomous-agentsclaude-codeclaude-code-skillscodexcoding-agentmulti-agentmultiple-agentone-person-businessone-person-companyone-person-teamopencodesolopreneur
fix(native): retire startup splash when the container attaches (#932)
Gener1b07edaab3b2
diff --git a/src/desktop/src-tauri/.cargo/config.toml b/src/desktop/src-tauri/.cargo/config.tomlindex 737a22f8f..3285b345c 100644--- a/src/desktop/src-tauri/.cargo/config.toml+++ b/src/desktop/src-tauri/.cargo/config.toml@@ -1,10 +1,5 @@[env]WRY_RUSTWEBVIEWCLIENT_CLASS_EXTENSION = { value = '''- override fun onPageCommitVisible(view: WebView, url: String?) {- super.onPageCommitVisible(view, url)- WebviewRecovery.handlePageCommitVisible(view, url)- }-@Suppress("DEPRECATION")override fun onReceivedError(view: WebView,diff --git a/src/desktop/src-tauri/gen/android/app/build.gradle.kts b/src/desktop/src-tauri/gen/android/app/build.gradle.ktsindex c9b358d6a..b640c1ee8 100644--- a/src/desktop/src-tauri/gen/android/app/build.gradle.kts+++ b/src/desktop/src-tauri/gen/android/app/build.gradle.kts@@ -29,13 +29,7 @@ val modernRecoveryDispatch = """}""".trim('\n')-val pageCommitVisibleDispatch = """-- override fun onPageCommitVisible(view: WebView, url: String?) {- super.onPageCommitVisible(view, url)- WebviewRecovery.handlePageCommitVisible(view, url)- }-""".trim('\n')+val pageLoadedCall = " Rust.onPageLoaded((view as RustWebView).id, url)"val legacyAndSslRecoveryDispatch = "\n\n" + """@Suppress("DEPRECATION")override fun onReceivedError(@@ -63,12 +57,8 @@ fun String.occurrencesOf(value: String): Int = windowed(value.length).count { itfun wireGeneratedWebViewRecovery(sourceFile: File) {var source = sourceFile.readText()- if (!source.contains("WebviewRecovery.handlePageCommitVisible(view, url)")) {- val classEnd = source.lastIndexOf("\n}")- if (classEnd < 0) {- throw GradleException("Wry RustWebViewClient class boundary is missing")- }- source = source.substring(0, classEnd) + "\n\n" + pageCommitVisibleDispatch + source.substring(classEnd)+ if (listOf("handlePageCommitVisible", "handlePageStarted", "handlePageFinished").any(source::contains)) {+ throw GradleException("Stale Wry page-ready callback; regenerate RustWebViewClient")}if (!source.contains(modernRecoveryDispatch)) {if (source.occurrencesOf(modernErrorMethod) != 1) {@@ -91,18 +81,26 @@ fun verifyGeneratedWebViewRecovery(sourceFile: File) {val required = listOf("modern main-frame recovery dispatch" to(modernErrorMethod + "\n" + modernRecoveryDispatch),- "startup visual-state dispatch" to- "WebviewRecovery.handlePageCommitVisible(view, url)","legacy recovery dispatch" to"WebviewRecovery.handleError(view, errorCode, currentUrl, failingUrl)","SSL recovery dispatch" to"WebviewRecovery.handleSslError(view, currentUrl, error.url)","Wry fallback" to "super.onReceivedError(view, request, error)",)- val missing = required.filterNot { source.contains(it.second) }.map { it.first }+ val missing = required.filterNot { source.occurrencesOf(it.second) == 1 }.map { it.first }if (missing.isNotEmpty()) {throw GradleException("Generated RustWebViewClient recovery gate failed: ${missing.joinToString()}")}+ val originalCalls = listOf(+ "currentUrl = url",+ "for (script in webView.initScripts)",+ "return Rust.onPageLoading((view as RustWebView).id, url)",+ pageLoadedCall,+ modernRecoveryDispatch,+ )+ if (originalCalls.any { source.occurrencesOf(it) != 1 } || listOf("handlePageCommitVisible", "handlePageStarted", "handlePageFinished").any(source::contains)) {+ throw GradleException("Generated RustWebViewClient lost Wry startup behavior")+ }}val tauriProperties = Properties().apply {@@ -144,7 +142,7 @@ android {}buildTypes {getByName("debug") {- applicationIdSuffix = ".qa.madox.nav112v2local"+ applicationIdSuffix = ".qa.livia.startup184container"manifestPlaceholders["usesCleartextTraffic"] = "true"isDebuggable = trueisJniDebuggable = truediff --git a/src/desktop/src-tauri/gen/android/app/src/main/java/ai/alook/android/MainActivity.kt b/src/desktop/src-tauri/gen/android/app/src/main/java/ai/alook/android/MainActivity.ktindex 578bf1b03..3980e7e5a 100644--- a/src/desktop/src-tauri/gen/android/app/src/main/java/ai/alook/android/MainActivity.kt+++ b/src/desktop/src-tauri/gen/android/app/src/main/java/ai/alook/android/MainActivity.kt@@ -3,12 +3,9 @@ package ai.alook.androidimport android.content.res.Configurationimport android.graphics.Colorimport android.os.Bundle-import android.os.Handler-import android.os.Looperimport android.view.Viewimport android.webkit.JavascriptInterfaceimport android.webkit.WebView-import android.webkit.WebView.VisualStateCallbackimport androidx.activity.OnBackPressedCallbackimport androidx.activity.enableEdgeToEdgeimport androidx.core.graphics.Insets@@ -25,7 +22,7 @@ class MainActivity : TauriActivity() {private var isReady = falseprivate var mainWebView: WebView? = null- @Volatile private var startupOffsetYCssPx = 0.0+ private var startupAttachListener: View.OnAttachStateChangeListener? = nullprivate lateinit var nativeBackCallback: OnBackPressedCallbackprivate lateinit var nativeBackDispatcher: NativeBackDispatcherprivate val mobileShareImageDocumentOwner = MobileShareImageDocumentOwner(this)@@ -50,16 +47,6 @@ class MainActivity : TauriActivity() {});})();"""-- const val STARTUP_LAYOUT_SCRIPT = """- (function() {- if (!window.AlookNative) return;- document.documentElement.style.setProperty(- '--alook-mobile-splash-offset-y',- window.AlookNative.startupOffsetYCssPx() + 'px'- );- })();- """}override fun onCreate(savedInstanceState: Bundle?) {@@ -84,13 +71,9 @@ class MainActivity : TauriActivity() {splashScreen.setKeepOnScreenCondition { !isReady }splashScreen.setOnExitAnimationListener { provider ->- provider.view.postOnAnimation {- provider.view.postOnAnimation { provider.remove() }- }+ provider.remove()}- Handler(Looper.getMainLooper()).postDelayed({ isReady = true }, 10000)-val rootView: View = findViewById(android.R.id.content)val isDark = (resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK) == Configuration.UI_MODE_NIGHT_YES@@ -103,11 +86,7 @@ class MainActivity : TauriActivity() {val imeInsets = insets.getInsets(imeType)val imeVisible = insets.isVisible(imeType)val bottomPadding = if (imeVisible) imeInsets.bottom else chromeInsets.bottom- startupOffsetYCssPx =- (chromeInsets.bottom - chromeInsets.top) / (2.0 * resources.displayMetrics.density)-v.setPadding(chromeInsets.left, chromeInsets.top, chromeInsets.right, bottomPadding)- syncStartupOffset()WindowInsetsCompat.Builder(insets).setInsets(chromeTypes, Insets.NONE).setInsets(imeType, Insets.of(imeInsets.left, imeInsets.top, imeInsets.right, 0))@@ -122,6 +101,7 @@ class MainActivity : TauriActivity() {override fun onDestroy() {nativeBackDispatcher.close()+ clearStartupAttachListener()mainWebView = nullmobileShareImageDocumentOwner.detach()super.onDestroy()@@ -129,34 +109,31 @@ class MainActivity : TauriActivity() {override fun onWebViewCreate(webView: WebView) {super.onWebViewCreate(webView)+ clearStartupAttachListener()mainWebView = webView+ if (!isReady && !isDestroyed && !isFinishing) {+ val listener = object : View.OnAttachStateChangeListener {+ override fun onViewAttachedToWindow(view: View) {+ if (view !== mainWebView || isDestroyed || isFinishing) return+ isReady = true+ clearStartupAttachListener()+ }+ override fun onViewDetachedFromWindow(view: View) {}+ }+ startupAttachListener = listener+ webView.addOnAttachStateChangeListener(listener)+ if (webView.isAttachedToWindow) listener.onViewAttachedToWindow(webView)+ }webView.addJavascriptInterface(ThemeBridge(this), "AlookNative")if (WebViewFeature.isFeatureSupported(WebViewFeature.DOCUMENT_START_SCRIPT)) {- WebViewCompat.addDocumentStartJavaScript(webView, STARTUP_LAYOUT_SCRIPT, setOf("*"))WebViewCompat.addDocumentStartJavaScript(webView, THEME_OBSERVER_SCRIPT, setOf("*"))}}- fun markStartupSurfaceReady(webView: WebView) {- if (isReady || webView !== mainWebView) return- syncStartupOffset(webView) {- webView.postVisualStateCallback(0L, object : VisualStateCallback() {- override fun onComplete(requestId: Long) {- isReady = true- }- })- }- }-- private fun syncStartupOffset(webView: WebView? = mainWebView, onComplete: (() -> Unit)? = null) {- if (webView == null) {- onComplete?.invoke()- return- }- val script = "document.documentElement.style.setProperty(" +- "'--alook-mobile-splash-offset-y','${startupOffsetYCssPx}px')"- webView.evaluateJavascript(script) { onComplete?.invoke() }+ private fun clearStartupAttachListener() {+ startupAttachListener?.let { mainWebView?.removeOnAttachStateChangeListener(it) }+ startupAttachListener = null}private fun delegateBackToSystem() {@@ -187,8 +164,5 @@ class MainActivity : TauriActivity() {fun setWindowTheme(dark: Boolean) {activity.applyWindowTheme(dark)}-- @JavascriptInterface- fun startupOffsetYCssPx(): Double = activity.startupOffsetYCssPx}}diff --git a/src/desktop/src-tauri/gen/android/app/src/main/java/ai/alook/android/WebviewRecovery.kt b/src/desktop/src-tauri/gen/android/app/src/main/java/ai/alook/android/WebviewRecovery.ktindex 6805abd56..8e20c94df 100644--- a/src/desktop/src-tauri/gen/android/app/src/main/java/ai/alook/android/WebviewRecovery.kt+++ b/src/desktop/src-tauri/gen/android/app/src/main/java/ai/alook/android/WebviewRecovery.kt@@ -1,7 +1,5 @@package ai.alook.android-import android.content.Context-import android.content.ContextWrapperimport android.webkit.WebViewimport android.webkit.WebViewClientimport java.net.URI@@ -53,26 +51,6 @@ internal object WebviewRecovery {return showRecovery(view, currentUrl, failingUrl)}- fun handlePageCommitVisible(view: WebView, url: String?) {- if (!isStartupDocument(url)) return- findActivity(view.context)?.markStartupSurfaceReady(view)- }-- private fun isStartupDocument(target: String?): Boolean {- if (target.isNullOrEmpty()) return false- return runCatching {- val parsed = URI(target)- parsed.host.equals(RECOVERY_ORIGIN, ignoreCase = true) ||- parsed.host.equals("alook.ai", ignoreCase = true)- }.getOrDefault(false)- }-- private tailrec fun findActivity(context: Context?): MainActivity? = when (context) {- is MainActivity -> context- is ContextWrapper -> findActivity(context.baseContext)- else -> null- }-private fun isHttpTarget(target: String?): Boolean {if (target.isNullOrEmpty()) return falsereturn runCatching {diff --git a/src/desktop/src-tauri/gen/apple/Sources/alook-desktop/main.mm b/src/desktop/src-tauri/gen/apple/Sources/alook-desktop/main.mmindex 2c87250cc..e8bb2d0e5 100644--- a/src/desktop/src-tauri/gen/apple/Sources/alook-desktop/main.mm+++ b/src/desktop/src-tauri/gen/apple/Sources/alook-desktop/main.mm@@ -14,11 +14,12 @@ static UIColor *alookDarkColor(void) {static const void *kAlookResolvedDarkThemeKey = &kAlookResolvedDarkThemeKey;static const void *kAlookWebDarkThemeKey = &kAlookWebDarkThemeKey;static const void *kAlookStartupOverlayKey = &kAlookStartupOverlayKey;-static const void *kAlookStartupProbeStartedKey = &kAlookStartupProbeStartedKey;static const void *kAlookStartupCompletedKey = &kAlookStartupCompletedKey;static const NSInteger kAlookStartupLogoTag = 8738;+static const NSInteger kAlookStartupErrorTag = 8739;static UIView *gAlookStartupOverlay = nil;static BOOL gAlookStartupCompleted = NO;+static BOOL gAlookStartupFailed = NO;static BOOL alookIsTauriRootController(UIViewController *viewController) {Class taoViewController = NSClassFromString(@"TaoUIViewController");@@ -67,6 +68,24 @@ static void alookAttachStartupOverlay(UIView *overlay, UIView *host, BOOL isDarksize,size);+ if (gAlookStartupFailed) {+ logo.hidden = YES;+ overlay.accessibilityElementsHidden = NO;+ UILabel *message = (UILabel *)[overlay viewWithTag:kAlookStartupErrorTag];+ if (message == nil) {+ message = [[UILabel alloc] initWithFrame:CGRectZero];+ message.tag = kAlookStartupErrorTag;+ message.text = @"Alook could not start. Close and reopen the app.";+ message.textAlignment = NSTextAlignmentCenter;+ message.numberOfLines = 0;+ message.font = [UIFont preferredFontForTextStyle:UIFontTextStyleBody];+ message.adjustsFontForContentSizeCategory = YES;+ message.isAccessibilityElement = YES;+ [overlay addSubview:message];+ }+ message.textColor = isDark ? UIColor.whiteColor : UIColor.blackColor;+ message.frame = CGRectInset(safeBounds, 24.0, 24.0);+ }[host bringSubviewToFront:overlay];}@@ -123,7 +142,7 @@ static void alookPrepareStartupOverlay(UIViewController *viewController) {}static void alookFinishStartupOverlay(UIViewController *viewController) {- if (viewController == nil) return;+ if (viewController == nil || gAlookStartupFailed) return;UIView *overlay = objc_getAssociatedObject(viewController, kAlookStartupOverlayKey);[overlay removeFromSuperview];if (overlay == gAlookStartupOverlay) gAlookStartupOverlay = nil;@@ -137,54 +156,6 @@ static void alookFinishStartupOverlay(UIViewController *viewController) {);}-static void alookWaitForWebViewSurface(- UIViewController *viewController,- WKWebView *webView,- NSInteger attempt-) {- if (viewController == nil || webView == nil) return;- if (attempt >= 200) {- alookFinishStartupOverlay(viewController);- return;- }- NSString *probe =- @"(function(){"- "if(location.hostname==='alook-recovery.localhost'&&location.pathname==='/bootstrap')return false;"- "return document.readyState==='complete'&&!!document.body&&"- "document.body.children.length>0&&document.body.getBoundingClientRect().height>0;"- "})()";- __weak UIViewController *weakViewController = viewController;- __weak WKWebView *weakWebView = webView;- [webView evaluateJavaScript:probe completionHandler:^(id result, NSError *error) {- UIViewController *strongViewController = weakViewController;- WKWebView *strongWebView = weakWebView;- if (strongViewController == nil || strongWebView == nil) return;- if (error == nil && [result respondsToSelector:@selector(boolValue)] && [result boolValue]) {- [strongWebView takeSnapshotWithConfiguration:nil completionHandler:^(UIImage *image, NSError *snapshotError) {- if (image == nil || snapshotError != nil) {- dispatch_after(- dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.05 * NSEC_PER_SEC)),- dispatch_get_main_queue(),- ^{ alookWaitForWebViewSurface(strongViewController, strongWebView, attempt + 1); }- );- return;- }- dispatch_after(- dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.05 * NSEC_PER_SEC)),- dispatch_get_main_queue(),- ^{ alookFinishStartupOverlay(strongViewController); }- );- }];- return;- }- dispatch_after(- dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.05 * NSEC_PER_SEC)),- dispatch_get_main_queue(),- ^{ alookWaitForWebViewSurface(strongViewController, strongWebView, attempt + 1); }- );- }];-}-static NSString *const kThemeObserverScript =@"(function(){""if(window.__alookThemeObserverInstalled)return;"@@ -226,6 +197,28 @@ static NSString *const kThemeObserverScript =@implementation UIViewController (AlookSafeArea)++ (BOOL)alook_finishStartupOverlayForController:(UIViewController *)controller+ webView:(WKWebView *)webView {+ if (![NSThread isMainThread] || gAlookStartupFailed) return NO;+ if (!alookIsTauriRootController(controller) ||+ ![controller.view.subviews containsObject:webView]) return NO;+ if ([objc_getAssociatedObject(controller, kAlookStartupCompletedKey) boolValue]) return YES;+ alookPrepareStartupOverlay(controller);+ if (objc_getAssociatedObject(controller, kAlookStartupOverlayKey) == nil) return NO;+ alookFinishStartupOverlay(controller);+ return YES;+}+++ (void)alook_showStartupInitializationError {+ if (![NSThread isMainThread] || gAlookStartupCompleted) return;+ gAlookStartupFailed = YES;+ UIView *host = gAlookStartupOverlay.superview;+ if (host != nil) {+ BOOL isDark = host.traitCollection.userInterfaceStyle == UIUserInterfaceStyleDark;+ alookAttachStartupOverlay(gAlookStartupOverlay, host, isDark);+ }+}++ (void)load {static dispatch_once_t onceToken;dispatch_once(&onceToken, ^{@@ -281,7 +274,6 @@ static NSString *const kThemeObserverScript =BOOL isTauriRoot = alookIsTauriRootController(self);if (isTauriRoot) alookPrepareStartupOverlay(self);UIEdgeInsets insets = self.view.safeAreaInsets;- WKWebView *startupWebView = nil;for (UIView *subview in self.view.subviews) {if ([subview isKindOfClass:[WKWebView class]]) {CGRect bounds = self.view.bounds;@@ -293,7 +285,6 @@ static NSString *const kThemeObserverScript =);WKWebView *webView = (WKWebView *)subview;- startupWebView = webView;static dispatch_once_t scriptToken;dispatch_once(&scriptToken, ^{AlookThemeHandler *handler = [[AlookThemeHandler alloc] init];@@ -310,20 +301,7 @@ static NSString *const kThemeObserverScript =alookApplyTheme(self, alookEffectiveDarkTheme(self));}}- if (startupWebView != nil) {- UIView *overlay = isTauriRoot ? objc_getAssociatedObject(self, kAlookStartupOverlayKey)- : alookInstallStartupOverlay(self);- if (overlay != nil) alookLayoutStartupOverlay(self, overlay);- if (![objc_getAssociatedObject(self, kAlookStartupProbeStartedKey) boolValue]) {- objc_setAssociatedObject(- self,- kAlookStartupProbeStartedKey,- @YES,- OBJC_ASSOCIATION_RETAIN_NONATOMIC- );- alookWaitForWebViewSurface(self, startupWebView, 0);- }- }+}@enddiff --git a/src/desktop/src-tauri/src/commands.rs b/src/desktop/src-tauri/src/commands.rsindex 64a5d77d6..eb9c4dd44 100644--- a/src/desktop/src-tauri/src/commands.rs+++ b/src/desktop/src-tauri/src/commands.rs@@ -381,13 +381,7 @@ async fn probe_runtime_command(command: &'static str, path: String) -> Result<Ststatic SPLASH_CLOSED: AtomicBool = AtomicBool::new(false);#[cfg(desktop)]-static SPLASH_FRONTEND_READY: AtomicBool = AtomicBool::new(false);--#[cfg(desktop)]-static SPLASH_MIN_ELAPSED: AtomicBool = AtomicBool::new(false);--#[cfg(desktop)]-static SPLASH_MAX_WAIT_ELAPSED: AtomicBool = AtomicBool::new(false);+static SPLASH_NATIVE_READY: AtomicBool = AtomicBool::new(false);#[cfg(desktop)]pub fn should_hide_on_close(window_label: &str) -> bool {@@ -395,8 +389,8 @@ pub fn should_hide_on_close(window_label: &str) -> bool {}#[cfg(desktop)]-fn should_close_splash(frontend_ready: bool, min_elapsed: bool, max_wait_elapsed: bool) -> bool {- max_wait_elapsed || (frontend_ready && min_elapsed)+fn should_close_splash(native_ready: bool, closed: bool) -> bool {+ native_ready && !closed}#[cfg(desktop)]@@ -516,49 +510,61 @@ pub fn create_splash_window(app: &tauri::App) -> Result<(), Box<dyn std::error::}#[cfg(desktop)]-fn do_close_splashscreen(handle: &AppHandle) {- if SPLASH_CLOSED.swap(true, Ordering::SeqCst) {- return;- }- let app = handle.clone();- let _ = handle.run_on_main_thread(move || {- if let Some(main) = app.get_webview_window("main") {- let _ = main.show();- let _ = main.set_focus();- }- if let Some(splash) = app.get_webview_window("splash") {- let _ = splash.close();- }- });+pub fn finish_native_startup(handle: &AppHandle) -> bool {+ SPLASH_NATIVE_READY.store(true, Ordering::SeqCst);+ try_close_splashscreen(handle)}-#[cfg(desktop)]-fn try_close_splashscreen(handle: &AppHandle) {- let frontend = SPLASH_FRONTEND_READY.load(Ordering::SeqCst);- let min = SPLASH_MIN_ELAPSED.load(Ordering::SeqCst);- let max = SPLASH_MAX_WAIT_ELAPSED.load(Ordering::SeqCst);- if should_close_splash(frontend, min, max) {- do_close_splashscreen(handle);+#[cfg(target_os = "macos")]+pub fn show_startup_initialization_error<R: tauri::Runtime>(handle: &AppHandle<R>) {+ use tauri_plugin_dialog::{DialogExt, MessageDialogButtons, MessageDialogKind};++ let mut dialog = handle+ .dialog()+ .message("Alook could not start. Close and reopen the app.")+ .title("Alook")+ .kind(MessageDialogKind::Error)+ .buttons(MessageDialogButtons::OkCustom("Close Alook".into()));+ if let Some(splash) = handle.get_webview_window("splash") {+ dialog = dialog.parent(&splash);}+ let exit_handle = handle.clone();+ dialog.show(move |_| exit_handle.exit(1));}#[cfg(desktop)]-pub fn mark_splash_min_elapsed(handle: &AppHandle) {- SPLASH_MIN_ELAPSED.store(true, Ordering::SeqCst);- try_close_splashscreen(handle);-}--#[cfg(desktop)]-pub fn mark_splash_max_wait_elapsed(handle: &AppHandle) {- SPLASH_MAX_WAIT_ELAPSED.store(true, Ordering::SeqCst);- try_close_splashscreen(handle);+fn try_close_splashscreen(handle: &AppHandle) -> bool {+ if SPLASH_CLOSED.load(Ordering::SeqCst) {+ return true;+ }+ if !should_close_splash(SPLASH_NATIVE_READY.load(Ordering::SeqCst), false) {+ return false;+ }+ let Some(main) = handle.get_webview_window("main") else {+ return false;+ };+ if let Err(error) = main.show() {+ eprintln!("startup main window unavailable: {error}");+ return false;+ }+ let _ = main.set_focus();+ if let Some(splash) = handle.get_webview_window("splash") {+ if let Err(error) = splash.close() {+ eprintln!("startup splash close unavailable: {error}");+ return false;+ }+ }+ SPLASH_CLOSED.store(true, Ordering::SeqCst);+ true}#[cfg(desktop)]#[tauri::command]pub fn close_splashscreen(app: AppHandle) {- SPLASH_FRONTEND_READY.store(true, Ordering::SeqCst);- try_close_splashscreen(&app);+ let handle = app.clone();+ let _ = app.run_on_main_thread(move || {+ try_close_splashscreen(&handle);+ });}// --- Daemon commands ---@@ -626,6 +632,13 @@ pub fn set_window_theme(window: tauri::WebviewWindow, dark: bool) {#[cfg(desktop)]pub fn show_main_window(app: &AppHandle) {+ if !SPLASH_CLOSED.load(Ordering::SeqCst) {+ if let Some(splash) = app.get_webview_window("splash") {+ let _ = splash.show();+ let _ = splash.set_focus();+ }+ return;+ }if let Some(window) = app.get_webview_window("main") {let _ = window.show();let _ = window.unminimize();@@ -960,16 +973,11 @@ mod tests {}#[test]- fn splash_closes_when_ready_or_when_the_native_deadline_expires() {- assert!(!should_close_splash(false, false, false));- assert!(!should_close_splash(true, false, false));- assert!(!should_close_splash(false, true, false));- assert!(should_close_splash(true, true, false));- assert!(should_close_splash(false, false, true));-- let app_source = include_str!("lib.rs");- assert!(app_source.contains("Duration::from_secs(10)"));- assert!(app_source.contains("mark_splash_max_wait_elapsed"));+ fn splash_closes_only_after_native_readiness_and_only_once() {+ assert!(!should_close_splash(false, false));+ assert!(should_close_splash(true, false));+ assert!(!should_close_splash(false, true));+ assert!(!should_close_splash(true, true));}#[test]diff --git a/src/desktop/src-tauri/src/lib.rs b/src/desktop/src-tauri/src/lib.rsindex 4c77aee22..fa3245fa4 100644--- a/src/desktop/src-tauri/src/lib.rs+++ b/src/desktop/src-tauri/src/lib.rs@@ -116,6 +116,8 @@ fn run_mobile(mut builder: tauri::Builder<tauri::Wry>) {}if let Some(window) = app.get_webview_window("main") {webview_recovery::attach(&window);+ #[cfg(target_os = "ios")]+ webview_recovery::finish_native_creation(&window);}if native_oauth_runtime::setup(app.handle()).is_err() {eprintln!("native OAuth storage unavailable");@@ -178,6 +180,7 @@ fn run_desktop(mut builder: tauri::Builder<tauri::Wry>) {// System tray + window setup (desktop only)builder = builder.setup(|app| {+ commands::create_splash_window(app)?;if file_save_runtime::setup(app.handle()).is_err() {eprintln!("file save storage unavailable");}@@ -194,22 +197,6 @@ fn run_desktop(mut builder: tauri::Builder<tauri::Wry>) {commands::setup_tray(app)?;updater::auto_check_updates(app.handle().clone());- // Serve the splash independently through its inline local protocol.- commands::create_splash_window(app)?;-- // Minimum splash display time (1s) to prevent flash- let h1 = app.handle().clone();- std::thread::spawn(move || {- std::thread::sleep(std::time::Duration::from_millis(1000));- commands::mark_splash_min_elapsed(&h1);- });-- let h2 = app.handle().clone();- std::thread::spawn(move || {- std::thread::sleep(std::time::Duration::from_secs(10));- commands::mark_splash_max_wait_elapsed(&h2);- });-// macOS: inset the webview with rounded corners, window bg as frame#[cfg(target_os = "macos")]{@@ -218,6 +205,9 @@ fn run_desktop(mut builder: tauri::Builder<tauri::Wry>) {macos_window::setup_inset_webview(&window);}}+ if let Some(window) = app.get_webview_window("main") {+ webview_recovery::finish_native_creation(&window);+ }Ok(())});diff --git a/src/desktop/src-tauri/src/webview_recovery.rs b/src/desktop/src-tauri/src/webview_recovery.rsindex b36c25cc6..e9ff0c83f 100644--- a/src/desktop/src-tauri/src/webview_recovery.rs+++ b/src/desktop/src-tauri/src/webview_recovery.rs@@ -1,6 +1,7 @@-use base64::{engine::general_purpose::STANDARD, Engine as _};use std::sync::atomic::{AtomicBool, Ordering};use tauri::http::{Request, Response, StatusCode};+#[cfg(desktop)]+use tauri::Manager;use url::Url;pub const SCHEME: &str = "alook-recovery";@@ -10,15 +11,13 @@ const RECOVERY_PATH: &str = "/network-error";const PRODUCTION_TARGET: &str = "https://alook.ai/c";const SPLASH_BACKGROUND_LIGHT: &str = "#fff";const SPLASH_BACKGROUND_DARK: &str = "#100d0a";-const SPLASH_LOGO_SIZE: u16 = 106;-const SPLASH_ICON_PNG: &[u8] =- include_bytes!("../gen/apple/Assets.xcassets/SplashIcon.imageset/[email protected]");static STARTUP: StartupRendezvous = StartupRendezvous::new();struct StartupRendezvous {hooks_ready: AtomicBool,bootstrap_finished: AtomicBool,navigation_started: AtomicBool,+ abandoned: AtomicBool,}impl StartupRendezvous {@@ -27,6 +26,7 @@ impl StartupRendezvous {hooks_ready: AtomicBool::new(false),bootstrap_finished: AtomicBool::new(false),navigation_started: AtomicBool::new(false),+ abandoned: AtomicBool::new(false),}}@@ -41,10 +41,19 @@ impl StartupRendezvous {}fn claim_navigation(&self) -> bool {- self.hooks_ready.load(Ordering::Acquire)+ !self.abandoned.load(Ordering::Acquire)+ && self.hooks_ready.load(Ordering::Acquire)&& self.bootstrap_finished.load(Ordering::Acquire)&& !self.navigation_started.swap(true, Ordering::AcqRel)}++ fn signal_failure(&self) -> bool {+ !self.abandoned.swap(true, Ordering::AcqRel)+ }++ fn abandon(&self) {+ self.abandoned.store(true, Ordering::Release);+ }}pub fn register_protocol(builder: tauri::Builder<tauri::Wry>) -> tauri::Builder<tauri::Wry> {@@ -87,7 +96,7 @@ fn response(request: Request<Vec<u8>>) -> Response<Vec<u8>> {let (status, csp, body) = match request.uri().path() {BOOTSTRAP_PATH => (StatusCode::OK,- "default-src 'none'; style-src 'unsafe-inline'; img-src data:; base-uri 'none'; form-action 'none'; frame-ancestors 'none'",+ "default-src 'none'; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'",bootstrap_html().into_bytes(),),RECOVERY_PATH => (@@ -189,16 +198,91 @@ fn windows_recovers(error_code: i32) -> bool {matches!(error_code, 1..=7 | 9..=13)}+#[cfg(any(desktop, target_os = "ios"))]+pub fn finish_native_creation(window: &tauri::WebviewWindow) {+ let ready_window = window.clone();+ let error_window = window.clone();+ if let Err(error) = window.with_webview(move |platform| {+ #[cfg(desktop)]+ {+ let _ = platform;+ if !crate::commands::finish_native_startup(ready_window.app_handle()) {+ eprintln!("native WebView startup handoff unavailable");+ }+ }+ #[cfg(target_os = "ios")]+ unsafe {+ use objc2::{msg_send, runtime::AnyObject, sel};++ let _ = ready_window;+ let controller = platform.view_controller().cast::<AnyObject>();+ let webview = platform.inner().cast::<AnyObject>();+ let completed = if controller.is_null() || webview.is_null() {+ false+ } else if let Some(class) = apple_class_method(+ c"UIViewController",+ sel!(alook_finishStartupOverlayForController:webView:),+ ) {+ msg_send![class, alook_finishStartupOverlayForController: controller, webView: webview]+ } else {+ false+ };+ if !completed {+ eprintln!("native WebView startup handoff unavailable");+ show_native_creation_error();+ }+ }+ }) {+ eprintln!("native WebView startup callback unavailable: {error}");+ #[cfg(target_os = "macos")]+ crate::commands::show_startup_initialization_error(error_window.app_handle());+ #[cfg(target_os = "ios")]+ if let Err(error) = error_window.run_on_main_thread(show_native_creation_error) {+ eprintln!("native WebView error dispatch unavailable: {error}");+ }+ #[cfg(not(any(target_os = "macos", target_os = "ios")))]+ let _ = error_window;+ }+}++#[cfg(any(target_os = "ios", all(test, target_os = "macos")))]+fn apple_class_method(+ name: &std::ffi::CStr,+ selector: objc2::runtime::Sel,+) -> Option<&'static objc2::runtime::AnyClass> {+ objc2::runtime::AnyClass::get(name).filter(|class| class.metaclass().responds_to(selector))+}++#[cfg(target_os = "ios")]+fn show_native_creation_error() {+ use objc2::{msg_send, sel};++ if let Some(class) = apple_class_method(+ c"UIViewController",+ sel!(alook_showStartupInitializationError),+ ) {+ let _: () = unsafe { msg_send![class, alook_showStartupInitializationError] };+ } else {+ eprintln!("native WebView initialization error bridge unavailable");+ }+}+pub fn attach(window: &tauri::WebviewWindow) {let startup_window = window.clone();+ let error_window = window.clone();if let Err(error) = window.with_webview(move |webview| match platform::attach(webview) {- Ok(()) if !tauri::is_dev() && STARTUP.signal_hooks_ready() => {- replace_window_with_production(&startup_window)+ Ok(()) => {+ if !tauri::is_dev() && STARTUP.signal_hooks_ready() {+ replace_window_with_production(&startup_window);+ }+ }+ Err(error) => {+ eprintln!("webview recovery unavailable: {error}");+ initialization_failure(&startup_window);}- Ok(()) => {}- Err(error) => eprintln!("webview recovery unavailable: {error}"),}) {- eprintln!("webview recovery unavailable: {error}");+ eprintln!("webview recovery callback unavailable: {error}");+ initialization_failure(&error_window);}}@@ -206,6 +290,12 @@ pub fn on_page_load<R: tauri::Runtime>(webview: &tauri::Webview<R>,payload: &tauri::webview::PageLoadPayload<'_>,) {+ if webview.label() == "main"+ && is_recovery_url(payload.url())+ && payload.url().path() == RECOVERY_PATH+ {+ STARTUP.abandon();+ }if webview.label() != "main"|| tauri::is_dev()|| !matches!(payload.event(), tauri::webview::PageLoadEvent::Finished)@@ -227,28 +317,55 @@ fn production_replace_script() -> String {fn replace_window_with_production(window: &tauri::WebviewWindow) {if let Err(error) = window.eval(production_replace_script()) {eprintln!("webview recovery initial navigation unavailable: {error}");+ initialization_failure(window);}}fn replace_webview_with_production<R: tauri::Runtime>(webview: &tauri::Webview<R>) {if let Err(error) = webview.eval(production_replace_script()) {eprintln!("webview recovery initial navigation unavailable: {error}");+ if STARTUP.signal_failure() {+ if let Err(error) = webview.navigate(initialization_error_url()) {+ eprintln!("webview initialization error navigation unavailable: {error}");+ }+ }+ }+}++fn initialization_error_url() -> Url {+ #[cfg(any(windows, target_os = "android"))]+ let base = format!("http://{HOST}{RECOVERY_PATH}#reason=initialization");+ #[cfg(not(any(windows, target_os = "android")))]+ let base = format!("{SCHEME}://localhost{RECOVERY_PATH}#reason=initialization");+ Url::parse(&base).unwrap()+}++fn initialization_failure(window: &tauri::WebviewWindow) {+ if STARTUP.signal_failure() {+ if let Err(error) = window.navigate(initialization_error_url()) {+ eprintln!("webview initialization error navigation unavailable: {error}");+ }}}fn bootstrap_html() -> String {- let icon = STANDARD.encode(SPLASH_ICON_PNG);format!(- r#"<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover"><title>Alook</title><style>:root{{color-scheme:light dark;--background:{light};--alook-mobile-splash-offset-y:0px}}html,body{{width:100%;height:100%;margin:0;overflow:hidden;background:var(--background)}}body{{display:grid;place-items:center;transform:translateY(var(--alook-mobile-splash-offset-y))}}img{{display:block;width:{size}px;height:{size}px;pointer-events:none;user-select:none}}@media(prefers-color-scheme:dark){{:root{{--background:{dark}}}}}</style></head><body><img src="data:image/png;base64,{icon}" width="{size}" height="{size}" alt="" aria-hidden="true" draggable="false"></body></html>"#,+ r#"<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover"><title>Alook</title><style>:root{{color-scheme:light dark;--background:{light}}}html,body{{width:100%;height:100%;margin:0;overflow:hidden;background:var(--background)}}@media(prefers-color-scheme:dark){{:root{{--background:{dark}}}}}</style></head><body></body></html>"#,light = SPLASH_BACKGROUND_LIGHT,dark = SPLASH_BACKGROUND_DARK,- size = SPLASH_LOGO_SIZE,)}#[cfg(any(target_os = "macos", target_os = "ios"))]mod platform {- use std::{ffi::c_void, panic::AssertUnwindSafe};+ use std::{+ ffi::c_void,+ panic::AssertUnwindSafe,+ sync::{+ atomic::{AtomicBool, Ordering},+ OnceLock,+ },+ };use super::{accepts_target, apple_recovers, recovery_url};use objc2::{@@ -265,13 +382,18 @@ mod platform {};static MAIN_WEBVIEW_MARKER: u8 = 0;+ struct Hooks {+ class: usize,+ originals: [Option<Imp>; 2],+ installed: AtomicBool,+ }+ static HOOKS: OnceLock<Hooks> = OnceLock::new();pub fn attach(platform: tauri::webview::PlatformWebview) -> Result<(), String> {let webview = unsafe { webview_object(platform.inner()) };let delegate: *mut AnyObject = unsafe { msg_send![webview, navigationDelegate] };let delegate = unsafe { delegate.as_ref() }.ok_or_else(|| "missing Wry navigation delegate".to_string())?;- let delegate_class = delegate.class() as *const AnyClass as *mut AnyClass;unsafe {#[cfg(target_os = "ios")]@@ -282,11 +404,7 @@ mod platform {webview as *const AnyObject as *mut AnyObject,OBJC_ASSOCIATION_ASSIGN,);- add_failure_method(- delegate_class,- sel!(webView:didFailProvisionalNavigation:withError:),- )?;- add_failure_method(delegate_class, sel!(webView:didFailNavigation:withError:))?;+ install_hooks(delegate.class())?;let _: () = msg_send![webview, setNavigationDelegate: delegate];}@@ -308,32 +426,156 @@ mod platform {&*pointer.cast::<AnyObject>()}- unsafe fn add_failure_method(class: *mut AnyClass, selector: Sel) -> Result<(), String> {- let implementation: Imp = std::mem::transmute::<- unsafe extern "C-unwind" fn(&AnyObject, Sel, &AnyObject, *mut AnyObject, &NSError),- Imp,- >(did_fail_navigation);- if bool::from(class_addMethod(- class,- selector,- implementation,- b"v@:@@@\0".as_ptr().cast(),- )) {- Ok(())- } else {- Err("failed to install WebKit navigation failure hook".to_string())+ unsafe fn install_hooks(class: &AnyClass) -> Result<(), String> {+ if let Some(hooks) = HOOKS.get() {+ return if hooks.class == class as *const AnyClass as usize+ && hooks.installed.load(Ordering::Acquire)+ {+ Ok(())+ } else {+ Err("Wry recovery hook installation unavailable".into())+ };+ }+ let selectors = [+ sel!(webView:didFailProvisionalNavigation:withError:),+ sel!(webView:didFailNavigation:withError:),+ ];+ let originals =+ selectors.map(|selector| class.instance_method(selector).map(|m| m.implementation()));+ HOOKS+ .set(Hooks {+ class: class as *const AnyClass as usize,+ originals,+ installed: AtomicBool::new(false),+ })+ .map_err(|_| "Wry recovery hooks already recorded".to_string())?;+ let implementations: [Imp; 2] = [+ std::mem::transmute(+ did_fail_provisional+ as unsafe extern "C-unwind" fn(+ &AnyObject,+ Sel,+ &AnyObject,+ *mut AnyObject,+ &NSError,+ ),+ ),+ std::mem::transmute(+ did_fail+ as unsafe extern "C-unwind" fn(+ &AnyObject,+ Sel,+ &AnyObject,+ *mut AnyObject,+ &NSError,+ ),+ ),+ ];+ let hooks = HOOKS.get().unwrap();+ install_hook_sequence(+ &hooks.installed,+ |index| {+ if let Some(method) = class.instance_method(selectors[index]) {+ method.set_implementation(implementations[index]);+ true+ } else {+ bool::from(class_addMethod(+ class as *const AnyClass as *mut AnyClass,+ selectors[index],+ implementations[index],+ b"v@:@@@\0".as_ptr().cast(),+ ))+ }+ },+ || {+ selectors+ .iter()+ .zip(implementations)+ .all(|(selector, implementation)| {+ class.instance_method(*selector).is_some_and(|m| {+ m.implementation() as *const () == implementation as *const ()+ })+ })+ },+ || {+ for (selector, original) in selectors.iter().zip(hooks.originals) {+ if let Some(original) = original {+ if let Some(method) = class.instance_method(*selector) {+ method.set_implementation(original);+ }+ }+ }+ },+ )+ }++ fn install_hook_sequence(+ installed: &AtomicBool,+ mut install: impl FnMut(usize) -> bool,+ verify: impl FnOnce() -> bool,+ rollback: impl FnOnce(),+ ) -> Result<(), String> {+ for index in 0..2 {+ if !install(index) {+ rollback();+ return Err("failed to install WebKit recovery hook".into());+ }+ }+ if !verify() {+ rollback();+ return Err("WebKit recovery hook verification failed".into());+ }+ installed.store(true, Ordering::Release);+ Ok(())+ }++ unsafe fn failure(+ index: usize,+ delegate: &AnyObject,+ selector: Sel,+ webview: &AnyObject,+ navigation: *mut AnyObject,+ error: &NSError,+ ) {+ if let Some(original) = HOOKS.get().and_then(|hooks| hooks.originals[index]) {+ let callback: unsafe extern "C-unwind" fn(+ &AnyObject,+ Sel,+ &AnyObject,+ *mut AnyObject,+ &NSError,+ ) = std::mem::transmute(original);+ callback(delegate, selector, webview, navigation, error);}+ if !HOOKS+ .get()+ .is_some_and(|hooks| hooks.installed.load(Ordering::Acquire))+ {+ return;+ }+ handle_failure(webview, error);}- unsafe extern "C-unwind" fn did_fail_navigation(- _delegate: &AnyObject,- _selector: Sel,+ unsafe extern "C-unwind" fn did_fail_provisional(+ delegate: &AnyObject,+ selector: Sel,+ webview: &AnyObject,+ navigation: *mut AnyObject,+ error: &NSError,+ ) {+ let _ = std::panic::catch_unwind(AssertUnwindSafe(|| unsafe {+ failure(0, delegate, selector, webview, navigation, error)+ }));+ }+ unsafe extern "C-unwind" fn did_fail(+ delegate: &AnyObject,+ selector: Sel,webview: &AnyObject,- _navigation: *mut AnyObject,+ navigation: *mut AnyObject,error: &NSError,) {let _ = std::panic::catch_unwind(AssertUnwindSafe(|| unsafe {- handle_failure(webview, error)+ failure(1, delegate, selector, webview, navigation, error)}));}@@ -370,6 +612,78 @@ mod platform {let _: *mut AnyObject = msg_send![webview, loadRequest: &*request];Ok(())}+ #[cfg(test)]+ mod hook_tests {+ use super::*;+ use std::cell::RefCell;++ #[test]+ fn hook_completion_is_published_only_after_all_installs_and_verification() {+ let installed = AtomicBool::new(false);+ let steps = RefCell::new(Vec::new());+ assert!(install_hook_sequence(+ &installed,+ |index| {+ assert!(!installed.load(Ordering::Acquire));+ steps.borrow_mut().push(index);+ true+ },+ || {+ assert!(!installed.load(Ordering::Acquire));+ assert_eq!(*steps.borrow(), vec![0, 1]);+ true+ },+ || panic!("successful installation must not roll back"),+ )+ .is_ok());+ assert!(installed.load(Ordering::Acquire));+ }++ #[test]+ fn every_partial_install_failure_rolls_back_without_publishing_completion() {+ for failure in 0..2 {+ let installed = AtomicBool::new(false);+ let methods = RefCell::new([false; 2]);+ let rolled_back = AtomicBool::new(false);+ assert!(install_hook_sequence(+ &installed,+ |index| {+ assert!(!installed.load(Ordering::Acquire));+ if index == failure {+ return false;+ }+ methods.borrow_mut()[index] = true;+ true+ },+ || panic!("partial installation must not verify"),+ || {+ assert!(!installed.load(Ordering::Acquire));+ *methods.borrow_mut() = [false; 2];+ rolled_back.store(true, Ordering::Release);+ },+ )+ .is_err());+ assert!(!installed.load(Ordering::Acquire));+ assert!(rolled_back.load(Ordering::Acquire));+ assert_eq!(*methods.borrow(), [false; 2]);+ }+ }++ #[test]+ fn unexpected_installed_imp_rolls_back_and_keeps_completion_false() {+ let installed = AtomicBool::new(false);+ let rolled_back = AtomicBool::new(false);+ assert!(install_hook_sequence(+ &installed,+ |_| true,+ || false,+ || rolled_back.store(true, Ordering::Release),+ )+ .is_err());+ assert!(!installed.load(Ordering::Acquire));+ assert!(rolled_back.load(Ordering::Acquire));+ }+ }}#[cfg(target_os = "android")]@@ -513,12 +827,14 @@ fn recovery_html() -> &'static str {const candidate=params.get("target")||"";const surface=document.querySelector('[data-testid="webview-recovery"]');const message=document.querySelector('[data-testid="recovery-message"]');+ if(params.get("reason")==="initialization")message.textContent="App initialization failed. Close and reopen Alook";const originalMessage=message.textContent;let target="";let retrying=false;let blurred=false;let hidden=document.hidden;try{const parsed=new URL(candidate);if((parsed.protocol==="http:"||parsed.protocol==="https:")&&parsed.hostname!=="alook-recovery.localhost")target=candidate}catch(_error){}+ if(params.get("reason")==="initialization")target="";if(!target)surface.setAttribute("aria-disabled","true");const refresh=()=>{if(retrying||!target)return;retrying=true;surface.setAttribute("aria-disabled","true");message.textContent="Retrying…";try{location.replace(target)}catch(_error){retrying=false;surface.setAttribute("aria-disabled","false");message.textContent=originalMessage}};const onKeydown=event=>{if(event.key==="Enter"||event.key===" "){event.preventDefault();refresh()}};@@ -535,7 +851,6 @@ fn recovery_html() -> &'static str {listen(window,"focus",onFocus);listen(document,"visibilitychange",onVisibilityChange);listen(window,"pagehide",cleanup);- if(window.__TAURI_INTERNALS__)window.__TAURI_INTERNALS__.invoke("close_splashscreen").catch(()=>{});</script></body></html>"##@@ -547,6 +862,31 @@ mod tests {use super::*;+ #[cfg(target_os = "macos")]+ #[test]+ fn apple_class_method_finds_registered_class_selector() {+ assert!(apple_class_method(c"NSString", objc2::sel!(string)).is_some());+ }++ #[cfg(target_os = "macos")]+ #[test]+ fn apple_class_method_rejects_missing_class_and_selector() {+ assert!(+ apple_class_method(c"AlookMissingStartupBridgeClass", objc2::sel!(string)).is_none()+ );+ assert!(+ apple_class_method(c"NSString", objc2::sel!(alookMissingStartupSelector)).is_none()+ );+ }++ #[cfg(target_os = "macos")]+ #[test]+ fn apple_class_method_rejects_instance_only_selector() {+ let class = objc2::runtime::AnyClass::get(c"NSString").unwrap();+ assert!(class.responds_to(objc2::sel!(length)));+ assert!(apple_class_method(c"NSString", objc2::sel!(length)).is_none());+ }+fn assert_order(source: &str, parts: &[&str]) {let mut offset = 0;for part in parts {@@ -719,7 +1059,7 @@ mod tests {assert_eq!(bootstrap_response.status(), 200);assert_eq!(bootstrap_response.headers()["content-security-policy"],- "default-src 'none'; style-src 'unsafe-inline'; img-src data:; base-uri 'none'; form-action 'none'; frame-ancestors 'none'"+ "default-src 'none'; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'");assert_eq!(bootstrap_response.headers()["x-content-type-options"],@@ -742,50 +1082,14 @@ mod tests {}#[test]- fn bootstrap_matches_the_ios_launch_screen() {+ fn bootstrap_is_theme_background_without_another_startup_logo() {let html = bootstrap_html();- let storyboard = include_str!("../gen/apple/LaunchScreen.storyboard");- let colors =- include_str!("../gen/apple/Assets.xcassets/SplashBackground.colorset/Contents.json");-assert!(html.contains("--background:#fff"));assert!(html.contains("--background:#100d0a"));- assert!(html.contains("--alook-mobile-splash-offset-y:0px"));- assert!(html.contains(- "body{display:grid;place-items:center;transform:translateY(var(--alook-mobile-splash-offset-y))}"- ));- assert!(html.contains("img{display:block;width:106px;height:106px"));- assert!(html.contains("width=\"106\" height=\"106\""));- assert!(!html.contains("animation"));- assert!(!html.contains("transition"));-- assert!(storyboard.contains("image=\"SplashIcon\""));- assert!(storyboard.contains("name=\"SplashBackground\""));- assert_eq!(storyboard.matches("constant=\"106\"").count(), 2);- assert!(storyboard.contains(- "firstAttribute=\"centerX\" secondItem=\"vDu-zF-Fre\" secondAttribute=\"centerX\""- ));- assert!(storyboard.contains(- "firstAttribute=\"centerY\" secondItem=\"vDu-zF-Fre\" secondAttribute=\"centerY\""- ));-- for component in [- "\"red\": \"1.000\"",- "\"green\": \"1.000\"",- "\"blue\": \"1.000\"",- "\"red\": \"0.063\"",- "\"green\": \"0.051\"",- "\"blue\": \"0.039\"",- ] {- assert!(colors.contains(component));- }-- let encoded = html- .split_once("src=\"data:image/png;base64,")- .and_then(|(_, source)| source.split_once('\"'))- .map(|(encoded, _)| encoded)- .expect("bootstrap must contain an inline PNG");- assert_eq!(STANDARD.decode(encoded).unwrap(), SPLASH_ICON_PNG);+ assert!(html.contains("<body></body>"));+ assert!(!html.contains("<img"));+ assert!(!html.contains("data:image"));+ assert!(!html.contains("--alook-mobile-splash-offset-y"));}#[test]@@ -880,80 +1184,67 @@ mod tests {}#[test]- fn native_source_installs_hooks_before_finished_bootstrap_navigation() {- let source = include_str!("webview_recovery.rs");- assert_order(- source,- &[- "objc_setAssociatedObject(",- "add_failure_method(",- "setNavigationDelegate: delegate",- ],- );- assert_order(- source,- &[- "connect_load_failed(move",- "connect_load_failed_with_tls_errors(move",- ],- );- assert_order(- source,- &[- "SetIsBuiltInErrorPageEnabled(false)",- "add_NavigationCompleted(&handler",- ],- );- assert!(source.contains("tauri::webview::PageLoadEvent::Finished"));- assert!(source.contains("is_bootstrap_url(payload.url())"));- assert_order(- source,- &[- "self.hooks_ready.load(Ordering::Acquire)",- "self.bootstrap_finished.load(Ordering::Acquire)",- "self.navigation_started.swap(true, Ordering::AcqRel)",- ],- );- assert!(source.contains("STARTUP.signal_hooks_ready()"));- assert!(source.contains("STARTUP.signal_bootstrap_finished()"));- assert!(source.contains("replace_window_with_production(&startup_window)"));- assert!(source.contains("replace_webview_with_production(webview)"));+ fn container_handoff_is_independent_of_page_and_recovery() {+ let lib = include_str!("lib.rs");assert_eq!(- production_replace_script(),- "location.replace(\"https://alook.ai/c\")"+ lib.matches("webview_recovery::finish_native_creation(&window);")+ .count(),+ 2);- assert!(source.contains("setAllowsBackForwardNavigationGestures: false"));- assert!(!source.contains(&["window", ".url()"].concat()));-let apple = include_str!("../gen/apple/Sources/alook-desktop/main.mm");- assert!(apple.contains("[UIImage imageNamed:@\"SplashIcon\"]"));- assert!(apple.contains("static const NSInteger kAlookStartupLogoTag = 8738"));- assert!(apple.contains("CGFloat size = 106.0"));- assert!(apple.contains("viewController.view.window ?: viewController.view"));- assert!(apple.contains("NSClassFromString(@\"TaoUIViewController\")"));- assert!(apple.contains("[host bringSubviewToFront:overlay]"));- assert!(apple.contains("UIWindowDidBecomeVisibleNotification"));- assert!(apple.contains("gAlookStartupOverlay.superview isKindOfClass:[UIWindow class]"));- assert!(apple.contains("queue:nil"));- assert!(apple.contains("alookInstallStartupOverlayInWindow(window)"));- assert!(apple.contains("@selector(alook_viewDidLoad)"));- assert!(apple.contains("@selector(alook_viewDidAppear:)"));- assert!(apple.contains("alookPrepareStartupOverlay(self)"));- assert!(apple.contains("UIEdgeInsetsInsetRect(overlay.bounds, host.safeAreaInsets)"));- assert!(apple.contains("takeSnapshotWithConfiguration:nil"));- assert!(!apple.contains("--alook-mobile-splash-offset-y"));- assert!(apple.contains("alookWaitForWebViewSurface(self, startupWebView, 0)"));+ assert!(apple.contains("[controller.view.subviews containsObject:webView]"));+ assert!(apple.contains("gAlookStartupCompleted = YES"));+ assert!(!apple.contains("takeSnapshot"));+ assert!(!apple.contains("document.readyState"));+ let activity =+ include_str!("../gen/android/app/src/main/java/ai/alook/android/MainActivity.kt");+ assert!(activity.contains("webView.addOnAttachStateChangeListener(listener)"));+ assert!(activity+ .contains("if (webView.isAttachedToWindow) listener.onViewAttachedToWindow(webView)"));+ assert!(activity.contains("view !== mainWebView || isDestroyed || isFinishing"));+ assert!(activity.contains("mainWebView?.removeOnAttachStateChangeListener(it)"));+ assert!(!activity.contains("postVisualStateCallback"));+ assert!(!activity.contains("postDelayed"));+ assert!(!activity.contains("StartupDocument"));+ let commands = include_str!("commands.rs");assert_order(- apple,+ commands,&[- "location.hostname==='alook-recovery.localhost'",- "location.pathname==='/bootstrap'",- "document.readyState==='complete'",- "alookFinishStartupOverlay(strongViewController)",+ "if let Err(error) = main.show()",+ "if let Err(error) = splash.close()",+ "SPLASH_CLOSED.store(true",],);}+ #[test]+ fn recovery_install_failure_and_bootstrap_finish_cannot_restart_production() {+ for finished_first in [false, true] {+ let startup = StartupRendezvous::new();+ if finished_first {+ assert!(!startup.signal_bootstrap_finished());+ }+ assert!(startup.signal_failure());+ assert!(!startup.signal_failure());+ assert!(!startup.signal_hooks_ready());+ assert!(!startup.signal_bootstrap_finished());+ assert!(!startup.navigation_started.load(Ordering::Acquire));+ }+ let startup = StartupRendezvous::new();+ assert!(!startup.signal_hooks_ready());+ assert!(startup.signal_bootstrap_finished());+ assert!(startup.signal_failure());+ assert!(!startup.signal_failure());+ assert!(!startup.signal_hooks_ready());+ assert!(!startup.signal_bootstrap_finished());+ assert!(+ recovery_html().contains("if(params.get(\"reason\")===\"initialization\")target=\"\"")+ );+ assert!(initialization_error_url()+ .as_str()+ .ends_with("#reason=initialization"));+ }+#[test]fn ready_then_finished_starts_once() {let startup = StartupRendezvous::new();@@ -986,14 +1277,10 @@ mod tests {}#[test]- fn android_extension_preserves_wry_client_and_cancels_ssl() {+ fn android_extension_preserves_network_and_wry_without_page_ready() {let extension = include_str!("../.cargo/config.toml");- assert!(extension.contains("WRY_RUSTWEBVIEWCLIENT_CLASS_EXTENSION"));- assert!(extension.contains("override fun onPageCommitVisible(view: WebView, url: String?)"));- assert!(extension.contains("WebviewRecovery.handlePageCommitVisible(view, url)"));- assert!(extension.contains("override fun onReceivedError("));- assert!(extension- .contains("WebviewRecovery.handleError(view, errorCode, currentUrl, failingUrl)"));+ assert!(!extension.contains("onPageCommitVisible"));+ assert!(!extension.contains("setWebViewClient"));assert_order(extension,&[@@ -1002,68 +1289,17 @@ mod tests {"WebviewRecovery.handleSslError(view, currentUrl, error.url)",],);- assert!(!extension.contains("setWebViewClient"));-- let helper =- include_str!("../gen/android/app/src/main/java/ai/alook/android/WebviewRecovery.kt");- assert!(helper.contains("findActivity(view.context)?.markStartupSurfaceReady(view)"));- assert!(helper.contains("parsed.host.equals(RECOVERY_ORIGIN"));- assert!(helper.contains("parsed.host.equals(\"alook.ai\""));- assert!(helper.contains("documentIdentity(currentUrl) != documentIdentity(failingUrl)"));- assert!(helper.contains("return recoveryUrl(currentUrl)"));-- let lock = include_str!("../Cargo.lock");- assert!(lock.contains("name = \"wry\"\nversion = \"0.57.0\""));let wry = wry_android_client_source();- assert!(wry.contains("request: WebResourceRequest"));- assert!(wry.contains("request.isForMainFrame"));- assert!(wry.contains("super.onReceivedError(view, request, error)"));-+ assert!(wry.contains("return Rust.onPageLoading((view as RustWebView).id, url)"));+ assert!(wry.contains("Rust.onPageLoaded((view as RustWebView).id, url)"));let gradle = include_str!("../gen/android/app/build.gradle.kts");- assert_order(- gradle,- &[- "request.isForMainFrame &&",- "WebviewRecovery.handleError(",- "error.errorCode",- "request.url.toString()",- "super.onReceivedError(view, request, error)",- ],- );- assert!(- gradle.contains("WebviewRecovery.handleError(view, errorCode, currentUrl, failingUrl)")- );- assert!(gradle.contains("WebviewRecovery.handleSslError(view, currentUrl, error.url)"));+ assert!(gradle.contains("source.occurrencesOf(it.second) == 1"));assert!(gradle.contains("wireGeneratedWebViewRecovery"));assert!(gradle.contains("verifyGeneratedWebViewRecovery"));- assert!(gradle.contains("it.name == \"rustBuild$variant\""));- assert!(gradle.contains("mustRunAfter(\"rustBuild$variant\")"));- assert!(gradle.contains("dependsOn(verify)"));-- let activity =- include_str!("../gen/android/app/src/main/java/ai/alook/android/MainActivity.kt");- assert!(activity.contains("override val handleBackNavigation: Boolean = false"));- assert!(activity.contains("NativeBackDispatcher(::delegateBackToSystem)"));- assert!(activity.contains("(chromeInsets.bottom - chromeInsets.top)"));- assert!(activity.contains("--alook-mobile-splash-offset-y"));- assert!(activity.contains("webView.postVisualStateCallback"));- assert_order(- activity,- &[- "splashScreen.setOnExitAnimationListener",- "provider.view.postOnAnimation",- "provider.view.postOnAnimation { provider.remove() }",- ],- );- assert!(activity- .contains("Handler(Looper.getMainLooper()).postDelayed({ isReady = true }, 10000)"));- assert!(!activity.contains(&["can", "GoBack()"].concat()));- assert!(!activity.contains(&[".", "goBack()"].concat()));-- let dispatcher = include_str!(- "../gen/android/app/src/main/java/ai/alook/android/NativeBackDispatcher.kt"- );- assert!(dispatcher.contains("alook:native-back"));- assert!(dispatcher.contains("if (closed || inFlight) return"));+ assert!(gradle.contains("handler.cancel()"));+ assert!(gradle.contains("return Rust.onPageLoading((view as RustWebView).id, url)"));+ assert!(gradle.contains("Rust.onPageLoaded((view as RustWebView).id, url)"));+ assert!(!gradle.contains("WebviewRecovery.handlePageFinished(view, url)"));+ assert!(!gradle.contains("WebviewRecovery.handlePageStarted(view)"));}}diff --git a/src/web/src/components/tauri-theme-sync.test.ts b/src/web/src/components/tauri-theme-sync.test.tsindex d004aad6e..69d3a2f84 100644--- a/src/web/src/components/tauri-theme-sync.test.ts+++ b/src/web/src/components/tauri-theme-sync.test.ts@@ -21,7 +21,7 @@ describe("syncTauriWindowTheme", () => {mocks.invoke.mockReset();});- it("closes the splash after applying the native theme", async () => {+ it("sends the legacy startup notification after applying the native theme", async () => {mocks.invoke.mockResolvedValue(undefined);await syncTauriWindowTheme(true);@@ -32,7 +32,7 @@ describe("syncTauriWindowTheme", () => {]);});- it("still closes the splash when native theme application rejects", async () => {+ it("still sends the legacy startup notification when the native theme rejects", async () => {mocks.invoke.mockRejectedValueOnce(new Error("theme unavailable")).mockResolvedValueOnce(undefined);@@ -43,4 +43,29 @@ describe("syncTauriWindowTheme", () => {["close_splashscreen"],]);});++ it("keeps a successful theme result when the legacy notification rejects", async () => {+ mocks.invoke+ .mockResolvedValueOnce(undefined)+ .mockRejectedValueOnce(new Error("startup notification unavailable"));++ await expect(syncTauriWindowTheme(true)).resolves.toBeUndefined();+ expect(mocks.invoke.mock.calls).toEqual([+ ["set_window_theme", { dark: true }],+ ["close_splashscreen"],+ ]);+ });++ it("keeps the original theme failure when the legacy notification also rejects", async () => {+ const themeError = new Error("theme unavailable");+ mocks.invoke+ .mockRejectedValueOnce(themeError)+ .mockRejectedValueOnce(new Error("startup notification unavailable"));++ await expect(syncTauriWindowTheme(false)).rejects.toBe(themeError);+ expect(mocks.invoke.mock.calls).toEqual([+ ["set_window_theme", { dark: false }],+ ["close_splashscreen"],+ ]);+ });});