diff --git a/apps/desktop/src-tauri/Cargo.lock b/apps/desktop/src-tauri/Cargo.lock index 2814f2f6..f26e14bd 100644 --- a/apps/desktop/src-tauri/Cargo.lock +++ b/apps/desktop/src-tauri/Cargo.lock @@ -6042,7 +6042,6 @@ dependencies = [ "jni 0.22.4", "keyring-core", "libc", - "ndk-context", "notify", "notify-debouncer-full", "percent-encoding", diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.toml index 2c9f999a..3ca5e6df 100644 --- a/apps/desktop/src-tauri/Cargo.toml +++ b/apps/desktop/src-tauri/Cargo.toml @@ -52,7 +52,6 @@ windows-sys = { version = "0.59", features = ["Win32_Storage_FileSystem", "Win32 rustls-platform-verifier = "0.7" jni = "0.22" android-native-keyring-store = "1.0.0" -ndk-context = "0.1.1" # The updater is desktop-only upstream, and this crate also builds for Android. # Gating it here rather than in `[dependencies]` keeps the mobile build from diff --git a/apps/desktop/src-tauri/gen/android/app/src/main/java/com/thinkbrain/notes/MainActivity.kt b/apps/desktop/src-tauri/gen/android/app/src/main/java/com/thinkbrain/notes/MainActivity.kt index f9df0833..5d11830e 100644 --- a/apps/desktop/src-tauri/gen/android/app/src/main/java/com/thinkbrain/notes/MainActivity.kt +++ b/apps/desktop/src-tauri/gen/android/app/src/main/java/com/thinkbrain/notes/MainActivity.kt @@ -56,33 +56,11 @@ class MainActivity : TauriActivity() { */ private external fun initRustlsPlatformVerifier(context: Context) - /** - * Publishes the JavaVM and app Context through `ndk-context`. - * - * Crates that expect to find them there get nothing under Tauri, which - * initialises `ndk-context` nowhere. The credential store is one such crate, - * so without this call saving a sign-in fails on Android. - * - * Implemented in `src-tauri/src/android_context.rs`. - */ - private external fun initNdkContext(context: Context) - override fun onCreate(savedInstanceState: Bundle?) { enableEdgeToEdge() - // Order matters here, and it is not the obvious one. - // - // `super.onCreate` is what starts the Rust side, and `run()` registers the - // credential store immediately — whose constructor reads the app Context - // out of `ndk-context`. So the Context has to be published *before* the - // call to super, or the app aborts on a panic from deep inside a crate - // that has no idea Tauri exists. - // - // loadLibrary has to come first in turn, so the symbols resolve. It is - // idempotent, so calling it ahead of the Tauri/Wry setup costs nothing. - System.loadLibrary("thinkbrain_notes_desktop_lib") - initNdkContext(applicationContext) - + // Tauri/tao publishes the app Context through `ndk-context` itself before + // starting Rust inside `super.onCreate`, so no bootstrap duplication here. super.onCreate(savedInstanceState) // TLS can wait until after: nothing opens an HTTPS connection during diff --git a/apps/desktop/src-tauri/src/android_context.rs b/apps/desktop/src-tauri/src/android_context.rs deleted file mode 100644 index a132dde6..00000000 --- a/apps/desktop/src-tauri/src/android_context.rs +++ /dev/null @@ -1,71 +0,0 @@ -//! Publishes the Android `Context` where crates expect to find it. -//! -//! `ndk-context` is the de-facto place a Rust crate looks for the JavaVM and -//! the app `Context` on Android. Under a normal `android_activity` app the -//! runtime fills it in; under Tauri nothing does — neither `tao` nor `wry` -//! initialise it — so any crate that reads it finds an empty slot and fails. -//! -//! `android-native-keyring-store` is one such crate: every vault operation -//! calls `ndk_context::android_context()`. It ships its own JNI entry point to -//! populate it, but that entry point is named for a Kotlin class of its own -//! (`io.crates.keyring.Keyring`) which this app does not have and should not -//! grow just to satisfy a symbol name. Populating `ndk-context` directly from -//! the `MainActivity` hook we already have is the same work without the extra -//! class. -//! -//! Kept separate from `android_tls.rs` on purpose: that module hands handles to -//! one specific crate, this one publishes them for anybody. They happen to be -//! called from the same place. - -use std::ffi::c_void; -use std::sync::OnceLock; - -use jni::EnvUnowned; -use jni::errors::ThrowRuntimeExAndDefault; -use jni::objects::JObject; -use jni::refs::Global; - -/// Holds the context reference for the life of the process. -/// -/// `ndk-context` stores a raw pointer and does not own what it points at, so -/// the global reference behind that pointer has to outlive every use of it — -/// which, for the app `Context`, means forever. Dropping it would leave -/// `ndk-context` handing out a dangling reference. -static CONTEXT: OnceLock>> = OnceLock::new(); - -/// Publishes the JavaVM and app `Context` through `ndk-context`. -/// -/// Called once from `MainActivity.onCreate`. Safe to call twice: the second -/// call finds the `OnceLock` already set and does nothing. -/// -/// # Safety -/// -/// Invoked by the JVM through JNI with a valid environment pointer and a live -/// `Context`. Not meant to be called from Rust. -#[unsafe(no_mangle)] -pub extern "system" fn Java_com_thinkbrain_notes_MainActivity_initNdkContext<'local>( - mut env: EnvUnowned<'local>, - _this: JObject<'local>, - context: JObject<'local>, -) { - // The error type needs naming: both `jni` and `rustls_platform_verifier` - // provide a `From`, so inference has two candidates. - env.with_env(|env| -> jni::errors::Result<()> { - if CONTEXT.get().is_some() { - return Ok(()); - } - let global = env.new_global_ref(&context)?; - let vm = env.get_java_vm()?; - // Set the OnceLock before publishing the pointer, so `ndk-context` - // can never hand out a reference this process has not yet anchored. - let anchored = CONTEXT.get_or_init(|| global); - unsafe { - ndk_context::initialize_android_context( - vm.get_raw() as *mut c_void, - anchored.as_obj().as_raw() as *mut c_void, - ); - } - Ok(()) - }) - .resolve::(); -} diff --git a/apps/desktop/src-tauri/src/android_tls.rs b/apps/desktop/src-tauri/src/android_tls.rs index 98efed6d..348981e9 100644 --- a/apps/desktop/src-tauri/src/android_tls.rs +++ b/apps/desktop/src-tauri/src/android_tls.rs @@ -7,10 +7,10 @@ //! "Expect rustls-platform-verifier to be initialized" — which is exactly what //! cloning a repository on a device did before this module existed. //! -//! Nothing hands it those pointers for us. The usual route, `ndk-context`, is -//! not an option here: neither `tao` nor `wry` initialise it, and the crate is -//! not in the dependency tree at all. So the handles come from Java — -//! `MainActivity.onCreate` calls the native method exported below. +//! `tao` publishes the app `Context` through `ndk-context` before Rust +//! startup, but `rustls-platform-verifier` additionally needs its own +//! `init_with_env` hook — so the handles still come from Java, via the +//! `MainActivity.onCreate` call to the native method exported below. //! //! Two details worth keeping in mind if this ever needs touching: //! diff --git a/apps/desktop/src-tauri/src/credential_store.rs b/apps/desktop/src-tauri/src/credential_store.rs index 1719df88..68c5159f 100644 --- a/apps/desktop/src-tauri/src/credential_store.rs +++ b/apps/desktop/src-tauri/src/credential_store.rs @@ -86,8 +86,8 @@ fn platform_store() -> Option Option>> { Some( diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs index 254b15bb..bfc25930 100644 --- a/apps/desktop/src-tauri/src/lib.rs +++ b/apps/desktop/src-tauri/src/lib.rs @@ -3,8 +3,6 @@ //! Main entry point for the Tauri desktop application, registering application state, //! plugins, and command handlers. -#[cfg(target_os = "android")] -mod android_context; #[cfg(target_os = "android")] mod android_tls; mod commands; diff --git a/knip.json b/knip.json index d0b99bce..cc7b1f52 100644 --- a/knip.json +++ b/knip.json @@ -3,7 +3,7 @@ "ignore": [".agents/**", "examples/**"], "workspaces": { ".": { - "ignoreBinaries": ["rustfmt", "where.exe"] + "ignoreBinaries": ["adb", "rustfmt", "where.exe"] }, "apps/desktop": { "entry": ["index.html", "demo/main.tsx", "e2e/**/*.spec.ts"], diff --git a/package.json b/package.json index 9e3330d4..c62a3b7e 100644 --- a/package.json +++ b/package.json @@ -28,6 +28,7 @@ "android:dev": "pnpm desktop:tauri android dev", "android:build": "pnpm desktop:tauri android build --debug", "android:build:release": "pnpm desktop:tauri android build", + "android:smoke": "node scripts/android-startup-smoke.mjs", "prepare": "husky", "knip": "knip" }, diff --git a/scripts/android-startup-smoke.mjs b/scripts/android-startup-smoke.mjs new file mode 100644 index 00000000..c6bf307b --- /dev/null +++ b/scripts/android-startup-smoke.mjs @@ -0,0 +1,112 @@ +#!/usr/bin/env node +/** + * android-startup-smoke — cold-launch smoke test for the installed ThinkBrain + * Notes Android app. + * + * Tests the INSTALLED package only: never installs, uninstalls, clears app + * data, or touches log buffers. + * + * Usage: + * node scripts/android-startup-smoke.mjs (or `pnpm android:smoke`) + * + * Environment: + * ANDROID_SERIAL device/emulator serial (default: adb picks the single + * connected device; set when more than one is attached) + * + * Exits 0 when two consecutive cold launches each yield a stable process for + * 10s; exits 1 immediately with the failing launch's evidence otherwise. + */ +import { execFileSync } from "node:child_process"; +import { setTimeout as delay } from "node:timers/promises"; + +const PKG = "com.thinkbrain.notes"; +const ACTIVITY = `${PKG}/.MainActivity`; +const LAUNCHES = 2; +const STABLE_SECONDS = 10; +const LOG_TAIL = 300; +const ADB_TIMEOUT_MS = 30_000; + +const deviceArgs = process.env.ANDROID_SERIAL + ? ["-s", process.env.ANDROID_SERIAL] + : []; + +function adb(...args) { + try { + return execFileSync("adb", [...deviceArgs, ...args], { + encoding: "utf8", + stdio: ["ignore", "pipe", "pipe"], + timeout: ADB_TIMEOUT_MS, + }).trim(); + } catch (err) { + // `pidof` exits 1 when the process is absent — that is data, not failure. + // Anything else (device offline, signal, timeout, adb itself missing) is + // an execution error and must not be masked as "no process". + if ( + args[0] === "shell" && + args[1] === "pidof" && + err.status === 1 && + !err.signal && + !err.stderr?.trim() + ) { + return ""; + } + throw new Error(`adb ${args.join(" ")} failed: ${err.message}`, { + cause: err, + }); + } +} + +function logcatTail() { + try { + return adb("logcat", "-d", "-t", String(LOG_TAIL)); + } catch (err) { + return `(logcat retrieval failed: ${err.message})`; + } +} + +function fail(launch, reason, amOutput, pidHistory) { + console.error( + `FAIL launch ${launch}/${LAUNCHES}: ${reason}\n` + + `am output: ${amOutput}\n` + + `pid history: ${pidHistory.join(", ") || "(none)"}\n` + + `--- logcat tail ---\n${logcatTail()}`, + ); + process.exit(1); +} + +for (let launch = 1; launch <= LAUNCHES; launch++) { + adb("shell", "am", "force-stop", PKG); + const amOutput = adb("shell", "am", "start", "-W", "-n", ACTIVITY); + if (/^Error\b/m.test(amOutput)) { + fail(launch, "am start reported an error", amOutput, []); + } + + // Sample the PID now, then once per second for STABLE_SECONDS — including + // the final interval — so a crash at any point is caught. + const pidHistory = [adb("shell", "pidof", PKG) || "DEAD"]; + const firstPid = pidHistory[0]; + let dead = firstPid === "DEAD"; + for (let s = 0; s < STABLE_SECONDS && !dead; s++) { + await delay(1000); + const pid = adb("shell", "pidof", PKG); + pidHistory.push(pid || "DEAD"); + if (!pid || pid !== firstPid) { + dead = true; + } + } + if (dead) { + fail( + launch, + firstPid === "DEAD" + ? "process never started" + : "process died or restarted", + amOutput, + pidHistory, + ); + } + console.log( + `launch ${launch}/${LAUNCHES}: pid ${firstPid} stable ${STABLE_SECONDS}s`, + ); +} + +console.log("PASS");