Modern Apps git

← Modern-Apps.git

various fixes

Commit
12a80e06a8f4e0dbee3c6e461cee49c893fd88a0
Author
vayun-mathur <[email protected]>
When
2026-08-28 13:49 UTC (3 months ago)
Parents
c686014

Diff

.gitattributes
diff --git a/.gitattributes b/.gitattributesindex 6e5059f8c3..10c661d721 100644--- a/.gitattributes+++ b/.gitattributes@@ -95,6 +95,12 @@ gradlew text eol=lf *.jks      -text *.keystore -text +# ---- Signed test vectors ----+# The Accrescent repodata vectors are real signify-signed files and the ed25519+# signature covers the raw bytes, so a single LF<->CRLF conversion would make the+# interop test fail for a reason that looks like a crypto bug.+appstore/src/main/rust/testvectors/** -text+ # ---- Vendored CAD supplied by the part vendor ---- # LCSC's STEP/WRL models are ASCII but machine-generated and never hand-edited, so they cannot # cause the review churn this policy exists to prevent. Excluded so they stay byte-identical to
appstore/build.gradle.kts
diff --git a/appstore/build.gradle.kts b/appstore/build.gradle.ktsindex c59a3d688c..8baadc9d7e 100644--- a/appstore/build.gradle.kts+++ b/appstore/build.gradle.kts@@ -34,6 +34,18 @@ android {     } } +androidComponents {+    onVariants { variant ->+        variant.sources.jniLibs?.addStaticSourceDirectory(+            layout.buildDirectory.dir("rustJniLibs").get().asFile.absolutePath+        )+    }+}++// ed25519 verification of Accrescent's signify-signed repodata (Rust).+// See appstore/src/main/rust/.+rustNativeLib("appstore_signify", "appstore-signify")+ dependencies {     implementRoom(libs)     implementation(project(":library:room"))@@ -62,8 +74,8 @@ dependencies {     implementation(libs.protobuf.kotlin.lite)     // grpc-java generated stubs reference @javax.annotation.Generated, absent on Android.     compileOnly(libs.javax.annotation.api)-    // ed25519 verification of Accrescent's signify-signed repodata allowlist.-    implementation(libs.bouncycastle.bcprov)+    // ed25519 verification of Accrescent's signify-signed repodata allowlist runs in+    // libappstore_signify.so (see rustNativeLib above), not Bouncy Castle. }  protobuf {
appstore/src/main/java/com/vayunmathur/appstore/data/accrescent/AccrescentSignify.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/accrescent/AccrescentSignify.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/accrescent/AccrescentSignify.ktindex ee36910fba..2d97e9b719 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/accrescent/AccrescentSignify.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/accrescent/AccrescentSignify.kt@@ -1,8 +1,6 @@ package com.vayunmathur.appstore.data.accrescent  import android.util.Base64-import org.bouncycastle.crypto.params.Ed25519PublicKeyParameters-import org.bouncycastle.crypto.signers.Ed25519Signer  /**  * ed25519 verification of an OpenBSD-signify signature, replicating Accrescent's@@ -19,6 +17,8 @@ import org.bouncycastle.crypto.signers.Ed25519Signer  *  * This is the whole trust anchor for the Accrescent source, so it fails closed: any parsing  * or verification problem returns `false` rather than throwing or assuming success.+ *+ * The framing above is parsed here; the raw ed25519 check itself is [SignifyNative].  */ object AccrescentSignify { @@ -51,11 +51,7 @@ object AccrescentSignify {                 ?: return false             val sigBytes = decodeRange(sigBase64, SIG_HEADER, SIG_END) ?: return false -            val publicKey = Ed25519PublicKeyParameters(pubKeyBytes, 0)-            Ed25519Signer().apply {-                init(false, publicKey)-                update(message, 0, message.size)-            }.verifySignature(sigBytes)+            SignifyNative.nativeVerify(pubKeyBytes, message, sigBytes)         } catch (_: Exception) {             false         }
appstore/src/main/java/com/vayunmathur/appstore/data/accrescent/SignifyNative.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/accrescent/SignifyNative.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/accrescent/SignifyNative.ktnew file mode 100644index 0000000000..1d684a892f--- /dev/null+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/accrescent/SignifyNative.kt@@ -0,0 +1,20 @@+// PACKAGE STRUCTURE EXCEPTION (JNI): FQN frozen for native RegisterNatives/symbol mangling+package com.vayunmathur.appstore.data.accrescent++/**+ * JNI surface for the native ed25519 verifier (libappstore_signify.so), backed+ * by the Rust `ed25519-dalek` crate. Replaces Bouncy Castle, whose only use+ * anywhere in the repo was this one signature check.+ *+ * Takes already-extracted raw bytes: signify's base64 and framing are parsed by+ * [AccrescentSignify], which stays in Kotlin. Returns false for a bad signature+ * and for any malformed input, so the caller's fail-closed contract holds+ * without this ever throwing.+ */+internal object SignifyNative {+    external fun nativeVerify(pubkey: ByteArray, message: ByteArray, signature: ByteArray): Boolean++    init {+        System.loadLibrary("appstore_signify")+    }+}
appstore/src/main/rust/.gitignore
diff --git a/appstore/src/main/rust/.gitignore b/appstore/src/main/rust/.gitignorenew file mode 100644index 0000000000..2f7896d1d1--- /dev/null+++ b/appstore/src/main/rust/.gitignore@@ -0,0 +1 @@+target/
appstore/src/main/rust/Cargo.toml
diff --git a/appstore/src/main/rust/Cargo.toml b/appstore/src/main/rust/Cargo.tomlnew file mode 100644index 0000000000..a925b893b5--- /dev/null+++ b/appstore/src/main/rust/Cargo.toml@@ -0,0 +1,16 @@+[package]+name = "appstore_signify"+version = "0.1.0"+edition = "2021"+description = "Raw ed25519 verification of Accrescent's signify-signed repodata for :appstore, exposed to Kotlin via JNI. Replaces Bouncy Castle, whose only remaining use in the repo was this one signature check."+license = "GPL-2.0-only"+[lib]+name = "appstore_signify"+crate-type = ["cdylib", "rlib"]+[dependencies]+ed25519-dalek.workspace = true+jni.workspace = true+[dev-dependencies]+# Test-only: the checked-in vectors are the real signify files, so the tests do+# the same base64 + offset extraction the Kotlin caller does.+base64.workspace = true
appstore/src/main/rust/src/jni_bridge.rs
diff --git a/appstore/src/main/rust/src/jni_bridge.rs b/appstore/src/main/rust/src/jni_bridge.rsnew file mode 100644index 0000000000..d91431dc0e--- /dev/null+++ b/appstore/src/main/rust/src/jni_bridge.rs@@ -0,0 +1,38 @@+//! JNI surface for `com.vayunmathur.appstore.data.accrescent.SignifyNative`.+use crate::verify;+use jni::objects::{JByteArray, JClass};+use jni::sys::jboolean;+use jni::JNIEnv;++fn bytes_in(env: &mut JNIEnv, arr: &JByteArray) -> Option<Vec<u8>> {+    env.convert_byte_array(arr).ok()+}++/// Returns `1` only for a valid signature; `0` for everything else, including a+/// failed array read. Never throws — the Kotlin caller treats `false` as "not+/// verified", so a thrown exception would only turn a clean rejection into a+/// crash.+#[no_mangle]+pub extern "system" fn Java_com_vayunmathur_appstore_data_accrescent_SignifyNative_nativeVerify<+    'l,+>(+    mut env: JNIEnv<'l>,+    _class: JClass<'l>,+    pubkey: JByteArray<'l>,+    msg: JByteArray<'l>,+    sig: JByteArray<'l>,+) -> jboolean {+    let (pk, m, s) = match (+        bytes_in(&mut env, &pubkey),+        bytes_in(&mut env, &msg),+        bytes_in(&mut env, &sig),+    ) {+        (Some(a), Some(b), Some(c)) => (a, b, c),+        _ => return 0,+    };+    if verify(&pk, &m, &s) {+        1+    } else {+        0+    }+}
appstore/src/main/rust/src/lib.rs
diff --git a/appstore/src/main/rust/src/lib.rs b/appstore/src/main/rust/src/lib.rsnew file mode 100644index 0000000000..789e8e2dee--- /dev/null+++ b/appstore/src/main/rust/src/lib.rs@@ -0,0 +1,51 @@+//! Raw ed25519 verification for `:appstore`, replacing Bouncy Castle.+//!+//! Scope is deliberately narrow: the signify wire format (base64 blobs, the+//! `2-byte algo id || 8-byte key id || key/signature` framing, and the+//! `untrusted comment:` line) is parsed in Kotlin by `AccrescentSignify` and+//! stays there. This crate receives an already-extracted 32-byte public key,+//! the exact signed bytes, and a 64-byte signature.+//!+//! Everything fails closed by returning `false`: this is the whole trust anchor+//! for the Accrescent app source, and a panic across the JNI boundary would+//! abort the process rather than reject the signature.++use ed25519_dalek::{Signature, VerifyingKey};++/// Length of a raw ed25519 public key.+const PUBKEY_LEN: usize = 32;++/// Length of a raw ed25519 signature.+const SIG_LEN: usize = 64;++/// True only if `sig` is a valid ed25519 signature over `msg` by `pubkey`.+///+/// Returns `false` — never panics — for a wrong-length key or signature, a+/// public key that is not a canonically-encoded curve point, or a bad+/// signature.+///+/// Uses `verify_strict`, which additionally rejects small-order public keys and+/// non-canonically-encoded `R`/`A` values. Bouncy Castle's `Ed25519Signer`+/// accepted those, so this is strictly narrower than what it replaced: a real+/// signify key cannot be small-order, and for a trust anchor the stricter check+/// is the safer direction to differ in.+pub fn verify(pubkey: &[u8], msg: &[u8], sig: &[u8]) -> bool {+    let pubkey: [u8; PUBKEY_LEN] = match pubkey.try_into() {+        Ok(k) => k,+        Err(_) => return false,+    };+    let sig: [u8; SIG_LEN] = match sig.try_into() {+        Ok(s) => s,+        Err(_) => return false,+    };+    let key = match VerifyingKey::from_bytes(&pubkey) {+        Ok(k) => k,+        Err(_) => return false,+    };+    key.verify_strict(msg, &Signature::from_bytes(&sig)).is_ok()+}++mod jni_bridge;++#[cfg(test)]+mod tests;
appstore/src/main/rust/src/tests.rs
diff --git a/appstore/src/main/rust/src/tests.rs b/appstore/src/main/rust/src/tests.rsnew file mode 100644index 0000000000..1c8246b3f1--- /dev/null+++ b/appstore/src/main/rust/src/tests.rs@@ -0,0 +1,78 @@+//! Interop test against the real, live Accrescent trust anchor.+//!+//! `testvectors/` holds the actual `repodata.1.json` and `repodata.1.json.sig`+//! served by `repo.accrescent.app` — files the Bouncy Castle path this crate+//! replaces accepted in production. They are checked in byte-exact (see the+//! `-text` entry in `.gitattributes`) because the signature covers the raw file+//! bytes, so a single EOL conversion would invalidate it.+//!+//! The base64 + offset extraction here mirrors `AccrescentSignify.kt` rather+//! than reusing it, so the vectors stay inspectable as the files they are.++use super::*;+use base64::engine::general_purpose::STANDARD;+use base64::Engine as _;++/// The exact bytes that were signed.+const REPODATA: &[u8] = include_bytes!("../testvectors/repodata.1.json");++/// The full `.sig` file: an `untrusted comment:` line plus the base64 blob.+const SIG_FILE: &str = include_str!("../testvectors/repodata.1.json.sig");++/// Must stay equal to `AccrescentRepo.REPODATA_PUBKEY`.+const PUBKEY_B64: &str = "RWT8aZ/NdUmXCPqQ0we7UyCe34q1xRfncBFVK5dI3ok9BkL1bFF3mgh3";++/// `2-byte algo id || 8-byte key id || 32-byte ed25519 public key`.+fn pubkey() -> Vec<u8> {+    STANDARD.decode(PUBKEY_B64).unwrap()[10..42].to_vec()+}++/// `2-byte algo id || 8-byte key id || 64-byte ed25519 signature`.+fn signature() -> Vec<u8> {+    let blob = SIG_FILE+        .lines()+        .map(str::trim)+        .filter(|l| !l.is_empty() && !l.starts_with("untrusted comment:"))+        .last()+        .unwrap();+    STANDARD.decode(blob).unwrap()[10..74].to_vec()+}++#[test]+fn verifies_real_accrescent_repodata_signature() {+    assert!(+        verify(&pubkey(), REPODATA, &signature()),+        "must accept the signature Bouncy Castle accepted in production"+    );+}++#[test]+fn rejects_tampered_message() {+    let mut tampered = REPODATA.to_vec();+    // Byte 3 is inside the `timestamp` value, the anti-rollback field.+    tampered[3] ^= 1;+    assert!(!verify(&pubkey(), &tampered, &signature()));+}++#[test]+fn rejects_tampered_signature() {+    let mut sig = signature();+    sig[0] ^= 1;+    assert!(!verify(&pubkey(), REPODATA, &sig));+}++#[test]+fn rejects_wrong_public_key() {+    let mut pk = pubkey();+    pk[0] ^= 1;+    assert!(!verify(&pk, REPODATA, &signature()));+}++#[test]+fn rejects_truncated_inputs() {+    let (pk, sig) = (pubkey(), signature());+    assert!(!verify(&pk[..31], REPODATA, &sig));+    assert!(!verify(&pk, REPODATA, &sig[..63]));+    assert!(!verify(&[], REPODATA, &sig));+    assert!(!verify(&pk, REPODATA, &[]));+}
appstore/src/main/rust/testvectors/repodata.1.json
diff --git a/appstore/src/main/rust/testvectors/repodata.1.json b/appstore/src/main/rust/testvectors/repodata.1.jsonnew file mode 100644index 0000000000..15a798fc3c--- /dev/null+++ b/appstore/src/main/rust/testvectors/repodata.1.json@@ -0,0 +1 @@+{"timestamp":1772051974,"apps":{"app.accrescent.client":{"min_version_code":49,"signing_cert_hash":"067a40c4193aad51ac87f9ddfdebb15e24a1850babfa4821c28c5c25c3fdc071"},"app.ninesevennine.twofactorauthenticator.accrescent":{"min_version_code":11,"signing_cert_hash":"e5b28ea1e051c232dea94c27c0592e2c002d17c5ca81788b51306d608afe52c5"},"app.organicmaps":{"min_version_code":24102302,"signing_cert_hash":"b9c7ae79a5a90270df08a132e536b9c666f5bef1f59b304fcecf8687865e4b5b"},"app.upryzing.clerotri":{"min_version_code":12,"signing_cert_hash":"90fd582a495a7ec59282a19527b80b09ab3bc91dbb8246121832bd61006ca9ae"},"ch.coredump.watertemp.zh":{"min_version_code":19,"signing_cert_hash":"b9a5bcc08afa69200aa6aa84b4a03bac8f3a63c98c86a2d4cbc826a0f73d1971"},"co.cape.matrix":{"min_version_code":5870,"signing_cert_hash":"f93072e344e691f4022314d3e6d0d61b800f108a3f0883ae130e725503a79142"},"co.uk.exocron.android.qlango":{"min_version_code":24080010,"signing_cert_hash":"5d404344b8e64cb73a96c08429fade9922bc2569e5f491a5a41f72b972f13985"},"com.brouken.player":{"min_version_code":171,"signing_cert_hash":"3cb97dba57d3d0bc190bae5f1f3a841643bcd9399bc31028ce25775d93d0109d"},"com.cakewallet.cake_wallet":{"min_version_code":236,"signing_cert_hash":"c54053ab0f10d9541762a3da7665ae3dba5e7c743ab4f108a5349d62ac106ef5"},"com.cakewallet.cupcake":{"min_version_code":2,"signing_cert_hash":"a4777207ccb244b41ed5e90b971bbbaed04bb774b250a5bee7e8947b8ca0117c"},"com.cyb3rko.flashdim":{"min_version_code":27,"signing_cert_hash":"ea78691cba418600a4563289b133f9d00d3d0c24a5f54c5c59ee1c952bb0e11d"},"com.donnnno.arcticons":{"min_version_code":1380,"signing_cert_hash":"299bb9312e39130d0d33ed42bf98567f726ab11a04dc950c5b6c162e28c869c5"},"com.donnnno.arcticons.light":{"min_version_code":1380,"signing_cert_hash":"299bb9312e39130d0d33ed42bf98567f726ab11a04dc950c5b6c162e28c869c5"},"com.donnnno.arcticons.you":{"min_version_code":1380,"signing_cert_hash":"299bb9312e39130d0d33ed42bf98567f726ab11a04dc950c5b6c162e28c869c5"},"com.github.lamarios.clipious":{"min_version_code":4065,"signing_cert_hash":"19de04e5d68466069d30ec63c6ba7d9e3cf73b5d61cb4b3762c2b9b253ecbd03"},"com.none.tom.exiferaser":{"min_version_code":39,"signing_cert_hash":"d910867ce2cf3dcd37db51853ebef8633fd83a142b2642274ed068152ff12201"},"de.jrpie.android.launcher.accrescent":{"min_version_code":35,"signing_cert_hash":"fab0cf1132914fad12a253616b9bb6ccab87b20797d258950e28eeabe4210cb1"},"de.quantumphysique.trale":{"min_version_code":20,"signing_cert_hash":"a26e7b1bc19f7f1181c0f15c96bfb95e999dfd284fe05f967d6045e16c411438"},"deckers.thibault.aves":{"min_version_code":135,"signing_cert_hash":"f4794727e45416d87c487138292b709f11d1cd7dab5584d8c6857d92e066604b"},"deckers.thibault.aves.libre":{"min_version_code":135,"signing_cert_hash":"f4794727e45416d87c487138292b709f11d1cd7dab5584d8c6857d92e066604b"},"dev.clombardo.dnsnet":{"min_version_code":25,"signing_cert_hash":"d76f6207d8182cdc1ee2dcbfe74db2edf37f36b82d084b017f79fe9f067121e4"},"dev.soupslurpr.appverifier":{"min_version_code":11,"signing_cert_hash":"3a04a80b2a88334c747485f0b2151640a38bb3d2d73a8eab81df503e0f0202b2"},"dev.soupslurpr.beautyxt":{"min_version_code":55,"signing_cert_hash":"000301cc291bb99b5ebc13be89f08c4603807127b55e21aa1e698b1de6b84346"},"dev.soupslurpr.transcribro":{"min_version_code":5,"signing_cert_hash":"7dbcfbfaa135b44e6e93910225dcb14e058291da8c2d3622734949b71ab3be64"},"digital.ventral.ips":{"min_version_code":1,"signing_cert_hash":"03243d0c0d44b6e0b41e3cb245b1dc269be4c3ffe177f843fc005bc4ea0c7426"},"im.molly.app":{"min_version_code":147602,"signing_cert_hash":"6aa80fdf4a8cc13737cfb434fc0cde486f09cf8fcda21a67bea5ee1ca2700886"},"io.spaceapi.community.myhackerspace":{"min_version_code":108,"signing_cert_hash":"4ec51acd06d3f9e79507c914ef15e2c09a18249a82af9064ff0495f926f93dd4"},"net.ivpn.client":{"min_version_code":135,"signing_cert_hash":"88a6b40fc97fdc842f231f50eb12de116f5b759e3c5b38aaccaf6a7b393c85bb"},"it.fast4x.rimusic":{"min_version_code":65,"signing_cert_hash":"a1ba8bd74af8f92cb3719a072113a218cfaec02bce2b736a280e31d8cd11808c"},"it.fast4x.riplay":{"min_version_code":60,"signing_cert_hash":"9762e9ab732b0a1cf3c721168450533c8b1905ae1c9e658f488abb84debef2fb"},"me.easyapps.easynotes":{"min_version_code":11,"signing_cert_hash":"79e85ce81df2f4f225c22fea0b2d1950b368627e475fb72b7385d250313bf7c1"},"net.leodesouza.blitz":{"min_version_code":202,"signing_cert_hash":"6d7fd2715ed21cff64086dc5fcf8820a685a793ebd07d972163d86172babba75"},"org.andbible.andbible":{"min_version_code":898,"signing_cert_hash":"8bf5168a01944d62a4a4c7b652f4738184000d57a48c52895ac6cb831c48cf30"},"org.cryptomator":{"min_version_code":2980,"signing_cert_hash":"f7c3ec3b0d588d3cb52983e9eb1a7421c93d4339a286398e71d7b651e8d8ecdd"},"org.ironfoxoss.ironfox":{"min_version_code":31340230,"signing_cert_hash":"c5e291b5a571f9c8cd9a9799c2c94e02ec9703948893f2ca756d67b94204f904"},"org.oxycblt.auxio":{"min_version_code":61,"signing_cert_hash":"da84e2534c1acc0b6e4f57dedb640d4dc893f5bf4137a2e1ecba87adf825ba44"},"org.unifiedpush.distributor.nextpush":{"min_version_code":43,"signing_cert_hash":"4d77eb02f166559e43b2a3b34e861d628ccceecbf7653ee13870971b25e175f0"},"org.unifiedpush.distributor.sunup":{"min_version_code":12,"signing_cert_hash":"3b33d78a5bcac1b952756b08fe8830ced387abb6b956b02a47ef80321d4a2b88"},"s1m.hwfido2provider":{"min_version_code":9,"signing_cert_hash":"94bd36ba4648d38697cdfcf3385b6c0088ff3d551ce9fc16050ee080b9553ec5"},"xyz.malkki.neostumbler":{"min_version_code":19,"signing_cert_hash":"7f839ac7afc4ff6f1c7fb1348ac10de2f17de8a78d0d812c1f43ae835a5111df"}}}
appstore/src/main/rust/testvectors/repodata.1.json.sig
diff --git a/appstore/src/main/rust/testvectors/repodata.1.json.sig b/appstore/src/main/rust/testvectors/repodata.1.json.signew file mode 100644index 0000000000..84d62c146d--- /dev/null+++ b/appstore/src/main/rust/testvectors/repodata.1.json.sig@@ -0,0 +1,2 @@+untrusted comment: verify with accrescent.pub+RWT8aZ/NdUmXCP33Vb42gaYSvcogbtBfLwDN8KbdlNLHRMfhULjrG/sPf5ya0u7kBYixBdlXgrlKYBK7cJhrsUS6cxkMVWxWOg8=
library/downloadservice/src/main/java/com/vayunmathur/library/downloadservice/ModelUrls.kt
diff --git a/library/downloadservice/src/main/java/com/vayunmathur/library/downloadservice/ModelUrls.kt b/library/downloadservice/src/main/java/com/vayunmathur/library/downloadservice/ModelUrls.ktindex 65e6d1fd31..44b9ba79fe 100644--- a/library/downloadservice/src/main/java/com/vayunmathur/library/downloadservice/ModelUrls.kt+++ b/library/downloadservice/src/main/java/com/vayunmathur/library/downloadservice/ModelUrls.kt@@ -11,44 +11,23 @@ package com.vayunmathur.library.downloadservice  *  *   models/gemma-4-E2B-it.litertlm  *     <- https://huggingface.co/litert-community/gemma-4-E2B-it-litert-lm/resolve/main/gemma-4-E2B-it.litertlm- *   models/siglip2_vision_model_fp16.onnx- *     <- https://huggingface.co/onnx-community/siglip2-base-patch16-224-ONNX/resolve/main/onnx/vision_model_fp16.onnx- *   models/siglip2_text_model_int8.onnx- *     <- https://huggingface.co/onnx-community/siglip2-base-patch16-224-ONNX/resolve/main/onnx/text_model_int8.onnx- *   models/siglip2_tokenizer.model- *     <- https://huggingface.co/onnx-community/siglip2-base-patch16-224-ONNX/resolve/main/tokenizer.model  */ object ModelUrls {     const val MIRROR_BASE = "https://data.vayunmathur.com/models/" -    // On-disk file names (also the mirror path for the SigLIP2 files).+    // On-disk file name.     const val GEMMA_FILE = "gemma4-2b.litertlm"-    const val SIGLIP_VISION_FILE = "siglip2_vision_model_fp16.onnx"-    const val SIGLIP_TEXT_FILE = "siglip2_text_model_int8.onnx"-    const val SIGLIP_TOKENIZER_FILE = "siglip2_tokenizer.model" -    // Mirror download URLs.+    // Mirror download URL.     const val GEMMA_URL = "${MIRROR_BASE}gemma-4-E2B-it.litertlm"-    const val SIGLIP_VISION_URL = "${MIRROR_BASE}siglip2_vision_model_fp16.onnx"-    const val SIGLIP_TEXT_URL = "${MIRROR_BASE}siglip2_text_model_int8.onnx"-    const val SIGLIP_TOKENIZER_URL = "${MIRROR_BASE}siglip2_tokenizer.model" -    // SHA-256 integrity checks (verified against the files uploaded to the mirror).+    // SHA-256 integrity check (verified against the file uploaded to the mirror).     const val GEMMA_SHA256 = "181938105e0eefd105961417e8da75903eacda102c4fce9ce90f50b97139a63c"-    const val SIGLIP_VISION_SHA256 = "a1959f7bd3993a607e48839f6d01e25b876fe76afda301b028b78eef68aabd95"-    const val SIGLIP_TEXT_SHA256 = "3a0603d3a00c05a80a6ded4743c16aaac7b1e62cdcc7e362e7ce418659b96400"-    const val SIGLIP_TOKENIZER_SHA256 = "61a7b147390c64585d6c3543dd6fc636906c9af3865a5548f27f31aee1d4c8e2"      val GEMMA = ModelDownloadItem(GEMMA_URL, GEMMA_FILE, "Model", GEMMA_SHA256)-    val SIGLIP_VISION = ModelDownloadItem(SIGLIP_VISION_URL, SIGLIP_VISION_FILE, "Vision Model", SIGLIP_VISION_SHA256)-    val SIGLIP_TEXT = ModelDownloadItem(SIGLIP_TEXT_URL, SIGLIP_TEXT_FILE, "Text Model", SIGLIP_TEXT_SHA256)-    val SIGLIP_TOKENIZER = ModelDownloadItem(SIGLIP_TOKENIZER_URL, SIGLIP_TOKENIZER_FILE, "Tokenizer", SIGLIP_TOKENIZER_SHA256) -    /** SigLIP2 semantic-search models fetched on demand by the photos app. */-    val SIGLIP = listOf(SIGLIP_VISION, SIGLIP_TEXT, SIGLIP_TOKENIZER)--    /** Everything downloaded on OpenAssistant first launch (Gemma + SigLIP2). */-    val INITIAL = listOf(GEMMA) + SIGLIP+    /** Everything downloaded on OpenAssistant first launch. */+    val INITIAL = listOf(GEMMA) }  /** A single model file fetched from the self-hosted mirror, with optional SHA-256. */
openassistant/build.gradle.kts
diff --git a/openassistant/build.gradle.kts b/openassistant/build.gradle.ktsindex 2c866f13aa..1f7c1e6f91 100644--- a/openassistant/build.gradle.kts+++ b/openassistant/build.gradle.kts@@ -15,17 +15,9 @@ android {         applicationId = "com.vayunmathur.openassistant"     } -    androidResources {-        // SigLIP2 .onnx encoders are downloaded to external files at runtime,-        // but the SentencePiece tokenizer.model is downloaded too; keep .onnx-        // uncompressed for consistency with the ONNX Runtime memory-mapped read.-        noCompress += "onnx"-    }-     packaging {         jniLibs {             pickFirsts.add("**/libLiteRtTopKOpenClSampler.so")-            pickFirsts.add("**/libc++_shared.so")         }     } }@@ -47,9 +39,6 @@ dependencies {     // litertlm 0.14.0 needs kotlinx-coroutines 1.11.0 (close$default on the     // SendChannel interface); requesting it directly wins over the transitive 1.9.0.     implementation(libs.kotlinx.coroutines.android)-    // SigLIP2 image/text embedding (semantic photo search served to the photos-    // app) runs on ONNX Runtime; litertlm stays for the chat LLM.-    implementation(libs.onnxruntime.android)      implementation(project(":library:downloadservice")) }\ No newline at end of file
openassistant/src/main/java/com/vayunmathur/openassistant/util/AssistantViewModel.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/util/AssistantViewModel.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/util/AssistantViewModel.ktindex 701c45a0d2..e3d1039d44 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/util/AssistantViewModel.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/util/AssistantViewModel.kt@@ -11,7 +11,6 @@ import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.viewModelScope-import com.vayunmathur.library.util.DataStoreUtils import com.vayunmathur.openassistant.data.Conversation import com.vayunmathur.openassistant.data.Memory import com.vayunmathur.openassistant.data.Message@@ -78,7 +77,6 @@ class AssistantViewModel(      init {         cleanupLegacyModelFile()-        cleanupStaleSiglipModels()         // Pre-warm the inference engine so the first user prompt is responsive.         val context = getApplication<Application>()         context.startService(Intent(context, InferenceService::class.java))@@ -190,7 +188,15 @@ class AssistantViewModel(         viewModelScope.launch(Dispatchers.IO) {             try {                 val externalDir = context.getExternalFilesDir(null) ?: return@launch-                val legacyModelFiles = listOf("gemma4.litertlm", "gemma4-4b.litertlm")+                // The siglip2_* files backed the SigLIP2 embedding provider, which is+                // gone along with ONNX Runtime; they are ~450 MB on installs that used it.+                val legacyModelFiles = listOf(+                    "gemma4.litertlm",+                    "gemma4-4b.litertlm",+                    "siglip2_vision_model_fp16.onnx",+                    "siglip2_text_model_int8.onnx",+                    "siglip2_tokenizer.model",+                )                 for (name in legacyModelFiles) {                     if (File(externalDir, name).delete()) {                         Log.i(TAG, "Deleted legacy model file $name")@@ -207,39 +213,6 @@ class AssistantViewModel(         audioRecorder = null     } -    /**-     * Version the on-demand SigLIP2 model files: if [SiglipEmbedder.MODEL_VERSION]-     * changed since we last downloaded them, delete the stale files and clear the-     * downloadservice `dlid_`/`progress_` keys so they re-download on the next-     * embedding request. Unlike the gemma path this never touches-     * `dbSetupComplete` — SigLIP2 is optional and fetched on demand.-     */-    private fun cleanupStaleSiglipModels() {-        val context = getApplication<Application>()-        viewModelScope.launch(Dispatchers.IO) {-            try {-                val ds = DataStoreUtils.getInstance(context)-                val stored = ds.getLong("siglip_model_version") ?: 0L-                if (stored == SiglipEmbedder.MODEL_VERSION.toLong()) return@launch--                val externalDir = context.getExternalFilesDir(null)-                val files = listOf(-                    SiglipEmbedder.VISION_FILE,-                    SiglipEmbedder.TEXT_FILE,-                    SiglipEmbedder.TOKENIZER_FILE,-                )-                for (name in files) {-                    externalDir?.let { File(it, name).takeIf { f -> f.exists() }?.delete() }-                    ds.setLong("dlid_$name", 0L)-                    ds.setDouble("progress_$name", 0.0)-                }-                ds.setLong("siglip_model_version", SiglipEmbedder.MODEL_VERSION.toLong())-            } catch (e: Exception) {-                Log.e(TAG, "Error cleaning up stale SigLIP2 model files", e)-            }-        }-    }-     companion object {         private const val TAG = "AssistantViewModel"     }
openassistant/src/main/java/com/vayunmathur/openassistant/util/InferenceService.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/util/InferenceService.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/util/InferenceService.ktindex 734746cff2..c308934b7b 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/util/InferenceService.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/util/InferenceService.kt@@ -16,8 +16,6 @@ import androidx.core.content.IntentCompat import com.google.ai.edge.litertlm.* import com.vayunmathur.library.util.SecureResultReceiver import com.vayunmathur.library.util.DataStoreUtils-import com.vayunmathur.library.downloadservice.downloadModels-import com.vayunmathur.library.downloadservice.ModelUrls import kotlinx.coroutines.* import kotlinx.coroutines.flow.catch import java.io.File@@ -75,27 +73,11 @@ class InferenceService : Service() {             val imagePaths: Array<String>,             val audioPath: String?         ) : InferenceJob()--        /**-         * A SigLIP2 embedding request from another app (photos). [mode] is-         * "text", "image", or "info". Runs on [SiglipEmbedder], independent of-         * the litertlm chat [Engine], so it can be served while the LLM is busy.-         */-        data class Embedding(-            val mode: String,-            val userText: String,-            val imagePath: String?,-            val receiver: ResultReceiver,-        ) : InferenceJob()     }      private val serviceScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)     private val standardQueue = Channel<InferenceJob.Standard>(Channel.UNLIMITED)     private val intentQueue = Channel<InferenceJob.Intent>(Channel.UNLIMITED)-    private val embeddingQueue = Channel<InferenceJob.Embedding>(Channel.UNLIMITED)--    /** Guards the on-demand SigLIP2 model download so we start it at most once. */-    @Volatile private var downloadJob: Job? = null      private var engine: Engine? = null     private var currentConversation: com.google.ai.edge.litertlm.Conversation? = null@@ -138,23 +120,6 @@ class InferenceService : Service() {                 }             }         }-        // Embeddings run on their own consumer so they don't wait behind the-        // (possibly long) chat/intent LLM jobs — they use SiglipEmbedder, not the-        // litertlm Engine.-        serviceScope.launch {-            for (job in embeddingQueue) {-                try {-                    processEmbeddingJob(job)-                } catch (e: CancellationException) {-                    throw e-                } catch (e: Exception) {-                    Log.e("InferenceService", "Error processing embedding job", e)-                    try {-                        job.receiver.send(-1, Bundle().apply { putString("error", e.localizedMessage ?: "Embedding failed") })-                    } catch (_: Exception) {}-                }-            }-        }     }      override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {@@ -166,7 +131,6 @@ class InferenceService : Service() {         val userText = intent.getStringExtra("user_text") ?: ""         val audioPath = intent.getStringExtra("audio_path")         val schema = intent.getStringExtra("schema")-        val embedMode = intent.getStringExtra("embed_mode")         val receiver = IntentCompat.getParcelableExtra(intent, "RECEIVER", ResultReceiver::class.java)          val imageUris = IntentCompat.getParcelableArrayListExtra(intent, "image_uris", Uri::class.java)@@ -179,13 +143,7 @@ class InferenceService : Service() {              val imagePaths = staticImagePaths + imagePathsFromUris -            if (embedMode != null && receiver != null) {-                // Embedding request from another app (photos): text/image/info.-                Log.i("InferenceService", "Queueing Embedding request mode=$embedMode")-                embeddingQueue.trySend(-                    InferenceJob.Embedding(embedMode, userText, imagePaths.firstOrNull(), receiver)-                )-            } else if (receiver != null && schema != null) {+            if (receiver != null && schema != null) {                 Log.i("InferenceService", "Queueing Intent Inference request")                 intentQueue.trySend(InferenceJob.Intent(userText, imagePaths, schema, receiver))             } else if (conversationId != -1L) {@@ -264,88 +222,6 @@ class InferenceService : Service() {         }     } -    // ---------- SigLIP2 embedding provider (served to the photos app) ------------    private suspend fun processEmbeddingJob(job: InferenceJob.Embedding) {-        val context = applicationContext--        // Models are downloaded on demand; until all three files are present,-        // report "downloading" (code 2) with aggregate progress and retry later.-        if (!SiglipEmbedder.filesPresent(context)) {-            startModelDownloadIfNeeded()-            job.receiver.send(2, Bundle().apply {-                putString("status", "downloading")-                putDouble("progress", currentDownloadProgress())-            })-            return-        }--        if (!SiglipEmbedder.isAvailable(context)) {-            job.receiver.send(-1, Bundle().apply { putString("error", "Embedder failed to load") })-            return-        }--        val dim = SiglipEmbedder.dim(context)-        when (job.mode) {-            "info" -> job.receiver.send(0, Bundle().apply {-                putString("model_id", SiglipEmbedder.MODEL_ID)-                putInt("dim", dim)-                putString("status", "ready")-            })-            "text" -> {-                val t0 = System.currentTimeMillis()-                val emb = SiglipEmbedder.textEmbedding(context, job.userText)-                Log.i("InferenceService", "Text embed (${emb?.size ?: 0}d) in ${System.currentTimeMillis() - t0}ms ok=${emb != null}")-                sendEmbedding(job.receiver, emb)-            }-            "image" -> {-                val path = job.imagePath-                val t0 = System.currentTimeMillis()-                val emb = if (path != null) SiglipEmbedder.imageEmbedding(context, File(path)) else null-                Log.i("InferenceService", "Image embed (${emb?.size ?: 0}d) in ${System.currentTimeMillis() - t0}ms ok=${emb != null} path=$path")-                sendEmbedding(job.receiver, emb)-                // The temp copy from copyUriToFile is no longer needed.-                if (path != null) runCatching { File(path).delete() }-            }-            else -> job.receiver.send(-1, Bundle().apply { putString("error", "Unknown embed_mode ${job.mode}") })-        }-    }--    private fun sendEmbedding(receiver: ResultReceiver, emb: FloatArray?) {-        if (emb == null) {-            // Provider is up but this specific item couldn't be embedded; mark it-            // per_item so the client skips just this one rather than pausing.-            receiver.send(-1, Bundle().apply {-                putString("error", "Embedding failed")-                putBoolean("per_item", true)-            })-        } else {-            receiver.send(0, Bundle().apply {-                putByteArray("embedding", SiglipEmbedder.floatsToBytes(emb))-                putString("model_id", SiglipEmbedder.MODEL_ID)-                putInt("dim", emb.size)-            })-        }-    }--    private fun startModelDownloadIfNeeded() {-        if (downloadJob?.isActive == true) return-        downloadJob = serviceScope.launch {-            try {-                val ds = DataStoreUtils.getInstance(applicationContext)-                downloadModels(applicationContext, ds, ModelUrls.SIGLIP)-            } catch (e: Exception) {-                Log.e("InferenceService", "SigLIP2 model download failed", e)-            }-        }-    }--    private fun currentDownloadProgress(): Double {-        val ds = DataStoreUtils.getInstance(applicationContext)-        val files = listOf(SiglipEmbedder.VISION_FILE, SiglipEmbedder.TEXT_FILE, SiglipEmbedder.TOKENIZER_FILE)-        return files.sumOf { ds.getDouble("progress_$it") ?: 0.0 } / files.size-    }-     private suspend fun resetConversation(conversationId: Long, userText: String) {         currentConversation?.close()         currentConversation = null
openassistant/src/main/java/com/vayunmathur/openassistant/util/SentencePieceTokenizer.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/util/SentencePieceTokenizer.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/util/SentencePieceTokenizer.ktdeleted file mode 100644index 0d3088f88e..0000000000--- a/openassistant/src/main/java/com/vayunmathur/openassistant/util/SentencePieceTokenizer.kt+++ /dev/null@@ -1,303 +0,0 @@-package com.vayunmathur.openassistant.util--import android.util.Log-import java.io.File-import java.nio.ByteBuffer-import java.nio.ByteOrder-import java.text.Normalizer-import kotlin.math.min--/**- * Minimal, dependency-free **SentencePiece Unigram** tokenizer for the Gemma- * SentencePiece model (`tokenizer.model`, ~4 MB, 256k vocab) that SigLIP2 uses- * for its text tower.- *- * We need raw token ids to feed SigLIP2's text ONNX model, and litertlm's Gemma- * engine does not expose them, so this is a standalone re-implementation of the- * two pieces we actually need:- *- *  1. **Model parsing** ([load]): the `.model` file is a serialized- *     `sentencepiece.ModelProto`. We hand-parse just the repeated `pieces`- *     (field 1) — each a `SentencePiece{ piece=1:string, score=2:float,- *     type=3:enum }` — because pulling in a protobuf runtime for three fields is- *     overkill. Piece **index == token id**.- *  2. **Encoding** ([encode]): Viterbi best-path Unigram segmentation over the- *     normalized text, with **byte fallback** (Gemma enables it and ships all- *     256 `<0xNN>` byte pieces) so every input is representable.- *- * ## SigLIP2 text preprocessing (flagged review risk)- *- * The exact normalization SigLIP2 applies is the highest-uncertainty part of the- * photos→OpenAssistant embedding move (see the plan's "Key risks"). We apply the- * documented SigLIP convention — lowercase, NFKC, whitespace-collapse, a- * SentencePiece dummy-prefix space, and pad/truncate to [SEQ_LEN] with the pad- * id — and keep every knob a named constant so it is easy to retune against the- * reference `transformers` `Siglip2Processor` output. Image and text vectors- * only line up if this matches, so this is the first thing to verify.- */-class SentencePieceTokenizer private constructor(-    private val pieceToId: HashMap<String, Int>,-    private val scores: FloatArray,-    private val byteToId: IntArray, // 256 entries, -1 if absent-    private val maxPieceLen: Int,-    val unkId: Int,-    val padId: Int,-) {--    companion object {-        private const val TAG = "SentencePieceTokenizer"--        /** SentencePiece meta symbol standing in for a space (U+2581, "▁"). */-        private const val SPACE = '\u2581'--        /** SigLIP2 text tower fixed context length (padded/truncated). */-        const val SEQ_LEN = 64--        // SentencePiece piece types (sentencepiece_model.proto).-        private const val TYPE_NORMAL = 1-        private const val TYPE_UNKNOWN = 2-        private const val TYPE_CONTROL = 3-        private const val TYPE_USER_DEFINED = 4-        private const val TYPE_BYTE = 6--        /**-         * Parse a Gemma `tokenizer.model` file, or null if it can't be read.-         * `padId`/`unkId` default to the Gemma special-token ids and are refined-         * from the parsed pieces where possible.-         */-        fun load(modelFile: File): SentencePieceTokenizer? {-            return try {-                val bytes = modelFile.readBytes()-                parse(bytes)-            } catch (e: Exception) {-                Log.e(TAG, "Failed to load SentencePiece model ${modelFile.absolutePath}", e)-                null-            }-        }--        private fun parse(data: ByteArray): SentencePieceTokenizer {-            val pieces = ArrayList<String>(256_000)-            val scoreList = ArrayList<Float>(256_000)-            val types = ArrayList<Int>(256_000)--            var pos = 0-            val end = data.size-            while (pos < end) {-                val (tag, p1) = readVarint(data, pos)-                pos = p1-                val field = (tag ushr 3).toInt()-                val wire = (tag and 0x7).toInt()-                if (field == 1 && wire == 2) {-                    // pieces: length-delimited SentencePiece message.-                    val (len, p2) = readVarint(data, pos)-                    pos = p2-                    val msgEnd = pos + len.toInt()-                    parsePiece(data, pos, msgEnd, pieces, scoreList, types)-                    pos = msgEnd-                } else {-                    pos = skipField(data, pos, wire)-                }-            }--            val n = pieces.size-            val scoresArr = FloatArray(n) { scoreList[it] }-            val pieceToId = HashMap<String, Int>(n * 2)-            val byteToId = IntArray(256) { -1 }-            var unkId = 3 // Gemma default <unk>-            var padId = 0 // Gemma default <pad>-            var maxLen = 1--            for (id in 0 until n) {-                val piece = pieces[id]-                when (types[id]) {-                    TYPE_UNKNOWN -> unkId = id-                    TYPE_BYTE -> {-                        val b = parseBytePiece(piece)-                        if (b in 0..255) byteToId[b] = id-                    }-                    TYPE_CONTROL -> {-                        if (piece == "<pad>") padId = id-                    }-                    TYPE_NORMAL, TYPE_USER_DEFINED -> {-                        pieceToId[piece] = id-                        val cpLen = piece.codePointCount(0, piece.length)-                        if (cpLen > maxLen) maxLen = cpLen-                    }-                }-            }-            // Cap the DP window; real Gemma pieces are short subwords.-            maxLen = min(maxLen, 48)-            Log.i(TAG, "Loaded SentencePiece: $n pieces, unkId=$unkId, padId=$padId, maxPieceLen=$maxLen")-            return SentencePieceTokenizer(pieceToId, scoresArr, byteToId, maxLen, unkId, padId)-        }--        private fun parsePiece(-            data: ByteArray,-            start: Int,-            end: Int,-            pieces: ArrayList<String>,-            scores: ArrayList<Float>,-            types: ArrayList<Int>,-        ) {-            var pos = start-            var piece = ""-            var score = 0f-            var type = TYPE_NORMAL-            while (pos < end) {-                val (tag, p1) = readVarint(data, pos)-                pos = p1-                val field = (tag ushr 3).toInt()-                val wire = (tag and 0x7).toInt()-                when {-                    field == 1 && wire == 2 -> {-                        val (len, p2) = readVarint(data, pos)-                        pos = p2-                        val l = len.toInt()-                        piece = String(data, pos, l, Charsets.UTF_8)-                        pos += l-                    }-                    field == 2 && wire == 5 -> {-                        score = ByteBuffer.wrap(data, pos, 4).order(ByteOrder.LITTLE_ENDIAN).float-                        pos += 4-                    }-                    field == 3 && wire == 0 -> {-                        val (t, p2) = readVarint(data, pos)-                        pos = p2-                        type = t.toInt()-                    }-                    else -> pos = skipField(data, pos, wire)-                }-            }-            pieces.add(piece)-            scores.add(score)-            types.add(type)-        }--        /** "<0x1F>" -> 31, else -1. */-        private fun parseBytePiece(piece: String): Int {-            if (piece.length == 6 && piece.startsWith("<0x") && piece.endsWith(">")) {-                return piece.substring(3, 5).toIntOrNull(16) ?: -1-            }-            return -1-        }--        private fun readVarint(data: ByteArray, start: Int): Pair<Long, Int> {-            var result = 0L-            var shift = 0-            var pos = start-            while (true) {-                val b = data[pos].toInt() and 0xFF-                pos++-                result = result or ((b and 0x7F).toLong() shl shift)-                if (b and 0x80 == 0) break-                shift += 7-            }-            return result to pos-        }--        private fun skipField(data: ByteArray, start: Int, wire: Int): Int {-            var pos = start-            when (wire) {-                0 -> pos = readVarint(data, pos).second-                1 -> pos += 8-                2 -> {-                    val (len, p) = readVarint(data, pos)-                    pos = p + len.toInt()-                }-                5 -> pos += 4-                else -> throw IllegalStateException("Unsupported wire type $wire")-            }-            return pos-        }-    }--    /**-     * Encode [text] into a fixed [SEQ_LEN]-long id array (SigLIP2 text input),-     * padded with [padId] and truncated as needed.-     */-    fun encode(text: String): IntArray {-        val ids = encodeVariable(text)-        val out = IntArray(SEQ_LEN) { padId }-        val take = min(ids.size, SEQ_LEN)-        for (i in 0 until take) out[i] = ids[i]-        return out-    }--    /** Viterbi Unigram segmentation of the normalized text (no padding). */-    private fun encodeVariable(text: String): IntArray {-        val normalized = normalize(text)-        if (normalized.isEmpty()) return IntArray(0)--        // Work over Unicode code points so multi-byte chars index cleanly.-        val cps = normalized.codePoints().toArray()-        val n = cps.size-        val bestScore = DoubleArray(n + 1) { Double.NEGATIVE_INFINITY }-        bestScore[0] = 0.0-        val prev = IntArray(n + 1) { -1 }-        val stepIds = arrayOfNulls<IntArray>(n + 1)--        for (i in 0 until n) {-            if (bestScore[i] == Double.NEGATIVE_INFINITY) continue-            // (a) Try every vocab piece starting at i.-            val maxL = min(maxPieceLen, n - i)-            val sb = StringBuilder()-            for (l in 1..maxL) {-                sb.appendCodePoint(cps[i + l - 1])-                val id = pieceToId[sb.toString()] ?: continue-                val sc = bestScore[i] + scores[id]-                if (sc > bestScore[i + l]) {-                    bestScore[i + l] = sc-                    prev[i + l] = i-                    stepIds[i + l] = intArrayOf(id)-                }-            }-            // (b) Byte fallback for the single code point at i, so every-            // position stays reachable even with no matching piece.-            val ch = String(Character.toChars(cps[i]))-            val chBytes = ch.toByteArray(Charsets.UTF_8)-            val fallbackIds = IntArray(chBytes.size)-            var ok = true-            var fbScore = bestScore[i]-            for (k in chBytes.indices) {-                val bid = byteToId[chBytes[k].toInt() and 0xFF]-                if (bid < 0) { ok = false; break }-                fallbackIds[k] = bid-                fbScore += scores[bid]-            }-            if (ok && fbScore > bestScore[i + 1]) {-                bestScore[i + 1] = fbScore-                prev[i + 1] = i-                stepIds[i + 1] = fallbackIds-            }-        }--        if (bestScore[n] == Double.NEGATIVE_INFINITY) {-            // Should not happen with byte fallback; degrade to a single unk.-            return intArrayOf(unkId)-        }--        // Backtrack, collecting ids, then reverse.-        val rev = ArrayList<Int>()-        var pos = n-        while (pos > 0) {-            val ids = stepIds[pos] ?: intArrayOf(unkId)-            for (k in ids.indices.reversed()) rev.add(ids[k])-            pos = prev[pos]-        }-        rev.reverse()-        return rev.toIntArray()-    }--    /**-     * SigLIP text normalization: lowercase, NFKC, collapse whitespace, then the-     * SentencePiece dummy-prefix space with spaces mapped to [SPACE] (▁).-     */-    private fun normalize(text: String): String {-        val lowered = text.lowercase()-        val nfkc = Normalizer.normalize(lowered, Normalizer.Form.NFKC)-        val collapsed = nfkc.trim().replace(Regex("\\s+"), " ")-        if (collapsed.isEmpty()) return ""-        // Dummy prefix + space→▁ (SentencePiece convention).-        return (" $collapsed").replace(' ', SPACE)-    }-}
openassistant/src/main/java/com/vayunmathur/openassistant/util/SiglipEmbedder.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/util/SiglipEmbedder.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/util/SiglipEmbedder.ktdeleted file mode 100644index f65aaca127..0000000000--- a/openassistant/src/main/java/com/vayunmathur/openassistant/util/SiglipEmbedder.kt+++ /dev/null@@ -1,319 +0,0 @@-package com.vayunmathur.openassistant.util--import ai.onnxruntime.OnnxTensor-import ai.onnxruntime.OrtEnvironment-import ai.onnxruntime.OrtSession-import android.content.Context-import android.graphics.Bitmap-import android.graphics.BitmapFactory-import android.util.Log-import com.vayunmathur.library.downloadservice.ModelUrls-import java.io.File-import java.nio.ByteBuffer-import java.nio.ByteOrder-import java.nio.FloatBuffer-import java.nio.LongBuffer-import kotlin.math.sqrt--/**- * On-device **SigLIP2-base** image/text embedder on ONNX Runtime, the semantic- * search provider OpenAssistant serves to the photos app over [InferenceService].- *- * SigLIP puts images and text in one shared space: the image encoder turns a- * photo into a vector, the text encoder turns a query into a vector, and their- * cosine similarity says how well the phrase describes the photo. photos stores- * the returned vectors and does cosine locally.- *- * Mirrors the old on-device `photos/.../ClipEmbedder.kt` (lazy single-threaded- * [OrtSession]s, [OnnxTensor] + `run`, L2-normalize, [floatsToBytes]) but with- * SigLIP2 preprocessing and the Gemma [SentencePieceTokenizer]:- *  - **Vision** ([VISION_FILE]): resize **directly** to [IMAGE_SIZE]² (square,- *    no shortest-side + center-crop), rescale 1/255, normalize mean/std 0.5 →- *    `(px-127.5)/127.5`, packed NCHW `[1,3,224,224]`.- *  - **Text** ([TEXT_FILE]): tokenize with [SentencePieceTokenizer] to a fixed- *    [SentencePieceTokenizer.SEQ_LEN] and run the text tower.- *- * The embedding [dim] is read from the model at run time (SigLIP2-base = 768)- * and flows back to photos via the IPC `dim` key, so nothing hardcodes it.- *- * The three model files are downloaded on demand to `getExternalFilesDir(null)`- * (see [InferenceService]); if any is missing [filesPresent] is false and the- * caller triggers the download instead.- */-object SiglipEmbedder {-    /** HuggingFace source, also the model id photos uses for change-detection. */-    const val MODEL_ID = "onnx-community/siglip2-base-patch16-224-ONNX"--    /**-     * Bump when the downloaded SigLIP2 files or preprocessing change, so-     * [com.vayunmathur.openassistant.util.AssistantViewModel] deletes the stale-     * on-disk files and they re-download on the next embedding request.-     */-    const val MODEL_VERSION = 1--    // On-disk names shared with the mirror-first downloader (single source of-    // truth in ModelUrls) so file-presence gating and the fetch always agree.-    const val VISION_FILE = ModelUrls.SIGLIP_VISION_FILE-    const val TEXT_FILE = ModelUrls.SIGLIP_TEXT_FILE-    const val TOKENIZER_FILE = ModelUrls.SIGLIP_TOKENIZER_FILE--    /** Square RGB input side the SigLIP2 image encoder expects. */-    const val IMAGE_SIZE = 224--    private const val TAG = "SiglipEmbedder"--    private val env: OrtEnvironment by lazy { OrtEnvironment.getEnvironment() }-    private val lock = Any()--    @Volatile private var visionSession: OrtSession? = null-    @Volatile private var textSession: OrtSession? = null-    @Volatile private var tokenizer: SentencePieceTokenizer? = null-    @Volatile private var visionOutputName: String? = null-    @Volatile private var textOutputName: String? = null-    @Volatile private var initTried = false-    @Volatile private var initOk = false--    /** True only if all three model files are present on disk. */-    fun filesPresent(context: Context): Boolean =-        modelFile(context, VISION_FILE).exists() &&-            modelFile(context, TEXT_FILE).exists() &&-            modelFile(context, TOKENIZER_FILE).exists()--    /** True if both encoders + tokenizer are loaded and ready. */-    fun isAvailable(context: Context): Boolean = ensureInit(context)--    /** Embedding dimension read from the vision model, or 0 if not initialised. */-    fun dim(context: Context): Int {-        if (!ensureInit(context)) return 0-        return cachedDim-    }--    @Volatile private var cachedDim = 0--    private fun modelFile(context: Context, name: String): File =-        File(context.applicationContext.getExternalFilesDir(null), name)--    private fun ensureInit(context: Context): Boolean {-        if (initOk) return true-        synchronized(lock) {-            if (initOk) return true-            if (initTried) return false-            initTried = true-            return try {-                val app = context.applicationContext-                if (!filesPresent(app)) {-                    Log.w(TAG, "SigLIP2 model files missing; embedder unavailable")-                    initTried = false // allow a retry once files are downloaded-                    return false-                }-                val tok = SentencePieceTokenizer.load(modelFile(app, TOKENIZER_FILE)) ?: run {-                    Log.w(TAG, "Failed to load SentencePiece tokenizer")-                    return false-                }-                val opts = OrtSession.SessionOptions().apply {-                    // Single-threaded keeps sustained CPU/battery use low.-                    setIntraOpNumThreads(1)-                    setInterOpNumThreads(1)-                }-                visionSession = env.createSession(modelFile(app, VISION_FILE).absolutePath, opts)-                textSession = env.createSession(modelFile(app, TEXT_FILE).absolutePath, opts)-                tokenizer = tok-                // These sub-model exports emit BOTH `last_hidden_state` and the-                // pooled embedding (`pooler_output`); we must read the pooled one,-                // not output index 0, or the vectors are meaningless.-                visionOutputName = bestOutputName(visionSession!!)-                textOutputName = bestOutputName(textSession!!)-                cachedDim = visionSession?.let { readOutputDim(it, visionOutputName!!) } ?: 0-                initOk = true-                Log.i(TAG, "SigLIP2 embedder ready (dim=$cachedDim, visionOut=$visionOutputName, textOut=$textOutputName)")-                true-            } catch (e: Throwable) {-                Log.e(TAG, "Failed to initialise SigLIP2 embedder", e)-                closeLocked()-                false-            }-        }-    }--    /**-     * Pick the output that holds the pooled embedding. SigLIP2's vision/text-     * sub-model exports emit `last_hidden_state` (rank-3) plus the pooled-     * `pooler_output` (rank-2 `[1, dim]`) — the latter is the retrieval vector.-     * Prefer a name hinting "pool"/"embed", else the first rank-2 output, else-     * output 0.-     */-    private fun bestOutputName(session: OrtSession): String {-        val info = session.outputInfo-        info.keys.firstOrNull { it.contains("pool", ignoreCase = true) }?.let { return it }-        info.keys.firstOrNull { it.contains("embed", ignoreCase = true) }?.let { return it }-        info.entries.firstOrNull { (it.value.info as? ai.onnxruntime.TensorInfo)?.shape?.size == 2 }-            ?.let { return it.key }-        return info.keys.first()-    }--    private fun readOutputDim(session: OrtSession, outputName: String): Int {-        return try {-            val info = session.outputInfo[outputName]!!.info as ai.onnxruntime.TensorInfo-            info.shape.last().toInt()-        } catch (_: Exception) {-            0-        }-    }--    /**-     * Embed the image at [file] into an L2-normalised vector, or null on-     * failure. The file is a decoded copy handed over by [InferenceService].-     */-    fun imageEmbedding(context: Context, file: File): FloatArray? {-        if (!ensureInit(context)) return null-        val session = visionSession ?: return null-        val bitmap = try {-            BitmapFactory.decodeFile(file.absolutePath)-        } catch (e: Exception) {-            Log.e(TAG, "Failed to decode image ${file.absolutePath}", e)-            null-        } ?: return null-        val input = try {-            preprocess(bitmap)-        } finally {-            bitmap.recycle()-        }-        return try {-            synchronized(lock) {-                val inputName = session.inputNames.iterator().next()-                val outName = visionOutputName ?: bestOutputName(session)-                OnnxTensor.createTensor(-                    env,-                    FloatBuffer.wrap(input),-                    longArrayOf(1, 3, IMAGE_SIZE.toLong(), IMAGE_SIZE.toLong()),-                ).use { tensor ->-                    session.run(mapOf(inputName to tensor)).use { result ->-                        val out = result.get(outName).get() as OnnxTensor-                        val vec = FloatArray(out.info.shape.last().toInt())-                        out.floatBuffer.get(vec)-                        l2Normalize(vec)-                    }-                }-            }-        } catch (e: Exception) {-            Log.e(TAG, "Image embedding failed", e)-            null-        }-    }--    /**-     * Embed [text] into an L2-normalised vector in the SAME space as-     * [imageEmbedding], or null on failure.-     */-    fun textEmbedding(context: Context, text: String): FloatArray? {-        if (!ensureInit(context)) return null-        val session = textSession ?: return null-        val tok = tokenizer ?: return null-        val ids = tok.encode(text)-        val longIds = LongArray(ids.size) { ids[it].toLong() }-        return try {-            synchronized(lock) {-                val tensors = HashMap<String, OnnxTensor>()-                try {-                    for (name in session.inputNames) {-                        val lname = name.lowercase()-                        when {-                            lname.contains("mask") -> {-                                // SigLIP attends over the full padded sequence; all-ones.-                                val mask = LongArray(ids.size) { 1L }-                                tensors[name] = OnnxTensor.createTensor(-                                    env, LongBuffer.wrap(mask), longArrayOf(1, ids.size.toLong())-                                )-                            }-                            lname.contains("position") -> {-                                // Sequential positions 0..seqLen-1.-                                val pos = LongArray(ids.size) { it.toLong() }-                                tensors[name] = OnnxTensor.createTensor(-                                    env, LongBuffer.wrap(pos), longArrayOf(1, ids.size.toLong())-                                )-                            }-                            else -> {-                                // input_ids-                                tensors[name] = OnnxTensor.createTensor(-                                    env, LongBuffer.wrap(longIds), longArrayOf(1, ids.size.toLong())-                                )-                            }-                        }-                    }-                    session.run(tensors).use { result ->-                        val outName = textOutputName ?: bestOutputName(session)-                        val out = result.get(outName).get() as OnnxTensor-                        val vec = FloatArray(out.info.shape.last().toInt())-                        out.floatBuffer.get(vec)-                        l2Normalize(vec)-                    }-                } finally {-                    tensors.values.forEach { it.close() }-                }-            }-        } catch (e: Exception) {-            Log.e(TAG, "Text embedding failed", e)-            null-        }-    }--    fun close() {-        synchronized(lock) { closeLocked() }-    }--    private fun closeLocked() {-        try { visionSession?.close() } catch (_: Exception) {}-        try { textSession?.close() } catch (_: Exception) {}-        visionSession = null-        textSession = null-        tokenizer = null-        visionOutputName = null-        textOutputName = null-        cachedDim = 0-        initOk = false-        initTried = false-    }--    /**-     * SigLIP preprocessing: resize [src] **directly** to [IMAGE_SIZE]² (no-     * center-crop), rescale to [0,1], normalize mean/std 0.5 → (px-127.5)/127.5,-     * packed NCHW (RGB).-     */-    private fun preprocess(src: Bitmap): FloatArray {-        val safe = if (src.config == Bitmap.Config.HARDWARE || src.config == null) {-            src.copy(Bitmap.Config.ARGB_8888, false)-        } else src--        val scaled = Bitmap.createScaledBitmap(safe, IMAGE_SIZE, IMAGE_SIZE, true)-        val px = IntArray(IMAGE_SIZE * IMAGE_SIZE)-        scaled.getPixels(px, 0, IMAGE_SIZE, 0, 0, IMAGE_SIZE, IMAGE_SIZE)-        if (scaled != safe) scaled.recycle()-        if (safe != src) safe.recycle()--        val area = IMAGE_SIZE * IMAGE_SIZE-        val out = FloatArray(3 * area)-        for (i in 0 until area) {-            val p = px[i]-            out[i] = (((p shr 16) and 0xFF) - 127.5f) / 127.5f          // R plane-            out[area + i] = (((p shr 8) and 0xFF) - 127.5f) / 127.5f    // G plane-            out[2 * area + i] = ((p and 0xFF) - 127.5f) / 127.5f        // B plane-        }-        return out-    }--    // ---- Shared math + serialisation helpers ------    fun l2Normalize(values: FloatArray): FloatArray {-        var norm = 0f-        for (v in values) norm += v * v-        norm = sqrt(norm)-        if (norm == 0f) return values-        return FloatArray(values.size) { values[it] / norm }-    }--    fun floatsToBytes(values: FloatArray): ByteArray {-        val buffer = ByteBuffer.allocate(values.size * 4).order(ByteOrder.LITTLE_ENDIAN)-        for (v in values) buffer.putFloat(v)-        return buffer.array()-    }-}
openassistant/src/main/res/xml/data_extraction_rules.xml
diff --git a/openassistant/src/main/res/xml/data_extraction_rules.xml b/openassistant/src/main/res/xml/data_extraction_rules.xmlindex 27cada0283..d34f10ae26 100644--- a/openassistant/src/main/res/xml/data_extraction_rules.xml+++ b/openassistant/src/main/res/xml/data_extraction_rules.xml@@ -6,11 +6,9 @@                               conversation history plus remembered facts. Free-form user                               text, so it can contain anything.        external/              on-demand model downloads in getExternalFilesDir(null):-                              gemma4-2b.litertlm, the SigLIP2 ONNX encoders and-                              tokenizer.model. Gigabytes, and re-downloadable.+                              gemma4-2b.litertlm. Gigabytes, and re-downloadable.        file/datastore_default.preferences_pb  model download progress and version markers-                              (progress_*, dlid_*, siglip_model_version). Meaningless once-                              the models are gone.+                              (progress_*, dlid_*). Meaningless once the models are gone.        cache/                 recordings and attachment scratch files; Android never backs                               up cacheDir.        sharedpref/secure_prefs  keystore-wrapped SQLCipher passphrase.
photos/src/main/AndroidManifest.xml
diff --git a/photos/src/main/AndroidManifest.xml b/photos/src/main/AndroidManifest.xmlindex 429f9fa0ec..861e8b4c58 100644--- a/photos/src/main/AndroidManifest.xml+++ b/photos/src/main/AndroidManifest.xml@@ -21,13 +21,6 @@     <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />     <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />     <uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />--    <uses-permission android:name="com.vayunmathur.openassistant.permission.ACCESS_INFERENCE" />--    <queries>-        <package android:name="com.vayunmathur.openassistant" />-    </queries>-     <application         android:allowBackup="true"         android:backupAgent=".util.AppBackupAgent"
proguard-rules.pro
diff --git a/proguard-rules.pro b/proguard-rules.proindex 7d0fa25118..04a9d58c33 100644--- a/proguard-rules.pro+++ b/proguard-rules.pro@@ -90,10 +90,6 @@ -keep interface com.vayunmathur.stockfish.** { *; } -dontwarn com.vayunmathur.stockfish.** -# BouncyCastle (post-quantum crypto for Office): keep providers/algorithms found via reflection.--keep class org.bouncycastle.** { *; }--dontwarn org.bouncycastle.**- # gRPC + okhttp + protobuf-lite (:appstore Accrescent source). grpc-okhttp is the first # okhttp in the repo. grpc looks up its transport/name-resolver providers via reflection and # META-INF/services; okhttp/okio and grpc reference optional compile-time deps (Conscrypp,
sdk/openassistant/src/main/java/com/vayunmathur/sdk/openassistant/Exceptions.kt
diff --git a/sdk/openassistant/src/main/java/com/vayunmathur/sdk/openassistant/Exceptions.kt b/sdk/openassistant/src/main/java/com/vayunmathur/sdk/openassistant/Exceptions.ktindex 4ff490ce41..397b39342d 100644--- a/sdk/openassistant/src/main/java/com/vayunmathur/sdk/openassistant/Exceptions.kt+++ b/sdk/openassistant/src/main/java/com/vayunmathur/sdk/openassistant/Exceptions.kt@@ -4,29 +4,3 @@ class AssistantNotInstalledException :     Exception("OpenAssistant app is not installed on this device")  class AssistantException(message: String) : Exception(message)--/**- * OpenAssistant is installed but its `versionCode` is below- * [OpenAssistant.MIN_EMBED_VERSION_CODE], so it predates embedding support and- * would silently ignore an embed request. The caller should prompt the user to- * update OpenAssistant.- */-class EmbeddingUnsupportedException :-    Exception("The installed OpenAssistant is too old to provide embeddings; please update it")--/**- * OpenAssistant is up and the models are ready, but this specific request could- * not be embedded (e.g. the image failed to decode on OpenAssistant's side).- * Unlike the other embedding exceptions this is **per-item**: the caller should- * skip this item rather than treat the whole provider as unavailable.- */-class EmbeddingImageFailedException(message: String) : Exception(message)--/**- * OpenAssistant accepted the embed request but the SigLIP2 models are still- * downloading on demand, so no vector is available yet. [progress] is a 0..1- * fraction when known (else 0). The caller should retry later and can surface- * the progress in its UI.- */-class EmbeddingModelDownloadingException(val progress: Double = 0.0) :-    Exception("OpenAssistant is downloading the embedding models (progress=$progress)")
sdk/openassistant/src/main/java/com/vayunmathur/sdk/openassistant/OpenAssistant.kt
diff --git a/sdk/openassistant/src/main/java/com/vayunmathur/sdk/openassistant/OpenAssistant.kt b/sdk/openassistant/src/main/java/com/vayunmathur/sdk/openassistant/OpenAssistant.ktindex e441c5f273..a981b40400 100644--- a/sdk/openassistant/src/main/java/com/vayunmathur/sdk/openassistant/OpenAssistant.kt+++ b/sdk/openassistant/src/main/java/com/vayunmathur/sdk/openassistant/OpenAssistant.kt@@ -1,18 +1,14 @@ package com.vayunmathur.sdk.openassistant -import android.content.ClipData import android.content.ComponentName import android.content.Context import android.content.Intent-import android.net.Uri import android.os.Handler import android.os.Looper import android.os.ResultReceiver import com.vayunmathur.library.util.SecureResultReceiver import kotlinx.coroutines.suspendCancellableCoroutine import kotlinx.coroutines.withTimeout-import java.nio.ByteBuffer-import java.nio.ByteOrder import kotlin.coroutines.resume import kotlin.coroutines.resumeWithException @@ -21,36 +17,8 @@ class OpenAssistant(private val context: Context, private val timeoutMs: Long =     companion object {         private const val OA_PACKAGE = "com.vayunmathur.openassistant"         private const val OA_SERVICE = "$OA_PACKAGE.util.InferenceService"--        /**-         * Lowest OpenAssistant `versionCode` that ships the embedding provider-         * (SigLIP2 image/text embedding over [InferenceService]). Must stay in-         * lockstep with the OA app's `versionCode` (root `version.txt`) at the-         * build that first shipped embedding support. Any OA older than this-         * would silently ignore an embed intent, so we detect it up front (no-         * timeout) and report [EmbeddingSupport.NEEDS_UPDATE].-         */-        const val MIN_EMBED_VERSION_CODE = 20260708L--        /** Embedding runs can involve a first-time model load; allow more time. */-        private const val EMBED_TIMEOUT_MS = 120_000L-    }--    /** Result of the fast, synchronous embedding-capability probe. */-    enum class EmbeddingSupport {-        /** OpenAssistant is not installed. */-        NOT_INSTALLED,--        /** Installed but too old to provide embeddings (< [MIN_EMBED_VERSION_CODE]). */-        NEEDS_UPDATE,--        /** Installed and recent enough; embedding requests will be accepted. */-        READY,     } -    /** Model identity behind the embeddings, for change-detection by callers. */-    data class EmbeddingInfo(val modelId: String, val dim: Int)-     suspend fun generate(prompt: String): String {         if (!isAvailable()) throw AssistantNotInstalledException()         return withTimeout(timeoutMs) {@@ -74,81 +42,10 @@ class OpenAssistant(private val context: Context, private val timeoutMs: Long =         }     } -    /**-     * Fast (no IPC round-trip) check of whether OpenAssistant can serve-     * embeddings, based purely on the installed package's `versionCode`. This is-     * what makes "needs update" instant instead of waiting for a timeout.-     */-    fun embeddingSupport(): EmbeddingSupport {-        val info = try {-            context.packageManager.getPackageInfo(OA_PACKAGE, 0)-        } catch (_: Exception) {-            return EmbeddingSupport.NOT_INSTALLED-        }-        // minSdk 31, so longVersionCode is always available.-        return if (info.longVersionCode >= MIN_EMBED_VERSION_CODE) {-            EmbeddingSupport.READY-        } else {-            EmbeddingSupport.NEEDS_UPDATE-        }-    }--    /**-     * Embed a search phrase into an L2-normalised SigLIP2 text vector, in the-     * same shared space as [embedImage].-     *-     * @throws AssistantNotInstalledException OpenAssistant is not installed.-     * @throws EmbeddingUnsupportedException OpenAssistant is too old.-     * @throws EmbeddingModelDownloadingException the models are still downloading.-     * @throws AssistantException any other failure.-     */-    suspend fun embedText(query: String): FloatArray {-        requireEmbeddingReady()-        return withTimeout(EMBED_TIMEOUT_MS) {-            dispatchEmbedding(mode = "text", text = query, uri = null).embedding-        }-    }--    /**-     * Embed an image (given by a readable `content://` [uri]) into an-     * L2-normalised SigLIP2 image vector. OpenAssistant decodes the image, so-     * the caller does not decode a bitmap. Same failure modes as [embedText].-     */-    suspend fun embedImage(uri: Uri): FloatArray {-        requireEmbeddingReady()-        return withTimeout(EMBED_TIMEOUT_MS) {-            dispatchEmbedding(mode = "image", text = null, uri = uri).embedding-        }-    }--    /**-     * Probe the embedding provider for its model id and dimensionality without-     * running an embedding. Callers use [EmbeddingInfo.modelId] to detect a-     * model change (and re-index) and [EmbeddingInfo.dim] for sizing.-     *-     * Same failure modes as [embedText] (including-     * [EmbeddingModelDownloadingException] if the models aren't ready yet).-     */-    suspend fun embeddingInfo(): EmbeddingInfo {-        requireEmbeddingReady()-        return withTimeout(timeoutMs) {-            val result = dispatchEmbedding(mode = "info", text = null, uri = null)-            EmbeddingInfo(result.modelId, result.dim)-        }-    }-     suspend fun close() {         // No persistent connection to clean up; reserved for future use.     } -    private fun requireEmbeddingReady() {-        when (embeddingSupport()) {-            EmbeddingSupport.NOT_INSTALLED -> throw AssistantNotInstalledException()-            EmbeddingSupport.NEEDS_UPDATE -> throw EmbeddingUnsupportedException()-            EmbeddingSupport.READY -> {}-        }-    }-     private suspend fun dispatchInference(prompt: String, schema: String?): String =         suspendCancellableCoroutine { cont ->             val receiver = SecureResultReceiver(Handler(Looper.getMainLooper())) { code, data ->@@ -174,69 +71,4 @@ class OpenAssistant(private val context: Context, private val timeoutMs: Long =                 cont.resumeWithException(AssistantException("Failed to start InferenceService: ${e.message}"))             }         }--    /** Raw embedding result parsed from a success bundle (code 0). */-    private class EmbedResult(val embedding: FloatArray, val modelId: String, val dim: Int)--    private suspend fun dispatchEmbedding(mode: String, text: String?, uri: Uri?): EmbedResult =-        suspendCancellableCoroutine { cont ->-            val receiver = SecureResultReceiver(Handler(Looper.getMainLooper())) { code, data ->-                when (code) {-                    0 -> {-                        val modelId = data?.getString("model_id") ?: ""-                        val dim = data?.getInt("dim") ?: 0-                        // "info" requests carry no vector; text/image requests do.-                        val bytes = data?.getByteArray("embedding")-                        if (mode != "info" && bytes == null) {-                            cont.resumeWithException(AssistantException("Embedding result missing vector"))-                        } else {-                            cont.resume(EmbedResult(bytes?.let { bytesToFloats(it) } ?: FloatArray(0), modelId, dim))-                        }-                    }-                    2 -> {-                        val progress = data?.getDouble("progress") ?: 0.0-                        cont.resumeWithException(EmbeddingModelDownloadingException(progress))-                    }-                    else -> {-                        val error = data?.getString("error") ?: "Embedding failed"-                        // per_item = the provider is up but this specific request-                        // couldn't be embedded → caller skips just this item.-                        if (data?.getBoolean("per_item") == true) {-                            cont.resumeWithException(EmbeddingImageFailedException(error))-                        } else {-                            cont.resumeWithException(AssistantException(error))-                        }-                    }-                }-            }--            val intent = Intent().apply {-                component = ComponentName(OA_PACKAGE, OA_SERVICE)-                putExtra("embed_mode", mode)-                if (text != null) putExtra("user_text", text)-                if (uri != null) {-                    // Single content:// URI in an ArrayList<Uri> for the service to-                    // read, AND in ClipData so FLAG_GRANT_READ_URI_PERMISSION-                    // actually grants access — the grant flag applies to the-                    // intent's data/ClipData, NOT to URIs buried in extras.-                    putParcelableArrayListExtra("image_uris", arrayListOf(uri))-                    clipData = ClipData.newRawUri("image_uris", uri)-                    addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)-                }-                putExtra("RECEIVER", receiver as ResultReceiver)-            }--            try {-                context.startForegroundService(intent)-            } catch (e: Exception) {-                cont.resumeWithException(AssistantException("Failed to start InferenceService: ${e.message}"))-            }-        }--    private fun bytesToFloats(bytes: ByteArray): FloatArray {-        val buffer = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN)-        val out = FloatArray(bytes.size / 4)-        for (i in out.indices) out[i] = buffer.float-        return out-    } }
speech/src/main/java/com/vayunmathur/speech/util/PiperTtsService.kt
diff --git a/speech/src/main/java/com/vayunmathur/speech/util/PiperTtsService.kt b/speech/src/main/java/com/vayunmathur/speech/util/PiperTtsService.ktnew file mode 100644index 0000000000..e69de29bb2