E3: the Kotlin/Java shell over a JNI bridge into Rust (RUST.md)
Two Java classes (MainActivity, NotificationService) hand their lifecycle to a new android-shell crate built on client-core; client-core gains notifications.rs (the /notifications SSE parse and attention_line, ported from Notifications.kt). Packaged as a new app/shellApp Gradle module rather than a rewrite of app/androidApp in place, so that module's working Compose UI is untouched. Both pass conditions held on the emulator: a notification arrived in Android's drawer with the app closed, and a shared text share landed as a real message in a sandbox session's transcript. Found and fixed three real bugs along the way (a silently-wrong JNI signature from a generic JObject parameter, a class-by-name lookup failing on this crate's own background thread for lack of an app ClassLoader, and onStartCommand opening two /notifications connections per enrollment -- the last a latent bug in Notifications.kt itself). Full account, exact commands and what was deliberately cut are in RUST.md's E3 box. Co-Authored-By: Claude Sonnet <noreply@anthropic.com>
This commit is contained in:
1 parent
8adda94a7a
commit
c9b273ff16
16 files changed
+2996
-6
No files matched your search
@@ -0,0 +1,115 @@
|
||||
plugins { alias(libs.plugins.androidApplication) }
|
||||
|
||||
// E3 (RUST.md): the Kotlin/Java shell being replaced by a thin JNI bridge
|
||||
// into Rust (`../../android-shell`). Deliberately its own module rather
|
||||
// than a rewrite of `:androidApp` in place -- that module is ~13,000 lines
|
||||
// of working Compose UI this experiment does not touch, and the two can be
|
||||
// installed side by side on the same development device (see
|
||||
// `settings.SCHEME`'s doc in `android-shell` for why the deep-link scheme
|
||||
// and Keystore alias are not the production app's). No Compose plugin, no
|
||||
// Kotlin source of its own: `MainActivity`/`NotificationService` are plain
|
||||
// Java, and the CA constant below is generated as Java too.
|
||||
//
|
||||
// The CA this build pins is baked in the same way `androidApp`'s does --
|
||||
// see that module's `build.gradle.kts` comment for the reasoning (the
|
||||
// trust boundary follows the machine that builds, never a pasted copy).
|
||||
// `PinnedCa.java`'s package must match `android-shell`'s
|
||||
// `settings::load_pinned_ca` lookup (`com/example/aiapp/shell/PinnedCa`).
|
||||
val pinnedCaPath: String =
|
||||
System.getenv("AI_APP_CA")
|
||||
?: "${System.getenv("XDG_CONFIG_HOME") ?: "${System.getProperty("user.home")}/.config"}" +
|
||||
"/ai-app/certs/ca.pem"
|
||||
|
||||
abstract class GeneratePinnedCa : DefaultTask() {
|
||||
@get:Input abstract val caPath: Property<String>
|
||||
|
||||
@get:InputFile
|
||||
@get:Optional
|
||||
@get:PathSensitive(PathSensitivity.NONE)
|
||||
abstract val caCertificate: RegularFileProperty
|
||||
|
||||
@get:OutputDirectory abstract val outputDir: DirectoryProperty
|
||||
|
||||
@TaskAction
|
||||
fun generate() {
|
||||
val path = caPath.get()
|
||||
val ca = File(path)
|
||||
if (!ca.isFile) {
|
||||
throw GradleException(
|
||||
"No CA certificate at $path.\n" +
|
||||
"Start ai-server (or app/ui-sandbox.sh) once on this machine first -- it " +
|
||||
"generates the CA this build pins.\n" +
|
||||
"Set AI_APP_CA=/path/to/ca.pem to build against a different one."
|
||||
)
|
||||
}
|
||||
val pem = ca.readText().trim()
|
||||
if (!pem.startsWith("-----BEGIN CERTIFICATE-----")) {
|
||||
throw GradleException("$path is not a PEM certificate.")
|
||||
}
|
||||
val dir = outputDir.get().dir("com/example/aiapp/shell").asFile
|
||||
dir.mkdirs()
|
||||
// Same reasoning as androidApp's generatePinnedCert: the text block
|
||||
// must start immediately after the opening `"""`, or
|
||||
// CertificateFactory stops recognising the "-----BEGIN" preamble.
|
||||
File(dir, "PinnedCa.java")
|
||||
.writeText(
|
||||
"""
|
||||
|// Generated from $path by the generatePinnedCa task. Do not edit.
|
||||
|package com.example.aiapp.shell;
|
||||
|
|
||||
|public final class PinnedCa {
|
||||
| private PinnedCa() {}
|
||||
| public static final String PINNED_CA_PEM = ""${'"'}
|
||||
|$pem""${'"'};
|
||||
|}
|
||||
|"""
|
||||
.trimMargin()
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
val generatePinnedCa =
|
||||
tasks.register<GeneratePinnedCa>("generatePinnedCa") {
|
||||
val ca = file(pinnedCaPath)
|
||||
caPath.set(pinnedCaPath)
|
||||
if (ca.isFile) {
|
||||
caCertificate.set(ca)
|
||||
}
|
||||
}
|
||||
|
||||
android {
|
||||
namespace = "com.example.aiapp.shell"
|
||||
compileSdk = 37
|
||||
|
||||
defaultConfig {
|
||||
applicationId = "com.example.aiapp.shell"
|
||||
minSdk = 24
|
||||
targetSdk = 37
|
||||
versionCode = 1
|
||||
versionName = "1.0"
|
||||
}
|
||||
compileOptions {
|
||||
sourceCompatibility = JavaVersion.VERSION_21
|
||||
targetCompatibility = JavaVersion.VERSION_21
|
||||
}
|
||||
}
|
||||
|
||||
androidComponents {
|
||||
onVariants { variant ->
|
||||
variant.sources.java?.addGeneratedSourceDirectory(generatePinnedCa, GeneratePinnedCa::outputDir)
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
// The Keystore-sealed enrollment (ServerStore/ServerSettings) --
|
||||
// android-shell's settings.rs calls into this Kotlin class directly
|
||||
// over JNI rather than re-sealing the token in Rust; see that file's
|
||||
// module doc.
|
||||
implementation(project(":link"))
|
||||
// NotificationCompat/NotificationManagerCompat/NotificationChannelCompat/
|
||||
// ServiceCompat -- android-shell's notify.rs calls these classes over
|
||||
// JNI so the pre-26 fallback behaviour (no channels) lives once, in
|
||||
// the library that already has it, rather than being re-derived as a
|
||||
// set of Build.VERSION.SDK_INT branches in Rust.
|
||||
implementation(libs.androidx.core.ktx)
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
xmlns:tools="http://schemas.android.com/tools">
|
||||
<!-- Mirrors androidApp's manifest (AGENTS.md: reuse it rather than
|
||||
re-deriving it) for the permissions and declarations E3 actually
|
||||
exercises. Not carried over: the QR scanner activity (this
|
||||
experiment enrolls via the aiappshell://enroll deep link directly,
|
||||
per AGENTS.md's ui-sandbox.sh banner) and the app icon warning
|
||||
suppression below, for the same reason androidApp's is there. -->
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
<uses-permission android:name="android.permission.ACCESS_LOCAL_NETWORK" />
|
||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_SPECIAL_USE" />
|
||||
|
||||
<application
|
||||
android:label="AI Sessions (shell)"
|
||||
android:allowBackup="true"
|
||||
android:theme="@android:style/Theme.Material.Light.NoActionBar"
|
||||
tools:ignore="MissingApplicationIcon">
|
||||
<activity
|
||||
android:name=".MainActivity"
|
||||
android:exported="true"
|
||||
android:launchMode="singleTop">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent-filter>
|
||||
<!-- Enrollment: aiappshell://enroll?host=...&port=...&token=...,
|
||||
per AGENTS.md's ui-sandbox.sh banner (fed to this app with
|
||||
`adb shell am start -a android.intent.action.VIEW -d
|
||||
'aiappshell://enroll?...'`, or -n'd at this component
|
||||
directly if a second app also claims the aiapp scheme). -->
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.VIEW" />
|
||||
<category android:name="android.intent.category.DEFAULT" />
|
||||
<category android:name="android.intent.category.BROWSABLE" />
|
||||
<data android:scheme="aiappshell" android:host="enroll" />
|
||||
</intent-filter>
|
||||
<!-- The share sheet - see android-shell's share.rs. -->
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.SEND" />
|
||||
<action android:name="android.intent.action.SEND_MULTIPLE" />
|
||||
<category android:name="android.intent.category.DEFAULT" />
|
||||
<data android:mimeType="*/*" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
|
||||
<!-- specialUse, not dataSync, for the reason androidApp's manifest
|
||||
gives: a connection that has to keep listening overnight
|
||||
cannot accept dataSync's six-hour cap. -->
|
||||
<service
|
||||
android:name=".NotificationService"
|
||||
android:exported="false"
|
||||
android:foregroundServiceType="specialUse">
|
||||
<property
|
||||
android:name="android.app.PROPERTY_SPECIAL_USE_FGS_SUBTYPE"
|
||||
android:value="E3 experiment: holds one connection to the sandbox server so a
|
||||
session that needs an answer can be reported while the app is closed." />
|
||||
</service>
|
||||
</application>
|
||||
</manifest>
|
||||
@@ -0,0 +1,50 @@
|
||||
package com.example.aiapp.shell;
|
||||
|
||||
import android.app.Activity;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.os.Bundle;
|
||||
import android.os.Handler;
|
||||
import android.os.Looper;
|
||||
import android.widget.Toast;
|
||||
|
||||
/**
|
||||
* E3's floor, per RUST.md's "How much Java is unavoidable": a class the framework
|
||||
* constructs by name from the manifest, with its lifecycle methods handing straight to Rust
|
||||
* (android-shell's {@code share::handle_intent}). No Compose, no layout -- there is no screen to
|
||||
* draw yet (that is E4's job, on iris); {@link #toast} is this experiment's stand-in for showing
|
||||
* something happened.
|
||||
*/
|
||||
public class MainActivity extends Activity {
|
||||
static {
|
||||
System.loadLibrary("android_shell");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onCreate(Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
NotificationService.sync(this);
|
||||
nativeHandleIntent(this, getIntent());
|
||||
}
|
||||
|
||||
// launchMode="singleTop": a notification tap or a share while this activity is already on
|
||||
// top lands here rather than in a second instance -- same reasoning as MainActivity.kt's.
|
||||
@Override
|
||||
protected void onNewIntent(Intent intent) {
|
||||
super.onNewIntent(intent);
|
||||
setIntent(intent);
|
||||
nativeHandleIntent(this, intent);
|
||||
}
|
||||
|
||||
/**
|
||||
* Called from android-shell, sometimes from a background thread (a share's network call is
|
||||
* never made on the calling thread -- see share.rs). {@code Toast} itself is main-thread-only,
|
||||
* so this hops there with a {@link Handler} rather than assuming the caller already has.
|
||||
*/
|
||||
static void toast(Context context, String message) {
|
||||
new Handler(Looper.getMainLooper())
|
||||
.post(() -> Toast.makeText(context, message, Toast.LENGTH_LONG).show());
|
||||
}
|
||||
|
||||
private static native void nativeHandleIntent(Activity activity, Intent intent);
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package com.example.aiapp.shell;
|
||||
|
||||
import android.app.Service;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.os.IBinder;
|
||||
|
||||
/**
|
||||
* E3's second unavoidable Java class (RUST.md): a foreground service constructed by the framework
|
||||
* from the manifest, existing only to hand its lifecycle to android-shell's {@code notify} module
|
||||
* -- the SSE follow loop, deciding what a notification says, and posting it are all Rust reached
|
||||
* through these three native calls. See {@code Notifications.kt}'s {@code NotificationService} for
|
||||
* the Kotlin original this mirrors.
|
||||
*/
|
||||
public class NotificationService extends Service {
|
||||
static {
|
||||
System.loadLibrary("android_shell");
|
||||
}
|
||||
|
||||
@Override
|
||||
public IBinder onBind(Intent intent) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int onStartCommand(Intent intent, int flags, int startId) {
|
||||
return nativeOnStartCommand(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDestroy() {
|
||||
nativeOnDestroy();
|
||||
}
|
||||
|
||||
/** Starts this service if there is a server to connect to, and stops it otherwise. */
|
||||
static void sync(Context context) {
|
||||
nativeSync(context);
|
||||
}
|
||||
|
||||
private static native void nativeSync(Context context);
|
||||
|
||||
private static native int nativeOnStartCommand(Service service);
|
||||
|
||||
private static native void nativeOnDestroy();
|
||||
}
|
||||
Reference in new issue
Block a user