feat(lab): load an on-device Lab build over the installed app

This commit is contained in:
Kurt Himebauch committed 2026-11-09 16:25:39 -05:00
1 parent 75a0230304
commit f3f3f9ce08
6 files changed
+307 -2

No files matched your search

@@ -7,8 +7,11 @@ import com.droiddeck.launcher.session.EnhancedSessionLogShare
import com.droiddeck.launcher.session.GpuClockPin
class App : Application() {
override fun attachBaseContext(base: android.content.Context) =
override fun attachBaseContext(base: android.content.Context) {
super.attachBaseContext(com.droiddeck.launcher.core.AppLanguage.wrap(base))
val process = if (android.os.Build.VERSION.SDK_INT >= 28) Application.getProcessName() else packageName
com.droiddeck.launcher.lab.LabOverlay.load(this, process == packageName)
}
override fun onConfigurationChanged(newConfig: android.content.res.Configuration) {
super.onConfigurationChanged(newConfig)
@@ -0,0 +1,191 @@
package com.droiddeck.launcher.lab
import android.app.Activity
import android.app.Application
import android.content.Context
import android.content.Intent
import android.content.res.Resources
import android.content.res.loader.ResourcesLoader
import android.content.res.loader.ResourcesProvider
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.ParcelFileDescriptor
import android.util.Log
import androidx.annotation.RequiresApi
import androidx.annotation.VisibleForTesting
import com.droiddeck.launcher.BuildConfig
import org.json.JSONObject
import java.io.File
/**
* A Lab build: app code and resources an on-device agent built from this install's own commit,
* loaded over the installed APK at startup so it can be tried without reinstalling or re-signing.
*
* `files/lab/next` holds a build waiting for the next start and `files/lab/active` the one in use,
* each with `overlay.apk` (the build's dex files and linked resources) and `overlay.json`.
*/
object LabOverlay {
data class Info(val label: String, val baseCommit: String, val baseApk: String)
private const val TAG = "LabOverlay"
private const val MAX_FAILED_STARTS = 2
private const val STABLE_AFTER_MS = 10_000L
@Volatile var active: Info? = null
private set
@Volatile var skipped: String? = null
private set
private var loader: Any? = null
@VisibleForTesting
internal var injectDex: (ClassLoader, File) -> Unit = ::prependDex
@VisibleForTesting
internal var openResources: (File) -> Any? = { if (Build.VERSION.SDK_INT >= 30) createLoader(it) else null }
fun root(context: Context) = File(context.filesDir, "lab")
/** Called from [Application.attachBaseContext], before any class the build may change is loaded. */
fun load(app: Application, mainProcess: Boolean) {
active = null
skipped = null
try {
val root = root(app)
if (mainProcess) promote(root)
val dir = File(root, "active")
val apk = File(dir, "overlay.apk")
val meta = File(dir, "overlay.json")
if (!apk.isFile || !meta.isFile) return
val info = parse(meta.readText()) ?: return refuse(root, mainProcess, "unreadable overlay.json")
// The APK's path changes with every install and update of the app.
if (info.baseCommit != BuildConfig.SOURCE_COMMIT || info.baseApk != app.applicationInfo.sourceDir)
return refuse(root, mainProcess, "built for another install")
if (Build.VERSION.SDK_INT < 30) return skip("needs Android 11")
// Classes in an app image are loaded before attachBaseContext and would ignore the overlay;
// dd-lab-build recompiles the app without one (cmd package compile -m verify).
if (hasAppImage(app)) return skip("app image present")
if (mainProcess) {
val starts = failedStarts(root) + 1
if (starts > MAX_FAILED_STARTS) return refuse(root, true, "did not start")
File(root, "starts").writeText(starts.toString())
}
apk.setReadOnly()
loader = openResources(apk)
injectDex(app.classLoader, apk)
active = info
addLoader(app.resources)
app.registerActivityLifecycleCallbacks(Callbacks(root, mainProcess))
} catch (e: Throwable) {
Log.w(TAG, "Lab build not loaded", e)
skipped = e.message ?: e.javaClass.simpleName
}
}
/** Leaves the Lab build and restarts the app on the installed APK. */
fun turnOff(context: Context) {
val root = root(context)
File(root, "active").renameTo(File(root, "off-${System.currentTimeMillis()}"))
File(root, "next").deleteRecursively()
File(root, "starts").delete()
val launch = context.packageManager.getLaunchIntentForPackage(context.packageName)
?.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
if (launch != null) context.startActivity(launch)
Runtime.getRuntime().exit(0)
}
@VisibleForTesting
internal fun parse(json: String): Info? = runCatching {
val o = JSONObject(json)
Info(o.getString("label"), o.getString("baseCommit"), o.getString("baseApk"))
}.getOrNull()
@VisibleForTesting
internal fun promote(root: File) {
val next = File(root, "next")
if (!File(next, "overlay.apk").isFile || !File(next, "overlay.json").isFile) return
val active = File(root, "active")
active.deleteRecursively()
if (next.renameTo(active)) File(root, "starts").delete()
}
@VisibleForTesting
internal fun failedStarts(root: File) = File(root, "starts").takeIf { it.isFile }?.readText()?.trim()?.toIntOrNull() ?: 0
private fun refuse(root: File, mainProcess: Boolean, reason: String) {
skipped = reason
Log.w(TAG, "Lab build turned off: $reason")
if (!mainProcess) return
File(root, "active").renameTo(File(root, "off-${System.currentTimeMillis()}"))
File(root, "starts").delete()
File(root, "last-off-reason").writeText(reason)
}
private fun skip(reason: String) {
skipped = reason
Log.w(TAG, "Lab build not loaded: $reason")
}
private fun hasAppImage(context: Context): Boolean {
val apk = File(context.applicationInfo.sourceDir)
val oat = File(apk.parentFile, "oat")
return oat.listFiles().orEmpty().any { File(it, "${apk.nameWithoutExtension}.art").isFile }
}
@RequiresApi(30)
private fun createLoader(apk: File): ResourcesLoader =
ParcelFileDescriptor.open(apk, ParcelFileDescriptor.MODE_READ_ONLY).use { fd ->
ResourcesLoader().apply { addProvider(ResourcesProvider.loadFromApk(fd)) }
}
/** Gives [resources] the Lab build's resources; contexts made from them inherit it. */
fun addLoader(resources: Resources) {
if (Build.VERSION.SDK_INT < 30) return
val current = loader as? ResourcesLoader ?: return
resources.addLoaders(current)
}
private fun prependDex(classLoader: ClassLoader, apk: File) {
val pathList = field(Class.forName("dalvik.system.BaseDexClassLoader"), "pathList").get(classLoader)!!
val elementsField = field(pathList.javaClass, "dexElements")
@Suppress("UNCHECKED_CAST") val installed = elementsField.get(pathList) as Array<Any?>
val errors = ArrayList<java.io.IOException>()
val made = try {
pathList.javaClass.getDeclaredMethod("makeDexElements", List::class.java, File::class.java, List::class.java, ClassLoader::class.java)
.apply { isAccessible = true }.invoke(null, listOf(apk), null, errors, classLoader)
} catch (_: NoSuchMethodException) {
pathList.javaClass.getDeclaredMethod(
"makeDexElements", List::class.java, File::class.java, List::class.java, ClassLoader::class.java, Boolean::class.javaPrimitiveType,
).apply { isAccessible = true }.invoke(null, listOf(apk), null, errors, classLoader, false)
}
errors.firstOrNull()?.let { throw it }
@Suppress("UNCHECKED_CAST") val added = made as Array<Any?>
if (added.isEmpty()) error("no dex in ${apk.name}")
val merged = java.lang.reflect.Array.newInstance(installed.javaClass.componentType!!, added.size + installed.size)
System.arraycopy(added, 0, merged, 0, added.size)
System.arraycopy(installed, 0, merged, added.size, installed.size)
elementsField.set(pathList, merged)
}
private fun field(type: Class<*>, name: String) = type.getDeclaredField(name).apply { isAccessible = true }
private class Callbacks(private val root: File, private val mainProcess: Boolean) : Application.ActivityLifecycleCallbacks {
private var settled = false
override fun onActivityPreCreated(activity: Activity, savedInstanceState: Bundle?) = addLoader(activity.resources)
override fun onActivityResumed(activity: Activity) {
if (settled || !mainProcess) return
settled = true
Handler(Looper.getMainLooper()).postDelayed({ File(root, "starts").delete() }, STABLE_AFTER_MS)
}
override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) = Unit
override fun onActivityStarted(activity: Activity) = Unit
override fun onActivityPaused(activity: Activity) = Unit
override fun onActivityStopped(activity: Activity) = Unit
override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) = Unit
override fun onActivityDestroyed(activity: Activity) = Unit
}
}
@@ -38,7 +38,8 @@ object BuildWatermark {
if (text.length <= TITLE_LIMIT) text else text.take(TITLE_LIMIT - 1).trimEnd() + "…"
fun install(app: Application) {
val lines = lines() ?: return
val lab = com.droiddeck.launcher.lab.LabOverlay.active?.let { "LAB | ${truncate(it.label)}" }
val lines = (listOfNotNull(lab) + lines().orEmpty()).ifEmpty { return }
app.registerActivityLifecycleCallbacks(object : Application.ActivityLifecycleCallbacks {
override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
if (activity is QuestXrActivity) return
@@ -280,6 +280,12 @@ private fun ChannelPicker(u: UpdatesState, ua: UpdatesActions) {
if (tests.isEmpty()) stringResource(R.string.upd_tests_none) else pluralStringResource(R.plurals.upd_tests_count, tests.size, tests.size),
u.follow.channel == Channel.TEST, enabled = tests.isNotEmpty() || u.follow.channel == Channel.TEST,
) { tests.firstOrNull()?.let { ua.onFollow(Follow(Channel.TEST, it.pr)) } }
com.droiddeck.launcher.lab.LabOverlay.active?.let { lab ->
val context = androidx.compose.ui.platform.LocalContext.current
ChannelCard(Icons.Outlined.Code, stringResource(R.string.upd_lab), lab.label, stringResource(R.string.upd_lab_off), true) {
com.droiddeck.launcher.lab.LabOverlay.turnOff(context)
}
}
AnimatedVisibility(u.follow.channel == Channel.TEST && tests.isNotEmpty(), enter = expandVertically(Motion.sp(1f)) + fadeIn(Motion.sp(1f)), exit = shrinkVertically(Motion.sp(1f)) + fadeOut(Motion.sp(1f))) {
Column(Modifier.padding(start = 18.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {
tests.forEach { t -> TestRow(t, u.follow.pr == t.pr) { ua.onFollow(Follow(Channel.TEST, t.pr)) } }
+2
View File
@@ -1118,6 +1118,8 @@
<string name="upd_tests">Test builds</string>
<string name="upd_tests_hint">Try a fix before it\'s released</string>
<string name="upd_tests_none">None right now</string>
<string name="upd_lab">Lab build</string>
<string name="upd_lab_off">Tap to go back to the installed version</string>
<string name="upd_pr">PR #%1$d</string>
<string name="upd_not_built">Not built for this copy of DroidDeck</string>
<string name="upd_updated">Updated %1$s</string>
@@ -0,0 +1,102 @@
package com.droiddeck.launcher.lab
import android.app.Application
import com.droiddeck.launcher.BuildConfig
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
import java.io.File
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33], manifest = Config.NONE)
class LabOverlayTest {
private lateinit var app: Application
private lateinit var root: File
private val injected = mutableListOf<File>()
private val originalInject = LabOverlay.injectDex
private val originalResources = LabOverlay.openResources
@Before fun prepare() {
app = RuntimeEnvironment.getApplication()
app.applicationInfo.sourceDir = "/data/app/~~test==/com.droiddeck.launcher-test==/base.apk"
root = LabOverlay.root(app).apply { deleteRecursively(); mkdirs() }
LabOverlay.injectDex = { _, apk -> injected += apk }
LabOverlay.openResources = { null }
}
@After fun restore() {
LabOverlay.injectDex = originalInject
LabOverlay.openResources = originalResources
root.deleteRecursively()
}
private fun stage(dir: String, commit: String = BuildConfig.SOURCE_COMMIT, apk: String = app.applicationInfo.sourceDir) =
File(root, dir).apply {
mkdirs()
File(this, "overlay.apk").writeText("dex")
File(this, "overlay.json").writeText("""{"label":"feat/x @ abc1234","baseCommit":"$commit","baseApk":"$apk"}""")
}
@Test fun aBuildForThisInstallIsLoaded() {
stage("active")
LabOverlay.load(app, mainProcess = true)
assertEquals("feat/x @ abc1234", LabOverlay.active?.label)
assertEquals(listOf(File(root, "active/overlay.apk")), injected)
assertEquals(1, LabOverlay.failedStarts(root))
}
@Test fun aStagedBuildIsPromotedAtStart() {
stage("next")
File(root, "starts").writeText("2")
LabOverlay.load(app, mainProcess = true)
assertFalse(File(root, "next").exists())
assertNotNull(LabOverlay.active)
assertEquals(1, LabOverlay.failedStarts(root))
}
@Test fun aBuildForAnotherInstallIsTurnedOff() {
stage("active", commit = "0000000")
LabOverlay.load(app, mainProcess = true)
assertNull(LabOverlay.active)
assertTrue(injected.isEmpty())
assertFalse(File(root, "active").exists())
assertEquals("built for another install", File(root, "last-off-reason").readText())
}
@Test fun aBuildForAnEarlierInstallOfTheSameCommitIsTurnedOff() {
stage("active", apk = "/data/app/old/base.apk")
LabOverlay.load(app, mainProcess = true)
assertNull(LabOverlay.active)
assertEquals("built for another install", File(root, "last-off-reason").readText())
}
@Test fun aBuildThatKeepsFailingToStartIsTurnedOff() {
stage("active")
File(root, "starts").writeText("2")
LabOverlay.load(app, mainProcess = true)
assertNull(LabOverlay.active)
assertEquals("did not start", File(root, "last-off-reason").readText())
}
@Test fun otherProcessesLoadWithoutCountingStarts() {
stage("active")
LabOverlay.load(app, mainProcess = false)
assertNotNull(LabOverlay.active)
assertEquals(0, LabOverlay.failedStarts(root))
}
@Test fun noBuildMeansNothingIsLoaded() {
LabOverlay.load(app, mainProcess = true)
assertNull(LabOverlay.active)
assertTrue(injected.isEmpty())
}
}